@compose-market/sdk 0.8.13 → 0.8.15

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