experimental-a2 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.
- package/CHANGELOG.md +28 -0
- package/dist/{ai-BMLlI2Ff.d.ts → ai-Cz3hqVhk.d.ts} +33 -16
- package/dist/ai-Cz3hqVhk.d.ts.map +1 -0
- package/dist/ai-client.d.ts +1 -1
- package/dist/ai-client.js +1 -1
- package/dist/ai-control-CvLbW10B.js +46 -0
- package/dist/ai-control-CvLbW10B.js.map +1 -0
- package/dist/ai-fx.d.ts +1 -1
- package/dist/ai-fx.d.ts.map +1 -1
- package/dist/ai-fx.js +30 -10
- package/dist/ai-fx.js.map +1 -1
- package/dist/{ai-harness-BuLh_EYi.js → ai-harness-BuuC-gJ3.js} +79 -15
- package/dist/ai-harness-BuuC-gJ3.js.map +1 -0
- package/dist/{ai-harness-B2suP2Qh.d.ts → ai-harness-CV6rXbB3.d.ts} +2 -2
- package/dist/ai-harness-CV6rXbB3.d.ts.map +1 -0
- package/dist/{ai-D6mGlO8j.js → ai-mMiWul1T.js} +116 -77
- package/dist/ai-mMiWul1T.js.map +1 -0
- package/dist/ai-pi.d.ts +1 -1
- package/dist/ai-pi.d.ts.map +1 -1
- package/dist/ai-pi.js +55 -10
- package/dist/ai-pi.js.map +1 -1
- package/dist/ai-react.d.ts +1 -1
- package/dist/ai-react.js +1 -1
- package/dist/ai-server.d.ts +2 -2
- package/dist/ai-server.d.ts.map +1 -1
- package/dist/ai-server.js +118 -50
- package/dist/ai-server.js.map +1 -1
- package/dist/ai.d.ts +2 -2
- package/dist/ai.js +1 -1
- package/dist/scheduler-vercel.d.ts.map +1 -1
- package/dist/scheduler-vercel.js +1 -4
- package/dist/scheduler-vercel.js.map +1 -1
- package/docs/agents/03-conversations.mdx +25 -13
- package/docs/agents/04-harnesses.mdx +51 -5
- package/docs/contract/03-sessions.mdx +1 -1
- package/docs/reference/04-ai.mdx +27 -18
- package/docs/reference/05-adapters.mdx +2 -2
- package/docs/server/02-timers.mdx +1 -1
- package/docs/server/05-production.mdx +2 -2
- package/examples/playground/DEPLOY.md +9 -0
- package/examples/playground/app/a0/a0.css +244 -5
- package/examples/playground/app/a0/app-view.tsx +2 -1
- package/examples/playground/app/a0/attachments.ts +133 -0
- package/examples/playground/app/a0/chat.test.tsx +504 -0
- package/examples/playground/app/a0/chat.tsx +623 -63
- package/examples/playground/app/a0/context-menu.tsx +38 -11
- package/examples/playground/app/a0/model.test.ts +28 -0
- package/examples/playground/app/a0/model.ts +30 -0
- package/examples/playground/app/a0/server.ts +5 -0
- package/examples/playground/app/a0/uploads/route.ts +29 -0
- package/examples/playground/app/agent/[agentId]/agent-client.tsx +2 -1
- package/examples/playground/app/agent/[agentId]/agent-queue.test.tsx +1 -0
- package/examples/playground/app/agent/model.test.ts +12 -3
- package/examples/playground/app/chat/[chatId]/agent-state.test.ts +1 -5
- package/examples/playground/next.config.ts +7 -4
- package/examples/playground/package.json +3 -1
- package/package.json +1 -1
- package/src/ai-agent.ts +4 -0
- package/src/ai-client-state.ts +21 -9
- package/src/ai-context-schema.ts +28 -4
- package/src/ai-context.ts +83 -3
- package/src/ai-control-server.ts +70 -43
- package/src/ai-control-state.ts +3 -4
- package/src/ai-control.ts +59 -10
- package/src/ai-coordinator.ts +7 -6
- package/src/ai-fx.ts +58 -20
- package/src/ai-harness.ts +153 -29
- package/src/ai-message-shape.ts +41 -0
- package/src/ai-pi.ts +88 -32
- package/src/ai-stored-state.ts +1 -3
- package/src/ai.ts +116 -77
- package/src/libfx.d.ts +8 -1
- package/src/scheduler-vercel.ts +1 -12
- package/dist/ai-BMLlI2Ff.d.ts.map +0 -1
- package/dist/ai-D6mGlO8j.js.map +0 -1
- package/dist/ai-harness-B2suP2Qh.d.ts.map +0 -1
- package/dist/ai-harness-BuLh_EYi.js.map +0 -1
- package/examples/playground/app/a0/no-photon.cjs +0 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.19.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 8f373b5: Under `fx()` and `pi()`, a user message's images now reach the model. A2 fetches each `image/*` file part from its `https:` or `data:` URL through the AI SDK's download, which refuses private addresses and checks redirects, up to 32 MiB of one message's files, and keeps what it fetched for the process. FX gets them as image prompt blocks and Pi as prompt and steering images. A file that isn't an image, an image A2 can't fetch, or a steer with files under FX fails the turn with an error that names the file. Every step sends the conversation so far with all its files, as under `{ type: 'ai-sdk' }`.
|
|
8
|
+
|
|
9
|
+
Before, both harnesses read only a message's text and dropped its files without a word.
|
|
10
|
+
|
|
11
|
+
- b83ba8b: `agent()` now throws a `TypeError` when a provider-defined tool (`type: 'provider'`, such as a provider's web search) is passed with `fx()` or `pi()`, as it does for a tool that sets `needsApproval`. Before, both harnesses dropped such a tool without a word, so the model never saw it.
|
|
12
|
+
- 88ee923: A2's AI log stores each message's content once, in the `ai.control.requested` command that brought it in. Before, a message sent with no turn running was stored three times, and a queued or steering one four: in its command, in `ai.control.committed`, and in `ai.message.created`.
|
|
13
|
+
|
|
14
|
+
- `ai.message.created` now records an admission as `{ messageId, role, generate? }`. `MessageCreatedPayload` is no longer generic. Only A2's control lane writes the event, after the command that brought its input in; `reduceAIState()` and `deriveUIMessages()` throw on one that no command explains.
|
|
15
|
+
- `ai.control.committed` never carries message content: queued inputs and `AIState.active.input` are the new `InputRef` type, `{ id, role, generate, afterStepOf? }`. `ActiveTurn` is no longer generic. `AIState.inbox.items` keep their `message`, now with `role`.
|
|
16
|
+
- `AIMessageOf` reads the message type from the contract's input command schema.
|
|
17
|
+
- The AI state, model context, and control reducers advance to `a2.ai.state.v27`, `a2.ai.context.v7`, and `a2.ai.control.v6`, so their checkpoints rebuild from the log. Logs written before this release don't fold.
|
|
18
|
+
|
|
19
|
+
Reading the log costs nothing more: the transcript's readers keep a queued input's content in their state from its command until its admission.
|
|
20
|
+
|
|
21
|
+
- da1e0e5: Steering hands off in the order it was sent, as one turn. `steer()` now queues new input right after the turn's earlier steering instead of ahead of it, and `queue.sendNow()` lands after that steering too. At the handoff, every input steering the turn enters together: the last one starts the new turn and the earlier ones enter as its context (`generate: false`), so the model answers them once. Under `fx()` and `pi()`, they reach the harness as one steering message. A turn paused with `pause({ when: 'now' })` keeps its steering until `resume()`, so every steer sent while it's paused targets it and they all enter on Resume.
|
|
22
|
+
|
|
23
|
+
Before, each steer jumped to the front, so several steers ran last-first, each as its own turn, and the first steer ended a paused turn at once, leaving later steers no turn to target.
|
|
24
|
+
|
|
25
|
+
### Patch Changes
|
|
26
|
+
|
|
27
|
+
- 9b80f3e: Under `pi()`, `speed: 'fast'` now asks AI Gateway for the model's fast tier on each of Pi's model calls, as it already did under `{ type: 'ai-sdk' }` and `fx()`. Before, `pi()` ignored `speed`, so every step ran at standard speed.
|
|
28
|
+
- b83ba8b: The interruption reason `'steered after step'` is reserved: A2 writes it when steering ends a response, and `fx()` and `pi()` replay the next response as that steering. A client interruption that carries it is now rejected. Before, one would make the harness replay a stopped response as steered, so the replay diverged and the session failed.
|
|
29
|
+
- c7afea6: `vercelQueues()` no longer refuses delays over six days itself. A task's delay goes to Vercel Queues as asked, with the seven-day retention it already set, and Vercel Queues refuses one longer than that.
|
|
30
|
+
|
|
3
31
|
## 0.18.1
|
|
4
32
|
|
|
5
33
|
### Patch Changes
|
|
@@ -22,12 +22,20 @@ type MessageBase = {
|
|
|
22
22
|
};
|
|
23
23
|
//#endregion
|
|
24
24
|
//#region src/ai-control.d.ts
|
|
25
|
-
|
|
25
|
+
/**
|
|
26
|
+
* An input in the queue or the active turn. Its content stays in the
|
|
27
|
+
* `ai.control.requested` command that brought it, and in no other event.
|
|
28
|
+
*/
|
|
29
|
+
type InputRef = {
|
|
26
30
|
id: string;
|
|
27
|
-
|
|
31
|
+
role: UIMessage["role"];
|
|
28
32
|
generate: boolean;
|
|
29
33
|
afterStepOf?: string;
|
|
30
34
|
};
|
|
35
|
+
/** A queued input with its content, as `AIState` shows it. */
|
|
36
|
+
type InboxItem<M extends UIMessage = UIMessage> = InputRef & {
|
|
37
|
+
message: M;
|
|
38
|
+
};
|
|
31
39
|
type ControlCommand<M extends UIMessage = UIMessage> = {
|
|
32
40
|
action: "send";
|
|
33
41
|
message: M;
|
|
@@ -86,9 +94,9 @@ type ControlReceipt = {
|
|
|
86
94
|
outcome: "applied" | "rejected";
|
|
87
95
|
reason?: "not-pending" | "role-mismatch" | "stale-turn" | "not-found" | "closed" | "stale-work" | "not-user-input";
|
|
88
96
|
};
|
|
89
|
-
type ActiveTurn
|
|
97
|
+
type ActiveTurn = {
|
|
90
98
|
turnId: string;
|
|
91
|
-
input:
|
|
99
|
+
input: InputRef;
|
|
92
100
|
phase: "starting" | "generating" | "tools" | "waiting" | "failed" | "pausing" | "paused";
|
|
93
101
|
};
|
|
94
102
|
type WorkFact = {
|
|
@@ -216,10 +224,15 @@ type SessionCreatedPayload = {
|
|
|
216
224
|
type SessionClosedPayload = {
|
|
217
225
|
reason?: string;
|
|
218
226
|
};
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
227
|
+
/**
|
|
228
|
+
* A message entering the transcript. Its content is the command's that brought
|
|
229
|
+
* it in, which every reader of the transcript has already folded.
|
|
230
|
+
*/
|
|
231
|
+
type MessageCreatedPayload = {
|
|
232
|
+
messageId: string;
|
|
233
|
+
role: UIMessage$1["role"];
|
|
234
|
+
/** For user messages, false records passive context. Omission schedules. */
|
|
235
|
+
generate?: false;
|
|
223
236
|
};
|
|
224
237
|
type MessageCompletedPayload = {
|
|
225
238
|
messageId: string;
|
|
@@ -400,7 +413,7 @@ type AIEventDefs<M extends UIMessage$1 = UIMessage$1> = {
|
|
|
400
413
|
}>;
|
|
401
414
|
"ai.session.created": StandardSchemaV1<SessionCreatedPayload>;
|
|
402
415
|
"ai.session.closed": StandardSchemaV1<SessionClosedPayload>;
|
|
403
|
-
"ai.message.created": StandardSchemaV1<MessageCreatedPayload
|
|
416
|
+
"ai.message.created": StandardSchemaV1<MessageCreatedPayload>;
|
|
404
417
|
"ai.message.completed": StandardSchemaV1<MessageCompletedPayload>;
|
|
405
418
|
"ai.message.interrupted": StandardSchemaV1<MessageInterruptedPayload>;
|
|
406
419
|
"ai.generation.requested": StandardSchemaV1<GenerationRequestedPayload>;
|
|
@@ -491,7 +504,7 @@ type AIState<M extends UIMessage$1 = UIMessage$1> = {
|
|
|
491
504
|
items: InboxItem<M>[];
|
|
492
505
|
};
|
|
493
506
|
pendingQueueCommands?: PendingQueueCommand<M>[];
|
|
494
|
-
active: ActiveTurn
|
|
507
|
+
active: ActiveTurn | null;
|
|
495
508
|
starting: boolean;
|
|
496
509
|
receipt: ControlReceipt | null;
|
|
497
510
|
pausedGenerationIds?: Record<string, true>;
|
|
@@ -518,10 +531,14 @@ type AIState<M extends UIMessage$1 = UIMessage$1> = {
|
|
|
518
531
|
usage: GenerationUsage[];
|
|
519
532
|
error: string | null;
|
|
520
533
|
};
|
|
521
|
-
/** The `UIMessage` type a contract's
|
|
534
|
+
/** The `UIMessage` type a contract's input commands carry. */
|
|
522
535
|
type AIMessageOf<D> = D extends {
|
|
523
|
-
readonly "ai.
|
|
524
|
-
} ? StandardSchemaV1.InferOutput<S
|
|
536
|
+
readonly "ai.control.requested": infer S extends StandardSchemaV1;
|
|
537
|
+
} ? Extract<StandardSchemaV1.InferOutput<S>, {
|
|
538
|
+
action: "send";
|
|
539
|
+
}> extends {
|
|
540
|
+
message: infer M extends UIMessage$1;
|
|
541
|
+
} ? M : UIMessage$1 : UIMessage$1;
|
|
525
542
|
/** What `agentContract()` returns: the AI protocol, with `X` as application state. */
|
|
526
543
|
type AgentContract<M extends UIMessage$1 = UIMessage$1, D extends EventDefs = AIEventDefs<M>, X extends object = Record<never, never>> = Contract<D, Record<never, never>, AgentReducer<M, D, X>>;
|
|
527
544
|
type AgentToolEventDefs = EventDefs & Pick<AIEventDefs, "ai.tool.execution.requested">;
|
|
@@ -640,7 +657,7 @@ declare const inputs: AIInputs;
|
|
|
640
657
|
*/
|
|
641
658
|
declare function handlerContext<D extends AgentToolEventDefs = AIEventDefs>(contract?: Contract<D>): AgentToolContext<D>;
|
|
642
659
|
/** The built-in AI reducer's name, and so its checkpoint identity. */
|
|
643
|
-
declare const AI_STATE_REDUCER = "a2.ai.state.
|
|
660
|
+
declare const AI_STATE_REDUCER = "a2.ai.state.v27";
|
|
644
661
|
/**
|
|
645
662
|
* The built-in AI protocol plus application events, as a core contract whose
|
|
646
663
|
* reducer folds `AIState`. Isomorphic: share it when a client needs
|
|
@@ -649,5 +666,5 @@ declare const AI_STATE_REDUCER = "a2.ai.state.v26";
|
|
|
649
666
|
*/
|
|
650
667
|
declare function agentContract<M extends UIMessage$1 = UIMessage$1, E extends EventDefs = Record<never, never>, X extends object = Record<never, never>>(options: AgentContractOptions<M, E, X>): AgentContract<M, AIEventDefs<M> & E, X>;
|
|
651
668
|
//#endregion
|
|
652
|
-
export { agentContract as $, InputRespondedPayload as A, PendingApproval as B, GenerationFailedPayload as C, GenerationStartedPayload as D, GenerationRequestedPayload as E, MessageInterruptedPayload as F, SessionClosedPayload as G, ReasoningLevel as H, ModelLimits as I, ToolCalledPayload as J, SessionCreatedPayload as K, ModelMetadataRequestedPayload as L, LanguageModelUsage as M, MessageCompletedPayload as N, GenerationUsage as O, MessageCreatedPayload as P, UIMessageChunk$1 as Q, ModelMetadataResolvedPayload as R, GenerationCompletedPayload as S, GenerationReason as T, RetryGenerationOptions as U, PendingInput as V, RetryRequestedPayload as W, TranscriptMessage as X, ToolResultPayload as Y, UIMessage$1 as Z, CompactionPart as _, AI_STATE_REDUCER as a, reasoningLevels as at, CompactionState as b, AgentContract as c, PendingQueueCommand as ct, AgentStatus as d, ControlReceipt as dt, createEvents as et, AgentToolContext as f, InboxItem as ft, CompactionCompletedPayload as g, ApprovalRespondedPayload as h, AIState as i, inputs as it, JSONValue$1 as j, InputRequestedPayload as k, AgentContractOptions as l, ActiveTurn as lt, ApprovalRequestedPayload as m, AIInputs as n, events as nt, ActiveGeneration as o, reduceAIState as ot, AgentToolEventDefs as p, ToolActivity as q, AIMessageOf as r, handlerContext as rt, ActiveGenerationProjection as s, isCompactionPart as st, AIEventDefs as t, deriveUIMessages as tt, AgentReducer as u, ControlCommand as ut, CompactionPartData as v, GenerationProgressPayload as w, FinishReason as x, CompactionRequestedPayload as y, ModelMetadataState as z };
|
|
653
|
-
//# sourceMappingURL=ai-
|
|
669
|
+
export { agentContract as $, InputRespondedPayload as A, PendingApproval as B, GenerationFailedPayload as C, GenerationStartedPayload as D, GenerationRequestedPayload as E, MessageInterruptedPayload as F, SessionClosedPayload as G, ReasoningLevel as H, ModelLimits as I, ToolCalledPayload as J, SessionCreatedPayload as K, ModelMetadataRequestedPayload as L, LanguageModelUsage as M, MessageCompletedPayload as N, GenerationUsage as O, MessageCreatedPayload as P, UIMessageChunk$1 as Q, ModelMetadataResolvedPayload as R, GenerationCompletedPayload as S, GenerationReason as T, RetryGenerationOptions as U, PendingInput as V, RetryRequestedPayload as W, TranscriptMessage as X, ToolResultPayload as Y, UIMessage$1 as Z, CompactionPart as _, AI_STATE_REDUCER as a, reasoningLevels as at, CompactionState as b, AgentContract as c, PendingQueueCommand as ct, AgentStatus as d, ControlReceipt as dt, createEvents as et, AgentToolContext as f, InboxItem as ft, CompactionCompletedPayload as g, ApprovalRespondedPayload as h, AIState as i, inputs as it, JSONValue$1 as j, InputRequestedPayload as k, AgentContractOptions as l, ActiveTurn as lt, ApprovalRequestedPayload as m, AIInputs as n, events as nt, ActiveGeneration as o, reduceAIState as ot, AgentToolEventDefs as p, InputRef as pt, ToolActivity as q, AIMessageOf as r, handlerContext as rt, ActiveGenerationProjection as s, isCompactionPart as st, AIEventDefs as t, deriveUIMessages as tt, AgentReducer as u, ControlCommand as ut, CompactionPartData as v, GenerationProgressPayload as w, FinishReason as x, CompactionRequestedPayload as y, ModelMetadataState as z };
|
|
670
|
+
//# sourceMappingURL=ai-Cz3hqVhk.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ai-Cz3hqVhk.d.ts","names":[],"sources":["../src/ai-message-base.ts","../src/ai-control.ts","../src/ai-client-state.ts","../src/ai-projector.ts","../src/ai-progress-batches.ts","../src/ai-message-projection.ts","../src/ai.ts"],"mappings":";;;;KAGK;EAAc;;EAAsB;;EAAmB;;KACvD,aAAa,eAAe;KAC5B;EAAa,OAAO;;EAAiC,QAAQ;;KAEtD;EACV;EACA,SAAS;EACT,QAAQ,eAAe;;;;;;;;KCQb;EACV;EACA,MAAM;EACN;EACA;;;KAIU,UAAU,UAAU,YAAY,aAAa;EACvD,SAAS;;KAGC,eAAe,UAAU,YAAY;EAC3C;EAAgB,SAAS;EAAG;;EAC5B;EAAgB,SAAS;;EACzB;EAAgB;EAAiB;;EACjC;EAAkB;;EAElB;EACA;EACA;EACA;;EAEA;EAAgB;EAAgB;;EAChC;EAAiB;EAAgB,SAAS;EAAG;;EAC7C;EAAiB;;EACjB;;EACA;EAAuB,QAAQ;;EAC/B;EAAoB,UAAU;;EAC9B;EAAiB,UAAU;;EAC3B;EAAyB,SAAS;;EAClC;EAAiB,SAAS;;EAC1B;EAAqB,SAAS;;KAExB;EACV;EACA;EACA;EACA;;KAUU;EACV;EACA,OAAO;EACP;;KA+BU;EAAa;EAAc;EAAY;;KACvC;EACV;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;;KAGE;EACV;EACA;EACA,MAAM;EACN,YAAY;;KAoDF;EACV;EACA;EACA;EACA;IAAW;IAAe;IAAqB;;EAC/C;IAAS;IAAc;;;KAGb;EACV,SAAS;EACT;IACE;IACA;IACA,OAAO;IACP;IACA;IACA;IACA,eAAe;IACf;IACA;;;;;KC7KQ,aAAa,UAAU,aAAa,QAC9C,eAAe;EAEb;;KAYQ,oBAAoB,UAAU;EACxC;EACA,SAAS,aAAa;;;;KCpBnB;EACH;EACA;EACA;EACA;EACA;EACA;EACA;;KAwJU;EACV,MAAM;EACN,WAAW;EACX,OAAO,eAAe;;;;KChJZ;EAAkB;EAAe,QAAQ;;KAChD,aAAa;EAAoB,MAAM;EAAY,OAAO;;KAEnD;EACV;EACA,MAAM;EACN,QAAQ,MAAM;;;;cCmgBH,mBAAoB;EAC/B;MACE,QAAQ;;;KCncA;KAGA;KAEA,iBAAiB,YAAY;cAE5B,0BAA0B;KAU3B;EACV;EACA;EACA;EACA;EACA,QAAQ;;;KAIE;EACV;EACA;EACA,MAAM;;;;;;KASI,kBAAkB,UAAU,eAAa,KAAK;EACxD,OAAO,MAAM,qBAAqB;;KAGxB;EAA0B,WAAW;;KACrC;EAAyB;;;;;;KAKzB;EACV;EACA,MAAM;;EAEN;;KAEU;EAA4B;;KACnC;EACH;EACA;;EAEA;;KAEU,4BAA4B;EAEhC;EAAsB;;EACtB;EAAmB;;KAEf;EACV;IAAY;IAAgB;;EAC5B;EACA,QAAQ;EACR;EACA;;KAEU;EACV;EACA;EACA;;KAEU,wBAAwB;KACxB;EACV;EACA;EACA;EACA;EACA;;EAEA;EACA;;KAEU;;EAEV;EACA,QAAQ;;KAEE;EACV;EACA;EACA;EACA;EACA,eAAe;EACf,QAAQ;EACR;;KAEU;EACV;EACA;EACA;EACA;EACA;;EAEA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA,WAAW;;KAED;EACV;EACA;EACA;EACA;EACA;EACA,OAAO;;KAEG;EACV;EACA;;KAEU;EAAkC;;KAClC;EACV;EACA,QAAQ;;KAEE;EACN;;EACA;EAAoB,QAAQ;;EAC5B;;KAEM;EACV;EACA;EACA;EACA;EACA;EACA;;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BAAkB;KAMhB,aAAa;EAAO;EAA8B,SAAS;EAAG;;KAC9D,aACH,UAAU,aACV,UAAU,eAAe,gBACvB,aAAa,QAAQ,eAAe;EAAM,QAAQ;OACnD;EAA+B;;KAEtB;EACV,QAAQ,UAAU,aAChB,SAAS,GACT;IAAY;MACX,aAAa;EAChB,KAAK,UAAU,aAAW,SAAS,IAAI,aAAa;EACpD;IACE,OAAO;MAAW;QAAoB,aAAa;IACnD,QAAQ;MACN;MACA;MACA;QACE,aAAa;IACjB,KAAK,UAAU,aAAW;MACxB,SAAS;QACP,aAAa;IACjB,KAAK;MACH;MACA;QACE,aAAa;;EAEnB,KAAK;IACH;IACA;MACE,aAAa;EACjB,MAAM,UAAU,aAAW;IACzB;IACA,SAAS;IACT;MACE,aAAa;EACjB,MAAM;IACJ;MACE,aAAa;EACjB,UAAU,aAAa;EACvB,SACE,UAAU,2BACT,aAAa;EAChB,MAAM,UAAU,wBAAwB,aAAa;EACrD,aACE,SAAS,wBACR,aAAa;EAChB,MAAM,SAAS,yBAAyB,aAAa;EACrD,UACE,SAAS,4BACR,aAAa;EAChB,WACE,QAAQ,oBACP,aAAa;;;cAsBL,QAAQ;;;;;;;;;iBAgEL,eAAe,UAAU,qBAAqB,aAC5D,WAAW,SAAS,KACnB,iBAAiB;;cAoBP;;;;;;;iBAQG,cACd,UAAU,cAAY,aACtB,UAAU,YAAY,sBACtB,mBAAmB,sBAEnB,SAAS,qBAAqB,GAAG,GAAG,KACnC,cAAc,GAAG,YAAY,KAAK,GAAG"}
|
package/dist/ai-client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { s as CreateClientOptions, t as A2Client } from "./client-h_DKFAjj.js";
|
|
2
|
-
import { a as AI_STATE_REDUCER, i as AIState, r as AIMessageOf, t as AIEventDefs } from "./ai-
|
|
2
|
+
import { a as AI_STATE_REDUCER, i as AIState, r as AIMessageOf, t as AIEventDefs } from "./ai-Cz3hqVhk.js";
|
|
3
3
|
//#region src/ai-client.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* The structural shape of `typeof` an `agent({ name })` server: one whose
|
package/dist/ai-client.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as createClient } from "./client-BhHLoNKF.js";
|
|
2
|
-
import { n as agentContract } from "./ai-
|
|
2
|
+
import { n as agentContract } from "./ai-mMiWul1T.js";
|
|
3
3
|
//#region src/ai-client.ts
|
|
4
4
|
/**
|
|
5
5
|
* experimental-a2/ai/client — a client for an `agent()` route that needs no
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
//#region src/ai-control.ts
|
|
2
|
+
/**
|
|
3
|
+
* The `ai.message.interrupted` reason A2 writes when steering ends a response
|
|
4
|
+
* after a step; a harness's replay continues the turn on it. Reserved, so a
|
|
5
|
+
* client's interruption can't carry it.
|
|
6
|
+
*/
|
|
7
|
+
const STEERED_REASON = "steered after step";
|
|
8
|
+
/**
|
|
9
|
+
* A fold met an admission no command explains. Only A2's control lane writes
|
|
10
|
+
* `ai.message.created`, after the command that brought its input in.
|
|
11
|
+
*/
|
|
12
|
+
const unexplainedAdmission = (messageId) => /* @__PURE__ */ new TypeError(`ai.message.created for ${messageId} follows no command that brought it in; only A2's control lane writes it`);
|
|
13
|
+
/**
|
|
14
|
+
* Where new steering for a turn goes in the inbox: right after the turn's
|
|
15
|
+
* earlier steering, or first, so it hands off in the order it was sent.
|
|
16
|
+
*/
|
|
17
|
+
const steeringEnd = (items, turnId) => items.findLastIndex((item) => item.afterStepOf === turnId) + 1;
|
|
18
|
+
/**
|
|
19
|
+
* Whether an input steering a turn enters as context for later steering: the
|
|
20
|
+
* run of inputs steering one turn is admitted together, and only its last
|
|
21
|
+
* generating input starts the next turn.
|
|
22
|
+
*/
|
|
23
|
+
const steersOn = (item, rest) => {
|
|
24
|
+
if (item.afterStepOf === void 0) return false;
|
|
25
|
+
for (const next of rest) {
|
|
26
|
+
if (next.afterStepOf !== item.afterStepOf) return false;
|
|
27
|
+
if (next.generate) return true;
|
|
28
|
+
}
|
|
29
|
+
return false;
|
|
30
|
+
};
|
|
31
|
+
const initialControlState = () => ({
|
|
32
|
+
pendingStops: {},
|
|
33
|
+
inbox: {
|
|
34
|
+
paused: false,
|
|
35
|
+
items: []
|
|
36
|
+
},
|
|
37
|
+
active: null,
|
|
38
|
+
coordinator: {
|
|
39
|
+
closed: false,
|
|
40
|
+
queued: []
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
//#endregion
|
|
44
|
+
export { unexplainedAdmission as a, steersOn as i, initialControlState as n, steeringEnd as r, STEERED_REASON as t };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=ai-control-CvLbW10B.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ai-control-CvLbW10B.js","names":[],"sources":["../src/ai-control.ts"],"sourcesContent":["import type { UIMessage } from 'ai'\nimport type { AICoordinatorState } from './ai-coordinator.ts'\nimport type {\n ApprovalRespondedPayload,\n GenerationStartedPayload,\n GenerationReason,\n InputRequestedPayload,\n InputRespondedPayload,\n MessageInterruptedPayload,\n RetryRequestedPayload,\n ToolCalledPayload,\n ToolResultPayload,\n} from './ai.ts'\n\n/**\n * An input in the queue or the active turn. Its content stays in the\n * `ai.control.requested` command that brought it, and in no other event.\n */\nexport type InputRef = {\n id: string\n role: UIMessage['role']\n generate: boolean\n afterStepOf?: string\n}\n\n/** A queued input with its content, as `AIState` shows it. */\nexport type InboxItem<M extends UIMessage = UIMessage> = InputRef & {\n message: M\n}\n\nexport type ControlCommand<M extends UIMessage = UIMessage> =\n | { action: 'send'; message: M; generate?: boolean }\n | { action: 'edit'; message: M }\n | { action: 'move'; inputId: string; beforeId: string | null }\n | { action: 'remove'; inputId: string }\n | {\n action: 'send-now'\n inputId: string\n turnId: string | null\n lastSeenIndex?: number\n }\n | { action: 'stop'; turnId: string; lastSeenIndex?: number }\n | { action: 'steer'; turnId: string; message: M; lastSeenIndex?: number }\n | { action: 'pause'; when: 'now' | 'after-turn' }\n | { action: 'resume' }\n | { action: 'tool-result'; result: ToolResultPayload }\n | { action: 'approval'; response: ApprovalRespondedPayload }\n | { action: 'input'; response: InputRespondedPayload }\n | { action: 'request-input'; request: InputRequestedPayload }\n | { action: 'retry'; request: RetryRequestedPayload }\n | { action: 'interrupt'; request: MessageInterruptedPayload }\n\nexport type ControlReceipt = {\n commandId: string\n work?: true\n outcome: 'applied' | 'rejected'\n reason?:\n | 'not-pending'\n | 'role-mismatch'\n | 'stale-turn'\n | 'not-found'\n | 'closed'\n | 'stale-work'\n | 'not-user-input'\n}\n\nexport type ActiveTurn = {\n turnId: string\n input: InputRef\n phase:\n | 'starting'\n | 'generating'\n | 'tools'\n | 'waiting'\n | 'failed'\n | 'pausing'\n | 'paused'\n}\n\nexport type ControlWork = {\n id: string\n version: number\n settled: boolean\n attempt?: number\n facts?: string[]\n}\n\nexport type AIControlState = {\n pendingStops: Record<string, string>\n inbox: { paused: boolean; items: InputRef[] }\n active:\n | (ActiveTurn & {\n version: number\n suspended: boolean\n model: ControlWork | null\n })\n | null\n coordinator: AICoordinatorState\n}\n\nexport type WorkFact = { type: string; id: string; payload: unknown }\nexport type WorkReport = {\n attempt: number\n workId: string\n turnId: string\n version: number\n kind: 'model' | 'tool'\n settled: boolean\n events: WorkFact[]\n}\n\nexport type ToolExecutionRequest = {\n turnId: string\n version: number\n call: ToolCalledPayload\n generation: GenerationStartedPayload\n}\n\n/**\n * The `ai.message.interrupted` reason A2 writes when steering ends a response\n * after a step; a harness's replay continues the turn on it. Reserved, so a\n * client's interruption can't carry it.\n */\nexport const STEERED_REASON = 'steered after step'\n\n/**\n * A fold met an admission no command explains. Only A2's control lane writes\n * `ai.message.created`, after the command that brought its input in.\n */\nexport const unexplainedAdmission = (messageId: string): TypeError =>\n new TypeError(\n `ai.message.created for ${messageId} follows no command that brought it in; only A2's control lane writes it`,\n )\n\n/**\n * Where new steering for a turn goes in the inbox: right after the turn's\n * earlier steering, or first, so it hands off in the order it was sent.\n */\nexport const steeringEnd = (\n items: readonly InputRef[],\n turnId: string,\n): number => items.findLastIndex((item) => item.afterStepOf === turnId) + 1\n\n/**\n * Whether an input steering a turn enters as context for later steering: the\n * run of inputs steering one turn is admitted together, and only its last\n * generating input starts the next turn.\n */\nexport const steersOn = (\n item: InputRef,\n rest: readonly InputRef[],\n): boolean => {\n if (item.afterStepOf === undefined) return false\n for (const next of rest) {\n if (next.afterStepOf !== item.afterStepOf) return false\n if (next.generate) return true\n }\n return false\n}\n\nexport const initialControlState = (): AIControlState => ({\n pendingStops: {},\n inbox: { paused: false, items: [] },\n active: null,\n coordinator: { closed: false, queued: [] },\n})\n\nexport type ControlChange = {\n path: (string | number)[]\n value?: unknown\n remove?: true\n splice?: { index: number; deleteCount: number; items: unknown[] }\n move?: { from: number; to: number }\n}\n\nexport type ControlCommit = {\n changes: ControlChange[]\n view: {\n turnId: string | null\n version: number | null\n phase: ActiveTurn['phase'] | null\n paused: boolean\n closed: boolean\n requestId: string | null\n requestReason: GenerationReason | null\n sourceGenerationId: string | null\n responseMessageId: string | null\n }\n}\n"],"mappings":";;;;;;AA2HA,MAAa,iBAAiB;;;;;AAM9B,MAAa,wBAAwB,8BACnC,IAAI,UACF,0BAA0B,UAAU,yEACtC;;;;;AAMF,MAAa,eACX,OACA,WACW,MAAM,eAAe,SAAS,KAAK,gBAAgB,MAAM,IAAI;;;;;;AAO1E,MAAa,YACX,MACA,SACY;CACZ,IAAI,KAAK,gBAAgB,KAAA,GAAW,OAAO;CAC3C,KAAK,MAAM,QAAQ,MAAM;EACvB,IAAI,KAAK,gBAAgB,KAAK,aAAa,OAAO;EAClD,IAAI,KAAK,UAAU,OAAO;CAC5B;CACA,OAAO;AACT;AAEA,MAAa,6BAA6C;CACxD,cAAc,CAAC;CACf,OAAO;EAAE,QAAQ;EAAO,OAAO,CAAC;CAAE;CAClC,QAAQ;CACR,aAAa;EAAE,QAAQ;EAAO,QAAQ,CAAC;CAAE;AAC3C"}
|
package/dist/ai-fx.d.ts
CHANGED
package/dist/ai-fx.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-fx.d.ts","names":[],"sources":["../src/ai-fx.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"ai-fx.d.ts","names":[],"sources":["../src/ai-fx.ts"],"mappings":";;;;;;iBA2CgB,MAAM"}
|
package/dist/ai-fx.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as boundedCache } from "./bounded-cache-CPHWF-8h.js";
|
|
2
|
-
import {
|
|
2
|
+
import { f as saveHarness, i as gatewayCredential, l as pending, n as deferred, o as harnessImages, r as defineHarness, t as Divergence, u as readHarness } from "./ai-harness-BuuC-gJ3.js";
|
|
3
3
|
import { t as schemaInput } from "./ai-tool-input-DmSqMUQi.js";
|
|
4
4
|
import { asSchema } from "ai";
|
|
5
5
|
//#region src/ai-fx.ts
|
|
@@ -19,6 +19,8 @@ function fx() {
|
|
|
19
19
|
}
|
|
20
20
|
const SNAPSHOT_VERSION = 1;
|
|
21
21
|
const CATALOG_TTL_MS = 36e5;
|
|
22
|
+
/** The Gateway model catalog libfx reads for each new kernel. */
|
|
23
|
+
const CATALOG_PATH = "/coding-agent/v1/models";
|
|
22
24
|
function fail(state, error) {
|
|
23
25
|
state.failure ??= error;
|
|
24
26
|
state.fxTurn.cancel();
|
|
@@ -111,7 +113,9 @@ async function runStep(step) {
|
|
|
111
113
|
};
|
|
112
114
|
const hostFetch = async (input, init = {}) => {
|
|
113
115
|
const url = input instanceof Request ? input.url : String(input);
|
|
114
|
-
|
|
116
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
117
|
+
if (method === "GET" && new URL(url).pathname === CATALOG_PATH) return catalog(url, credential, withAuth(init.headers, credential));
|
|
118
|
+
if (method === "GET") return fetch(input, init);
|
|
115
119
|
const state = turn;
|
|
116
120
|
if (state.failure) throw state.failure;
|
|
117
121
|
const compaction = isCompaction(decodeBody(init.body));
|
|
@@ -208,7 +212,7 @@ async function runStep(step) {
|
|
|
208
212
|
}
|
|
209
213
|
return fail(state, diverged(`no recorded result for ${toolName}`));
|
|
210
214
|
});
|
|
211
|
-
|
|
215
|
+
const plans = (turns) => Promise.all(turns.map((recorded) => turnPlan(recorded, step.signal)));
|
|
212
216
|
let results = read.results;
|
|
213
217
|
let controller;
|
|
214
218
|
let closed = false;
|
|
@@ -239,11 +243,10 @@ async function runStep(step) {
|
|
|
239
243
|
} catch (error) {
|
|
240
244
|
if (read.saved === void 0) throw error;
|
|
241
245
|
read = await replayAll();
|
|
242
|
-
turns = read.turns.map(turnPlan);
|
|
243
246
|
results = read.results;
|
|
244
247
|
agent = await create(void 0);
|
|
245
248
|
}
|
|
246
|
-
await run(streamController, turns);
|
|
249
|
+
await run(streamController, await plans(read.turns));
|
|
247
250
|
closed = true;
|
|
248
251
|
streamController.close();
|
|
249
252
|
} catch (error) {
|
|
@@ -266,24 +269,41 @@ async function runStep(step) {
|
|
|
266
269
|
completion: () => completion
|
|
267
270
|
};
|
|
268
271
|
}
|
|
269
|
-
function turnPlan(turn) {
|
|
272
|
+
async function turnPlan(turn, signal) {
|
|
270
273
|
const calls = [];
|
|
271
274
|
const steers = /* @__PURE__ */ new Map();
|
|
272
|
-
const steer = (at,
|
|
273
|
-
if (
|
|
275
|
+
const steer = (at, inputs) => {
|
|
276
|
+
if (inputs !== void 0) steers.set(Math.max(0, at), inputs.map(steerText));
|
|
274
277
|
};
|
|
275
278
|
steer(0, turn.generations.length === 0 ? turn.steers.get(0) : void 0);
|
|
276
279
|
turn.generations.forEach((generation, index) => {
|
|
277
280
|
calls.push(...recordedCalls(generation.chunks, generation.completed));
|
|
278
281
|
steer(calls.length - 1, turn.steers.get(index));
|
|
279
282
|
});
|
|
283
|
+
const images = await harnessImages({
|
|
284
|
+
harness: "fx()",
|
|
285
|
+
input: turn.prompt,
|
|
286
|
+
signal
|
|
287
|
+
});
|
|
280
288
|
return {
|
|
281
|
-
prompt: turn.prompt
|
|
289
|
+
prompt: images.length === 0 ? turn.prompt.text : [...images.map((image) => ({
|
|
290
|
+
type: "image",
|
|
291
|
+
data: image.data,
|
|
292
|
+
mimeType: image.mediaType
|
|
293
|
+
})), ...turn.prompt.text === "" ? [] : [{
|
|
294
|
+
type: "text",
|
|
295
|
+
text: turn.prompt.text
|
|
296
|
+
}]],
|
|
282
297
|
calls,
|
|
283
298
|
steers,
|
|
284
299
|
end: turn.end
|
|
285
300
|
};
|
|
286
301
|
}
|
|
302
|
+
/** libfx steers with text alone, so a steer's files fail the step. */
|
|
303
|
+
function steerText(input) {
|
|
304
|
+
if (input.files.length > 0) throw new Error("fx() steers with text only: send files in a message of their own");
|
|
305
|
+
return input.text;
|
|
306
|
+
}
|
|
287
307
|
/** A completed generation's model calls: its compactions, then its step. */
|
|
288
308
|
function recordedCalls(chunks, completed) {
|
|
289
309
|
const calls = [];
|
|
@@ -585,7 +605,7 @@ function kernelModel(step) {
|
|
|
585
605
|
};
|
|
586
606
|
}
|
|
587
607
|
async function kernelTools(tools, execute) {
|
|
588
|
-
return Promise.all(Object.entries(tools).
|
|
608
|
+
return Promise.all(Object.entries(tools).map(async ([toolName, tool]) => ({
|
|
589
609
|
name: toolName,
|
|
590
610
|
description: typeof tool.description === "string" ? tool.description : toolName,
|
|
591
611
|
inputSchema: await asSchema(tool.inputSchema).jsonSchema,
|
package/dist/ai-fx.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-fx.js","names":[],"sources":["../src/ai-fx.ts"],"sourcesContent":["/**\n * experimental-a2/ai/fx — `fx()`: the FX harness for `agent({ harness })`.\n * Server-only; FX's kernel comes from the optional `libfx` peer dependency.\n */\n\n// oxlint-disable no-await-in-loop -- turns replay in order, each on the kernel the last one left.\n\nimport {\n asSchema,\n type FinishReason,\n type LanguageModelUsage,\n type ToolSet,\n type UIMessageChunk,\n} from 'ai'\nimport type { FxAgent, FxHostTool, FxTurn } from 'libfx'\nimport {\n type Deferred,\n defineHarness,\n deferred,\n Divergence,\n gatewayCredential,\n type GatewayCredential,\n type Harness,\n type HarnessGeneration,\n type HarnessRead,\n type HarnessStep,\n type HarnessTurn,\n pending,\n readHarness,\n saveHarness,\n} from './ai-harness.ts'\nimport type { CompactionPartData, GenerationCompletedPayload } from './ai.ts'\nimport { schemaInput } from './ai-tool-input.ts'\nimport { boundedCache } from './bounded-cache.ts'\n\nexport type { Harness } from './ai-harness.ts'\n\n/**\n * The FX harness. Every model call FX makes is one durable step; A2 rebuilds\n * the kernel for each step from its latest checkpoint and the log since.\n */\nexport function fx(): Harness<'fx', never> {\n return defineHarness('fx', {\n tools: {},\n step: runStep,\n })\n}\n\nconst SNAPSHOT_VERSION = 1\nconst CATALOG_TTL_MS = 60 * 60 * 1000\n\ntype StreamPart = { type: string } & Record<string, unknown>\n/** A recorded tool call, with the input the kernel reads from its text. */\ntype ToolCall = { toolCallId: string; toolName: string; input: unknown }\n\n/** A model response A2 recorded, in the Gateway's stream format. */\ntype RecordedCall = {\n kind: 'step' | 'compaction'\n sse: string\n toolCalls: ToolCall[]\n}\n\n/** One FX turn to replay: its prompt, recorded calls, and how it ended. */\ntype TurnPlan = {\n prompt: string\n calls: RecordedCall[]\n /** Steering to queue while serving the call at that index. */\n steers: Map<number, string[]>\n end: 'stop' | 'interrupted' | 'live'\n}\n\ntype Completion = { finishReason?: FinishReason; usage?: LanguageModelUsage }\n\n/** The turn being replayed or run live, as the fetch and tool hooks see it. */\ntype TurnState = {\n plan: TurnPlan\n fxTurn: FxTurn\n next: number\n /** Tool calls of the last served step and the ones already answered. */\n served: ToolCall[]\n answered: Set<string>\n live: boolean\n liveStep: boolean\n failure?: Error\n /** Resolves when the live step is over: FX asked for its tools. */\n toolsRequested: Deferred\n parsed?: Promise<void>\n}\n\nfunction fail(state: TurnState, error: Error): never {\n state.failure ??= error\n state.fxTurn.cancel()\n throw state.failure\n}\n\nconst diverged = (message: string): Divergence => new Divergence('FX', message)\n\n// ---------------------------------------------------------------- step\n\nasync function runStep(step: HarnessStep): Promise<HarnessGeneration> {\n const { createFxAgent } = await loadLibfx()\n const credential = gatewayCredential('fx')\n const name = `${step.agentName}.a2.harness.fx`\n const { replayAll, ...first } = await readHarness({\n step,\n name,\n parse: savedCheckpoint,\n })\n let read: HarnessRead<Uint8Array> = first\n\n let completion: Completion = {}\n let stopped = false\n // Live responses belong to the step: the kernel aborts its fetch once it\n // has read a response's finish, while A2 may still be reading its copy.\n const released = new AbortController()\n const network = AbortSignal.any([step.signal, released.signal])\n let agent: FxAgent | undefined\n let turn: TurnState | undefined\n\n const run = async (\n controller: ReadableStreamDefaultController<UIMessageChunk>,\n turns: TurnPlan[],\n ): Promise<void> => {\n controller.enqueue({ type: 'start', messageId: step.responseMessageId })\n for (const plan of turns) {\n if (stopped) return\n const fxTurn = agent!.prompt(plan.prompt, { signal: step.signal })\n const state: TurnState = {\n plan,\n fxTurn,\n next: 0,\n served: [],\n answered: new Set(),\n live: false,\n liveStep: false,\n toolsRequested: deferred(),\n }\n turn = state\n const drained = (async () => {\n for await (const _ of fxTurn) {\n // Live output reaches A2 from the Gateway response itself.\n }\n })()\n // A failed turn surfaces through its result.\n drained.catch(() => {})\n if (plan.end !== 'live') {\n const result = await fxTurn.result.catch((error: unknown) => {\n throw state.failure ?? error\n })\n await drained\n if (state.failure) throw state.failure\n const expected = plan.end === 'stop' ? 'end_turn' : 'cancelled'\n if (result.stopReason !== expected)\n throw diverged(\n `a recorded turn ended with ${result.stopReason}, not ${expected}`,\n )\n continue\n }\n const outcome = await Promise.race([\n fxTurn.result.then((result) => ({ ended: true, result })),\n state.toolsRequested.promise.then(() => ({ ended: false as const })),\n ]).catch((error: unknown) => {\n throw state.failure ?? error\n })\n if (state.failure) throw state.failure\n await state.parsed\n if (outcome.ended) {\n await drained\n // Only a turn this attempt finished describes the log.\n if (outcome.result.stopReason === 'end_turn' && !step.signal.aborted)\n await saveCheckpoint()\n } else {\n // FX now waits on tools that A2's tool handlers run.\n fxTurn.cancel()\n }\n controller.enqueue({ type: 'finish-step' })\n controller.enqueue({\n type: 'finish',\n ...(completion.finishReason === undefined\n ? {}\n : { finishReason: completion.finishReason }),\n })\n }\n }\n\n const saveCheckpoint = async (): Promise<void> => {\n let checkpoint: Uint8Array\n try {\n checkpoint = await agent!.checkpoint()\n } catch {\n // Over libfx's bound: later steps replay from the previous snapshot.\n return\n }\n await saveHarness({\n step,\n name,\n state: {\n version: SNAPSHOT_VERSION,\n checkpoint: Buffer.from(checkpoint).toString('base64'),\n },\n })\n }\n\n const hostFetch = async (\n input: string | URL | Request,\n init: RequestInit = {},\n ): Promise<Response> => {\n const url = input instanceof Request ? input.url : String(input)\n if ((init.method ?? 'GET').toUpperCase() === 'GET')\n return catalog(url, credential, withAuth(init.headers, credential))\n const state = turn!\n if (state.failure) throw state.failure\n const body = decodeBody(init.body)\n const compaction = isCompaction(body)\n const recorded = state.plan.calls[state.next]\n if (recorded !== undefined) {\n if ((recorded.kind === 'compaction') !== compaction)\n fail(state, diverged(`request ${state.next} is not a ${recorded.kind}`))\n const index = state.next++\n if (recorded.kind === 'step') {\n state.served = recorded.toolCalls\n state.answered = new Set()\n }\n const steers = state.plan.steers.get(index) ?? []\n return relay(recorded.sse, async () => {\n for (const text of steers) await state.fxTurn.steer(text)\n })\n }\n if (state.plan.end === 'stop')\n fail(state, diverged('FX continued a turn the log ended'))\n if (state.plan.end === 'interrupted') {\n state.fxTurn.cancel()\n throw new DOMException('The recorded turn was interrupted', 'AbortError')\n }\n if (state.liveStep && !compaction) {\n // One generation is one step; the next step is A2's next generation.\n state.toolsRequested.resolve()\n return pending(init.signal)\n }\n state.live = true\n return live(state, url, init, compaction)\n }\n\n let compactions = 0\n const live = async (\n state: TurnState,\n url: string,\n init: RequestInit,\n compaction: boolean,\n ): Promise<Response> => {\n const response = await fetch(url, {\n ...init,\n headers: withAuth(init.headers, credential),\n signal: network,\n })\n // Abandoned before its headers came: the kernel has moved on without it.\n if (init.signal?.aborted) {\n void response.body?.cancel()\n throw init.signal.reason\n }\n if (!response.ok || response.body === null) return response\n const [fromNetwork, forLog] = response.body.tee()\n const forKernel = init.signal\n ? fromNetwork.pipeThrough(new TransformStream(), { signal: init.signal })\n : fromNetwork\n // Live responses reach the log in request order: a compaction's part\n // precedes the step that follows it.\n const previous = state.parsed\n if (compaction) {\n // Unique across the response's generations: the transcript keys data parts by ID.\n const id = `fx-compaction:${step.requestIndex}:${compactions++}`\n state.parsed = (async () => {\n const all = await readParts(forLog)\n await previous\n emit({\n type: 'data-a2-compaction',\n id,\n data: compactionData(all),\n })\n })()\n } else {\n state.liveStep = true\n state.parsed = (async () => {\n await previous\n emit({ type: 'start-step' })\n await streamStep({\n body: forLog,\n tools: step.tools,\n emit,\n finished: (finished) => {\n completion = finished\n },\n })\n })()\n }\n // A stopped step abandons its parse; its failure surfaces through the turn.\n state.parsed.catch(() => {})\n return new Response(forKernel, {\n status: response.status,\n headers: response.headers,\n })\n }\n\n const hostTools = await kernelTools(step.tools, (toolName, toolInput) => {\n const state = turn!\n if (state.failure) throw state.failure\n const call = state.served.find(\n (candidate) =>\n candidate.toolName === toolName &&\n !state.answered.has(candidate.toolCallId) &&\n sameJson(candidate.input, toolInput),\n )\n const result = call === undefined ? undefined : results.get(call.toolCallId)\n if (call !== undefined && result !== undefined) {\n state.answered.add(call.toolCallId)\n if (result.error !== undefined) throw new Error(result.error)\n if (result.denied === true) throw new Error('The tool call was denied.')\n return result.output ?? null\n }\n if (state.live) {\n state.toolsRequested.resolve()\n return pending(undefined)\n }\n if (state.plan.end === 'interrupted') {\n state.fxTurn.cancel()\n return pending(undefined)\n }\n return fail(state, diverged(`no recorded result for ${toolName}`))\n })\n\n let turns = read.turns.map(turnPlan)\n let results = read.results\n let controller: ReadableStreamDefaultController<UIMessageChunk> | undefined\n let closed = false\n const emit = (chunk: UIMessageChunk): void => {\n if (!closed) controller!.enqueue(chunk)\n }\n\n const create = (checkpoint: Uint8Array | undefined) =>\n createFxAgent({\n apiKey: credential.token,\n model: kernelModel(step),\n ...(step.instructions.length === 0\n ? {}\n : { instructions: step.instructions }),\n tools: hostTools,\n ...(checkpoint === undefined ? {} : { checkpoint }),\n fetch: hostFetch,\n })\n\n const stream = new ReadableStream<UIMessageChunk>({\n start(streamController) {\n controller = streamController\n const abort = () => {\n stopped = true\n turn?.fxTurn.cancel()\n }\n step.signal.addEventListener('abort', abort, { once: true })\n void (async () => {\n try {\n try {\n agent = await create(read.saved)\n } catch (error) {\n if (read.saved === undefined) throw error\n // An unusable checkpoint: replay the whole log instead.\n read = await replayAll()\n turns = read.turns.map(turnPlan)\n results = read.results\n agent = await create(undefined)\n }\n await run(streamController, turns)\n closed = true\n streamController.close()\n } catch (error) {\n closed = true\n streamController.error(\n step.signal.aborted ? step.signal.reason : error,\n )\n } finally {\n released.abort()\n step.signal.removeEventListener('abort', abort)\n await agent?.close().catch(() => {})\n }\n })()\n },\n cancel() {\n closed = true\n stopped = true\n released.abort()\n turn?.fxTurn.cancel()\n },\n })\n\n return { stream, completion: () => completion }\n}\n\n// ------------------------------------------------------------ the plan\n\nfunction turnPlan(turn: HarnessTurn): TurnPlan {\n const calls: RecordedCall[] = []\n const steers = new Map<number, string[]>()\n const steer = (at: number, texts: string[] | undefined) => {\n if (texts !== undefined) steers.set(Math.max(0, at), texts)\n }\n steer(0, turn.generations.length === 0 ? turn.steers.get(0) : undefined)\n turn.generations.forEach((generation, index) => {\n calls.push(...recordedCalls(generation.chunks, generation.completed))\n // A generation's step is its last call.\n steer(calls.length - 1, turn.steers.get(index))\n })\n return { prompt: turn.prompt, calls, steers, end: turn.end }\n}\n\n/** A completed generation's model calls: its compactions, then its step. */\nfunction recordedCalls(\n chunks: readonly UIMessageChunk[],\n completed: GenerationCompletedPayload,\n): RecordedCall[] {\n const calls: RecordedCall[] = []\n const parts: StreamPart[] = []\n const toolCalls: ToolCall[] = []\n // A streamed call's input is the provider's exact text; the kernel copies it.\n const inputText = new Map<string, string>()\n for (const chunk of chunks) {\n const metadata =\n 'providerMetadata' in chunk && chunk.providerMetadata !== undefined\n ? { providerMetadata: chunk.providerMetadata }\n : {}\n switch (chunk.type) {\n case 'data-a2-compaction':\n calls.push({\n kind: 'compaction',\n sse: compactionSse(chunk.data as CompactionPartData),\n toolCalls: [],\n })\n break\n case 'text-start':\n case 'text-end':\n case 'reasoning-start':\n case 'reasoning-end':\n parts.push({ type: chunk.type, id: chunk.id, ...metadata })\n break\n case 'text-delta':\n case 'reasoning-delta':\n parts.push({\n type: chunk.type,\n id: chunk.id,\n delta: chunk.delta,\n ...metadata,\n })\n break\n case 'tool-input-start':\n inputText.set(chunk.toolCallId, '')\n parts.push({\n type: 'tool-input-start',\n id: chunk.toolCallId,\n toolName: chunk.toolName,\n ...metadata,\n })\n break\n case 'tool-input-delta':\n inputText.set(\n chunk.toolCallId,\n (inputText.get(chunk.toolCallId) ?? '') + chunk.inputTextDelta,\n )\n parts.push({\n type: 'tool-input-delta',\n id: chunk.toolCallId,\n delta: chunk.inputTextDelta,\n })\n break\n case 'tool-input-error':\n case 'tool-input-available': {\n // A call recorded without its text: input that failed to parse is\n // that text.\n const text =\n inputText.get(chunk.toolCallId) ||\n (chunk.type === 'tool-input-error' && typeof chunk.input === 'string'\n ? chunk.input\n : JSON.stringify(chunk.input))\n if (inputText.has(chunk.toolCallId))\n parts.push({ type: 'tool-input-end', id: chunk.toolCallId })\n // The kernel calls back with this text's JSON, not the input the\n // tool's schema made of it. A call it answers itself, such as one\n // whose text is not JSON, is never asked for.\n const input = parseJson(text)\n if (input !== undefined)\n toolCalls.push({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n input,\n })\n parts.push({\n type: 'tool-call',\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n input: text,\n ...metadata,\n })\n break\n }\n }\n }\n parts.push({\n type: 'finish',\n finishReason: { unified: completed.finishReason ?? 'other' },\n usage: streamUsage(completed.usage),\n })\n calls.push({ kind: 'step', sse: sse(parts), toolCalls })\n return calls\n}\n\nfunction compactionSse(data: CompactionPartData): string {\n return sse([\n { type: 'text-start', id: '0' },\n { type: 'text-delta', id: '0', delta: data.summary ?? '' },\n { type: 'text-end', id: '0' },\n {\n type: 'finish',\n finishReason: { unified: 'stop' },\n usage: streamUsage(data.usage),\n },\n ])\n}\n\n// ------------------------------------------------------- live responses\n\n/** Streams one live step response as UI chunks and reports its finish. */\nasync function streamStep({\n body,\n tools,\n emit,\n finished,\n}: {\n body: ReadableStream<Uint8Array>\n tools: ToolSet\n emit: (chunk: UIMessageChunk) => void\n finished: (completion: Completion) => void\n}): Promise<void> {\n // The tool calls whose input started streaming, and whether text arrived.\n const streamed = new Map<string, boolean>()\n for await (const part of sseParts(body)) {\n const metadata =\n part['providerMetadata'] === undefined\n ? {}\n : { providerMetadata: part['providerMetadata'] as never }\n switch (part.type) {\n case 'text-start':\n case 'text-end':\n case 'reasoning-start':\n case 'reasoning-end':\n emit({ type: part.type, id: part['id'] as string, ...metadata })\n break\n case 'text-delta':\n case 'reasoning-delta':\n emit({\n type: part.type,\n id: part['id'] as string,\n delta: part['delta'] as string,\n ...metadata,\n })\n break\n case 'tool-input-start':\n streamed.set(part['id'] as string, false)\n emit({\n type: 'tool-input-start',\n toolCallId: part['id'] as string,\n toolName: part['toolName'] as string,\n ...metadata,\n })\n break\n case 'tool-input-delta':\n if (part['delta'] !== '') streamed.set(part['id'] as string, true)\n emit({\n type: 'tool-input-delta',\n toolCallId: part['id'] as string,\n inputTextDelta: part['delta'] as string,\n })\n break\n case 'tool-call': {\n const toolCallId = part['toolCallId'] as string\n const toolName = part['toolName'] as string\n const text = part['input'] as string\n // Replay hands the kernel the text the log holds, so the log keeps\n // the provider's text when it streamed none.\n if (streamed.get(toolCallId) !== true && text !== '') {\n if (!streamed.has(toolCallId))\n emit({ type: 'tool-input-start', toolCallId, toolName })\n emit({ type: 'tool-input-delta', toolCallId, inputTextDelta: text })\n }\n const input = await parseToolInput({\n tools,\n toolName,\n text,\n })\n emit(\n input.success\n ? {\n type: 'tool-input-available',\n toolCallId,\n toolName,\n input: input.value,\n ...metadata,\n }\n : {\n type: 'tool-input-error',\n toolCallId,\n toolName,\n input: input.input,\n errorText: input.errorText,\n ...metadata,\n },\n )\n break\n }\n case 'finish': {\n const reason = part['finishReason'] as { unified?: FinishReason }\n finished({\n ...(reason?.unified === undefined\n ? {}\n : { finishReason: reason.unified }),\n usage: modelUsage(part['usage']),\n })\n break\n }\n case 'error':\n emit({ type: 'error', errorText: errorText(part['error']) })\n break\n }\n }\n}\n\ntype ToolInput =\n | { success: true; value: unknown }\n | { success: false; input: unknown; errorText: string }\n\n/**\n * A live call's input as the AI SDK step reads it: JSON, then the tool's\n * schema with its defaults. Input that fails either is an input error, which\n * A2 answers without running the tool.\n */\nasync function parseToolInput({\n tools,\n toolName,\n text,\n}: {\n tools: ToolSet\n toolName: string\n text: string\n}): Promise<ToolInput> {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch (error) {\n return { success: false, input: text, errorText: errorText(error) }\n }\n const input = await schemaInput({ tools, toolName, value })\n return input.success ? input : { ...input, input: value }\n}\n\nasync function readParts(\n body: ReadableStream<Uint8Array>,\n): Promise<StreamPart[]> {\n const all: StreamPart[] = []\n for await (const part of sseParts(body)) all.push(part)\n return all\n}\n\nfunction compactionData(all: readonly StreamPart[]): CompactionPartData {\n const finish = all.find((part) => part.type === 'finish')\n return {\n status: 'completed',\n summary: all\n .filter((part) => part.type === 'text-delta')\n .map((part) => part['delta'] as string)\n .join(''),\n ...(finish === undefined ? {} : { usage: modelUsage(finish['usage']) }),\n }\n}\n\nasync function* sseParts(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<StreamPart> {\n const decoder = new TextDecoder()\n let pendingText = ''\n for await (const chunk of body) {\n pendingText += decoder.decode(chunk, { stream: true })\n let end: number\n while ((end = pendingText.indexOf('\\n\\n')) !== -1) {\n const frame = pendingText.slice(0, end)\n pendingText = pendingText.slice(end + 2)\n if (frame.startsWith('data: {')) yield JSON.parse(frame.slice(6))\n }\n }\n}\n\n/**\n * Hands a recorded response to the kernel frame by frame. Steering due after\n * it is queued before its finish part, while the kernel still waits on it.\n */\nfunction relay(text: string, beforeFinish: () => Promise<void>): Response {\n const encoder = new TextEncoder()\n const frames = text.split(/(?<=\\n\\n)/)\n let index = 0\n let steered = false\n return new Response(\n new ReadableStream({\n async pull(controller) {\n const frame = frames[index++]\n if (frame === undefined) {\n controller.close()\n return\n }\n if (!steered && frame.includes('\"type\":\"finish\"')) {\n steered = true\n await beforeFinish()\n }\n controller.enqueue(encoder.encode(frame))\n },\n }),\n { headers: { 'content-type': 'text/event-stream' } },\n )\n}\n\n// ----------------------------------------------------------- the kernel\n\nasync function loadLibfx(): Promise<typeof import('libfx')> {\n try {\n return await import('libfx')\n } catch (error) {\n throw new Error('fx() needs the libfx package: install libfx', {\n cause: error,\n })\n }\n}\n\nfunction withAuth(\n headers: HeadersInit | undefined,\n credential: GatewayCredential,\n): Headers {\n const result = new Headers(headers)\n result.set('ai-gateway-auth-method', credential.method)\n return result\n}\n\nfunction kernelModel(\n step: HarnessStep,\n): string | { id: string; effort?: string; fast?: boolean } {\n const effort =\n step.reasoning === undefined || step.reasoning === 'provider-default'\n ? undefined\n : step.reasoning\n const fast = step.speed === 'fast'\n if (effort === undefined && !fast) return step.model\n return {\n id: step.model,\n ...(effort === undefined ? {} : { effort }),\n ...(fast ? { fast } : {}),\n }\n}\n\nasync function kernelTools(\n tools: ToolSet,\n execute: (toolName: string, input: unknown) => unknown,\n): Promise<FxHostTool[]> {\n return Promise.all(\n Object.entries(tools)\n .filter(([, tool]) => tool.type !== 'provider')\n .map(async ([toolName, tool]) => ({\n name: toolName,\n description:\n typeof tool.description === 'string' ? tool.description : toolName,\n inputSchema: (await asSchema(tool.inputSchema).jsonSchema) as object,\n execute: (input: unknown) => execute(toolName, input),\n })),\n )\n}\n\n// Keyed by credential, and Vercel's OIDC tokens rotate, so it is bounded.\nconst catalogCache = boundedCache<\n string,\n { expires: number; body: Promise<string> }\n>({ maxEntries: 16, maxBytes: 16 })\n\n/**\n * Model catalog reads, shared for an hour by every step in the process that\n * uses the same credential; credentials can see different catalogs.\n */\nasync function catalog(\n url: string,\n credential: GatewayCredential,\n headers: Headers,\n): Promise<Response> {\n const key = `${url}\\n${credential.token}`\n const now = Date.now()\n let entry = catalogCache.get(key)\n if (entry === undefined || entry.expires <= now) {\n const body = fetch(url, { headers }).then(async (response) => {\n if (!response.ok)\n throw new Error(`catalog request failed: ${response.status}`)\n return response.text()\n })\n entry = { expires: now + CATALOG_TTL_MS, body }\n catalogCache.set(key, entry, 1)\n body.catch(() => catalogCache.delete(key))\n }\n return new Response(await entry.body, {\n headers: { 'content-type': 'application/json' },\n })\n}\n\n// ------------------------------------------------------------- helpers\n\nfunction savedCheckpoint(state: unknown): Uint8Array | undefined {\n if (typeof state !== 'object' || state === null) return undefined\n const { version, checkpoint } = state as Record<string, unknown>\n if (version !== SNAPSHOT_VERSION || typeof checkpoint !== 'string')\n return undefined\n return new Uint8Array(Buffer.from(checkpoint, 'base64'))\n}\n\nfunction isCompaction(body: string): boolean {\n const request = JSON.parse(body) as { toolChoice?: { type?: string } }\n return request.toolChoice?.type === 'none'\n}\n\nfunction decodeBody(body: BodyInit | null | undefined): string {\n if (typeof body === 'string') return body\n if (body instanceof Uint8Array || body instanceof ArrayBuffer)\n return new TextDecoder().decode(body)\n throw new TypeError('FX sent an unexpected request body')\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n\nfunction sameJson(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b)\n}\n\nfunction sse(all: readonly object[]): string {\n return (\n all.map((part) => `data: ${JSON.stringify(part)}\\n\\n`).join('') +\n 'data: [DONE]\\n\\n'\n )\n}\n\nfunction errorText(error: unknown): string {\n if (typeof error === 'string') return error\n if (error instanceof Error) return error.message\n return JSON.stringify(error)\n}\n\ntype StreamUsage = {\n inputTokens?: {\n total?: number | undefined\n noCache?: number | undefined\n cacheRead?: number | undefined\n cacheWrite?: number | undefined\n }\n outputTokens?: {\n total?: number | undefined\n text?: number | undefined\n reasoning?: number | undefined\n }\n}\n\n/** A Gateway stream usage, as AI SDK normalizes it. */\nfunction modelUsage(value: unknown): LanguageModelUsage {\n const usage = (value ?? {}) as StreamUsage\n const input = usage.inputTokens ?? {}\n const output = usage.outputTokens ?? {}\n return {\n inputTokens: input.total,\n inputTokenDetails: {\n noCacheTokens: input.noCache,\n cacheReadTokens: input.cacheRead,\n cacheWriteTokens: input.cacheWrite,\n },\n outputTokens: output.total,\n outputTokenDetails: {\n textTokens: output.text,\n reasoningTokens: output.reasoning,\n },\n totalTokens:\n input.total === undefined && output.total === undefined\n ? undefined\n : (input.total ?? 0) + (output.total ?? 0),\n }\n}\n\n/** The inverse of `modelUsage`, for replay. */\nfunction streamUsage(usage: LanguageModelUsage | undefined): StreamUsage {\n return {\n inputTokens: {\n total: usage?.inputTokens,\n noCache: usage?.inputTokenDetails?.noCacheTokens,\n cacheRead: usage?.inputTokenDetails?.cacheReadTokens,\n cacheWrite: usage?.inputTokenDetails?.cacheWriteTokens,\n },\n outputTokens: {\n total: usage?.outputTokens,\n text: usage?.outputTokenDetails?.textTokens,\n reasoning: usage?.outputTokenDetails?.reasoningTokens,\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAyCA,SAAgB,KAA2B;CACzC,OAAO,cAAc,MAAM;EACzB,OAAO,CAAC;EACR,MAAM;CACR,CAAC;AACH;AAEA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AAwCvB,SAAS,KAAK,OAAkB,OAAqB;CACnD,MAAM,YAAY;CAClB,MAAM,OAAO,OAAO;CACpB,MAAM,MAAM;AACd;AAEA,MAAM,YAAY,YAAgC,IAAI,WAAW,MAAM,OAAO;AAI9E,eAAe,QAAQ,MAA+C;CACpE,MAAM,EAAE,kBAAkB,MAAM,UAAU;CAC1C,MAAM,aAAa,kBAAkB,IAAI;CACzC,MAAM,OAAO,GAA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OAAO,mBAAmB;GACnC,WAAW,OAAO,mBAAmB;GACrC,YAAY,OAAO,mBAAmB;EACxC;EACA,cAAc;GACZ,OAAO,OAAO;GACd,MAAM,OAAO,oBAAoB;GACjC,WAAW,OAAO,oBAAoB;EACxC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"ai-fx.js","names":[],"sources":["../src/ai-fx.ts"],"sourcesContent":["/**\n * experimental-a2/ai/fx — `fx()`: the FX harness for `agent({ harness })`.\n * Server-only; FX's kernel comes from the optional `libfx` peer dependency.\n */\n\n// oxlint-disable no-await-in-loop -- turns replay in order, each on the kernel the last one left.\n\nimport {\n asSchema,\n type FinishReason,\n type LanguageModelUsage,\n type ToolSet,\n type UIMessageChunk,\n} from 'ai'\nimport type { FxAgent, FxHostTool, FxPromptBlock, FxTurn } from 'libfx'\nimport {\n type Deferred,\n defineHarness,\n deferred,\n Divergence,\n gatewayCredential,\n type GatewayCredential,\n type Harness,\n type HarnessGeneration,\n harnessImages,\n type HarnessInput,\n type HarnessRead,\n type HarnessStep,\n type HarnessTurn,\n pending,\n readHarness,\n saveHarness,\n} from './ai-harness.ts'\nimport type { CompactionPartData, GenerationCompletedPayload } from './ai.ts'\nimport { schemaInput } from './ai-tool-input.ts'\nimport { boundedCache } from './bounded-cache.ts'\n\nexport type { Harness } from './ai-harness.ts'\n\n/**\n * The FX harness. Every model call FX makes is one durable step; A2 rebuilds\n * the kernel for each step from its latest checkpoint and the log since.\n */\nexport function fx(): Harness<'fx', never> {\n return defineHarness('fx', {\n tools: {},\n step: runStep,\n })\n}\n\nconst SNAPSHOT_VERSION = 1\nconst CATALOG_TTL_MS = 60 * 60 * 1000\n/** The Gateway model catalog libfx reads for each new kernel. */\nconst CATALOG_PATH = '/coding-agent/v1/models'\n\ntype StreamPart = { type: string } & Record<string, unknown>\n/** A recorded tool call, with the input the kernel reads from its text. */\ntype ToolCall = { toolCallId: string; toolName: string; input: unknown }\n\n/** A model response A2 recorded, in the Gateway's stream format. */\ntype RecordedCall = {\n kind: 'step' | 'compaction'\n sse: string\n toolCalls: ToolCall[]\n}\n\n/** One FX turn to replay: its prompt, recorded calls, and how it ended. */\ntype TurnPlan = {\n prompt: string | FxPromptBlock[]\n calls: RecordedCall[]\n /** Steering to queue while serving the call at that index. */\n steers: Map<number, string[]>\n end: 'stop' | 'interrupted' | 'live'\n}\n\ntype Completion = { finishReason?: FinishReason; usage?: LanguageModelUsage }\n\n/** The turn being replayed or run live, as the fetch and tool hooks see it. */\ntype TurnState = {\n plan: TurnPlan\n fxTurn: FxTurn\n next: number\n /** Tool calls of the last served step and the ones already answered. */\n served: ToolCall[]\n answered: Set<string>\n live: boolean\n liveStep: boolean\n failure?: Error\n /** Resolves when the live step is over: FX asked for its tools. */\n toolsRequested: Deferred\n parsed?: Promise<void>\n}\n\nfunction fail(state: TurnState, error: Error): never {\n state.failure ??= error\n state.fxTurn.cancel()\n throw state.failure\n}\n\nconst diverged = (message: string): Divergence => new Divergence('FX', message)\n\n// ---------------------------------------------------------------- step\n\nasync function runStep(step: HarnessStep): Promise<HarnessGeneration> {\n const { createFxAgent } = await loadLibfx()\n const credential = gatewayCredential('fx')\n const name = `${step.agentName}.a2.harness.fx`\n const { replayAll, ...first } = await readHarness({\n step,\n name,\n parse: savedCheckpoint,\n })\n let read: HarnessRead<Uint8Array> = first\n\n let completion: Completion = {}\n let stopped = false\n // Live responses belong to the step: the kernel aborts its fetch once it\n // has read a response's finish, while A2 may still be reading its copy.\n const released = new AbortController()\n const network = AbortSignal.any([step.signal, released.signal])\n let agent: FxAgent | undefined\n let turn: TurnState | undefined\n\n const run = async (\n controller: ReadableStreamDefaultController<UIMessageChunk>,\n turns: TurnPlan[],\n ): Promise<void> => {\n controller.enqueue({ type: 'start', messageId: step.responseMessageId })\n for (const plan of turns) {\n if (stopped) return\n const fxTurn = agent!.prompt(plan.prompt, { signal: step.signal })\n const state: TurnState = {\n plan,\n fxTurn,\n next: 0,\n served: [],\n answered: new Set(),\n live: false,\n liveStep: false,\n toolsRequested: deferred(),\n }\n turn = state\n const drained = (async () => {\n for await (const _ of fxTurn) {\n // Live output reaches A2 from the Gateway response itself.\n }\n })()\n // A failed turn surfaces through its result.\n drained.catch(() => {})\n if (plan.end !== 'live') {\n const result = await fxTurn.result.catch((error: unknown) => {\n throw state.failure ?? error\n })\n await drained\n if (state.failure) throw state.failure\n const expected = plan.end === 'stop' ? 'end_turn' : 'cancelled'\n if (result.stopReason !== expected)\n throw diverged(\n `a recorded turn ended with ${result.stopReason}, not ${expected}`,\n )\n continue\n }\n const outcome = await Promise.race([\n fxTurn.result.then((result) => ({ ended: true, result })),\n state.toolsRequested.promise.then(() => ({ ended: false as const })),\n ]).catch((error: unknown) => {\n throw state.failure ?? error\n })\n if (state.failure) throw state.failure\n await state.parsed\n if (outcome.ended) {\n await drained\n // Only a turn this attempt finished describes the log.\n if (outcome.result.stopReason === 'end_turn' && !step.signal.aborted)\n await saveCheckpoint()\n } else {\n // FX now waits on tools that A2's tool handlers run.\n fxTurn.cancel()\n }\n controller.enqueue({ type: 'finish-step' })\n controller.enqueue({\n type: 'finish',\n ...(completion.finishReason === undefined\n ? {}\n : { finishReason: completion.finishReason }),\n })\n }\n }\n\n const saveCheckpoint = async (): Promise<void> => {\n let checkpoint: Uint8Array\n try {\n checkpoint = await agent!.checkpoint()\n } catch {\n // Later steps replay from the previous snapshot.\n return\n }\n await saveHarness({\n step,\n name,\n state: {\n version: SNAPSHOT_VERSION,\n checkpoint: Buffer.from(checkpoint).toString('base64'),\n },\n })\n }\n\n const hostFetch = async (\n input: string | URL | Request,\n init: RequestInit = {},\n ): Promise<Response> => {\n const url = input instanceof Request ? input.url : String(input)\n const method = (init.method ?? 'GET').toUpperCase()\n if (method === 'GET' && new URL(url).pathname === CATALOG_PATH)\n return catalog(url, credential, withAuth(init.headers, credential))\n if (method === 'GET') return fetch(input, init)\n const state = turn!\n if (state.failure) throw state.failure\n const body = decodeBody(init.body)\n const compaction = isCompaction(body)\n const recorded = state.plan.calls[state.next]\n if (recorded !== undefined) {\n if ((recorded.kind === 'compaction') !== compaction)\n fail(state, diverged(`request ${state.next} is not a ${recorded.kind}`))\n const index = state.next++\n if (recorded.kind === 'step') {\n state.served = recorded.toolCalls\n state.answered = new Set()\n }\n const steers = state.plan.steers.get(index) ?? []\n return relay(recorded.sse, async () => {\n for (const text of steers) await state.fxTurn.steer(text)\n })\n }\n if (state.plan.end === 'stop')\n fail(state, diverged('FX continued a turn the log ended'))\n if (state.plan.end === 'interrupted') {\n state.fxTurn.cancel()\n throw new DOMException('The recorded turn was interrupted', 'AbortError')\n }\n if (state.liveStep && !compaction) {\n // One generation is one step; the next step is A2's next generation.\n state.toolsRequested.resolve()\n return pending(init.signal)\n }\n state.live = true\n return live(state, url, init, compaction)\n }\n\n let compactions = 0\n const live = async (\n state: TurnState,\n url: string,\n init: RequestInit,\n compaction: boolean,\n ): Promise<Response> => {\n const response = await fetch(url, {\n ...init,\n headers: withAuth(init.headers, credential),\n signal: network,\n })\n // Abandoned before its headers came: the kernel has moved on without it.\n if (init.signal?.aborted) {\n void response.body?.cancel()\n throw init.signal.reason\n }\n if (!response.ok || response.body === null) return response\n const [fromNetwork, forLog] = response.body.tee()\n const forKernel = init.signal\n ? fromNetwork.pipeThrough(new TransformStream(), { signal: init.signal })\n : fromNetwork\n // Live responses reach the log in request order: a compaction's part\n // precedes the step that follows it.\n const previous = state.parsed\n if (compaction) {\n // Unique across the response's generations: the transcript keys data parts by ID.\n const id = `fx-compaction:${step.requestIndex}:${compactions++}`\n state.parsed = (async () => {\n const all = await readParts(forLog)\n await previous\n emit({\n type: 'data-a2-compaction',\n id,\n data: compactionData(all),\n })\n })()\n } else {\n state.liveStep = true\n state.parsed = (async () => {\n await previous\n emit({ type: 'start-step' })\n await streamStep({\n body: forLog,\n tools: step.tools,\n emit,\n finished: (finished) => {\n completion = finished\n },\n })\n })()\n }\n // A stopped step abandons its parse; its failure surfaces through the turn.\n state.parsed.catch(() => {})\n return new Response(forKernel, {\n status: response.status,\n headers: response.headers,\n })\n }\n\n const hostTools = await kernelTools(step.tools, (toolName, toolInput) => {\n const state = turn!\n if (state.failure) throw state.failure\n const call = state.served.find(\n (candidate) =>\n candidate.toolName === toolName &&\n !state.answered.has(candidate.toolCallId) &&\n sameJson(candidate.input, toolInput),\n )\n const result = call === undefined ? undefined : results.get(call.toolCallId)\n if (call !== undefined && result !== undefined) {\n state.answered.add(call.toolCallId)\n if (result.error !== undefined) throw new Error(result.error)\n if (result.denied === true) throw new Error('The tool call was denied.')\n return result.output ?? null\n }\n if (state.live) {\n state.toolsRequested.resolve()\n return pending(undefined)\n }\n if (state.plan.end === 'interrupted') {\n state.fxTurn.cancel()\n return pending(undefined)\n }\n return fail(state, diverged(`no recorded result for ${toolName}`))\n })\n\n const plans = (turns: HarnessTurn[]): Promise<TurnPlan[]> =>\n Promise.all(turns.map((recorded) => turnPlan(recorded, step.signal)))\n let results = read.results\n let controller: ReadableStreamDefaultController<UIMessageChunk> | undefined\n let closed = false\n const emit = (chunk: UIMessageChunk): void => {\n if (!closed) controller!.enqueue(chunk)\n }\n\n const create = (checkpoint: Uint8Array | undefined) =>\n createFxAgent({\n apiKey: credential.token,\n model: kernelModel(step),\n ...(step.instructions.length === 0\n ? {}\n : { instructions: step.instructions }),\n tools: hostTools,\n ...(checkpoint === undefined ? {} : { checkpoint }),\n fetch: hostFetch,\n })\n\n const stream = new ReadableStream<UIMessageChunk>({\n start(streamController) {\n controller = streamController\n const abort = () => {\n stopped = true\n turn?.fxTurn.cancel()\n }\n step.signal.addEventListener('abort', abort, { once: true })\n void (async () => {\n try {\n try {\n agent = await create(read.saved)\n } catch (error) {\n if (read.saved === undefined) throw error\n // An unusable checkpoint: replay the whole log instead.\n read = await replayAll()\n results = read.results\n agent = await create(undefined)\n }\n await run(streamController, await plans(read.turns))\n closed = true\n streamController.close()\n } catch (error) {\n closed = true\n streamController.error(\n step.signal.aborted ? step.signal.reason : error,\n )\n } finally {\n released.abort()\n step.signal.removeEventListener('abort', abort)\n await agent?.close().catch(() => {})\n }\n })()\n },\n cancel() {\n closed = true\n stopped = true\n released.abort()\n turn?.fxTurn.cancel()\n },\n })\n\n return { stream, completion: () => completion }\n}\n\n// ------------------------------------------------------------ the plan\n\nasync function turnPlan(\n turn: HarnessTurn,\n signal: AbortSignal,\n): Promise<TurnPlan> {\n const calls: RecordedCall[] = []\n const steers = new Map<number, string[]>()\n const steer = (at: number, inputs: HarnessInput[] | undefined) => {\n if (inputs !== undefined) steers.set(Math.max(0, at), inputs.map(steerText))\n }\n steer(0, turn.generations.length === 0 ? turn.steers.get(0) : undefined)\n turn.generations.forEach((generation, index) => {\n calls.push(...recordedCalls(generation.chunks, generation.completed))\n // A generation's step is its last call.\n steer(calls.length - 1, turn.steers.get(index))\n })\n const images = await harnessImages({\n harness: 'fx()',\n input: turn.prompt,\n signal,\n })\n return {\n prompt:\n images.length === 0\n ? turn.prompt.text\n : [\n ...images.map((image): FxPromptBlock => ({\n type: 'image',\n data: image.data,\n mimeType: image.mediaType,\n })),\n ...(turn.prompt.text === ''\n ? []\n : [{ type: 'text' as const, text: turn.prompt.text }]),\n ],\n calls,\n steers,\n end: turn.end,\n }\n}\n\n/** libfx steers with text alone, so a steer's files fail the step. */\nfunction steerText(input: HarnessInput): string {\n if (input.files.length > 0)\n throw new Error(\n 'fx() steers with text only: send files in a message of their own',\n )\n return input.text\n}\n\n/** A completed generation's model calls: its compactions, then its step. */\nfunction recordedCalls(\n chunks: readonly UIMessageChunk[],\n completed: GenerationCompletedPayload,\n): RecordedCall[] {\n const calls: RecordedCall[] = []\n const parts: StreamPart[] = []\n const toolCalls: ToolCall[] = []\n // A streamed call's input is the provider's exact text; the kernel copies it.\n const inputText = new Map<string, string>()\n for (const chunk of chunks) {\n const metadata =\n 'providerMetadata' in chunk && chunk.providerMetadata !== undefined\n ? { providerMetadata: chunk.providerMetadata }\n : {}\n switch (chunk.type) {\n case 'data-a2-compaction':\n calls.push({\n kind: 'compaction',\n sse: compactionSse(chunk.data as CompactionPartData),\n toolCalls: [],\n })\n break\n case 'text-start':\n case 'text-end':\n case 'reasoning-start':\n case 'reasoning-end':\n parts.push({ type: chunk.type, id: chunk.id, ...metadata })\n break\n case 'text-delta':\n case 'reasoning-delta':\n parts.push({\n type: chunk.type,\n id: chunk.id,\n delta: chunk.delta,\n ...metadata,\n })\n break\n case 'tool-input-start':\n inputText.set(chunk.toolCallId, '')\n parts.push({\n type: 'tool-input-start',\n id: chunk.toolCallId,\n toolName: chunk.toolName,\n ...metadata,\n })\n break\n case 'tool-input-delta':\n inputText.set(\n chunk.toolCallId,\n (inputText.get(chunk.toolCallId) ?? '') + chunk.inputTextDelta,\n )\n parts.push({\n type: 'tool-input-delta',\n id: chunk.toolCallId,\n delta: chunk.inputTextDelta,\n })\n break\n case 'tool-input-error':\n case 'tool-input-available': {\n // A call recorded without its text: input that failed to parse is\n // that text.\n const text =\n inputText.get(chunk.toolCallId) ||\n (chunk.type === 'tool-input-error' && typeof chunk.input === 'string'\n ? chunk.input\n : JSON.stringify(chunk.input))\n if (inputText.has(chunk.toolCallId))\n parts.push({ type: 'tool-input-end', id: chunk.toolCallId })\n // The kernel calls back with this text's JSON, not the input the\n // tool's schema made of it. A call it answers itself, such as one\n // whose text is not JSON, is never asked for.\n const input = parseJson(text)\n if (input !== undefined)\n toolCalls.push({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n input,\n })\n parts.push({\n type: 'tool-call',\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n input: text,\n ...metadata,\n })\n break\n }\n }\n }\n parts.push({\n type: 'finish',\n finishReason: { unified: completed.finishReason ?? 'other' },\n usage: streamUsage(completed.usage),\n })\n calls.push({ kind: 'step', sse: sse(parts), toolCalls })\n return calls\n}\n\nfunction compactionSse(data: CompactionPartData): string {\n return sse([\n { type: 'text-start', id: '0' },\n { type: 'text-delta', id: '0', delta: data.summary ?? '' },\n { type: 'text-end', id: '0' },\n {\n type: 'finish',\n finishReason: { unified: 'stop' },\n usage: streamUsage(data.usage),\n },\n ])\n}\n\n// ------------------------------------------------------- live responses\n\n/** Streams one live step response as UI chunks and reports its finish. */\nasync function streamStep({\n body,\n tools,\n emit,\n finished,\n}: {\n body: ReadableStream<Uint8Array>\n tools: ToolSet\n emit: (chunk: UIMessageChunk) => void\n finished: (completion: Completion) => void\n}): Promise<void> {\n // The tool calls whose input started streaming, and whether text arrived.\n const streamed = new Map<string, boolean>()\n for await (const part of sseParts(body)) {\n const metadata =\n part['providerMetadata'] === undefined\n ? {}\n : { providerMetadata: part['providerMetadata'] as never }\n switch (part.type) {\n case 'text-start':\n case 'text-end':\n case 'reasoning-start':\n case 'reasoning-end':\n emit({ type: part.type, id: part['id'] as string, ...metadata })\n break\n case 'text-delta':\n case 'reasoning-delta':\n emit({\n type: part.type,\n id: part['id'] as string,\n delta: part['delta'] as string,\n ...metadata,\n })\n break\n case 'tool-input-start':\n streamed.set(part['id'] as string, false)\n emit({\n type: 'tool-input-start',\n toolCallId: part['id'] as string,\n toolName: part['toolName'] as string,\n ...metadata,\n })\n break\n case 'tool-input-delta':\n if (part['delta'] !== '') streamed.set(part['id'] as string, true)\n emit({\n type: 'tool-input-delta',\n toolCallId: part['id'] as string,\n inputTextDelta: part['delta'] as string,\n })\n break\n case 'tool-call': {\n const toolCallId = part['toolCallId'] as string\n const toolName = part['toolName'] as string\n const text = part['input'] as string\n // Replay hands the kernel the text the log holds, so the log keeps\n // the provider's text when it streamed none.\n if (streamed.get(toolCallId) !== true && text !== '') {\n if (!streamed.has(toolCallId))\n emit({ type: 'tool-input-start', toolCallId, toolName })\n emit({ type: 'tool-input-delta', toolCallId, inputTextDelta: text })\n }\n const input = await parseToolInput({\n tools,\n toolName,\n text,\n })\n emit(\n input.success\n ? {\n type: 'tool-input-available',\n toolCallId,\n toolName,\n input: input.value,\n ...metadata,\n }\n : {\n type: 'tool-input-error',\n toolCallId,\n toolName,\n input: input.input,\n errorText: input.errorText,\n ...metadata,\n },\n )\n break\n }\n case 'finish': {\n const reason = part['finishReason'] as { unified?: FinishReason }\n finished({\n ...(reason?.unified === undefined\n ? {}\n : { finishReason: reason.unified }),\n usage: modelUsage(part['usage']),\n })\n break\n }\n case 'error':\n emit({ type: 'error', errorText: errorText(part['error']) })\n break\n }\n }\n}\n\ntype ToolInput =\n | { success: true; value: unknown }\n | { success: false; input: unknown; errorText: string }\n\n/**\n * A live call's input as the AI SDK step reads it: JSON, then the tool's\n * schema with its defaults. Input that fails either is an input error, which\n * A2 answers without running the tool.\n */\nasync function parseToolInput({\n tools,\n toolName,\n text,\n}: {\n tools: ToolSet\n toolName: string\n text: string\n}): Promise<ToolInput> {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch (error) {\n return { success: false, input: text, errorText: errorText(error) }\n }\n const input = await schemaInput({ tools, toolName, value })\n return input.success ? input : { ...input, input: value }\n}\n\nasync function readParts(\n body: ReadableStream<Uint8Array>,\n): Promise<StreamPart[]> {\n const all: StreamPart[] = []\n for await (const part of sseParts(body)) all.push(part)\n return all\n}\n\nfunction compactionData(all: readonly StreamPart[]): CompactionPartData {\n const finish = all.find((part) => part.type === 'finish')\n return {\n status: 'completed',\n summary: all\n .filter((part) => part.type === 'text-delta')\n .map((part) => part['delta'] as string)\n .join(''),\n ...(finish === undefined ? {} : { usage: modelUsage(finish['usage']) }),\n }\n}\n\nasync function* sseParts(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<StreamPart> {\n const decoder = new TextDecoder()\n let pendingText = ''\n for await (const chunk of body) {\n pendingText += decoder.decode(chunk, { stream: true })\n let end: number\n while ((end = pendingText.indexOf('\\n\\n')) !== -1) {\n const frame = pendingText.slice(0, end)\n pendingText = pendingText.slice(end + 2)\n if (frame.startsWith('data: {')) yield JSON.parse(frame.slice(6))\n }\n }\n}\n\n/**\n * Hands a recorded response to the kernel frame by frame. Steering due after\n * it is queued before its finish part, while the kernel still waits on it.\n */\nfunction relay(text: string, beforeFinish: () => Promise<void>): Response {\n const encoder = new TextEncoder()\n const frames = text.split(/(?<=\\n\\n)/)\n let index = 0\n let steered = false\n return new Response(\n new ReadableStream({\n async pull(controller) {\n const frame = frames[index++]\n if (frame === undefined) {\n controller.close()\n return\n }\n if (!steered && frame.includes('\"type\":\"finish\"')) {\n steered = true\n await beforeFinish()\n }\n controller.enqueue(encoder.encode(frame))\n },\n }),\n { headers: { 'content-type': 'text/event-stream' } },\n )\n}\n\n// ----------------------------------------------------------- the kernel\n\nasync function loadLibfx(): Promise<typeof import('libfx')> {\n try {\n return await import('libfx')\n } catch (error) {\n throw new Error('fx() needs the libfx package: install libfx', {\n cause: error,\n })\n }\n}\n\nfunction withAuth(\n headers: HeadersInit | undefined,\n credential: GatewayCredential,\n): Headers {\n const result = new Headers(headers)\n result.set('ai-gateway-auth-method', credential.method)\n return result\n}\n\nfunction kernelModel(\n step: HarnessStep,\n): string | { id: string; effort?: string; fast?: boolean } {\n const effort =\n step.reasoning === undefined || step.reasoning === 'provider-default'\n ? undefined\n : step.reasoning\n const fast = step.speed === 'fast'\n if (effort === undefined && !fast) return step.model\n return {\n id: step.model,\n ...(effort === undefined ? {} : { effort }),\n ...(fast ? { fast } : {}),\n }\n}\n\nasync function kernelTools(\n tools: ToolSet,\n execute: (toolName: string, input: unknown) => unknown,\n): Promise<FxHostTool[]> {\n return Promise.all(\n Object.entries(tools).map(async ([toolName, tool]) => ({\n name: toolName,\n description:\n typeof tool.description === 'string' ? tool.description : toolName,\n inputSchema: (await asSchema(tool.inputSchema).jsonSchema) as object,\n execute: (input: unknown) => execute(toolName, input),\n })),\n )\n}\n\n// Keyed by credential, and Vercel's OIDC tokens rotate, so it is bounded.\nconst catalogCache = boundedCache<\n string,\n { expires: number; body: Promise<string> }\n>({ maxEntries: 16, maxBytes: 16 })\n\n/**\n * Model catalog reads, shared for an hour by every step in the process that\n * uses the same credential; credentials can see different catalogs.\n */\nasync function catalog(\n url: string,\n credential: GatewayCredential,\n headers: Headers,\n): Promise<Response> {\n const key = `${url}\\n${credential.token}`\n const now = Date.now()\n let entry = catalogCache.get(key)\n if (entry === undefined || entry.expires <= now) {\n const body = fetch(url, { headers }).then(async (response) => {\n if (!response.ok)\n throw new Error(`catalog request failed: ${response.status}`)\n return response.text()\n })\n entry = { expires: now + CATALOG_TTL_MS, body }\n catalogCache.set(key, entry, 1)\n body.catch(() => catalogCache.delete(key))\n }\n return new Response(await entry.body, {\n headers: { 'content-type': 'application/json' },\n })\n}\n\n// ------------------------------------------------------------- helpers\n\nfunction savedCheckpoint(state: unknown): Uint8Array | undefined {\n if (typeof state !== 'object' || state === null) return undefined\n const { version, checkpoint } = state as Record<string, unknown>\n if (version !== SNAPSHOT_VERSION || typeof checkpoint !== 'string')\n return undefined\n return new Uint8Array(Buffer.from(checkpoint, 'base64'))\n}\n\nfunction isCompaction(body: string): boolean {\n const request = JSON.parse(body) as { toolChoice?: { type?: string } }\n return request.toolChoice?.type === 'none'\n}\n\nfunction decodeBody(body: BodyInit | null | undefined): string {\n if (typeof body === 'string') return body\n if (body instanceof Uint8Array || body instanceof ArrayBuffer)\n return new TextDecoder().decode(body)\n throw new TypeError('FX sent an unexpected request body')\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n\nfunction sameJson(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b)\n}\n\nfunction sse(all: readonly object[]): string {\n return (\n all.map((part) => `data: ${JSON.stringify(part)}\\n\\n`).join('') +\n 'data: [DONE]\\n\\n'\n )\n}\n\nfunction errorText(error: unknown): string {\n if (typeof error === 'string') return error\n if (error instanceof Error) return error.message\n return JSON.stringify(error)\n}\n\ntype StreamUsage = {\n inputTokens?: {\n total?: number | undefined\n noCache?: number | undefined\n cacheRead?: number | undefined\n cacheWrite?: number | undefined\n }\n outputTokens?: {\n total?: number | undefined\n text?: number | undefined\n reasoning?: number | undefined\n }\n}\n\n/** A Gateway stream usage, as AI SDK normalizes it. */\nfunction modelUsage(value: unknown): LanguageModelUsage {\n const usage = (value ?? {}) as StreamUsage\n const input = usage.inputTokens ?? {}\n const output = usage.outputTokens ?? {}\n return {\n inputTokens: input.total,\n inputTokenDetails: {\n noCacheTokens: input.noCache,\n cacheReadTokens: input.cacheRead,\n cacheWriteTokens: input.cacheWrite,\n },\n outputTokens: output.total,\n outputTokenDetails: {\n textTokens: output.text,\n reasoningTokens: output.reasoning,\n },\n totalTokens:\n input.total === undefined && output.total === undefined\n ? undefined\n : (input.total ?? 0) + (output.total ?? 0),\n }\n}\n\n/** The inverse of `modelUsage`, for replay. */\nfunction streamUsage(usage: LanguageModelUsage | undefined): StreamUsage {\n return {\n inputTokens: {\n total: usage?.inputTokens,\n noCache: usage?.inputTokenDetails?.noCacheTokens,\n cacheRead: usage?.inputTokenDetails?.cacheReadTokens,\n cacheWrite: usage?.inputTokenDetails?.cacheWriteTokens,\n },\n outputTokens: {\n total: usage?.outputTokens,\n text: usage?.outputTokenDetails?.textTokens,\n reasoning: usage?.outputTokenDetails?.reasoningTokens,\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA2CA,SAAgB,KAA2B;CACzC,OAAO,cAAc,MAAM;EACzB,OAAO,CAAC;EACR,MAAM;CACR,CAAC;AACH;AAEA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;AAEvB,MAAM,eAAe;AAwCrB,SAAS,KAAK,OAAkB,OAAqB;CACnD,MAAM,YAAY;CAClB,MAAM,OAAO,OAAO;CACpB,MAAM,MAAM;AACd;AAEA,MAAM,YAAY,YAAgC,IAAI,WAAW,MAAM,OAAO;AAI9E,eAAe,QAAQ,MAA+C;CACpE,MAAM,EAAE,kBAAkB,MAAM,UAAU;CAC1C,MAAM,aAAa,kBAAkB,IAAI;CACzC,MAAM,OAAO,GAAG,KAAK,UAAU;CAC/B,MAAM,EAAE,WAAW,GAAG,UAAU,MAAM,YAAY;EAChD;EACA;EACA,OAAO;CACT,CAAC;CACD,IAAI,OAAgC;CAEpC,IAAI,aAAyB,CAAC;CAC9B,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