@athenaintel/react 0.41.1 → 0.41.2
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 +6 -0
- package/dist/agent-runtime/src/protocol.cjs +15 -0
- package/dist/agent-runtime/src/protocol.cjs.map +1 -1
- package/dist/agent-runtime/src/protocol.js +16 -1
- package/dist/agent-runtime/src/protocol.js.map +1 -1
- package/dist/agent-runtime/src/thread-snapshot-cache.cjs +2 -1
- package/dist/agent-runtime/src/thread-snapshot-cache.cjs.map +1 -1
- package/dist/agent-runtime/src/thread-snapshot-cache.js +2 -1
- package/dist/agent-runtime/src/thread-snapshot-cache.js.map +1 -1
- package/dist/react/package.json.cjs +1 -1
- package/dist/react/package.json.js +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.cjs +4 -14
- package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.d.ts +5 -4
- package/dist/runtime/useAthenaStatewireRuntime.js +4 -14
- package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -807,6 +807,12 @@ Both use the same bearer / API key as session creation. The full recipe
|
|
|
807
807
|
template skill `voice-session-guide.md`. `createAthenaVoiceSession` is also
|
|
808
808
|
exported if you hold the bridge state yourself.
|
|
809
809
|
|
|
810
|
+
## What's new in 0.41.2
|
|
811
|
+
|
|
812
|
+
**A session opened while its run is streaming shows, and keeps, its own model.** `useAthenaThreadModel()` could report `ready` with no model before the session's snapshot had arrived. On a session whose run was streaming, the connection reported `connected` before the attach snapshot applied, and the SDK took the placeholder the thread shows meanwhile, which holds no server config, as what the server sent. A picker seeded from it showed the agent's default model, and the provider then wrote that pick to the session (`config/patch {model: null}`), so the session lost its model for its next turns. `ready`, and every config write the provider decides, now wait for a state the server sent: the placeholder and a remembered snapshot never count, whenever the connection reports `connected`. The `statewire.attach` diagnostics span (time to the session's snapshot) now ends when that snapshot arrives, not when the thread first renders.
|
|
813
|
+
|
|
814
|
+
Nothing to change in your app.
|
|
815
|
+
|
|
810
816
|
## What's new in 0.41.1
|
|
811
817
|
|
|
812
818
|
**A chip in a computer app links to Athena, not to the app.** In an app a computer serves, Marathon hands the provider the app's own origin as its `appUrl`, so every asset and citation chip linked to `https://<app>/dashboard/spaces/…`, the app itself. Chips now link to the deployment's Athena frontend there (`https://staging-app.athenaintel.com/…` on staging), as the workbench's "Open in Athena" links already did. This matters most for a repository file citation, which 0.41.0 opens as its link. `athenaLinkAppUrl` is now exported from the URL helpers (still from the package root). An `appUrl` you configure that is not the page's own origin is used as configured.
|
|
@@ -18,6 +18,19 @@ function projectDeepAgentProtocol(state) {
|
|
|
18
18
|
clientVersion: runconfigContract.DEEP_AGENT_PROTOCOL_VERSION
|
|
19
19
|
};
|
|
20
20
|
}
|
|
21
|
+
const seedProtocolLanes = /* @__PURE__ */ new WeakSet();
|
|
22
|
+
function withSeedProtocolLane(state) {
|
|
23
|
+
const lane = state.protocol;
|
|
24
|
+
if (typeof lane !== "object" || lane === null) return state;
|
|
25
|
+
const seeded = { ...lane };
|
|
26
|
+
seedProtocolLanes.add(seeded);
|
|
27
|
+
return { ...state, protocol: seeded };
|
|
28
|
+
}
|
|
29
|
+
function isDeepAgentHostState(state) {
|
|
30
|
+
if (typeof state !== "object" || state === null) return false;
|
|
31
|
+
const lane = state[runconfigContract.DEEP_AGENT_PROTOCOL_STATE_KEY];
|
|
32
|
+
return typeof lane === "object" && lane !== null && readDeepAgentProtocol(state) !== null && !seedProtocolLanes.has(lane);
|
|
33
|
+
}
|
|
21
34
|
function withDeclaredProtocolVersion(headers) {
|
|
22
35
|
if (runconfigContract.DEEP_AGENT_PROTOCOL_VERSION_HEADER in headers) return headers;
|
|
23
36
|
return {
|
|
@@ -25,7 +38,9 @@ function withDeclaredProtocolVersion(headers) {
|
|
|
25
38
|
[runconfigContract.DEEP_AGENT_PROTOCOL_VERSION_HEADER]: String(runconfigContract.DEEP_AGENT_PROTOCOL_VERSION)
|
|
26
39
|
};
|
|
27
40
|
}
|
|
41
|
+
exports.isDeepAgentHostState = isDeepAgentHostState;
|
|
28
42
|
exports.projectDeepAgentProtocol = projectDeepAgentProtocol;
|
|
29
43
|
exports.readDeepAgentProtocol = readDeepAgentProtocol;
|
|
30
44
|
exports.withDeclaredProtocolVersion = withDeclaredProtocolVersion;
|
|
45
|
+
exports.withSeedProtocolLane = withSeedProtocolLane;
|
|
31
46
|
//# sourceMappingURL=protocol.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protocol.cjs","sources":["../../../../agent-runtime/src/protocol.ts"],"sourcesContent":["import {\n DEEP_AGENT_PROTOCOL_STATE_KEY,\n DEEP_AGENT_PROTOCOL_VERSION,\n DEEP_AGENT_PROTOCOL_VERSION_HEADER,\n} from './generated/runconfig-contract';\n\n/**\n * Wire-contract version declaration between the deep-agent statewire host and\n * this client build (the client half of agora's\n * `agora/graphs/athena_deep_agent/protocol_version.py`; upstream ask\n * assistant-ui/statewire #31506 would make this a library concern).\n *\n * - Declaration: {@link withDeclaredProtocolVersion} stamps the version this\n * build speaks (`DEEP_AGENT_PROTOCOL_VERSION`, generated from the Python\n * source of truth) onto the attach headers — they ride the first WS frame's\n * mandatory `headers` field / the SSE request headers, so no statewire\n * change is needed. The host records it for attach telemetry and\n * per-version behaviour selection only.\n * - Advertisement: the host publishes its own `version` under the `protocol`\n * state key in every attach snapshot; {@link readDeepAgentProtocol} /\n * {@link projectDeepAgentProtocol} read it.\n *\n * There is no minimum client version: the host refuses no command for the\n * version its client declared (or for declaring none), so nothing here\n * compares versions or gates a send. Hosts still publish a `minClientVersion`\n * key (the constant 1) for installed clients whose lane reader required it;\n * this reader ignores it.\n *\n * Skew-tolerant on both sides: an old server advertises nothing (project\n * `null`, gate nothing), and a malformed lane reads as absent — the\n * declaration must never brick a client that could otherwise talk.\n */\nexport interface DeepAgentWireProtocol {\n /** The wire-contract version the server speaks. */\n version: number;\n}\n\n/** The advertised-lane projection a host surface reads. */\nexport interface DeepAgentProtocolStatus {\n /** Server-advertised current contract version. */\n protocolVersion: number;\n /** The contract version THIS client build declares. */\n clientVersion: number;\n}\n\nconst isContractVersion = (value: unknown): value is number =>\n typeof value === 'number' && Number.isInteger(value) && value >= 1;\n\n/**\n * The server-advertised version lane off a raw statewire state, or `null`\n * while it is unreadable — pre-attach, a pre-negotiation server's snapshot\n * (no lane), or a malformed lane (tolerated as absent, never thrown on).\n */\nexport function readDeepAgentProtocol(state: unknown): DeepAgentWireProtocol | null {\n if (typeof state !== 'object' || state === null) return null;\n const lane = (state as Record<string, unknown>)[DEEP_AGENT_PROTOCOL_STATE_KEY];\n if (typeof lane !== 'object' || lane === null) return null;\n const { version } = lane as Record<string, unknown>;\n if (!isContractVersion(version)) return null;\n return { version };\n}\n\n/**\n * Project the advertised version for a host surface, or `null` while the\n * server has not advertised (see {@link readDeepAgentProtocol}). Pure and\n * selector-safe, mirroring `readSessionPersisted`.\n */\nexport function projectDeepAgentProtocol(state: unknown): DeepAgentProtocolStatus | null {\n const lane = readDeepAgentProtocol(state);\n if (lane === null) return null;\n return {\n protocolVersion: lane.version,\n clientVersion: DEEP_AGENT_PROTOCOL_VERSION,\n };\n}\n\n/**\n * Attach headers with this build's contract version declared. Applied by\n * `useDeepAgentThread` to every resolved header set, so all surfaces declare\n * without per-host wiring; an explicit entry (tests, forced overrides) wins.\n */\nexport function withDeclaredProtocolVersion(\n headers: Record<string, string>\n): Record<string, string> {\n if (DEEP_AGENT_PROTOCOL_VERSION_HEADER in headers) return headers;\n return {\n ...headers,\n [DEEP_AGENT_PROTOCOL_VERSION_HEADER]: String(DEEP_AGENT_PROTOCOL_VERSION),\n };\n}\n"],"names":["DEEP_AGENT_PROTOCOL_STATE_KEY","DEEP_AGENT_PROTOCOL_VERSION","DEEP_AGENT_PROTOCOL_VERSION_HEADER"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"protocol.cjs","sources":["../../../../agent-runtime/src/protocol.ts"],"sourcesContent":["import {\n DEEP_AGENT_PROTOCOL_STATE_KEY,\n DEEP_AGENT_PROTOCOL_VERSION,\n DEEP_AGENT_PROTOCOL_VERSION_HEADER,\n} from './generated/runconfig-contract';\nimport type { DeepAgentStreamValues } from './types';\n\n/**\n * Wire-contract version declaration between the deep-agent statewire host and\n * this client build (the client half of agora's\n * `agora/graphs/athena_deep_agent/protocol_version.py`; upstream ask\n * assistant-ui/statewire #31506 would make this a library concern).\n *\n * - Declaration: {@link withDeclaredProtocolVersion} stamps the version this\n * build speaks (`DEEP_AGENT_PROTOCOL_VERSION`, generated from the Python\n * source of truth) onto the attach headers — they ride the first WS frame's\n * mandatory `headers` field / the SSE request headers, so no statewire\n * change is needed. The host records it for attach telemetry and\n * per-version behaviour selection only.\n * - Advertisement: the host publishes its own `version` under the `protocol`\n * state key in every attach snapshot; {@link readDeepAgentProtocol} /\n * {@link projectDeepAgentProtocol} read it.\n *\n * There is no minimum client version: the host refuses no command for the\n * version its client declared (or for declaring none), so nothing here\n * compares versions or gates a send. Hosts still publish a `minClientVersion`\n * key (the constant 1) for installed clients whose lane reader required it;\n * this reader ignores it.\n *\n * Skew-tolerant on both sides: an old server advertises nothing (project\n * `null`, gate nothing), and a malformed lane reads as absent — the\n * declaration must never brick a client that could otherwise talk.\n */\nexport interface DeepAgentWireProtocol {\n /** The wire-contract version the server speaks. */\n version: number;\n}\n\n/** The advertised-lane projection a host surface reads. */\nexport interface DeepAgentProtocolStatus {\n /** Server-advertised current contract version. */\n protocolVersion: number;\n /** The contract version THIS client build declares. */\n clientVersion: number;\n}\n\nconst isContractVersion = (value: unknown): value is number =>\n typeof value === 'number' && Number.isInteger(value) && value >= 1;\n\n/**\n * The server-advertised version lane off a raw statewire state, or `null`\n * while it is unreadable — pre-attach, a pre-negotiation server's snapshot\n * (no lane), or a malformed lane (tolerated as absent, never thrown on).\n */\nexport function readDeepAgentProtocol(state: unknown): DeepAgentWireProtocol | null {\n if (typeof state !== 'object' || state === null) return null;\n const lane = (state as Record<string, unknown>)[DEEP_AGENT_PROTOCOL_STATE_KEY];\n if (typeof lane !== 'object' || lane === null) return null;\n const { version } = lane as Record<string, unknown>;\n if (!isContractVersion(version)) return null;\n return { version };\n}\n\n/**\n * Project the advertised version for a host surface, or `null` while the\n * server has not advertised (see {@link readDeepAgentProtocol}). Pure and\n * selector-safe, mirroring `readSessionPersisted`.\n */\nexport function projectDeepAgentProtocol(state: unknown): DeepAgentProtocolStatus | null {\n const lane = readDeepAgentProtocol(state);\n if (lane === null) return null;\n return {\n protocolVersion: lane.version,\n clientVersion: DEEP_AGENT_PROTOCOL_VERSION,\n };\n}\n\n/**\n * The protocol lanes seeds carry ({@link withSeedProtocolLane}), by identity.\n * Statewire's optimistic folds are copy-on-write, so every state folded over a\n * seed keeps its lane object, while a state the host sent never holds one\n * (each is parsed off the wire).\n */\nconst seedProtocolLanes = new WeakSet<object>();\n\n/**\n * `state` with a protocol lane of its own, remembered as a seed's — for the\n * remembered states a mount is seeded with (`toThreadSnapshotSeed`), whose\n * lanes are what the host sent an earlier attach. The lane is copied rather\n * than remembered in place, so a live attach still holding the original object\n * is never read as a seed.\n */\nexport function withSeedProtocolLane(state: DeepAgentStreamValues): DeepAgentStreamValues {\n const lane = state.protocol;\n if (typeof lane !== 'object' || lane === null) return state;\n const seeded = { ...lane };\n seedProtocolLanes.add(seeded);\n return { ...state, protocol: seeded };\n}\n\n/**\n * Whether `state` is one the host sent on this attach. The host advertises the\n * protocol lane in every attach snapshot and keeps it on every later frame;\n * the states a thread renders before its snapshot carry none (the placeholder\n * an existing thread loads with, and any optimistic fold over it) or a seed's\n * ({@link withSeedProtocolLane}).\n *\n * Decide anything about what the host holds — its config lane above all —\n * from these states only, never from the connection status: on a thread\n * mid-run the channel reports `connected` before the attach snapshot applies,\n * and a placeholder read as the host's says the thread has no config.\n *\n * A host predating the lane (2026-08-28) never answers true; the config lane\n * writes clients make (`config/patch`, 2026-09-05) came after it.\n */\nexport function isDeepAgentHostState(state: unknown): boolean {\n if (typeof state !== 'object' || state === null) return false;\n const lane = (state as Record<string, unknown>)[DEEP_AGENT_PROTOCOL_STATE_KEY];\n return (\n typeof lane === 'object' &&\n lane !== null &&\n readDeepAgentProtocol(state) !== null &&\n !seedProtocolLanes.has(lane)\n );\n}\n\n/**\n * Attach headers with this build's contract version declared. Applied by\n * `useDeepAgentThread` to every resolved header set, so all surfaces declare\n * without per-host wiring; an explicit entry (tests, forced overrides) wins.\n */\nexport function withDeclaredProtocolVersion(\n headers: Record<string, string>\n): Record<string, string> {\n if (DEEP_AGENT_PROTOCOL_VERSION_HEADER in headers) return headers;\n return {\n ...headers,\n [DEEP_AGENT_PROTOCOL_VERSION_HEADER]: String(DEEP_AGENT_PROTOCOL_VERSION),\n };\n}\n"],"names":["DEEP_AGENT_PROTOCOL_STATE_KEY","DEEP_AGENT_PROTOCOL_VERSION","DEEP_AGENT_PROTOCOL_VERSION_HEADER"],"mappings":";;;AA8CA,MAAM,oBAAoB,CAAC,UACzB,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,KAAK,SAAS;AAO5D,SAAS,sBAAsB,OAA8C;AAClF,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,OAAQ,MAAkCA,+CAA6B;AAC7E,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,EAAE,YAAY;AACpB,MAAI,CAAC,kBAAkB,OAAO,EAAG,QAAO;AACxC,SAAO,EAAE,QAAA;AACX;AAOO,SAAS,yBAAyB,OAAgD;AACvF,QAAM,OAAO,sBAAsB,KAAK;AACxC,MAAI,SAAS,KAAM,QAAO;AAC1B,SAAO;AAAA,IACL,iBAAiB,KAAK;AAAA,IACtB,eAAeC,kBAAAA;AAAAA,EAAA;AAEnB;AAQA,MAAM,wCAAwB,QAAA;AASvB,SAAS,qBAAqB,OAAqD;AACxF,QAAM,OAAO,MAAM;AACnB,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,SAAS,EAAE,GAAG,KAAA;AACpB,oBAAkB,IAAI,MAAM;AAC5B,SAAO,EAAE,GAAG,OAAO,UAAU,OAAA;AAC/B;AAiBO,SAAS,qBAAqB,OAAyB;AAC5D,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,OAAQ,MAAkCD,+CAA6B;AAC7E,SACE,OAAO,SAAS,YAChB,SAAS,QACT,sBAAsB,KAAK,MAAM,QACjC,CAAC,kBAAkB,IAAI,IAAI;AAE/B;AAOO,SAAS,4BACd,SACwB;AACxB,MAAIE,kBAAAA,sCAAsC,QAAS,QAAO;AAC1D,SAAO;AAAA,IACL,GAAG;AAAA,IACH,CAACA,kBAAAA,kCAAkC,GAAG,OAAOD,kBAAAA,2BAA2B;AAAA,EAAA;AAE5E;;;;;;"}
|
|
@@ -16,6 +16,19 @@ function projectDeepAgentProtocol(state) {
|
|
|
16
16
|
clientVersion: DEEP_AGENT_PROTOCOL_VERSION
|
|
17
17
|
};
|
|
18
18
|
}
|
|
19
|
+
const seedProtocolLanes = /* @__PURE__ */ new WeakSet();
|
|
20
|
+
function withSeedProtocolLane(state) {
|
|
21
|
+
const lane = state.protocol;
|
|
22
|
+
if (typeof lane !== "object" || lane === null) return state;
|
|
23
|
+
const seeded = { ...lane };
|
|
24
|
+
seedProtocolLanes.add(seeded);
|
|
25
|
+
return { ...state, protocol: seeded };
|
|
26
|
+
}
|
|
27
|
+
function isDeepAgentHostState(state) {
|
|
28
|
+
if (typeof state !== "object" || state === null) return false;
|
|
29
|
+
const lane = state[DEEP_AGENT_PROTOCOL_STATE_KEY];
|
|
30
|
+
return typeof lane === "object" && lane !== null && readDeepAgentProtocol(state) !== null && !seedProtocolLanes.has(lane);
|
|
31
|
+
}
|
|
19
32
|
function withDeclaredProtocolVersion(headers) {
|
|
20
33
|
if (DEEP_AGENT_PROTOCOL_VERSION_HEADER in headers) return headers;
|
|
21
34
|
return {
|
|
@@ -24,8 +37,10 @@ function withDeclaredProtocolVersion(headers) {
|
|
|
24
37
|
};
|
|
25
38
|
}
|
|
26
39
|
export {
|
|
40
|
+
isDeepAgentHostState,
|
|
27
41
|
projectDeepAgentProtocol,
|
|
28
42
|
readDeepAgentProtocol,
|
|
29
|
-
withDeclaredProtocolVersion
|
|
43
|
+
withDeclaredProtocolVersion,
|
|
44
|
+
withSeedProtocolLane
|
|
30
45
|
};
|
|
31
46
|
//# sourceMappingURL=protocol.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protocol.js","sources":["../../../../agent-runtime/src/protocol.ts"],"sourcesContent":["import {\n DEEP_AGENT_PROTOCOL_STATE_KEY,\n DEEP_AGENT_PROTOCOL_VERSION,\n DEEP_AGENT_PROTOCOL_VERSION_HEADER,\n} from './generated/runconfig-contract';\n\n/**\n * Wire-contract version declaration between the deep-agent statewire host and\n * this client build (the client half of agora's\n * `agora/graphs/athena_deep_agent/protocol_version.py`; upstream ask\n * assistant-ui/statewire #31506 would make this a library concern).\n *\n * - Declaration: {@link withDeclaredProtocolVersion} stamps the version this\n * build speaks (`DEEP_AGENT_PROTOCOL_VERSION`, generated from the Python\n * source of truth) onto the attach headers — they ride the first WS frame's\n * mandatory `headers` field / the SSE request headers, so no statewire\n * change is needed. The host records it for attach telemetry and\n * per-version behaviour selection only.\n * - Advertisement: the host publishes its own `version` under the `protocol`\n * state key in every attach snapshot; {@link readDeepAgentProtocol} /\n * {@link projectDeepAgentProtocol} read it.\n *\n * There is no minimum client version: the host refuses no command for the\n * version its client declared (or for declaring none), so nothing here\n * compares versions or gates a send. Hosts still publish a `minClientVersion`\n * key (the constant 1) for installed clients whose lane reader required it;\n * this reader ignores it.\n *\n * Skew-tolerant on both sides: an old server advertises nothing (project\n * `null`, gate nothing), and a malformed lane reads as absent — the\n * declaration must never brick a client that could otherwise talk.\n */\nexport interface DeepAgentWireProtocol {\n /** The wire-contract version the server speaks. */\n version: number;\n}\n\n/** The advertised-lane projection a host surface reads. */\nexport interface DeepAgentProtocolStatus {\n /** Server-advertised current contract version. */\n protocolVersion: number;\n /** The contract version THIS client build declares. */\n clientVersion: number;\n}\n\nconst isContractVersion = (value: unknown): value is number =>\n typeof value === 'number' && Number.isInteger(value) && value >= 1;\n\n/**\n * The server-advertised version lane off a raw statewire state, or `null`\n * while it is unreadable — pre-attach, a pre-negotiation server's snapshot\n * (no lane), or a malformed lane (tolerated as absent, never thrown on).\n */\nexport function readDeepAgentProtocol(state: unknown): DeepAgentWireProtocol | null {\n if (typeof state !== 'object' || state === null) return null;\n const lane = (state as Record<string, unknown>)[DEEP_AGENT_PROTOCOL_STATE_KEY];\n if (typeof lane !== 'object' || lane === null) return null;\n const { version } = lane as Record<string, unknown>;\n if (!isContractVersion(version)) return null;\n return { version };\n}\n\n/**\n * Project the advertised version for a host surface, or `null` while the\n * server has not advertised (see {@link readDeepAgentProtocol}). Pure and\n * selector-safe, mirroring `readSessionPersisted`.\n */\nexport function projectDeepAgentProtocol(state: unknown): DeepAgentProtocolStatus | null {\n const lane = readDeepAgentProtocol(state);\n if (lane === null) return null;\n return {\n protocolVersion: lane.version,\n clientVersion: DEEP_AGENT_PROTOCOL_VERSION,\n };\n}\n\n/**\n * Attach headers with this build's contract version declared. Applied by\n * `useDeepAgentThread` to every resolved header set, so all surfaces declare\n * without per-host wiring; an explicit entry (tests, forced overrides) wins.\n */\nexport function withDeclaredProtocolVersion(\n headers: Record<string, string>\n): Record<string, string> {\n if (DEEP_AGENT_PROTOCOL_VERSION_HEADER in headers) return headers;\n return {\n ...headers,\n [DEEP_AGENT_PROTOCOL_VERSION_HEADER]: String(DEEP_AGENT_PROTOCOL_VERSION),\n };\n}\n"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"protocol.js","sources":["../../../../agent-runtime/src/protocol.ts"],"sourcesContent":["import {\n DEEP_AGENT_PROTOCOL_STATE_KEY,\n DEEP_AGENT_PROTOCOL_VERSION,\n DEEP_AGENT_PROTOCOL_VERSION_HEADER,\n} from './generated/runconfig-contract';\nimport type { DeepAgentStreamValues } from './types';\n\n/**\n * Wire-contract version declaration between the deep-agent statewire host and\n * this client build (the client half of agora's\n * `agora/graphs/athena_deep_agent/protocol_version.py`; upstream ask\n * assistant-ui/statewire #31506 would make this a library concern).\n *\n * - Declaration: {@link withDeclaredProtocolVersion} stamps the version this\n * build speaks (`DEEP_AGENT_PROTOCOL_VERSION`, generated from the Python\n * source of truth) onto the attach headers — they ride the first WS frame's\n * mandatory `headers` field / the SSE request headers, so no statewire\n * change is needed. The host records it for attach telemetry and\n * per-version behaviour selection only.\n * - Advertisement: the host publishes its own `version` under the `protocol`\n * state key in every attach snapshot; {@link readDeepAgentProtocol} /\n * {@link projectDeepAgentProtocol} read it.\n *\n * There is no minimum client version: the host refuses no command for the\n * version its client declared (or for declaring none), so nothing here\n * compares versions or gates a send. Hosts still publish a `minClientVersion`\n * key (the constant 1) for installed clients whose lane reader required it;\n * this reader ignores it.\n *\n * Skew-tolerant on both sides: an old server advertises nothing (project\n * `null`, gate nothing), and a malformed lane reads as absent — the\n * declaration must never brick a client that could otherwise talk.\n */\nexport interface DeepAgentWireProtocol {\n /** The wire-contract version the server speaks. */\n version: number;\n}\n\n/** The advertised-lane projection a host surface reads. */\nexport interface DeepAgentProtocolStatus {\n /** Server-advertised current contract version. */\n protocolVersion: number;\n /** The contract version THIS client build declares. */\n clientVersion: number;\n}\n\nconst isContractVersion = (value: unknown): value is number =>\n typeof value === 'number' && Number.isInteger(value) && value >= 1;\n\n/**\n * The server-advertised version lane off a raw statewire state, or `null`\n * while it is unreadable — pre-attach, a pre-negotiation server's snapshot\n * (no lane), or a malformed lane (tolerated as absent, never thrown on).\n */\nexport function readDeepAgentProtocol(state: unknown): DeepAgentWireProtocol | null {\n if (typeof state !== 'object' || state === null) return null;\n const lane = (state as Record<string, unknown>)[DEEP_AGENT_PROTOCOL_STATE_KEY];\n if (typeof lane !== 'object' || lane === null) return null;\n const { version } = lane as Record<string, unknown>;\n if (!isContractVersion(version)) return null;\n return { version };\n}\n\n/**\n * Project the advertised version for a host surface, or `null` while the\n * server has not advertised (see {@link readDeepAgentProtocol}). Pure and\n * selector-safe, mirroring `readSessionPersisted`.\n */\nexport function projectDeepAgentProtocol(state: unknown): DeepAgentProtocolStatus | null {\n const lane = readDeepAgentProtocol(state);\n if (lane === null) return null;\n return {\n protocolVersion: lane.version,\n clientVersion: DEEP_AGENT_PROTOCOL_VERSION,\n };\n}\n\n/**\n * The protocol lanes seeds carry ({@link withSeedProtocolLane}), by identity.\n * Statewire's optimistic folds are copy-on-write, so every state folded over a\n * seed keeps its lane object, while a state the host sent never holds one\n * (each is parsed off the wire).\n */\nconst seedProtocolLanes = new WeakSet<object>();\n\n/**\n * `state` with a protocol lane of its own, remembered as a seed's — for the\n * remembered states a mount is seeded with (`toThreadSnapshotSeed`), whose\n * lanes are what the host sent an earlier attach. The lane is copied rather\n * than remembered in place, so a live attach still holding the original object\n * is never read as a seed.\n */\nexport function withSeedProtocolLane(state: DeepAgentStreamValues): DeepAgentStreamValues {\n const lane = state.protocol;\n if (typeof lane !== 'object' || lane === null) return state;\n const seeded = { ...lane };\n seedProtocolLanes.add(seeded);\n return { ...state, protocol: seeded };\n}\n\n/**\n * Whether `state` is one the host sent on this attach. The host advertises the\n * protocol lane in every attach snapshot and keeps it on every later frame;\n * the states a thread renders before its snapshot carry none (the placeholder\n * an existing thread loads with, and any optimistic fold over it) or a seed's\n * ({@link withSeedProtocolLane}).\n *\n * Decide anything about what the host holds — its config lane above all —\n * from these states only, never from the connection status: on a thread\n * mid-run the channel reports `connected` before the attach snapshot applies,\n * and a placeholder read as the host's says the thread has no config.\n *\n * A host predating the lane (2026-08-28) never answers true; the config lane\n * writes clients make (`config/patch`, 2026-09-05) came after it.\n */\nexport function isDeepAgentHostState(state: unknown): boolean {\n if (typeof state !== 'object' || state === null) return false;\n const lane = (state as Record<string, unknown>)[DEEP_AGENT_PROTOCOL_STATE_KEY];\n return (\n typeof lane === 'object' &&\n lane !== null &&\n readDeepAgentProtocol(state) !== null &&\n !seedProtocolLanes.has(lane)\n );\n}\n\n/**\n * Attach headers with this build's contract version declared. Applied by\n * `useDeepAgentThread` to every resolved header set, so all surfaces declare\n * without per-host wiring; an explicit entry (tests, forced overrides) wins.\n */\nexport function withDeclaredProtocolVersion(\n headers: Record<string, string>\n): Record<string, string> {\n if (DEEP_AGENT_PROTOCOL_VERSION_HEADER in headers) return headers;\n return {\n ...headers,\n [DEEP_AGENT_PROTOCOL_VERSION_HEADER]: String(DEEP_AGENT_PROTOCOL_VERSION),\n };\n}\n"],"names":[],"mappings":";AA8CA,MAAM,oBAAoB,CAAC,UACzB,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,KAAK,SAAS;AAO5D,SAAS,sBAAsB,OAA8C;AAClF,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,OAAQ,MAAkC,6BAA6B;AAC7E,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,EAAE,YAAY;AACpB,MAAI,CAAC,kBAAkB,OAAO,EAAG,QAAO;AACxC,SAAO,EAAE,QAAA;AACX;AAOO,SAAS,yBAAyB,OAAgD;AACvF,QAAM,OAAO,sBAAsB,KAAK;AACxC,MAAI,SAAS,KAAM,QAAO;AAC1B,SAAO;AAAA,IACL,iBAAiB,KAAK;AAAA,IACtB,eAAe;AAAA,EAAA;AAEnB;AAQA,MAAM,wCAAwB,QAAA;AASvB,SAAS,qBAAqB,OAAqD;AACxF,QAAM,OAAO,MAAM;AACnB,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,SAAS,EAAE,GAAG,KAAA;AACpB,oBAAkB,IAAI,MAAM;AAC5B,SAAO,EAAE,GAAG,OAAO,UAAU,OAAA;AAC/B;AAiBO,SAAS,qBAAqB,OAAyB;AAC5D,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,OAAQ,MAAkC,6BAA6B;AAC7E,SACE,OAAO,SAAS,YAChB,SAAS,QACT,sBAAsB,KAAK,MAAM,QACjC,CAAC,kBAAkB,IAAI,IAAI;AAE/B;AAOO,SAAS,4BACd,SACwB;AACxB,MAAI,sCAAsC,QAAS,QAAO;AAC1D,SAAO;AAAA,IACL,GAAG;AAAA,IACH,CAAC,kCAAkC,GAAG,OAAO,2BAA2B;AAAA,EAAA;AAE5E;"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const protocol = require("./protocol.cjs");
|
|
3
4
|
const DEFAULT_MAX_THREADS = 30;
|
|
4
5
|
const DEFAULT_MAX_AGE_MS = 60 * 60 * 1e3;
|
|
5
6
|
function createDeepAgentThreadSnapshotCache(options = {}) {
|
|
@@ -70,7 +71,7 @@ function toThreadSnapshotSeed(state) {
|
|
|
70
71
|
outOfBandRunActive: _outOfBandRunActive,
|
|
71
72
|
...rest
|
|
72
73
|
} = state;
|
|
73
|
-
return { ...rest, runs: seedRunsLane(state.runs) };
|
|
74
|
+
return protocol.withSeedProtocolLane({ ...rest, runs: seedRunsLane(state.runs) });
|
|
74
75
|
}
|
|
75
76
|
function seedRunsLane(runs) {
|
|
76
77
|
const live = runs == null ? void 0 : runs[0];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-snapshot-cache.cjs","sources":["../../../../agent-runtime/src/thread-snapshot-cache.ts"],"sourcesContent":["import type { DeepAgentStreamValues } from './types';\n\n/**\n * Per-tab LRU of the last wire state seen per thread, so a switch back to a\n * recently-visited thread can mount with that snapshot instead of an empty\n * \"loading\" state (see `UseDeepAgentThreadOptions.snapshotCache`). Entries are\n * references into states the wire already produced — remembering is O(1) and\n * copies nothing; the bound is `maxThreads` retained states.\n */\nexport interface DeepAgentThreadSnapshotCache {\n /** Record the latest hydrated wire state for a thread. */\n remember(threadId: string, state: DeepAgentStreamValues): void;\n /** The freshest remembered state for a thread, or `undefined` when none is\n * held or the entry aged out. */\n take(threadId: string): DeepAgentStreamValues | undefined;\n /**\n * Drop a single thread's entry. Called when the server refuses\n * authorization for the thread — a refused thread must not warm-paint on\n * its next mount.\n */\n forget(threadId: string): void;\n /**\n * Drop every entry. Called when the acting identity changes — a snapshot\n * captured under one account must never seed a mount under another.\n */\n clear(): void;\n /**\n * Whether a fresh entry is held for the thread, without consuming or\n * touching it. Hosts read it at selection time to decide whether the switch\n * can paint from a seed (no loading treatment) or must cover the attach\n * wait. Optional so hand-rolled caches keep type-checking; the built-in\n * cache implements it.\n */\n peek?(threadId: string): boolean;\n}\n\n/** A write observed on the cache — the durable-mirror seam (see `onChange`). */\nexport type DeepAgentThreadSnapshotCacheChange =\n | { type: 'remember'; threadId: string; state: DeepAgentStreamValues; at: number }\n | { type: 'forget'; threadId: string }\n | { type: 'clear' };\n\nexport interface DeepAgentThreadSnapshotCacheOptions {\n /** Threads retained; the least-recently written entry evicts beyond this. */\n maxThreads?: number;\n /**\n * Entries older than this are dropped at read time. The seed's value is\n * \"the thread you just left\" — a snapshot from long ago is more likely to\n * flash content the server has since rewritten than to save a paint.\n */\n maxAgeMs?: number;\n /**\n * Observer of every write (`remember`, `forget`, `clear`). Hosts mirror\n * entries into durable storage from here so a reload can seed too; the\n * observer is never invoked for `restore`, which re-admits mirrored entries.\n * Exceptions are swallowed — a mirror fault must not break the wire path.\n */\n onChange?: (change: DeepAgentThreadSnapshotCacheChange) => void;\n /** Injectable clock (tests). */\n now?: () => number;\n}\n\n/** The built-in cache: the host contract plus the durable-mirror re-admission. */\nexport interface CreatedDeepAgentThreadSnapshotCache extends DeepAgentThreadSnapshotCache {\n peek(threadId: string): boolean;\n /**\n * Re-admit an entry captured earlier — a mirrored snapshot after a reload —\n * under its ORIGINAL capture time, so the age bound still applies. Never\n * displaces a fresher in-memory entry and never notifies `onChange`.\n */\n restore(threadId: string, state: DeepAgentStreamValues, at: number): void;\n}\n\nconst DEFAULT_MAX_THREADS = 30;\nconst DEFAULT_MAX_AGE_MS = 60 * 60 * 1000;\n\nexport function createDeepAgentThreadSnapshotCache(\n options: DeepAgentThreadSnapshotCacheOptions = {}\n): CreatedDeepAgentThreadSnapshotCache {\n const maxThreads = options.maxThreads ?? DEFAULT_MAX_THREADS;\n const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n const now = options.now ?? (() => Date.now());\n const notify = (change: DeepAgentThreadSnapshotCacheChange): void => {\n try {\n options.onChange?.(change);\n } catch {\n // The mirror is best-effort; the in-memory cache stays authoritative.\n }\n };\n // Map iteration order is insertion order; delete-then-set on every write\n // keeps the first key the least-recently written.\n const entries = new Map<string, { state: DeepAgentStreamValues; at: number }>();\n const evict = (): void => {\n while (entries.size > maxThreads) {\n const oldest = entries.keys().next().value;\n if (oldest === undefined) break;\n entries.delete(oldest);\n }\n };\n const fresh = (threadId: string): { state: DeepAgentStreamValues; at: number } | undefined => {\n const entry = entries.get(threadId);\n if (!entry) return undefined;\n if (now() - entry.at > maxAgeMs) {\n entries.delete(threadId);\n return undefined;\n }\n return entry;\n };\n return {\n remember(threadId, state) {\n const at = now();\n entries.delete(threadId);\n entries.set(threadId, { state, at });\n evict();\n notify({ type: 'remember', threadId, state, at });\n },\n take(threadId) {\n return fresh(threadId)?.state;\n },\n peek(threadId) {\n return fresh(threadId) !== undefined;\n },\n restore(threadId, state, at) {\n if (now() - at > maxAgeMs) return;\n const existing = entries.get(threadId);\n if (existing && existing.at >= at) return;\n entries.delete(threadId);\n entries.set(threadId, { state, at });\n evict();\n },\n forget(threadId) {\n entries.delete(threadId);\n notify({ type: 'forget', threadId });\n },\n clear() {\n entries.clear();\n notify({ type: 'clear' });\n },\n };\n}\n\n/**\n * Shape a remembered wire state for use as a mount's `initialState`.\n *\n * Messages/todos and the other app-owned keys seed as captured. The run lane\n * seeds by what the user left: a thread whose run was `running` when the\n * snapshot was taken seeds a running entry (see {@link seedRunsLane}) so the\n * switch back reads Running with a Stop control on its first frame — the same\n * frame `runs: []` would render as \"ready\" with a Send button over a thread the\n * server is still mid-run on. Every other live-lifecycle lane normalizes to\n * resting: a seeded input request could collect a decision the server may have\n * already resolved, so an `input-required` entry seeds as no run at all.\n * `__interrupt__` is dropped for the same reason, and so are `ptc_subagents`\n * (the live in-eval dispatch lane — a seeded \"running\" dispatch card under a\n * resting thread would render active with no eval behind it) and\n * `outOfBandRunActive` (the host's out-of-band-run-in-progress flag — seeding a\n * finished run's `true` would hide the composer until the attach corrected\n * it). Durable thread properties (`runConfig`, `sessionPersisted`, …) seed as\n * captured; the attach snapshot then replaces the whole seed.\n */\nexport function toThreadSnapshotSeed(state: DeepAgentStreamValues): DeepAgentStreamValues {\n const {\n __interrupt__: _interrupt,\n ptc_subagents: _ptcSubagents,\n outOfBandRunActive: _outOfBandRunActive,\n ...rest\n } = state;\n return { ...rest, runs: seedRunsLane(state.runs) };\n}\n\n/**\n * The run entries a seed carries.\n *\n * Only a `running` entry survives, and only its replicated identity and its\n * durable lanes: `runId` (the target of a Stop sent during the attach\n * round-trip — the live run's id if it is still running, and a refused stop\n * if it finished meanwhile), `epoch` (rides that Stop so a replayed stop cannot\n * end a later leg) and the `queue`/`steerQueue` entries (server lanes the tray\n * renders). The in-flight records rest until the snapshot: `dispatching` and\n * `nextDispatch` are batches the materializer would re-apply onto messages\n * that already contain them, `stopping` is a rewind the host may have\n * finished, `inputRequests` is a parked decision, and `error` is a failure the\n * next user run clears. An entry in any other status — `stopped`, `error`,\n * `input-required` — seeds as no run.\n */\nfunction seedRunsLane(\n runs: DeepAgentStreamValues['runs']\n): NonNullable<DeepAgentStreamValues['runs']> {\n const live = runs?.[0];\n if (live === undefined || live.status !== 'running') return [];\n return [\n {\n runId: live.runId,\n status: 'running',\n queue: live.queue,\n steerQueue: live.steerQueue,\n ...(live.epoch !== undefined && { epoch: live.epoch }),\n },\n ];\n}\n"],"names":[],"mappings":";;AAyEA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB,K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EAAE,OAAO,IAAI;AACnC,YAAA;AAAA,IACF;AAAA,IACA,OAAO,UAAU;AACf,cAAQ,OAAO,QAAQ;AACvB,aAAO,EAAE,MAAM,UAAU,SAAA,CAAU;AAAA,IACrC;AAAA,IACA,QAAQ;AACN,cAAQ,MAAA;AACR,aAAO,EAAE,MAAM,SAAS;AAAA,IAC1B;AAAA,EAAA;AAEJ;AAqBO,SAAS,qBAAqB,OAAqD;AACxF,QAAM;AAAA,IACJ,eAAe;AAAA,IACf,eAAe;AAAA,IACf,oBAAoB;AAAA,IACpB,GAAG;AAAA,EAAA,IACD;AACJ,SAAO,EAAE,GAAG,MAAM,MAAM,aAAa,MAAM,IAAI,EAAA;AACjD;AAiBA,SAAS,aACP,MAC4C;AAC5C,QAAM,OAAO,6BAAO;AACpB,MAAI,SAAS,UAAa,KAAK,WAAW,kBAAkB,CAAA;AAC5D,SAAO;AAAA,IACL;AAAA,MACE,OAAO,KAAK;AAAA,MACZ,QAAQ;AAAA,MACR,OAAO,KAAK;AAAA,MACZ,YAAY,KAAK;AAAA,MACjB,GAAI,KAAK,UAAU,UAAa,EAAE,OAAO,KAAK,MAAA;AAAA,IAAM;AAAA,EACtD;AAEJ;;;"}
|
|
1
|
+
{"version":3,"file":"thread-snapshot-cache.cjs","sources":["../../../../agent-runtime/src/thread-snapshot-cache.ts"],"sourcesContent":["import { withSeedProtocolLane } from './protocol';\nimport type { DeepAgentStreamValues } from './types';\n\n/**\n * Per-tab LRU of the last wire state seen per thread, so a switch back to a\n * recently-visited thread can mount with that snapshot instead of an empty\n * \"loading\" state (see `UseDeepAgentThreadOptions.snapshotCache`). Entries are\n * references into states the wire already produced — remembering is O(1) and\n * copies nothing; the bound is `maxThreads` retained states.\n */\nexport interface DeepAgentThreadSnapshotCache {\n /** Record the latest hydrated wire state for a thread. */\n remember(threadId: string, state: DeepAgentStreamValues): void;\n /** The freshest remembered state for a thread, or `undefined` when none is\n * held or the entry aged out. */\n take(threadId: string): DeepAgentStreamValues | undefined;\n /**\n * Drop a single thread's entry. Called when the server refuses\n * authorization for the thread — a refused thread must not warm-paint on\n * its next mount.\n */\n forget(threadId: string): void;\n /**\n * Drop every entry. Called when the acting identity changes — a snapshot\n * captured under one account must never seed a mount under another.\n */\n clear(): void;\n /**\n * Whether a fresh entry is held for the thread, without consuming or\n * touching it. Hosts read it at selection time to decide whether the switch\n * can paint from a seed (no loading treatment) or must cover the attach\n * wait. Optional so hand-rolled caches keep type-checking; the built-in\n * cache implements it.\n */\n peek?(threadId: string): boolean;\n}\n\n/** A write observed on the cache — the durable-mirror seam (see `onChange`). */\nexport type DeepAgentThreadSnapshotCacheChange =\n | { type: 'remember'; threadId: string; state: DeepAgentStreamValues; at: number }\n | { type: 'forget'; threadId: string }\n | { type: 'clear' };\n\nexport interface DeepAgentThreadSnapshotCacheOptions {\n /** Threads retained; the least-recently written entry evicts beyond this. */\n maxThreads?: number;\n /**\n * Entries older than this are dropped at read time. The seed's value is\n * \"the thread you just left\" — a snapshot from long ago is more likely to\n * flash content the server has since rewritten than to save a paint.\n */\n maxAgeMs?: number;\n /**\n * Observer of every write (`remember`, `forget`, `clear`). Hosts mirror\n * entries into durable storage from here so a reload can seed too; the\n * observer is never invoked for `restore`, which re-admits mirrored entries.\n * Exceptions are swallowed — a mirror fault must not break the wire path.\n */\n onChange?: (change: DeepAgentThreadSnapshotCacheChange) => void;\n /** Injectable clock (tests). */\n now?: () => number;\n}\n\n/** The built-in cache: the host contract plus the durable-mirror re-admission. */\nexport interface CreatedDeepAgentThreadSnapshotCache extends DeepAgentThreadSnapshotCache {\n peek(threadId: string): boolean;\n /**\n * Re-admit an entry captured earlier — a mirrored snapshot after a reload —\n * under its ORIGINAL capture time, so the age bound still applies. Never\n * displaces a fresher in-memory entry and never notifies `onChange`.\n */\n restore(threadId: string, state: DeepAgentStreamValues, at: number): void;\n}\n\nconst DEFAULT_MAX_THREADS = 30;\nconst DEFAULT_MAX_AGE_MS = 60 * 60 * 1000;\n\nexport function createDeepAgentThreadSnapshotCache(\n options: DeepAgentThreadSnapshotCacheOptions = {}\n): CreatedDeepAgentThreadSnapshotCache {\n const maxThreads = options.maxThreads ?? DEFAULT_MAX_THREADS;\n const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n const now = options.now ?? (() => Date.now());\n const notify = (change: DeepAgentThreadSnapshotCacheChange): void => {\n try {\n options.onChange?.(change);\n } catch {\n // The mirror is best-effort; the in-memory cache stays authoritative.\n }\n };\n // Map iteration order is insertion order; delete-then-set on every write\n // keeps the first key the least-recently written.\n const entries = new Map<string, { state: DeepAgentStreamValues; at: number }>();\n const evict = (): void => {\n while (entries.size > maxThreads) {\n const oldest = entries.keys().next().value;\n if (oldest === undefined) break;\n entries.delete(oldest);\n }\n };\n const fresh = (threadId: string): { state: DeepAgentStreamValues; at: number } | undefined => {\n const entry = entries.get(threadId);\n if (!entry) return undefined;\n if (now() - entry.at > maxAgeMs) {\n entries.delete(threadId);\n return undefined;\n }\n return entry;\n };\n return {\n remember(threadId, state) {\n const at = now();\n entries.delete(threadId);\n entries.set(threadId, { state, at });\n evict();\n notify({ type: 'remember', threadId, state, at });\n },\n take(threadId) {\n return fresh(threadId)?.state;\n },\n peek(threadId) {\n return fresh(threadId) !== undefined;\n },\n restore(threadId, state, at) {\n if (now() - at > maxAgeMs) return;\n const existing = entries.get(threadId);\n if (existing && existing.at >= at) return;\n entries.delete(threadId);\n entries.set(threadId, { state, at });\n evict();\n },\n forget(threadId) {\n entries.delete(threadId);\n notify({ type: 'forget', threadId });\n },\n clear() {\n entries.clear();\n notify({ type: 'clear' });\n },\n };\n}\n\n/**\n * Shape a remembered wire state for use as a mount's `initialState`.\n *\n * Messages/todos and the other app-owned keys seed as captured. The run lane\n * seeds by what the user left: a thread whose run was `running` when the\n * snapshot was taken seeds a running entry (see {@link seedRunsLane}) so the\n * switch back reads Running with a Stop control on its first frame — the same\n * frame `runs: []` would render as \"ready\" with a Send button over a thread the\n * server is still mid-run on. Every other live-lifecycle lane normalizes to\n * resting: a seeded input request could collect a decision the server may have\n * already resolved, so an `input-required` entry seeds as no run at all.\n * `__interrupt__` is dropped for the same reason, and so are `ptc_subagents`\n * (the live in-eval dispatch lane — a seeded \"running\" dispatch card under a\n * resting thread would render active with no eval behind it) and\n * `outOfBandRunActive` (the host's out-of-band-run-in-progress flag — seeding a\n * finished run's `true` would hide the composer until the attach corrected\n * it). Durable thread properties (`runConfig`, `config`, `sessionPersisted`, …)\n * seed as captured; the attach snapshot then replaces the whole seed. The\n * protocol lane seeds as a seed's own copy (`withSeedProtocolLane`), so\n * `isDeepAgentHostState` never reads the seed, or a state folded over it, as\n * what the host holds now.\n */\nexport function toThreadSnapshotSeed(state: DeepAgentStreamValues): DeepAgentStreamValues {\n const {\n __interrupt__: _interrupt,\n ptc_subagents: _ptcSubagents,\n outOfBandRunActive: _outOfBandRunActive,\n ...rest\n } = state;\n return withSeedProtocolLane({ ...rest, runs: seedRunsLane(state.runs) });\n}\n\n/**\n * The run entries a seed carries.\n *\n * Only a `running` entry survives, and only its replicated identity and its\n * durable lanes: `runId` (the target of a Stop sent during the attach\n * round-trip — the live run's id if it is still running, and a refused stop\n * if it finished meanwhile), `epoch` (rides that Stop so a replayed stop cannot\n * end a later leg) and the `queue`/`steerQueue` entries (server lanes the tray\n * renders). The in-flight records rest until the snapshot: `dispatching` and\n * `nextDispatch` are batches the materializer would re-apply onto messages\n * that already contain them, `stopping` is a rewind the host may have\n * finished, `inputRequests` is a parked decision, and `error` is a failure the\n * next user run clears. An entry in any other status — `stopped`, `error`,\n * `input-required` — seeds as no run.\n */\nfunction seedRunsLane(\n runs: DeepAgentStreamValues['runs']\n): NonNullable<DeepAgentStreamValues['runs']> {\n const live = runs?.[0];\n if (live === undefined || live.status !== 'running') return [];\n return [\n {\n runId: live.runId,\n status: 'running',\n queue: live.queue,\n steerQueue: live.steerQueue,\n ...(live.epoch !== undefined && { epoch: live.epoch }),\n },\n ];\n}\n"],"names":["withSeedProtocolLane"],"mapp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ACnC,cAAQ,OAAO,QAAQ;AACvB,cAAQ,IAAI,UAAU,EAAE,OAAO,IAAI;AACnC,YAAA;AAAA,IACF;AAAA,IACA,OAAO,UAAU;AACf,cAAQ,OAAO,QAAQ;AACvB,aAAO,EAAE,MAAM,UAAU,SAAA,CAAU;AAAA,IACrC;AAAA,IACA,QAAQ;AACN,cAAQ,MAAA;AACR,aAAO,EAAE,MAAM,SAAS;AAAA,IAC1B;AAAA,EAAA;AAEJ;AAwBO,SAAS,qBAAqB,OAAqD;AACxF,QAAM;AAAA,IACJ,eAAe;AAAA,IACf,eAAe;AAAA,IACf,oBAAoB;AAAA,IACpB,GAAG;AAAA,EAAA,IACD;AACJ,SAAOA,SAAAA,qBAAqB,EAAE,GAAG,MAAM,MAAM,aAAa,MAAM,IAAI,GAAG;AACzE;AAiBA,SAAS,aACP,MAC4C;AAC5C,QAAM,OAAO,6BAAO;AACpB,MAAI,SAAS,UAAa,KAAK,WAAW,kBAAkB,CAAA;AAC5D,SAAO;AAAA,IACL;AAAA,MACE,OAAO,KAAK;AAAA,MACZ,QAAQ;AAAA,MACR,OAAO,KAAK;AAAA,MACZ,YAAY,KAAK;AAAA,MACjB,GAAI,KAAK,UAAU,UAAa,EAAE,OAAO,KAAK,MAAA;AAAA,IAAM;AAAA,EACtD;AAEJ;;;"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { withSeedProtocolLane } from "./protocol.js";
|
|
1
2
|
const DEFAULT_MAX_THREADS = 30;
|
|
2
3
|
const DEFAULT_MAX_AGE_MS = 60 * 60 * 1e3;
|
|
3
4
|
function createDeepAgentThreadSnapshotCache(options = {}) {
|
|
@@ -68,7 +69,7 @@ function toThreadSnapshotSeed(state) {
|
|
|
68
69
|
outOfBandRunActive: _outOfBandRunActive,
|
|
69
70
|
...rest
|
|
70
71
|
} = state;
|
|
71
|
-
return { ...rest, runs: seedRunsLane(state.runs) };
|
|
72
|
+
return withSeedProtocolLane({ ...rest, runs: seedRunsLane(state.runs) });
|
|
72
73
|
}
|
|
73
74
|
function seedRunsLane(runs) {
|
|
74
75
|
const live = runs == null ? void 0 : runs[0];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-snapshot-cache.js","sources":["../../../../agent-runtime/src/thread-snapshot-cache.ts"],"sourcesContent":["import type { DeepAgentStreamValues } from './types';\n\n/**\n * Per-tab LRU of the last wire state seen per thread, so a switch back to a\n * recently-visited thread can mount with that snapshot instead of an empty\n * \"loading\" state (see `UseDeepAgentThreadOptions.snapshotCache`). Entries are\n * references into states the wire already produced — remembering is O(1) and\n * copies nothing; the bound is `maxThreads` retained states.\n */\nexport interface DeepAgentThreadSnapshotCache {\n /** Record the latest hydrated wire state for a thread. */\n remember(threadId: string, state: DeepAgentStreamValues): void;\n /** The freshest remembered state for a thread, or `undefined` when none is\n * held or the entry aged out. */\n take(threadId: string): DeepAgentStreamValues | undefined;\n /**\n * Drop a single thread's entry. Called when the server refuses\n * authorization for the thread — a refused thread must not warm-paint on\n * its next mount.\n */\n forget(threadId: string): void;\n /**\n * Drop every entry. Called when the acting identity changes — a snapshot\n * captured under one account must never seed a mount under another.\n */\n clear(): void;\n /**\n * Whether a fresh entry is held for the thread, without consuming or\n * touching it. Hosts read it at selection time to decide whether the switch\n * can paint from a seed (no loading treatment) or must cover the attach\n * wait. Optional so hand-rolled caches keep type-checking; the built-in\n * cache implements it.\n */\n peek?(threadId: string): boolean;\n}\n\n/** A write observed on the cache — the durable-mirror seam (see `onChange`). */\nexport type DeepAgentThreadSnapshotCacheChange =\n | { type: 'remember'; threadId: string; state: DeepAgentStreamValues; at: number }\n | { type: 'forget'; threadId: string }\n | { type: 'clear' };\n\nexport interface DeepAgentThreadSnapshotCacheOptions {\n /** Threads retained; the least-recently written entry evicts beyond this. */\n maxThreads?: number;\n /**\n * Entries older than this are dropped at read time. The seed's value is\n * \"the thread you just left\" — a snapshot from long ago is more likely to\n * flash content the server has since rewritten than to save a paint.\n */\n maxAgeMs?: number;\n /**\n * Observer of every write (`remember`, `forget`, `clear`). Hosts mirror\n * entries into durable storage from here so a reload can seed too; the\n * observer is never invoked for `restore`, which re-admits mirrored entries.\n * Exceptions are swallowed — a mirror fault must not break the wire path.\n */\n onChange?: (change: DeepAgentThreadSnapshotCacheChange) => void;\n /** Injectable clock (tests). */\n now?: () => number;\n}\n\n/** The built-in cache: the host contract plus the durable-mirror re-admission. */\nexport interface CreatedDeepAgentThreadSnapshotCache extends DeepAgentThreadSnapshotCache {\n peek(threadId: string): boolean;\n /**\n * Re-admit an entry captured earlier — a mirrored snapshot after a reload —\n * under its ORIGINAL capture time, so the age bound still applies. Never\n * displaces a fresher in-memory entry and never notifies `onChange`.\n */\n restore(threadId: string, state: DeepAgentStreamValues, at: number): void;\n}\n\nconst DEFAULT_MAX_THREADS = 30;\nconst DEFAULT_MAX_AGE_MS = 60 * 60 * 1000;\n\nexport function createDeepAgentThreadSnapshotCache(\n options: DeepAgentThreadSnapshotCacheOptions = {}\n): CreatedDeepAgentThreadSnapshotCache {\n const maxThreads = options.maxThreads ?? DEFAULT_MAX_THREADS;\n const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n const now = options.now ?? (() => Date.now());\n const notify = (change: DeepAgentThreadSnapshotCacheChange): void => {\n try {\n options.onChange?.(change);\n } catch {\n // The mirror is best-effort; the in-memory cache stays authoritative.\n }\n };\n // Map iteration order is insertion order; delete-then-set on every write\n // keeps the first key the least-recently written.\n const entries = new Map<string, { state: DeepAgentStreamValues; at: number }>();\n const evict = (): void => {\n while (entries.size > maxThreads) {\n const oldest = entries.keys().next().value;\n if (oldest === undefined) break;\n entries.delete(oldest);\n }\n };\n const fresh = (threadId: string): { state: DeepAgentStreamValues; at: number } | undefined => {\n const entry = entries.get(threadId);\n if (!entry) return undefined;\n if (now() - entry.at > maxAgeMs) {\n entries.delete(threadId);\n return undefined;\n }\n return entry;\n };\n return {\n remember(threadId, state) {\n const at = now();\n entries.delete(threadId);\n entries.set(threadId, { state, at });\n evict();\n notify({ type: 'remember', threadId, state, at });\n },\n take(threadId) {\n return fresh(threadId)?.state;\n },\n peek(threadId) {\n return fresh(threadId) !== undefined;\n },\n restore(threadId, state, at) {\n if (now() - at > maxAgeMs) return;\n const existing = entries.get(threadId);\n if (existing && existing.at >= at) return;\n entries.delete(threadId);\n entries.set(threadId, { state, at });\n evict();\n },\n forget(threadId) {\n entries.delete(threadId);\n notify({ type: 'forget', threadId });\n },\n clear() {\n entries.clear();\n notify({ type: 'clear' });\n },\n };\n}\n\n/**\n * Shape a remembered wire state for use as a mount's `initialState`.\n *\n * Messages/todos and the other app-owned keys seed as captured. The run lane\n * seeds by what the user left: a thread whose run was `running` when the\n * snapshot was taken seeds a running entry (see {@link seedRunsLane}) so the\n * switch back reads Running with a Stop control on its first frame — the same\n * frame `runs: []` would render as \"ready\" with a Send button over a thread the\n * server is still mid-run on. Every other live-lifecycle lane normalizes to\n * resting: a seeded input request could collect a decision the server may have\n * already resolved, so an `input-required` entry seeds as no run at all.\n * `__interrupt__` is dropped for the same reason, and so are `ptc_subagents`\n * (the live in-eval dispatch lane — a seeded \"running\" dispatch card under a\n * resting thread would render active with no eval behind it) and\n * `outOfBandRunActive` (the host's out-of-band-run-in-progress flag — seeding a\n * finished run's `true` would hide the composer until the attach corrected\n * it). Durable thread properties (`runConfig`, `sessionPersisted`, …) seed as\n * captured; the attach snapshot then replaces the whole seed.\n */\nexport function toThreadSnapshotSeed(state: DeepAgentStreamValues): DeepAgentStreamValues {\n const {\n __interrupt__: _interrupt,\n ptc_subagents: _ptcSubagents,\n outOfBandRunActive: _outOfBandRunActive,\n ...rest\n } = state;\n return { ...rest, runs: seedRunsLane(state.runs) };\n}\n\n/**\n * The run entries a seed carries.\n *\n * Only a `running` entry survives, and only its replicated identity and its\n * durable lanes: `runId` (the target of a Stop sent during the attach\n * round-trip — the live run's id if it is still running, and a refused stop\n * if it finished meanwhile), `epoch` (rides that Stop so a replayed stop cannot\n * end a later leg) and the `queue`/`steerQueue` entries (server lanes the tray\n * renders). The in-flight records rest until the snapshot: `dispatching` and\n * `nextDispatch` are batches the materializer would re-apply onto messages\n * that already contain them, `stopping` is a rewind the host may have\n * finished, `inputRequests` is a parked decision, and `error` is a failure the\n * next user run clears. An entry in any other status — `stopped`, `error`,\n * `input-required` — seeds as no run.\n */\nfunction seedRunsLane(\n runs: DeepAgentStreamValues['runs']\n): NonNullable<DeepAgentStreamValues['runs']> {\n const live = runs?.[0];\n if (live === undefined || live.status !== 'running') return [];\n return [\n {\n runId: live.runId,\n status: 'running',\n queue: live.queue,\n steerQueue: live.steerQueue,\n ...(live.epoch !== undefined && { epoch: live.epoch }),\n },\n ];\n}\n"],"names":[],"mappings":"AAyEA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB,KAAK,KAAK;AAE9B,SAAS,mCACd,UAA+C,IACV;AACrC,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,MAAM,QAAQ,QAAQ,MAAM,KAAK,IAAA;AACvC,QAAM,SAAS,CAAC,WAAqD;AATvE;AAUI,QAAI;AACF,oBAAQ,aAAR,iCAAmB;AAAA,IACrB,QAAQ;AAAA,IAER;AAAA,EACF;AAGA,QAAM,8BAAc,IAAA;AACpB,QAAM,QAAQ,MAAY;AACxB,WAAO,QAAQ,OAAO,YAAY;AAChC,YAAM,SAAS,QAAQ,KAAA,EAAO,OAAO;AACrC,UAAI,WAAW,OAAW;AAC1B,cAAQ,OAAO,MAAM;AAAA,IACvB;AAAA,EACF;AACA,QAAM,QAAQ,CAAC,aAA+E;AAC5F,UAAM,QAAQ,QAAQ,IAAI,QAAQ;AAClC,QAAI,CAAC,MAAO,QAAO;AACnB,QAAI,IAAA,IAAQ,MAAM,KAAK,UAAU;AAC/B,cAAQ,OAAO,QAAQ;AACvB,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL,SAAS,UAAU,OAAO;AACxB,YAAM,KAAK,IA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;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"thread-snapshot-cache.js","sources":["../../../../agent-runtime/src/thread-snapshot-cache.ts"],"sourcesContent":["import { withSeedProtocolLane } from './protocol';\nimport type { DeepAgentStreamValues } from './types';\n\n/**\n * Per-tab LRU of the last wire state seen per thread, so a switch back to a\n * recently-visited thread can mount with that snapshot instead of an empty\n * \"loading\" state (see `UseDeepAgentThreadOptions.snapshotCache`). Entries are\n * references into states the wire already produced — remembering is O(1) and\n * copies nothing; the bound is `maxThreads` retained states.\n */\nexport interface DeepAgentThreadSnapshotCache {\n /** Record the latest hydrated wire state for a thread. */\n remember(threadId: string, state: DeepAgentStreamValues): void;\n /** The freshest remembered state for a thread, or `undefined` when none is\n * held or the entry aged out. */\n take(threadId: string): DeepAgentStreamValues | undefined;\n /**\n * Drop a single thread's entry. Called when the server refuses\n * authorization for the thread — a refused thread must not warm-paint on\n * its next mount.\n */\n forget(threadId: string): void;\n /**\n * Drop every entry. Called when the acting identity changes — a snapshot\n * captured under one account must never seed a mount under another.\n */\n clear(): void;\n /**\n * Whether a fresh entry is held for the thread, without consuming or\n * touching it. Hosts read it at selection time to decide whether the switch\n * can paint from a seed (no loading treatment) or must cover the attach\n * wait. Optional so hand-rolled caches keep type-checking; the built-in\n * cache implements it.\n */\n peek?(threadId: string): boolean;\n}\n\n/** A write observed on the cache — the durable-mirror seam (see `onChange`). */\nexport type DeepAgentThreadSnapshotCacheChange =\n | { type: 'remember'; threadId: string; state: DeepAgentStreamValues; at: number }\n | { type: 'forget'; threadId: string }\n | { type: 'clear' };\n\nexport interface DeepAgentThreadSnapshotCacheOptions {\n /** Threads retained; the least-recently written entry evicts beyond this. */\n maxThreads?: number;\n /**\n * Entries older than this are dropped at read time. The seed's value is\n * \"the thread you just left\" — a snapshot from long ago is more likely to\n * flash content the server has since rewritten than to save a paint.\n */\n maxAgeMs?: number;\n /**\n * Observer of every write (`remember`, `forget`, `clear`). Hosts mirror\n * entries into durable storage from here so a reload can seed too; the\n * observer is never invoked for `restore`, which re-admits mirrored entries.\n * Exceptions are swallowed — a mirror fault must not break the wire path.\n */\n onChange?: (change: DeepAgentThreadSnapshotCacheChange) => void;\n /** Injectable clock (tests). */\n now?: () => number;\n}\n\n/** The built-in cache: the host contract plus the durable-mirror re-admission. */\nexport interface CreatedDeepAgentThreadSnapshotCache extends DeepAgentThreadSnapshotCache {\n peek(threadId: string): boolean;\n /**\n * Re-admit an entry captured earlier — a mirrored snapshot after a reload —\n * under its ORIGINAL capture time, so the age bound still applies. Never\n * displaces a fresher in-memory entry and never notifies `onChange`.\n */\n restore(threadId: string, state: DeepAgentStreamValues, at: number): void;\n}\n\nconst DEFAULT_MAX_THREADS = 30;\nconst DEFAULT_MAX_AGE_MS = 60 * 60 * 1000;\n\nexport function createDeepAgentThreadSnapshotCache(\n options: DeepAgentThreadSnapshotCacheOptions = {}\n): CreatedDeepAgentThreadSnapshotCache {\n const maxThreads = options.maxThreads ?? DEFAULT_MAX_THREADS;\n const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n const now = options.now ?? (() => Date.now());\n const notify = (change: DeepAgentThreadSnapshotCacheChange): void => {\n try {\n options.onChange?.(change);\n } catch {\n // The mirror is best-effort; the in-memory cache stays authoritative.\n }\n };\n // Map iteration order is insertion order; delete-then-set on every write\n // keeps the first key the least-recently written.\n const entries = new Map<string, { state: DeepAgentStreamValues; at: number }>();\n const evict = (): void => {\n while (entries.size > maxThreads) {\n const oldest = entries.keys().next().value;\n if (oldest === undefined) break;\n entries.delete(oldest);\n }\n };\n const fresh = (threadId: string): { state: DeepAgentStreamValues; at: number } | undefined => {\n const entry = entries.get(threadId);\n if (!entry) return undefined;\n if (now() - entry.at > maxAgeMs) {\n entries.delete(threadId);\n return undefined;\n }\n return entry;\n };\n return {\n remember(threadId, state) {\n const at = now();\n entries.delete(threadId);\n entries.set(threadId, { state, at });\n evict();\n notify({ type: 'remember', threadId, state, at });\n },\n take(threadId) {\n return fresh(threadId)?.state;\n },\n peek(threadId) {\n return fresh(threadId) !== undefined;\n },\n restore(threadId, state, at) {\n if (now() - at > maxAgeMs) return;\n const existing = entries.get(threadId);\n if (existing && existing.at >= at) return;\n entries.delete(threadId);\n entries.set(threadId, { state, at });\n evict();\n },\n forget(threadId) {\n entries.delete(threadId);\n notify({ type: 'forget', threadId });\n },\n clear() {\n entries.clear();\n notify({ type: 'clear' });\n },\n };\n}\n\n/**\n * Shape a remembered wire state for use as a mount's `initialState`.\n *\n * Messages/todos and the other app-owned keys seed as captured. The run lane\n * seeds by what the user left: a thread whose run was `running` when the\n * snapshot was taken seeds a running entry (see {@link seedRunsLane}) so the\n * switch back reads Running with a Stop control on its first frame — the same\n * frame `runs: []` would render as \"ready\" with a Send button over a thread the\n * server is still mid-run on. Every other live-lifecycle lane normalizes to\n * resting: a seeded input request could collect a decision the server may have\n * already resolved, so an `input-required` entry seeds as no run at all.\n * `__interrupt__` is dropped for the same reason, and so are `ptc_subagents`\n * (the live in-eval dispatch lane — a seeded \"running\" dispatch card under a\n * resting thread would render active with no eval behind it) and\n * `outOfBandRunActive` (the host's out-of-band-run-in-progress flag — seeding a\n * finished run's `true` would hide the composer until the attach corrected\n * it). Durable thread properties (`runConfig`, `config`, `sessionPersisted`, …)\n * seed as captured; the attach snapshot then replaces the whole seed. The\n * protocol lane seeds as a seed's own copy (`withSeedProtocolLane`), so\n * `isDeepAgentHostState` never reads the seed, or a state folded over it, as\n * what the host holds now.\n */\nexport function toThreadSnapshotSeed(state: DeepAgentStreamValues): DeepAgentStreamValues {\n const {\n __interrupt__: _interrupt,\n ptc_subagents: _ptcSubagents,\n outOfBandRunActive: _outOfBandRunActive,\n ...rest\n } = state;\n return withSeedProtocolLane({ ...rest, runs: seedRunsLane(state.runs) });\n}\n\n/**\n * The run entries a seed carries.\n *\n * Only a `running` entry survives, and only its replicated identity and its\n * durable lanes: `runId` (the target of a Stop sent during the attach\n * round-trip — the live run's id if it is still running, and a refused stop\n * if it finished meanwhile), `epoch` (rides that Stop so a replayed stop cannot\n * end a later leg) and the `queue`/`steerQueue` entries (server lanes the tray\n * renders). The in-flight records rest until the snapshot: `dispatching` and\n * `nextDispatch` are batches the materializer would re-apply onto messages\n * that already contain them, `stopping` is a rewind the host may have\n * finished, `inputRequests` is a parked decision, and `error` is a failure the\n * next user run clears. An entry in any other status — `stopped`, `error`,\n * `input-required` — seeds as no run.\n */\nfunction seedRunsLane(\n runs: DeepAgentStreamValues['runs']\n): NonNullable<DeepAgentStreamValues['runs']> {\n const live = runs?.[0];\n if (live === undefined || live.status !== 'running') return [];\n return [\n {\n runId: live.runId,\n status: 'running',\n queue: live.queue,\n steerQueue: live.steerQueue,\n ...(live.epoch !== undefined && { epoch: live.epoch }),\n },\n ];\n}\n"],"names":[],"mappings":";AA0EA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB,KAAK,KAAK;AAE9B,SAAS,mCACd,UAA+C,IACV;AACrC,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,MAAM,QAAQ,QAAQ,MAAM,KAAK,IAAA;AACvC,QAAM,SAAS,CAAC,WAAqD;;AACnE,QAAI;AACF,oBAAQ,aAAR,iCAAmB;AAAA,IACrB,QAAQ;AAAA,IAER;AAAA,EACF;AAGA,QAAM,8BAAc,IAAA;AACpB,QAAM,QAAQ,MAAY;AACxB,WAAO,QAAQ,OAAO,YAAY;AAChC,YAAM,SAAS,QAAQ,KAAA,EAAO,OAAO;AACrC,UAAI,WAAW,OAAW;AAC1B,cAAQ,OAAO,MAAM;AAAA,IACvB;AAAA,EACF;AACA,QAAM,QAAQ,CAAC,aAA+E;AAC5F,UAAM,QAAQ,QAAQ,IAAI,QAAQ;AAClC,QAAI,CAAC,MAAO,QAAO;AACnB,QAAI,IAAA,IAAQ,MAAM,KAAK,UAAU;AAC/B,cAAQ,OAAO,QAAQ;AACvB,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL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AO,KAAK,MAAA;AAAA,IAAM;AAAA,EACtD;AAEJ;"}
|
|
@@ -11,7 +11,7 @@ const statewireRunConfig = require("./statewire-run-config.cjs");
|
|
|
11
11
|
const runconfigContract = require("../agent-runtime/src/generated/runconfig-contract.cjs");
|
|
12
12
|
const useDeepAgentRuntime = require("../agent-runtime/src/use-deep-agent-runtime.cjs");
|
|
13
13
|
const errors = require("../agent-runtime/src/errors.cjs");
|
|
14
|
-
const
|
|
14
|
+
const protocol = require("../agent-runtime/src/protocol.cjs");
|
|
15
15
|
const composerMarkdown = require("../agent-runtime/src/composer-markdown.cjs");
|
|
16
16
|
const ATHENA_SDK_MESSAGE_WINDOW = {
|
|
17
17
|
size: runconfigContract.DEEP_AGENT_DEFAULT_MESSAGE_WINDOW
|
|
@@ -83,8 +83,6 @@ function useAthenaStatewireRuntime(config) {
|
|
|
83
83
|
clientTools: statewireClientTools.statewireClientToolWireEntries(clientTools)
|
|
84
84
|
});
|
|
85
85
|
const runConfigKey = JSON.stringify(runConfigValue);
|
|
86
|
-
const lastStateRef = react.useRef(null);
|
|
87
|
-
const helloLandedRef = react.useRef(false);
|
|
88
86
|
const auiTools = react.useMemo(() => react$1.Tools({ toolkit: frontendToolkit }), [frontendToolkit]);
|
|
89
87
|
const useSdkClient = (thread) => react$1.useAui({ thread, tools: auiTools });
|
|
90
88
|
return useDeepAgentRuntime.useDeepAgentRuntime({
|
|
@@ -123,14 +121,13 @@ function useAthenaStatewireRuntime(config) {
|
|
|
123
121
|
getMessageMetadata: composerMarkdown.withStagedComposerMarkdown({ threadId }),
|
|
124
122
|
useClient: useSdkClient,
|
|
125
123
|
onStateChange: (state) => {
|
|
124
|
+
if (!protocol.isDeepAgentHostState(state)) return;
|
|
126
125
|
const endSpan = attachSpanRef.current;
|
|
127
126
|
if (endSpan) {
|
|
128
127
|
attachSpanRef.current = null;
|
|
129
128
|
endSpan("statewire.snapshot", { data: { thread_id: threadId } });
|
|
130
129
|
}
|
|
131
|
-
|
|
132
|
-
lastStateRef.current = state;
|
|
133
|
-
if (helloLandedRef.current) onServerState == null ? void 0 : onServerState(state);
|
|
130
|
+
onServerState == null ? void 0 : onServerState(state);
|
|
134
131
|
},
|
|
135
132
|
onConnectionChange: (connection) => {
|
|
136
133
|
athenaDiagnostics.athenaDiagnostics.gauge("statewire.connection", (connection == null ? void 0 : connection.status) ?? null);
|
|
@@ -146,14 +143,7 @@ function useAthenaStatewireRuntime(config) {
|
|
|
146
143
|
}
|
|
147
144
|
onConnectionChange == null ? void 0 : onConnectionChange(connection);
|
|
148
145
|
},
|
|
149
|
-
onRawConnectionChange
|
|
150
|
-
if (connection.status === "connected" && !helloLandedRef.current) {
|
|
151
|
-
helloLandedRef.current = true;
|
|
152
|
-
const helloState = lastStateRef.current;
|
|
153
|
-
if (helloState) onServerState == null ? void 0 : onServerState(helloState);
|
|
154
|
-
}
|
|
155
|
-
onRawConnectionChange == null ? void 0 : onRawConnectionChange(connection);
|
|
156
|
-
},
|
|
146
|
+
onRawConnectionChange,
|
|
157
147
|
onRunningChange,
|
|
158
148
|
// Each model-context notification pulls the latest getter through the
|
|
159
149
|
// core's per-render ref; the value-stable key re-registers (and so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAthenaStatewireRuntime.cjs","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentStreamValues,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isDeepAgentStateHydrated,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n withStagedComposerMarkdown,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The head interest every SDK attach states (`athena/interest`): the host\n * mounts the transcript's tail as message documents instead of every message\n * — megabytes on long threads, over the 1 MiB frame limit of stock websocket\n * clients. Older pages load from the `StatewireHistoryEdge` row the chat UI\n * mounts above the messages, and cut tool outputs are fetched back for the\n * cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /** The head interest stated on the attach (see {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). */\n messageWindow?: DeepAgentMessageWindowDeclaration;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** The agent's mode picked for this thread (`AthenaProvider` `modes`). */\n mode?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n /**\n * Observes the host's own state: called once the attach's hello has landed\n * (with the snapshot it carried) and then on every later frame — never with\n * the placeholder or remembered snapshot a thread renders before its hello.\n * Called per streamed token, so keep it cheap.\n */\n onServerState?: (state: DeepAgentStreamValues) => void;\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n onServerState,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n // Built every render so its JSON signature can key the model-context\n // registration below: consumers commonly pass fresh array literals per\n // render, which must not thrash registration, while a changed value (a new\n // `model`, channel, tool list, system prompt, …) must re-sync the context\n // before the next send. The core pulls this value only on model-context\n // notifications, which a key change triggers.\n const runConfigValue = buildStatewireRunConfig({\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n });\n const runConfigKey = JSON.stringify(runConfigValue);\n\n // The host's state, told apart from what the thread renders before its\n // hello: statewire publishes the initial (placeholder or remembered) state\n // through `onStateChange` too, and reports `connected` in the same flush\n // right after publishing the state the hello carried. So the latest state\n // seen when the connection first turns `connected` is the hello's, and every\n // state after it is the host's. Refs are per attach: the runtime is mounted\n // per thread.\n const lastStateRef = useRef<DeepAgentStreamValues | null>(null);\n const helloLandedRef = useRef(false);\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Head interest (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n // The composer stages the draft each send came from right before it\n // sends; the message carries it as its composer markdown, so its bubble\n // shows the text exactly as typed (`UserMessageText`).\n getMessageMetadata: withStagedComposerMarkdown({ threadId }),\n useClient: useSdkClient,\n onStateChange: (state) => {\n // First snapshot for this attach ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n // A replay boundary republishes the pre-stream default: not host state.\n if (!isDeepAgentStateHydrated(state)) return;\n lastStateRef.current = state;\n if (helloLandedRef.current) onServerState?.(state);\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange: (connection) => {\n if (connection.status === 'connected' && !helloLandedRef.current) {\n helloLandedRef.current = true;\n const helloState = lastStateRef.current;\n if (helloState) onServerState?.(helloState);\n }\n onRawConnectionChange?.(connection);\n },\n onRunningChange,\n // Each model-context notification pulls the latest getter through the\n // core's per-render ref; the value-stable key re-registers (and so\n // notifies) only when the built runConfig actually changed. On a thread\n // with a server config lane, agora keeps only the per-send keys of what\n // this carries; `StatewireThreadConfigLaneSync` writes a changed model,\n // system prompt, tool list, workbench or knowledge base to the lane itself.\n runConfig: {\n get: () => runConfigValue,\n key: runConfigKey,\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":["DEEP_AGENT_DEFAULT_MESSAGE_WINDOW","useMemo","collectStatewireClientTools","resolveAgentProp","useContext","AthenaAuthContext","useRef","athenaDiagnostics","buildStatewireRunConfig","statewireClientToolWireEntries","Tools","useAui","useDeepAgentRuntime","resolveStatewireAuthHeaders","statewireSessionKey","withStagedComposerMarkdown","isDeepAgentStateHydrated","isStatewireChannelTeardown","logUnhandledStatewireError"],"mappings":";;;;;;;;;;;;;;;AA+CO,MAAM,4BAA+D;AAAA,EAC1E,MAAMA,kBAAAA;AACR;AA+EA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAOC,MAAAA;AAAAA,IACL,MAAMC,qBAAAA,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB;AAAA,IACA;A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A,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,WAAW;AAAA,MACT,KAAK,MAAM;AAAA,MACX,KAAK;AAAA,IAAA;AAAA,IAEP,SAAS,CAAC,UAAU;AAClB,UAAI,CAACU,OAAAA,2BAA2B,KAAK,GAAG;AACtCV,0BAAAA,kBAAkB;AAAA,UAChB;AAAA,UACA;AAAA,UACA;AAAA,YACE,MAAM;AAAA,YACN,SAAS;AAAA,YACT,MAAM;AAAA,UAAA;AAAA,UAER,EAAE,WAAW,SAAA;AAAA,QAAS;AAAA,MAE1B;AACA,UAAI,SAAS;AACX,gBAAQ,KAAK;AACb;AAAA,MACF;AACAW,0BAAAA,2BAA2B,aAAa,KAAK;AAAA,IAC/C;AAAA,EAAA,CACD;AACH;;;;;"}
|
|
1
|
+
{"version":3,"file":"useAthenaStatewireRuntime.cjs","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentStreamValues,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isDeepAgentHostState,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n withStagedComposerMarkdown,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The head interest every SDK attach states (`athena/interest`): the host\n * mounts the transcript's tail as message documents instead of every message\n * — megabytes on long threads, over the 1 MiB frame limit of stock websocket\n * clients. Older pages load from the `StatewireHistoryEdge` row the chat UI\n * mounts above the messages, and cut tool outputs are fetched back for the\n * cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /** The head interest stated on the attach (see {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). */\n messageWindow?: DeepAgentMessageWindowDeclaration;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** The agent's mode picked for this thread (`AthenaProvider` `modes`). */\n mode?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n /**\n * Observes the host's own state: called with the attach snapshot and then on\n * every later frame (`isDeepAgentHostState`) — never with the placeholder or\n * remembered snapshot a thread renders before its snapshot applies, which\n * can be after the connection reports `connected`. Called per streamed\n * token, so keep it cheap.\n */\n onServerState?: (state: DeepAgentStreamValues) => void;\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n onServerState,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n // Built every render so its JSON signature can key the model-context\n // registration below: consumers commonly pass fresh array literals per\n // render, which must not thrash registration, while a changed value (a new\n // `model`, channel, tool list, system prompt, …) must re-sync the context\n // before the next send. The core pulls this value only on model-context\n // notifications, which a key change triggers.\n const runConfigValue = buildStatewireRunConfig({\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n });\n const runConfigKey = JSON.stringify(runConfigValue);\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Head interest (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n // The composer stages the draft each send came from right before it\n // sends; the message carries it as its composer markdown, so its bubble\n // shows the text exactly as typed (`UserMessageText`).\n getMessageMetadata: withStagedComposerMarkdown({ threadId }),\n useClient: useSdkClient,\n onStateChange: (state) => {\n // Statewire publishes what the thread renders before its attach snapshot\n // through here too (the placeholder, a remembered snapshot, and a replay\n // boundary's pre-stream default), and on a thread mid-run it reports\n // `connected` before the snapshot applies: only a state the host sent\n // counts, whatever the connection says.\n if (!isDeepAgentHostState(state)) return;\n // The attach's first one ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n onServerState?.(state);\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange,\n onRunningChange,\n // Each model-context notification pulls the latest getter through the\n // core's per-render ref; the value-stable key re-registers (and so\n // notifies) only when the built runConfig actually changed. On a thread\n // with a server config lane, agora keeps only the per-send keys of what\n // this carries; `StatewireThreadConfigLaneSync` writes a changed model,\n // system prompt, tool list, workbench or knowledge base to the lane itself.\n runConfig: {\n get: () => runConfigValue,\n key: runConfigKey,\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":["DEEP_AGENT_DEFAULT_MESSAGE_WINDOW","useMemo","collectStatewireClientTools","resolveAgentProp","useContext","AthenaAuthContext","useRef","athenaDiagnostics","buildStatewireRunConfig","statewireClientToolWireEntries","Tools","useAui","useDeepAgentRuntime","resolveStatewireAuthHeaders","statewireSessionKey","withStagedComposerMarkdown","isDeepAgentHostState","isStatewireChannelTeardown","logUnhandledStatewireError"],"mappings":";;;;;;;;;;;;;;;AA+CO,MAAM,4BAA+D;AAAA,EAC1E,MAAMA,kBAAAA;AACR;AAgFA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAOC,MAAAA;AAAAA,IACL,MAAMC,qBAAAA,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,IACE;AAMJC,qBAAAA,iBAAiB,EAAE,OAAO;AAE1B,QAAM,cAAc,wBAAwB,eAAe;AAI3D,QAAM,cAAcC,MAAAA,WAAWC,mCAAiB;AAChD,QAAM,cAAY,gDAAa,SAAb,mBAAmB,WAAU;AAG/C,QAAM,gBAAgBC,MAAAA,OAAwD,IAAI;AAClF,QAAM,kBAAkBA,MAAAA,OAAsB,IAAI;AAClD,MAAI,gBAAgB,YAAY,UAAU;AACxC,oBAAgB,UAAU;AAC1B,kBAAc,UAAUC,kBAAAA,kBAAkB;AAAA,MACxC,oBAAoB,QAAQ;AAAA,MAC5B;AAAA,MACA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AE,WAAW,SAAA,GAAY;AAAA,MACjE;AACA,qDAAgB;AAAA,IAClB;AAAA,IACA,oBAAoB,CAAC,eAAe;AAClCT,wBAAAA,kBAAkB,MAAM,yBAAwB,yCAAY,WAAU,IAAI;AAC1E,WAAI,yCAAY,YAAW,WAAW;AACpCA,0BAAAA,kBAAkB,KAAK,wBAAwB;AAAA,UAC7C,OAAO;AAAA,UACP,MAAM;AAAA,YACJ,QAAQ,WAAW;AAAA,YACnB,QAAQ,WAAW;AAAA,YACnB,SAAS,WAAW;AAAA,UAAA;AAAA,QACtB,CACD;AAAA,MACH;AACA,+DAAqB;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,WAAW;AAAA,MACT,KAAK,MAAM;AAAA,MACX,KAAK;AAAA,IAAA;AAAA,IAEP,SAAS,CAAC,UAAU;AAClB,UAAI,CAACU,OAAAA,2BAA2B,KAAK,GAAG;AACtCV,0BAAAA,kBAAkB;AAAA,UAChB;AAAA,UACA;AAAA,UACA;AAAA,YACE,MAAM;AAAA,YACN,SAAS;AAAA,YACT,MAAM;AAAA,UAAA;AAAA,UAER,EAAE,WAAW,SAAA;AAAA,QAAS;AAAA,MAE1B;AACA,UAAI,SAAS;AACX,gBAAQ,KAAK;AACb;AAAA,MACF;AACAW,0BAAAA,2BAA2B,aAAa,KAAK;AAAA,IAC/C;AAAA,EAAA,CACD;AACH;;;;;"}
|
|
@@ -81,10 +81,11 @@ export interface AthenaStatewireRuntimeConfig {
|
|
|
81
81
|
/** Notified when a run starts/stops. */
|
|
82
82
|
onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];
|
|
83
83
|
/**
|
|
84
|
-
* Observes the host's own state: called
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
84
|
+
* Observes the host's own state: called with the attach snapshot and then on
|
|
85
|
+
* every later frame (`isDeepAgentHostState`) — never with the placeholder or
|
|
86
|
+
* remembered snapshot a thread renders before its snapshot applies, which
|
|
87
|
+
* can be after the connection reports `connected`. Called per streamed
|
|
88
|
+
* token, so keep it cheap.
|
|
88
89
|
*/
|
|
89
90
|
onServerState?: (state: DeepAgentStreamValues) => void;
|
|
90
91
|
}
|
|
@@ -10,7 +10,7 @@ import { DEFAULT_STATEWIRE_MODEL } from "./statewire-run-config.js";
|
|
|
10
10
|
import { DEEP_AGENT_DEFAULT_MESSAGE_WINDOW } from "../agent-runtime/src/generated/runconfig-contract.js";
|
|
11
11
|
import { useDeepAgentRuntime, logUnhandledStatewireError } from "../agent-runtime/src/use-deep-agent-runtime.js";
|
|
12
12
|
import { isStatewireChannelTeardown } from "../agent-runtime/src/errors.js";
|
|
13
|
-
import {
|
|
13
|
+
import { isDeepAgentHostState } from "../agent-runtime/src/protocol.js";
|
|
14
14
|
import { withStagedComposerMarkdown } from "../agent-runtime/src/composer-markdown.js";
|
|
15
15
|
const ATHENA_SDK_MESSAGE_WINDOW = {
|
|
16
16
|
size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW
|
|
@@ -82,8 +82,6 @@ function useAthenaStatewireRuntime(config) {
|
|
|
82
82
|
clientTools: statewireClientToolWireEntries(clientTools)
|
|
83
83
|
});
|
|
84
84
|
const runConfigKey = JSON.stringify(runConfigValue);
|
|
85
|
-
const lastStateRef = useRef(null);
|
|
86
|
-
const helloLandedRef = useRef(false);
|
|
87
85
|
const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);
|
|
88
86
|
const useSdkClient = (thread) => useAui({ thread, tools: auiTools });
|
|
89
87
|
return useDeepAgentRuntime({
|
|
@@ -122,14 +120,13 @@ function useAthenaStatewireRuntime(config) {
|
|
|
122
120
|
getMessageMetadata: withStagedComposerMarkdown({ threadId }),
|
|
123
121
|
useClient: useSdkClient,
|
|
124
122
|
onStateChange: (state) => {
|
|
123
|
+
if (!isDeepAgentHostState(state)) return;
|
|
125
124
|
const endSpan = attachSpanRef.current;
|
|
126
125
|
if (endSpan) {
|
|
127
126
|
attachSpanRef.current = null;
|
|
128
127
|
endSpan("statewire.snapshot", { data: { thread_id: threadId } });
|
|
129
128
|
}
|
|
130
|
-
|
|
131
|
-
lastStateRef.current = state;
|
|
132
|
-
if (helloLandedRef.current) onServerState == null ? void 0 : onServerState(state);
|
|
129
|
+
onServerState == null ? void 0 : onServerState(state);
|
|
133
130
|
},
|
|
134
131
|
onConnectionChange: (connection) => {
|
|
135
132
|
athenaDiagnostics.gauge("statewire.connection", (connection == null ? void 0 : connection.status) ?? null);
|
|
@@ -145,14 +142,7 @@ function useAthenaStatewireRuntime(config) {
|
|
|
145
142
|
}
|
|
146
143
|
onConnectionChange == null ? void 0 : onConnectionChange(connection);
|
|
147
144
|
},
|
|
148
|
-
onRawConnectionChange
|
|
149
|
-
if (connection.status === "connected" && !helloLandedRef.current) {
|
|
150
|
-
helloLandedRef.current = true;
|
|
151
|
-
const helloState = lastStateRef.current;
|
|
152
|
-
if (helloState) onServerState == null ? void 0 : onServerState(helloState);
|
|
153
|
-
}
|
|
154
|
-
onRawConnectionChange == null ? void 0 : onRawConnectionChange(connection);
|
|
155
|
-
},
|
|
145
|
+
onRawConnectionChange,
|
|
156
146
|
onRunningChange,
|
|
157
147
|
// Each model-context notification pulls the latest getter through the
|
|
158
148
|
// core's per-render ref; the value-stable key re-registers (and so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAthenaStatewireRuntime.js","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentStreamValues,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isDeepAgentStateHydrated,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n withStagedComposerMarkdown,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The head interest every SDK attach states (`athena/interest`): the host\n * mounts the transcript's tail as message documents instead of every message\n * — megabytes on long threads, over the 1 MiB frame limit of stock websocket\n * clients. Older pages load from the `StatewireHistoryEdge` row the chat UI\n * mounts above the messages, and cut tool outputs are fetched back for the\n * cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /** The head interest stated on the attach (see {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). */\n messageWindow?: DeepAgentMessageWindowDeclaration;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** The agent's mode picked for this thread (`AthenaProvider` `modes`). */\n mode?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n /**\n * Observes the host's own state: called once the attach's hello has landed\n * (with the snapshot it carried) and then on every later frame — never with\n * the placeholder or remembered snapshot a thread renders before its hello.\n * Called per streamed token, so keep it cheap.\n */\n onServerState?: (state: DeepAgentStreamValues) => void;\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n onServerState,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n // Built every render so its JSON signature can key the model-context\n // registration below: consumers commonly pass fresh array literals per\n // render, which must not thrash registration, while a changed value (a new\n // `model`, channel, tool list, system prompt, …) must re-sync the context\n // before the next send. The core pulls this value only on model-context\n // notifications, which a key change triggers.\n const runConfigValue = buildStatewireRunConfig({\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n });\n const runConfigKey = JSON.stringify(runConfigValue);\n\n // The host's state, told apart from what the thread renders before its\n // hello: statewire publishes the initial (placeholder or remembered) state\n // through `onStateChange` too, and reports `connected` in the same flush\n // right after publishing the state the hello carried. So the latest state\n // seen when the connection first turns `connected` is the hello's, and every\n // state after it is the host's. Refs are per attach: the runtime is mounted\n // per thread.\n const lastStateRef = useRef<DeepAgentStreamValues | null>(null);\n const helloLandedRef = useRef(false);\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Head interest (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n // The composer stages the draft each send came from right before it\n // sends; the message carries it as its composer markdown, so its bubble\n // shows the text exactly as typed (`UserMessageText`).\n getMessageMetadata: withStagedComposerMarkdown({ threadId }),\n useClient: useSdkClient,\n onStateChange: (state) => {\n // First snapshot for this attach ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n // A replay boundary republishes the pre-stream default: not host state.\n if (!isDeepAgentStateHydrated(state)) return;\n lastStateRef.current = state;\n if (helloLandedRef.current) onServerState?.(state);\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange: (connection) => {\n if (connection.status === 'connected' && !helloLandedRef.current) {\n helloLandedRef.current = true;\n const helloState = lastStateRef.current;\n if (helloState) onServerState?.(helloState);\n }\n onRawConnectionChange?.(connection);\n },\n onRunningChange,\n // Each model-context notification pulls the latest getter through the\n // core's per-render ref; the value-stable key re-registers (and so\n // notifies) only when the built runConfig actually changed. On a thread\n // with a server config lane, agora keeps only the per-send keys of what\n // this carries; `StatewireThreadConfigLaneSync` writes a changed model,\n // system prompt, tool list, workbench or knowledge base to the lane itself.\n runConfig: {\n get: () => runConfigValue,\n key: runConfigKey,\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;AA+CO,MAAM,4BAA+D;AAAA,EAC1E,MAAM;AACR;AA+EA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAO;AAAA,IACL,MAAM,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,IACE;AAMJ,mBAAiB,EAAE,OAAO;AAE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,SAAA;AAAA,QAAS;AAAA,MAE1B;AACA,UAAI,SAAS;AACX,gBAAQ,KAAK;AACb;AAAA,MACF;AACA,iCAA2B,aAAa,KAAK;AAAA,IAC/C;AAAA,EAAA,CACD;AACH;"}
|
|
1
|
+
{"version":3,"file":"useAthenaStatewireRuntime.js","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentStreamValues,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isDeepAgentHostState,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n withStagedComposerMarkdown,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The head interest every SDK attach states (`athena/interest`): the host\n * mounts the transcript's tail as message documents instead of every message\n * — megabytes on long threads, over the 1 MiB frame limit of stock websocket\n * clients. Older pages load from the `StatewireHistoryEdge` row the chat UI\n * mounts above the messages, and cut tool outputs are fetched back for the\n * cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /** The head interest stated on the attach (see {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). */\n messageWindow?: DeepAgentMessageWindowDeclaration;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** The agent's mode picked for this thread (`AthenaProvider` `modes`). */\n mode?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n /**\n * Observes the host's own state: called with the attach snapshot and then on\n * every later frame (`isDeepAgentHostState`) — never with the placeholder or\n * remembered snapshot a thread renders before its snapshot applies, which\n * can be after the connection reports `connected`. Called per streamed\n * token, so keep it cheap.\n */\n onServerState?: (state: DeepAgentStreamValues) => void;\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n onServerState,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n // Built every render so its JSON signature can key the model-context\n // registration below: consumers commonly pass fresh array literals per\n // render, which must not thrash registration, while a changed value (a new\n // `model`, channel, tool list, system prompt, …) must re-sync the context\n // before the next send. The core pulls this value only on model-context\n // notifications, which a key change triggers.\n const runConfigValue = buildStatewireRunConfig({\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n });\n const runConfigKey = JSON.stringify(runConfigValue);\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Head interest (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n // The composer stages the draft each send came from right before it\n // sends; the message carries it as its composer markdown, so its bubble\n // shows the text exactly as typed (`UserMessageText`).\n getMessageMetadata: withStagedComposerMarkdown({ threadId }),\n useClient: useSdkClient,\n onStateChange: (state) => {\n // Statewire publishes what the thread renders before its attach snapshot\n // through here too (the placeholder, a remembered snapshot, and a replay\n // boundary's pre-stream default), and on a thread mid-run it reports\n // `connected` before the snapshot applies: only a state the host sent\n // counts, whatever the connection says.\n if (!isDeepAgentHostState(state)) return;\n // The attach's first one ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n onServerState?.(state);\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange,\n onRunningChange,\n // Each model-context notification pulls the latest getter through the\n // core's per-render ref; the value-stable key re-registers (and so\n // notifies) only when the built runConfig actually changed. On a thread\n // with a server config lane, agora keeps only the per-send keys of what\n // this carries; `StatewireThreadConfigLaneSync` writes a changed model,\n // system prompt, tool list, workbench or knowledge base to the lane itself.\n runConfig: {\n get: () => runConfigValue,\n key: runConfigKey,\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;AA+CO,MAAM,4BAA+D;AAAA,EAC1E,MAAM;AACR;AAgFA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAO;AAAA,IACL,MAAM,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;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