experimental-a2 0.2.0 → 0.4.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 (92) hide show
  1. package/CHANGELOG.md +169 -0
  2. package/dist/ai-B4YhEnfw.d.ts +333 -0
  3. package/dist/ai-server.d.ts +48 -9
  4. package/dist/ai-server.js +121 -49
  5. package/dist/ai.d.ts +2 -303
  6. package/dist/ai.js +231 -86
  7. package/dist/cli-B3VuxoDe.js +597 -0
  8. package/dist/cli-bin.d.ts +1 -0
  9. package/dist/cli-bin.js +5 -0
  10. package/dist/cli.d.ts +19 -0
  11. package/dist/cli.js +2 -0
  12. package/dist/client-BrfDXQ8A.d.ts +155 -0
  13. package/dist/client-Bt4tAKi9.js +798 -0
  14. package/dist/client.d.ts +2 -90
  15. package/dist/client.js +1 -409
  16. package/dist/{contract-CG_adnu_.js → contract-48bUMgcL.js} +10 -2
  17. package/dist/{contract-C_3dIIEU.d.ts → contract-jIfaR085.d.ts} +62 -8
  18. package/dist/devtools-J_jZ2vQf.d.ts +151 -0
  19. package/dist/devtools-kJJaORn-.js +338 -0
  20. package/dist/devtools-server.browser.js +1 -1
  21. package/dist/devtools-server.d.ts +2 -2
  22. package/dist/devtools-server.js +224 -43
  23. package/dist/devtools.d.ts +2 -0
  24. package/dist/devtools.js +2 -0
  25. package/dist/{errors-BJRMd-h6.js → errors-BQuJpe82.js} +4 -4
  26. package/dist/{errors-xL_JTXsY.d.ts → errors-W6nwJ-fm.d.ts} +1 -1
  27. package/dist/http.d.ts +71 -13
  28. package/dist/http.js +302 -41
  29. package/dist/{idempotent-replay-BMyHrP0L.js → idempotent-replay-DuqEkYA7.js} +2 -2
  30. package/dist/index.d.ts +5 -5
  31. package/dist/index.js +2 -2
  32. package/dist/{inspection-E7qbD0Xj.js → inspection-DaxB5jM2.js} +2 -1
  33. package/dist/internal-aEotMzu_.js +209 -0
  34. package/dist/otel.d.ts +1 -1
  35. package/dist/platform-B4TnJtWu.js +32 -0
  36. package/dist/react.d.ts +37 -14
  37. package/dist/react.js +26 -15
  38. package/dist/scheduler-qstash.d.ts +78 -0
  39. package/dist/scheduler-qstash.js +499 -0
  40. package/dist/scheduler-task-BpzhPnRS.js +54 -0
  41. package/dist/{recovery-vercel.d.ts → scheduler-vercel.d.ts} +17 -24
  42. package/dist/scheduler-vercel.js +226 -0
  43. package/dist/server-CcNnFnoW.js +1405 -0
  44. package/dist/server-YtPq7hjw.d.ts +260 -0
  45. package/dist/server.d.ts +4 -155
  46. package/dist/server.js +2 -2
  47. package/dist/{log-ldf5g8Cx.d.ts → store-C3sNAaBT.d.ts} +111 -35
  48. package/dist/{log-yJbXUf72.js → store-N8PXxDAS.js} +1 -1
  49. package/dist/store-codec-DTG0Ftek.js +8 -0
  50. package/dist/store-memory.d.ts +11 -0
  51. package/dist/{log-memory.js → store-memory.js} +127 -24
  52. package/dist/{log-polling-6COoN60V.js → store-polling-DgrrAE3d.js} +7 -6
  53. package/dist/{log-postgres.d.ts → store-postgres.d.ts} +6 -6
  54. package/dist/{log-postgres.js → store-postgres.js} +158 -24
  55. package/dist/{log-redis.js → store-redis-core-DWqx3F47.js} +294 -156
  56. package/dist/store-redis-http.d.ts +21 -0
  57. package/dist/store-redis-http.js +70 -0
  58. package/dist/store-redis.d.ts +37 -0
  59. package/dist/store-redis.js +298 -0
  60. package/dist/{log-sqlite.d.ts → store-sqlite.d.ts} +6 -6
  61. package/dist/{log-sqlite.js → store-sqlite.js} +116 -22
  62. package/dist/{telemetry-Cso0qyHQ.d.ts → telemetry-BjYHTfh2.d.ts} +1 -1
  63. package/dist/testing.browser.d.ts +1 -0
  64. package/dist/testing.browser.js +4 -0
  65. package/dist/testing.d.ts +31 -0
  66. package/dist/testing.js +101 -0
  67. package/dist/wire-DCUZBUlT.js +222 -0
  68. package/docs/01-quickstart.mdx +4 -5
  69. package/docs/concepts/01-contracts.mdx +21 -17
  70. package/docs/concepts/02-handlers.mdx +7 -7
  71. package/docs/concepts/03-durability.mdx +26 -29
  72. package/docs/concepts/04-state.mdx +18 -21
  73. package/docs/guides/01-timers.mdx +154 -54
  74. package/docs/guides/02-cancellation.mdx +30 -4
  75. package/docs/guides/03-react.mdx +20 -21
  76. package/docs/guides/04-local-first.mdx +1 -1
  77. package/docs/guides/05-production.mdx +321 -60
  78. package/docs/guides/06-ai-agents.mdx +249 -49
  79. package/docs/guides/07-devtools.mdx +137 -12
  80. package/docs/guides/08-application-data.mdx +1 -1
  81. package/docs/guides/09-presence.mdx +284 -0
  82. package/docs/guides/10-transports.mdx +131 -0
  83. package/docs/index.mdx +22 -46
  84. package/docs/reference/01-api.mdx +751 -102
  85. package/docs/reference/02-errors.mdx +10 -5
  86. package/package.json +23 -6
  87. package/dist/internal-D6wNxTck.js +0 -36
  88. package/dist/log-memory.d.ts +0 -11
  89. package/dist/log-redis.d.ts +0 -31
  90. package/dist/recovery-vercel.js +0 -119
  91. package/dist/server-DJgD2YWP.js +0 -877
  92. package/dist/wire-BVsgR8o9.js +0 -62
package/dist/ai-server.js CHANGED
@@ -1,5 +1,7 @@
1
- import { t as A2Error } from "./errors-BJRMd-h6.js";
2
- import { t as createServer } from "./server-DJgD2YWP.js";
1
+ import { t as A2Error } from "./errors-BQuJpe82.js";
2
+ import { m as installAmbientToolScopeStorage, p as consumeSchedulerSendFailure } from "./internal-aEotMzu_.js";
3
+ import { t as createServer } from "./server-CcNnFnoW.js";
4
+ import { AsyncLocalStorage } from "node:async_hooks";
3
5
  import { convertToModelMessages, stepCountIs, streamText, toUIMessageStream } from "ai";
4
6
  //#region src/ai-sdk-step.ts
5
7
  const CONTROLLED_SETTINGS = [
@@ -19,8 +21,7 @@ const CONTROLLED_SETTINGS = [
19
21
  "prepareStep",
20
22
  "stopWhen",
21
23
  "system",
22
- "tools",
23
- "toolsContext"
24
+ "tools"
24
25
  ];
25
26
  const safeSettings = (settings) => {
26
27
  const result = { ...settings };
@@ -72,7 +73,8 @@ async function generateAISDKStep(input) {
72
73
  tools,
73
74
  originalMessages: input.messages,
74
75
  generateMessageId: () => input.responseMessageId,
75
- onError: errorMessage$1
76
+ onError: errorMessage$1,
77
+ ...input.messageMetadata === void 0 ? {} : { messageMetadata: input.messageMetadata }
76
78
  }),
77
79
  completion() {
78
80
  if (fatalError !== void 0) throw fatalError.value;
@@ -95,13 +97,15 @@ const foldCoordinator = (state, event) => {
95
97
  queued: []
96
98
  };
97
99
  case "ai.message.created": {
98
- const message = event.payload.message;
100
+ const payload = event.payload;
101
+ const message = payload.message;
99
102
  if (message.role !== "user") return state;
100
103
  return {
101
104
  ...state,
102
105
  queued: [...state.queued.filter((item) => item.messageId !== message.id), {
103
106
  index: event.index,
104
- messageId: message.id
107
+ messageId: message.id,
108
+ generate: payload.generate !== false
105
109
  }].toSorted((left, right) => left.index - right.index)
106
110
  };
107
111
  }
@@ -109,9 +113,10 @@ const foldCoordinator = (state, event) => {
109
113
  const request = event.payload;
110
114
  if (request.reason === "message") {
111
115
  const responseMessageId = request.responseMessageId ?? `${request.messageId}:assistant`;
116
+ const requested = state.queued.find((item) => item.messageId === request.messageId);
112
117
  return {
113
118
  ...state,
114
- queued: state.queued.filter((item) => item.messageId !== request.messageId),
119
+ queued: requested === void 0 ? state.queued.filter((item) => item.messageId !== request.messageId) : state.queued.filter((item) => item.index > requested.index),
115
120
  response: {
116
121
  rootMessageId: request.messageId,
117
122
  responseMessageId,
@@ -177,7 +182,7 @@ const foldCoordinator = (state, event) => {
177
182
  case "ai.message.interrupted": {
178
183
  const interruption = event.payload;
179
184
  const response = state.response;
180
- return response?.responseMessageId === interruption.messageId && (interruption.generationId === void 0 || interruption.generationId === response.generation?.generationId) ? {
185
+ return response?.responseMessageId === interruption.messageId && (interruption.generationId === response.generation?.generationId || interruption.requestId === response.activeRequestId) ? {
181
186
  closed: state.closed,
182
187
  queued: state.queued
183
188
  } : state;
@@ -255,7 +260,7 @@ const foldCoordinator = (state, event) => {
255
260
  }
256
261
  };
257
262
  const aiCoordinatorReducer = (contract) => contract.reducer({
258
- name: "a2.ai.coordinator.v1",
263
+ name: "a2.ai.coordinator.v3",
259
264
  initialState: {
260
265
  closed: false,
261
266
  queued: []
@@ -288,8 +293,18 @@ const modelName = (model) => {
288
293
  return "custom";
289
294
  };
290
295
  const errorMessage = (error) => error instanceof Error ? error.message : String(error);
296
+ const toolScopeStorage = installAmbientToolScopeStorage(() => new AsyncLocalStorage());
297
+ /** Run `fn` with `ctx` as the ambient tool handler context, for direct tool tests. */
298
+ function runWithHandlerContext(ctx, fn) {
299
+ return toolScopeStorage.run({ context: ctx }, fn);
300
+ }
291
301
  const promptCacheKey = (sessionId, generationId) => `${sessionId}\u001f${generationId}`;
292
- const isAsyncIterable = (value) => typeof value === "object" && value !== null && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
302
+ const asyncIterator = (value) => {
303
+ if (typeof value !== "object" || value === null) return void 0;
304
+ const factory = Reflect.get(value, Symbol.asyncIterator);
305
+ if (typeof factory !== "function") return void 0;
306
+ return factory.call(value);
307
+ };
293
308
  const isBoundaryChunk = (chunk) => chunk !== void 0 && (chunk.type === "text-end" || chunk.type === "reasoning-end" || chunk.type === "tool-input-available" || chunk.type === "tool-input-error" || chunk.type === "tool-output-available" || chunk.type === "tool-output-error" || chunk.type === "tool-output-denied" || chunk.type === "tool-approval-request" || chunk.type === "finish" || chunk.type === "abort" || chunk.type === "error");
294
309
  const nextOrTimer = async (next, delayMs) => {
295
310
  let timer;
@@ -305,7 +320,7 @@ const nextOrTimer = async (next, delayMs) => {
305
320
  if (timer !== void 0) clearTimeout(timer);
306
321
  }
307
322
  };
308
- async function generateWithAISDK(context) {
323
+ async function generateWithAISDK(context, messageMetadata) {
309
324
  const step = await generateAISDKStep({
310
325
  model: context.model,
311
326
  tools: context.tools,
@@ -313,7 +328,11 @@ async function generateWithAISDK(context) {
313
328
  responseMessageId: context.responseMessageId,
314
329
  abortSignal: context.signal,
315
330
  ...context.instructions === void 0 ? {} : { instructions: context.instructions },
316
- settings: context.generation
331
+ settings: context.generation,
332
+ ...messageMetadata === void 0 ? {} : { messageMetadata: ({ part }) => messageMetadata({
333
+ ...context,
334
+ part
335
+ }) }
317
336
  });
318
337
  return {
319
338
  stream: step.stream,
@@ -408,6 +427,10 @@ const activeContextMessages = (state, coordinator) => {
408
427
  const queued = new Set(coordinator.queued.map((item) => item.messageId));
409
428
  return contextMessages(state).filter((message) => !queued.has(message.id));
410
429
  };
430
+ const generationRequestId = (generationId) => {
431
+ const markerIndex = generationId.lastIndexOf(":generation:");
432
+ return markerIndex === -1 ? void 0 : generationId.slice(0, markerIndex);
433
+ };
411
434
  const toolCalledEvent = (payload) => ({
412
435
  type: "ai.tool.called",
413
436
  id: `${payload.generationId}:tool:${payload.toolCallId}:called`,
@@ -576,15 +599,27 @@ const lifecycleEvents = (options) => {
576
599
  };
577
600
  };
578
601
  function queuedMessagesAt(history) {
579
- const started = new Set(history.filter((event) => event.type === "ai.generation.requested").map((event) => event.payload).filter((request) => request.reason === "message").map((request) => request.messageId));
580
- return history.flatMap((event) => {
581
- if (event.type !== "ai.message.created") return [];
582
- const message = event.payload.message;
583
- return message.role === "user" && !started.has(message.id) ? [{
584
- index: event.index,
585
- messageId: message.id
586
- }] : [];
587
- });
602
+ const queued = [];
603
+ for (const event of history) {
604
+ if (event.type === "ai.message.created") {
605
+ const payload = event.payload;
606
+ if (payload.message.role !== "user") continue;
607
+ const duplicate = queued.findIndex((item) => item.messageId === payload.message.id);
608
+ if (duplicate !== -1) queued.splice(duplicate, 1);
609
+ queued.push({
610
+ index: event.index,
611
+ messageId: payload.message.id,
612
+ generate: payload.generate !== false
613
+ });
614
+ continue;
615
+ }
616
+ if (event.type !== "ai.generation.requested") continue;
617
+ const request = event.payload;
618
+ if (request.reason !== "message") continue;
619
+ const requested = queued.findIndex((item) => item.messageId === request.messageId);
620
+ if (requested !== -1) queued.splice(0, requested + 1);
621
+ }
622
+ return queued;
588
623
  }
589
624
  function withoutGenerationLifecycle(history, generationIds) {
590
625
  if (generationIds.size === 0) return history;
@@ -612,10 +647,10 @@ function createHandlers(options) {
612
647
  if (options.model === void 0) throw new TypeError("createHandlers requires model");
613
648
  if (options.progress?.maxChunks !== void 0 && (!Number.isInteger(options.progress.maxChunks) || options.progress.maxChunks < 1)) throw new TypeError("progress.maxChunks must be a positive integer");
614
649
  if (options.progress?.maxDelayMs !== void 0 && (!Number.isFinite(options.progress.maxDelayMs) || options.progress.maxDelayMs < 0)) throw new TypeError("progress.maxDelayMs must be a non-negative number");
615
- if (options.maxSteps !== void 0 && (!Number.isInteger(options.maxSteps) || options.maxSteps < 1)) throw new TypeError("maxSteps must be a positive integer");
650
+ if (options.maxSteps !== void 0 && options.maxSteps !== Number.POSITIVE_INFINITY && (!Number.isInteger(options.maxSteps) || options.maxSteps < 1)) throw new TypeError("maxSteps must be a positive integer or Infinity");
616
651
  const tools = options.tools ?? {};
617
652
  const generation = options.generation ?? {};
618
- const maxSteps = options.maxSteps ?? 20;
653
+ const maxSteps = options.maxSteps ?? Number.POSITIVE_INFINITY;
619
654
  const coordinator = aiCoordinatorReducer(options.agent.contract);
620
655
  const promptCache = /* @__PURE__ */ new Map();
621
656
  const coordinatorStateAt = (history, frontier = Number.POSITIVE_INFINITY) => {
@@ -628,7 +663,7 @@ function createHandlers(options) {
628
663
  };
629
664
  const requestForNextMessage = (state) => {
630
665
  if (state.closed || state.response !== void 0) return void 0;
631
- const next = state.queued[0];
666
+ const next = state.queued.find((item) => item.generate !== false);
632
667
  if (next === void 0) return void 0;
633
668
  return {
634
669
  type: "ai.generation.requested",
@@ -710,36 +745,72 @@ function createHandlers(options) {
710
745
  });
711
746
  return computation;
712
747
  };
713
- const executeTool = async (ctx, call) => {
714
- const tool = tools[call.toolName];
715
- if (tool?.execute === void 0) return resultEvent(call, "execution:error", { error: `Tool '${call.toolName}' has no server executor` });
716
- const messages = await promptMessages(ctx.event.sessionId, call, ctx.session.history);
748
+ const toolExecutionFailure = (ctx, call, error) => {
749
+ const schedulerFailure = consumeSchedulerSendFailure(error);
750
+ if (ctx.signal.aborted) return;
751
+ if (schedulerFailure === "retryable") throw error;
752
+ return resultEvent(call, "execution:error", { error: errorMessage(error) });
753
+ };
754
+ const runToolExecution = async (ctx, call, execute, messages) => {
717
755
  let output;
718
756
  try {
719
- output = await tool.execute(call.input, {
757
+ output = await execute(call.input, {
720
758
  toolCallId: call.toolCallId,
721
759
  messages,
722
- abortSignal: ctx.signal,
723
- context: void 0
760
+ abortSignal: ctx.signal
724
761
  });
725
762
  } catch (error) {
726
- if (ctx.signal.aborted) return;
727
- return resultEvent(call, "execution:error", { error: errorMessage(error) });
763
+ return toolExecutionFailure(ctx, call, error);
728
764
  }
729
- if (!isAsyncIterable(output)) return resultEvent(call, "execution:0", { output });
765
+ let iterator;
766
+ try {
767
+ iterator = asyncIterator(output);
768
+ } catch (error) {
769
+ return toolExecutionFailure(ctx, call, error);
770
+ }
771
+ if (iterator === void 0) return resultEvent(call, "execution:0", { output });
730
772
  let last;
731
773
  let sequence = 0;
732
- for await (const value of output) {
733
- if (ctx.signal.aborted) return;
734
- last = value;
735
- await ctx.session.append(`tool:${call.toolCallId}:preliminary:${sequence}`, resultEvent(call, `execution:${sequence}:preliminary`, {
736
- output: value,
737
- preliminary: true
738
- }));
774
+ for (;;) {
775
+ let result;
776
+ try {
777
+ result = await iterator.next();
778
+ } catch (error) {
779
+ return toolExecutionFailure(ctx, call, error);
780
+ }
781
+ if (result.done) break;
782
+ if (ctx.signal.aborted) {
783
+ try {
784
+ await iterator.return?.();
785
+ } catch {}
786
+ return;
787
+ }
788
+ last = result.value;
789
+ try {
790
+ await ctx.session.append(`tool:${call.toolCallId}:preliminary:${sequence}`, resultEvent(call, `execution:${sequence}:preliminary`, {
791
+ output: result.value,
792
+ preliminary: true
793
+ }));
794
+ } catch (error) {
795
+ try {
796
+ await iterator.return?.();
797
+ } catch {}
798
+ throw error;
799
+ }
739
800
  sequence += 1;
740
801
  }
741
802
  return resultEvent(call, `execution:${sequence}:final`, sequence === 0 ? {} : { output: last });
742
803
  };
804
+ const executeTool = async (ctx, call) => {
805
+ const execute = tools[call.toolName]?.execute;
806
+ if (execute === void 0) return resultEvent(call, "execution:error", { error: `Tool '${call.toolName}' has no server executor` });
807
+ const messages = await promptMessages(ctx.event.sessionId, call, ctx.session.history);
808
+ const scope = {
809
+ contract: options.agent.contract,
810
+ context: ctx
811
+ };
812
+ return toolScopeStorage.run(scope, () => runToolExecution(ctx, call, execute, messages));
813
+ };
743
814
  const handleToolCall = async (ctx) => {
744
815
  const response = (await ctx.session.state(coordinator)).state.response;
745
816
  const current = response?.calls.find((candidate) => candidate.index === ctx.event.index);
@@ -914,7 +985,7 @@ function createHandlers(options) {
914
985
  };
915
986
  const custom = options.generate !== void 0;
916
987
  const updates = consumeGeneration({
917
- source: options.generate === void 0 ? await generateWithAISDK(generateContext) : { stream: await options.generate(generateContext) },
988
+ source: options.generate === void 0 ? await generateWithAISDK(generateContext, options.messageMetadata) : { stream: await options.generate(generateContext) },
918
989
  ...options.progress === void 0 ? {} : { progress: options.progress }
919
990
  });
920
991
  let sequence = 0;
@@ -1008,7 +1079,7 @@ function createHandlers(options) {
1008
1079
  }
1009
1080
  };
1010
1081
  const handleMessageCreated = async (ctx) => {
1011
- if (ctx.event.payload.message.role !== "user") return;
1082
+ if (ctx.event.payload.message.role !== "user" || ctx.event.payload.generate === false) return;
1012
1083
  return scheduleNext(ctx);
1013
1084
  };
1014
1085
  const handleRetry = async (ctx) => {
@@ -1071,7 +1142,7 @@ function createHandlers(options) {
1071
1142
  abortOn: {
1072
1143
  "ai.message.interrupted": (event, trigger, context) => {
1073
1144
  const responseMessageId = trigger.payload.responseMessageId ?? (trigger.payload.reason === "message" ? `${trigger.payload.messageId}:assistant` : trigger.payload.messageId);
1074
- return event.payload.messageId === responseMessageId && (event.payload.generationId === void 0 || event.payload.generationId === `${trigger.id}:generation:${context.attempt}`);
1145
+ return event.payload.messageId === responseMessageId && (event.payload.requestId === trigger.id || event.payload.generationId === `${trigger.id}:generation:${context.attempt}`);
1075
1146
  },
1076
1147
  "ai.session.closed": true
1077
1148
  },
@@ -1081,7 +1152,7 @@ function createHandlers(options) {
1081
1152
  "ai.tool.called": {
1082
1153
  abortOn: {
1083
1154
  "ai.generation.failed": (event, trigger) => event.payload.generationId === trigger.payload.generationId,
1084
- "ai.message.interrupted": (event, trigger) => event.payload.messageId === trigger.payload.messageId && (event.payload.generationId === void 0 || event.payload.generationId === trigger.payload.generationId),
1155
+ "ai.message.interrupted": (event, trigger) => event.payload.messageId === trigger.payload.messageId && (event.payload.requestId === trigger.payload.requestId || event.payload.generationId === trigger.payload.generationId),
1085
1156
  "ai.session.closed": true
1086
1157
  },
1087
1158
  handler: handleToolCall
@@ -1089,7 +1160,7 @@ function createHandlers(options) {
1089
1160
  "ai.approval.responded": {
1090
1161
  abortOn: {
1091
1162
  "ai.generation.failed": (event, trigger) => event.payload.responseMessageId === trigger.payload.messageId && event.payload.generationId === trigger.payload.generationId,
1092
- "ai.message.interrupted": (event, trigger) => event.payload.messageId === trigger.payload.messageId && (event.payload.generationId === void 0 || event.payload.generationId === trigger.payload.generationId),
1163
+ "ai.message.interrupted": (event, trigger) => event.payload.messageId === trigger.payload.messageId && (event.payload.requestId === generationRequestId(trigger.payload.generationId) || event.payload.generationId === trigger.payload.generationId),
1093
1164
  "ai.session.closed": true
1094
1165
  },
1095
1166
  handler: handleApproval
@@ -1102,7 +1173,7 @@ function createHandlers(options) {
1102
1173
  }
1103
1174
  /** Assemble an A2 server with the built-in agent handlers and app extensions. */
1104
1175
  function createAgentServer(options) {
1105
- const { agent: definition, model, tools, instructions, generation, maxSteps, generate, compaction, progress, handlers, ...serverOptions } = options;
1176
+ const { agent: definition, model, tools, instructions, generation, maxSteps, messageMetadata, generate, compaction, progress, handlers, ...serverOptions } = options;
1106
1177
  const builtIns = createHandlers({
1107
1178
  agent: definition,
1108
1179
  model,
@@ -1110,6 +1181,7 @@ function createAgentServer(options) {
1110
1181
  ...instructions === void 0 ? {} : { instructions },
1111
1182
  ...generation === void 0 ? {} : { generation },
1112
1183
  ...maxSteps === void 0 ? {} : { maxSteps },
1184
+ ...messageMetadata === void 0 ? {} : { messageMetadata },
1113
1185
  ...generate === void 0 ? {} : { generate },
1114
1186
  ...compaction === void 0 ? {} : { compaction },
1115
1187
  ...progress === void 0 ? {} : { progress }
@@ -1125,4 +1197,4 @@ function createAgentServer(options) {
1125
1197
  });
1126
1198
  }
1127
1199
  //#endregion
1128
- export { createAgentServer, createHandlers, validateAgentPush };
1200
+ export { createAgentServer, createHandlers, runWithHandlerContext, validateAgentPush };
package/dist/ai.d.ts CHANGED
@@ -1,303 +1,2 @@
1
- import { a as EventDefs, c as Reducer, n as Contract, t as AppendInput, u as StandardSchemaV1 } from "./contract-C_3dIIEU.js";
2
- import { FinishReason, JSONValue, LanguageModelUsage, UIMessage, UIMessageChunk } from "ai";
3
- //#region src/ai.d.ts
4
- type AgentStatus = "idle" | "generating" | "waiting" | "failed" | "closed";
5
- type GenerationReason = "message" | "tool" | "input" | "retry";
6
- type SessionCreatedPayload = {
7
- metadata?: JSONValue;
8
- };
9
- type SessionClosedPayload = {
10
- reason?: string;
11
- };
12
- type MessageCreatedPayload<M extends UIMessage> = {
13
- message: M;
14
- };
15
- type MessageCompletedPayload = {
16
- messageId: string;
17
- };
18
- type MessageInterruptedPayload = {
19
- messageId: string;
20
- generationId?: string;
21
- reason?: string;
22
- /** Last confirmed log index visible to the interrupter. */
23
- lastSeenIndex?: number;
24
- };
25
- type GenerationRequestedPayload = {
26
- messageId: string;
27
- reason: GenerationReason;
28
- responseMessageId?: string;
29
- };
30
- type RetryGenerationOptions = {
31
- messageId: string;
32
- responseMessageId: string;
33
- retryId: string;
34
- };
35
- type RetryRequestedPayload = RetryGenerationOptions;
36
- type GenerationStartedPayload = {
37
- requestId: string;
38
- messageId: string;
39
- generationId: string;
40
- responseMessageId: string;
41
- attempt: number;
42
- model: string;
43
- };
44
- type GenerationProgressPayload = {
45
- requestId: string;
46
- messageId: string;
47
- generationId: string;
48
- responseMessageId: string;
49
- sequence: number;
50
- chunks: UIMessageChunk[];
51
- };
52
- type GenerationCompletedPayload = {
53
- requestId: string;
54
- messageId: string;
55
- generationId: string;
56
- responseMessageId: string;
57
- finishReason?: FinishReason;
58
- usage?: LanguageModelUsage;
59
- };
60
- type GenerationFailedPayload = {
61
- requestId: string;
62
- messageId: string;
63
- generationId: string;
64
- responseMessageId: string;
65
- error: string;
66
- /** True when a later attempt replaced an incomplete attempt. */
67
- superseded?: boolean;
68
- stepLimit?: boolean;
69
- };
70
- type ToolCalledPayload = {
71
- requestId: string;
72
- messageId: string;
73
- generationId: string;
74
- toolCallId: string;
75
- toolName: string;
76
- input: unknown;
77
- dynamic?: boolean;
78
- providerExecuted?: boolean;
79
- supportsDeferredResults?: boolean;
80
- providerMetadata?: unknown;
81
- toolMetadata?: unknown;
82
- title?: string;
83
- };
84
- type ToolResultPayload = {
85
- requestId: string;
86
- messageId: string;
87
- generationId: string;
88
- toolCallId: string;
89
- toolName?: string;
90
- input?: unknown;
91
- rawInput?: unknown;
92
- output?: unknown;
93
- error?: string;
94
- denied?: boolean;
95
- preliminary?: boolean;
96
- phase?: "input" | "execution";
97
- dynamic?: boolean;
98
- providerExecuted?: boolean;
99
- providerMetadata?: unknown;
100
- toolMetadata?: unknown;
101
- };
102
- type ApprovalRequestedPayload = {
103
- messageId: string;
104
- generationId: string;
105
- approvalId: string;
106
- toolCallId: string;
107
- isAutomatic?: boolean;
108
- signature?: string;
109
- };
110
- type ApprovalRespondedPayload = {
111
- messageId: string;
112
- generationId: string;
113
- approvalId: string;
114
- approved: boolean;
115
- reason?: string;
116
- };
117
- type InputRequestedPayload = {
118
- messageId: string;
119
- generationId: string;
120
- inputId: string;
121
- name: string;
122
- question?: JSONValue;
123
- };
124
- type InputRespondedPayload = {
125
- messageId: string;
126
- generationId: string;
127
- inputId: string;
128
- name: string;
129
- value: JSONValue;
130
- };
131
- type CompactionRequestedPayload = {
132
- generationId: string;
133
- throughMessageId: string;
134
- };
135
- type CompactionCompletedPayload<M extends UIMessage> = {
136
- generationId: string;
137
- throughMessageId: string;
138
- messages: M[];
139
- retainedMessageIds?: string[];
140
- };
141
- type AIEventDefs<M extends UIMessage = UIMessage> = {
142
- "ai.session.created": StandardSchemaV1<SessionCreatedPayload>;
143
- "ai.session.closed": StandardSchemaV1<SessionClosedPayload>;
144
- "ai.message.created": StandardSchemaV1<MessageCreatedPayload<M>>;
145
- "ai.message.completed": StandardSchemaV1<MessageCompletedPayload>;
146
- "ai.message.interrupted": StandardSchemaV1<MessageInterruptedPayload>;
147
- "ai.generation.requested": StandardSchemaV1<GenerationRequestedPayload>;
148
- "ai.retry.requested": StandardSchemaV1<RetryRequestedPayload>;
149
- "ai.generation.started": StandardSchemaV1<GenerationStartedPayload>;
150
- "ai.generation.progress": StandardSchemaV1<GenerationProgressPayload>;
151
- "ai.generation.completed": StandardSchemaV1<GenerationCompletedPayload>;
152
- "ai.generation.failed": StandardSchemaV1<GenerationFailedPayload>;
153
- "ai.tool.called": StandardSchemaV1<ToolCalledPayload>;
154
- "ai.tool.result": StandardSchemaV1<ToolResultPayload>;
155
- "ai.approval.requested": StandardSchemaV1<ApprovalRequestedPayload>;
156
- "ai.approval.responded": StandardSchemaV1<ApprovalRespondedPayload>;
157
- "ai.input.requested": StandardSchemaV1<InputRequestedPayload>;
158
- "ai.input.responded": StandardSchemaV1<InputRespondedPayload>;
159
- "ai.compaction.requested": StandardSchemaV1<CompactionRequestedPayload>;
160
- "ai.compaction.completed": StandardSchemaV1<CompactionCompletedPayload<M>>;
161
- };
162
- type ActiveGeneration = GenerationStartedPayload;
163
- type ActiveGenerationProjection<M extends UIMessage = UIMessage> = {
164
- generationId: string;
165
- responseMessageId: string;
166
- baseMessage?: M;
167
- batches: Array<{
168
- index: number;
169
- chunks: UIMessageChunk[];
170
- }>;
171
- baseTools: ToolActivity[];
172
- toolEvents: Array<{
173
- index: number;
174
- type: "ai.tool.called";
175
- payload: ToolCalledPayload;
176
- } | {
177
- index: number;
178
- type: "ai.tool.result";
179
- payload: ToolResultPayload;
180
- }>;
181
- approvalEvents: Array<{
182
- index: number;
183
- type: "ai.approval.requested";
184
- payload: ApprovalRequestedPayload;
185
- } | {
186
- index: number;
187
- type: "ai.approval.responded";
188
- payload: ApprovalRespondedPayload;
189
- }>;
190
- };
191
- type PendingApproval = ApprovalRequestedPayload;
192
- type PendingInput = InputRequestedPayload;
193
- type ToolActivity = {
194
- requestId: string;
195
- messageId: string;
196
- generationId: string;
197
- toolCallId: string;
198
- toolName?: string;
199
- input?: unknown;
200
- rawInput?: unknown;
201
- output?: unknown;
202
- error?: string;
203
- preliminary?: boolean;
204
- phase?: "input" | "execution";
205
- dynamic?: boolean;
206
- providerExecuted?: boolean;
207
- callProviderMetadata?: unknown;
208
- resultProviderMetadata?: unknown;
209
- toolMetadata?: unknown;
210
- title?: string;
211
- status: "running" | "completed" | "failed" | "denied";
212
- };
213
- type CompactionState<M extends UIMessage> = {
214
- status: "running" | "completed";
215
- generationId: string;
216
- throughMessageId: string;
217
- messages?: M[];
218
- retainedMessageIds?: string[];
219
- };
220
- type GenerationUsage = {
221
- generationId: string;
222
- usage: LanguageModelUsage;
223
- };
224
- type AIState<M extends UIMessage = UIMessage> = {
225
- session: {
226
- created: boolean;
227
- metadata?: JSONValue;
228
- };
229
- messages: M[];
230
- status: AgentStatus;
231
- activeGeneration: ActiveGeneration | null;
232
- activeRequestId: string | null;
233
- activeResponseMessageId: string | null;
234
- activeProjection: ActiveGenerationProjection<M> | null;
235
- responseGenerationIds: Record<string, string>;
236
- pendingApprovals: PendingApproval[];
237
- pendingInputs: PendingInput[];
238
- tools: ToolActivity[];
239
- compaction: CompactionState<M> | null;
240
- usage: GenerationUsage[];
241
- error: string | null;
242
- };
243
- type AgentDefinition<M extends UIMessage = UIMessage, D extends EventDefs = AIEventDefs<M>> = {
244
- readonly contract: Contract<D>;
245
- readonly reducer: Reducer<D, AIState<M>>;
246
- };
247
- type AgentOptions<M extends UIMessage, E extends EventDefs> = {
248
- name: string;
249
- events?: E;
250
- /** Optional stricter schema for custom UIMessage metadata/data/tool types. */
251
- messageSchema?: StandardSchemaV1<M>;
252
- /** Snapshot identity. Bump when application-level projection semantics change. */
253
- reducerName?: string;
254
- };
255
- type AIMessageFrom<D extends EventDefs> = D extends Record<"ai.message.created", infer S extends StandardSchemaV1> ? StandardSchemaV1.InferOutput<S> extends MessageCreatedPayload<infer M extends UIMessage> ? M : UIMessage : UIMessage;
256
- declare function createEvents<M extends UIMessage = UIMessage>(options?: {
257
- messageSchema?: StandardSchemaV1<M>;
258
- }): AIEventDefs<M>;
259
- declare const events: AIEventDefs<UIMessage>;
260
- /** Pure projection of the built-in AI protocol. Unknown extension events are ignored. */
261
- declare function reduceAIState<M extends UIMessage>(state: AIState<M>, event: {
262
- type: string;
263
- payload: unknown;
264
- index: number;
265
- id?: string;
266
- }): AIState<M>;
267
- /** Derive AI SDK UI messages directly from an A2 event history. */
268
- declare function deriveUIMessages<M extends UIMessage = UIMessage>(history: readonly {
269
- type: string;
270
- payload: unknown;
271
- index: number;
272
- }[]): M[];
273
- /** Build the standard AI state projection for any contract containing the protocol. */
274
- declare function createReducer<D extends EventDefs>(options: {
275
- contract: Contract<D>;
276
- name?: string;
277
- }): Reducer<D, AIState<AIMessageFrom<D>>>;
278
- type ProtocolInput<M extends UIMessage, K extends keyof AIEventDefs<M> & string> = AppendInput<Pick<AIEventDefs<M>, K>>;
279
- type AIInputs = {
280
- /** Record a message. The server schedules user messages in arrival order. */
281
- message<M extends UIMessage>(message: M): ProtocolInput<M, "ai.message.created">[];
282
- /** Record a message without requesting a generation. */
283
- seed<M extends UIMessage>(message: M): ProtocolInput<M, "ai.message.created">[];
284
- /** Answer an AI SDK tool approval. The tool barrier owns continuation. */
285
- approval(response: ApprovalRespondedPayload): ProtocolInput<UIMessage, "ai.approval.responded">[];
286
- /** Answer an application-defined input request. */
287
- input(response: InputRespondedPayload): ProtocolInput<UIMessage, "ai.input.responded">[];
288
- /** Record an application-defined request for input. */
289
- requestInput(request: InputRequestedPayload): ProtocolInput<UIMessage, "ai.input.requested">[];
290
- /** Request a fresh attempt for a failed response. */
291
- retry(options: RetryGenerationOptions): ProtocolInput<UIMessage, "ai.retry.requested">[];
292
- /** Interrupt the active response for a message. */
293
- interrupt(interruption: MessageInterruptedPayload): ProtocolInput<UIMessage, "ai.message.interrupted">[];
294
- };
295
- /** Pure append inputs for the built-in AI protocol. */
296
- declare const inputs: AIInputs;
297
- /**
298
- * Define an agent: built-in AI protocol + application events and one state
299
- * reducer. The result is isomorphic.
300
- */
301
- declare function agent<M extends UIMessage = UIMessage, E extends EventDefs = Record<never, never>>(options: AgentOptions<M, E>): AgentDefinition<M, AIEventDefs<M> & E>;
302
- //#endregion
303
- export { AIEventDefs, AIInputs, AIState, ActiveGeneration, ActiveGenerationProjection, AgentDefinition, AgentOptions, AgentStatus, ApprovalRequestedPayload, ApprovalRespondedPayload, CompactionCompletedPayload, CompactionRequestedPayload, CompactionState, type FinishReason, GenerationCompletedPayload, GenerationFailedPayload, GenerationProgressPayload, GenerationReason, GenerationRequestedPayload, GenerationStartedPayload, GenerationUsage, InputRequestedPayload, InputRespondedPayload, type JSONValue, type LanguageModelUsage, MessageCompletedPayload, MessageCreatedPayload, MessageInterruptedPayload, PendingApproval, PendingInput, RetryGenerationOptions, RetryRequestedPayload, SessionClosedPayload, SessionCreatedPayload, ToolActivity, ToolCalledPayload, ToolResultPayload, type UIMessage, type UIMessageChunk, agent, createEvents, createReducer, deriveUIMessages, events, inputs, reduceAIState };
1
+ import { A as MessageInterruptedPayload, B as UIMessage, C as GenerationUsage, D as LanguageModelUsage, E as JSONValue, F as SessionClosedPayload, G as deriveUIMessages, H as agent, I as SessionCreatedPayload, J as inputs, K as events, L as ToolActivity, M as PendingInput, N as RetryGenerationOptions, O as MessageCompletedPayload, P as RetryRequestedPayload, R as ToolCalledPayload, S as GenerationStartedPayload, T as InputRespondedPayload, U as createEvents, V as UIMessageChunk, W as createReducer, Y as reduceAIState, _ as GenerationCompletedPayload, a as ActiveGenerationProjection, b as GenerationReason, c as AgentStatus, d as ApprovalRequestedPayload, f as ApprovalRespondedPayload, g as FinishReason, h as CompactionState, i as ActiveGeneration, j as PendingApproval, k as MessageCreatedPayload, l as AgentToolContext, m as CompactionRequestedPayload, n as AIInputs, o as AgentDefinition, p as CompactionCompletedPayload, q as handlerContext, r as AIState, s as AgentOptions, t as AIEventDefs, u as AgentToolEventDefs, v as GenerationFailedPayload, w as InputRequestedPayload, x as GenerationRequestedPayload, y as GenerationProgressPayload, z as ToolResultPayload } from "./ai-B4YhEnfw.js";
2
+ export { AIEventDefs, AIInputs, AIState, ActiveGeneration, ActiveGenerationProjection, AgentDefinition, AgentOptions, AgentStatus, AgentToolContext, AgentToolEventDefs, ApprovalRequestedPayload, ApprovalRespondedPayload, CompactionCompletedPayload, CompactionRequestedPayload, CompactionState, type FinishReason, GenerationCompletedPayload, GenerationFailedPayload, GenerationProgressPayload, GenerationReason, GenerationRequestedPayload, GenerationStartedPayload, GenerationUsage, InputRequestedPayload, InputRespondedPayload, type JSONValue, type LanguageModelUsage, MessageCompletedPayload, MessageCreatedPayload, MessageInterruptedPayload, PendingApproval, PendingInput, RetryGenerationOptions, RetryRequestedPayload, SessionClosedPayload, SessionCreatedPayload, ToolActivity, ToolCalledPayload, ToolResultPayload, type UIMessage, type UIMessageChunk, agent, createEvents, createReducer, deriveUIMessages, events, handlerContext, inputs, reduceAIState };