@tangle-network/agent-runtime 0.50.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/agent.js +1 -1
  2. package/dist/{chunk-CM2IK7VS.js → chunk-2OU7ZQPD.js} +38 -8
  3. package/dist/chunk-2OU7ZQPD.js.map +1 -0
  4. package/dist/{chunk-OM3YNZIW.js → chunk-4JI4BCBI.js} +5 -360
  5. package/dist/chunk-4JI4BCBI.js.map +1 -0
  6. package/dist/{chunk-NDM5VXZW.js → chunk-7SP2OVYZ.js} +7 -5
  7. package/dist/{chunk-NDM5VXZW.js.map → chunk-7SP2OVYZ.js.map} +1 -1
  8. package/dist/{chunk-RHW75JW5.js → chunk-BERLUBAP.js} +2 -2
  9. package/dist/{chunk-BKAIVNFA.js → chunk-COAVO6QB.js} +3 -3
  10. package/dist/chunk-G3RGMA7C.js +361 -0
  11. package/dist/chunk-G3RGMA7C.js.map +1 -0
  12. package/dist/{chunk-ML4IXGTV.js → chunk-V2K35HF2.js} +2 -2
  13. package/dist/improvement.d.ts +96 -8
  14. package/dist/improvement.js +191 -9
  15. package/dist/improvement.js.map +1 -1
  16. package/dist/index.d.ts +114 -4
  17. package/dist/index.js +144 -18
  18. package/dist/index.js.map +1 -1
  19. package/dist/intelligence.d.ts +423 -0
  20. package/dist/intelligence.js +427 -0
  21. package/dist/intelligence.js.map +1 -0
  22. package/dist/loop-runner-bin.js +4 -3
  23. package/dist/loops.d.ts +2 -1
  24. package/dist/loops.js +3 -1
  25. package/dist/mcp/bin.js +5 -4
  26. package/dist/mcp/bin.js.map +1 -1
  27. package/dist/mcp/index.js +6 -5
  28. package/dist/mcp/index.js.map +1 -1
  29. package/dist/platform.d.ts +120 -62
  30. package/dist/platform.js +68 -26
  31. package/dist/platform.js.map +1 -1
  32. package/dist/runtime.d.ts +47 -8
  33. package/dist/runtime.js +3 -1
  34. package/dist/workflow.js +1 -1
  35. package/package.json +6 -1
  36. package/skills/agent-runtime-adoption/SKILL.md +41 -26
  37. package/skills/build-with-agent-runtime/SKILL.md +143 -0
  38. package/skills/loop-writer/SKILL.md +6 -7
  39. package/dist/chunk-CM2IK7VS.js.map +0 -1
  40. package/dist/chunk-OM3YNZIW.js.map +0 -1
  41. /package/dist/{chunk-RHW75JW5.js.map → chunk-BERLUBAP.js.map} +0 -0
  42. /package/dist/{chunk-BKAIVNFA.js.map → chunk-COAVO6QB.js.map} +0 -0
  43. /package/dist/{chunk-ML4IXGTV.js.map → chunk-V2K35HF2.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/bin.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * @experimental\n *\n * `agent-runtime-mcp` — stdio MCP server entry point.\n *\n * Spins up a server with the default coder delegate (wired against the\n * real `@tangle-network/sandbox` client) and, when the optional\n * `@tangle-network/agent-knowledge` peer is installed, a researcher\n * delegate against `multiHarnessResearcherFanout`.\n *\n * Environment variables:\n * TANGLE_API_KEY required — passed to `new Sandbox({ apiKey })`\n * SANDBOX_BASE_URL optional — sandbox-SDK base URL override\n * TANGLE_FLEET_ID optional — when set, delegations dispatch\n * INTO this fleet's shared workspace instead\n * of creating sibling sandboxes. Set by the\n * parent sandbox when launching this MCP\n * server so worker diffs land on the caller's\n * filesystem with no cross-sandbox boundary.\n * TANGLE_FLEET_EXCLUDE_MACHINES optional — comma-separated machine ids to\n * skip during fleet-mode round-robin\n * (typically the coordinator machine this\n * MCP server is running on).\n * MCP_MAX_CONCURRENT_SANDBOXES default 4 — kernel maxConcurrency cap\n * MCP_CODER_FANOUT_HARNESSES comma-separated harness ids to use for variants > 1\n * MCP_DISABLE_CODER set to `1` to omit `delegate_code`\n * MCP_DISABLE_RESEARCHER set to `1` to omit `delegate_research` even when peer is present\n * AGENT_RUNTIME_DELEGATION_STATE_FILE\n * optional — absolute path of a JSON state\n * file. When set, delegation records persist\n * across MCP restarts (FileDelegationStore):\n * status/history survive and idempotency keys\n * dedupe across processes. Single-variant\n * coder/researcher delegations additionally\n * dispatch DETACHED (driveTurn ticks against a\n * deterministic session id) on session-backed\n * placements, so restored in-flight records\n * resume against their still-running sandbox\n * sessions; non-detached in-flight records\n * settle as failed with a truthful\n * driver-restart error.\n * AGENT_RUNTIME_DELEGATION_DETACHED\n * set to `0` to keep every delegation on the\n * streaming path even when the state file is\n * configured (disables detached dispatch +\n * resume).\n * AGENT_RUNTIME_DELEGATION_STATE_RECOVER\n * set to `1` to archive a corrupt state file\n * (`<file>.corrupt-<ts>`) and start empty\n * instead of refusing to boot.\n * AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL\n * optional — positive integer cap on retained\n * terminal records. Unset = keep forever.\n */\n\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { coderProfile } from '../profiles/coder'\nimport type { AgentRunSpec, LoopTraceEmitter, SandboxClient } from '../runtime'\nimport { runLoop } from '../runtime'\nimport { detectExecutor } from './bin-helpers'\nimport {\n coderTaskFromArgs,\n createDefaultCoderDelegate,\n type ResearcherDelegate,\n settleDetachedCoderTurn,\n} from './delegates'\nimport { FileDelegationStore } from './delegation-store'\nimport { composeLoopTraceEmitters } from './delegation-trace'\nimport {\n createDriveTurnResumeDriver,\n type DetachedTurn,\n type DriveTurnCapableBox,\n detachedTurnEvents,\n formatDetachedSessionRef,\n parseDetachedSessionRef,\n runDetachedTurn,\n} from './detached-turn'\nimport type { DelegationExecutor } from './executor'\nimport { createMcpServer } from './server'\nimport { type DelegationResumeDriver, DelegationTaskQueue } from './task-queue'\nimport {\n createPropagatingTraceEmitter,\n readTraceContextFromEnv,\n type TraceContext,\n} from './trace-propagation'\nimport type { DelegateCodeArgs, DelegateResearchArgs, ResearchOutputShape } from './types'\n\nasync function main(): Promise<void> {\n const fanoutHarnesses = parseHarnesses(process.env.MCP_CODER_FANOUT_HARNESSES)\n const maxConcurrency = parseConcurrency(process.env.MCP_MAX_CONCURRENT_SANDBOXES)\n const wantCoder = !process.env.MCP_DISABLE_CODER\n const wantResearcher = !process.env.MCP_DISABLE_RESEARCHER\n const fleetId = parseFleetId(process.env.TANGLE_FLEET_ID)\n\n // Skip the sandbox client load entirely when no profile delegate needs it —\n // the feedback + status + history tools are queue-bound and require no\n // sandbox. Useful for tooling that mounts the MCP server purely for\n // self-introspection.\n const needsSandbox = wantCoder || wantResearcher\n let sandboxClient: SandboxClient | undefined\n let executor: DelegationExecutor | undefined\n if (needsSandbox) {\n const apiKey = process.env.TANGLE_API_KEY\n if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {\n process.stderr.write(\n 'agent-runtime-mcp: TANGLE_API_KEY is required. Set AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 to run without it for diagnostics, or MCP_DISABLE_CODER=1 MCP_DISABLE_RESEARCHER=1 to run the queue-only subset.\\n',\n )\n process.exit(2)\n }\n // Fleet mode against a diagnostic stub is meaningless — the stub can't\n // resolve a real fleet handle. Refuse rather than silently degrading,\n // otherwise a fleet-mounted MCP would behave differently than configured.\n if (fleetId && !apiKey) {\n process.stderr.write(\n 'agent-runtime-mcp: TANGLE_FLEET_ID was set but TANGLE_API_KEY is missing; cannot resolve fleet handle. Provide an api key or unset TANGLE_FLEET_ID.\\n',\n )\n process.exit(2)\n }\n sandboxClient = await loadSandboxClient(apiKey)\n executor = await detectExecutor({ sandboxClient })\n if (fleetId) {\n process.stderr.write(`agent-runtime-mcp: fleet-aware delegation: fleetId=${fleetId}\\n`)\n }\n process.stderr.write(`agent-runtime-mcp: delegation placement → ${executor.describe()}\\n`)\n }\n\n // Export delegated-loop topology spans to the OTLP / Tangle Intelligence sink\n // when OTEL_EXPORTER_OTLP_ENDPOINT is set (+ TRACE_ID / PARENT_SPAN_ID for\n // correlation with the caller's trace). A cheap no-op when the endpoint is\n // unset — the fleet forwards the env into this MCP's process to turn it on.\n // The same context is stamped onto every delegation record (traceId /\n // parentSpanId) so journal consumers join records into the caller's trace.\n const traceContext = readTraceContextFromEnv()\n const { emitter: traceEmitter, exporter: traceExporter } =\n createPropagatingTraceEmitter(traceContext)\n if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {\n process.stderr.write(\n `agent-runtime-mcp: exporting loop topology → ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}\\n`,\n )\n }\n\n const coderDelegate =\n wantCoder && executor\n ? createDefaultCoderDelegate({\n executor,\n fanoutHarnesses,\n maxConcurrency,\n traceEmitter,\n })\n : undefined\n\n const researcherSupport =\n wantResearcher && executor\n ? await loadResearcherSupport(executor, maxConcurrency, traceEmitter)\n : undefined\n\n // Detached dispatch + resume turn on together with the durable store, and\n // only for session-backed placements with real credentials: in-process\n // placement has no sandbox session to detach, and the diagnostic no-key stub\n // cannot resolve boxes. AGENT_RUNTIME_DELEGATION_DETACHED=0 keeps everything\n // on the streaming path.\n const detachedDispatch =\n Boolean(process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim()) &&\n process.env.AGENT_RUNTIME_DELEGATION_DETACHED !== '0' &&\n Boolean(process.env.TANGLE_API_KEY) &&\n (executor?.placement === 'sibling' || executor?.placement === 'fleet')\n if (detachedDispatch) {\n process.stderr.write(\n 'agent-runtime-mcp: detached dispatch enabled — single-variant delegations resume across restarts\\n',\n )\n }\n const resumeDriver =\n detachedDispatch && sandboxClient\n ? buildResumeDriver({ sandboxClient, researcherResume: researcherSupport?.resume })\n : undefined\n\n const durableQueue = await buildDurableQueueFromEnv(resumeDriver, traceContext)\n const server = createMcpServer({\n coderDelegate,\n researcherDelegate: researcherSupport?.delegate,\n detachedDispatch,\n traceContext,\n ...(durableQueue ? { queue: durableQueue } : {}),\n })\n\n const shutdown = () => {\n server.stop()\n const pending: Promise<unknown>[] = []\n if (traceExporter) pending.push(traceExporter.shutdown())\n // Drain journal writes so the state file reflects the final record\n // states before the process exits. A persist failure already routed\n // through onPersistError; swallow the duplicate rejection here.\n if (durableQueue) pending.push(durableQueue.flush().catch(() => {}))\n if (pending.length === 0) {\n process.exit(0)\n return\n }\n void Promise.allSettled(pending).finally(() => process.exit(0))\n }\n process.on('SIGINT', shutdown)\n process.on('SIGTERM', shutdown)\n\n await server.serve()\n}\n\nasync function buildDurableQueueFromEnv(\n resumeDriver: DelegationResumeDriver | undefined,\n traceContext: TraceContext,\n): Promise<DelegationTaskQueue | undefined> {\n const stateFile = process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim()\n if (!stateFile) return undefined\n const store = new FileDelegationStore({\n filePath: stateFile,\n recoverCorrupt: process.env.AGENT_RUNTIME_DELEGATION_STATE_RECOVER === '1',\n })\n const maxTerminalRecords = parseRetention(process.env.AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL)\n // With a resume driver, restored in-flight records that carry a\n // detachedSessionRef re-attach to their still-running sandbox sessions;\n // without one (detached dispatch disabled / no credentials) they settle as\n // failed with a truthful driver-restart error.\n const queue = await DelegationTaskQueue.restore({\n store,\n traceContext,\n ...(resumeDriver ? { resumeDelegate: resumeDriver } : {}),\n ...(maxTerminalRecords !== undefined ? { maxTerminalRecords } : {}),\n onPersistError: (error) => {\n // Durable mode that can no longer write is a broken contract: crash\n // loud instead of degrading to memory-only behind the caller's back.\n process.stderr.write(`agent-runtime-mcp: ${error.message}\\n`)\n process.exit(1)\n },\n })\n process.stderr.write(`agent-runtime-mcp: durable delegation state → ${stateFile}\\n`)\n return queue\n}\n\ninterface ResearcherResumeSupport {\n message(args: DelegateResearchArgs): string\n settle(\n turn: DetachedTurn,\n args: DelegateResearchArgs,\n signal: AbortSignal,\n ): Promise<ResearchOutputShape>\n}\n\n/**\n * Compose the `driveTurn`-backed resume driver over the real sandbox client.\n * Profile dispatch: coder records settle through the same parse + validate\n * gate the delegate applies; researcher records settle through the\n * agent-knowledge preset when the peer is installed. Profiles without resume\n * support (ui-auditor, researcher-without-peer) fail loud — the record settles\n * as failed with the reason instead of fabricating an output.\n */\nfunction buildResumeDriver(args: {\n sandboxClient: SandboxClient\n researcherResume: ResearcherResumeSupport | undefined\n}): DelegationResumeDriver {\n const client = args.sandboxClient as SandboxClient & {\n get?: (id: string) => Promise<SandboxInstance | null>\n }\n return createDriveTurnResumeDriver({\n async resolveSandbox(sandboxId) {\n if (typeof client.get !== 'function') {\n throw new Error(\n 'agent-runtime-mcp: the sandbox client exposes no get(sandboxId); upgrade @tangle-network/sandbox to >= 0.6 to resume detached delegations',\n )\n }\n const box = await client.get(sandboxId)\n if (!box) {\n throw new Error(\n `agent-runtime-mcp: sandbox ${sandboxId} no longer exists — the detached run cannot be resumed`,\n )\n }\n return box as unknown as DriveTurnCapableBox\n },\n buildMessage(record) {\n if (record.profile === 'coder') {\n const task = coderTaskFromArgs(record.args as DelegateCodeArgs)\n return coderProfile({ task }).taskToPrompt(task)\n }\n if (record.profile === 'researcher' && args.researcherResume) {\n return args.researcherResume.message(record.args as DelegateResearchArgs)\n }\n throw new Error(\n `agent-runtime-mcp: no detached resume support for profile \"${record.profile}\"`,\n )\n },\n async settleOutput(turn, record, ctx) {\n if (record.profile === 'coder') {\n if (!record.detachedSessionRef) {\n throw new Error(\n `agent-runtime-mcp: record ${record.taskId} reached the resume settle without a detachedSessionRef`,\n )\n }\n return settleDetachedCoderTurn(turn, {\n task: coderTaskFromArgs(record.args as DelegateCodeArgs),\n sessionId: parseDetachedSessionRef(record.detachedSessionRef).sessionId,\n signal: ctx.signal,\n })\n }\n if (record.profile === 'researcher' && args.researcherResume) {\n return args.researcherResume.settle(turn, record.args as DelegateResearchArgs, ctx.signal)\n }\n throw new Error(\n `agent-runtime-mcp: no detached resume support for profile \"${record.profile}\"`,\n )\n },\n })\n}\n\nfunction parseRetention(raw: string | undefined): number | undefined {\n if (raw === undefined || raw.trim() === '') return undefined\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1) {\n process.stderr.write(\n `agent-runtime-mcp: AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL must be a positive integer, got \"${raw}\"\\n`,\n )\n process.exit(2)\n }\n return n\n}\n\nasync function loadSandboxClient(apiKey: string | undefined): Promise<SandboxClient> {\n // Diagnostic mode: AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 enables tools/list + the\n // queue-bound tools (status / history / feedback) without sandbox creds.\n // Coder + researcher delegations require a real client; the stub fails loud\n // at create() so the agent observes the cause instead of silent success.\n if (!apiKey) {\n return {\n async create() {\n throw new Error(\n 'agent-runtime-mcp: TANGLE_API_KEY is unset; coder/researcher delegations are disabled in diagnostic mode. Set TANGLE_API_KEY or use MCP_DISABLE_CODER=1 MCP_DISABLE_RESEARCHER=1 to remove the unsupported tools from the tool list.',\n )\n },\n } satisfies SandboxClient\n }\n // Dynamic import keeps the bin importable in environments that haven't\n // installed `@tangle-network/sandbox` yet (the runtime package lists it\n // as a peer dep, not a hard dep).\n const mod = await import('@tangle-network/sandbox').catch((err) => {\n process.stderr.write(\n `agent-runtime-mcp: failed to load @tangle-network/sandbox (${err.message}); install the peer dependency\\n`,\n )\n process.exit(2)\n })\n const SandboxCtor = (mod as { Sandbox?: new (config: unknown) => SandboxClient }).Sandbox\n if (!SandboxCtor) {\n process.stderr.write(\n 'agent-runtime-mcp: @tangle-network/sandbox does not export Sandbox; cannot construct client\\n',\n )\n process.exit(2)\n }\n const baseUrl = process.env.SANDBOX_BASE_URL\n return new SandboxCtor({\n apiKey,\n ...(baseUrl ? { baseUrl } : {}),\n })\n}\n\ninterface ResearcherProfilePreset {\n agentRunSpec: Parameters<typeof runLoop>[0]['agentRun'] extends infer T ? NonNullable<T> : never\n output: Parameters<typeof runLoop>[0]['output']\n validator: Parameters<typeof runLoop>[0]['validator']\n}\n\ninterface ResearcherFanoutPreset {\n agentRuns: NonNullable<Parameters<typeof runLoop>[0]['agentRuns']>\n output: Parameters<typeof runLoop>[0]['output']\n validator: Parameters<typeof runLoop>[0]['validator']\n driver: Parameters<typeof runLoop>[0]['driver']\n}\n\ninterface ResearcherSupport {\n delegate: ResearcherDelegate\n resume: ResearcherResumeSupport\n}\n\nasync function loadResearcherSupport(\n executor: DelegationExecutor,\n maxConcurrency: number,\n traceEmitter?: LoopTraceEmitter,\n): Promise<ResearcherSupport | undefined> {\n const sandboxClient = executor.client\n // Optional peer — when `@tangle-network/agent-knowledge` isn't installed,\n // we silently omit the researcher tool from the advertisement. The\n // dynamic-import path is resolved at runtime; TypeScript cannot see the\n // peer, so we type the module structurally rather than via its own\n // declaration file.\n const profilesSpecifier = '@tangle-network/agent-knowledge/profiles'\n const mod = await import(profilesSpecifier).catch(() => undefined)\n if (!mod) return undefined\n type SingleFactory = (opts: { task: unknown }) => ResearcherProfilePreset\n type FanoutFactory = (opts: { task: unknown }) => ResearcherFanoutPreset\n const fanoutFactory = (mod as { multiHarnessResearcherFanout?: FanoutFactory })\n .multiHarnessResearcherFanout\n const singleFactory = (mod as { researcherProfile?: SingleFactory }).researcherProfile\n if (!fanoutFactory || !singleFactory) return undefined\n\n const settleSingle = async (\n turn: DetachedTurn,\n args: DelegateResearchArgs,\n sessionId: string,\n signal: AbortSignal,\n ): Promise<ResearchOutputShape> => {\n const task = buildResearchTask(args)\n const preset = singleFactory({ task })\n if (!preset.validator) {\n throw new Error('agent-runtime-mcp: researcher preset exposes no validator; cannot settle')\n }\n const parsed = preset.output.parse(detachedTurnEvents(sessionId, turn))\n const verdict = await preset.validator.validate(parsed, { iteration: 0, signal })\n if ((verdict as { valid?: boolean }).valid !== true) {\n throw new Error('researcher delegate produced no winner')\n }\n return parsed as ResearchOutputShape\n }\n\n const delegate: ResearcherDelegate = async (args, ctx) => {\n const task = buildResearchTask(args)\n const variants = Math.max(1, Math.trunc(args.variants ?? 1))\n const loopEmitter = composeLoopTraceEmitters(traceEmitter, ctx.traceEmitter)\n ctx.report({ iteration: 0, phase: 'starting' })\n if (variants <= 1) {\n const preset = singleFactory({ task })\n // Detached dispatch — same contract as the coder delegate: one session\n // on one box, driveTurn ticks, resume key bound to the sandbox id.\n if (ctx.detachedSessionRef !== undefined && ctx.updateDetachedSessionRef) {\n const { sessionId } = parseDetachedSessionRef(ctx.detachedSessionRef)\n const rebind = ctx.updateDetachedSessionRef\n const spec = preset.agentRunSpec as AgentRunSpec<unknown>\n const turn = await runDetachedTurn({\n client: sandboxClient,\n spec,\n prompt: spec.taskToPrompt(task),\n sessionId,\n bindSandbox: (sandboxId) => rebind(formatDetachedSessionRef({ sandboxId, sessionId })),\n signal: ctx.signal,\n report: ctx.report,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n ...(executor.placement === 'fleet' ? { placement: 'fleet' as const } : {}),\n })\n const output = await settleSingle(turn, args, sessionId, ctx.signal)\n ctx.report({ iteration: 1, phase: 'completed' })\n return output\n }\n const result = await runLoop({\n driver: {\n name: 'mcp-researcher-single',\n async plan(t, history) {\n return history.length === 0 ? [t] : []\n },\n decide(history) {\n return history.length > 0 ? 'pick-winner' : 'fail'\n },\n },\n agentRun: preset.agentRunSpec,\n output: preset.output,\n validator: preset.validator,\n task,\n ctx: {\n sandboxClient,\n signal: ctx.signal,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n },\n maxIterations: 1,\n maxConcurrency,\n })\n const output = result.winner?.output\n if (!output) throw new Error('researcher delegate produced no winner')\n ctx.report({ iteration: 1, phase: 'completed' })\n return output as ResearchOutputShape\n }\n const fanout = fanoutFactory({ task })\n const result = await runLoop({\n driver: fanout.driver,\n agentRuns: fanout.agentRuns.slice(0, variants),\n output: fanout.output,\n validator: fanout.validator,\n task,\n ctx: {\n sandboxClient,\n signal: ctx.signal,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n },\n maxIterations: variants,\n maxConcurrency: Math.min(maxConcurrency, variants),\n })\n const output = result.winner?.output\n if (!output) throw new Error('researcher delegate fanout produced no winner')\n ctx.report({ iteration: result.iterations.length, phase: 'completed' })\n return output as ResearchOutputShape\n }\n\n return {\n delegate,\n resume: {\n message(args) {\n const task = buildResearchTask(args)\n const spec = singleFactory({ task }).agentRunSpec as AgentRunSpec<unknown>\n return spec.taskToPrompt(task)\n },\n async settle(turn, args, signal) {\n // The session id is only the synthesized event's id — the parser reads\n // data.result / data.text, never the id.\n return settleSingle(turn, args, 'resumed-detached-turn', signal)\n },\n },\n }\n}\n\nfunction buildResearchTask(args: DelegateResearchArgs): unknown {\n return {\n question: args.question,\n knowledgeNamespace: args.namespace,\n scope: args.scope,\n sources: args.sources,\n recencyWindow: args.config?.recencyWindow\n ? {\n since: args.config.recencyWindow.since\n ? new Date(args.config.recencyWindow.since)\n : undefined,\n until: args.config.recencyWindow.until\n ? new Date(args.config.recencyWindow.until)\n : undefined,\n }\n : undefined,\n maxItems: args.config?.maxItems,\n minConfidence: args.config?.minConfidence,\n }\n}\n\nfunction parseHarnesses(raw: string | undefined): string[] | undefined {\n if (!raw) return undefined\n const list = raw\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean)\n return list.length > 0 ? list : undefined\n}\n\nfunction parseFleetId(raw: string | undefined): string | undefined {\n if (typeof raw !== 'string') return undefined\n const trimmed = raw.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction parseConcurrency(raw: string | undefined): number {\n if (!raw) return 4\n const n = Number(raw)\n if (!Number.isFinite(n) || n < 1) return 4\n return Math.min(Math.trunc(n), 32)\n}\n\nmain().catch((err) => {\n process.stderr.write(`agent-runtime-mcp: ${err instanceof Error ? err.stack : String(err)}\\n`)\n process.exit(1)\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,eAAe,OAAsB;AACnC,QAAM,kBAAkB,eAAe,QAAQ,IAAI,0BAA0B;AAC7E,QAAM,iBAAiB,iBAAiB,QAAQ,IAAI,4BAA4B;AAChF,QAAM,YAAY,CAAC,QAAQ,IAAI;AAC/B,QAAM,iBAAiB,CAAC,QAAQ,IAAI;AACpC,QAAM,UAAU,aAAa,QAAQ,IAAI,eAAe;AAMxD,QAAM,eAAe,aAAa;AAClC,MAAI;AACJ,MAAI;AACJ,MAAI,cAAc;AAChB,UAAM,SAAS,QAAQ,IAAI;AAC3B,QAAI,C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I,UAAU;AACxC;AAEA,SAAS,iBAAiB,KAAiC;AACzD,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,IAAI,OAAO,GAAG;AACpB,MAAI,CAAC,OAAO,SAAS,CAAC,KAAK,IAAI,EAAG,QAAO;AACzC,SAAO,KAAK,IAAI,KAAK,MAAM,CAAC,GAAG,EAAE;AACnC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,OAAO,MAAM,sBAAsB,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,CAAC;AAAA,CAAI;AAC7F,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["output","result"]}
1
+ {"version":3,"sources":["../../src/mcp/bin.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * @experimental\n *\n * `agent-runtime-mcp` — stdio MCP server entry point.\n *\n * Spins up a server with the default coder delegate (wired against the\n * real `@tangle-network/sandbox` client) and, when the optional\n * `@tangle-network/agent-knowledge` peer is installed, a researcher\n * delegate against `multiHarnessResearcherFanout`.\n *\n * Environment variables:\n * TANGLE_API_KEY required — passed to `new Sandbox({ apiKey })`\n * SANDBOX_BASE_URL optional — sandbox-SDK base URL override\n * TANGLE_FLEET_ID optional — when set, delegations dispatch\n * INTO this fleet's shared workspace instead\n * of creating sibling sandboxes. Set by the\n * parent sandbox when launching this MCP\n * server so worker diffs land on the caller's\n * filesystem with no cross-sandbox boundary.\n * TANGLE_FLEET_EXCLUDE_MACHINES optional — comma-separated machine ids to\n * skip during fleet-mode round-robin\n * (typically the coordinator machine this\n * MCP server is running on).\n * MCP_MAX_CONCURRENT_SANDBOXES default 4 — kernel maxConcurrency cap\n * MCP_CODER_FANOUT_HARNESSES comma-separated harness ids to use for variants > 1\n * MCP_DISABLE_CODER set to `1` to omit `delegate_code`\n * MCP_DISABLE_RESEARCHER set to `1` to omit `delegate_research` even when peer is present\n * AGENT_RUNTIME_DELEGATION_STATE_FILE\n * optional — absolute path of a JSON state\n * file. When set, delegation records persist\n * across MCP restarts (FileDelegationStore):\n * status/history survive and idempotency keys\n * dedupe across processes. Single-variant\n * coder/researcher delegations additionally\n * dispatch DETACHED (driveTurn ticks against a\n * deterministic session id) on session-backed\n * placements, so restored in-flight records\n * resume against their still-running sandbox\n * sessions; non-detached in-flight records\n * settle as failed with a truthful\n * driver-restart error.\n * AGENT_RUNTIME_DELEGATION_DETACHED\n * set to `0` to keep every delegation on the\n * streaming path even when the state file is\n * configured (disables detached dispatch +\n * resume).\n * AGENT_RUNTIME_DELEGATION_STATE_RECOVER\n * set to `1` to archive a corrupt state file\n * (`<file>.corrupt-<ts>`) and start empty\n * instead of refusing to boot.\n * AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL\n * optional — positive integer cap on retained\n * terminal records. Unset = keep forever.\n */\n\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { coderProfile } from '../profiles/coder'\nimport type { AgentRunSpec, LoopTraceEmitter, SandboxClient } from '../runtime'\nimport { runLoop } from '../runtime'\nimport { detectExecutor } from './bin-helpers'\nimport {\n coderTaskFromArgs,\n createDefaultCoderDelegate,\n type ResearcherDelegate,\n settleDetachedCoderTurn,\n} from './delegates'\nimport { FileDelegationStore } from './delegation-store'\nimport { composeLoopTraceEmitters } from './delegation-trace'\nimport {\n createDriveTurnResumeDriver,\n type DetachedTurn,\n type DriveTurnCapableBox,\n detachedTurnEvents,\n formatDetachedSessionRef,\n parseDetachedSessionRef,\n runDetachedTurn,\n} from './detached-turn'\nimport type { DelegationExecutor } from './executor'\nimport { createMcpServer } from './server'\nimport { type DelegationResumeDriver, DelegationTaskQueue } from './task-queue'\nimport {\n createPropagatingTraceEmitter,\n readTraceContextFromEnv,\n type TraceContext,\n} from './trace-propagation'\nimport type { DelegateCodeArgs, DelegateResearchArgs, ResearchOutputShape } from './types'\n\nasync function main(): Promise<void> {\n const fanoutHarnesses = parseHarnesses(process.env.MCP_CODER_FANOUT_HARNESSES)\n const maxConcurrency = parseConcurrency(process.env.MCP_MAX_CONCURRENT_SANDBOXES)\n const wantCoder = !process.env.MCP_DISABLE_CODER\n const wantResearcher = !process.env.MCP_DISABLE_RESEARCHER\n const fleetId = parseFleetId(process.env.TANGLE_FLEET_ID)\n\n // Skip the sandbox client load entirely when no profile delegate needs it —\n // the feedback + status + history tools are queue-bound and require no\n // sandbox. Useful for tooling that mounts the MCP server purely for\n // self-introspection.\n const needsSandbox = wantCoder || wantResearcher\n let sandboxClient: SandboxClient | undefined\n let executor: DelegationExecutor | undefined\n if (needsSandbox) {\n const apiKey = process.env.TANGLE_API_KEY\n if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {\n process.stderr.write(\n 'agent-runtime-mcp: TANGLE_API_KEY is required. Set AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 to run without it for diagnostics, or MCP_DISABLE_CODER=1 MCP_DISABLE_RESEARCHER=1 to run the queue-only subset.\\n',\n )\n process.exit(2)\n }\n // Fleet mode against a diagnostic stub is meaningless — the stub can't\n // resolve a real fleet handle. Refuse rather than silently degrading,\n // otherwise a fleet-mounted MCP would behave differently than configured.\n if (fleetId && !apiKey) {\n process.stderr.write(\n 'agent-runtime-mcp: TANGLE_FLEET_ID was set but TANGLE_API_KEY is missing; cannot resolve fleet handle. Provide an api key or unset TANGLE_FLEET_ID.\\n',\n )\n process.exit(2)\n }\n sandboxClient = await loadSandboxClient(apiKey)\n executor = await detectExecutor({ sandboxClient })\n if (fleetId) {\n process.stderr.write(`agent-runtime-mcp: fleet-aware delegation: fleetId=${fleetId}\\n`)\n }\n process.stderr.write(`agent-runtime-mcp: delegation placement → ${executor.describe()}\\n`)\n }\n\n // Export delegated-loop topology spans to the OTLP / Tangle Intelligence sink\n // when OTEL_EXPORTER_OTLP_ENDPOINT is set (+ TRACE_ID / PARENT_SPAN_ID for\n // correlation with the caller's trace). A cheap no-op when the endpoint is\n // unset — the fleet forwards the env into this MCP's process to turn it on.\n // The same context is stamped onto every delegation record (traceId /\n // parentSpanId) so journal consumers join records into the caller's trace.\n const traceContext = readTraceContextFromEnv()\n const { emitter: traceEmitter, exporter: traceExporter } =\n createPropagatingTraceEmitter(traceContext)\n if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {\n process.stderr.write(\n `agent-runtime-mcp: exporting loop topology → ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}\\n`,\n )\n }\n\n const coderDelegate =\n wantCoder && executor\n ? createDefaultCoderDelegate({\n executor,\n fanoutHarnesses,\n maxConcurrency,\n traceEmitter,\n })\n : undefined\n\n const researcherSupport =\n wantResearcher && executor\n ? await loadResearcherSupport(executor, maxConcurrency, traceEmitter)\n : undefined\n\n // Detached dispatch + resume turn on together with the durable store, and\n // only for session-backed placements with real credentials: in-process\n // placement has no sandbox session to detach, and the diagnostic no-key stub\n // cannot resolve boxes. AGENT_RUNTIME_DELEGATION_DETACHED=0 keeps everything\n // on the streaming path.\n const detachedDispatch =\n Boolean(process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim()) &&\n process.env.AGENT_RUNTIME_DELEGATION_DETACHED !== '0' &&\n Boolean(process.env.TANGLE_API_KEY) &&\n (executor?.placement === 'sibling' || executor?.placement === 'fleet')\n if (detachedDispatch) {\n process.stderr.write(\n 'agent-runtime-mcp: detached dispatch enabled — single-variant delegations resume across restarts\\n',\n )\n }\n const resumeDriver =\n detachedDispatch && sandboxClient\n ? buildResumeDriver({ sandboxClient, researcherResume: researcherSupport?.resume })\n : undefined\n\n const durableQueue = await buildDurableQueueFromEnv(resumeDriver, traceContext)\n const server = createMcpServer({\n coderDelegate,\n researcherDelegate: researcherSupport?.delegate,\n detachedDispatch,\n traceContext,\n ...(durableQueue ? { queue: durableQueue } : {}),\n })\n\n const shutdown = () => {\n server.stop()\n const pending: Promise<unknown>[] = []\n if (traceExporter) pending.push(traceExporter.shutdown())\n // Drain journal writes so the state file reflects the final record\n // states before the process exits. A persist failure already routed\n // through onPersistError; swallow the duplicate rejection here.\n if (durableQueue) pending.push(durableQueue.flush().catch(() => {}))\n if (pending.length === 0) {\n process.exit(0)\n return\n }\n void Promise.allSettled(pending).finally(() => process.exit(0))\n }\n process.on('SIGINT', shutdown)\n process.on('SIGTERM', shutdown)\n\n await server.serve()\n}\n\nasync function buildDurableQueueFromEnv(\n resumeDriver: DelegationResumeDriver | undefined,\n traceContext: TraceContext,\n): Promise<DelegationTaskQueue | undefined> {\n const stateFile = process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim()\n if (!stateFile) return undefined\n const store = new FileDelegationStore({\n filePath: stateFile,\n recoverCorrupt: process.env.AGENT_RUNTIME_DELEGATION_STATE_RECOVER === '1',\n })\n const maxTerminalRecords = parseRetention(process.env.AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL)\n // With a resume driver, restored in-flight records that carry a\n // detachedSessionRef re-attach to their still-running sandbox sessions;\n // without one (detached dispatch disabled / no credentials) they settle as\n // failed with a truthful driver-restart error.\n const queue = await DelegationTaskQueue.restore({\n store,\n traceContext,\n ...(resumeDriver ? { resumeDelegate: resumeDriver } : {}),\n ...(maxTerminalRecords !== undefined ? { maxTerminalRecords } : {}),\n onPersistError: (error) => {\n // Durable mode that can no longer write is a broken contract: crash\n // loud instead of degrading to memory-only behind the caller's back.\n process.stderr.write(`agent-runtime-mcp: ${error.message}\\n`)\n process.exit(1)\n },\n })\n process.stderr.write(`agent-runtime-mcp: durable delegation state → ${stateFile}\\n`)\n return queue\n}\n\ninterface ResearcherResumeSupport {\n message(args: DelegateResearchArgs): string\n settle(\n turn: DetachedTurn,\n args: DelegateResearchArgs,\n signal: AbortSignal,\n ): Promise<ResearchOutputShape>\n}\n\n/**\n * Compose the `driveTurn`-backed resume driver over the real sandbox client.\n * Profile dispatch: coder records settle through the same parse + validate\n * gate the delegate applies; researcher records settle through the\n * agent-knowledge preset when the peer is installed. Profiles without resume\n * support (ui-auditor, researcher-without-peer) fail loud — the record settles\n * as failed with the reason instead of fabricating an output.\n */\nfunction buildResumeDriver(args: {\n sandboxClient: SandboxClient\n researcherResume: ResearcherResumeSupport | undefined\n}): DelegationResumeDriver {\n const client = args.sandboxClient as SandboxClient & {\n get?: (id: string) => Promise<SandboxInstance | null>\n }\n return createDriveTurnResumeDriver({\n async resolveSandbox(sandboxId) {\n if (typeof client.get !== 'function') {\n throw new Error(\n 'agent-runtime-mcp: the sandbox client exposes no get(sandboxId); upgrade @tangle-network/sandbox to >= 0.6 to resume detached delegations',\n )\n }\n const box = await client.get(sandboxId)\n if (!box) {\n throw new Error(\n `agent-runtime-mcp: sandbox ${sandboxId} no longer exists — the detached run cannot be resumed`,\n )\n }\n return box as unknown as DriveTurnCapableBox\n },\n buildMessage(record) {\n if (record.profile === 'coder') {\n const task = coderTaskFromArgs(record.args as DelegateCodeArgs)\n return coderProfile({ task }).taskToPrompt(task)\n }\n if (record.profile === 'researcher' && args.researcherResume) {\n return args.researcherResume.message(record.args as DelegateResearchArgs)\n }\n throw new Error(\n `agent-runtime-mcp: no detached resume support for profile \"${record.profile}\"`,\n )\n },\n async settleOutput(turn, record, ctx) {\n if (record.profile === 'coder') {\n if (!record.detachedSessionRef) {\n throw new Error(\n `agent-runtime-mcp: record ${record.taskId} reached the resume settle without a detachedSessionRef`,\n )\n }\n return settleDetachedCoderTurn(turn, {\n task: coderTaskFromArgs(record.args as DelegateCodeArgs),\n sessionId: parseDetachedSessionRef(record.detachedSessionRef).sessionId,\n signal: ctx.signal,\n })\n }\n if (record.profile === 'researcher' && args.researcherResume) {\n return args.researcherResume.settle(turn, record.args as DelegateResearchArgs, ctx.signal)\n }\n throw new Error(\n `agent-runtime-mcp: no detached resume support for profile \"${record.profile}\"`,\n )\n },\n })\n}\n\nfunction parseRetention(raw: string | undefined): number | undefined {\n if (raw === undefined || raw.trim() === '') return undefined\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1) {\n process.stderr.write(\n `agent-runtime-mcp: AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL must be a positive integer, got \"${raw}\"\\n`,\n )\n process.exit(2)\n }\n return n\n}\n\nasync function loadSandboxClient(apiKey: string | undefined): Promise<SandboxClient> {\n // Diagnostic mode: AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 enables tools/list + the\n // queue-bound tools (status / history / feedback) without sandbox creds.\n // Coder + researcher delegations require a real client; the stub fails loud\n // at create() so the agent observes the cause instead of silent success.\n if (!apiKey) {\n return {\n async create() {\n throw new Error(\n 'agent-runtime-mcp: TANGLE_API_KEY is unset; coder/researcher delegations are disabled in diagnostic mode. Set TANGLE_API_KEY or use MCP_DISABLE_CODER=1 MCP_DISABLE_RESEARCHER=1 to remove the unsupported tools from the tool list.',\n )\n },\n } satisfies SandboxClient\n }\n // Dynamic import keeps the bin importable in environments that haven't\n // installed `@tangle-network/sandbox` yet (the runtime package lists it\n // as a peer dep, not a hard dep).\n const mod = await import('@tangle-network/sandbox').catch((err) => {\n process.stderr.write(\n `agent-runtime-mcp: failed to load @tangle-network/sandbox (${err.message}); install the peer dependency\\n`,\n )\n process.exit(2)\n })\n const SandboxCtor = (mod as { Sandbox?: new (config: unknown) => SandboxClient }).Sandbox\n if (!SandboxCtor) {\n process.stderr.write(\n 'agent-runtime-mcp: @tangle-network/sandbox does not export Sandbox; cannot construct client\\n',\n )\n process.exit(2)\n }\n const baseUrl = process.env.SANDBOX_BASE_URL\n return new SandboxCtor({\n apiKey,\n ...(baseUrl ? { baseUrl } : {}),\n })\n}\n\ninterface ResearcherProfilePreset {\n agentRunSpec: Parameters<typeof runLoop>[0]['agentRun'] extends infer T ? NonNullable<T> : never\n output: Parameters<typeof runLoop>[0]['output']\n validator: Parameters<typeof runLoop>[0]['validator']\n}\n\ninterface ResearcherFanoutPreset {\n agentRuns: NonNullable<Parameters<typeof runLoop>[0]['agentRuns']>\n output: Parameters<typeof runLoop>[0]['output']\n validator: Parameters<typeof runLoop>[0]['validator']\n driver: Parameters<typeof runLoop>[0]['driver']\n}\n\ninterface ResearcherSupport {\n delegate: ResearcherDelegate\n resume: ResearcherResumeSupport\n}\n\nasync function loadResearcherSupport(\n executor: DelegationExecutor,\n maxConcurrency: number,\n traceEmitter?: LoopTraceEmitter,\n): Promise<ResearcherSupport | undefined> {\n const sandboxClient = executor.client\n // Optional peer — when `@tangle-network/agent-knowledge` isn't installed,\n // we silently omit the researcher tool from the advertisement. The\n // dynamic-import path is resolved at runtime; TypeScript cannot see the\n // peer, so we type the module structurally rather than via its own\n // declaration file.\n const profilesSpecifier = '@tangle-network/agent-knowledge/profiles'\n const mod = await import(profilesSpecifier).catch(() => undefined)\n if (!mod) return undefined\n type SingleFactory = (opts: { task: unknown }) => ResearcherProfilePreset\n type FanoutFactory = (opts: { task: unknown }) => ResearcherFanoutPreset\n const fanoutFactory = (mod as { multiHarnessResearcherFanout?: FanoutFactory })\n .multiHarnessResearcherFanout\n const singleFactory = (mod as { researcherProfile?: SingleFactory }).researcherProfile\n if (!fanoutFactory || !singleFactory) return undefined\n\n const settleSingle = async (\n turn: DetachedTurn,\n args: DelegateResearchArgs,\n sessionId: string,\n signal: AbortSignal,\n ): Promise<ResearchOutputShape> => {\n const task = buildResearchTask(args)\n const preset = singleFactory({ task })\n if (!preset.validator) {\n throw new Error('agent-runtime-mcp: researcher preset exposes no validator; cannot settle')\n }\n const parsed = preset.output.parse(detachedTurnEvents(sessionId, turn))\n const verdict = await preset.validator.validate(parsed, { iteration: 0, signal })\n if ((verdict as { valid?: boolean }).valid !== true) {\n throw new Error('researcher delegate produced no winner')\n }\n return parsed as ResearchOutputShape\n }\n\n const delegate: ResearcherDelegate = async (args, ctx) => {\n const task = buildResearchTask(args)\n const variants = Math.max(1, Math.trunc(args.variants ?? 1))\n const loopEmitter = composeLoopTraceEmitters(traceEmitter, ctx.traceEmitter)\n ctx.report({ iteration: 0, phase: 'starting' })\n if (variants <= 1) {\n const preset = singleFactory({ task })\n // Detached dispatch — same contract as the coder delegate: one session\n // on one box, driveTurn ticks, resume key bound to the sandbox id.\n if (ctx.detachedSessionRef !== undefined && ctx.updateDetachedSessionRef) {\n const { sessionId } = parseDetachedSessionRef(ctx.detachedSessionRef)\n const rebind = ctx.updateDetachedSessionRef\n const spec = preset.agentRunSpec as AgentRunSpec<unknown>\n const turn = await runDetachedTurn({\n client: sandboxClient,\n spec,\n prompt: spec.taskToPrompt(task),\n sessionId,\n bindSandbox: (sandboxId) => rebind(formatDetachedSessionRef({ sandboxId, sessionId })),\n signal: ctx.signal,\n report: ctx.report,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n ...(executor.placement === 'fleet' ? { placement: 'fleet' as const } : {}),\n })\n const output = await settleSingle(turn, args, sessionId, ctx.signal)\n ctx.report({ iteration: 1, phase: 'completed' })\n return output\n }\n const result = await runLoop({\n driver: {\n name: 'mcp-researcher-single',\n async plan(t, history) {\n return history.length === 0 ? [t] : []\n },\n decide(history) {\n return history.length > 0 ? 'pick-winner' : 'fail'\n },\n },\n agentRun: preset.agentRunSpec,\n output: preset.output,\n validator: preset.validator,\n task,\n ctx: {\n sandboxClient,\n signal: ctx.signal,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n },\n maxIterations: 1,\n maxConcurrency,\n })\n const output = result.winner?.output\n if (!output) throw new Error('researcher delegate produced no winner')\n ctx.report({ iteration: 1, phase: 'completed' })\n return output as ResearchOutputShape\n }\n const fanout = fanoutFactory({ task })\n const result = await runLoop({\n driver: fanout.driver,\n agentRuns: fanout.agentRuns.slice(0, variants),\n output: fanout.output,\n validator: fanout.validator,\n task,\n ctx: {\n sandboxClient,\n signal: ctx.signal,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n },\n maxIterations: variants,\n maxConcurrency: Math.min(maxConcurrency, variants),\n })\n const output = result.winner?.output\n if (!output) throw new Error('researcher delegate fanout produced no winner')\n ctx.report({ iteration: result.iterations.length, phase: 'completed' })\n return output as ResearchOutputShape\n }\n\n return {\n delegate,\n resume: {\n message(args) {\n const task = buildResearchTask(args)\n const spec = singleFactory({ task }).agentRunSpec as AgentRunSpec<unknown>\n return spec.taskToPrompt(task)\n },\n async settle(turn, args, signal) {\n // The session id is only the synthesized event's id — the parser reads\n // data.result / data.text, never the id.\n return settleSingle(turn, args, 'resumed-detached-turn', signal)\n },\n },\n }\n}\n\nfunction buildResearchTask(args: DelegateResearchArgs): unknown {\n return {\n question: args.question,\n knowledgeNamespace: args.namespace,\n scope: args.scope,\n sources: args.sources,\n recencyWindow: args.config?.recencyWindow\n ? {\n since: args.config.recencyWindow.since\n ? new Date(args.config.recencyWindow.since)\n : undefined,\n until: args.config.recencyWindow.until\n ? new Date(args.config.recencyWindow.until)\n : undefined,\n }\n : undefined,\n maxItems: args.config?.maxItems,\n minConfidence: args.config?.minConfidence,\n }\n}\n\nfunction parseHarnesses(raw: string | undefined): string[] | undefined {\n if (!raw) return undefined\n const list = raw\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean)\n return list.length > 0 ? list : undefined\n}\n\nfunction parseFleetId(raw: string | undefined): string | undefined {\n if (typeof raw !== 'string') return undefined\n const trimmed = raw.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction parseConcurrency(raw: string | undefined): number {\n if (!raw) return 4\n const n = Number(raw)\n if (!Number.isFinite(n) || n < 1) return 4\n return Math.min(Math.trunc(n), 32)\n}\n\nmain().catch((err) => {\n process.stderr.write(`agent-runtime-mcp: ${err instanceof Error ? err.stack : String(err)}\\n`)\n process.exit(1)\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,eAAe,OAAsB;AACnC,QAAM,kBAAkB,eAAe,QAAQ,IAAI,0BAA0B;AAC7E,QAAM,iBAAiB,iBAAiB,QAAQ,IAAI,4BAA4B;AAChF,QAAM,YAAY,CAAC,QAAQ,IAAI;AAC/B,QAAM,iBAAiB,CAAC,QAAQ,IAAI;AACpC,QAAM,UAAU,aAAa,QAAQ,IAAI,eAAe;AAMxD,QAAM,eAAe,aAAa;AAClC,MAAI;AACJ,MAAI;AACJ,MAAI,cAAc;AAChB,UAAM,SAAS,Q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zB,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,iBAAiB,KAAiC;AACzD,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,IAAI,OAAO,GAAG;AACpB,MAAI,CAAC,OAAO,SAAS,CAAC,KAAK,IAAI,EAAG,QAAO;AACzC,SAAO,KAAK,IAAI,KAAK,MAAM,CAAC,GAAG,EAAE;AACnC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,OAAO,MAAM,sBAAsB,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,CAAC;AAAA,CAAI;AAC7F,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["output","result"]}
package/dist/mcp/index.js CHANGED
@@ -14,12 +14,12 @@ import {
14
14
  removeWorktree,
15
15
  traceContextToEnv,
16
16
  validateDelegateUiAuditArgs
17
- } from "../chunk-NDM5VXZW.js";
17
+ } from "../chunk-7SP2OVYZ.js";
18
18
  import "../chunk-WIR4HOOJ.js";
19
19
  import {
20
20
  mcpToolsForRuntimeMcp,
21
21
  mcpToolsForRuntimeMcpSubset
22
- } from "../chunk-ML4IXGTV.js";
22
+ } from "../chunk-V2K35HF2.js";
23
23
  import {
24
24
  DELEGATE_CODE_DESCRIPTION,
25
25
  DELEGATE_CODE_INPUT_SCHEMA,
@@ -54,7 +54,7 @@ import {
54
54
  validateDelegateResearchArgs,
55
55
  validateDelegationHistoryArgs,
56
56
  validateDelegationStatusArgs
57
- } from "../chunk-RHW75JW5.js";
57
+ } from "../chunk-BERLUBAP.js";
58
58
  import {
59
59
  createKbGate
60
60
  } from "../chunk-FNMGYYSS.js";
@@ -75,7 +75,7 @@ import {
75
75
  parseDetachedSessionRef,
76
76
  runDetachedTurn,
77
77
  settleDetachedCoderTurn
78
- } from "../chunk-OM3YNZIW.js";
78
+ } from "../chunk-4JI4BCBI.js";
79
79
  import "../chunk-KADIJAD4.js";
80
80
  import {
81
81
  runLocalHarness
@@ -85,9 +85,10 @@ import {
85
85
  buildDelegationMcpServer,
86
86
  composeProductionAgentProfile
87
87
  } from "../chunk-7JITYN6T.js";
88
+ import "../chunk-G3RGMA7C.js";
88
89
  import {
89
90
  assertTraceDerivedFindings
90
- } from "../chunk-CM2IK7VS.js";
91
+ } from "../chunk-2OU7ZQPD.js";
91
92
  import "../chunk-GSUO5QS6.js";
92
93
  import "../chunk-DGUM43GV.js";
93
94
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/tools/checks.ts","../../src/mcp/tools/coordination.ts"],"sourcesContent":["/**\n * @experimental\n *\n * The trace-analyst KIND directory — the operator's lenses, as composable DATA.\n *\n * An analyst is not one question. A kind is ONE lens (completeness, correctness, policy, efficiency,\n * tool-use, …); each emits `AnalystFinding`s tagged by its `area`. The driver `list_analysts` to see\n * the menu, `run_analyst(kind, worker)` to apply a lens, and `define_analyst` to author a new one —\n * so at test time you compose the exact lenses a domain needs (maximum specificity), not one generic\n * reviewer. The kinds are data, the runner is generic, and the finding shape + firewall are reused\n * from agent-eval / the keystone — never re-derived.\n *\n * A kind here is a lightweight lens (`Check`); it is a deliberate SUBSET of agent-eval's full\n * `TraceAnalystKindSpec`, so a kind that needs the heavy agentic actor (sub-agent recursion, tools,\n * goldens) upgrades to `createTraceAnalystKind` without changing this directory's surface.\n */\n\nimport {\n type AnalystFinding,\n type AnalystSeverity,\n type EvidenceRef,\n makeFinding,\n} from '@tangle-network/agent-eval'\nimport { assertTraceDerivedFindings } from '../../runtime'\n\n// agent-eval's root entry exports the lift (`makeFinding`) + the `AnalystFinding`/`EvidenceRef` shapes\n// but NOT the raw-row validator / schema prompt (kind-factory-internal). We inline a minimal,\n// equivalent pair so a lens emits the SAME finding shape without reaching into an unstable internal.\nconst ANALYST_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const\n\nconst FINDING_SCHEMA_PROMPT = [\n 'Each finding is a JSON object with these fields:',\n '- severity: one of \"critical\" | \"high\" | \"medium\" | \"low\" | \"info\"',\n '- claim: one-sentence statement',\n '- evidence_uri: REQUIRED, never blank — exactly one of \"span://<trace>/<span>\", \"artifact://<path>\",',\n ' or \"metric://<name>\"; ALWAYS cite a real id from the trace. No citable id ⇒ omit the finding.',\n '- evidence_excerpt?: a short quote from the cited evidence',\n '- confidence: number 0..1',\n '- rationale?: one sentence of reasoning',\n '- recommended_action?: a concrete imperative (\"Add ...\", \"Replace ...\", \"Stop ...\")',\n 'Emit an empty array when there is nothing to report. Never fabricate evidence.',\n].join('\\n')\n\ninterface RawRow {\n severity: AnalystSeverity\n claim: string\n evidence_uri: string\n confidence: number\n evidence_excerpt?: string\n rationale?: string\n recommended_action?: string\n subject?: string\n}\n\n/** Validate one raw finding row (the lightweight equivalent of agent-eval's `parseRawFinding`):\n * require a claim + a real trace evidence_uri; drop anything else. Returns null to discard. */\nfunction validateRawFinding(row: unknown): RawRow | null {\n if (!row || typeof row !== 'object') return null\n const r = row as Record<string, unknown>\n if (typeof r.claim !== 'string' || r.claim.length === 0) return null\n if (typeof r.evidence_uri !== 'string' || !/^(span|artifact|metric):\\/\\//.test(r.evidence_uri))\n return null\n const sev = (ANALYST_SEVERITIES as readonly string[]).includes(r.severity as string)\n ? (r.severity as AnalystSeverity)\n : 'medium'\n return {\n severity: sev,\n claim: r.claim,\n evidence_uri: r.evidence_uri,\n confidence: typeof r.confidence === 'number' ? r.confidence : 0.5,\n ...(typeof r.evidence_excerpt === 'string' ? { evidence_excerpt: r.evidence_excerpt } : {}),\n ...(typeof r.rationale === 'string' ? { rationale: r.rationale } : {}),\n ...(typeof r.recommended_action === 'string'\n ? { recommended_action: r.recommended_action }\n : {}),\n ...(typeof r.subject === 'string' ? { subject: r.subject } : {}),\n }\n}\n\n/** One lens — a composable analyst kind. Identity fields mirror `TraceAnalystKindSpec` so a kind is\n * upgradeable to the full agentic factory; `lookFor` is the lens question the actor applies. */\nexport interface Check {\n readonly id: string\n readonly description: string\n /** Coarse classification stamped on every finding this kind emits (the renderer groups by it). */\n readonly area: string\n readonly version: string\n /** The lens — what this analyst looks for in the trace. */\n readonly lookFor: string\n}\n\n/** The built-in lens directory. Domain-blind (about any agent trace); compose at test time. */\nexport const defaultChecks: Record<string, Check> = {\n completeness: {\n id: 'completeness',\n description: 'Required work the trace does not yet show done or verified.',\n area: 'failure-mode',\n version: '1',\n lookFor:\n 'every change the task requires that the trace does NOT yet show completed AND verified by a ' +\n 'tool result. One finding per missing/unverified requirement.',\n },\n correctness: {\n id: 'correctness',\n description: 'Tool calls that produced wrong, erroring, or contradicted results.',\n area: 'correctness',\n version: '1',\n lookFor:\n 'tool calls whose RESULT shows an error, a wrong value, or contradicts what the task required ' +\n '(e.g. set the wrong field, value did not take, an error was ignored).',\n },\n policy: {\n id: 'policy',\n description: 'Actions that violate a stated policy, constraint, or allow-list.',\n area: 'safety',\n version: '1',\n lookFor:\n 'actions in the trace that violate a policy/constraint stated in the task or system prompt ' +\n '(forbidden tool, missing approval, out-of-scope mutation, skipped precondition).',\n },\n efficiency: {\n id: 'efficiency',\n description: 'Wasted, redundant, or looping work.',\n area: 'cost',\n version: '1',\n lookFor:\n 'redundant or wasted actions — repeated identical calls, a stalled line retried the same way, ' +\n 'work that produced no progress toward the goal.',\n },\n 'tool-use': {\n id: 'tool-use',\n description: 'Malformed or misused tool calls.',\n area: 'tool-use',\n version: '1',\n lookFor:\n 'tool calls with malformed/invalid arguments, the wrong tool for the intent, or a tool used ' +\n 'against its contract — judged from the call + its result.',\n },\n}\n\n/** Lift validated raw rows into `AnalystFinding`s (agent-eval `makeFinding` stamps `finding_id`/\n * `produced_at`), then enforce the trace-derived firewall (selector ≠ judge). Pure — no LLM. */\nexport function liftFindings(kind: Check, rows: unknown[], producedAt: string): AnalystFinding[] {\n const findings: AnalystFinding[] = []\n for (const row of rows) {\n const raw = validateRawFinding(row)\n if (!raw) continue\n findings.push(\n makeFinding({\n analyst_id: kind.id,\n area: kind.area,\n severity: raw.severity,\n claim: raw.claim,\n confidence: raw.confidence,\n produced_at: producedAt,\n evidence_refs: evidenceRefs(raw.evidence_uri, raw.evidence_excerpt),\n ...(raw.rationale ? { rationale: raw.rationale } : {}),\n ...(raw.recommended_action ? { recommended_action: raw.recommended_action } : {}),\n ...(raw.subject ? { subject: raw.subject } : {}),\n metadata: { kind_version: kind.version },\n }),\n )\n }\n assertTraceDerivedFindings(findings) // throws if a finding cites judge/verdict/score evidence\n return findings\n}\n\n/** Map a raw `evidence_uri` (span:// | artifact:// | metric://<name>) to a typed `EvidenceRef`. A\n * metric ref carries the bare NAME (the firewall checks the metric name for judge/verdict/score —\n * so a finding that cites a judge metric is rejected as not trace-derived). */\nfunction evidenceRefs(uri: string, excerpt?: string): EvidenceRef[] {\n const scheme = uri.split('://', 1)[0]\n if (scheme === 'metric')\n return [\n { kind: 'metric', uri: uri.replace(/^metric:\\/\\//, ''), ...(excerpt ? { excerpt } : {}) },\n ]\n const kind: EvidenceRef['kind'] = scheme === 'span' ? 'span' : 'artifact'\n return [{ kind, uri, ...(excerpt ? { excerpt } : {}) }]\n}\n\n/** Render a worker's trace (tool calls + results) into the text an analyst lens reads. Generic over\n * the trace shape: a `{ messages }` conversation, a bare message array, else stringified. */\nexport function renderTrace(trace: unknown): string {\n const messages = Array.isArray(trace)\n ? trace\n : trace &&\n typeof trace === 'object' &&\n Array.isArray((trace as { messages?: unknown[] }).messages)\n ? (trace as { messages: unknown[] }).messages\n : undefined\n if (!messages) return JSON.stringify(trace ?? {}).slice(0, 8000)\n return messages\n .map((m) => {\n const r = m as {\n role?: string\n content?: unknown\n tool_calls?: Array<{ function?: { name?: string; arguments?: string } }>\n }\n if (r.role === 'tool') return `RESULT ${String(r.content).slice(0, 300)}`\n const calls = r.tool_calls\n ?.map((c) => `${c.function?.name}(${c.function?.arguments})`)\n .join(', ')\n return calls ? `CALL ${calls}` : `SAY ${String(r.content ?? '').slice(0, 200)}`\n })\n .join('\\n')\n .slice(0, 8000)\n}\n\nexport interface CheckRunnerOptions {\n routerBaseUrl: string\n routerKey: string\n model: string\n /** Test/override seam — replace the LLM call. Default: a router chat completion. */\n chat?: (system: string, user: string) => Promise<string>\n}\n\n/** Run ONE lens over a trace → findings. Generic over any kind: prompt = the lens + the agent-eval\n * finding schema; the model's JSON array is parsed (`parseRawFinding`), lifted, and firewalled. */\nexport async function runCheck(\n kind: Check,\n trace: unknown,\n opts: CheckRunnerOptions,\n producedAt: string,\n): Promise<AnalystFinding[]> {\n const sys =\n `You are a trace analyst applying ONE lens: look for ${kind.lookFor}\\n\\n` +\n `${FINDING_SCHEMA_PROMPT}\\n\\nReturn ONLY a fenced \\`\\`\\`json array of finding objects (possibly empty).`\n const user = `WORKER TRACE:\\n${renderTrace(trace)}\\n\\nApply your lens and emit the findings array.`\n const chat = opts.chat ?? defaultChat(opts)\n const content = await chat(sys, user)\n const match = content.match(/```(?:json)?\\s*([\\s\\S]*?)```/)\n let rows: unknown[] = []\n try {\n const parsed = JSON.parse((match?.[1] ?? content).trim())\n rows = Array.isArray(parsed)\n ? parsed\n : Array.isArray((parsed as { findings?: unknown[] })?.findings)\n ? (parsed as { findings: unknown[] }).findings\n : []\n } catch {\n rows = []\n }\n return liftFindings(kind, rows, producedAt)\n}\n\nfunction defaultChat(opts: CheckRunnerOptions): (system: string, user: string) => Promise<string> {\n return async (system, user) => {\n const res = await fetch(`${opts.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.routerKey}` },\n body: JSON.stringify({\n model: opts.model,\n messages: [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n temperature: 0.3,\n }),\n })\n if (!res.ok) throw new Error(`analyst router ${res.status}`)\n const data = (await res.json()) as { choices?: Array<{ message?: { content?: string } }> }\n return data.choices?.[0]?.message?.content ?? ''\n }\n}\n\n/**\n * Build a `run_analyst` runner over a kind directory.\n * Returns findings, or a typed error for an unknown kind. `producedAt` is\n * passed in because replay-safe paths must not read `Date.now`.\n */\nexport function makeCheckRunner(\n kinds: Record<string, Check>,\n opts: CheckRunnerOptions,\n): (\n kindId: string,\n trace: unknown,\n producedAt: string,\n) => Promise<AnalystFinding[] | { error: string }> {\n return async (kindId, trace, producedAt) => {\n const kind = kinds[kindId]\n if (!kind)\n return {\n error: `unknown analyst kind ${JSON.stringify(kindId)} (have: ${Object.keys(kinds).join(', ')})`,\n }\n return runCheck(kind, trace, opts, producedAt)\n }\n}\n","/**\n * @experimental\n *\n * MCP binding for a live `Scope`. A sandbox driver gets the same small verbs\n * the in-process driver has: spawn, observe, await, steer, ask/answer, analyze,\n * and stop. Settled outputs remain Scope artifacts; product code can project\n * them into any UI/report envelope it needs.\n */\n\nimport type {\n Budget,\n ResultBlobStore,\n Scope,\n Settled,\n Agent as SuperviseAgent,\n} from '../../runtime'\nimport type { McpToolDescriptor } from '../server'\n\n/** A worker the driver has drained via `await_next`. */\nexport interface SettledWorker {\n readonly id: string\n readonly status: 'done' | 'down'\n readonly score?: number\n readonly valid?: boolean\n readonly outRef?: string\n readonly reason?: string\n}\n\nexport type QuestionLevel = 'worker' | 'driver' | 'loop'\nexport type QuestionUrgency = 'continue-without' | 'blocks-step' | 'blocks-run'\n\nexport interface QuestionOption {\n readonly label: string\n readonly tradeoff: string\n}\n\nexport interface Question {\n readonly id: string\n readonly from: string\n readonly level: QuestionLevel\n readonly question: string\n readonly reason: string\n readonly urgency: QuestionUrgency\n readonly options?: ReadonlyArray<QuestionOption>\n}\n\nexport type QuestionDecision =\n | { readonly kind: 'answer'; readonly answer: string; readonly by: string }\n | { readonly kind: 'defer'; readonly reason: string }\n | { readonly kind: 'escalate'; readonly to: 'parent' | 'user' | string; readonly reason: string }\n\nexport interface QuestionRecord extends Question {\n readonly status: 'open' | 'answered' | 'deferred' | 'escalated'\n readonly decision?: QuestionDecision\n readonly openedAt: number\n}\n\ntype QuestionInput = Omit<Question, 'id'> & { readonly id?: string }\nexport type QuestionPolicy = 'auto' | 'mustDecide' | 'bubble' | 'failClosed'\n\nexport interface AnalystRegistry {\n readonly kinds: ReadonlyArray<{ id: string; description: string; area: string }>\n readonly run: (kindId: string, trace: unknown) => Promise<unknown>\n}\n\nexport type CoordinationEvent = { readonly type: 'question'; readonly question: QuestionRecord }\n\nexport type MakeWorkerAgent = (profile: unknown) => SuperviseAgent<unknown, unknown>\n\nexport interface CoordinationToolsOptions {\n readonly scope: Scope<unknown>\n readonly blobs: ResultBlobStore\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly perWorker: Budget\n readonly analysts?: AnalystRegistry\n readonly onEvent?: (event: CoordinationEvent) => void | Promise<void>\n readonly questionPolicy?: QuestionPolicy\n}\n\nexport interface CoordinationTools {\n readonly tools: McpToolDescriptor[]\n isStopped(): boolean\n stopReason(): string | undefined\n settled(): ReadonlyArray<SettledWorker>\n questions(): ReadonlyArray<QuestionRecord>\n}\n\nconst idArg = { type: 'string', description: 'The workerId returned by spawn_worker.' } as const\n\n/** Build the driver's MCP tools over a live scope. */\nexport function createCoordinationTools(opts: CoordinationToolsOptions): CoordinationTools {\n let stopped = false\n let reason: string | undefined\n let questionSeq = 0\n const ledger: SettledWorker[] = []\n const questions: QuestionRecord[] = []\n const questionPolicy = opts.questionPolicy ?? 'auto'\n\n const str = (v: unknown, field: string): string => {\n if (typeof v !== 'string' || v.length === 0)\n throw new Error(`coordination tools: \"${field}\" must be a non-empty string`)\n return v\n }\n const obj = (raw: unknown): Record<string, unknown> => {\n if (!raw || typeof raw !== 'object')\n throw new Error('coordination tools: arguments must be an object')\n return raw as Record<string, unknown>\n }\n const level = (v: unknown): Question['level'] => {\n if (v === 'worker' || v === 'driver' || v === 'loop') return v\n throw new Error('coordination tools: \"level\" must be worker, driver, or loop')\n }\n const urgency = (v: unknown): Question['urgency'] => {\n if (v === 'continue-without' || v === 'blocks-step' || v === 'blocks-run') return v\n throw new Error(\n 'coordination tools: \"urgency\" must be continue-without, blocks-step, or blocks-run',\n )\n }\n\n const recordSettled = (s: Settled<unknown>): SettledWorker => {\n const w: SettledWorker =\n s.kind === 'done'\n ? {\n id: s.handle.id,\n status: 'done',\n score: s.verdict?.score ?? 0,\n valid: s.verdict?.valid ?? false,\n outRef: s.outRef,\n }\n : { id: s.handle.id, status: 'down', reason: s.reason }\n ledger.push(w)\n return w\n }\n\n const nextQuestionId = (from: string): string => `${from}:q${questionSeq++}`\n const normalizeQuestion = (q: QuestionInput, fallbackFrom: string): Question => {\n const from = str(q.from ?? fallbackFrom, 'from')\n return {\n id: typeof q.id === 'string' && q.id.length > 0 ? q.id : nextQuestionId(from),\n from,\n level: level(q.level),\n question: str(q.question, 'question'),\n reason: str(q.reason, 'reason'),\n ...(q.options ? { options: q.options } : {}),\n urgency: urgency(q.urgency),\n }\n }\n const addQuestion = (\n raw: QuestionInput,\n fallbackFrom: string,\n decision?: QuestionDecision,\n ): { question: QuestionRecord; added: boolean } => {\n const q = normalizeQuestion(raw, fallbackFrom)\n const existing = questions.find((x) => x.id === q.id)\n if (existing) return { question: existing, added: false }\n const effectiveDecision =\n decision ??\n (questionPolicy === 'bubble'\n ? ({\n kind: 'escalate',\n to: 'parent',\n reason: 'question policy bubbled to parent',\n } as const)\n : undefined)\n const status: QuestionRecord['status'] =\n effectiveDecision?.kind === 'answer'\n ? 'answered'\n : effectiveDecision?.kind === 'defer'\n ? 'deferred'\n : effectiveDecision?.kind === 'escalate'\n ? 'escalated'\n : 'open'\n const record: QuestionRecord = {\n ...q,\n status,\n openedAt: Date.now(),\n ...(effectiveDecision ? { decision: effectiveDecision } : {}),\n }\n questions.push(record)\n return { question: record, added: true }\n }\n const emitNewQuestion = async (record: {\n question: QuestionRecord\n added: boolean\n }): Promise<QuestionRecord> => {\n if (record.added) await opts.onEvent?.({ type: 'question', question: record.question })\n return record.question\n }\n const decideQuestion = (questionId: string, decision: QuestionDecision): QuestionRecord => {\n const idx = questions.findIndex((q) => q.id === questionId)\n if (idx < 0) throw new Error(`unknown questionId ${JSON.stringify(questionId)}`)\n const prior = questions[idx] as QuestionRecord\n const status: QuestionRecord['status'] =\n decision.kind === 'answer' ? 'answered' : decision.kind === 'defer' ? 'deferred' : 'escalated'\n const next: QuestionRecord = { ...prior, status, decision }\n questions[idx] = next\n return next\n }\n const blockingQuestionsForStop = (): QuestionRecord[] => {\n if (questionPolicy === 'auto' || questionPolicy === 'bubble') return []\n return questions.filter((q) => {\n const blocking = q.urgency === 'blocks-step' || q.urgency === 'blocks-run'\n if (!blocking) return false\n if (questionPolicy === 'mustDecide') return q.status === 'open'\n return q.status !== 'answered' && q.status !== 'deferred'\n })\n }\n\n const tools: McpToolDescriptor[] = [\n {\n name: 'spawn_worker',\n description:\n 'Start a worker the driver will drive. `profile` is the worker or another driver; ' +\n '`task` is what it should do. Reserves budget from the conserved pool and fails closed.',\n inputSchema: {\n type: 'object',\n properties: {\n profile: { description: 'The worker/driver profile to run.' },\n task: { description: 'The task the worker should perform.' },\n label: { type: 'string', description: 'Optional trace label.' },\n },\n required: ['profile', 'task'],\n },\n handler: (raw) => {\n const a = obj(raw)\n const agent = opts.makeWorkerAgent(a.profile)\n const res = opts.scope.spawn(agent, a.task, {\n budget: opts.perWorker,\n label: typeof a.label === 'string' ? a.label : 'worker',\n })\n return Promise.resolve(res.ok ? { workerId: res.handle.id } : { error: res.reason })\n },\n },\n {\n name: 'observe_worker',\n description: 'Inspect a worker status, spend, and settled output artifact when available.',\n inputSchema: { type: 'object', properties: { workerId: idArg }, required: ['workerId'] },\n handler: async (raw) => {\n const id = str(obj(raw).workerId, 'workerId')\n const node = opts.scope.view.nodes.find((n) => n.id === id)\n if (!node) return { error: `unknown workerId ${JSON.stringify(id)}` }\n const output = node.outRef ? await opts.blobs.get(node.outRef) : undefined\n return {\n status: node.status,\n spent: node.spent,\n outRef: node.outRef ?? null,\n output: output ?? null,\n }\n },\n },\n {\n name: 'steer_worker',\n description: 'Deliver an out-of-band instruction to a running worker inbox.',\n inputSchema: {\n type: 'object',\n properties: {\n workerId: idArg,\n instruction: { type: 'string', description: 'What the worker should do next.' },\n },\n required: ['workerId', 'instruction'],\n },\n handler: (raw) => {\n const a = obj(raw)\n const delivered = opts.scope.send(str(a.workerId, 'workerId'), {\n steer: str(a.instruction, 'instruction'),\n })\n return Promise.resolve({ delivered })\n },\n },\n {\n name: 'await_next',\n description:\n 'Wait for the next spawned worker to settle. Returns { idle: true } when none are live.',\n inputSchema: { type: 'object', properties: {} },\n handler: async () => {\n const s = await opts.scope.next()\n if (!s) return { idle: true }\n const w = recordSettled(s)\n return w.status === 'done'\n ? {\n settled: w.id,\n status: 'done',\n score: w.score,\n valid: w.valid,\n outRef: w.outRef,\n }\n : { settled: w.id, status: 'down', reason: w.reason }\n },\n },\n {\n name: 'list_questions',\n description:\n 'List questions raised by workers, drivers, or analysts. Blocking stop behavior follows questionPolicy.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ questions }),\n },\n {\n name: 'answer_question',\n description: 'Record an answer, deferral, or escalation for a loop question.',\n inputSchema: {\n type: 'object',\n properties: {\n questionId: { type: 'string' },\n answer: { type: 'string' },\n by: { type: 'string', description: 'Node id or \"user\".' },\n deferReason: { type: 'string' },\n escalateTo: { type: 'string', enum: ['parent', 'user'] },\n escalateReason: { type: 'string' },\n },\n required: ['questionId'],\n },\n handler: (raw) => {\n const a = obj(raw)\n const questionId = str(a.questionId, 'questionId')\n if (typeof a.answer === 'string' && a.answer.length > 0) {\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'answer',\n answer: a.answer,\n by: typeof a.by === 'string' && a.by.length > 0 ? a.by : 'user',\n }),\n })\n }\n if (typeof a.deferReason === 'string' && a.deferReason.length > 0) {\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'defer',\n reason: a.deferReason,\n }),\n })\n }\n if (a.escalateTo === 'parent' || a.escalateTo === 'user') {\n const escalateReason =\n typeof a.escalateReason === 'string' && a.escalateReason.length > 0\n ? a.escalateReason\n : 'driver escalated'\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'escalate',\n to: a.escalateTo,\n reason: escalateReason,\n }),\n })\n }\n throw new Error('answer_question: provide answer, deferReason, or escalateTo')\n },\n },\n {\n name: 'ask_parent',\n description: 'Raise a question to the parent driver/Pi/user when this driver cannot decide.',\n inputSchema: {\n type: 'object',\n properties: {\n from: { type: 'string' },\n level: { type: 'string', enum: ['worker', 'driver', 'loop'] },\n question: { type: 'string' },\n reason: { type: 'string' },\n urgency: { type: 'string', enum: ['continue-without', 'blocks-step', 'blocks-run'] },\n },\n required: ['from', 'level', 'question', 'reason', 'urgency'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const from = str(a.from, 'from')\n const q = await emitNewQuestion(\n addQuestion(\n {\n from,\n level: level(a.level),\n question: str(a.question, 'question'),\n reason: str(a.reason, 'reason'),\n urgency: urgency(a.urgency),\n },\n from,\n { kind: 'escalate', to: 'parent', reason: 'asked parent' },\n ),\n )\n return { question: q }\n },\n },\n {\n name: 'stop',\n description: 'Declare the run complete.',\n inputSchema: {\n type: 'object',\n properties: { reason: { type: 'string', description: 'Why you are stopping.' } },\n },\n handler: (raw) => {\n const blocking = blockingQuestionsForStop()\n if (blocking.length) {\n return Promise.resolve({\n stopped: false,\n error: 'unresolved-blocking-questions',\n questions: blocking,\n })\n }\n stopped = true\n const r = obj(raw).reason\n reason = typeof r === 'string' ? r : undefined\n return Promise.resolve({ stopped: true })\n },\n },\n ]\n\n if (opts.analysts) {\n tools.push({\n name: 'list_analysts',\n description: 'List trace-analyst lenses available to run over a settled worker.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ analysts: opts.analysts?.kinds }),\n })\n tools.push({\n name: 'run_analyst',\n description: 'Apply an analyst lens to a settled worker trace.',\n inputSchema: {\n type: 'object',\n properties: {\n kind: { type: 'string', description: 'The analyst kind id.' },\n workerId: idArg,\n },\n required: ['kind', 'workerId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const id = str(a.workerId, 'workerId')\n const node = opts.scope.view.nodes.find((n) => n.id === id)\n if (!node) return { error: `unknown workerId ${JSON.stringify(id)}` }\n if (!node.outRef)\n return { error: `worker ${JSON.stringify(id)} has not settled — no trace to analyze yet` }\n const trace = await opts.blobs.get(node.outRef)\n return { findings: await opts.analysts?.run(str(a.kind, 'kind'), trace) }\n },\n })\n }\n\n return {\n tools,\n isStopped: () => stopped,\n stopReason: () => reason,\n settled: () => ledger,\n questions: () => questions,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA;AAAA,EAIE;AAAA,OACK;AAMP,IAAM,qBAAqB,CAAC,YAAY,QAAQ,UAAU,OAAO,MAAM;AAEvE,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,EAAE,KAAK,IAAI;AAeX,SAAS,mBAAmB,KAA6B;AACvD,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,IAAI;AACV,MAAI,OAAO,EAAE,UAAU,YAAY,EAAE,MAAM,WAAW,EAAG,QAAO;AAChE,MAAI,OAAO,EAAE,iBAAiB,YAAY,CAAC,+BAA+B,KAAK,EAAE,YAAY;AAC3F,WAAO;AACT,QAAM,MAAO,mBAAyC,SAAS,EAAE,QAAkB,IAC9E,EAAE,WACH;AACJ,SAAO;AAAA,IACL,UAAU;AAAA,IACV,OAAO,EAAE;AAAA,IACT,cAAc,EAAE;AAAA,IAChB,YAAY,OAAO,EAAE,eAAe,WAAW,EAAE,aAAa;AAAA,IAC9D,GAAI,OAAO,EAAE,qBAAqB,WAAW,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,CAAC;AAAA,IACzF,GAAI,OAAO,EAAE,cAAc,WAAW,EAAE,WAAW,EAAE,UAAU,IAAI,CAAC;AAAA,IACpE,GAAI,OAAO,EAAE,uBAAuB,WAChC,EAAE,oBAAo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a;AAAA,MACb,aAAa,EAAE,MAAM,UAAU,YAAY,CAAC,EAAE;AAAA,MAC9C,SAAS,MAAM,QAAQ,QAAQ,EAAE,UAAU,KAAK,UAAU,MAAM,CAAC;AAAA,IACnE,CAAC;AACD,UAAM,KAAK;AAAA,MACT,MAAM;AAAA,MACN,aAAa;AAAA,MACb,aAAa;AAAA,QACX,MAAM;AAAA,QACN,YAAY;AAAA,UACV,MAAM,EAAE,MAAM,UAAU,aAAa,uBAAuB;AAAA,UAC5D,UAAU;AAAA,QACZ;AAAA,QACA,UAAU,CAAC,QAAQ,UAAU;AAAA,MAC/B;AAAA,MACA,SAAS,OAAO,QAAQ;AACtB,cAAM,IAAI,IAAI,GAAG;AACjB,cAAM,KAAK,IAAI,EAAE,UAAU,UAAU;AACrC,cAAM,OAAO,KAAK,MAAM,KAAK,MAAM,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE;AAC1D,YAAI,CAAC,KAAM,QAAO,EAAE,OAAO,oBAAoB,KAAK,UAAU,EAAE,CAAC,GAAG;AACpE,YAAI,CAAC,KAAK;AACR,iBAAO,EAAE,OAAO,UAAU,KAAK,UAAU,EAAE,CAAC,kDAA6C;AAC3F,cAAM,QAAQ,MAAM,KAAK,MAAM,IAAI,KAAK,MAAM;AAC9C,eAAO,EAAE,UAAU,MAAM,KAAK,UAAU,IAAI,IAAI,EAAE,MAAM,MAAM,GAAG,KAAK,EAAE;AAAA,MAC1E;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA,WAAW,MAAM;AAAA,IACjB,YAAY,MAAM;AAAA,IAClB,SAAS,MAAM;AAAA,IACf,WAAW,MAAM;AAAA,EACnB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/mcp/tools/checks.ts","../../src/mcp/tools/coordination.ts"],"sourcesContent":["/**\n * @experimental\n *\n * The trace-analyst KIND directory — the operator's lenses, as composable DATA.\n *\n * An analyst is not one question. A kind is ONE lens (completeness, correctness, policy, efficiency,\n * tool-use, …); each emits `AnalystFinding`s tagged by its `area`. The driver `list_analysts` to see\n * the menu, `run_analyst(kind, worker)` to apply a lens, and `define_analyst` to author a new one —\n * so at test time you compose the exact lenses a domain needs (maximum specificity), not one generic\n * reviewer. The kinds are data, the runner is generic, and the finding shape + firewall are reused\n * from agent-eval / the keystone — never re-derived.\n *\n * A kind here is a lightweight lens (`Check`); it is a deliberate SUBSET of agent-eval's full\n * `TraceAnalystKindSpec`, so a kind that needs the heavy agentic actor (sub-agent recursion, tools,\n * goldens) upgrades to `createTraceAnalystKind` without changing this directory's surface.\n */\n\nimport {\n type AnalystFinding,\n type AnalystSeverity,\n type EvidenceRef,\n makeFinding,\n} from '@tangle-network/agent-eval'\nimport { assertTraceDerivedFindings } from '../../runtime'\n\n// agent-eval's root entry exports the lift (`makeFinding`) + the `AnalystFinding`/`EvidenceRef` shapes\n// but NOT the raw-row validator / schema prompt (kind-factory-internal). We inline a minimal,\n// equivalent pair so a lens emits the SAME finding shape without reaching into an unstable internal.\nconst ANALYST_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const\n\nconst FINDING_SCHEMA_PROMPT = [\n 'Each finding is a JSON object with these fields:',\n '- severity: one of \"critical\" | \"high\" | \"medium\" | \"low\" | \"info\"',\n '- claim: one-sentence statement',\n '- evidence_uri: REQUIRED, never blank — exactly one of \"span://<trace>/<span>\", \"artifact://<path>\",',\n ' or \"metric://<name>\"; ALWAYS cite a real id from the trace. No citable id ⇒ omit the finding.',\n '- evidence_excerpt?: a short quote from the cited evidence',\n '- confidence: number 0..1',\n '- rationale?: one sentence of reasoning',\n '- recommended_action?: a concrete imperative (\"Add ...\", \"Replace ...\", \"Stop ...\")',\n 'Emit an empty array when there is nothing to report. Never fabricate evidence.',\n].join('\\n')\n\ninterface RawRow {\n severity: AnalystSeverity\n claim: string\n evidence_uri: string\n confidence: number\n evidence_excerpt?: string\n rationale?: string\n recommended_action?: string\n subject?: string\n}\n\n/** Validate one raw finding row (the lightweight equivalent of agent-eval's `parseRawFinding`):\n * require a claim + a real trace evidence_uri; drop anything else. Returns null to discard. */\nfunction validateRawFinding(row: unknown): RawRow | null {\n if (!row || typeof row !== 'object') return null\n const r = row as Record<string, unknown>\n if (typeof r.claim !== 'string' || r.claim.length === 0) return null\n if (typeof r.evidence_uri !== 'string' || !/^(span|artifact|metric):\\/\\//.test(r.evidence_uri))\n return null\n const sev = (ANALYST_SEVERITIES as readonly string[]).includes(r.severity as string)\n ? (r.severity as AnalystSeverity)\n : 'medium'\n return {\n severity: sev,\n claim: r.claim,\n evidence_uri: r.evidence_uri,\n confidence: typeof r.confidence === 'number' ? r.confidence : 0.5,\n ...(typeof r.evidence_excerpt === 'string' ? { evidence_excerpt: r.evidence_excerpt } : {}),\n ...(typeof r.rationale === 'string' ? { rationale: r.rationale } : {}),\n ...(typeof r.recommended_action === 'string'\n ? { recommended_action: r.recommended_action }\n : {}),\n ...(typeof r.subject === 'string' ? { subject: r.subject } : {}),\n }\n}\n\n/** One lens — a composable analyst kind. Identity fields mirror `TraceAnalystKindSpec` so a kind is\n * upgradeable to the full agentic factory; `lookFor` is the lens question the actor applies. */\nexport interface Check {\n readonly id: string\n readonly description: string\n /** Coarse classification stamped on every finding this kind emits (the renderer groups by it). */\n readonly area: string\n readonly version: string\n /** The lens — what this analyst looks for in the trace. */\n readonly lookFor: string\n}\n\n/** The built-in lens directory. Domain-blind (about any agent trace); compose at test time. */\nexport const defaultChecks: Record<string, Check> = {\n completeness: {\n id: 'completeness',\n description: 'Required work the trace does not yet show done or verified.',\n area: 'failure-mode',\n version: '1',\n lookFor:\n 'every change the task requires that the trace does NOT yet show completed AND verified by a ' +\n 'tool result. One finding per missing/unverified requirement.',\n },\n correctness: {\n id: 'correctness',\n description: 'Tool calls that produced wrong, erroring, or contradicted results.',\n area: 'correctness',\n version: '1',\n lookFor:\n 'tool calls whose RESULT shows an error, a wrong value, or contradicts what the task required ' +\n '(e.g. set the wrong field, value did not take, an error was ignored).',\n },\n policy: {\n id: 'policy',\n description: 'Actions that violate a stated policy, constraint, or allow-list.',\n area: 'safety',\n version: '1',\n lookFor:\n 'actions in the trace that violate a policy/constraint stated in the task or system prompt ' +\n '(forbidden tool, missing approval, out-of-scope mutation, skipped precondition).',\n },\n efficiency: {\n id: 'efficiency',\n description: 'Wasted, redundant, or looping work.',\n area: 'cost',\n version: '1',\n lookFor:\n 'redundant or wasted actions — repeated identical calls, a stalled line retried the same way, ' +\n 'work that produced no progress toward the goal.',\n },\n 'tool-use': {\n id: 'tool-use',\n description: 'Malformed or misused tool calls.',\n area: 'tool-use',\n version: '1',\n lookFor:\n 'tool calls with malformed/invalid arguments, the wrong tool for the intent, or a tool used ' +\n 'against its contract — judged from the call + its result.',\n },\n}\n\n/** Lift validated raw rows into `AnalystFinding`s (agent-eval `makeFinding` stamps `finding_id`/\n * `produced_at`), then enforce the trace-derived firewall (selector ≠ judge). Pure — no LLM. */\nexport function liftFindings(kind: Check, rows: unknown[], producedAt: string): AnalystFinding[] {\n const findings: AnalystFinding[] = []\n for (const row of rows) {\n const raw = validateRawFinding(row)\n if (!raw) continue\n findings.push(\n makeFinding({\n analyst_id: kind.id,\n area: kind.area,\n severity: raw.severity,\n claim: raw.claim,\n confidence: raw.confidence,\n produced_at: producedAt,\n evidence_refs: evidenceRefs(raw.evidence_uri, raw.evidence_excerpt),\n ...(raw.rationale ? { rationale: raw.rationale } : {}),\n ...(raw.recommended_action ? { recommended_action: raw.recommended_action } : {}),\n ...(raw.subject ? { subject: raw.subject } : {}),\n metadata: { kind_version: kind.version },\n }),\n )\n }\n assertTraceDerivedFindings(findings) // throws if a finding cites judge/verdict/score evidence\n return findings\n}\n\n/** Map a raw `evidence_uri` (span:// | artifact:// | metric://<name>) to a typed `EvidenceRef`. A\n * metric ref carries the bare NAME (the firewall checks the metric name for judge/verdict/score —\n * so a finding that cites a judge metric is rejected as not trace-derived). */\nfunction evidenceRefs(uri: string, excerpt?: string): EvidenceRef[] {\n const scheme = uri.split('://', 1)[0]\n if (scheme === 'metric')\n return [\n { kind: 'metric', uri: uri.replace(/^metric:\\/\\//, ''), ...(excerpt ? { excerpt } : {}) },\n ]\n const kind: EvidenceRef['kind'] = scheme === 'span' ? 'span' : 'artifact'\n return [{ kind, uri, ...(excerpt ? { excerpt } : {}) }]\n}\n\n/** Render a worker's trace (tool calls + results) into the text an analyst lens reads. Generic over\n * the trace shape: a `{ messages }` conversation, a bare message array, else stringified. */\nexport function renderTrace(trace: unknown): string {\n const messages = Array.isArray(trace)\n ? trace\n : trace &&\n typeof trace === 'object' &&\n Array.isArray((trace as { messages?: unknown[] }).messages)\n ? (trace as { messages: unknown[] }).messages\n : undefined\n if (!messages) return JSON.stringify(trace ?? {}).slice(0, 8000)\n return messages\n .map((m) => {\n const r = m as {\n role?: string\n content?: unknown\n tool_calls?: Array<{ function?: { name?: string; arguments?: string } }>\n }\n if (r.role === 'tool') return `RESULT ${String(r.content).slice(0, 300)}`\n const calls = r.tool_calls\n ?.map((c) => `${c.function?.name}(${c.function?.arguments})`)\n .join(', ')\n return calls ? `CALL ${calls}` : `SAY ${String(r.content ?? '').slice(0, 200)}`\n })\n .join('\\n')\n .slice(0, 8000)\n}\n\nexport interface CheckRunnerOptions {\n routerBaseUrl: string\n routerKey: string\n model: string\n /** Test/override seam — replace the LLM call. Default: a router chat completion. */\n chat?: (system: string, user: string) => Promise<string>\n}\n\n/** Run ONE lens over a trace → findings. Generic over any kind: prompt = the lens + the agent-eval\n * finding schema; the model's JSON array is parsed (`parseRawFinding`), lifted, and firewalled. */\nexport async function runCheck(\n kind: Check,\n trace: unknown,\n opts: CheckRunnerOptions,\n producedAt: string,\n): Promise<AnalystFinding[]> {\n const sys =\n `You are a trace analyst applying ONE lens: look for ${kind.lookFor}\\n\\n` +\n `${FINDING_SCHEMA_PROMPT}\\n\\nReturn ONLY a fenced \\`\\`\\`json array of finding objects (possibly empty).`\n const user = `WORKER TRACE:\\n${renderTrace(trace)}\\n\\nApply your lens and emit the findings array.`\n const chat = opts.chat ?? defaultChat(opts)\n const content = await chat(sys, user)\n const match = content.match(/```(?:json)?\\s*([\\s\\S]*?)```/)\n let rows: unknown[] = []\n try {\n const parsed = JSON.parse((match?.[1] ?? content).trim())\n rows = Array.isArray(parsed)\n ? parsed\n : Array.isArray((parsed as { findings?: unknown[] })?.findings)\n ? (parsed as { findings: unknown[] }).findings\n : []\n } catch {\n rows = []\n }\n return liftFindings(kind, rows, producedAt)\n}\n\nfunction defaultChat(opts: CheckRunnerOptions): (system: string, user: string) => Promise<string> {\n return async (system, user) => {\n const res = await fetch(`${opts.routerBaseUrl.replace(/\\/$/, '')}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.routerKey}` },\n body: JSON.stringify({\n model: opts.model,\n messages: [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n temperature: 0.3,\n }),\n })\n if (!res.ok) throw new Error(`analyst router ${res.status}`)\n const data = (await res.json()) as { choices?: Array<{ message?: { content?: string } }> }\n return data.choices?.[0]?.message?.content ?? ''\n }\n}\n\n/**\n * Build a `run_analyst` runner over a kind directory.\n * Returns findings, or a typed error for an unknown kind. `producedAt` is\n * passed in because replay-safe paths must not read `Date.now`.\n */\nexport function makeCheckRunner(\n kinds: Record<string, Check>,\n opts: CheckRunnerOptions,\n): (\n kindId: string,\n trace: unknown,\n producedAt: string,\n) => Promise<AnalystFinding[] | { error: string }> {\n return async (kindId, trace, producedAt) => {\n const kind = kinds[kindId]\n if (!kind)\n return {\n error: `unknown analyst kind ${JSON.stringify(kindId)} (have: ${Object.keys(kinds).join(', ')})`,\n }\n return runCheck(kind, trace, opts, producedAt)\n }\n}\n","/**\n * @experimental\n *\n * MCP binding for a live `Scope`. A sandbox driver gets the same small verbs\n * the in-process driver has: spawn, observe, await, steer, ask/answer, analyze,\n * and stop. Settled outputs remain Scope artifacts; product code can project\n * them into any UI/report envelope it needs.\n */\n\nimport type {\n Budget,\n ResultBlobStore,\n Scope,\n Settled,\n Agent as SuperviseAgent,\n} from '../../runtime'\nimport type { McpToolDescriptor } from '../server'\n\n/** A worker the driver has drained via `await_next`. */\nexport interface SettledWorker {\n readonly id: string\n readonly status: 'done' | 'down'\n readonly score?: number\n readonly valid?: boolean\n readonly outRef?: string\n readonly reason?: string\n}\n\nexport type QuestionLevel = 'worker' | 'driver' | 'loop'\nexport type QuestionUrgency = 'continue-without' | 'blocks-step' | 'blocks-run'\n\nexport interface QuestionOption {\n readonly label: string\n readonly tradeoff: string\n}\n\nexport interface Question {\n readonly id: string\n readonly from: string\n readonly level: QuestionLevel\n readonly question: string\n readonly reason: string\n readonly urgency: QuestionUrgency\n readonly options?: ReadonlyArray<QuestionOption>\n}\n\nexport type QuestionDecision =\n | { readonly kind: 'answer'; readonly answer: string; readonly by: string }\n | { readonly kind: 'defer'; readonly reason: string }\n | { readonly kind: 'escalate'; readonly to: 'parent' | 'user' | string; readonly reason: string }\n\nexport interface QuestionRecord extends Question {\n readonly status: 'open' | 'answered' | 'deferred' | 'escalated'\n readonly decision?: QuestionDecision\n readonly openedAt: number\n}\n\ntype QuestionInput = Omit<Question, 'id'> & { readonly id?: string }\nexport type QuestionPolicy = 'auto' | 'mustDecide' | 'bubble' | 'failClosed'\n\nexport interface AnalystRegistry {\n readonly kinds: ReadonlyArray<{ id: string; description: string; area: string }>\n readonly run: (kindId: string, trace: unknown) => Promise<unknown>\n}\n\nexport type CoordinationEvent = { readonly type: 'question'; readonly question: QuestionRecord }\n\nexport type MakeWorkerAgent = (profile: unknown) => SuperviseAgent<unknown, unknown>\n\nexport interface CoordinationToolsOptions {\n readonly scope: Scope<unknown>\n readonly blobs: ResultBlobStore\n readonly makeWorkerAgent: MakeWorkerAgent\n readonly perWorker: Budget\n readonly analysts?: AnalystRegistry\n readonly onEvent?: (event: CoordinationEvent) => void | Promise<void>\n readonly questionPolicy?: QuestionPolicy\n}\n\nexport interface CoordinationTools {\n readonly tools: McpToolDescriptor[]\n isStopped(): boolean\n stopReason(): string | undefined\n settled(): ReadonlyArray<SettledWorker>\n questions(): ReadonlyArray<QuestionRecord>\n}\n\nconst idArg = { type: 'string', description: 'The workerId returned by spawn_worker.' } as const\n\n/** Build the driver's MCP tools over a live scope. */\nexport function createCoordinationTools(opts: CoordinationToolsOptions): CoordinationTools {\n let stopped = false\n let reason: string | undefined\n let questionSeq = 0\n const ledger: SettledWorker[] = []\n const questions: QuestionRecord[] = []\n const questionPolicy = opts.questionPolicy ?? 'auto'\n\n const str = (v: unknown, field: string): string => {\n if (typeof v !== 'string' || v.length === 0)\n throw new Error(`coordination tools: \"${field}\" must be a non-empty string`)\n return v\n }\n const obj = (raw: unknown): Record<string, unknown> => {\n if (!raw || typeof raw !== 'object')\n throw new Error('coordination tools: arguments must be an object')\n return raw as Record<string, unknown>\n }\n const level = (v: unknown): Question['level'] => {\n if (v === 'worker' || v === 'driver' || v === 'loop') return v\n throw new Error('coordination tools: \"level\" must be worker, driver, or loop')\n }\n const urgency = (v: unknown): Question['urgency'] => {\n if (v === 'continue-without' || v === 'blocks-step' || v === 'blocks-run') return v\n throw new Error(\n 'coordination tools: \"urgency\" must be continue-without, blocks-step, or blocks-run',\n )\n }\n\n const recordSettled = (s: Settled<unknown>): SettledWorker => {\n const w: SettledWorker =\n s.kind === 'done'\n ? {\n id: s.handle.id,\n status: 'done',\n score: s.verdict?.score ?? 0,\n valid: s.verdict?.valid ?? false,\n outRef: s.outRef,\n }\n : { id: s.handle.id, status: 'down', reason: s.reason }\n ledger.push(w)\n return w\n }\n\n const nextQuestionId = (from: string): string => `${from}:q${questionSeq++}`\n const normalizeQuestion = (q: QuestionInput, fallbackFrom: string): Question => {\n const from = str(q.from ?? fallbackFrom, 'from')\n return {\n id: typeof q.id === 'string' && q.id.length > 0 ? q.id : nextQuestionId(from),\n from,\n level: level(q.level),\n question: str(q.question, 'question'),\n reason: str(q.reason, 'reason'),\n ...(q.options ? { options: q.options } : {}),\n urgency: urgency(q.urgency),\n }\n }\n const addQuestion = (\n raw: QuestionInput,\n fallbackFrom: string,\n decision?: QuestionDecision,\n ): { question: QuestionRecord; added: boolean } => {\n const q = normalizeQuestion(raw, fallbackFrom)\n const existing = questions.find((x) => x.id === q.id)\n if (existing) return { question: existing, added: false }\n const effectiveDecision =\n decision ??\n (questionPolicy === 'bubble'\n ? ({\n kind: 'escalate',\n to: 'parent',\n reason: 'question policy bubbled to parent',\n } as const)\n : undefined)\n const status: QuestionRecord['status'] =\n effectiveDecision?.kind === 'answer'\n ? 'answered'\n : effectiveDecision?.kind === 'defer'\n ? 'deferred'\n : effectiveDecision?.kind === 'escalate'\n ? 'escalated'\n : 'open'\n const record: QuestionRecord = {\n ...q,\n status,\n openedAt: Date.now(),\n ...(effectiveDecision ? { decision: effectiveDecision } : {}),\n }\n questions.push(record)\n return { question: record, added: true }\n }\n const emitNewQuestion = async (record: {\n question: QuestionRecord\n added: boolean\n }): Promise<QuestionRecord> => {\n if (record.added) await opts.onEvent?.({ type: 'question', question: record.question })\n return record.question\n }\n const decideQuestion = (questionId: string, decision: QuestionDecision): QuestionRecord => {\n const idx = questions.findIndex((q) => q.id === questionId)\n if (idx < 0) throw new Error(`unknown questionId ${JSON.stringify(questionId)}`)\n const prior = questions[idx] as QuestionRecord\n const status: QuestionRecord['status'] =\n decision.kind === 'answer' ? 'answered' : decision.kind === 'defer' ? 'deferred' : 'escalated'\n const next: QuestionRecord = { ...prior, status, decision }\n questions[idx] = next\n return next\n }\n const blockingQuestionsForStop = (): QuestionRecord[] => {\n if (questionPolicy === 'auto' || questionPolicy === 'bubble') return []\n return questions.filter((q) => {\n const blocking = q.urgency === 'blocks-step' || q.urgency === 'blocks-run'\n if (!blocking) return false\n if (questionPolicy === 'mustDecide') return q.status === 'open'\n return q.status !== 'answered' && q.status !== 'deferred'\n })\n }\n\n const tools: McpToolDescriptor[] = [\n {\n name: 'spawn_worker',\n description:\n 'Start a worker the driver will drive. `profile` is the worker or another driver; ' +\n '`task` is what it should do. Reserves budget from the conserved pool and fails closed.',\n inputSchema: {\n type: 'object',\n properties: {\n profile: { description: 'The worker/driver profile to run.' },\n task: { description: 'The task the worker should perform.' },\n label: { type: 'string', description: 'Optional trace label.' },\n },\n required: ['profile', 'task'],\n },\n handler: (raw) => {\n const a = obj(raw)\n const agent = opts.makeWorkerAgent(a.profile)\n const res = opts.scope.spawn(agent, a.task, {\n budget: opts.perWorker,\n label: typeof a.label === 'string' ? a.label : 'worker',\n })\n return Promise.resolve(res.ok ? { workerId: res.handle.id } : { error: res.reason })\n },\n },\n {\n name: 'observe_worker',\n description: 'Inspect a worker status, spend, and settled output artifact when available.',\n inputSchema: { type: 'object', properties: { workerId: idArg }, required: ['workerId'] },\n handler: async (raw) => {\n const id = str(obj(raw).workerId, 'workerId')\n const node = opts.scope.view.nodes.find((n) => n.id === id)\n if (!node) return { error: `unknown workerId ${JSON.stringify(id)}` }\n const output = node.outRef ? await opts.blobs.get(node.outRef) : undefined\n return {\n status: node.status,\n spent: node.spent,\n outRef: node.outRef ?? null,\n output: output ?? null,\n }\n },\n },\n {\n name: 'steer_worker',\n description: 'Deliver an out-of-band instruction to a running worker inbox.',\n inputSchema: {\n type: 'object',\n properties: {\n workerId: idArg,\n instruction: { type: 'string', description: 'What the worker should do next.' },\n },\n required: ['workerId', 'instruction'],\n },\n handler: (raw) => {\n const a = obj(raw)\n const delivered = opts.scope.send(str(a.workerId, 'workerId'), {\n steer: str(a.instruction, 'instruction'),\n })\n return Promise.resolve({ delivered })\n },\n },\n {\n name: 'await_next',\n description:\n 'Wait for the next spawned worker to settle. Returns { idle: true } when none are live.',\n inputSchema: { type: 'object', properties: {} },\n handler: async () => {\n const s = await opts.scope.next()\n if (!s) return { idle: true }\n const w = recordSettled(s)\n return w.status === 'done'\n ? {\n settled: w.id,\n status: 'done',\n score: w.score,\n valid: w.valid,\n outRef: w.outRef,\n }\n : { settled: w.id, status: 'down', reason: w.reason }\n },\n },\n {\n name: 'list_questions',\n description:\n 'List questions raised by workers, drivers, or analysts. Blocking stop behavior follows questionPolicy.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ questions }),\n },\n {\n name: 'answer_question',\n description: 'Record an answer, deferral, or escalation for a loop question.',\n inputSchema: {\n type: 'object',\n properties: {\n questionId: { type: 'string' },\n answer: { type: 'string' },\n by: { type: 'string', description: 'Node id or \"user\".' },\n deferReason: { type: 'string' },\n escalateTo: { type: 'string', enum: ['parent', 'user'] },\n escalateReason: { type: 'string' },\n },\n required: ['questionId'],\n },\n handler: (raw) => {\n const a = obj(raw)\n const questionId = str(a.questionId, 'questionId')\n if (typeof a.answer === 'string' && a.answer.length > 0) {\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'answer',\n answer: a.answer,\n by: typeof a.by === 'string' && a.by.length > 0 ? a.by : 'user',\n }),\n })\n }\n if (typeof a.deferReason === 'string' && a.deferReason.length > 0) {\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'defer',\n reason: a.deferReason,\n }),\n })\n }\n if (a.escalateTo === 'parent' || a.escalateTo === 'user') {\n const escalateReason =\n typeof a.escalateReason === 'string' && a.escalateReason.length > 0\n ? a.escalateReason\n : 'driver escalated'\n return Promise.resolve({\n question: decideQuestion(questionId, {\n kind: 'escalate',\n to: a.escalateTo,\n reason: escalateReason,\n }),\n })\n }\n throw new Error('answer_question: provide answer, deferReason, or escalateTo')\n },\n },\n {\n name: 'ask_parent',\n description: 'Raise a question to the parent driver/Pi/user when this driver cannot decide.',\n inputSchema: {\n type: 'object',\n properties: {\n from: { type: 'string' },\n level: { type: 'string', enum: ['worker', 'driver', 'loop'] },\n question: { type: 'string' },\n reason: { type: 'string' },\n urgency: { type: 'string', enum: ['continue-without', 'blocks-step', 'blocks-run'] },\n },\n required: ['from', 'level', 'question', 'reason', 'urgency'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const from = str(a.from, 'from')\n const q = await emitNewQuestion(\n addQuestion(\n {\n from,\n level: level(a.level),\n question: str(a.question, 'question'),\n reason: str(a.reason, 'reason'),\n urgency: urgency(a.urgency),\n },\n from,\n { kind: 'escalate', to: 'parent', reason: 'asked parent' },\n ),\n )\n return { question: q }\n },\n },\n {\n name: 'stop',\n description: 'Declare the run complete.',\n inputSchema: {\n type: 'object',\n properties: { reason: { type: 'string', description: 'Why you are stopping.' } },\n },\n handler: (raw) => {\n const blocking = blockingQuestionsForStop()\n if (blocking.length) {\n return Promise.resolve({\n stopped: false,\n error: 'unresolved-blocking-questions',\n questions: blocking,\n })\n }\n stopped = true\n const r = obj(raw).reason\n reason = typeof r === 'string' ? r : undefined\n return Promise.resolve({ stopped: true })\n },\n },\n ]\n\n if (opts.analysts) {\n tools.push({\n name: 'list_analysts',\n description: 'List trace-analyst lenses available to run over a settled worker.',\n inputSchema: { type: 'object', properties: {} },\n handler: () => Promise.resolve({ analysts: opts.analysts?.kinds }),\n })\n tools.push({\n name: 'run_analyst',\n description: 'Apply an analyst lens to a settled worker trace.',\n inputSchema: {\n type: 'object',\n properties: {\n kind: { type: 'string', description: 'The analyst kind id.' },\n workerId: idArg,\n },\n required: ['kind', 'workerId'],\n },\n handler: async (raw) => {\n const a = obj(raw)\n const id = str(a.workerId, 'workerId')\n const node = opts.scope.view.nodes.find((n) => n.id === id)\n if (!node) return { error: `unknown workerId ${JSON.stringify(id)}` }\n if (!node.outRef)\n return { error: `worker ${JSON.stringify(id)} has not settled — no trace to analyze yet` }\n const trace = await opts.blobs.get(node.outRef)\n return { findings: await opts.analysts?.run(str(a.kind, 'kind'), trace) }\n },\n })\n }\n\n return {\n tools,\n isStopped: () => stopped,\n stopReason: () => reason,\n settled: () => ledger,\n questions: () => questions,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA;AAAA,EAIE;AAAA,OACK;AAMP,IAAM,qBAAqB,CAAC,YAAY,QAAQ,UAAU,OAAO,MAAM;AAEvE,IAAM,w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