@compose-market/sdk 0.8.2 → 0.8.3

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 (128) hide show
  1. package/.speakeasy/a2a.arazzo.yaml +1 -1
  2. package/.speakeasy/memory.arazzo.yaml +1 -1
  3. package/.speakeasy/tests.arazzo.yaml +1 -1
  4. package/dist/errors.d.ts +2 -0
  5. package/dist/errors.d.ts.map +1 -0
  6. package/dist/errors.js +2 -0
  7. package/dist/errors.js.map +1 -0
  8. package/dist/events.d.ts +202 -0
  9. package/dist/events.d.ts.map +1 -0
  10. package/dist/events.js +70 -0
  11. package/dist/events.js.map +1 -0
  12. package/dist/index.d.ts +277 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +551 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/resources/accounts.d.ts +32 -0
  17. package/dist/resources/accounts.d.ts.map +1 -0
  18. package/dist/resources/accounts.js +128 -0
  19. package/dist/resources/accounts.js.map +1 -0
  20. package/dist/resources/agent.d.ts +58 -0
  21. package/dist/resources/agent.d.ts.map +1 -0
  22. package/dist/resources/agent.js +787 -0
  23. package/dist/resources/agent.js.map +1 -0
  24. package/dist/resources/channels.d.ts +24 -0
  25. package/dist/resources/channels.d.ts.map +1 -0
  26. package/dist/resources/channels.js +74 -0
  27. package/dist/resources/channels.js.map +1 -0
  28. package/dist/resources/directory.d.ts +43 -0
  29. package/dist/resources/directory.d.ts.map +1 -0
  30. package/dist/resources/directory.js +97 -0
  31. package/dist/resources/directory.js.map +1 -0
  32. package/dist/resources/dispenser.d.ts +25 -0
  33. package/dist/resources/dispenser.d.ts.map +1 -0
  34. package/dist/resources/dispenser.js +56 -0
  35. package/dist/resources/dispenser.js.map +1 -0
  36. package/dist/resources/feedback.d.ts +35 -0
  37. package/dist/resources/feedback.d.ts.map +1 -0
  38. package/dist/resources/feedback.js +127 -0
  39. package/dist/resources/feedback.js.map +1 -0
  40. package/dist/resources/inference.d.ts +206 -0
  41. package/dist/resources/inference.d.ts.map +1 -0
  42. package/dist/resources/inference.js +1049 -0
  43. package/dist/resources/inference.js.map +1 -0
  44. package/dist/resources/instrumentation.d.ts +29 -0
  45. package/dist/resources/instrumentation.d.ts.map +1 -0
  46. package/dist/resources/instrumentation.js +43 -0
  47. package/dist/resources/instrumentation.js.map +1 -0
  48. package/dist/resources/keys.d.ts +56 -0
  49. package/dist/resources/keys.d.ts.map +1 -0
  50. package/dist/resources/keys.js +186 -0
  51. package/dist/resources/keys.js.map +1 -0
  52. package/dist/resources/local.d.ts +56 -0
  53. package/dist/resources/local.d.ts.map +1 -0
  54. package/dist/resources/local.js +163 -0
  55. package/dist/resources/local.js.map +1 -0
  56. package/dist/resources/memory.d.ts +249 -0
  57. package/dist/resources/memory.d.ts.map +1 -0
  58. package/dist/resources/memory.js +217 -0
  59. package/dist/resources/memory.js.map +1 -0
  60. package/dist/resources/models.d.ts +45 -0
  61. package/dist/resources/models.d.ts.map +1 -0
  62. package/dist/resources/models.js +101 -0
  63. package/dist/resources/models.js.map +1 -0
  64. package/dist/resources/permissions.d.ts +23 -0
  65. package/dist/resources/permissions.d.ts.map +1 -0
  66. package/dist/resources/permissions.js +69 -0
  67. package/dist/resources/permissions.js.map +1 -0
  68. package/dist/resources/receipts.d.ts +23 -0
  69. package/dist/resources/receipts.d.ts.map +1 -0
  70. package/dist/resources/receipts.js +48 -0
  71. package/dist/resources/receipts.js.map +1 -0
  72. package/dist/resources/session-events.d.ts +51 -0
  73. package/dist/resources/session-events.d.ts.map +1 -0
  74. package/dist/resources/session-events.js +404 -0
  75. package/dist/resources/session-events.js.map +1 -0
  76. package/dist/resources/settlement.d.ts +21 -0
  77. package/dist/resources/settlement.d.ts.map +1 -0
  78. package/dist/resources/settlement.js +30 -0
  79. package/dist/resources/settlement.js.map +1 -0
  80. package/dist/resources/system.d.ts +9 -0
  81. package/dist/resources/system.d.ts.map +1 -0
  82. package/dist/resources/system.js +19 -0
  83. package/dist/resources/system.js.map +1 -0
  84. package/dist/resources/webhooks.d.ts +27 -0
  85. package/dist/resources/webhooks.d.ts.map +1 -0
  86. package/dist/resources/webhooks.js +78 -0
  87. package/dist/resources/webhooks.js.map +1 -0
  88. package/dist/resources/workflow.d.ts +49 -0
  89. package/dist/resources/workflow.d.ts.map +1 -0
  90. package/dist/resources/workflow.js +364 -0
  91. package/dist/resources/workflow.js.map +1 -0
  92. package/dist/resources/x402.d.ts +113 -0
  93. package/dist/resources/x402.d.ts.map +1 -0
  94. package/dist/resources/x402.js +231 -0
  95. package/dist/resources/x402.js.map +1 -0
  96. package/dist/tools/index.d.ts +55 -0
  97. package/dist/tools/index.d.ts.map +1 -0
  98. package/dist/tools/index.js +51 -0
  99. package/dist/tools/index.js.map +1 -0
  100. package/dist/types/index.d.ts +1859 -0
  101. package/dist/types/index.d.ts.map +1 -0
  102. package/dist/types/index.js +14 -0
  103. package/dist/types/index.js.map +1 -0
  104. package/dist/version.d.ts +9 -0
  105. package/dist/version.d.ts.map +1 -0
  106. package/dist/version.js +9 -0
  107. package/dist/version.js.map +1 -0
  108. package/generated/inference/esm/lib/config.d.ts +3 -3
  109. package/generated/inference/esm/lib/config.js +3 -3
  110. package/generated/inference/package.json +1 -1
  111. package/generated/inference/src/lib/config.ts +3 -3
  112. package/generated/manowar/esm/lib/config.d.ts +3 -3
  113. package/generated/manowar/esm/lib/config.js +3 -3
  114. package/generated/manowar/package.json +1 -1
  115. package/generated/manowar/src/lib/config.ts +3 -3
  116. package/generated/memory/esm/lib/config.d.ts +3 -3
  117. package/generated/memory/esm/lib/config.js +3 -3
  118. package/generated/memory/package.json +1 -1
  119. package/generated/memory/src/lib/config.ts +3 -3
  120. package/generated/x402/esm/lib/config.d.ts +3 -3
  121. package/generated/x402/esm/lib/config.js +3 -3
  122. package/generated/x402/package.json +1 -1
  123. package/generated/x402/src/lib/config.ts +3 -3
  124. package/package.json +2 -2
  125. package/specs/inference.openapi.yaml +1 -1
  126. package/specs/manowar.openapi.yaml +1 -1
  127. package/specs/memory.openapi.yaml +1 -1
  128. package/specs/x402.openapi.yaml +1 -1
@@ -0,0 +1,787 @@
1
+ /**
2
+ * Compose agent runtime stream resource.
3
+ *
4
+ * Subscribes to POST /agent/:wallet/stream on the Compose runtime service
5
+ * and yields ordered model/activity events. The runtime emits OpenAI-ish
6
+ * chat.completion.chunk frames for text deltas AND Compose-native frames
7
+ * (`thinking_start`, `thinking_end`, `tool_start`, `tool_end`, `done`,
8
+ * `error`). This resource normalises both into the single
9
+ * text frames for chat content and Compose-native activity frames for
10
+ * execution lifecycle. This resource keeps those domains separate.
11
+ *
12
+ * Integrates with:
13
+ * - `sdk.events.toolCallStart` / `toolCallEnd` — emitted whenever the
14
+ * runtime tool vocabulary fires, so UI strips can react uniformly
15
+ * regardless of whether the source is agent, workflow, or chat.
16
+ * - `sdk.events.agentStreamStart` / `agentStreamEnd` — lifecycle notifications.
17
+ * - `instrumentBillableResponse` — budget/receipt/sessionInvalid surfaced
18
+ * exactly as on every other billable SDK call.
19
+ */
20
+ import { Error } from "../errors.js";
21
+ import { parseSSEStream } from "@compose-market/core/transport";
22
+ import { extractReceiptFromResponse, parseReceiptEvent } from "@compose-market/core/sse/receipt";
23
+ import { extractSessionBudgetFromResponse } from "@compose-market/core/sse/budget";
24
+ import { decode as decodeActivityEvent } from "@compose-market/core/activity";
25
+ import { decode as decodeModelEvent } from "@compose-market/core/model";
26
+ import { buildCallHeaders, StreamIterator, requestResponseWithPayment, } from "./inference.js";
27
+ export class AgentResource {
28
+ ctx;
29
+ constructor(ctx) {
30
+ this.ctx = ctx;
31
+ }
32
+ stream(params, options = {}) {
33
+ return new StreamIterator(driveAgentStream(this.ctx, params, options));
34
+ }
35
+ /**
36
+ * Abort an in-flight stream for (agentWallet, runId). Conversation/CoT/memory
37
+ * for the thread are preserved by the LangGraph checkpoint and can be resumed
38
+ * by issuing a new stream call with the same threadId.
39
+ */
40
+ async stop(params) {
41
+ const wallet = this.ctx.getWalletMaybe();
42
+ const token = this.ctx.getTokenMaybe();
43
+ const headers = {
44
+ "Content-Type": "application/json",
45
+ "User-Agent": this.ctx.userAgent,
46
+ };
47
+ if (token)
48
+ headers.Authorization = `Bearer ${token}`;
49
+ if (wallet.address)
50
+ headers["x-session-user-address"] = wallet.address;
51
+ if (wallet.chainId !== null)
52
+ headers["x-chain-id"] = String(wallet.chainId);
53
+ const path = `/agent/${encodeURIComponent(params.agentWallet)}/runs/${encodeURIComponent(params.runId)}/stop`;
54
+ const response = await this.ctx.http.request({
55
+ method: "POST",
56
+ path,
57
+ headers,
58
+ body: params.threadId ? { threadId: params.threadId } : {},
59
+ }).withResponse();
60
+ const data = response.data;
61
+ return { stopped: Boolean(data?.stopped) };
62
+ }
63
+ async decide(params) {
64
+ const wallet = this.ctx.getWalletMaybe();
65
+ const token = this.ctx.getTokenMaybe();
66
+ const headers = {
67
+ "Content-Type": "application/json",
68
+ "User-Agent": this.ctx.userAgent,
69
+ };
70
+ if (token)
71
+ headers.Authorization = `Bearer ${token}`;
72
+ if (wallet.address)
73
+ headers["x-session-user-address"] = wallet.address;
74
+ if (wallet.chainId !== null)
75
+ headers["x-chain-id"] = String(wallet.chainId);
76
+ const path = `/agent/${encodeURIComponent(params.agentWallet)}/runs/${encodeURIComponent(params.runId)}/approval`;
77
+ return await this.ctx.http.request({
78
+ method: "POST",
79
+ path,
80
+ headers,
81
+ body: {
82
+ proposalId: params.proposalId,
83
+ version: params.version,
84
+ decision: params.decision,
85
+ ...(params.approvalId ? { approvalId: params.approvalId } : {}),
86
+ ...(params.approver ? { approver: params.approver } : {}),
87
+ ...(params.reason ? { reason: params.reason } : {}),
88
+ ...(params.feedback ? { feedback: params.feedback } : {}),
89
+ },
90
+ });
91
+ }
92
+ }
93
+ async function* driveAgentStream(ctx, params, options) {
94
+ const path = `/agent/${encodeURIComponent(params.agentWallet)}/stream`;
95
+ const wallet = ctx.getWalletMaybe();
96
+ const token = ctx.getTokenMaybe();
97
+ const body = {
98
+ message: params.message,
99
+ threadId: params.threadId,
100
+ userAddress: params.userAddress,
101
+ };
102
+ if (params.agentCard)
103
+ body.agentCard = params.agentCard;
104
+ if (params.runId)
105
+ body.runId = params.runId;
106
+ if (params.cloudPermissions)
107
+ body.cloudPermissions = params.cloudPermissions;
108
+ if (params.attachment)
109
+ body.attachment = params.attachment;
110
+ if (params.attachments)
111
+ body.attachments = params.attachments;
112
+ if (params.mode)
113
+ body.mode = params.mode;
114
+ if (params.scope)
115
+ body.scope = params.scope;
116
+ if (params.action)
117
+ body.action = params.action;
118
+ if (params.plan !== undefined)
119
+ body.plan = params.plan;
120
+ if (params.sandbox !== undefined)
121
+ body.sandbox = params.sandbox;
122
+ if (params.proof !== undefined)
123
+ body.proof = params.proof;
124
+ if (params.constraints)
125
+ body.constraints = params.constraints;
126
+ const timeoutController = new AbortController();
127
+ const timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;
128
+ const timer = setTimeout(() => timeoutController.abort(), timeoutMs);
129
+ ctx.events.emit("agentStreamStart", {
130
+ userAddress: wallet.address,
131
+ chainId: wallet.chainId,
132
+ requestId: null,
133
+ agentWallet: params.agentWallet,
134
+ threadId: params.threadId,
135
+ runId: params.runId,
136
+ });
137
+ const requestSignal = mergeSignals(options.signal, timeoutController.signal);
138
+ let response;
139
+ try {
140
+ response = await requestResponseWithPayment(ctx.http, ctx, {
141
+ method: "POST",
142
+ path,
143
+ body,
144
+ headers: {
145
+ ...buildCallHeaders(options, wallet, token),
146
+ runId: params.runId ?? options.runId,
147
+ },
148
+ signal: requestSignal.signal,
149
+ timeoutMs,
150
+ expectStream: true,
151
+ }, options);
152
+ }
153
+ catch (fetchError) {
154
+ requestSignal.cleanup();
155
+ clearTimeout(timer);
156
+ if (fetchError instanceof Error)
157
+ throw fetchError;
158
+ throw new Error({
159
+ code: "network_error",
160
+ message: fetchError instanceof Error ? fetchError.message : String(fetchError),
161
+ });
162
+ }
163
+ requestSignal.cleanup();
164
+ clearTimeout(timer);
165
+ if (!response.ok) {
166
+ const text = await response.text().catch(() => "");
167
+ throw new Error({
168
+ code: "upstream_error",
169
+ message: `Agent runtime returned ${response.status}: ${text.slice(0, 500)}`,
170
+ status: response.status,
171
+ });
172
+ }
173
+ if (!response.body) {
174
+ throw new Error({ code: "upstream_error", message: "Agent runtime stream had no body" });
175
+ }
176
+ const requestId = response.headers.get("x-request-id") ?? response.headers.get("X-Request-Id");
177
+ const headerReceipt = extractReceiptFromResponse(response);
178
+ const { budget, sessionInvalidReason } = extractSessionBudgetFromResponse(response);
179
+ if (headerReceipt) {
180
+ ctx.events.emit("receipt", {
181
+ userAddress: wallet.address,
182
+ chainId: wallet.chainId,
183
+ receipt: headerReceipt,
184
+ requestId,
185
+ source: "response-header",
186
+ });
187
+ }
188
+ if (budget) {
189
+ ctx.events.emit("budget", {
190
+ userAddress: wallet.address,
191
+ chainId: wallet.chainId,
192
+ snapshot: budget,
193
+ requestId,
194
+ });
195
+ }
196
+ if (sessionInvalidReason) {
197
+ ctx.events.emit("sessionInvalid", {
198
+ userAddress: wallet.address,
199
+ chainId: wallet.chainId,
200
+ reason: sessionInvalidReason,
201
+ requestId,
202
+ });
203
+ }
204
+ let text = "";
205
+ let streamReceipt = null;
206
+ let emittedDone = false;
207
+ const postDoneTimeoutMs = options.paymentMode === "x402" ? 90_000 : 250;
208
+ const toolCalls = [];
209
+ const activeTools = new Map();
210
+ const decodeOptions = { runId: params.runId };
211
+ try {
212
+ const sse = parseSSEStream(response.body, { signal: options.signal })[Symbol.asyncIterator]();
213
+ while (true) {
214
+ const next = await readAgentStreamFrame(sse, emittedDone ? postDoneTimeoutMs : undefined);
215
+ if (next.done)
216
+ break;
217
+ const frame = next.value;
218
+ if (frame.data === "[DONE]") {
219
+ if (!emittedDone) {
220
+ emittedDone = true;
221
+ }
222
+ continue;
223
+ }
224
+ if (isReceiptEvent(frame.event)) {
225
+ try {
226
+ streamReceipt = parseReceiptEvent(frame.data);
227
+ ctx.events.emit("receipt", {
228
+ userAddress: wallet.address,
229
+ chainId: wallet.chainId,
230
+ receipt: streamReceipt,
231
+ requestId,
232
+ source: "stream",
233
+ });
234
+ }
235
+ catch { /* skip malformed */ }
236
+ if (emittedDone)
237
+ break;
238
+ continue;
239
+ }
240
+ if (frame.event === "compose.error") {
241
+ const decoded = decodeActivityEvent(frame, decodeOptions)
242
+ ?? decodeActivityEvent({ type: "error", message: frame.data }, decodeOptions);
243
+ if (decoded)
244
+ yield decoded;
245
+ continue;
246
+ }
247
+ if (!frame.data)
248
+ continue;
249
+ if (emittedDone)
250
+ continue;
251
+ let payload = null;
252
+ try {
253
+ payload = JSON.parse(frame.data);
254
+ }
255
+ catch {
256
+ const delta = frame.data;
257
+ text += delta;
258
+ const decoded = decodeModelEvent(delta, decodeOptions);
259
+ if (decoded)
260
+ yield decoded;
261
+ continue;
262
+ }
263
+ if (payload.domain === "model") {
264
+ const decoded = decodeModelEvent(payload, decodeOptions);
265
+ if (decoded) {
266
+ if (decoded.type === "model.text.delta" && decoded.delta)
267
+ text += decoded.delta;
268
+ if (decoded.type === "model.text.done" && decoded.text && !text)
269
+ text = decoded.text;
270
+ yield decoded;
271
+ }
272
+ continue;
273
+ }
274
+ if (payload.domain === "activity") {
275
+ const decoded = decodeActivityEvent(payload, decodeOptions);
276
+ if (decoded)
277
+ yield decoded;
278
+ continue;
279
+ }
280
+ // OpenAI chat.completion.chunk passthrough — runtime forwards these
281
+ // for streamed assistant text.
282
+ const choices = Array.isArray(payload.choices) ? payload.choices : null;
283
+ if (choices && choices.length > 0) {
284
+ const delta = choices[0].delta;
285
+ const reasoningChunk = typeof delta?.reasoning_content === "string"
286
+ ? delta.reasoning_content
287
+ : null;
288
+ if (reasoningChunk) {
289
+ const decoded = decodeModelEvent({ type: "reasoning-delta", delta: reasoningChunk }, decodeOptions);
290
+ if (decoded)
291
+ yield decoded;
292
+ }
293
+ const streamedChunk = typeof delta?.content === "string"
294
+ ? delta.content
295
+ : null;
296
+ if (streamedChunk) {
297
+ text += streamedChunk;
298
+ const decoded = decodeModelEvent({ type: "text-delta", delta: streamedChunk }, decodeOptions);
299
+ if (decoded)
300
+ yield decoded;
301
+ }
302
+ continue;
303
+ }
304
+ const type = typeof payload.type === "string" ? payload.type : "";
305
+ const proposalFrame = proposal(payload, type);
306
+ if (proposalFrame) {
307
+ emitProposal(ctx.events, wallet, requestId, proposalFrame);
308
+ const decoded = decodeActivityEvent(proposalFrame, decodeOptions);
309
+ if (decoded)
310
+ yield decoded;
311
+ continue;
312
+ }
313
+ const childFrame = child(payload, type);
314
+ if (childFrame) {
315
+ emitChild(ctx.events, wallet, requestId, childFrame);
316
+ const decoded = decodeActivityEvent(childFrame, decodeOptions);
317
+ if (decoded)
318
+ yield decoded;
319
+ continue;
320
+ }
321
+ const traceFrame = trace(payload, type);
322
+ if (traceFrame) {
323
+ const decoded = decodeActivityEvent(traceFrame, decodeOptions);
324
+ if (decoded)
325
+ yield decoded;
326
+ continue;
327
+ }
328
+ const conclaveFrame = conclave(payload, type);
329
+ if (conclaveFrame) {
330
+ const decoded = decodeActivityEvent(conclaveFrame, decodeOptions);
331
+ if (decoded)
332
+ yield decoded;
333
+ continue;
334
+ }
335
+ if (type === "thinking_start") {
336
+ const decoded = decodeActivityEvent(payload, decodeOptions);
337
+ if (decoded)
338
+ yield decoded;
339
+ continue;
340
+ }
341
+ if (type === "thinking_end") {
342
+ const decoded = decodeActivityEvent(payload, decodeOptions);
343
+ if (decoded)
344
+ yield decoded;
345
+ continue;
346
+ }
347
+ if (type === "reasoning_delta") {
348
+ const delta = typeof payload.delta === "string"
349
+ ? payload.delta
350
+ : typeof payload.content === "string"
351
+ ? payload.content
352
+ : "";
353
+ if (delta) {
354
+ const decoded = decodeModelEvent({ type: "reasoning-delta", delta }, decodeOptions);
355
+ if (decoded)
356
+ yield decoded;
357
+ }
358
+ continue;
359
+ }
360
+ if (type === "tool_args_delta") {
361
+ const argsDelta = typeof payload.argsDelta === "string"
362
+ ? payload.argsDelta
363
+ : typeof payload.delta === "string"
364
+ ? payload.delta
365
+ : "";
366
+ if (argsDelta) {
367
+ const id = typeof payload.id === "string" ? payload.id : undefined;
368
+ const toolName = typeof payload.toolName === "string" ? payload.toolName : undefined;
369
+ const decoded = decodeModelEvent({ type: "tool_args_delta", id, toolName, argsDelta }, decodeOptions);
370
+ if (decoded)
371
+ yield decoded;
372
+ }
373
+ continue;
374
+ }
375
+ if (type === "stopped") {
376
+ const reason = typeof payload.reason === "string" ? payload.reason : "user_stop";
377
+ const decoded = decodeActivityEvent({ type: "stopped", reason }, decodeOptions);
378
+ if (decoded)
379
+ yield decoded;
380
+ continue;
381
+ }
382
+ if (type === "tool_start") {
383
+ const toolName = typeof payload.toolName === "string" ? payload.toolName : "tool";
384
+ const summary = typeof payload.content === "string" ? payload.content : undefined;
385
+ const content = typeof payload.content === "string" ? payload.content : undefined;
386
+ const meta = view(payload.display);
387
+ const shown = {
388
+ ...(meta?.name ? { displayName: meta.name } : {}),
389
+ ...(meta ? { display: meta, targetKind: meta.kind } : {}),
390
+ ...(meta?.target ? { target: meta.target } : {}),
391
+ };
392
+ activeTools.set(toolName, { summary });
393
+ ctx.events.emit("toolCallStart", {
394
+ userAddress: wallet.address,
395
+ chainId: wallet.chainId,
396
+ requestId,
397
+ source: "agent",
398
+ toolCallId: toolName,
399
+ toolName,
400
+ ...shown,
401
+ summary,
402
+ });
403
+ const decoded = decodeActivityEvent({ type: "tool-start", toolName, display: meta, summary, content, input: payload.input }, decodeOptions);
404
+ if (decoded)
405
+ yield decoded;
406
+ continue;
407
+ }
408
+ if (type === "tool_end") {
409
+ const toolName = typeof payload.toolName === "string" ? payload.toolName : "tool";
410
+ const summary = typeof payload.message === "string" ? payload.message : undefined;
411
+ const failed = typeof payload.error === "string" && payload.error.length > 0;
412
+ const error = failed ? payload.error : undefined;
413
+ const meta = view(payload.display);
414
+ const displayName = meta?.name ?? display(toolName, payload);
415
+ const shown = {
416
+ ...(displayName ? { displayName } : {}),
417
+ ...(meta ? { display: meta, targetKind: meta.kind } : {}),
418
+ ...(meta?.target ? { target: meta.target } : {}),
419
+ };
420
+ toolCalls.push({ toolName, ...shown, summary, failed, error });
421
+ activeTools.delete(toolName);
422
+ ctx.events.emit("toolCallEnd", {
423
+ userAddress: wallet.address,
424
+ chainId: wallet.chainId,
425
+ requestId,
426
+ source: "agent",
427
+ toolCallId: toolName,
428
+ toolName,
429
+ ...shown,
430
+ summary,
431
+ failed,
432
+ error,
433
+ });
434
+ const decoded = decodeActivityEvent({
435
+ type: "tool-end",
436
+ toolName,
437
+ display: meta,
438
+ summary,
439
+ failed,
440
+ error,
441
+ output: payload.output ?? payload.message,
442
+ }, decodeOptions);
443
+ if (decoded)
444
+ yield decoded;
445
+ continue;
446
+ }
447
+ if (type === "error") {
448
+ const code = typeof payload.code === "string" ? payload.code : undefined;
449
+ const message = typeof payload.content === "string"
450
+ ? payload.content
451
+ : typeof payload.error === "string"
452
+ ? payload.error
453
+ : typeof payload.message === "string"
454
+ ? payload.message
455
+ : "Agent stream failed";
456
+ const decoded = decodeActivityEvent({ type: "error", code, message }, decodeOptions);
457
+ if (decoded)
458
+ yield decoded;
459
+ continue;
460
+ }
461
+ if (type === "done") {
462
+ if (!emittedDone) {
463
+ emittedDone = true;
464
+ const decoded = decodeActivityEvent(payload, decodeOptions);
465
+ if (decoded)
466
+ yield decoded;
467
+ }
468
+ continue;
469
+ }
470
+ if (typeof payload.content === "string") {
471
+ text += payload.content;
472
+ const decoded = decodeModelEvent({ type: "text-delta", delta: payload.content }, decodeOptions);
473
+ if (decoded)
474
+ yield decoded;
475
+ continue;
476
+ }
477
+ if (typeof payload.text === "string") {
478
+ text += payload.text;
479
+ const decoded = decodeModelEvent({ type: "text-delta", delta: payload.text }, decodeOptions);
480
+ if (decoded)
481
+ yield decoded;
482
+ continue;
483
+ }
484
+ }
485
+ }
486
+ finally {
487
+ try {
488
+ await response.body?.cancel();
489
+ }
490
+ catch { /* best-effort */ }
491
+ ctx.events.emit("agentStreamEnd", {
492
+ userAddress: wallet.address,
493
+ chainId: wallet.chainId,
494
+ requestId,
495
+ agentWallet: params.agentWallet,
496
+ threadId: params.threadId,
497
+ runId: params.runId,
498
+ });
499
+ }
500
+ const finalReceipt = streamReceipt ?? headerReceipt;
501
+ return {
502
+ text,
503
+ toolCalls,
504
+ requestId,
505
+ receipt: finalReceipt,
506
+ budget,
507
+ sessionInvalidReason,
508
+ };
509
+ }
510
+ function isReceiptEvent(event) {
511
+ return event === "receipt" || event === "compose.receipt";
512
+ }
513
+ function obj(value) {
514
+ return value && typeof value === "object" && !Array.isArray(value)
515
+ ? value
516
+ : null;
517
+ }
518
+ function str(value) {
519
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
520
+ }
521
+ function num(value) {
522
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
523
+ }
524
+ function strings(value) {
525
+ return Array.isArray(value) && value.every((item) => typeof item === "string")
526
+ ? value
527
+ : undefined;
528
+ }
529
+ function childKind(type) {
530
+ switch (type) {
531
+ case "swarm_child_start":
532
+ return "start";
533
+ case "swarm_child_delta":
534
+ return "delta";
535
+ case "swarm_child_tool_start":
536
+ return "tool-start";
537
+ case "swarm_child_tool_end":
538
+ return "tool-end";
539
+ case "swarm_child_done":
540
+ return "done";
541
+ case "swarm_child_error":
542
+ return "error";
543
+ default:
544
+ return null;
545
+ }
546
+ }
547
+ function view(value) {
548
+ const record = obj(value);
549
+ if (!record)
550
+ return undefined;
551
+ const kind = str(record.kind);
552
+ if (!kind || !["tool", "model", "connector", "agent", "search", "harness", "swarm", "conclave", "route"].includes(kind)) {
553
+ return undefined;
554
+ }
555
+ const details = obj(record.details);
556
+ return {
557
+ kind: kind,
558
+ ...(str(record.id) ? { id: str(record.id) } : {}),
559
+ ...(str(record.name) ? { name: str(record.name) } : {}),
560
+ ...(str(record.target) ? { target: str(record.target) } : {}),
561
+ ...(str(record.summary) ? { summary: str(record.summary) } : {}),
562
+ ...(details ? { details } : {}),
563
+ };
564
+ }
565
+ function decision(value) {
566
+ return value === "approved" || value === "rejected" || value === "changes_requested"
567
+ ? value
568
+ : undefined;
569
+ }
570
+ function proposal(payload, type) {
571
+ if (type !== "plan.proposed" && type !== "approval.requested" && type !== "approval.decided" && type !== "plan.feedback_requested")
572
+ return null;
573
+ const proposalId = str(payload.proposalId);
574
+ const version = num(payload.version);
575
+ const state = str(payload.state);
576
+ if (!proposalId || version === undefined || !state)
577
+ return null;
578
+ const details = obj(payload.details);
579
+ return {
580
+ type,
581
+ proposalId,
582
+ version,
583
+ state,
584
+ ...(decision(payload.decision) ? { decision: decision(payload.decision) } : {}),
585
+ ...(str(payload.rootRunId) ? { rootRunId: str(payload.rootRunId) } : {}),
586
+ ...(str(payload.runId) ? { runId: str(payload.runId) } : {}),
587
+ ...(str(payload.requestedBy) ? { requestedBy: str(payload.requestedBy) } : {}),
588
+ ...("proposal" in payload ? { proposal: payload.proposal } : {}),
589
+ ...(str(payload.markdown) ? { markdown: str(payload.markdown) } : {}),
590
+ ...(num(payload.ts) !== undefined ? { ts: num(payload.ts) } : {}),
591
+ ...(num(payload.updatedAt) !== undefined ? { updatedAt: num(payload.updatedAt) } : {}),
592
+ ...(str(payload.approver) ? { approver: str(payload.approver) } : {}),
593
+ ...(str(payload.reason) ? { reason: str(payload.reason) } : {}),
594
+ ...(str(payload.feedback) ? { feedback: str(payload.feedback) } : {}),
595
+ ...(view(payload.display) ? { display: view(payload.display) } : {}),
596
+ ...(details ? { details } : {}),
597
+ };
598
+ }
599
+ function child(payload, type) {
600
+ const event = childKind(type);
601
+ if (!event)
602
+ return null;
603
+ const display = view(payload.display);
604
+ return {
605
+ type: "child",
606
+ event,
607
+ ...(str(payload.rootRunId) ? { rootRunId: str(payload.rootRunId) } : {}),
608
+ ...(str(payload.parentRunId) ? { parentRunId: str(payload.parentRunId) } : {}),
609
+ ...(str(payload.subId) ? { subId: str(payload.subId) } : {}),
610
+ ...(num(payload.depth) !== undefined ? { depth: num(payload.depth) } : {}),
611
+ ...(str(payload.agentWallet) ? { agentWallet: str(payload.agentWallet) } : {}),
612
+ ...(str(payload.userAddress) ? { userAddress: str(payload.userAddress) } : {}),
613
+ ...(str(payload.runKey) ? { runKey: str(payload.runKey) } : {}),
614
+ ...(strings(payload.runKeyChain) ? { runKeyChain: strings(payload.runKeyChain) } : {}),
615
+ ...(typeof payload.delta === "string" ? { delta: payload.delta } : {}),
616
+ ...(str(payload.toolName) ? { toolName: str(payload.toolName) } : {}),
617
+ ...("input" in payload ? { input: payload.input } : {}),
618
+ ...("output" in payload ? { output: payload.output } : {}),
619
+ ...(typeof payload.failed === "boolean" ? { failed: payload.failed } : {}),
620
+ ...(str(payload.error) ? { error: str(payload.error) } : {}),
621
+ ...(obj(payload.usage) ? { usage: obj(payload.usage) } : {}),
622
+ ...(num(payload.toolBatches) !== undefined ? { toolBatches: num(payload.toolBatches) } : {}),
623
+ ...(str(payload.stopReason) ? { stopReason: str(payload.stopReason) } : {}),
624
+ ...(num(payload.wallMs) !== undefined ? { wallMs: num(payload.wallMs) } : {}),
625
+ ...(display ? { display } : {}),
626
+ ...(num(payload.ts) !== undefined ? { ts: num(payload.ts) } : {}),
627
+ };
628
+ }
629
+ function trace(payload, type) {
630
+ if (type !== "trace")
631
+ return null;
632
+ const source = str(payload.source);
633
+ if (!source || !["capability", "model", "tool", "agent", "harness", "swarm", "route"].includes(source))
634
+ return null;
635
+ const details = obj(payload.details);
636
+ return {
637
+ type: "trace",
638
+ source: source,
639
+ ...(str(payload.stage) ? { stage: str(payload.stage) } : {}),
640
+ ...(str(payload.action) ? { action: str(payload.action) } : {}),
641
+ ...(str(payload.message) ? { message: str(payload.message) } : {}),
642
+ ...(view(payload.display) ? { display: view(payload.display) } : {}),
643
+ ...(num(payload.ts) !== undefined ? { ts: num(payload.ts) } : {}),
644
+ ...(details ? { details } : {}),
645
+ };
646
+ }
647
+ function conclave(payload, type) {
648
+ if (type !== "conclave")
649
+ return null;
650
+ const action = str(payload.action);
651
+ if (!action || !["write", "read", "list", "delete"].includes(action))
652
+ return null;
653
+ return {
654
+ type: "conclave",
655
+ action: action,
656
+ success: payload.success === true,
657
+ ...(str(payload.key) ? { key: str(payload.key) } : {}),
658
+ ...(view(payload.display) ? { display: view(payload.display) } : {}),
659
+ ...(obj(payload.details) ? { details: obj(payload.details) } : {}),
660
+ };
661
+ }
662
+ function emitChild(events, wallet, requestId, event) {
663
+ if (event.event === "delta")
664
+ return;
665
+ const payload = {
666
+ userAddress: wallet.address,
667
+ chainId: wallet.chainId,
668
+ requestId,
669
+ source: "agent",
670
+ event: event.event,
671
+ ...(event.rootRunId ? { rootRunId: event.rootRunId } : {}),
672
+ ...(event.parentRunId ? { parentRunId: event.parentRunId } : {}),
673
+ ...(event.subId ? { subId: event.subId } : {}),
674
+ ...(event.depth !== undefined ? { depth: event.depth } : {}),
675
+ ...(event.agentWallet ? { agentWallet: event.agentWallet } : {}),
676
+ ...(event.runKey ? { runKey: event.runKey } : {}),
677
+ ...(event.runKeyChain ? { runKeyChain: event.runKeyChain } : {}),
678
+ ...(event.toolName ? { toolName: event.toolName } : {}),
679
+ ...("input" in event ? { input: event.input } : {}),
680
+ ...("output" in event ? { output: event.output } : {}),
681
+ ...(event.failed !== undefined ? { failed: event.failed } : {}),
682
+ ...(event.error ? { error: event.error } : {}),
683
+ ...(event.usage ? { usage: event.usage } : {}),
684
+ ...(event.toolBatches !== undefined ? { toolBatches: event.toolBatches } : {}),
685
+ ...(event.stopReason ? { stopReason: event.stopReason } : {}),
686
+ ...(event.wallMs !== undefined ? { wallMs: event.wallMs } : {}),
687
+ ...(event.display ? { display: event.display } : {}),
688
+ ...(event.ts !== undefined ? { ts: event.ts } : {}),
689
+ };
690
+ if (event.event === "start") {
691
+ events.emit("childAgentStart", payload);
692
+ }
693
+ else if (event.event === "tool-start") {
694
+ events.emit("childAgentToolStart", payload);
695
+ }
696
+ else if (event.event === "tool-end") {
697
+ events.emit("childAgentToolEnd", payload);
698
+ }
699
+ else if (event.event === "done") {
700
+ events.emit("childAgentDone", payload);
701
+ }
702
+ else if (event.event === "error") {
703
+ events.emit("childAgentError", payload);
704
+ }
705
+ }
706
+ function emitProposal(events, wallet, requestId, event) {
707
+ const payload = {
708
+ ...event,
709
+ userAddress: wallet.address,
710
+ chainId: wallet.chainId,
711
+ requestId,
712
+ source: "agent",
713
+ };
714
+ switch (event.type) {
715
+ case "plan.proposed":
716
+ events.emit("planProposed", payload);
717
+ break;
718
+ case "approval.requested":
719
+ events.emit("approvalRequested", payload);
720
+ break;
721
+ case "approval.decided":
722
+ events.emit("approvalDecided", payload);
723
+ break;
724
+ case "plan.feedback_requested":
725
+ events.emit("planFeedbackRequested", payload);
726
+ break;
727
+ }
728
+ }
729
+ function body(value) {
730
+ const record = obj(value);
731
+ if (!record)
732
+ return str(value);
733
+ return str(record.content)
734
+ ?? str(obj(record.kwargs)?.content)
735
+ ?? str(obj(record.lc_kwargs)?.content);
736
+ }
737
+ function json(value) {
738
+ const text = body(value);
739
+ if (!text)
740
+ return null;
741
+ try {
742
+ return obj(JSON.parse(text));
743
+ }
744
+ catch {
745
+ return null;
746
+ }
747
+ }
748
+ function display(toolName, payload) {
749
+ if (toolName !== "models_call")
750
+ return undefined;
751
+ const parsed = json(payload.output) ?? json(payload.message);
752
+ const model = obj(parsed?.model);
753
+ return str(model?.name) ?? str(model?.id) ?? str(model?.modelId);
754
+ }
755
+ function mergeSignals(a, b) {
756
+ if (!a)
757
+ return { signal: b, cleanup: () => { } };
758
+ const c = new AbortController();
759
+ const forward = () => c.abort();
760
+ if (a.aborted || b.aborted)
761
+ c.abort();
762
+ a.addEventListener("abort", forward, { once: true });
763
+ b.addEventListener("abort", forward, { once: true });
764
+ return {
765
+ signal: c.signal,
766
+ cleanup: () => {
767
+ a.removeEventListener("abort", forward);
768
+ b.removeEventListener("abort", forward);
769
+ },
770
+ };
771
+ }
772
+ async function readAgentStreamFrame(iterator, timeoutMs) {
773
+ const pending = iterator.next();
774
+ if (!timeoutMs) {
775
+ return pending;
776
+ }
777
+ let timer;
778
+ const timeout = new Promise((resolve) => {
779
+ timer = setTimeout(() => resolve({ done: true, value: undefined }), timeoutMs);
780
+ });
781
+ pending.catch(() => undefined);
782
+ const result = await Promise.race([pending, timeout]);
783
+ if (timer)
784
+ clearTimeout(timer);
785
+ return result;
786
+ }
787
+ //# sourceMappingURL=agent.js.map