@compose-market/sdk 0.8.0 → 0.8.2

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