@tangle-network/agent-runtime 0.104.0 → 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 (73) hide show
  1. package/README.md +176 -42
  2. package/dist/agent.js +4 -4
  3. package/dist/candidate-execution/index.d.ts +2 -2
  4. package/dist/candidate-execution/index.js +4 -4
  5. package/dist/{chunk-2QJSNOGK.js → chunk-C5RTIBNZ.js} +2 -2
  6. package/dist/{chunk-SNSMRT6H.js → chunk-CTRA64LY.js} +3 -3
  7. package/dist/{chunk-ZXICDSAK.js → chunk-H5QPIZNX.js} +2 -2
  8. package/dist/{chunk-2X65HYMI.js → chunk-HLKC4UYB.js} +1 -13
  9. package/dist/chunk-HLKC4UYB.js.map +1 -0
  10. package/dist/{chunk-3PPVCS75.js → chunk-HNP72PNU.js} +3 -10
  11. package/dist/chunk-HNP72PNU.js.map +1 -0
  12. package/dist/chunk-OPVWXJ2H.js +75 -0
  13. package/dist/chunk-OPVWXJ2H.js.map +1 -0
  14. package/dist/{chunk-B7K7V22Y.js → chunk-RDOAVVHY.js} +2 -2
  15. package/dist/{chunk-L5DST3QC.js → chunk-SMQXZGLZ.js} +1 -1
  16. package/dist/chunk-SMQXZGLZ.js.map +1 -0
  17. package/dist/{chunk-FJI3EXU3.js → chunk-UHEZW5BU.js} +1104 -588
  18. package/dist/chunk-UHEZW5BU.js.map +1 -0
  19. package/dist/{chunk-HAO4CXHP.js → chunk-VISA6CI3.js} +3 -3
  20. package/dist/{chunk-2UABGGUB.js → chunk-WMTCUOQL.js} +5 -5
  21. package/dist/{chunk-ATDFUJYI.js → chunk-WRTOVNN4.js} +4 -4
  22. package/dist/{chunk-ATDFUJYI.js.map → chunk-WRTOVNN4.js.map} +1 -1
  23. package/dist/{chunk-SBTWKPVR.js → chunk-WSTRQZYQ.js} +1 -1
  24. package/dist/chunk-WSTRQZYQ.js.map +1 -0
  25. package/dist/{chunk-5HNDYWUT.js → chunk-XBG2W2VW.js} +13 -3
  26. package/dist/chunk-XBG2W2VW.js.map +1 -0
  27. package/dist/{chunk-STJEHM5F.js → chunk-YJZA2BIK.js} +2 -2
  28. package/dist/{chunk-STJEHM5F.js.map → chunk-YJZA2BIK.js.map} +1 -1
  29. package/dist/{completion-gate-Bv47cOnn.d.ts → completion-gate-BMy5LGoP.d.ts} +1 -1
  30. package/dist/{coordination-CxtzMxSM.d.ts → coordination-BZZSVYpZ.d.ts} +2 -2
  31. package/dist/index.d.ts +101 -177
  32. package/dist/index.js +373 -235
  33. package/dist/index.js.map +1 -1
  34. package/dist/intelligence.d.ts +49 -40
  35. package/dist/intelligence.js +14 -57
  36. package/dist/intelligence.js.map +1 -1
  37. package/dist/knowledge.d.ts +4 -4
  38. package/dist/knowledge.js +8 -8
  39. package/dist/{local-harness-CtK9dSny.d.ts → local-harness-BDNcl6jI.d.ts} +1 -1
  40. package/dist/{loop-runner-bin-DUOGtvOl.d.ts → loop-runner-bin-68aoM9-7.d.ts} +3 -11
  41. package/dist/loop-runner-bin.d.ts +4 -6
  42. package/dist/loop-runner-bin.js +5 -5
  43. package/dist/loops.d.ts +11 -11
  44. package/dist/loops.js +5 -5
  45. package/dist/mcp/bin.js +2 -2
  46. package/dist/mcp/index.d.ts +7 -8
  47. package/dist/mcp/index.js +6 -6
  48. package/dist/mcp/memory-bin.js +1 -1
  49. package/dist/primeintellect/index.d.ts +2 -3
  50. package/dist/primeintellect/index.js +5 -6
  51. package/dist/primeintellect/index.js.map +1 -1
  52. package/dist/{protected-model-port-DzkUY3HQ.d.ts → protected-model-port-B4t-OQjL.d.ts} +1 -1
  53. package/dist/{improve--2A0gK1-.d.ts → redact-BuFjxBUJ.d.ts} +201 -160
  54. package/dist/{structural-rollout-C4mabf87.d.ts → structural-rollout-DEh6CEsa.d.ts} +2 -2
  55. package/dist/{supervise-7q9F5brx.d.ts → supervise-4_48wwvy.d.ts} +2 -2
  56. package/dist/testing.js +9 -9
  57. package/dist/testing.js.map +1 -1
  58. package/dist/{worktree-fanout-WsOzt8qu.d.ts → worktree-fanout-DxhAWr5Z.d.ts} +2 -2
  59. package/package.json +6 -5
  60. package/skills/build-with-agent-runtime/SKILL.md +15 -9
  61. package/skills/loop-writer/SKILL.md +1 -1
  62. package/dist/chunk-2X65HYMI.js.map +0 -1
  63. package/dist/chunk-3PPVCS75.js.map +0 -1
  64. package/dist/chunk-5HNDYWUT.js.map +0 -1
  65. package/dist/chunk-FJI3EXU3.js.map +0 -1
  66. package/dist/chunk-L5DST3QC.js.map +0 -1
  67. package/dist/chunk-SBTWKPVR.js.map +0 -1
  68. /package/dist/{chunk-2QJSNOGK.js.map → chunk-C5RTIBNZ.js.map} +0 -0
  69. /package/dist/{chunk-SNSMRT6H.js.map → chunk-CTRA64LY.js.map} +0 -0
  70. /package/dist/{chunk-ZXICDSAK.js.map → chunk-H5QPIZNX.js.map} +0 -0
  71. /package/dist/{chunk-B7K7V22Y.js.map → chunk-RDOAVVHY.js.map} +0 -0
  72. /package/dist/{chunk-HAO4CXHP.js.map → chunk-VISA6CI3.js.map} +0 -0
  73. /package/dist/{chunk-2UABGGUB.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-ATDFUJYI.js";
8
+ } from "./chunk-WRTOVNN4.js";
9
9
  import {
10
10
  createExecutorRegistry
11
- } from "./chunk-5HNDYWUT.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-3PPVCS75.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,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;AACjC,QAAM,SAAS,SAAS,IAAI;AAC5B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR,oDAAoD,IAAI,kBACtD,OAAO,KAAK,QAAQ,EAAE,KAAK,IAAI,KAAK,MACtC;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,QAAQ,OAAO,KAAK;AAChC,QAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,EAAE;AACvD,QAAM,QAAQ,IAAI;AAClB,MAAI;AACF,UAAM,SAAS,MAAM,OAAO,MAAM;AAClC,WAAO,EAAE,MAAM,IAAI,MAAM,QAAQ,YAAY,IAAI,IAAI,MAAM;AAAA,EAC7D,SAAS,KAAK;AACZ,WAAO;AAAA,MACL;AAAA,MACA,IAAI;AAAA,MACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACtD,YA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M,EAAE,MAAM,OAAO,IAAI,oBAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC;AAClE,MAAI,CAAC,QAAQ,CAAC,QAAQ;AACpB,YAAQ,OAAO;AAAA,MACb;AAAA,WACc,qBAAqB,KAAK,KAAK,CAAC;AAAA;AAAA;AAAA,IAEhD;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,QAAM,EAAE,cAAc,IAAI,MAAM,OAAO,KAAU;AACjD,QAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,MAAW;AAC5C,QAAM,MAAM,MAAM,iBAAiB;AAAA,IACjC;AAAA,IACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,EAAE,KAAK;AAAA,EAC7F,CAAC;AACD,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,CAAC;AAAA,CAAI;AACvF,MAAI,IAAI,MAAO,SAAQ,OAAO,MAAM,GAAG,IAAI,KAAK;AAAA,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":[]}
@@ -0,0 +1,75 @@
1
+ // src/redact.ts
2
+ var redactedMarker = "[redacted]";
3
+ var secretKeyPattern = /(api[-_]?key|secret|token|password|passwd|authorization|auth|private[-_]?key|credential|access[-_]?key|client[-_]?secret|session[-_]?(id|token)|cookie|bearer)/i;
4
+ var valuePatterns = [
5
+ // Bearer tokens.
6
+ /\bBearer\s+[A-Za-z0-9._\-+/=]{8,}/gi,
7
+ // Provider-style API keys (sk-..., sk-tan-..., pk_live_..., ghp_...).
8
+ /\b(?:sk|pk|rk|ak)[-_][A-Za-z0-9_-]{12,}/g,
9
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
10
+ // AWS access key ids.
11
+ /\bAKIA[0-9A-Z]{16}\b/g,
12
+ // PEM private-key blocks.
13
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
14
+ // Email addresses.
15
+ /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g
16
+ ];
17
+ var secretAssignmentPattern = /((?:"|')?(?:api[-_]?key|secret|token|password|passwd|authorization|auth|private[-_]?key|credential|access[-_]?key|client[-_]?secret|session[-_]?(?:id|token)|cookie|bearer)(?:"|')?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;}]+)/gi;
18
+ function scrubString(input) {
19
+ let out = input;
20
+ for (const pattern of valuePatterns) {
21
+ out = out.replace(pattern, redactedMarker);
22
+ }
23
+ return out.replace(secretAssignmentPattern, `$1${redactedMarker}`);
24
+ }
25
+ function defaultRedactor(value) {
26
+ return walk(value, /* @__PURE__ */ new WeakSet(), 0);
27
+ }
28
+ var maxDepth = 32;
29
+ function walk(value, seen, depth) {
30
+ if (depth > maxDepth) return "[truncated]";
31
+ if (typeof value === "string") return scrubString(value);
32
+ if (value === null || typeof value !== "object") return value;
33
+ if (seen.has(value)) return "[circular]";
34
+ seen.add(value);
35
+ if (Array.isArray(value)) {
36
+ return value.map((item) => walk(item, seen, depth + 1));
37
+ }
38
+ const out = {};
39
+ for (const [key, v] of Object.entries(value)) {
40
+ if (secretKeyPattern.test(key)) {
41
+ out[key] = redactedMarker;
42
+ continue;
43
+ }
44
+ out[key] = walk(v, seen, depth + 1);
45
+ }
46
+ return out;
47
+ }
48
+ function defaultRedactorIdentityMaterial() {
49
+ const patternIdentity = (pattern) => ({
50
+ source: pattern.source,
51
+ flags: pattern.flags
52
+ });
53
+ return {
54
+ marker: redactedMarker,
55
+ secretKeyPattern: patternIdentity(secretKeyPattern),
56
+ valuePatterns: valuePatterns.map(patternIdentity),
57
+ secretAssignmentPattern: patternIdentity(secretAssignmentPattern),
58
+ maxDepth,
59
+ scrubString: Function.prototype.toString.call(scrubString),
60
+ walk: Function.prototype.toString.call(walk),
61
+ defaultRedactor: Function.prototype.toString.call(defaultRedactor)
62
+ };
63
+ }
64
+ function resolveRedactor(redact) {
65
+ if (redact === false) return (value) => value;
66
+ if (!redact) return defaultRedactor;
67
+ return (value) => defaultRedactor(redact(value));
68
+ }
69
+
70
+ export {
71
+ defaultRedactor,
72
+ defaultRedactorIdentityMaterial,
73
+ resolveRedactor
74
+ };
75
+ //# sourceMappingURL=chunk-OPVWXJ2H.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/redact.ts"],"sourcesContent":["/**\n *\n * Redaction for values that may leave the Runtime process. The default scrubs\n * common leak classes (API keys, bearer tokens, emails, private keys) from\n * strings and walks nested objects and arrays. A customer with domain-specific\n * PII supplies their own `redact` hook.\n *\n * This is intentionally narrower than `src/sanitize.ts` (which redacts the\n * runtime's *event envelope* field-by-field): here the value is opaque\n * customer payload, so the scrub is value-shaped, not schema-shaped.\n *\n * @experimental\n */\n\n/** A redactor maps an arbitrary trace value to a safe-to-export value. Pure;\n * must not throw on cyclic input (the default tolerates cycles). */\nexport type Redactor = (value: unknown) => unknown\n\nconst redactedMarker = '[redacted]'\n\n/** Secret-bearing key names: when an object key matches, its value is fully\n * replaced regardless of the value's own content. Lowercased compare. */\nconst secretKeyPattern =\n /(api[-_]?key|secret|token|password|passwd|authorization|auth|private[-_]?key|credential|access[-_]?key|client[-_]?secret|session[-_]?(id|token)|cookie|bearer)/i\n\n/** In-value secret/PII patterns scrubbed from any string, regardless of key. */\nconst valuePatterns: ReadonlyArray<RegExp> = [\n // Bearer tokens.\n /\\bBearer\\s+[A-Za-z0-9._\\-+/=]{8,}/gi,\n // Provider-style API keys (sk-..., sk-tan-..., pk_live_..., ghp_...).\n /\\b(?:sk|pk|rk|ak)[-_][A-Za-z0-9_-]{12,}/g,\n /\\bgh[pousr]_[A-Za-z0-9]{20,}/g,\n // AWS access key ids.\n /\\bAKIA[0-9A-Z]{16}\\b/g,\n // PEM private-key blocks.\n /-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,\n // Email addresses.\n /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n]\n\n/** Secret assignments embedded inside an otherwise opaque string, including\n * serialized JSON and log-style `key=value` text. */\nconst secretAssignmentPattern =\n /((?:\"|')?(?:api[-_]?key|secret|token|password|passwd|authorization|auth|private[-_]?key|credential|access[-_]?key|client[-_]?secret|session[-_]?(?:id|token)|cookie|bearer)(?:\"|')?\\s*[:=]\\s*)(?:\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*'|[^\\s,;}]+)/gi\n\n/** Scrub a single string of in-value secret/PII patterns. */\nfunction scrubString(input: string): string {\n let out = input\n for (const pattern of valuePatterns) {\n out = out.replace(pattern, redactedMarker)\n }\n return out.replace(secretAssignmentPattern, `$1${redactedMarker}`)\n}\n\n/**\n * The built-in redactor. Walks objects and arrays; replaces values under\n * secret-bearing keys wholesale; scrubs in-value patterns from every string.\n * Cycle-safe (a seen-set short-circuits self-referential payloads to\n * `'[circular]'`), depth-bounded, and total — never throws on customer input.\n */\nexport function defaultRedactor(value: unknown): unknown {\n return walk(value, new WeakSet(), 0)\n}\n\nconst maxDepth = 32\n\nfunction walk(value: unknown, seen: WeakSet<object>, depth: number): unknown {\n if (depth > maxDepth) return '[truncated]'\n if (typeof value === 'string') return scrubString(value)\n if (value === null || typeof value !== 'object') return value\n if (seen.has(value)) return '[circular]'\n seen.add(value)\n\n if (Array.isArray(value)) {\n return value.map((item) => walk(item, seen, depth + 1))\n }\n\n const out: Record<string, unknown> = {}\n for (const [key, v] of Object.entries(value as Record<string, unknown>)) {\n if (secretKeyPattern.test(key)) {\n out[key] = redactedMarker\n continue\n }\n out[key] = walk(v, seen, depth + 1)\n }\n return out\n}\n\n/** Stable identity input for saved work that depends on built-in redaction behavior. */\nexport function defaultRedactorIdentityMaterial(): unknown {\n const patternIdentity = (pattern: RegExp) => ({\n source: pattern.source,\n flags: pattern.flags,\n })\n return {\n marker: redactedMarker,\n secretKeyPattern: patternIdentity(secretKeyPattern),\n valuePatterns: valuePatterns.map(patternIdentity),\n secretAssignmentPattern: patternIdentity(secretAssignmentPattern),\n maxDepth,\n scrubString: Function.prototype.toString.call(scrubString),\n walk: Function.prototype.toString.call(walk),\n defaultRedactor: Function.prototype.toString.call(defaultRedactor),\n }\n}\n\n/**\n * Resolve the redactor a client uses. A caller-supplied hook handles\n * domain-specific values first, then the built-in scrubber still removes\n * common credentials and email addresses. Returning `false` is the explicit\n * opt-out for already-reviewed public values.\n */\nexport function resolveRedactor(redact: Redactor | false | undefined): Redactor {\n if (redact === false) return (value) => value\n if (!redact) return defaultRedactor\n return (value) => defaultRedactor(redact(value))\n}\n"],"mappings":";AAkBA,IAAM,iBAAiB;AAIvB,IAAM,mBACJ;AAGF,IAAM,gBAAuC;AAAA;AAAA,EAE3C;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AACF;AAIA,IAAM,0BACJ;AAGF,SAAS,YAAY,OAAuB;AAC1C,MAAI,MAAM;AACV,aAAW,WAAW,eAAe;AACnC,UAAM,IAAI,QAAQ,SAAS,cAAc;AAAA,EAC3C;AACA,SAAO,IAAI,QAAQ,yBAAyB,KAAK,cAAc,EAAE;AACnE;AAQO,SAAS,gBAAgB,OAAyB;AACvD,SAAO,KAAK,OAAO,oBAAI,QAAQ,GAAG,CAAC;AACrC;AAEA,IAAM,WAAW;AAEjB,SAAS,KAAK,OAAgB,MAAuB,OAAwB;AAC3E,MAAI,QAAQ,SAAU,QAAO;AAC7B,MAAI,OAAO,UAAU,SAAU,QAAO,YAAY,KAAK;AACvD,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AACxD,MAAI,KAAK,IAAI,KAAK,EAAG,QAAO;AAC5B,OAAK,IAAI,KAAK;AAEd,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,CAAC,SAAS,KAAK,MAAM,MAAM,QAAQ,CAAC,CAAC;AAAA,EACxD;AAEA,QAAM,MAA+B,CAAC;AACtC,aAAW,CAAC,KAAK,CAAC,KAAK,OAAO,QAAQ,KAAgC,GAAG;AACvE,QAAI,iBAAiB,KAAK,GAAG,GAAG;AAC9B,UAAI,GAAG,IAAI;AACX;AAAA,IACF;AACA,QAAI,GAAG,IAAI,KAAK,GAAG,MAAM,QAAQ,CAAC;AAAA,EACpC;AACA,SAAO;AACT;AAGO,SAAS,kCAA2C;AACzD,QAAM,kBAAkB,CAAC,aAAqB;AAAA,IAC5C,QAAQ,QAAQ;AAAA,IAChB,OAAO,QAAQ;AAAA,EACjB;AACA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,kBAAkB,gBAAgB,gBAAgB;AAAA,IAClD,eAAe,cAAc,IAAI,eAAe;AAAA,IAChD,yBAAyB,gBAAgB,uBAAuB;AAAA,IAChE;AAAA,IACA,aAAa,SAAS,UAAU,SAAS,KAAK,WAAW;AAAA,IACzD,MAAM,SAAS,UAAU,SAAS,KAAK,IAAI;AAAA,IAC3C,iBAAiB,SAAS,UAAU,SAAS,KAAK,eAAe;AAAA,EACnE;AACF;AAQO,SAAS,gBAAgB,QAAgD;AAC9E,MAAI,WAAW,MAAO,QAAO,CAAC,UAAU;AACxC,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,CAAC,UAAU,gBAAgB,OAAO,KAAK,CAAC;AACjD;","names":[]}
@@ -14,7 +14,7 @@ import {
14
14
  sha256Bytes,
15
15
  verifyBytes,
16
16
  verifyMaterializedWorkspace
17
- } from "./chunk-SBTWKPVR.js";
17
+ } from "./chunk-WSTRQZYQ.js";
18
18
 
19
19
  // src/candidate-execution/bundle.ts
20
20
  import { agentCandidateBundleSchema } from "@tangle-network/agent-interface";
@@ -696,4 +696,4 @@ export {
696
696
  captureAgentCandidateWorkspaceFiles,
697
697
  createAgentCandidateWorkspacePort
698
698
  };
699
- //# sourceMappingURL=chunk-B7K7V22Y.js.map
699
+ //# sourceMappingURL=chunk-RDOAVVHY.js.map
@@ -348,4 +348,4 @@ export {
348
348
  readMemoryItemsFile,
349
349
  resolveMemoryFromEnv
350
350
  };
351
- //# sourceMappingURL=chunk-L5DST3QC.js.map
351
+ //# sourceMappingURL=chunk-SMQXZGLZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/tool-server.ts","../src/mcp/memory-server.ts"],"sourcesContent":["/**\n * `createStdioToolServer` — the generic newline-delimited JSON-RPC 2.0 MCP\n * server core: `initialize` / `notifications/initialized` / `tools/list` /\n * `tools/call` over a stdio-shaped transport, protocol 2024-11-05.\n *\n * Extracted from `createMcpServer` (server.ts) so every in-repo MCP server —\n * the delegation server, the memory server — serves the ONE wire protocol the\n * same-host client (`connectStdioMcp`, runtime/stdio-mcp-client.ts) speaks.\n * A second hand-rolled serve loop could drift from what the client expects;\n * this core makes that impossible by construction.\n *\n * @experimental\n */\n\nimport { createInterface, type Interface as ReadlineInterface } from 'node:readline'\nimport { ValidationError } from '../errors'\n\nconst PROTOCOL_VERSION = '2024-11-05'\n\n/** @experimental */\nexport interface McpToolDescriptor {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n handler: (raw: unknown) => Promise<unknown>\n}\n\n/** @experimental */\nexport interface McpTransport {\n input: NodeJS.ReadableStream\n output: NodeJS.WritableStream\n}\n\n/** @experimental */\nexport interface JsonRpcMessage {\n jsonrpc: '2.0'\n id?: number | string | null\n method: string\n params?: unknown\n}\n\n/** @experimental */\nexport interface JsonRpcResponse {\n jsonrpc: '2.0'\n id: number | string | null\n result?: unknown\n error?: { code: number; message: string; data?: unknown }\n}\n\n/** @experimental */\nexport interface StdioToolServerOptions {\n /** Server display name surfaced via `initialize`. */\n serverName: string\n /** Server version surfaced via `initialize`. */\n serverVersion: string\n /** The tools to serve. Duplicate names throw — a silent shadow would hide a tool. */\n tools: readonly McpToolDescriptor[]\n}\n\n/** @experimental */\nexport interface StdioToolServer {\n /** Tools currently registered, keyed by name. */\n readonly tools: ReadonlyMap<string, McpToolDescriptor>\n /** Handle a single parsed JSON-RPC message. Returns the response object (or `null` for notifications). */\n handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null>\n /** Drive the server on a stdio-shaped transport until `stop()` is called. */\n serve(transport?: McpTransport): Promise<void>\n /** Stop a `serve` call. Subsequent requests are rejected. */\n stop(): void\n}\n\n/** Build the generic stdio JSON-RPC tool server. */\nexport function createStdioToolServer(options: StdioToolServerOptions): StdioToolServer {\n const tools = new Map<string, McpToolDescriptor>()\n for (const tool of options.tools) {\n if (tools.has(tool.name)) {\n throw new ValidationError(`createStdioToolServer: duplicate tool name \"${tool.name}\"`)\n }\n tools.set(tool.name, tool)\n }\n\n let stopped = false\n let activeReadline: ReadlineInterface | undefined\n\n async function handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null> {\n if (stopped) {\n return rpcError(message.id ?? null, -32099, 'server stopped')\n }\n if (message.method === 'initialize') {\n return rpcResult(message.id ?? null, {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: { tools: {} },\n serverInfo: { name: options.serverName, version: options.serverVersion },\n })\n }\n if (message.method === 'notifications/initialized') {\n // MCP clients send this after the handshake; it has no id and expects\n // no response.\n return null\n }\n if (message.method === 'tools/list') {\n return rpcResult(message.id ?? null, {\n tools: [...tools.values()].map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n })),\n })\n }\n if (message.method === 'tools/call') {\n const params = (message.params ?? {}) as { name?: unknown; arguments?: unknown }\n const name = typeof params.name === 'string' ? params.name : ''\n const tool = tools.get(name)\n if (!tool) {\n return rpcError(message.id ?? null, -32601, `unknown tool: ${name}`)\n }\n try {\n const output = await tool.handler(params.arguments ?? {})\n return rpcResult(message.id ?? null, {\n content: [{ type: 'text', text: JSON.stringify(output) }],\n structuredContent: output,\n isError: false,\n })\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n const code = err instanceof TypeError || err instanceof RangeError ? -32602 : -32000\n return rpcError(message.id ?? null, code, reason)\n }\n }\n if (message.id === undefined || message.id === null) return null\n return rpcError(message.id, -32601, `unknown method: ${message.method}`)\n }\n\n async function serve(transport?: McpTransport): Promise<void> {\n const input = transport?.input ?? process.stdin\n const output = transport?.output ?? process.stdout\n const rl = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY })\n activeReadline = rl\n return new Promise<void>((resolve, reject) => {\n rl.on('line', (line) => {\n const trimmed = line.trim()\n if (!trimmed) return\n let parsed: JsonRpcMessage | undefined\n try {\n parsed = JSON.parse(trimmed) as JsonRpcMessage\n } catch (err) {\n writeResponse(output, rpcError(null, -32700, `parse error: ${(err as Error).message}`))\n return\n }\n if (!parsed || parsed.jsonrpc !== '2.0' || typeof parsed.method !== 'string') {\n writeResponse(output, rpcError(parsed?.id ?? null, -32600, 'invalid request'))\n return\n }\n void handle(parsed).then((response) => {\n if (response) writeResponse(output, response)\n })\n })\n rl.on('close', () => resolve())\n rl.on('error', (err) => reject(err))\n if (stopped) {\n rl.close()\n resolve()\n }\n })\n }\n\n function stop(): void {\n stopped = true\n activeReadline?.close()\n activeReadline = undefined\n }\n\n return { tools, handle, serve, stop }\n}\n\nfunction rpcResult(id: number | string | null, result: unknown): JsonRpcResponse {\n return { jsonrpc: '2.0', id, result }\n}\n\nfunction rpcError(\n id: number | string | null,\n code: number,\n message: string,\n data?: unknown,\n): JsonRpcResponse {\n return {\n jsonrpc: '2.0',\n id,\n error: data === undefined ? { code, message } : { code, message, data },\n }\n}\n\nfunction writeResponse(output: NodeJS.WritableStream, response: JsonRpcResponse): void {\n output.write(`${JSON.stringify(response)}\\n`)\n}\n","/**\n * Memory MCP server — the LIVE serving half of the `memory` profile surface\n * (Phase 5). A curated memory (lessons distilled from prior runs) is only\n * real if the DRIVEN agent can query it mid-task; this module serves a flat\n * store of `MemoryItem` rows as `memory_search` / `memory_get` tools over the\n * ONE in-repo stdio JSON-RPC core (`createStdioToolServer`), so the exact\n * wire protocol the same-host client (`connectStdioMcp` /\n * `materializeLocalMcp`, runtime/stdio-mcp-client.ts) speaks is guaranteed by\n * construction — serve and consume cannot drift.\n *\n * Retrieval is DETERMINISTIC lexical overlap (no vectors, no LLM): a lift\n * measured with this memory mounted is attributable to the lessons\n * themselves, never to retrieval-model noise. Every\n * `memory_search` can append one JSONL row to a retrieval log (`logPath`) —\n * the per-query record an off-policy retrieval estimator (agent-knowledge's\n * `RetrievalHoldout`) consumes. agent-knowledge is NOT a dependency of this\n * repo, so the log file is the flagged cross-package seam, not an import.\n *\n * Fail-loud discipline (mirrors `materializeLocalMcp`): an EMPTY memory is\n * never served — a profile without memory simply omits the artifact, and\n * silently serving zero rows would fake the with/without ablation.\n *\n * @experimental\n */\n\nimport { appendFileSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { AgentProfileMcpServer } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\nimport { createStdioToolServer, type McpToolDescriptor, type StdioToolServer } from './tool-server'\n\n/** One row of agent memory: a crisp lesson/fact with provenance. */\nexport interface MemoryItem {\n /** Stable id (content-hash by convention; see `memoryArtifactFromLessons`). */\n id: string\n /** The lesson itself — one imperative or observation the agent should recall. */\n text: string\n /** Optional retrieval tags, matched by `memory_search` alongside the text. */\n tags?: string[]\n /** Provenance: the finding / trace / curation pass this row came from. */\n source?: string\n}\n\n/**\n * The `memory` artifact payload — HOW a profile's memory is stored and served:\n *\n * - `store: 'file'` — served by the in-repo memory bin\n * (`agent-runtime-memory-mcp`, src/mcp/memory-bin.ts): rows load from\n * `path` (a JSON array or JSONL file of `MemoryItem`) and/or the inline\n * `items` seed (inline wins on id collision). At least one of\n * `path`/`items` is required.\n * - `store: 'mcp'` — an EXTERNAL, already-runnable MCP server that exposes\n * the memory tools itself; `server` is required and mounts verbatim.\n *\n * `logPath` makes the served memory append one JSONL row per `memory_search`\n * — the retrieval log a holdout estimator reads (see module doc).\n */\nexport interface AgentMemorySpec {\n store: 'file' | 'mcp'\n /** `store:'file'` — host path to the durable row store (JSON array or JSONL). */\n path?: string\n /** Inline seed rows, served alongside (and winning over) `path` rows. */\n items?: MemoryItem[]\n /** `store:'mcp'` — the external server that already serves memory tools. */\n server?: AgentProfileMcpServer\n /** JSONL retrieval log: one row per `memory_search` (ts, query, k, returned). */\n logPath?: string\n}\n\n/** Env var naming the durable row store file the memory bin loads (the\n * `memoryMcpServer` ↔ memory-bin contract). */\nexport const MEMORY_FILE_ENV = 'AGENT_MEMORY_FILE'\n/** Env var carrying inline JSON `MemoryItem` rows (win over file rows on id). */\nexport const MEMORY_ITEMS_ENV = 'AGENT_MEMORY_ITEMS'\n/** Env var naming the JSONL retrieval log (one row per `memory_search`). */\nexport const MEMORY_LOG_ENV = 'AGENT_MEMORY_LOG'\n/** Env var overriding the served display name (default 'agent-memory'). */\nexport const MEMORY_NAME_ENV = 'AGENT_MEMORY_NAME'\n\nexport interface CreateMemoryToolServerOptions {\n /** The rows to serve. MUST be non-empty (an empty memory is never served). */\n items: readonly MemoryItem[]\n /** Server display name surfaced via `initialize`. Default 'agent-memory'. */\n serverName?: string\n /** Server version surfaced via `initialize`. Default '0'. */\n serverVersion?: string\n /** Default result count for `memory_search`. Default 5. */\n defaultK?: number\n /** Append one JSONL row per `memory_search` (the retrieval-holdout seam). */\n logPath?: string\n}\n\n/**\n * Build the memory MCP server: `memory_search` (lexical top-k over the rows)\n * and `memory_get` (one row by id) on the generic stdio JSON-RPC core.\n */\nexport function createMemoryToolServer(opts: CreateMemoryToolServerOptions): StdioToolServer {\n if (opts.items.length === 0) {\n throw new ValidationError(\n 'createMemoryToolServer: refusing to serve an EMPTY memory — a profile without memory omits the artifact; serving zero rows would fake the with/without ablation',\n )\n }\n const byId = new Map<string, MemoryItem>()\n for (const item of opts.items) {\n if (byId.has(item.id)) {\n throw new ValidationError(`createMemoryToolServer: duplicate memory item id '${item.id}'`)\n }\n byId.set(item.id, item)\n }\n const items = [...byId.values()]\n const defaultK = opts.defaultK ?? 5\n const logPath = opts.logPath\n if (logPath) mkdirSync(dirname(logPath), { recursive: true })\n\n const search: McpToolDescriptor = {\n name: 'memory_search',\n description:\n 'Search the agent memory of lessons learned from prior runs. Give what you are about to do or the problem you face; returns the top-k lessons ranked by relevance. Consult it BEFORE repeating work a prior run already learned from.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'The task/problem at hand — matched against lesson text and tags.',\n },\n k: { type: 'number', description: `Max results (default ${defaultK}).` },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Only return items carrying at least one of these tags.',\n },\n },\n required: ['query'],\n },\n handler: async (raw) => {\n const args = (raw ?? {}) as { query?: unknown; k?: unknown; tags?: unknown }\n if (typeof args.query !== 'string' || args.query.trim().length === 0) {\n throw new TypeError('memory_search: query must be a non-empty string')\n }\n const k = args.k === undefined ? defaultK : Math.floor(Number(args.k))\n if (!Number.isFinite(k) || k < 1) {\n throw new TypeError('memory_search: k must be a positive integer')\n }\n let tagFilter: string[] | undefined\n if (args.tags !== undefined) {\n if (!Array.isArray(args.tags) || args.tags.some((t) => typeof t !== 'string')) {\n throw new TypeError('memory_search: tags must be an array of strings')\n }\n tagFilter = args.tags as string[]\n }\n const queryTokens = tokenize(args.query)\n const pool = tagFilter\n ? items.filter((i) => (i.tags ?? []).some((t) => tagFilter.includes(t)))\n : items\n const results = pool\n .map((item) => ({ item, score: scoreItem(queryTokens, item) }))\n .filter((r) => r.score > 0)\n // Highest score first; stable on ties (curation order is the tiebreak).\n .sort((a, b) => b.score - a.score)\n .slice(0, k)\n .map(({ item, score }) => ({\n id: item.id,\n text: item.text,\n score: Number(score.toFixed(4)),\n ...(item.tags ? { tags: item.tags } : {}),\n ...(item.source ? { source: item.source } : {}),\n }))\n if (logPath) {\n // The retrieval log: what was asked, what came back, at what rank —\n // exactly the per-query record an off-policy estimator needs.\n appendFileSync(\n logPath,\n `${JSON.stringify({\n ts: new Date().toISOString(),\n query: args.query,\n k,\n returned: results.map((r) => ({ id: r.id, score: r.score })),\n })}\\n`,\n )\n }\n return { query: args.query, results }\n },\n }\n\n const get: McpToolDescriptor = {\n name: 'memory_get',\n description: 'Fetch one memory item verbatim by its id (ids come from memory_search results).',\n inputSchema: {\n type: 'object',\n properties: { id: { type: 'string', description: 'The memory item id.' } },\n required: ['id'],\n },\n handler: async (raw) => {\n const args = (raw ?? {}) as { id?: unknown }\n if (typeof args.id !== 'string' || args.id.trim().length === 0) {\n throw new TypeError('memory_get: id must be a non-empty string')\n }\n const item = byId.get(args.id)\n if (!item) throw new Error(`memory_get: no memory item with id '${args.id}'`)\n return item\n },\n }\n\n return createStdioToolServer({\n serverName: opts.serverName ?? 'agent-memory',\n serverVersion: opts.serverVersion ?? '0',\n tools: [search, get],\n })\n}\n\n/** Coerce an untrusted JSON array into validated `MemoryItem` rows. */\nexport function parseMemoryItems(value: unknown, source: string): MemoryItem[] {\n if (!Array.isArray(value)) {\n throw new ValidationError(`${source}: expected a JSON array of memory items`)\n }\n return value.map((row, i) => coerceMemoryItem(row, `${source}[${i}]`))\n}\n\n/** Read a memory store file: a JSON array, or JSONL (one `MemoryItem` per line). */\nexport function readMemoryItemsFile(path: string): MemoryItem[] {\n let raw: string\n try {\n raw = readFileSync(path, 'utf8')\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: cannot read '${path}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const trimmed = raw.trim()\n if (trimmed.length === 0) return []\n if (trimmed.startsWith('[')) {\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: '${path}' is not valid JSON: ${(err as Error).message}`,\n )\n }\n return parseMemoryItems(parsed, path)\n }\n return trimmed\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line, i) => {\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: '${path}' line ${i + 1} is not valid JSON: ${(err as Error).message}`,\n )\n }\n return coerceMemoryItem(parsed, `${path}:${i + 1}`)\n })\n}\n\n/** What the memory bin resolved from its environment. */\nexport interface ResolvedMemoryEnv {\n items: MemoryItem[]\n serverName?: string\n logPath?: string\n}\n\n/**\n * Resolve the bin's memory from `AGENT_MEMORY_FILE` (durable store) and/or\n * `AGENT_MEMORY_ITEMS` (inline JSON rows; wins on id collision). Zero rows is\n * a boot FAILURE, matching the fail-closed materialization discipline.\n */\nexport function resolveMemoryFromEnv(env: Record<string, string | undefined>): ResolvedMemoryEnv {\n const filePath = env[MEMORY_FILE_ENV]\n const inlineRaw = env[MEMORY_ITEMS_ENV]\n const fromFile = filePath ? readMemoryItemsFile(filePath) : []\n let inline: MemoryItem[] = []\n if (inlineRaw) {\n let parsed: unknown\n try {\n parsed = JSON.parse(inlineRaw)\n } catch (err) {\n throw new ValidationError(\n `${MEMORY_ITEMS_ENV} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n inline = parseMemoryItems(parsed, MEMORY_ITEMS_ENV)\n }\n const byId = new Map<string, MemoryItem>()\n for (const item of fromFile) byId.set(item.id, item)\n for (const item of inline) byId.set(item.id, item)\n if (byId.size === 0) {\n throw new ValidationError(\n `memory bin: no memory items — set ${MEMORY_FILE_ENV} and/or ${MEMORY_ITEMS_ENV}; an EMPTY memory must never be served (a profile without memory omits the artifact)`,\n )\n }\n const serverName = env[MEMORY_NAME_ENV]\n const logPath = env[MEMORY_LOG_ENV]\n return {\n items: [...byId.values()],\n ...(serverName ? { serverName } : {}),\n ...(logPath ? { logPath } : {}),\n }\n}\n\nfunction coerceMemoryItem(row: unknown, at: string): MemoryItem {\n if (!row || typeof row !== 'object' || Array.isArray(row)) {\n throw new ValidationError(`${at}: memory item must be an object`)\n }\n const r = row as Record<string, unknown>\n if (typeof r.id !== 'string' || r.id.trim().length === 0) {\n throw new ValidationError(`${at}: 'id' must be a non-empty string`)\n }\n if (typeof r.text !== 'string' || r.text.trim().length === 0) {\n throw new ValidationError(`${at}: 'text' must be a non-empty string`)\n }\n let tags: string[] | undefined\n if (r.tags !== undefined) {\n if (!Array.isArray(r.tags) || r.tags.some((t) => typeof t !== 'string')) {\n throw new ValidationError(`${at}: 'tags' must be an array of strings`)\n }\n tags = r.tags as string[]\n }\n if (r.source !== undefined && typeof r.source !== 'string') {\n throw new ValidationError(`${at}: 'source' must be a string`)\n }\n return {\n id: r.id,\n text: r.text,\n ...(tags ? { tags } : {}),\n ...(typeof r.source === 'string' ? { source: r.source } : {}),\n }\n}\n\n/** Unique lowercase alphanumeric tokens of length >= 2. */\nfunction tokenize(text: string): string[] {\n return [\n ...new Set(\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length >= 2),\n ),\n ]\n}\n\n/** Fraction of query tokens present in the item's text + tags (0..1). */\nfunction scoreItem(queryTokens: readonly string[], item: MemoryItem): number {\n if (queryTokens.length === 0) return 0\n const hay = new Set(tokenize(`${item.text} ${(item.tags ?? []).join(' ')}`))\n let hit = 0\n for (const t of queryTokens) if (hay.has(t)) hit += 1\n return hit / queryTokens.length\n}\n"],"mappings":";;;;;AAcA,SAAS,uBAA4D;AAGrE,IAAM,mBAAmB;AAuDlB,SAAS,sBAAsB,SAAkD;AACtF,QAAM,QAAQ,oBAAI,IAA+B;AACjD,aAAW,QAAQ,QAAQ,OAAO;AAChC,QAAI,MAAM,IAAI,KAAK,IAAI,GAAG;AACxB,YAAM,IAAI,gBAAgB,+CAA+C,KAAK,IAAI,GAAG;AAAA,IACvF;AACA,UAAM,IAAI,KAAK,MAAM,IAAI;AAAA,EAC3B;AAEA,MAAI,UAAU;AACd,MAAI;AAEJ,iBAAe,OAAO,SAA0D;AAC9E,QAAI,SAAS;AACX,aAAO,SAAS,QAA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