@athenaintel/react 0.38.1 → 0.40.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 +23 -3
- package/dist/agent-runtime/src/errors.cjs +8 -0
- package/dist/agent-runtime/src/errors.cjs.map +1 -1
- package/dist/agent-runtime/src/errors.js +8 -0
- package/dist/agent-runtime/src/errors.js.map +1 -1
- package/dist/agent-runtime/src/messages.cjs +76 -16
- package/dist/agent-runtime/src/messages.cjs.map +1 -1
- package/dist/agent-runtime/src/messages.js +76 -16
- package/dist/agent-runtime/src/messages.js.map +1 -1
- package/dist/agent-runtime/src/tool-metadata.cjs +15 -0
- package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
- package/dist/agent-runtime/src/tool-metadata.js +15 -0
- package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
- package/dist/assets/use-asset-content.cjs +127 -0
- package/dist/assets/use-asset-content.cjs.map +1 -0
- package/dist/assets/use-asset-content.d.ts +60 -0
- package/dist/assets/use-asset-content.js +127 -0
- package/dist/assets/use-asset-content.js.map +1 -0
- package/dist/chat/super-grouping/CollapsibleGroup.cjs +16 -8
- package/dist/chat/super-grouping/CollapsibleGroup.cjs.map +1 -1
- package/dist/chat/super-grouping/CollapsibleGroup.d.ts +26 -1
- package/dist/chat/super-grouping/CollapsibleGroup.js +16 -8
- package/dist/chat/super-grouping/CollapsibleGroup.js.map +1 -1
- package/dist/chat/super-grouping/GroupedMessageParts.cjs +59 -0
- package/dist/chat/super-grouping/GroupedMessageParts.cjs.map +1 -0
- package/dist/chat/super-grouping/GroupedMessageParts.d.ts +25 -0
- package/dist/chat/super-grouping/GroupedMessageParts.js +59 -0
- package/dist/chat/super-grouping/GroupedMessageParts.js.map +1 -0
- package/dist/chat/super-grouping/SuperGroupingCard.cjs +9 -5
- package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
- package/dist/chat/super-grouping/SuperGroupingCard.d.ts +2 -1
- package/dist/chat/super-grouping/SuperGroupingCard.js +13 -9
- package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
- package/dist/chat/super-grouping/SuperGroupingTranscript.cjs +10 -6
- package/dist/chat/super-grouping/SuperGroupingTranscript.cjs.map +1 -1
- package/dist/chat/super-grouping/SuperGroupingTranscript.js +14 -10
- package/dist/chat/super-grouping/SuperGroupingTranscript.js.map +1 -1
- package/dist/chat/super-grouping/grouped-part-keys.cjs +104 -0
- package/dist/chat/super-grouping/grouped-part-keys.cjs.map +1 -0
- package/dist/chat/super-grouping/grouped-part-keys.d.ts +37 -0
- package/dist/chat/super-grouping/grouped-part-keys.js +104 -0
- package/dist/chat/super-grouping/grouped-part-keys.js.map +1 -0
- package/dist/chat/super-grouping/index.cjs +2 -0
- package/dist/chat/super-grouping/index.cjs.map +1 -1
- package/dist/chat/super-grouping/index.d.ts +3 -1
- package/dist/chat/super-grouping/index.js +2 -0
- package/dist/chat/super-grouping/index.js.map +1 -1
- package/dist/chat-ui/composer/tiptap-composer.cjs +25 -19
- package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
- package/dist/chat-ui/composer/tiptap-composer.d.ts +5 -0
- package/dist/chat-ui/composer/tiptap-composer.js +26 -20
- package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.cjs +13 -0
- package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.js +13 -0
- package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
- package/dist/composer/clipboard.cjs +16 -0
- package/dist/composer/clipboard.cjs.map +1 -1
- package/dist/composer/clipboard.d.ts +9 -0
- package/dist/composer/clipboard.js +17 -1
- package/dist/composer/clipboard.js.map +1 -1
- package/dist/diagnostics/errors.cjs +11 -0
- package/dist/diagnostics/errors.cjs.map +1 -1
- package/dist/diagnostics/errors.d.ts +11 -0
- package/dist/diagnostics/errors.js +11 -0
- package/dist/diagnostics/errors.js.map +1 -1
- package/dist/index.cjs +37 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +14 -1
- package/dist/index.js +37 -0
- package/dist/index.js.map +1 -1
- package/dist/provider/AthenaProvider.cjs +5 -2
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.js +5 -2
- package/dist/provider/AthenaProvider.js.map +1 -1
- package/dist/provider/statewire-history-context.cjs +48 -0
- package/dist/provider/statewire-history-context.cjs.map +1 -0
- package/dist/provider/statewire-history-context.d.ts +36 -0
- package/dist/provider/statewire-history-context.js +48 -0
- package/dist/provider/statewire-history-context.js.map +1 -0
- package/dist/react/package.json.cjs +1 -1
- package/dist/react/package.json.js +1 -1
- package/dist/runtime/statewire-lifecycle.cjs +8 -0
- package/dist/runtime/statewire-lifecycle.cjs.map +1 -1
- package/dist/runtime/statewire-lifecycle.js +9 -1
- package/dist/runtime/statewire-lifecycle.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/tools/index.cjs +7 -0
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +7 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/inline-tools.cjs +10 -0
- package/dist/tools/inline-tools.cjs.map +1 -0
- package/dist/tools/inline-tools.d.ts +2 -0
- package/dist/tools/inline-tools.js +10 -0
- package/dist/tools/inline-tools.js.map +1 -0
- package/dist/tools/test-recording-report.cjs +175 -0
- package/dist/tools/test-recording-report.cjs.map +1 -0
- package/dist/tools/test-recording-report.d.ts +82 -0
- package/dist/tools/test-recording-report.js +175 -0
- package/dist/tools/test-recording-report.js.map +1 -0
- package/dist/tools/test-recording-tool-uis.cjs +498 -0
- package/dist/tools/test-recording-tool-uis.cjs.map +1 -0
- package/dist/tools/test-recording-tool-uis.d.ts +32 -0
- package/dist/tools/test-recording-tool-uis.js +498 -0
- package/dist/tools/test-recording-tool-uis.js.map +1 -0
- package/dist/tools/tool-summary.cjs +49 -1
- package/dist/tools/tool-summary.cjs.map +1 -1
- package/dist/tools/tool-summary.js +49 -1
- package/dist/tools/tool-summary.js.map +1 -1
- package/dist/tools/tool-uis.cjs +6 -1
- package/dist/tools/tool-uis.cjs.map +1 -1
- package/dist/tools/tool-uis.js +6 -1
- package/dist/tools/tool-uis.js.map +1 -1
- package/dist/workbench/ComputerLiveDesktop.cjs +287 -0
- package/dist/workbench/ComputerLiveDesktop.cjs.map +1 -0
- package/dist/workbench/ComputerLiveDesktop.d.ts +27 -0
- package/dist/workbench/ComputerLiveDesktop.js +287 -0
- package/dist/workbench/ComputerLiveDesktop.js.map +1 -0
- package/dist/workbench/SessionWorkbench.cjs +2 -2
- package/dist/workbench/SessionWorkbench.cjs.map +1 -1
- package/dist/workbench/SessionWorkbench.js +2 -2
- package/dist/workbench/SessionWorkbench.js.map +1 -1
- package/dist/workbench/live-desktop-api.cjs +139 -0
- package/dist/workbench/live-desktop-api.cjs.map +1 -0
- package/dist/workbench/live-desktop-api.d.ts +69 -0
- package/dist/workbench/live-desktop-api.js +139 -0
- package/dist/workbench/live-desktop-api.js.map +1 -0
- package/dist/workbench/session-workbench-context.cjs.map +1 -1
- package/dist/workbench/session-workbench-context.d.ts +7 -0
- package/dist/workbench/session-workbench-context.js.map +1 -1
- package/dist/workbench/session-workbench-panes.cjs +38 -2
- package/dist/workbench/session-workbench-panes.cjs.map +1 -1
- package/dist/workbench/session-workbench-panes.js +38 -2
- package/dist/workbench/session-workbench-panes.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -634,8 +634,8 @@ Built-in panes and what each reads:
|
|
|
634
634
|
| Pane | id | Source |
|
|
635
635
|
|---|---|---|
|
|
636
636
|
| Tasks | `tasks` | The thread state's `todos` channel (the deepagents plan), else the newest `write_todos` call in the loaded transcript — "N/M done" and numbered steps with their status |
|
|
637
|
-
| Shell | `shell` | Every `execute` call in the loaded transcript, newest first: first line of the command, the machine it ran on (`sandbox_asset_id` named through the workspace's computers, else "Session sandbox"), the exit status parsed from `[Command succeeded/failed with exit code N]`, the time; searchable; a row expands to its output (first 4,000 characters) |
|
|
638
|
-
| Computer | `computer` | `GET /api/conversations/threads/{id}/workspace`: the session computer, else the most recent computer — its state (`GET /api/sandbox/computer/{id}/status`, a read that never wakes it, re-read every 30 s while shown), "Open in Athena", and "Copy SSH command" (`GET /api/v0/computer/{id}/ssh-access`, offered only when the viewer may edit the computer); the other computers it used below |
|
|
637
|
+
| Shell | `shell` | Every `execute` call in the loaded transcript, newest first: first line of the command, the machine it ran on (`sandbox_asset_id` named through the workspace's computers, else "Session sandbox"), the exit status parsed from `[Command succeeded/failed with exit code N]`, the time; searchable; a row expands to its output (first 4,000 characters). While the thread holds history the chat has not loaded (the chat's history edge reports it, `useStatewireHistory`), the count reads "so far" and **Load earlier commands** loads the next page, the same one scrolling up loads |
|
|
638
|
+
| Computer | `computer` | `GET /api/conversations/threads/{id}/workspace`: the session computer, else the most recent computer — **its screen, live** (`ComputerLiveDesktop`, below), its state (`GET /api/sandbox/computer/{id}/status`, a read that never wakes it, re-read every 30 s while shown), "Open in Athena", and "Copy SSH command" (`GET /api/v0/computer/{id}/ssh-access`, offered only when the viewer may edit the computer); the other computers it used below |
|
|
639
639
|
| Pull requests | `pull-requests` | The thread list's live pull-request state for the session (`enableThreadList`): number, title, state, checks and review decision, each a link to GitHub |
|
|
640
640
|
| Attachments | `attachments` | The workspace's assets — what the session created or edited — with type, last update, "Open in Athena", and a click that opens it in the asset panel when an `AthenaLayout` hosts one |
|
|
641
641
|
|
|
@@ -685,6 +685,18 @@ const MATTER_PANE: SessionWorkbenchPane = {
|
|
|
685
685
|
/>
|
|
686
686
|
```
|
|
687
687
|
|
|
688
|
+
**The computer's screen, live.** `ComputerLiveDesktop` (in the Computer pane,
|
|
689
|
+
or mounted on its own with `assetId`) watches a running computer's display as
|
|
690
|
+
soon as it mounts — `POST /api/sandbox/computer/{id}/live-desktop/session`
|
|
691
|
+
with this page as `embed_origin` — and frames agora's Selkies viewer; **Take
|
|
692
|
+
control** reopens it in control mode, and closing the pane ends the stream (an
|
|
693
|
+
open view keeps the computer awake, up to agora's 30-minute cap). It needs EDIT
|
|
694
|
+
on the computer, in its own workspace, and an app the computer serves on Athena
|
|
695
|
+
(a Marathon host or a verified custom domain in that workspace): agora lets
|
|
696
|
+
only that origin and Olympus frame the viewer, and tells the app only how the
|
|
697
|
+
stream fares. A computer without a display (one not made from the Browser
|
|
698
|
+
template) says so, and a stopped one is never woken.
|
|
699
|
+
|
|
688
700
|
The built-in pane bodies (`SessionTasksPane`, `SessionShellPane`, …), their
|
|
689
701
|
registry entries (`SESSION_WORKBENCH_TASKS_PANE`, …), the data hooks
|
|
690
702
|
(`useAthenaSessionWorkspace`, `useAthenaComputerStatus`,
|
|
@@ -777,6 +789,14 @@ Both use the same bearer / API key as session creation. The full recipe
|
|
|
777
789
|
template skill `voice-session-guide.md`. `createAthenaVoiceSession` is also
|
|
778
790
|
exported if you hold the bridge state yourself.
|
|
779
791
|
|
|
792
|
+
## What's new in 0.40.0
|
|
793
|
+
|
|
794
|
+
**`AthenaChat` shows an agent's UI test recording.** When an agent with the UI Testing toolkit checks a change in its computer's browser, `test_recording_stop` now renders a report card: the recording's title, "N passed · M failed" (with "· K untested" when a test was never checked), each test with its ✓ / ✗ assertions and what the agent saw (a failed assertion is tinted red, a test with no assertion reads "Not checked"), the summary, and the edited video. Every test's start time is a chapter: click it and the video plays from there (an assertion's time works the same way). A **Watch in Athena** link opens the asset in Athena. The card stays in the conversation instead of folding into the turn's collapsed steps. `test_recording_start` and `test_recording_mark` each render one compact row ("Recording started", "Test", "Pass", "Fail", "Note" with the time in the recording), and their collapsed steps read "Started recording "…"", "Started test: It should …", "Passed: …", "Failed: …".
|
|
795
|
+
|
|
796
|
+
**The video plays with the signed-in user's own credential.** It is read only when the person presses play or picks a chapter, from `GET /api/asset/content/{asset_id}` with the provider's `Authorization` / `X-API-KEY` header. Agora checks the asset's permission on that read, and the bytes play from an object URL that only this page holds. No presigned storage URL or embed link is minted, so there is no link that works without the credential. Each card reads its own copy and drops it when it unmounts, so a card mounted later (perhaps for another account behind your `getToken`) reads through the permission check again instead of reusing bytes. A failed read says why ("You don't have access to this recording", "The recording could not be loaded") and offers **Try again** and the Athena link. Outside an `AthenaProvider` the card shows the report and the link, without a player. The same read is exported for your own UI: `useAthenaAssetContent({ assetId, enabled })` (TanStack Query, a `Blob`, one copy per mounted hook), `fetchAthenaAssetContent`, and `useObjectUrl(blob)`. A failed read is an `AthenaSdkError` with the new code `asset_content_failed` (a network failure, a credential that cannot be resolved, a download cut off, a 404), or `auth_rejected` for a 401 / 403.
|
|
797
|
+
|
|
798
|
+
New exports: `TestRecordingStopToolUI`, `TestRecordingStartToolUI`, `TestRecordingMarkToolUI`, `TestRecordingReportCard`, `parseTestRecordingStopResult` and the result types, and `isSdkInlineTool` (the default `isInlineTool` of `SuperGroupingTranscript` and `SuperGroupingCard`: the shared registry's inline tools plus `test_recording_stop`). Nothing to change in your app; override any of the three with `toolUIs` as before.
|
|
799
|
+
|
|
780
800
|
## What's new in 0.38.1
|
|
781
801
|
|
|
782
802
|
**`AthenaChat`'s composer stays put while the transcript scrolls.** The composer is a sticky footer inside the transcript's scroll viewport, so whatever moved the viewport's content moved the composer with it. The viewport is now `overflow-x-hidden` (was `overflow-x-auto`): anything wider than the message column made the whole transcript, composer included, scroll sideways under a trackpad. Wide tables and code blocks scroll inside their own boxes, as before. It is also `overscroll-y-none`: a fling that reaches the top or bottom no longer chains into the page or starts the macOS elastic bounce, either of which carried the composer off its place before it settled. Olympus's own chat thread has the same two guards. Nothing to change in your app.
|
|
@@ -1918,7 +1938,7 @@ Your own portals can read the same context: `usePortalContainer()` returns the p
|
|
|
1918
1938
|
|
|
1919
1939
|
The transcript is `SuperGroupingTranscript` from `@athenaintel/react/super-grouping`; it takes the same renderer and host slots as `SuperGroupingCard` (which keeps the single-card layout for hosts that mount it). `splitTurnSegments`, `readTurnTiming` and `formatWorkDuration` are exported for hosts that lay a turn out themselves.
|
|
1920
1940
|
|
|
1921
|
-
Every step row and every thread tool card reads one summary registry, `summarizeToolCall({ toolName, args, result, status })` → `{ label, detail?, meta?, code? }` (also on `@athenaintel/react/tools`). It has rules for the deep agent's core tools (`execute`, the workspace file tools, `search_assets`, the computer and GitHub tools, web search and browse, `read_asset`, `write_todos`, `task`); other tools read the shared display registry, and a tool neither knows falls back to a host catalog name (`resolveToolDisplayName`), else its sentence-cased name. A call that targets a machine or document by id (`sandbox_asset_id`, `computer_asset_id`) is named by its title when an earlier result in the turn carried one (`collectAssetTitles`); nothing is fetched.
|
|
1941
|
+
Every step row and every thread tool card reads one summary registry, `summarizeToolCall({ toolName, args, result, status })` → `{ label, detail?, meta?, code? }` (also on `@athenaintel/react/tools`). It has rules for the deep agent's core tools (`execute`, the workspace file tools, `search_assets`, the computer and GitHub tools, web search and browse, `read_asset`, `write_todos`, `task`, and the UI Testing toolkit's `test_recording_start` / `_mark` / `_stop`); other tools read the shared display registry, and a tool neither knows falls back to a host catalog name (`resolveToolDisplayName`), else its sentence-cased name. A call that targets a machine or document by id (`sandbox_asset_id`, `computer_asset_id`) is named by its title when an earlier result in the turn carried one (`collectAssetTitles`); nothing is fetched.
|
|
1922
1942
|
|
|
1923
1943
|
Every tool call it renders — the generic `ToolFallback`, the built-in tool UIs, nested sub-calls — shares one row anatomy: a status glyph (spinner / check / x / alert), the verb and its target on one line, a running call's elapsed seconds after three, a failed call tinted red, and a disclosure for the arguments and result.
|
|
1924
1944
|
|
|
@@ -49,6 +49,11 @@ function readRetryableCommandRejection(error) {
|
|
|
49
49
|
const payload = statewireRejectionPayload(error);
|
|
50
50
|
return payload === null ? null : readRetryableDetail(payload.detail);
|
|
51
51
|
}
|
|
52
|
+
const CONVERSATION_ARCHIVED = "conversation_archived";
|
|
53
|
+
const CONVERSATION_ARCHIVED_MESSAGE = "This conversation is archived. Restore it to continue.";
|
|
54
|
+
function isConversationArchivedRejection(error) {
|
|
55
|
+
return statewireRejectionCode(error) === CONVERSATION_ARCHIVED;
|
|
56
|
+
}
|
|
52
57
|
function isLegacyThreadReadOnlyRejection(error) {
|
|
53
58
|
const payload = statewireRejectionPayload(error);
|
|
54
59
|
if ((payload == null ? void 0 : payload.status) !== 409) return false;
|
|
@@ -122,6 +127,9 @@ function unknownConnectionStatus(connection) {
|
|
|
122
127
|
);
|
|
123
128
|
}
|
|
124
129
|
exports.COLLAB_AGENT_CHANNEL_SESSION_MISMATCH = COLLAB_AGENT_CHANNEL_SESSION_MISMATCH;
|
|
130
|
+
exports.CONVERSATION_ARCHIVED = CONVERSATION_ARCHIVED;
|
|
131
|
+
exports.CONVERSATION_ARCHIVED_MESSAGE = CONVERSATION_ARCHIVED_MESSAGE;
|
|
132
|
+
exports.isConversationArchivedRejection = isConversationArchivedRejection;
|
|
125
133
|
exports.isLegacyThreadReadOnlyRejection = isLegacyThreadReadOnlyRejection;
|
|
126
134
|
exports.isStatewireChannelTeardown = isStatewireChannelTeardown;
|
|
127
135
|
exports.isStatewireExpiredVerdict = isStatewireExpiredVerdict;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","sources":["../../../../agent-runtime/src/errors.ts"],"sourcesContent":["import type { StatewireClient } from 'statewire';\nimport type { DeepAgentConnectionState } from './types';\n\n/** Structured payload attached to a server-rejected Statewire command. */\nexport interface StatewireRejectionPayload {\n status: number;\n detail: unknown;\n}\n\n/** Return a rejected command's structured `{ status, detail }` payload. */\nexport function statewireRejectionPayload(error: unknown): StatewireRejectionPayload | null {\n const failure = (error as { failure?: { fate?: unknown; payload?: unknown } } | null)?.failure;\n if (failure?.fate !== 'rejected') return null;\n\n const payload = failure.payload as { status?: unknown; detail?: unknown } | undefined;\n if (typeof payload?.status !== 'number') return null;\n return { status: payload.status, detail: payload.detail };\n}\n\n/**\n * The server's human-readable reason for a rejected command — `detail.message`\n * (or a plain-string `detail`) — else `null`. Hosts surface it as send\n * feedback so the user sees the actionable cause instead of the generic\n * client-side `command rejected (<status>)`.\n */\nexport function statewireRejectionDetailMessage(error: unknown): string | null {\n const detail = statewireRejectionPayload(error)?.detail;\n if (typeof detail === 'string') return detail.length > 0 ? detail : null;\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const message = (detail as { message?: unknown }).message;\n return typeof message === 'string' && message.length > 0 ? message : null;\n}\n\n/**\n * A structured, retryable refusal the host recorded as the run error\n * (`runs.error`): the dispatch never started — the pod or instance was\n * closing (`pod_draining`) — and the entries stayed in their lanes for the\n * thread's next placement. Distinct from a rejected COMMAND\n * ({@link statewireRejectionPayload}): this is the shape harness-sdk writes\n * when the run executor raises the rejection, so it lives on the replicated\n * run entry, not on a command settle.\n */\nexport interface RetryableRunRefusal {\n /** The structured `detail.code` (`pod_draining`). */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n}\n\n/** The `{ code, message, retryable: true }` detail of a structured refusal, or `null`. */\nfunction readRetryableDetail(detail: unknown): { code: string; message: string | null } | null {\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const { code, message, retryable } = detail as {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n };\n if (retryable !== true || typeof code !== 'string' || code.length === 0) return null;\n return { code, message: typeof message === 'string' && message.length > 0 ? message : null };\n}\n\nexport function readRetryableRunRefusal(error: unknown): RetryableRunRefusal | null {\n if (error === null || typeof error !== 'object' || Array.isArray(error)) return null;\n return readRetryableDetail((error as { detail?: unknown }).detail);\n}\n\n/**\n * The `detail.code` agora answers when a send names another channel of the\n * collab agent a session started on (`collab_agent_bridge.py`): a session\n * keeps its channel — the SDK app's Agent / Ask mode — for its lifetime, and\n * the way to the other mode is a new session. Wire-frozen.\n */\nexport const COLLAB_AGENT_CHANNEL_SESSION_MISMATCH = 'collab_agent_channel_session_mismatch';\n\n/**\n * A structured refusal the host recorded as the run error when the run could\n * not START: the run executor raised the gate's `{status, detail: {code,\n * message}}` envelope (agora's `_status_reject`) before it accepted the\n * dispatched input, so the message went back to its lane and the thread rests\n * `error` with it still queued. Unlike a retryable refusal\n * ({@link readRetryableRunRefusal}) nothing will dispatch it later: resending\n * the same input is refused the same way, so the server's message is the only\n * explanation the person gets.\n */\nexport interface RunStartRefusal {\n /** The structured `detail.code` (`collab_agent_channel_session_mismatch`, …). */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n /** The HTTP-style status the gate raised with, when recorded. */\n status: number | null;\n}\n\n/**\n * The non-retryable structured refusal off a replicated run error\n * (`runs.error`), or `null` — for a run that failed while it was running (a\n * plain `{message}`), a retryable refusal, or no error at all.\n */\nexport function readRunStartRefusal(error: unknown): RunStartRefusal | null {\n if (error === null || typeof error !== 'object' || Array.isArray(error)) return null;\n const { detail, status } = error as { detail?: unknown; status?: unknown };\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const { code, message, retryable } = detail as {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n };\n if (retryable === true || typeof code !== 'string' || code.length === 0) return null;\n return {\n code,\n message: typeof message === 'string' && message.length > 0 ? message : null,\n status: typeof status === 'number' ? status : null,\n };\n}\n\n/** The structured `detail.code` of a rejected command, or `null`. */\nexport function statewireRejectionCode(error: unknown): string | null {\n const detail = statewireRejectionPayload(error)?.detail;\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const code = (detail as { code?: unknown }).code;\n return typeof code === 'string' && code.length > 0 ? code : null;\n}\n\n/**\n * A structured, retryable refusal of a COMMAND, read off its rejection\n * ({@link statewireRejectionPayload}): the host's `_structured_reject(...,\n * retryable=True)` envelope — `command_auth_context_expired` when a pod\n * replacement dropped the socket-scoped auth a replayed command needed,\n * `pod_draining` when the host was closing. The command never ran, and the\n * host itself says a resend after the reconnect will; `detail.code` is the\n * wire-frozen contract clients classify on. Same shape as\n * {@link readRetryableRunRefusal}, which reads it off a replicated run entry.\n */\nexport interface RetryableCommandRejection {\n /** The structured `detail.code`. */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n}\n\nexport function readRetryableCommandRejection(error: unknown): RetryableCommandRejection | null {\n const payload = statewireRejectionPayload(error);\n return payload === null ? null : readRetryableDetail(payload.detail);\n}\n\n/** The host's `detail.code` for a command replayed onto a pod that could not restore its auth context. */\nexport const STATEWIRE_COMMAND_AUTH_CONTEXT_EXPIRED = 'command_auth_context_expired';\n\n/**\n * Whether a rejected command hit the host's fail-closed auth recovery: the\n * command was replayed onto a replacement pod that could not restore the\n * attach's auth context, so it was refused unrun (503, retryable). The\n * reconnect already under way restores the context; a single resend after it\n * is the recovery, not a failure to report.\n */\nexport function isStatewireCommandAuthContextExpired(error: unknown): boolean {\n const payload = statewireRejectionPayload(error);\n return (\n payload?.status === 503 &&\n readRetryableDetail(payload.detail)?.code === STATEWIRE_COMMAND_AUTH_CONTEXT_EXPIRED\n );\n}\n\n/**\n * Whether a rejected command hit the legacy-thread dispatch fence: the\n * structured 409 the server answers when an out-of-band run is writing a\n * pre-cutover thread (or its adoption failed). A per-send failure — the\n * snapshot never carries a standing read-only flag.\n */\nexport function isLegacyThreadReadOnlyRejection(error: unknown): boolean {\n const payload = statewireRejectionPayload(error);\n if (payload?.status !== 409) return false;\n\n const detail = payload.detail as { code?: unknown } | undefined;\n return detail?.code === 'legacy_thread_read_only';\n}\n\n/**\n * Whether a rejected command was refused because its rewind anchor no longer\n * matches the host's parent for the edited message (`wrong-anchor`).\n *\n * A retry/edit resubmit is dispatched optimistically, so this rejection lands\n * after the UI already cleared its edit affordances: the turn simply never\n * re-runs. Callers use this to tell the user the resubmit was dropped instead\n * of leaving a console-only failure.\n */\nexport function isStatewireRewindAnchorRejection(error: unknown): boolean {\n const failure = (error as { failure?: { fate?: unknown; payload?: unknown } } | null | undefined)\n ?.failure;\n if (failure?.fate !== 'rejected') return false;\n return (failure.payload as { reason?: unknown } | undefined)?.reason === 'wrong-anchor';\n}\n\n/**\n * Whether a statewire send failure is the host's `expired` verdict\n * (`result-unavailable`): the command's seq was at or below the host's\n * admitted watermark and no retained result was left for it. Either the\n * command ran and settled but the client re-asked for the answer (a resend\n * after the stream came back) only after the host had let the retained result\n * go, or the seq was already admitted and the command was absorbed as a\n * duplicate without ever running — a client whose shared session record fell\n * behind the watermark stays there until a reconnect re-syncs it. The library\n * never reruns the command on replay, so for an idempotent read the answer is\n * simply gone — asking again is the correct reaction, not reporting a failure;\n * a write cannot assume it was applied.\n */\nexport function isStatewireExpiredVerdict(error: unknown): boolean {\n const failure = (error as { failure?: { fate?: unknown; cause?: unknown } | null | undefined })\n ?.failure;\n return failure?.fate === 'expired' && failure.cause === 'server';\n}\n\n/**\n * Whether a statewire send failure is a local channel death rather than a\n * command error.\n *\n * The library's contract for `SendFailure.cause`: `\"server\"` is the server's\n * own answer; every other cause is \"a channel death the client settled\n * locally\" — `unmount`, `stream-gone`, and `session-lost`. A thread switch\n * settles every in-flight command that way, so logging these at error level\n * reports two failures for an ordinary switch and buries the ones that mean\n * something.\n *\n * Channel health is already surfaced where it belongs: the connection\n * indicator renders the connection state. This\n * predicate only decides the log level.\n */\nexport function isStatewireChannelTeardown(error: unknown): boolean {\n const cause = (error as { failure?: { cause?: unknown } } | null | undefined)?.failure?.cause;\n return typeof cause === 'string' && cause !== 'server';\n}\n\n/**\n * The low-cardinality reason a statewire send settled as transport weather\n * rather than a defect, or `null` when the failure is a real error.\n *\n * Three families qualify: a channel death the client settled locally\n * ({@link isStatewireChannelTeardown} — the cause: `unmount`, `stream-gone`,\n * `session-lost`), the host's `expired` verdict\n * ({@link isStatewireExpiredVerdict} — the answer outlived the host's\n * retention before the post-reconnect resend collected it), and a retryable\n * structured rejection ({@link readRetryableCommandRejection} — its code: the\n * host asked for a resend). In every case the sender's own retry or poll is\n * the recovery and the connection indicator already shows the channel, so\n * error reporting counts the outcome instead of paging on it. Handler\n * failures, crashes, and non-retryable rejections stay `null`: those are\n * defects to page on.\n */\nexport function statewireTransportOutcome(error: unknown): string | null {\n const cause = (error as { failure?: { cause?: unknown } } | null | undefined)?.failure?.cause;\n if (typeof cause === 'string' && cause !== 'server') return cause;\n if (isStatewireExpiredVerdict(error)) return 'expired';\n return readRetryableCommandRejection(error)?.code ?? null;\n}\n\nconst sanitizeConnectionMessage = (message: string): string | undefined => {\n const printable = Array.from(message, (character) => {\n const code = character.charCodeAt(0);\n return code < 32 || code === 127 ? ' ' : character;\n })\n .join('')\n .replace(/\\s+/g, ' ')\n .trim();\n return printable ? printable.slice(0, 200) : undefined;\n};\n\n/** Preserve the Statewire lifecycle and sanitize host detail for display. */\nexport function projectDeepAgentConnection(\n connection: StatewireClient.ConnectionState\n): DeepAgentConnectionState {\n const message =\n 'message' in connection && typeof connection.message === 'string'\n ? sanitizeConnectionMessage(connection.message)\n : undefined;\n switch (connection.status) {\n case 'standby':\n return {\n status: connection.status,\n reason: connection.reason,\n degraded: connection.degraded,\n ...(message !== undefined && { message }),\n };\n case 'connecting':\n case 'connected':\n return { status: connection.status, degraded: connection.degraded };\n case 'retrying':\n return {\n status: connection.status,\n degraded: connection.degraded,\n attempt: connection.attempt,\n ...(connection.cause !== undefined && { cause: connection.cause }),\n ...(connection.code !== undefined && { code: connection.code }),\n ...(connection.nextRetryAt !== undefined && { nextRetryAt: connection.nextRetryAt }),\n ...(connection.lastError !== undefined && { lastError: connection.lastError }),\n ...(message !== undefined && { message }),\n };\n case 'stopped':\n return {\n status: connection.status,\n degraded: connection.degraded,\n reason: connection.reason,\n ...(connection.payload !== undefined && { payload: connection.payload }),\n ...(message !== undefined && { message }),\n };\n default:\n return unknownConnectionStatus(connection);\n }\n}\n\n/** Compile-time exhaustiveness: reachable only when the library grows a status this build does not project. */\nfunction unknownConnectionStatus(connection: never): never {\n throw new Error(\n `statewire: unknown connection status ${JSON.stringify(\n (connection as { status?: unknown }).status\n )}`\n );\n}\n"],"names":[],"mappings":";;AAUO,SAAS,0BAA0B,OAAkD;AAC1F,QAAM,UAAW,+BAAsE;AACvF,OAAI,mCAAS,UAAS,WAAY,QAAO;AAEzC,QAAM,UAAU,QAAQ;AACxB,MAAI,QA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wC,KAAK;AAAA,MAC1C,WAAoC;AAAA,IAAA,CACtC;AAAA,EAAA;AAEL;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"errors.cjs","sources":["../../../../agent-runtime/src/errors.ts"],"sourcesContent":["import type { StatewireClient } from 'statewire';\nimport type { DeepAgentConnectionState } from './types';\n\n/** Structured payload attached to a server-rejected Statewire command. */\nexport interface StatewireRejectionPayload {\n status: number;\n detail: unknown;\n}\n\n/** Return a rejected command's structured `{ status, detail }` payload. */\nexport function statewireRejectionPayload(error: unknown): StatewireRejectionPayload | null {\n const failure = (error as { failure?: { fate?: unknown; payload?: unknown } } | null)?.failure;\n if (failure?.fate !== 'rejected') return null;\n\n const payload = failure.payload as { status?: unknown; detail?: unknown } | undefined;\n if (typeof payload?.status !== 'number') return null;\n return { status: payload.status, detail: payload.detail };\n}\n\n/**\n * The server's human-readable reason for a rejected command — `detail.message`\n * (or a plain-string `detail`) — else `null`. Hosts surface it as send\n * feedback so the user sees the actionable cause instead of the generic\n * client-side `command rejected (<status>)`.\n */\nexport function statewireRejectionDetailMessage(error: unknown): string | null {\n const detail = statewireRejectionPayload(error)?.detail;\n if (typeof detail === 'string') return detail.length > 0 ? detail : null;\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const message = (detail as { message?: unknown }).message;\n return typeof message === 'string' && message.length > 0 ? message : null;\n}\n\n/**\n * A structured, retryable refusal the host recorded as the run error\n * (`runs.error`): the dispatch never started — the pod or instance was\n * closing (`pod_draining`) — and the entries stayed in their lanes for the\n * thread's next placement. Distinct from a rejected COMMAND\n * ({@link statewireRejectionPayload}): this is the shape harness-sdk writes\n * when the run executor raises the rejection, so it lives on the replicated\n * run entry, not on a command settle.\n */\nexport interface RetryableRunRefusal {\n /** The structured `detail.code` (`pod_draining`). */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n}\n\n/** The `{ code, message, retryable: true }` detail of a structured refusal, or `null`. */\nfunction readRetryableDetail(detail: unknown): { code: string; message: string | null } | null {\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const { code, message, retryable } = detail as {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n };\n if (retryable !== true || typeof code !== 'string' || code.length === 0) return null;\n return { code, message: typeof message === 'string' && message.length > 0 ? message : null };\n}\n\nexport function readRetryableRunRefusal(error: unknown): RetryableRunRefusal | null {\n if (error === null || typeof error !== 'object' || Array.isArray(error)) return null;\n return readRetryableDetail((error as { detail?: unknown }).detail);\n}\n\n/**\n * The `detail.code` agora answers when a send names another channel of the\n * collab agent a session started on (`collab_agent_bridge.py`): a session\n * keeps its channel — the SDK app's Agent / Ask mode — for its lifetime, and\n * the way to the other mode is a new session. Wire-frozen.\n */\nexport const COLLAB_AGENT_CHANNEL_SESSION_MISMATCH = 'collab_agent_channel_session_mismatch';\n\n/**\n * A structured refusal the host recorded as the run error when the run could\n * not START: the run executor raised the gate's `{status, detail: {code,\n * message}}` envelope (agora's `_status_reject`) before it accepted the\n * dispatched input, so the message went back to its lane and the thread rests\n * `error` with it still queued. Unlike a retryable refusal\n * ({@link readRetryableRunRefusal}) nothing will dispatch it later: resending\n * the same input is refused the same way, so the server's message is the only\n * explanation the person gets.\n */\nexport interface RunStartRefusal {\n /** The structured `detail.code` (`collab_agent_channel_session_mismatch`, …). */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n /** The HTTP-style status the gate raised with, when recorded. */\n status: number | null;\n}\n\n/**\n * The non-retryable structured refusal off a replicated run error\n * (`runs.error`), or `null` — for a run that failed while it was running (a\n * plain `{message}`), a retryable refusal, or no error at all.\n */\nexport function readRunStartRefusal(error: unknown): RunStartRefusal | null {\n if (error === null || typeof error !== 'object' || Array.isArray(error)) return null;\n const { detail, status } = error as { detail?: unknown; status?: unknown };\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const { code, message, retryable } = detail as {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n };\n if (retryable === true || typeof code !== 'string' || code.length === 0) return null;\n return {\n code,\n message: typeof message === 'string' && message.length > 0 ? message : null,\n status: typeof status === 'number' ? status : null,\n };\n}\n\n/** The structured `detail.code` of a rejected command, or `null`. */\nexport function statewireRejectionCode(error: unknown): string | null {\n const detail = statewireRejectionPayload(error)?.detail;\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const code = (detail as { code?: unknown }).code;\n return typeof code === 'string' && code.length > 0 ? code : null;\n}\n\n/**\n * A structured, retryable refusal of a COMMAND, read off its rejection\n * ({@link statewireRejectionPayload}): the host's `_structured_reject(...,\n * retryable=True)` envelope — `command_auth_context_expired` when a pod\n * replacement dropped the socket-scoped auth a replayed command needed,\n * `pod_draining` when the host was closing. The command never ran, and the\n * host itself says a resend after the reconnect will; `detail.code` is the\n * wire-frozen contract clients classify on. Same shape as\n * {@link readRetryableRunRefusal}, which reads it off a replicated run entry.\n */\nexport interface RetryableCommandRejection {\n /** The structured `detail.code`. */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n}\n\nexport function readRetryableCommandRejection(error: unknown): RetryableCommandRejection | null {\n const payload = statewireRejectionPayload(error);\n return payload === null ? null : readRetryableDetail(payload.detail);\n}\n\n/** The host's `detail.code` for a command replayed onto a pod that could not restore its auth context. */\nexport const STATEWIRE_COMMAND_AUTH_CONTEXT_EXPIRED = 'command_auth_context_expired';\n\n/**\n * Whether a rejected command hit the host's fail-closed auth recovery: the\n * command was replayed onto a replacement pod that could not restore the\n * attach's auth context, so it was refused unrun (503, retryable). The\n * reconnect already under way restores the context; a single resend after it\n * is the recovery, not a failure to report.\n */\nexport function isStatewireCommandAuthContextExpired(error: unknown): boolean {\n const payload = statewireRejectionPayload(error);\n return (\n payload?.status === 503 &&\n readRetryableDetail(payload.detail)?.code === STATEWIRE_COMMAND_AUTH_CONTEXT_EXPIRED\n );\n}\n\n/**\n * The `detail.code` agora answers for a write to an archived (trashed)\n * conversation (`host_rejects._conversation_archived_reject`, a 409): it\n * takes no new turns, config writes or approval answers until it is\n * restored, and stopping still works. Wire-frozen.\n */\nexport const CONVERSATION_ARCHIVED = 'conversation_archived';\n\n/** What a person is told when that refusal comes back (the server says the same). */\nexport const CONVERSATION_ARCHIVED_MESSAGE =\n 'This conversation is archived. Restore it to continue.';\n\n/**\n * Whether a rejected command was refused because the conversation is archived\n * ({@link CONVERSATION_ARCHIVED}). Not retriable: nothing changes until a\n * restore, so callers show {@link CONVERSATION_ARCHIVED_MESSAGE} rather than a\n * \"try again\".\n */\nexport function isConversationArchivedRejection(error: unknown): boolean {\n return statewireRejectionCode(error) === CONVERSATION_ARCHIVED;\n}\n\n/**\n * Whether a rejected command hit the legacy-thread dispatch fence: the\n * structured 409 the server answers when an out-of-band run is writing a\n * pre-cutover thread (or its adoption failed). A per-send failure — the\n * snapshot never carries a standing read-only flag.\n */\nexport function isLegacyThreadReadOnlyRejection(error: unknown): boolean {\n const payload = statewireRejectionPayload(error);\n if (payload?.status !== 409) return false;\n\n const detail = payload.detail as { code?: unknown } | undefined;\n return detail?.code === 'legacy_thread_read_only';\n}\n\n/**\n * Whether a rejected command was refused because its rewind anchor no longer\n * matches the host's parent for the edited message (`wrong-anchor`).\n *\n * A retry/edit resubmit is dispatched optimistically, so this rejection lands\n * after the UI already cleared its edit affordances: the turn simply never\n * re-runs. Callers use this to tell the user the resubmit was dropped instead\n * of leaving a console-only failure.\n */\nexport function isStatewireRewindAnchorRejection(error: unknown): boolean {\n const failure = (error as { failure?: { fate?: unknown; payload?: unknown } } | null | undefined)\n ?.failure;\n if (failure?.fate !== 'rejected') return false;\n return (failure.payload as { reason?: unknown } | undefined)?.reason === 'wrong-anchor';\n}\n\n/**\n * Whether a statewire send failure is the host's `expired` verdict\n * (`result-unavailable`): the command's seq was at or below the host's\n * admitted watermark and no retained result was left for it. Either the\n * command ran and settled but the client re-asked for the answer (a resend\n * after the stream came back) only after the host had let the retained result\n * go, or the seq was already admitted and the command was absorbed as a\n * duplicate without ever running — a client whose shared session record fell\n * behind the watermark stays there until a reconnect re-syncs it. The library\n * never reruns the command on replay, so for an idempotent read the answer is\n * simply gone — asking again is the correct reaction, not reporting a failure;\n * a write cannot assume it was applied.\n */\nexport function isStatewireExpiredVerdict(error: unknown): boolean {\n const failure = (error as { failure?: { fate?: unknown; cause?: unknown } | null | undefined })\n ?.failure;\n return failure?.fate === 'expired' && failure.cause === 'server';\n}\n\n/**\n * Whether a statewire send failure is a local channel death rather than a\n * command error.\n *\n * The library's contract for `SendFailure.cause`: `\"server\"` is the server's\n * own answer; every other cause is \"a channel death the client settled\n * locally\" — `unmount`, `stream-gone`, and `session-lost`. A thread switch\n * settles every in-flight command that way, so logging these at error level\n * reports two failures for an ordinary switch and buries the ones that mean\n * something.\n *\n * Channel health is already surfaced where it belongs: the connection\n * indicator renders the connection state. This\n * predicate only decides the log level.\n */\nexport function isStatewireChannelTeardown(error: unknown): boolean {\n const cause = (error as { failure?: { cause?: unknown } } | null | undefined)?.failure?.cause;\n return typeof cause === 'string' && cause !== 'server';\n}\n\n/**\n * The low-cardinality reason a statewire send settled as transport weather\n * rather than a defect, or `null` when the failure is a real error.\n *\n * Three families qualify: a channel death the client settled locally\n * ({@link isStatewireChannelTeardown} — the cause: `unmount`, `stream-gone`,\n * `session-lost`), the host's `expired` verdict\n * ({@link isStatewireExpiredVerdict} — the answer outlived the host's\n * retention before the post-reconnect resend collected it), and a retryable\n * structured rejection ({@link readRetryableCommandRejection} — its code: the\n * host asked for a resend). In every case the sender's own retry or poll is\n * the recovery and the connection indicator already shows the channel, so\n * error reporting counts the outcome instead of paging on it. Handler\n * failures, crashes, and non-retryable rejections stay `null`: those are\n * defects to page on.\n */\nexport function statewireTransportOutcome(error: unknown): string | null {\n const cause = (error as { failure?: { cause?: unknown } } | null | undefined)?.failure?.cause;\n if (typeof cause === 'string' && cause !== 'server') return cause;\n if (isStatewireExpiredVerdict(error)) return 'expired';\n return readRetryableCommandRejection(error)?.code ?? null;\n}\n\nconst sanitizeConnectionMessage = (message: string): string | undefined => {\n const printable = Array.from(message, (character) => {\n const code = character.charCodeAt(0);\n return code < 32 || code === 127 ? ' ' : character;\n })\n .join('')\n .replace(/\\s+/g, ' ')\n .trim();\n return printable ? printable.slice(0, 200) : undefined;\n};\n\n/** Preserve the Statewire lifecycle and sanitize host detail for display. */\nexport function projectDeepAgentConnection(\n connection: StatewireClient.ConnectionState\n): DeepAgentConnectionState {\n const message =\n 'message' in connection && typeof connection.message === 'string'\n ? sanitizeConnectionMessage(connection.message)\n : undefined;\n switch (connection.status) {\n case 'standby':\n return {\n status: connection.status,\n reason: connection.reason,\n degraded: connection.degraded,\n ...(message !== undefined && { message }),\n };\n case 'connecting':\n case 'connected':\n return { status: connection.status, degraded: connection.degraded };\n case 'retrying':\n return {\n status: connection.status,\n degraded: connection.degraded,\n attempt: connection.attempt,\n ...(connection.cause !== undefined && { cause: connection.cause }),\n ...(connection.code !== undefined && { code: connection.code }),\n ...(connection.nextRetryAt !== undefined && { nextRetryAt: connection.nextRetryAt }),\n ...(connection.lastError !== undefined && { lastError: connection.lastError }),\n ...(message !== undefined && { message }),\n };\n case 'stopped':\n return {\n status: connection.status,\n degraded: connection.degraded,\n reason: connection.reason,\n ...(connection.payload !== undefined && { payload: connection.payload }),\n ...(message !== undefined && { message }),\n };\n default:\n return unknownConnectionStatus(connection);\n }\n}\n\n/** Compile-time exhaustiveness: reachable only when the library grows a status this build does not project. */\nfunction unknownConnectionStatus(connection: never): never {\n throw new Error(\n `statewire: unknown connection status ${JSON.stringify(\n (connection as { status?: unknown }).status\n )}`\n );\n}\n"],"names":[],"mappings":";;AAUO,SAAS,0BAA0B,OAAkD;AAC1F,QAAM,UAAW,+BAAsE;AACvF,OAAI,mCAAS,UAAS,WAAY,QAAO;AAEzC,QAAM,UAAU,QAAQ;AACxB,MAAI,QAAO,mCAAS,YAAW,SAAU,QAAO;AAChD,SAAO,EAAE,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,OAAA;AACnD;AAQO,SAAS,gC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,KAAK;AAAA,MAC1C,WAAoC;AAAA,IAAA,CACtC;AAAA,EAAA;AAEL;;;;;;;;;;;;;;;;"}
|
|
@@ -47,6 +47,11 @@ function readRetryableCommandRejection(error) {
|
|
|
47
47
|
const payload = statewireRejectionPayload(error);
|
|
48
48
|
return payload === null ? null : readRetryableDetail(payload.detail);
|
|
49
49
|
}
|
|
50
|
+
const CONVERSATION_ARCHIVED = "conversation_archived";
|
|
51
|
+
const CONVERSATION_ARCHIVED_MESSAGE = "This conversation is archived. Restore it to continue.";
|
|
52
|
+
function isConversationArchivedRejection(error) {
|
|
53
|
+
return statewireRejectionCode(error) === CONVERSATION_ARCHIVED;
|
|
54
|
+
}
|
|
50
55
|
function isLegacyThreadReadOnlyRejection(error) {
|
|
51
56
|
const payload = statewireRejectionPayload(error);
|
|
52
57
|
if ((payload == null ? void 0 : payload.status) !== 409) return false;
|
|
@@ -121,6 +126,9 @@ function unknownConnectionStatus(connection) {
|
|
|
121
126
|
}
|
|
122
127
|
export {
|
|
123
128
|
COLLAB_AGENT_CHANNEL_SESSION_MISMATCH,
|
|
129
|
+
CONVERSATION_ARCHIVED,
|
|
130
|
+
CONVERSATION_ARCHIVED_MESSAGE,
|
|
131
|
+
isConversationArchivedRejection,
|
|
124
132
|
isLegacyThreadReadOnlyRejection,
|
|
125
133
|
isStatewireChannelTeardown,
|
|
126
134
|
isStatewireExpiredVerdict,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sources":["../../../../agent-runtime/src/errors.ts"],"sourcesContent":["import type { StatewireClient } from 'statewire';\nimport type { DeepAgentConnectionState } from './types';\n\n/** Structured payload attached to a server-rejected Statewire command. */\nexport interface StatewireRejectionPayload {\n status: number;\n detail: unknown;\n}\n\n/** Return a rejected command's structured `{ status, detail }` payload. */\nexport function statewireRejectionPayload(error: unknown): StatewireRejectionPayload | null {\n const failure = (error as { failure?: { fate?: unknown; payload?: unknown } } | null)?.failure;\n if (failure?.fate !== 'rejected') return null;\n\n const payload = failure.payload as { status?: unknown; detail?: unknown } | undefined;\n if (typeof payload?.status !== 'number') return null;\n return { status: payload.status, detail: payload.detail };\n}\n\n/**\n * The server's human-readable reason for a rejected command — `detail.message`\n * (or a plain-string `detail`) — else `null`. Hosts surface it as send\n * feedback so the user sees the actionable cause instead of the generic\n * client-side `command rejected (<status>)`.\n */\nexport function statewireRejectionDetailMessage(error: unknown): string | null {\n const detail = statewireRejectionPayload(error)?.detail;\n if (typeof detail === 'string') return detail.length > 0 ? detail : null;\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const message = (detail as { message?: unknown }).message;\n return typeof message === 'string' && message.length > 0 ? message : null;\n}\n\n/**\n * A structured, retryable refusal the host recorded as the run error\n * (`runs.error`): the dispatch never started — the pod or instance was\n * closing (`pod_draining`) — and the entries stayed in their lanes for the\n * thread's next placement. Distinct from a rejected COMMAND\n * ({@link statewireRejectionPayload}): this is the shape harness-sdk writes\n * when the run executor raises the rejection, so it lives on the replicated\n * run entry, not on a command settle.\n */\nexport interface RetryableRunRefusal {\n /** The structured `detail.code` (`pod_draining`). */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n}\n\n/** The `{ code, message, retryable: true }` detail of a structured refusal, or `null`. */\nfunction readRetryableDetail(detail: unknown): { code: string; message: string | null } | null {\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const { code, message, retryable } = detail as {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n };\n if (retryable !== true || typeof code !== 'string' || code.length === 0) return null;\n return { code, message: typeof message === 'string' && message.length > 0 ? message : null };\n}\n\nexport function readRetryableRunRefusal(error: unknown): RetryableRunRefusal | null {\n if (error === null || typeof error !== 'object' || Array.isArray(error)) return null;\n return readRetryableDetail((error as { detail?: unknown }).detail);\n}\n\n/**\n * The `detail.code` agora answers when a send names another channel of the\n * collab agent a session started on (`collab_agent_bridge.py`): a session\n * keeps its channel — the SDK app's Agent / Ask mode — for its lifetime, and\n * the way to the other mode is a new session. Wire-frozen.\n */\nexport const COLLAB_AGENT_CHANNEL_SESSION_MISMATCH = 'collab_agent_channel_session_mismatch';\n\n/**\n * A structured refusal the host recorded as the run error when the run could\n * not START: the run executor raised the gate's `{status, detail: {code,\n * message}}` envelope (agora's `_status_reject`) before it accepted the\n * dispatched input, so the message went back to its lane and the thread rests\n * `error` with it still queued. Unlike a retryable refusal\n * ({@link readRetryableRunRefusal}) nothing will dispatch it later: resending\n * the same input is refused the same way, so the server's message is the only\n * explanation the person gets.\n */\nexport interface RunStartRefusal {\n /** The structured `detail.code` (`collab_agent_channel_session_mismatch`, …). */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n /** The HTTP-style status the gate raised with, when recorded. */\n status: number | null;\n}\n\n/**\n * The non-retryable structured refusal off a replicated run error\n * (`runs.error`), or `null` — for a run that failed while it was running (a\n * plain `{message}`), a retryable refusal, or no error at all.\n */\nexport function readRunStartRefusal(error: unknown): RunStartRefusal | null {\n if (error === null || typeof error !== 'object' || Array.isArray(error)) return null;\n const { detail, status } = error as { detail?: unknown; status?: unknown };\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const { code, message, retryable } = detail as {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n };\n if (retryable === true || typeof code !== 'string' || code.length === 0) return null;\n return {\n code,\n message: typeof message === 'string' && message.length > 0 ? message : null,\n status: typeof status === 'number' ? status : null,\n };\n}\n\n/** The structured `detail.code` of a rejected command, or `null`. */\nexport function statewireRejectionCode(error: unknown): string | null {\n const detail = statewireRejectionPayload(error)?.detail;\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const code = (detail as { code?: unknown }).code;\n return typeof code === 'string' && code.length > 0 ? code : null;\n}\n\n/**\n * A structured, retryable refusal of a COMMAND, read off its rejection\n * ({@link statewireRejectionPayload}): the host's `_structured_reject(...,\n * retryable=True)` envelope — `command_auth_context_expired` when a pod\n * replacement dropped the socket-scoped auth a replayed command needed,\n * `pod_draining` when the host was closing. The command never ran, and the\n * host itself says a resend after the reconnect will; `detail.code` is the\n * wire-frozen contract clients classify on. Same shape as\n * {@link readRetryableRunRefusal}, which reads it off a replicated run entry.\n */\nexport interface RetryableCommandRejection {\n /** The structured `detail.code`. */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n}\n\nexport function readRetryableCommandRejection(error: unknown): RetryableCommandRejection | null {\n const payload = statewireRejectionPayload(error);\n return payload === null ? null : readRetryableDetail(payload.detail);\n}\n\n/** The host's `detail.code` for a command replayed onto a pod that could not restore its auth context. */\nexport const STATEWIRE_COMMAND_AUTH_CONTEXT_EXPIRED = 'command_auth_context_expired';\n\n/**\n * Whether a rejected command hit the host's fail-closed auth recovery: the\n * command was replayed onto a replacement pod that could not restore the\n * attach's auth context, so it was refused unrun (503, retryable). The\n * reconnect already under way restores the context; a single resend after it\n * is the recovery, not a failure to report.\n */\nexport function isStatewireCommandAuthContextExpired(error: unknown): boolean {\n const payload = statewireRejectionPayload(error);\n return (\n payload?.status === 503 &&\n readRetryableDetail(payload.detail)?.code === STATEWIRE_COMMAND_AUTH_CONTEXT_EXPIRED\n );\n}\n\n/**\n * Whether a rejected command hit the legacy-thread dispatch fence: the\n * structured 409 the server answers when an out-of-band run is writing a\n * pre-cutover thread (or its adoption failed). A per-send failure — the\n * snapshot never carries a standing read-only flag.\n */\nexport function isLegacyThreadReadOnlyRejection(error: unknown): boolean {\n const payload = statewireRejectionPayload(error);\n if (payload?.status !== 409) return false;\n\n const detail = payload.detail as { code?: unknown } | undefined;\n return detail?.code === 'legacy_thread_read_only';\n}\n\n/**\n * Whether a rejected command was refused because its rewind anchor no longer\n * matches the host's parent for the edited message (`wrong-anchor`).\n *\n * A retry/edit resubmit is dispatched optimistically, so this rejection lands\n * after the UI already cleared its edit affordances: the turn simply never\n * re-runs. Callers use this to tell the user the resubmit was dropped instead\n * of leaving a console-only failure.\n */\nexport function isStatewireRewindAnchorRejection(error: unknown): boolean {\n const failure = (error as { failure?: { fate?: unknown; payload?: unknown } } | null | undefined)\n ?.failure;\n if (failure?.fate !== 'rejected') return false;\n return (failure.payload as { reason?: unknown } | undefined)?.reason === 'wrong-anchor';\n}\n\n/**\n * Whether a statewire send failure is the host's `expired` verdict\n * (`result-unavailable`): the command's seq was at or below the host's\n * admitted watermark and no retained result was left for it. Either the\n * command ran and settled but the client re-asked for the answer (a resend\n * after the stream came back) only after the host had let the retained result\n * go, or the seq was already admitted and the command was absorbed as a\n * duplicate without ever running — a client whose shared session record fell\n * behind the watermark stays there until a reconnect re-syncs it. The library\n * never reruns the command on replay, so for an idempotent read the answer is\n * simply gone — asking again is the correct reaction, not reporting a failure;\n * a write cannot assume it was applied.\n */\nexport function isStatewireExpiredVerdict(error: unknown): boolean {\n const failure = (error as { failure?: { fate?: unknown; cause?: unknown } | null | undefined })\n ?.failure;\n return failure?.fate === 'expired' && failure.cause === 'server';\n}\n\n/**\n * Whether a statewire send failure is a local channel death rather than a\n * command error.\n *\n * The library's contract for `SendFailure.cause`: `\"server\"` is the server's\n * own answer; every other cause is \"a channel death the client settled\n * locally\" — `unmount`, `stream-gone`, and `session-lost`. A thread switch\n * settles every in-flight command that way, so logging these at error level\n * reports two failures for an ordinary switch and buries the ones that mean\n * something.\n *\n * Channel health is already surfaced where it belongs: the connection\n * indicator renders the connection state. This\n * predicate only decides the log level.\n */\nexport function isStatewireChannelTeardown(error: unknown): boolean {\n const cause = (error as { failure?: { cause?: unknown } } | null | undefined)?.failure?.cause;\n return typeof cause === 'string' && cause !== 'server';\n}\n\n/**\n * The low-cardinality reason a statewire send settled as transport weather\n * rather than a defect, or `null` when the failure is a real error.\n *\n * Three families qualify: a channel death the client settled locally\n * ({@link isStatewireChannelTeardown} — the cause: `unmount`, `stream-gone`,\n * `session-lost`), the host's `expired` verdict\n * ({@link isStatewireExpiredVerdict} — the answer outlived the host's\n * retention before the post-reconnect resend collected it), and a retryable\n * structured rejection ({@link readRetryableCommandRejection} — its code: the\n * host asked for a resend). In every case the sender's own retry or poll is\n * the recovery and the connection indicator already shows the channel, so\n * error reporting counts the outcome instead of paging on it. Handler\n * failures, crashes, and non-retryable rejections stay `null`: those are\n * defects to page on.\n */\nexport function statewireTransportOutcome(error: unknown): string | null {\n const cause = (error as { failure?: { cause?: unknown } } | null | undefined)?.failure?.cause;\n if (typeof cause === 'string' && cause !== 'server') return cause;\n if (isStatewireExpiredVerdict(error)) return 'expired';\n return readRetryableCommandRejection(error)?.code ?? null;\n}\n\nconst sanitizeConnectionMessage = (message: string): string | undefined => {\n const printable = Array.from(message, (character) => {\n const code = character.charCodeAt(0);\n return code < 32 || code === 127 ? ' ' : character;\n })\n .join('')\n .replace(/\\s+/g, ' ')\n .trim();\n return printable ? printable.slice(0, 200) : undefined;\n};\n\n/** Preserve the Statewire lifecycle and sanitize host detail for display. */\nexport function projectDeepAgentConnection(\n connection: StatewireClient.ConnectionState\n): DeepAgentConnectionState {\n const message =\n 'message' in connection && typeof connection.message === 'string'\n ? sanitizeConnectionMessage(connection.message)\n : undefined;\n switch (connection.status) {\n case 'standby':\n return {\n status: connection.status,\n reason: connection.reason,\n degraded: connection.degraded,\n ...(message !== undefined && { message }),\n };\n case 'connecting':\n case 'connected':\n return { status: connection.status, degraded: connection.degraded };\n case 'retrying':\n return {\n status: connection.status,\n degraded: connection.degraded,\n attempt: connection.attempt,\n ...(connection.cause !== undefined && { cause: connection.cause }),\n ...(connection.code !== undefined && { code: connection.code }),\n ...(connection.nextRetryAt !== undefined && { nextRetryAt: connection.nextRetryAt }),\n ...(connection.lastError !== undefined && { lastError: connection.lastError }),\n ...(message !== undefined && { message }),\n };\n case 'stopped':\n return {\n status: connection.status,\n degraded: connection.degraded,\n reason: connection.reason,\n ...(connection.payload !== undefined && { payload: connection.payload }),\n ...(message !== undefined && { message }),\n };\n default:\n return unknownConnectionStatus(connection);\n }\n}\n\n/** Compile-time exhaustiveness: reachable only when the library grows a status this build does not project. */\nfunction unknownConnectionStatus(connection: never): never {\n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,QAAQ,WAAW;AAAA,QACnB,GAAI,WAAW,YAAY,UAAa,EAAE,SAAS,WAAW,QAAA;AAAA,QAC9D,GAAI,YAAY,UAAa,EAAE,QAAA;AAAA,MAAQ;AAAA,IAE3C;AACE,aAAO,wBAAwB,UAAU;AAAA,EAAA;AAE/C;AAGA,SAAS,wBAAwB,YAA0B;AACzD,QAAM,IAAI;AAAA,IACR,wCAAwC,KAAK;AAAA,MAC1C,WAAoC;AAAA,IAAA,CACtC;AAAA,EAAA;AAEL;"}
|
|
1
|
+
{"version":3,"file":"errors.js","sources":["../../../../agent-runtime/src/errors.ts"],"sourcesContent":["import type { StatewireClient } from 'statewire';\nimport type { DeepAgentConnectionState } from './types';\n\n/** Structured payload attached to a server-rejected Statewire command. */\nexport interface StatewireRejectionPayload {\n status: number;\n detail: unknown;\n}\n\n/** Return a rejected command's structured `{ status, detail }` payload. */\nexport function statewireRejectionPayload(error: unknown): StatewireRejectionPayload | null {\n const failure = (error as { failure?: { fate?: unknown; payload?: unknown } } | null)?.failure;\n if (failure?.fate !== 'rejected') return null;\n\n const payload = failure.payload as { status?: unknown; detail?: unknown } | undefined;\n if (typeof payload?.status !== 'number') return null;\n return { status: payload.status, detail: payload.detail };\n}\n\n/**\n * The server's human-readable reason for a rejected command — `detail.message`\n * (or a plain-string `detail`) — else `null`. Hosts surface it as send\n * feedback so the user sees the actionable cause instead of the generic\n * client-side `command rejected (<status>)`.\n */\nexport function statewireRejectionDetailMessage(error: unknown): string | null {\n const detail = statewireRejectionPayload(error)?.detail;\n if (typeof detail === 'string') return detail.length > 0 ? detail : null;\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const message = (detail as { message?: unknown }).message;\n return typeof message === 'string' && message.length > 0 ? message : null;\n}\n\n/**\n * A structured, retryable refusal the host recorded as the run error\n * (`runs.error`): the dispatch never started — the pod or instance was\n * closing (`pod_draining`) — and the entries stayed in their lanes for the\n * thread's next placement. Distinct from a rejected COMMAND\n * ({@link statewireRejectionPayload}): this is the shape harness-sdk writes\n * when the run executor raises the rejection, so it lives on the replicated\n * run entry, not on a command settle.\n */\nexport interface RetryableRunRefusal {\n /** The structured `detail.code` (`pod_draining`). */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n}\n\n/** The `{ code, message, retryable: true }` detail of a structured refusal, or `null`. */\nfunction readRetryableDetail(detail: unknown): { code: string; message: string | null } | null {\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const { code, message, retryable } = detail as {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n };\n if (retryable !== true || typeof code !== 'string' || code.length === 0) return null;\n return { code, message: typeof message === 'string' && message.length > 0 ? message : null };\n}\n\nexport function readRetryableRunRefusal(error: unknown): RetryableRunRefusal | null {\n if (error === null || typeof error !== 'object' || Array.isArray(error)) return null;\n return readRetryableDetail((error as { detail?: unknown }).detail);\n}\n\n/**\n * The `detail.code` agora answers when a send names another channel of the\n * collab agent a session started on (`collab_agent_bridge.py`): a session\n * keeps its channel — the SDK app's Agent / Ask mode — for its lifetime, and\n * the way to the other mode is a new session. Wire-frozen.\n */\nexport const COLLAB_AGENT_CHANNEL_SESSION_MISMATCH = 'collab_agent_channel_session_mismatch';\n\n/**\n * A structured refusal the host recorded as the run error when the run could\n * not START: the run executor raised the gate's `{status, detail: {code,\n * message}}` envelope (agora's `_status_reject`) before it accepted the\n * dispatched input, so the message went back to its lane and the thread rests\n * `error` with it still queued. Unlike a retryable refusal\n * ({@link readRetryableRunRefusal}) nothing will dispatch it later: resending\n * the same input is refused the same way, so the server's message is the only\n * explanation the person gets.\n */\nexport interface RunStartRefusal {\n /** The structured `detail.code` (`collab_agent_channel_session_mismatch`, …). */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n /** The HTTP-style status the gate raised with, when recorded. */\n status: number | null;\n}\n\n/**\n * The non-retryable structured refusal off a replicated run error\n * (`runs.error`), or `null` — for a run that failed while it was running (a\n * plain `{message}`), a retryable refusal, or no error at all.\n */\nexport function readRunStartRefusal(error: unknown): RunStartRefusal | null {\n if (error === null || typeof error !== 'object' || Array.isArray(error)) return null;\n const { detail, status } = error as { detail?: unknown; status?: unknown };\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const { code, message, retryable } = detail as {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n };\n if (retryable === true || typeof code !== 'string' || code.length === 0) return null;\n return {\n code,\n message: typeof message === 'string' && message.length > 0 ? message : null,\n status: typeof status === 'number' ? status : null,\n };\n}\n\n/** The structured `detail.code` of a rejected command, or `null`. */\nexport function statewireRejectionCode(error: unknown): string | null {\n const detail = statewireRejectionPayload(error)?.detail;\n if (detail === null || typeof detail !== 'object' || Array.isArray(detail)) return null;\n const code = (detail as { code?: unknown }).code;\n return typeof code === 'string' && code.length > 0 ? code : null;\n}\n\n/**\n * A structured, retryable refusal of a COMMAND, read off its rejection\n * ({@link statewireRejectionPayload}): the host's `_structured_reject(...,\n * retryable=True)` envelope — `command_auth_context_expired` when a pod\n * replacement dropped the socket-scoped auth a replayed command needed,\n * `pod_draining` when the host was closing. The command never ran, and the\n * host itself says a resend after the reconnect will; `detail.code` is the\n * wire-frozen contract clients classify on. Same shape as\n * {@link readRetryableRunRefusal}, which reads it off a replicated run entry.\n */\nexport interface RetryableCommandRejection {\n /** The structured `detail.code`. */\n code: string;\n /** The server's human-readable reason, when it sent one. */\n message: string | null;\n}\n\nexport function readRetryableCommandRejection(error: unknown): RetryableCommandRejection | null {\n const payload = statewireRejectionPayload(error);\n return payload === null ? null : readRetryableDetail(payload.detail);\n}\n\n/** The host's `detail.code` for a command replayed onto a pod that could not restore its auth context. */\nexport const STATEWIRE_COMMAND_AUTH_CONTEXT_EXPIRED = 'command_auth_context_expired';\n\n/**\n * Whether a rejected command hit the host's fail-closed auth recovery: the\n * command was replayed onto a replacement pod that could not restore the\n * attach's auth context, so it was refused unrun (503, retryable). The\n * reconnect already under way restores the context; a single resend after it\n * is the recovery, not a failure to report.\n */\nexport function isStatewireCommandAuthContextExpired(error: unknown): boolean {\n const payload = statewireRejectionPayload(error);\n return (\n payload?.status === 503 &&\n readRetryableDetail(payload.detail)?.code === STATEWIRE_COMMAND_AUTH_CONTEXT_EXPIRED\n );\n}\n\n/**\n * The `detail.code` agora answers for a write to an archived (trashed)\n * conversation (`host_rejects._conversation_archived_reject`, a 409): it\n * takes no new turns, config writes or approval answers until it is\n * restored, and stopping still works. Wire-frozen.\n */\nexport const CONVERSATION_ARCHIVED = 'conversation_archived';\n\n/** What a person is told when that refusal comes back (the server says the same). */\nexport const CONVERSATION_ARCHIVED_MESSAGE =\n 'This conversation is archived. Restore it to continue.';\n\n/**\n * Whether a rejected command was refused because the conversation is archived\n * ({@link CONVERSATION_ARCHIVED}). Not retriable: nothing changes until a\n * restore, so callers show {@link CONVERSATION_ARCHIVED_MESSAGE} rather than a\n * \"try again\".\n */\nexport function isConversationArchivedRejection(error: unknown): boolean {\n return statewireRejectionCode(error) === CONVERSATION_ARCHIVED;\n}\n\n/**\n * Whether a rejected command hit the legacy-thread dispatch fence: the\n * structured 409 the server answers when an out-of-band run is writing a\n * pre-cutover thread (or its adoption failed). A per-send failure — the\n * snapshot never carries a standing read-only flag.\n */\nexport function isLegacyThreadReadOnlyRejection(error: unknown): boolean {\n const payload = statewireRejectionPayload(error);\n if (payload?.status !== 409) return false;\n\n const detail = payload.detail as { code?: unknown } | undefined;\n return detail?.code === 'legacy_thread_read_only';\n}\n\n/**\n * Whether a rejected command was refused because its rewind anchor no longer\n * matches the host's parent for the edited message (`wrong-anchor`).\n *\n * A retry/edit resubmit is dispatched optimistically, so this rejection lands\n * after the UI already cleared its edit affordances: the turn simply never\n * re-runs. Callers use this to tell the user the resubmit was dropped instead\n * of leaving a console-only failure.\n */\nexport function isStatewireRewindAnchorRejection(error: unknown): boolean {\n const failure = (error as { failure?: { fate?: unknown; payload?: unknown } } | null | undefined)\n ?.failure;\n if (failure?.fate !== 'rejected') return false;\n return (failure.payload as { reason?: unknown } | undefined)?.reason === 'wrong-anchor';\n}\n\n/**\n * Whether a statewire send failure is the host's `expired` verdict\n * (`result-unavailable`): the command's seq was at or below the host's\n * admitted watermark and no retained result was left for it. Either the\n * command ran and settled but the client re-asked for the answer (a resend\n * after the stream came back) only after the host had let the retained result\n * go, or the seq was already admitted and the command was absorbed as a\n * duplicate without ever running — a client whose shared session record fell\n * behind the watermark stays there until a reconnect re-syncs it. The library\n * never reruns the command on replay, so for an idempotent read the answer is\n * simply gone — asking again is the correct reaction, not reporting a failure;\n * a write cannot assume it was applied.\n */\nexport function isStatewireExpiredVerdict(error: unknown): boolean {\n const failure = (error as { failure?: { fate?: unknown; cause?: unknown } | null | undefined })\n ?.failure;\n return failure?.fate === 'expired' && failure.cause === 'server';\n}\n\n/**\n * Whether a statewire send failure is a local channel death rather than a\n * command error.\n *\n * The library's contract for `SendFailure.cause`: `\"server\"` is the server's\n * own answer; every other cause is \"a channel death the client settled\n * locally\" — `unmount`, `stream-gone`, and `session-lost`. A thread switch\n * settles every in-flight command that way, so logging these at error level\n * reports two failures for an ordinary switch and buries the ones that mean\n * something.\n *\n * Channel health is already surfaced where it belongs: the connection\n * indicator renders the connection state. This\n * predicate only decides the log level.\n */\nexport function isStatewireChannelTeardown(error: unknown): boolean {\n const cause = (error as { failure?: { cause?: unknown } } | null | undefined)?.failure?.cause;\n return typeof cause === 'string' && cause !== 'server';\n}\n\n/**\n * The low-cardinality reason a statewire send settled as transport weather\n * rather than a defect, or `null` when the failure is a real error.\n *\n * Three families qualify: a channel death the client settled locally\n * ({@link isStatewireChannelTeardown} — the cause: `unmount`, `stream-gone`,\n * `session-lost`), the host's `expired` verdict\n * ({@link isStatewireExpiredVerdict} — the answer outlived the host's\n * retention before the post-reconnect resend collected it), and a retryable\n * structured rejection ({@link readRetryableCommandRejection} — its code: the\n * host asked for a resend). In every case the sender's own retry or poll is\n * the recovery and the connection indicator already shows the channel, so\n * error reporting counts the outcome instead of paging on it. Handler\n * failures, crashes, and non-retryable rejections stay `null`: those are\n * defects to page on.\n */\nexport function statewireTransportOutcome(error: unknown): string | null {\n const cause = (error as { failure?: { cause?: unknown } } | null | undefined)?.failure?.cause;\n if (typeof cause === 'string' && cause !== 'server') return cause;\n if (isStatewireExpiredVerdict(error)) return 'expired';\n return readRetryableCommandRejection(error)?.code ?? null;\n}\n\nconst sanitizeConnectionMessage = (message: string): string | undefined => {\n const printable = Array.from(message, (character) => {\n const code = character.charCodeAt(0);\n return code < 32 || code === 127 ? ' ' : character;\n })\n .join('')\n .replace(/\\s+/g, ' ')\n .trim();\n return printable ? printable.slice(0, 200) : undefined;\n};\n\n/** Preserve the Statewire lifecycle and sanitize host detail for display. */\nexport function projectDeepAgentConnection(\n connection: StatewireClient.ConnectionState\n): DeepAgentConnectionState {\n const message =\n 'message' in connection && typeof connection.message === 'string'\n ? sanitizeConnectionMessage(connection.message)\n : undefined;\n switch (connection.status) {\n case 'standby':\n return {\n status: connection.status,\n reason: connection.reason,\n degraded: connection.degraded,\n ...(message !== undefined && { message }),\n };\n case 'connecting':\n case 'connected':\n return { status: connection.status, degraded: connection.degraded };\n case 'retrying':\n return {\n status: connection.status,\n degraded: connection.degraded,\n attempt: connection.attempt,\n ...(connection.cause !== undefined && { cause: connection.cause }),\n ...(connection.code !== undefined && { code: connection.code }),\n ...(connection.nextRetryAt !== undefined && { nextRetryAt: connection.nextRetryAt }),\n ...(connection.lastError !== undefined && { lastError: connection.lastError }),\n ...(message !== undefined && { message }),\n };\n case 'stopped':\n return {\n status: connection.status,\n degraded: connection.degraded,\n reason: connection.reason,\n ...(connection.payload !== undefined && { payload: connection.payload }),\n ...(message !== undefined && { message }),\n };\n default:\n return unknownConnectionStatus(connection);\n }\n}\n\n/** Compile-time exhaustiveness: reachable only when the library grows a status this build does not project. */\nfunction unknownConnectionStatus(connection: never): never {\n throw new Error(\n `statewire: unknown connection status ${JSON.stringify(\n (connection as { status?: unknown }).status\n )}`\n );\n}\n"],"names":[],"mappings":"AAUO,SAAS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AAA,QACrB,QAAQ,WAAW;AAAA,QACnB,GAAI,WAAW,YAAY,UAAa,EAAE,SAAS,WAAW,QAAA;AAAA,QAC9D,GAAI,YAAY,UAAa,EAAE,QAAA;AAAA,MAAQ;AAAA,IAE3C;AACE,aAAO,wBAAwB,UAAU;AAAA,EAAA;AAE/C;AAGA,SAAS,wBAAwB,YAA0B;AACzD,QAAM,IAAI;AAAA,IACR,wCAAwC,KAAK;AAAA,MAC1C,WAAoC;AAAA,IAAA,CACtC;AAAA,EAAA;AAEL;"}
|
|
@@ -33,7 +33,8 @@ class DeepAgentMessageConversionCache {
|
|
|
33
33
|
/**
|
|
34
34
|
* Convert one pass's LangChain messages. Returns the previous pass's array
|
|
35
35
|
* itself when every converted message is unchanged, so a packet that moved
|
|
36
|
-
* no message re-renders no message; a re-converted turn keeps the
|
|
36
|
+
* no message re-renders no message; a re-converted turn keeps the row key
|
|
37
|
+
* of the row it continues (see {@link deepAgentRowKey}) and the previous
|
|
37
38
|
* pass's part objects for the parts that did not change
|
|
38
39
|
* (see {@link keepUnchangedParts}).
|
|
39
40
|
*/
|
|
@@ -70,36 +71,94 @@ function sameMessagePart(previous, next) {
|
|
|
70
71
|
}
|
|
71
72
|
return true;
|
|
72
73
|
}
|
|
74
|
+
const ROW_KEY = Symbol.for("@athenaintel/agent-runtime/row-key");
|
|
75
|
+
function deepAgentRowKey(message) {
|
|
76
|
+
const key = Reflect.get(message, ROW_KEY);
|
|
77
|
+
return typeof key === "string" ? key : message.id;
|
|
78
|
+
}
|
|
73
79
|
function keepUnchangedParts({
|
|
74
80
|
previous,
|
|
75
81
|
previousConverted,
|
|
76
82
|
converted
|
|
77
83
|
}) {
|
|
78
84
|
let previousByConverted = null;
|
|
85
|
+
let previousBySource = null;
|
|
79
86
|
let previousById = null;
|
|
87
|
+
let rowIds = null;
|
|
88
|
+
const continuedKeys = /* @__PURE__ */ new Set();
|
|
89
|
+
const continuedRow = (message, index) => {
|
|
90
|
+
const atIndex = previous[index];
|
|
91
|
+
if ((atIndex == null ? void 0 : atIndex.id) === message.id) return atIndex;
|
|
92
|
+
previousBySource ?? (previousBySource = rowsBySourceMessage(previous));
|
|
93
|
+
for (const source of core.getExternalStoreMessages(message)) {
|
|
94
|
+
const row = previousBySource.get(source);
|
|
95
|
+
if (row !== void 0) return row;
|
|
96
|
+
}
|
|
97
|
+
previousById ?? (previousById = new Map(previous.map((row) => [row.id, row])));
|
|
98
|
+
return previousById.get(message.id);
|
|
99
|
+
};
|
|
80
100
|
return converted.map((message, index) => {
|
|
81
101
|
if (message === previousConverted[index]) return previous[index] ?? message;
|
|
82
102
|
previousByConverted ?? (previousByConverted = new Map(
|
|
83
|
-
previousConverted.map((
|
|
103
|
+
previousConverted.map((row2, rowIndex) => [row2, previous[rowIndex] ?? row2])
|
|
84
104
|
));
|
|
85
105
|
const unchanged = previousByConverted.get(message);
|
|
86
106
|
if (unchanged !== void 0) return unchanged;
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
107
|
+
const before = continuedRow(message, index);
|
|
108
|
+
const row = (before == null ? void 0 : before.role) === "assistant" && message.role === "assistant" ? withUnchangedParts({ before, message }) : message;
|
|
109
|
+
const key = before === void 0 ? message.id : deepAgentRowKey(before);
|
|
110
|
+
if (key === message.id) return row;
|
|
111
|
+
rowIds ?? (rowIds = new Set(converted.map((candidate) => candidate.id)));
|
|
112
|
+
if (rowIds.has(key) || continuedKeys.has(key)) return row;
|
|
113
|
+
continuedKeys.add(key);
|
|
114
|
+
const keyed = { ...row };
|
|
115
|
+
Reflect.set(keyed, ROW_KEY, key);
|
|
116
|
+
return keyed;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
function rowsBySourceMessage(rows) {
|
|
120
|
+
const bySource = /* @__PURE__ */ new Map();
|
|
121
|
+
for (const row of rows) {
|
|
122
|
+
for (const source of core.getExternalStoreMessages(row)) {
|
|
123
|
+
if (!bySource.has(source)) bySource.set(source, row);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return bySource;
|
|
127
|
+
}
|
|
128
|
+
function withUnchangedParts({
|
|
129
|
+
before,
|
|
130
|
+
message
|
|
131
|
+
}) {
|
|
132
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
133
|
+
const bySource = /* @__PURE__ */ new Map();
|
|
134
|
+
for (const part of before.content) {
|
|
135
|
+
if (part.type === "tool-call") {
|
|
136
|
+
toolCalls.set(part.toolCallId, part);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const source = core.getExternalStoreMessages(part)[0];
|
|
140
|
+
const parts = bySource.get(source);
|
|
141
|
+
if (parts === void 0) bySource.set(source, [part]);
|
|
142
|
+
else parts.push(part);
|
|
143
|
+
}
|
|
144
|
+
const placesBySource = /* @__PURE__ */ new Map();
|
|
145
|
+
let kept = 0;
|
|
146
|
+
const content = message.content.map((part) => {
|
|
147
|
+
var _a;
|
|
148
|
+
let candidate;
|
|
149
|
+
if (part.type === "tool-call") {
|
|
150
|
+
candidate = toolCalls.get(part.toolCallId);
|
|
151
|
+
} else {
|
|
152
|
+
const source = core.getExternalStoreMessages(part)[0];
|
|
153
|
+
const place = placesBySource.get(source) ?? 0;
|
|
154
|
+
placesBySource.set(source, place + 1);
|
|
155
|
+
candidate = (_a = bySource.get(source)) == null ? void 0 : _a[place];
|
|
91
156
|
}
|
|
92
|
-
if (
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const content = message.content.map((part, partIndex) => {
|
|
96
|
-
const candidate = beforeContent[partIndex];
|
|
97
|
-
if (candidate === void 0 || !sameMessagePart(candidate, part)) return part;
|
|
98
|
-
kept += 1;
|
|
99
|
-
return candidate;
|
|
100
|
-
});
|
|
101
|
-
return kept === 0 ? message : { ...message, content };
|
|
157
|
+
if (candidate === void 0 || !sameMessagePart(candidate, part)) return part;
|
|
158
|
+
kept += 1;
|
|
159
|
+
return candidate;
|
|
102
160
|
});
|
|
161
|
+
return kept === 0 ? message : { ...message, content };
|
|
103
162
|
}
|
|
104
163
|
function createDeepAgentMessageConversionCache() {
|
|
105
164
|
return new DeepAgentMessageConversionCache();
|
|
@@ -594,6 +653,7 @@ exports.PENDING_ASSISTANT_MESSAGE_ID = PENDING_ASSISTANT_MESSAGE_ID;
|
|
|
594
653
|
exports.convertDeepAgentState = convertDeepAgentState;
|
|
595
654
|
exports.createDeepAgentMaterialize = createDeepAgentMaterialize;
|
|
596
655
|
exports.createDeepAgentMessageConversionCache = createDeepAgentMessageConversionCache;
|
|
656
|
+
exports.deepAgentRowKey = deepAgentRowKey;
|
|
597
657
|
exports.isConvertibleChatMessage = isConvertibleChatMessage;
|
|
598
658
|
exports.isLangGraphState = isLangGraphState;
|
|
599
659
|
exports.isMessageHiddenFromFrontend = isMessageHiddenFromFrontend;
|