@tangle-network/agent-runtime 0.103.1 → 0.105.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 (89) hide show
  1. package/README.md +177 -39
  2. package/dist/agent.d.ts +1 -1
  3. package/dist/agent.js +5 -5
  4. package/dist/analyst-loop.d.ts +1 -1
  5. package/dist/candidate-execution/index.d.ts +2 -2
  6. package/dist/candidate-execution/index.js +4 -4
  7. package/dist/{chunk-TUSOOIDV.js → chunk-C5RTIBNZ.js} +2 -2
  8. package/dist/{chunk-SNSMRT6H.js → chunk-CTRA64LY.js} +3 -3
  9. package/dist/{chunk-ZXICDSAK.js → chunk-H5QPIZNX.js} +2 -2
  10. package/dist/{chunk-6WZZXQV5.js → chunk-HLKC4UYB.js} +1 -13
  11. package/dist/chunk-HLKC4UYB.js.map +1 -0
  12. package/dist/{chunk-AAN2MB2X.js → chunk-HNP72PNU.js} +3 -10
  13. package/dist/chunk-HNP72PNU.js.map +1 -0
  14. package/dist/{chunk-M6MD6JBS.js → chunk-KRBFHMV6.js} +429 -1
  15. package/dist/chunk-KRBFHMV6.js.map +1 -0
  16. package/dist/chunk-OPVWXJ2H.js +75 -0
  17. package/dist/chunk-OPVWXJ2H.js.map +1 -0
  18. package/dist/{chunk-AYU35OTU.js → chunk-PZZKQVQV.js} +1 -1
  19. package/dist/chunk-PZZKQVQV.js.map +1 -0
  20. package/dist/{chunk-B7K7V22Y.js → chunk-RDOAVVHY.js} +2 -2
  21. package/dist/{chunk-L5DST3QC.js → chunk-SMQXZGLZ.js} +1 -1
  22. package/dist/chunk-SMQXZGLZ.js.map +1 -0
  23. package/dist/{chunk-LFM4JBRW.js → chunk-UHEZW5BU.js} +1084 -527
  24. package/dist/chunk-UHEZW5BU.js.map +1 -0
  25. package/dist/{chunk-5AITUUHO.js → chunk-VISA6CI3.js} +3 -3
  26. package/dist/{chunk-ZOYN3JR5.js → chunk-WMTCUOQL.js} +5 -5
  27. package/dist/{chunk-3LJF5XSE.js → chunk-WRTOVNN4.js} +6 -6
  28. package/dist/chunk-WRTOVNN4.js.map +1 -0
  29. package/dist/{chunk-SBTWKPVR.js → chunk-WSTRQZYQ.js} +1 -1
  30. package/dist/chunk-WSTRQZYQ.js.map +1 -0
  31. package/dist/{chunk-EAQ5YRRY.js → chunk-XBG2W2VW.js} +50 -23
  32. package/dist/chunk-XBG2W2VW.js.map +1 -0
  33. package/dist/{chunk-QYCKIV6C.js → chunk-YJZA2BIK.js} +2 -2
  34. package/dist/{chunk-QYCKIV6C.js.map → chunk-YJZA2BIK.js.map} +1 -1
  35. package/dist/{completion-gate-DLINnrkM.d.ts → completion-gate-BMy5LGoP.d.ts} +3 -3
  36. package/dist/{coordination-DTehA977.d.ts → coordination-BZZSVYpZ.d.ts} +28 -28
  37. package/dist/environment-provider.d.ts +18 -7
  38. package/dist/environment-provider.js +3 -1
  39. package/dist/index.d.ts +106 -182
  40. package/dist/index.js +374 -236
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +93 -47
  43. package/dist/intelligence.js +127 -73
  44. package/dist/intelligence.js.map +1 -1
  45. package/dist/knowledge.d.ts +6 -6
  46. package/dist/knowledge.js +9 -9
  47. package/dist/{local-harness-CtK9dSny.d.ts → local-harness-BDNcl6jI.d.ts} +1 -1
  48. package/dist/{loop-runner-bin-DhIXsLAd.d.ts → loop-runner-bin-68aoM9-7.d.ts} +5 -13
  49. package/dist/loop-runner-bin.d.ts +6 -8
  50. package/dist/loop-runner-bin.js +6 -6
  51. package/dist/loops.d.ts +67 -42
  52. package/dist/loops.js +10 -6
  53. package/dist/mcp/bin.js +4 -4
  54. package/dist/mcp/index.d.ts +9 -10
  55. package/dist/mcp/index.js +11 -11
  56. package/dist/mcp/index.js.map +1 -1
  57. package/dist/mcp/memory-bin.js +1 -1
  58. package/dist/primeintellect/index.d.ts +3 -4
  59. package/dist/primeintellect/index.js +5 -6
  60. package/dist/primeintellect/index.js.map +1 -1
  61. package/dist/profiles.d.ts +6 -6
  62. package/dist/profiles.js.map +1 -1
  63. package/dist/{protected-model-port-DzkUY3HQ.d.ts → protected-model-port-B4t-OQjL.d.ts} +1 -1
  64. package/dist/{improve-B40dRu0X.d.ts → redact-BuFjxBUJ.d.ts} +201 -154
  65. package/dist/{structural-rollout-BFPIy3iw.d.ts → structural-rollout-DEh6CEsa.d.ts} +4 -4
  66. package/dist/{supervise-Cp8bNcJi.d.ts → supervise-4_48wwvy.d.ts} +3 -3
  67. package/dist/testing.js +9 -9
  68. package/dist/testing.js.map +1 -1
  69. package/dist/{types-DK11_O4L.d.ts → types-BCoemcXU.d.ts} +4 -4
  70. package/dist/{types-lZTE_LBd.d.ts → types-CvNwMzQt.d.ts} +4 -4
  71. package/dist/{worktree-fanout-DiiJWjJO.d.ts → worktree-fanout-DxhAWr5Z.d.ts} +6 -6
  72. package/package.json +8 -7
  73. package/skills/build-with-agent-runtime/SKILL.md +15 -9
  74. package/skills/loop-writer/SKILL.md +1 -1
  75. package/dist/chunk-3LJF5XSE.js.map +0 -1
  76. package/dist/chunk-6WZZXQV5.js.map +0 -1
  77. package/dist/chunk-AAN2MB2X.js.map +0 -1
  78. package/dist/chunk-AYU35OTU.js.map +0 -1
  79. package/dist/chunk-EAQ5YRRY.js.map +0 -1
  80. package/dist/chunk-L5DST3QC.js.map +0 -1
  81. package/dist/chunk-LFM4JBRW.js.map +0 -1
  82. package/dist/chunk-M6MD6JBS.js.map +0 -1
  83. package/dist/chunk-SBTWKPVR.js.map +0 -1
  84. /package/dist/{chunk-TUSOOIDV.js.map → chunk-C5RTIBNZ.js.map} +0 -0
  85. /package/dist/{chunk-SNSMRT6H.js.map → chunk-CTRA64LY.js.map} +0 -0
  86. /package/dist/{chunk-ZXICDSAK.js.map → chunk-H5QPIZNX.js.map} +0 -0
  87. /package/dist/{chunk-B7K7V22Y.js.map → chunk-RDOAVVHY.js.map} +0 -0
  88. /package/dist/{chunk-5AITUUHO.js.map → chunk-VISA6CI3.js.map} +0 -0
  89. /package/dist/{chunk-ZOYN3JR5.js.map → chunk-WMTCUOQL.js.map} +0 -0
@@ -5,10 +5,10 @@ import {
5
5
  definePersona,
6
6
  runPersonified,
7
7
  worktreeFanout
8
- } from "./chunk-3LJF5XSE.js";
8
+ } from "./chunk-WRTOVNN4.js";
9
9
  import {
10
10
  createExecutorRegistry
11
- } from "./chunk-EAQ5YRRY.js";
11
+ } from "./chunk-XBG2W2VW.js";
12
12
  import {
13
13
  runAnalystLoop
14
14
  } from "./chunk-FD2MBMOH.js";
@@ -17,9 +17,6 @@ import {
17
17
  } from "./chunk-YEJR7IXO.js";
18
18
 
19
19
  // src/loop-runner.ts
20
- import {
21
- selfImprove
22
- } from "@tangle-network/agent-eval/contract";
23
20
  var DELEGATED_LOOP_MODES = ["code", "review", "research", "audit", "self-improve"];
24
21
  function isDelegatedLoopMode(value) {
25
22
  return typeof value === "string" && DELEGATED_LOOP_MODES.includes(value);
@@ -106,9 +103,6 @@ function researchLoopRunner(o) {
106
103
  return { accepted, vetoed, rounds };
107
104
  };
108
105
  }
109
- function selfImproveLoopRunner(options) {
110
- return async () => selfImprove(options);
111
- }
112
106
  function auditLoopRunner(options) {
113
107
  return async () => runAnalystLoop(options);
114
108
  }
@@ -191,9 +185,8 @@ export {
191
185
  runDelegatedLoop,
192
186
  worktreeLoopRunner,
193
187
  researchLoopRunner,
194
- selfImproveLoopRunner,
195
188
  auditLoopRunner,
196
189
  runLoopRunnerCli,
197
190
  parseLoopRunnerArgv
198
191
  };
199
- //# sourceMappingURL=chunk-AAN2MB2X.js.map
192
+ //# sourceMappingURL=chunk-HNP72PNU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"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 { 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 /** 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: { name: 'worktree-coder' }, 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":";;;;;;;;;;;;;;;;;;;AAwCO,IAAM,uBAAuB,CAAC,QAAQ,UAAU,YAAY,SAAS,cAAc;AAMnF,SAAS,oBAAoB,OAA4C;AAC9E,SAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;AAoCA,eAA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A,CAAI;AACpD,UAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,IAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,CAAC,IAAI;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GAAG;AACxE,OAAK,KAAK;AACZ;","names":[]}
@@ -2,6 +2,433 @@ import {
2
2
  zeroTokenUsage
3
3
  } from "./chunk-3MDZX7YU.js";
4
4
 
5
+ // src/runtime/tangle-sandbox-exact-process-provider.ts
6
+ import { isDeepStrictEqual } from "util";
7
+ var exactProcessProviderMarker = "agent-runtime.exact-process-provider";
8
+ var exactProcessEgressMarker = "agent-runtime.exact-process-egress";
9
+ function createTangleSandboxExactProcessProvider(client, options = {}) {
10
+ const name = options.name ?? "tangle-sandbox-exact-process";
11
+ if (!name.trim()) throw new Error("Tangle Sandbox exact-process provider name must not be empty");
12
+ const exactProcess = {
13
+ async create(input) {
14
+ throwIfAborted(input.signal);
15
+ assertNoProviderOptions(input.providerOptions);
16
+ const egressPolicy = sandboxEgressPolicy(input.egress);
17
+ const metadata = exactMetadata(input.metadata, name, egressPolicy);
18
+ const sandbox = await client.create(
19
+ {
20
+ image: requiredText(input.image, "exact-process image"),
21
+ agent: false,
22
+ bare: false,
23
+ publicEdge: false,
24
+ ephemeral: true,
25
+ egressPolicy,
26
+ resources: sandboxResources(input),
27
+ maxLifetimeSeconds: sandboxLifetimeSeconds(input.maxLifetimeMs),
28
+ metadata,
29
+ idempotencyKey: requiredText(input.idempotencyKey, "exact-process idempotency key")
30
+ },
31
+ {
32
+ ...input.provisionTimeoutMs === void 0 ? {} : { timeoutMs: positiveInteger(input.provisionTimeoutMs, "provision timeout") },
33
+ ...input.signal === void 0 ? {} : { signal: input.signal }
34
+ }
35
+ );
36
+ try {
37
+ throwIfAborted(input.signal);
38
+ assertExactSandboxMetadata(sandbox, metadata);
39
+ await assertExactSandboxEgress(sandbox, egressPolicy);
40
+ } catch (error) {
41
+ await discardInvalidSandbox(sandbox, error);
42
+ }
43
+ return sandboxAsExactProcessEnvironment(sandbox, name);
44
+ },
45
+ async get(id) {
46
+ const sandbox = await client.get(id);
47
+ if (!sandbox || !isExactSandbox(sandbox, name)) return null;
48
+ await assertExactSandboxEgress(sandbox, egressFromMetadata(sandbox.metadata));
49
+ return sandboxAsExactProcessEnvironment(sandbox, name);
50
+ },
51
+ async list(query) {
52
+ assertNoProviderOptions(query?.providerOptions);
53
+ const sandboxes = await client.list();
54
+ return Promise.all(
55
+ sandboxes.filter((sandbox) => isExactSandbox(sandbox, name)).filter((sandbox) => metadataMatches(sandbox.metadata, query?.metadata)).map(async (sandbox) => {
56
+ await assertExactSandboxEgress(sandbox, egressFromMetadata(sandbox.metadata));
57
+ return sandboxAsExactProcessEnvironment(sandbox, name);
58
+ })
59
+ );
60
+ }
61
+ };
62
+ return {
63
+ name,
64
+ exactProcess,
65
+ capabilities: exactProcessOnlyCapabilities,
66
+ async create() {
67
+ throw new Error(`agent environment provider "${name}" supports exactProcess.create() only`);
68
+ }
69
+ };
70
+ }
71
+ function sandboxAsExactProcessEnvironment(sandbox, provider) {
72
+ return {
73
+ id: requiredText(sandbox.id, "Sandbox id"),
74
+ provider,
75
+ ...sandbox.metadata ? { metadata: sandbox.metadata } : {},
76
+ process: {
77
+ async list() {
78
+ return (await sandbox.process.list()).map((status) => exactProcessStatus(status));
79
+ },
80
+ async get(pid) {
81
+ const process = await sandbox.process.get(pid);
82
+ return process ? sandboxProcessAsExactProcess(process) : null;
83
+ },
84
+ async spawn(input, options) {
85
+ const process = await afterAbortCheck(
86
+ options?.signal,
87
+ () => sandbox.process.spawnExact(input.executable, [...input.args], {
88
+ cwd: input.cwd,
89
+ env: { ...input.env },
90
+ inheritEnv: false,
91
+ ...input.stdin === void 0 ? {} : { stdin: input.stdin },
92
+ timeoutMs: input.timeoutMs
93
+ })
94
+ );
95
+ return sandboxProcessAsExactProcess(process);
96
+ }
97
+ },
98
+ async writeFile(path, bytes, options) {
99
+ if (sandbox.fs.supportsWriteMode !== true) {
100
+ throw new Error("Tangle Sandbox does not declare exact file-mode support");
101
+ }
102
+ await afterAbortCheck(
103
+ options.signal,
104
+ () => sandbox.fs.write(path, Buffer.from(bytes).toString("base64"), {
105
+ encoding: "base64",
106
+ mode: fileMode(options.mode)
107
+ })
108
+ );
109
+ },
110
+ async readFile(path, options) {
111
+ const maxBytes = nonnegativeInteger(options.maxBytes, "exact-process file read maximum");
112
+ const initialSize = nonnegativeInteger(
113
+ (await afterAbortCheck(options.signal, () => sandbox.fs.stat(path))).size,
114
+ `Tangle Sandbox file size for "${path}"`
115
+ );
116
+ if (initialSize > maxBytes) {
117
+ throw new Error(
118
+ `Tangle Sandbox file "${path}" exceeds the ${maxBytes}-byte exact read maximum`
119
+ );
120
+ }
121
+ const result = await afterAbortCheck(
122
+ options.signal,
123
+ () => sandbox.fs.readBatch([path], { encoding: "base64" })
124
+ );
125
+ const failure = result.errors.find((entry) => entry.path === path);
126
+ if (failure) {
127
+ throw new Error(`Tangle Sandbox failed to read "${path}": ${failure.error}`);
128
+ }
129
+ const files = result.files.filter((entry) => entry.path === path);
130
+ if (files.length !== 1) {
131
+ throw new Error(`Tangle Sandbox returned ${files.length} files for exact read "${path}"`);
132
+ }
133
+ const file = files[0];
134
+ if (file.encoding !== "base64") {
135
+ throw new Error(`Tangle Sandbox returned non-binary content for exact read "${path}"`);
136
+ }
137
+ const size = nonnegativeInteger(file.size, `Tangle Sandbox file size for "${path}"`);
138
+ if (size !== initialSize) {
139
+ throw new Error(`Tangle Sandbox file "${path}" changed during exact read`);
140
+ }
141
+ if (size > maxBytes) {
142
+ throw new Error(
143
+ `Tangle Sandbox file "${path}" exceeds the ${maxBytes}-byte exact read maximum`
144
+ );
145
+ }
146
+ const bytes = Buffer.from(file.content, "base64");
147
+ if (bytes.byteLength !== size || bytes.toString("base64") !== file.content) {
148
+ throw new Error(
149
+ `Tangle Sandbox returned an invalid binary payload for exact read "${path}"`
150
+ );
151
+ }
152
+ return Uint8Array.from(bytes);
153
+ },
154
+ async destroy() {
155
+ await sandbox.delete();
156
+ }
157
+ };
158
+ }
159
+ function sandboxProcessAsExactProcess(process) {
160
+ const pid = positiveInteger(process.pid, "Tangle Sandbox process pid");
161
+ return {
162
+ pid,
163
+ async status() {
164
+ return exactProcessStatus(await process.status(), pid);
165
+ },
166
+ async wait() {
167
+ const waitExitCode = await process.wait();
168
+ if (!Number.isSafeInteger(waitExitCode)) {
169
+ throw new Error("Tangle Sandbox process wait returned an invalid exit code");
170
+ }
171
+ const status = exactProcessStatus(await process.status(), pid);
172
+ if (status.running || !status.termination) {
173
+ throw new Error("Tangle Sandbox process wait returned before terminal status");
174
+ }
175
+ if (status.termination.kind === "exit" && status.termination.exitCode !== waitExitCode) {
176
+ throw new Error("Tangle Sandbox process wait and status disagree on exit code");
177
+ }
178
+ return status.termination;
179
+ },
180
+ async kill() {
181
+ await process.kill("SIGKILL", { tree: true });
182
+ },
183
+ async *stdout() {
184
+ yield* process.stdout();
185
+ },
186
+ async *stderr() {
187
+ yield* process.stderr();
188
+ }
189
+ };
190
+ }
191
+ function exactProcessStatus(status, expectedPid) {
192
+ const pid = positiveInteger(status.pid, "Tangle Sandbox process pid");
193
+ if (expectedPid !== void 0 && pid !== expectedPid) {
194
+ throw new Error("Tangle Sandbox process status changed process identity");
195
+ }
196
+ if (typeof status.running !== "boolean") {
197
+ throw new Error("Tangle Sandbox process status is missing running state");
198
+ }
199
+ if (!Number.isSafeInteger(status.exitCode)) {
200
+ throw new Error("Tangle Sandbox process status is missing an integer exit code");
201
+ }
202
+ const exitSignal = optionalText(status.exitSignal, "Tangle Sandbox process exit signal");
203
+ if (status.running) {
204
+ if (status.exitCode !== -1) {
205
+ throw new Error("Tangle Sandbox running process must report exit code -1");
206
+ }
207
+ if (exitSignal) {
208
+ throw new Error("Tangle Sandbox running process must not report an exit signal");
209
+ }
210
+ return {
211
+ pid,
212
+ running: true,
213
+ exitCode: -1
214
+ };
215
+ }
216
+ const termination = exitSignal ? { kind: "signal", signal: exitSignal } : status.exitCode >= 0 ? { kind: "exit", exitCode: status.exitCode } : void 0;
217
+ if (!termination) {
218
+ throw new Error("Tangle Sandbox stopped process has no terminal reason");
219
+ }
220
+ return {
221
+ pid,
222
+ running: false,
223
+ exitCode: status.exitCode,
224
+ ...exitSignal ? { exitSignal } : {},
225
+ termination
226
+ };
227
+ }
228
+ function exactMetadata(metadata, provider, egressPolicy) {
229
+ for (const marker of [exactProcessProviderMarker, exactProcessEgressMarker]) {
230
+ if (Object.hasOwn(metadata, marker)) {
231
+ throw new Error(`exact-process metadata must not set "${marker}"`);
232
+ }
233
+ }
234
+ return {
235
+ ...metadata,
236
+ [exactProcessProviderMarker]: provider,
237
+ [exactProcessEgressMarker]: serializeEgressPolicy(egressPolicy)
238
+ };
239
+ }
240
+ function isExactSandbox(sandbox, provider) {
241
+ return sandbox.metadata?.[exactProcessProviderMarker] === provider;
242
+ }
243
+ function metadataMatches(metadata, expected) {
244
+ return expected === void 0 || Object.entries(expected).every(([key, value]) => isDeepStrictEqual(metadata?.[key], value));
245
+ }
246
+ function assertExactSandboxMetadata(sandbox, expected) {
247
+ if (!metadataMatches(sandbox.metadata, expected)) {
248
+ throw new Error("Tangle Sandbox did not persist exact-process metadata");
249
+ }
250
+ }
251
+ function egressFromMetadata(metadata) {
252
+ const encoded = metadata?.[exactProcessEgressMarker];
253
+ if (typeof encoded !== "string") {
254
+ throw new Error("Tangle Sandbox exact-process environment is missing egress metadata");
255
+ }
256
+ try {
257
+ const parsed = JSON.parse(encoded);
258
+ if (!parsed || typeof parsed !== "object") throw new Error("expected egress object");
259
+ const policy = parsed;
260
+ if (policy.mode === "blocked" && policy.allowDomains === void 0) return { mode: "blocked" };
261
+ if (policy.mode === "strict" && policy.includeImplicitDomains === false && Array.isArray(policy.allowDomains) && policy.allowDomains.every((domain) => typeof domain === "string")) {
262
+ const allowDomains = sortedDomains(policy.allowDomains);
263
+ if (new Set(allowDomains).size === allowDomains.length) {
264
+ return { mode: "strict", allowDomains, includeImplicitDomains: false };
265
+ }
266
+ }
267
+ } catch {
268
+ throw new Error("Tangle Sandbox exact-process environment has invalid egress metadata");
269
+ }
270
+ throw new Error("Tangle Sandbox exact-process environment has invalid egress metadata");
271
+ }
272
+ async function assertExactSandboxEgress(sandbox, expected) {
273
+ const actual = (await sandbox.egress.get()).policy;
274
+ if (actual.mode !== expected.mode) {
275
+ throw new Error(
276
+ `Tangle Sandbox egress mismatch: expected ${expected.mode}, received ${actual.mode}`
277
+ );
278
+ }
279
+ if (expected.mode === "blocked") {
280
+ const allowDomains = actual.allowDomains;
281
+ if (actual.mode === "blocked" && (allowDomains === void 0 || Array.isArray(allowDomains) && allowDomains.length === 0)) {
282
+ return;
283
+ }
284
+ throw new Error("Tangle Sandbox blocked egress retained an allowlist");
285
+ }
286
+ if (actual.mode !== "strict") {
287
+ throw new Error("Tangle Sandbox did not return strict egress policy");
288
+ }
289
+ const expectedDomains = sortedDomains(expected.allowDomains);
290
+ const actualDomains = sortedDomains(actual.allowDomains ?? []);
291
+ if (!isDeepStrictEqual(actualDomains, expectedDomains)) {
292
+ throw new Error("Tangle Sandbox strict egress differs from the exact allowlist");
293
+ }
294
+ if (actual.includeImplicitDomains !== false) {
295
+ throw new Error("Tangle Sandbox strict egress retained implicit domains");
296
+ }
297
+ }
298
+ function sandboxEgressPolicy(input) {
299
+ if (input.mode === "blocked") return { mode: "blocked" };
300
+ const allowDomains = input.allowDomains.map(
301
+ (domain) => requiredText(domain, "strict egress domain")
302
+ );
303
+ if (new Set(allowDomains).size !== allowDomains.length) {
304
+ throw new Error("strict egress domains must not contain duplicates");
305
+ }
306
+ return { mode: "strict", allowDomains, includeImplicitDomains: false };
307
+ }
308
+ function serializeEgressPolicy(policy) {
309
+ return JSON.stringify(
310
+ policy.mode === "blocked" ? { mode: "blocked" } : {
311
+ mode: "strict",
312
+ allowDomains: sortedDomains(policy.allowDomains),
313
+ includeImplicitDomains: false
314
+ }
315
+ );
316
+ }
317
+ function sandboxResources(input) {
318
+ const cpuCores = positiveNumber(input.resources.cpu, "exact-process cpu");
319
+ const memoryMB = positiveInteger(input.resources.memoryMb, "exact-process memory");
320
+ const diskMb = positiveInteger(input.resources.diskMb, "exact-process disk");
321
+ if (diskMb % 1024 !== 0) {
322
+ throw new Error("Tangle Sandbox exact-process disk must be a whole GiB");
323
+ }
324
+ return { cpuCores, memoryMB, diskGB: diskMb / 1024 };
325
+ }
326
+ function sandboxLifetimeSeconds(maxLifetimeMs) {
327
+ const milliseconds = positiveInteger(maxLifetimeMs, "exact-process maximum lifetime");
328
+ if (milliseconds % 1e3 !== 0) {
329
+ throw new Error(
330
+ "Tangle Sandbox exact-process maximum lifetime must be a whole number of seconds"
331
+ );
332
+ }
333
+ return milliseconds / 1e3;
334
+ }
335
+ function fileMode(value) {
336
+ const mode = nonnegativeInteger(value, "exact-process file mode");
337
+ if (mode > 4095) throw new Error("exact-process file mode exceeds POSIX mode bits");
338
+ return mode;
339
+ }
340
+ function assertNoProviderOptions(providerOptions) {
341
+ if (providerOptions && Object.keys(providerOptions).length > 0) {
342
+ throw new Error("Tangle Sandbox exact-process provider does not accept providerOptions");
343
+ }
344
+ }
345
+ function exactProcessOnlyCapabilities() {
346
+ return {
347
+ profile: {
348
+ namedProfiles: false,
349
+ systemPrompt: false,
350
+ instructions: false,
351
+ tools: false,
352
+ permissions: false,
353
+ mcp: false,
354
+ subagents: false,
355
+ resources: {
356
+ files: false,
357
+ instructions: false,
358
+ tools: false,
359
+ skills: false,
360
+ agents: false,
361
+ commands: false
362
+ },
363
+ hooks: false,
364
+ modes: false,
365
+ runtimeUpdate: false,
366
+ validation: false
367
+ },
368
+ streaming: { live: false, replay: false, detach: false, turnIdempotency: false },
369
+ sessions: { continue: false, list: false, messages: false },
370
+ workspace: {
371
+ read: false,
372
+ write: false,
373
+ exec: false,
374
+ git: false,
375
+ upload: false,
376
+ download: false
377
+ },
378
+ branching: { checkpoint: false, fork: false },
379
+ placement: false,
380
+ usage: false,
381
+ confidential: false,
382
+ exactProcess: { egress: ["blocked", "strict"] }
383
+ };
384
+ }
385
+ async function discardInvalidSandbox(sandbox, cause) {
386
+ try {
387
+ await sandbox.delete();
388
+ } catch (destroyError) {
389
+ throw new AggregateError(
390
+ [cause, destroyError],
391
+ "Tangle Sandbox exact-process creation failed and cleanup failed"
392
+ );
393
+ }
394
+ throw cause;
395
+ }
396
+ function sortedDomains(domains) {
397
+ return [...domains].sort((left, right) => left.localeCompare(right));
398
+ }
399
+ function requiredText(value, label) {
400
+ if (typeof value !== "string" || !value.trim())
401
+ throw new Error(`${label} must be a non-empty string`);
402
+ return value;
403
+ }
404
+ function optionalText(value, label) {
405
+ if (value === void 0) return void 0;
406
+ return requiredText(value, label);
407
+ }
408
+ function positiveNumber(value, label) {
409
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`${label} must be positive`);
410
+ return value;
411
+ }
412
+ function positiveInteger(value, label) {
413
+ if (!Number.isSafeInteger(value) || value < 1)
414
+ throw new Error(`${label} must be a positive integer`);
415
+ return value;
416
+ }
417
+ function nonnegativeInteger(value, label) {
418
+ if (!Number.isSafeInteger(value) || value < 0)
419
+ throw new Error(`${label} must be a non-negative integer`);
420
+ return value;
421
+ }
422
+ function throwIfAborted(signal) {
423
+ signal?.throwIfAborted();
424
+ }
425
+ async function afterAbortCheck(signal, operation) {
426
+ throwIfAborted(signal);
427
+ const result = await operation();
428
+ throwIfAborted(signal);
429
+ return result;
430
+ }
431
+
5
432
  // src/runtime/environment-provider.ts
6
433
  var ValidationError = class extends Error {
7
434
  constructor(message, options) {
@@ -791,10 +1218,11 @@ function hasExec(box) {
791
1218
  }
792
1219
 
793
1220
  export {
1221
+ createTangleSandboxExactProcessProvider,
794
1222
  createAgentEnvironmentProviderRegistry,
795
1223
  resolveAgentEnvironmentProvider,
796
1224
  providerAsSandboxClient,
797
1225
  sandboxClientAsProvider,
798
1226
  providerAsExecutor
799
1227
  };
800
- //# sourceMappingURL=chunk-M6MD6JBS.js.map
1228
+ //# sourceMappingURL=chunk-KRBFHMV6.js.map