diff --git a/apps/host/server/agent/gateway-client.mjs b/apps/host/server/agent/gateway-client.mjs new file mode 100644 index 00000000..55b5ed3e --- /dev/null +++ b/apps/host/server/agent/gateway-client.mjs @@ -0,0 +1,147 @@ +/** + * A client for the Harness Gateway (the `dsh web` HTTP + WebSocket surface). + * + * Two carriers, both authenticated by the cookie the launch URL's token buys: + * - HTTP unary RPC: POST /api/ with the gateway's envelope + * - WebSocket mux: /api/remote.mux carrying many independent logical streams + * + * The streams used here are `$events` (Host notifications and the approval waterfall) and + * `session/follow` (a session's durable event log plus live assistant frames). + * + * Node 24's global WebSocket accepts a `headers` option, which is how the cookie reaches the upgrade. + * No dependency is added to the host. + */ + +export class GatewayError extends Error { + constructor(message, { code = 'gateway/error', details } = {}) { + super(message); + this.name = 'GatewayError'; + this.code = code; + this.details = details; + } +} + +export class GatewayClient { + #base; #token; #cookie = null; #rpcId = 0; #ws = null; #wsReady = null; #streams = new Map(); #nextStream = 0; + #closed = false; #reconnectTimer = null; #onState; + + /** + * @param {{baseUrl: string, token: string, onState?: (state: 'open'|'closed') => void}} options + */ + constructor({ baseUrl, token, onState = () => {} }) { + this.#base = baseUrl.replace(/\/+$/, ''); + this.#token = token; + this.#onState = onState; + } + + /** Exchange the launch token for the API cookie. */ + async connect() { + const res = await fetch(`${this.#base}/?token=${encodeURIComponent(this.#token)}`, { redirect: 'manual' }); + const cookie = (res.headers.get('set-cookie') ?? '').split(';')[0]; + if (!cookie.startsWith('dsh-auth-')) throw new GatewayError(`the agent refused the launch token (HTTP ${res.status})`, { code: 'gateway/auth' }); + this.#cookie = cookie; + } + + /** One unary call. Resolves with the value, rejects with a GatewayError carrying the gateway's code. */ + async rpc(method, args = {}, { signal } = {}) { + if (!this.#cookie) throw new GatewayError('not connected', { code: 'gateway/not-connected' }); + const rpcId = `h${++this.#rpcId}`; + const res = await fetch(`${this.#base}/api/${method}`, { + method: 'POST', + headers: { 'content-type': 'application/json', cookie: this.#cookie }, + body: JSON.stringify({ type: 'client-request', rpcId, method, payload: { args } }), + signal, + }); + let body; + try { body = await res.json(); } catch { throw new GatewayError(`${method}: the agent returned a non-JSON answer (HTTP ${res.status})`, { code: 'gateway/bad-response' }); } + const result = body?.result; + if (!result?.ok) { + const e = result?.error ?? {}; + throw new GatewayError(`${method}: ${e.message ?? `HTTP ${res.status}`}`, { code: e.code ?? 'gateway/error', details: e.details }); + } + return result.value; + } + + /** + * Open a logical stream on the mux. Handlers: `onItem(value)`, `onEnd()`, `onError(error)`. + * The stream is re-opened after a socket reconnect and `onItem` receives it from the start again + * (a `session/follow` opens with a fresh snapshot, so callers de-duplicate by sequence number). + */ + openStream(endpoint, args, handlers) { + const streamId = `s${++this.#nextStream}`; + const entry = { streamId, endpoint, args, ...handlers, closed: false }; + this.#streams.set(streamId, entry); + void this.#ensureSocket().then(() => this.#sendOpen(entry), () => {}); + return { + streamId, + close: () => { + entry.closed = true; + this.#streams.delete(streamId); + if (this.#ws?.readyState === 1) { + try { this.#ws.send(JSON.stringify({ type: 'cancel', streamId })); } catch { /* socket going away */ } + } + }, + }; + } + + /** Answer one forwarded approval waterfall. `outcome` is `allowed-once`, `rejected`, or `next`. */ + async answerEvent({ clientId, eventId, outcome }) { + const wire = outcome === 'next' ? { kind: 'next' } : { kind: 'result', value: outcome }; + return this.rpc('$events/result', { clientId, eventId, outcome: wire }); + } + + close() { + this.#closed = true; + clearTimeout(this.#reconnectTimer); + for (const s of this.#streams.values()) s.closed = true; + this.#streams.clear(); + try { this.#ws?.close(); } catch { /* already closed */ } + this.#ws = null; + } + + // -- socket --------------------------------------------------------------------------------------- + + #ensureSocket() { + if (this.#closed) return Promise.reject(new GatewayError('closed', { code: 'gateway/closed' })); + if (this.#ws && this.#ws.readyState === 1) return Promise.resolve(); + if (this.#wsReady) return this.#wsReady; + this.#wsReady = new Promise((resolve, reject) => { + const url = `${this.#base.replace(/^http/, 'ws')}/api/remote.mux`; + const ws = new WebSocket(url, { headers: { cookie: this.#cookie } }); + this.#ws = ws; + ws.onopen = () => { this.#wsReady = null; this.#onState('open'); resolve(); }; + ws.onmessage = e => this.#onMessage(String(e.data)); + ws.onerror = () => { /* the close handler reports it */ }; + ws.onclose = () => { + const wasReady = this.#wsReady; + this.#wsReady = null; + if (this.#ws === ws) this.#ws = null; + this.#onState('closed'); + if (wasReady) reject(new GatewayError('the agent socket closed before it opened', { code: 'gateway/socket' })); + if (this.#closed) return; + // Streams are re-opened by a new socket; a dropped socket must not strand a follower. + clearTimeout(this.#reconnectTimer); + if (this.#streams.size) this.#reconnectTimer = setTimeout(() => { + this.#ensureSocket().then(() => { for (const s of this.#streams.values()) this.#sendOpen(s); }).catch(() => { + for (const s of [...this.#streams.values()]) s.onError?.(new GatewayError('the agent socket could not be re-opened', { code: 'gateway/socket' })); + }); + }, 500); + }; + }); + return this.#wsReady; + } + + #sendOpen(entry) { + if (entry.closed || this.#ws?.readyState !== 1) return; + this.#ws.send(JSON.stringify({ type: 'open', streamId: entry.streamId, endpoint: entry.endpoint, payload: { args: entry.args } })); + } + + #onMessage(text) { + let m; try { m = JSON.parse(text); } catch { return; } + const s = this.#streams.get(m.streamId); + if (!s) return; + if (m.type === 'item') s.onItem?.(m.value); + else if (m.type === 'end') { this.#streams.delete(s.streamId); s.onEnd?.(); } + else if (m.type === 'error') s.onError?.(new GatewayError(m.error?.message ?? 'stream failed', { code: m.error?.code, details: m.error?.details })); + } +} diff --git a/apps/host/server/agent/harness-runtime.mjs b/apps/host/server/agent/harness-runtime.mjs new file mode 100644 index 00000000..f9df9ef9 --- /dev/null +++ b/apps/host/server/agent/harness-runtime.mjs @@ -0,0 +1,121 @@ +/** + * Locates and runs the pinned DeepSeek Harness (`dsh`) for the web profile. + * + * The Harness is a separate component, not part of the host: it is found through `STRATA_HARNESS_DIR` + * (or `/harness`), checked for the files a run needs, and started with the Strata profile + * on a loopback port the OS picks. Nothing here downloads or installs anything. + * + * One process, one gateway, many sessions: every chat is a Harness session inside it, and cancelling + * one chat never touches the process. Stopping the process is a lifecycle act (shutdown, or a model + * route change while idle), never a way to implement Stop. + */ +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +const URL_PATTERN = /http:\/\/127\.0\.0\.1:(\d+)\/\?token=([A-Za-z0-9_-]+)/; + +/** Environment names that carry ambient credentials and must not reach the agent unless named. */ +const SECRET_NAME = /(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH)/i; +/** Names the agent and its shell tools need to behave like a normal user process. */ +const KEEP = /^(PATH|PATHEXT|SYSTEMROOT|WINDIR|COMSPEC|TEMP|TMP|TMPDIR|HOME|USERPROFILE|HOMEDRIVE|HOMEPATH|APPDATA|LOCALAPPDATA|PROGRAMDATA|PROGRAMFILES(\(X86\))?|PROGRAMW6432|COMMONPROGRAMFILES(\(X86\))?|USERNAME|USERDOMAIN|COMPUTERNAME|OS|PROCESSOR_ARCHITECTURE|NUMBER_OF_PROCESSORS|LANG|LC_ALL|TERM|SHELL|USER|LOGNAME|XDG_.*|SYSTEMDRIVE|PSMODULEPATH)$/i; + +/** The environment the agent gets: a filtered copy of the host's, plus exactly the names passed in `extra`. */ +export function agentEnvironment(base = process.env, extra = {}) { + const out = {}; + for (const [k, v] of Object.entries(base)) { + if (v === undefined || !KEEP.test(k) || SECRET_NAME.test(k)) continue; + out[k] = v; + } + return { ...out, DSH_TELEMETRY_DISABLED: '1', ...extra }; +} + +/** + * Find a usable Harness. Returns `{ ok:true, dir, bin, version }` or `{ ok:false, reason }`; the reason + * is user-readable because it becomes the capability state shown in the app. + */ +export function resolveHarness({ env = process.env, componentsDir = null } = {}) { + const candidates = [env.STRATA_HARNESS_DIR, componentsDir ? join(componentsDir, 'harness') : null].filter(Boolean); + if (!candidates.length) return { ok: false, reason: 'The agent component (DeepSeek Harness) is not installed.' }; + for (const dir of candidates.map(c => resolve(c))) { + const bin = join(dir, 'apps', 'cli', 'lib', 'bin.js'); + if (!existsSync(bin)) continue; + if (!existsSync(join(dir, 'node_modules'))) return { ok: false, reason: `The agent component at ${dir} has no installed dependencies.` }; + let version = null; + try { version = JSON.parse(readFileSync(join(dir, 'apps', 'cli', 'package.json'), 'utf8')).version ?? null; } catch { /* version is informational */ } + return { ok: true, dir, bin, version }; + } + return { ok: false, reason: `The agent component was not found at ${candidates.join(' or ')}. Install or repair it.` }; +} + +export class HarnessProcess { + #child = null; + /** @type {{baseUrl:string, token:string, port:number}|null} */ + info = null; + exited = null; + #onExit; + + constructor({ harness, home, patchFile, cwd, env = {}, nodePath = process.execPath, logFile = null, onExit = () => {} }) { + Object.assign(this, { harness, home, patchFile, cwd, extraEnv: env, nodePath, logFile }); + this.#onExit = onExit; + } + + get pid() { return this.#child?.pid ?? null; } + get running() { return this.#child !== null && this.exited === null; } + + /** Start the agent and resolve with its loopback URL and launch token. */ + async start({ timeoutMs = 120_000 } = {}) { + mkdirSync(this.home, { recursive: true }); + mkdirSync(this.cwd, { recursive: true }); + const args = [this.harness.bin, '--profile', 'web', '--patch', this.patchFile, '--port', '0', '--no-open']; + const child = spawn(this.nodePath, args, { + cwd: this.cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], + env: agentEnvironment(process.env, { ...this.extraEnv, DSH_HOME: this.home }), + }); + this.#child = child; + let text = ''; + const log = []; + const keep = chunk => { log.push(chunk.toString()); if (log.length > 200) log.shift(); }; + child.on('exit', (code, signal) => { + this.exited = { code, signal }; + if (this.logFile) { try { writeFileSync(this.logFile, redact(log.join(''), Object.values(this.extraEnv))); } catch { /* best effort */ } } + this.#onExit(this.exited); + }); + child.stderr.on('data', keep); + const info = await new Promise((resolveInfo, reject) => { + const timer = setTimeout(() => reject(new Error(`the agent did not print its address within ${Math.round(timeoutMs / 1000)}s`)), timeoutMs); + child.stdout.on('data', chunk => { + keep(chunk); + text += chunk.toString(); + const m = URL_PATTERN.exec(text); + if (m) { clearTimeout(timer); resolveInfo({ port: Number(m[1]), token: m[2], baseUrl: `http://127.0.0.1:${m[1]}` }); } + }); + child.on('exit', code => { clearTimeout(timer); reject(new Error(`the agent exited during start (code ${code}): ${redact(log.join('').slice(-600), Object.values(this.extraEnv))}`)); }); + child.on('error', e => { clearTimeout(timer); reject(e); }); + }).catch(async error => { await this.stop(); throw error; }); + this.info = info; + return info; + } + + /** Stop this process and its children. Only ever touches the PID this object started. */ + async stop({ graceMs = 3000 } = {}) { + const child = this.#child; + if (!child || this.exited) return; + const done = new Promise(r => child.once('exit', r)); + if (process.platform === 'win32') { + // /T takes the shells and PTYs the agent started; /PID is this child only. + spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }); + } else { + child.kill('SIGTERM'); + setTimeout(() => { if (!this.exited) child.kill('SIGKILL'); }, graceMs).unref(); + } + await Promise.race([done, new Promise(r => setTimeout(r, graceMs + 2000))]); + } +} + +/** Remove any occurrence of a secret value from text bound for a log. */ +export function redact(text, secrets) { + let out = String(text); + for (const s of secrets) if (typeof s === 'string' && s.length >= 6) out = out.split(s).join('[redacted]'); + return out.replace(/token=[A-Za-z0-9_-]+/g, 'token=[redacted]'); +} diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs new file mode 100644 index 00000000..eca41c72 --- /dev/null +++ b/apps/host/server/agent/profile.mjs @@ -0,0 +1,118 @@ +/** + * The Strata profile for the Harness, generated from what the host knows right now. + * + * The static profile in `integrations/harness/profile/cordis.patch.yml` names one local route on a + * fixed port. The app needs more than that: whichever local Strata instances are ready, and one route + * per saved API connection, so that each chat can pick its own model. This module writes the same two + * Cordis entries (`agent-default-model`, `llm-pi-ai`) for the current set. + * + * Rules carried over from the integration notes (docs/work/IMPLEMENTATION_STATUS.md section 1.8): + * - `llm-pi-ai` config is `{ providers: { "": {...} } }`; a route key at the top level is + * silently ignored. + * - the output budget must fit the whole request, so `maxTokens` is derived from the real context. + * - no cloud route is declared unless the user saved that connection, so nothing can fall back to a + * hosted model by itself. + * + * Secrets: a route names a credential by an environment-variable NAME (`apiKeyEnv`). The values are + * returned separately in `env` for the host to hand to the agent process; they are never written to + * the profile file, a prompt, or a log. + */ +import { createHash } from 'node:crypto'; + +const PROTOCOL = { 'openai-chat': 'openai-completions', 'openai-responses': 'openai-responses', anthropic: 'anthropic-messages' }; + +/** A conservative window for an API model whose connection does not report one. */ +export const ASSUMED_API_CONTEXT = 128_000; + +const slug = value => String(value).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24) || 'x'; + +/** Identity of one route's wire configuration, secret included by hash only. */ +function fingerprint(provider, secret) { + return createHash('sha256').update(JSON.stringify(provider)).update('|').update(secret ?? '').digest('hex').slice(0, 16); +} + +/** Output budget that leaves the prompt room: a quarter of the window, between 1K and 8K. */ +export function outputBudget(context) { + const c = Number.isFinite(context) && context > 0 ? context : 32768; + return Math.max(1024, Math.min(8192, Math.floor(c / 4))); +} + +/** + * @param {object} input + * @param {Array<{id:string,label?:string,baseUrl:string,modelId:string,context?:number,key?:string,vision?:boolean}>} input.local + * ready local instances; the first is the default route (`strata-local`) + * @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 = [] }) { + const providers = {}; + const env = {}; + const routes = []; + + local.forEach((inst, index) => { + const route = index === 0 ? 'strata-local' : `strata-local-${slug(inst.id)}`; + const keyEnv = `STRATA_LOCAL_KEY_${index}`; + // pi-ai's OpenAI-compatible client insists on some key before it sends anything. A worker that + // does not authenticate gets a fixed placeholder; one that does gets its real key, by reference. + env[keyEnv] = inst.key || 'strata-local'; + const context = inst.context ?? 32768; + providers[route] = { + displayName: inst.label ? `Strata (local) ${inst.label}` : 'Strata (local)', + api: 'openai-completions', + baseURL: inst.baseUrl, + apiKeyEnv: keyEnv, + compat: { supportsStore: false }, + models: [{ + id: inst.modelId, name: inst.label || inst.modelId, contextWindow: context, maxTokens: outputBudget(context), + input: inst.vision ? ['text', 'image'] : ['text'], + }], + }; + routes.push({ route, fp: fingerprint(providers[route], env[keyEnv]), kind: 'local', instanceId: inst.id, modelId: inst.modelId, name: inst.label || inst.modelId, contextWindow: context }); + }); + + connections.forEach(conn => { + const protocol = PROTOCOL[conn.protocol]; + if (!protocol) return; + const route = `api-${slug(conn.id).slice(0, 12)}`; + const keyEnv = `STRATA_API_KEY_${slug(conn.id).replace(/-/g, '_').toUpperCase().slice(0, 12)}`; + if (conn.apiKey) env[keyEnv] = conn.apiKey; + let baseURL = conn.baseUrl; + if (protocol === 'anthropic-messages') baseURL = baseURL.replace(/\/v1\/?$/, ''); + providers[route] = { + displayName: conn.name, + api: protocol, + baseURL, + ...(conn.apiKey ? { apiKeyEnv: keyEnv } : {}), + models: conn.models.map(m => ({ + id: m.id, name: m.name || m.id, + contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT, maxTokens: outputBudget(m.contextMax ?? ASSUMED_API_CONTEXT), + input: ['text'], + })), + }; + const fp = fingerprint(providers[route], conn.apiKey ?? ''); + for (const m of conn.models) routes.push({ route, fp, kind: 'api', connectionId: conn.id, modelId: m.id, name: m.name || m.id, contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT }); + }); + + const defaultRoute = routes.find(r => r.kind === 'local') ?? null; + const entries = [ + ...(defaultRoute ? [{ id: 'agent-default-model', name: '@deepseek-ai/dsh-agent-default-model', config: { provider: defaultRoute.route, model: defaultRoute.modelId } }] : []), + { id: 'llm-pi-ai', name: '@deepseek-ai/dsh-llm-pi-ai', config: { providers } }, + // 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 }, + ]; + // JSON is valid YAML, and a JSON document cannot be mis-quoted by a model id or a display name. + const patch = `# Generated by the Strata host. Contains credential NAMES only, never values.\n${JSON.stringify(entries, null, 2)}\n`; + // The signature decides whether the running agent must be restarted. It covers the secret values + // through a hash so a changed key is noticed, and the hash is never reversible into the key. + const signature = createHash('sha256').update(patch).update(JSON.stringify(Object.entries(env).sort())).digest('hex').slice(0, 16); + return { patch, env, routes, defaultRoute, signature }; +} + +/** Find the route for a chat's model choice. */ +export function routeFor(profile, choice) { + if (!choice) return profile.defaultRoute; + if (choice.connectionId) return profile.routes.find(r => r.kind === 'api' && r.connectionId === choice.connectionId && r.modelId === choice.modelId) ?? null; + if (choice.instanceId) return profile.routes.find(r => r.kind === 'local' && r.instanceId === choice.instanceId) ?? null; + return profile.defaultRoute; +}