Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Skills: write one in the Skills page (New skill), saved as a folder in the app's data; the whole list is written out for the agent, which scans it (customSkillDirs) and watches it, so a saved skill reaches the next message without a restart; tests

Niko12214818b1f4a16f
diff --git a/apps/host/scripts/agent-http.mjs b/apps/host/scripts/agent-http.mjs
new file mode 100644
index 000000000..e7603316b
--- /dev/null
+++ b/apps/host/scripts/agent-http.mjs
@@ -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.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);
+}
diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs
index a1e18ba33..6c10fff2e 100644
--- a/apps/host/server/agent/agent-bridge.mjs
+++ b/apps/host/server/agent/agent-bridge.mjs
@@ -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
diff --git a/apps/host/server/agent/preset.mjs b/apps/host/server/agent/preset.mjs
index 3a213d070..bd36e68c0 100644
--- a/apps/host/server/agent/preset.mjs
+++ b/apps/host/server/agent/preset.mjs
@@ -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' },
diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs
index 3129c0edf..3d076838d 100644
--- a/apps/host/server/agent/profile.mjs
+++ b/apps/host/server/agent/profile.mjs
@@ -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 },
diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs
index 128f629d9..5914dde0b 100644
--- a/apps/host/server/index.mjs
+++ b/apps/host/server/index.mjs
@@ -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);
}
diff --git a/apps/host/server/skill-files.mjs b/apps/host/server/skill-files.mjs
new file mode 100644
index 000000000..e76771ca7
--- /dev/null
+++ b/apps/host/server/skill-files.mjs
@@ -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];
+}
diff --git a/apps/host/src/screens/Skills.tsx b/apps/host/src/screens/Skills.tsx
index 85d50441f..7ad8efd16 100644
--- a/apps/host/src/screens/Skills.tsx
+++ b/apps/host/src/screens/Skills.tsx
@@ -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();
diff --git a/apps/host/tests/agent-skills.test.mjs b/apps/host/tests/agent-skills.test.mjs
new file mode 100644
index 000000000..32442868a
--- /dev/null
+++ b/apps/host/tests/agent-skills.test.mjs
@@ -0,0 +1,89 @@
+/**
+ * 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.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');
+});
diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjs
index c94af3ede..961d40d28 100644
--- a/apps/host/tests/helpers/scripted-worker.mjs
+++ b/apps/host/tests/helpers/scripted-worker.mjs
@@ -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}`);