@tangle-network/agent-runtime 0.105.0 → 0.106.1

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 (218) hide show
  1. package/README.md +2 -2
  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-CiOCyRHb.js +743 -0
  13. package/dist/backends-CiOCyRHb.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-BpLQZGPH.js +1265 -0
  21. package/dist/conversation-BpLQZGPH.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 -1058
  40. package/dist/index.js +2106 -2082
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +768 -889
  43. package/dist/intelligence.js +1466 -1367
  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-CRagyuNb.js +268 -0
  55. package/dist/loop-runner-bin-CRagyuNb.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -15
  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 -436
  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 +149 -145
  84. package/dist/primeintellect/index.js +626 -1003
  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-5zM5XxLr.js +5408 -0
  100. package/dist/runtime-5zM5XxLr.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 +44 -56
  130. package/skills/build-with-agent-runtime/SKILL.md +1 -0
  131. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  132. package/dist/analyst-loop.js.map +0 -1
  133. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  134. package/dist/candidate-execution/index.js.map +0 -1
  135. package/dist/chunk-2KGAN2HM.js +0 -1256
  136. package/dist/chunk-2KGAN2HM.js.map +0 -1
  137. package/dist/chunk-2VZYRB55.js +0 -834
  138. package/dist/chunk-2VZYRB55.js.map +0 -1
  139. package/dist/chunk-3MDZX7YU.js +0 -125
  140. package/dist/chunk-3MDZX7YU.js.map +0 -1
  141. package/dist/chunk-5IBQAPVB.js +0 -29
  142. package/dist/chunk-5IBQAPVB.js.map +0 -1
  143. package/dist/chunk-5QOB7H74.js +0 -387
  144. package/dist/chunk-5QOB7H74.js.map +0 -1
  145. package/dist/chunk-C5RTIBNZ.js +0 -48
  146. package/dist/chunk-C5RTIBNZ.js.map +0 -1
  147. package/dist/chunk-CTRA64LY.js +0 -680
  148. package/dist/chunk-CTRA64LY.js.map +0 -1
  149. package/dist/chunk-DPEUKJRO.js +0 -27
  150. package/dist/chunk-DPEUKJRO.js.map +0 -1
  151. package/dist/chunk-FD2MBMOH.js +0 -494
  152. package/dist/chunk-FD2MBMOH.js.map +0 -1
  153. package/dist/chunk-H5QPIZNX.js +0 -907
  154. package/dist/chunk-H5QPIZNX.js.map +0 -1
  155. package/dist/chunk-HLKC4UYB.js +0 -3514
  156. package/dist/chunk-HLKC4UYB.js.map +0 -1
  157. package/dist/chunk-HNP72PNU.js +0 -192
  158. package/dist/chunk-HNP72PNU.js.map +0 -1
  159. package/dist/chunk-ISPWRSEC.js +0 -408
  160. package/dist/chunk-ISPWRSEC.js.map +0 -1
  161. package/dist/chunk-KRBFHMV6.js +0 -1228
  162. package/dist/chunk-KRBFHMV6.js.map +0 -1
  163. package/dist/chunk-M22PL4GH.js +0 -171
  164. package/dist/chunk-M22PL4GH.js.map +0 -1
  165. package/dist/chunk-NURIQBJQ.js +0 -72
  166. package/dist/chunk-NURIQBJQ.js.map +0 -1
  167. package/dist/chunk-OPVWXJ2H.js +0 -75
  168. package/dist/chunk-OPVWXJ2H.js.map +0 -1
  169. package/dist/chunk-PZZKQVQV.js +0 -52
  170. package/dist/chunk-PZZKQVQV.js.map +0 -1
  171. package/dist/chunk-Q2JSAVQ3.js +0 -671
  172. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  173. package/dist/chunk-RDOAVVHY.js +0 -699
  174. package/dist/chunk-RDOAVVHY.js.map +0 -1
  175. package/dist/chunk-SGKPNBXE.js +0 -60
  176. package/dist/chunk-SGKPNBXE.js.map +0 -1
  177. package/dist/chunk-SMQXZGLZ.js +0 -351
  178. package/dist/chunk-SMQXZGLZ.js.map +0 -1
  179. package/dist/chunk-UHEZW5BU.js +0 -2918
  180. package/dist/chunk-UHEZW5BU.js.map +0 -1
  181. package/dist/chunk-UPWGXKXB.js +0 -254
  182. package/dist/chunk-UPWGXKXB.js.map +0 -1
  183. package/dist/chunk-VISA6CI3.js +0 -200
  184. package/dist/chunk-VISA6CI3.js.map +0 -1
  185. package/dist/chunk-WMTCUOQL.js +0 -474
  186. package/dist/chunk-WMTCUOQL.js.map +0 -1
  187. package/dist/chunk-WRTOVNN4.js +0 -4728
  188. package/dist/chunk-WRTOVNN4.js.map +0 -1
  189. package/dist/chunk-WSTRQZYQ.js +0 -5576
  190. package/dist/chunk-WSTRQZYQ.js.map +0 -1
  191. package/dist/chunk-XBG2W2VW.js +0 -6434
  192. package/dist/chunk-XBG2W2VW.js.map +0 -1
  193. package/dist/chunk-YEJR7IXO.js +0 -68
  194. package/dist/chunk-YEJR7IXO.js.map +0 -1
  195. package/dist/chunk-YJZA2BIK.js +0 -1338
  196. package/dist/chunk-YJZA2BIK.js.map +0 -1
  197. package/dist/completion-gate-BMy5LGoP.d.ts +0 -256
  198. package/dist/conversation.js.map +0 -1
  199. package/dist/coordination-BZZSVYpZ.d.ts +0 -2570
  200. package/dist/environment-provider.js.map +0 -1
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-BDNcl6jI.d.ts +0 -175
  204. package/dist/loop-runner-bin-68aoM9-7.d.ts +0 -199
  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-B4t-OQjL.d.ts +0 -271
  209. package/dist/redact-BuFjxBUJ.d.ts +0 -481
  210. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  211. package/dist/structural-rollout-DEh6CEsa.d.ts +0 -446
  212. package/dist/supervise-4_48wwvy.d.ts +0 -379
  213. package/dist/types-BCoemcXU.d.ts +0 -802
  214. package/dist/types-BwoZWq-i.d.ts +0 -510
  215. package/dist/types-Cbp72qyu.d.ts +0 -491
  216. package/dist/types-CmYCMbFT.d.ts +0 -203
  217. package/dist/types-CvNwMzQt.d.ts +0 -957
  218. package/dist/worktree-fanout-DxhAWr5Z.d.ts +0 -999
@@ -1,671 +0,0 @@
1
- import {
2
- BackendTransportError,
3
- SessionMismatchError
4
- } from "./chunk-YEJR7IXO.js";
5
-
6
- // src/sessions.ts
7
- function newRuntimeSession(backend, requestedId, metadata) {
8
- const now = nowIso();
9
- return {
10
- id: requestedId || crypto.randomUUID(),
11
- backend,
12
- status: "active",
13
- createdAt: now,
14
- updatedAt: now,
15
- metadata
16
- };
17
- }
18
- function touchSession(session) {
19
- return { ...session, updatedAt: nowIso() };
20
- }
21
- function nowIso() {
22
- return (/* @__PURE__ */ new Date()).toISOString();
23
- }
24
- async function startOrResumeRuntimeSession(options) {
25
- const existing = options.resume && options.sessionId ? await options.store?.get(options.sessionId) : void 0;
26
- if (!existing) {
27
- const input2 = resolveSessionInput(options.input);
28
- const session2 = options.backend.start ? await options.backend.start(input2, {
29
- ...options.context,
30
- requestedSessionId: options.sessionId
31
- }) : newRuntimeSession(options.backend.kind, options.sessionId);
32
- assertSessionBackend(session2, options.backend.kind);
33
- options.validateSession?.(session2);
34
- await options.store?.put(session2);
35
- return { session: session2, input: input2, resumed: false };
36
- }
37
- assertSessionBackend(existing, options.backend.kind);
38
- const continued = options.backend.resume !== void 0;
39
- const input = resolveSessionInput(
40
- continued ? options.continuationInput ?? options.input : options.input
41
- );
42
- const session = options.backend.resume ? await options.backend.resume(existing, input, options.context) : touchSession({ ...existing, status: "active" });
43
- assertSessionBackend(session, options.backend.kind);
44
- options.validateSession?.(session);
45
- await options.store?.put(session);
46
- return { session, input, resumed: true };
47
- }
48
- function resolveSessionInput(input) {
49
- return typeof input === "function" ? input() : input;
50
- }
51
- function assertSessionBackend(session, backend) {
52
- if (session.backend !== backend) throw new SessionMismatchError(session.backend, backend);
53
- }
54
- var InMemoryRuntimeSessionStore = class {
55
- sessions = /* @__PURE__ */ new Map();
56
- events = /* @__PURE__ */ new Map();
57
- get(sessionId) {
58
- return this.sessions.get(sessionId);
59
- }
60
- put(session) {
61
- this.sessions.set(session.id, session);
62
- }
63
- appendEvent(sessionId, event) {
64
- const existing = this.events.get(sessionId) ?? [];
65
- existing.push(event);
66
- this.events.set(sessionId, existing);
67
- }
68
- listEvents(sessionId) {
69
- return [...this.events.get(sessionId) ?? []];
70
- }
71
- };
72
-
73
- // src/backends.ts
74
- function createIterableBackend(options) {
75
- return options;
76
- }
77
- function createSandboxPromptBackend(options) {
78
- const kind = options.kind ?? "sandbox";
79
- return {
80
- kind,
81
- async start(input, context) {
82
- const box = await options.getBox(input, context);
83
- return newRuntimeSession(
84
- kind,
85
- options.getSessionId?.(box, input) ?? context.requestedSessionId,
86
- { resumable: true }
87
- );
88
- },
89
- resume(session) {
90
- return touchSession({ ...session, status: "active" });
91
- },
92
- async *stream(input, context) {
93
- const box = await options.getBox(input, context);
94
- const message = input.message ?? input.messages?.at(-1)?.content ?? context.task.intent;
95
- for await (const event of options.streamPrompt(box, message, context)) {
96
- const mapped = options.mapEvent?.(event, context) ?? mapCommonBackendEvent(event, context);
97
- if (mapped) yield mapped;
98
- }
99
- }
100
- };
101
- }
102
- var DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504];
103
- function pickRetryDelayMs(attempt, policy) {
104
- const exp = policy.initialBackoffMs * 2 ** (attempt - 1);
105
- const capped = Math.min(exp, policy.maxBackoffMs);
106
- const jitter = capped * policy.jitter * (Math.random() * 2 - 1);
107
- return Math.max(0, Math.round(capped + jitter));
108
- }
109
- function withTimeout(callerSignal, timeoutMs) {
110
- if (timeoutMs <= 0) {
111
- return { signal: callerSignal ?? new AbortController().signal, dispose: () => void 0 };
112
- }
113
- const controller = new AbortController();
114
- const timer = setTimeout(
115
- () => controller.abort(new Error(`request timed out after ${timeoutMs}ms`)),
116
- timeoutMs
117
- );
118
- if (typeof timer.unref === "function") {
119
- ;
120
- timer.unref();
121
- }
122
- const onCallerAbort = () => controller.abort(callerSignal?.reason ?? new Error("aborted"));
123
- if (callerSignal) {
124
- if (callerSignal.aborted) onCallerAbort();
125
- else callerSignal.addEventListener("abort", onCallerAbort, { once: true });
126
- }
127
- return {
128
- signal: controller.signal,
129
- dispose: () => {
130
- clearTimeout(timer);
131
- callerSignal?.removeEventListener("abort", onCallerAbort);
132
- }
133
- };
134
- }
135
- function sleep(ms, signal) {
136
- return new Promise((resolve, reject) => {
137
- if (signal?.aborted) {
138
- reject(signal.reason ?? new Error("aborted"));
139
- return;
140
- }
141
- const t = setTimeout(() => {
142
- signal?.removeEventListener("abort", onAbort);
143
- resolve();
144
- }, ms);
145
- const onAbort = () => {
146
- clearTimeout(t);
147
- reject(signal?.reason ?? new Error("aborted"));
148
- };
149
- signal?.addEventListener("abort", onAbort, { once: true });
150
- });
151
- }
152
- function createOpenAICompatibleBackend(options) {
153
- const fetcher = options.fetchImpl ?? fetch;
154
- const kind = options.kind ?? "tcloud";
155
- const retryPolicy = {
156
- maxAttempts: options.retry?.maxAttempts ?? 5,
157
- initialBackoffMs: options.retry?.initialBackoffMs ?? 1e3,
158
- maxBackoffMs: options.retry?.maxBackoffMs ?? 3e4,
159
- jitter: options.retry?.jitter ?? 0.25,
160
- retryStatuses: options.retry?.retryStatuses ?? DEFAULT_RETRY_STATUSES,
161
- requestTimeoutMs: options.retry?.requestTimeoutMs ?? 12e4
162
- };
163
- return {
164
- kind,
165
- start(_input, context) {
166
- return newRuntimeSession(kind, context.requestedSessionId);
167
- },
168
- async *stream(input, context) {
169
- const url = `${options.baseUrl.replace(/\/$/, "")}/chat/completions`;
170
- const bodyPayload = {
171
- model: options.model,
172
- stream: true,
173
- stream_options: { include_usage: true },
174
- messages: input.messages ?? [
175
- { role: "user", content: input.message ?? context.task.intent }
176
- ]
177
- };
178
- if (options.tools && options.tools.length > 0) {
179
- bodyPayload.tools = options.tools;
180
- if (options.toolChoice !== void 0) bodyPayload.tool_choice = options.toolChoice;
181
- }
182
- if (options.responseFormat !== void 0) {
183
- bodyPayload.response_format = options.responseFormat;
184
- }
185
- if (options.temperature !== void 0) {
186
- bodyPayload.temperature = options.temperature;
187
- }
188
- if (options.maxTokens !== void 0) {
189
- bodyPayload.max_tokens = options.maxTokens;
190
- }
191
- const requestBody = JSON.stringify(bodyPayload);
192
- let response;
193
- let lastStatus = 0;
194
- let lastThrown;
195
- for (let attempt = 1; attempt <= retryPolicy.maxAttempts; attempt++) {
196
- lastThrown = void 0;
197
- const attemptSignal = withTimeout(context.signal, retryPolicy.requestTimeoutMs);
198
- try {
199
- response = await fetcher(url, {
200
- method: "POST",
201
- headers: {
202
- Authorization: `Bearer ${options.apiKey}`,
203
- "Content-Type": "application/json",
204
- // Cross-gateway forwarding: when this call is part of a
205
- // multi-agent conversation, the runner stamps run/turn/
206
- // depth/forwarded-auth headers onto the context. They flow
207
- // through to the downstream gateway verbatim so the original
208
- // user gets billed, the recursion depth stays bounded, and
209
- // the trace correlates across hops.
210
- ...context.propagatedHeaders ?? {}
211
- },
212
- body: requestBody,
213
- signal: attemptSignal.signal
214
- });
215
- } catch (err) {
216
- attemptSignal.dispose();
217
- if (context.signal?.aborted) throw err;
218
- lastThrown = err;
219
- response = void 0;
220
- if (attempt === retryPolicy.maxAttempts) break;
221
- await sleep(pickRetryDelayMs(attempt, retryPolicy), context.signal);
222
- continue;
223
- }
224
- attemptSignal.dispose();
225
- if (response.ok) break;
226
- lastStatus = response.status;
227
- if (!retryPolicy.retryStatuses.includes(response.status)) break;
228
- if (attempt === retryPolicy.maxAttempts) break;
229
- try {
230
- await response.body?.cancel();
231
- } catch {
232
- }
233
- const delayMs = pickRetryDelayMs(attempt, retryPolicy);
234
- await sleep(delayMs, context.signal);
235
- }
236
- if (!response) {
237
- const reason = lastThrown instanceof Error ? lastThrown.message : String(lastThrown);
238
- throw new BackendTransportError(
239
- kind,
240
- `chat backend unreachable after ${retryPolicy.maxAttempts} attempts: ${reason}`,
241
- { status: 0 }
242
- );
243
- }
244
- if (!response.ok) {
245
- let body;
246
- try {
247
- const raw = await response.text();
248
- body = raw.length > MAX_ERROR_BODY_BYTES ? `${raw.slice(0, MAX_ERROR_BODY_BYTES)}\u2026` : raw;
249
- } catch {
250
- body = void 0;
251
- }
252
- throw new BackendTransportError(kind, `chat backend returned ${lastStatus || "unknown"}`, {
253
- status: lastStatus || 0,
254
- body
255
- });
256
- }
257
- yield* streamResponseEvents(response, context, options.model);
258
- }
259
- };
260
- }
261
- var MAX_ERROR_BODY_BYTES = 2048;
262
- function normalizeBackendStreamEvent(event, task, session) {
263
- if ("task" in event && event.task && "session" in event && event.session && "timestamp" in event && event.timestamp) {
264
- return event;
265
- }
266
- return {
267
- ...event,
268
- task: "task" in event && event.task ? event.task : task,
269
- session: "session" in event && event.session ? event.session : session,
270
- timestamp: "timestamp" in event && event.timestamp ? event.timestamp : nowIso()
271
- };
272
- }
273
- function mapCommonBackendEvent(event, context) {
274
- if (!event || typeof event !== "object") return void 0;
275
- const record = event;
276
- const type = String(record.type ?? "");
277
- const data = record.data && typeof record.data === "object" ? record.data : record;
278
- if (type === "message.part.updated" || type === "text_delta" || type === "delta") {
279
- const part = data.part;
280
- const partText = part !== void 0 && typeof part === "object" && (part.type === "text" || part.type === void 0) ? stringValue(part.text) : void 0;
281
- const text = stringValue(data.text) ?? stringValue(data.delta) ?? stringValue(record.text) ?? partText;
282
- return text ? {
283
- type: "text_delta",
284
- task: context.task,
285
- session: context.session,
286
- text,
287
- timestamp: nowIso()
288
- } : void 0;
289
- }
290
- if (type === "reasoning_delta") {
291
- const text = stringValue(data.text) ?? stringValue(record.text);
292
- return text ? {
293
- type: "reasoning_delta",
294
- task: context.task,
295
- session: context.session,
296
- text,
297
- timestamp: nowIso()
298
- } : void 0;
299
- }
300
- if (type === "tool_call") {
301
- return {
302
- type: "tool_call",
303
- task: context.task,
304
- session: context.session,
305
- toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? "tool",
306
- toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),
307
- args: data.args ?? data.input ?? record.args,
308
- timestamp: nowIso()
309
- };
310
- }
311
- if (type === "tool_result") {
312
- return {
313
- type: "tool_result",
314
- task: context.task,
315
- session: context.session,
316
- toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? "tool",
317
- toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),
318
- result: data.result ?? data.output ?? record.result,
319
- timestamp: nowIso()
320
- };
321
- }
322
- if (type === "artifact") {
323
- const artifactId = stringValue(data.artifactId) ?? stringValue(data.id) ?? stringValue(record.artifactId);
324
- if (!artifactId) return void 0;
325
- return {
326
- type: "artifact",
327
- task: context.task,
328
- session: context.session,
329
- artifactId,
330
- name: stringValue(data.name) ?? stringValue(record.name),
331
- mimeType: stringValue(data.mimeType) ?? stringValue(record.mimeType),
332
- uri: stringValue(data.uri) ?? stringValue(record.uri),
333
- content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),
334
- metadata: data.metadata && typeof data.metadata === "object" ? data.metadata : void 0,
335
- timestamp: nowIso()
336
- };
337
- }
338
- if (type === "proposal_created" || type === "proposal" || type === "filing") {
339
- const proposalId = stringValue(data.proposalId) ?? stringValue(data.id) ?? stringValue(record.proposalId);
340
- if (!proposalId) return void 0;
341
- const status = stringValue(data.status) ?? stringValue(record.status);
342
- return {
343
- type: "proposal_created",
344
- task: context.task,
345
- session: context.session,
346
- proposalId,
347
- title: stringValue(data.title) ?? stringValue(record.title) ?? proposalId,
348
- status: status === "pending" || status === "approved" || status === "rejected" ? status : void 0,
349
- content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),
350
- timestamp: nowIso()
351
- };
352
- }
353
- if (type === "result" || type === "final") {
354
- const text = stringValue(data.finalText) ?? stringValue(data.text) ?? stringValue(record.text);
355
- return text ? {
356
- type: "text_delta",
357
- task: context.task,
358
- session: context.session,
359
- text,
360
- timestamp: nowIso()
361
- } : void 0;
362
- }
363
- return void 0;
364
- }
365
- async function* streamResponseEvents(response, context, requestedModel) {
366
- const body = response.body;
367
- if (!body) return;
368
- const reader = body.getReader();
369
- const decoder = new TextDecoder();
370
- let buffer = "";
371
- const usage = { saw: false };
372
- const toolCalls = /* @__PURE__ */ new Map();
373
- const startedAt = Date.now();
374
- for (; ; ) {
375
- const { done, value } = await reader.read();
376
- if (done) break;
377
- buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
378
- for (const event of drainStreamBuffer(false)) yield event;
379
- }
380
- buffer += decoder.decode().replace(/\r\n/g, "\n");
381
- for (const event of drainStreamBuffer(true)) yield event;
382
- if (buffer.trim()) {
383
- for (const event of parseStreamChunk(buffer, context, usage, toolCalls)) yield event;
384
- }
385
- for (const event of flushPendingToolCalls(toolCalls, context)) yield event;
386
- if (usage.saw) {
387
- yield {
388
- type: "llm_call",
389
- task: context.task,
390
- session: context.session,
391
- model: usage.model ?? requestedModel,
392
- tokensIn: usage.tokensIn,
393
- tokensOut: usage.tokensOut,
394
- // `costUsd` is intentionally absent — pricing tables live in consumers
395
- // (agent-eval's `estimateCost`, MetricsCollector). Emitting a wrong
396
- // number here is worse than emitting none.
397
- latencyMs: Date.now() - startedAt,
398
- finishReason: usage.finishReason,
399
- timestamp: nowIso()
400
- };
401
- }
402
- function* drainStreamBuffer(flush) {
403
- for (; ; ) {
404
- const sseBoundary = buffer.indexOf("\n\n");
405
- if (sseBoundary >= 0) {
406
- const chunk = buffer.slice(0, sseBoundary);
407
- buffer = buffer.slice(sseBoundary + 2);
408
- for (const event of parseStreamChunk(chunk, context, usage, toolCalls)) yield event;
409
- continue;
410
- }
411
- const newline = buffer.indexOf("\n");
412
- if (newline >= 0 && !buffer.slice(0, newline).startsWith("data:")) {
413
- const line = buffer.slice(0, newline);
414
- buffer = buffer.slice(newline + 1);
415
- for (const event of parseStreamChunk(line, context, usage, toolCalls)) yield event;
416
- continue;
417
- }
418
- if (flush && buffer.trim() && !buffer.trimStart().startsWith("data:")) {
419
- const line = buffer;
420
- buffer = "";
421
- for (const event of parseStreamChunk(line, context, usage, toolCalls)) yield event;
422
- continue;
423
- }
424
- break;
425
- }
426
- }
427
- }
428
- function* parseStreamChunk(chunk, context, usage, toolCalls) {
429
- const lines = chunk.split(/\r?\n/);
430
- const dataLines = lines.filter((line) => line.startsWith("data:"));
431
- if (dataLines.length === 0 && lines.every((line) => {
432
- const trimmed = line.trim();
433
- return trimmed.length === 0 || trimmed.startsWith(":");
434
- })) {
435
- return;
436
- }
437
- const data = dataLines.length > 0 ? dataLines.map((line) => line.slice(5).trimStart()).join("\n") : chunk.trim();
438
- if (!data || data === "[DONE]") return;
439
- let parsed;
440
- try {
441
- parsed = JSON.parse(data);
442
- } catch {
443
- yield {
444
- type: "text_delta",
445
- task: context.task,
446
- session: context.session,
447
- text: data,
448
- timestamp: nowIso()
449
- };
450
- return;
451
- }
452
- captureStreamUsage(parsed, usage);
453
- const choices = parsed.choices;
454
- const choice = Array.isArray(choices) ? choices[0] : void 0;
455
- const delta = choice?.delta;
456
- const message = choice?.message;
457
- const deltaToolCalls = delta?.tool_calls;
458
- if (Array.isArray(deltaToolCalls)) {
459
- for (const tc of deltaToolCalls) {
460
- if (!tc || typeof tc !== "object") continue;
461
- const rec = tc;
462
- const idx = numberValue(rec.index) ?? 0;
463
- const key = `openai:${idx}`;
464
- const acc = toolCalls.get(key) ?? { argsRaw: "", source: "openai", finalized: false };
465
- const id = stringValue(rec.id);
466
- if (id) acc.id = id;
467
- const fn = rec.function;
468
- const name = stringValue(fn?.name);
469
- if (name) acc.name = name;
470
- const args = stringValue(fn?.arguments);
471
- if (args) acc.argsRaw += args;
472
- toolCalls.set(key, acc);
473
- }
474
- }
475
- const messageToolCalls = message?.tool_calls;
476
- if (Array.isArray(messageToolCalls)) {
477
- for (const tc of messageToolCalls) {
478
- if (!tc || typeof tc !== "object") continue;
479
- const rec = tc;
480
- const fn = rec.function;
481
- const idx = numberValue(rec.index) ?? messageToolCalls.indexOf(tc);
482
- const key = `openai:${idx}`;
483
- const acc = toolCalls.get(key) ?? { argsRaw: "", source: "openai", finalized: false };
484
- const id = stringValue(rec.id);
485
- if (id) acc.id = id;
486
- const name = stringValue(fn?.name);
487
- if (name) acc.name = name;
488
- const args = stringValue(fn?.arguments);
489
- if (args) acc.argsRaw += args;
490
- acc.finalized = true;
491
- toolCalls.set(key, acc);
492
- }
493
- }
494
- const finishReason = stringValue(choice?.finish_reason);
495
- if (finishReason === "tool_calls") {
496
- for (const [key, acc] of toolCalls) {
497
- if (acc.source === "openai" && !acc.finalized) acc.finalized = true;
498
- toolCalls.set(key, acc);
499
- }
500
- }
501
- const eventType = stringValue(parsed.type);
502
- if (eventType === "content_block_start") {
503
- const block = parsed.content_block;
504
- if (block && stringValue(block.type) === "tool_use") {
505
- const idx = numberValue(parsed.index) ?? 0;
506
- const key = `anthropic:${idx}`;
507
- toolCalls.set(key, {
508
- id: stringValue(block.id),
509
- name: stringValue(block.name),
510
- argsRaw: "",
511
- source: "anthropic",
512
- finalized: false
513
- });
514
- }
515
- }
516
- if (eventType === "content_block_delta") {
517
- const d = parsed.delta;
518
- const dType = stringValue(d?.type);
519
- if (dType === "input_json_delta") {
520
- const idx = numberValue(parsed.index) ?? 0;
521
- const key = `anthropic:${idx}`;
522
- const acc = toolCalls.get(key);
523
- if (acc) {
524
- const partial = stringValue(d?.partial_json) ?? "";
525
- acc.argsRaw += partial;
526
- toolCalls.set(key, acc);
527
- }
528
- } else {
529
- const text2 = stringValue(d?.text);
530
- if (text2) {
531
- yield {
532
- type: "text_delta",
533
- task: context.task,
534
- session: context.session,
535
- text: text2,
536
- timestamp: nowIso()
537
- };
538
- }
539
- }
540
- }
541
- if (eventType === "content_block_stop") {
542
- const idx = numberValue(parsed.index) ?? 0;
543
- const key = `anthropic:${idx}`;
544
- const acc = toolCalls.get(key);
545
- if (acc) {
546
- acc.finalized = true;
547
- toolCalls.set(key, acc);
548
- }
549
- }
550
- for (const event of drainFinalizedToolCalls(toolCalls, context)) yield event;
551
- const text = stringValue(delta?.content) ?? stringValue(message?.content) ?? stringValue(parsed.text);
552
- if (text) {
553
- yield {
554
- type: "text_delta",
555
- task: context.task,
556
- session: context.session,
557
- text,
558
- timestamp: nowIso()
559
- };
560
- return;
561
- }
562
- const mapped = mapCommonBackendEvent(parsed, context);
563
- if (mapped) yield mapped;
564
- }
565
- function* drainFinalizedToolCalls(toolCalls, context) {
566
- for (const [key, acc] of toolCalls) {
567
- if (!acc.finalized) continue;
568
- toolCalls.delete(key);
569
- yield buildToolCallEvent(acc, context);
570
- }
571
- }
572
- function* flushPendingToolCalls(toolCalls, context) {
573
- for (const [key, acc] of toolCalls) {
574
- toolCalls.delete(key);
575
- yield buildToolCallEvent(acc, context);
576
- }
577
- }
578
- function buildToolCallEvent(acc, context) {
579
- let args = acc.argsRaw;
580
- if (acc.argsRaw.length > 0) {
581
- try {
582
- args = JSON.parse(acc.argsRaw);
583
- } catch {
584
- args = acc.argsRaw;
585
- }
586
- } else {
587
- args = {};
588
- }
589
- return {
590
- type: "tool_call",
591
- task: context.task,
592
- session: context.session,
593
- toolName: acc.name ?? "tool",
594
- toolCallId: acc.id,
595
- args,
596
- timestamp: nowIso()
597
- };
598
- }
599
- function captureStreamUsage(parsed, usage) {
600
- const model = stringValue(parsed.model);
601
- if (model && !usage.model) usage.model = model;
602
- const openAiUsage = parsed.usage;
603
- if (openAiUsage && typeof openAiUsage === "object") {
604
- const promptTokens = numberValue(openAiUsage.prompt_tokens);
605
- const completionTokens = numberValue(openAiUsage.completion_tokens);
606
- const inputTokens = numberValue(openAiUsage.input_tokens);
607
- const outputTokens = numberValue(openAiUsage.output_tokens);
608
- if (promptTokens !== void 0) {
609
- usage.tokensIn = promptTokens;
610
- usage.saw = true;
611
- } else if (inputTokens !== void 0) {
612
- usage.tokensIn = (usage.tokensIn ?? 0) + inputTokens;
613
- usage.saw = true;
614
- }
615
- if (completionTokens !== void 0) {
616
- usage.tokensOut = completionTokens;
617
- usage.saw = true;
618
- } else if (outputTokens !== void 0) {
619
- usage.tokensOut = (usage.tokensOut ?? 0) + outputTokens;
620
- usage.saw = true;
621
- }
622
- }
623
- const type = stringValue(parsed.type);
624
- if (type === "message_start") {
625
- const message = parsed.message;
626
- const messageModel = stringValue(message?.model);
627
- if (messageModel && !usage.model) usage.model = messageModel;
628
- const messageUsage = message?.usage;
629
- const inputTokens = numberValue(messageUsage?.input_tokens);
630
- if (inputTokens !== void 0) {
631
- usage.tokensIn = inputTokens;
632
- usage.saw = true;
633
- }
634
- const outputTokens = numberValue(messageUsage?.output_tokens);
635
- if (outputTokens !== void 0) {
636
- usage.tokensOut = (usage.tokensOut ?? 0) + outputTokens;
637
- usage.saw = true;
638
- }
639
- }
640
- if (type === "message_delta") {
641
- const delta = parsed.delta;
642
- const stopReason = stringValue(delta?.stop_reason);
643
- if (stopReason) usage.finishReason = stopReason;
644
- }
645
- const choices = parsed.choices;
646
- if (Array.isArray(choices)) {
647
- const finishReason = stringValue(
648
- choices[0]?.finish_reason
649
- );
650
- if (finishReason) usage.finishReason = finishReason;
651
- }
652
- }
653
- function numberValue(value) {
654
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
655
- }
656
- function stringValue(value) {
657
- return typeof value === "string" && value.length > 0 ? value : void 0;
658
- }
659
-
660
- export {
661
- newRuntimeSession,
662
- touchSession,
663
- nowIso,
664
- startOrResumeRuntimeSession,
665
- InMemoryRuntimeSessionStore,
666
- createIterableBackend,
667
- createSandboxPromptBackend,
668
- createOpenAICompatibleBackend,
669
- normalizeBackendStreamEvent
670
- };
671
- //# sourceMappingURL=chunk-Q2JSAVQ3.js.map