@tangle-network/agent-runtime 0.104.0 → 0.106.0

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