@tangle-network/agent-runtime 0.185.2 → 0.188.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.
- package/dist/{activation-wYQYXdaN.js → activation-CpEoQaj5.js} +3 -3
- package/dist/{activation-wYQYXdaN.js.map → activation-CpEoQaj5.js.map} +1 -1
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +3 -3
- package/dist/{analyst-loop-DCTra9Qy.js → analyst-loop-CSH7P-Bf.js} +2 -2
- package/dist/{analyst-loop-DCTra9Qy.js.map → analyst-loop-CSH7P-Bf.js.map} +1 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/analyst-loop.js +1 -1
- package/dist/{authoring-DPBWqmKI.js → authoring-fsUwd9hg.js} +2 -2
- package/dist/{authoring-DPBWqmKI.js.map → authoring-fsUwd9hg.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-7lVEly33.js → candidate-execution-CehLeZmx.js} +4 -4
- package/dist/{candidate-execution-7lVEly33.js.map → candidate-execution-CehLeZmx.js.map} +1 -1
- package/dist/{conversation-DOuYw0ke.js → conversation-DILnmy84.js} +2 -2
- package/dist/{conversation-DOuYw0ke.js.map → conversation-DILnmy84.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/{coordination-driver-CMA8JjHm.js → coordination-driver-CtbyZv5d.js} +4 -4
- package/dist/{coordination-driver-CMA8JjHm.js.map → coordination-driver-CtbyZv5d.js.map} +1 -1
- package/dist/durable.d.ts +24 -3
- package/dist/durable.js +12 -2
- package/dist/durable.js.map +1 -1
- package/dist/environment-provider-C4AQiUxj.d.ts +143 -0
- package/dist/{environment-provider-CoHsIFp5.js → environment-provider-DZxuH3E4.js} +55 -8
- package/dist/environment-provider-DZxuH3E4.js.map +1 -0
- package/dist/environment-provider.d.ts +2 -2
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-BE92JgZp.js → graph-Cox_7pht.js} +92 -4
- package/dist/graph-Cox_7pht.js.map +1 -0
- package/dist/graph.d.ts +3 -3
- package/dist/graph.js +5 -5
- package/dist/{improvement-cycle-DpZ-QVJ7.js → improvement-cycle-BYHefgVo.js} +6 -6
- package/dist/{improvement-cycle-DpZ-QVJ7.js.map → improvement-cycle-BYHefgVo.js.map} +1 -1
- package/dist/{index-DHSZjuLC.d.ts → index-DA9jKuJc.d.ts} +3 -3
- package/dist/{index-BhtdFMnG.d.ts → index-DVob1IA1.d.ts} +117 -14
- package/dist/{index-Dg2UXocB.d.ts → index-DdmozvB8.d.ts} +4 -4
- package/dist/index.d.ts +9 -9
- package/dist/index.js +13 -13
- package/dist/intelligence.d.ts +5 -5
- package/dist/intelligence.js +6 -6
- package/dist/kernel.d.ts +7 -7
- package/dist/kernel.js +13 -13
- package/dist/{knowledge-ChNVQklk.js → knowledge-Bj1rDycX.js} +5 -5
- package/dist/{knowledge-ChNVQklk.js.map → knowledge-Bj1rDycX.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-JEk_AK4l.js → loop-runner-bin-DgmtU0F0.js} +4 -4
- package/dist/{loop-runner-bin-JEk_AK4l.js.map → loop-runner-bin-DgmtU0F0.js.map} +1 -1
- package/dist/{loop-runner-bin-NanoP_bG.d.ts → loop-runner-bin-g9fWDuOh.d.ts} +3 -3
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +6 -6
- package/dist/mcp/index.js +6 -6
- package/dist/{openai-tools-Cbk5uBUu.d.ts → openai-tools-BDwAdxk5.d.ts} +2 -2
- package/dist/{openai-tools-5SoV8xqN.js → openai-tools-Cz04RKfD.js} +2 -2
- package/dist/{openai-tools-5SoV8xqN.js.map → openai-tools-Cz04RKfD.js.map} +1 -1
- package/dist/{prepare-Tip-2ZoZ.js → prepare-BpIGs5Tc.js} +123 -40
- package/dist/prepare-BpIGs5Tc.js.map +1 -0
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/profiles.d.ts +2 -2
- package/dist/{protected-model-port-Dd3a1SRm.js → protected-model-port-YclORl0x.js} +2 -2
- package/dist/{protected-model-port-Dd3a1SRm.js.map → protected-model-port-YclORl0x.js.map} +1 -1
- package/dist/{provision-supervisor-DptgdNBI.js → provision-supervisor-B-_4I1In.js} +5 -5
- package/dist/{provision-supervisor-DptgdNBI.js.map → provision-supervisor-B-_4I1In.js.map} +1 -1
- package/dist/{redact-BYcuQ6R_.d.ts → redact-C9EWk1FT.d.ts} +3 -3
- package/dist/{runtime-DtzMGguV.js → runtime-DN0SxAaM.js} +13 -13
- package/dist/{runtime-DtzMGguV.js.map → runtime-DN0SxAaM.js.map} +1 -1
- package/dist/{runtime-B-DLSfE5.d.ts → runtime-EQgE3942.d.ts} +23 -7
- package/dist/{sandbox-events-DGXLxiuX.js → sandbox-events-DWeQRWxg.js} +4 -2
- package/dist/sandbox-events-DWeQRWxg.js.map +1 -0
- package/dist/{spawn-journal--N8Ten1q.js → spawn-journal-CxRa-NJ2.js} +2 -2
- package/dist/{spawn-journal--N8Ten1q.js.map → spawn-journal-CxRa-NJ2.js.map} +1 -1
- package/dist/{stream-agent-turn-DY-y9yW1.d.ts → stream-agent-turn-BomJ21AK.d.ts} +3 -3
- package/dist/{stream-agent-turn-C82amSXX.js → stream-agent-turn-DWWe_7bh.js} +2 -2
- package/dist/{stream-agent-turn-C82amSXX.js.map → stream-agent-turn-DWWe_7bh.js.map} +1 -1
- package/dist/{structural-rollout-BXxt_yLq.js → structural-rollout-DPmVZaLI.js} +4 -4
- package/dist/{structural-rollout-BXxt_yLq.js.map → structural-rollout-DPmVZaLI.js.map} +1 -1
- package/dist/{substrate-RrmNZoL3.d.ts → substrate-qLePHqvH.d.ts} +2 -2
- package/dist/{supervise-CgVFzWv-.js → supervise-BUy1cr2L.js} +245 -29
- package/dist/supervise-BUy1cr2L.js.map +1 -0
- package/dist/{supervisor-D7FrKvu6.js → supervisor-BSNkaM2a.js} +149 -20
- package/dist/supervisor-BSNkaM2a.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +13 -13
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{types-B-rWcun_.d.ts → types-BbkiJR1D.d.ts} +37 -4
- package/dist/{types-CrTTgig6.d.ts → types-BdolQ6Zi.d.ts} +20 -1
- package/dist/{util-D6ZEuBMi.js → util-BfoW6RU7.js} +53 -4
- package/dist/util-BfoW6RU7.js.map +1 -0
- package/dist/{workspace-archive-ByonPBl-.js → workspace-archive-5K72EnlT.js} +2 -2
- package/dist/{workspace-archive-ByonPBl-.js.map → workspace-archive-5K72EnlT.js.map} +1 -1
- package/package.json +8 -8
- package/dist/environment-provider-CoHsIFp5.js.map +0 -1
- package/dist/environment-provider-CzohJCuk.d.ts +0 -89
- package/dist/graph-BE92JgZp.js.map +0 -1
- package/dist/prepare-Tip-2ZoZ.js.map +0 -1
- package/dist/sandbox-events-DGXLxiuX.js.map +0 -1
- package/dist/supervise-CgVFzWv-.js.map +0 -1
- package/dist/supervisor-D7FrKvu6.js.map +0 -1
- package/dist/util-D6ZEuBMi.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop-runner-bin-JEk_AK4l.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAo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ADc,OAAO,QAAQ,aAAc,IAAsB,IAAI;AAEvE;AAEA,SAAS,OAAO,KAAsB;CACpC,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;;AAGA,eAAe,OAAsB;CACnC,MAAM,EAAE,MAAM,WAAW,oBAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC;CAClE,IAAI,CAAC,QAAQ,CAAC,QAAQ;EACpB,QAAQ,OAAO,MACb;WACc,qBAAqB,KAAK,KAAK,EAAE;CAEjD;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK;CAC7F,CAAC;CACD,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
|
|
1
|
+
{"version":3,"file":"loop-runner-bin-DgmtU0F0.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAm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A,OAAO;AACT;;AAGA,SAAS,gBAAgB,KAAqC;CAC5D,MAAM,MAAO,KAA+B,WAAW;CAEvD,OADc,OAAO,QAAQ,aAAc,IAAsB,IAAI;AAEvE;AAEA,SAAS,OAAO,KAAsB;CACpC,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;;AAGA,eAAe,OAAsB;CACnC,MAAM,EAAE,MAAM,WAAW,oBAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC;CAClE,IAAI,CAAC,QAAQ,CAAC,QAAQ;EACpB,QAAQ,OAAO,MACb;WACc,qBAAqB,KAAK,KAAK,EAAE;CAEjD;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK;CAC7F,CAAC;CACD,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { d as RunAnalystLoopOpts, f as RunAnalystLoopResult } from "./types-zWfqDjeL.js";
|
|
2
|
-
import { D as AuthoredHarness, O as WorktreeFanoutOptions,
|
|
3
|
-
import { i as Budget } from "./types-
|
|
2
|
+
import { D as AuthoredHarness, O as WorktreeFanoutOptions, hl as WinnerStrategy, ln as WorktreePatchArtifact } from "./index-DVob1IA1.js";
|
|
3
|
+
import { i as Budget } from "./types-BbkiJR1D.js";
|
|
4
4
|
import { n as FactCandidate, t as CreateKbGateOptions } from "./kb-gate-C8z2juK8.js";
|
|
5
5
|
import { AgentProfile } from "@tangle-network/agent-interface";
|
|
6
6
|
//#region src/loop-runner.d.ts
|
|
@@ -162,4 +162,4 @@ declare function parseLoopRunnerArgv(argv: string[]): {
|
|
|
162
162
|
};
|
|
163
163
|
//#endregion
|
|
164
164
|
export { researchLoopRunner as _, DELEGATED_LOOP_MODES as a, DelegatedLoopResult as c, ResearchLoopRunnerOptions as d, RunDelegatedLoopOptions as f, isDelegatedLoopMode as g, auditLoopRunner as h, runLoopRunnerCli as i, DelegatedLoopRunner as l, WorktreeLoopRunnerOptions as m, LoopRunnerCliResult as n, DelegatedLoopMode as o, VetoedFact as p, parseLoopRunnerArgv as r, DelegatedLoopRegistry as s, LoopRunnerCliArgs as t, ResearchLoopResult as u, runDelegatedLoop as v, worktreeLoopRunner as y };
|
|
165
|
-
//# sourceMappingURL=loop-runner-bin-
|
|
165
|
+
//# sourceMappingURL=loop-runner-bin-g9fWDuOh.d.ts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-
|
|
1
|
+
import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-g9fWDuOh.js";
|
|
2
2
|
export { LoopRunnerCliArgs, LoopRunnerCliResult, parseLoopRunnerArgv, runLoopRunnerCli };
|
package/dist/loop-runner-bin.js
CHANGED
package/dist/mcp/bin.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { i as ConfigError } from "../errors-CDZ8XsVj.js";
|
|
3
|
-
import { Zt as readTraceContextFromEnv } from "../supervisor-
|
|
4
|
-
import {
|
|
5
|
-
import { a as supervisorInstructions } from "../authoring-
|
|
3
|
+
import { Zt as readTraceContextFromEnv } from "../supervisor-BSNkaM2a.js";
|
|
4
|
+
import { $ as DelegationTaskQueue, lt as FileDelegationStore, w as createMcpServer } from "../supervise-BUy1cr2L.js";
|
|
5
|
+
import { a as supervisorInstructions } from "../authoring-fsUwd9hg.js";
|
|
6
6
|
//#region src/mcp/delegate-supervisor-provisioning.ts
|
|
7
7
|
function trimmed(value) {
|
|
8
8
|
const v = value?.trim();
|
package/dist/mcp/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { E as SandboxClient, h as LoopSandboxPlacement } from "../types-
|
|
2
|
-
import { $d as
|
|
3
|
-
import { _t as mergeTraceEnv, gt as createPropagatingTraceEmitter, ht as TraceContext, vt as readTraceContextFromEnv, yt as traceContextToEnv } from "../types-
|
|
4
|
-
import { $ as DiffOptions, Gt as JsonRpcMessage, Jt as McpTransport, Kt as JsonRpcResponse, Q as CreateWorktreeOptions, _t as parseCodexTokenUsage, at as createWorktree, ct as CodexExecutionPolicy, dt as LOCAL_HARNESSES, et as DiffResult, ft as LocalHarness, gt as localHarnessExecutable, ht as harnessSupportsReasoningEffort, it as captureWorktreeDiff, lt as CodexTokenUsage, mt as RunLocalHarnessOptions, nt as RemoveWorktreeOptions, ot as removeWorktree, pt as LocalHarnessResult, qt as McpToolDescriptor, rt as WorktreeHandle, st as CodexExecutionEvidence, tt as GitRunner, ut as DEFAULT_LOCAL_HARNESS, vt as runLocalHarness } from "../runtime-
|
|
5
|
-
import { d as ResearchSource, o as UiLens } from "../substrate-
|
|
1
|
+
import { E as SandboxClient, h as LoopSandboxPlacement } from "../types-BdolQ6Zi.js";
|
|
2
|
+
import { $d as detachedTurnEvents, $f as DelegationPersistenceError, $u as QuestionUrgency, Ad as CoderReview, Af as DelegationHistoryResult, Au as AnalystRegistry, Bd as DelegationExecutor, Bf as UiAuditLensFilter, Bu as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Cd as createDelegateHandler, Cf as DelegateUiAuditConfig, Dd as InMemoryFeedbackStore, Df as DelegationFeedbackSnapshot, Ed as FeedbackStore, Ef as DelegationError, Fd as SettleDetachedCoderTurnOptions, Ff as DelegationStatusArgs, Gd as createSiblingSandboxExecutor, Gf as DELEGATION_TRACE_MAX_SPANS, Gu as MakeWorkerAgent, Hd as FleetWorkspaceExecutorOptions, Hf as delegationProfiles, Hu as DownMessageDeliveryAttempt, Id as UiAuditorDelegate, If as DelegationStatusResult, Iu as CoordinationEvent, Jd as DetachedTurnResumeDriverOptions, Jf as DelegationTraceSpan, Ju as QuestionEscalationTarget, Kd as DetachedSessionRefParts, Kf as DelegationTraceCaps, Ku as Question, Ld as coderTaskFromArgs, Lf as FeedbackRating, Md as DelegateRunCtx, Mf as DelegationProgress, Mu as AuthorizeDownMessage, Nd as DetachedSessionDelegateOptions, Nf as DelegationResultPayload, Nu as AuthorizedDownMessage, Od as eventToSnapshot, Of as DelegationHistoryArgs, Ou as AnalystFindingEvent, Pd as DetachedWinnerSelection, Pf as DelegationStatus, Pu as ContinuationInstruction, Qd as createDetachedTurnResumeDriver, Qf as createDelegationTraceCollector, Qu as QuestionRecord, Rd as detachedSessionDelegate, Rf as FeedbackRefersTo, Ru as CoordinationTools, Sd as DelegateResult, Sf as DelegateUiAuditArgs, Td as FeedbackEvent, Tf as DelegateUiAuditRoute, Ud as SiblingSandboxExecutorOptions, Uf as CappedDelegationTrace, Uu as DownMessageDeliveryOutcome, Vd as FleetHandle, Vf as UiAuditorDelegationOutput, Vu as DownMessageAuthorizationInput, Wd as createFleetWorkspaceExecutor, Wf as DELEGATION_TRACE_MAX_BYTES, Wu as DownMessageEvent, Xd as DriveTurnTick, Xf as capDelegationTrace, Xu as QuestionOption, Yd as DriveTurnCapableBox, Yf as buildDelegationTraceSpans, Yu as QuestionLevel, Zd as RunDetachedTurnOptions, Zf as composeLoopTraceEmitters, Zu as QuestionPolicy, _d as DELEGATE_INPUT_SCHEMA, _f as DelegateFeedbackArgs, af as DelegationResumeContext, bd as DelegateError, bf as DelegateResearchConfig, cf as DelegationRunContext, dd as questionEscalationTargets, df as SubmitInput, ed as SettledWorker, ef as formatDetachedSessionRef, ep as DelegationStateCorruptError, fd as McpServer, ff as SubmitOutput, gd as DELEGATE_DESCRIPTION, gf as DelegateCodeResult, hd as createMcpServer, hf as DelegateCodeConfig, if as DelegationRecord, ip as InMemoryDelegationStore, jd as CoderReviewer, jf as DelegationProfile, kd as CoderDelegate, kf as DelegationHistoryEntry, ld as createCoordinationTools, lf as DelegationTaskQueue, md as createInProcessTransport, mf as DelegateCodeArgs, nf as runDetachedTurn, np as FileDelegationStore, od as WorkerSpawnContext, of as DelegationResumeDriver, pd as McpServerOptions, pf as hashIdempotencyInput, qd as DetachedTurn, qf as DelegationTraceCollector, qu as QuestionDecision, rf as DelegationArgs, rp as FileDelegationStoreOptions, sd as WorkerWatchOptions, sf as DelegationResumeTick, tf as parseDetachedSessionRef, tp as DelegationStore, uf as DelegationTaskQueueOptions, vd as DELEGATE_TOOL_NAME, vf as DelegateFeedbackResult, vp as CoderOutput, wd as validateDelegateArgs, wf as DelegateUiAuditResult, xd as DelegateHandlerOptions, xf as DelegateResearchResult, yd as DelegateArgs, yf as DelegateResearchArgs, zd as settleDetachedCoderTurn, zf as ResearchOutputShape, zu as CoordinationToolsOptions } from "../index-DVob1IA1.js";
|
|
3
|
+
import { _t as mergeTraceEnv, gt as createPropagatingTraceEmitter, ht as TraceContext, vt as readTraceContextFromEnv, yt as traceContextToEnv } from "../types-BbkiJR1D.js";
|
|
4
|
+
import { $ as DiffOptions, Gt as JsonRpcMessage, Jt as McpTransport, Kt as JsonRpcResponse, Q as CreateWorktreeOptions, _t as parseCodexTokenUsage, at as createWorktree, ct as CodexExecutionPolicy, dt as LOCAL_HARNESSES, et as DiffResult, ft as LocalHarness, gt as localHarnessExecutable, ht as harnessSupportsReasoningEffort, it as captureWorktreeDiff, lt as CodexTokenUsage, mt as RunLocalHarnessOptions, nt as RemoveWorktreeOptions, ot as removeWorktree, pt as LocalHarnessResult, qt as McpToolDescriptor, rt as WorktreeHandle, st as CodexExecutionEvidence, tt as GitRunner, ut as DEFAULT_LOCAL_HARNESS, vt as runLocalHarness } from "../runtime-EQgE3942.js";
|
|
5
|
+
import { d as ResearchSource, o as UiLens } from "../substrate-qLePHqvH.js";
|
|
6
6
|
import { a as KbGateResult, i as FactJudgeVerdict, n as FactCandidate, o as createKbGate, r as FactJudge, t as CreateKbGateOptions } from "../kb-gate-C8z2juK8.js";
|
|
7
|
-
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-
|
|
7
|
+
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-BDwAdxk5.js";
|
|
8
8
|
import { AgentProfileMcpServer, HarnessType } from "@tangle-network/agent-interface";
|
|
9
9
|
//#region src/mcp/codex-diagnostics.d.ts
|
|
10
10
|
/** Bounded, credential-redacted process context attached when reproducible Codex output fails
|
package/dist/mcp/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { i as ConfigError, m as ValidationError } from "../errors-CDZ8XsVj.js";
|
|
2
|
-
import {
|
|
2
|
+
import { _ as throwIfAborted, g as throwAbort, m as sleep, o as deleteBoxSafe } from "../util-BfoW6RU7.js";
|
|
3
3
|
import { t as assertExecutableAgentProfile } from "../model-policy-Wf2MxXJ9.js";
|
|
4
|
-
import { Cn as LOCAL_HARNESSES, Dn as CodexExecutionDiagnosticError, En as parseCodexTokenUsage, It as createSandboxForSpec, Qt as traceContextToEnv, Sn as DEFAULT_LOCAL_HARNESS, Tn as localHarnessExecutable, Ut as assertBoxlessPromptOptions, Xt as mergeTraceEnv, Yt as createPropagatingTraceEmitter, Zt as readTraceContextFromEnv, bn as createWorktree, vn as runWorktreeHarness, wn as harnessSupportsReasoningEffort, xn as removeWorktree, yn as captureWorktreeDiff, zt as runAgentRounds } from "../supervisor-
|
|
5
|
-
import { E as runCoderChecks, ot as selectValidWinner } from "../runtime-
|
|
6
|
-
import { E as questionEscalationTargets, w as createCoordinationTools, x as DEFAULT_AWAIT_EVENT_TIMEOUT_MS } from "../coordination-driver-
|
|
7
|
-
import { $ as
|
|
4
|
+
import { Cn as LOCAL_HARNESSES, Dn as CodexExecutionDiagnosticError, En as parseCodexTokenUsage, It as createSandboxForSpec, Qt as traceContextToEnv, Sn as DEFAULT_LOCAL_HARNESS, Tn as localHarnessExecutable, Ut as assertBoxlessPromptOptions, Xt as mergeTraceEnv, Yt as createPropagatingTraceEmitter, Zt as readTraceContextFromEnv, bn as createWorktree, vn as runWorktreeHarness, wn as harnessSupportsReasoningEffort, xn as removeWorktree, yn as captureWorktreeDiff, zt as runAgentRounds } from "../supervisor-BSNkaM2a.js";
|
|
5
|
+
import { E as runCoderChecks, ot as selectValidWinner } from "../runtime-DN0SxAaM.js";
|
|
6
|
+
import { E as questionEscalationTargets, w as createCoordinationTools, x as DEFAULT_AWAIT_EVENT_TIMEOUT_MS } from "../coordination-driver-CtbyZv5d.js";
|
|
7
|
+
import { $ as DelegationTaskQueue, A as DELEGATION_HISTORY_DESCRIPTION, B as validateDelegateUiAuditArgs, C as createInProcessTransport, D as DELEGATION_STATUS_TOOL_NAME, E as DELEGATION_STATUS_INPUT_SCHEMA, F as delegationProfiles, G as validateDelegateFeedbackArgs, H as DELEGATE_FEEDBACK_INPUT_SCHEMA, I as DELEGATE_UI_AUDIT_DESCRIPTION, J as DELEGATE_TOOL_NAME, K as DELEGATE_DESCRIPTION, L as DELEGATE_UI_AUDIT_INPUT_SCHEMA, M as DELEGATION_HISTORY_TOOL_NAME, N as createDelegationHistoryHandler, O as createDelegationStatusHandler, P as validateDelegationHistoryArgs, R as DELEGATE_UI_AUDIT_TOOL_NAME, T as DELEGATION_STATUS_DESCRIPTION, U as DELEGATE_FEEDBACK_TOOL_NAME, V as DELEGATE_FEEDBACK_DESCRIPTION, W as createDelegateFeedbackHandler, X as validateDelegateArgs, Y as createDelegateHandler, at as composeLoopTraceEmitters, ct as DelegationStateCorruptError, dt as InMemoryFeedbackStore, et as hashIdempotencyInput, ft as eventToSnapshot, it as capDelegationTrace, j as DELEGATION_HISTORY_INPUT_SCHEMA, k as validateDelegationStatusArgs, lt as FileDelegationStore, nt as DELEGATION_TRACE_MAX_SPANS, ot as createDelegationTraceCollector, q as DELEGATE_INPUT_SCHEMA, rt as buildDelegationTraceSpans, st as DelegationPersistenceError, tt as DELEGATION_TRACE_MAX_BYTES, ut as InMemoryDelegationStore, w as createMcpServer, z as createDelegateUiAuditHandler } from "../supervise-BUy1cr2L.js";
|
|
8
8
|
import { t as createStdioToolServer } from "../tool-server-DEmLr9YY.js";
|
|
9
9
|
import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
|
|
10
|
-
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-
|
|
10
|
+
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-Cz04RKfD.js";
|
|
11
11
|
import { t as coderTaskToPrompt } from "../coder-yhVWbdWc.js";
|
|
12
12
|
import { a as createMemoryToolServer, c as resolveMemoryFromEnv, i as MEMORY_NAME_ENV, n as MEMORY_ITEMS_ENV, o as parseMemoryItems, r as MEMORY_LOG_ENV, s as readMemoryItemsFile, t as MEMORY_FILE_ENV } from "../memory-server-DsKOhzGf.js";
|
|
13
13
|
import { agentProfileSchema } from "@tangle-network/agent-interface";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Q as OpenAIChatTool } from "./types-
|
|
1
|
+
import { Q as OpenAIChatTool } from "./types-BdolQ6Zi.js";
|
|
2
2
|
//#region src/mcp/openai-tools.d.ts
|
|
3
3
|
/**
|
|
4
4
|
*
|
|
@@ -21,4 +21,4 @@ declare function mcpToolsForRuntimeMcp(): OpenAIChatTool[];
|
|
|
21
21
|
declare function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[];
|
|
22
22
|
//#endregion
|
|
23
23
|
export { mcpToolsForRuntimeMcpSubset as n, mcpToolsForRuntimeMcp as t };
|
|
24
|
-
//# sourceMappingURL=openai-tools-
|
|
24
|
+
//# sourceMappingURL=openai-tools-BDwAdxk5.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { A as DELEGATION_HISTORY_DESCRIPTION, D as DELEGATION_STATUS_TOOL_NAME, E as DELEGATION_STATUS_INPUT_SCHEMA, H as DELEGATE_FEEDBACK_INPUT_SCHEMA, M as DELEGATION_HISTORY_TOOL_NAME, T as DELEGATION_STATUS_DESCRIPTION, U as DELEGATE_FEEDBACK_TOOL_NAME, V as DELEGATE_FEEDBACK_DESCRIPTION, j as DELEGATION_HISTORY_INPUT_SCHEMA } from "./supervise-BUy1cr2L.js";
|
|
2
2
|
//#region src/mcp/openai-tools.ts
|
|
3
3
|
function buildTool(name, description, parameters) {
|
|
4
4
|
return {
|
|
@@ -41,4 +41,4 @@ function mcpToolsForRuntimeMcpSubset(names) {
|
|
|
41
41
|
//#endregion
|
|
42
42
|
export { mcpToolsForRuntimeMcpSubset as n, mcpToolsForRuntimeMcp as t };
|
|
43
43
|
|
|
44
|
-
//# sourceMappingURL=openai-tools-
|
|
44
|
+
//# sourceMappingURL=openai-tools-Cz04RKfD.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-tools-
|
|
1
|
+
{"version":3,"file":"openai-tools-Cz04RKfD.js","names":[],"sources":["../src/mcp/openai-tools.ts"],"sourcesContent":["/**\n *\n * OpenAI Chat Completions `tools[]` projection of the queue-bound agent-runtime\n * MCP delegation tools.\n *\n * Use when a caller-owned OpenAI-compatible transport needs the model to call\n * `delegate_feedback`, `delegation_status`, and `delegation_history`. Execution\n * is the caller's responsibility (typically the parent sandbox runtime's MCP\n * mount); Runtime's profile-bound model path materializes profile tools through\n * its executor instead.\n *\n * Sandbox-SDK callers do NOT need this helper: the sandbox runtime mounts\n * MCP servers natively and the in-sandbox harness discovers tools via the\n * runtime, not via an OpenAI tools array.\n *\n * Tool name + description + JSON-schema are pulled from the canonical\n * `DELEGATE_*` constants exported by `./tools/*` so the projection cannot\n * drift from the server's own validators.\n *\n * @experimental\n */\n\nimport type { OpenAIChatTool } from '../types'\nimport {\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\n\nfunction buildTool(\n name: string,\n description: string,\n parameters: Readonly<Record<string, unknown>>,\n): OpenAIChatTool {\n // `parameters` arrives as a deeply-readonly `as const` literal. The\n // OpenAI-compatible transports JSON-serialize the body, so a shallow copy\n // into a plain object is sufficient and shields callers that mutate\n // the returned descriptor from corrupting the source constant.\n return {\n type: 'function',\n function: { name, description, parameters: { ...parameters } },\n }\n}\n\n/**\n *\n * Returns the queue-bound delegation tools projected into OpenAI Chat\n * Completions `tools[]` shape. The order is stable: `delegate_feedback`,\n * `delegation_status`, `delegation_history`.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcp(): OpenAIChatTool[] {\n return [\n buildTool(\n DELEGATE_FEEDBACK_TOOL_NAME,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_STATUS_TOOL_NAME,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_HISTORY_TOOL_NAME,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n ]\n}\n\n/**\n *\n * Subset filter — return only the projected tools whose `function.name`\n * appears in `names`. Useful for curated mounts (e.g. only the queue-bound\n * delegation tools, omitting `delegate_feedback`). Unknown names are\n * silently ignored; pass an empty array to get an empty result.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[] {\n const allowed = new Set(names)\n return mcpToolsForRuntimeMcp().filter((tool) => allowed.has(tool.function.name))\n}\n"],"mappings":";;AAuCA,SAAS,UACP,MACA,aACA,YACgB;CAKhB,OAAO;EACL,MAAM;EACN,UAAU;GAAE;GAAM;GAAa,YAAY,EAAE,GAAG,WAAW;EAAE;CAC/D;AACF;;;;;;;;;AAUA,SAAgB,wBAA0C;CACxD,OAAO;EACL,UACE,6BACA,+BACA,8BACF;EACA,UACE,6BACA,+BACA,8BACF;EACA,UACE,8BACA,gCACA,+BACF;CACF;AACF;;;;;;;;;;AAWA,SAAgB,4BAA4B,OAAgD;CAC1F,MAAM,UAAU,IAAI,IAAI,KAAK;CAC7B,OAAO,sBAAsB,CAAC,CAAC,QAAQ,SAAS,QAAQ,IAAI,KAAK,SAAS,IAAI,CAAC;AACjF"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { x as contentAddress } from "./spawn-journal
|
|
1
|
+
import { x as contentAddress } from "./spawn-journal-CxRa-NJ2.js";
|
|
2
2
|
import { i as redactProtectedValue, n as createProtectedRecordRedactor, r as redactProtectedReason, t as assertNoProtectedBytes } from "./protected-redaction--F3v1oo8.js";
|
|
3
3
|
import { agentCandidateArtifactRefSchema, agentCandidateBenchmarkResultEvidenceSchema, agentCandidateBenchmarkSuiteSchema, agentCandidateBenchmarkTaskSchema, agentCandidateBundleSchema, agentCandidateContainerSchema, agentCandidateExecutionLimitsSchema, agentCandidateExecutionPlanEvidenceSchema, agentCandidateExecutionPlanMaterialSchema, agentCandidateMaterializationReceiptSchema, agentCandidateModelAccessNetworkSchema, agentCandidateModelSettlementEvidenceSchema, agentCandidateProfileActivationSchema, agentCandidateProfilePlanEvidenceSchema, agentCandidateProfileSchema, agentCandidateResolvedModelSchema, agentCandidateRunCellSchema, agentCandidateRunReceiptSchema, agentCandidateTaskOutcomeEvidenceSchema, agentCandidateTaskOutcomeSpecSchema, agentCandidateTerminationSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema, agentProfileDiffSchema, agentProfileSchema, applyAgentProfileDiff, sha256DigestSchema } from "@tangle-network/agent-interface";
|
|
4
4
|
import { REDACTION_VERSION, canonicalJson, isLlmSpan } from "@tangle-network/agent-eval";
|
|
5
5
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
6
|
-
import { isAbsolute, join, posix, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
|
|
7
7
|
import { applyAgentCandidateWorkspacePlan, isMaterializerHarness, materializeCandidateProfile } from "@tangle-network/agent-profile-materialize";
|
|
8
|
-
import { lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rm, stat } from "node:fs/promises";
|
|
8
|
+
import { lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rm, stat } from "node:fs/promises";
|
|
9
9
|
import { constants } from "node:fs";
|
|
10
10
|
import { spawn } from "node:child_process";
|
|
11
11
|
import { tmpdir } from "node:os";
|
|
@@ -910,16 +910,28 @@ async function verifyWorkspaceSnapshotArtifacts(snapshot, port) {
|
|
|
910
910
|
};
|
|
911
911
|
}
|
|
912
912
|
async function verifyMaterializedWorkspace(root, expected, options = {}) {
|
|
913
|
-
assertWorkspaceManifest(
|
|
913
|
+
assertWorkspaceManifest(await scanMaterializedWorkspaceManifest(root, options), expected);
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* The canonical manifest of one materialized workspace, read without holding any file.
|
|
917
|
+
*
|
|
918
|
+
* Every file is digested by streaming, so the size of the largest file does not decide whether the
|
|
919
|
+
* workspace can be described. `FileHandle.readFile` refuses anything above 2 GiB with
|
|
920
|
+
* `ERR_FS_FILE_TOO_LARGE`, which made a workspace holding one such artifact impossible to verify
|
|
921
|
+
* against a manifest it already matched. The digest is sha-256 over the same bytes either way, so
|
|
922
|
+
* a manifest a buffered read produced is reproduced exactly.
|
|
923
|
+
*/
|
|
924
|
+
async function scanMaterializedWorkspaceManifest(root, options = {}) {
|
|
925
|
+
return workspaceManifestFromEntries(await walkWorkspace(root, options, false));
|
|
914
926
|
}
|
|
915
927
|
async function captureMaterializedWorkspace(root, options = {}) {
|
|
916
|
-
const
|
|
928
|
+
const entries = await walkWorkspace(root, options, true);
|
|
917
929
|
return {
|
|
918
|
-
manifest:
|
|
919
|
-
files:
|
|
920
|
-
path:
|
|
921
|
-
mode:
|
|
922
|
-
bytes: Uint8Array.from(
|
|
930
|
+
manifest: workspaceManifestFromEntries(entries),
|
|
931
|
+
files: entries.map((entry) => ({
|
|
932
|
+
path: entry.path,
|
|
933
|
+
mode: entry.mode,
|
|
934
|
+
bytes: Uint8Array.from(capturedBytes(entry))
|
|
923
935
|
}))
|
|
924
936
|
};
|
|
925
937
|
}
|
|
@@ -933,36 +945,65 @@ async function readMaterializedWorkspaceFiles(root, expected, options = {}) {
|
|
|
933
945
|
bytes: Uint8Array.from(file.bytes)
|
|
934
946
|
}));
|
|
935
947
|
}
|
|
936
|
-
function candidateWorkspaceManifest(files) {
|
|
948
|
+
function candidateWorkspaceManifest(files, options = {}) {
|
|
949
|
+
return workspaceManifestFromEntries(files.map((file) => ({
|
|
950
|
+
path: file.path,
|
|
951
|
+
mode: options.portableTree === true ? portableFileMode(file.mode) : file.mode,
|
|
952
|
+
sha256: sha256Bytes(file.bytes),
|
|
953
|
+
byteLength: file.bytes.byteLength
|
|
954
|
+
})));
|
|
955
|
+
}
|
|
956
|
+
function workspaceManifestFromEntries(entries) {
|
|
937
957
|
return {
|
|
938
958
|
kind: "agent-candidate-workspace-manifest",
|
|
939
|
-
files:
|
|
940
|
-
path:
|
|
941
|
-
mode:
|
|
942
|
-
sha256:
|
|
943
|
-
byteLength:
|
|
959
|
+
files: entries.map((entry) => ({
|
|
960
|
+
path: entry.path,
|
|
961
|
+
mode: entry.mode,
|
|
962
|
+
sha256: entry.sha256,
|
|
963
|
+
byteLength: entry.byteLength
|
|
944
964
|
})).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
|
|
945
965
|
};
|
|
946
966
|
}
|
|
967
|
+
/** Git records exactly two file modes, and a portable-tree scan records the same two. */
|
|
968
|
+
function portableFileMode(mode) {
|
|
969
|
+
return (mode & 73) !== 0 ? 493 : 420;
|
|
970
|
+
}
|
|
971
|
+
function capturedBytes(entry) {
|
|
972
|
+
if (!entry.bytes) throw new Error(`workspace file was digested without its bytes: ${entry.path}`);
|
|
973
|
+
return entry.bytes;
|
|
974
|
+
}
|
|
947
975
|
function assertWorkspaceManifest(observed, expected) {
|
|
948
|
-
if (
|
|
976
|
+
if (Buffer.from(canonicalCandidateBytes(observed)).equals(canonicalCandidateBytes(expected))) return;
|
|
977
|
+
if (Buffer.from(canonicalCandidateBytes(withPortableModes(observed))).equals(canonicalCandidateBytes(withPortableModes(expected)))) throw new Error("materialized workspace files do not match the signed manifest: only the file modes differ, so the capture and this verify disagree about portableTree");
|
|
978
|
+
throw new Error("materialized workspace files, modes, or bytes do not match the signed manifest");
|
|
979
|
+
}
|
|
980
|
+
function withPortableModes(material) {
|
|
981
|
+
return {
|
|
982
|
+
...material,
|
|
983
|
+
files: material.files.map((file) => ({
|
|
984
|
+
...file,
|
|
985
|
+
mode: portableFileMode(file.mode)
|
|
986
|
+
}))
|
|
987
|
+
};
|
|
949
988
|
}
|
|
950
989
|
async function verifyMaterializedProfileWorkspace(root, expected) {
|
|
951
|
-
const observedProfile = (await
|
|
990
|
+
const observedProfile = (await scanMaterializedWorkspaceManifest(root)).files.map(({ path, mode, sha256 }) => ({
|
|
952
991
|
relPath: path,
|
|
953
992
|
mode,
|
|
954
993
|
contentSha256: sha256
|
|
955
994
|
}));
|
|
956
995
|
if (!Buffer.from(canonicalCandidateBytes(observedProfile)).equals(canonicalCandidateBytes(expected.files))) throw new Error("profile staging files, modes, or bytes do not match the signed profile plan");
|
|
957
996
|
}
|
|
958
|
-
async function
|
|
997
|
+
async function walkWorkspace(root, options, keepBytes) {
|
|
998
|
+
const ignoredProtectedRootEntries = new Set(options.ignoredProtectedRootEntries ?? []);
|
|
999
|
+
const limits = options.limits;
|
|
959
1000
|
const requestedRoot = resolve(root);
|
|
960
1001
|
const rootStats = await lstat(requestedRoot);
|
|
961
1002
|
if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) throw new Error("workspace root must be a real directory");
|
|
962
1003
|
const absoluteRoot = await realpath(requestedRoot);
|
|
963
1004
|
const resolvedStats = await lstat(absoluteRoot);
|
|
964
1005
|
if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) throw new Error("workspace root must resolve to a real directory");
|
|
965
|
-
const
|
|
1006
|
+
const scanned = [];
|
|
966
1007
|
let totalBytes = 0;
|
|
967
1008
|
async function visit(directory) {
|
|
968
1009
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
@@ -973,28 +1014,30 @@ async function scanWorkspace(root, ignoredProtectedRootEntries, limits) {
|
|
|
973
1014
|
const relPath = relative(absoluteRoot, absolute).split(sep).join("/");
|
|
974
1015
|
if (!relPath || relPath.startsWith("../") || relPath.includes("/../")) throw new Error(`workspace entry escapes root: ${relPath}`);
|
|
975
1016
|
const stats = await lstat(absolute);
|
|
976
|
-
if (stats.isSymbolicLink()) throw new Error(
|
|
1017
|
+
if (stats.isSymbolicLink()) throw new Error(await symlinkRefusal(absolute, relPath, absoluteRoot));
|
|
977
1018
|
if (stats.isDirectory()) {
|
|
978
1019
|
await visit(absolute);
|
|
979
1020
|
continue;
|
|
980
1021
|
}
|
|
981
1022
|
if (!stats.isFile()) throw new Error(`workspace contains a non-regular entry: ${relPath}`);
|
|
982
|
-
if (limits &&
|
|
1023
|
+
if (limits && scanned.length >= limits.maxFiles) throw new Error("workspace exceeds maxFiles");
|
|
983
1024
|
const descriptor = await open(absolute, constants.O_RDONLY | (typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0));
|
|
984
1025
|
try {
|
|
985
1026
|
const openedStats = await descriptor.stat();
|
|
986
1027
|
if (!openedStats.isFile()) throw new Error(`workspace contains a non-regular entry: ${relPath}`);
|
|
987
1028
|
if (openedStats.nlink !== 1) throw new Error(`workspace contains a hard-linked file: ${relPath}`);
|
|
988
|
-
const mode = openedStats.mode & 511;
|
|
1029
|
+
const mode = options.portableTree === true ? portableFileMode(openedStats.mode) : openedStats.mode & 511;
|
|
989
1030
|
if (limits && openedStats.size > limits.maxFileBytes) throw new Error(`workspace file exceeds maxFileBytes: ${relPath}`);
|
|
990
1031
|
const remainingBytes = limits ? limits.maxTotalFileBytes - totalBytes : void 0;
|
|
991
1032
|
if (remainingBytes !== void 0 && openedStats.size > remainingBytes) throw new Error("workspace exceeds maxTotalFileBytes");
|
|
992
|
-
const
|
|
993
|
-
totalBytes +=
|
|
994
|
-
|
|
1033
|
+
const read = await readWorkspaceFile(descriptor, limits ? Math.min(limits.maxFileBytes, remainingBytes ?? limits.maxFileBytes) : void 0, keepBytes, relPath);
|
|
1034
|
+
totalBytes += read.byteLength;
|
|
1035
|
+
scanned.push({
|
|
995
1036
|
path: relPath,
|
|
996
1037
|
mode,
|
|
997
|
-
|
|
1038
|
+
sha256: read.sha256,
|
|
1039
|
+
byteLength: read.byteLength,
|
|
1040
|
+
...read.bytes === void 0 ? {} : { bytes: read.bytes }
|
|
998
1041
|
});
|
|
999
1042
|
} finally {
|
|
1000
1043
|
await descriptor.close();
|
|
@@ -1002,25 +1045,65 @@ async function scanWorkspace(root, ignoredProtectedRootEntries, limits) {
|
|
|
1002
1045
|
}
|
|
1003
1046
|
}
|
|
1004
1047
|
await visit(absoluteRoot);
|
|
1005
|
-
return
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1048
|
+
return scanned;
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* Why one symbolic link is refused, in the terms that separate a portable link from a link that
|
|
1052
|
+
* reaches outside the tree.
|
|
1053
|
+
*
|
|
1054
|
+
* Every link is refused, in both mode policies. `AgentCandidateWorkspaceManifestMaterial` has no
|
|
1055
|
+
* representation for one — `mode`, `sha256` and `byteLength` describe a regular file — so a link
|
|
1056
|
+
* recorded as a file would let two different trees share one digest. The reason says which kind of
|
|
1057
|
+
* link it was, so a caller can tell a link it can rewrite from one it cannot.
|
|
1058
|
+
*/
|
|
1059
|
+
async function symlinkRefusal(absolute, relPath, absoluteRoot) {
|
|
1060
|
+
const target = await readlink(absolute);
|
|
1061
|
+
if (isAbsolute(target)) return `workspace contains an absolute symlink: ${relPath} -> ${target}`;
|
|
1062
|
+
if (!isWithin(absoluteRoot, resolve(dirname(absolute), target))) return `workspace contains a symlink that escapes its tree: ${relPath} -> ${target}`;
|
|
1063
|
+
let physical;
|
|
1064
|
+
try {
|
|
1065
|
+
physical = await realpath(absolute);
|
|
1066
|
+
} catch {
|
|
1067
|
+
return `workspace contains an unresolved symlink: ${relPath} -> ${target}`;
|
|
1068
|
+
}
|
|
1069
|
+
if (!isWithin(absoluteRoot, physical)) return `workspace contains a symlink that resolves outside its tree: ${relPath} -> ${target}`;
|
|
1070
|
+
return `workspace contains a symlink: ${relPath} -> ${target}`;
|
|
1009
1071
|
}
|
|
1010
|
-
|
|
1011
|
-
|
|
1072
|
+
function isWithin(root, path) {
|
|
1073
|
+
return path === root || path.startsWith(`${root}${sep}`);
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* Read one open regular file into its digest, keeping the bytes only when the caller needs them.
|
|
1077
|
+
*
|
|
1078
|
+
* The content reaches the hash in 1 MiB chunks and is never held whole for a digest-only walk, so
|
|
1079
|
+
* the size of the largest file does not decide whether a workspace can be described.
|
|
1080
|
+
* `FileHandle.readFile` refuses anything above 2 GiB with `ERR_FS_FILE_TOO_LARGE`. Hashing the
|
|
1081
|
+
* chunks in order equals hashing the whole buffer, so a manifest a buffered read produced is
|
|
1082
|
+
* reproduced byte for byte.
|
|
1083
|
+
*/
|
|
1084
|
+
async function readWorkspaceFile(descriptor, maxBytes, keepBytes, path) {
|
|
1085
|
+
const hash = createHash("sha256");
|
|
1086
|
+
const buffer = Buffer.allocUnsafe(1024 * 1024);
|
|
1012
1087
|
const chunks = [];
|
|
1013
1088
|
let total = 0;
|
|
1014
1089
|
while (true) {
|
|
1015
|
-
const
|
|
1016
|
-
const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, remaining + 1));
|
|
1017
|
-
const { bytesRead } = await descriptor.read(chunk, 0, chunk.byteLength, null);
|
|
1090
|
+
const { bytesRead } = await descriptor.read(buffer, 0, buffer.byteLength, null);
|
|
1018
1091
|
if (bytesRead === 0) break;
|
|
1019
1092
|
total += bytesRead;
|
|
1020
|
-
if (total > maxBytes) throw new Error(`workspace file exceeds its capture limit: ${path}`);
|
|
1021
|
-
|
|
1093
|
+
if (maxBytes !== void 0 && total > maxBytes) throw new Error(`workspace file exceeds its capture limit: ${path}`);
|
|
1094
|
+
const chunk = buffer.subarray(0, bytesRead);
|
|
1095
|
+
hash.update(chunk);
|
|
1096
|
+
if (keepBytes) chunks.push(Buffer.from(chunk));
|
|
1022
1097
|
}
|
|
1023
|
-
|
|
1098
|
+
const sha256 = `sha256:${hash.digest("hex")}`;
|
|
1099
|
+
return keepBytes ? {
|
|
1100
|
+
sha256,
|
|
1101
|
+
byteLength: total,
|
|
1102
|
+
bytes: Buffer.concat(chunks, total)
|
|
1103
|
+
} : {
|
|
1104
|
+
sha256,
|
|
1105
|
+
byteLength: total
|
|
1106
|
+
};
|
|
1024
1107
|
}
|
|
1025
1108
|
//#endregion
|
|
1026
1109
|
//#region src/candidate-execution/git-materialize.ts
|
|
@@ -4486,4 +4569,4 @@ function errorMessage(error) {
|
|
|
4486
4569
|
//#endregion
|
|
4487
4570
|
export { parseAgentCandidateProfileActivation as $, verifyMaterializedWorkspace as A, rejectedStage as B, assertNoGitIndirection as C, captureMaterializedWorkspace as D, candidateWorkspaceManifest as E, assertTerminalAllowedInPhase as F, isWellFormedUnicode as G, sealTerminalDigest as H, assertTerminalMatchesClaim as I, assertCandidateProfileBinding as J, agentCandidateProfileAsAgentProfile as K, assertTerminalMatchesStaged as L, candidateCleanupTimeout as M, withinCandidateCleanupDeadline as N, readVerifiedArtifact as O, assertRecoveryMatchesStaged as P, omitUndefinedObjectFields as Q, recoveredTerminalRecord as R, CANDIDATE_TRACE_TAGS as S, runCandidateGit as T, terminalRecord as U, requireStagedTerminal as V, assertExactObjectKeys as W, freezeGenericAgentCandidateProfile as X, createAgentCandidateProfileActivation as Y, materializeAgentCandidateProfilePlan as Z, candidateExecutionClaim as _, persistCandidateOutputArtifact as a, canonicalCandidateDocument as at, consumePreparedCandidateExecution as b, CANDIDATE_KNOWLEDGE_ROOT_ENV as c, immutableCandidateValue as ct, verifiedResourceTextByDigest as d, verifyCanonicalCandidateDocument as dt, parseExactAgentProfile as et, verifyAgentCandidateBundle as f, candidateClaimFileInternals as g, InMemoryAgentCandidateExecutionClaimStore as h, persistCandidateModelSettlementEvidence as i, canonicalCandidateDigest$1 as it, candidateCleanupDeadline as j, verifyBytes as k, candidateKnowledgeExecutionPaths as l, omitTopLevelDigest as lt, usdToNanos as m, executePreparedAgentCandidate as n, parseExactCandidateProfile as nt, sealAgentCandidateExecutorStopAcknowledgement as o, deepFreezeCandidate as ot, sealAgentCandidateModelSettlement as p, applyExactAgentProfileDiff as q, RecoveryAgentCandidateTraceStore as r, canonicalCandidateBytes as rt, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV as s, embeddedCandidateArtifact as st, prepareAgentCandidateExecution as t, parseExactAgentProfileDiff as tt, AGENT_CANDIDATE_EXECUTION_SUPPORT as u, sha256Bytes as ut, assertPreparedCandidateIntegrity as v, readCandidateGitTreeFiles as w, CANDIDATE_TRACE_ENV as x, beginPreparedCandidateDisposal as y, rejectedFinish as z };
|
|
4488
4571
|
|
|
4489
|
-
//# sourceMappingURL=prepare-
|
|
4572
|
+
//# sourceMappingURL=prepare-BpIGs5Tc.js.map
|