@guuey/agent-client 0.4.0 → 0.6.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 +39 -5
- package/dist/error-codes.d.ts +29 -0
- package/dist/error-codes.d.ts.map +1 -1
- package/dist/error-codes.js +27 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +23 -9
- 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 +41 -0
- package/dist/saturation-retry.d.ts.map +1 -1
- package/dist/saturation-retry.js +78 -6
- 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 +73 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/useAgentInvoke.d.ts +28 -0
- package/dist/useAgentInvoke.d.ts.map +1 -1
- package/dist/useAgentInvoke.js +281 -90
- package/dist/web-adapters.d.ts +1 -11
- package/dist/web-adapters.d.ts.map +1 -1
- package/dist/web-adapters.js +9 -121
- package/package.json +9 -3
- package/src/error-codes.ts +31 -0
- package/src/index.ts +33 -9
- package/src/invoke-turn.ts +187 -0
- package/src/react.ts +7 -1
- package/src/saturation-retry.ts +103 -6
- package/src/transport.ts +260 -0
- package/src/types.ts +74 -1
- package/src/useAgentInvoke.ts +271 -89
- package/src/web-adapters.ts +10 -150
package/src/useAgentInvoke.ts
CHANGED
|
@@ -23,15 +23,10 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
25
25
|
import { Reducer, type AgReduceResult } 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";
|
|
26
|
+
import { invokeTurn, toInvokeUrl } from "./invoke-turn.js";
|
|
34
27
|
import { AgentResponseError } from "./errors.js";
|
|
28
|
+
import { withActivityObserver } from "./transport.js";
|
|
29
|
+
import { CLIENT_ERROR_CODES } from "./error-codes.js";
|
|
35
30
|
import type {
|
|
36
31
|
AgentInvokeAdapters,
|
|
37
32
|
AgentInvokeStatus,
|
|
@@ -40,6 +35,7 @@ import type {
|
|
|
40
35
|
HistoryLoadResult,
|
|
41
36
|
ProfileConsentRequest,
|
|
42
37
|
ProfileLinkRequest,
|
|
38
|
+
StallRecoveryOptions,
|
|
43
39
|
UseAgentInvokeOptions,
|
|
44
40
|
UseAgentInvokeReturn,
|
|
45
41
|
} from "./types.js";
|
|
@@ -70,6 +66,53 @@ export function applyHistoryResult(
|
|
|
70
66
|
return { kind: "seed", messages: result.messages };
|
|
71
67
|
}
|
|
72
68
|
|
|
69
|
+
/** The guuey#192 stall watchdog's resolved tuning (see {@link stallProbeDecision}). */
|
|
70
|
+
export const STALL_RECOVERY_DEFAULTS = { windowMs: 25_000, probeAttempts: 4 } as const;
|
|
71
|
+
|
|
72
|
+
function resolveStallRecovery(
|
|
73
|
+
option: false | StallRecoveryOptions | undefined,
|
|
74
|
+
): { windowMs: number; probeAttempts: number } | null {
|
|
75
|
+
if (option === false) return null;
|
|
76
|
+
return {
|
|
77
|
+
windowMs: option?.windowMs ?? STALL_RECOVERY_DEFAULTS.windowMs,
|
|
78
|
+
probeAttempts: option?.probeAttempts ?? STALL_RECOVERY_DEFAULTS.probeAttempts,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Pure decision seam for the guuey#192 stall probe: does a freshly-loaded
|
|
84
|
+
* transcript already contain THIS turn's finished reply?
|
|
85
|
+
*
|
|
86
|
+
* `adopt` requires BOTH signals, because each alone lies in a real case:
|
|
87
|
+
*
|
|
88
|
+
* - **user-count**: history must hold at least as many user turns as the
|
|
89
|
+
* local transcript (which includes the just-sent optimistic one). Without
|
|
90
|
+
* it, a thread whose PREVIOUS turn ended in a completed assistant reply
|
|
91
|
+
* would adopt that OLD transcript and silently drop the in-flight turn.
|
|
92
|
+
* - **finished tail**: history's last message must be a non-empty assistant
|
|
93
|
+
* reply. Without it, a history read that caught the persisted user row
|
|
94
|
+
* before the assistant row would adopt a reply-less transcript.
|
|
95
|
+
*
|
|
96
|
+
* KNOWN LIMIT (documented, accepted): the runtime persists a turn's rows at
|
|
97
|
+
* completion — the guuey#192 evidence (a reload mid-stall renders the FULL
|
|
98
|
+
* reply) is only possible under that model, and the read plane carries no
|
|
99
|
+
* per-row clientMessageId to match against. If persistence ever becomes
|
|
100
|
+
* progressive (partial assistant rows), this heuristic needs the read plane
|
|
101
|
+
* to grow a turn-completion marker — do not "fix" it client-side by text
|
|
102
|
+
* comparison, which cannot distinguish a partial row from a finished one.
|
|
103
|
+
*/
|
|
104
|
+
export function stallProbeDecision(
|
|
105
|
+
history: AgentMessage[],
|
|
106
|
+
localUserCount: number,
|
|
107
|
+
): "adopt" | "in-flight" {
|
|
108
|
+
let historyUserCount = 0;
|
|
109
|
+
for (const m of history) if (m.role === "user") historyUserCount += 1;
|
|
110
|
+
if (historyUserCount < localUserCount) return "in-flight";
|
|
111
|
+
const last = history[history.length - 1];
|
|
112
|
+
if (!last || last.role !== "assistant" || last.text.trim() === "") return "in-flight";
|
|
113
|
+
return "adopt";
|
|
114
|
+
}
|
|
115
|
+
|
|
73
116
|
export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeReturn {
|
|
74
117
|
const { endpointUrl, appId } = opts;
|
|
75
118
|
const [messages, setMessages] = useState<AgentMessage[]>([]);
|
|
@@ -102,6 +145,13 @@ export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeRetur
|
|
|
102
145
|
// explicit dismiss, same lifecycle as `profileConsentRequest` — the two are
|
|
103
146
|
// independent (an unlinked-invite vs an already-linked consent ask).
|
|
104
147
|
const [profileLinkRequest, setProfileLinkRequest] = useState<ProfileLinkRequest | null>(null);
|
|
148
|
+
// The last turn's ending posture + the optimistic-send ledger — the
|
|
149
|
+
// transcript renderer's inputs (guuey#135 wave 3b; see the return-type
|
|
150
|
+
// contract for each). `aborted` is USER abort only — the #192 watchdog's
|
|
151
|
+
// internal stream abort never sets it.
|
|
152
|
+
const [aborted, setAborted] = useState(false);
|
|
153
|
+
const [adopted, setAdopted] = useState(false);
|
|
154
|
+
const [sendStates, setSendStates] = useState<Readonly<Record<string, "sending" | "failed">>>({});
|
|
105
155
|
|
|
106
156
|
const abortRef = useRef<AbortController | null>(null);
|
|
107
157
|
// Mirror the latest threadId + adapters into refs so `send` reads fresh
|
|
@@ -110,6 +160,13 @@ export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeRetur
|
|
|
110
160
|
const threadIdRef = useRef<string | null>(null);
|
|
111
161
|
const adaptersRef = useRef<AgentInvokeAdapters>(opts.adapters);
|
|
112
162
|
adaptersRef.current = opts.adapters;
|
|
163
|
+
// The stall probe (guuey#192) needs the committed transcript's user-turn
|
|
164
|
+
// count long after `send`'s closures captured state — same render-time
|
|
165
|
+
// mirror idiom as `adaptersRef`.
|
|
166
|
+
const messagesRef = useRef<AgentMessage[]>(messages);
|
|
167
|
+
messagesRef.current = messages;
|
|
168
|
+
const stallRecoveryRef = useRef(opts.stallRecovery);
|
|
169
|
+
stallRecoveryRef.current = opts.stallRecovery;
|
|
113
170
|
// The per-conversation AgJSON fold (only built when `preserveBlocks`).
|
|
114
171
|
// Lazily (re)created on the first valid AgEvent after a fresh start / reset,
|
|
115
172
|
// so an off run never constructs one and a bypass run never allocates.
|
|
@@ -147,6 +204,9 @@ export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeRetur
|
|
|
147
204
|
// A prior app's consent ask must never leak into the new conversation.
|
|
148
205
|
setProfileConsentRequest(null);
|
|
149
206
|
setProfileLinkRequest(null);
|
|
207
|
+
setAborted(false);
|
|
208
|
+
setAdopted(false);
|
|
209
|
+
setSendStates({});
|
|
150
210
|
|
|
151
211
|
let cancelled = false;
|
|
152
212
|
const key = threadStorageKey(appId);
|
|
@@ -237,6 +297,9 @@ export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeRetur
|
|
|
237
297
|
setHistoryCards([]);
|
|
238
298
|
setProfileConsentRequest(null);
|
|
239
299
|
setProfileLinkRequest(null);
|
|
300
|
+
setAborted(false);
|
|
301
|
+
setAdopted(false);
|
|
302
|
+
setSendStates({});
|
|
240
303
|
}, [appId]);
|
|
241
304
|
|
|
242
305
|
const clearProfileConsentRequest = useCallback(() => {
|
|
@@ -249,14 +312,47 @@ export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeRetur
|
|
|
249
312
|
|
|
250
313
|
const send = useCallback(
|
|
251
314
|
async (input: string) => {
|
|
252
|
-
|
|
315
|
+
// An already-aborted external signal refuses the send outright —
|
|
316
|
+
// before the optimistic transcript push, so nothing is left to undo.
|
|
317
|
+
if (!endpointUrl || !input.trim() || status !== "ready" || opts.signal?.aborted) return;
|
|
253
318
|
setError(null);
|
|
254
319
|
setErrorCode(null);
|
|
320
|
+
setAborted(false);
|
|
321
|
+
setAdopted(false);
|
|
255
322
|
setStatus("connecting");
|
|
256
|
-
|
|
323
|
+
// ONE id for the whole turn: the optimistic user entry, the send-state
|
|
324
|
+
// ledger, and the invoke body all carry it — the R0 lifecycle join.
|
|
325
|
+
const clientMessageId = adaptersRef.current.generateId();
|
|
326
|
+
/** Move this turn's ledger entry; `null` removes it (absent = sent). */
|
|
327
|
+
const markSend = (state: "sending" | "failed" | null): void => {
|
|
328
|
+
setSendStates((prev) => {
|
|
329
|
+
if (state === null) {
|
|
330
|
+
if (!(clientMessageId in prev)) return prev;
|
|
331
|
+
const next: Record<string, "sending" | "failed"> = { ...prev };
|
|
332
|
+
delete next[clientMessageId];
|
|
333
|
+
return next;
|
|
334
|
+
}
|
|
335
|
+
if (prev[clientMessageId] === state) return prev;
|
|
336
|
+
return { ...prev, [clientMessageId]: state };
|
|
337
|
+
});
|
|
338
|
+
};
|
|
339
|
+
markSend("sending");
|
|
340
|
+
let admitted = false;
|
|
341
|
+
setMessages((prev) => [
|
|
342
|
+
...prev,
|
|
343
|
+
{ role: "user", text: input, clientMessageId },
|
|
344
|
+
{ role: "assistant", text: "" },
|
|
345
|
+
]);
|
|
257
346
|
|
|
258
347
|
const controller = new AbortController();
|
|
259
348
|
abortRef.current = controller;
|
|
349
|
+
// Compose the host's external abort authority (opts.signal) with the
|
|
350
|
+
// per-turn controller: an external abort stops this turn exactly as
|
|
351
|
+
// `abort()` would. Listener removed in `finally` — the signal outlives
|
|
352
|
+
// the turn, the subscription must not.
|
|
353
|
+
const externalSignal = opts.signal;
|
|
354
|
+
const onExternalAbort = (): void => controller.abort();
|
|
355
|
+
externalSignal?.addEventListener("abort", onExternalAbort, { once: true });
|
|
260
356
|
const adapters = adaptersRef.current;
|
|
261
357
|
// Wait for the persisted threadId to load before deciding whether to
|
|
262
358
|
// replay it — otherwise a fast first send mints a new orphan thread and
|
|
@@ -280,92 +376,155 @@ export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeRetur
|
|
|
280
376
|
});
|
|
281
377
|
};
|
|
282
378
|
|
|
379
|
+
// ── guuey#192 stall watchdog ─────────────────────────────────────
|
|
380
|
+
// A half-dead connection (TCP alive, zero bytes, no error, no `done`)
|
|
381
|
+
// never resolves the read below, so a parallel clock watches byte
|
|
382
|
+
// activity: armed by the FIRST chunk (so a silent cold start never
|
|
383
|
+
// trips it), reset by every chunk, and on expiry it probes history
|
|
384
|
+
// WITHOUT touching the stream — killing a live-but-quiet stream on a
|
|
385
|
+
// timer would trade a frozen cursor for a lost turn. Only two things
|
|
386
|
+
// end the turn early: adoption (history already holds the finished
|
|
387
|
+
// reply — the reload the user would have done, minus the reload) and
|
|
388
|
+
// the bounded give-up (STREAM_STALLED after `probeAttempts` fruitless
|
|
389
|
+
// probes with still-zero bytes).
|
|
390
|
+
const stall = resolveStallRecovery(stallRecoveryRef.current);
|
|
391
|
+
let turnEnded = false;
|
|
392
|
+
let probeInFlight = false;
|
|
393
|
+
let fruitlessProbes = 0;
|
|
394
|
+
let activityCount = 0;
|
|
395
|
+
let stallTimer: ReturnType<typeof setTimeout> | null = null;
|
|
396
|
+
const clearStallTimer = (): void => {
|
|
397
|
+
if (stallTimer !== null) {
|
|
398
|
+
clearTimeout(stallTimer);
|
|
399
|
+
stallTimer = null;
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
const armStallTimer = (): void => {
|
|
403
|
+
if (!stall || turnEnded || controller.signal.aborted) return;
|
|
404
|
+
clearStallTimer();
|
|
405
|
+
stallTimer = setTimeout(() => {
|
|
406
|
+
void onStallWindow();
|
|
407
|
+
}, stall.windowMs);
|
|
408
|
+
};
|
|
409
|
+
const endTurnWith = (apply: () => void): void => {
|
|
410
|
+
turnEnded = true;
|
|
411
|
+
clearStallTimer();
|
|
412
|
+
apply();
|
|
413
|
+
// Unwinds the suspended read; the catch sees `aborted` and stays
|
|
414
|
+
// silent, so whatever `apply` decided IS the turn's outcome.
|
|
415
|
+
controller.abort();
|
|
416
|
+
};
|
|
417
|
+
const onStallWindow = async (): Promise<void> => {
|
|
418
|
+
if (!stall || turnEnded || controller.signal.aborted || probeInFlight) return;
|
|
419
|
+
const tid = threadIdRef.current;
|
|
420
|
+
const history = adaptersRef.current.history;
|
|
421
|
+
if (tid && history) {
|
|
422
|
+
probeInFlight = true;
|
|
423
|
+
const countAtProbe = activityCount;
|
|
424
|
+
let result: HistoryLoadResult | null = null;
|
|
425
|
+
try {
|
|
426
|
+
result = await history.load(tid);
|
|
427
|
+
} catch {
|
|
428
|
+
result = null; // transient read failure = one fruitless probe
|
|
429
|
+
}
|
|
430
|
+
probeInFlight = false;
|
|
431
|
+
if (turnEnded || controller.signal.aborted) return;
|
|
432
|
+
// Bytes resumed while the probe was in flight: the stream is alive
|
|
433
|
+
// — discard the now-stale read; the chunk observer already reset
|
|
434
|
+
// the count and re-armed the clock.
|
|
435
|
+
if (activityCount !== countAtProbe) return;
|
|
436
|
+
if (result && !("gone" in result)) {
|
|
437
|
+
let localUserCount = 0;
|
|
438
|
+
for (const m of messagesRef.current) if (m.role === "user") localUserCount += 1;
|
|
439
|
+
if (stallProbeDecision(result.messages, localUserCount) === "adopt") {
|
|
440
|
+
const adoptedResult = result;
|
|
441
|
+
endTurnWith(() => {
|
|
442
|
+
setMessages(adoptedResult.messages);
|
|
443
|
+
if ("cards" in adoptedResult && adoptedResult.cards && adoptedResult.cards.length > 0) {
|
|
444
|
+
setHistoryCards(adoptedResult.cards);
|
|
445
|
+
}
|
|
446
|
+
// The renderer's #192 signal: calm renders the adopted turn
|
|
447
|
+
// identically; debug may mark it (guuey#135 3b).
|
|
448
|
+
setAdopted(true);
|
|
449
|
+
});
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
// No probe possible (no threadId yet / no history adapter), a failed
|
|
455
|
+
// read, or history says the turn is still in flight — all count the
|
|
456
|
+
// same: one fruitless window.
|
|
457
|
+
fruitlessProbes += 1;
|
|
458
|
+
if (fruitlessProbes >= stall.probeAttempts) {
|
|
459
|
+
endTurnWith(() => {
|
|
460
|
+
setError("The response stream stalled and the finished reply was not found in history.");
|
|
461
|
+
setErrorCode(CLIENT_ERROR_CODES.STREAM_STALLED);
|
|
462
|
+
});
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
armStallTimer();
|
|
466
|
+
};
|
|
467
|
+
const transport = stall
|
|
468
|
+
? withActivityObserver(adapters.transport, () => {
|
|
469
|
+
activityCount += 1;
|
|
470
|
+
fruitlessProbes = 0;
|
|
471
|
+
armStallTimer();
|
|
472
|
+
})
|
|
473
|
+
: adapters.transport;
|
|
474
|
+
|
|
283
475
|
try {
|
|
284
|
-
|
|
285
|
-
// invoke URL the deploy-controller records (`https://host/agent/invoke`).
|
|
286
|
-
// Normalize to exactly one `/agent/invoke`.
|
|
287
|
-
const base = endpointUrl.replace(/\/+$/, "");
|
|
288
|
-
const invokeUrl = base.endsWith("/agent/invoke") ? base : `${base}/agent/invoke`;
|
|
476
|
+
const invokeUrl = toInvokeUrl(endpointUrl);
|
|
289
477
|
const body = {
|
|
290
478
|
input,
|
|
291
479
|
...(threadIdRef.current ? { threadId: threadIdRef.current } : {}),
|
|
292
|
-
clientMessageId
|
|
480
|
+
clientMessageId,
|
|
293
481
|
};
|
|
294
482
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
frameType === "text.delta" ||
|
|
328
|
-
frameType === "text" ||
|
|
329
|
-
frameType === "assistant"
|
|
330
|
-
) {
|
|
331
|
-
setStatus("responding");
|
|
332
|
-
}
|
|
333
|
-
renderAssistant(reduceAssistantText(assistantText, ev.data));
|
|
334
|
-
// Additively fold the SAME frame into the AgJSON reducer when
|
|
335
|
-
// opted in. The text surface above is untouched; only VALID
|
|
336
|
-
// AgEvents advance the reducer (bypass frames ingest to [] and
|
|
337
|
-
// leave `reduceResult` null — see the return-type contract).
|
|
338
|
-
if (preserveBlocksRef.current) {
|
|
339
|
-
const agEvents = ingestMessageFrame(ev.data);
|
|
340
|
-
if (agEvents.length > 0) {
|
|
341
|
-
if (!reducerRef.current) reducerRef.current = new Reducer();
|
|
342
|
-
for (const agEvent of agEvents) reducerRef.current.push(agEvent);
|
|
343
|
-
setReduceResult(reducerRef.current.result());
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
} else if (ev.event === "error") {
|
|
347
|
-
// In-band failure frame — one of the two channels that carry the
|
|
348
|
-
// pod's wire code (the other is the pre-stream refusal caught
|
|
349
|
-
// below). A frame without a `code` clears it rather than leaving
|
|
350
|
-
// a previous turn's code standing beside a new message.
|
|
351
|
-
setError(stringField(ev.data, "message") ?? "agent error");
|
|
352
|
-
setErrorCode(stringField(ev.data, "code") ?? null);
|
|
353
|
-
} else if (ev.event === "profile-consent-needed") {
|
|
354
|
-
// Cross-app profile consent ask (T6). Only a well-formed payload
|
|
355
|
-
// updates state; a malformed one is dropped, leaving any prior
|
|
356
|
-
// valid request untouched (never clobbered to null).
|
|
357
|
-
const parsed = parseConsentRequest(ev.data);
|
|
358
|
-
if (parsed) setProfileConsentRequest(parsed);
|
|
359
|
-
} else if (ev.event === "profile-link-needed") {
|
|
360
|
-
// Cross-app profile LINK invite (linkcoh T3) for an unlinked byo
|
|
361
|
-
// caller. Same drop-if-malformed contract as consent above.
|
|
362
|
-
const parsed = parseLinkRequest(ev.data);
|
|
363
|
-
if (parsed) setProfileLinkRequest(parsed);
|
|
483
|
+
// The wire walk lives in `invokeTurn` (the pure per-turn generator —
|
|
484
|
+
// its docblock owns the switch semantics); this hook only maps each
|
|
485
|
+
// semantic event onto React state.
|
|
486
|
+
for await (const ev of invokeTurn(
|
|
487
|
+
{ url: invokeUrl, body, signal: controller.signal },
|
|
488
|
+
transport,
|
|
489
|
+
)) {
|
|
490
|
+
if (ev.kind === "session") {
|
|
491
|
+
// The pod is awake and the turn is admitted — 'connecting' ends
|
|
492
|
+
// here, and so does the R0 "sending" state (absent = sent).
|
|
493
|
+
admitted = true;
|
|
494
|
+
markSend(null);
|
|
495
|
+
setStatus("thinking");
|
|
496
|
+
if (ev.threadId) {
|
|
497
|
+
threadIdRef.current = ev.threadId;
|
|
498
|
+
setThreadId(ev.threadId);
|
|
499
|
+
void adapters.storage.save(threadStorageKey(appId), ev.threadId);
|
|
500
|
+
}
|
|
501
|
+
} else if (ev.kind === "message") {
|
|
502
|
+
// Absent status/activeTool mean "no change" — never touched, so
|
|
503
|
+
// an unknown frame type leaves both standing (guuey#91 rule).
|
|
504
|
+
if (ev.status !== undefined) setStatus(ev.status);
|
|
505
|
+
if (ev.activeTool !== undefined) setActiveTool(ev.activeTool);
|
|
506
|
+
renderAssistant(ev.assistantText);
|
|
507
|
+
// Additively fold the frame's AgEvents into the AgJSON reducer
|
|
508
|
+
// when opted in. The text surface above is untouched; only VALID
|
|
509
|
+
// AgEvents advance the reducer (bypass frames carry [] and leave
|
|
510
|
+
// `reduceResult` null — see the return-type contract).
|
|
511
|
+
if (preserveBlocksRef.current && ev.agEvents.length > 0) {
|
|
512
|
+
if (!reducerRef.current) reducerRef.current = new Reducer();
|
|
513
|
+
for (const agEvent of ev.agEvents) reducerRef.current.push(agEvent);
|
|
514
|
+
setReduceResult(reducerRef.current.result());
|
|
364
515
|
}
|
|
365
|
-
|
|
366
|
-
//
|
|
367
|
-
//
|
|
516
|
+
} else if (ev.kind === "error") {
|
|
517
|
+
// In-band failure frame — the code moves in lockstep with the
|
|
518
|
+
// message (an event without one carries null rather than leaving
|
|
519
|
+
// a previous turn's code standing).
|
|
520
|
+
setError(ev.message);
|
|
521
|
+
setErrorCode(ev.code);
|
|
522
|
+
} else if (ev.kind === "profile-consent") {
|
|
523
|
+
setProfileConsentRequest(ev.request);
|
|
524
|
+
} else if (ev.kind === "profile-link") {
|
|
525
|
+
setProfileLinkRequest(ev.request);
|
|
368
526
|
}
|
|
527
|
+
// `done` needs no handling here — the stream closes after it.
|
|
369
528
|
}
|
|
370
529
|
} catch (e) {
|
|
371
530
|
if (!controller.signal.aborted) {
|
|
@@ -376,8 +535,21 @@ export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeRetur
|
|
|
376
535
|
// other throw — a network drop, a host-adapter failure — has no wire
|
|
377
536
|
// code, so the field stays null beside the message.
|
|
378
537
|
setErrorCode(e instanceof AgentResponseError ? (e.code ?? null) : null);
|
|
538
|
+
// A failure BEFORE admission means the message never reached the
|
|
539
|
+
// agent — the R0 failed-to-send state. Post-admission failures
|
|
540
|
+
// leave the entry removed (the send itself succeeded).
|
|
541
|
+
if (!admitted) markSend("failed");
|
|
379
542
|
}
|
|
380
543
|
} finally {
|
|
544
|
+
// The turn is over however it ended — no probe may fire after this,
|
|
545
|
+
// and the pending timer must not leak past the turn. `turnEnded`
|
|
546
|
+
// already true here ⟺ the #192 watchdog ended the turn (adoption or
|
|
547
|
+
// stall give-up) — its internal `controller.abort()` must not read
|
|
548
|
+
// as a USER abort below.
|
|
549
|
+
const endedByWatchdog = turnEnded;
|
|
550
|
+
turnEnded = true;
|
|
551
|
+
clearStallTimer();
|
|
552
|
+
externalSignal?.removeEventListener("abort", onExternalAbort);
|
|
381
553
|
setStatus("ready");
|
|
382
554
|
setActiveTool(null);
|
|
383
555
|
abortRef.current = null;
|
|
@@ -392,9 +564,16 @@ export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeRetur
|
|
|
392
564
|
: prev;
|
|
393
565
|
});
|
|
394
566
|
}
|
|
567
|
+
if (controller.signal.aborted && !endedByWatchdog) {
|
|
568
|
+
// USER abort (abort() or the external signal): surface it, and a
|
|
569
|
+
// pre-admission cancel clears the "sending" entry — a turn the
|
|
570
|
+
// user stopped is not a failed send.
|
|
571
|
+
setAborted(true);
|
|
572
|
+
if (!admitted) markSend(null);
|
|
573
|
+
}
|
|
395
574
|
}
|
|
396
575
|
},
|
|
397
|
-
[endpointUrl, appId, status],
|
|
576
|
+
[endpointUrl, appId, status, opts.signal],
|
|
398
577
|
);
|
|
399
578
|
|
|
400
579
|
return {
|
|
@@ -413,5 +592,8 @@ export function useAgentInvoke(opts: UseAgentInvokeOptions): UseAgentInvokeRetur
|
|
|
413
592
|
clearProfileConsentRequest,
|
|
414
593
|
profileLinkRequest,
|
|
415
594
|
clearProfileLinkRequest,
|
|
595
|
+
aborted,
|
|
596
|
+
adopted,
|
|
597
|
+
sendStates,
|
|
416
598
|
};
|
|
417
599
|
}
|
package/src/web-adapters.ts
CHANGED
|
@@ -15,19 +15,9 @@ import {
|
|
|
15
15
|
type ResolvedViewMount,
|
|
16
16
|
type UiActionRequest,
|
|
17
17
|
} from "@guuey/mcp-apps-host";
|
|
18
|
-
import type {
|
|
19
|
-
AgentInvokeAdapters,
|
|
20
|
-
InvokeRequest,
|
|
21
|
-
InvokeTransport,
|
|
22
|
-
ThreadIdStore,
|
|
23
|
-
} from "./types.js";
|
|
18
|
+
import type { AgentInvokeAdapters, InvokeTransport, ThreadIdStore } from "./types.js";
|
|
24
19
|
import { fetchThreadHistory, HistoryUnauthorizedError } from "./history.js";
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
parseRetryAfterSeconds,
|
|
28
|
-
withSaturationRetry,
|
|
29
|
-
type SaturationRetryOptions,
|
|
30
|
-
} from "./saturation-retry.js";
|
|
20
|
+
import { fetchStreamTransport, sendableGuestSecret, GUEST_HEADER } from "./transport.js";
|
|
31
21
|
|
|
32
22
|
/** Persists the threadId in `window.localStorage` (synchronously). */
|
|
33
23
|
export const localStorageThreadStore: ThreadIdStore = {
|
|
@@ -57,142 +47,6 @@ export function webGenerateId(): string {
|
|
|
57
47
|
return `cmid-${Date.now()}-${Math.floor(Math.random() * 1e9)}`;
|
|
58
48
|
}
|
|
59
49
|
|
|
60
|
-
/**
|
|
61
|
-
* Header carrying a caller-owned anonymous guest secret. A LOCAL MIRROR of the
|
|
62
|
-
* two server-side constants — the pod's `GUEST_HEADER_NAME`
|
|
63
|
-
* (`backend/services/nocode-runtime/src/identity.ts`) and the read plane's
|
|
64
|
-
* `GUEST_HEADER` (`backend/amplify/functions/publicApi/identity.ts`) — because
|
|
65
|
-
* this is a published npm package and cannot take a `@guuey-private` dep (same
|
|
66
|
-
* arrangement as `@guuey/host`'s mirrored fs-contract constants). The string is
|
|
67
|
-
* a wire contract: both planes already advertise it in
|
|
68
|
-
* `Access-Control-Allow-Headers`, so changing it is a breaking protocol change,
|
|
69
|
-
* not a rename.
|
|
70
|
-
*/
|
|
71
|
-
const GUEST_HEADER = "x-guuey-guest";
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* A well-formed guest secret: exactly 32 bytes as 64 LOWERCASE hex chars —
|
|
75
|
-
* the shape `crypto.getRandomValues` + hex-encoding mints.
|
|
76
|
-
*
|
|
77
|
-
* Deliberately stricter than the server's `/^[a-f0-9]{64}$/i` (pod
|
|
78
|
-
* `identity.ts`, publicApi `identity.ts`): both sides lowercase before
|
|
79
|
-
* hashing, so an uppercase secret would in fact be accepted, but the only
|
|
80
|
-
* supported mint path emits lowercase and a non-canonical value means the
|
|
81
|
-
* caller's storage is not what this adapter expects. Anything that fails is
|
|
82
|
-
* IGNORED — the request falls through to cookie mode rather than sending a
|
|
83
|
-
* secret the two identity planes might key differently.
|
|
84
|
-
*/
|
|
85
|
-
const GUEST_SECRET_RE = /^[0-9a-f]{64}$/;
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Narrow a caller-supplied guest secret to a value that is safe to put on the
|
|
89
|
-
* wire, or `null`. The single gate for the header: every write of
|
|
90
|
-
* {@link GUEST_HEADER} in this module goes through it, so a malformed secret
|
|
91
|
-
* can never reach a request. The value is never logged (here or anywhere on
|
|
92
|
-
* this path) — it IS the anonymous identity, so a leak is an impersonation.
|
|
93
|
-
*/
|
|
94
|
-
function sendableGuestSecret(secret: string | null | undefined): string | null {
|
|
95
|
-
return typeof secret === "string" && GUEST_SECRET_RE.test(secret) ? secret : null;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* One invoke attempt: opens the request and yields decoded SSE chunks.
|
|
100
|
-
* {@link fetchStreamTransport} wraps this with the shared saturation retry —
|
|
101
|
-
* every behaviour below is per-attempt.
|
|
102
|
-
*
|
|
103
|
-
* Exactly ONE identity carrier per request, in order:
|
|
104
|
-
*
|
|
105
|
-
* 1. `accessToken` → `Authorization: Bearer` — the pod identifies the caller
|
|
106
|
-
* by their verified access token (the same identity the history read
|
|
107
|
-
* plane uses, so persisted threads round-trip on reload).
|
|
108
|
-
* 2. a well-formed `guestSecret` → `x-guuey-guest` — the caller owns and
|
|
109
|
-
* persists its own anonymous secret. The path for hosts with no usable
|
|
110
|
-
* cookie jar: React-Native, and the embedded widget, whose third-party
|
|
111
|
-
* iframe cannot rely on the pod's cookie surviving browser partitioning.
|
|
112
|
-
* The pod never mints a cookie for a header client.
|
|
113
|
-
* 3. neither → `credentials: "include"`, which round-trips the HttpOnly
|
|
114
|
-
* `guuey_guest` cookie the pod mints for anonymous browser callers.
|
|
115
|
-
*
|
|
116
|
-
* Never two at once: a bearer wins over a guest secret, and a request that
|
|
117
|
-
* carries either header does NOT also send cookie credentials.
|
|
118
|
-
*
|
|
119
|
-
* Reads the body via `ReadableStream.getReader()` (browser).
|
|
120
|
-
*/
|
|
121
|
-
async function* streamInvokeOnce(
|
|
122
|
-
req: InvokeRequest,
|
|
123
|
-
accessToken?: string | null,
|
|
124
|
-
guestSecret?: string | null,
|
|
125
|
-
): AsyncGenerator<string> {
|
|
126
|
-
const headers: Record<string, string> = {
|
|
127
|
-
"Content-Type": "application/json",
|
|
128
|
-
Accept: "text/event-stream",
|
|
129
|
-
};
|
|
130
|
-
const init: RequestInit = {
|
|
131
|
-
method: "POST",
|
|
132
|
-
signal: req.signal,
|
|
133
|
-
headers,
|
|
134
|
-
body: JSON.stringify(req.body),
|
|
135
|
-
};
|
|
136
|
-
const guest = sendableGuestSecret(guestSecret);
|
|
137
|
-
if (accessToken) {
|
|
138
|
-
headers.Authorization = `Bearer ${accessToken}`;
|
|
139
|
-
} else if (guest) {
|
|
140
|
-
headers[GUEST_HEADER] = guest;
|
|
141
|
-
} else {
|
|
142
|
-
init.credentials = "include";
|
|
143
|
-
}
|
|
144
|
-
const resp = await fetch(req.url, init);
|
|
145
|
-
if (!resp.ok || !resp.body) {
|
|
146
|
-
// Surface a structured pod error ({ code, message }) when present — e.g. a
|
|
147
|
-
// QUOTA_EXCEEDED 429 carries an upgrade message the UI should show. Fall
|
|
148
|
-
// back to the bare status for non-JSON failures.
|
|
149
|
-
const body: unknown = await resp.json().catch(() => null);
|
|
150
|
-
let message = `agent responded ${resp.status}`;
|
|
151
|
-
let code: string | undefined;
|
|
152
|
-
if (body !== null && typeof body === "object") {
|
|
153
|
-
if ("message" in body && typeof body.message === "string" && body.message) {
|
|
154
|
-
message = body.message;
|
|
155
|
-
}
|
|
156
|
-
if ("code" in body && typeof body.code === "string") {
|
|
157
|
-
code = body.code;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
throw new AgentResponseError(
|
|
161
|
-
message,
|
|
162
|
-
resp.status,
|
|
163
|
-
code,
|
|
164
|
-
parseRetryAfterSeconds(resp.headers.get("Retry-After")),
|
|
165
|
-
);
|
|
166
|
-
}
|
|
167
|
-
const reader = resp.body.getReader();
|
|
168
|
-
const decoder = new TextDecoder();
|
|
169
|
-
for (;;) {
|
|
170
|
-
const { value, done } = await reader.read();
|
|
171
|
-
if (done) break;
|
|
172
|
-
yield decoder.decode(value, { stream: true });
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* The web SSE transport: {@link streamInvokeOnce} under the shared
|
|
178
|
-
* {@link withSaturationRetry} wrapper. Every consumer of this transport
|
|
179
|
-
* (Studio, the widget, anything built on {@link createWebAdapters}) therefore
|
|
180
|
-
* inherits the single `POD_SATURATED` retry, and inherits the SAME one Portal's
|
|
181
|
-
* React-Native transport wears — see that wrapper's docblock for which refusals
|
|
182
|
-
* retry, which deliberately do not, and why the retry is invisible to the hook.
|
|
183
|
-
*/
|
|
184
|
-
export function fetchStreamTransport(
|
|
185
|
-
req: InvokeRequest,
|
|
186
|
-
accessToken?: string | null,
|
|
187
|
-
guestSecret?: string | null,
|
|
188
|
-
options: SaturationRetryOptions = {},
|
|
189
|
-
): AsyncIterable<string> {
|
|
190
|
-
return withSaturationRetry(
|
|
191
|
-
(attempt) => streamInvokeOnce(attempt, accessToken, guestSecret),
|
|
192
|
-
options,
|
|
193
|
-
)(req);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
50
|
export interface CreateWebAdaptersOptions {
|
|
197
51
|
/**
|
|
198
52
|
* Public read-plane base (ending in `/v1`) for transcript history. When
|
|
@@ -274,10 +128,16 @@ export function createWebAdapters(
|
|
|
274
128
|
const { apiBaseUrl, getAccessToken, getGuestSecret } = opts;
|
|
275
129
|
|
|
276
130
|
const transport: InvokeTransport = async function* (req) {
|
|
277
|
-
const token = getAccessToken ? await getAccessToken() : null;
|
|
278
131
|
// Both candidates go to the transport; it owns the precedence (and the
|
|
279
132
|
// never-two-carriers rule) so there is exactly one place that decides.
|
|
280
|
-
|
|
133
|
+
// The bearer goes through as the PROVIDER, not a pre-resolved value:
|
|
134
|
+
// the transport re-asks it per attempt, so a cold-start retry after a
|
|
135
|
+
// backoff wait re-reads a fresh token instead of replaying one that may
|
|
136
|
+
// have expired during the wait (the same reason Portal's RN transport
|
|
137
|
+
// resolves inside its generator).
|
|
138
|
+
yield* fetchStreamTransport(req, null, getGuestSecret ? getGuestSecret() : null, {
|
|
139
|
+
getBearer: getAccessToken,
|
|
140
|
+
});
|
|
281
141
|
};
|
|
282
142
|
|
|
283
143
|
const adapters: AgentInvokeAdapters = {
|