@tangle-network/agent-runtime 0.301.0 → 0.306.2

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 (85) hide show
  1. package/dist/{activation-V6aaOlZV.js → activation-kaJzXM7Y.js} +3 -3
  2. package/dist/{activation-V6aaOlZV.js.map → activation-kaJzXM7Y.js.map} +1 -1
  3. package/dist/{activation-CRgEJutr.d.ts → activation-wZ-8vOjV.d.ts} +88 -13
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/{bundle-C9v5TH_H.js → bundle-E6mbRX2P.js} +2 -2
  7. package/dist/{bundle-C9v5TH_H.js.map → bundle-E6mbRX2P.js.map} +1 -1
  8. package/dist/candidate-execution/index.d.ts +3 -26
  9. package/dist/candidate-execution/index.js +6 -6
  10. package/dist/{coordination-driver-vNrdQBSH.js → coordination-driver-Y2gf8pBT.js} +9 -16
  11. package/dist/coordination-driver-Y2gf8pBT.js.map +1 -0
  12. package/dist/{delegate-B-jFJcbW.js → delegate-B7bwEFQl.js} +2 -2
  13. package/dist/{delegate-B-jFJcbW.js.map → delegate-B7bwEFQl.js.map} +1 -1
  14. package/dist/durable.d.ts +3 -15
  15. package/dist/durable.js +158 -124
  16. package/dist/durable.js.map +1 -1
  17. package/dist/{graph-Dwv_hQB_.js → graph-VUwNFYff.js} +4 -5
  18. package/dist/graph-VUwNFYff.js.map +1 -0
  19. package/dist/{improvement-cycle-Cf37Kexd.js → improvement-cycle-DuIGusyA.js} +1129 -10
  20. package/dist/improvement-cycle-DuIGusyA.js.map +1 -0
  21. package/dist/{index-CxBVmgqL.d.ts → index-DflDZq_I.d.ts} +50 -688
  22. package/dist/index.d.ts +378 -12
  23. package/dist/index.js +223 -320
  24. package/dist/index.js.map +1 -1
  25. package/dist/intelligence.d.ts +5 -5
  26. package/dist/intelligence.js +7 -8
  27. package/dist/intelligence.js.map +1 -1
  28. package/dist/kernel.d.ts +4 -4
  29. package/dist/kernel.js +9 -9
  30. package/dist/{loop-runner-bin-DiTNiJNs.d.ts → loop-runner-bin-DZfRUVWy.d.ts} +3 -3
  31. package/dist/{loop-runner-bin-C8MI8N1A.js → loop-runner-bin-Dp1V3P2W.js} +3 -3
  32. package/dist/{loop-runner-bin-C8MI8N1A.js.map → loop-runner-bin-Dp1V3P2W.js.map} +1 -1
  33. package/dist/loop-runner-bin.d.ts +1 -1
  34. package/dist/loop-runner-bin.js +1 -1
  35. package/dist/mcp/bin.js +3 -3
  36. package/dist/mcp/index.d.ts +6 -35
  37. package/dist/mcp/index.js +311 -364
  38. package/dist/mcp/index.js.map +1 -1
  39. package/dist/model-policy-DydyWTQg.js.map +1 -1
  40. package/dist/{openai-tools-BeogJ6V8.d.ts → openai-tools-YO30D2s3.d.ts} +2 -2
  41. package/dist/{prepare-CGVNMb1o.js → prepare-CulUz6Wm.js} +7 -13
  42. package/dist/prepare-CulUz6Wm.js.map +1 -0
  43. package/dist/{profile-BetOB4_Q.js → profile-DY9lT3gH.js} +2 -2
  44. package/dist/{profile-BetOB4_Q.js.map → profile-DY9lT3gH.js.map} +1 -1
  45. package/dist/profiles.d.ts +2 -94
  46. package/dist/profiles.js +2 -451
  47. package/dist/profiles.js.map +1 -1
  48. package/dist/{protected-model-port-CuVHkhti.js → protected-model-port-BT2iYAsU.js} +4 -4
  49. package/dist/{protected-model-port-CuVHkhti.js.map → protected-model-port-BT2iYAsU.js.map} +1 -1
  50. package/dist/{protected-model-port-CAa0t1MT.d.ts → protected-model-port-C9QtEf3y.d.ts} +2 -2
  51. package/dist/{provision-supervisor-CS0fBIhp.js → provision-supervisor-CfK8fla-.js} +4 -3
  52. package/dist/{provision-supervisor-CS0fBIhp.js.map → provision-supervisor-CfK8fla-.js.map} +1 -1
  53. package/dist/{runtime-6VPSJVeg.js → runtime-D452tieK.js} +67 -469
  54. package/dist/runtime-D452tieK.js.map +1 -0
  55. package/dist/{search-method-wTTS7mGG.js → search-executor-D3AT8_hb.js} +239 -1132
  56. package/dist/search-executor-D3AT8_hb.js.map +1 -0
  57. package/dist/{server-BfHD5iLD.js → server-D1Tfxo-v.js} +5 -12
  58. package/dist/server-D1Tfxo-v.js.map +1 -0
  59. package/dist/{stream-agent-turn-B1ipFtOc.d.ts → stream-agent-turn-B1giFgOg.d.ts} +2 -2
  60. package/dist/{substrate-DKBMd0Dl.d.ts → substrate-L_sC7jCD.d.ts} +2 -2
  61. package/dist/{supervise-BJrEC2Mh.js → supervise-CtewGpxh.js} +14 -24
  62. package/dist/supervise-CtewGpxh.js.map +1 -0
  63. package/dist/{supervisor-DA_nvF-h.js → supervisor-DYKPbcZa.js} +488 -1407
  64. package/dist/supervisor-DYKPbcZa.js.map +1 -0
  65. package/dist/testing.d.ts +2 -2
  66. package/dist/testing.js +14 -14
  67. package/dist/tui/index.d.ts +1 -1
  68. package/dist/tui/index.js +1 -1
  69. package/dist/{types-jD9mNnJM.d.ts → types-DeuEkBhI.d.ts} +114 -258
  70. package/dist/{workspace-archive-pz8YJ1fr.d.ts → workspace-streams-CpSmt3zx.d.ts} +67 -3
  71. package/dist/{workspace-streams-D5gHJdTb.js → workspace-streams-DaQceg2p.js} +699 -2
  72. package/dist/workspace-streams-DaQceg2p.js.map +1 -0
  73. package/package.json +8 -8
  74. package/skills/generate-eval/SKILL.md +1 -1
  75. package/skills/profile-authoring/SKILL.md +2 -2
  76. package/dist/coordination-driver-vNrdQBSH.js.map +0 -1
  77. package/dist/graph-Dwv_hQB_.js.map +0 -1
  78. package/dist/improvement-cycle-Cf37Kexd.js.map +0 -1
  79. package/dist/prepare-CGVNMb1o.js.map +0 -1
  80. package/dist/runtime-6VPSJVeg.js.map +0 -1
  81. package/dist/search-method-wTTS7mGG.js.map +0 -1
  82. package/dist/server-BfHD5iLD.js.map +0 -1
  83. package/dist/supervise-BJrEC2Mh.js.map +0 -1
  84. package/dist/supervisor-DA_nvF-h.js.map +0 -1
  85. package/dist/workspace-streams-D5gHJdTb.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
- import { $i as executableAgentProfileSnapshot, $r as sanitizeAgentRuntimeEvent, Br as buildLoopOtelSpans, Hr as buildRuntimeEventOtelSpans, Jr as padSpanId, Kr as generateSpanId, Mi as prepareJsonlAppend, Ni as readCommittedJsonLines, Pi as writeAllBytes, Qr as createRuntimeStreamEventCollector, Rr as defaultRedactorIdentityMaterial, Ur as createOpenInferenceFileExporter, Vr as buildLoopSpanNodes, Wa as providerMessageText, Wr as createOtelExporter, Xr as toOtelAttributes, Yr as padTraceId, Zr as createRuntimeEventCollector, ei as sanitizeKnowledgeReadinessReport, qr as loopEventToOtelSpan, ti as sanitizeRuntimeStreamEvent, zr as resolveRedactor } from "./supervisor-DA_nvF-h.js";
1
+ import { Ar as buildRuntimeEventOtelSpans, Br as createRuntimeStreamEventCollector, Dr as resolveRedactor, Er as defaultRedactorIdentityMaterial, Fr as loopEventToOtelSpan, Hr as sanitizeKnowledgeReadinessReport, Ir as padSpanId, Li as executableAgentProfileSnapshot, Lr as padTraceId, Mr as createOtelExporter, Or as buildLoopOtelSpans, Pr as generateSpanId, Rr as toOtelAttributes, Ur as sanitizeRuntimeStreamEvent, Vr as sanitizeAgentRuntimeEvent, jr as createOpenInferenceFileExporter, kr as buildLoopSpanNodes, oa as providerMessageText, zr as createRuntimeEventCollector } from "./supervisor-DYKPbcZa.js";
2
2
  import { a as JudgeError, c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, i as ConfigError, l as RetainedInteractiveBindingError, m as ValidationError, o as NotFoundError, r as BackendTransportError, s as PlannerError, t as AgentEvalError, u as RetainedRunAdmissionError } from "./errors-DodWX-cb.js";
3
- import { A as parseRolloutPolicy, C as privateValuePaths, D as ROLLOUT_POLICY_EXTENSION, M as structuralRolloutPolicyFromProfile, O as applyRolloutPolicyToProfile, S as parseExecutionRef, _t as startOrResumeRuntimeSession, a as SearchEnvironmentFault, b as assertCandidateValidator, ct as strategyAuthorMethod, d as sharedBoxLane, dt as createIterableBackend, f as subscriptionLane, ft as createSandboxPromptBackend, gt as nowIso, ht as newRuntimeSession, i as searchMethod, j as serializeRolloutPolicy, k as normalizeRolloutPolicy, l as routerLane, mt as InMemoryRuntimeSessionStore, o as dedicatedLane, pt as normalizeBackendStreamEvent, s as isSearchEnvironmentFault, st as optimizerMethod, ut as streamAgentTurn, vt as touchSession } from "./search-method-wTTS7mGG.js";
3
+ import { $ as createIterableBackend, Q as streamAgentTurn, X as strategyAuthorMethod, Y as optimizerMethod, at as startOrResumeRuntimeSession, et as createSandboxPromptBackend, i as isSearchEnvironmentFault, it as nowIso, l as sharedBoxLane, nt as InMemoryRuntimeSessionStore, o as routerLane, ot as touchSession, r as dedicatedLane, rt as newRuntimeSession, t as SearchEnvironmentFault, tt as normalizeBackendStreamEvent, u as subscriptionLane, y as decideSearchImprovement } from "./search-executor-D3AT8_hb.js";
4
+ import { A as canonicalCandidateBytes$1, F as immutableCandidateValue, I as omitTopLevelDigest, P as embeddedCandidateArtifact, d as persistCandidateOutputArtifact, j as canonicalCandidateDigest$1, s as captureAgentCandidateWorkspace } from "./workspace-streams-DaQceg2p.js";
4
5
  import { t as assertExecutableAgentProfile } from "./model-policy-DydyWTQg.js";
5
- import { a as createRuntimeUsageTotals, i as addRuntimeUsage, o as isUsageAmount, t as createAgentImprovementActivationResult } from "./activation-V6aaOlZV.js";
6
- import { M as embeddedCandidateArtifact, N as immutableCandidateValue, O as canonicalCandidateBytes$1, P as omitTopLevelDigest, a as captureAgentCandidateWorkspace, k as canonicalCandidateDigest$1, l as persistCandidateOutputArtifact } from "./workspace-streams-D5gHJdTb.js";
7
- import { Jt as connectStdioMcp, qt as McpSpawnFault } from "./runtime-6VPSJVeg.js";
6
+ import { a as createRuntimeUsageTotals, i as addRuntimeUsage, o as isUsageAmount, t as createAgentImprovementActivationResult } from "./activation-kaJzXM7Y.js";
7
+ import { Ht as McpSpawnFault, Ut as connectStdioMcp } from "./runtime-D452tieK.js";
8
8
  import { i as notifyRuntimeHookEvent, n as defineRuntimeHooks, r as notifyRuntimeDecisionPoint, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
9
- import { B as rawTraceDistiller, H as commandVerifier, L as improve, R as createCommandProfileTrainer, U as defaultBuildPrompt, V as agenticGenerator, z as withMethodRuntimeControls } from "./improvement-cycle-Cf37Kexd.js";
10
- import { t as sealAgentCandidateBundle } from "./bundle-C9v5TH_H.js";
11
- import { r as supervise } from "./supervise-BJrEC2Mh.js";
12
- import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-C8MI8N1A.js";
9
+ import { $ as commandVerifier, B as assertCandidateValidator, G as rawTraceDistiller, H as parseExecutionRef, J as normalizeRolloutPolicy, K as ROLLOUT_POLICY_EXTENSION, L as improve, Q as agenticGenerator, R as createCommandProfileTrainer, U as privateValuePaths, W as withMethodRuntimeControls, X as serializeRolloutPolicy, Y as parseRolloutPolicy, Z as structuralRolloutPolicyFromProfile, et as defaultBuildPrompt, q as applyRolloutPolicyToProfile, z as searchMethod } from "./improvement-cycle-DuIGusyA.js";
10
+ import { t as sealAgentCandidateBundle } from "./bundle-E6mbRX2P.js";
11
+ import { r as supervise } from "./supervise-CtewGpxh.js";
12
+ import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-Dp1V3P2W.js";
13
13
  import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "./openai-tools-DoQ32vpe.js";
14
14
  import { agentCandidateKnowledgeSchema, agentCandidateWorkspaceManifestMaterialSchema, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sha256DigestSchema } from "@tangle-network/agent-interface";
15
15
  import { FAILURE_CLASSES, acquisitionPlansForKnowledgeGaps, blockingKnowledgeEval, canonicalJson, runAgentControlLoop, scoreKnowledgeReadiness, userQuestionsForKnowledgeGaps } from "@tangle-network/agent-eval";
@@ -340,66 +340,22 @@ async function* runConversationStream(conversation, options) {
340
340
  const cfg = participant.callPolicy?.circuitBreaker ?? conversation.policy.defaultCallPolicy?.circuitBreaker;
341
341
  breakers.set(participant.name, new CircuitBreakerState(cfg));
342
342
  }
343
- let transcript = [];
343
+ const transcript = [];
344
344
  let spentCreditsCents = 0;
345
- let startedAt = nowIso();
346
- let resumed = false;
345
+ const startedAt = nowIso();
347
346
  const sessionStore = options.sessionStore ?? new InMemoryRuntimeSessionStore();
348
- if (options.journal) {
349
- const prior = await options.journal.loadRun(runId);
350
- if (prior) {
351
- if (prior.halted) {
352
- const replayResult = {
353
- runId,
354
- transcript: prior.turns,
355
- turns: prior.turns.length,
356
- spentCreditsCents: prior.turns.reduce((sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0), 0),
357
- halted: prior.halted,
358
- durationMs: 0,
359
- startedAt: prior.startedAt,
360
- endedAt: prior.endedAt ?? prior.startedAt
361
- };
362
- yield {
363
- type: "conversation_resumed",
364
- runId,
365
- participants: conversation.participants.map((p) => p.name),
366
- transcript: prior.turns,
367
- timestamp: nowIso()
368
- };
369
- yield {
370
- type: "conversation_end",
371
- runId,
372
- result: replayResult,
373
- timestamp: nowIso()
374
- };
375
- return;
376
- }
377
- transcript = [...prior.turns];
378
- spentCreditsCents = transcript.reduce((sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0), 0);
379
- startedAt = prior.startedAt;
380
- resumed = true;
381
- } else await options.journal.beginRun(runId, startedAt);
382
- }
383
347
  const startedAtMs = Date.now();
384
- const participantSessions = sessionIdsFrom(transcript);
385
- if (resumed) yield {
386
- type: "conversation_resumed",
387
- runId,
388
- participants: conversation.participants.map((p) => p.name),
389
- transcript: [...transcript],
390
- timestamp: nowIso()
391
- };
392
- else yield {
348
+ const participantSessions = /* @__PURE__ */ new Map();
349
+ yield {
393
350
  type: "conversation_start",
394
351
  runId,
395
352
  participants: conversation.participants.map((p) => p.name),
396
353
  seed: options.seed,
397
354
  timestamp: startedAt
398
355
  };
399
- let currentInput = transcript.length === 0 ? options.seed : transcript[transcript.length - 1]?.text ?? options.seed;
356
+ let currentInput = options.seed;
400
357
  let halt;
401
- const initialOffset = transcript.length;
402
- for (let turnIndex = initialOffset; turnIndex < conversation.policy.maxTurns; turnIndex++) {
358
+ for (let turnIndex = 0; turnIndex < conversation.policy.maxTurns; turnIndex++) {
403
359
  if (options.signal?.aborted) {
404
360
  halt = { kind: "abort" };
405
361
  break;
@@ -526,7 +482,6 @@ async function* runConversationStream(conversation, options) {
526
482
  if (turn.sessionId) bindParticipantSession(participantSessions, turn.speaker, turn.sessionId);
527
483
  transcript.push(turn);
528
484
  spentCreditsCents += centsFromUsd(turn.usage?.costUsd ?? 0);
529
- if (options.journal) await options.journal.appendTurn(runId, turn);
530
485
  yield {
531
486
  type: "turn_end",
532
487
  runId,
@@ -563,21 +518,19 @@ async function* runConversationStream(conversation, options) {
563
518
  turns: transcript.length
564
519
  };
565
520
  const endedAt = nowIso();
566
- const result = {
567
- runId,
568
- transcript,
569
- turns: transcript.length,
570
- spentCreditsCents,
571
- halted: halt,
572
- durationMs: Date.now() - startedAtMs,
573
- startedAt,
574
- endedAt
575
- };
576
- if (options.journal) await options.journal.recordHalt(runId, halt, endedAt);
577
521
  yield {
578
522
  type: "conversation_end",
579
523
  runId,
580
- result,
524
+ result: {
525
+ runId,
526
+ transcript,
527
+ turns: transcript.length,
528
+ spentCreditsCents,
529
+ halted: halt,
530
+ durationMs: Date.now() - startedAtMs,
531
+ startedAt,
532
+ endedAt
533
+ },
581
534
  timestamp: endedAt
582
535
  };
583
536
  }
@@ -747,11 +700,6 @@ function continuedConversationInput(task, speakerName, transcript) {
747
700
  }]
748
701
  };
749
702
  }
750
- function sessionIdsFrom(transcript) {
751
- const sessions = /* @__PURE__ */ new Map();
752
- for (const turn of transcript) if (turn.sessionId) bindParticipantSession(sessions, turn.speaker, turn.sessionId);
753
- return sessions;
754
- }
755
703
  function bindParticipantSession(sessions, speakerName, sessionId) {
756
704
  assertParticipantSessionAvailable(sessions, speakerName, sessionId);
757
705
  sessions.set(speakerName, sessionId);
@@ -976,248 +924,6 @@ function normalizePolicy(policy, participantCount) {
976
924
  };
977
925
  }
978
926
  //#endregion
979
- //#region src/conversation/journal.ts
980
- /**
981
- *
982
- * Durable conversation transcript — survives a driver process crash mid-run.
983
- * The runner journals every committed turn before yielding `turn_end`, so a
984
- * resumed run replays the same `runId` against the same journal and picks up
985
- * from the first un-recorded turn. Combined with the deterministic
986
- * `turnId(runId, index, speaker)`, a retried turn collides with the prior
987
- * attempt's id and any caching gateway can dedupe.
988
- *
989
- * The interface is small enough that a Cloudflare D1 / R2 / postgres adapter
990
- * is ~30 lines. The in-memory adapter is the default for tests and scratch.
991
- * The file adapter (JSONL on disk) is the default-durable choice when no
992
- * upstream store is wired.
993
- *
994
- * @stable
995
- */
996
- /** In-memory `ConversationJournal` — suitable for testing and single-process runs. */
997
- var InMemoryConversationJournal = class {
998
- entries = /* @__PURE__ */ new Map();
999
- async loadRun(runId) {
1000
- const entry = this.entries.get(runId);
1001
- if (!entry) return void 0;
1002
- return {
1003
- runId: entry.runId,
1004
- startedAt: entry.startedAt,
1005
- halted: entry.halted,
1006
- endedAt: entry.endedAt,
1007
- turns: [...entry.turns]
1008
- };
1009
- }
1010
- async beginRun(runId, startedAt) {
1011
- const existing = this.entries.get(runId);
1012
- if (existing) {
1013
- if (existing.startedAt !== startedAt) throw new Error(`runId '${runId}' already exists with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`);
1014
- return;
1015
- }
1016
- this.entries.set(runId, {
1017
- runId,
1018
- startedAt,
1019
- turns: []
1020
- });
1021
- }
1022
- async appendTurn(runId, turn) {
1023
- const entry = this.entries.get(runId);
1024
- if (!entry) throw new Error(`appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`);
1025
- if (entry.halted) throw new Error(`cannot append turn to halted run '${runId}' (halt reason: ${JSON.stringify(entry.halted)})`);
1026
- entry.turns.push(turn);
1027
- }
1028
- async recordHalt(runId, halt, endedAt) {
1029
- const entry = this.entries.get(runId);
1030
- if (!entry) throw new Error(`recordHalt called for unknown runId '${runId}'`);
1031
- entry.halted = halt;
1032
- entry.endedAt = endedAt;
1033
- }
1034
- };
1035
- /**
1036
- * JSONL on disk. One line per record; first line is the `begin`, subsequent
1037
- * lines are `turn` records, terminal line is `halt`. Replays the whole file
1038
- * on `loadRun` — cheap for the conversation sizes this is designed for
1039
- * (thousands of turns, not millions). For huge runs, plug in a real DB
1040
- * adapter; the interface is small.
1041
- *
1042
- * Reads and appends over the shared append-only spine (`durable/jsonl-file`): each
1043
- * `appendTurn` / `recordHalt` finishes a short write and calls `fsync`, so a process
1044
- * crash between writes never loses an acknowledged turn, and a crash DURING one leaves
1045
- * an uncommitted final line that the next read skips and the next append truncates.
1046
- */
1047
- var FileConversationJournal = class {
1048
- path;
1049
- constructor(path) {
1050
- this.path = path;
1051
- }
1052
- async loadRun(runId) {
1053
- let entry;
1054
- for await (const record of readCommittedJsonLines(this.path, { allowMissing: true })) {
1055
- if (record.runId !== runId) continue;
1056
- if (record.kind === "begin") entry = {
1057
- runId,
1058
- startedAt: record.startedAt,
1059
- turns: []
1060
- };
1061
- else if (record.kind === "turn") {
1062
- if (!entry) throw new Error(`journal corrupted: turn record for runId '${runId}' precedes its begin record`);
1063
- entry.turns.push(record.turn);
1064
- } else if (record.kind === "halt") {
1065
- if (!entry) throw new Error(`journal corrupted: halt record for runId '${runId}' precedes its begin record`);
1066
- entry.halted = record.halted;
1067
- entry.endedAt = record.endedAt;
1068
- }
1069
- }
1070
- return entry;
1071
- }
1072
- async beginRun(runId, startedAt) {
1073
- const existing = await this.loadRun(runId);
1074
- if (existing) {
1075
- if (existing.startedAt !== startedAt) throw new Error(`runId '${runId}' already exists in ${this.path} with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`);
1076
- return;
1077
- }
1078
- await this.appendRecord({
1079
- kind: "begin",
1080
- runId,
1081
- startedAt
1082
- });
1083
- }
1084
- async appendTurn(runId, turn) {
1085
- await this.appendRecord({
1086
- kind: "turn",
1087
- runId,
1088
- turn
1089
- });
1090
- }
1091
- async recordHalt(runId, halt, endedAt) {
1092
- await this.appendRecord({
1093
- kind: "halt",
1094
- runId,
1095
- halted: halt,
1096
- endedAt
1097
- });
1098
- }
1099
- async appendRecord(record) {
1100
- const fs = await import("node:fs/promises");
1101
- const path = await import("node:path");
1102
- await fs.mkdir(path.dirname(this.path), { recursive: true });
1103
- const needsSeparator = await prepareJsonlAppend(this.path);
1104
- const fh = await fs.open(this.path, "a");
1105
- try {
1106
- await writeAllBytes(fh, `${needsSeparator ? "\n" : ""}${JSON.stringify(record)}\n`);
1107
- await fh.sync();
1108
- } finally {
1109
- await fh.close();
1110
- }
1111
- }
1112
- };
1113
- //#endregion
1114
- //#region src/conversation/journal-sql.ts
1115
- /**
1116
- * Adapt a Cloudflare D1 binding to the SqlAdapter shape. Lives here so D1
1117
- * consumers don't have to write the wrapper themselves; the runtime never
1118
- * imports `@cloudflare/workers-types` directly (peer-style typing).
1119
- */
1120
- function d1ToSqlAdapter(db) {
1121
- return {
1122
- async exec(sql, params = []) {
1123
- const stmt = db.prepare(sql);
1124
- const meta = (await (params.length > 0 ? stmt.bind(...params) : stmt).run()).meta;
1125
- return { rowsAffected: meta?.rows_written ?? meta?.changes ?? 0 };
1126
- },
1127
- async query(sql, params = []) {
1128
- const stmt = db.prepare(sql);
1129
- return (await (params.length > 0 ? stmt.bind(...params) : stmt).all()).results ?? [];
1130
- }
1131
- };
1132
- }
1133
- const RUNS_TABLE_DDL = (table) => `
1134
- CREATE TABLE IF NOT EXISTS ${table}_runs (
1135
- run_id TEXT PRIMARY KEY,
1136
- started_at TEXT NOT NULL,
1137
- halted_kind TEXT,
1138
- halted_payload TEXT,
1139
- ended_at TEXT
1140
- )
1141
- `;
1142
- const TURNS_TABLE_DDL = (table) => `
1143
- CREATE TABLE IF NOT EXISTS ${table}_turns (
1144
- run_id TEXT NOT NULL,
1145
- turn_index INTEGER NOT NULL,
1146
- payload TEXT NOT NULL,
1147
- PRIMARY KEY (run_id, turn_index)
1148
- )
1149
- `;
1150
- const TURNS_INDEX_DDL = (table) => `
1151
- CREATE INDEX IF NOT EXISTS idx_${table}_turns_run ON ${table}_turns (run_id, turn_index)
1152
- `;
1153
- /**
1154
- * SQL-backed ConversationJournal. Two tables — runs (one row per runId, holds
1155
- * start/halt timestamps + halt reason) and turns (one row per committed turn,
1156
- * payload is the ConversationTurn JSON). Replays the turns table on
1157
- * `loadRun` and writes append-only per `appendTurn`.
1158
- */
1159
- var SqlConversationJournal = class {
1160
- db;
1161
- table;
1162
- /**
1163
- * @param db SQL adapter (D1, postgres, sqlite, libSQL — all work)
1164
- * @param table Table-name prefix; the journal creates `${table}_runs` and
1165
- * `${table}_turns`. Lets multiple journals share a database
1166
- * without colliding (e.g. one per product surface).
1167
- */
1168
- constructor(db, table = "agent_runtime_journal") {
1169
- this.db = db;
1170
- this.table = table;
1171
- }
1172
- /**
1173
- * Create the journal's tables if absent. Idempotent. Call once at deploy
1174
- * (or at app boot) — running on every request is harmless but adds latency.
1175
- */
1176
- async migrate() {
1177
- await this.db.exec(RUNS_TABLE_DDL(this.table));
1178
- await this.db.exec(TURNS_TABLE_DDL(this.table));
1179
- await this.db.exec(TURNS_INDEX_DDL(this.table));
1180
- }
1181
- async loadRun(runId) {
1182
- const row = (await this.db.query(`SELECT run_id, started_at, halted_kind, halted_payload, ended_at FROM ${this.table}_runs WHERE run_id = ?`, [runId]))[0];
1183
- if (!row) return void 0;
1184
- const turns = await this.db.query(`SELECT payload, turn_index FROM ${this.table}_turns WHERE run_id = ? ORDER BY turn_index ASC`, [runId]);
1185
- return {
1186
- runId: row.run_id,
1187
- startedAt: row.started_at,
1188
- halted: row.halted_payload ? JSON.parse(row.halted_payload) : void 0,
1189
- endedAt: row.ended_at ?? void 0,
1190
- turns: turns.map((t) => JSON.parse(t.payload))
1191
- };
1192
- }
1193
- async beginRun(runId, startedAt) {
1194
- const existing = await this.db.query(`SELECT started_at FROM ${this.table}_runs WHERE run_id = ?`, [runId]);
1195
- if (existing.length > 0) {
1196
- if (existing[0]?.started_at !== startedAt) throw new Error(`runId '${runId}' already exists with startedAt=${existing[0]?.started_at}; refusing to overwrite with ${startedAt}`);
1197
- return;
1198
- }
1199
- await this.db.exec(`INSERT INTO ${this.table}_runs (run_id, started_at) VALUES (?, ?)`, [runId, startedAt]);
1200
- }
1201
- async appendTurn(runId, turn) {
1202
- const halted = await this.db.query(`SELECT halted_kind FROM ${this.table}_runs WHERE run_id = ?`, [runId]);
1203
- if (halted.length === 0) throw new Error(`appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`);
1204
- if (halted[0]?.halted_kind) throw new Error(`cannot append turn to halted run '${runId}' (halt kind: ${halted[0]?.halted_kind})`);
1205
- await this.db.exec(`INSERT INTO ${this.table}_turns (run_id, turn_index, payload) VALUES (?, ?, ?)`, [
1206
- runId,
1207
- turn.index,
1208
- JSON.stringify(turn)
1209
- ]);
1210
- }
1211
- async recordHalt(runId, halt, endedAt) {
1212
- if ((await this.db.exec(`UPDATE ${this.table}_runs SET halted_kind = ?, halted_payload = ?, ended_at = ? WHERE run_id = ?`, [
1213
- halt.kind,
1214
- JSON.stringify(halt),
1215
- endedAt,
1216
- runId
1217
- ])).rowsAffected === 0) throw new Error(`recordHalt called for unknown runId '${runId}'`);
1218
- }
1219
- };
1220
- //#endregion
1221
927
  //#region src/conversation/run-persona.ts
1222
928
  /** Adapt one exact profile + Runtime executor into the conversation stream protocol. */
1223
929
  function profileRuntimeBackend(profile, factory, counter) {
@@ -1347,6 +1053,26 @@ function runPersonaDispatch(config) {
1347
1053
  };
1348
1054
  }
1349
1055
  //#endregion
1056
+ //#region src/durable/sql-adapter.ts
1057
+ /**
1058
+ * Adapt a Cloudflare D1 binding to the SqlAdapter shape. Lives here so D1
1059
+ * consumers don't have to write the wrapper themselves; the runtime never
1060
+ * imports `@cloudflare/workers-types` directly (peer-style typing).
1061
+ */
1062
+ function d1ToSqlAdapter(db) {
1063
+ return {
1064
+ async exec(sql, params = []) {
1065
+ const stmt = db.prepare(sql);
1066
+ const meta = (await (params.length > 0 ? stmt.bind(...params) : stmt).run()).meta;
1067
+ return { rowsAffected: meta?.rows_written ?? meta?.changes ?? 0 };
1068
+ },
1069
+ async query(sql, params = []) {
1070
+ const stmt = db.prepare(sql);
1071
+ return (await (params.length > 0 ? stmt.bind(...params) : stmt).all()).results ?? [];
1072
+ }
1073
+ };
1074
+ }
1075
+ //#endregion
1350
1076
  //#region src/improvement/build-prompts.ts
1351
1077
  /** Render findings as the ranked-evidence block every build prompt ends with. */
1352
1078
  function findingLines(findings) {
@@ -1943,6 +1669,183 @@ function applyPatches(edits, cwd) {
1943
1669
  if (result.status !== 0) throw new Error(`reflectiveGenerator: patch batch failed: ${result.stderr.trim()}`);
1944
1670
  }
1945
1671
  //#endregion
1672
+ //#region src/improvement/reflective-profile-proposer.ts
1673
+ const OPERATOR = {
1674
+ draft: "OPERATOR: draft. Write a substantially different approach from the parent below, not an edit of it.",
1675
+ improve: "OPERATOR: improve. Edit the parent below to fix its dominant failure mode; keep what already works.",
1676
+ debug: "OPERATOR: debug. The parent below failed as a defect (crashes, no answer, a broken format). Fix the cause.",
1677
+ merge: "OPERATOR: merge. Combine the strengths of the parents below into one surface."
1678
+ };
1679
+ /** Build the maintained reflective proposer for a profile text surface. */
1680
+ function reflectiveProfileProposer(options) {
1681
+ const kind = options.kind ?? "reflective-profile";
1682
+ const maxOutputTokens = options.maxOutputTokens ?? 16e3;
1683
+ const maxSurfaceChars = options.maxSurfaceChars ?? 12e3;
1684
+ if (!kind.trim() || kind.trim() !== kind) throw new ConfigError("reflectiveProfileProposer(): kind must be a trimmed non-empty string");
1685
+ if (!options.model?.trim()) throw new ConfigError("reflectiveProfileProposer(): model is required");
1686
+ if (typeof options.chat !== "function") throw new ConfigError("reflectiveProfileProposer(): chat must be a function");
1687
+ if (!options.frame?.trim()) throw new ConfigError("reflectiveProfileProposer(): frame is required");
1688
+ for (const [name, value] of [["maxOutputTokens", maxOutputTokens], ["maxSurfaceChars", maxSurfaceChars]]) if (!Number.isSafeInteger(value) || value < 1) throw new ConfigError(`reflectiveProfileProposer(): ${name} must be a positive integer`);
1689
+ const evidenceOf = options.evidence ?? defaultEvidence;
1690
+ return {
1691
+ kind,
1692
+ async propose(ctx) {
1693
+ if (!ctx.costLedger) throw new ConfigError("reflectiveProfileProposer(): the proposal has no cost ledger; run it through improve() with searchMethod");
1694
+ const parents = (ctx.parents ?? [{
1695
+ nodeId: null,
1696
+ artifact: ctx.currentSurface
1697
+ }]).map((parent) => ({
1698
+ nodeId: parent.nodeId,
1699
+ surface: parent.artifact,
1700
+ trainCells: parent.nodeId && ctx.train ? [...ctx.train.scoredCells(parent.nodeId)] : []
1701
+ }));
1702
+ const shape = surfaceShape(ctx.currentSurface);
1703
+ const sections = [];
1704
+ for (const [index, parent] of parents.entries()) {
1705
+ const evidence = await evidenceOf(parent);
1706
+ sections.push([
1707
+ `## Parent ${index + 1}${parent.nodeId ? ` (${parent.nodeId})` : ""}: its current surface`,
1708
+ renderSurface(parent.surface),
1709
+ `## Parent ${index + 1}: its train results (${parent.trainCells.length} scored cells)`,
1710
+ ...evidence
1711
+ ].join("\n"));
1712
+ }
1713
+ const system = [
1714
+ optimizerMethod,
1715
+ "",
1716
+ options.frame.trim(),
1717
+ "",
1718
+ outputContract(shape, maxSurfaceChars)
1719
+ ].join("\n");
1720
+ const user = [
1721
+ OPERATOR[ctx.operator ?? "improve"],
1722
+ "",
1723
+ ...sections,
1724
+ "",
1725
+ "## The search so far (train split only)",
1726
+ ctx.summary?.trim() || "(nothing measured yet)"
1727
+ ].join("\n");
1728
+ const messages = [{
1729
+ role: "system",
1730
+ content: system
1731
+ }, {
1732
+ role: "user",
1733
+ content: user
1734
+ }];
1735
+ const inputTokens = messages.reduce((total, message) => total + Buffer.byteLength(message.content, "utf8"), 0) + 16 * messages.length;
1736
+ const paid = await ctx.costLedger.runPaidCall({
1737
+ channel: "proposer",
1738
+ phase: ctx.costPhase ?? "proposal",
1739
+ actor: kind,
1740
+ model: options.model,
1741
+ signal: ctx.signal,
1742
+ maximumCharge: {
1743
+ customTokenPricing: options.pricing,
1744
+ inputTokens,
1745
+ outputTokens: maxOutputTokens
1746
+ },
1747
+ execute: (signal, callId) => options.chat({
1748
+ messages,
1749
+ maxOutputTokens,
1750
+ callId,
1751
+ signal
1752
+ }),
1753
+ receipt: (reply) => reply.usage === null ? {
1754
+ model: reply.model ?? options.model,
1755
+ inputTokens: 0,
1756
+ outputTokens: 0,
1757
+ costUnknown: true,
1758
+ usageUnknown: true
1759
+ } : {
1760
+ model: reply.model ?? options.model,
1761
+ inputTokens: reply.usage.inputTokens,
1762
+ outputTokens: reply.usage.outputTokens,
1763
+ ...reply.usage.reasoningTokens === void 0 ? {} : { reasoningTokens: reply.usage.reasoningTokens },
1764
+ ...reply.usage.cachedTokens === void 0 ? {} : { cachedTokens: reply.usage.cachedTokens },
1765
+ customTokenPricing: options.pricing
1766
+ }
1767
+ });
1768
+ if (!paid.succeeded) throw paid.error;
1769
+ const proposal = parseProposal(paid.value.content, shape, maxSurfaceChars);
1770
+ return proposal === null ? [] : [proposal];
1771
+ }
1772
+ };
1773
+ }
1774
+ function surfaceShape(surface) {
1775
+ if (typeof surface === "string") return { kind: "text" };
1776
+ if (surface.kind === "components") return {
1777
+ kind: "components",
1778
+ names: Object.keys(surface.components).sort()
1779
+ };
1780
+ throw new ConfigError("reflectiveProfileProposer(): a code surface is improved through worktrees, not a text proposer");
1781
+ }
1782
+ function renderSurface(surface) {
1783
+ if (typeof surface === "string") return [
1784
+ "\"\"\"",
1785
+ surface,
1786
+ "\"\"\""
1787
+ ].join("\n");
1788
+ if (surface.kind !== "components") return "(a code surface)";
1789
+ return Object.keys(surface.components).sort().map((name) => [
1790
+ `### Component ${name}`,
1791
+ "\"\"\"",
1792
+ surface.components[name],
1793
+ "\"\"\""
1794
+ ].join("\n")).join("\n");
1795
+ }
1796
+ function outputContract(shape, maxChars) {
1797
+ return [
1798
+ "OUTPUT. Reply with one JSON object and nothing else:",
1799
+ `{"label": "<at most 8 words naming the change>", "hypothesis": "<the dominant failure mode, the mechanism, and the predicted effect on the score>", ${shape.kind === "text" ? "\"surface\": \"<the complete new text>\"" : `"surface": { ${shape.names.map((name) => `"${name}": "<its complete new text>"`).join(", ")} }`}}`,
1800
+ shape.kind === "text" ? `The surface must stand alone, at most ${maxChars} characters: the agent sees nothing else from you.` : `Return every component, each complete, at most ${maxChars} characters in all: the agent sees nothing else from you.`
1801
+ ].join("\n");
1802
+ }
1803
+ /** The proposal in a reply: the whole reply as JSON, else its outermost {...} span. */
1804
+ function parseProposal(content, shape, maxChars) {
1805
+ const start = content.indexOf("{");
1806
+ const end = content.lastIndexOf("}");
1807
+ for (const text of [content, start >= 0 && end > start ? content.slice(start, end + 1) : ""]) {
1808
+ let value;
1809
+ try {
1810
+ value = JSON.parse(text);
1811
+ } catch {
1812
+ continue;
1813
+ }
1814
+ if (typeof value !== "object" || value === null) continue;
1815
+ const { label, hypothesis, surface } = value;
1816
+ const parsed = surfaceOf(surface, shape, maxChars);
1817
+ if (parsed === null) continue;
1818
+ return {
1819
+ surface: parsed,
1820
+ label: String(label ?? "").slice(0, 80),
1821
+ rationale: String(hypothesis ?? "").slice(0, 4e3)
1822
+ };
1823
+ }
1824
+ return null;
1825
+ }
1826
+ function surfaceOf(value, shape, maxChars) {
1827
+ if (shape.kind === "text") return typeof value === "string" && value.trim() && value.length <= maxChars ? value : null;
1828
+ if (typeof value !== "object" || value === null) return null;
1829
+ const record = value;
1830
+ const names = Object.keys(record).sort();
1831
+ if (names.join("\n") !== shape.names.join("\n")) return null;
1832
+ let total = 0;
1833
+ const components = {};
1834
+ for (const name of names) {
1835
+ const text = record[name];
1836
+ if (typeof text !== "string" || !text.trim()) return null;
1837
+ total += text.length;
1838
+ components[name] = text;
1839
+ }
1840
+ return total <= maxChars ? {
1841
+ kind: "components",
1842
+ components
1843
+ } : null;
1844
+ }
1845
+ function defaultEvidence(parent) {
1846
+ return parent.trainCells.map((cell) => `- train unit ${cell.unitId}: score ${cell.score}`);
1847
+ }
1848
+ //#endregion
1946
1849
  //#region src/knowledge/activation.ts
1947
1850
  /** Apply or restore one local knowledge candidate through the shared activation contract. */
1948
1851
  function createKnowledgeImprovementActivationExecutor(options) {
@@ -3183,6 +3086,6 @@ function stripNewlines(value) {
3183
3086
  return value.replace(/[\r\n]/g, " ");
3184
3087
  }
3185
3088
  //#endregion
3186
- export { AgentEvalError, BackendTransportError, ConfigError, DEFAULT_ROUTER_BASE_URL, DELEGATED_LOOP_MODES, FileConversationJournal, InMemoryConversationJournal, InMemoryRuntimeSessionStore, JudgeError, NotFoundError, OfficialOptimizerUnavailableError, PROMPT_INSTRUCTION_COMPONENT_PREFIX, PlannerError, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, ROLLOUT_POLICY_EXTENSION, RetainedInteractiveAdmissionError, RetainedInteractiveBindingError, RetainedRunAdmissionError, RetainedRunDispatchBindingError, RuntimeRunStateError, SearchEnvironmentFault, SqlConversationJournal, ValidationError, agenticGenerator, applyRolloutPolicyToProfile, applyRunRecordDefaults, auditLoopRunner, buildKnowledgeImprovementExperimentBundles, buildLoopOtelSpans, buildLoopSpanNodes, buildRuntimeEventOtelSpans, cleanModelId, commandVerifier, composeRuntimeHooks, createAgentKnowledgeReadinessCheck, createCommandProfileTrainer, createConversationBackend, createIterableBackend, createKnowledgeImprovementActivationExecutor, createOpenInferenceFileExporter, createOtelExporter, createProfileExecutionBackend, createProfileImprovementHarness, createRuntimeEventCollector, createRuntimeStreamEventCollector, createSandboxPromptBackend, createSupervisedKnowledgeUpdater, d1ToSqlAdapter, decideKnowledgeReadiness, dedicatedLane, defaultBuildPrompt, defineConversation, defineRuntimeHooks, findingLines, formatSupervisedKnowledgeTask, generateSpanId, getModels, improve, isDelegatedLoopMode, isSearchEnvironmentFault, isolatedCheckBoxEvidenceSchema, isolatedCheckResultSchema, knowledgeReadinessDeliverable, loopEventToOtelSpan, mcpBuildPrompt, mcpServeVerifier, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, normalizeRolloutPolicy, notifyRuntimeDecisionPoint, notifyRuntimeHookEvent, officialGepa, officialSkillOpt, optimizerMethod, padSpanId, padTraceId, parseLoopRunnerArgv, parseRolloutPolicy, promptInstructionsProfileComponents, rawTraceDistiller, readinessServerSentEvent, reflectiveGenerator, researchLoopRunner, resolveChatModel, resolveRouterBaseUrl, routerLane, runAgentTask, runAgentTaskStream, runConversation, runConversationStream, runDelegatedLoop, runKnowledgeImprovementJob, runLoopRunnerCli, runPersonaConversation, runPersonaDispatch, runSupervisedKnowledgeUpdate, runtimeStreamServerSentEvent, sanitizeAgentRuntimeEvent, sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent, searchMethod, serializeRolloutPolicy, sharedBoxLane, startRuntimeRun, strategyAuthorMethod, structuralRolloutPolicyFromProfile, subscriptionLane, toOtelAttributes, toolBuildPrompt, validateChatModelId, worktreeLoopRunner };
3089
+ export { AgentEvalError, BackendTransportError, ConfigError, DEFAULT_ROUTER_BASE_URL, DELEGATED_LOOP_MODES, InMemoryRuntimeSessionStore, JudgeError, NotFoundError, OfficialOptimizerUnavailableError, PROMPT_INSTRUCTION_COMPONENT_PREFIX, PlannerError, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, ROLLOUT_POLICY_EXTENSION, RetainedInteractiveAdmissionError, RetainedInteractiveBindingError, RetainedRunAdmissionError, RetainedRunDispatchBindingError, RuntimeRunStateError, SearchEnvironmentFault, ValidationError, agenticGenerator, applyRolloutPolicyToProfile, applyRunRecordDefaults, auditLoopRunner, buildKnowledgeImprovementExperimentBundles, buildLoopOtelSpans, buildLoopSpanNodes, buildRuntimeEventOtelSpans, cleanModelId, commandVerifier, composeRuntimeHooks, createAgentKnowledgeReadinessCheck, createCommandProfileTrainer, createConversationBackend, createIterableBackend, createKnowledgeImprovementActivationExecutor, createOpenInferenceFileExporter, createOtelExporter, createProfileExecutionBackend, createProfileImprovementHarness, createRuntimeEventCollector, createRuntimeStreamEventCollector, createSandboxPromptBackend, createSupervisedKnowledgeUpdater, d1ToSqlAdapter, decideKnowledgeReadiness, decideSearchImprovement, dedicatedLane, defaultBuildPrompt, defineConversation, defineRuntimeHooks, findingLines, formatSupervisedKnowledgeTask, generateSpanId, getModels, improve, isDelegatedLoopMode, isSearchEnvironmentFault, isolatedCheckBoxEvidenceSchema, isolatedCheckResultSchema, knowledgeReadinessDeliverable, loopEventToOtelSpan, mcpBuildPrompt, mcpServeVerifier, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, normalizeRolloutPolicy, notifyRuntimeDecisionPoint, notifyRuntimeHookEvent, officialGepa, officialSkillOpt, optimizerMethod, padSpanId, padTraceId, parseLoopRunnerArgv, parseRolloutPolicy, promptInstructionsProfileComponents, rawTraceDistiller, readinessServerSentEvent, reflectiveGenerator, reflectiveProfileProposer, researchLoopRunner, resolveChatModel, resolveRouterBaseUrl, routerLane, runAgentTask, runAgentTaskStream, runConversation, runConversationStream, runDelegatedLoop, runKnowledgeImprovementJob, runLoopRunnerCli, runPersonaConversation, runPersonaDispatch, runSupervisedKnowledgeUpdate, runtimeStreamServerSentEvent, sanitizeAgentRuntimeEvent, sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent, searchMethod, serializeRolloutPolicy, sharedBoxLane, startRuntimeRun, strategyAuthorMethod, structuralRolloutPolicyFromProfile, subscriptionLane, toOtelAttributes, toolBuildPrompt, validateChatModelId, worktreeLoopRunner };
3187
3090
 
3188
3091
  //# sourceMappingURL=index.js.map