diff --git a/apps/host/scripts/agent-http.mjs b/apps/host/scripts/agent-http.mjs new file mode 100644 index 00000000..2f18b0bd --- /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 [args] + * + * connect save an API connection to a model server (once per STRATA_HOME) + * stream "" [mode] one chat turn; prints every frame compactly with its time (status, goal, tools, deltas counted) + * goal "" /goal run, then the goal bar calls: state, pause, edit, clear, resume + * timeskip "" [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); +} diff --git a/apps/host/scripts/skills-shot.mjs b/apps/host/scripts/skills-shot.mjs new file mode 100644 index 00000000..e0b23dec --- /dev/null +++ b/apps/host/scripts/skills-shot.mjs @@ -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(); } diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index a1e18ba3..6c10fff2 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/events.mjs b/apps/host/server/agent/events.mjs index 4bc58407..749d4b2e 100644 --- a/apps/host/server/agent/events.mjs +++ b/apps/host/server/agent/events.mjs @@ -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"], diff --git a/apps/host/server/agent/preset.mjs b/apps/host/server/agent/preset.mjs index 3a213d07..bd36e68c 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 3129c0ed..3d076838 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, 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/agent/status.mjs b/apps/host/server/agent/status.mjs index aff00f95..60bb3d9d 100644 --- a/apps/host/server/agent/status.mjs +++ b/apps/host/server/agent/status.mjs @@ -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); } diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 128f629d..5914dde0 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 `/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 00000000..e76771ca --- /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 (`/skills//SKILL.md`). The agent (the Harness) finds skills by scanning + * folders of `/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/locales/de.json b/apps/host/src/locales/de.json index 296ac9a0..124e034b 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -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" } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index 9d7d67b7..9870caad 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -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" } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index 54338fd8..c5c32346 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -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" } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index a7e26689..e4fb7050 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3035,5 +3035,10 @@ "s3037": "ファイルを読んでいます…", "s3038": "改良版を試しています…", "s3039": "結果を確認しています…", - "s3040": "2つの版を比較しています…" + "s3040": "2つの版を比較しています…", + "s3041": "新しいスキル", + "s3042": "スキルを保存", + "s3043": "スキルを読み込んでいます", + "s3044": "スキルを読み込みました", + "s3045": "スキルを読み込めませんでした" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index 3d1477ab..64b494ab 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3035,5 +3035,10 @@ "s3037": "파일을 읽는 중…", "s3038": "개선된 버전을 시도하는 중…", "s3039": "결과를 확인하는 중…", - "s3040": "두 버전을 비교하는 중…" + "s3040": "두 버전을 비교하는 중…", + "s3041": "새 스킬", + "s3042": "스킬 저장", + "s3043": "스킬을 불러오는 중", + "s3044": "스킬을 불러왔습니다", + "s3045": "스킬을 불러올 수 없었습니다" } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index df87c752..1982b966 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -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" } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index 03c7ba46..390f0672 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3035,5 +3035,10 @@ "s3037": "Чтение ваших файлов…", "s3038": "Пробуется улучшенная версия…", "s3039": "Проверка результата…", - "s3040": "Сравнение двух версий…" + "s3040": "Сравнение двух версий…", + "s3041": "Новый навык", + "s3042": "Сохранить навык", + "s3043": "Загрузка вашего навыка", + "s3044": "Ваш навык загружен", + "s3045": "Не удалось загрузить навык" } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index 0e14a4eb..4eb36ff5 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3035,5 +3035,10 @@ "s3037": "正在读取你的文件…", "s3038": "正在尝试改进版本…", "s3039": "正在检查结果…", - "s3040": "正在比较两个版本…" + "s3040": "正在比较两个版本…", + "s3041": "新建技能", + "s3042": "保存技能", + "s3043": "正在加载你的技能", + "s3044": "已加载你的技能", + "s3045": "无法加载技能" } diff --git a/apps/host/src/screens/Skills.tsx b/apps/host/src/screens/Skills.tsx index 85d50441..7ad8efd1 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 void action('add', add)}>{tr("Add skill")} setQuery(e.target.value)}/> void action('refresh', loadSkills)}/>}> + return {tr("New skill")} void action('add', add)}>{tr("Add skill")} setQuery(e.target.value)}/> void action('refresh', loadSkills)}/>}>
{tr(error && !editing ? 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 ?
{tr(group === 'added' ?

{tr("Added skills")}

: null)}
{tr(rows.map(s =>

{s.source === 'bundled' ? tr(s.name) : s.name}

{s.source === 'bundled' ? tr(s.description) : s.description}

{tr(s.onlyIn ? {tr(s.onlyIn === workspace ? 'This workspace' : `Only in ${workspaces.find(w => w.id === s.onlyIn)?.name ?? 'another workspace'}`)} : null)}
openEditor(s)}/>
))}
: null; }))} {tr(!visible.length ? skills.length ? setQuery('') : void action('add', add)}>{tr(skills.length ? 'Clear search' : 'Add skill')})}/> : null)}
- {tr("Cancel")} void action(editing!.id, save)}>{tr(pending ? 'Saving…' : 'Save changes')}}> + {tr("Cancel")} void action(editing!.id, save)}>{tr(pending ? 'Saving…' : editing && !editing.id ? 'Save skill' : 'Save changes')}}> {tr(editing ? <>
{tr((['details', 'instructions'] as const).map(t =>