@tangle-network/agent-runtime 0.197.1 → 0.198.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 (103) hide show
  1. package/README.md +1 -2
  2. package/dist/{improve-DZs0KXhK.d.ts → activation-DFRTurvU.d.ts} +99 -5
  3. package/dist/{activation-BxMZybuo.js → activation-IBEVN3VI.js} +2 -2
  4. package/dist/{activation-BxMZybuo.js.map → activation-IBEVN3VI.js.map} +1 -1
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +2 -2
  7. package/dist/candidate-execution/index.d.ts +370 -2
  8. package/dist/candidate-execution/index.js +828 -4
  9. package/dist/candidate-execution/index.js.map +1 -0
  10. package/dist/{coordination-driver-zkCrfEbS.js → coordination-driver-NFvZ5ofi.js} +57 -26
  11. package/dist/coordination-driver-NFvZ5ofi.js.map +1 -0
  12. package/dist/{delegate-DHeUYU5E.js → delegate-dN5yooEj.js} +2 -2
  13. package/dist/{delegate-DHeUYU5E.js.map → delegate-dN5yooEj.js.map} +1 -1
  14. package/dist/durable.d.ts +2 -2
  15. package/dist/durable.js +4 -5
  16. package/dist/durable.js.map +1 -1
  17. package/dist/{graph-51SJOEcw.js → graph-CgCVtMuz.js} +3 -3
  18. package/dist/{graph-51SJOEcw.js.map → graph-CgCVtMuz.js.map} +1 -1
  19. package/dist/{improvement-cycle-Tw5nYT5R.js → improvement-cycle-Cfu6kDOs.js} +8 -10
  20. package/dist/{improvement-cycle-Tw5nYT5R.js.map → improvement-cycle-Cfu6kDOs.js.map} +1 -1
  21. package/dist/{index-CYOJsxSg.d.ts → index-CMTUgh-T.d.ts} +9 -11
  22. package/dist/index.d.ts +694 -16
  23. package/dist/index.js +1780 -17
  24. package/dist/index.js.map +1 -1
  25. package/dist/intelligence.d.ts +3 -7
  26. package/dist/intelligence.js +5 -6
  27. package/dist/intelligence.js.map +1 -1
  28. package/dist/kernel.d.ts +2 -5
  29. package/dist/kernel.js +8 -10
  30. package/dist/{loop-runner-bin-DwrSB04m.d.ts → loop-runner-bin-CAf1OQot.d.ts} +3 -3
  31. package/dist/{loop-runner-bin-2LQSjRTB.js → loop-runner-bin-WQniYJ8C.js} +3 -3
  32. package/dist/{loop-runner-bin-2LQSjRTB.js.map → loop-runner-bin-WQniYJ8C.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 +2 -3
  37. package/dist/mcp/index.js +4 -5
  38. package/dist/mcp/index.js.map +1 -1
  39. package/dist/{prepare-DDGp0-rW.js → prepare-CAO1yXov.js} +2407 -2407
  40. package/dist/prepare-CAO1yXov.js.map +1 -0
  41. package/dist/{protected-model-port-DxFN8DLS.js → protected-model-port-B5avcRiQ.js} +2 -2
  42. package/dist/{protected-model-port-DxFN8DLS.js.map → protected-model-port-B5avcRiQ.js.map} +1 -1
  43. package/dist/{provision-supervisor-CpMMShE_.js → provision-supervisor-BxsIaJ35.js} +3 -6
  44. package/dist/{provision-supervisor-CpMMShE_.js.map → provision-supervisor-BxsIaJ35.js.map} +1 -1
  45. package/dist/{redact-Cbl2O-4N.js → redact-DqfB7oB4.js} +5233 -2526
  46. package/dist/redact-DqfB7oB4.js.map +1 -0
  47. package/dist/{runtime-BSFz2z7h.js → runtime-CHEtvaTY.js} +427 -23
  48. package/dist/runtime-CHEtvaTY.js.map +1 -0
  49. package/dist/{server-COXa19sp.js → server-ccGua5tH.js} +4 -4
  50. package/dist/{server-COXa19sp.js.map → server-ccGua5tH.js.map} +1 -1
  51. package/dist/{types-DFLZMaeh.d.ts → stream-agent-turn-CLOQr497.d.ts} +1986 -6
  52. package/dist/{structural-rollout-DPbZWgEm.js → structural-rollout-BmDuXyR9.js} +1101 -8
  53. package/dist/structural-rollout-BmDuXyR9.js.map +1 -0
  54. package/dist/{supervise-b93YUaka.js → supervise-DVt8-TI-.js} +9 -5
  55. package/dist/supervise-DVt8-TI-.js.map +1 -0
  56. package/dist/testing.d.ts +2 -2
  57. package/dist/testing.js +13 -13
  58. package/dist/tui/index.d.ts +1 -1
  59. package/dist/tui/index.js +1 -1
  60. package/dist/{workspace-archive-Ybomp7AN.js → workspace-archive-BMOnloFf.js} +3 -3
  61. package/dist/{workspace-archive-Ybomp7AN.js.map → workspace-archive-BMOnloFf.js.map} +1 -1
  62. package/package.json +1 -28
  63. package/dist/activation-DyWB0K6E.d.ts +0 -98
  64. package/dist/authored-code-URmkdgjv.js +0 -37
  65. package/dist/authored-code-URmkdgjv.js.map +0 -1
  66. package/dist/candidate-execution-nvqVIMyS.js +0 -829
  67. package/dist/candidate-execution-nvqVIMyS.js.map +0 -1
  68. package/dist/conversation-BxJ0SIBM.js +0 -1363
  69. package/dist/conversation-BxJ0SIBM.js.map +0 -1
  70. package/dist/conversation.d.ts +0 -2
  71. package/dist/conversation.js +0 -2
  72. package/dist/coordination-driver-zkCrfEbS.js.map +0 -1
  73. package/dist/environment-provider-1fKZh2zl.js +0 -2281
  74. package/dist/environment-provider-1fKZh2zl.js.map +0 -1
  75. package/dist/environment-provider-B-I2jlQy.d.ts +0 -143
  76. package/dist/environment-provider.d.ts +0 -2
  77. package/dist/environment-provider.js +0 -2
  78. package/dist/graph.d.ts +0 -753
  79. package/dist/graph.js +0 -2111
  80. package/dist/graph.js.map +0 -1
  81. package/dist/index-CUosKU4N.d.ts +0 -372
  82. package/dist/index-D9mb6fn2.d.ts +0 -691
  83. package/dist/index-ZnxSe6iK.d.ts +0 -138
  84. package/dist/jsonl-file-BEpaEYjT.js +0 -141
  85. package/dist/jsonl-file-BEpaEYjT.js.map +0 -1
  86. package/dist/knowledge-B_MsOtDG.js +0 -428
  87. package/dist/knowledge-B_MsOtDG.js.map +0 -1
  88. package/dist/knowledge.d.ts +0 -2
  89. package/dist/knowledge.js +0 -2
  90. package/dist/materialization-Cy0oM8tb.js +0 -672
  91. package/dist/materialization-Cy0oM8tb.js.map +0 -1
  92. package/dist/prepare-DDGp0-rW.js.map +0 -1
  93. package/dist/primeintellect/index.d.ts +0 -218
  94. package/dist/primeintellect/index.js +0 -739
  95. package/dist/primeintellect/index.js.map +0 -1
  96. package/dist/redact-Cbl2O-4N.js.map +0 -1
  97. package/dist/runtime-0xNaV6TJ.d.ts +0 -1699
  98. package/dist/runtime-BSFz2z7h.js.map +0 -1
  99. package/dist/stream-agent-turn-Dt5mZpc3.js +0 -1103
  100. package/dist/stream-agent-turn-Dt5mZpc3.js.map +0 -1
  101. package/dist/stream-agent-turn-urHpmO_Z.d.ts +0 -160
  102. package/dist/structural-rollout-DPbZWgEm.js.map +0 -1
  103. package/dist/supervise-b93YUaka.js.map +0 -1
@@ -1,1363 +0,0 @@
1
- import { et as providerMessageText } from "./materialization-Cy0oM8tb.js";
2
- import { m as ValidationError, r as BackendTransportError } from "./errors-DodWX-cb.js";
3
- import { c as nowIso, l as startOrResumeRuntimeSession, n as streamAgentTurn, o as InMemoryRuntimeSessionStore, r as createIterableBackend, s as newRuntimeSession } from "./stream-agent-turn-Dt5mZpc3.js";
4
- import { a as executableAgentProfileSnapshot, i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-BEpaEYjT.js";
5
- //#region src/runtime/profile-execution-backend.ts
6
- /**
7
- * Bind one exact profile and Runtime executor to the stable `AgentExecutionBackend` contract used
8
- * by `runAgentTaskStream` and conversations.
9
- *
10
- * Runtime still owns the model call through `streamAgentTurn`.
11
- * The adapter only translates the two stream protocols and carries the caller's request headers
12
- * into `ExecutorContext` so an HTTP executor can preserve authorization, recursion depth, and
13
- * trace identity.
14
- *
15
- * @stable
16
- */
17
- function createProfileExecutionBackend(options) {
18
- const profile = executableAgentProfileSnapshot(options.profile, "createProfileExecutionBackend");
19
- const executor = options.executor;
20
- return {
21
- kind: "runtime-profile",
22
- async *stream(input, context) {
23
- const propagatedHeaders = snapshotPropagatedHeaders(context.propagatedHeaders);
24
- const contextualExecutor = (spec, executorContext) => executor(spec, {
25
- ...executorContext,
26
- ...propagatedHeaders === void 0 ? {} : { propagatedHeaders }
27
- });
28
- const providerMessages = input.providerOptions?.messages;
29
- const turnInput = input.messages !== void 0 ? { providerOptions: { messages: input.messages.map((message) => ({ ...message })) } } : Array.isArray(providerMessages) ? { providerOptions: { messages: structuredClone(providerMessages) } } : { prompt: input.message ?? context.task.intent };
30
- let terminal = false;
31
- let emittedText = false;
32
- for await (const event of streamAgentTurn({
33
- kind: "executor",
34
- profile,
35
- factory: contextualExecutor
36
- }, turnInput, {
37
- signal: context.signal,
38
- ...context.turnId ? { callId: context.turnId } : {},
39
- ...context.runId ? { correlationId: context.runId } : {}
40
- })) {
41
- if (event.type === "backend_start") continue;
42
- if (event.type === "backend_error") throw backendError(event.error, event.message);
43
- if (event.type === "final") {
44
- terminal = true;
45
- if (event.status !== "completed") throw backendError(event.error, event.reason);
46
- if (!emittedText && event.text) yield {
47
- type: "text_delta",
48
- task: context.task,
49
- session: context.session,
50
- text: event.text,
51
- timestamp: event.timestamp
52
- };
53
- continue;
54
- }
55
- if (event.type === "text_delta") emittedText = true;
56
- yield rebindEvent(event, context);
57
- }
58
- if (!terminal) throw new ValidationError("createProfileExecutionBackend: streamAgentTurn ended without a terminal event");
59
- }
60
- };
61
- }
62
- function snapshotPropagatedHeaders(headers) {
63
- if (headers === void 0) return void 0;
64
- const snapshot = {};
65
- for (const [name, value] of Object.entries(headers)) {
66
- if (typeof value !== "string") throw new ValidationError(`createProfileExecutionBackend: propagated header ${JSON.stringify(name)} must be a string`);
67
- snapshot[name] = value;
68
- }
69
- return Object.freeze(snapshot);
70
- }
71
- function backendError(detail, message) {
72
- if (detail?.kind === "transport") return new BackendTransportError("runtime-profile", detail.message, {
73
- status: detail.status,
74
- body: detail.body
75
- });
76
- return new Error(detail?.message ?? message);
77
- }
78
- function rebindEvent(event, context) {
79
- return {
80
- ...event,
81
- task: context.task,
82
- session: context.session
83
- };
84
- }
85
- //#endregion
86
- //#region src/conversation/call-policy.ts
87
- /** Thrown when the circuit breaker is open for a participant and no retry is allowed yet. */
88
- var CircuitOpenError = class extends Error {
89
- constructor(participant, retryAfterMs) {
90
- super(`circuit open for participant '${participant}'; ${retryAfterMs}ms remaining before retry allowed`);
91
- this.name = "CircuitOpenError";
92
- }
93
- };
94
- /** Thrown when a backend call exceeds its per-attempt deadline. */
95
- var DeadlineExceededError = class extends Error {
96
- constructor(deadlineMs) {
97
- super(`backend call exceeded per-attempt deadline of ${deadlineMs}ms`);
98
- this.name = "DeadlineExceededError";
99
- }
100
- };
101
- /**
102
- * Default retryable classification — network/timeout class errors. Errors
103
- * a model deliberately throws (validation, refusal, 4xx) are not retried;
104
- * those represent real outcomes, not transient infrastructure faults.
105
- */
106
- const defaultIsRetryable = (err) => {
107
- if (err instanceof DeadlineExceededError) return true;
108
- if (err instanceof Error) {
109
- const name = err.name;
110
- const message = err.message.toLowerCase();
111
- if (name === "AbortError" || name === "TimeoutError") return true;
112
- if (message.includes("econnreset") || message.includes("etimedout") || message.includes("econnrefused") || message.includes("socket hang up") || message.includes("network") || message.includes("fetch failed")) return true;
113
- }
114
- return false;
115
- };
116
- /** Live circuit-breaker state — one instance per (participant, conversation run). */
117
- var CircuitBreakerState = class {
118
- config;
119
- consecutiveFailures = 0;
120
- openedAt;
121
- constructor(config) {
122
- this.config = config;
123
- }
124
- /**
125
- * Check whether the next call is allowed. Throws `CircuitOpenError` when
126
- * the breaker is open and the cooldown hasn't elapsed.
127
- */
128
- preflight(participant, now = Date.now()) {
129
- if (!this.config || this.openedAt === void 0) return;
130
- const remaining = this.config.cooldownMs - (now - this.openedAt);
131
- if (remaining > 0) throw new CircuitOpenError(participant, remaining);
132
- this.openedAt = void 0;
133
- this.consecutiveFailures = 0;
134
- }
135
- recordSuccess() {
136
- this.consecutiveFailures = 0;
137
- this.openedAt = void 0;
138
- }
139
- recordFailure(now = Date.now()) {
140
- if (!this.config) return;
141
- this.consecutiveFailures += 1;
142
- if (this.consecutiveFailures >= this.config.failuresToOpen) this.openedAt = now;
143
- }
144
- };
145
- /**
146
- * Build a per-attempt AbortSignal linked to the parent signal AND fired when
147
- * the deadline elapses. The returned `dispose()` MUST be called in a
148
- * `finally` (clears the timer, detaches the listener) so we don't leak.
149
- *
150
- * When the deadline fires, the signal's `reason` is a `DeadlineExceededError`
151
- * — callers can detect timeout-vs-cancel by reading `signal.reason` after
152
- * the underlying operation throws.
153
- */
154
- function makePerAttemptSignal(parentSignal, deadlineMs) {
155
- const controller = new AbortController();
156
- let deadlineError;
157
- const cleanups = [];
158
- if (parentSignal) if (parentSignal.aborted) controller.abort(parentSignal.reason);
159
- else {
160
- const onAbort = () => controller.abort(parentSignal.reason);
161
- parentSignal.addEventListener("abort", onAbort, { once: true });
162
- cleanups.push(() => parentSignal.removeEventListener("abort", onAbort));
163
- }
164
- if (deadlineMs !== void 0) {
165
- const ms = deadlineMs;
166
- const timer = setTimeout(() => {
167
- deadlineError = new DeadlineExceededError(ms);
168
- controller.abort(deadlineError);
169
- }, ms);
170
- cleanups.push(() => clearTimeout(timer));
171
- }
172
- return {
173
- signal: controller.signal,
174
- dispose() {
175
- for (const c of cleanups) c();
176
- },
177
- getDeadlineError() {
178
- return deadlineError;
179
- }
180
- };
181
- }
182
- /** Compute the delay before the next attempt. Default: 250ms exponential with jitter. */
183
- function computeBackoff(spec, attempt) {
184
- if (spec === void 0) {
185
- const base = 250;
186
- const jitter = Math.floor(Math.random() * base);
187
- return base * 2 ** (attempt - 1) + jitter;
188
- }
189
- if (typeof spec === "function") return Math.max(0, spec(attempt));
190
- return Math.max(0, spec);
191
- }
192
- /** Resolve after `ms` milliseconds — used for retry backoff in conversation call policy. */
193
- function sleep(ms) {
194
- return new Promise((resolve) => setTimeout(resolve, ms));
195
- }
196
- //#endregion
197
- //#region src/conversation/headers.ts
198
- /**
199
- *
200
- * Cross-gateway forwarding headers — the wire-level contract that makes
201
- * agent-to-agent communication composable across organizational boundaries.
202
- * Every header here is read on inbound and re-emitted on outbound, so a chain
203
- * `caller → A's gateway → A's runtime → B's gateway → B's runtime` ends with
204
- * B billing the original user, the depth counter monotonically incremented,
205
- * and the run/turn correlation IDs preserved end-to-end.
206
- *
207
- * The actual depth refusal (HTTP 413 at MAX_DEPTH) is enforced by
208
- * `agent-gateway`'s middleware; this module owns the names + the propagation
209
- * rules so both sides agree.
210
- *
211
- * Full protocol: `docs/agent-bus-protocol.md`.
212
- *
213
- * @stable
214
- */
215
- /** Standard names — lowercased so Headers maps interop on every runtime. */
216
- const FORWARD_HEADERS = {
217
- /** Forwarded original-user identity (`Bearer sk-tan-<user>`); downstream gateways bill against this. */
218
- authorization: "x-tangle-forwarded-authorization",
219
- /** Monotonically incremented on every gateway hop. Refused at MAX_DEPTH. */
220
- depth: "x-tangle-forwarded-depth",
221
- /** Top-level conversation run identifier, propagated through every nested call. */
222
- runId: "x-tangle-runid",
223
- /** This call's turn within the run; deterministic + stable across retries. */
224
- turnId: "x-tangle-turnid",
225
- /** When the call is *inside* another turn (recursion), the parent turn's id. */
226
- parentTurnId: "x-tangle-parent-turnid",
227
- /** Logical conversation peer label at the sending side, for trace stitching. */
228
- speaker: "x-tangle-speaker"
229
- };
230
- /** Hard cap on chained gateway hops; refused beyond this. Default keeps recursion bounded. */
231
- const DEFAULT_MAX_DEPTH = 4;
232
- /**
233
- * Lowercase a header lookup so we read the same key regardless of source
234
- * casing (Hono, fetch's `Headers`, raw Node IncomingMessage, …).
235
- */
236
- function lc(name) {
237
- return name.toLowerCase();
238
- }
239
- /**
240
- * Read the depth counter off an inbound request. Missing → 0 (caller is the
241
- * origin). Non-integer → throws — silent coercion would let a bad caller
242
- * reset depth and bypass the limit.
243
- */
244
- function readDepth(headers) {
245
- const raw = pickHeader(headers, FORWARD_HEADERS.depth);
246
- if (raw === void 0 || raw === "") return 0;
247
- const n = Number(raw);
248
- if (!Number.isInteger(n) || n < 0) throw new Error(`invalid ${FORWARD_HEADERS.depth} header value '${raw}' — must be a non-negative integer`);
249
- return n;
250
- }
251
- /**
252
- * Refuse further forwarding when the inbound depth has reached the limit.
253
- * Callers (the gateway middleware) translate the boolean to an HTTP 413.
254
- */
255
- function isDepthExceeded(inboundDepth, max = 4) {
256
- return inboundDepth >= max;
257
- }
258
- /**
259
- * Build the headers to emit on an outbound participant call, given the
260
- * conversation's propagation context. Depth is incremented from the inbound
261
- * value; runId / turnId / speaker stamp the current hop; the user's
262
- * `Authorization` is preserved verbatim so the downstream gateway bills the
263
- * right wallet.
264
- */
265
- function buildForwardHeaders(input) {
266
- const out = {
267
- [FORWARD_HEADERS.depth]: String(input.inboundDepth + 1),
268
- [FORWARD_HEADERS.runId]: input.runId,
269
- [FORWARD_HEADERS.turnId]: input.turnId,
270
- [FORWARD_HEADERS.speaker]: input.speaker
271
- };
272
- if (input.forwardedAuthorization !== void 0) out[FORWARD_HEADERS.authorization] = input.forwardedAuthorization;
273
- if (input.parentTurnId !== void 0) out[FORWARD_HEADERS.parentTurnId] = input.parentTurnId;
274
- return out;
275
- }
276
- function pickHeader(headers, name) {
277
- const target = lc(name);
278
- for (const key of Object.keys(headers)) if (lc(key) === target) {
279
- const value = headers[key];
280
- if (Array.isArray(value)) return value[0];
281
- return value;
282
- }
283
- }
284
- //#endregion
285
- //#region src/conversation/turn-id.ts
286
- /**
287
- *
288
- * Deterministic turn identifier. Stable across retries of the same logical
289
- * turn so backends (and any caching gateway in between) can dedupe on it.
290
- * A retry triggered by a network blip or deadline timeout MUST produce the
291
- * same `turn_id`; only the underlying attempt count differs.
292
- *
293
- * Shape: `${runId}.t${index}.${speakerSlug}` — readable in logs, sortable by
294
- * turn index, attributable to a speaker. Slugify keeps the speaker portion
295
- * URL-safe so it can ride in HTTP headers without escaping.
296
- *
297
- * @stable
298
- */
299
- function turnId(runId, index, speaker) {
300
- return `${runId}.t${index}.${slugifySpeaker(speaker)}`;
301
- }
302
- /**
303
- * Reduce a speaker name to ASCII alphanumerics + dashes. Preserves enough
304
- * substance to read in a log line; collisions between speakers within a
305
- * single Conversation are prevented by `defineConversation`'s
306
- * unique-name check, so the slug only needs to be deterministic, not unique.
307
- */
308
- function slugifySpeaker(speaker) {
309
- return speaker.normalize("NFKD").replace(/[^\w-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase() || "anon";
310
- }
311
- //#endregion
312
- //#region src/conversation/run-conversation.ts
313
- /** Run a conversation to completion and return its terminal result. */
314
- async function runConversation(conversation, options) {
315
- let result;
316
- for await (const event of runConversationStream(conversation, options)) {
317
- if (options.onEvent) await options.onEvent(event);
318
- if (event.type === "conversation_end") result = event.result;
319
- }
320
- if (!result) throw new BackendTransportError("conversation", "conversation stream ended without a conversation_end event");
321
- return result;
322
- }
323
- /** Streaming conversation orchestrator: drives N participants in turn through their own backends, enforcing `maxTurns` / `maxCreditsCents` / `haltOn`, yielding per-event stream markers. */
324
- async function* runConversationStream(conversation, options) {
325
- const runId = options.runId ?? `conv_${crypto.randomUUID()}`;
326
- const inboundDepth = options.inboundDepth ?? 0;
327
- const forwardedAuthorization = (options.propagatedHeaders ?? {})[FORWARD_HEADERS.authorization];
328
- const breakers = /* @__PURE__ */ new Map();
329
- for (const participant of conversation.participants) {
330
- const cfg = participant.callPolicy?.circuitBreaker ?? conversation.policy.defaultCallPolicy?.circuitBreaker;
331
- breakers.set(participant.name, new CircuitBreakerState(cfg));
332
- }
333
- let transcript = [];
334
- let spentCreditsCents = 0;
335
- let startedAt = nowIso();
336
- let resumed = false;
337
- const sessionStore = options.sessionStore ?? new InMemoryRuntimeSessionStore();
338
- if (options.journal) {
339
- const prior = await options.journal.loadRun(runId);
340
- if (prior) {
341
- if (prior.halted) {
342
- const replayResult = {
343
- runId,
344
- transcript: prior.turns,
345
- turns: prior.turns.length,
346
- spentCreditsCents: prior.turns.reduce((sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0), 0),
347
- halted: prior.halted,
348
- durationMs: 0,
349
- startedAt: prior.startedAt,
350
- endedAt: prior.endedAt ?? prior.startedAt
351
- };
352
- yield {
353
- type: "conversation_resumed",
354
- runId,
355
- participants: conversation.participants.map((p) => p.name),
356
- transcript: prior.turns,
357
- timestamp: nowIso()
358
- };
359
- yield {
360
- type: "conversation_end",
361
- runId,
362
- result: replayResult,
363
- timestamp: nowIso()
364
- };
365
- return;
366
- }
367
- transcript = [...prior.turns];
368
- spentCreditsCents = transcript.reduce((sum, t) => sum + centsFromUsd(t.usage?.costUsd ?? 0), 0);
369
- startedAt = prior.startedAt;
370
- resumed = true;
371
- } else await options.journal.beginRun(runId, startedAt);
372
- }
373
- const startedAtMs = Date.now();
374
- const participantSessions = sessionIdsFrom(transcript);
375
- if (resumed) yield {
376
- type: "conversation_resumed",
377
- runId,
378
- participants: conversation.participants.map((p) => p.name),
379
- transcript: [...transcript],
380
- timestamp: nowIso()
381
- };
382
- else yield {
383
- type: "conversation_start",
384
- runId,
385
- participants: conversation.participants.map((p) => p.name),
386
- seed: options.seed,
387
- timestamp: startedAt
388
- };
389
- let currentInput = transcript.length === 0 ? options.seed : transcript[transcript.length - 1]?.text ?? options.seed;
390
- let halt;
391
- const initialOffset = transcript.length;
392
- for (let turnIndex = initialOffset; turnIndex < conversation.policy.maxTurns; turnIndex++) {
393
- if (options.signal?.aborted) {
394
- halt = { kind: "abort" };
395
- break;
396
- }
397
- if (conversation.policy.maxCreditsCents !== void 0 && spentCreditsCents >= conversation.policy.maxCreditsCents) {
398
- halt = {
399
- kind: "max_credits",
400
- spentCents: spentCreditsCents,
401
- capCents: conversation.policy.maxCreditsCents
402
- };
403
- break;
404
- }
405
- const speakerIdx = selectSpeaker(conversation.policy.turnOrder, conversation.participants.length, {
406
- transcript,
407
- turnIndex,
408
- spentCreditsCents
409
- });
410
- const speaker = conversation.participants[speakerIdx];
411
- if (!speaker) throw new BackendTransportError("conversation", `turnOrder selector returned out-of-range index ${speakerIdx} for ${conversation.participants.length} participants`);
412
- const tid = turnId(runId, turnIndex, speaker.name);
413
- const callPolicy = speaker.callPolicy ?? conversation.policy.defaultCallPolicy;
414
- const breaker = breakers.get(speaker.name);
415
- if (!breaker) throw new BackendTransportError("conversation", `internal: no circuit-breaker state registered for participant '${speaker.name}'`);
416
- const isRetryable = callPolicy?.isRetryable ?? defaultIsRetryable;
417
- const totalAttempts = 1 + (callPolicy?.maxRetries ?? 0);
418
- yield {
419
- type: "turn_start",
420
- runId,
421
- index: turnIndex,
422
- speaker: speaker.name,
423
- turnId: tid,
424
- attempt: 1,
425
- timestamp: nowIso()
426
- };
427
- let aggregator;
428
- let attemptCount = 0;
429
- let lastError;
430
- let breakerOpenFailure;
431
- for (let attempt = 1; attempt <= totalAttempts; attempt++) {
432
- attemptCount = attempt;
433
- try {
434
- breaker.preflight(speaker.name);
435
- } catch (err) {
436
- breakerOpenFailure = err;
437
- break;
438
- }
439
- if (attempt > 1) yield {
440
- type: "turn_retry",
441
- runId,
442
- index: turnIndex,
443
- speaker: speaker.name,
444
- turnId: tid,
445
- attempt,
446
- reason: lastError instanceof Error ? lastError.message : String(lastError),
447
- timestamp: nowIso()
448
- };
449
- const perAttempt = makePerAttemptSignal(options.signal, callPolicy?.perAttemptDeadlineMs);
450
- const localAgg = new TurnAggregator({
451
- index: turnIndex,
452
- speaker: speaker.name,
453
- startedAt: nowIso()
454
- });
455
- try {
456
- for await (const delta of driveSingleAttempt({
457
- speaker,
458
- participants: conversation.participants,
459
- seed: options.seed,
460
- input: currentInput,
461
- turnIndex,
462
- runId,
463
- turnId: tid,
464
- transcript,
465
- participantSessions,
466
- sessionStore,
467
- signal: perAttempt.signal,
468
- aggregator: localAgg,
469
- propagatedHeaders: buildForwardHeaders({
470
- inboundDepth,
471
- forwardedAuthorization: resolveAuthForwarding(speaker, {
472
- transcript,
473
- turnIndex,
474
- spentCreditsCents
475
- }) ? forwardedAuthorization : void 0,
476
- runId,
477
- turnId: tid,
478
- parentTurnId: options.parentTurnId,
479
- speaker: speaker.name
480
- })
481
- })) yield {
482
- type: "turn_text_delta",
483
- runId,
484
- index: turnIndex,
485
- speaker: speaker.name,
486
- turnId: tid,
487
- text: delta.text,
488
- timestamp: delta.timestamp
489
- };
490
- perAttempt.dispose();
491
- breaker.recordSuccess();
492
- aggregator = localAgg;
493
- break;
494
- } catch (err) {
495
- perAttempt.dispose();
496
- breaker.recordFailure();
497
- lastError = perAttempt.getDeadlineError() ?? err;
498
- if (attempt >= totalAttempts || !isRetryable(lastError)) break;
499
- await sleep(computeBackoff(callPolicy?.retryBackoffMs, attempt));
500
- }
501
- }
502
- if (!aggregator) {
503
- const failure = breakerOpenFailure ?? lastError;
504
- const message = failure instanceof Error ? failure.message : String(failure);
505
- halt = {
506
- kind: "participant_error",
507
- participant: speaker.name,
508
- message
509
- };
510
- break;
511
- }
512
- const turn = aggregator.toTurn({
513
- turnId: tid,
514
- attempts: attemptCount
515
- });
516
- if (turn.sessionId) bindParticipantSession(participantSessions, turn.speaker, turn.sessionId);
517
- transcript.push(turn);
518
- spentCreditsCents += centsFromUsd(turn.usage?.costUsd ?? 0);
519
- if (options.journal) await options.journal.appendTurn(runId, turn);
520
- yield {
521
- type: "turn_end",
522
- runId,
523
- turn,
524
- timestamp: nowIso()
525
- };
526
- if (conversation.policy.haltOn) {
527
- const haltCtx = {
528
- transcript,
529
- lastTurn: turn,
530
- turnIndex,
531
- spentCreditsCents
532
- };
533
- const decision = await conversation.policy.haltOn(haltCtx);
534
- if (decision === true) {
535
- halt = {
536
- kind: "predicate",
537
- reason: "predicate_true"
538
- };
539
- break;
540
- }
541
- if (typeof decision === "object" && decision !== null && decision.halted) {
542
- halt = {
543
- kind: "predicate",
544
- reason: decision.reason
545
- };
546
- break;
547
- }
548
- }
549
- currentInput = turn.text;
550
- }
551
- if (!halt) halt = {
552
- kind: "max_turns",
553
- turns: transcript.length
554
- };
555
- const endedAt = nowIso();
556
- const result = {
557
- runId,
558
- transcript,
559
- turns: transcript.length,
560
- spentCreditsCents,
561
- halted: halt,
562
- durationMs: Date.now() - startedAtMs,
563
- startedAt,
564
- endedAt
565
- };
566
- if (options.journal) await options.journal.recordHalt(runId, halt, endedAt);
567
- yield {
568
- type: "conversation_end",
569
- runId,
570
- result,
571
- timestamp: endedAt
572
- };
573
- }
574
- async function* driveSingleAttempt(args) {
575
- const task = {
576
- id: args.turnId,
577
- intent: args.input,
578
- metadata: {
579
- runId: args.runId,
580
- turnId: args.turnId,
581
- turnIndex: args.turnIndex,
582
- speaker: args.speaker.name,
583
- participants: args.participants.map((p) => p.name)
584
- }
585
- };
586
- const knowledge = passingReadiness(task.id);
587
- const startCtx = {
588
- task,
589
- knowledge,
590
- signal: args.signal,
591
- runId: args.runId,
592
- turnId: args.turnId,
593
- propagatedHeaders: args.propagatedHeaders
594
- };
595
- const previousSessionId = args.participantSessions.get(args.speaker.name);
596
- const opened = await startOrResumeRuntimeSession({
597
- backend: args.speaker.backend,
598
- input: () => fullConversationInput(task, args.speaker.name, args.seed, args.transcript),
599
- continuationInput: () => continuedConversationInput(task, args.speaker.name, args.transcript),
600
- context: startCtx,
601
- store: args.sessionStore,
602
- sessionId: previousSessionId ?? participantSessionId(args.runId, args.speaker.name, args.participants),
603
- resume: previousSessionId !== void 0 && args.speaker.backend.resume !== void 0,
604
- validateSession: (session) => assertParticipantSessionAvailable(args.participantSessions, args.speaker.name, session.id)
605
- });
606
- const session = opened.session;
607
- args.aggregator.recordSession(session.id);
608
- const streamCtx = {
609
- task,
610
- knowledge,
611
- session,
612
- signal: args.signal,
613
- runId: args.runId,
614
- turnId: args.turnId,
615
- propagatedHeaders: args.propagatedHeaders
616
- };
617
- for await (const event of args.speaker.backend.stream(opened.input, streamCtx)) {
618
- if (args.signal.aborted) {
619
- const reason = args.signal.reason;
620
- throw reason instanceof Error ? reason : /* @__PURE__ */ new Error("aborted");
621
- }
622
- if (event.type === "text_delta") {
623
- args.aggregator.appendText(event.text);
624
- yield {
625
- text: event.text,
626
- timestamp: event.timestamp
627
- };
628
- } else if (event.type === "llm_call") args.aggregator.recordUsage(event);
629
- else if (event.type === "backend_error") throw new BackendTransportError(args.speaker.backend.kind, event.message, {
630
- status: event.error?.status,
631
- body: event.error?.body
632
- });
633
- else if (event.type === "final") {
634
- if (event.status !== "completed") throw new BackendTransportError(args.speaker.backend.kind, event.error?.message ?? event.reason, {
635
- status: event.error?.status,
636
- body: event.error?.body
637
- });
638
- args.aggregator.adoptFinalText(event.text);
639
- }
640
- }
641
- if (!args.aggregator.hasText()) throw new BackendTransportError(args.speaker.backend.kind, `backend '${args.speaker.backend.kind}' completed without text`);
642
- }
643
- var TurnAggregator = class {
644
- base;
645
- text = "";
646
- adoptedFinal = false;
647
- sessionId;
648
- usage;
649
- constructor(base) {
650
- this.base = base;
651
- }
652
- appendText(text) {
653
- if (this.adoptedFinal) return;
654
- this.text += text;
655
- }
656
- /**
657
- * Use the backend's `final.text` only when no streamed deltas were observed.
658
- * Some backends emit deltas AND a final summary; treating both as content
659
- * would double-count.
660
- */
661
- adoptFinalText(text) {
662
- if (!text) return;
663
- if (this.text.length > 0) return;
664
- this.text = text;
665
- this.adoptedFinal = true;
666
- }
667
- hasText() {
668
- return this.text.trim().length > 0;
669
- }
670
- recordSession(sessionId) {
671
- this.sessionId = sessionId;
672
- }
673
- recordUsage(event) {
674
- const u = this.usage ?? {};
675
- if (event.tokensIn !== void 0) u.tokensIn = (u.tokensIn ?? 0) + event.tokensIn;
676
- if (event.tokensOut !== void 0) u.tokensOut = (u.tokensOut ?? 0) + event.tokensOut;
677
- if (event.costUsd !== void 0) u.costUsd = (u.costUsd ?? 0) + event.costUsd;
678
- if (event.latencyMs !== void 0) u.latencyMs = event.latencyMs;
679
- if (event.model !== void 0) u.model = event.model;
680
- this.usage = u;
681
- }
682
- toTurn(meta) {
683
- return {
684
- index: this.base.index,
685
- speaker: this.base.speaker,
686
- turnId: meta.turnId,
687
- ...this.sessionId ? { sessionId: this.sessionId } : {},
688
- text: this.text.trim(),
689
- usage: this.usage,
690
- attempts: meta.attempts,
691
- startedAt: this.base.startedAt,
692
- endedAt: nowIso()
693
- };
694
- }
695
- };
696
- /**
697
- * Build the participant's POV of the transcript so an OpenAI-compatible
698
- * backend sees its own turns as `assistant` and everyone else's as `user`,
699
- * with explicit speaker tags so 3+ party conversations stay disambiguated.
700
- */
701
- function buildMessagesFor(speakerName, seed, transcript) {
702
- const messages = seed ? [{
703
- role: "user",
704
- content: seed
705
- }] : [];
706
- for (const turn of transcript) if (turn.speaker === speakerName) messages.push({
707
- role: "assistant",
708
- content: turn.text
709
- });
710
- else messages.push({
711
- role: "user",
712
- content: `[${turn.speaker}] ${turn.text}`
713
- });
714
- return messages;
715
- }
716
- function fullConversationInput(task, speakerName, seed, transcript) {
717
- return {
718
- task,
719
- message: [seed, ...transcript.map((turn) => `[${turn.speaker}] ${turn.text}`)].filter((part) => part.length > 0).join("\n\n"),
720
- messages: buildMessagesFor(speakerName, seed, transcript)
721
- };
722
- }
723
- function continuedConversationInput(task, speakerName, transcript) {
724
- let lastOwnTurn = -1;
725
- for (let index = transcript.length - 1; index >= 0; index -= 1) if (transcript[index]?.speaker === speakerName) {
726
- lastOwnTurn = index;
727
- break;
728
- }
729
- const unseen = transcript.slice(lastOwnTurn + 1);
730
- const message = unseen.length > 0 ? unseen.map((turn) => `[${turn.speaker}] ${turn.text}`).join("\n\n") : "Continue.";
731
- return {
732
- task,
733
- message,
734
- messages: [{
735
- role: "user",
736
- content: message
737
- }]
738
- };
739
- }
740
- function sessionIdsFrom(transcript) {
741
- const sessions = /* @__PURE__ */ new Map();
742
- for (const turn of transcript) if (turn.sessionId) bindParticipantSession(sessions, turn.speaker, turn.sessionId);
743
- return sessions;
744
- }
745
- function bindParticipantSession(sessions, speakerName, sessionId) {
746
- assertParticipantSessionAvailable(sessions, speakerName, sessionId);
747
- sessions.set(speakerName, sessionId);
748
- }
749
- function assertParticipantSessionAvailable(sessions, speakerName, sessionId) {
750
- for (const [boundSpeaker, boundSessionId] of sessions) if (boundSpeaker !== speakerName && boundSessionId === sessionId) throw new BackendTransportError("conversation", `session '${sessionId}' is already bound to participant '${boundSpeaker}'`);
751
- }
752
- function participantSessionId(runId, speakerName, participants) {
753
- const participantIndex = participants.findIndex((participant) => participant.name === speakerName);
754
- if (participantIndex < 0) throw new BackendTransportError("conversation", `participant '${speakerName}' is not registered in this conversation`);
755
- return `${runId}.participant.${participantIndex}.${slugifySpeaker(speakerName)}`;
756
- }
757
- /**
758
- * True when this participant should forward the caller's
759
- * `X-Tangle-Forwarded-Authorization` on outbound calls (the "pass-through"
760
- * commercial mode). False when it elects to pay for its own outbound calls
761
- * (the "reseller" / "bundle" mode). See ConversationParticipant.authSource.
762
- */
763
- function resolveAuthForwarding(participant, state) {
764
- return (typeof participant.authSource === "function" ? participant.authSource(state) : participant.authSource ?? "forward-user") === "forward-user";
765
- }
766
- function selectSpeaker(order, participantCount, state) {
767
- const resolved = order ?? (participantCount === 2 ? "alternate" : "round-robin");
768
- if (resolved === "alternate" || resolved === "round-robin") return state.turnIndex % participantCount;
769
- if (typeof resolved === "function") {
770
- const idx = resolved(state);
771
- if (!Number.isInteger(idx) || idx < 0 || idx >= participantCount) throw new BackendTransportError("conversation", `turnOrder function returned invalid index ${String(idx)} for ${participantCount} participants`);
772
- return idx;
773
- }
774
- throw new BackendTransportError("conversation", `unknown turnOrder: ${String(resolved)}`);
775
- }
776
- function centsFromUsd(usd) {
777
- return Math.round(usd * 100);
778
- }
779
- /**
780
- * Synthesize a knowledge-readiness report that *passes* every gate, used to
781
- * satisfy `AgentBackendContext.knowledge` per turn. Conversations don't apply
782
- * task-level readiness gating per-turn — that's a `runAgentTask` concern.
783
- */
784
- function passingReadiness(taskId) {
785
- return {
786
- taskId,
787
- readinessScore: 1,
788
- blockingMissingRequirements: [],
789
- nonBlockingGaps: [],
790
- recommendedAction: "run_agent",
791
- bundle: {
792
- taskId,
793
- requirements: [],
794
- evidenceIds: [],
795
- claimIds: [],
796
- wikiPageIds: [],
797
- userAnswers: {},
798
- missing: [],
799
- readinessScore: 1
800
- },
801
- severity: "info",
802
- reason: "conversation-mode: readiness gating not applied per-turn"
803
- };
804
- }
805
- //#endregion
806
- //#region src/conversation/conversation-backend.ts
807
- /**
808
- *
809
- * Wrap a `Conversation` so it satisfies `AgentExecutionBackend`. The result is
810
- * an addressable "single agent" whose internal behavior is an N-party
811
- * orchestrated conversation — the recursion primitive that lets a swarm be a
812
- * participant inside another swarm, or be published behind a single
813
- * agent-gateway endpoint.
814
- *
815
- * Stream events from inner participants are NOT forwarded verbatim. Outer
816
- * callers see one `text_delta` per inner turn (the turn's full text), tagged
817
- * with `[speaker] ` prefix so the outer transcript stays attributable. The
818
- * conversation's `conversation_end` halt reason rides on a `final` event.
819
- *
820
- * @stable
821
- */
822
- /** Adapt a multi-participant conversation into the standard execution backend contract. */
823
- function createConversationBackend(options) {
824
- const kind = options.kind ?? "conversation";
825
- return {
826
- kind,
827
- start(_input, context) {
828
- return newRuntimeSession(kind, context.requestedSessionId, { participants: options.conversation.participants.map((p) => p.name) });
829
- },
830
- async *stream(input, context) {
831
- const seed = input.message ?? input.messages?.at(-1)?.content ?? providerMessageText(input.providerOptions) ?? context.task.intent;
832
- const task = context.task;
833
- const session = context.session;
834
- yield {
835
- type: "backend_start",
836
- task,
837
- session,
838
- backend: kind,
839
- timestamp: nowIso()
840
- };
841
- let finalText = "";
842
- let totalCostUsd = 0;
843
- let totalTokensIn = 0;
844
- let totalTokensOut = 0;
845
- const inboundDepth = parseInboundDepth(context.propagatedHeaders);
846
- for await (const event of runConversationStream(options.conversation, {
847
- seed,
848
- signal: context.signal,
849
- runId: context.runId,
850
- propagatedHeaders: context.propagatedHeaders,
851
- inboundDepth,
852
- parentTurnId: context.turnId
853
- })) if (event.type === "turn_end") {
854
- const tagged = `[${event.turn.speaker}] ${event.turn.text}\n`;
855
- finalText += tagged;
856
- yield {
857
- type: "text_delta",
858
- task,
859
- session,
860
- text: tagged,
861
- timestamp: event.timestamp
862
- };
863
- if (event.turn.usage) {
864
- const u = event.turn.usage;
865
- if (u.costUsd !== void 0) totalCostUsd += u.costUsd;
866
- if (u.tokensIn !== void 0) totalTokensIn += u.tokensIn;
867
- if (u.tokensOut !== void 0) totalTokensOut += u.tokensOut;
868
- yield {
869
- type: "llm_call",
870
- task,
871
- session,
872
- model: u.model ?? `${kind}/${event.turn.speaker}`,
873
- tokensIn: u.tokensIn,
874
- tokensOut: u.tokensOut,
875
- costUsd: u.costUsd,
876
- latencyMs: u.latencyMs,
877
- timestamp: event.timestamp
878
- };
879
- }
880
- } else if (event.type === "conversation_end") {
881
- const halt = event.result.halted;
882
- yield {
883
- type: "final",
884
- task,
885
- session,
886
- status: halt.kind === "participant_error" ? "failed" : "completed",
887
- reason: describeHalt(halt),
888
- text: finalText.trim(),
889
- metadata: {
890
- conversationRunId: event.result.runId,
891
- turns: event.result.turns,
892
- spentCreditsCents: event.result.spentCreditsCents,
893
- halted: halt,
894
- durationMs: event.result.durationMs,
895
- tokensIn: totalTokensIn,
896
- tokensOut: totalTokensOut,
897
- costUsd: totalCostUsd
898
- },
899
- timestamp: event.timestamp
900
- };
901
- }
902
- yield {
903
- type: "backend_end",
904
- task,
905
- session,
906
- backend: kind,
907
- timestamp: nowIso()
908
- };
909
- }
910
- };
911
- }
912
- function parseInboundDepth(headers) {
913
- if (!headers) return 0;
914
- const raw = headers[FORWARD_HEADERS.depth];
915
- if (raw === void 0) return 0;
916
- try {
917
- return readDepth({ [FORWARD_HEADERS.depth]: raw });
918
- } catch {
919
- return 0;
920
- }
921
- }
922
- function describeHalt(halt) {
923
- switch (halt.kind) {
924
- case "max_turns": return `max_turns (${halt.turns})`;
925
- case "max_credits": return `max_credits (${halt.spentCents}/${halt.capCents}¢)`;
926
- case "predicate": return `predicate: ${halt.reason}`;
927
- case "abort": return "abort";
928
- case "participant_error": return `participant_error[${halt.participant}]: ${halt.message}`;
929
- }
930
- }
931
- //#endregion
932
- //#region src/conversation/define-conversation.ts
933
- /**
934
- *
935
- * Declarative constructor for a multi-agent `Conversation`. Validates inputs
936
- * fail-loud at definition time (duplicate participant names, alternate order
937
- * with ≠2 participants, non-positive `maxTurns`) so misconfiguration is caught
938
- * before `runConversation` is called and not buried inside a streaming run.
939
- *
940
- * @stable
941
- */
942
- /** Validate and define a conversation before execution. */
943
- function defineConversation(input) {
944
- if (input.participants.length < 2) throw new ValidationError(`Conversation requires at least 2 participants; received ${input.participants.length}.`);
945
- const seen = /* @__PURE__ */ new Set();
946
- for (const p of input.participants) {
947
- if (!p.name || p.name.trim() === "") throw new ValidationError("Conversation participant.name must be a non-empty string.");
948
- if (seen.has(p.name)) throw new ValidationError(`Conversation participant names must be unique within a Conversation; '${p.name}' appears more than once.`);
949
- seen.add(p.name);
950
- if (!p.backend || typeof p.backend.stream !== "function") throw new ValidationError(`Conversation participant '${p.name}' is missing a backend with a stream() method.`);
951
- }
952
- const policy = normalizePolicy(input.policy, input.participants.length);
953
- return {
954
- participants: input.participants,
955
- policy
956
- };
957
- }
958
- function normalizePolicy(policy, participantCount) {
959
- if (!Number.isInteger(policy.maxTurns) || policy.maxTurns < 1) throw new ValidationError(`ConversationPolicy.maxTurns must be a positive integer; received ${String(policy.maxTurns)}.`);
960
- if (policy.maxCreditsCents !== void 0 && (!Number.isFinite(policy.maxCreditsCents) || policy.maxCreditsCents < 0)) throw new ValidationError(`ConversationPolicy.maxCreditsCents must be a non-negative finite number when set; received ${String(policy.maxCreditsCents)}.`);
961
- const turnOrder = policy.turnOrder ?? (participantCount === 2 ? "alternate" : "round-robin");
962
- if (turnOrder === "alternate" && participantCount !== 2) throw new ValidationError(`ConversationPolicy.turnOrder 'alternate' requires exactly 2 participants; received ${participantCount}. Use 'round-robin' or a custom selector for N-party conversations.`);
963
- return {
964
- ...policy,
965
- turnOrder
966
- };
967
- }
968
- //#endregion
969
- //#region src/conversation/journal.ts
970
- /**
971
- *
972
- * Durable conversation transcript — survives a driver process crash mid-run.
973
- * The runner journals every committed turn before yielding `turn_end`, so a
974
- * resumed run replays the same `runId` against the same journal and picks up
975
- * from the first un-recorded turn. Combined with the deterministic
976
- * `turnId(runId, index, speaker)`, a retried turn collides with the prior
977
- * attempt's id and any caching gateway can dedupe.
978
- *
979
- * The interface is small enough that a Cloudflare D1 / R2 / postgres adapter
980
- * is ~30 lines. The in-memory adapter is the default for tests and scratch.
981
- * The file adapter (JSONL on disk) is the default-durable choice when no
982
- * upstream store is wired.
983
- *
984
- * @stable
985
- */
986
- /** In-memory `ConversationJournal` — suitable for testing and single-process runs. */
987
- var InMemoryConversationJournal = class {
988
- entries = /* @__PURE__ */ new Map();
989
- async loadRun(runId) {
990
- const entry = this.entries.get(runId);
991
- if (!entry) return void 0;
992
- return {
993
- runId: entry.runId,
994
- startedAt: entry.startedAt,
995
- halted: entry.halted,
996
- endedAt: entry.endedAt,
997
- turns: [...entry.turns]
998
- };
999
- }
1000
- async beginRun(runId, startedAt) {
1001
- const existing = this.entries.get(runId);
1002
- if (existing) {
1003
- if (existing.startedAt !== startedAt) throw new Error(`runId '${runId}' already exists with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`);
1004
- return;
1005
- }
1006
- this.entries.set(runId, {
1007
- runId,
1008
- startedAt,
1009
- turns: []
1010
- });
1011
- }
1012
- async appendTurn(runId, turn) {
1013
- const entry = this.entries.get(runId);
1014
- if (!entry) throw new Error(`appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`);
1015
- if (entry.halted) throw new Error(`cannot append turn to halted run '${runId}' (halt reason: ${JSON.stringify(entry.halted)})`);
1016
- entry.turns.push(turn);
1017
- }
1018
- async recordHalt(runId, halt, endedAt) {
1019
- const entry = this.entries.get(runId);
1020
- if (!entry) throw new Error(`recordHalt called for unknown runId '${runId}'`);
1021
- entry.halted = halt;
1022
- entry.endedAt = endedAt;
1023
- }
1024
- };
1025
- /**
1026
- * JSONL on disk. One line per record; first line is the `begin`, subsequent
1027
- * lines are `turn` records, terminal line is `halt`. Replays the whole file
1028
- * on `loadRun` — cheap for the conversation sizes this is designed for
1029
- * (thousands of turns, not millions). For huge runs, plug in a real DB
1030
- * adapter; the interface is small.
1031
- *
1032
- * Reads and appends over the shared append-only spine (`durable/jsonl-file`): each
1033
- * `appendTurn` / `recordHalt` finishes a short write and calls `fsync`, so a process
1034
- * crash between writes never loses an acknowledged turn, and a crash DURING one leaves
1035
- * an uncommitted final line that the next read skips and the next append truncates.
1036
- */
1037
- var FileConversationJournal = class {
1038
- path;
1039
- constructor(path) {
1040
- this.path = path;
1041
- }
1042
- async loadRun(runId) {
1043
- const fs = await import("node:fs/promises");
1044
- let text;
1045
- try {
1046
- text = await fs.readFile(this.path, "utf8");
1047
- } catch (err) {
1048
- if (isNoEntError(err)) return void 0;
1049
- throw err;
1050
- }
1051
- let entry;
1052
- for (const record of parseCommittedJsonLines(text, this.path)) {
1053
- if (record.runId !== runId) continue;
1054
- if (record.kind === "begin") entry = {
1055
- runId,
1056
- startedAt: record.startedAt,
1057
- turns: []
1058
- };
1059
- else if (record.kind === "turn") {
1060
- if (!entry) throw new Error(`journal corrupted: turn record for runId '${runId}' precedes its begin record`);
1061
- entry.turns.push(record.turn);
1062
- } else if (record.kind === "halt") {
1063
- if (!entry) throw new Error(`journal corrupted: halt record for runId '${runId}' precedes its begin record`);
1064
- entry.halted = record.halted;
1065
- entry.endedAt = record.endedAt;
1066
- }
1067
- }
1068
- return entry;
1069
- }
1070
- async beginRun(runId, startedAt) {
1071
- const existing = await this.loadRun(runId);
1072
- if (existing) {
1073
- if (existing.startedAt !== startedAt) throw new Error(`runId '${runId}' already exists in ${this.path} with startedAt=${existing.startedAt}; refusing to overwrite with ${startedAt}`);
1074
- return;
1075
- }
1076
- await this.appendRecord({
1077
- kind: "begin",
1078
- runId,
1079
- startedAt
1080
- });
1081
- }
1082
- async appendTurn(runId, turn) {
1083
- await this.appendRecord({
1084
- kind: "turn",
1085
- runId,
1086
- turn
1087
- });
1088
- }
1089
- async recordHalt(runId, halt, endedAt) {
1090
- await this.appendRecord({
1091
- kind: "halt",
1092
- runId,
1093
- halted: halt,
1094
- endedAt
1095
- });
1096
- }
1097
- async appendRecord(record) {
1098
- const fs = await import("node:fs/promises");
1099
- const path = await import("node:path");
1100
- await fs.mkdir(path.dirname(this.path), { recursive: true });
1101
- const needsSeparator = await prepareJsonlAppend(this.path);
1102
- const fh = await fs.open(this.path, "a");
1103
- try {
1104
- await writeAllBytes(fh, `${needsSeparator ? "\n" : ""}${JSON.stringify(record)}\n`);
1105
- await fh.sync();
1106
- } finally {
1107
- await fh.close();
1108
- }
1109
- }
1110
- };
1111
- //#endregion
1112
- //#region src/conversation/journal-sql.ts
1113
- /**
1114
- * Adapt a Cloudflare D1 binding to the SqlAdapter shape. Lives here so D1
1115
- * consumers don't have to write the wrapper themselves; the runtime never
1116
- * imports `@cloudflare/workers-types` directly (peer-style typing).
1117
- */
1118
- function d1ToSqlAdapter(db) {
1119
- return {
1120
- async exec(sql, params = []) {
1121
- const stmt = db.prepare(sql);
1122
- const meta = (await (params.length > 0 ? stmt.bind(...params) : stmt).run()).meta;
1123
- return { rowsAffected: meta?.rows_written ?? meta?.changes ?? 0 };
1124
- },
1125
- async query(sql, params = []) {
1126
- const stmt = db.prepare(sql);
1127
- return (await (params.length > 0 ? stmt.bind(...params) : stmt).all()).results ?? [];
1128
- }
1129
- };
1130
- }
1131
- const RUNS_TABLE_DDL = (table) => `
1132
- CREATE TABLE IF NOT EXISTS ${table}_runs (
1133
- run_id TEXT PRIMARY KEY,
1134
- started_at TEXT NOT NULL,
1135
- halted_kind TEXT,
1136
- halted_payload TEXT,
1137
- ended_at TEXT
1138
- )
1139
- `;
1140
- const TURNS_TABLE_DDL = (table) => `
1141
- CREATE TABLE IF NOT EXISTS ${table}_turns (
1142
- run_id TEXT NOT NULL,
1143
- turn_index INTEGER NOT NULL,
1144
- payload TEXT NOT NULL,
1145
- PRIMARY KEY (run_id, turn_index)
1146
- )
1147
- `;
1148
- const TURNS_INDEX_DDL = (table) => `
1149
- CREATE INDEX IF NOT EXISTS idx_${table}_turns_run ON ${table}_turns (run_id, turn_index)
1150
- `;
1151
- /**
1152
- * SQL-backed ConversationJournal. Two tables — runs (one row per runId, holds
1153
- * start/halt timestamps + halt reason) and turns (one row per committed turn,
1154
- * payload is the ConversationTurn JSON). Replays the turns table on
1155
- * `loadRun` and writes append-only per `appendTurn`.
1156
- */
1157
- var SqlConversationJournal = class {
1158
- db;
1159
- table;
1160
- /**
1161
- * @param db SQL adapter (D1, postgres, sqlite, libSQL — all work)
1162
- * @param table Table-name prefix; the journal creates `${table}_runs` and
1163
- * `${table}_turns`. Lets multiple journals share a database
1164
- * without colliding (e.g. one per product surface).
1165
- */
1166
- constructor(db, table = "agent_runtime_journal") {
1167
- this.db = db;
1168
- this.table = table;
1169
- }
1170
- /**
1171
- * Create the journal's tables if absent. Idempotent. Call once at deploy
1172
- * (or at app boot) — running on every request is harmless but adds latency.
1173
- */
1174
- async migrate() {
1175
- await this.db.exec(RUNS_TABLE_DDL(this.table));
1176
- await this.db.exec(TURNS_TABLE_DDL(this.table));
1177
- await this.db.exec(TURNS_INDEX_DDL(this.table));
1178
- }
1179
- async loadRun(runId) {
1180
- 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];
1181
- if (!row) return void 0;
1182
- const turns = await this.db.query(`SELECT payload, turn_index FROM ${this.table}_turns WHERE run_id = ? ORDER BY turn_index ASC`, [runId]);
1183
- return {
1184
- runId: row.run_id,
1185
- startedAt: row.started_at,
1186
- halted: row.halted_payload ? JSON.parse(row.halted_payload) : void 0,
1187
- endedAt: row.ended_at ?? void 0,
1188
- turns: turns.map((t) => JSON.parse(t.payload))
1189
- };
1190
- }
1191
- async beginRun(runId, startedAt) {
1192
- const existing = await this.db.query(`SELECT started_at FROM ${this.table}_runs WHERE run_id = ?`, [runId]);
1193
- if (existing.length > 0) {
1194
- if (existing[0]?.started_at !== startedAt) throw new Error(`runId '${runId}' already exists with startedAt=${existing[0]?.started_at}; refusing to overwrite with ${startedAt}`);
1195
- return;
1196
- }
1197
- await this.db.exec(`INSERT INTO ${this.table}_runs (run_id, started_at) VALUES (?, ?)`, [runId, startedAt]);
1198
- }
1199
- async appendTurn(runId, turn) {
1200
- const halted = await this.db.query(`SELECT halted_kind FROM ${this.table}_runs WHERE run_id = ?`, [runId]);
1201
- if (halted.length === 0) throw new Error(`appendTurn called for unknown runId '${runId}'; call beginRun first or use the runner which handles it`);
1202
- if (halted[0]?.halted_kind) throw new Error(`cannot append turn to halted run '${runId}' (halt kind: ${halted[0]?.halted_kind})`);
1203
- await this.db.exec(`INSERT INTO ${this.table}_turns (run_id, turn_index, payload) VALUES (?, ?, ?)`, [
1204
- runId,
1205
- turn.index,
1206
- JSON.stringify(turn)
1207
- ]);
1208
- }
1209
- async recordHalt(runId, halt, endedAt) {
1210
- if ((await this.db.exec(`UPDATE ${this.table}_runs SET halted_kind = ?, halted_payload = ?, ended_at = ? WHERE run_id = ?`, [
1211
- halt.kind,
1212
- JSON.stringify(halt),
1213
- endedAt,
1214
- runId
1215
- ])).rowsAffected === 0) throw new Error(`recordHalt called for unknown runId '${runId}'`);
1216
- }
1217
- };
1218
- //#endregion
1219
- //#region src/conversation/run-persona.ts
1220
- /** Adapt one exact profile + Runtime executor into the conversation stream protocol. */
1221
- function profileRuntimeBackend(profile, factory, counter) {
1222
- const backend = createProfileExecutionBackend({
1223
- profile,
1224
- executor: factory
1225
- });
1226
- if (!counter) return backend;
1227
- return {
1228
- ...backend,
1229
- async *stream(input, context) {
1230
- for await (const event of backend.stream(input, context)) {
1231
- if (event.type === "llm_call") {
1232
- counter.sawLlmCall = true;
1233
- counter.tokensIn += event.tokensIn ?? 0;
1234
- counter.tokensOut += event.tokensOut ?? 0;
1235
- counter.costUsd += event.costUsd ?? 0;
1236
- if (event.tokensKnown === false || event.tokensIn === void 0 || event.tokensOut === void 0) counter.tokensKnown = false;
1237
- if (event.usdKnown === false || event.costUsd === void 0) counter.usdKnown = false;
1238
- }
1239
- yield event;
1240
- }
1241
- }
1242
- };
1243
- }
1244
- /** A persona participant that replays scripted user turns in order. */
1245
- function scriptedPersonaBackend(turns) {
1246
- let idx = 0;
1247
- return createIterableBackend({
1248
- kind: "persona-user",
1249
- async *stream(_input, context) {
1250
- const text = turns[idx];
1251
- if (text === void 0) throw new Error(`persona-user: ran out of scripted turns at index ${idx} (had ${turns.length})`);
1252
- idx += 1;
1253
- yield {
1254
- type: "text_delta",
1255
- task: context.task,
1256
- session: context.session,
1257
- text,
1258
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1259
- };
1260
- }
1261
- });
1262
- }
1263
- /**
1264
- * Run one worker profile against one persona as a multi-round conversation.
1265
- * The persona leads (participant 0): it speaks, the worker answers, repeat,
1266
- * until `maxTurns`. Returns the persistent transcript + worker-only usage.
1267
- */
1268
- async function runPersonaConversation(opts) {
1269
- const counter = {
1270
- tokensIn: 0,
1271
- tokensOut: 0,
1272
- costUsd: 0,
1273
- sawLlmCall: false,
1274
- tokensKnown: true,
1275
- usdKnown: true
1276
- };
1277
- const workerName = opts.workerName ?? "agent";
1278
- const worker = profileRuntimeBackend(opts.worker, opts.executorFor(opts.worker, "worker"), counter);
1279
- let persona;
1280
- let maxTurns;
1281
- if (opts.persona.kind === "scripted") {
1282
- if (opts.persona.turns.length === 0) throw new Error("runPersonaConversation: scripted persona has no turns");
1283
- persona = scriptedPersonaBackend(opts.persona.turns);
1284
- maxTurns = opts.maxTurns ?? 2 * opts.persona.turns.length;
1285
- } else {
1286
- persona = profileRuntimeBackend(opts.persona.profile, opts.executorFor(opts.persona.profile, "persona"));
1287
- if (opts.maxTurns === void 0) throw new Error("runPersonaConversation: maxTurns is required for a profile-driven persona");
1288
- maxTurns = opts.maxTurns;
1289
- }
1290
- const result = await runConversation(defineConversation({
1291
- participants: [{
1292
- name: "user",
1293
- backend: persona
1294
- }, {
1295
- name: workerName,
1296
- backend: worker
1297
- }],
1298
- policy: {
1299
- maxTurns,
1300
- turnOrder: "alternate",
1301
- ...opts.haltOn ? { haltOn: opts.haltOn } : {}
1302
- }
1303
- }), {
1304
- seed: opts.seed ?? "Begin.",
1305
- signal: opts.signal
1306
- });
1307
- const fallbackCostKnown = !counter.sawLlmCall && opts.persona.kind === "scripted" && result.spentCreditsCents > 0;
1308
- const costUsd = fallbackCostKnown ? result.spentCreditsCents / 100 : counter.costUsd;
1309
- const tokensKnown = counter.sawLlmCall && counter.tokensKnown;
1310
- const costUsdKnown = counter.sawLlmCall ? counter.usdKnown : fallbackCostKnown;
1311
- return {
1312
- transcript: result.transcript,
1313
- turns: result.turns,
1314
- halted: result.halted,
1315
- costUsd,
1316
- tokensIn: counter.tokensIn,
1317
- tokensOut: counter.tokensOut,
1318
- ...tokensKnown ? {} : { tokensKnown: false },
1319
- ...costUsdKnown ? {} : { costUsdKnown: false }
1320
- };
1321
- }
1322
- /**
1323
- * Wrap {@link runPersonaConversation} as a `ProfileDispatchFn` for
1324
- * `runProfileMatrix`: the profile axis is the worker-under-test, the scenario
1325
- * axis is the persona, and the runner is the cell. Meters the worker through
1326
- * `ctx.cost` so the matrix's backend-integrity guard sees real usage.
1327
- */
1328
- function runPersonaDispatch(config) {
1329
- return async (worker, scenario, ctx) => {
1330
- const model = worker.model?.default ?? "unknown";
1331
- const maximumCharge = typeof config.maximumCharge === "function" ? config.maximumCharge(worker, scenario) : config.maximumCharge;
1332
- const paid = await ctx.cost.runPaidCall({
1333
- channel: "agent",
1334
- actor: "persona-conversation",
1335
- model,
1336
- signal: ctx.signal,
1337
- ...maximumCharge ? { maximumCharge } : {},
1338
- execute: (executionSignal) => runPersonaConversation({
1339
- worker,
1340
- persona: config.personaOf(scenario),
1341
- executorFor: config.executorFor,
1342
- maxTurns: config.maxTurns?.(scenario),
1343
- seed: config.seed?.(scenario),
1344
- signal: executionSignal,
1345
- workerName: config.workerName
1346
- }),
1347
- receipt: (result) => ({
1348
- model,
1349
- inputTokens: result.tokensIn,
1350
- outputTokens: result.tokensOut,
1351
- ...result.tokensKnown === false ? { usageUnknown: true } : {},
1352
- ...result.costUsdKnown === false ? { costUnknown: true } : { actualCostUsd: result.costUsd }
1353
- })
1354
- });
1355
- if (!paid.succeeded) throw paid.error;
1356
- const result = paid.value;
1357
- return config.artifactOf(result.transcript, scenario);
1358
- };
1359
- }
1360
- //#endregion
1361
- export { makePerAttemptSignal as C, defaultIsRetryable as S, createProfileExecutionBackend as T, readDepth as _, FileConversationJournal as a, DeadlineExceededError as b, createConversationBackend as c, slugifySpeaker as d, turnId as f, isDepthExceeded as g, buildForwardHeaders as h, d1ToSqlAdapter as i, runConversation as l, FORWARD_HEADERS as m, runPersonaDispatch as n, InMemoryConversationJournal as o, DEFAULT_MAX_DEPTH as p, SqlConversationJournal as r, defineConversation as s, runPersonaConversation as t, runConversationStream as u, CircuitBreakerState as v, sleep as w, computeBackoff as x, CircuitOpenError as y };
1362
-
1363
- //# sourceMappingURL=conversation-BxJ0SIBM.js.map