@tangle-network/agent-app 0.50.9 → 0.50.11
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/dist/assistant/index.js +1 -1
- package/dist/chat-routes/index.js +3 -3
- package/dist/{chunk-DPO7FGCN.js → chunk-53K4S3K6.js} +1 -1
- package/dist/chunk-53K4S3K6.js.map +1 -0
- package/dist/{chunk-XZPJ3VM4.js → chunk-O2UKPZRF.js} +153 -121
- package/dist/chunk-O2UKPZRF.js.map +1 -0
- package/dist/{chunk-ZSSCVT6H.js → chunk-WWFE5EXY.js} +49 -78
- package/dist/chunk-WWFE5EXY.js.map +1 -0
- package/dist/{chunk-3MIQCPUX.js → chunk-XFCKMBOC.js} +3 -3
- package/dist/interactions/index.js +1 -1
- package/dist/interactions/sidecar.d.ts +3 -3
- package/dist/public-consultation/index.js +3 -3
- package/dist/stream/index.js +1 -1
- package/dist/stream/turn-identity.d.ts +3 -0
- package/dist/web-react/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-DPO7FGCN.js.map +0 -1
- package/dist/chunk-XZPJ3VM4.js.map +0 -1
- package/dist/chunk-ZSSCVT6H.js.map +0 -1
- /package/dist/{chunk-3MIQCPUX.js.map → chunk-XFCKMBOC.js.map} +0 -0
|
@@ -10,49 +10,56 @@ function sanitizeUpstreamMessage(input) {
|
|
|
10
10
|
const message = input instanceof Error ? input.message : String(input);
|
|
11
11
|
return message.replace(/Bearer\s+[^\s]+/gi, "Bearer [redacted]").replace(/\b(?:sk|pk|tc)[_-][A-Za-z0-9_-]{8,}\b/g, "[redacted-key]");
|
|
12
12
|
}
|
|
13
|
-
async function
|
|
14
|
-
const
|
|
15
|
-
const
|
|
13
|
+
async function sidecarFetch(connection, family, init = { method: "GET" }) {
|
|
14
|
+
const session = `/agents/sessions/${encodeURIComponent(connection.sessionId)}`;
|
|
15
|
+
const path = family === "interactions" ? `${session}/interactions` : init.method === "POST" ? `${session}/abort` : session;
|
|
16
|
+
const failure = (code, message, status) => ({
|
|
17
|
+
succeeded: false,
|
|
18
|
+
error: { code, message: sanitizeUpstreamMessage(message), status }
|
|
19
|
+
});
|
|
16
20
|
let response;
|
|
21
|
+
let parsed;
|
|
17
22
|
try {
|
|
18
|
-
response = await
|
|
23
|
+
response = await (connection.fetchImpl ?? fetch)(`${connection.runtimeUrl.replace(/\/$/, "")}${path}`, {
|
|
19
24
|
method: init.method,
|
|
20
25
|
headers: {
|
|
21
|
-
...connection.authToken ? {
|
|
22
|
-
...init.method === "POST" ? { "
|
|
26
|
+
...connection.authToken ? { authorization: `Bearer ${connection.authToken}` } : {},
|
|
27
|
+
...init.method === "POST" ? { "content-type": "application/json" } : {}
|
|
23
28
|
},
|
|
24
|
-
...init.method === "POST" ? { body: JSON.stringify(init.body) } : {},
|
|
29
|
+
...init.method === "POST" ? { body: JSON.stringify(init.body ?? {}) } : {},
|
|
30
|
+
redirect: "manual",
|
|
31
|
+
credentials: "omit",
|
|
25
32
|
signal: AbortSignal.timeout(connection.timeoutMs ?? DEFAULT_TIMEOUT_MS)
|
|
26
33
|
});
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
if (response.redirected || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
|
|
35
|
+
await response.body?.cancel().catch(() => void 0);
|
|
36
|
+
return failure("UPSTREAM_REDIRECT", "The sidecar request refused a redirect.", response.status);
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
parsed = await response.json();
|
|
40
|
+
} catch {
|
|
41
|
+
parsed = void 0;
|
|
42
|
+
}
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return family === "interactions" ? failure("UPSTREAM_UNREACHABLE", error, 0) : failure("SIDECAR_UNREACHABLE", error, 502);
|
|
38
45
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
error:
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
),
|
|
48
|
-
status: response.status
|
|
49
|
-
}
|
|
50
|
-
};
|
|
46
|
+
const payload = asRecord(parsed);
|
|
47
|
+
if (!response.ok || payload?.success === false) {
|
|
48
|
+
const error = asRecord(payload?.error);
|
|
49
|
+
return failure(
|
|
50
|
+
typeof error?.code === "string" && error.code ? error.code : family === "interactions" ? "UPSTREAM_ERROR" : "SIDECAR_SESSION_FAILED",
|
|
51
|
+
typeof error?.message === "string" && error.message ? error.message : `sidecar ${family} ${init.method} failed (${response.status})`,
|
|
52
|
+
response.status
|
|
53
|
+
);
|
|
51
54
|
}
|
|
52
|
-
|
|
55
|
+
if (!payload) return failure("MALFORMED_RESPONSE", "The sidecar returned no JSON object.", response.status);
|
|
56
|
+
return { succeeded: true, value: payload };
|
|
57
|
+
}
|
|
58
|
+
function asRecord(value) {
|
|
59
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
53
60
|
}
|
|
54
61
|
async function listSessionInteractions(connection) {
|
|
55
|
-
const result = await
|
|
62
|
+
const result = await sidecarFetch(connection, "interactions");
|
|
56
63
|
if (!result.succeeded) return result;
|
|
57
64
|
const data = result.value.data;
|
|
58
65
|
if (!Array.isArray(data?.interactions)) {
|
|
@@ -64,7 +71,7 @@ async function listSessionInteractions(connection) {
|
|
|
64
71
|
return { succeeded: true, value: data.interactions };
|
|
65
72
|
}
|
|
66
73
|
async function respondToSessionInteraction(connection, response) {
|
|
67
|
-
const result = await
|
|
74
|
+
const result = await sidecarFetch(connection, "interactions", {
|
|
68
75
|
method: "POST",
|
|
69
76
|
body: {
|
|
70
77
|
id: response.id,
|
|
@@ -73,6 +80,12 @@ async function respondToSessionInteraction(connection, response) {
|
|
|
73
80
|
}
|
|
74
81
|
});
|
|
75
82
|
if (!result.succeeded) return result;
|
|
83
|
+
if (result.value.success !== true && asRecord(result.value.data)?.ok !== true) {
|
|
84
|
+
return {
|
|
85
|
+
succeeded: false,
|
|
86
|
+
error: { code: "MALFORMED_RESPONSE", message: "sidecar answer returned no acknowledgement", status: 200 }
|
|
87
|
+
};
|
|
88
|
+
}
|
|
76
89
|
return { succeeded: true, value: void 0 };
|
|
77
90
|
}
|
|
78
91
|
function isTerminalSidecarState(state) {
|
|
@@ -82,48 +95,6 @@ function isTerminalSidecarState(state) {
|
|
|
82
95
|
return TERMINAL_SESSION_STATES.includes(state.state ?? "") || state.reconnectable === false;
|
|
83
96
|
}
|
|
84
97
|
var TERMINAL_SESSION_STATES = ["completed", "failed", "aborted", "expired", "idle", "terminal"];
|
|
85
|
-
async function sessionFetch(connection, init = { method: "GET" }) {
|
|
86
|
-
const doFetch = connection.fetchImpl ?? fetch;
|
|
87
|
-
const base = `${connection.runtimeUrl.replace(/\/$/, "")}/agents/sessions/${encodeURIComponent(connection.sessionId)}`;
|
|
88
|
-
const url = init.method === "POST" ? `${base}/abort` : base;
|
|
89
|
-
let response;
|
|
90
|
-
try {
|
|
91
|
-
response = await doFetch(url, {
|
|
92
|
-
method: init.method,
|
|
93
|
-
headers: {
|
|
94
|
-
...connection.authToken ? { authorization: `Bearer ${connection.authToken}` } : {},
|
|
95
|
-
...init.method === "POST" ? { "content-type": "application/json" } : {}
|
|
96
|
-
},
|
|
97
|
-
...init.method === "POST" ? { body: "{}" } : {},
|
|
98
|
-
signal: AbortSignal.timeout(connection.timeoutMs ?? DEFAULT_TIMEOUT_MS)
|
|
99
|
-
});
|
|
100
|
-
} catch (err) {
|
|
101
|
-
return {
|
|
102
|
-
succeeded: false,
|
|
103
|
-
error: { code: "SIDECAR_UNREACHABLE", message: sanitizeUpstreamMessage(err), status: 502 }
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
let parsed = {};
|
|
107
|
-
try {
|
|
108
|
-
parsed = await response.json();
|
|
109
|
-
} catch {
|
|
110
|
-
parsed = {};
|
|
111
|
-
}
|
|
112
|
-
if (!response.ok) {
|
|
113
|
-
const upstreamError = parsed.error && typeof parsed.error === "object" ? parsed.error : {};
|
|
114
|
-
return {
|
|
115
|
-
succeeded: false,
|
|
116
|
-
error: {
|
|
117
|
-
code: typeof upstreamError.code === "string" && upstreamError.code ? upstreamError.code : "SIDECAR_SESSION_FAILED",
|
|
118
|
-
message: sanitizeUpstreamMessage(
|
|
119
|
-
typeof upstreamError.message === "string" && upstreamError.message ? upstreamError.message : `sidecar session ${init.method} failed (${response.status})`
|
|
120
|
-
),
|
|
121
|
-
status: response.status
|
|
122
|
-
}
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
return { succeeded: true, value: parsed };
|
|
126
|
-
}
|
|
127
98
|
function sessionStateFromPayload(payload) {
|
|
128
99
|
const data = payload.data && typeof payload.data === "object" ? payload.data : payload;
|
|
129
100
|
const session = data.session && typeof data.session === "object" ? data.session : data;
|
|
@@ -142,12 +113,12 @@ function sessionStateFromPayload(payload) {
|
|
|
142
113
|
};
|
|
143
114
|
}
|
|
144
115
|
async function getSessionState(connection) {
|
|
145
|
-
const result = await
|
|
116
|
+
const result = await sidecarFetch(connection, "session");
|
|
146
117
|
if (!result.succeeded) return result;
|
|
147
118
|
return { succeeded: true, value: sessionStateFromPayload(result.value) };
|
|
148
119
|
}
|
|
149
120
|
async function abortSession(connection) {
|
|
150
|
-
const result = await
|
|
121
|
+
const result = await sidecarFetch(connection, "session", { method: "POST" });
|
|
151
122
|
if (!result.succeeded) {
|
|
152
123
|
if (result.error.status === 404) return { succeeded: true, value: { cancelled: false, reason: "not-found" } };
|
|
153
124
|
return result;
|
|
@@ -395,4 +366,4 @@ export {
|
|
|
395
366
|
mapInteractionRespondFailure,
|
|
396
367
|
createInteractionAnswerRoute
|
|
397
368
|
};
|
|
398
|
-
//# sourceMappingURL=chunk-
|
|
369
|
+
//# sourceMappingURL=chunk-WWFE5EXY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/interactions/sidecar.ts","../src/interactions/route.ts"],"sourcesContent":["/**\n * Server-side client for the sandbox sidecar's generic interaction routes\n * (`GET/POST {runtimeUrl}/agents/sessions/{sessionId}/interactions`). The\n * transport supports structural connections and older response shapes across\n * question/permission/plan interactions. Exact-run cancellation belongs to the\n * native SDK, not this session-wide compatibility surface.\n *\n * Server-only: the sidecar bearer must never reach browser code. The caller\n * supplies the connection as a structural value (runtime URL + bearer +\n * session id) — no sandbox-SDK import, so any box-resolution strategy works.\n */\n\nimport type { InteractionData, InteractionOutcome, InteractionRequestWire } from './contract'\n\n/** Describe error details including code, message, and upstream HTTP status for sidecar interactions */\nexport interface SidecarInteractionsError {\n code: string\n message: string\n /** Upstream HTTP status; 0 when the sidecar was unreachable. */\n status: number\n}\n\n/** Represent the outcome of sidecar interactions with success or error details */\nexport type SidecarInteractionsResult<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: SidecarInteractionsError }\n\n/** Where and how to reach one session's interaction registry. */\nexport interface SidecarInteractionsConnection {\n runtimeUrl: string\n authToken?: string\n /** The sidecar agent-session id (the chat thread's session). */\n sessionId: string\n /** Request deadline. A pending interaction means the box is up and the\n * sidecar responsive; a short default keeps a wedged runtime from stalling\n * the answering request. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global fetch. */\n fetchImpl?: typeof fetch\n}\n\nconst DEFAULT_TIMEOUT_MS = 5_000\n\n/** Strips bearer tokens / key material before an upstream message is logged\n * or surfaced. */\nfunction sanitizeUpstreamMessage(input: unknown): string {\n const message = input instanceof Error ? input.message : String(input)\n return message\n .replace(/Bearer\\s+[^\\s]+/gi, 'Bearer [redacted]')\n .replace(/\\b(?:sk|pk|tc)[_-][A-Za-z0-9_-]{8,}\\b/g, '[redacted-key]')\n}\n\n/** One transport for session controls and interaction answers. Keep the established\n * error codes per family; authentication, deadlines and decoding cannot drift. */\nasync function sidecarFetch(\n connection: SidecarInteractionsConnection,\n family: 'interactions' | 'session',\n init: { method: 'GET' | 'POST'; body?: Record<string, unknown> } = { method: 'GET' },\n): Promise<SidecarInteractionsResult<Record<string, unknown>>> {\n const session = `/agents/sessions/${encodeURIComponent(connection.sessionId)}`\n const path = family === 'interactions' ? `${session}/interactions`\n : init.method === 'POST' ? `${session}/abort` : session\n const failure = (code: string, message: unknown, status: number): SidecarInteractionsResult<never> => ({\n succeeded: false, error: { code, message: sanitizeUpstreamMessage(message), status },\n })\n let response: Response\n let parsed: unknown\n try {\n response = await (connection.fetchImpl ?? fetch)(`${connection.runtimeUrl.replace(/\\/$/, '')}${path}`, {\n method: init.method,\n headers: {\n ...(connection.authToken ? { authorization: `Bearer ${connection.authToken}` } : {}),\n ...(init.method === 'POST' ? { 'content-type': 'application/json' } : {}),\n },\n ...(init.method === 'POST' ? { body: JSON.stringify(init.body ?? {}) } : {}),\n redirect: 'manual',\n credentials: 'omit',\n signal: AbortSignal.timeout(connection.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n if (response.redirected || response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {\n await response.body?.cancel().catch(() => undefined)\n return failure('UPSTREAM_REDIRECT', 'The sidecar request refused a redirect.', response.status)\n }\n try { parsed = await response.json() } catch { parsed = undefined }\n } catch (error) {\n return family === 'interactions'\n ? failure('UPSTREAM_UNREACHABLE', error, 0)\n : failure('SIDECAR_UNREACHABLE', error, 502)\n }\n const payload = asRecord(parsed)\n if (!response.ok || payload?.success === false) {\n const error = asRecord(payload?.error)\n return failure(\n typeof error?.code === 'string' && error.code ? error.code\n : family === 'interactions' ? 'UPSTREAM_ERROR' : 'SIDECAR_SESSION_FAILED',\n typeof error?.message === 'string' && error.message ? error.message\n : `sidecar ${family} ${init.method} failed (${response.status})`,\n response.status,\n )\n }\n if (!payload) return failure('MALFORMED_RESPONSE', 'The sidecar returned no JSON object.', response.status)\n return { succeeded: true, value: payload }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown> : undefined\n}\n\n/** Outstanding (unanswered) interactions for the session — the sidecar's\n * registry is authoritative, so this is the reconnect/reload source of truth. */\nexport async function listSessionInteractions(\n connection: SidecarInteractionsConnection,\n): Promise<SidecarInteractionsResult<InteractionRequestWire[]>> {\n const result = await sidecarFetch(connection, 'interactions')\n if (!result.succeeded) return result\n const data = result.value.data as { interactions?: unknown } | undefined\n if (!Array.isArray(data?.interactions)) {\n return {\n succeeded: false,\n error: { code: 'MALFORMED_RESPONSE', message: 'sidecar list returned no interactions array', status: 200 },\n }\n }\n return { succeeded: true, value: data.interactions as InteractionRequestWire[] }\n}\n\n/** Resolves one interaction. `data` is required by the sidecar only for\n * `accepted` outcomes and is validated fail-closed against the answerSpec\n * (400 INVALID_INTERACTION_ANSWER on mismatch). */\nexport async function respondToSessionInteraction(\n connection: SidecarInteractionsConnection,\n response: { id: string; outcome: InteractionOutcome; data?: InteractionData },\n): Promise<SidecarInteractionsResult<void>> {\n const result = await sidecarFetch(connection, 'interactions', {\n method: 'POST',\n body: {\n id: response.id,\n outcome: response.outcome,\n ...(response.data ? { data: response.data } : {}),\n },\n })\n if (!result.succeeded) return result\n // An HTTP success is not an acknowledgement that the answer was applied.\n // Current runtimes return success:true; retain the supported data.ok receipt.\n if (result.value.success !== true && asRecord(result.value.data)?.ok !== true) {\n return {\n succeeded: false,\n error: { code: 'MALFORMED_RESPONSE', message: 'sidecar answer returned no acknowledgement', status: 200 },\n }\n }\n return { succeeded: true, value: undefined }\n}\n\n/**\n * A sandbox session's lifecycle as the sidecar reports it.\n *\n * Every field is optional because the sidecar's payload has grown over time and\n * an older box answers with a subset. A reader that assumes a field is present\n * mis-reads an old box as terminal; the shapes below are read defensively for\n * that reason, not out of caution about types.\n */\nexport interface SidecarSessionState {\n state?: string\n activeExecutionId?: string | null\n activeExecutionStatus?: string | null\n reconnectable?: boolean\n registryAuthority?: string | null\n terminalReason?: string | null\n lastEventAt?: string | number | null\n outstandingInteractions?: unknown[]\n}\n\nexport interface SidecarAbortResult {\n cancelled: boolean\n reason?: string\n session?: SidecarSessionState\n}\n\n/**\n * Whether a session has finished and will not produce more events.\n *\n * The three early returns are the ones that matter: a session with a live\n * execution, one the platform says is reconnectable, or one holding an\n * unanswered interaction is NOT terminal however its `state` string reads. An\n * app that treats such a session as finished abandons a turn mid-flight, or\n * leaves an agent blocked on an answer nobody will send.\n */\nexport function isTerminalSidecarState(state: {\n state?: string\n activeExecutionId?: string | null\n reconnectable?: boolean\n outstandingInteractions?: unknown[]\n}): boolean {\n if (state.activeExecutionId) return false\n if (state.reconnectable === true) return false\n if (state.outstandingInteractions && state.outstandingInteractions.length > 0) return false\n return TERMINAL_SESSION_STATES.includes(state.state ?? '') || state.reconnectable === false\n}\n\nconst TERMINAL_SESSION_STATES = ['completed', 'failed', 'aborted', 'expired', 'idle', 'terminal']\n\n/** Read the session payload defensively: newer boxes nest under `data`, and\n * the execution id appears either on the session or on `activeExecution`. */\nfunction sessionStateFromPayload(payload: Record<string, unknown>): SidecarSessionState {\n const data = (payload.data && typeof payload.data === 'object' ? payload.data : payload) as Record<string, unknown>\n const session = data.session && typeof data.session === 'object'\n ? data.session as Record<string, unknown>\n : data\n const activeExecution = data.activeExecution && typeof data.activeExecution === 'object'\n ? data.activeExecution as Record<string, unknown>\n : session.activeExecution && typeof session.activeExecution === 'object'\n ? session.activeExecution as Record<string, unknown>\n : null\n const interactions = session.outstandingInteractions ?? session.interactions\n return {\n ...(typeof session.state === 'string' ? { state: session.state } : {}),\n ...(typeof session.activeExecutionId === 'string'\n ? { activeExecutionId: session.activeExecutionId }\n : session.activeExecutionId === null ? { activeExecutionId: null } : {}),\n ...(typeof session.reconnectable === 'boolean' ? { reconnectable: session.reconnectable } : {}),\n ...(typeof session.registryAuthority === 'string'\n ? { registryAuthority: session.registryAuthority }\n : session.registryAuthority === null ? { registryAuthority: null } : {}),\n ...(typeof session.terminalReason === 'string'\n ? { terminalReason: session.terminalReason }\n : session.terminalReason === null ? { terminalReason: null } : {}),\n ...(typeof session.lastEventAt === 'string' || typeof session.lastEventAt === 'number' || session.lastEventAt === null\n ? { lastEventAt: session.lastEventAt }\n : {}),\n ...(Array.isArray(interactions) ? { outstandingInteractions: interactions } : {}),\n ...(activeExecution && typeof activeExecution.id === 'string' && typeof session.activeExecutionId !== 'string'\n ? { activeExecutionId: activeExecution.id }\n : {}),\n ...(activeExecution && typeof activeExecution.status === 'string'\n ? { activeExecutionStatus: activeExecution.status }\n : activeExecution === null && session.activeExecution === null ? { activeExecutionStatus: null } : {}),\n }\n}\n\n/** The session's current lifecycle, for reconnect and resume decisions. */\nexport async function getSessionState(\n connection: SidecarInteractionsConnection,\n): Promise<SidecarInteractionsResult<SidecarSessionState>> {\n const result = await sidecarFetch(connection, 'session')\n if (!result.succeeded) return result\n return { succeeded: true, value: sessionStateFromPayload(result.value) }\n}\n\n/**\n * Cancel a running session.\n *\n * A 404 is reported as a SUCCESSFUL no-op rather than an error: the caller's\n * intent is \"this session must not be running\", and a session the sidecar has\n * never heard of already satisfies that. Surfacing it as a failure makes every\n * cancel-after-completion look like an outage.\n */\nexport async function abortSession(\n connection: SidecarInteractionsConnection,\n): Promise<SidecarInteractionsResult<SidecarAbortResult>> {\n const result = await sidecarFetch(connection, 'session', { method: 'POST' })\n if (!result.succeeded) {\n if (result.error.status === 404) return { succeeded: true, value: { cancelled: false, reason: 'not-found' } }\n return result\n }\n const data = (result.value.data && typeof result.value.data === 'object'\n ? result.value.data\n : result.value) as Record<string, unknown>\n const reason = typeof data.reason === 'string' && data.reason.trim()\n ? data.reason.trim()\n : typeof data.noopReason === 'string' && data.noopReason.trim()\n ? data.noopReason.trim()\n : undefined\n return {\n succeeded: true,\n value: {\n cancelled: data.cancelled === true,\n ...(reason ? { reason } : {}),\n ...(data.session && typeof data.session === 'object' ? { session: sessionStateFromPayload(result.value) } : {}),\n },\n }\n}\n","/**\n * Framework-neutral interaction-answer endpoints, lifted out of the per-app\n * route files (gtm `api.chat.interactions`, legal `api.chat.interactions`,\n * tax `api.sessions.$id.interactions` — three byte-similar forks):\n *\n * list(request) — GET: outstanding asks for a live turn (reload restore)\n * answer(request) — POST `{ id, outcome, data? }`: resolve one ask\n *\n * The product supplies ONE seam, `resolveConnection`: authenticate the caller,\n * authorize the thread/session, and resolve the sidecar connection. Everything\n * behind the seam is mechanism the forks kept re-fixing:\n *\n * - body validation (safe field keys, typed values),\n * - sidecar error → client contract mapping (every \"the ask is gone\" shape\n * becomes 410 so the card flips to its expired state),\n * - duplicate resolution: after answering, every other outstanding ask with\n * the same content signature (a re-emitted duplicate) gets the same answer,\n * - unblock verification: re-list and fail loud (503 INTERACTION_STILL_PENDING)\n * when the sidecar accepted the POST but the ask is still open,\n * - best-effort list: sidecar failures return `{ interactions: [],\n * unavailable }` so a reload restore never breaks the live stream.\n *\n * Handlers return web-standard `Response`s (Workers, Node 18+, Deno) — no\n * router import anywhere.\n */\n\nimport {\n interactionFromWireRequest,\n isSafeInteractionFieldKey,\n questionInteractionContentSignature,\n type InteractionData,\n type InteractionRequestWire,\n} from './contract'\nimport {\n listSessionInteractions,\n respondToSessionInteraction,\n type SidecarInteractionsConnection,\n type SidecarInteractionsError,\n} from './sidecar'\n\n// A client resolves an ask by answering (`accepted`) or refusing (`declined`).\n// Withdrawal (`cancelled`) is an agent/broker outcome delivered via the\n// `interaction.cancel` event, never a client POST, so it is not accepted here.\n/** Define possible outcomes for an interaction client as accepted or declined */\nexport type InteractionClientOutcome = 'accepted' | 'declined'\n\n/** Validate interaction answer body and return success with data or failure with error message */\nexport type InteractionAnswerBodyValidation =\n | { ok: true; id: string; outcome: InteractionClientOutcome; data?: InteractionData }\n | { ok: false; error: string }\n\n/** Validates the client POST body: `{ id, outcome, data? }` with\n * identifier-safe field keys and primitive/string-array values only. */\nexport function validateInteractionAnswerBody(body: Record<string, unknown>): InteractionAnswerBodyValidation {\n const id = typeof body.id === 'string' && body.id ? body.id : null\n if (!id) return { ok: false, error: 'Missing interaction id' }\n const outcome = body.outcome\n if (outcome !== 'accepted' && outcome !== 'declined') {\n return { ok: false, error: 'Invalid outcome: expected accepted or declined' }\n }\n if (body.data === undefined) return { ok: true, id, outcome }\n if (!body.data || typeof body.data !== 'object' || Array.isArray(body.data)) {\n return { ok: false, error: 'Invalid data: expected an object of field values' }\n }\n const data: InteractionData = {}\n for (const [key, value] of Object.entries(body.data)) {\n if (!isSafeInteractionFieldKey(key)) {\n return { ok: false, error: 'Invalid data: field names must contain only letters, numbers, underscores, or hyphens' }\n }\n const validValue =\n typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ||\n (Array.isArray(value) && value.every((item) => typeof item === 'string'))\n if (!validValue) {\n return { ok: false, error: 'Invalid data: field values must be strings, numbers, booleans, or string arrays' }\n }\n data[key] = value as InteractionData[string]\n }\n return { ok: true, id, outcome, data }\n}\n\n/** Provide logging methods for warnings and errors in interaction routes */\nexport type InteractionRouteLogger = Pick<Console, 'warn' | 'error'>\n\n/** Sidecar error → the client-actionable contract. Every \"the ask is gone\"\n * shape maps to 410 so the card flips to its expired state — a raw 404/409\n * must never surface. */\nexport function mapInteractionRespondFailure(\n error: SidecarInteractionsError,\n logger: InteractionRouteLogger = console,\n): Response {\n if (error.code === 'INVALID_INTERACTION_ANSWER') {\n return Response.json(\n { code: 'INVALID_INTERACTION_ANSWER', error: 'This question needs an answer from the card above — pick one of the listed options.' },\n { status: 400 },\n )\n }\n if (error.status === 404) {\n return Response.json(\n { code: 'INTERACTION_EXPIRED', error: 'This question is no longer waiting for an answer.' },\n { status: 410 },\n )\n }\n if (error.status === 501 || error.code === 'NOT_IMPLEMENTED') {\n return Response.json(\n { code: 'INTERACTIONS_UNSUPPORTED', error: 'This agent backend cannot accept answers this way.' },\n { status: 501 },\n )\n }\n logger.error('[interactions] respond failed:', error)\n return Response.json(\n { code: 'INTERACTION_UPSTREAM_FAILED', error: 'Could not reach the agent. Try again.' },\n { status: 503 },\n )\n}\n\n/** The product seam's verdict for one request. `response` short-circuits with\n * a product-authored Response (401/404/429…); `unavailable` means the caller\n * is fine but the sandbox runtime is not reachable — the factory shapes that\n * per intent (empty list for `list`, 503 for `answer`). */\nexport type InteractionConnectionResolution =\n | { ok: true; connection: SidecarInteractionsConnection }\n | { ok: false; response: Response }\n | { ok: false; unavailable: string }\n\n/** Define arguments required to resolve interaction connections based on request and intent */\nexport interface ResolveInteractionConnectionArgs {\n request: Request\n intent: 'list' | 'answer'\n /** The parsed, validated POST body (answer intent only) so the resolver can\n * read product routing fields (workspaceId/threadId) without re-parsing. */\n body?: Record<string, unknown>\n}\n\n/** Describe the arguments provided before processing an interaction answer including request, body, and connection details */\nexport interface BeforeInteractionAnswerArgs {\n request: Request\n /** Original parsed body, including product routing fields. */\n body: Record<string, unknown>\n /** Shared validation result; products never need to parse the answer again. */\n answer: Extract<InteractionAnswerBodyValidation, { ok: true }>\n connection: SidecarInteractionsConnection\n /** The route's single authoritative pre-answer sidecar snapshot. */\n outstanding: InteractionRequestWire[]\n answeredRequest?: InteractionRequestWire\n /** Content-identical questions that the shared route will also answer. */\n duplicateRequests: InteractionRequestWire[]\n}\n\n/** Define arguments for durable interaction routes including a stable caller-created attempt key */\nexport interface DurableInteractionRouteArgs extends BeforeInteractionAnswerArgs {\n /** Caller-created opaque identifier, stable across an ambiguous retry. */\n attemptKey: string\n}\n\n/** Crash-recoverable persistence lifecycle for the answer route. The product\n * binds this structural port to its OWN durable store — agent-app ships no\n * implementation (the `/durable-chat` module that used to provide one was\n * removed in 0.44.0 after nine repos produced zero imports of it). Existing\n * `beforeAnswer` behavior remains independent and unchanged. */\nexport interface DurableInteractionRoutePersistence<TPrepared = unknown> {\n guarantee: 'reconciled' | 'best-effort'\n prepare(args: DurableInteractionRouteArgs): TPrepared | Promise<TPrepared>\n /** Resolve an ambiguous retry (for example, the sidecar says the ask is\n * already gone). Only `settled:true` permits the route to report success. */\n reconcile(args: DurableInteractionRouteArgs & { prepared: TPrepared }):\n | { settled: boolean }\n | Promise<{ settled: boolean }>\n /** Record the authority acknowledgement before terminal projection. */\n acknowledge(args: DurableInteractionRouteArgs & {\n prepared: TPrepared\n duplicateIds: string[]\n }): void | Promise<void>\n /** Idempotently materialize terminal status and accepted values. */\n finalize(args: DurableInteractionRouteArgs & {\n prepared: TPrepared\n duplicateIds: string[]\n }): void | Promise<void>\n fail?(args: DurableInteractionRouteArgs & { prepared: TPrepared; error: unknown }): void | Promise<void>\n}\n\n/** Define options to authenticate, authorize, and manage persistence for interaction answer routes */\nexport interface InteractionAnswerRouteOptions {\n /** Authenticate + authorize the caller and resolve the sidecar connection.\n * This is the only product-supplied step: session auth, workspace/thread\n * access, rate limiting, and box resolution all live here. */\n resolveConnection: (args: ResolveInteractionConnectionArgs) => Promise<InteractionConnectionResolution>\n /** Product persistence seam that runs before the answer can unblock and\n * finalize the agent turn. A throw aborts the request before any answer POST. */\n beforeAnswer?: (args: BeforeInteractionAnswerArgs) => void | Promise<void>\n /** Additive crash-recoverable settlement. When configured, POST requires an\n * `attemptKey`; accepted values are finalized only after sidecar ack. */\n durable?: DurableInteractionRoutePersistence\n logger?: InteractionRouteLogger\n}\n\n/** Define routes to list outstanding interactions and resolve answers for live turns */\nexport interface InteractionAnswerRoute {\n /** GET — outstanding interactions for a live turn. Failures return an empty\n * list with an explicit `unavailable` code: the caller is a best-effort\n * reload restore, and the live/replayed stream must stay untouched when the\n * sidecar cannot answer. */\n list: (request: Request) => Promise<Response>\n /** POST `{ id, outcome, data?, ...productFields }` — resolve one ask, answer\n * content-identical duplicates the same way, then re-list to prove the run\n * actually unblocked. */\n answer: (request: Request) => Promise<Response>\n}\n\n/** Create an interaction answer route that handles listing and resolving interaction requests */\nexport function createInteractionAnswerRoute(options: InteractionAnswerRouteOptions): InteractionAnswerRoute {\n const logger = options.logger ?? console\n\n async function list(request: Request): Promise<Response> {\n const resolution = await options.resolveConnection({ request, intent: 'list' })\n if (!resolution.ok) {\n if ('response' in resolution) return resolution.response\n return Response.json({ interactions: [], unavailable: resolution.unavailable })\n }\n const result = await listSessionInteractions(resolution.connection)\n if (!result.succeeded) {\n logger.warn('[interactions] list failed:', result.error)\n return Response.json({ interactions: [], unavailable: result.error.code })\n }\n return Response.json({ interactions: result.value })\n }\n\n async function answer(request: Request): Promise<Response> {\n const body = await request.json().catch(() => null) as Record<string, unknown> | null\n if (!body || typeof body !== 'object' || Array.isArray(body)) {\n return Response.json({ error: 'Invalid JSON body' }, { status: 400 })\n }\n const validation = validateInteractionAnswerBody(body)\n if (!validation.ok) return Response.json({ error: validation.error }, { status: 400 })\n const attemptKey = typeof body.attemptKey === 'string' ? body.attemptKey.trim() : ''\n if (options.durable && !attemptKey) {\n return Response.json({ error: 'Missing attemptKey for durable interaction answer' }, { status: 400 })\n }\n\n const resolution = await options.resolveConnection({ request, intent: 'answer', body })\n if (!resolution.ok) {\n if ('response' in resolution) return resolution.response\n return mapInteractionRespondFailure(\n { code: resolution.unavailable, message: 'sandbox runtime unavailable', status: 0 },\n logger,\n )\n }\n const connection = resolution.connection\n const answerPayload = {\n outcome: validation.outcome,\n ...(validation.data ? { data: validation.data } : {}),\n }\n\n // Snapshot the answered ask's content signature BEFORE resolving it, so any\n // content-identical duplicates still outstanding afterwards (the agent may\n // have re-emitted the same question N times) can be answered the same way.\n const before = await listSessionInteractions(connection)\n if (!before.succeeded && (options.beforeAnswer || options.durable)) {\n return mapInteractionRespondFailure(before.error, logger)\n }\n const answeredRequest = before.succeeded ? before.value.find((item) => item.id === validation.id) : undefined\n if (options.beforeAnswer && !options.durable && !answeredRequest) {\n return mapInteractionRespondFailure(\n { code: 'NOT_FOUND', message: 'interaction not found', status: 404 },\n logger,\n )\n }\n const answeredSignature = answeredRequest\n ? questionInteractionContentSignature(interactionFromWireRequest(answeredRequest))\n : null\n const duplicateRequests = before.succeeded && answeredSignature\n ? before.value.filter((item) => item.id !== validation.id && (\n questionInteractionContentSignature(interactionFromWireRequest(item)) === answeredSignature\n ))\n : []\n\n const lifecycleArgs: BeforeInteractionAnswerArgs = {\n request,\n body,\n answer: validation,\n connection,\n outstanding: before.succeeded ? before.value : [],\n ...(answeredRequest ? { answeredRequest } : {}),\n duplicateRequests,\n }\n\n if (options.beforeAnswer && answeredRequest) {\n try {\n await options.beforeAnswer(lifecycleArgs)\n } catch (error) {\n logger.error('[interactions] beforeAnswer failed:', error)\n return Response.json(\n { code: 'INTERACTION_BEFORE_ANSWER_FAILED', error: 'Could not save the answer. Try again.' },\n { status: 503 },\n )\n }\n }\n\n let prepared: unknown\n const durableArgs = options.durable\n ? { ...lifecycleArgs, attemptKey }\n : null\n if (options.durable && durableArgs) {\n try {\n prepared = await options.durable.prepare(durableArgs)\n } catch (error) {\n logger.error('[interactions] durable prepare failed:', error)\n return Response.json(\n { code: 'INTERACTION_PREPARE_FAILED', error: 'Could not prepare the answer. Try again.' },\n { status: 503 },\n )\n }\n if (!answeredRequest) {\n let reconciled: { settled: boolean }\n try {\n reconciled = await options.durable.reconcile({ ...durableArgs, prepared })\n } catch (error) {\n logger.error('[interactions] durable reconcile failed:', error)\n reconciled = { settled: false }\n }\n if (reconciled.settled) return Response.json({ ok: true, idempotent: true })\n return Response.json(\n { code: 'INTERACTION_RECONCILIATION_PENDING', error: 'The answer status is still being checked. Retry with the same attempt.' },\n { status: 503 },\n )\n }\n }\n\n const result = await respondToSessionInteraction(connection, { id: validation.id, ...answerPayload })\n if (!result.succeeded) {\n if (options.durable && durableArgs) {\n let reconciled: { settled: boolean }\n try {\n reconciled = await options.durable.reconcile({ ...durableArgs, prepared })\n } catch {\n reconciled = { settled: false }\n }\n if (reconciled.settled) return Response.json({ ok: true, idempotent: true })\n if (result.error.status === 404) {\n return Response.json(\n { code: 'INTERACTION_RECONCILIATION_PENDING', error: 'The answer status is still being checked. Retry with the same attempt.' },\n { status: 503 },\n )\n }\n try {\n await options.durable.fail?.({ ...durableArgs, prepared, error: result.error })\n } catch {\n // The upstream failure remains authoritative; a persistence cleanup\n // failure must not replace its client-facing mapping.\n }\n }\n return mapInteractionRespondFailure(result.error, logger)\n }\n\n let remaining = await listSessionInteractions(connection)\n const acknowledgedDuplicateIds: string[] = []\n if (remaining.succeeded && answeredSignature) {\n const remainingDuplicates = remaining.value.filter((item) => {\n if (item.id === validation.id) return false\n return questionInteractionContentSignature(interactionFromWireRequest(item)) === answeredSignature\n })\n for (const duplicate of remainingDuplicates) {\n const duplicateResult = await respondToSessionInteraction(connection, { id: duplicate.id, ...answerPayload })\n if (!duplicateResult.succeeded) break\n acknowledgedDuplicateIds.push(duplicate.id)\n }\n if (remainingDuplicates.length > 0) remaining = await listSessionInteractions(connection)\n }\n\n // Prove the run actually unblocked: neither the answered id nor any\n // content-duplicate may still be outstanding. If one is, the sidecar\n // accepted the POST but did not release the run — report it rather than\n // tell the user it was answered.\n if (remaining.succeeded && remaining.value.some((item) => item.id === validation.id || (\n answeredSignature && questionInteractionContentSignature(interactionFromWireRequest(item)) === answeredSignature\n ))) {\n logger.error('[interactions] respond returned ok but interaction is still pending:', {\n sessionId: connection.sessionId,\n interactionId: validation.id,\n })\n return Response.json(\n { code: 'INTERACTION_STILL_PENDING', error: 'The agent did not accept the answer. Try answering again.' },\n { status: 503 },\n )\n }\n\n if (options.durable && durableArgs) {\n try {\n await options.durable.acknowledge({\n ...durableArgs,\n prepared,\n duplicateIds: acknowledgedDuplicateIds,\n })\n await options.durable.finalize({\n ...durableArgs,\n prepared,\n duplicateIds: acknowledgedDuplicateIds,\n })\n } catch (error) {\n logger.error('[interactions] durable finalize failed:', error)\n return Response.json(\n { code: 'INTERACTION_FINALIZE_FAILED', error: 'The answer was accepted but is still being saved. Retry to reconcile it.' },\n { status: 503 },\n )\n }\n }\n\n return Response.json({ ok: true })\n }\n\n return { list, answer }\n}\n"],"mappings":";;;;;;;AAyCA,IAAM,qBAAqB;AAI3B,SAAS,wBAAwB,OAAwB;AACvD,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,SAAO,QACJ,QAAQ,qBAAqB,mBAAmB,EAChD,QAAQ,0CAA0C,gBAAgB;AACvE;AAIA,eAAe,aACb,YACA,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O,SAAS;AAAA,UACd,EAAE,MAAM,+BAA+B,OAAO,2EAA2E;AAAA,UACzH,EAAE,QAAQ,IAAI;AAAA,QAChB;AAAA,MACF;AAAA,IACF;AAEA,WAAO,SAAS,KAAK,EAAE,IAAI,KAAK,CAAC;AAAA,EACnC;AAEA,SAAO,EAAE,MAAM,OAAO;AACxB;","names":[]}
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-3NCPXNBZ.js";
|
|
4
4
|
import {
|
|
5
5
|
createInteractionAnswerRoute
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-WWFE5EXY.js";
|
|
7
7
|
import {
|
|
8
8
|
mentionInputToPart,
|
|
9
9
|
toChatMessageParts
|
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
import {
|
|
19
19
|
normalizeClientTurnId,
|
|
20
20
|
resolveChatTurn
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-53K4S3K6.js";
|
|
22
22
|
import {
|
|
23
23
|
coalesceDeltas,
|
|
24
24
|
createBufferedTurnTap,
|
|
@@ -1078,4 +1078,4 @@ export {
|
|
|
1078
1078
|
createChatTurnRoutes,
|
|
1079
1079
|
streamChatRouteAsSandboxEvents
|
|
1080
1080
|
};
|
|
1081
|
-
//# sourceMappingURL=chunk-
|
|
1081
|
+
//# sourceMappingURL=chunk-XFCKMBOC.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Server-side client for the sandbox sidecar's generic interaction routes
|
|
3
3
|
* (`GET/POST {runtimeUrl}/agents/sessions/{sessionId}/interactions`). The
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* transport supports structural connections and older response shapes across
|
|
5
|
+
* question/permission/plan interactions. Exact-run cancellation belongs to the
|
|
6
|
+
* native SDK, not this session-wide compatibility surface.
|
|
7
7
|
*
|
|
8
8
|
* Server-only: the sidecar bearer must never reach browser code. The caller
|
|
9
9
|
* supplies the connection as a structural value (runtime URL + bearer +
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createChatTurnRoutes,
|
|
3
3
|
streamChatRouteAsSandboxEvents
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-XFCKMBOC.js";
|
|
5
5
|
import "../chunk-TZEEGDHS.js";
|
|
6
6
|
import "../chunk-3NCPXNBZ.js";
|
|
7
|
-
import "../chunk-
|
|
7
|
+
import "../chunk-WWFE5EXY.js";
|
|
8
8
|
import "../chunk-RACQDXJ7.js";
|
|
9
9
|
import "../chunk-X47R2IVO.js";
|
|
10
10
|
import "../chunk-ZVEEWGDK.js";
|
|
11
11
|
import "../chunk-TXD5HXLE.js";
|
|
12
|
-
import "../chunk-
|
|
12
|
+
import "../chunk-53K4S3K6.js";
|
|
13
13
|
import "../chunk-MX55JP7D.js";
|
|
14
14
|
import "../chunk-YJMCRXQQ.js";
|
|
15
15
|
import "../chunk-M3K2HVQD.js";
|
package/dist/stream/index.js
CHANGED
|
@@ -8,6 +8,9 @@ interface TurnIdentityMessage {
|
|
|
8
8
|
}
|
|
9
9
|
/** Retained compatibility shape for callers using unstructured message records. */
|
|
10
10
|
export interface PersistedChatMessageForTurn extends TurnIdentityMessage {
|
|
11
|
+
id: string;
|
|
12
|
+
role: TurnIdentityMessage['role'];
|
|
13
|
+
content: string;
|
|
11
14
|
parts: Array<Record<string, unknown>> | null;
|
|
12
15
|
}
|
|
13
16
|
/** Represent a chat turn with resolved user message insertion and prior message context */
|
package/dist/web-react/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/stream/turn-identity.ts","../src/stream/turn-observation.ts"],"sourcesContent":["import type { JsonRecord } from './stream-normalizer'\n\n/** Minimum read-only shape; typed chat parts need no dictionary index signature. */\ninterface TurnIdentityMessage {\n readonly id: string\n readonly role: 'user' | 'assistant' | 'system' | 'tool'\n readonly content: string\n readonly parts: readonly object[] | null\n}\n\n/** Retained compatibility shape for callers using unstructured message records. */\nexport interface PersistedChatMessageForTurn extends TurnIdentityMessage {\n parts: Array<Record<string, unknown>> | null\n}\n\n/** Represent a chat turn with resolved user message insertion and prior message context */\nexport interface ResolvedChatTurn<Message extends TurnIdentityMessage = PersistedChatMessageForTurn> {\n turnIndex: number\n shouldInsertUserMessage: boolean\n priorMessages: Message[]\n userParts: JsonRecord[]\n /** The id of the user row this turn REUSES (retry dedup), when one was\n * found. Absent on the insert path, where no row exists yet.\n *\n * The reused row is deliberately EXCLUDED from `priorMessages` (it is this\n * turn's own user message, not prior context), so this field is the only\n * way a caller can name it. */\n reusedUserMessageId?: string\n}\n\n/** Normalize and validate a client turn ID string ensuring it meets format and length requirements */\nexport function normalizeClientTurnId(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined\n if (typeof value !== 'string') throw new Error('turnId must be a string')\n const trimmed = value.trim()\n if (!trimmed) throw new Error('turnId must not be blank')\n if (trimmed.length > 160) throw new Error('turnId is too long')\n if (!/^[A-Za-z0-9:_-]+$/.test(trimmed)) {\n throw new Error('turnId contains unsupported characters')\n }\n return trimmed\n}\n\n/** Build an array of text parts with optional turn ID for user input */\nexport function buildUserTextParts(text: string, turnId: string | undefined): JsonRecord[] {\n const part: JsonRecord = { type: 'text', text }\n if (turnId) part.turnId = turnId\n return [part]\n}\n\n/** Resolve whether a message contains any part with the specified turn ID */\nexport function messageHasTurnId(message: Pick<TurnIdentityMessage, 'parts'>, turnId: string): boolean {\n for (const part of message.parts ?? []) {\n if (part && typeof part === 'object' && 'turnId' in part && String(part.turnId ?? '') === turnId) {\n return true\n }\n }\n return false\n}\n\n/** Resolve a chat turn by determining message reuse and constructing user message parts */\nexport function resolveChatTurn<Message extends TurnIdentityMessage>(input: {\n existingMessages: readonly Message[]\n userContent: string\n turnId?: string\n /** True when the thread has a turn still RUNNING in the turn-event buffer\n * (`turnStore.listRunning(threadId)`).\n *\n * Without incremental persistence the trailing row of a thread mid-turn is\n * always the user row, so the content fallback below could assume it. With\n * incremental persistence the assistant row lands seconds into the turn, so\n * a retry of that same turn finds an ASSISTANT row trailing and would\n * insert a duplicate user row.\n *\n * This flag is the discriminator that keeps both cases right, and it needs\n * no new state: an assistant row trailing a turn that is still running is\n * that turn's in-flight draft (walk past it — this is a retry), whereas an\n * assistant row trailing a SETTLED turn is a completed answer (stop — the\n * user genuinely repeated a message and deserves a new turn). */\n hasRunningTurn?: boolean\n}): ResolvedChatTurn<Message> {\n const { existingMessages, userContent, turnId } = input\n const reusableIndex = findReusableUserMessageIndex(\n existingMessages,\n userContent,\n turnId,\n input.hasRunningTurn === true,\n )\n if (reusableIndex >= 0) {\n // Guarded read: `id` is typed `string`, but these rows come from a product\n // store the shell does not validate, so an adapter that omits it must\n // surface as \"no id\" rather than as the string \"undefined\".\n const reusedId = existingMessages[reusableIndex]?.id\n const priorMessages = existingMessages.slice(0, reusableIndex)\n return {\n turnIndex: countUserMessages(priorMessages),\n shouldInsertUserMessage: false,\n priorMessages,\n userParts: buildUserTextParts(userContent, turnId),\n ...(typeof reusedId === 'string' && reusedId ? { reusedUserMessageId: reusedId } : {}),\n }\n }\n\n return {\n turnIndex: countUserMessages(existingMessages),\n shouldInsertUserMessage: true,\n priorMessages: existingMessages.slice(),\n userParts: buildUserTextParts(userContent, turnId),\n }\n}\n\nfunction findReusableUserMessageIndex(\n messages: readonly TurnIdentityMessage[],\n userContent: string,\n turnId: string | undefined,\n hasRunningTurn: boolean,\n): number {\n if (turnId) {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n if (message?.role === 'user' && messageHasTurnId(message, turnId)) return index\n }\n // A caller-supplied id is authoritative. A different id with identical\n // text is a deliberate new turn, while a transport retry reuses the same\n // id and takes the match above. Falling through to content dedup here lets\n // an unrelated abandoned running row swallow an intentional repeat.\n return -1\n }\n\n // Content fallback for a client that sends no turnId. Only the trailing rows\n // of a turn still RUNNING are walked past (they are that turn's incrementally\n // persisted assistant draft); a settled assistant row still ends the scan, so\n // a user who genuinely repeats a message gets a new turn exactly as before.\n let index = messages.length - 1\n if (hasRunningTurn) {\n while (index >= 0 && messages[index]?.role === 'assistant') index -= 1\n }\n const latest = index >= 0 ? messages[index] : undefined\n if (latest?.role === 'user' && latest.content === userContent) return index\n\n return -1\n}\n\nfunction countUserMessages(messages: readonly TurnIdentityMessage[]): number {\n let count = 0\n for (const message of messages) if (message.role === 'user') count++\n return count\n}\n","/** Read-side checkpoints for native chat NDJSON. This never submits or cancels work. */\nexport interface TurnObservation {\n schema: 'turn-observation-v1'\n streamId: string | null\n /** Replay ordinals only. Unsequenced live frames cannot advance this cursor. */\n lastSeq: number\n outcome: 'completed' | 'failed' | null\n replayStatus: string | null\n eventCount: number\n}\n\nexport function parseTurnObservation(value?: unknown): TurnObservation {\n if (value === undefined) return {\n schema: 'turn-observation-v1', streamId: null, lastSeq: 0,\n outcome: null, replayStatus: null, eventCount: 0,\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Invalid turn observation')\n const v = value as Record<string, unknown>\n if (v.schema !== 'turn-observation-v1'\n || !(v.streamId === null || (typeof v.streamId === 'string' && /^[A-Za-z0-9_-]+$/.test(v.streamId)))\n || !Number.isSafeInteger(v.lastSeq) || Number(v.lastSeq) < 0\n || !Number.isSafeInteger(v.eventCount) || Number(v.eventCount) < 0\n || !(v.outcome === null || v.outcome === 'completed' || v.outcome === 'failed')\n || !(v.replayStatus === null || typeof v.replayStatus === 'string')\n || (v.streamId === null && Number(v.lastSeq) > 0)) throw new TypeError('Invalid turn observation')\n return {\n schema: 'turn-observation-v1', streamId: v.streamId as string | null,\n lastSeq: Number(v.lastSeq), outcome: v.outcome as TurnObservation['outcome'],\n replayStatus: v.replayStatus as string | null, eventCount: Number(v.eventCount),\n }\n}\n\nexport interface TurnObservationUpdate {\n checkpoint: TurnObservation\n /** False only for an already-checkpointed replay ordinal. */\n accepted: boolean\n event: Record<string, unknown>\n}\n\n/** Reduce an observed frame. Ordered replay gaps are errors, not silent lost work. */\nexport function observeTurnEvent(previous: TurnObservation, raw: unknown): TurnObservationUpdate {\n const checkpoint = parseTurnObservation(previous)\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new TypeError('Turn frame must be an object')\n const outer = raw as Record<string, unknown>\n const inner = outer.kind === 'event' ? outer.event : outer\n if (!inner || typeof inner !== 'object' || Array.isArray(inner)) throw new TypeError('Invalid turn event envelope')\n const event = inner as Record<string, unknown>\n if (typeof event.type !== 'string' || !event.type) throw new TypeError('Turn frame requires a type')\n\n // Even a duplicate marker must not switch which execution we are observing.\n if (event.type === 'turn') {\n if (typeof event.turnId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(event.turnId)) throw new TypeError('Invalid stream identity')\n if (checkpoint.streamId !== null && checkpoint.streamId !== event.turnId) throw new Error('Replay stream identity changed')\n checkpoint.streamId = event.turnId\n }\n const seq = outer.seq\n if (seq !== undefined && seq !== -1) {\n if (!Number.isSafeInteger(seq) || Number(seq) < 1) throw new TypeError('Invalid replay ordinal')\n if (checkpoint.streamId === null) throw new Error('Replay ordinal arrived before stream identity')\n if (Number(seq) <= checkpoint.lastSeq) return { checkpoint, accepted: false, event }\n if (Number(seq) !== checkpoint.lastSeq + 1) throw new Error('Replay has a gap; retain the checkpoint and inspect durable history')\n checkpoint.lastSeq = Number(seq)\n } else if (seq === -1 && event.type !== 'turn_status') {\n throw new TypeError('Only a turn-status sentinel may have ordinal -1')\n }\n\n if (event.type === 'error' || event.type === 'session.run.failed') checkpoint.outcome = 'failed'\n if (event.type === 'session.run.completed' && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n if (event.type === 'turn_status') {\n if (typeof event.status !== 'string') throw new TypeError('Turn status requires a value')\n checkpoint.replayStatus = event.status\n if (['error', 'failed', 'aborted', 'cancelled'].includes(event.status)) checkpoint.outcome = 'failed'\n if (['complete', 'completed'].includes(event.status) && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n }\n checkpoint.eventCount += 1\n return { checkpoint, accepted: true, event }\n}\n\nexport interface ConsumeTurnStreamOptions {\n checkpoint?: TurnObservation\n /** Commit evidence and its checkpoint durably before acknowledging this frame. */\n commit(update: TurnObservationUpdate): Promise<void>\n /** Bound untrusted frame memory, not total run duration or total transcript size. */\n maxFrameBytes?: number\n}\n\n/**\n * Consume one viewing connection. EOF without a terminal event stays incomplete.\n * A disconnect/abort propagates; the last committed checkpoint remains resumable.\n * The caller owns network observation windows separately from execution deadlines.\n */\nexport async function consumeTurnStream(\n body: AsyncIterable<Uint8Array>,\n options: ConsumeTurnStreamOptions,\n): Promise<TurnObservation> {\n const maxFrameBytes = options.maxFrameBytes ?? 4 * 1024 * 1024\n if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes < 1) throw new RangeError('Frame byte limit must be positive')\n let state = parseTurnObservation(options.checkpoint)\n const decoder = new TextDecoder('utf-8', { fatal: true })\n let pending = ''\n let frameBytes = 0\n async function accept(line: string): Promise<void> {\n if (!line.trim()) return\n const update = observeTurnEvent(state, JSON.parse(line))\n if (update.accepted) await options.commit(update)\n state = update.checkpoint\n }\n for await (const chunk of body) {\n // Count bytes before decoding: a malicious unterminated frame cannot grow\n // without bound, and splitting UTF-8 characters across chunks stays valid.\n let start = 0\n for (let end = 0; end < chunk.length; end += 1) {\n if (chunk[end] !== 10) continue\n frameBytes += end - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start, end + 1), { stream: true })\n await accept(pending)\n pending = ''; frameBytes = 0; start = end + 1\n }\n frameBytes += chunk.length - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start), { stream: true })\n }\n pending += decoder.decode()\n await accept(pending)\n return state\n}\n"],"mappings":";AA+BO,SAAS,sBAAsB,OAAoC;AACxE,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,OAA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