@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,691 +0,0 @@
1
- import { V as AgentExecutionBackend, it as RuntimeSessionStore } from "./types-Q0PMagdm.js";
2
- import { p as ExecutorFactory } from "./types-DFLZMaeh.js";
3
- import { AgentProfile } from "@tangle-network/agent-interface";
4
- import { AgentProfile as AgentProfile$1, MaximumCharge } from "@tangle-network/agent-eval";
5
- import { ProfileDispatchFn, Scenario } from "@tangle-network/agent-eval/campaign";
6
- //#region src/runtime/profile-execution-backend.d.ts
7
- /**
8
- * Bind one exact profile and Runtime executor to the stable `AgentExecutionBackend` contract used
9
- * by `runAgentTaskStream` and conversations.
10
- *
11
- * Runtime still owns the model call through `streamAgentTurn`.
12
- * The adapter only translates the two stream protocols and carries the caller's request headers
13
- * into `ExecutorContext` so an HTTP executor can preserve authorization, recursion depth, and
14
- * trace identity.
15
- *
16
- * @stable
17
- */
18
- declare function createProfileExecutionBackend(options: {
19
- profile: AgentProfile;
20
- executor: ExecutorFactory<unknown>;
21
- }): AgentExecutionBackend;
22
- //#endregion
23
- //#region src/conversation/call-policy.d.ts
24
- /**
25
- *
26
- * Per-call resilience policy for participant backends: deadline, retry with
27
- * backoff, and a circuit breaker. Each policy is applied *around* a single
28
- * turn's backend invocation, not across the whole conversation — the
29
- * conversation-level credit cap and `maxTurns` bound the broader run.
30
- *
31
- * Deadlines abort the underlying backend stream via `AbortSignal` linkage so
32
- * the OpenAI/SDK clients tear down their HTTP request cleanly instead of
33
- * leaking sockets. Retries replay the same logical turn (same `turnId`) so
34
- * any caching gateway can dedupe. Circuit breakers are *per participant*: A's
35
- * failures don't open B's breaker.
36
- *
37
- * @stable
38
- */
39
- /** Pure judgment of whether an error is worth retrying. Defaults: TimeoutError, AbortError, fetch-level network errors. */
40
- type RetryableErrorPredicate = (err: unknown) => boolean;
41
- /** Backoff between attempts. Constant ms, or `(attempt: 1-indexed) => ms`. */
42
- type RetryBackoff = number | ((attempt: number) => number);
43
- /** Circuit-breaker tuning. `failuresToOpen` consecutive failures opens it; closed only after `cooldownMs`. */
44
- interface CircuitBreakerConfig {
45
- failuresToOpen: number;
46
- cooldownMs: number;
47
- }
48
- interface BackendCallPolicy {
49
- /** Per-attempt wall clock limit. Exceeding fires an AbortSignal and is treated as a retryable failure. */
50
- perAttemptDeadlineMs?: number;
51
- /** Number of retries after the first attempt; total attempts = 1 + maxRetries. Default 0. */
52
- maxRetries?: number;
53
- /** Backoff between attempts. Default 250ms with jitter. */
54
- retryBackoffMs?: RetryBackoff;
55
- /** Custom retry classifier. Defaults to {@link defaultIsRetryable}. */
56
- isRetryable?: RetryableErrorPredicate;
57
- /** Circuit breaker that opens after N consecutive failures per participant. */
58
- circuitBreaker?: CircuitBreakerConfig;
59
- }
60
- /** Thrown when the circuit breaker is open for a participant and no retry is allowed yet. */
61
- declare class CircuitOpenError extends Error {
62
- constructor(participant: string, retryAfterMs: number);
63
- }
64
- /** Thrown when a backend call exceeds its per-attempt deadline. */
65
- declare class DeadlineExceededError extends Error {
66
- constructor(deadlineMs: number);
67
- }
68
- /**
69
- * Default retryable classification — network/timeout class errors. Errors
70
- * a model deliberately throws (validation, refusal, 4xx) are not retried;
71
- * those represent real outcomes, not transient infrastructure faults.
72
- */
73
- declare const defaultIsRetryable: RetryableErrorPredicate;
74
- /** Live circuit-breaker state — one instance per (participant, conversation run). */
75
- declare class CircuitBreakerState {
76
- private readonly config;
77
- private consecutiveFailures;
78
- private openedAt;
79
- constructor(config: CircuitBreakerConfig | undefined);
80
- /**
81
- * Check whether the next call is allowed. Throws `CircuitOpenError` when
82
- * the breaker is open and the cooldown hasn't elapsed.
83
- */
84
- preflight(participant: string, now?: number): void;
85
- recordSuccess(): void;
86
- recordFailure(now?: number): void;
87
- }
88
- /**
89
- * Build a per-attempt AbortSignal linked to the parent signal AND fired when
90
- * the deadline elapses. The returned `dispose()` MUST be called in a
91
- * `finally` (clears the timer, detaches the listener) so we don't leak.
92
- *
93
- * When the deadline fires, the signal's `reason` is a `DeadlineExceededError`
94
- * — callers can detect timeout-vs-cancel by reading `signal.reason` after
95
- * the underlying operation throws.
96
- */
97
- declare function makePerAttemptSignal(parentSignal: AbortSignal | undefined, deadlineMs: number | undefined): {
98
- signal: AbortSignal;
99
- dispose: () => void;
100
- getDeadlineError(): DeadlineExceededError | undefined;
101
- };
102
- /** Compute the delay before the next attempt. Default: 250ms exponential with jitter. */
103
- declare function computeBackoff(spec: RetryBackoff | undefined, attempt: number): number;
104
- /** Resolve after `ms` milliseconds — used for retry backoff in conversation call policy. */
105
- declare function sleep(ms: number): Promise<void>;
106
- //#endregion
107
- //#region src/conversation/headers.d.ts
108
- /**
109
- *
110
- * Cross-gateway forwarding headers — the wire-level contract that makes
111
- * agent-to-agent communication composable across organizational boundaries.
112
- * Every header here is read on inbound and re-emitted on outbound, so a chain
113
- * `caller → A's gateway → A's runtime → B's gateway → B's runtime` ends with
114
- * B billing the original user, the depth counter monotonically incremented,
115
- * and the run/turn correlation IDs preserved end-to-end.
116
- *
117
- * The actual depth refusal (HTTP 413 at MAX_DEPTH) is enforced by
118
- * `agent-gateway`'s middleware; this module owns the names + the propagation
119
- * rules so both sides agree.
120
- *
121
- * Full protocol: `docs/agent-bus-protocol.md`.
122
- *
123
- * @stable
124
- */
125
- /** Standard names — lowercased so Headers maps interop on every runtime. */
126
- declare const FORWARD_HEADERS: {
127
- /** Forwarded original-user identity (`Bearer sk-tan-<user>`); downstream gateways bill against this. */
128
- readonly authorization: "x-tangle-forwarded-authorization";
129
- /** Monotonically incremented on every gateway hop. Refused at MAX_DEPTH. */
130
- readonly depth: "x-tangle-forwarded-depth";
131
- /** Top-level conversation run identifier, propagated through every nested call. */
132
- readonly runId: "x-tangle-runid";
133
- /** This call's turn within the run; deterministic + stable across retries. */
134
- readonly turnId: "x-tangle-turnid";
135
- /** When the call is *inside* another turn (recursion), the parent turn's id. */
136
- readonly parentTurnId: "x-tangle-parent-turnid";
137
- /** Logical conversation peer label at the sending side, for trace stitching. */
138
- readonly speaker: "x-tangle-speaker";
139
- };
140
- type ForwardHeaderName = (typeof FORWARD_HEADERS)[keyof typeof FORWARD_HEADERS];
141
- /** Hard cap on chained gateway hops; refused beyond this. Default keeps recursion bounded. */
142
- declare const DEFAULT_MAX_DEPTH = 4;
143
- /**
144
- * Read the depth counter off an inbound request. Missing → 0 (caller is the
145
- * origin). Non-integer → throws — silent coercion would let a bad caller
146
- * reset depth and bypass the limit.
147
- */
148
- declare function readDepth(headers: Readonly<Record<string, string | string[] | undefined>>): number;
149
- /**
150
- * Refuse further forwarding when the inbound depth has reached the limit.
151
- * Callers (the gateway middleware) translate the boolean to an HTTP 413.
152
- */
153
- declare function isDepthExceeded(inboundDepth: number, max?: number): boolean;
154
- /**
155
- * Build the headers to emit on an outbound participant call, given the
156
- * conversation's propagation context. Depth is incremented from the inbound
157
- * value; runId / turnId / speaker stamp the current hop; the user's
158
- * `Authorization` is preserved verbatim so the downstream gateway bills the
159
- * right wallet.
160
- */
161
- declare function buildForwardHeaders(input: {
162
- inboundDepth: number;
163
- forwardedAuthorization?: string;
164
- runId: string;
165
- turnId: string;
166
- parentTurnId?: string;
167
- speaker: string;
168
- }): Record<string, string>;
169
- /**
170
- * Header bag carried through `AgentBackendContext.propagatedHeaders` so
171
- * backends that opt in can merge them into their outbound HTTP requests.
172
- * Distinct from `buildForwardHeaders` so callers can attach extra
173
- * non-protocol headers (e.g. tracing) without colliding.
174
- */
175
- type PropagatedHeaders = Readonly<Record<string, string>>;
176
- //#endregion
177
- //#region src/conversation/journal.d.ts
178
- interface ConversationJournalEntry {
179
- runId: string;
180
- startedAt: string;
181
- /** Set when the run reaches a terminal state. */
182
- halted?: HaltReason;
183
- endedAt?: string;
184
- turns: ConversationTurn[];
185
- }
186
- interface ConversationJournal {
187
- /**
188
- * Load any prior state for `runId`. Returns `undefined` for a fresh run.
189
- * Implementations MUST NOT mutate the returned object — the runner clones
190
- * before continuing — but the runtime treats absence and emptiness
191
- * identically, so a journal with zero turns is equivalent to "fresh."
192
- */
193
- loadRun(runId: string): Promise<ConversationJournalEntry | undefined>;
194
- /**
195
- * Initialise journal state for a fresh run. Called once per run, before any
196
- * `appendTurn`. Idempotent: calling with an existing runId is a no-op if
197
- * the entry already exists with the same `startedAt`.
198
- */
199
- beginRun(runId: string, startedAt: string): Promise<void>;
200
- /**
201
- * Append a committed turn. The runner only calls this AFTER the turn's
202
- * backend stream completed and the credit total has been updated, so an
203
- * appended turn is observed-committed and never speculative.
204
- */
205
- appendTurn(runId: string, turn: ConversationTurn): Promise<void>;
206
- /**
207
- * Record the run's terminal halt reason + end time. Once called, the run
208
- * is observed-final; subsequent `loadRun` returns the same halt.
209
- */
210
- recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void>;
211
- }
212
- /** In-memory `ConversationJournal` — suitable for testing and single-process runs. */
213
- declare class InMemoryConversationJournal implements ConversationJournal {
214
- private readonly entries;
215
- loadRun(runId: string): Promise<ConversationJournalEntry | undefined>;
216
- beginRun(runId: string, startedAt: string): Promise<void>;
217
- appendTurn(runId: string, turn: ConversationTurn): Promise<void>;
218
- recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void>;
219
- }
220
- /**
221
- * JSONL on disk. One line per record; first line is the `begin`, subsequent
222
- * lines are `turn` records, terminal line is `halt`. Replays the whole file
223
- * on `loadRun` — cheap for the conversation sizes this is designed for
224
- * (thousands of turns, not millions). For huge runs, plug in a real DB
225
- * adapter; the interface is small.
226
- *
227
- * Reads and appends over the shared append-only spine (`durable/jsonl-file`): each
228
- * `appendTurn` / `recordHalt` finishes a short write and calls `fsync`, so a process
229
- * crash between writes never loses an acknowledged turn, and a crash DURING one leaves
230
- * an uncommitted final line that the next read skips and the next append truncates.
231
- */
232
- declare class FileConversationJournal implements ConversationJournal {
233
- private readonly path;
234
- constructor(path: string);
235
- loadRun(runId: string): Promise<ConversationJournalEntry | undefined>;
236
- beginRun(runId: string, startedAt: string): Promise<void>;
237
- appendTurn(runId: string, turn: ConversationTurn): Promise<void>;
238
- recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void>;
239
- private appendRecord;
240
- }
241
- //#endregion
242
- //#region src/conversation/types.d.ts
243
- /** @stable */
244
- interface ConversationParticipant {
245
- /**
246
- * Stable name used as the speaker label in the transcript. Must be unique
247
- * within a `Conversation`.
248
- */
249
- name: string;
250
- /**
251
- * Backend that runs this participant's turn. Reuses the existing
252
- * `AgentExecutionBackend` contract from `runAgentTaskStream`, so an iterable,
253
- * sandbox, or profile-backed Runtime executor works through the same runner.
254
- */
255
- backend: AgentExecutionBackend;
256
- /**
257
- * Optional human label for traces / dashboards. Distinct from `name`, which
258
- * is the addressing key.
259
- */
260
- label?: string;
261
- /**
262
- * Optional per-participant override of the conversation's default
263
- * `callPolicy`. Use to tighten the deadline or raise the retry budget for
264
- * a participant known to be slow or flaky.
265
- */
266
- callPolicy?: BackendCallPolicy;
267
- /**
268
- * Who pays for THIS participant's outbound calls?
269
- *
270
- * - `'forward-user'` (default) — propagate the caller's
271
- * `X-Tangle-Forwarded-Authorization` so the downstream gateway bills the
272
- * original user. Right for pass-through agents that aggregate/route
273
- * without taking economic risk.
274
- * - `'agent-owned'` — DO NOT forward the user's auth; the participant's
275
- * backend uses its own credentials (typically a sk-tan-AGENT or x402
276
- * wallet baked into the backend at construction). Downstream charges
277
- * land on the agent, not the user. Right for resold-bundle agents that
278
- * take margin between their inbound price and their sub-agent costs.
279
- * - `(state) => AuthSource` — per-turn / per-condition decision, e.g. base
280
- * sub-services are agent-owned but premium add-ons forward the user.
281
- *
282
- * The agent's own credentials live on its caller-owned backend or
283
- * profile-bound Runtime executor; this field is purely about *whether to
284
- * also forward the user's identity downstream*.
285
- */
286
- authSource?: AuthSource;
287
- }
288
- /** @stable */
289
- type AuthSource = 'forward-user' | 'agent-owned' | ((state: ConversationDriveState) => 'forward-user' | 'agent-owned');
290
- /** @stable */
291
- type TurnOrder = 'alternate' | 'round-robin' | ((state: ConversationDriveState) => number);
292
- /** @stable */
293
- interface ConversationDriveState {
294
- transcript: readonly ConversationTurn[];
295
- turnIndex: number;
296
- spentCreditsCents: number;
297
- }
298
- /** @stable */
299
- interface HaltContext extends ConversationDriveState {
300
- lastTurn: ConversationTurn;
301
- }
302
- /** @stable */
303
- interface HaltSignal {
304
- halted: true;
305
- reason: string;
306
- }
307
- /** @stable */
308
- type HaltPredicate = (ctx: HaltContext) => boolean | HaltSignal | Promise<boolean | HaltSignal>;
309
- /** @stable */
310
- type HaltReason = {
311
- kind: 'max_turns';
312
- turns: number;
313
- } | {
314
- kind: 'max_credits';
315
- spentCents: number;
316
- capCents: number;
317
- } | {
318
- kind: 'predicate';
319
- reason: string;
320
- } | {
321
- kind: 'abort';
322
- } | {
323
- kind: 'participant_error';
324
- participant: string;
325
- message: string;
326
- };
327
- /** @stable */
328
- interface ConversationPolicy {
329
- /** Hard cap on speaker-turns. Each call into a participant's backend counts as 1. */
330
- maxTurns: number;
331
- /**
332
- * Hard cap on aggregate credit spend across all participants, in cents.
333
- * Computed by summing `llm_call.costUsd` from every participant's stream.
334
- * Unset (`undefined`) means no credit ceiling — the run is bounded only by
335
- * `maxTurns` and `haltOn`.
336
- */
337
- maxCreditsCents?: number;
338
- /**
339
- * Speaker selection. Defaults to `'alternate'` for two-participant
340
- * conversations and `'round-robin'` for any other arity.
341
- */
342
- turnOrder?: TurnOrder;
343
- /**
344
- * Optional convergence / content-based halt. Called after every turn ends;
345
- * returning truthy stops the loop with `{ kind: 'predicate', ... }`.
346
- */
347
- haltOn?: HaltPredicate;
348
- /**
349
- * Default per-turn resilience policy applied to every participant call
350
- * (deadline, retries, circuit breaker). Individual participants may
351
- * override via `ConversationParticipant.callPolicy`.
352
- */
353
- defaultCallPolicy?: BackendCallPolicy;
354
- }
355
- /** @stable */
356
- interface ConversationTurn {
357
- index: number;
358
- speaker: string;
359
- /**
360
- * Deterministic turn identifier — stable across retries of the same logical
361
- * turn so caching gateways and trace backends can dedupe. Shape:
362
- * `${runId}.t${index}.${speakerSlug}`.
363
- */
364
- turnId: string;
365
- /** Backend session used for this turn. Present on turns recorded by session-aware runners. */
366
- sessionId?: string;
367
- text: string;
368
- /**
369
- * Aggregated backend usage for this turn alone. Populated from any
370
- * `llm_call` stream events the backend emitted; `undefined` when the
371
- * backend reports no usage.
372
- */
373
- usage?: {
374
- tokensIn?: number;
375
- tokensOut?: number;
376
- costUsd?: number;
377
- latencyMs?: number;
378
- model?: string;
379
- };
380
- /**
381
- * Number of attempts that ran before this turn committed. `1` is the
382
- * common case; higher means the call policy retried after transient
383
- * failures.
384
- */
385
- attempts: number;
386
- startedAt: string;
387
- endedAt: string;
388
- }
389
- /** @stable */
390
- interface Conversation {
391
- participants: readonly ConversationParticipant[];
392
- policy: ConversationPolicy;
393
- }
394
- /** @stable */
395
- interface RunConversationOptions {
396
- /** First message kicking off the conversation. Routes to the first speaker. */
397
- seed: string;
398
- /**
399
- * Optional run identifier for cross-participant trace correlation. Auto-
400
- * generated when omitted. Reusing a runId against the same `journal`
401
- * resumes the prior run — the runner replays the persisted transcript and
402
- * continues from the first un-recorded turn.
403
- */
404
- runId?: string;
405
- /** Cancellation signal — aborts mid-stream and halts with `{ kind: 'abort' }`. */
406
- signal?: AbortSignal;
407
- /**
408
- * Event sink for per-turn micro-events. Distinct from the result transcript:
409
- * the sink fires for every text-delta, every turn-start/end, and the
410
- * conversation-start/end markers. Used to drive SSE / dashboard updates
411
- * without waiting for the conversation to finish.
412
- */
413
- onEvent?: (event: ConversationStreamEvent) => void | Promise<void>;
414
- /**
415
- * Optional durable transcript. When set, the runner persists every
416
- * committed turn before yielding `turn_end`. Reusing the same `runId`
417
- * against the same journal resumes from the last committed turn — so a
418
- * driver process crash mid-run loses zero acknowledged turns.
419
- */
420
- journal?: ConversationJournal;
421
- /**
422
- * Stores each participant's backend session. The runner keeps an in-memory
423
- * store for one invocation when omitted. Reuse a durable store with the same
424
- * `runId` and journal after a process restart. Backends implementing `resume`
425
- * continue their provider session; other backends receive the full transcript.
426
- */
427
- sessionStore?: RuntimeSessionStore;
428
- /**
429
- * Headers to forward verbatim to every participant backend call (gateway
430
- * propagation: `X-Tangle-Forwarded-Authorization`, run/turn correlation,
431
- * depth counter). Backends opt in by reading `propagatedHeaders` from
432
- * their `AgentBackendContext`; backends that ignore the field still work.
433
- */
434
- propagatedHeaders?: PropagatedHeaders;
435
- /**
436
- * Inbound depth at the point this driver was invoked. The runner
437
- * increments it on every outbound participant call; gateways refuse at
438
- * `DEFAULT_MAX_DEPTH`. Default 0 (origin caller).
439
- */
440
- inboundDepth?: number;
441
- /**
442
- * Parent turn id when this conversation is *inside* another turn (i.e. the
443
- * driver is itself a participant via `createConversationBackend`). The
444
- * runner stamps each outbound call with this as `X-Tangle-Parent-TurnId`
445
- * so trace stitching survives nested orchestration.
446
- */
447
- parentTurnId?: string;
448
- }
449
- /** @stable */
450
- interface ConversationResult {
451
- runId: string;
452
- transcript: ConversationTurn[];
453
- turns: number;
454
- spentCreditsCents: number;
455
- halted: HaltReason;
456
- durationMs: number;
457
- startedAt: string;
458
- endedAt: string;
459
- }
460
- /** @stable */
461
- type ConversationStreamEvent = {
462
- type: 'conversation_start';
463
- runId: string;
464
- participants: readonly string[];
465
- seed: string;
466
- timestamp: string;
467
- } | {
468
- type: 'conversation_resumed';
469
- runId: string;
470
- participants: readonly string[];
471
- transcript: readonly ConversationTurn[];
472
- timestamp: string;
473
- } | {
474
- type: 'turn_start';
475
- runId: string;
476
- index: number;
477
- speaker: string;
478
- turnId: string;
479
- attempt: number;
480
- timestamp: string;
481
- } | {
482
- type: 'turn_text_delta';
483
- runId: string;
484
- index: number;
485
- speaker: string;
486
- turnId: string;
487
- text: string;
488
- timestamp?: string;
489
- } | {
490
- type: 'turn_retry';
491
- runId: string;
492
- index: number;
493
- speaker: string;
494
- turnId: string;
495
- attempt: number;
496
- reason: string;
497
- timestamp: string;
498
- } | {
499
- type: 'turn_end';
500
- runId: string;
501
- turn: ConversationTurn;
502
- timestamp: string;
503
- } | {
504
- type: 'conversation_end';
505
- runId: string;
506
- result: ConversationResult;
507
- timestamp: string;
508
- };
509
- //#endregion
510
- //#region src/conversation/conversation-backend.d.ts
511
- /** Adapt a multi-participant conversation into the standard execution backend contract. */
512
- declare function createConversationBackend(options: {
513
- conversation: Conversation;
514
- /** Optional backend kind label. Defaults to `'conversation'`. */
515
- kind?: string;
516
- }): AgentExecutionBackend;
517
- //#endregion
518
- //#region src/conversation/define-conversation.d.ts
519
- /** Validate and define a conversation before execution. */
520
- declare function defineConversation(input: {
521
- participants: ConversationParticipant[];
522
- policy: ConversationPolicy;
523
- }): Conversation;
524
- //#endregion
525
- //#region src/conversation/journal-sql.d.ts
526
- /**
527
- * Minimal SQL driver shape. Implementations forward to whichever client the
528
- * deployment already uses; agent-runtime takes no opinion on which.
529
- *
530
- * Parameter placeholders MUST be `?` (positional). All adapters listed in the
531
- * file header accept this convention.
532
- */
533
- interface SqlAdapter {
534
- /** Execute a write statement (INSERT/UPDATE/DELETE/DDL). */
535
- exec(sql: string, params?: readonly unknown[]): Promise<{
536
- rowsAffected: number;
537
- }>;
538
- /** Execute a read statement (SELECT). Returns rows as plain objects. */
539
- query<TRow = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<TRow[]>;
540
- }
541
- /**
542
- * Adapt a Cloudflare D1 binding to the SqlAdapter shape. Lives here so D1
543
- * consumers don't have to write the wrapper themselves; the runtime never
544
- * imports `@cloudflare/workers-types` directly (peer-style typing).
545
- */
546
- declare function d1ToSqlAdapter(db: D1DatabaseLike): SqlAdapter;
547
- /**
548
- * Structural type matching the surface of `D1Database` we depend on, so the
549
- * SDK never imports `@cloudflare/workers-types`. Consumers pass their real
550
- * `D1Database` from `env.DB` and TS structural compatibility lines it up.
551
- */
552
- interface D1DatabaseLike {
553
- prepare(sql: string): D1StmtLike;
554
- }
555
- interface D1StmtLike {
556
- bind(...params: unknown[]): D1StmtLike;
557
- run(): Promise<unknown>;
558
- all<TRow = unknown>(): Promise<{
559
- results?: TRow[];
560
- }>;
561
- }
562
- /**
563
- * SQL-backed ConversationJournal. Two tables — runs (one row per runId, holds
564
- * start/halt timestamps + halt reason) and turns (one row per committed turn,
565
- * payload is the ConversationTurn JSON). Replays the turns table on
566
- * `loadRun` and writes append-only per `appendTurn`.
567
- */
568
- declare class SqlConversationJournal implements ConversationJournal {
569
- private readonly db;
570
- private readonly table;
571
- /**
572
- * @param db SQL adapter (D1, postgres, sqlite, libSQL — all work)
573
- * @param table Table-name prefix; the journal creates `${table}_runs` and
574
- * `${table}_turns`. Lets multiple journals share a database
575
- * without colliding (e.g. one per product surface).
576
- */
577
- constructor(db: SqlAdapter, table?: string);
578
- /**
579
- * Create the journal's tables if absent. Idempotent. Call once at deploy
580
- * (or at app boot) — running on every request is harmless but adds latency.
581
- */
582
- migrate(): Promise<void>;
583
- loadRun(runId: string): Promise<ConversationJournalEntry | undefined>;
584
- beginRun(runId: string, startedAt: string): Promise<void>;
585
- appendTurn(runId: string, turn: ConversationTurn): Promise<void>;
586
- recordHalt(runId: string, halt: HaltReason, endedAt: string): Promise<void>;
587
- }
588
- //#endregion
589
- //#region src/conversation/run-conversation.d.ts
590
- /** Run a conversation to completion and return its terminal result. */
591
- declare function runConversation(conversation: Conversation, options: RunConversationOptions): Promise<ConversationResult>;
592
- /** Streaming conversation orchestrator: drives N participants in turn through their own backends, enforcing `maxTurns` / `maxCreditsCents` / `haltOn`, yielding per-event stream markers. */
593
- declare function runConversationStream(conversation: Conversation, options: RunConversationOptions): AsyncIterable<ConversationStreamEvent>;
594
- //#endregion
595
- //#region src/conversation/run-persona.d.ts
596
- /** A persona that drives the conversation: either a full driver `AgentProfile`
597
- * (an LLM user-sim) or a deterministic script of user turns (the fast-path). */
598
- type PersonaDriver = {
599
- kind: 'profile';
600
- profile: AgentProfile$1;
601
- } | {
602
- kind: 'scripted';
603
- turns: string[];
604
- };
605
- interface RunPersonaConversationOptions {
606
- /** The agent under test. Metered; its rendered prompt leads its turns. */
607
- worker: AgentProfile$1;
608
- /** The simulated user driving the dialogue. */
609
- persona: PersonaDriver;
610
- /** Resolve transport/executable ports for the exact profile. Runtime still materializes the
611
- * profile and owns every model call. Applied to the worker and a profile-driven persona. */
612
- executorFor: (profile: AgentProfile$1, role: 'worker' | 'persona') => ExecutorFactory<unknown>;
613
- /** Speaker-turn cap. Default for a scripted persona = `2 * turns.length`
614
- * (worker answers each user turn). REQUIRED for a `profile` persona. */
615
- maxTurns?: number;
616
- /** Kickoff message routed to the first speaker (the persona). Default 'Begin.' */
617
- seed?: string;
618
- /** Content-based "until satisfied" halt, called after every turn. `maxTurns` is the
619
- * hard ceiling; this is the early stop (the persona declares the goal met / unreachable). */
620
- haltOn?: HaltPredicate;
621
- signal?: AbortSignal;
622
- /** Worker participant / transcript speaker label. Default 'agent'. */
623
- workerName?: string;
624
- }
625
- interface PersonaConversationResult {
626
- transcript: ConversationTurn[];
627
- turns: number;
628
- halted: HaltReason;
629
- /** Worker-only spend (the side under test). */
630
- costUsd: number;
631
- tokensIn: number;
632
- tokensOut: number;
633
- /** Absent means every worker call reported complete token usage. */
634
- tokensKnown?: false;
635
- /** Absent means every worker call reported provider-billed cost, including a known zero. */
636
- costUsdKnown?: false;
637
- }
638
- /**
639
- * Run one worker profile against one persona as a multi-round conversation.
640
- * The persona leads (participant 0): it speaks, the worker answers, repeat,
641
- * until `maxTurns`. Returns the persistent transcript + worker-only usage.
642
- */
643
- declare function runPersonaConversation(opts: RunPersonaConversationOptions): Promise<PersonaConversationResult>;
644
- interface RunPersonaConfig<TScenario extends Scenario, TArtifact> {
645
- /** Resolve transport/executable ports for each exact profile. */
646
- executorFor: (profile: AgentProfile$1, role: 'worker' | 'persona') => ExecutorFactory<unknown>;
647
- /** The persona driving each scenario — a driver profile or scripted turns. */
648
- personaOf: (scenario: TScenario) => PersonaDriver;
649
- /** Build the scored artifact from the finished transcript. */
650
- artifactOf: (transcript: ConversationTurn[], scenario: TScenario) => TArtifact;
651
- /** Speaker-turn cap (required when a persona is profile-driven). */
652
- maxTurns?: (scenario: TScenario) => number;
653
- seed?: (scenario: TScenario) => string;
654
- workerName?: string;
655
- /** Provider- or executor-enforced maximum for the whole worker conversation.
656
- * Required before execution when the enclosing campaign is cost-capped. */
657
- maximumCharge?: MaximumCharge | ((worker: AgentProfile$1, scenario: TScenario) => MaximumCharge | undefined);
658
- }
659
- /**
660
- * Wrap {@link runPersonaConversation} as a `ProfileDispatchFn` for
661
- * `runProfileMatrix`: the profile axis is the worker-under-test, the scenario
662
- * axis is the persona, and the runner is the cell. Meters the worker through
663
- * `ctx.cost` so the matrix's backend-integrity guard sees real usage.
664
- */
665
- declare function runPersonaDispatch<TScenario extends Scenario, TArtifact>(config: RunPersonaConfig<TScenario, TArtifact>): ProfileDispatchFn<TScenario, TArtifact>;
666
- //#endregion
667
- //#region src/conversation/turn-id.d.ts
668
- /**
669
- *
670
- * Deterministic turn identifier. Stable across retries of the same logical
671
- * turn so backends (and any caching gateway in between) can dedupe on it.
672
- * A retry triggered by a network blip or deadline timeout MUST produce the
673
- * same `turn_id`; only the underlying attempt count differs.
674
- *
675
- * Shape: `${runId}.t${index}.${speakerSlug}` — readable in logs, sortable by
676
- * turn index, attributable to a speaker. Slugify keeps the speaker portion
677
- * URL-safe so it can ride in HTTP headers without escaping.
678
- *
679
- * @stable
680
- */
681
- declare function turnId(runId: string, index: number, speaker: string): string;
682
- /**
683
- * Reduce a speaker name to ASCII alphanumerics + dashes. Preserves enough
684
- * substance to read in a log line; collisions between speakers within a
685
- * single Conversation are prevented by `defineConversation`'s
686
- * unique-name check, so the slug only needs to be deterministic, not unique.
687
- */
688
- declare function slugifySpeaker(speaker: string): string;
689
- //#endregion
690
- export { sleep as $, RunConversationOptions as A, buildForwardHeaders as B, ConversationResult as C, HaltPredicate as D, HaltContext as E, InMemoryConversationJournal as F, CircuitBreakerState as G, readDepth as H, DEFAULT_MAX_DEPTH as I, RetryBackoff as J, CircuitOpenError as K, FORWARD_HEADERS as L, ConversationJournal as M, ConversationJournalEntry as N, HaltReason as O, FileConversationJournal as P, makePerAttemptSignal as Q, ForwardHeaderName as R, ConversationPolicy as S, ConversationTurn as T, BackendCallPolicy as U, isDepthExceeded as V, CircuitBreakerConfig as W, computeBackoff as X, RetryableErrorPredicate as Y, defaultIsRetryable as Z, createConversationBackend as _, RunPersonaConfig as a, ConversationDriveState as b, runPersonaDispatch as c, D1DatabaseLike as d, createProfileExecutionBackend as et, D1StmtLike as f, defineConversation as g, d1ToSqlAdapter as h, PersonaDriver as i, TurnOrder as j, HaltSignal as k, runConversation as l, SqlConversationJournal as m, turnId as n, RunPersonaConversationOptions as o, SqlAdapter as p, DeadlineExceededError as q, PersonaConversationResult as r, runPersonaConversation as s, slugifySpeaker as t, runConversationStream as u, AuthSource as v, ConversationStreamEvent as w, ConversationParticipant as x, Conversation as y, PropagatedHeaders as z };
691
- //# sourceMappingURL=index-D9mb6fn2.d.ts.map