fascicle 0.18.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +27 -1
  3. package/dist/AGENTS.md +11 -10
  4. package/dist/a2a.d.ts +358 -0
  5. package/dist/a2a.js +2234 -0
  6. package/dist/a2a.js.map +1 -0
  7. package/dist/acp.d.ts +120 -9
  8. package/dist/acp.js +927 -154
  9. package/dist/acp.js.map +1 -1
  10. package/dist/adapters-DYFauXE1.js +1147 -0
  11. package/dist/adapters-DYFauXE1.js.map +1 -0
  12. package/dist/adapters.d.ts +124 -36
  13. package/dist/adapters.js +1 -1
  14. package/dist/agents.d.ts +2 -2
  15. package/dist/agents.js +1 -1
  16. package/dist/{core-BH7sWpEG.js → core-xTtRZqdb.js} +217 -99
  17. package/dist/core-xTtRZqdb.js.map +1 -0
  18. package/dist/diagram_bin.js +1 -1
  19. package/dist/durable-CgU0kO2H.d.ts +144 -0
  20. package/dist/{engine-fOjYHcv6.js → engine-B_Yl7acj.js} +128 -42
  21. package/dist/engine-B_Yl7acj.js.map +1 -0
  22. package/dist/index.d.ts +9 -136
  23. package/dist/index.js +6 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-7iu8db6V.js → invoke-Bbk0RuVL.js} +3 -3
  26. package/dist/{invoke-7iu8db6V.js.map → invoke-Bbk0RuVL.js.map} +1 -1
  27. package/dist/{leading_system-BeQUSAim.js → leading_system-m-x7HzbQ.js} +16 -4
  28. package/dist/leading_system-m-x7HzbQ.js.map +1 -0
  29. package/dist/mcp-D1hN5ywq.js +662 -0
  30. package/dist/mcp-D1hN5ywq.js.map +1 -0
  31. package/dist/mcp.d.ts +115 -5
  32. package/dist/mcp.js +2 -2
  33. package/dist/otel.d.ts +1 -1
  34. package/dist/stdio.d.ts +1 -1
  35. package/dist/stdio.js +2 -2
  36. package/dist/testing.d.ts +7 -5
  37. package/dist/testing.js +618 -318
  38. package/dist/testing.js.map +1 -1
  39. package/dist/{types-BUXt_zgJ.d.ts → types-BtRpSctv.d.ts} +38 -5
  40. package/dist/{types-Dk9tLpUq.d.ts → types-CDTW7XWB.d.ts} +2 -2
  41. package/dist/ui.d.ts +2 -2
  42. package/dist/viewer.js +2 -2
  43. package/dist/web.d.ts +1 -1
  44. package/package.json +17 -5
  45. package/dist/adapters-CpKpDk7r.js +0 -461
  46. package/dist/adapters-CpKpDk7r.js.map +0 -1
  47. package/dist/core-BH7sWpEG.js.map +0 -1
  48. package/dist/engine-fOjYHcv6.js.map +0 -1
  49. package/dist/leading_system-BeQUSAim.js.map +0 -1
  50. package/dist/mcp-CHJ88HiG.js +0 -262
  51. package/dist/mcp-CHJ88HiG.js.map +0 -1
package/dist/a2a.js ADDED
@@ -0,0 +1,2234 @@
1
+ import { r as memory_store } from "./adapters-DYFauXE1.js";
2
+ import { L as resume_validation_error, _ as step, a as suspend, j as aborted_error, k as describe, o as checkpoint, v as assert_valid_step_id, x as durable } from "./core-xTtRZqdb.js";
3
+ import { n as is_record } from "./records-Btlmvunj.js";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { constants } from "node:os";
6
+ import { createServer } from "node:http";
7
+ import { Readable } from "node:stream";
8
+ // src/a2a/parts.ts
9
+ const BYTES = "$bytes";
10
+ /**
11
+ * A text part.
12
+ */
13
+ function text_part(text) {
14
+ return {
15
+ content: {
16
+ $case: "text",
17
+ value: text
18
+ },
19
+ metadata: void 0,
20
+ filename: "",
21
+ mediaType: "text/plain"
22
+ };
23
+ }
24
+ /**
25
+ * A data part holding any JSON value.
26
+ */
27
+ function data_part(value) {
28
+ return {
29
+ content: {
30
+ $case: "data",
31
+ value
32
+ },
33
+ metadata: void 0,
34
+ filename: "",
35
+ mediaType: "application/json"
36
+ };
37
+ }
38
+ /**
39
+ * The default `to_parts`: a string as a text part, nothing for a flow that
40
+ * returns nothing, and anything else as a data part.
41
+ */
42
+ function output_parts(output) {
43
+ if (typeof output === "string") return [text_part(output)];
44
+ if (output === void 0 || output === null) return [];
45
+ return [data_part(output)];
46
+ }
47
+ /**
48
+ * The text parts among `parts`, joined with `separator`.
49
+ */
50
+ function text_of(parts, separator = "") {
51
+ const texts = [];
52
+ for (const part of parts) if (part.content?.$case === "text") texts.push(part.content.value);
53
+ return texts.join(separator);
54
+ }
55
+ /**
56
+ * The values of the data parts among `parts`, in order.
57
+ */
58
+ function data_of(parts) {
59
+ const values = [];
60
+ for (const part of parts) if (part.content?.$case === "data") values.push(part.content.value);
61
+ return values;
62
+ }
63
+ /**
64
+ * The file parts among `parts` (the ones that carry bytes or a URL), with
65
+ * bytes as base64 so that they survive a trip through a store.
66
+ */
67
+ function files_of(parts) {
68
+ const files = [];
69
+ for (const part of parts) {
70
+ const base = {
71
+ filename: part.filename,
72
+ media_type: part.mediaType
73
+ };
74
+ if (part.content?.$case === "url") files.push({
75
+ ...base,
76
+ url: part.content.value
77
+ });
78
+ if (part.content?.$case === "raw") files.push({
79
+ ...base,
80
+ base64: Buffer.from(part.content.value).toString("base64")
81
+ });
82
+ }
83
+ return files;
84
+ }
85
+ /**
86
+ * A copy of `value` that JSON can hold, with every run of raw bytes written
87
+ * as `{ $bytes: <base64> }`.
88
+ */
89
+ function to_plain(value) {
90
+ if (value instanceof Uint8Array) return { [BYTES]: Buffer.from(value).toString("base64") };
91
+ if (Array.isArray(value)) return value.map(to_plain);
92
+ if (!is_record(value)) return value;
93
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, to_plain(inner)]));
94
+ }
95
+ /**
96
+ * The inverse of `to_plain`: every `{ $bytes }` it wrote becomes a `Buffer`
97
+ * again.
98
+ */
99
+ function from_plain(value) {
100
+ if (Array.isArray(value)) return value.map(from_plain);
101
+ if (!is_record(value)) return value;
102
+ const bytes = value[BYTES];
103
+ if (typeof bytes === "string" && Object.keys(value).length === 1) return Buffer.from(bytes, "base64");
104
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, from_plain(inner)]));
105
+ }
106
+ // src/a2a/task_status.ts
107
+ /**
108
+ * How a run's resting place reads as an A2A task status.
109
+ *
110
+ * A drive that rests, and a task record that has fallen behind its run, both
111
+ * need the same translation: done is `COMPLETED`, a client gate is
112
+ * `INPUT_REQUIRED` with the gate's question, an external gate is `WORKING`
113
+ * with a note that names the gate, and a failure is `FAILED`. Keeping it in
114
+ * one place is what keeps `GetTask` and a live stream telling the same story.
115
+ *
116
+ * The gate a status belongs to rides in its message's metadata, as
117
+ * `metadata.fascicle.gate`, beside the gate's `deadline_at` when it set one.
118
+ */
119
+ /**
120
+ * The default `to_question`: a line that names the gate, then the gate's
121
+ * payload as a data part, so the client sees what the run is asking about.
122
+ */
123
+ function default_question(gate, payload) {
124
+ const line = text_part(`Waiting for input at "${gate}".`);
125
+ return payload === void 0 ? [line] : [line, data_part(payload)];
126
+ }
127
+ /**
128
+ * The default `to_failure`: one line that says the task failed and nothing
129
+ * about why.
130
+ *
131
+ * A failed task's status goes to whoever sent the message, and an error's
132
+ * text can hold a connection string or a path that shouldn't leave the
133
+ * server. The error itself goes to the agent's own trajectory or stderr.
134
+ */
135
+ function default_failure() {
136
+ return "The agent could not finish the task.";
137
+ }
138
+ /**
139
+ * A `to_failure` that sends the error's own message, for an agent whose
140
+ * callers are trusted with it.
141
+ */
142
+ function failure_message(err) {
143
+ return err instanceof Error ? err.message : String(err);
144
+ }
145
+ /**
146
+ * Whether a task has ended, in a state no message or event can move it from.
147
+ */
148
+ function is_terminal(wire, task) {
149
+ const state = task.status?.state;
150
+ return state === wire.TaskState.TASK_STATE_COMPLETED || state === wire.TaskState.TASK_STATE_FAILED || state === wire.TaskState.TASK_STATE_CANCELED || state === wire.TaskState.TASK_STATE_REJECTED;
151
+ }
152
+ /**
153
+ * The gate a task's status belongs to, read from its message's metadata.
154
+ */
155
+ function gate_of(task) {
156
+ const fascicle = task.status?.message?.metadata?.["fascicle"];
157
+ const gate = is_record(fascicle) ? fascicle["gate"] : void 0;
158
+ return typeof gate === "string" ? gate : void 0;
159
+ }
160
+ /**
161
+ * A message from the agent on a task.
162
+ */
163
+ function agent_message(wire, ids, parts, metadata) {
164
+ return {
165
+ messageId: randomUUID(),
166
+ contextId: ids.context_id,
167
+ taskId: ids.task_id,
168
+ role: wire.Role.ROLE_AGENT,
169
+ parts: [...parts],
170
+ metadata,
171
+ extensions: [],
172
+ referenceTaskIds: []
173
+ };
174
+ }
175
+ /**
176
+ * A status stamped now, which is what `ListTasks` orders tasks by.
177
+ */
178
+ function status_of(state, message) {
179
+ return {
180
+ state,
181
+ message,
182
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
183
+ };
184
+ }
185
+ /**
186
+ * Wrap a status as the bus event that carries it.
187
+ */
188
+ function status_event(ids, status) {
189
+ return {
190
+ kind: "statusUpdate",
191
+ data: {
192
+ taskId: ids.task_id,
193
+ contextId: ids.context_id,
194
+ status,
195
+ metadata: void 0
196
+ }
197
+ };
198
+ }
199
+ /**
200
+ * The metadata that ties a status to its gate.
201
+ */
202
+ function gate_metadata(gate, deadline_at) {
203
+ return { fascicle: deadline_at === void 0 ? { gate } : {
204
+ gate,
205
+ deadline_at
206
+ } };
207
+ }
208
+ /**
209
+ * The status of a run that waits at a gate: the client's question, or a note
210
+ * that the run waits on something A2A doesn't carry.
211
+ */
212
+ function gate_status(wire, hooks, ids, rest) {
213
+ const metadata = gate_metadata(rest.id, rest.deadline_at);
214
+ if (hooks.gates(rest.id) === "external") {
215
+ const note = [text_part(`Waiting on "${rest.id}", which this agent's clients don't answer.`)];
216
+ return status_of(wire.TaskState.TASK_STATE_WORKING, agent_message(wire, ids, note, metadata));
217
+ }
218
+ const question = hooks.to_question(rest.id, rest.payload);
219
+ const parts = typeof question === "string" ? [text_part(question)] : question;
220
+ return status_of(wire.TaskState.TASK_STATE_INPUT_REQUIRED, agent_message(wire, ids, parts, metadata));
221
+ }
222
+ /**
223
+ * One line for each issue a gate's schema raised, with the path it sits at.
224
+ */
225
+ function issue_lines(issues) {
226
+ return issues.map((issue) => {
227
+ const path = (issue.path ?? []).map(String).join(".");
228
+ return path === "" ? issue.message : `${path}: ${issue.message}`;
229
+ }).join("; ");
230
+ }
231
+ /**
232
+ * The task status for where a run rests, or `undefined` for a run that's
233
+ * still being driven, which changes nothing by itself.
234
+ */
235
+ function status_for(wire, hooks, ids, rest) {
236
+ const state = wire.TaskState;
237
+ switch (rest.kind) {
238
+ case "done": return status_of(state.TASK_STATE_COMPLETED);
239
+ case "suspended": return gate_status(wire, hooks, ids, rest);
240
+ case "refused": {
241
+ const message = agent_message(wire, ids, [text_part(`The answer to "${rest.gate}" was refused: ${issue_lines(rest.issues)}`)], gate_metadata(rest.gate));
242
+ return status_of(state.TASK_STATE_INPUT_REQUIRED, message);
243
+ }
244
+ case "failed": return status_of(state.TASK_STATE_FAILED, agent_message(wire, ids, [text_part(hooks.to_failure(rest.error))]));
245
+ case "canceled": return status_of(state.TASK_STATE_CANCELED, agent_message(wire, ids, [text_part("The task was canceled.")]));
246
+ default: return;
247
+ }
248
+ }
249
+ // src/a2a/errors.ts
250
+ /**
251
+ * Typed errors for the A2A adapter.
252
+ *
253
+ * Listed alongside src/acp/errors.ts in the `no-class` rule ignores:
254
+ * `instanceof` branching is how callers tell a missing optional peer apart
255
+ * from a remote task that didn't complete.
256
+ */
257
+ var a2a_sdk_missing_error = class extends Error {
258
+ kind = "a2a_sdk_missing_error";
259
+ constructor(message = "@a2a-js/sdk is required for fascicle/a2a; install it: pnpm add @a2a-js/sdk") {
260
+ super(message);
261
+ this.name = "a2a_sdk_missing_error";
262
+ }
263
+ };
264
+ /**
265
+ * A task that came to rest somewhere other than `COMPLETED`, or a call the
266
+ * adapter can't carry out. `state` and `status_text` are set when a remote
267
+ * task ended failed, rejected, canceled, or waiting for credentials.
268
+ */
269
+ var a2a_error = class extends Error {
270
+ kind = "a2a_error";
271
+ state;
272
+ status_text;
273
+ task_id;
274
+ constructor(message, detail = {}) {
275
+ super(message);
276
+ this.name = "a2a_error";
277
+ this.state = detail.state;
278
+ this.status_text = detail.status_text;
279
+ this.task_id = detail.task_id;
280
+ }
281
+ };
282
+ // src/a2a/to_task_events.ts
283
+ /**
284
+ * Maps a drive's events onto A2A task events.
285
+ *
286
+ * A drive runs with `record_chunks`, so each `model_call` records
287
+ * `model_chunk` events carrying the engine's `StreamChunk`, the same source
288
+ * fascicle/ui and the ACP mapper read. This half of a task does no I/O and
289
+ * holds no SDK value, so a flow author can wrap `to_task_events` in their
290
+ * own `to_events` and add to what it returns, as long as every event still
291
+ * reaches it: a `step_replayed` mutes the step it names, and the step speaks
292
+ * again once its span ends, or sooner, once the drive has passed every gate
293
+ * the event names. From there on the step is doing new work. An `a2a_step`
294
+ * is the case that needs it: its span stays open across the remote
295
+ * question, and the text that follows the answer is the remote agent's
296
+ * next round, which no client has read.
297
+ *
298
+ * Text goes into one artifact for each drive, in chunks. A2A marks the last
299
+ * chunk of an artifact, and no chunk knows it's the last, so the mapper
300
+ * holds the newest one back until the next arrives. `end_task_events` sends
301
+ * the one it still holds once the drive has come to rest, with the output's
302
+ * parts behind it when the drive has some.
303
+ *
304
+ * Reasoning and tool calls map to nothing, because A2A has no thought
305
+ * channel and no tool card, and neither do spans, `cost`, or `emit` events.
306
+ */
307
+ /**
308
+ * Create the state for one drive's events, routing every model call's text
309
+ * to the drive's artifact unless `stream` says otherwise.
310
+ */
311
+ function create_a2a_mapper_state(options) {
312
+ return {
313
+ task_id: options.task_id,
314
+ context_id: options.context_id,
315
+ artifact_id: options.artifact_id ?? randomUUID(),
316
+ stream: options.stream ?? (() => "artifact"),
317
+ replaying: /* @__PURE__ */ new Map(),
318
+ pending: void 0,
319
+ sent: 0
320
+ };
321
+ }
322
+ /**
323
+ * One chunk of the drive's artifact. Every chunk after the first appends.
324
+ */
325
+ function artifact_update(state, parts, last) {
326
+ const append = state.sent > 0;
327
+ state.sent += 1;
328
+ return {
329
+ kind: "artifactUpdate",
330
+ data: {
331
+ taskId: state.task_id,
332
+ contextId: state.context_id,
333
+ artifact: {
334
+ artifactId: state.artifact_id,
335
+ name: "",
336
+ description: "",
337
+ parts,
338
+ metadata: void 0,
339
+ extensions: []
340
+ },
341
+ append,
342
+ lastChunk: last,
343
+ metadata: void 0
344
+ }
345
+ };
346
+ }
347
+ /**
348
+ * The text of a `model_chunk` event's text chunk, or `undefined` for a chunk
349
+ * of any other kind.
350
+ */
351
+ function chunk_text(chunk) {
352
+ if (!is_record(chunk) || chunk["kind"] !== "text") return void 0;
353
+ const text = chunk["text"];
354
+ return typeof text === "string" ? text : void 0;
355
+ }
356
+ /**
357
+ * Hold `text` back as the newest chunk, and send the one held before it.
358
+ */
359
+ function hold(state, text) {
360
+ const before = state.pending;
361
+ state.pending = text;
362
+ return before === void 0 ? [] : [artifact_update(state, [text_part(before)], false)];
363
+ }
364
+ /**
365
+ * Whether a step is running again in a span that hasn't ended.
366
+ */
367
+ function is_replaying(state, step_id) {
368
+ for (const replayed of state.replaying.values()) if (replayed.step_id === step_id) return true;
369
+ return false;
370
+ }
371
+ /**
372
+ * The gates a `step_replayed` event says are still ahead of the drive.
373
+ */
374
+ function gates_of(event) {
375
+ const ids = event["suspend_ids"];
376
+ return new Set(Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : []);
377
+ }
378
+ /**
379
+ * Note that the drive has passed `gate`, and let every step speak that was
380
+ * waiting on no other. A replay that named no gate waits for its span.
381
+ */
382
+ function pass_gate(state, gate) {
383
+ for (const [span_id, replayed] of state.replaying) if (replayed.gates.delete(gate) && replayed.gates.size === 0) state.replaying.delete(span_id);
384
+ }
385
+ /**
386
+ * Mute the step a `step_replayed` event names, for as long as its span runs
387
+ * or until the drive has passed the gates the event names.
388
+ */
389
+ function start_replay(event, state) {
390
+ const span_id = event.span_id;
391
+ const step_id = event["step_id"];
392
+ if (typeof span_id !== "string" || typeof step_id !== "string") return;
393
+ state.replaying.set(span_id, {
394
+ step_id,
395
+ gates: gates_of(event)
396
+ });
397
+ }
398
+ /**
399
+ * Take in the end of a span: a replay that ran in it is over, and a gate
400
+ * that it was has been passed. A gate's span ends without an error only
401
+ * when the gate took its answer.
402
+ */
403
+ function end_span(event, state) {
404
+ if (typeof event.span_id === "string") state.replaying.delete(event.span_id);
405
+ const ended = event["id"];
406
+ if (typeof ended === "string" && event["error"] === void 0) pass_gate(state, ended);
407
+ }
408
+ /**
409
+ * Map one run event to zero or more task events. Only a `model_chunk` that
410
+ * carries text produces any, and it produces the chunk before it. The
411
+ * function does no I/O.
412
+ */
413
+ function to_task_events(event, state) {
414
+ if (event.kind === "step_replayed") start_replay(event, state);
415
+ if (event.kind === "span_end") end_span(event, state);
416
+ const step_id = event["step_id"];
417
+ if (event.kind !== "model_chunk" || typeof step_id !== "string") return [];
418
+ const text = chunk_text(event["chunk"]);
419
+ if (text === void 0 || text === "") return [];
420
+ if (is_replaying(state, step_id) || state.stream(step_id) !== "artifact") return [];
421
+ return hold(state, text);
422
+ }
423
+ /**
424
+ * Close the drive's artifact once the drive has come to rest: the chunk the
425
+ * mapper still holds goes out as the last one, with `parts` behind it. A
426
+ * drive that streamed no text sends `parts` as its whole artifact, and one
427
+ * with neither sends nothing.
428
+ */
429
+ function end_task_events(state, parts = []) {
430
+ const held = state.pending === void 0 ? [] : [text_part(state.pending)];
431
+ state.pending = void 0;
432
+ const closing = [...held, ...parts];
433
+ return closing.length === 0 ? [] : [artifact_update(state, closing, true)];
434
+ }
435
+ /**
436
+ * Whether the drive has streamed any text into its artifact.
437
+ */
438
+ function has_streamed(state) {
439
+ return state.pending !== void 0 || state.sent > 0;
440
+ }
441
+ // src/a2a/task_runner.ts
442
+ /**
443
+ * Drives the durable run behind each A2A task.
444
+ *
445
+ * A task is a durable run, and the task id is the run id. A message with no
446
+ * task starts a run, a message for a task that waits at a client gate
447
+ * resumes it with the client's answer, and an outside event resumes it
448
+ * through `resume`. Every drive records model chunks, maps the run's events
449
+ * onto the task's event bus, and can be aborted by a cancel. Where the drive
450
+ * comes to rest decides the task's state (see task_status.ts).
451
+ *
452
+ * The SDK's request handler owns the bus and writes each event to the task
453
+ * store as the request reads it. A drive that the SDK didn't start (an
454
+ * outside event) writes its events through the SDK's `ResultManager`
455
+ * instead, and publishes them on a bus of its own as well, for a client
456
+ * that subscribes while it runs.
457
+ *
458
+ * One drive at a time holds a task in this process. The handle it holds is
459
+ * what a cancel aborts, what `close` waits for, and what makes a second
460
+ * message find the task working. A drive lets go only once its resting
461
+ * status has reached the task store, so a `GetTask` that lands in between
462
+ * reads the record as the drive left it and not as its run alone suggests.
463
+ *
464
+ * A cancel can land in a process that doesn't hold the drive. That process
465
+ * can only mark the record `CANCELED`, so every drive reads its own task's
466
+ * record on an interval and aborts itself once the record says so.
467
+ *
468
+ * A failed task tells its caller only what `to_failure` makes of the error.
469
+ * The error itself goes to the config's `trajectory` as an
470
+ * `a2a_task_failed` event, or to stderr when the config has none, so the
471
+ * people who run the agent can always read why a task failed.
472
+ */
473
+ const DEFAULT_HISTORY_LIMIT = 20;
474
+ const MAX_HISTORY_LIMIT = 100;
475
+ const SAVE_WAIT_MS = 2e3;
476
+ const DEFAULT_CANCEL_POLL_MS = 2e3;
477
+ /**
478
+ * Take a hold on `task_id` for a drive, or for a message on its way to one.
479
+ */
480
+ function take_hold(holds, task_id) {
481
+ const { promise, resolve } = Promise.withResolvers();
482
+ const hold = {
483
+ abort: new AbortController(),
484
+ canceled: false,
485
+ taken: false,
486
+ settled: promise,
487
+ release: () => {
488
+ if (holds.get(task_id) === hold) holds.delete(task_id);
489
+ resolve();
490
+ }
491
+ };
492
+ holds.set(task_id, hold);
493
+ return hold;
494
+ }
495
+ /**
496
+ * A logger that hands every event of a drive to `on_event`, spans included,
497
+ * and passes each call on to the config's own logger when it has one.
498
+ */
499
+ function drive_logger(on_event, sink) {
500
+ return {
501
+ record: (event) => {
502
+ sink?.record(event);
503
+ on_event(event);
504
+ },
505
+ start_span: (name, meta) => {
506
+ const span_id = sink?.start_span(name, meta) ?? `${name}:${randomUUID().slice(0, 8)}`;
507
+ on_event({
508
+ kind: "span_start",
509
+ span_id,
510
+ name,
511
+ ...meta
512
+ });
513
+ return span_id;
514
+ },
515
+ end_span: (span_id, meta) => {
516
+ sink?.end_span(span_id, meta);
517
+ on_event({
518
+ kind: "span_end",
519
+ span_id,
520
+ ...meta
521
+ });
522
+ }
523
+ };
524
+ }
525
+ /**
526
+ * A gate's refusal of its answer, read from the error a drive threw, or
527
+ * `undefined` for any other error. `durable` has already put the run back at
528
+ * the gate by the time the error surfaces.
529
+ */
530
+ function refusal_of(err) {
531
+ if (!(err instanceof resume_validation_error) || err.suspend_id === void 0) return void 0;
532
+ return {
533
+ kind: "refused",
534
+ gate: err.suspend_id,
535
+ issues: err.issues
536
+ };
537
+ }
538
+ /**
539
+ * The trajectory event for a drive that failed: the task it belongs to, and
540
+ * the error's message, name, and stack, none of which the caller is sent.
541
+ */
542
+ function failure_event(ids, err) {
543
+ const known = err instanceof Error;
544
+ return {
545
+ kind: "a2a_task_failed",
546
+ task_id: ids.task_id,
547
+ context_id: ids.context_id,
548
+ error: known ? err.message : String(err),
549
+ ...known ? { error_name: err.name } : {},
550
+ ...known && err.stack !== void 0 ? { error_stack: err.stack } : {}
551
+ };
552
+ }
553
+ /**
554
+ * The caller behind a request, as a flow sees them.
555
+ */
556
+ function user_of(context) {
557
+ return {
558
+ name: context.user?.userName ?? "",
559
+ authenticated: context.user?.isAuthenticated ?? false
560
+ };
561
+ }
562
+ /**
563
+ * The two sides of one earlier task: what the user opened it with, and the
564
+ * text it ended with (its artifacts' text, or else its status message).
565
+ */
566
+ function exchange_of(sdk, task) {
567
+ const opened = task.history.find((message) => message.role === sdk.wire.Role.ROLE_USER);
568
+ const reply = task.artifacts.map((artifact) => text_of(artifact.parts)).filter((text) => text !== "").join("\n") || text_of(task.status?.message?.parts ?? [], "\n");
569
+ const entries = [];
570
+ if (opened !== void 0) entries.push({
571
+ task_id: task.id,
572
+ role: "user",
573
+ text: text_of(opened.parts, "\n")
574
+ });
575
+ if (reply !== "") entries.push({
576
+ task_id: task.id,
577
+ role: "agent",
578
+ text: reply
579
+ });
580
+ return entries;
581
+ }
582
+ /**
583
+ * Build the runner that drives tasks for one agent.
584
+ */
585
+ function task_runner(deps) {
586
+ const { sdk, config, runs, records, holds, slots, hooks, buses } = deps;
587
+ const state = sdk.wire.TaskState;
588
+ const store = records.store;
589
+ const cancel_poll_ms = config.cancel_poll_ms ?? DEFAULT_CANCEL_POLL_MS;
590
+ let shutting_down = false;
591
+ const report_failure = (ids, err, hold) => {
592
+ const event = failure_event(ids, err);
593
+ if (config.trajectory !== void 0) {
594
+ config.trajectory.record(event);
595
+ return;
596
+ }
597
+ const detail = !(shutting_down && hold.abort.signal.aborted) && typeof event["error_stack"] === "string" ? event["error_stack"] : String(event["error"]);
598
+ process.stderr.write(`a2a_agent: task ${ids.task_id} failed: ${detail}\n`);
599
+ };
600
+ const watch_for_cancel = (ids, hold, context) => {
601
+ if (!(cancel_poll_ms > 0)) return () => {};
602
+ let stopped = false;
603
+ let timer;
604
+ const check = async () => {
605
+ const task = await store.load(ids.task_id, context).catch(() => void 0);
606
+ if (stopped) return;
607
+ if (task?.status?.state === state.TASK_STATE_CANCELED) {
608
+ hold.canceled = true;
609
+ hold.abort.abort(new aborted_error("the task was canceled in another process"));
610
+ return;
611
+ }
612
+ wait();
613
+ };
614
+ const wait = () => {
615
+ timer = setTimeout(() => {
616
+ check();
617
+ }, cancel_poll_ms);
618
+ timer.unref();
619
+ };
620
+ wait();
621
+ return () => {
622
+ stopped = true;
623
+ clearTimeout(timer);
624
+ };
625
+ };
626
+ const history_of = async (ids, context) => {
627
+ const limit = Math.min(MAX_HISTORY_LIMIT, Math.max(0, Math.trunc(config.history_limit ?? DEFAULT_HISTORY_LIMIT)));
628
+ if (limit === 0) return [];
629
+ return (await store.list({
630
+ tenant: context.tenant ?? "",
631
+ contextId: ids.context_id,
632
+ status: state.TASK_STATE_UNSPECIFIED,
633
+ pageSize: Math.min(MAX_HISTORY_LIMIT, limit + 1),
634
+ pageToken: "",
635
+ statusTimestampAfter: void 0,
636
+ includeArtifacts: true
637
+ }, context)).tasks.filter((task) => task.id !== ids.task_id).slice(0, limit).toReversed().flatMap((task) => exchange_of(sdk, task));
638
+ };
639
+ const turn_of = async (ids, message, context) => ({
640
+ task_id: ids.task_id,
641
+ context_id: ids.context_id,
642
+ text: text_of(message.parts, "\n"),
643
+ data: data_of(message.parts),
644
+ files: files_of(message.parts),
645
+ message,
646
+ history: await history_of(ids, context),
647
+ user: user_of(context)
648
+ });
649
+ const input_of = (turn) => {
650
+ if (config.to_input !== void 0) return config.to_input(turn);
651
+ return turn.text;
652
+ };
653
+ const answer_of = (turn, gate) => {
654
+ if (config.to_resume !== void 0) return config.to_resume(turn, gate);
655
+ return turn.data.length > 0 ? turn.data[0] : turn.text;
656
+ };
657
+ const drive = async (ids, hold, context, publish, begin) => {
658
+ const mapper = create_a2a_mapper_state({
659
+ ...ids,
660
+ stream: config.stream
661
+ });
662
+ const to_events = config.to_events ?? to_task_events;
663
+ const logger = drive_logger((event) => {
664
+ for (const mapped of to_events(event, mapper)) publish(mapped);
665
+ }, config.trajectory);
666
+ let rest;
667
+ const unwatch = watch_for_cancel(ids, hold, context);
668
+ try {
669
+ const outcome = await begin({
670
+ record_chunks: true,
671
+ trajectory: logger,
672
+ abort: hold.abort.signal,
673
+ install_signal_handlers: false
674
+ });
675
+ if (outcome.kind !== "busy") rest = outcome;
676
+ } catch (err) {
677
+ rest = refusal_of(err) ?? {
678
+ kind: "failed",
679
+ error: err
680
+ };
681
+ } finally {
682
+ unwatch();
683
+ }
684
+ if (hold.canceled) rest = { kind: "canceled" };
685
+ if (rest?.kind === "failed") report_failure(ids, rest.error, hold);
686
+ const parts = rest?.kind === "done" && !(has_streamed(mapper) && typeof rest.output === "string") ? deps.to_parts(rest.output) : [];
687
+ for (const closing of end_task_events(mapper, parts)) publish(closing);
688
+ const status = rest === void 0 ? void 0 : status_for(sdk.wire, hooks, ids, rest);
689
+ if (status === void 0) return void 0;
690
+ const saved = records.saved(ids.task_id, status, SAVE_WAIT_MS);
691
+ publish(status_event(ids, status));
692
+ await saved;
693
+ return status;
694
+ };
695
+ const finish = async (ids, context, hold) => {
696
+ try {
697
+ await store.load(ids.task_id, context);
698
+ } finally {
699
+ hold.release();
700
+ }
701
+ };
702
+ const execute = async (request, bus) => {
703
+ const ids = {
704
+ task_id: request.taskId,
705
+ context_id: request.contextId
706
+ };
707
+ const hold = holds.get(ids.task_id) ?? take_hold(holds, ids.task_id);
708
+ hold.taken = true;
709
+ slots.get(request.context)?.();
710
+ const publish = (event) => {
711
+ bus.publish(event);
712
+ };
713
+ const message = request.userMessage;
714
+ const opening = request.task ?? {
715
+ id: ids.task_id,
716
+ contextId: ids.context_id,
717
+ status: status_of(state.TASK_STATE_SUBMITTED),
718
+ artifacts: [],
719
+ history: [message],
720
+ metadata: void 0
721
+ };
722
+ try {
723
+ publish({
724
+ kind: "task",
725
+ data: opening
726
+ });
727
+ publish(status_event(ids, status_of(state.TASK_STATE_WORKING)));
728
+ await drive(ids, hold, request.context, publish, async (options) => {
729
+ const turn = await turn_of(ids, message, request.context);
730
+ if (request.task === void 0) return runs.start(ids.task_id, config.flow, input_of(turn), options);
731
+ const run = await runs.get(ids.task_id);
732
+ const data = run?.kind === "suspended" ? { [run.id]: answer_of(turn, run.id) } : {};
733
+ return runs.resume(ids.task_id, config.flow, data, options);
734
+ });
735
+ } finally {
736
+ await finish(ids, request.context, hold);
737
+ }
738
+ };
739
+ const cancel = async (task_id, bus) => {
740
+ const hold = holds.get(task_id);
741
+ if (hold !== void 0) {
742
+ hold.canceled = true;
743
+ hold.abort.abort(new aborted_error("the task was canceled"));
744
+ await hold.settled;
745
+ return;
746
+ }
747
+ const sighting = records.seen.get(task_id);
748
+ const ids = {
749
+ task_id,
750
+ context_id: sighting?.context_id ?? ""
751
+ };
752
+ const status = status_for(sdk.wire, hooks, ids, { kind: "canceled" });
753
+ if (status !== void 0) bus.publish(status_event(ids, status));
754
+ if (sighting !== void 0) buses.cleanupByTaskId(task_id, sighting.context);
755
+ };
756
+ const load_free = async (task_id, context) => {
757
+ for (;;) {
758
+ const held = holds.get(task_id);
759
+ if (held !== void 0) {
760
+ await held.settled;
761
+ continue;
762
+ }
763
+ const task = await store.load(task_id, context);
764
+ if (!holds.has(task_id)) return task;
765
+ }
766
+ };
767
+ const resume = async (task_id, resume_data, options = {}) => {
768
+ const user = options.user;
769
+ const context = user === void 0 ? records.seen.get(task_id)?.context ?? new sdk.server.ServerCallContext() : new sdk.server.ServerCallContext({ user: {
770
+ isAuthenticated: user.authenticated,
771
+ userName: user.name
772
+ } });
773
+ const task = await load_free(task_id, context);
774
+ if (task === void 0) throw new a2a_error(`no task ${task_id} to resume: check the id, and pass \`user\` when the task belongs to an authenticated caller`, { task_id });
775
+ if (is_terminal(sdk.wire, task)) return;
776
+ const ids = {
777
+ task_id,
778
+ context_id: task.contextId
779
+ };
780
+ const hold = take_hold(holds, task_id);
781
+ hold.taken = true;
782
+ const bus = buses.createOrGetByTaskId(task_id, context);
783
+ const writer = new sdk.server.ResultManager(store, context);
784
+ let writes = Promise.resolve();
785
+ const publish = (event) => {
786
+ writes = writes.then(() => writer.processEvent(event));
787
+ bus.publish(event);
788
+ };
789
+ try {
790
+ publish(status_event(ids, status_of(state.TASK_STATE_WORKING)));
791
+ const status = await drive(ids, hold, context, publish, (run_options) => runs.resume(task_id, config.flow, resume_data, run_options));
792
+ await writes;
793
+ if (status?.state !== state.TASK_STATE_INPUT_REQUIRED) {
794
+ bus.finished();
795
+ buses.cleanupByTaskId(task_id, context);
796
+ }
797
+ } finally {
798
+ await finish(ids, context, hold);
799
+ }
800
+ };
801
+ const close = async () => {
802
+ shutting_down = true;
803
+ const open = [...holds.values()];
804
+ for (const hold of open) hold.abort.abort(new aborted_error("the agent closed while the task was running"));
805
+ await Promise.all(open.map((hold) => hold.settled));
806
+ };
807
+ return {
808
+ executor: {
809
+ execute,
810
+ cancelTask: cancel
811
+ },
812
+ resume,
813
+ close
814
+ };
815
+ }
816
+ // src/a2a/admission.ts
817
+ /**
818
+ * Give back a hold that no drive took, which happens when the SDK refused
819
+ * the message after it was admitted.
820
+ */
821
+ function give_back(hold) {
822
+ if (hold !== void 0 && !hold.taken) hold.release();
823
+ }
824
+ /**
825
+ * Wrap `config.inner` so that `SendMessage` and `SendStreamingMessage`
826
+ * refuse a message its task isn't waiting for. Every other method passes
827
+ * straight through.
828
+ */
829
+ function admitting_handler(config) {
830
+ const { sdk, inner, store, runs, holds } = config;
831
+ const refuse = (task_id, why) => {
832
+ throw new sdk.errors.UnsupportedOperationError(`Task ${task_id} can't take a message: ${why}`);
833
+ };
834
+ const admit = async (params, context) => {
835
+ const task_id = params.message?.taskId;
836
+ if (!task_id) return void 0;
837
+ const task = await store.load(task_id, context);
838
+ if (task === void 0 || is_terminal(sdk.wire, task)) return void 0;
839
+ if (holds.has(task_id)) return refuse(task_id, "it's working, so wait until it asks for input");
840
+ const hold = take_hold(holds, task_id);
841
+ try {
842
+ const run = await runs.get(task_id);
843
+ if (run === void 0) return refuse(task_id, "it has no run left to resume");
844
+ if (run.kind !== "suspended") return refuse(task_id, "it's working, so wait until it asks for input");
845
+ if (config.gates(run.id) !== "client") return refuse(task_id, `it waits on "${run.id}", which this agent's clients don't answer`);
846
+ return hold;
847
+ } catch (err) {
848
+ hold.release();
849
+ throw err;
850
+ }
851
+ };
852
+ return {
853
+ getAgentCard: () => inner.getAgentCard(),
854
+ getAuthenticatedExtendedAgentCard: (params, context) => inner.getAuthenticatedExtendedAgentCard(params, context),
855
+ sendMessage: async (params, context) => {
856
+ const hold = await admit(params, context);
857
+ try {
858
+ return await inner.sendMessage(params, context);
859
+ } finally {
860
+ give_back(hold);
861
+ }
862
+ },
863
+ sendMessageStream: async function* (params, context) {
864
+ const hold = await admit(params, context);
865
+ try {
866
+ yield* inner.sendMessageStream(params, context);
867
+ } finally {
868
+ give_back(hold);
869
+ }
870
+ },
871
+ getTask: (params, context) => inner.getTask(params, context),
872
+ cancelTask: (params, context) => inner.cancelTask(params, context),
873
+ createTaskPushNotificationConfig: (params, context) => inner.createTaskPushNotificationConfig(params, context),
874
+ getTaskPushNotificationConfig: (params, context) => inner.getTaskPushNotificationConfig(params, context),
875
+ listTaskPushNotificationConfigs: (params, context) => inner.listTaskPushNotificationConfigs(params, context),
876
+ deleteTaskPushNotificationConfig: (params, context) => inner.deleteTaskPushNotificationConfig(params, context),
877
+ resubscribe: (params, context) => inner.resubscribe(params, context),
878
+ listTasks: (params, context) => inner.listTasks(params, context)
879
+ };
880
+ }
881
+ // src/a2a/http.ts
882
+ const CARD_PATH = "/.well-known/agent-card.json";
883
+ const CARD_MAX_AGE_SECONDS = 300;
884
+ const JSON_TYPE = "application/json";
885
+ const STARTS_A_TASK = /* @__PURE__ */ new Set(["SendMessage", "SendStreamingMessage"]);
886
+ const PARSE_ERROR = -32700;
887
+ const INTERNAL_ERROR = -32603;
888
+ /**
889
+ * A JSON response.
890
+ */
891
+ function json(body, status = 200, headers = {}) {
892
+ return new Response(JSON.stringify(body), {
893
+ status,
894
+ headers: {
895
+ "content-type": JSON_TYPE,
896
+ ...headers
897
+ }
898
+ });
899
+ }
900
+ /**
901
+ * A plain refusal that isn't JSON-RPC, with the reason in its body. The
902
+ * body has no `error` field, which a JSON-RPC client would read as an error
903
+ * object and find empty.
904
+ */
905
+ function refusal(status, message, headers = {}) {
906
+ return json({ message }, status, headers);
907
+ }
908
+ /**
909
+ * Read a request's body as text, or `undefined` once it passes `limit`
910
+ * bytes. A declared length over the limit is refused without reading.
911
+ */
912
+ async function read_body(request, limit) {
913
+ if (Number(request.headers.get("content-length") ?? 0) > limit) return void 0;
914
+ if (request.body === null) return "";
915
+ const decoder = new TextDecoder();
916
+ let text = "";
917
+ let size = 0;
918
+ for await (const chunk of request.body) {
919
+ size += chunk.byteLength;
920
+ if (size > limit) return void 0;
921
+ text += decoder.decode(chunk, { stream: true });
922
+ }
923
+ return text + decoder.decode();
924
+ }
925
+ /**
926
+ * Whether a JSON-RPC body is a message that would start a task (one that
927
+ * names no task of its own).
928
+ */
929
+ function starts_a_task(body) {
930
+ if (!is_record(body) || !STARTS_A_TASK.has(body["method"])) return false;
931
+ const params = body["params"];
932
+ const message = is_record(params) ? params["message"] : void 0;
933
+ return !(is_record(message) && typeof message["taskId"] === "string" && message["taskId"] !== "");
934
+ }
935
+ /**
936
+ * The id of a JSON-RPC request, for the error that answers it.
937
+ */
938
+ function id_of(body) {
939
+ const id = is_record(body) ? body["id"] : null;
940
+ return typeof id === "string" || typeof id === "number" ? id : null;
941
+ }
942
+ /**
943
+ * Whether a value is the stream of responses a streaming method returns.
944
+ */
945
+ function is_stream(value) {
946
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
947
+ }
948
+ /**
949
+ * Build the fetch handler for one agent.
950
+ */
951
+ function http_handler(config) {
952
+ const { sdk, card, handler } = config;
953
+ const transport = new sdk.server.JsonRpcTransportHandler(handler);
954
+ const card_body = JSON.stringify(sdk.wire.AgentCard.toJSON(card));
955
+ const error_response = (id, err) => ({
956
+ jsonrpc: "2.0",
957
+ id,
958
+ error: sdk.server.JsonRpcTransportHandler.mapToJSONRPCError(err)
959
+ });
960
+ const event_stream = (first, rest, id, headers) => {
961
+ const encoder = new TextEncoder();
962
+ let open = true;
963
+ const body = new ReadableStream({
964
+ start: (controller) => {
965
+ const send = (frame) => {
966
+ if (open) controller.enqueue(encoder.encode(frame));
967
+ };
968
+ const pump = async () => {
969
+ try {
970
+ if (first !== void 0) send(sdk.wire.formatSSEEvent(first));
971
+ for (let next = await rest.next(); next.done !== true; next = await rest.next()) send(sdk.wire.formatSSEEvent(next.value));
972
+ } catch (err) {
973
+ send(sdk.wire.formatSSEErrorEvent(error_response(id, err)));
974
+ }
975
+ if (open) controller.close();
976
+ open = false;
977
+ };
978
+ pump();
979
+ },
980
+ cancel: () => {
981
+ open = false;
982
+ }
983
+ });
984
+ return new Response(body, {
985
+ status: 200,
986
+ headers: {
987
+ ...sdk.wire.SSE_HEADERS,
988
+ ...headers
989
+ }
990
+ });
991
+ };
992
+ const context_for = (request, user) => {
993
+ const version = request.headers.get(sdk.wire.A2A_VERSION_HEADER);
994
+ return new sdk.server.ServerCallContext({
995
+ requestedExtensions: sdk.wire.Extensions.parseServiceParameter(request.headers.get(sdk.wire.HTTP_EXTENSION_HEADER) ?? void 0),
996
+ user: {
997
+ isAuthenticated: user.authenticated,
998
+ userName: user.name
999
+ },
1000
+ ...version === null ? {} : { requestedVersion: version },
1001
+ state: /* @__PURE__ */ new Map([[sdk.server.STATE_HEADERS_KEY, Object.fromEntries(request.headers)]])
1002
+ });
1003
+ };
1004
+ const dispatch = async (body, context) => {
1005
+ const id = id_of(body);
1006
+ try {
1007
+ sdk.server.validateVersion(context.requestedVersion, card, "JSONRPC");
1008
+ } catch (err) {
1009
+ return json(error_response(id, err));
1010
+ }
1011
+ const result = await transport.handle(body, context);
1012
+ const activated = context.activatedExtensions;
1013
+ const headers = activated === void 0 ? {} : { [sdk.wire.HTTP_EXTENSION_HEADER]: activated.join(",") };
1014
+ if (!is_stream(result)) return json(result, 200, headers);
1015
+ let first;
1016
+ try {
1017
+ first = await result.next();
1018
+ } catch (err) {
1019
+ return json(error_response(id, err), 200, headers);
1020
+ }
1021
+ return event_stream(first.done === true ? void 0 : first.value, result, id, headers);
1022
+ };
1023
+ const rpc = async (request) => {
1024
+ const user = config.authenticate === void 0 ? {
1025
+ name: "",
1026
+ authenticated: false
1027
+ } : await config.authenticate(request);
1028
+ if (user === null) return refusal(401, "unauthorized");
1029
+ const type = request.headers.get("content-type") ?? "";
1030
+ if (type.split(";", 1)[0]?.trim().toLowerCase() !== JSON_TYPE) {
1031
+ const unsupported = new sdk.errors.ContentTypeNotSupportedError(`Unsupported Content-Type "${type}"; expected ${JSON_TYPE}.`);
1032
+ return json(error_response(null, unsupported));
1033
+ }
1034
+ const text = await read_body(request, config.max_body_bytes);
1035
+ if (text === void 0) return refusal(413, `the request body is over ${config.max_body_bytes} bytes`);
1036
+ let body;
1037
+ try {
1038
+ body = JSON.parse(text);
1039
+ } catch {
1040
+ return json({
1041
+ jsonrpc: "2.0",
1042
+ id: null,
1043
+ error: {
1044
+ code: PARSE_ERROR,
1045
+ message: "Invalid JSON payload."
1046
+ }
1047
+ });
1048
+ }
1049
+ const context = context_for(request, user);
1050
+ const release = starts_a_task(body) ? config.reserve(context) : () => {};
1051
+ if (release === void 0) return refusal(429, "the agent is running as many tasks as it takes at once: try again shortly", { "retry-after": "1" });
1052
+ try {
1053
+ return await dispatch(body, context);
1054
+ } catch (err) {
1055
+ const mapped = error_response(id_of(body), err);
1056
+ return json(mapped, is_record(mapped.error) && mapped.error["code"] === INTERNAL_ERROR ? 500 : 200);
1057
+ } finally {
1058
+ release();
1059
+ }
1060
+ };
1061
+ return async (request) => {
1062
+ if (config.is_closed()) return refusal(503, "the agent has closed");
1063
+ const path = new URL(request.url).pathname;
1064
+ if (path === CARD_PATH) {
1065
+ if (request.method !== "GET") return refusal(405, "the agent card takes GET", { allow: "GET" });
1066
+ return new Response(card_body, {
1067
+ status: 200,
1068
+ headers: {
1069
+ "content-type": JSON_TYPE,
1070
+ "cache-control": `public, max-age=${CARD_MAX_AGE_SECONDS}`
1071
+ }
1072
+ });
1073
+ }
1074
+ if (path !== config.rpc_path) return refusal(404, `nothing is served at ${path}`);
1075
+ if (request.method !== "POST") return refusal(405, "JSON-RPC takes POST", { allow: "POST" });
1076
+ return rpc(request);
1077
+ };
1078
+ }
1079
+ // src/a2a/sdk_loader.ts
1080
+ /**
1081
+ * Lazy loaders for the optional `@a2a-js/sdk` peer.
1082
+ *
1083
+ * The adapter needs SDK values (the request handler, the JSON-RPC transport,
1084
+ * the client factory, the wire enums), so it imports the SDK dynamically
1085
+ * instead of statically. A consumer can import `fascicle/a2a` without the
1086
+ * SDK installed and only pays for it when they serve a flow or call a remote
1087
+ * agent. A missing peer surfaces as a typed `a2a_sdk_missing_error` that
1088
+ * says how to install it, the way src/acp/sdk_loader.ts and
1089
+ * src/mcp/sdk_loader.ts do for theirs.
1090
+ *
1091
+ * The SDK publishes each entry point as a bundle of its own, so the server
1092
+ * half and the client half load apart, and a flow that only calls a remote
1093
+ * agent never loads the request handler.
1094
+ */
1095
+ /**
1096
+ * Throw the typed missing-peer error for a failed import of the SDK.
1097
+ */
1098
+ function missing(err) {
1099
+ throw new a2a_sdk_missing_error(`@a2a-js/sdk is required for fascicle/a2a; install it: pnpm add @a2a-js/sdk (cause: ${err instanceof Error ? err.message : String(err)})`);
1100
+ }
1101
+ /**
1102
+ * Dynamically imports what serving needs of `@a2a-js/sdk`: the wire types'
1103
+ * codecs and enums, the server, and the protocol's errors. Throws a typed
1104
+ * `a2a_sdk_missing_error` when the optional peer is not installed.
1105
+ */
1106
+ async function load_a2a_server() {
1107
+ try {
1108
+ const [wire, server, errors] = await Promise.all([
1109
+ import("@a2a-js/sdk"),
1110
+ import("@a2a-js/sdk/server"),
1111
+ import("@a2a-js/sdk/errors")
1112
+ ]);
1113
+ return {
1114
+ wire,
1115
+ server,
1116
+ errors
1117
+ };
1118
+ } catch (err) {
1119
+ return missing(err);
1120
+ }
1121
+ }
1122
+ /**
1123
+ * Dynamically imports what calling a remote agent needs of `@a2a-js/sdk`:
1124
+ * the wire enums and the client. Throws a typed `a2a_sdk_missing_error` when
1125
+ * the optional peer is not installed.
1126
+ */
1127
+ async function load_a2a_client() {
1128
+ try {
1129
+ const [wire, client] = await Promise.all([import("@a2a-js/sdk"), import("@a2a-js/sdk/client")]);
1130
+ return {
1131
+ wire,
1132
+ client
1133
+ };
1134
+ } catch (err) {
1135
+ return missing(err);
1136
+ }
1137
+ }
1138
+ // src/a2a/task_records.ts
1139
+ /**
1140
+ * The task store the agent hands to the SDK: the caller's store, with the
1141
+ * runs kept in step behind it.
1142
+ *
1143
+ * Task records and runs live in two stores that can't share a transaction,
1144
+ * so the runs are the source of truth and every `load` brings the record up
1145
+ * to date. A task that isn't terminal takes on whatever its run did since
1146
+ * (another process drove it, or an outside event called `runs.resume`
1147
+ * directly), which keeps `GetTask` honest and repairs a record that a crash
1148
+ * left behind between the two writes. A task this process is driving is left
1149
+ * alone, since its own events are on their way.
1150
+ *
1151
+ * A terminal task needs no run. `FAILED` is final in A2A, while `durable`
1152
+ * would drive a failed run again at the next event, so the task's state
1153
+ * wins: a `save` that makes a task terminal deletes its run, and so does a
1154
+ * `load` that finds one. The run store only ever holds live tasks.
1155
+ *
1156
+ * A terminal task doesn't change either. A drive that another process
1157
+ * canceled runs on to its next resting place, and the SDK drops the status it
1158
+ * publishes there but would still fold its artifacts into the record. The
1159
+ * SDK loads a task before every write to it, so once a load has seen a task
1160
+ * ended, the store refuses every later `save` of it.
1161
+ *
1162
+ * `list` answers from the same records, so it brings each task on its page
1163
+ * up to date the way `load` does. The inner store applies a status filter
1164
+ * to the states it has stored, so a filtered `list` first brings up to date
1165
+ * the tasks the filter could misplace: the ones stored in a state a task
1166
+ * can still leave, up to `STALE_SCAN_LIMIT` of them in each such state.
1167
+ */
1168
+ const REMEMBERED_LIMIT = 1e4;
1169
+ const SEEN_LIMIT = 1e4;
1170
+ /**
1171
+ * Where a stored run stands, in the terms a task status is built from.
1172
+ */
1173
+ function rest_of$1(state) {
1174
+ if (state.kind === "failed") return {
1175
+ kind: "failed",
1176
+ error: new Error(state.error)
1177
+ };
1178
+ return state;
1179
+ }
1180
+ /**
1181
+ * Whether a task's record already says what its run does, so that a load
1182
+ * leaves it alone. A waiting task matches its run when both name the same
1183
+ * gate, and a working one matches a run that's being driven.
1184
+ */
1185
+ function is_current(wire, task, rest, next) {
1186
+ if (next === void 0) return task.status?.state !== wire.TaskState.TASK_STATE_INPUT_REQUIRED;
1187
+ if (rest.kind !== "suspended") return false;
1188
+ return task.status?.state === next.state && gate_of(task) === rest.id;
1189
+ }
1190
+ /**
1191
+ * Add a task id to a set of remembered ones, emptying the set first once it
1192
+ * has grown to its limit. Forgetting costs a repeated store call, never a
1193
+ * wrong answer, since the next load of the task remembers it again.
1194
+ */
1195
+ function remember(ids, task_id) {
1196
+ if (ids.size >= REMEMBERED_LIMIT) ids.clear();
1197
+ ids.add(task_id);
1198
+ }
1199
+ /**
1200
+ * Note where a task was last seen, as the newest sighting, and forget the
1201
+ * oldest one once more than `limit` are held. A forgotten task is still
1202
+ * served: `resume` then needs `user` for a task that belongs to someone.
1203
+ */
1204
+ function sight(seen, task_id, sighting, limit) {
1205
+ seen.delete(task_id);
1206
+ seen.set(task_id, sighting);
1207
+ if (seen.size <= limit) return;
1208
+ for (const oldest of seen.keys()) {
1209
+ seen.delete(oldest);
1210
+ return;
1211
+ }
1212
+ }
1213
+ /**
1214
+ * Wrap `config.inner` so that its task records follow their runs.
1215
+ */
1216
+ function task_records(config) {
1217
+ const { wire, inner, runs, hooks } = config;
1218
+ const seen = /* @__PURE__ */ new Map();
1219
+ const ended = /* @__PURE__ */ new Set();
1220
+ const dropped = /* @__PURE__ */ new Set();
1221
+ const waiters = /* @__PURE__ */ new Map();
1222
+ const drop_run = async (task_id) => {
1223
+ if (dropped.has(task_id)) return;
1224
+ if (await runs.delete(task_id)) remember(dropped, task_id);
1225
+ };
1226
+ const settle = async (task) => {
1227
+ if (!is_terminal(wire, task)) return;
1228
+ seen.delete(task.id);
1229
+ remember(ended, task.id);
1230
+ await drop_run(task.id);
1231
+ };
1232
+ const announce = (task) => {
1233
+ for (const waiter of waiters.get(task.id) ?? []) if (waiter.status.state === task.status?.state && waiter.status.timestamp === task.status.timestamp) waiter.resolve();
1234
+ };
1235
+ const write = async (task, context) => {
1236
+ if (ended.has(task.id)) return;
1237
+ await inner.save(task, context);
1238
+ sight(seen, task.id, {
1239
+ context,
1240
+ context_id: task.contextId
1241
+ }, SEEN_LIMIT);
1242
+ announce(task);
1243
+ await settle(task);
1244
+ };
1245
+ const reconcile = async (task, context) => {
1246
+ const state = await runs.get(task.id);
1247
+ if (state === void 0) return task;
1248
+ const rest = rest_of$1(state);
1249
+ const ids = {
1250
+ task_id: task.id,
1251
+ context_id: task.contextId
1252
+ };
1253
+ const next = status_for(wire, hooks, ids, rest);
1254
+ if (is_current(wire, task, rest, next)) return task;
1255
+ const status = next ?? {
1256
+ state: wire.TaskState.TASK_STATE_WORKING,
1257
+ message: void 0,
1258
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1259
+ };
1260
+ const parts = rest.kind === "done" ? config.to_parts(rest.output) : [];
1261
+ const artifact = {
1262
+ artifactId: randomUUID(),
1263
+ name: "",
1264
+ description: "",
1265
+ parts: [...parts],
1266
+ metadata: void 0,
1267
+ extensions: []
1268
+ };
1269
+ const updated = {
1270
+ ...task,
1271
+ status,
1272
+ artifacts: parts.length === 0 ? task.artifacts : [...task.artifacts, artifact],
1273
+ history: status.message === void 0 ? task.history : [...task.history, status.message]
1274
+ };
1275
+ await write(updated, context);
1276
+ return updated;
1277
+ };
1278
+ const load = async (task_id, context) => {
1279
+ const task = await inner.load(task_id, context);
1280
+ if (task === void 0) return void 0;
1281
+ if (is_terminal(wire, task)) {
1282
+ await settle(task);
1283
+ return task;
1284
+ }
1285
+ sight(seen, task_id, {
1286
+ context,
1287
+ context_id: task.contextId
1288
+ }, SEEN_LIMIT);
1289
+ return config.is_live(task_id) ? task : reconcile(task, context);
1290
+ };
1291
+ const refresh = async (listed, with_artifacts, context) => {
1292
+ if (is_terminal(wire, listed) || config.is_live(listed.id)) return listed;
1293
+ const loaded = await load(listed.id, context);
1294
+ if (loaded === void 0) return listed;
1295
+ return with_artifacts ? loaded : {
1296
+ ...loaded,
1297
+ artifacts: []
1298
+ };
1299
+ };
1300
+ const catch_up = async (params, context) => {
1301
+ const open = [
1302
+ wire.TaskState.TASK_STATE_SUBMITTED,
1303
+ wire.TaskState.TASK_STATE_WORKING,
1304
+ wire.TaskState.TASK_STATE_INPUT_REQUIRED
1305
+ ];
1306
+ const stale = (await Promise.all(open.map((status) => inner.list({
1307
+ ...params,
1308
+ status,
1309
+ pageSize: 100,
1310
+ pageToken: "",
1311
+ statusTimestampAfter: void 0,
1312
+ includeArtifacts: false
1313
+ }, context)))).flatMap((page) => page.tasks).filter((task) => !config.is_live(task.id));
1314
+ await Promise.all(stale.map((task) => load(task.id, context)));
1315
+ return new Set(stale.map((task) => task.id));
1316
+ };
1317
+ const list = async (params, context) => {
1318
+ const filtered = params.status !== wire.TaskState.TASK_STATE_UNSPECIFIED;
1319
+ const current = filtered ? await catch_up(params, context) : /* @__PURE__ */ new Set();
1320
+ const page = await inner.list(params, context);
1321
+ const tasks = await Promise.all(page.tasks.map(async (task) => current.has(task.id) ? task : refresh(task, params.includeArtifacts === true, context)));
1322
+ return {
1323
+ ...page,
1324
+ tasks: filtered ? tasks.filter((task) => task.status?.state === params.status) : tasks
1325
+ };
1326
+ };
1327
+ const store = {
1328
+ load,
1329
+ save: write,
1330
+ list
1331
+ };
1332
+ const saved = (task_id, status, timeout_ms) => {
1333
+ if (ended.has(task_id)) return Promise.resolve();
1334
+ const { promise, resolve } = Promise.withResolvers();
1335
+ const waiting = waiters.get(task_id) ?? /* @__PURE__ */ new Set();
1336
+ waiters.set(task_id, waiting);
1337
+ const waiter = {
1338
+ status,
1339
+ resolve
1340
+ };
1341
+ waiting.add(waiter);
1342
+ const timer = setTimeout(resolve, timeout_ms);
1343
+ timer.unref();
1344
+ return promise.finally(() => {
1345
+ clearTimeout(timer);
1346
+ waiting.delete(waiter);
1347
+ if (waiting.size === 0) waiters.delete(task_id);
1348
+ });
1349
+ };
1350
+ return {
1351
+ store,
1352
+ seen,
1353
+ saved
1354
+ };
1355
+ }
1356
+ // src/a2a/a2a_agent.ts
1357
+ const DEFAULT_MODES = ["text/plain", "application/json"];
1358
+ const DEFAULT_MAX_BODY_BYTES = 1048576;
1359
+ const DEFAULT_MAX_DRIVES = 8;
1360
+ /**
1361
+ * The SDK's agent card for a config's card: one JSON-RPC interface at the
1362
+ * card's URL, streaming on, and push notifications and the extended card off.
1363
+ */
1364
+ function agent_card(card) {
1365
+ return {
1366
+ name: card.name,
1367
+ description: card.description,
1368
+ supportedInterfaces: [{
1369
+ url: card.url,
1370
+ protocolBinding: "JSONRPC",
1371
+ tenant: "",
1372
+ protocolVersion: "1.0"
1373
+ }],
1374
+ provider: card.provider === void 0 ? void 0 : { ...card.provider },
1375
+ version: card.version ?? "0.0.0",
1376
+ documentationUrl: card.documentation_url,
1377
+ capabilities: {
1378
+ streaming: true,
1379
+ pushNotifications: false,
1380
+ extensions: [],
1381
+ extendedAgentCard: false
1382
+ },
1383
+ securitySchemes: { ...card.security_schemes },
1384
+ securityRequirements: [...card.security_requirements ?? []],
1385
+ defaultInputModes: [...card.input_modes ?? DEFAULT_MODES],
1386
+ defaultOutputModes: [...card.output_modes ?? DEFAULT_MODES],
1387
+ skills: card.skills.map((skill) => ({
1388
+ id: skill.id,
1389
+ name: skill.name,
1390
+ description: skill.description,
1391
+ tags: [...skill.tags ?? []],
1392
+ examples: [...skill.examples ?? []],
1393
+ inputModes: [...skill.input_modes ?? []],
1394
+ outputModes: [...skill.output_modes ?? []],
1395
+ securityRequirements: []
1396
+ })),
1397
+ signatures: [],
1398
+ iconUrl: card.icon_url
1399
+ };
1400
+ }
1401
+ /**
1402
+ * Warn on stderr about the steps that every answer to a gate runs again. A
1403
+ * resumed drive replays the flow from its input, so a model call before a
1404
+ * gate that no `checkpoint` holds bills again each time a client answers.
1405
+ */
1406
+ function warn_about_replays(config) {
1407
+ const replays = describe.replays(config.flow);
1408
+ if (replays.length === 0) return;
1409
+ const names = replays.map((hint) => `${hint.id} (before ${hint.gates.join(", ")})`).join("; ");
1410
+ process.stderr.write(`a2a_agent: ${config.card.name} runs these steps again on every answer to a gate, so wrap each in checkpoint(): ${names}\n`);
1411
+ }
1412
+ /**
1413
+ * Build an A2A agent over `config.flow`, with its handlers ready and
1414
+ * nothing listening.
1415
+ *
1416
+ * Every task is a durable run in `config.runs`, over `memory_store` when
1417
+ * the caller gives none, so a task that outlives the process is a choice of
1418
+ * store and not a second code path. Throws `a2a_sdk_missing_error` when the
1419
+ * `@a2a-js/sdk` peer isn't installed.
1420
+ */
1421
+ async function a2a_agent(config) {
1422
+ const sdk = await load_a2a_server();
1423
+ const card = agent_card(config.card);
1424
+ const runs = config.runs ?? durable({ store: memory_store() });
1425
+ const holds = /* @__PURE__ */ new Map();
1426
+ const slots = /* @__PURE__ */ new WeakMap();
1427
+ const custom_parts = config.to_parts;
1428
+ const to_parts = custom_parts === void 0 ? output_parts : (output) => custom_parts(output);
1429
+ const hooks = {
1430
+ gates: config.gates ?? (() => "client"),
1431
+ to_question: config.to_question ?? default_question,
1432
+ to_failure: config.to_failure ?? default_failure
1433
+ };
1434
+ const records = task_records({
1435
+ wire: sdk.wire,
1436
+ inner: config.task_store ?? new sdk.server.InMemoryTaskStore(),
1437
+ runs,
1438
+ hooks,
1439
+ to_parts,
1440
+ is_live: (task_id) => holds.has(task_id)
1441
+ });
1442
+ const buses = new sdk.server.DefaultExecutionEventBusManager();
1443
+ const runner = task_runner({
1444
+ sdk,
1445
+ config,
1446
+ runs,
1447
+ records,
1448
+ holds,
1449
+ slots,
1450
+ hooks,
1451
+ to_parts,
1452
+ buses
1453
+ });
1454
+ const request_handler = admitting_handler({
1455
+ sdk,
1456
+ inner: new sdk.server.DefaultRequestHandler(card, records.store, runner.executor, buses),
1457
+ store: records.store,
1458
+ runs,
1459
+ holds,
1460
+ gates: hooks.gates
1461
+ });
1462
+ const max_drives = config.max_drives ?? DEFAULT_MAX_DRIVES;
1463
+ let closed = false;
1464
+ let reserved = 0;
1465
+ warn_about_replays(config);
1466
+ const reserve = (context) => {
1467
+ if (holds.size + reserved >= max_drives) return void 0;
1468
+ reserved += 1;
1469
+ let held = true;
1470
+ const release = () => {
1471
+ if (!held) return;
1472
+ held = false;
1473
+ reserved -= 1;
1474
+ };
1475
+ slots.set(context, release);
1476
+ return release;
1477
+ };
1478
+ return {
1479
+ fetch: http_handler({
1480
+ sdk,
1481
+ card,
1482
+ handler: request_handler,
1483
+ authenticate: config.authenticate,
1484
+ rpc_path: config.rpc_path ?? "/",
1485
+ max_body_bytes: config.max_body_bytes ?? DEFAULT_MAX_BODY_BYTES,
1486
+ reserve,
1487
+ is_closed: () => closed
1488
+ }),
1489
+ resume: runner.resume,
1490
+ request_handler,
1491
+ card,
1492
+ close: async () => {
1493
+ closed = true;
1494
+ await runner.close();
1495
+ }
1496
+ };
1497
+ }
1498
+ // src/a2a/remote_task.ts
1499
+ /**
1500
+ * One message to a remote A2A agent, and what its task comes to.
1501
+ *
1502
+ * `a2a_step` sends each round through here. The message goes out as a
1503
+ * stream when the remote agent's card says it can stream, and as a blocking
1504
+ * `SendMessage` otherwise. Either way a task that's still working when the
1505
+ * call returns is polled with `GetTask`, on a backoff that starts at half a
1506
+ * second and stops growing at five, until it rests.
1507
+ *
1508
+ * While a stream is read, each text chunk of the task's artifacts is
1509
+ * recorded as a `model_chunk` event under the step's id when the run asked
1510
+ * for chunks, so every consumer that shows a model call's text shows the
1511
+ * remote agent's too. Each change of the task's status becomes an `emit`
1512
+ * event with the state and the status message's text, and so does the id of
1513
+ * the task a round opens.
1514
+ *
1515
+ * A round ends in one of two ways the flow can go on from: the task
1516
+ * completed, or it asked a question. A task that failed, was rejected or
1517
+ * canceled, or wants credentials throws `a2a_error`. An abort stops the
1518
+ * stream, asks the remote agent to cancel the task (best effort), and
1519
+ * throws the abort's reason.
1520
+ *
1521
+ * What a round resolves is plain JSON, bytes included, because `a2a_step`
1522
+ * keeps it in a checkpoint.
1523
+ */
1524
+ const FIRST_POLL_MS = 500;
1525
+ const MAX_POLL_MS = 5e3;
1526
+ const CANCEL_WAIT_MS = 5e3;
1527
+ /**
1528
+ * The request that carries `outgoing` as one user message.
1529
+ */
1530
+ function request_for(remote, outgoing) {
1531
+ return {
1532
+ tenant: "",
1533
+ message: {
1534
+ messageId: randomUUID(),
1535
+ contextId: outgoing.context_id ?? "",
1536
+ taskId: outgoing.task_id ?? "",
1537
+ role: remote.sdk.wire.Role.ROLE_USER,
1538
+ parts: [...outgoing.parts],
1539
+ metadata: void 0,
1540
+ extensions: [],
1541
+ referenceTaskIds: []
1542
+ },
1543
+ configuration: void 0,
1544
+ metadata: void 0
1545
+ };
1546
+ }
1547
+ /**
1548
+ * Take a whole task as the latest word on it.
1549
+ */
1550
+ function see_task(seen, task) {
1551
+ seen.task_id = task.id;
1552
+ seen.context_id = task.contextId;
1553
+ seen.state = task.status?.state;
1554
+ seen.status = task.status?.message;
1555
+ seen.artifacts.clear();
1556
+ for (const artifact of task.artifacts) seen.artifacts.set(artifact.artifactId, artifact);
1557
+ }
1558
+ /**
1559
+ * Fold one chunk of an artifact into what the round has of it, the way the
1560
+ * task itself does: a chunk that appends adds its parts, and any other
1561
+ * replaces the artifact.
1562
+ */
1563
+ function see_artifact(seen, artifact, append) {
1564
+ const held = seen.artifacts.get(artifact.artifactId);
1565
+ const parts = append && held !== void 0 ? [...held.parts, ...artifact.parts] : artifact.parts;
1566
+ seen.artifacts.set(artifact.artifactId, {
1567
+ ...held ?? artifact,
1568
+ ...artifact,
1569
+ parts
1570
+ });
1571
+ }
1572
+ /**
1573
+ * Whether a task is still on its way somewhere, so the round keeps asking.
1574
+ */
1575
+ function is_working(remote, state) {
1576
+ const states = remote.sdk.wire.TaskState;
1577
+ return state === states.TASK_STATE_WORKING || state === states.TASK_STATE_SUBMITTED;
1578
+ }
1579
+ /**
1580
+ * Wait `ms`, or reject with the signal's reason as soon as it aborts.
1581
+ */
1582
+ function pause(ms, signal) {
1583
+ return new Promise((resolve, reject) => {
1584
+ const on_abort = () => {
1585
+ clearTimeout(timer);
1586
+ reject(signal.reason instanceof Error ? signal.reason : new aborted_error("aborted", { reason: signal.reason }));
1587
+ };
1588
+ const timer = setTimeout(() => {
1589
+ signal.removeEventListener("abort", on_abort);
1590
+ resolve();
1591
+ }, ms);
1592
+ if (signal.aborted) on_abort();
1593
+ else signal.addEventListener("abort", on_abort, { once: true });
1594
+ });
1595
+ }
1596
+ /**
1597
+ * Where the round rests, given the last the task said: a completion, a
1598
+ * question, or an `a2a_error` for anything the flow can't go on from.
1599
+ */
1600
+ function rest_of(remote, seen) {
1601
+ const { task_id, context_id } = seen;
1602
+ if (seen.reply !== void 0) return {
1603
+ kind: "completed",
1604
+ task_id,
1605
+ context_id,
1606
+ artifacts: to_plain([{
1607
+ artifactId: seen.reply.messageId,
1608
+ name: "",
1609
+ description: "",
1610
+ parts: seen.reply.parts,
1611
+ metadata: void 0,
1612
+ extensions: []
1613
+ }])
1614
+ };
1615
+ const states = remote.sdk.wire.TaskState;
1616
+ if (seen.state === states.TASK_STATE_COMPLETED) return {
1617
+ kind: "completed",
1618
+ task_id,
1619
+ context_id,
1620
+ artifacts: to_plain([...seen.artifacts.values()])
1621
+ };
1622
+ const parts = seen.status?.parts ?? [];
1623
+ if (seen.state === states.TASK_STATE_INPUT_REQUIRED) return {
1624
+ kind: "question",
1625
+ task_id,
1626
+ context_id,
1627
+ text: text_of(parts, "\n"),
1628
+ data: data_of(parts)
1629
+ };
1630
+ const state = seen.state === void 0 ? "TASK_STATE_UNSPECIFIED" : remote.sdk.wire.taskStateToJSON(seen.state);
1631
+ const status_text = text_of(parts, "\n");
1632
+ throw new a2a_error(`the remote task ${task_id} ended in ${state}${status_text === "" ? "" : `: ${status_text}`}`, {
1633
+ state,
1634
+ status_text,
1635
+ task_id
1636
+ });
1637
+ }
1638
+ /**
1639
+ * Send one message to the remote agent and resolve where its task rests.
1640
+ */
1641
+ async function send_round(remote, step_id, outgoing, ctx) {
1642
+ const { client } = remote;
1643
+ const options = { signal: ctx.abort };
1644
+ const seen = {
1645
+ task_id: outgoing.task_id ?? "",
1646
+ context_id: outgoing.context_id ?? "",
1647
+ state: void 0,
1648
+ status: void 0,
1649
+ reply: void 0,
1650
+ artifacts: /* @__PURE__ */ new Map()
1651
+ };
1652
+ const see_status = (state, message) => {
1653
+ seen.state = state;
1654
+ seen.status = message;
1655
+ ctx.emit({
1656
+ step_id,
1657
+ a2a_status: {
1658
+ task_id: seen.task_id,
1659
+ state: state === void 0 ? "TASK_STATE_UNSPECIFIED" : remote.sdk.wire.taskStateToJSON(state),
1660
+ text: text_of(message?.parts ?? [], "\n")
1661
+ }
1662
+ });
1663
+ };
1664
+ const see_chunk = (artifact, append) => {
1665
+ see_artifact(seen, artifact, append);
1666
+ const text = text_of(artifact.parts);
1667
+ if (!ctx.streaming || text === "") return;
1668
+ ctx.trajectory.record({
1669
+ kind: "model_chunk",
1670
+ step_id,
1671
+ chunk: {
1672
+ kind: "text",
1673
+ text,
1674
+ step_index: 0
1675
+ }
1676
+ });
1677
+ };
1678
+ let announced = outgoing.task_id !== void 0;
1679
+ const announce = () => {
1680
+ if (announced || seen.task_id === "") return;
1681
+ announced = true;
1682
+ ctx.emit({
1683
+ step_id,
1684
+ a2a_task: {
1685
+ task_id: seen.task_id,
1686
+ context_id: seen.context_id
1687
+ }
1688
+ });
1689
+ };
1690
+ const see = (event) => {
1691
+ const payload = event.payload;
1692
+ if (payload === void 0) return;
1693
+ if (payload.$case === "task") {
1694
+ see_task(seen, payload.value);
1695
+ announce();
1696
+ }
1697
+ if (payload.$case === "message") seen.reply = payload.value;
1698
+ if (payload.$case === "statusUpdate") {
1699
+ seen.task_id = payload.value.taskId;
1700
+ see_status(payload.value.status?.state, payload.value.status?.message);
1701
+ }
1702
+ if (payload.$case === "artifactUpdate" && payload.value.artifact !== void 0) see_chunk(payload.value.artifact, payload.value.append);
1703
+ };
1704
+ const exchange = async () => {
1705
+ const request = request_for(remote, outgoing);
1706
+ if (remote.streams) for await (const event of client.sendMessageStream(request, options)) see(event);
1707
+ else {
1708
+ const answer = await client.sendMessage(request, options);
1709
+ if ("messageId" in answer) seen.reply = answer;
1710
+ else see_task(seen, answer);
1711
+ announce();
1712
+ }
1713
+ let wait_ms = FIRST_POLL_MS;
1714
+ while (seen.reply === void 0 && is_working(remote, seen.state)) {
1715
+ await pause(wait_ms, ctx.abort);
1716
+ wait_ms = Math.min(MAX_POLL_MS, wait_ms * 2);
1717
+ see_task(seen, await client.getTask({
1718
+ tenant: "",
1719
+ id: seen.task_id,
1720
+ historyLength: void 0
1721
+ }, options));
1722
+ }
1723
+ };
1724
+ try {
1725
+ await exchange();
1726
+ } catch (err) {
1727
+ if (!ctx.abort.aborted) throw err;
1728
+ if (seen.task_id !== "") await client.cancelTask({
1729
+ tenant: "",
1730
+ id: seen.task_id,
1731
+ metadata: void 0
1732
+ }, { signal: AbortSignal.timeout(CANCEL_WAIT_MS) }).catch(() => {});
1733
+ const reason = ctx.abort.reason;
1734
+ throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
1735
+ }
1736
+ return rest_of(remote, seen);
1737
+ }
1738
+ // src/a2a/scoped_fetch.ts
1739
+ /**
1740
+ * Wrap `inner` so the headers go with a request only when it is bound for the
1741
+ * origin of `base_url`.
1742
+ *
1743
+ * The headers are usually credentials, and the agent's card chooses the URL
1744
+ * that messages are sent to. A card that names another origin would otherwise
1745
+ * be handed the caller's token, so a request to any other origin goes out
1746
+ * without them, and the headers function isn't run for it.
1747
+ */
1748
+ function scoped_fetch(base_url, source, inner = fetch) {
1749
+ const home = new URL(base_url).origin;
1750
+ return async (input, init) => {
1751
+ const target = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
1752
+ if (source === void 0 || new URL(target, base_url).origin !== home) return inner(input, init);
1753
+ const extra = typeof source === "function" ? await source() : source;
1754
+ const headers = new Headers(init?.headers);
1755
+ for (const [name, value] of Object.entries(extra)) headers.set(name, value);
1756
+ return inner(input, {
1757
+ ...init,
1758
+ headers
1759
+ });
1760
+ };
1761
+ }
1762
+ // src/a2a/a2a_step.ts
1763
+ /**
1764
+ * a2a_step: a step that hands its input to a remote A2A agent and resolves
1765
+ * what the agent's task produced.
1766
+ *
1767
+ * The step is a leaf that streams text much as a model call does, so it's
1768
+ * marked `side_effect`, and under `run.stream` or `record_chunks` the remote
1769
+ * agent's text arrives as `model_chunk` events under the step's id.
1770
+ *
1771
+ * A remote question becomes a local `suspend`, which is what lets agents
1772
+ * chain: a Fascicle agent that calls another and gets a question surfaces it
1773
+ * as its own, all the way up to whoever runs the outermost flow. When the
1774
+ * remote task stops at `INPUT_REQUIRED`, the step suspends the local run at
1775
+ * a gate named `<step id>_<round>`, with the remote question as the gate's
1776
+ * payload, and a resume hands the answer to the same remote task as its
1777
+ * next message. The step builds this from public composites inside its own
1778
+ * body. Each round's send runs inside a `checkpoint`, so a replay doesn't
1779
+ * send it again, and each gate is a `suspend` that the step calls through
1780
+ * `ctx.call`. That needs a checkpoint store, which `durable` gives every
1781
+ * drive. Without one a remote question throws `a2a_error`, since a resume
1782
+ * would otherwise open a second remote task.
1783
+ *
1784
+ * A round's checkpoint is keyed by the step id, the round, and a digest of
1785
+ * what the round sends. Under one checkpoint store, a second call that
1786
+ * sends the same thing gets the first call's reply and doesn't reach the
1787
+ * remote agent.
1788
+ *
1789
+ * The card is read once for each step value, on first use, and the step
1790
+ * streams when the card says the agent can and `stream` doesn't say
1791
+ * otherwise.
1792
+ */
1793
+ const ANY_ANSWER = { "~standard": {
1794
+ version: 1,
1795
+ vendor: "fascicle",
1796
+ validate: (value) => ({ value })
1797
+ } };
1798
+ /**
1799
+ * The parts a request sends: its text, then its data.
1800
+ */
1801
+ function request_parts(input) {
1802
+ if (typeof input === "string") return [text_part(input)];
1803
+ const parts = [];
1804
+ if (input.text !== void 0) parts.push(text_part(input.text));
1805
+ if (input.data !== void 0) parts.push(data_part(input.data));
1806
+ return parts;
1807
+ }
1808
+ /**
1809
+ * The parts an answer to a remote question sends: a string as text, and
1810
+ * anything else as data.
1811
+ */
1812
+ function answer_parts(answer) {
1813
+ return typeof answer === "string" ? [text_part(answer)] : [data_part(answer)];
1814
+ }
1815
+ /**
1816
+ * The checkpoint key of one round's send. It carries a digest of what the
1817
+ * round sends, so a step that runs for several inputs in one run keeps each
1818
+ * input's rounds apart.
1819
+ */
1820
+ function round_key(step_id, outgoing) {
1821
+ const sent = JSON.stringify([
1822
+ outgoing.task_id ?? "",
1823
+ outgoing.context_id ?? "",
1824
+ outgoing.parts
1825
+ ]);
1826
+ const digest = createHash("sha256").update(sent).digest("hex").slice(0, 16);
1827
+ return `a2a_step:${step_id}:${outgoing.round}:${digest}`;
1828
+ }
1829
+ /**
1830
+ * What the step resolves for a completed round.
1831
+ */
1832
+ function result_of(round) {
1833
+ const artifacts = from_plain(round.artifacts);
1834
+ const parts = artifacts.flatMap((artifact) => artifact.parts);
1835
+ return {
1836
+ task_id: round.task_id,
1837
+ context_id: round.context_id,
1838
+ text: text_of(parts),
1839
+ data: data_of(parts),
1840
+ artifacts
1841
+ };
1842
+ }
1843
+ /**
1844
+ * Reach the remote agent: read its card, and build a client that sends the
1845
+ * config's headers with every request to the configured URL's origin, the
1846
+ * card's included.
1847
+ */
1848
+ async function connect(config) {
1849
+ const sdk = await load_a2a_client();
1850
+ const fetch_with_headers = scoped_fetch(config.url, config.headers);
1851
+ const client = await new sdk.client.ClientFactory({
1852
+ transports: [new sdk.client.JsonRpcTransportFactory({ fetchImpl: fetch_with_headers })],
1853
+ cardResolver: new sdk.client.DefaultAgentCardResolver({ fetchImpl: fetch_with_headers })
1854
+ }).createFromUrl(config.url);
1855
+ const card = await client.getAgentCard();
1856
+ return {
1857
+ sdk,
1858
+ client,
1859
+ streams: config.stream ?? card.capabilities?.streaming === true
1860
+ };
1861
+ }
1862
+ /**
1863
+ * Build a step that sends its input to the A2A agent at `config.url` as one
1864
+ * message and resolves the task's artifacts.
1865
+ *
1866
+ * A string input is the message's text. An object's `text` and `data`
1867
+ * become a text part and a data part, and its `context_id` continues a
1868
+ * conversation with the remote agent. A task that ends failed, rejected,
1869
+ * canceled, or waiting for credentials throws `a2a_error` with the state
1870
+ * and the status text, and an abort cancels the remote task before the step
1871
+ * throws.
1872
+ */
1873
+ function a2a_step(config) {
1874
+ assert_valid_step_id(config.id, "a2a_step id", "put the label in name");
1875
+ const step_id = config.id;
1876
+ let remote;
1877
+ const reach = () => {
1878
+ remote ??= connect(config).catch((err) => {
1879
+ remote = void 0;
1880
+ throw err;
1881
+ });
1882
+ return remote;
1883
+ };
1884
+ const send = checkpoint(step(`${step_id}_send`, async (outgoing, ctx) => send_round(await reach(), step_id, outgoing, ctx)), {
1885
+ key: (outgoing) => round_key(step_id, outgoing),
1886
+ name: `${step_id} send`
1887
+ });
1888
+ const gates = /* @__PURE__ */ new Map();
1889
+ const gate_for = (round) => {
1890
+ const built = gates.get(round) ?? suspend({
1891
+ id: `${step_id}_${round}`,
1892
+ name: `${step_id} question ${round}`,
1893
+ on: () => {},
1894
+ resume_schema: ANY_ANSWER,
1895
+ combine: (_question, answer) => answer
1896
+ });
1897
+ gates.set(round, built);
1898
+ return built;
1899
+ };
1900
+ const ask = async (input, ctx) => {
1901
+ let outgoing = {
1902
+ round: 1,
1903
+ parts: request_parts(input),
1904
+ context_id: typeof input === "string" ? void 0 : input.context_id
1905
+ };
1906
+ for (;;) {
1907
+ const round = await ctx.call(send, outgoing);
1908
+ if (round.kind === "completed") return result_of(round);
1909
+ if (ctx.checkpoint_store === void 0) throw new a2a_error(`the remote agent asked a question (${JSON.stringify(round.text)}) and step "${step_id}" has no checkpoint store to wait with: drive the flow with durable(), or pass checkpoint_store to run()`, {
1910
+ state: "TASK_STATE_INPUT_REQUIRED",
1911
+ status_text: round.text,
1912
+ task_id: round.task_id
1913
+ });
1914
+ const answer = await ctx.call(gate_for(outgoing.round), round);
1915
+ outgoing = {
1916
+ round: outgoing.round + 1,
1917
+ parts: answer_parts(answer),
1918
+ task_id: round.task_id,
1919
+ context_id: round.context_id
1920
+ };
1921
+ }
1922
+ };
1923
+ return {
1924
+ ...step(step_id, ask, {
1925
+ side_effect: true,
1926
+ ...config.name === void 0 ? {} : { name: config.name },
1927
+ ...config.description === void 0 ? {} : { description: config.description }
1928
+ }),
1929
+ config: Object.freeze({
1930
+ remote: "a2a",
1931
+ url: config.url
1932
+ })
1933
+ };
1934
+ }
1935
+ // src/a2a/serve_a2a.ts
1936
+ /**
1937
+ * Process glue for serving a flow as an A2A agent over `node:http`.
1938
+ *
1939
+ * Binds `a2a_agent` to a real server: each request becomes a web `Request`
1940
+ * with its body streamed, and the agent's `Response` is piped back out,
1941
+ * server-sent events included. The server binds to `127.0.0.1` unless
1942
+ * `host` says otherwise, so reaching the network is a choice someone makes.
1943
+ *
1944
+ * SIGTERM and SIGINT stop new connections, close the agent (which aborts
1945
+ * every drive and waits for each to settle), dispose the engine, and exit
1946
+ * with the signal's code. The handlers are one-shot, so a second Ctrl-C
1947
+ * falls through to Node's default and kills the process outright when a
1948
+ * shutdown hangs.
1949
+ *
1950
+ * Stdout isn't the protocol here, so unlike `serve_acp`, the console stays
1951
+ * where it is.
1952
+ *
1953
+ * Excluded from mutation testing as process glue (see stryker.config.mjs);
1954
+ * the spawn test in `__tests__/e2e/` exercises it for real.
1955
+ */
1956
+ const DEFAULT_HOST = "127.0.0.1";
1957
+ /**
1958
+ * The web `Request` for a Node request, with its body streamed and its
1959
+ * signal aborted when the connection closes before the response has ended.
1960
+ */
1961
+ function web_request(incoming, outgoing, base) {
1962
+ const gone = new AbortController();
1963
+ outgoing.on("close", () => {
1964
+ if (!outgoing.writableFinished) gone.abort();
1965
+ });
1966
+ const headers = new Headers();
1967
+ for (const [name, value] of Object.entries(incoming.headers)) if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
1968
+ const has_body = incoming.method !== "GET" && incoming.method !== "HEAD";
1969
+ return new Request(new URL(incoming.url ?? "/", base), {
1970
+ method: incoming.method ?? "GET",
1971
+ headers,
1972
+ signal: gone.signal,
1973
+ ...has_body ? {
1974
+ body: Readable.toWeb(incoming),
1975
+ duplex: "half"
1976
+ } : {}
1977
+ });
1978
+ }
1979
+ /**
1980
+ * Write a web `Response` out through a Node response, a chunk at a time, so
1981
+ * a stream reaches the client as it's produced.
1982
+ */
1983
+ async function send(response, outgoing) {
1984
+ outgoing.writeHead(response.status, Object.fromEntries(response.headers));
1985
+ if (response.body === null) {
1986
+ outgoing.end();
1987
+ return;
1988
+ }
1989
+ const reader = response.body.getReader();
1990
+ outgoing.on("close", () => {
1991
+ reader.cancel().catch(() => {});
1992
+ });
1993
+ for (;;) {
1994
+ const { done, value } = await reader.read();
1995
+ if (done) break;
1996
+ outgoing.write(value);
1997
+ }
1998
+ outgoing.end();
1999
+ }
2000
+ /**
2001
+ * Answer one Node request with the agent's `fetch`. A handler that throws
2002
+ * answers 500, or just ends a response that has already begun.
2003
+ */
2004
+ async function answer(agent, incoming, outgoing, base) {
2005
+ try {
2006
+ await send(await agent.fetch(web_request(incoming, outgoing, base)), outgoing);
2007
+ } catch {
2008
+ if (outgoing.headersSent) {
2009
+ outgoing.end();
2010
+ return;
2011
+ }
2012
+ outgoing.writeHead(500, { "content-type": "application/json" });
2013
+ outgoing.end("{\"message\":\"internal error\"}");
2014
+ }
2015
+ }
2016
+ /**
2017
+ * Start listening, and resolve once the server has its address.
2018
+ */
2019
+ function listen(server, port, host) {
2020
+ return new Promise((resolve, reject) => {
2021
+ server.once("error", reject);
2022
+ server.listen(port, host, () => {
2023
+ server.off("error", reject);
2024
+ resolve(server.address());
2025
+ });
2026
+ });
2027
+ }
2028
+ /**
2029
+ * Serve a flow as an A2A agent over `node:http` until `close`, SIGTERM, or
2030
+ * SIGINT. Resolves the address it bound, the agent's `resume` for outside
2031
+ * events, and a `close` that stops taking connections, closes the agent, and
2032
+ * disposes the engine. A signal does the same, then exits with the signal's
2033
+ * code.
2034
+ */
2035
+ async function serve_a2a(config) {
2036
+ const agent = await a2a_agent(config);
2037
+ const host = config.host ?? DEFAULT_HOST;
2038
+ let base = `http://${host}`;
2039
+ const server = createServer((incoming, outgoing) => {
2040
+ answer(agent, incoming, outgoing, base);
2041
+ });
2042
+ const address = await listen(server, config.port, host);
2043
+ base = `http://${address.family === "IPv6" ? `[${address.address}]` : address.address}:${address.port}`;
2044
+ let closing;
2045
+ const shut_down = async () => {
2046
+ const stopped = new Promise((resolve) => {
2047
+ server.close(() => {
2048
+ resolve();
2049
+ });
2050
+ });
2051
+ await agent.close();
2052
+ server.closeAllConnections();
2053
+ await stopped;
2054
+ await config.engine?.dispose();
2055
+ };
2056
+ const on_signal = (signal) => {
2057
+ close().finally(() => process.exit(128 + constants.signals[signal]));
2058
+ };
2059
+ const close = () => {
2060
+ process.off("SIGTERM", on_signal);
2061
+ process.off("SIGINT", on_signal);
2062
+ closing ??= shut_down();
2063
+ return closing;
2064
+ };
2065
+ process.once("SIGTERM", on_signal);
2066
+ process.once("SIGINT", on_signal);
2067
+ return {
2068
+ url: base,
2069
+ resume: agent.resume,
2070
+ close
2071
+ };
2072
+ }
2073
+ // src/a2a/sqlite_task_store.ts
2074
+ const DEFAULT_TIMEOUT_MS = 5e3;
2075
+ const DEFAULT_PAGE_SIZE = 50;
2076
+ const SCHEMA = `
2077
+ CREATE TABLE IF NOT EXISTS a2a_tasks (
2078
+ tenant TEXT NOT NULL,
2079
+ owner TEXT NOT NULL,
2080
+ id TEXT NOT NULL,
2081
+ context_id TEXT NOT NULL,
2082
+ state INTEGER NOT NULL,
2083
+ status_at TEXT NOT NULL,
2084
+ status_ms INTEGER,
2085
+ task TEXT NOT NULL,
2086
+ PRIMARY KEY (tenant, owner, id)
2087
+ ) WITHOUT ROWID;
2088
+ CREATE INDEX IF NOT EXISTS a2a_tasks_by_time ON a2a_tasks (tenant, owner, status_at DESC, id DESC);
2089
+ CREATE INDEX IF NOT EXISTS a2a_tasks_by_context ON a2a_tasks (tenant, owner, context_id);
2090
+ `;
2091
+ /**
2092
+ * Whose rows a call may touch: the request's tenant and the caller's name,
2093
+ * with every unauthenticated caller in one shared scope, as in the SDK's own
2094
+ * stores.
2095
+ */
2096
+ function scope_of(context) {
2097
+ const name = context.user?.userName;
2098
+ return {
2099
+ tenant: context.tenant ?? "",
2100
+ owner: name === void 0 || name === "" ? "unknown" : name
2101
+ };
2102
+ }
2103
+ /**
2104
+ * Parse a stored row back into a task, or `undefined` for a row that holds
2105
+ * anything else.
2106
+ */
2107
+ function task_of(row) {
2108
+ const text = row?.["task"];
2109
+ if (typeof text !== "string") return void 0;
2110
+ return from_plain(JSON.parse(text));
2111
+ }
2112
+ /**
2113
+ * The epoch milliseconds of an ISO timestamp, or `null` when it isn't one.
2114
+ */
2115
+ function millis(timestamp) {
2116
+ const at = timestamp === void 0 ? NaN : Date.parse(timestamp);
2117
+ return Number.isNaN(at) ? null : at;
2118
+ }
2119
+ /**
2120
+ * Encode the last row of a page as the cursor for the next one.
2121
+ */
2122
+ function encode_cursor(cursor) {
2123
+ return Buffer.from(`${cursor.status_at}|${cursor.id}`).toString("base64");
2124
+ }
2125
+ /**
2126
+ * Read a page token back, or throw the SDK's `RequestMalformedError` for a
2127
+ * token this store didn't write.
2128
+ */
2129
+ async function decode_cursor(token) {
2130
+ const [status_at, ...rest] = Buffer.from(token, "base64").toString("utf8").split("|");
2131
+ if (status_at === void 0 || rest.length === 0) {
2132
+ const { errors } = await load_a2a_server();
2133
+ throw new errors.RequestMalformedError("Invalid page token format.");
2134
+ }
2135
+ return {
2136
+ status_at,
2137
+ id: rest.join("|")
2138
+ };
2139
+ }
2140
+ /**
2141
+ * The conditions a list request puts on the caller's rows, before paging.
2142
+ */
2143
+ function filter_of(params, scope) {
2144
+ const where = ["tenant = ?", "owner = ?"];
2145
+ const values = [scope.tenant, scope.owner];
2146
+ if (params.contextId) {
2147
+ where.push("context_id = ?");
2148
+ values.push(params.contextId);
2149
+ }
2150
+ if (params.status) {
2151
+ where.push("state = ?");
2152
+ values.push(params.status);
2153
+ }
2154
+ const after = millis(params.statusTimestampAfter);
2155
+ if (after !== null) {
2156
+ where.push("status_ms > ?");
2157
+ values.push(after);
2158
+ }
2159
+ return {
2160
+ where: where.join(" AND "),
2161
+ values
2162
+ };
2163
+ }
2164
+ /**
2165
+ * Open the database at `path` in WAL mode with a busy timeout, and make the
2166
+ * task table when it isn't there.
2167
+ */
2168
+ function open_tasks(config) {
2169
+ const { DatabaseSync } = process.getBuiltinModule("node:sqlite");
2170
+ const db = new DatabaseSync(config.path);
2171
+ const timeout_ms = config.timeout_ms ?? DEFAULT_TIMEOUT_MS;
2172
+ db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.trunc(timeout_ms))}`);
2173
+ db.exec("PRAGMA journal_mode = WAL");
2174
+ db.exec(SCHEMA);
2175
+ return db;
2176
+ }
2177
+ /**
2178
+ * Build a `TaskStore` over a SQLite database, for `a2a_agent`'s
2179
+ * `task_store`. It can share its file with a `sqlite_store`. `close` closes
2180
+ * the database.
2181
+ */
2182
+ function sqlite_task_store(config) {
2183
+ const db = open_tasks(config);
2184
+ const select = db.prepare("SELECT task FROM a2a_tasks WHERE tenant = ? AND owner = ? AND id = ?");
2185
+ const upsert = db.prepare(`INSERT INTO a2a_tasks (tenant, owner, id, context_id, state, status_at, status_ms, task)
2186
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
2187
+ ON CONFLICT (tenant, owner, id) DO UPDATE SET
2188
+ context_id = excluded.context_id, state = excluded.state, status_at = excluded.status_at,
2189
+ status_ms = excluded.status_ms, task = excluded.task`);
2190
+ return {
2191
+ load: async (task_id, context) => {
2192
+ const { tenant, owner } = scope_of(context);
2193
+ return task_of(select.get(tenant, owner, task_id));
2194
+ },
2195
+ save: async (task, context) => {
2196
+ const { tenant, owner } = scope_of(context);
2197
+ const timestamp = task.status?.timestamp;
2198
+ upsert.run(tenant, owner, task.id, task.contextId, task.status?.state ?? 0, timestamp ?? "", millis(timestamp), JSON.stringify(to_plain(task)));
2199
+ },
2200
+ list: async (params, context) => {
2201
+ const page_size = params.pageSize ?? DEFAULT_PAGE_SIZE;
2202
+ const filter = filter_of(params, scope_of(context));
2203
+ const total = db.prepare(`SELECT COUNT(*) AS n FROM a2a_tasks WHERE ${filter.where}`).get(...filter.values);
2204
+ const cursor = params.pageToken ? await decode_cursor(params.pageToken) : void 0;
2205
+ const paged = cursor === void 0 ? "" : " AND (status_at, id) < (?, ?)";
2206
+ const rows = db.prepare(`SELECT status_at, id, task FROM a2a_tasks WHERE ${filter.where}${paged}
2207
+ ORDER BY status_at DESC, id DESC LIMIT ?`).all(...filter.values, ...cursor === void 0 ? [] : [cursor.status_at, cursor.id], page_size + 1);
2208
+ const page = rows.slice(0, page_size);
2209
+ const last = page.at(-1);
2210
+ return {
2211
+ tasks: page.flatMap((row) => {
2212
+ const task = task_of(row);
2213
+ if (task === void 0) return [];
2214
+ return [params.includeArtifacts === true ? task : {
2215
+ ...task,
2216
+ artifacts: []
2217
+ }];
2218
+ }),
2219
+ nextPageToken: rows.length > page_size && last !== void 0 ? encode_cursor({
2220
+ status_at: String(last["status_at"]),
2221
+ id: String(last["id"])
2222
+ }) : "",
2223
+ pageSize: page_size,
2224
+ totalSize: Number(total?.["n"] ?? 0)
2225
+ };
2226
+ },
2227
+ close: () => {
2228
+ db.close();
2229
+ }
2230
+ };
2231
+ }
2232
+ export { a2a_agent, a2a_error, a2a_sdk_missing_error, a2a_step, create_a2a_mapper_state, end_task_events, failure_message, serve_a2a, sqlite_task_store, to_task_events };
2233
+
2234
+ //# sourceMappingURL=a2a.js.map