@athenaintel/react 0.41.1 → 0.41.3
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 +12 -0
- package/dist/agent-runtime/src/durable-thread-snapshot-cache.cjs +158 -0
- package/dist/agent-runtime/src/durable-thread-snapshot-cache.cjs.map +1 -0
- package/dist/agent-runtime/src/durable-thread-snapshot-cache.js +158 -0
- package/dist/agent-runtime/src/durable-thread-snapshot-cache.js.map +1 -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/agent-runtime/src/thread-snapshot-mirror.cjs +400 -0
- package/dist/agent-runtime/src/thread-snapshot-mirror.cjs.map +1 -0
- package/dist/agent-runtime/src/thread-snapshot-mirror.js +400 -0
- package/dist/agent-runtime/src/thread-snapshot-mirror.js.map +1 -0
- package/dist/chat/AthenaChat.cjs +5 -1
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.js +5 -1
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.cjs +4 -3
- package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.d.ts +7 -1
- package/dist/chat/super-grouping/activity-timeline.js +4 -3
- package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/offline/offline-history.cjs +77 -0
- package/dist/offline/offline-history.cjs.map +1 -0
- package/dist/offline/offline-history.d.ts +60 -0
- package/dist/offline/offline-history.js +77 -0
- package/dist/offline/offline-history.js.map +1 -0
- package/dist/provider/AthenaProvider.cjs +46 -3
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.d.ts +8 -1
- package/dist/provider/AthenaProvider.js +46 -3
- package/dist/provider/AthenaProvider.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/dist/threads/offline-session-list.cjs +75 -0
- package/dist/threads/offline-session-list.cjs.map +1 -0
- package/dist/threads/offline-session-list.d.ts +27 -0
- package/dist/threads/offline-session-list.js +75 -0
- package/dist/threads/offline-session-list.js.map +1 -0
- package/dist/threads/statewire-thread-list.cjs +63 -4
- package/dist/threads/statewire-thread-list.cjs.map +1 -1
- package/dist/threads/statewire-thread-list.d.ts +21 -2
- package/dist/threads/statewire-thread-list.js +64 -5
- package/dist/threads/statewire-thread-list.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -807,6 +807,18 @@ 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.3
|
|
811
|
+
|
|
812
|
+
**A pinned session stays in the sidebar.** The session list reads the newest 50 sessions, and its Pinned group was built from that page alone, so a session pinned long ago left the sidebar once 50 newer sessions existed (on staging, four pinned sessions became three when two new sessions started). The provider now also reads the viewer's pinned sessions on their own (`favorites_only`, under the same app scope and search, every page of them up to 500) and adds the ones the page does not list to the Pinned group. Unpinning such a session takes it out of the sidebar, since it is not one of the newest. Nothing to change in your app.
|
|
813
|
+
|
|
814
|
+
**"Completed with issues" means the turn ended on a problem.** A finished turn's collapsed card said "Completed with issues" when any tool call in it had failed, so a long run that opened its pull request after a few failed reads or commands read as a failure. It now says so only when the turn ended on a failed call (no later call completed) or held a call the person refused; otherwise it reads `Used N tools`. `getActivitySummary` follows the same rule.
|
|
815
|
+
|
|
816
|
+
## What's new in 0.41.2
|
|
817
|
+
|
|
818
|
+
**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.
|
|
819
|
+
|
|
820
|
+
Nothing to change in your app.
|
|
821
|
+
|
|
810
822
|
## What's new in 0.41.1
|
|
811
823
|
|
|
812
824
|
**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.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const threadSnapshotCache = require("./thread-snapshot-cache.cjs");
|
|
4
|
+
const threadSnapshotMirror = require("./thread-snapshot-mirror.cjs");
|
|
5
|
+
const DEFAULT_MAX_THREADS = 30;
|
|
6
|
+
const OFFLINE_SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
7
|
+
function browserOffline() {
|
|
8
|
+
var _a;
|
|
9
|
+
const host = globalThis;
|
|
10
|
+
return ((_a = host.navigator) == null ? void 0 : _a.onLine) === false;
|
|
11
|
+
}
|
|
12
|
+
function createDurableThreadSnapshotCache({
|
|
13
|
+
mirror,
|
|
14
|
+
isOffline = browserOffline,
|
|
15
|
+
maxThreads = DEFAULT_MAX_THREADS,
|
|
16
|
+
maxAgeMs,
|
|
17
|
+
offlineMaxAgeMs = OFFLINE_SNAPSHOT_MAX_AGE_MS,
|
|
18
|
+
now = () => Date.now()
|
|
19
|
+
}) {
|
|
20
|
+
let ownerId = null;
|
|
21
|
+
let epoch = 0;
|
|
22
|
+
let primed = null;
|
|
23
|
+
let hydration = Promise.resolve();
|
|
24
|
+
const offline = /* @__PURE__ */ new Map();
|
|
25
|
+
const offlineSeeds = /* @__PURE__ */ new Map();
|
|
26
|
+
const restored = /* @__PURE__ */ new Set();
|
|
27
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
28
|
+
const notify = () => {
|
|
29
|
+
for (const listener of listeners) {
|
|
30
|
+
try {
|
|
31
|
+
listener();
|
|
32
|
+
} catch {
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
const clearOfflineSeed = (threadId) => {
|
|
37
|
+
if (offlineSeeds.delete(threadId)) notify();
|
|
38
|
+
};
|
|
39
|
+
const keepOffline = (threadId, entry) => {
|
|
40
|
+
offline.delete(threadId);
|
|
41
|
+
offline.set(threadId, entry);
|
|
42
|
+
while (offline.size > maxThreads) {
|
|
43
|
+
const oldest = offline.keys().next().value;
|
|
44
|
+
if (oldest === void 0) break;
|
|
45
|
+
offline.delete(oldest);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
const memory = threadSnapshotCache.createDeepAgentThreadSnapshotCache({
|
|
49
|
+
maxThreads,
|
|
50
|
+
maxAgeMs,
|
|
51
|
+
now,
|
|
52
|
+
onChange: (change) => {
|
|
53
|
+
const owner = ownerId;
|
|
54
|
+
if (owner === null) return;
|
|
55
|
+
switch (change.type) {
|
|
56
|
+
case "remember":
|
|
57
|
+
mirror.write({ ownerId: owner, threadId: change.threadId, state: change.state, at: change.at });
|
|
58
|
+
return;
|
|
59
|
+
case "forget":
|
|
60
|
+
mirror.remove({ ownerId: owner, threadId: change.threadId });
|
|
61
|
+
return;
|
|
62
|
+
case "clear":
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
const offlineEntry = (threadId) => {
|
|
68
|
+
const entry = offline.get(threadId);
|
|
69
|
+
return entry && now() - entry.at <= offlineMaxAgeMs ? entry : void 0;
|
|
70
|
+
};
|
|
71
|
+
const dropEverything = () => {
|
|
72
|
+
memory.clear();
|
|
73
|
+
offline.clear();
|
|
74
|
+
restored.clear();
|
|
75
|
+
if (offlineSeeds.size > 0) {
|
|
76
|
+
offlineSeeds.clear();
|
|
77
|
+
notify();
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
remember(threadId, state) {
|
|
82
|
+
memory.remember(threadId, state);
|
|
83
|
+
restored.delete(threadId);
|
|
84
|
+
if (threadSnapshotMirror.isRestingThreadSnapshot(state)) keepOffline(threadId, { state, at: now() });
|
|
85
|
+
clearOfflineSeed(threadId);
|
|
86
|
+
},
|
|
87
|
+
take(threadId) {
|
|
88
|
+
if (!isOffline()) return memory.take(threadId);
|
|
89
|
+
const entry = offlineEntry(threadId);
|
|
90
|
+
if (!entry) return void 0;
|
|
91
|
+
if (offlineSeeds.get(threadId) !== entry.at) {
|
|
92
|
+
offlineSeeds.set(threadId, entry.at);
|
|
93
|
+
notify();
|
|
94
|
+
}
|
|
95
|
+
return entry.state;
|
|
96
|
+
},
|
|
97
|
+
peek(threadId) {
|
|
98
|
+
return isOffline() ? offlineEntry(threadId) !== void 0 : memory.peek(threadId);
|
|
99
|
+
},
|
|
100
|
+
forget(threadId) {
|
|
101
|
+
memory.forget(threadId);
|
|
102
|
+
offline.delete(threadId);
|
|
103
|
+
restored.delete(threadId);
|
|
104
|
+
clearOfflineSeed(threadId);
|
|
105
|
+
},
|
|
106
|
+
clear() {
|
|
107
|
+
dropEverything();
|
|
108
|
+
},
|
|
109
|
+
owner: () => ownerId,
|
|
110
|
+
setOwner(next) {
|
|
111
|
+
if (next === ownerId) return hydration;
|
|
112
|
+
const previous = ownerId;
|
|
113
|
+
ownerId = next;
|
|
114
|
+
epoch += 1;
|
|
115
|
+
dropEverything();
|
|
116
|
+
if (previous !== null) void mirror.clearOwner(previous);
|
|
117
|
+
if (next === null) {
|
|
118
|
+
hydration = Promise.resolve();
|
|
119
|
+
return hydration;
|
|
120
|
+
}
|
|
121
|
+
const readEpoch = epoch;
|
|
122
|
+
const read = (primed == null ? void 0 : primed.ownerId) === next ? primed.read : mirror.load(next);
|
|
123
|
+
primed = null;
|
|
124
|
+
hydration = read.then((entries) => {
|
|
125
|
+
if (readEpoch !== epoch || ownerId !== next) return;
|
|
126
|
+
for (const entry of entries) {
|
|
127
|
+
if (!offline.has(entry.threadId)) keepOffline(entry.threadId, { state: entry.state, at: entry.at });
|
|
128
|
+
if (memory.peek(entry.threadId)) continue;
|
|
129
|
+
memory.restore(entry.threadId, entry.state, entry.at);
|
|
130
|
+
if (memory.peek(entry.threadId)) restored.add(entry.threadId);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
return hydration;
|
|
134
|
+
},
|
|
135
|
+
prime(next) {
|
|
136
|
+
if (next === ownerId || (primed == null ? void 0 : primed.ownerId) === next) return;
|
|
137
|
+
primed = { ownerId: next, read: mirror.load(next) };
|
|
138
|
+
},
|
|
139
|
+
offlineSeedAt: (threadId) => offlineSeeds.get(threadId) ?? null,
|
|
140
|
+
subscribeOfflineSeeds(listener) {
|
|
141
|
+
listeners.add(listener);
|
|
142
|
+
return () => {
|
|
143
|
+
listeners.delete(listener);
|
|
144
|
+
};
|
|
145
|
+
},
|
|
146
|
+
isRestored: (threadId) => restored.has(threadId),
|
|
147
|
+
whenHydrated: () => hydration,
|
|
148
|
+
async wipe() {
|
|
149
|
+
epoch += 1;
|
|
150
|
+
primed = null;
|
|
151
|
+
dropEverything();
|
|
152
|
+
await mirror.clearAll();
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
exports.OFFLINE_SNAPSHOT_MAX_AGE_MS = OFFLINE_SNAPSHOT_MAX_AGE_MS;
|
|
157
|
+
exports.createDurableThreadSnapshotCache = createDurableThreadSnapshotCache;
|
|
158
|
+
//# sourceMappingURL=durable-thread-snapshot-cache.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"durable-thread-snapshot-cache.cjs","sources":["../../../../agent-runtime/src/durable-thread-snapshot-cache.ts"],"sourcesContent":["import {\n createDeepAgentThreadSnapshotCache,\n type DeepAgentThreadSnapshotCache,\n} from \"./thread-snapshot-cache\";\nimport { isRestingThreadSnapshot, type ThreadSnapshotMirror } from \"./thread-snapshot-mirror\";\nimport type { DeepAgentStreamValues } from \"./types\";\n\n/**\n * The thread snapshot cache with a durable, encrypted mirror behind it (`thread-snapshot-mirror.ts`):\n * a reload seeds a recently visited thread from what it last showed, and a thread can be read while\n * the transport cannot connect at all.\n *\n * - **Online, nothing changes.** `take` serves the in-memory entry within its age bound (one hour by\n * default), exactly as the plain cache does, and the attach snapshot replaces the seed.\n * - **Offline** (`isOffline()`: the host's own word that Athena can't be reached), `take` serves the\n * thread's last resting transcript this page holds (what it read, or what the mirror kept), up to\n * `offlineMaxAgeMs` old and past the online bound, so a person can read their recent\n * conversations on a plane. Never a mid-stream state: a run the connection dropped is a partial\n * transcript, and the resting one before it is what shows. Every offline seed, however recent, is\n * recorded with its capture time (`offlineSeedAt`) so the host can say the transcript is \"as of\"\n * then; only the next state the wire delivers for the thread (its attach) clears it.\n * - **Owned.** Entries belong to one owner (`setOwner`): a change drops every entry, deletes the\n * previous owner's mirrored records and reads the new owner's. A snapshot captured under one\n * account never seeds a mount under another. `wipe` drops everything (a sign-out).\n */\nexport interface DurableThreadSnapshotCache extends DeepAgentThreadSnapshotCache {\n peek(threadId: string): boolean;\n /** Bind the cache to the acting owner (`null`: nobody signed in; nothing is mirrored). */\n setOwner(ownerId: string | null): Promise<void>;\n /**\n * Start reading an owner's mirrored snapshots before the owner is known for sure (a host's\n * last-owner hint at boot): `setOwner` adopts the read if that owner is the one bound, and it\n * is discarded otherwise. Binds nothing and deletes nothing.\n */\n prime(ownerId: string): void;\n /** The owner the cache is bound to. */\n owner(): string | null;\n /**\n * When the seed `take` last served for `threadId` was captured, if it was served while Athena\n * could not be reached; `null` otherwise, and again once the wire delivers the thread.\n */\n offlineSeedAt(threadId: string): number | null;\n /** Calls `listener` whenever an offline seed is served or cleared; returns what stops it. */\n subscribeOfflineSeeds(listener: () => void): () => void;\n /** Whether the entry `take` would serve for `threadId` came back from the mirror. */\n isRestored(threadId: string): boolean;\n /** Resolves once the current owner's mirrored snapshots have been read (tests, telemetry). */\n whenHydrated(): Promise<void>;\n /** Drop every entry, in memory and in the mirror (a sign-out, a workspace switch). */\n wipe(): Promise<void>;\n}\n\nexport interface DurableThreadSnapshotCacheOptions {\n mirror: ThreadSnapshotMirror;\n /** Whether Athena can't be reached right now (the host's reachability, or the browser's). */\n isOffline?: () => boolean;\n maxThreads?: number;\n /** The online age bound (the plain cache's). */\n maxAgeMs?: number;\n /** How old a mirrored snapshot may be and still be read offline. */\n offlineMaxAgeMs?: number;\n now?: () => number;\n}\n\nconst DEFAULT_MAX_THREADS = 30;\n/** What a device keeps for reading offline: the offline plan's 30 days. */\nexport const OFFLINE_SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\n\nfunction browserOffline(): boolean {\n const host = globalThis as { navigator?: { onLine?: boolean } };\n return host.navigator?.onLine === false;\n}\n\nexport function createDurableThreadSnapshotCache({\n mirror,\n isOffline = browserOffline,\n maxThreads = DEFAULT_MAX_THREADS,\n maxAgeMs,\n offlineMaxAgeMs = OFFLINE_SNAPSHOT_MAX_AGE_MS,\n now = () => Date.now(),\n}: DurableThreadSnapshotCacheOptions): DurableThreadSnapshotCache {\n let ownerId: string | null = null;\n // Bumped on every owner change and wipe: a mirror read in flight then must not admit what it read.\n let epoch = 0;\n let primed: { ownerId: string; read: ReturnType<ThreadSnapshotMirror[\"load\"]> } | null = null;\n let hydration: Promise<void> = Promise.resolve();\n // Every resting snapshot readable offline (the mirror's, and this page's own), newest last.\n const offline = new Map<string, { state: DeepAgentStreamValues; at: number }>();\n const offlineSeeds = new Map<string, number>();\n const restored = new Set<string>();\n const listeners = new Set<() => void>();\n\n const notify = (): void => {\n for (const listener of listeners) {\n try {\n listener();\n } catch {\n // A host listener's fault never reaches the wire path.\n }\n }\n };\n const clearOfflineSeed = (threadId: string): void => {\n if (offlineSeeds.delete(threadId)) notify();\n };\n const keepOffline = (threadId: string, entry: { state: DeepAgentStreamValues; at: number }): void => {\n offline.delete(threadId);\n offline.set(threadId, entry);\n while (offline.size > maxThreads) {\n const oldest = offline.keys().next().value;\n if (oldest === undefined) break;\n offline.delete(oldest);\n }\n };\n\n const memory = createDeepAgentThreadSnapshotCache({\n maxThreads,\n maxAgeMs,\n now,\n onChange: (change) => {\n const owner = ownerId;\n if (owner === null) return;\n switch (change.type) {\n case \"remember\":\n mirror.write({ ownerId: owner, threadId: change.threadId, state: change.state, at: change.at });\n return;\n case \"forget\":\n mirror.remove({ ownerId: owner, threadId: change.threadId });\n return;\n case \"clear\":\n return;\n }\n },\n });\n\n /** The thread's last resting transcript within the offline bound. */\n const offlineEntry = (threadId: string): { state: DeepAgentStreamValues; at: number } | undefined => {\n const entry = offline.get(threadId);\n return entry && now() - entry.at <= offlineMaxAgeMs ? entry : undefined;\n };\n\n const dropEverything = (): void => {\n memory.clear();\n offline.clear();\n restored.clear();\n if (offlineSeeds.size > 0) {\n offlineSeeds.clear();\n notify();\n }\n };\n\n return {\n remember(threadId, state) {\n memory.remember(threadId, state);\n restored.delete(threadId);\n // A mid-stream state keeps the resting transcript before it readable offline, as the mirror\n // keeps that one's record. One too long to seal still reads from memory.\n if (isRestingThreadSnapshot(state)) keepOffline(threadId, { state, at: now() });\n // The wire delivered the thread: the transcript is current again.\n clearOfflineSeed(threadId);\n },\n take(threadId) {\n if (!isOffline()) return memory.take(threadId);\n const entry = offlineEntry(threadId);\n if (!entry) return undefined;\n if (offlineSeeds.get(threadId) !== entry.at) {\n offlineSeeds.set(threadId, entry.at);\n notify();\n }\n return entry.state;\n },\n peek(threadId) {\n return isOffline() ? offlineEntry(threadId) !== undefined : memory.peek(threadId);\n },\n forget(threadId) {\n memory.forget(threadId);\n offline.delete(threadId);\n restored.delete(threadId);\n clearOfflineSeed(threadId);\n },\n clear() {\n dropEverything();\n },\n owner: () => ownerId,\n setOwner(next) {\n if (next === ownerId) return hydration;\n const previous = ownerId;\n ownerId = next;\n epoch += 1;\n dropEverything();\n if (previous !== null) void mirror.clearOwner(previous);\n if (next === null) {\n hydration = Promise.resolve();\n return hydration;\n }\n const readEpoch = epoch;\n const read = primed?.ownerId === next ? primed.read : mirror.load(next);\n primed = null;\n hydration = read.then((entries) => {\n // The owner moved on, or everything was wiped, while the read was in flight.\n if (readEpoch !== epoch || ownerId !== next) return;\n for (const entry of entries) {\n if (!offline.has(entry.threadId)) keepOffline(entry.threadId, { state: entry.state, at: entry.at });\n if (memory.peek(entry.threadId)) continue;\n memory.restore(entry.threadId, entry.state, entry.at);\n if (memory.peek(entry.threadId)) restored.add(entry.threadId);\n }\n });\n return hydration;\n },\n prime(next) {\n if (next === ownerId || primed?.ownerId === next) return;\n primed = { ownerId: next, read: mirror.load(next) };\n },\n offlineSeedAt: (threadId) => offlineSeeds.get(threadId) ?? null,\n subscribeOfflineSeeds(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n isRestored: (threadId) => restored.has(threadId),\n whenHydrated: () => hydration,\n async wipe() {\n epoch += 1;\n primed = null;\n dropEverything();\n await mirror.clearAll();\n },\n };\n}\n"],"names":["createDeepAgentThreadSnapshotCache","isRestingThreadSnapshot"],"mappings":";;;;AAgEA,MAAM,sBAAsB;AAErB,MAAM,8BAA8B,KAAK,KAAK,KAAK,KAAK;AAE/D,SAAS,iBAA0B;;AACjC,QAAM,OAAO;AACb,WAAO,UAAK,cAAL,mBAAgB,YAAW;AACpC;AAEO,SAAS,iCAAiC;AAAA,EAC/C;AAAA,EACA,YAAY;AAAA,EACZ,aAAa;AAAA,EACb;AAAA,EACA,kBAAkB;AAAA,EAClB,MAAM,MAAM,KAAK,IAAA;AACnB,GAAkE;AAChE,MAAI,UAAyB;AAE7B,MAAI,QAAQ;AACZ,MAAI,SAAqF;AACzF,MAAI,YAA2B,QAAQ,QAAA;AAEvC,QAAM,8BAAc,IAAA;AACpB,QAAM,mCAAmB,IAAA;AACzB,QAAM,+BAAe,IAAA;AACrB,QAAM,gCAAgB,IAAA;AAEtB,QAAM,SAAS,MAAY;AACzB,eAAW,YAAY,WAAW;AAChC,UAAI;AACF,iBAAA;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACA,QAAM,mBAAmB,CAAC,aAA2B;AACnD,QAAI,aAAa,OAAO,QAAQ,EAAG,QAAA;AAAA,EACrC;AACA,QAAM,cAAc,CAAC,UAAkB,UAA8D;AACnG,YAAQ,OAAO,QAAQ;AACvB,YAAQ,IAAI,UAAU,KAAK;AAC3B,WAAO,QAAQ,OAAO,YAAY;AAChC,YAAM,SAAS,QAAQ,KAAA,EAAO,OAAO;AACrC,UAAI,WAAW,OAAW;AAC1B,cAAQ,OAAO,MAAM;AAAA,IACvB;AAAA,EACF;AAEA,QAAM,SAASA,oBAAAA,mCAAmC;AAAA,IAChD;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU,CAAC,WAAW;AACpB,YAAM,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B;AAAA,IACF;AAAA,IACA,YAAY,CAAC,aAAa,SAAS,IAAI,QAAQ;AAAA,IAC/C,cAAc,MAAM;AAAA,IACpB,MAAM,OAAO;AACX,eAAS;AACT,eAAS;AACT,qBAAA;AACA,YAAM,OAAO,SAAA;AAAA,IACf;AAAA,EAAA;AAEJ;;;"}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { createDeepAgentThreadSnapshotCache } from "./thread-snapshot-cache.js";
|
|
2
|
+
import { isRestingThreadSnapshot } from "./thread-snapshot-mirror.js";
|
|
3
|
+
const DEFAULT_MAX_THREADS = 30;
|
|
4
|
+
const OFFLINE_SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
5
|
+
function browserOffline() {
|
|
6
|
+
var _a;
|
|
7
|
+
const host = globalThis;
|
|
8
|
+
return ((_a = host.navigator) == null ? void 0 : _a.onLine) === false;
|
|
9
|
+
}
|
|
10
|
+
function createDurableThreadSnapshotCache({
|
|
11
|
+
mirror,
|
|
12
|
+
isOffline = browserOffline,
|
|
13
|
+
maxThreads = DEFAULT_MAX_THREADS,
|
|
14
|
+
maxAgeMs,
|
|
15
|
+
offlineMaxAgeMs = OFFLINE_SNAPSHOT_MAX_AGE_MS,
|
|
16
|
+
now = () => Date.now()
|
|
17
|
+
}) {
|
|
18
|
+
let ownerId = null;
|
|
19
|
+
let epoch = 0;
|
|
20
|
+
let primed = null;
|
|
21
|
+
let hydration = Promise.resolve();
|
|
22
|
+
const offline = /* @__PURE__ */ new Map();
|
|
23
|
+
const offlineSeeds = /* @__PURE__ */ new Map();
|
|
24
|
+
const restored = /* @__PURE__ */ new Set();
|
|
25
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
26
|
+
const notify = () => {
|
|
27
|
+
for (const listener of listeners) {
|
|
28
|
+
try {
|
|
29
|
+
listener();
|
|
30
|
+
} catch {
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
const clearOfflineSeed = (threadId) => {
|
|
35
|
+
if (offlineSeeds.delete(threadId)) notify();
|
|
36
|
+
};
|
|
37
|
+
const keepOffline = (threadId, entry) => {
|
|
38
|
+
offline.delete(threadId);
|
|
39
|
+
offline.set(threadId, entry);
|
|
40
|
+
while (offline.size > maxThreads) {
|
|
41
|
+
const oldest = offline.keys().next().value;
|
|
42
|
+
if (oldest === void 0) break;
|
|
43
|
+
offline.delete(oldest);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const memory = createDeepAgentThreadSnapshotCache({
|
|
47
|
+
maxThreads,
|
|
48
|
+
maxAgeMs,
|
|
49
|
+
now,
|
|
50
|
+
onChange: (change) => {
|
|
51
|
+
const owner = ownerId;
|
|
52
|
+
if (owner === null) return;
|
|
53
|
+
switch (change.type) {
|
|
54
|
+
case "remember":
|
|
55
|
+
mirror.write({ ownerId: owner, threadId: change.threadId, state: change.state, at: change.at });
|
|
56
|
+
return;
|
|
57
|
+
case "forget":
|
|
58
|
+
mirror.remove({ ownerId: owner, threadId: change.threadId });
|
|
59
|
+
return;
|
|
60
|
+
case "clear":
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
const offlineEntry = (threadId) => {
|
|
66
|
+
const entry = offline.get(threadId);
|
|
67
|
+
return entry && now() - entry.at <= offlineMaxAgeMs ? entry : void 0;
|
|
68
|
+
};
|
|
69
|
+
const dropEverything = () => {
|
|
70
|
+
memory.clear();
|
|
71
|
+
offline.clear();
|
|
72
|
+
restored.clear();
|
|
73
|
+
if (offlineSeeds.size > 0) {
|
|
74
|
+
offlineSeeds.clear();
|
|
75
|
+
notify();
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
remember(threadId, state) {
|
|
80
|
+
memory.remember(threadId, state);
|
|
81
|
+
restored.delete(threadId);
|
|
82
|
+
if (isRestingThreadSnapshot(state)) keepOffline(threadId, { state, at: now() });
|
|
83
|
+
clearOfflineSeed(threadId);
|
|
84
|
+
},
|
|
85
|
+
take(threadId) {
|
|
86
|
+
if (!isOffline()) return memory.take(threadId);
|
|
87
|
+
const entry = offlineEntry(threadId);
|
|
88
|
+
if (!entry) return void 0;
|
|
89
|
+
if (offlineSeeds.get(threadId) !== entry.at) {
|
|
90
|
+
offlineSeeds.set(threadId, entry.at);
|
|
91
|
+
notify();
|
|
92
|
+
}
|
|
93
|
+
return entry.state;
|
|
94
|
+
},
|
|
95
|
+
peek(threadId) {
|
|
96
|
+
return isOffline() ? offlineEntry(threadId) !== void 0 : memory.peek(threadId);
|
|
97
|
+
},
|
|
98
|
+
forget(threadId) {
|
|
99
|
+
memory.forget(threadId);
|
|
100
|
+
offline.delete(threadId);
|
|
101
|
+
restored.delete(threadId);
|
|
102
|
+
clearOfflineSeed(threadId);
|
|
103
|
+
},
|
|
104
|
+
clear() {
|
|
105
|
+
dropEverything();
|
|
106
|
+
},
|
|
107
|
+
owner: () => ownerId,
|
|
108
|
+
setOwner(next) {
|
|
109
|
+
if (next === ownerId) return hydration;
|
|
110
|
+
const previous = ownerId;
|
|
111
|
+
ownerId = next;
|
|
112
|
+
epoch += 1;
|
|
113
|
+
dropEverything();
|
|
114
|
+
if (previous !== null) void mirror.clearOwner(previous);
|
|
115
|
+
if (next === null) {
|
|
116
|
+
hydration = Promise.resolve();
|
|
117
|
+
return hydration;
|
|
118
|
+
}
|
|
119
|
+
const readEpoch = epoch;
|
|
120
|
+
const read = (primed == null ? void 0 : primed.ownerId) === next ? primed.read : mirror.load(next);
|
|
121
|
+
primed = null;
|
|
122
|
+
hydration = read.then((entries) => {
|
|
123
|
+
if (readEpoch !== epoch || ownerId !== next) return;
|
|
124
|
+
for (const entry of entries) {
|
|
125
|
+
if (!offline.has(entry.threadId)) keepOffline(entry.threadId, { state: entry.state, at: entry.at });
|
|
126
|
+
if (memory.peek(entry.threadId)) continue;
|
|
127
|
+
memory.restore(entry.threadId, entry.state, entry.at);
|
|
128
|
+
if (memory.peek(entry.threadId)) restored.add(entry.threadId);
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
return hydration;
|
|
132
|
+
},
|
|
133
|
+
prime(next) {
|
|
134
|
+
if (next === ownerId || (primed == null ? void 0 : primed.ownerId) === next) return;
|
|
135
|
+
primed = { ownerId: next, read: mirror.load(next) };
|
|
136
|
+
},
|
|
137
|
+
offlineSeedAt: (threadId) => offlineSeeds.get(threadId) ?? null,
|
|
138
|
+
subscribeOfflineSeeds(listener) {
|
|
139
|
+
listeners.add(listener);
|
|
140
|
+
return () => {
|
|
141
|
+
listeners.delete(listener);
|
|
142
|
+
};
|
|
143
|
+
},
|
|
144
|
+
isRestored: (threadId) => restored.has(threadId),
|
|
145
|
+
whenHydrated: () => hydration,
|
|
146
|
+
async wipe() {
|
|
147
|
+
epoch += 1;
|
|
148
|
+
primed = null;
|
|
149
|
+
dropEverything();
|
|
150
|
+
await mirror.clearAll();
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
export {
|
|
155
|
+
OFFLINE_SNAPSHOT_MAX_AGE_MS,
|
|
156
|
+
createDurableThreadSnapshotCache
|
|
157
|
+
};
|
|
158
|
+
//# sourceMappingURL=durable-thread-snapshot-cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"durable-thread-snapshot-cache.js","sources":["../../../../agent-runtime/src/durable-thread-snapshot-cache.ts"],"sourcesContent":["import {\n createDeepAgentThreadSnapshotCache,\n type DeepAgentThreadSnapshotCache,\n} from \"./thread-snapshot-cache\";\nimport { isRestingThreadSnapshot, type ThreadSnapshotMirror } from \"./thread-snapshot-mirror\";\nimport type { DeepAgentStreamValues } from \"./types\";\n\n/**\n * The thread snapshot cache with a durable, encrypted mirror behind it (`thread-snapshot-mirror.ts`):\n * a reload seeds a recently visited thread from what it last showed, and a thread can be read while\n * the transport cannot connect at all.\n *\n * - **Online, nothing changes.** `take` serves the in-memory entry within its age bound (one hour by\n * default), exactly as the plain cache does, and the attach snapshot replaces the seed.\n * - **Offline** (`isOffline()`: the host's own word that Athena can't be reached), `take` serves the\n * thread's last resting transcript this page holds (what it read, or what the mirror kept), up to\n * `offlineMaxAgeMs` old and past the online bound, so a person can read their recent\n * conversations on a plane. Never a mid-stream state: a run the connection dropped is a partial\n * transcript, and the resting one before it is what shows. Every offline seed, however recent, is\n * recorded with its capture time (`offlineSeedAt`) so the host can say the transcript is \"as of\"\n * then; only the next state the wire delivers for the thread (its attach) clears it.\n * - **Owned.** Entries belong to one owner (`setOwner`): a change drops every entry, deletes the\n * previous owner's mirrored records and reads the new owner's. A snapshot captured under one\n * account never seeds a mount under another. `wipe` drops everything (a sign-out).\n */\nexport interface DurableThreadSnapshotCache extends DeepAgentThreadSnapshotCache {\n peek(threadId: string): boolean;\n /** Bind the cache to the acting owner (`null`: nobody signed in; nothing is mirrored). */\n setOwner(ownerId: string | null): Promise<void>;\n /**\n * Start reading an owner's mirrored snapshots before the owner is known for sure (a host's\n * last-owner hint at boot): `setOwner` adopts the read if that owner is the one bound, and it\n * is discarded otherwise. Binds nothing and deletes nothing.\n */\n prime(ownerId: string): void;\n /** The owner the cache is bound to. */\n owner(): string | null;\n /**\n * When the seed `take` last served for `threadId` was captured, if it was served while Athena\n * could not be reached; `null` otherwise, and again once the wire delivers the thread.\n */\n offlineSeedAt(threadId: string): number | null;\n /** Calls `listener` whenever an offline seed is served or cleared; returns what stops it. */\n subscribeOfflineSeeds(listener: () => void): () => void;\n /** Whether the entry `take` would serve for `threadId` came back from the mirror. */\n isRestored(threadId: string): boolean;\n /** Resolves once the current owner's mirrored snapshots have been read (tests, telemetry). */\n whenHydrated(): Promise<void>;\n /** Drop every entry, in memory and in the mirror (a sign-out, a workspace switch). */\n wipe(): Promise<void>;\n}\n\nexport interface DurableThreadSnapshotCacheOptions {\n mirror: ThreadSnapshotMirror;\n /** Whether Athena can't be reached right now (the host's reachability, or the browser's). */\n isOffline?: () => boolean;\n maxThreads?: number;\n /** The online age bound (the plain cache's). */\n maxAgeMs?: number;\n /** How old a mirrored snapshot may be and still be read offline. */\n offlineMaxAgeMs?: number;\n now?: () => number;\n}\n\nconst DEFAULT_MAX_THREADS = 30;\n/** What a device keeps for reading offline: the offline plan's 30 days. */\nexport const OFFLINE_SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\n\nfunction browserOffline(): boolean {\n const host = globalThis as { navigator?: { onLine?: boolean } };\n return host.navigator?.onLine === false;\n}\n\nexport function createDurableThreadSnapshotCache({\n mirror,\n isOffline = browserOffline,\n maxThreads = DEFAULT_MAX_THREADS,\n maxAgeMs,\n offlineMaxAgeMs = OFFLINE_SNAPSHOT_MAX_AGE_MS,\n now = () => Date.now(),\n}: DurableThreadSnapshotCacheOptions): DurableThreadSnapshotCache {\n let ownerId: string | null = null;\n // Bumped on every owner change and wipe: a mirror read in flight then must not admit what it read.\n let epoch = 0;\n let primed: { ownerId: string; read: ReturnType<ThreadSnapshotMirror[\"load\"]> } | null = null;\n let hydration: Promise<void> = Promise.resolve();\n // Every resting snapshot readable offline (the mirror's, and this page's own), newest last.\n const offline = new Map<string, { state: DeepAgentStreamValues; at: number }>();\n const offlineSeeds = new Map<string, number>();\n const restored = new Set<string>();\n const listeners = new Set<() => void>();\n\n const notify = (): void => {\n for (const listener of listeners) {\n try {\n listener();\n } catch {\n // A host listener's fault never reaches the wire path.\n }\n }\n };\n const clearOfflineSeed = (threadId: string): void => {\n if (offlineSeeds.delete(threadId)) notify();\n };\n const keepOffline = (threadId: string, entry: { state: DeepAgentStreamValues; at: number }): void => {\n offline.delete(threadId);\n offline.set(threadId, entry);\n while (offline.size > maxThreads) {\n const oldest = offline.keys().next().value;\n if (oldest === undefined) break;\n offline.delete(oldest);\n }\n };\n\n const memory = createDeepAgentThreadSnapshotCache({\n maxThreads,\n maxAgeMs,\n now,\n onChange: (change) => {\n const owner = ownerId;\n if (owner === null) return;\n switch (change.type) {\n case \"remember\":\n mirror.write({ ownerId: owner, threadId: change.threadId, state: change.state, at: change.at });\n return;\n case \"forget\":\n mirror.remove({ ownerId: owner, threadId: change.threadId });\n return;\n case \"clear\":\n return;\n }\n },\n });\n\n /** The thread's last resting transcript within the offline bound. */\n const offlineEntry = (threadId: string): { state: DeepAgentStreamValues; at: number } | undefined => {\n const entry = offline.get(threadId);\n return entry && now() - entry.at <= offlineMaxAgeMs ? entry : undefined;\n };\n\n const dropEverything = (): void => {\n memory.clear();\n offline.clear();\n restored.clear();\n if (offlineSeeds.size > 0) {\n offlineSeeds.clear();\n notify();\n }\n };\n\n return {\n remember(threadId, state) {\n memory.remember(threadId, state);\n restored.delete(threadId);\n // A mid-stream state keeps the resting transcript before it readable offline, as the mirror\n // keeps that one's record. One too long to seal still reads from memory.\n if (isRestingThreadSnapshot(state)) keepOffline(threadId, { state, at: now() });\n // The wire delivered the thread: the transcript is current again.\n clearOfflineSeed(threadId);\n },\n take(threadId) {\n if (!isOffline()) return memory.take(threadId);\n const entry = offlineEntry(threadId);\n if (!entry) return undefined;\n if (offlineSeeds.get(threadId) !== entry.at) {\n offlineSeeds.set(threadId, entry.at);\n notify();\n }\n return entry.state;\n },\n peek(threadId) {\n return isOffline() ? offlineEntry(threadId) !== undefined : memory.peek(threadId);\n },\n forget(threadId) {\n memory.forget(threadId);\n offline.delete(threadId);\n restored.delete(threadId);\n clearOfflineSeed(threadId);\n },\n clear() {\n dropEverything();\n },\n owner: () => ownerId,\n setOwner(next) {\n if (next === ownerId) return hydration;\n const previous = ownerId;\n ownerId = next;\n epoch += 1;\n dropEverything();\n if (previous !== null) void mirror.clearOwner(previous);\n if (next === null) {\n hydration = Promise.resolve();\n return hydration;\n }\n const readEpoch = epoch;\n const read = primed?.ownerId === next ? primed.read : mirror.load(next);\n primed = null;\n hydration = read.then((entries) => {\n // The owner moved on, or everything was wiped, while the read was in flight.\n if (readEpoch !== epoch || ownerId !== next) return;\n for (const entry of entries) {\n if (!offline.has(entry.threadId)) keepOffline(entry.threadId, { state: entry.state, at: entry.at });\n if (memory.peek(entry.threadId)) continue;\n memory.restore(entry.threadId, entry.state, entry.at);\n if (memory.peek(entry.threadId)) restored.add(entry.threadId);\n }\n });\n return hydration;\n },\n prime(next) {\n if (next === ownerId || primed?.ownerId === next) return;\n primed = { ownerId: next, read: mirror.load(next) };\n },\n offlineSeedAt: (threadId) => offlineSeeds.get(threadId) ?? null,\n subscribeOfflineSeeds(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n isRestored: (threadId) => restored.has(threadId),\n whenHydrated: () => hydration,\n async wipe() {\n epoch += 1;\n primed = null;\n dropEverything();\n await mirror.clearAll();\n },\n };\n}\n"],"names":[],"mappings":";;AAgEA,MAAM,sBAAsB;AAErB,MAAM,8BAA8B,KAAK,KAAK,KAAK,KAAK;AAE/D,SAAS,iBAA0B;;AACjC,QAAM,OAAO;AACb,WAAO,UAAK,cAAL,mBAAgB,YAAW;AACpC;AAEO,SAAS,iCAAiC;AAAA,EAC/C;AAAA,EACA,YAAY;AAAA,EACZ,aAAa;AAAA,EACb;AAAA,EACA,kBAAkB;AAAA,EAClB,MAAM,MAAM,KAAK,IAAA;AACnB,GAAkE;AAChE,MAAI,UAAyB;AAE7B,MAAI,QAAQ;AACZ,MAAI,SAAqF;AACzF,MAAI,YAA2B,QAAQ,QAAA;AAEvC,QAAM,8BAAc,IAAA;AACpB,QAAM,mCAAmB,IAAA;AACzB,QAAM,+BAAe,IAAA;AACrB,QAAM,gCAAgB,IAAA;AAEtB,QAAM,SAAS,MAAY;AACzB,eAAW,YAAY,WAAW;AAChC,UAAI;AACF,iBAAA;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACA,QAAM,mBAAmB,CAAC,aAA2B;AACnD,QAAI,aAAa,OAAO,QAAQ,EAAG,QAAA;AAAA,EACrC;AACA,QAAM,cAAc,CAAC,UAAkB,UAA8D;AACnG,YAAQ,OAAO,QAAQ;AACvB,YAAQ,IAAI,UAAU,KAAK;AAC3B,WAAO,QAAQ,OAA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AAS,MAAM,MAAM,OAAO,KAAK,IAAI,EAAA;AAAA,IAClD;AAAA,IACA,eAAe,CAAC,aAAa,aAAa,IAAI,QAAQ,KAAK;AAAA,IAC3D,sBAAsB,UAAU;AAC9B,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM;AACX,kBAAU,OAAO,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,IACA,YAAY,CAAC,aAAa,SAAS,IAAI,QAAQ;AAAA,IAC/C,cAAc,MAAM;AAAA,IACpB,MAAM,OAAO;AACX,eAAS;AACT,eAAS;AACT,qBAAA;AACA,YAAM,OAAO,SAAA;AAAA,IACf;AAAA,EAAA;AAEJ;"}
|
|
@@ -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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ACvB,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;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"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AAY,SAAS,MAAM,GAAI;AACnC,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];
|