@tangle-network/agent-runtime 0.104.0 → 0.106.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 (217) hide show
  1. package/README.md +176 -42
  2. package/dist/activation-CRjVfOiy.js +203 -0
  3. package/dist/activation-CRjVfOiy.js.map +1 -0
  4. package/dist/activation-DyWB0K6E.d.ts +98 -0
  5. package/dist/agent.d.ts +216 -234
  6. package/dist/agent.js +615 -547
  7. package/dist/agent.js.map +1 -1
  8. package/dist/analyst-loop-DGdtVENg.js +517 -0
  9. package/dist/analyst-loop-DGdtVENg.js.map +1 -0
  10. package/dist/analyst-loop.d.ts +10 -43
  11. package/dist/analyst-loop.js +2 -11
  12. package/dist/backends-Dy8NujB4.js +713 -0
  13. package/dist/backends-Dy8NujB4.js.map +1 -0
  14. package/dist/candidate-execution/index.d.ts +4 -192
  15. package/dist/candidate-execution/index.js +5 -66
  16. package/dist/candidate-execution-DqMbv1rU.js +488 -0
  17. package/dist/candidate-execution-DqMbv1rU.js.map +1 -0
  18. package/dist/coder-yhVWbdWc.js +40 -0
  19. package/dist/coder-yhVWbdWc.js.map +1 -0
  20. package/dist/conversation-XucG_K3l.js +1265 -0
  21. package/dist/conversation-XucG_K3l.js.map +1 -0
  22. package/dist/conversation.d.ts +2 -804
  23. package/dist/conversation.js +2 -55
  24. package/dist/environment-provider-CfLUmKmf.js +1168 -0
  25. package/dist/environment-provider-CfLUmKmf.js.map +1 -0
  26. package/dist/environment-provider-IUGU3epE.d.ts +964 -0
  27. package/dist/environment-provider.d.ts +2 -78
  28. package/dist/environment-provider.js +2 -18
  29. package/dist/errors-DEAvWQPy.js +111 -0
  30. package/dist/errors-DEAvWQPy.js.map +1 -0
  31. package/dist/improvement-adapter-Cr5TBSji.d.ts +166 -0
  32. package/dist/improvement-cycle-C095kS_g.js +2624 -0
  33. package/dist/improvement-cycle-C095kS_g.js.map +1 -0
  34. package/dist/index-BGdxAwfO.d.ts +838 -0
  35. package/dist/index-C-FYUuFG.d.ts +193 -0
  36. package/dist/index-CbNM40xG.d.ts +140 -0
  37. package/dist/index-DruSKs3Z.d.ts +7224 -0
  38. package/dist/index-Efjb3nrQ.d.ts +671 -0
  39. package/dist/index.d.ts +14 -1134
  40. package/dist/index.js +2134 -1972
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +776 -888
  43. package/dist/intelligence.js +1466 -1410
  44. package/dist/intelligence.js.map +1 -1
  45. package/dist/{kb-gate-CwHO0vz6.d.ts → kb-gate-C8z2juK8.d.ts} +33 -31
  46. package/dist/kb-gate-DpaSwXVx.js +80 -0
  47. package/dist/kb-gate-DpaSwXVx.js.map +1 -0
  48. package/dist/knowledge-Ku-mPP4f.js +433 -0
  49. package/dist/knowledge-Ku-mPP4f.js.map +1 -0
  50. package/dist/knowledge.d.ts +2 -150
  51. package/dist/knowledge.js +2 -40
  52. package/dist/local-harness-Dh8PJ0ot.d.ts +455 -0
  53. package/dist/loop-runner-bin-BXsFEUcf.d.ts +162 -0
  54. package/dist/loop-runner-bin-BwjQ1NfH.js +268 -0
  55. package/dist/loop-runner-bin-BwjQ1NfH.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -17
  57. package/dist/loop-runner-bin.js +2 -24
  58. package/dist/loops.d.ts +5 -4164
  59. package/dist/loops.js +8 -419
  60. package/dist/mcp/bin.d.ts +1 -1
  61. package/dist/mcp/bin.js +116 -146
  62. package/dist/mcp/bin.js.map +1 -1
  63. package/dist/mcp/index.d.ts +295 -437
  64. package/dist/mcp/index.js +1242 -1177
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/memory-bin.d.ts +1 -1
  67. package/dist/mcp/memory-bin.js +37 -16
  68. package/dist/mcp/memory-bin.js.map +1 -1
  69. package/dist/memory-server-DL6cE2Ag.js +234 -0
  70. package/dist/memory-server-DL6cE2Ag.js.map +1 -0
  71. package/dist/model-resolution-Btd9iIKV.js +98 -0
  72. package/dist/model-resolution-Btd9iIKV.js.map +1 -0
  73. package/dist/openai-tools-B68JaOCx.d.ts +24 -0
  74. package/dist/openai-tools-CKLy1C7M.js +44 -0
  75. package/dist/openai-tools-CKLy1C7M.js.map +1 -0
  76. package/dist/otel-export-D34IQW1C.js +843 -0
  77. package/dist/otel-export-D34IQW1C.js.map +1 -0
  78. package/dist/platform.d.ts +188 -185
  79. package/dist/platform.js +185 -218
  80. package/dist/platform.js.map +1 -1
  81. package/dist/prepare-B53sPV7M.js +4292 -0
  82. package/dist/prepare-B53sPV7M.js.map +1 -0
  83. package/dist/primeintellect/index.d.ts +150 -147
  84. package/dist/primeintellect/index.js +626 -1004
  85. package/dist/primeintellect/index.js.map +1 -1
  86. package/dist/profiles.d.ts +296 -490
  87. package/dist/profiles.js +722 -749
  88. package/dist/profiles.js.map +1 -1
  89. package/dist/protected-model-port-BLPH5VVv.js +722 -0
  90. package/dist/protected-model-port-BLPH5VVv.js.map +1 -0
  91. package/dist/protected-model-port-BP6Z4eau.d.ts +283 -0
  92. package/dist/protected-redaction--F3v1oo8.js +200 -0
  93. package/dist/protected-redaction--F3v1oo8.js.map +1 -0
  94. package/dist/redact-D-u-rrcn.js +82 -0
  95. package/dist/redact-D-u-rrcn.js.map +1 -0
  96. package/dist/redact-kbIOjfjM.d.ts +452 -0
  97. package/dist/researcher-CoVqNhfI.js +433 -0
  98. package/dist/researcher-CoVqNhfI.js.map +1 -0
  99. package/dist/runtime-BG0BziaP.js +5408 -0
  100. package/dist/runtime-BG0BziaP.js.map +1 -0
  101. package/dist/sandbox-events-DeI5xX8P.js +316 -0
  102. package/dist/sandbox-events-DeI5xX8P.js.map +1 -0
  103. package/dist/spawn-journal-CwPvKUTa.js +456 -0
  104. package/dist/spawn-journal-CwPvKUTa.js.map +1 -0
  105. package/dist/structural-rollout-IXUEplky.js +1445 -0
  106. package/dist/structural-rollout-IXUEplky.js.map +1 -0
  107. package/dist/substrate-B0TYNrXn.js +27 -0
  108. package/dist/substrate-B0TYNrXn.js.map +1 -0
  109. package/dist/{substrate-Dyiqmd3o.d.ts → substrate-BcnuSHXm.d.ts} +57 -54
  110. package/dist/supervise-BiRutHS9.js +7321 -0
  111. package/dist/supervise-BiRutHS9.js.map +1 -0
  112. package/dist/supervisor-DTKhF-RV.js +3826 -0
  113. package/dist/supervisor-DTKhF-RV.js.map +1 -0
  114. package/dist/testing.d.ts +4 -3
  115. package/dist/testing.js +2478 -2637
  116. package/dist/testing.js.map +1 -1
  117. package/dist/tool-server-RcWgLIsL.js +141 -0
  118. package/dist/tool-server-RcWgLIsL.js.map +1 -0
  119. package/dist/trace-propagation-CJJC7SVB.js +57 -0
  120. package/dist/trace-propagation-CJJC7SVB.js.map +1 -0
  121. package/dist/types-BaIpb0XT.d.ts +492 -0
  122. package/dist/types-BevOjfTY.d.ts +765 -0
  123. package/dist/types-C9j4qg6l.d.ts +500 -0
  124. package/dist/types-Cja5OTGh.d.ts +190 -0
  125. package/dist/util-MVgdwuIS.js +145 -0
  126. package/dist/util-MVgdwuIS.js.map +1 -0
  127. package/dist/workspace-archive-BosQiotA.js +575 -0
  128. package/dist/workspace-archive-BosQiotA.js.map +1 -0
  129. package/package.json +43 -55
  130. package/skills/build-with-agent-runtime/SKILL.md +16 -9
  131. package/skills/loop-writer/SKILL.md +1 -1
  132. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  133. package/dist/analyst-loop.js.map +0 -1
  134. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  135. package/dist/candidate-execution/index.js.map +0 -1
  136. package/dist/chunk-2KGAN2HM.js +0 -1256
  137. package/dist/chunk-2KGAN2HM.js.map +0 -1
  138. package/dist/chunk-2QJSNOGK.js +0 -48
  139. package/dist/chunk-2QJSNOGK.js.map +0 -1
  140. package/dist/chunk-2UABGGUB.js +0 -474
  141. package/dist/chunk-2UABGGUB.js.map +0 -1
  142. package/dist/chunk-2VZYRB55.js +0 -834
  143. package/dist/chunk-2VZYRB55.js.map +0 -1
  144. package/dist/chunk-2X65HYMI.js +0 -3526
  145. package/dist/chunk-2X65HYMI.js.map +0 -1
  146. package/dist/chunk-3MDZX7YU.js +0 -125
  147. package/dist/chunk-3MDZX7YU.js.map +0 -1
  148. package/dist/chunk-3PPVCS75.js +0 -199
  149. package/dist/chunk-3PPVCS75.js.map +0 -1
  150. package/dist/chunk-5HNDYWUT.js +0 -6424
  151. package/dist/chunk-5HNDYWUT.js.map +0 -1
  152. package/dist/chunk-5IBQAPVB.js +0 -29
  153. package/dist/chunk-5IBQAPVB.js.map +0 -1
  154. package/dist/chunk-5QOB7H74.js +0 -387
  155. package/dist/chunk-5QOB7H74.js.map +0 -1
  156. package/dist/chunk-ATDFUJYI.js +0 -4728
  157. package/dist/chunk-ATDFUJYI.js.map +0 -1
  158. package/dist/chunk-B7K7V22Y.js +0 -699
  159. package/dist/chunk-B7K7V22Y.js.map +0 -1
  160. package/dist/chunk-DPEUKJRO.js +0 -27
  161. package/dist/chunk-DPEUKJRO.js.map +0 -1
  162. package/dist/chunk-FD2MBMOH.js +0 -494
  163. package/dist/chunk-FD2MBMOH.js.map +0 -1
  164. package/dist/chunk-FJI3EXU3.js +0 -2402
  165. package/dist/chunk-FJI3EXU3.js.map +0 -1
  166. package/dist/chunk-HAO4CXHP.js +0 -200
  167. package/dist/chunk-HAO4CXHP.js.map +0 -1
  168. package/dist/chunk-ISPWRSEC.js +0 -408
  169. package/dist/chunk-ISPWRSEC.js.map +0 -1
  170. package/dist/chunk-KRBFHMV6.js +0 -1228
  171. package/dist/chunk-KRBFHMV6.js.map +0 -1
  172. package/dist/chunk-L5DST3QC.js +0 -351
  173. package/dist/chunk-L5DST3QC.js.map +0 -1
  174. package/dist/chunk-M22PL4GH.js +0 -171
  175. package/dist/chunk-M22PL4GH.js.map +0 -1
  176. package/dist/chunk-NURIQBJQ.js +0 -72
  177. package/dist/chunk-NURIQBJQ.js.map +0 -1
  178. package/dist/chunk-PZZKQVQV.js +0 -52
  179. package/dist/chunk-PZZKQVQV.js.map +0 -1
  180. package/dist/chunk-Q2JSAVQ3.js +0 -671
  181. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  182. package/dist/chunk-SBTWKPVR.js +0 -5576
  183. package/dist/chunk-SBTWKPVR.js.map +0 -1
  184. package/dist/chunk-SGKPNBXE.js +0 -60
  185. package/dist/chunk-SGKPNBXE.js.map +0 -1
  186. package/dist/chunk-SNSMRT6H.js +0 -680
  187. package/dist/chunk-SNSMRT6H.js.map +0 -1
  188. package/dist/chunk-STJEHM5F.js +0 -1338
  189. package/dist/chunk-STJEHM5F.js.map +0 -1
  190. package/dist/chunk-UPWGXKXB.js +0 -254
  191. package/dist/chunk-UPWGXKXB.js.map +0 -1
  192. package/dist/chunk-YEJR7IXO.js +0 -68
  193. package/dist/chunk-YEJR7IXO.js.map +0 -1
  194. package/dist/chunk-ZXICDSAK.js +0 -907
  195. package/dist/chunk-ZXICDSAK.js.map +0 -1
  196. package/dist/completion-gate-Bv47cOnn.d.ts +0 -256
  197. package/dist/conversation.js.map +0 -1
  198. package/dist/coordination-CxtzMxSM.d.ts +0 -2570
  199. package/dist/environment-provider.js.map +0 -1
  200. package/dist/improve--2A0gK1-.d.ts +0 -440
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-CtK9dSny.d.ts +0 -175
  204. package/dist/loop-runner-bin-DUOGtvOl.d.ts +0 -207
  205. package/dist/loop-runner-bin.js.map +0 -1
  206. package/dist/loops.js.map +0 -1
  207. package/dist/openai-tools-fnj6SRVg.d.ts +0 -46
  208. package/dist/protected-model-port-DzkUY3HQ.d.ts +0 -271
  209. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  210. package/dist/structural-rollout-C4mabf87.d.ts +0 -446
  211. package/dist/supervise-7q9F5brx.d.ts +0 -379
  212. package/dist/types-BCoemcXU.d.ts +0 -802
  213. package/dist/types-BwoZWq-i.d.ts +0 -510
  214. package/dist/types-Cbp72qyu.d.ts +0 -491
  215. package/dist/types-CmYCMbFT.d.ts +0 -203
  216. package/dist/types-CvNwMzQt.d.ts +0 -957
  217. package/dist/worktree-fanout-WsOzt8qu.d.ts +0 -999
@@ -1,1256 +0,0 @@
1
- import {
2
- InMemoryRuntimeSessionStore,
3
- createIterableBackend,
4
- newRuntimeSession,
5
- nowIso,
6
- startOrResumeRuntimeSession
7
- } from "./chunk-Q2JSAVQ3.js";
8
- import {
9
- BackendTransportError,
10
- ValidationError
11
- } from "./chunk-YEJR7IXO.js";
12
-
13
- // src/conversation/call-policy.ts
14
- var CircuitOpenError = class extends Error {
15
- constructor(participant, retryAfterMs) {
16
- super(
17
- `circuit open for participant '${participant}'; ${retryAfterMs}ms remaining before retry allowed`
18
- );
19
- this.name = "CircuitOpenError";
20
- }
21
- };
22
- var DeadlineExceededError = class extends Error {
23
- constructor(deadlineMs) {
24
- super(`backend call exceeded per-attempt deadline of ${deadlineMs}ms`);
25
- this.name = "DeadlineExceededError";
26
- }
27
- };
28
- var defaultIsRetryable = (err) => {
29
- if (err instanceof DeadlineExceededError) return true;
30
- if (err instanceof Error) {
31
- const name = err.name;
32
- const message = err.message.toLowerCase();
33
- if (name === "AbortError" || name === "TimeoutError") return true;
34
- if (message.includes("econnreset") || message.includes("etimedout") || message.includes("econnrefused") || message.includes("socket hang up") || message.includes("network") || message.includes("fetch failed")) {
35
- return true;
36
- }
37
- }
38
- return false;
39
- };
40
- var CircuitBreakerState = class {
41
- constructor(config) {
42
- this.config = config;
43
- }
44
- config;
45
- consecutiveFailures = 0;
46
- openedAt;
47
- /**
48
- * Check whether the next call is allowed. Throws `CircuitOpenError` when
49
- * the breaker is open and the cooldown hasn't elapsed.
50
- */
51
- preflight(participant, now = Date.now()) {
52
- if (!this.config || this.openedAt === void 0) return;
53
- const remaining = this.config.cooldownMs - (now - this.openedAt);
54
- if (remaining > 0) {
55
- throw new CircuitOpenError(participant, remaining);
56
- }
57
- this.openedAt = void 0;
58
- this.consecutiveFailures = 0;
59
- }
60
- recordSuccess() {
61
- this.consecutiveFailures = 0;
62
- this.openedAt = void 0;
63
- }
64
- recordFailure(now = Date.now()) {
65
- if (!this.config) return;
66
- this.consecutiveFailures += 1;
67
- if (this.consecutiveFailures >= this.config.failuresToOpen) {
68
- this.openedAt = now;
69
- }
70
- }
71
- };
72
- function makePerAttemptSignal(parentSignal, deadlineMs) {
73
- const controller = new AbortController();
74
- let deadlineError;
75
- const cleanups = [];
76
- if (parentSignal) {
77
- if (parentSignal.aborted) controller.abort(parentSignal.reason);
78
- else {
79
- const onAbort = () => controller.abort(parentSignal.reason);
80
- parentSignal.addEventListener("abort", onAbort, { once: true });
81
- cleanups.push(() => parentSignal.removeEventListener("abort", onAbort));
82
- }
83
- }
84
- if (deadlineMs !== void 0) {
85
- const ms = deadlineMs;
86
- const timer = setTimeout(() => {
87
- deadlineError = new DeadlineExceededError(ms);
88
- controller.abort(deadlineError);
89
- }, ms);
90
- cleanups.push(() => clearTimeout(timer));
91
- }
92
- return {
93
- signal: controller.signal,
94
- dispose() {
95
- for (const c of cleanups) c();
96
- },
97
- getDeadlineError() {
98
- return deadlineError;
99
- }
100
- };
101
- }
102
- function computeBackoff(spec, attempt) {
103
- if (spec === void 0) {
104
- const base = 250;
105
- const jitter = Math.floor(Math.random() * base);
106
- return base * 2 ** (attempt - 1) + jitter;
107
- }
108
- if (typeof spec === "function") return Math.max(0, spec(attempt));
109
- return Math.max(0, spec);
110
- }
111
- function sleep(ms) {
112
- return new Promise((resolve) => setTimeout(resolve, ms));
113
- }
114
-
115
- // src/conversation/headers.ts
116
- var FORWARD_HEADERS = {
117
- /** Forwarded original-user identity (`Bearer sk-tan-<user>`); downstream gateways bill against this. */
118
- authorization: "x-tangle-forwarded-authorization",
119
- /** Monotonically incremented on every gateway hop. Refused at MAX_DEPTH. */
120
- depth: "x-tangle-forwarded-depth",
121
- /** Top-level conversation run identifier, propagated through every nested call. */
122
- runId: "x-tangle-runid",
123
- /** This call's turn within the run; deterministic + stable across retries. */
124
- turnId: "x-tangle-turnid",
125
- /** When the call is *inside* another turn (recursion), the parent turn's id. */
126
- parentTurnId: "x-tangle-parent-turnid",
127
- /** Logical conversation peer label at the sending side, for trace stitching. */
128
- speaker: "x-tangle-speaker"
129
- };
130
- var DEFAULT_MAX_DEPTH = 4;
131
- function lc(name) {
132
- return name.toLowerCase();
133
- }
134
- function readDepth(headers) {
135
- const raw = pickHeader(headers, FORWARD_HEADERS.depth);
136
- if (raw === void 0 || raw === "") return 0;
137
- const n = Number(raw);
138
- if (!Number.isInteger(n) || n < 0) {
139
- throw new Error(
140
- `invalid ${FORWARD_HEADERS.depth} header value '${raw}' \u2014 must be a non-negative integer`
141
- );
142
- }
143
- return n;
144
- }
145
- function isDepthExceeded(inboundDepth, max = DEFAULT_MAX_DEPTH) {
146
- return inboundDepth >= max;
147
- }
148
- function buildForwardHeaders(input) {
149
- const out = {
150
- [FORWARD_HEADERS.depth]: String(input.inboundDepth + 1),
151
- [FORWARD_HEADERS.runId]: input.runId,
152
- [FORWARD_HEADERS.turnId]: input.turnId,
153
- [FORWARD_HEADERS.speaker]: input.speaker
154
- };
155
- if (input.forwardedAuthorization !== void 0) {
156
- out[FORWARD_HEADERS.authorization] = input.forwardedAuthorization;
157
- }
158
- if (input.parentTurnId !== void 0) {
159
- out[FORWARD_HEADERS.parentTurnId] = input.parentTurnId;
160
- }
161
- return out;
162
- }
163
- function pickHeader(headers, name) {
164
- const target = lc(name);
165
- for (const key of Object.keys(headers)) {
166
- if (lc(key) === target) {
167
- const value = headers[key];
168
- if (Array.isArray(value)) return value[0];
169
- return value;
170
- }
171
- }
172
- return void 0;
173
- }
174
-
175
- // src/conversation/turn-id.ts
176
- function turnId(runId, index, speaker) {
177
- return `${runId}.t${index}.${slugifySpeaker(speaker)}`;
178
- }
179
- function slugifySpeaker(speaker) {
180
- const cleaned = speaker.normalize("NFKD").replace(/[^\w-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
181
- return cleaned || "anon";
182
- }
183
-
184
- // src/conversation/run-conversation.ts
185
- async function runConversation(conversation, options) {
186
- let result;
187
- for await (const event of runConversationStream(conversation, options)) {
188
- if (options.onEvent) await options.onEvent(event);
189
- if (event.type === "conversation_end") result = event.result;
190
- }
191
- if (!result) {
192
- throw new BackendTransportError(
193
- "conversation",
194
- "conversation stream ended without a conversation_end event"
195
- );
196
- }
197
- return result;
198
- }
199
- async function* runConversationStream(conversation, options) {
200
- const runId = options.runId ?? `conv_${crypto.randomUUID()}`;
201
- const inboundDepth = options.inboundDepth ?? 0;
202
- const callerHeaders = options.propagatedHeaders ?? {};
203
- const forwardedAuthorization = callerHeaders[FORWARD_HEADERS.authorization];
204
- const breakers = /* @__PURE__ */ new Map();
205
- for (const participant of conversation.participants) {
206
- const cfg = participant.callPolicy?.circuitBreaker ?? conversation.policy.defaultCallPolicy?.circuitBreaker;
207
- breakers.set(participant.name, new CircuitBreakerState(cfg));
208
- }
209
- let transcript = [];
210
- let spentCreditsCents = 0;
211
- let startedAt = nowIso();
212
- let resumed = false;
213
- const sessionStore = options.sessionStore ?? new InMemoryRuntimeSessionStore();
214
- if (options.journal) {
215
- const prior = await options.journal.loadRun(runId);
216
- if (prior) {
217
- if (prior.halted) {
218
- const replayResult = {
219
- runId,
220
- transcript: prior.turns,
221
- turns: prior.turns.length,
222
- spentCreditsCents: prior.turns.reduce(
223
- (sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0),
224
- 0
225
- ),
226
- halted: prior.halted,
227
- durationMs: 0,
228
- startedAt: prior.startedAt,
229
- endedAt: prior.endedAt ?? prior.startedAt
230
- };
231
- yield {
232
- type: "conversation_resumed",
233
- runId,
234
- participants: conversation.participants.map((p) => p.name),
235
- transcript: prior.turns,
236
- timestamp: nowIso()
237
- };
238
- yield { type: "conversation_end", runId, result: replayResult, timestamp: nowIso() };
239
- return;
240
- }
241
- transcript = [...prior.turns];
242
- spentCreditsCents = transcript.reduce(
243
- (sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0),
244
- 0
245
- );
246
- startedAt = prior.startedAt;
247
- resumed = true;
248
- } else {
249
- await options.journal.beginRun(runId, startedAt);
250
- }
251
- }
252
- const startedAtMs = Date.now();
253
- const participantSessions = sessionIdsFrom(transcript);
254
- if (resumed) {
255
- yield {
256
- type: "conversation_resumed",
257
- runId,
258
- participants: conversation.participants.map((p) => p.name),
259
- // Snapshot the resumed transcript — the live `transcript` array gets
260
- // pushed to as the run continues, so handing the bare reference to a
261
- // subscriber would leak future writes into a past event.
262
- transcript: [...transcript],
263
- timestamp: nowIso()
264
- };
265
- } else {
266
- yield {
267
- type: "conversation_start",
268
- runId,
269
- participants: conversation.participants.map((p) => p.name),
270
- seed: options.seed,
271
- timestamp: startedAt
272
- };
273
- }
274
- let currentInput = transcript.length === 0 ? options.seed : transcript[transcript.length - 1]?.text ?? options.seed;
275
- let halt;
276
- const initialOffset = transcript.length;
277
- for (let turnIndex = initialOffset; turnIndex < conversation.policy.maxTurns; turnIndex++) {
278
- if (options.signal?.aborted) {
279
- halt = { kind: "abort" };
280
- break;
281
- }
282
- if (conversation.policy.maxCreditsCents !== void 0 && spentCreditsCents >= conversation.policy.maxCreditsCents) {
283
- halt = {
284
- kind: "max_credits",
285
- spentCents: spentCreditsCents,
286
- capCents: conversation.policy.maxCreditsCents
287
- };
288
- break;
289
- }
290
- const speakerIdx = selectSpeaker(
291
- conversation.policy.turnOrder,
292
- conversation.participants.length,
293
- { transcript, turnIndex, spentCreditsCents }
294
- );
295
- const speaker = conversation.participants[speakerIdx];
296
- if (!speaker) {
297
- throw new BackendTransportError(
298
- "conversation",
299
- `turnOrder selector returned out-of-range index ${speakerIdx} for ${conversation.participants.length} participants`
300
- );
301
- }
302
- const tid = turnId(runId, turnIndex, speaker.name);
303
- const callPolicy = speaker.callPolicy ?? conversation.policy.defaultCallPolicy;
304
- const breaker = breakers.get(speaker.name);
305
- if (!breaker) {
306
- throw new BackendTransportError(
307
- "conversation",
308
- `internal: no circuit-breaker state registered for participant '${speaker.name}'`
309
- );
310
- }
311
- const isRetryable = callPolicy?.isRetryable ?? defaultIsRetryable;
312
- const totalAttempts = 1 + (callPolicy?.maxRetries ?? 0);
313
- yield {
314
- type: "turn_start",
315
- runId,
316
- index: turnIndex,
317
- speaker: speaker.name,
318
- turnId: tid,
319
- attempt: 1,
320
- timestamp: nowIso()
321
- };
322
- let aggregator;
323
- let attemptCount = 0;
324
- let lastError;
325
- let breakerOpenFailure;
326
- for (let attempt = 1; attempt <= totalAttempts; attempt++) {
327
- attemptCount = attempt;
328
- try {
329
- breaker.preflight(speaker.name);
330
- } catch (err) {
331
- breakerOpenFailure = err;
332
- break;
333
- }
334
- if (attempt > 1) {
335
- yield {
336
- type: "turn_retry",
337
- runId,
338
- index: turnIndex,
339
- speaker: speaker.name,
340
- turnId: tid,
341
- attempt,
342
- reason: lastError instanceof Error ? lastError.message : String(lastError),
343
- timestamp: nowIso()
344
- };
345
- }
346
- const perAttempt = makePerAttemptSignal(options.signal, callPolicy?.perAttemptDeadlineMs);
347
- const localAgg = new TurnAggregator({
348
- index: turnIndex,
349
- speaker: speaker.name,
350
- startedAt: nowIso()
351
- });
352
- try {
353
- for await (const delta of driveSingleAttempt({
354
- speaker,
355
- participants: conversation.participants,
356
- seed: options.seed,
357
- input: currentInput,
358
- turnIndex,
359
- runId,
360
- turnId: tid,
361
- transcript,
362
- participantSessions,
363
- sessionStore,
364
- signal: perAttempt.signal,
365
- aggregator: localAgg,
366
- propagatedHeaders: buildForwardHeaders({
367
- inboundDepth,
368
- // When the participant elects to pay for its own outbound calls,
369
- // drop the forwarded user identity so the downstream gateway
370
- // bills the participant's own credentials instead. The backend
371
- // brings its own `Authorization` header at construction time
372
- // (e.g. `createOpenAICompatibleBackend({ apiKey: sk-tan-AGENT })`);
373
- // omitting the forwarded header is what flips the billing target.
374
- forwardedAuthorization: resolveAuthForwarding(speaker, {
375
- transcript,
376
- turnIndex,
377
- spentCreditsCents
378
- }) ? forwardedAuthorization : void 0,
379
- runId,
380
- turnId: tid,
381
- parentTurnId: options.parentTurnId,
382
- speaker: speaker.name
383
- })
384
- })) {
385
- yield {
386
- type: "turn_text_delta",
387
- runId,
388
- index: turnIndex,
389
- speaker: speaker.name,
390
- turnId: tid,
391
- text: delta.text,
392
- timestamp: delta.timestamp
393
- };
394
- }
395
- perAttempt.dispose();
396
- breaker.recordSuccess();
397
- aggregator = localAgg;
398
- break;
399
- } catch (err) {
400
- perAttempt.dispose();
401
- breaker.recordFailure();
402
- lastError = perAttempt.getDeadlineError() ?? err;
403
- if (attempt >= totalAttempts || !isRetryable(lastError)) {
404
- break;
405
- }
406
- await sleep(computeBackoff(callPolicy?.retryBackoffMs, attempt));
407
- }
408
- }
409
- if (!aggregator) {
410
- const failure = breakerOpenFailure ?? lastError;
411
- const message = failure instanceof Error ? failure.message : String(failure);
412
- halt = { kind: "participant_error", participant: speaker.name, message };
413
- break;
414
- }
415
- const turn = aggregator.toTurn({ turnId: tid, attempts: attemptCount });
416
- if (turn.sessionId) {
417
- bindParticipantSession(participantSessions, turn.speaker, turn.sessionId);
418
- }
419
- transcript.push(turn);
420
- spentCreditsCents += centsFromUsd(turn.usage?.costUsd ?? 0);
421
- if (options.journal) {
422
- await options.journal.appendTurn(runId, turn);
423
- }
424
- yield { type: "turn_end", runId, turn, timestamp: nowIso() };
425
- if (conversation.policy.haltOn) {
426
- const haltCtx = {
427
- transcript,
428
- lastTurn: turn,
429
- turnIndex,
430
- spentCreditsCents
431
- };
432
- const decision = await conversation.policy.haltOn(haltCtx);
433
- if (decision === true) {
434
- halt = { kind: "predicate", reason: "predicate_true" };
435
- break;
436
- }
437
- if (typeof decision === "object" && decision !== null && decision.halted) {
438
- halt = { kind: "predicate", reason: decision.reason };
439
- break;
440
- }
441
- }
442
- currentInput = turn.text;
443
- }
444
- if (!halt) halt = { kind: "max_turns", turns: transcript.length };
445
- const endedAt = nowIso();
446
- const result = {
447
- runId,
448
- transcript,
449
- turns: transcript.length,
450
- spentCreditsCents,
451
- halted: halt,
452
- durationMs: Date.now() - startedAtMs,
453
- startedAt,
454
- endedAt
455
- };
456
- if (options.journal) {
457
- await options.journal.recordHalt(runId, halt, endedAt);
458
- }
459
- yield { type: "conversation_end", runId, result, timestamp: endedAt };
460
- }
461
- async function* driveSingleAttempt(args) {
462
- const task = {
463
- id: args.turnId,
464
- intent: args.input,
465
- metadata: {
466
- runId: args.runId,
467
- turnId: args.turnId,
468
- turnIndex: args.turnIndex,
469
- speaker: args.speaker.name,
470
- participants: args.participants.map((p) => p.name)
471
- }
472
- };
473
- const knowledge = passingReadiness(task.id);
474
- const startCtx = {
475
- task,
476
- knowledge,
477
- signal: args.signal,
478
- runId: args.runId,
479
- turnId: args.turnId,
480
- propagatedHeaders: args.propagatedHeaders
481
- };
482
- const previousSessionId = args.participantSessions.get(args.speaker.name);
483
- const opened = await startOrResumeRuntimeSession({
484
- backend: args.speaker.backend,
485
- input: () => fullConversationInput(task, args.speaker.name, args.seed, args.transcript),
486
- continuationInput: () => continuedConversationInput(task, args.speaker.name, args.transcript),
487
- context: startCtx,
488
- store: args.sessionStore,
489
- sessionId: previousSessionId ?? participantSessionId(args.runId, args.speaker.name, args.participants),
490
- resume: previousSessionId !== void 0 && args.speaker.backend.resume !== void 0,
491
- validateSession: (session2) => assertParticipantSessionAvailable(args.participantSessions, args.speaker.name, session2.id)
492
- });
493
- const session = opened.session;
494
- args.aggregator.recordSession(session.id);
495
- const streamCtx = {
496
- task,
497
- knowledge,
498
- session,
499
- signal: args.signal,
500
- runId: args.runId,
501
- turnId: args.turnId,
502
- propagatedHeaders: args.propagatedHeaders
503
- };
504
- for await (const event of args.speaker.backend.stream(opened.input, streamCtx)) {
505
- if (args.signal.aborted) {
506
- const reason = args.signal.reason;
507
- throw reason instanceof Error ? reason : new Error("aborted");
508
- }
509
- if (event.type === "text_delta") {
510
- args.aggregator.appendText(event.text);
511
- yield { text: event.text, timestamp: event.timestamp };
512
- } else if (event.type === "llm_call") {
513
- args.aggregator.recordUsage(event);
514
- } else if (event.type === "backend_error") {
515
- throw new BackendTransportError(args.speaker.backend.kind, event.message, {
516
- status: event.error?.status,
517
- body: event.error?.body
518
- });
519
- } else if (event.type === "final") {
520
- if (event.status !== "completed") {
521
- throw new BackendTransportError(
522
- args.speaker.backend.kind,
523
- event.error?.message ?? event.reason,
524
- { status: event.error?.status, body: event.error?.body }
525
- );
526
- }
527
- args.aggregator.adoptFinalText(event.text);
528
- }
529
- }
530
- if (!args.aggregator.hasText()) {
531
- throw new BackendTransportError(
532
- args.speaker.backend.kind,
533
- `backend '${args.speaker.backend.kind}' completed without text`
534
- );
535
- }
536
- }
537
- var TurnAggregator = class {
538
- constructor(base) {
539
- this.base = base;
540
- }
541
- base;
542
- text = "";
543
- adoptedFinal = false;
544
- sessionId;
545
- usage;
546
- appendText(text) {
547
- if (this.adoptedFinal) return;
548
- this.text += text;
549
- }
550
- /**
551
- * Use the backend's `final.text` only when no streamed deltas were observed.
552
- * Some backends emit deltas AND a final summary; treating both as content
553
- * would double-count.
554
- */
555
- adoptFinalText(text) {
556
- if (!text) return;
557
- if (this.text.length > 0) return;
558
- this.text = text;
559
- this.adoptedFinal = true;
560
- }
561
- hasText() {
562
- return this.text.trim().length > 0;
563
- }
564
- recordSession(sessionId) {
565
- this.sessionId = sessionId;
566
- }
567
- recordUsage(event) {
568
- const u = this.usage ?? {};
569
- if (event.tokensIn !== void 0) u.tokensIn = (u.tokensIn ?? 0) + event.tokensIn;
570
- if (event.tokensOut !== void 0) u.tokensOut = (u.tokensOut ?? 0) + event.tokensOut;
571
- if (event.costUsd !== void 0) u.costUsd = (u.costUsd ?? 0) + event.costUsd;
572
- if (event.latencyMs !== void 0) u.latencyMs = event.latencyMs;
573
- if (event.model !== void 0) u.model = event.model;
574
- this.usage = u;
575
- }
576
- toTurn(meta) {
577
- return {
578
- index: this.base.index,
579
- speaker: this.base.speaker,
580
- turnId: meta.turnId,
581
- ...this.sessionId ? { sessionId: this.sessionId } : {},
582
- text: this.text.trim(),
583
- usage: this.usage,
584
- attempts: meta.attempts,
585
- startedAt: this.base.startedAt,
586
- endedAt: nowIso()
587
- };
588
- }
589
- };
590
- function buildMessagesFor(speakerName, seed, transcript) {
591
- const messages = seed ? [{ role: "user", content: seed }] : [];
592
- for (const turn of transcript) {
593
- if (turn.speaker === speakerName) {
594
- messages.push({ role: "assistant", content: turn.text });
595
- } else {
596
- messages.push({ role: "user", content: `[${turn.speaker}] ${turn.text}` });
597
- }
598
- }
599
- return messages;
600
- }
601
- function fullConversationInput(task, speakerName, seed, transcript) {
602
- const transcriptText = transcript.map((turn) => `[${turn.speaker}] ${turn.text}`);
603
- return {
604
- task,
605
- message: [seed, ...transcriptText].filter((part) => part.length > 0).join("\n\n"),
606
- messages: buildMessagesFor(speakerName, seed, transcript)
607
- };
608
- }
609
- function continuedConversationInput(task, speakerName, transcript) {
610
- let lastOwnTurn = -1;
611
- for (let index = transcript.length - 1; index >= 0; index -= 1) {
612
- if (transcript[index]?.speaker === speakerName) {
613
- lastOwnTurn = index;
614
- break;
615
- }
616
- }
617
- const unseen = transcript.slice(lastOwnTurn + 1);
618
- const message = unseen.length > 0 ? unseen.map((turn) => `[${turn.speaker}] ${turn.text}`).join("\n\n") : "Continue.";
619
- return { task, message, messages: [{ role: "user", content: message }] };
620
- }
621
- function sessionIdsFrom(transcript) {
622
- const sessions = /* @__PURE__ */ new Map();
623
- for (const turn of transcript) {
624
- if (turn.sessionId) bindParticipantSession(sessions, turn.speaker, turn.sessionId);
625
- }
626
- return sessions;
627
- }
628
- function bindParticipantSession(sessions, speakerName, sessionId) {
629
- assertParticipantSessionAvailable(sessions, speakerName, sessionId);
630
- sessions.set(speakerName, sessionId);
631
- }
632
- function assertParticipantSessionAvailable(sessions, speakerName, sessionId) {
633
- for (const [boundSpeaker, boundSessionId] of sessions) {
634
- if (boundSpeaker !== speakerName && boundSessionId === sessionId) {
635
- throw new BackendTransportError(
636
- "conversation",
637
- `session '${sessionId}' is already bound to participant '${boundSpeaker}'`
638
- );
639
- }
640
- }
641
- }
642
- function participantSessionId(runId, speakerName, participants) {
643
- const participantIndex = participants.findIndex((participant) => participant.name === speakerName);
644
- if (participantIndex < 0) {
645
- throw new BackendTransportError(
646
- "conversation",
647
- `participant '${speakerName}' is not registered in this conversation`
648
- );
649
- }
650
- return `${runId}.participant.${participantIndex}.${slugifySpeaker(speakerName)}`;
651
- }
652
- function resolveAuthForwarding(participant, state) {
653
- const decision = typeof participant.authSource === "function" ? participant.authSource(state) : participant.authSource ?? "forward-user";
654
- return decision === "forward-user";
655
- }
656
- function selectSpeaker(order, participantCount, state) {
657
- const resolved = order ?? (participantCount === 2 ? "alternate" : "round-robin");
658
- if (resolved === "alternate" || resolved === "round-robin") {
659
- return state.turnIndex % participantCount;
660
- }
661
- if (typeof resolved === "function") {
662
- const idx = resolved(state);
663
- if (!Number.isInteger(idx) || idx < 0 || idx >= participantCount) {
664
- throw new BackendTransportError(
665
- "conversation",
666
- `turnOrder function returned invalid index ${String(idx)} for ${participantCount} participants`
667
- );
668
- }
669
- return idx;
670
- }
671
- throw new BackendTransportError("conversation", `unknown turnOrder: ${String(resolved)}`);
672
- }
673
- function centsFromUsd(usd) {
674
- return Math.round(usd * 100);
675
- }
676
- function passingReadiness(taskId) {
677
- return {
678
- taskId,
679
- readinessScore: 1,
680
- blockingMissingRequirements: [],
681
- nonBlockingGaps: [],
682
- recommendedAction: "run_agent",
683
- bundle: {
684
- taskId,
685
- requirements: [],
686
- evidenceIds: [],
687
- claimIds: [],
688
- wikiPageIds: [],
689
- userAnswers: {},
690
- missing: [],
691
- readinessScore: 1
692
- },
693
- severity: "info",
694
- reason: "conversation-mode: readiness gating not applied per-turn"
695
- };
696
- }
697
-
698
- // src/conversation/conversation-backend.ts
699
- function createConversationBackend(options) {
700
- const kind = options.kind ?? "conversation";
701
- return {
702
- kind,
703
- start(_input, context) {
704
- return newRuntimeSession(kind, context.requestedSessionId, {
705
- participants: options.conversation.participants.map((p) => p.name)
706
- });
707
- },
708
- async *stream(input, context) {
709
- const seed = input.message ?? input.messages?.at(-1)?.content ?? context.task.intent;
710
- const task = context.task;
711
- const session = context.session;
712
- yield { type: "backend_start", task, session, backend: kind, timestamp: nowIso() };
713
- let finalText = "";
714
- let totalCostUsd = 0;
715
- let totalTokensIn = 0;
716
- let totalTokensOut = 0;
717
- const inboundDepth = parseInboundDepth(context.propagatedHeaders);
718
- for await (const event of runConversationStream(options.conversation, {
719
- seed,
720
- signal: context.signal,
721
- runId: context.runId,
722
- propagatedHeaders: context.propagatedHeaders,
723
- inboundDepth,
724
- parentTurnId: context.turnId
725
- })) {
726
- if (event.type === "turn_end") {
727
- const tagged = `[${event.turn.speaker}] ${event.turn.text}
728
- `;
729
- finalText += tagged;
730
- yield { type: "text_delta", task, session, text: tagged, timestamp: event.timestamp };
731
- if (event.turn.usage) {
732
- const u = event.turn.usage;
733
- if (u.costUsd !== void 0) totalCostUsd += u.costUsd;
734
- if (u.tokensIn !== void 0) totalTokensIn += u.tokensIn;
735
- if (u.tokensOut !== void 0) totalTokensOut += u.tokensOut;
736
- yield {
737
- type: "llm_call",
738
- task,
739
- session,
740
- model: u.model ?? `${kind}/${event.turn.speaker}`,
741
- tokensIn: u.tokensIn,
742
- tokensOut: u.tokensOut,
743
- costUsd: u.costUsd,
744
- latencyMs: u.latencyMs,
745
- timestamp: event.timestamp
746
- };
747
- }
748
- } else if (event.type === "conversation_end") {
749
- const halt = event.result.halted;
750
- yield {
751
- type: "final",
752
- task,
753
- session,
754
- status: halt.kind === "participant_error" ? "failed" : "completed",
755
- reason: describeHalt(halt),
756
- text: finalText.trim(),
757
- metadata: {
758
- conversationRunId: event.result.runId,
759
- turns: event.result.turns,
760
- spentCreditsCents: event.result.spentCreditsCents,
761
- halted: halt,
762
- durationMs: event.result.durationMs,
763
- tokensIn: totalTokensIn,
764
- tokensOut: totalTokensOut,
765
- costUsd: totalCostUsd
766
- },
767
- timestamp: event.timestamp
768
- };
769
- }
770
- }
771
- yield { type: "backend_end", task, session, backend: kind, timestamp: nowIso() };
772
- }
773
- };
774
- }
775
- function parseInboundDepth(headers) {
776
- if (!headers) return 0;
777
- const raw = headers[FORWARD_HEADERS.depth];
778
- if (raw === void 0) return 0;
779
- try {
780
- return readDepth({ [FORWARD_HEADERS.depth]: raw });
781
- } catch {
782
- return 0;
783
- }
784
- }
785
- function describeHalt(halt) {
786
- switch (halt.kind) {
787
- case "max_turns":
788
- return `max_turns (${halt.turns})`;
789
- case "max_credits":
790
- return `max_credits (${halt.spentCents}/${halt.capCents}\xA2)`;
791
- case "predicate":
792
- return `predicate: ${halt.reason}`;
793
- case "abort":
794
- return "abort";
795
- case "participant_error":
796
- return `participant_error[${halt.participant}]: ${halt.message}`;
797
- }
798
- }
799
-
800
- // src/conversation/define-conversation.ts
801
- function defineConversation(input) {
802
- if (input.participants.length < 2) {
803
- throw new ValidationError(
804
- `Conversation requires at least 2 participants; received ${input.participants.length}.`
805
- );
806
- }
807
- const seen = /* @__PURE__ */ new Set();
808
- for (const p of input.participants) {
809
- if (!p.name || p.name.trim() === "") {
810
- throw new ValidationError("Conversation participant.name must be a non-empty string.");
811
- }
812
- if (seen.has(p.name)) {
813
- throw new ValidationError(
814
- `Conversation participant names must be unique within a Conversation; '${p.name}' appears more than once.`
815
- );
816
- }
817
- seen.add(p.name);
818
- if (!p.backend || typeof p.backend.stream !== "function") {
819
- throw new ValidationError(
820
- `Conversation participant '${p.name}' is missing a backend with a stream() method.`
821
- );
822
- }
823
- }
824
- const policy = normalizePolicy(input.policy, input.participants.length);
825
- return {
826
- participants: input.participants,
827
- policy
828
- };
829
- }
830
- function normalizePolicy(policy, participantCount) {
831
- if (!Number.isInteger(policy.maxTurns) || policy.maxTurns < 1) {
832
- throw new ValidationError(
833
- `ConversationPolicy.maxTurns must be a positive integer; received ${String(policy.maxTurns)}.`
834
- );
835
- }
836
- if (policy.maxCreditsCents !== void 0 && (!Number.isFinite(policy.maxCreditsCents) || policy.maxCreditsCents < 0)) {
837
- throw new ValidationError(
838
- `ConversationPolicy.maxCreditsCents must be a non-negative finite number when set; received ${String(
839
- policy.maxCreditsCents
840
- )}.`
841
- );
842
- }
843
- const turnOrder = policy.turnOrder ?? (participantCount === 2 ? "alternate" : "round-robin");
844
- if (turnOrder === "alternate" && participantCount !== 2) {
845
- throw new ValidationError(
846
- `ConversationPolicy.turnOrder 'alternate' requires exactly 2 participants; received ${participantCount}. Use 'round-robin' or a custom selector for N-party conversations.`
847
- );
848
- }
849
- return { ...policy, turnOrder };
850
- }
851
-
852
- // src/conversation/journal.ts
853
- var InMemoryConversationJournal = class {
854
- entries = /* @__PURE__ */ new Map();
855
- async loadRun(runId) {
856
- const entry = this.entries.get(runId);
857
- if (!entry) return void 0;
858
- return {
859
- runId: entry.runId,
860
- startedAt: entry.startedAt,
861
- halted: entry.halted,
862
- endedAt: entry.endedAt,
863
- turns: [...entry.turns]
864
- };
865
- }
866
- async beginRun(runId, startedAt) {
867
- const existing = this.entries.get(runId);
868
- if (existing) {
869
- if (existing.startedAt !== startedAt) {
870
- throw new Error(
871
- `runId '${runId}' already exists with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`
872
- );
873
- }
874
- return;
875
- }
876
- this.entries.set(runId, { runId, startedAt, turns: [] });
877
- }
878
- async appendTurn(runId, turn) {
879
- const entry = this.entries.get(runId);
880
- if (!entry) {
881
- throw new Error(
882
- `appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`
883
- );
884
- }
885
- if (entry.halted) {
886
- throw new Error(
887
- `cannot append turn to halted run '${runId}' (halt reason: ${JSON.stringify(entry.halted)})`
888
- );
889
- }
890
- entry.turns.push(turn);
891
- }
892
- async recordHalt(runId, halt, endedAt) {
893
- const entry = this.entries.get(runId);
894
- if (!entry) {
895
- throw new Error(`recordHalt called for unknown runId '${runId}'`);
896
- }
897
- entry.halted = halt;
898
- entry.endedAt = endedAt;
899
- }
900
- };
901
- var FileConversationJournal = class {
902
- constructor(path) {
903
- this.path = path;
904
- }
905
- path;
906
- async loadRun(runId) {
907
- const fs = await import("fs/promises");
908
- let text;
909
- try {
910
- text = await fs.readFile(this.path, "utf8");
911
- } catch (err) {
912
- if (isNoEntError(err)) return void 0;
913
- throw err;
914
- }
915
- const lines = text.split("\n").filter((line) => line.length > 0);
916
- let entry;
917
- for (const line of lines) {
918
- const record = JSON.parse(line);
919
- if (record.runId !== runId) continue;
920
- if (record.kind === "begin") {
921
- entry = { runId, startedAt: record.startedAt, turns: [] };
922
- } else if (record.kind === "turn") {
923
- if (!entry) {
924
- throw new Error(
925
- `journal corrupted: turn record for runId '${runId}' precedes its begin record`
926
- );
927
- }
928
- entry.turns.push(record.turn);
929
- } else if (record.kind === "halt") {
930
- if (!entry) {
931
- throw new Error(
932
- `journal corrupted: halt record for runId '${runId}' precedes its begin record`
933
- );
934
- }
935
- entry.halted = record.halted;
936
- entry.endedAt = record.endedAt;
937
- }
938
- }
939
- return entry;
940
- }
941
- async beginRun(runId, startedAt) {
942
- const existing = await this.loadRun(runId);
943
- if (existing) {
944
- if (existing.startedAt !== startedAt) {
945
- throw new Error(
946
- `runId '${runId}' already exists in ${this.path} with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`
947
- );
948
- }
949
- return;
950
- }
951
- await this.appendRecord({ kind: "begin", runId, startedAt });
952
- }
953
- async appendTurn(runId, turn) {
954
- await this.appendRecord({ kind: "turn", runId, turn });
955
- }
956
- async recordHalt(runId, halt, endedAt) {
957
- await this.appendRecord({ kind: "halt", runId, halted: halt, endedAt });
958
- }
959
- async appendRecord(record) {
960
- const fs = await import("fs/promises");
961
- const path = await import("path");
962
- await fs.mkdir(path.dirname(this.path), { recursive: true });
963
- const fh = await fs.open(this.path, "a");
964
- try {
965
- await fh.write(`${JSON.stringify(record)}
966
- `);
967
- await fh.sync();
968
- } finally {
969
- await fh.close();
970
- }
971
- }
972
- };
973
- function isNoEntError(err) {
974
- return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
975
- }
976
-
977
- // src/conversation/journal-sql.ts
978
- function d1ToSqlAdapter(db) {
979
- return {
980
- async exec(sql, params = []) {
981
- const stmt = db.prepare(sql);
982
- const bound = params.length > 0 ? stmt.bind(...params) : stmt;
983
- const result = await bound.run();
984
- const meta = result.meta;
985
- return { rowsAffected: meta?.rows_written ?? meta?.changes ?? 0 };
986
- },
987
- async query(sql, params = []) {
988
- const stmt = db.prepare(sql);
989
- const bound = params.length > 0 ? stmt.bind(...params) : stmt;
990
- const result = await bound.all();
991
- return result.results ?? [];
992
- }
993
- };
994
- }
995
- var RUNS_TABLE_DDL = (table) => `
996
- CREATE TABLE IF NOT EXISTS ${table}_runs (
997
- run_id TEXT PRIMARY KEY,
998
- started_at TEXT NOT NULL,
999
- halted_kind TEXT,
1000
- halted_payload TEXT,
1001
- ended_at TEXT
1002
- )
1003
- `;
1004
- var TURNS_TABLE_DDL = (table) => `
1005
- CREATE TABLE IF NOT EXISTS ${table}_turns (
1006
- run_id TEXT NOT NULL,
1007
- turn_index INTEGER NOT NULL,
1008
- payload TEXT NOT NULL,
1009
- PRIMARY KEY (run_id, turn_index)
1010
- )
1011
- `;
1012
- var TURNS_INDEX_DDL = (table) => `
1013
- CREATE INDEX IF NOT EXISTS idx_${table}_turns_run ON ${table}_turns (run_id, turn_index)
1014
- `;
1015
- var SqlConversationJournal = class {
1016
- /**
1017
- * @param db SQL adapter (D1, postgres, sqlite, libSQL — all work)
1018
- * @param table Table-name prefix; the journal creates `${table}_runs` and
1019
- * `${table}_turns`. Lets multiple journals share a database
1020
- * without colliding (e.g. one per product surface).
1021
- */
1022
- constructor(db, table = "agent_runtime_journal") {
1023
- this.db = db;
1024
- this.table = table;
1025
- }
1026
- db;
1027
- table;
1028
- /**
1029
- * Create the journal's tables if absent. Idempotent. Call once at deploy
1030
- * (or at app boot) — running on every request is harmless but adds latency.
1031
- */
1032
- async migrate() {
1033
- await this.db.exec(RUNS_TABLE_DDL(this.table));
1034
- await this.db.exec(TURNS_TABLE_DDL(this.table));
1035
- await this.db.exec(TURNS_INDEX_DDL(this.table));
1036
- }
1037
- async loadRun(runId) {
1038
- const runs = await this.db.query(
1039
- `SELECT run_id, started_at, halted_kind, halted_payload, ended_at FROM ${this.table}_runs WHERE run_id = ?`,
1040
- [runId]
1041
- );
1042
- const row = runs[0];
1043
- if (!row) return void 0;
1044
- const turns = await this.db.query(
1045
- `SELECT payload, turn_index FROM ${this.table}_turns WHERE run_id = ? ORDER BY turn_index ASC`,
1046
- [runId]
1047
- );
1048
- return {
1049
- runId: row.run_id,
1050
- startedAt: row.started_at,
1051
- halted: row.halted_payload ? JSON.parse(row.halted_payload) : void 0,
1052
- endedAt: row.ended_at ?? void 0,
1053
- turns: turns.map((t) => JSON.parse(t.payload))
1054
- };
1055
- }
1056
- async beginRun(runId, startedAt) {
1057
- const existing = await this.db.query(
1058
- `SELECT started_at FROM ${this.table}_runs WHERE run_id = ?`,
1059
- [runId]
1060
- );
1061
- if (existing.length > 0) {
1062
- if (existing[0]?.started_at !== startedAt) {
1063
- throw new Error(
1064
- `runId '${runId}' already exists with startedAt=${existing[0]?.started_at}; refusing to overwrite with ${startedAt}`
1065
- );
1066
- }
1067
- return;
1068
- }
1069
- await this.db.exec(`INSERT INTO ${this.table}_runs (run_id, started_at) VALUES (?, ?)`, [
1070
- runId,
1071
- startedAt
1072
- ]);
1073
- }
1074
- async appendTurn(runId, turn) {
1075
- const halted = await this.db.query(
1076
- `SELECT halted_kind FROM ${this.table}_runs WHERE run_id = ?`,
1077
- [runId]
1078
- );
1079
- if (halted.length === 0) {
1080
- throw new Error(
1081
- `appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`
1082
- );
1083
- }
1084
- if (halted[0]?.halted_kind) {
1085
- throw new Error(
1086
- `cannot append turn to halted run '${runId}' (halt kind: ${halted[0]?.halted_kind})`
1087
- );
1088
- }
1089
- await this.db.exec(
1090
- `INSERT INTO ${this.table}_turns (run_id, turn_index, payload) VALUES (?, ?, ?)`,
1091
- [runId, turn.index, JSON.stringify(turn)]
1092
- );
1093
- }
1094
- async recordHalt(runId, halt, endedAt) {
1095
- const rs = await this.db.exec(
1096
- `UPDATE ${this.table}_runs SET halted_kind = ?, halted_payload = ?, ended_at = ? WHERE run_id = ?`,
1097
- [halt.kind, JSON.stringify(halt), endedAt, runId]
1098
- );
1099
- if (rs.rowsAffected === 0) {
1100
- throw new Error(`recordHalt called for unknown runId '${runId}'`);
1101
- }
1102
- }
1103
- };
1104
-
1105
- // src/conversation/run-persona.ts
1106
- function withProfilePrompt(inner, systemPrompt, counter) {
1107
- return {
1108
- kind: inner.kind,
1109
- start: inner.start ? (input, ctx) => inner.start(input, ctx) : void 0,
1110
- resume: inner.resume ? (session, input, ctx) => inner.resume(session, input, ctx) : void 0,
1111
- stop: inner.stop ? (session, reason) => inner.stop(session, reason) : void 0,
1112
- async *stream(input, context) {
1113
- const base = input.messages ?? (input.message ? [{ role: "user", content: input.message }] : []);
1114
- const messages = base[0]?.role === "system" ? base : [{ role: "system", content: systemPrompt }, ...base];
1115
- for await (const event of inner.stream({ ...input, messages }, context)) {
1116
- if (counter && event.type === "llm_call") {
1117
- counter.tokensIn += event.tokensIn ?? 0;
1118
- counter.tokensOut += event.tokensOut ?? 0;
1119
- counter.costUsd += event.costUsd ?? 0;
1120
- }
1121
- yield event;
1122
- }
1123
- }
1124
- };
1125
- }
1126
- function scriptedPersonaBackend(turns) {
1127
- let idx = 0;
1128
- return createIterableBackend({
1129
- kind: "persona-user",
1130
- async *stream(_input, context) {
1131
- const text = turns[idx];
1132
- if (text === void 0) {
1133
- throw new Error(
1134
- `persona-user: ran out of scripted turns at index ${idx} (had ${turns.length})`
1135
- );
1136
- }
1137
- idx += 1;
1138
- yield {
1139
- type: "text_delta",
1140
- task: context.task,
1141
- session: context.session,
1142
- text,
1143
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1144
- };
1145
- }
1146
- });
1147
- }
1148
- async function runPersonaConversation(opts) {
1149
- const counter = { tokensIn: 0, tokensOut: 0, costUsd: 0 };
1150
- const workerName = opts.workerName ?? "agent";
1151
- const worker = withProfilePrompt(
1152
- opts.backendFor(opts.worker, "worker"),
1153
- opts.systemPromptOf(opts.worker),
1154
- counter
1155
- );
1156
- let persona;
1157
- let maxTurns;
1158
- if (opts.persona.kind === "scripted") {
1159
- if (opts.persona.turns.length === 0) {
1160
- throw new Error("runPersonaConversation: scripted persona has no turns");
1161
- }
1162
- persona = scriptedPersonaBackend(opts.persona.turns);
1163
- maxTurns = opts.maxTurns ?? 2 * opts.persona.turns.length;
1164
- } else {
1165
- persona = withProfilePrompt(
1166
- opts.backendFor(opts.persona.profile, "persona"),
1167
- opts.systemPromptOf(opts.persona.profile)
1168
- );
1169
- if (opts.maxTurns === void 0) {
1170
- throw new Error("runPersonaConversation: maxTurns is required for a profile-driven persona");
1171
- }
1172
- maxTurns = opts.maxTurns;
1173
- }
1174
- const conversation = defineConversation({
1175
- // Persona leads (participant 0): the seed routes to it, it produces the
1176
- // user turn, the worker answers, alternate.
1177
- participants: [
1178
- { name: "user", backend: persona },
1179
- { name: workerName, backend: worker }
1180
- ],
1181
- policy: { maxTurns, turnOrder: "alternate", ...opts.haltOn ? { haltOn: opts.haltOn } : {} }
1182
- });
1183
- const result = await runConversation(conversation, {
1184
- seed: opts.seed ?? "Begin.",
1185
- signal: opts.signal
1186
- });
1187
- const costUsd = counter.costUsd > 0 ? counter.costUsd : opts.persona.kind === "scripted" ? result.spentCreditsCents / 100 : 0;
1188
- return {
1189
- transcript: result.transcript,
1190
- turns: result.turns,
1191
- halted: result.halted,
1192
- costUsd,
1193
- tokensIn: counter.tokensIn,
1194
- tokensOut: counter.tokensOut
1195
- };
1196
- }
1197
- function runPersonaDispatch(config) {
1198
- return async (worker, scenario, ctx) => {
1199
- const model = worker.model?.default ?? "unknown";
1200
- const maximumCharge = typeof config.maximumCharge === "function" ? config.maximumCharge(worker, scenario) : config.maximumCharge;
1201
- const paid = await ctx.cost.runPaidCall({
1202
- channel: "agent",
1203
- actor: "persona-conversation",
1204
- model,
1205
- signal: ctx.signal,
1206
- ...maximumCharge ? { maximumCharge } : {},
1207
- execute: (executionSignal) => runPersonaConversation({
1208
- worker,
1209
- persona: config.personaOf(scenario),
1210
- backendFor: config.backendFor,
1211
- systemPromptOf: config.systemPromptOf,
1212
- maxTurns: config.maxTurns?.(scenario),
1213
- seed: config.seed?.(scenario),
1214
- signal: executionSignal,
1215
- workerName: config.workerName
1216
- }),
1217
- receipt: (result2) => ({
1218
- model,
1219
- inputTokens: result2.tokensIn,
1220
- outputTokens: result2.tokensOut,
1221
- ...result2.costUsd > 0 ? { actualCostUsd: result2.costUsd } : {}
1222
- })
1223
- });
1224
- if (!paid.succeeded) throw paid.error;
1225
- const result = paid.value;
1226
- return config.artifactOf(result.transcript, scenario);
1227
- };
1228
- }
1229
-
1230
- export {
1231
- CircuitOpenError,
1232
- DeadlineExceededError,
1233
- defaultIsRetryable,
1234
- CircuitBreakerState,
1235
- makePerAttemptSignal,
1236
- computeBackoff,
1237
- sleep,
1238
- FORWARD_HEADERS,
1239
- DEFAULT_MAX_DEPTH,
1240
- readDepth,
1241
- isDepthExceeded,
1242
- buildForwardHeaders,
1243
- turnId,
1244
- slugifySpeaker,
1245
- runConversation,
1246
- runConversationStream,
1247
- createConversationBackend,
1248
- defineConversation,
1249
- InMemoryConversationJournal,
1250
- FileConversationJournal,
1251
- d1ToSqlAdapter,
1252
- SqlConversationJournal,
1253
- runPersonaConversation,
1254
- runPersonaDispatch
1255
- };
1256
- //# sourceMappingURL=chunk-2KGAN2HM.js.map