@guuey/agent-client 0.3.1 → 0.5.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/README.md +54 -7
- package/dist/error-codes.d.ts +87 -0
- package/dist/error-codes.d.ts.map +1 -0
- package/dist/error-codes.js +82 -0
- package/dist/errors.d.ts +39 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +36 -0
- package/dist/history.d.ts +1 -1
- package/dist/history.d.ts.map +1 -1
- package/dist/index.d.ts +13 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +31 -6
- package/dist/invoke-turn.d.ts +101 -0
- package/dist/invoke-turn.d.ts.map +1 -0
- package/dist/invoke-turn.js +124 -0
- package/dist/react.d.ts +1 -1
- package/dist/react.d.ts.map +1 -1
- package/dist/react.js +1 -1
- package/dist/saturation-retry.d.ts +101 -0
- package/dist/saturation-retry.d.ts.map +1 -0
- package/dist/saturation-retry.js +207 -0
- package/dist/sse.d.ts +1 -1
- package/dist/sse.d.ts.map +1 -1
- package/dist/transport.d.ts +90 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +189 -0
- package/dist/types.d.ts +101 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/useAgentInvoke.d.ts +29 -1
- package/dist/useAgentInvoke.d.ts.map +1 -1
- package/dist/useAgentInvoke.js +297 -86
- package/dist/web-adapters.d.ts +30 -34
- package/dist/web-adapters.d.ts.map +1 -1
- package/dist/web-adapters.js +72 -123
- package/package.json +11 -5
- package/src/error-codes.ts +89 -0
- package/src/errors.ts +35 -0
- package/src/history.ts +1 -1
- package/src/index.ts +50 -10
- package/src/invoke-turn.ts +187 -0
- package/src/react.ts +7 -1
- package/src/saturation-retry.ts +247 -0
- package/src/sse.ts +1 -1
- package/src/transport.ts +260 -0
- package/src/types.ts +102 -3
- package/src/useAgentInvoke.ts +288 -86
- package/src/web-adapters.ts +92 -134
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* invokeTurn — one agent turn as a pure async generator (guuey#186 G5).
|
|
3
|
+
*
|
|
4
|
+
* The per-turn loop `useAgentInvoke` runs — SSE accumulate → event switch →
|
|
5
|
+
* cumulative text fold → AgJSON block ingest — used to exist only fused to
|
|
6
|
+
* React state inside the hook, so a host with its own turn state machine
|
|
7
|
+
* (a game loop, a native view model, a server-side driver) had to re-walk
|
|
8
|
+
* the wire switch by hand. This module IS that loop, wire-in / semantics-out
|
|
9
|
+
* and React-free: feed it the request and a transport, iterate
|
|
10
|
+
* {@link InvokeTurnEvent}s. The hook is a thin wrapper that maps each event
|
|
11
|
+
* onto its state setters — behaviour-identical, one walk of the switch,
|
|
12
|
+
* owned here.
|
|
13
|
+
*
|
|
14
|
+
* Turn-scoped by design: the generator owns the CUMULATIVE assistant text
|
|
15
|
+
* for this turn (every `message` event carries the full folded text so far,
|
|
16
|
+
* not a delta). Cross-turn state stays with the caller — notably the AgJSON
|
|
17
|
+
* `Reducer`, which folds an entire conversation: this generator yields each
|
|
18
|
+
* frame's validated `agEvents` and never touches a reducer.
|
|
19
|
+
*
|
|
20
|
+
* Transport failures (e.g. `AgentResponseError` on a pre-stream refusal)
|
|
21
|
+
* propagate out of iteration — catch around the `for await`, exactly as the
|
|
22
|
+
* hook does. Unknown SSE events yield nothing, matching the hook's silent
|
|
23
|
+
* fall-through, so new wire events are additive for every consumer.
|
|
24
|
+
*/
|
|
25
|
+
import type { AgEvent } from "@silverprotocol/core";
|
|
26
|
+
import {
|
|
27
|
+
parseConsentRequest,
|
|
28
|
+
parseLinkRequest,
|
|
29
|
+
parseSseEvents,
|
|
30
|
+
reduceAssistantText,
|
|
31
|
+
stringField,
|
|
32
|
+
} from "./sse.js";
|
|
33
|
+
import { ingestMessageFrame } from "./blocks.js";
|
|
34
|
+
import type {
|
|
35
|
+
AgentInvokeStatus,
|
|
36
|
+
InvokeRequest,
|
|
37
|
+
InvokeTransport,
|
|
38
|
+
ProfileConsentRequest,
|
|
39
|
+
ProfileLinkRequest,
|
|
40
|
+
} from "./types.js";
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* One semantic step of a turn. Field conventions:
|
|
44
|
+
*
|
|
45
|
+
* - `message.status` / `message.activeTool` are ABSENT (not null) when the
|
|
46
|
+
* frame implies no change — apply them only when present, so an unknown
|
|
47
|
+
* frame type leaves your state machine untouched (the hook's exact rule:
|
|
48
|
+
* only `tool.start`/`tool.done` ever move `activeTool`, and a text frame
|
|
49
|
+
* moving status to `responding` does NOT clear a lingering tool name).
|
|
50
|
+
* - `message.assistantText` is the full folded text of the turn so far —
|
|
51
|
+
* render it as-is on every event; there is no delta bookkeeping to do.
|
|
52
|
+
* - `message.agEvents` are the frame's validated AgJSON events (empty for
|
|
53
|
+
* bypass frames) — push them into your own cross-turn `Reducer` if you
|
|
54
|
+
* keep a block-preserving transcript, ignore them otherwise.
|
|
55
|
+
*/
|
|
56
|
+
export type InvokeTurnEvent =
|
|
57
|
+
| { kind: "session"; threadId: string | null }
|
|
58
|
+
| {
|
|
59
|
+
kind: "message";
|
|
60
|
+
status?: Extract<AgentInvokeStatus, "thinking" | "using-tool" | "responding">;
|
|
61
|
+
activeTool?: string | null;
|
|
62
|
+
assistantText: string;
|
|
63
|
+
agEvents: AgEvent[];
|
|
64
|
+
}
|
|
65
|
+
| { kind: "error"; message: string; code: string | null }
|
|
66
|
+
| { kind: "profile-consent"; request: ProfileConsentRequest }
|
|
67
|
+
| { kind: "profile-link"; request: ProfileLinkRequest }
|
|
68
|
+
| { kind: "done"; stopReason: string | null };
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Normalize an agent endpoint to its invoke URL (guuey#186 G3). Accepts BOTH
|
|
72
|
+
* shapes a consumer legitimately holds — a pod base (`https://host`) and the
|
|
73
|
+
* full invoke URL the deploy-controller records (`https://host/agent/invoke`)
|
|
74
|
+
* — and returns exactly one `/agent/invoke`, trailing slashes dropped. This
|
|
75
|
+
* is the single normalization `useAgentInvoke` applies to its `endpointUrl`;
|
|
76
|
+
* a host driving {@link invokeTurn} (or any raw transport) directly builds
|
|
77
|
+
* its request URL with the same call instead of re-implementing the rule.
|
|
78
|
+
*/
|
|
79
|
+
export function toInvokeUrl(endpointUrl: string): string {
|
|
80
|
+
const base = endpointUrl.replace(/\/+$/, "");
|
|
81
|
+
return base.endsWith("/agent/invoke") ? base : `${base}/agent/invoke`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Drive one `/agent/invoke` turn over `transport`, yielding semantic events.
|
|
86
|
+
* Pure per-turn: no React, no storage, no retry policy (the transport owns
|
|
87
|
+
* saturation retry), no reducer — see the module docblock for what belongs
|
|
88
|
+
* to the caller.
|
|
89
|
+
*
|
|
90
|
+
* The event stream is also the OBSERVATION channel (guuey#186 Gap 4): there
|
|
91
|
+
* is deliberately no `onToolResult` callback API, because filtering the
|
|
92
|
+
* generator expresses it directly — every tool result arrives as a typed
|
|
93
|
+
* `tool.done` AgEvent on a `message` event, carrying `toolCallId`,
|
|
94
|
+
* `content`, `outcome` and `structuredContent`.
|
|
95
|
+
*
|
|
96
|
+
* @example Telemetry off the fold — observe tool results without touching
|
|
97
|
+
* the transcript path:
|
|
98
|
+
* ```ts
|
|
99
|
+
* for await (const ev of invokeTurn(req, transport)) {
|
|
100
|
+
* if (ev.kind !== "message") continue;
|
|
101
|
+
* for (const agEvent of ev.agEvents) {
|
|
102
|
+
* if (agEvent.type === "tool.done") {
|
|
103
|
+
* telemetry.record(agEvent.toolCallId, agEvent.outcome ?? "ok");
|
|
104
|
+
* }
|
|
105
|
+
* }
|
|
106
|
+
* render(ev.assistantText); // the fold is untouched by the observation
|
|
107
|
+
* }
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
export async function* invokeTurn(
|
|
111
|
+
req: InvokeRequest,
|
|
112
|
+
transport: InvokeTransport,
|
|
113
|
+
): AsyncGenerator<InvokeTurnEvent> {
|
|
114
|
+
let assistantText = "";
|
|
115
|
+
let buffer = "";
|
|
116
|
+
for await (const chunk of transport(req)) {
|
|
117
|
+
buffer += chunk;
|
|
118
|
+
const { events, rest } = parseSseEvents(buffer);
|
|
119
|
+
buffer = rest;
|
|
120
|
+
for (const ev of events) {
|
|
121
|
+
if (ev.event === "session") {
|
|
122
|
+
// The pod is awake and the turn is admitted (this frame arrives
|
|
123
|
+
// within ~1s of a warm pod; a cold scale-to-zero start is exactly
|
|
124
|
+
// the long wait before it).
|
|
125
|
+
yield { kind: "session", threadId: stringField(ev.data, "threadId") ?? null };
|
|
126
|
+
} else if (ev.event === "message") {
|
|
127
|
+
// Status derivation (guuey#91) — read the frame's `type` before the
|
|
128
|
+
// text fold. Silver frames announce tools + text explicitly; bypass
|
|
129
|
+
// frames ('text' / 'assistant' SDKMessages) only ever carry
|
|
130
|
+
// assistant text, so they map to 'responding'. Unknown types
|
|
131
|
+
// deliberately imply no status change.
|
|
132
|
+
const frameType = stringField(ev.data, "type");
|
|
133
|
+
assistantText = reduceAssistantText(assistantText, ev.data);
|
|
134
|
+
// Only VALID AgEvents surface (bypass frames ingest to []) — the
|
|
135
|
+
// caller's reducer, if any, advances on these alone.
|
|
136
|
+
const agEvents = ingestMessageFrame(ev.data);
|
|
137
|
+
if (frameType === "tool.start") {
|
|
138
|
+
yield {
|
|
139
|
+
kind: "message",
|
|
140
|
+
status: "using-tool",
|
|
141
|
+
activeTool: stringField(ev.data, "name") ?? null,
|
|
142
|
+
assistantText,
|
|
143
|
+
agEvents,
|
|
144
|
+
};
|
|
145
|
+
} else if (frameType === "tool.done") {
|
|
146
|
+
yield { kind: "message", status: "thinking", activeTool: null, assistantText, agEvents };
|
|
147
|
+
} else if (
|
|
148
|
+
frameType === "text.start" ||
|
|
149
|
+
frameType === "text.delta" ||
|
|
150
|
+
frameType === "text" ||
|
|
151
|
+
frameType === "assistant"
|
|
152
|
+
) {
|
|
153
|
+
yield { kind: "message", status: "responding", assistantText, agEvents };
|
|
154
|
+
} else {
|
|
155
|
+
yield { kind: "message", assistantText, agEvents };
|
|
156
|
+
}
|
|
157
|
+
} else if (ev.event === "error") {
|
|
158
|
+
// In-band failure frame — one of the two channels that carry the
|
|
159
|
+
// pod's wire code (the other is the pre-stream refusal thrown by the
|
|
160
|
+
// transport). A frame without a `code` yields null rather than
|
|
161
|
+
// leaving a previous turn's code standing beside a new message.
|
|
162
|
+
yield {
|
|
163
|
+
kind: "error",
|
|
164
|
+
message: stringField(ev.data, "message") ?? "agent error",
|
|
165
|
+
code: stringField(ev.data, "code") ?? null,
|
|
166
|
+
};
|
|
167
|
+
} else if (ev.event === "profile-consent-needed") {
|
|
168
|
+
// Cross-app profile consent ask (T6). Only a well-formed payload
|
|
169
|
+
// yields; a malformed one is dropped, leaving any prior valid
|
|
170
|
+
// request untouched (never clobbered to null).
|
|
171
|
+
const parsed = parseConsentRequest(ev.data);
|
|
172
|
+
if (parsed) yield { kind: "profile-consent", request: parsed };
|
|
173
|
+
} else if (ev.event === "profile-link-needed") {
|
|
174
|
+
// Cross-app profile LINK invite (linkcoh T3) for an unlinked byo
|
|
175
|
+
// caller. Same drop-if-malformed contract as consent above.
|
|
176
|
+
const parsed = parseLinkRequest(ev.data);
|
|
177
|
+
if (parsed) yield { kind: "profile-link", request: parsed };
|
|
178
|
+
} else if (ev.event === "done") {
|
|
179
|
+
// The stream closes after this frame; yielded so a host can read the
|
|
180
|
+
// pod's stop reason without private wire knowledge.
|
|
181
|
+
yield { kind: "done", stopReason: stringField(ev.data, "stopReason") ?? null };
|
|
182
|
+
}
|
|
183
|
+
// Any other (unknown) event falls through silently — additive wire
|
|
184
|
+
// events never disturb a consumer.
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
package/src/react.ts
CHANGED
|
@@ -6,7 +6,13 @@
|
|
|
6
6
|
* history reader, and the web adapters). Consumers that only need those never
|
|
7
7
|
* import React at all; consumers that render chat import the hook from here.
|
|
8
8
|
*/
|
|
9
|
-
export {
|
|
9
|
+
export {
|
|
10
|
+
useAgentInvoke,
|
|
11
|
+
applyHistoryResult,
|
|
12
|
+
type HistoryApplication,
|
|
13
|
+
stallProbeDecision,
|
|
14
|
+
STALL_RECOVERY_DEFAULTS,
|
|
15
|
+
} from "./useAgentInvoke.js";
|
|
10
16
|
// The block-preserving transcript surfaces `AgReduceResult`; re-export it (and
|
|
11
17
|
// `AgEvent`) here so `./react` consumers can type `reduceResult` without a
|
|
12
18
|
// direct `@silverprotocol/core` import.
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The invoke-refusal retry wrappers, transport-agnostic: the single
|
|
3
|
+
* `POD_SATURATED` auto-retry ({@link withSaturationRetry}) and the bounded
|
|
4
|
+
* cold-start 503 retry ({@link withColdStartRetry}).
|
|
5
|
+
*
|
|
6
|
+
* Their own module — rather than living inside `./web-adapters.ts`, where the
|
|
7
|
+
* first was born — because the behaviour is a property of the platform's
|
|
8
|
+
* refusal vocabulary, not of `fetch`. Every host that speaks `/agent/invoke`
|
|
9
|
+
* wants them, including the ones that cannot import the web adapter bundle:
|
|
10
|
+
* Portal's React-Native transport wraps its own `fetch` call with these the
|
|
11
|
+
* same way `fetchStreamTransport` wraps its browser streaming reader, so the
|
|
12
|
+
* two wear byte-identical retry semantics instead of two hand-written copies
|
|
13
|
+
* that drift.
|
|
14
|
+
*
|
|
15
|
+
* The two wrappers are DELIBERATELY distinct code paths: saturation retry is
|
|
16
|
+
* driven by the pod's structured refusal envelope (`code: POD_SATURATED`),
|
|
17
|
+
* while the cold-start retry matches only an envelope-LESS 503 — the raw
|
|
18
|
+
* infra answer (ingress with no ready pod) during the post-redeploy window,
|
|
19
|
+
* which by definition carries no wire code. They share the backoff machinery,
|
|
20
|
+
* never the predicate.
|
|
21
|
+
*
|
|
22
|
+
* This module imports only `./types.js`, `./errors.js` and `./error-codes.js`
|
|
23
|
+
* — all pure — so pulling it in costs a React-Native build nothing.
|
|
24
|
+
*/
|
|
25
|
+
import { AGENT_ERROR_CODES } from "./error-codes.js";
|
|
26
|
+
import { AgentResponseError } from "./errors.js";
|
|
27
|
+
import type { InvokeRequest, InvokeTransport } from "./types.js";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Fallback wait before the saturation retry when the pod sent no usable
|
|
31
|
+
* `Retry-After` — the same 15s the pod's governor hints today
|
|
32
|
+
* (`GOVERNOR_RETRY_AFTER_SECONDS`), so a stripped header behaves like the
|
|
33
|
+
* normal case rather than hammering.
|
|
34
|
+
*/
|
|
35
|
+
const SATURATION_FALLBACK_DELAY_SECONDS = 15;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Ceiling on the honoured hint. A pod that (mis)configures a multi-minute
|
|
39
|
+
* `Retry-After` must not park a chat UI in `connecting` for that long — past
|
|
40
|
+
* this the user is better served by the visible failure they can act on.
|
|
41
|
+
*/
|
|
42
|
+
const SATURATION_MAX_DELAY_SECONDS = 30;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Read `Retry-After` as WHOLE SECONDS, or `undefined`.
|
|
46
|
+
*
|
|
47
|
+
* HTTP also allows an absolute HTTP-date, which is deliberately NOT parsed:
|
|
48
|
+
* the pod only ever emits a delta-seconds integer, and silently mis-reading a
|
|
49
|
+
* date as `NaN` seconds is worse than falling back to the fixed delay.
|
|
50
|
+
*
|
|
51
|
+
* Exported because every transport that builds an {@link AgentResponseError}
|
|
52
|
+
* has to fill `retryAfterSeconds` the same way for {@link withSaturationRetry}
|
|
53
|
+
* to honour the same hint — a second hand-rolled regex in a host adapter is
|
|
54
|
+
* exactly the drift this module exists to prevent.
|
|
55
|
+
*/
|
|
56
|
+
export function parseRetryAfterSeconds(header: string | null): number | undefined {
|
|
57
|
+
if (header === null) return undefined;
|
|
58
|
+
const trimmed = header.trim();
|
|
59
|
+
if (!/^\d+$/.test(trimmed)) return undefined;
|
|
60
|
+
const seconds = Number(trimmed);
|
|
61
|
+
return Number.isSafeInteger(seconds) ? seconds : undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** How long to wait before the single saturation retry, in milliseconds. */
|
|
65
|
+
function saturationDelayMs(retryAfterSeconds: number | undefined): number {
|
|
66
|
+
const hinted = retryAfterSeconds ?? SATURATION_FALLBACK_DELAY_SECONDS;
|
|
67
|
+
return Math.min(hinted, SATURATION_MAX_DELAY_SECONDS) * 1000;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Wait `ms`, or resolve early if the turn is aborted — a user who hits stop
|
|
72
|
+
* must not sit through the remainder of a 15s backoff before the UI settles.
|
|
73
|
+
*/
|
|
74
|
+
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
75
|
+
return new Promise<void>((resolve) => {
|
|
76
|
+
if (signal.aborted) {
|
|
77
|
+
resolve();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const finish = (): void => {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
signal.removeEventListener("abort", finish);
|
|
83
|
+
resolve();
|
|
84
|
+
};
|
|
85
|
+
const timer = setTimeout(finish, ms);
|
|
86
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Options for {@link withSaturationRetry}. */
|
|
91
|
+
export interface SaturationRetryOptions {
|
|
92
|
+
/**
|
|
93
|
+
* The saturation-retry wait. Injectable so tests drive the retry without a
|
|
94
|
+
* real 15s timer; production uses an abort-aware `setTimeout`.
|
|
95
|
+
*/
|
|
96
|
+
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Wrap an invoke transport with ONE automatic retry on a saturated pod.
|
|
101
|
+
*
|
|
102
|
+
* ## What retries, and what deliberately does not
|
|
103
|
+
*
|
|
104
|
+
* `POD_SATURATED` (503) means the pod is at its concurrent-turn cap right now
|
|
105
|
+
* — a transient queue state that clears as in-flight turns finish, so a single
|
|
106
|
+
* delayed re-send usually just works. The wait is the pod's own `Retry-After`
|
|
107
|
+
* hint (via {@link AgentResponseError.retryAfterSeconds}), defaulting to 15s
|
|
108
|
+
* when it sent none and capped at 30s.
|
|
109
|
+
*
|
|
110
|
+
* `DRAINING` (also 503 + `Retry-After`) is NOT retried in v1. The refusing pod
|
|
111
|
+
* is shutting down: its readiness probe is already failing and the endpoint
|
|
112
|
+
* pull is in flight, so the useful retry is the one that reaches a DIFFERENT
|
|
113
|
+
* pod — and a wrapped transport re-sends to the same URL. Retrying here would
|
|
114
|
+
* spend the user's 15s to arrive back at the same draining pod (or at a fresh
|
|
115
|
+
* one by luck), which is not a guarantee worth building on. When the retry can
|
|
116
|
+
* be made routing-aware, this is the code to revisit.
|
|
117
|
+
*
|
|
118
|
+
* Exactly ONE retry: a second saturation propagates as
|
|
119
|
+
* {@link AgentResponseError}, so a genuinely overloaded agent surfaces instead
|
|
120
|
+
* of looping. Nothing is retried once a chunk has been yielded — replaying
|
|
121
|
+
* mid-stream would duplicate a partial assistant turn (the same `yielded`
|
|
122
|
+
* guard the widget's `withIdentifiedToken` 401-retry uses). An abort during
|
|
123
|
+
* the wait skips the retry and surfaces the original refusal.
|
|
124
|
+
*
|
|
125
|
+
* The retry is INVISIBLE to `useAgentInvoke`: no frames were yielded, so the
|
|
126
|
+
* turn simply stays in `connecting` for the duration of the wait. There is no
|
|
127
|
+
* `retrying` status by design — the hook's state machine describes the pod's
|
|
128
|
+
* turn lifecycle, not the transport's plumbing.
|
|
129
|
+
*
|
|
130
|
+
* The wrapped transport is re-invoked from scratch for the retry, so a host
|
|
131
|
+
* that resolves identity inside its own generator (Portal's RN transport reads
|
|
132
|
+
* the bearer bridge per attempt) re-reads it on the second try rather than
|
|
133
|
+
* replaying a token that may have expired during the wait.
|
|
134
|
+
*/
|
|
135
|
+
export function withSaturationRetry(
|
|
136
|
+
transport: InvokeTransport,
|
|
137
|
+
options: SaturationRetryOptions = {},
|
|
138
|
+
): InvokeTransport {
|
|
139
|
+
return async function* retrying(req: InvokeRequest): AsyncGenerator<string> {
|
|
140
|
+
let yielded = false;
|
|
141
|
+
try {
|
|
142
|
+
for await (const chunk of transport(req)) {
|
|
143
|
+
yielded = true;
|
|
144
|
+
yield chunk;
|
|
145
|
+
}
|
|
146
|
+
return;
|
|
147
|
+
} catch (err) {
|
|
148
|
+
const saturated =
|
|
149
|
+
err instanceof AgentResponseError && err.code === AGENT_ERROR_CODES.POD_SATURATED;
|
|
150
|
+
if (!saturated || yielded) throw err;
|
|
151
|
+
await (options.sleep ?? delay)(saturationDelayMs(err.retryAfterSeconds), req.signal);
|
|
152
|
+
// Aborted mid-wait: the user is done with this turn. Surface the refusal
|
|
153
|
+
// that caused the wait rather than spending a request that `fetch` would
|
|
154
|
+
// reject on the signal anyway.
|
|
155
|
+
if (req.signal.aborted) throw err;
|
|
156
|
+
}
|
|
157
|
+
yield* transport(req);
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Options for {@link withColdStartRetry}. */
|
|
162
|
+
export interface ColdStartRetryOptions {
|
|
163
|
+
/**
|
|
164
|
+
* Retries after the initial attempt (`0` disables the wrapper's behaviour
|
|
165
|
+
* entirely). Default 3 — a small, bounded budget: the point is parity with
|
|
166
|
+
* guuey's first-party embeds during the ordinary post-redeploy window, not
|
|
167
|
+
* riding out an outage. Raise it for an unattended harness that would
|
|
168
|
+
* rather wait than fail.
|
|
169
|
+
*/
|
|
170
|
+
attempts?: number;
|
|
171
|
+
/**
|
|
172
|
+
* First wait in ms; each subsequent wait doubles, capped at
|
|
173
|
+
* {@link maxDelayMs}. Default 2000 → 2s / 4s / 8s for the default budget.
|
|
174
|
+
*/
|
|
175
|
+
baseDelayMs?: number;
|
|
176
|
+
/** Ceiling on any single wait (hinted or computed), in ms. Default 10000. */
|
|
177
|
+
maxDelayMs?: number;
|
|
178
|
+
/** The wait itself — injectable so tests drive the retry without timers. */
|
|
179
|
+
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const COLD_START_DEFAULT_ATTEMPTS = 3;
|
|
183
|
+
const COLD_START_BASE_DELAY_MS = 2_000;
|
|
184
|
+
const COLD_START_MAX_DELAY_MS = 10_000;
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Is this failure the cold-start refusal shape? An envelope-less 503: the
|
|
188
|
+
* status came from infra (no ready pod behind the route — the ~30–60s window
|
|
189
|
+
* after a redeploy), so there is no wire `code`. A 503 that DOES carry a code
|
|
190
|
+
* is the pod itself refusing (`POD_SATURATED`, `DRAINING`) and belongs to
|
|
191
|
+
* {@link withSaturationRetry}'s policy — including its deliberate decision NOT
|
|
192
|
+
* to retry `DRAINING` — never to this wrapper.
|
|
193
|
+
*/
|
|
194
|
+
function isColdStartRefusal(err: unknown): err is AgentResponseError {
|
|
195
|
+
return err instanceof AgentResponseError && err.status === 503 && err.code === undefined;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Wrap an invoke transport with a bounded retry on cold-start 503s
|
|
200
|
+
* (guuey#186 Gap 3 — parity with first-party embeds, which already carry
|
|
201
|
+
* this behaviour; SDK consumers were eating the raw 503 window instead).
|
|
202
|
+
*
|
|
203
|
+
* Matches ONLY {@link isColdStartRefusal} — an envelope-less 503 — and
|
|
204
|
+
* retries up to `attempts` times with doubling, capped backoff (honouring a
|
|
205
|
+
* `Retry-After` hint when the response carried one). Exhaustion propagates
|
|
206
|
+
* the final refusal untouched.
|
|
207
|
+
*
|
|
208
|
+
* Nothing is retried once a chunk has been yielded: a stream that dies
|
|
209
|
+
* MID-turn is never silently re-POSTed — the turn may have had side effects
|
|
210
|
+
* and the consumer already saw partial output. Same `yielded` guard as
|
|
211
|
+
* {@link withSaturationRetry}, same reasoning. An abort during a wait
|
|
212
|
+
* surfaces the refusal that caused the wait.
|
|
213
|
+
*
|
|
214
|
+
* Like the saturation wrapper, the retry is invisible to `useAgentInvoke`
|
|
215
|
+
* (the turn stays in `connecting`), and the wrapped transport is re-invoked
|
|
216
|
+
* from scratch so per-attempt identity resolution re-runs.
|
|
217
|
+
*/
|
|
218
|
+
export function withColdStartRetry(
|
|
219
|
+
transport: InvokeTransport,
|
|
220
|
+
options: ColdStartRetryOptions = {},
|
|
221
|
+
): InvokeTransport {
|
|
222
|
+
const attempts = options.attempts ?? COLD_START_DEFAULT_ATTEMPTS;
|
|
223
|
+
const baseDelayMs = options.baseDelayMs ?? COLD_START_BASE_DELAY_MS;
|
|
224
|
+
const maxDelayMs = options.maxDelayMs ?? COLD_START_MAX_DELAY_MS;
|
|
225
|
+
const sleep = options.sleep ?? delay;
|
|
226
|
+
return async function* retrying(req: InvokeRequest): AsyncGenerator<string> {
|
|
227
|
+
let yielded = false;
|
|
228
|
+
for (let attempt = 0; ; attempt++) {
|
|
229
|
+
try {
|
|
230
|
+
for await (const chunk of transport(req)) {
|
|
231
|
+
yielded = true;
|
|
232
|
+
yield chunk;
|
|
233
|
+
}
|
|
234
|
+
return;
|
|
235
|
+
} catch (err) {
|
|
236
|
+
if (!isColdStartRefusal(err) || yielded || attempt >= attempts) throw err;
|
|
237
|
+
const hintedMs =
|
|
238
|
+
err.retryAfterSeconds !== undefined ? err.retryAfterSeconds * 1000 : undefined;
|
|
239
|
+
const waitMs = Math.min(hintedMs ?? baseDelayMs * 2 ** attempt, maxDelayMs);
|
|
240
|
+
await sleep(waitMs, req.signal);
|
|
241
|
+
// Aborted mid-wait: surface the refusal that caused the wait rather
|
|
242
|
+
// than spending a request that `fetch` would reject on the signal.
|
|
243
|
+
if (req.signal.aborted) throw err;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
}
|
package/src/sse.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* verbatim across web (Studio) and React-Native (Portal).
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import type { ProfileConsentRequest, ProfileLinkRequest } from "./types";
|
|
7
|
+
import type { ProfileConsentRequest, ProfileLinkRequest } from "./types.js";
|
|
8
8
|
|
|
9
9
|
export interface ParsedSseEvent {
|
|
10
10
|
event: string;
|