merge f-split-agent4 4b5cc08d1 (skills end to end, New skill button, agent skills folder, goal-status race fix) into f-split-int

This commit is contained in:
Niko1221 committed 2026-10-16 14:26:57 +02:00
commit 19ea30f6ab
21 files changed
+469 -39

No files matched your search

+139
View File
@@ -0,0 +1,139 @@
/**
* Drive the host over HTTP (no browser) against a real model and print what the page would receive.
*
* STRATA_URL=http://127.0.0.1:8899 node scripts/agent3-http.mjs <command> [args]
*
* connect <baseUrl> <modelId> save an API connection to a model server (once per STRATA_HOME)
* stream "<message>" [mode] one chat turn; prints every frame compactly with its time (status, goal, tools, deltas counted)
* goal "<objective>" /goal run, then the goal bar calls: state, pause, edit, clear, resume
* timeskip "<request>" [stopAfterS] a Time-skip job; polls status (phase + activity); with stopAfterS, presses Stop that many seconds in
*
* Environment: STRATA_URL (required), CHAT (chat id, default a fresh one), WORKSPACE_ID.
*/
const BASE = process.env.STRATA_URL;
if (!BASE) { console.error('STRATA_URL is required'); process.exit(2); }
const [command, ...rest] = process.argv.slice(2);
const t0 = Date.now();
const stamp = () => `${String(Math.round((Date.now() - t0) / 1000)).padStart(4)}s`;
const j = async (path, body, method = body ? 'POST' : 'GET') => {
const res = await fetch(BASE + path, { method, headers: { 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
const text = await res.text();
let data; try { data = JSON.parse(text); } catch { data = { raw: text }; }
if (!res.ok) throw new Error(`${path} -> ${res.status} ${data.error ?? text.slice(0, 200)}`);
return data;
};
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function model() {
const providers = await j('/api/model-providers');
const c = providers.connections.at(-1);
if (!c) throw new Error('no API connection saved: run "connect" first');
return { connectionId: c.id, modelId: c.models[0].id };
}
/** One chat stream; returns the frames. `print` shows a compact line per frame, deltas and reasoning as counters. */
async function stream(body, { quiet = false } = {}) {
const res = await fetch(BASE + '/api/chat/stream', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
if (!res.ok) throw new Error(`stream -> ${res.status} ${await res.text()}`);
const frames = []; let buffer = '', text = 0, reasoning = 0, lastLine = '';
const flushCounters = () => { if (text || reasoning) { console.log(`${stamp()} ... ${reasoning} reasoning chars, ${text} answer chars`); text = 0; reasoning = 0; } };
const reader = res.body.getReader(); const dec = new TextDecoder();
for (;;) {
const { value, done } = await reader.read();
if (value) {
buffer += dec.decode(value, { stream: true });
const lines = buffer.split('\n'); buffer = lines.pop() ?? '';
for (const line of lines.filter(Boolean)) {
const f = JSON.parse(line); f._at = Date.now(); frames.push(f);
if (f.type === 'delta') { text += (f.text ?? '').length; continue; }
if (f.type === 'reasoning') { reasoning += (f.text ?? '').length; continue; }
if (f.type === 'stats') continue;
flushCounters();
let out = f.type;
if (f.type === 'status') out = `status[${f.seq}] ${f.phase}/${f.code}: ${f.text}${f.tokens !== undefined ? ` (tokens ${f.tokens})` : ''} +${f.elapsedMs}ms`;
else if (f.type === 'goal') out = `goal ${JSON.stringify(f.goal)}`;
else if (f.type === 'agent-tool') {
out = `tool ${f.tool.state} ${f.tool.verb} ${f.tool.target ?? ''}${f.tool.state === 'proposed' ? ` [asks: ${f.tool.effect}]` : ''}`;
// ANSWER=approve|deny answers every card that asks (the card is the real Approve/Deny card of Manual mode)
if (f.tool.state === 'proposed' && process.env.ANSWER) void j('/api/chat/approval', { sessionId: body.sessionId, toolId: f.tool.id, decision: process.env.APPROVE_MATCH && new RegExp(process.env.APPROVE_MATCH, 'i').test(`${f.tool.target} ${f.tool.effect}`) ? 'approve' : process.env.ANSWER }).then(() => console.log(`${stamp()} -> ${process.env.ANSWER} ${f.tool.id}`), e => console.log(`${stamp()} answer failed: ${e.message}`));
}
else if (f.type === 'done') out = `done ${f.finishReason} tokensOut=${f.tokensOut}`;
else if (f.type === 'error') out = `ERROR ${f.message}`;
if (!quiet && out !== lastLine) console.log(`${stamp()} ${out}`);
lastLine = out;
}
}
if (done) break;
}
flushCounters();
return frames;
}
if (command === 'connect') {
const [baseUrl, modelId] = rest;
await j('/api/model-providers', { kind: 'custom', name: 'Cloud model', baseUrl, protocol: 'openai-chat', apiKey: '', models: [{ id: modelId, name: 'Test model' }] });
console.log('saved');
} else if (command === 'stream') {
const [message, mode = 'bypass'] = rest;
const chat = process.env.CHAT ?? `c-${Date.now()}`;
await stream({ sessionId: chat, message, mode, remoteModel: await model(), workspaceId: process.env.WORKSPACE_ID, ...(process.env.PLAIN ? { agent: false } : {}), ...(process.env.THINK ? { thinking: process.env.THINK } : {}) });
} else if (command === 'skill') {
// create a skill through the Skills page route: skill "Name" "description" "instructions"
const [name, description, instructions] = rest;
const out = await j('/api/skills', { name, description, body: instructions });
console.log('saved', out.id, '| skills now:', out.skills.map(s => `${s.id}(${s.source})`).join(', '));
} else if (command === 'goal') {
const [objective] = rest;
const chat = process.env.CHAT ?? `g-${Date.now()}`;
const common = { sessionId: chat, mode: 'bypass', remoteModel: await model() };
console.log(`${stamp()} -- /goal run`);
const frames = await stream({ ...common, message: `/goal ${objective}` });
const last = frames.filter(f => f.type === 'goal').at(-1);
console.log(`${stamp()} -- goal bar: state`, JSON.stringify((await j(`/api/goal?chatId=${chat}`)).goal));
console.log(`${stamp()} -- pause`, JSON.stringify(await j('/api/goal/pause', { chatId: chat })));
console.log(`${stamp()} -- edit`, JSON.stringify(await j('/api/goal/edit', { chatId: chat, text: `${objective} (edited)` })));
console.log(`${stamp()} -- resume (stream)`);
await stream({ ...common, goalAction: 'resume' });
console.log(`${stamp()} -- clear`, JSON.stringify(await j('/api/goal/clear', { chatId: chat })));
console.log(`${stamp()} -- state after clear`, JSON.stringify(await j(`/api/goal?chatId=${chat}`)));
void last;
} else if (command === 'goalbar') {
// Pause from the goal bar while a round runs, then resume through the chat stream.
const [objective, pauseAfter = '6'] = rest;
const chat = process.env.CHAT ?? `gb-${Date.now()}`;
const common = { sessionId: chat, mode: 'bypass', remoteModel: await model() };
const running = stream({ ...common, message: `/goal ${objective}` });
await sleep(Number(pauseAfter) * 1000);
console.log(`${stamp()} -- pause from the bar`, JSON.stringify(await j('/api/goal/pause', { chatId: chat })));
await running;
console.log(`${stamp()} -- state after the run`, JSON.stringify((await j(`/api/goal?chatId=${chat}`)).goal));
console.log(`${stamp()} -- resume (stream, no message)`);
await stream({ ...common, goalAction: 'resume' });
console.log(`${stamp()} -- state after resume`, JSON.stringify((await j(`/api/goal?chatId=${chat}`)).goal));
console.log(`${stamp()} -- remove`, JSON.stringify(await j('/api/goal/clear', { chatId: chat })));
} else if (command === 'timeskip') {
const [request, stopAfter] = rest;
const chat = process.env.CHAT ?? `t-${Date.now()}`;
const started = await j('/api/timeskip/start', { prompt: request, sessionId: chat, attempts: 1, workspaceId: process.env.WORKSPACE_ID, remoteModel: await model() });
const id = started.run.id;
console.log(`${stamp()} started ${id} activity=${JSON.stringify(started.run.activity)}`);
let last = '', stopped = false;
for (;;) {
const { run } = await j(`/api/timeskip/status?id=${id}`);
const line = `${run.phase}${run.activity ? ` | ${run.activity.text}${run.activity.args?.step ? ` | assistant: ${run.activity.args.step}` : ''}` : ''}`;
if (line !== last) { console.log(`${stamp()} ${line}`); last = line; }
if (stopAfter && !stopped && (Date.now() - t0) / 1000 >= Number(stopAfter)) {
console.log(`${stamp()} -- pressing Stop (the chat Stop route)`);
console.log(`${stamp()} `, JSON.stringify(await j('/api/chat/stop', { sessionId: chat })));
stopped = true;
}
if (['completed', 'cancelled', 'failed', 'interrupted'].includes(run.phase)) {
console.log(`${stamp()} END ${run.phase}${run.error ? ` error=${run.error}` : ''} needsReview=${run.needsUserReview}`);
try { const files = await j(`/api/timeskip/files?id=${id}`); console.log(`${stamp()} files: ${files.files.map(f => `${f.status} ${f.path}`).join(', ') || '(none)'}`); } catch (e) { console.log(`${stamp()} files: ${e.message}`); }
break;
}
await sleep(4000);
}
} else {
console.error('commands: connect | stream | goal | timeskip'); process.exit(2);
}
+27
View File
@@ -0,0 +1,27 @@
/** One short headless render of the Skills page and the New skill dialog (closed when done). STRATA_URL, SHOTS */
import { chromium } from 'playwright-core';
import { existsSync, mkdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
const BASE = process.env.STRATA_URL, SHOTS = resolve(process.env.SHOTS ?? 'skills-shots');
mkdirSync(SHOTS, { recursive: true });
const chrome = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
const browser = await chromium.launch({ executablePath: chrome, headless: true });
try {
const page = await browser.newPage({ viewport: { width: 1360, height: 900 } });
await page.goto(`${BASE}/`);
const skip = page.getByText('Go straight to the app'); await skip.waitFor({ timeout: 8000 }).then(() => skip.click()).catch(() => {});
await page.getByText('Skills', { exact: true }).first().click();
await page.waitForSelector('.skills-page', { timeout: 15000 });
await page.waitForTimeout(600);
await page.screenshot({ path: join(SHOTS, '01-skills-list.png') });
await page.getByRole('button', { name: 'New skill' }).click();
await page.getByRole('dialog').locator('input.st-input').nth(0).fill('Folder helper');
await page.getByRole('dialog').locator('input.st-input').nth(1).fill('Opens a folder for you');
await page.getByRole('tab', { name: 'Instructions' }).click();
await page.getByRole('dialog').locator('textarea').fill('Open the Downloads folder, then the Documents folder, and say which two you opened.');
await page.screenshot({ path: join(SHOTS, '02-new-skill-dialog.png') });
await page.getByRole('button', { name: 'Save skill' }).click();
await page.waitForTimeout(1500);
await page.screenshot({ path: join(SHOTS, '03-after-save.png') });
console.log('rendered', await page.locator('.skill-row').allInnerTexts().then(r => r.map(t => t.split('\n')[0]).join(' | ')));
} finally { await browser.close(); }
+3 -3
View File
@@ -55,7 +55,7 @@ const deferred = () => { let resolve; const promise = new Promise(r => { resolve
* @param {string} [options.nodePath] the Node runtime that runs the Harness
* @param {(line:string)=>void} [options.log]
*/
export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, onGoal = () => {}, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {
export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {
const root = join(dataDir, 'agent');
const home = join(root, 'home');
const sessionsFile = join(root, 'sessions.json');
@@ -100,7 +100,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
function status() {
const h = harnessInfo();
if (!h.ok) return { state: 'unavailable', reason: 'The coding assistant isn’t installed on this computer yet. Chat works without it.', detail: h.reason, code: 'component-missing' };
const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools() });
const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir() });
return {
state: rt?.hp.running ? 'ready' : starting ? 'starting' : lastError ? 'error' : 'idle',
reason: lastError ? plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again.' : plainAgentFailure(lastError) : null,
@@ -148,7 +148,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
async function ensureRuntime(choice, signal) {
for (;;) {
if (starting) { await starting.catch(() => {}); continue; }
const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools() });
const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir() });
const route = routeFor(profile, choice);
if (!route) {
throw new AgentUnavailable(choice?.connectionId
+1
View File
@@ -80,6 +80,7 @@ const VERBS = {
create_goal: ['Setting the goal', 'Set the goal', "Couldn't set the goal"],
update_goal: ['Updating the goal', 'Updated the goal', "Couldn't update the goal"],
get_goal: ['Checking the goal', 'Checked the goal', "Couldn't check the goal"],
skill: ['Loading your skill', 'Loaded your skill', "Couldn't load the skill"],
todo_write: ['Updating its to-do list', 'Updated its to-do list', "Couldn't update its to-do list"],
present: ['Showing you a result', 'Showed you a result', "Couldn't show the result"],
working_directory: ['Checking the folder', 'Checked the folder', "Couldn't check the folder"],
+3 -2
View File
@@ -50,7 +50,7 @@ export const AGENT_PROMPT = [
* @param {{platform?: string, search?: boolean}} [options]
* @returns {object} the `config` of the `preset-standard` row
*/
export function standardPreset({ platform = process.platform, search = false, off = new Set() } = {}) {
export function standardPreset({ platform = process.platform, search = false, off = new Set(), skillsDir = null } = {}) {
const windows = platform === 'win32';
const plugins = [
{ id: 'persona', name: '@deepseek-ai/dsh-persona', config: { prefix: AGENT_PROMPT, complete: true, includeRuntimeContext: false } },
@@ -62,7 +62,8 @@ export function standardPreset({ platform = process.platform, search = false, of
{ id: 'tool-fs', name: '@deepseek-ai/dsh-tool-fs' },
{ id: 'tool-fs-search', name: '@deepseek-ai/dsh-tool-fs-search', config: { sampleOverCapGlobResults: false } },
{ id: 'tool-jobs', name: '@deepseek-ai/dsh-tool-jobs' },
{ id: 'skill-filesystem', name: '@deepseek-ai/dsh-skill-filesystem' },
// The skills of the Skills page, written out as folders the Harness scans (and watches: a skill saved in the app is there at once).
{ id: 'skill-filesystem', name: '@deepseek-ai/dsh-skill-filesystem', ...(skillsDir ? { config: { customSkillDirs: [skillsDir] } } : {}) },
{ id: 'tool-skill', name: '@deepseek-ai/dsh-tool-skill' },
{ id: 'command-goal', name: '@deepseek-ai/dsh-command-goal' },
{ id: 'tool-goal', name: '@deepseek-ai/dsh-tool-goal' },
+2 -2
View File
@@ -137,7 +137,7 @@ export function outputBudget(context, maxOutput = null) {
* @param {Array<{id:string,name:string,baseUrl:string,protocol:string,apiKey?:string,models:Array<{id:string,name?:string,contextMax?:number|null}>}>} input.connections
* @returns {{patch:string, env:Record<string,string>, routes:Array, defaultRoute:object|null, signature:string}}
*/
export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS }) {
export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null }) {
const providers = {};
const env = {};
const routes = [];
@@ -226,7 +226,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools
...(mcp.length || ownRows.length ? [{ insert: [...mcp, ...ownRows] }] : []),
...webRows,
// The reminder tools would be a second scheduler beside the app's Tasks. The tool groups the person switched off in Settings -> Tools are left out.
{ id: 'preset-standard', name: '@deepseek-ai/dsh-agent-preset', config: standardPreset({ off: tools.off, search: searchOn }) },
{ id: 'preset-standard', name: '@deepseek-ai/dsh-agent-preset', config: standardPreset({ off: tools.off, search: searchOn, skillsDir }) },
// Strata names its chats itself; the Harness's own title request would be an extra model call on
// every first prompt (and, for an API route, an unrequested one).
{ id: 'session-title-llm', disabled: true },
+1 -1
View File
@@ -89,7 +89,7 @@ export class StatusReporter {
this.wanted = next;
const sinceEmit = this.now() - this.lastEmitAt;
const due = changed ? this.gapMs : this.beatMs;
if (!this.current || sinceEmit >= due) this.#flush();
if (!this.current || sinceEmit >= due || update.phase === 'goal') this.#flush(); // a goal step is rare and the page should always hear it
else if (this.#differs()) this.#arm(due - sinceEmit);
}
+59 -20
View File
@@ -10,6 +10,7 @@ import { createTaskService, validateTask } from './tasks.mjs';
import { createAgentTaskRunner } from './agent/task-run.mjs';
import { migrateSetup } from './setup.mjs';
import { skillEdit } from './skill-edits.mjs';
import { materializeSkills, parseSkillFile, skillSlug, writeCreatedSkill } from './skill-files.mjs';
import { systemFonts } from './fonts.mjs';
import { tuningDir } from './platform-paths.mjs';
import { createAgentBridge } from './agent/agent-bridge.mjs';
@@ -27,7 +28,7 @@ import { findBrowser, findPlaywrightMcp } from './agent/browser-probe.mjs';
*/
import http from 'node:http';
import { homedir } from 'node:os';
import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
@@ -113,6 +114,7 @@ const agentTools = createAgentTools({ read: () => store.get().agentTools, write:
agentTools.ensureFile();
const agent = createAgentBridge({
tools: () => agentTools.profileView(),
skillsDir: () => AGENT_SKILLS,
onGoal: (chatId, goal) => hub.send('goal', { chatId, goal }),
dataDir: store.DATA_DIR,
componentsDir: componentsDirectory(),
@@ -210,6 +212,11 @@ function setupState() {
};
}
/** Skills written in the Skills page live here (one folder each, SKILL.md inside). */
const CREATED_SKILLS = join(store.DATA_DIR, 'skills');
/** What the agent scans: the whole current list, written out by syncAgentSkills (the Harness watches it, so no restart). */
const AGENT_SKILLS = join(store.DATA_DIR, 'agent', 'skills-live');
function skills() {
const bundled = [
{
@@ -283,32 +290,26 @@ for the choice being made.`,
},
];
// Two places hold skills a person brought or wrote: the app's own folder (written in the Skills page) and the workspace's skills folder (added
// with "Add skill"). Both are plain `<name>/SKILL.md` folders; the frontmatter (name, description) is optional.
const extra = [];
const dir = join(WORKSPACE, 'skills');
if (existsSync(dir) && statSync(dir).isDirectory()) {
for (const [dir, source, prefix] of [[CREATED_SKILLS, 'created', 'my-'], [join(WORKSPACE, 'skills'), 'workspace', 'ws-']]) {
if (!existsSync(dir) || !statSync(dir).isDirectory()) continue;
for (const name of readdirSync(dir)) {
const full = join(dir, name);
if (!statSync(full).isDirectory()) continue;
// The description always claimed this file was the source; now it is.
// Its instruction text is the thing a reader needs in order to decide
// whether to leave the skill switched on.
let body = '';
let sizeKb = 1;
try { if (!statSync(full).isDirectory()) continue; } catch { continue; }
let text = '', sizeKb = 1;
const md = join(full, 'SKILL.md');
try {
body = readFileSync(md, 'utf8');
sizeKb = Math.max(0.1, statSync(md).size / 1024);
} catch {
/* a folder with no SKILL.md is listed but has nothing to show */
}
try { text = readFileSync(md, 'utf8'); sizeKb = Math.max(0.1, statSync(md).size / 1024); } catch { /* a folder with no SKILL.md is listed but has nothing to show */ }
const parsed = parseSkillFile(text);
extra.push({
id: `ws-${name}`,
name,
description: `Workspace skill loaded from ${name}/SKILL.md`,
source: 'workspace',
id: `${prefix}${name}`,
name: parsed.title ?? name.replace(/-/g, ' ').replace(/^./, c => c.toUpperCase()),
description: parsed.description ?? (source === 'created' ? 'A skill you wrote.' : `Workspace skill loaded from ${name}/SKILL.md`),
source,
enabled: true,
triggers: [name.replace(/-/g, ' ')],
body,
body: parsed.body,
sizeKb: Number(sizeKb.toFixed(1)),
});
}
@@ -327,6 +328,15 @@ let skillState = skills().map((s) => ({
lastUsedAt: null,
}));
/**
* Write the skills the agent may use into its folder. A skill narrowed to one workspace is left out (the agent has no such scope), a skill
* switched off is written as hidden. Called after every change to the list.
*/
function syncAgentSkills() {
try { materializeSkills(AGENT_SKILLS, skillState.filter(s => !s.onlyIn)); } catch (e) { console.warn('skills · could not write the agent skills folder:', e.message); }
}
syncAgentSkills();
/** Whether a skill applies, given where the reader is. */
/**
* Records which enabled skills a prompt actually triggered.
@@ -1392,6 +1402,34 @@ async function api(req, res, path, method, url) {
? { ...s, enabled: before.enabled, onlyIn: before.onlyIn ?? null, useCount: before.useCount, lastUsedAt: before.lastUsedAt }
: { ...s, onlyIn: null, useCount: 0, lastUsedAt: null };
});
syncAgentSkills();
return json(res, 200, skillState);
}
// A skill written in the app: a name, what it is for, and the instructions. Saved as a folder the agent can read; no restart.
if (path === '/api/skills' && method === 'POST') {
const body = await readBody(req);
try {
const name = String(body.name ?? '').trim().slice(0, 80);
const instructions = String(body.body ?? '').trim();
if (!name) throw new Error('Give the skill a name.');
if (!instructions) throw new Error('Write the instructions the assistant should follow.');
const id = writeCreatedSkill(CREATED_SKILLS, { name, description: String(body.description ?? '').trim().slice(0, 400), body: instructions.slice(0, 40000) });
const before = new Map(skillState.map(s => [s.id, s]));
skillState = skills().map(s => before.has(s.id) ? { ...s, enabled: before.get(s.id).enabled, onlyIn: before.get(s.id).onlyIn ?? null, useCount: before.get(s.id).useCount, lastUsedAt: before.get(s.id).lastUsedAt } : { ...s, onlyIn: null, useCount: 0, lastUsedAt: null });
syncAgentSkills();
hub.send('skills', skillState);
return json(res, 201, { id: `my-${id}`, skills: skillState });
} catch (e) { return error(res, 400, e.message); }
}
const skillDelete = /^\/api\/skills\/([^/]+)$/.exec(path);
if (skillDelete && method === 'DELETE') {
const skill = skillState.find(s => s.id === decodeURIComponent(skillDelete[1]));
if (!skill) return error(res, 404, 'Skill not found.');
if (skill.source !== 'created') return error(res, 400, 'Only a skill you wrote here can be removed from this page.');
rmSync(join(CREATED_SKILLS, skill.id.replace(/^my-/, '')), { recursive: true, force: true });
skillState = skillState.filter(s => s.id !== skill.id);
syncAgentSkills();
hub.send('skills', skillState);
return json(res, 200, skillState);
}
const skillMatch = /^\/api\/skills\/([^/]+)$/.exec(path);
@@ -1414,6 +1452,7 @@ async function api(req, res, path, method, url) {
: s,
);
store.update({ skillPreferences: Object.fromEntries(skillState.map(s => [s.id, { enabled: s.enabled, onlyIn: s.onlyIn }])), skillEdits: { ...store.get().skillEdits, [skillId]: { ...store.get().skillEdits?.[skillId], ...edit } } });
syncAgentSkills();
hub.send('skills', skillState);
return json(res, 200, skillState);
}
+74
View File
@@ -0,0 +1,74 @@
/**
* Skills on disk, for the app and for the agent.
*
* The app keeps the skills a person writes in its own folder (`<data>/skills/<id>/SKILL.md`). The agent (the Harness) finds skills by scanning
* folders of `<name>/SKILL.md` files whose frontmatter has a kebab-case `name` and a `description`. So the app also writes the whole current
* list (bundled, written, added, edited, switched on or off) into one folder the Harness is told to scan (`materializeSkills`), every time
* anything changes. The Harness watches that folder, so a skill saved in the app is there for the next message without a restart.
*/
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
/** The kebab-case name the Harness requires, from what a person typed ("Directory opener" -> "directory-opener"). */
export function skillSlug(name) {
return String(name ?? '').toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60);
}
const yamlText = value => JSON.stringify(String(value ?? '').replace(/\s+/g, ' ').trim());
/** `SKILL.md` text: the frontmatter the Harness reads, then the instructions. */
export function skillFileText({ name, title = null, description, body, hidden = false }) {
return `---\nname: ${skillSlug(name)}\n${title ? `title: ${yamlText(title)}\n` : ''}description: ${yamlText(description || name)}\n${hidden ? 'disable-model-invocation: true\n' : ''}---\n\n${String(body ?? '').trim()}\n`;
}
/** Name, description and instructions out of a SKILL.md (frontmatter optional). */
export function parseSkillFile(text) {
const raw = String(text ?? '').replace(/^/, '').replace(/\r\n/g, '\n');
const m = /^---\n([\s\S]*?)\n---\n?/.exec(raw);
if (!m) return { name: null, title: null, description: null, body: raw.trim() };
const field = key => {
const line = new RegExp(`^${key}:\\s*(.*)$`, 'mi').exec(m[1])?.[1]?.trim();
if (line === undefined) return null;
try { if (/^["']/.test(line)) return typeof JSON.parse(line.replace(/^'(.*)'$/, '"$1"')) === 'string' ? JSON.parse(line.replace(/^'(.*)'$/, '"$1"')) : line; } catch { /* plain scalar */ }
return line;
};
return { name: field('name'), title: field('title'), description: field('description'), body: raw.slice(m[0].length).trim() };
}
/** Where a skill written in the app lives, and writing it there. */
export function writeCreatedSkill(root, { name, description, body }) {
const id = skillSlug(name);
if (!id) throw new Error('Give the skill a name with letters or numbers in it.');
const dir = join(root, id);
if (existsSync(dir)) throw new Error(`You already have a skill called "${id}". Choose another name, or edit the one you have.`);
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'SKILL.md'), skillFileText({ name: id, title: String(name).trim(), description, body }));
return id;
}
/**
* Make `root` hold exactly the skills the agent may use: one folder each, a SKILL.md with frontmatter. A skill switched off is written
* with `disable-model-invocation` (the agent does not offer it); folders of skills that are gone are removed. Only this folder is touched.
* @param {string} root
* @param {Array<{id: string, name: string, description?: string, body?: string, enabled?: boolean}>} skills
*/
export function materializeSkills(root, skills) {
mkdirSync(root, { recursive: true });
const keep = new Set();
for (const s of skills) {
const slug = skillSlug(s.id.replace(/^(?:ws|my)-/, '') || s.name);
if (!slug || !s.body?.trim()) continue;
let unique = slug, n = 2;
while (keep.has(unique)) unique = `${slug}-${n++}`;
keep.add(unique);
const dir = join(root, unique);
mkdirSync(dir, { recursive: true });
const text = skillFileText({ name: unique, description: `${s.name}. ${s.description ?? ''}`.trim(), body: s.body, hidden: s.enabled === false });
const file = join(dir, 'SKILL.md');
// Only a changed skill is rewritten: the agent watches this folder and treats every write as a change to its list.
let same = false; try { same = readFileSync(file, 'utf8') === text; } catch { /* not there yet */ }
if (!same) writeFileSync(file, text);
}
for (const entry of readdirSync(root, { withFileTypes: true })) if (entry.isDirectory() && !keep.has(entry.name)) rmSync(join(root, entry.name), { recursive: true, force: true });
return [...keep];
}
+6 -1
View File
@@ -3035,5 +3035,10 @@
"s3037": "Deine Dateien werden gelesen…",
"s3038": "Eine verbesserte Version wird ausprobiert…",
"s3039": "Das Ergebnis wird geprüft…",
"s3040": "Die beiden Versionen werden verglichen…"
"s3040": "Die beiden Versionen werden verglichen…",
"s3041": "Neuer Skill",
"s3042": "Skill speichern",
"s3043": "Dein Skill wird geladen",
"s3044": "Deinen Skill geladen",
"s3045": "Der Skill ließ sich nicht laden"
}
+6 -1
View File
@@ -3035,5 +3035,10 @@
"s3037": "Reading your files…",
"s3038": "Trying an improved version…",
"s3039": "Checking the result…",
"s3040": "Comparing the two versions…"
"s3040": "Comparing the two versions…",
"s3041": "New skill",
"s3042": "Save skill",
"s3043": "Loading your skill",
"s3044": "Loaded your skill",
"s3045": "Couldn't load the skill"
}
+6 -1
View File
@@ -3035,5 +3035,10 @@
"s3037": "Leyendo tus archivos…",
"s3038": "Probando una versión mejorada…",
"s3039": "Comprobando el resultado…",
"s3040": "Comparando las dos versiones…"
"s3040": "Comparando las dos versiones…",
"s3041": "Nueva habilidad",
"s3042": "Guardar habilidad",
"s3043": "Cargando tu habilidad",
"s3044": "Cargó tu habilidad",
"s3045": "No se pudo cargar la habilidad"
}
+6 -1
View File
@@ -3035,5 +3035,10 @@
"s3037": "ファイルを読んでいます…",
"s3038": "改良版を試しています…",
"s3039": "結果を確認しています…",
"s3040": "2つの版を比較しています…"
"s3040": "2つの版を比較しています…",
"s3041": "新しいスキル",
"s3042": "スキルを保存",
"s3043": "スキルを読み込んでいます",
"s3044": "スキルを読み込みました",
"s3045": "スキルを読み込めませんでした"
}
+6 -1
View File
@@ -3035,5 +3035,10 @@
"s3037": "파일을 읽는 중…",
"s3038": "개선된 버전을 시도하는 중…",
"s3039": "결과를 확인하는 중…",
"s3040": "두 버전을 비교하는 중…"
"s3040": "두 버전을 비교하는 중…",
"s3041": "새 스킬",
"s3042": "스킬 저장",
"s3043": "스킬을 불러오는 중",
"s3044": "스킬을 불러왔습니다",
"s3045": "스킬을 불러올 수 없었습니다"
}
+6 -1
View File
@@ -3035,5 +3035,10 @@
"s3037": "Lendo os seus arquivos…",
"s3038": "Testando uma versão melhorada…",
"s3039": "Verificando o resultado…",
"s3040": "Comparando as duas versões…"
"s3040": "Comparando as duas versões…",
"s3041": "Nova habilidade",
"s3042": "Salvar habilidade",
"s3043": "Carregando a sua habilidade",
"s3044": "Carregou a sua habilidade",
"s3045": "Não foi possível carregar a habilidade"
}
+6 -1
View File
@@ -3035,5 +3035,10 @@
"s3037": "Чтение ваших файлов…",
"s3038": "Пробуется улучшенная версия…",
"s3039": "Проверка результата…",
"s3040": "Сравнение двух версий…"
"s3040": "Сравнение двух версий…",
"s3041": "Новый навык",
"s3042": "Сохранить навык",
"s3043": "Загрузка вашего навыка",
"s3044": "Ваш навык загружен",
"s3045": "Не удалось загрузить навык"
}
+6 -1
View File
@@ -3035,5 +3035,10 @@
"s3037": "正在读取你的文件…",
"s3038": "正在尝试改进版本…",
"s3039": "正在检查结果…",
"s3040": "正在比较两个版本…"
"s3040": "正在比较两个版本…",
"s3041": "新建技能",
"s3042": "保存技能",
"s3043": "正在加载你的技能",
"s3044": "已加载你的技能",
"s3045": "无法加载技能"
}
+10 -2
View File
@@ -38,6 +38,8 @@ export function SkillsScreen() {
if (!result.cancelled)
await loadSkills();
}
/** A skill written here: a name, what it is for, and the instructions. Saved as a folder the assistant reads; it is there for the next message. */
function openNew() { setTab('details'); setEditing({ id: '', name: '', description: '', body: '', triggers: [], enabled: true, source: 'created', onlyIn: null, sizeKb: 0, useCount: 0, lastUsedAt: null } as unknown as Skill); setTriggers(''); setError(''); }
function openEditor(skill: Skill) { setTab('details'); setEditing({ ...skill }); setTriggers(skill.triggers.join(', ')); setError(''); }
function closeEditor() {
if (!pending) {
@@ -48,16 +50,22 @@ export function SkillsScreen() {
async function save() {
if (!editing)
return;
if (!editing.id) {
await api.post('/api/skills', { name: editing.name.trim(), description: editing.description.trim(), body: editing.body ?? '' });
await loadSkills();
setEditing(null);
return;
}
await editSkill(editing.id, { name: editing.name.trim(), description: editing.description.trim(), body: editing.body, triggers: triggers.split(',').map(t => t.trim()).filter(Boolean), enabled: editing.enabled, onlyIn: editing.onlyIn ?? null });
setEditing(null);
}
return <Screen title={tr("Skills")} titleDetail={tr("Manage your skills library")} actions={<><Btn icon="folder-plus" disabled={!!pending} onClick={() => void action('add', add)}>{tr("Add skill")}</Btn><input className="st-input skills-header-search" type="search" aria-label={tr("Search skills")} placeholder={tr("Search skills…")} value={query} onChange={e => setQuery(e.target.value)}/><IconBtn name="refresh" title={tr("Refresh skills")} disabled={!!pending} onClick={() => void action('refresh', loadSkills)}/></>}>
return <Screen title={tr("Skills")} titleDetail={tr("Manage your skills library")} actions={<><Btn icon="plus" variant="primary" disabled={!!pending} onClick={openNew}>{tr("New skill")}</Btn><Btn icon="folder-plus" disabled={!!pending} onClick={() => void action('add', add)}>{tr("Add skill")}</Btn><input className="st-input skills-header-search" type="search" aria-label={tr("Search skills")} placeholder={tr("Search skills…")} value={query} onChange={e => setQuery(e.target.value)}/><IconBtn name="refresh" title={tr("Refresh skills")} disabled={!!pending} onClick={() => void action('refresh', loadSkills)}/></>}>
<div className="skills-page">{tr(error && !editing ? <ErrorNotice message={error} action={tr("Retry")} onRetry={() => void action('refresh', loadSkills)}/> : null)}
{tr((['bundled', 'added'] as const).map(group => { const rows = visible.filter(s => group === 'bundled' ? s.source === 'bundled' : s.source !== 'bundled'); return rows.length ? <section className="skill-group" aria-label={tr(group === 'bundled' ? 'Built-in skills' : 'Added skills')} key={group}>{tr(group === 'added' ? <h3 className="h4">{tr("Added skills")}</h3> : null)}<div>{tr(rows.map(s => <article className="skill-row" key={s.id}><span className="skill-symbol"><Icon name="skills" size={26}/></span><div className="skill-copy"><h3 className="h4">{s.source === 'bundled' ? tr(s.name) : s.name}</h3><p className="small muted">{s.source === 'bundled' ? tr(s.description) : s.description}</p>{tr(s.onlyIn ? <span className="xs muted">{tr(s.onlyIn === workspace ? 'This workspace' : `Only in ${workspaces.find(w => w.id === s.onlyIn)?.name ?? 'another workspace'}`)}</span> : null)}</div><div className="skill-row-actions"><IconBtn name="pencil" title={tr("Edit {0}", [s.name])} disabled={!!pending} onClick={() => openEditor(s)}/><button className="st-toggle" role="switch" aria-checked={s.enabled} aria-label={tr("Enable {0}", [s.name])} disabled={!!pending} onClick={() => void action(s.id, () => toggleSkill(s.id, !s.enabled))}/></div></article>))}</div></section> : null; }))}
{tr(!visible.length ? <Empty icon="skills" title={tr(skills.length ? 'No matching skills' : 'No skills yet')} body={skills.length ? 'Try another search.' : 'Add a folder containing SKILL.md.'} action={tr(<Btn onClick={() => skills.length ? setQuery('') : void action('add', add)}>{tr(skills.length ? 'Clear search' : 'Add skill')}</Btn>)}/> : null)}
</div>
<Dialog open={!!editing} title={tr("Edit skill")} onClose={closeEditor} actions={<><Btn disabled={!!pending} onClick={closeEditor}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!!pending || !editing?.name.trim() || !editing?.body?.trim()} onClick={() => void action(editing!.id, save)}>{tr(pending ? 'Saving…' : 'Save changes')}</Btn></>}>
<Dialog open={!!editing} title={tr(editing && !editing.id ? 'New skill' : 'Edit skill')} onClose={closeEditor} actions={<><Btn disabled={!!pending} onClick={closeEditor}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!!pending || !editing?.name.trim() || !editing?.body?.trim()} onClick={() => void action(editing!.id, save)}>{tr(pending ? 'Saving…' : editing && !editing.id ? 'Save skill' : 'Save changes')}</Btn></>}>
{tr(editing ? <><div className="editor-tabs" role="tablist" aria-label={tr("Skill editor sections")}>{tr((['details', 'instructions'] as const).map(t => <button key={t} id={`skill-tab-${t}`} role="tab" aria-selected={tab === t} aria-controls={`skill-panel-${t}`} tabIndex={tab === t ? 0 : -1} onClick={() => setTab(t)} onKeyDown={e => {
if (['ArrowLeft', 'ArrowRight'].includes(e.key)) {
e.preventDefault();
+90
View File
@@ -0,0 +1,90 @@
/**
* Skills, end to end: a skill written in the app is saved as a folder, written out for the agent, listed in the agent's skill catalog,
* loadable by name through the `skill` tool, and a skill added or switched off later reaches the NEXT message without a restart.
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { startScriptedWorker } from './helpers/scripted-worker.mjs';
import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
import { resolveHarness } from '../server/agent/harness-runtime.mjs';
import { buildProfile } from '../server/agent/profile.mjs';
import { materializeSkills, parseSkillFile, skillFileText, skillSlug, writeCreatedSkill } from '../server/skill-files.mjs';
const skip = !process.env.STRATA_HARNESS_DIR || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } };
const INSTRUCTIONS = 'Open the Downloads folder, then open the Documents folder, using the command line. Say which folders you opened.';
test('a skill name becomes the kebab-case name the agent requires, and its file carries what the agent reads', () => {
assert.equal(skillSlug('Directory opener'), 'directory-opener');
assert.equal(skillSlug(' Écrire des notes!! '), 'ecrire-des-notes');
assert.equal(skillSlug('???'), '');
const text = skillFileText({ name: 'directory-opener', title: 'Directory opener', description: 'Opens "folders"\nfor you', body: INSTRUCTIONS });
const parsed = parseSkillFile(text);
assert.deepEqual([parsed.name, parsed.title, parsed.description, parsed.body], ['directory-opener', 'Directory opener', 'Opens "folders" for you', INSTRUCTIONS]);
assert.match(skillFileText({ name: 'x', description: 'd', body: 'b', hidden: true }), /disable-model-invocation: true/);
assert.deepEqual(parseSkillFile('just text'), { name: null, title: null, description: null, body: 'just text' });
});
test('writing a skill refuses a duplicate and an empty name, and materializing makes the agent folder match the list exactly', () => {
const dir = mkdtempSync(join(tmpdir(), 'strata-skill-files-'));
try {
const mine = join(dir, 'mine');
assert.equal(writeCreatedSkill(mine, { name: 'Directory opener', description: 'Opens folders', body: INSTRUCTIONS }), 'directory-opener');
assert.throws(() => writeCreatedSkill(mine, { name: 'directory opener', body: 'x' }), /already have a skill/);
assert.throws(() => writeCreatedSkill(mine, { name: '!!!', body: 'x' }), /name with letters/);
const live = join(dir, 'live');
const list = [{ id: 'my-directory-opener', name: 'Directory opener', description: 'Opens folders', body: INSTRUCTIONS, enabled: true },
{ id: 'commit-messages', name: 'Commit messages', description: 'Writes commits', body: 'Write them well.', enabled: false },
{ id: 'ws-empty', name: 'Empty', body: '', enabled: true }];
assert.deepEqual(materializeSkills(live, list).sort(), ['commit-messages', 'directory-opener']);
assert.match(readFileSync(join(live, 'commit-messages', 'SKILL.md'), 'utf8'), /disable-model-invocation: true/);
assert.ok(!existsSync(join(live, 'empty')), 'a skill with no instructions is not offered');
mkdirSync(join(live, 'old-one'));
materializeSkills(live, list.slice(0, 1));
assert.ok(!existsSync(join(live, 'old-one')) && !existsSync(join(live, 'commit-messages')), 'removed skills disappear from the agent folder');
} finally { cleanup(dir); }
});
test('the agent profile tells the skills plugin to scan the app skill folder', () => {
const dir = '/data/agent/skills-live';
const entries = JSON.parse(buildProfile({ local: [], connections: [], skillsDir: dir }).patch.split('\n').slice(1).join('\n'));
const plugins = entries.find(e => e.id === 'preset-standard').config.plugins;
assert.deepEqual(plugins.find(p => p.id === 'skill-filesystem').config, { customSkillDirs: [dir] });
assert.ok(plugins.some(p => p.id === 'tool-skill'), 'the skill loader tool is in the preset');
});
test('real Harness: a skill saved in the app is in the catalog, loads by name, and one added later is seen without a restart', { skip }, async (t) => {
const worker = await startScriptedWorker({});
const dir = mkdtempSync(join(tmpdir(), 'strata-skills-'));
const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
const live = join(dir, 'skills-live');
const list = [{ id: 'my-directory-opener', name: 'Directory opener', description: 'Opens the Downloads and Documents folders', body: INSTRUCTIONS, enabled: true }];
materializeSkills(live, list);
const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2 }];
const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], skillsDir: () => live, env: process.env, startTimeoutMs: 90_000 });
t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
const run = async (chatId, message) => {
const frames = [];
await bridge.runTurn({ chatId, message, workspacePath: ws, mode: 'bypass', onFrame: f => frames.push(f) });
return frames.filter(f => f.type === 'agent-tool').map(f => f.tool);
};
await run('s1', 'SCRIPT:say hello');
const first = worker.requests.at(-1);
assert.ok(first.toolNames.includes('skill'), 'the agent has the skill loader');
assert.match(first.raw, /directory-opener/, 'the skill is in what the model is told');
const pid = bridge.status().runtime.pid;
const cards = await run('s1', `SCRIPT:call skill ${JSON.stringify({ name: 'directory-opener' })}`);
assert.equal(cards.at(-1).state, 'done');
assert.equal(cards.at(-1).verb, 'Loaded your skill', 'the card says it in the person own words');
assert.match(cards.at(-1).result, /Open the Downloads folder, then open the Documents folder/, 'loading it returns the instructions the person wrote');
// saved later, while the agent runs
list.push({ id: 'my-release-notes', name: 'Release notes', description: 'Writes release notes', body: 'Start with one line.', enabled: true });
materializeSkills(live, list);
let seen = false;
for (let i = 0; i < 20 && !seen; i++) { await new Promise(r => setTimeout(r, 500)); await run('s2', 'SCRIPT:say hi'); seen = /release-notes/.test(worker.requests.at(-1).raw); }
assert.ok(seen, 'a skill saved while the agent runs reaches a later message');
assert.equal(bridge.status().runtime.pid, pid, 'without restarting the agent');
});
+11
View File
@@ -165,3 +165,14 @@ test('a sentence with a name or a number also carries its catalog template and v
'Opening {0}…', 'Opening a web page…', 'Using the browser…', 'Setting the goal…', 'Updating the goal…', 'Checking the goal…', 'Using a tool…', 'Reading your files…', 'Trying an improved version…', 'Checking the result…', 'Comparing the two versions…'];
for (const key of keys) { const id = idOf(key); assert.ok(id, `${key} is in the catalog`); for (const l of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) { assert.ok(catalog[l][id]?.trim(), `${l}: ${key}`); assert.deepEqual((catalog[l][id].match(/\{\d\}/g) ?? []).sort(), (key.match(/\{\d\}/g) ?? []).sort(), `${l} keeps the slots of ${key}`); } }
});
test('a goal step is always sent, even right after another status (it used to be swallowed by the 300 ms gap, which made a test flaky)', () => {
const { reporter, frames, advance } = rig();
reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' });
advance(20);
reporter.set({ phase: 'goal', code: 'goal-step', text: 'Working on the goal, step 1', key: 'Working on the goal, step {0}', values: [1], args: { round: 1, max: 3 } });
advance(10);
reporter.set({ phase: 'thinking', code: 'thinking', text: 'Thinking… 1 tokens', tokens: 1 });
advance(400);
assert.ok(frames.some(f => f.phase === 'goal' && f.args.round === 1), frames.map(f => f.phase).join(','));
});
+1 -1
View File
@@ -65,7 +65,7 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =
lastRole: last.role, directive: directive?.[1] ?? null, messageCount: messages.length,
authorization: req.headers.authorization ? 'present' : 'absent',
authSha: req.headers.authorization ? createHash('sha256').update(req.headers.authorization).digest('hex') : null,
promptChars: raw.length,
promptChars: raw.length, raw,
});
const shellName = () => (body.tools ?? []).find(t => ['bash', 'pwsh'].includes(t.function?.name))?.function?.name ?? 'bash';
const shellCommand = (file, value) => (shellName() === 'pwsh' ? `Add-Content -Path '${file}' -Value '${value}'` : `echo ${value} >> ${file}`);