@radheim/client 0.0.0-stage → 2.4.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.
Files changed (100) hide show
  1. package/README.md +27 -3
  2. package/dist/chunks/contract-0d78mgf1.js +52 -0
  3. package/dist/chunks/contract-20jd153t.js +2089 -0
  4. package/dist/chunks/contract-2h09qg7t.js +62 -0
  5. package/dist/chunks/contract-5f99ddep.js +149 -0
  6. package/dist/chunks/contract-6mptkzbc.js +0 -0
  7. package/dist/chunks/contract-6mq2wh8y.js +33 -0
  8. package/dist/chunks/contract-6r38tsk5.js +0 -0
  9. package/dist/chunks/contract-6sr7f8yw.js +92 -0
  10. package/dist/chunks/contract-850x4mfy.js +948 -0
  11. package/dist/chunks/contract-8s2anffy.js +11 -0
  12. package/dist/chunks/contract-96mz1w8q.js +104 -0
  13. package/dist/chunks/contract-9rqn6x4v.js +16 -0
  14. package/dist/chunks/contract-d9s8wkgw.js +2082 -0
  15. package/dist/chunks/contract-mn9bt8t4.js +4 -0
  16. package/dist/chunks/contract-mwrzahmf.js +38 -0
  17. package/dist/chunks/contract-n4yq1n4a.js +111 -0
  18. package/dist/chunks/contract-nwcpakzx.js +12 -0
  19. package/dist/chunks/contract-qav6mfdz.js +0 -0
  20. package/dist/chunks/contract-qtt7zwr0.js +30 -0
  21. package/dist/chunks/contract-rhrawkx2.js +49 -0
  22. package/dist/chunks/contract-rrraq56y.js +67 -0
  23. package/dist/chunks/contract-sxt88q69.js +12 -0
  24. package/dist/chunks/contract-t5nrycbt.js +39 -0
  25. package/dist/chunks/contract-vyas3vgt.js +0 -0
  26. package/dist/chunks/contract-xgnj2w4v.js +20 -0
  27. package/dist/chunks/contract-y2etg5bs.js +9 -0
  28. package/dist/chunks/contract-ydhz1zrh.js +238 -0
  29. package/dist/chunks/contract-ztxd8xjp.js +81 -0
  30. package/dist/contract.d.ts +1 -0
  31. package/dist/contract.js +14 -0
  32. package/dist/effect/api/api.d.ts +3744 -0
  33. package/dist/effect/api/api.js +0 -0
  34. package/dist/effect/api.d.ts +5 -0
  35. package/dist/effect/api.js +0 -0
  36. package/dist/effect/client.d.ts +3129 -0
  37. package/dist/effect/client.js +15 -0
  38. package/dist/effect/generated/client-error.d.ts +7 -0
  39. package/dist/effect/generated/client-error.js +6 -0
  40. package/dist/effect/generated/client.d.ts +3158 -0
  41. package/dist/effect/generated/client.js +8 -0
  42. package/dist/effect/generated/index.d.ts +2 -0
  43. package/dist/effect/generated/index.js +12 -0
  44. package/dist/effect/index.d.ts +35 -0
  45. package/dist/effect/index.js +75 -0
  46. package/dist/effect/rpc.d.ts +20 -0
  47. package/dist/effect/rpc.js +11 -0
  48. package/dist/effect/service.d.ts +90 -0
  49. package/dist/effect/service.js +187 -0
  50. package/dist/mcp.d.ts +44 -0
  51. package/dist/mcp.js +110 -0
  52. package/dist/promise/api.d.ts +25 -0
  53. package/dist/promise/api.js +0 -0
  54. package/dist/promise/client.d.ts +414 -0
  55. package/dist/promise/client.js +14 -0
  56. package/dist/promise/generated/client-error.d.ts +8 -0
  57. package/dist/promise/generated/client-error.js +6 -0
  58. package/dist/promise/generated/client.d.ts +456 -0
  59. package/dist/promise/generated/client.js +7 -0
  60. package/dist/promise/generated/index.d.ts +3 -0
  61. package/dist/promise/generated/index.js +105 -0
  62. package/dist/promise/generated/types.d.ts +6642 -0
  63. package/dist/promise/generated/types.js +96 -0
  64. package/dist/promise/index.d.ts +8 -0
  65. package/dist/promise/index.js +115 -0
  66. package/dist/promise/media.d.ts +424 -0
  67. package/dist/promise/media.js +8 -0
  68. package/dist/promise/rpc.d.ts +32 -0
  69. package/dist/promise/rpc.js +7 -0
  70. package/dist/promise/service.d.ts +24 -0
  71. package/dist/promise/service.js +188 -0
  72. package/dist/pty-handoff.d.ts +12 -0
  73. package/dist/pty-handoff.js +17 -0
  74. package/dist/rpc-runtime.d.ts +20 -0
  75. package/dist/rpc-runtime.js +14 -0
  76. package/dist/service-contender.d.ts +37 -0
  77. package/dist/service-contender.js +10 -0
  78. package/dist/service-probe.d.ts +74 -0
  79. package/dist/service-probe.js +16 -0
  80. package/dist/service-timing.d.ts +12 -0
  81. package/dist/service-timing.js +10 -0
  82. package/dist/service-version.d.ts +2 -0
  83. package/dist/service-version.js +6 -0
  84. package/dist/service.d.ts +52 -0
  85. package/dist/service.js +1 -0
  86. package/dist/shared-events.d.ts +16 -0
  87. package/dist/shared-events.js +8 -0
  88. package/dist/solid/connection.d.ts +37 -0
  89. package/dist/solid/connection.js +10 -0
  90. package/dist/solid/data.d.ts +238 -0
  91. package/dist/solid/data.js +19 -0
  92. package/dist/solid/index.d.ts +5 -0
  93. package/dist/solid/index.js +45 -0
  94. package/dist/solid/pty.d.ts +80 -0
  95. package/dist/solid/pty.js +12 -0
  96. package/dist/solid/retention.d.ts +10 -0
  97. package/dist/solid/retention.js +6 -0
  98. package/dist/solid/usage.d.ts +9 -0
  99. package/dist/solid/usage.js +6 -0
  100. package/package.json +89 -4
@@ -0,0 +1,2089 @@
1
+ import {
2
+ ClientError3
3
+ } from "./contract-nwcpakzx.js";
4
+ import {
5
+ isSessionNotFoundError2,
6
+ isMessageNotFoundError2,
7
+ isFormNotFoundError2,
8
+ isFormAlreadySettledError2,
9
+ isPermissionNotFoundError2
10
+ } from "./contract-rhrawkx2.js";
11
+
12
+ // src/solid/data.ts
13
+ import { Worktree } from "@radheim/schema/worktree";
14
+ import { SessionID } from "@radheim/schema/session-id";
15
+ import { SessionMessage } from "@radheim/schema/session-message";
16
+ import { createStore, produce, reconcile } from "solid-js/store";
17
+ import { batch, createEffect, createMemo, createSignal, onCleanup } from "solid-js";
18
+ var messagePageLimit = 20;
19
+ var bridgePageLimits = [20, 40, 140];
20
+ var settleMs2 = 150;
21
+ function locationKey2(location) {
22
+ return JSON.stringify([location.directory, location.workspaceID]);
23
+ }
24
+ var catalogEvents = [
25
+ "provider.updated",
26
+ "model.updated",
27
+ "agent.updated",
28
+ "command.updated",
29
+ "skill.updated"
30
+ ];
31
+ function isCatalogEvent(type) {
32
+ return catalogEvents.some((catalog) => catalog === type);
33
+ }
34
+ function locationQuery(ref) {
35
+ return { directory: ref.directory };
36
+ }
37
+ function optimisticFiles(files) {
38
+ const items = files?.flatMap((file) => {
39
+ if (!file.uri.startsWith("data:"))
40
+ return [];
41
+ const comma = file.uri.indexOf(",");
42
+ if (comma < 0)
43
+ return [];
44
+ const header = file.uri.slice(5, comma);
45
+ const parts = header.split(";");
46
+ if (!parts.slice(1).some((part) => part.toLowerCase() === "base64"))
47
+ return [];
48
+ const item = {
49
+ data: file.uri.slice(comma + 1),
50
+ mime: parts[0] || "application/octet-stream",
51
+ source: { type: "inline" }
52
+ };
53
+ if (file.name !== undefined)
54
+ item.name = file.name;
55
+ if (file.description !== undefined)
56
+ item.description = file.description;
57
+ if (file.mention !== undefined)
58
+ item.mention = { ...file.mention };
59
+ return [item];
60
+ });
61
+ return items?.length ? items : undefined;
62
+ }
63
+ function omitFileData(content) {
64
+ const omit = (item) => item.type === "file" && item.uri.startsWith("data:") ? { ...item, uri: `data:${item.mime};base64,` } : item;
65
+ return [omit(content[0]), ...content.slice(1).map(omit)];
66
+ }
67
+ var hasFileData = (part) => part.type === "tool" && ("content" in part.state) && !!part.state.content?.some((item) => item.type === "file" && item.uri.startsWith("data:"));
68
+ var isDroppedFile = (item) => item.type === "file" && item.uri === `data:${item.mime};base64,`;
69
+ var hasDroppedFileData = (message) => message.type === "assistant" && message.content.some((part) => part.type === "tool" && ("content" in part.state) && !!part.state.content?.some(isDroppedFile));
70
+ var unsettled = (message) => message.type === "assistant" ? !message.time.completed || message.content.some((part) => part.type === "tool" && (part.state.status === "streaming" || part.state.status === "running")) : (message.type === "shell" || message.type === "compaction") && message.status === "running";
71
+ function apart(history, fetched) {
72
+ const oldest = history[0];
73
+ const first = fetched[0];
74
+ if (!oldest || !first)
75
+ return false;
76
+ return !history.some((item) => item.id === first.id) && !fetched.some((item) => item.id === oldest.id);
77
+ }
78
+ function before(history, fetched) {
79
+ const at = history.findIndex((item) => item.id === fetched[0]?.id);
80
+ return at < 0 ? undefined : history.slice(0, at);
81
+ }
82
+ function omitMessageFileData(message) {
83
+ if (message.type !== "assistant" || !message.content.some(hasFileData))
84
+ return message;
85
+ return {
86
+ ...message,
87
+ content: message.content.map((part) => part.type === "tool" && ("content" in part.state) && part.state.content ? { ...part, state: { ...part.state, content: omitFileData(part.state.content) } } : part)
88
+ };
89
+ }
90
+ function formRequestOptions(sessionID, ref) {
91
+ if (sessionID !== "global" || !ref)
92
+ return;
93
+ return {
94
+ headers: {
95
+ "x-opencode-directory": encodeURIComponent(ref.directory)
96
+ }
97
+ };
98
+ }
99
+ function createSync() {
100
+ const state = new Map;
101
+ const start = (key, load, wait) => {
102
+ const entry = { promise: Promise.resolve(), invalidated: false, started: !wait };
103
+ state.set(key, entry);
104
+ const run = () => {
105
+ entry.started = true;
106
+ return load();
107
+ };
108
+ entry.promise = (wait ? wait.catch(() => {
109
+ return;
110
+ }).then(run) : run()).then(() => {
111
+ if (state.get(key) === entry && !entry.invalidated)
112
+ state.set(key, true);
113
+ }).finally(() => {
114
+ if (state.get(key) === entry)
115
+ state.delete(key);
116
+ });
117
+ return entry.promise;
118
+ };
119
+ return {
120
+ run(key, load) {
121
+ const active = state.get(key);
122
+ if (active === true)
123
+ return Promise.resolve();
124
+ if (!active)
125
+ return start(key, load);
126
+ if (!active.invalidated)
127
+ return active.promise;
128
+ return start(key, load, active.promise);
129
+ },
130
+ complete(key) {
131
+ if (state.has(key))
132
+ return;
133
+ state.set(key, true);
134
+ },
135
+ has(key) {
136
+ return state.has(key);
137
+ },
138
+ pending(key) {
139
+ const active = state.get(key);
140
+ return active !== undefined && active !== true;
141
+ },
142
+ invalidate(key) {
143
+ if (key) {
144
+ const active = state.get(key);
145
+ if (active === true)
146
+ state.delete(key);
147
+ if (active !== undefined && active !== true && active.started)
148
+ active.invalidated = true;
149
+ return;
150
+ }
151
+ state.forEach((active, current) => {
152
+ if (active === true)
153
+ state.delete(current);
154
+ if (active !== true && active.started)
155
+ active.invalidated = true;
156
+ });
157
+ }
158
+ };
159
+ }
160
+ var CHILD_PAGE = 200;
161
+ var SEQUENCE_HANDOFF_MS = 250;
162
+ var DELETED_SESSION_LIMIT = 512;
163
+ function createData2(config) {
164
+ const api = config.api;
165
+ let disposed = false;
166
+ onCleanup(() => disposed = true);
167
+ function refresh(load) {
168
+ if (disposed || config.connection && config.connection.status() !== "connected")
169
+ return;
170
+ load().catch(refreshFailed);
171
+ }
172
+ function restoreMessageFiles(sessionID, messageID) {
173
+ return api().session.message.get({ sessionID, messageID }).then((item) => {
174
+ if (item.type !== "assistant" || omitFiles())
175
+ return;
176
+ message.editAssistant(sessionID, item.id, (assistant) => {
177
+ assistant.content.forEach((part) => {
178
+ if (part.type !== "tool" || !("content" in part.state) || !part.state.content?.some(isDroppedFile))
179
+ return;
180
+ const fetched = item.content.findLast((other) => other.type === "tool" && other.id === part.id);
181
+ if (fetched?.type === "tool" && "content" in fetched.state && fetched.state.content)
182
+ part.state.content = fetched.state.content;
183
+ });
184
+ });
185
+ });
186
+ }
187
+ function refreshFailed(error) {
188
+ if (disposed || config.connection && config.connection.status() !== "connected")
189
+ return;
190
+ if (isSessionNotFoundError2(error)) {
191
+ markDeleted(error.sessionID);
192
+ return;
193
+ }
194
+ if (isMessageNotFoundError2(error))
195
+ return;
196
+ if (config.onError)
197
+ return config.onError(error);
198
+ console.error("Failed to refresh client data", error);
199
+ }
200
+ const settling = new Map;
201
+ onCleanup(() => settling.forEach((timer) => clearTimeout(timer)));
202
+ function settle(key, load) {
203
+ clearTimeout(settling.get(key));
204
+ settling.set(key, setTimeout(() => {
205
+ settling.delete(key);
206
+ refresh(load);
207
+ }, settleMs2));
208
+ }
209
+ const [store, setStore] = createStore({
210
+ session: {
211
+ info: {},
212
+ missing: {},
213
+ family: {},
214
+ active: {},
215
+ message: {},
216
+ messageCursor: {},
217
+ messageLoading: {},
218
+ pending: {},
219
+ permission: {},
220
+ form: {}
221
+ },
222
+ project: {
223
+ info: {},
224
+ permission: {}
225
+ },
226
+ location: {},
227
+ job: {},
228
+ jobTree: {}
229
+ });
230
+ const [defaultLocation, setDefaultLocation] = createSignal({ directory: config.directory });
231
+ const sessions = createMemo(() => Object.values(store.session.info).toSorted((a, b) => b.time.updated - a.time.updated));
232
+ const messageIndex = new Map;
233
+ const anchored = new Set;
234
+ const stranded = new Map;
235
+ const omitFiles = () => typeof config.omitToolFileData === "function" ? config.omitToolFileData() : config.omitToolFileData === true;
236
+ const stored = (message) => omitFiles() ? omitMessageFileData(message) : message;
237
+ const sync = createSync();
238
+ let activeUpdates;
239
+ const jobUpdates = new Map;
240
+ const pendingUpdates = new Map;
241
+ function setSessionActive(sessionID, status) {
242
+ activeUpdates?.set(sessionID, status);
243
+ setStore("session", "active", sessionID, status);
244
+ }
245
+ function removePending(sessionID, inboxID) {
246
+ if (!inboxID)
247
+ return;
248
+ pendingUpdates.get(sessionID)?.set(inboxID, undefined);
249
+ if (store.session.pending[sessionID]?.some((item) => item.id === inboxID))
250
+ setStore("session", "pending", sessionID, (store.session.pending[sessionID] ?? []).filter((item) => item.id !== inboxID));
251
+ }
252
+ function removePermission(sessionID, requestID) {
253
+ const requests = store.session.permission[sessionID];
254
+ if (!requests?.some((request) => request.id === requestID))
255
+ return;
256
+ setStore("session", "permission", sessionID, requests.filter((request) => request.id !== requestID));
257
+ }
258
+ function removeForm(sessionID, formID, ref) {
259
+ const forms = store.session.form[sessionID];
260
+ if (!forms)
261
+ return false;
262
+ const location = ref && locationKey2(ref);
263
+ const next = forms.filter((form) => {
264
+ if (form.id !== formID)
265
+ return true;
266
+ if (sessionID !== "global" || !location)
267
+ return false;
268
+ return !form.location || locationKey2(form.location) !== location;
269
+ });
270
+ if (next.length === forms.length)
271
+ return false;
272
+ setStore("session", "form", sessionID, next);
273
+ return true;
274
+ }
275
+ function settleForm(input, ref, request) {
276
+ return request.catch((error) => {
277
+ if (!isFormNotFoundError2(error) && !isFormAlreadySettledError2(error) || error.id !== input.formID)
278
+ throw error;
279
+ }).then(() => {
280
+ if (!removeForm(input.sessionID, input.formID, ref))
281
+ return;
282
+ result.session.form.invalidate(input.sessionID, ref);
283
+ result.session.form.sync(input.sessionID, ref).catch(() => {
284
+ return;
285
+ });
286
+ });
287
+ }
288
+ function updatePending(sessionID, inboxID, delivery) {
289
+ const index = store.session.pending[sessionID]?.findIndex((item) => item.id === inboxID) ?? -1;
290
+ const item = store.session.pending[sessionID]?.[index];
291
+ pendingUpdates.get(sessionID)?.set(inboxID, item ? { ...item, delivery } : delivery);
292
+ if (index < 0 || !item || item.delivery === delivery)
293
+ return;
294
+ setStore("session", "pending", sessionID, index, { ...item, delivery });
295
+ }
296
+ const outbox = new Set;
297
+ const sessionOutbox = new Set;
298
+ const creating = new Map;
299
+ const sending = new Map;
300
+ const messageLoads = new Map;
301
+ const compacting = new Map;
302
+ onCleanup(() => compacting.clear());
303
+ function track(map, key, promise) {
304
+ map.set(key, promise);
305
+ const settle = () => {
306
+ if (map.get(key) === promise)
307
+ map.delete(key);
308
+ };
309
+ promise.then(settle, settle);
310
+ }
311
+ function sendAdmission(sessionID, send, gate, link) {
312
+ const created = creating.get(sessionID);
313
+ const previous = sending.get(sessionID);
314
+ const request = Promise.resolve().then(() => Promise.all([gate, created, previous])).then(send);
315
+ track(sending, sessionID, (link?.(request) ?? request).catch(() => {
316
+ return;
317
+ }));
318
+ return request;
319
+ }
320
+ function admitLocal(item) {
321
+ batch(() => {
322
+ const pending = store.session.pending[item.sessionID] ?? [];
323
+ const at = pending.findIndex((entry) => entry.id === item.id);
324
+ setStore("session", "pending", item.sessionID, at < 0 ? [...pending, item] : pending.map((entry, index) => index === at ? item : entry));
325
+ if (item.type === "compaction")
326
+ return;
327
+ materializeInboxMessage(item);
328
+ });
329
+ }
330
+ function materializeInboxMessage(item) {
331
+ if (item.type !== "user" && item.type !== "synthetic")
332
+ return;
333
+ message.update(item.sessionID, (draft, index) => {
334
+ const row = item.type === "user" ? { id: item.id, type: "user", ...item.payload, time: { created: item.time.created } } : { id: item.id, type: "synthetic", ...item.payload, time: { created: item.time.created } };
335
+ const position = index.get(item.id);
336
+ if (position === undefined)
337
+ return message.append(draft, index, row);
338
+ draft[position] = row;
339
+ });
340
+ }
341
+ function retractLocal(sessionID, inboxID) {
342
+ batch(() => {
343
+ removePending(sessionID, inboxID);
344
+ if (!messageIndex.get(sessionID)?.has(inboxID))
345
+ return;
346
+ message.update(sessionID, (draft, index) => {
347
+ const position = index.get(inboxID);
348
+ if (position === undefined)
349
+ return;
350
+ draft.splice(position, 1);
351
+ index.delete(inboxID);
352
+ message.reindex(draft, index, position);
353
+ });
354
+ });
355
+ }
356
+ const message = {
357
+ update(sessionID, fn) {
358
+ setStore("session", "message", produce((draft) => {
359
+ fn(draft[sessionID] ??= [], index(sessionID));
360
+ }));
361
+ },
362
+ append(messages, index, item) {
363
+ if (index.has(item.id))
364
+ return;
365
+ index.set(item.id, messages.length);
366
+ messages.push(item);
367
+ },
368
+ insert(sessionID, item) {
369
+ message.update(sessionID, (draft, index) => message.append(draft, index, item));
370
+ },
371
+ editAssistant(sessionID, messageID, fn) {
372
+ if (!messageIndex.get(sessionID)?.has(messageID))
373
+ return;
374
+ message.update(sessionID, (draft, index) => {
375
+ const position = index.get(messageID);
376
+ const item = position === undefined ? undefined : draft[position];
377
+ if (item?.type === "assistant")
378
+ fn(item);
379
+ });
380
+ },
381
+ editTool(sessionID, messageID, toolID, fn) {
382
+ message.editAssistant(sessionID, messageID, (assistant) => {
383
+ const tool = assistant.content.findLast((item) => item.type === "tool" && item.id === toolID);
384
+ if (tool)
385
+ fn(tool);
386
+ });
387
+ },
388
+ editText(sessionID, messageID, fn) {
389
+ message.editAssistant(sessionID, messageID, (assistant) => {
390
+ const text = assistant.content.findLast((item) => item.type === "text");
391
+ if (text)
392
+ fn(text);
393
+ });
394
+ },
395
+ editReasoning(sessionID, messageID, fn) {
396
+ message.editAssistant(sessionID, messageID, (assistant) => {
397
+ const reasoning = assistant.content.findLast((item) => item.type === "reasoning" && !item.time?.completed);
398
+ if (reasoning)
399
+ fn(reasoning);
400
+ });
401
+ },
402
+ activeAssistant(messages) {
403
+ const item = messages.findLast((item) => item.type === "assistant" && !item.time.completed);
404
+ return item?.type === "assistant" ? item : undefined;
405
+ },
406
+ shell(messages, shellID) {
407
+ const item = messages.findLast((item) => item.type === "shell" && item.shellID === shellID);
408
+ return item?.type === "shell" ? item : undefined;
409
+ },
410
+ compaction(messages) {
411
+ const item = messages.findLast((item) => item.type === "compaction" && item.status === "running");
412
+ return item?.type === "compaction" ? item : undefined;
413
+ },
414
+ reindex(messages, index, start) {
415
+ for (let position = start;position < messages.length; position++) {
416
+ const item = messages[position];
417
+ if (item)
418
+ index.set(item.id, position);
419
+ }
420
+ }
421
+ };
422
+ function index(sessionID) {
423
+ const existing = messageIndex.get(sessionID);
424
+ if (existing)
425
+ return existing;
426
+ const created = new Map;
427
+ messageIndex.set(sessionID, created);
428
+ return created;
429
+ }
430
+ async function listChildren(input) {
431
+ const page = await api().session.list(input);
432
+ if (page.data.length < CHILD_PAGE || !page.cursor.next)
433
+ return page.data;
434
+ return [...page.data, ...await listChildren({ cursor: page.cursor.next, limit: CHILD_PAGE })];
435
+ }
436
+ function resolveRoot(sessionID) {
437
+ let current = sessionID;
438
+ let parentID = store.session.info[sessionID]?.parentID;
439
+ const seen = new Set([sessionID]);
440
+ while (parentID) {
441
+ if (seen.has(parentID))
442
+ break;
443
+ seen.add(parentID);
444
+ current = parentID;
445
+ parentID = store.session.info[parentID]?.parentID;
446
+ }
447
+ return current;
448
+ }
449
+ function registerSession(sessionID) {
450
+ const info = store.session.info[sessionID];
451
+ if (!info)
452
+ return;
453
+ const rootID = resolveRoot(sessionID);
454
+ setStore("session", "family", produce((draft) => {
455
+ if (sessionID !== rootID && draft[sessionID]) {
456
+ const members = draft[rootID] ??= [];
457
+ for (const id of draft[sessionID]) {
458
+ if (!members.includes(id))
459
+ members.push(id);
460
+ }
461
+ delete draft[sessionID];
462
+ }
463
+ const family = draft[rootID] ??= [];
464
+ if (!family.includes(sessionID))
465
+ family.push(sessionID);
466
+ }));
467
+ }
468
+ function evictSession(sessionID) {
469
+ if (sessionOutbox.has(sessionID))
470
+ return;
471
+ sync.invalidate(`session.pending:${sessionID}`);
472
+ sync.invalidate(`session.message:${sessionID}`);
473
+ messageLoads.delete(sessionID);
474
+ anchored.delete(sessionID);
475
+ stranded.delete(sessionID);
476
+ const pending = store.session.pending[sessionID]?.filter((item) => outbox.has(item.id)) ?? [];
477
+ const messages = store.session.message[sessionID]?.filter((item) => outbox.has(item.id)) ?? [];
478
+ messageIndex.delete(sessionID);
479
+ if (messages.length)
480
+ messageIndex.set(sessionID, new Map(messages.map((item, index) => [item.id, index])));
481
+ setStore("session", produce((draft) => {
482
+ delete draft.message[sessionID];
483
+ delete draft.messageCursor[sessionID];
484
+ delete draft.messageLoading[sessionID];
485
+ delete draft.pending[sessionID];
486
+ if (messages.length)
487
+ draft.message[sessionID] = messages;
488
+ if (pending.length)
489
+ draft.pending[sessionID] = pending;
490
+ }));
491
+ }
492
+ let deletionEpoch = 0;
493
+ const deletedAt = new Map;
494
+ function clearDeleted(sessionID) {
495
+ deletedAt.delete(sessionID);
496
+ if (store.session.missing[sessionID])
497
+ setStore("session", "missing", sessionID, undefined);
498
+ }
499
+ function markDeleted(sessionID) {
500
+ if (sessionOutbox.has(sessionID))
501
+ return;
502
+ batch(() => {
503
+ deletedAt.delete(sessionID);
504
+ deletedAt.set(sessionID, ++deletionEpoch);
505
+ if (deletedAt.size > DELETED_SESSION_LIMIT) {
506
+ const oldest = deletedAt.keys().next().value;
507
+ if (oldest !== undefined) {
508
+ deletedAt.delete(oldest);
509
+ setStore("session", "missing", oldest, undefined);
510
+ }
511
+ }
512
+ setStore("session", "missing", sessionID, true);
513
+ removeSession(sessionID);
514
+ });
515
+ }
516
+ function evictMissing(error) {
517
+ if (isSessionNotFoundError2(error))
518
+ markDeleted(error.sessionID);
519
+ throw error;
520
+ }
521
+ function removeSession(sessionID) {
522
+ activeUpdates?.set(sessionID, undefined);
523
+ removeJobTree(sessionID);
524
+ store.session.pending[sessionID]?.forEach((item) => outbox.delete(item.id));
525
+ messageIndex.delete(sessionID);
526
+ anchored.delete(sessionID);
527
+ stranded.delete(sessionID);
528
+ sync.invalidate(`session:${sessionID}`);
529
+ sync.invalidate(`session.family:${sessionID}`);
530
+ sync.invalidate(`session.pending:${sessionID}`);
531
+ sync.invalidate(`session.message:${sessionID}`);
532
+ sync.invalidate(`session.permission:${sessionID}`);
533
+ sync.invalidate(`session.form:${sessionID}:`);
534
+ setStore("session", produce((draft) => {
535
+ delete draft.info[sessionID];
536
+ delete draft.active[sessionID];
537
+ delete draft.message[sessionID];
538
+ delete draft.messageCursor[sessionID];
539
+ delete draft.messageLoading[sessionID];
540
+ delete draft.pending[sessionID];
541
+ delete draft.permission[sessionID];
542
+ delete draft.form[sessionID];
543
+ for (const [rootID, family] of Object.entries(draft.family)) {
544
+ const next = family.filter((id) => id !== sessionID);
545
+ if (next.length === 0)
546
+ delete draft.family[rootID];
547
+ else
548
+ draft.family[rootID] = next;
549
+ }
550
+ }));
551
+ }
552
+ function handleEvent(event) {
553
+ switch (event.type) {
554
+ case "server.connected": {
555
+ const updates = new Map;
556
+ activeUpdates = updates;
557
+ refresh(() => api().session.active().then((active) => {
558
+ if (activeUpdates !== updates)
559
+ return;
560
+ const snapshot = new Map(Object.keys(active).map((id) => [id, "running"]));
561
+ updates.forEach((status, id) => {
562
+ if (status === undefined)
563
+ return snapshot.delete(id);
564
+ snapshot.set(id, status);
565
+ });
566
+ activeUpdates = undefined;
567
+ setStore("session", "active", reconcile(Object.fromEntries(snapshot)));
568
+ snapshot.forEach((status, id) => {
569
+ if (status === "running" && !store.session.info[id])
570
+ refresh(() => result.session.sync(id));
571
+ });
572
+ }).catch(() => {
573
+ if (activeUpdates === updates)
574
+ activeUpdates = undefined;
575
+ }));
576
+ refresh(() => api().location.get({ location: locationQuery(defaultLocation()) }).then((location) => {
577
+ const key = locationKey2(location);
578
+ setStore("location", key, { info: location });
579
+ }));
580
+ refresh(() => result.location.vcs.sync());
581
+ refresh(() => result.project.sync());
582
+ Object.entries(store.location).forEach(([key, data]) => {
583
+ if (data.flags === undefined || dormantFlags.has(key))
584
+ return;
585
+ const ref = JSON.parse(key);
586
+ const location = { directory: ref[0], workspaceID: ref[1] ?? undefined };
587
+ flags.invalidate(location);
588
+ refresh(() => flags.sync(location));
589
+ });
590
+ Object.keys(store.jobTree).forEach((sessionID) => {
591
+ result.job.invalidate(sessionID);
592
+ refresh(() => result.job.sync(sessionID));
593
+ });
594
+ return;
595
+ }
596
+ case "experimental.job.updated": {
597
+ const info = event.data.info;
598
+ const running = info.status === "running";
599
+ jobUpdates.forEach((updates) => updates.set(info.id, running ? info : undefined));
600
+ if (!running) {
601
+ if (!store.job[info.id])
602
+ return;
603
+ setStore(produce((draft) => {
604
+ delete draft.job[info.id];
605
+ Object.values(draft.jobTree).forEach((members) => delete members[info.id]);
606
+ }));
607
+ return;
608
+ }
609
+ setStore(produce((draft) => {
610
+ draft.job[info.id] = info;
611
+ Object.entries(draft.jobTree).forEach(([rootID, members]) => {
612
+ if (jobWithin(info, rootID))
613
+ members[info.id] = true;
614
+ });
615
+ }));
616
+ return;
617
+ }
618
+ case "project.updated":
619
+ setStore("project", "info", event.data.id, reconcile(event.data));
620
+ return;
621
+ case "session.created":
622
+ clearDeleted(event.data.sessionID);
623
+ sessionOutbox.delete(event.data.sessionID);
624
+ result.session.invalidate(event.data.sessionID);
625
+ refresh(() => result.session.sync(event.data.sessionID));
626
+ sync.complete(`session.pending:${event.data.sessionID}`);
627
+ sync.complete(`session.message:${event.data.sessionID}`);
628
+ anchored.add(event.data.sessionID);
629
+ return;
630
+ case "session.deleted":
631
+ markDeleted(event.data.sessionID);
632
+ return;
633
+ case "session.usage.updated":
634
+ if (store.session.info[event.data.sessionID])
635
+ setStore("session", "info", event.data.sessionID, {
636
+ cost: event.data.cost,
637
+ tokens: event.data.tokens
638
+ });
639
+ return;
640
+ case "session.agent.selected": {
641
+ const previous = store.session.info[event.data.sessionID]?.agent;
642
+ if (store.session.info[event.data.sessionID])
643
+ setStore("session", "info", event.data.sessionID, "agent", event.data.agent);
644
+ message.insert(event.data.sessionID, {
645
+ id: SessionMessage.ID.fromEvent(event.id),
646
+ type: "agent-switched",
647
+ agent: event.data.agent,
648
+ previous,
649
+ time: { created: event.created }
650
+ });
651
+ return;
652
+ }
653
+ case "session.model.selected": {
654
+ const previous = event.data.previous ?? store.session.info[event.data.sessionID]?.model;
655
+ if (store.session.info[event.data.sessionID])
656
+ setStore("session", "info", event.data.sessionID, "model", event.data.model);
657
+ if (!store.session.message[event.data.sessionID])
658
+ return;
659
+ message.insert(event.data.sessionID, {
660
+ id: SessionMessage.ID.fromEvent(event.id),
661
+ type: "model-switched",
662
+ model: event.data.model,
663
+ previous,
664
+ time: { created: event.created }
665
+ });
666
+ refresh(() => api().session.message.get({ sessionID: event.data.sessionID, messageID: SessionMessage.ID.fromEvent(event.id) }).then((item) => {
667
+ message.update(event.data.sessionID, (draft, index) => {
668
+ const position = index.get(item.id);
669
+ if (position === undefined)
670
+ return message.append(draft, index, item);
671
+ draft[position] = item;
672
+ });
673
+ }));
674
+ return;
675
+ }
676
+ case "session.renamed": {
677
+ refresh(() => {
678
+ const family = sync.pending(`session.family:${event.data.sessionID}`) ? result.session.sync(event.data.sessionID, { children: true }) : Promise.resolve();
679
+ return Promise.all([result.session.sync(event.data.sessionID), family]).then(() => {
680
+ if (store.session.info[event.data.sessionID])
681
+ setStore("session", "info", event.data.sessionID, "title", event.data.title);
682
+ });
683
+ });
684
+ return;
685
+ }
686
+ case "session.permissions":
687
+ if (store.session.info[event.data.sessionID])
688
+ setStore("session", "info", event.data.sessionID, "permissions", event.data.permissions);
689
+ return;
690
+ case "session.metadata.updated":
691
+ if (store.session.info[event.data.sessionID])
692
+ setStore("session", "info", event.data.sessionID, "metadata", reconcile(event.data.metadata));
693
+ return;
694
+ case "session.archived":
695
+ if (store.session.info[event.data.sessionID])
696
+ setStore("session", "info", event.data.sessionID, "time", "archived", event.created);
697
+ return;
698
+ case "session.unarchived":
699
+ if (store.session.info[event.data.sessionID])
700
+ setStore("session", "info", event.data.sessionID, "time", "archived", undefined);
701
+ return;
702
+ case "session.moved": {
703
+ const current = store.session.info[event.data.sessionID];
704
+ if (current) {
705
+ const previous = {
706
+ location: { ...current.location },
707
+ projectID: current.projectID,
708
+ subpath: current.subpath
709
+ };
710
+ setStore("session", "info", event.data.sessionID, "location", event.data.location);
711
+ setStore("session", "info", event.data.sessionID, "projectID", event.data.projectID);
712
+ setStore("session", "info", event.data.sessionID, "subpath", event.data.subpath);
713
+ message.insert(event.data.sessionID, {
714
+ id: SessionMessage.ID.fromEvent(event.id),
715
+ type: "location-switched",
716
+ location: event.data.location,
717
+ projectID: event.data.projectID,
718
+ subpath: event.data.subpath,
719
+ previous,
720
+ time: { created: event.created }
721
+ });
722
+ }
723
+ return;
724
+ }
725
+ case "worktree.resolved": {
726
+ for (const [sessionID, info] of Object.entries(store.session.info)) {
727
+ const explicit = event.data.adopted?.includes(info.projectID);
728
+ const directory = explicit ? store.project.info[info.projectID]?.canonical : info.location.directory;
729
+ if (!directory) {
730
+ result.session.invalidate(sessionID);
731
+ refresh(() => result.session.sync(sessionID));
732
+ continue;
733
+ }
734
+ const adopted = Worktree.adopt({
735
+ projectID: info.projectID,
736
+ directory
737
+ }, event.data);
738
+ if (!adopted)
739
+ continue;
740
+ setStore("session", "info", sessionID, "projectID", adopted.projectID);
741
+ setStore("session", "info", sessionID, "subpath", adopted.subpath);
742
+ }
743
+ return;
744
+ }
745
+ case "session.inbox.delivered": {
746
+ const admitted = result.session.input.has(event.data.sessionID, event.data.inboxID);
747
+ removePending(event.data.sessionID, event.data.inboxID);
748
+ message.update(event.data.sessionID, (draft, index) => {
749
+ const position = index.get(event.data.inboxID);
750
+ if (position === undefined)
751
+ return;
752
+ const existing = draft[position];
753
+ if (!existing || !admitted)
754
+ return;
755
+ existing.time.created = event.created;
756
+ draft.splice(position, 1);
757
+ draft.push(existing);
758
+ message.reindex(draft, index, position);
759
+ });
760
+ compacting.get(event.data.sessionID)?.observed.add(event.data.inboxID);
761
+ return;
762
+ }
763
+ case "session.inbox.delivery.changed":
764
+ updatePending(event.data.sessionID, event.data.inboxID, event.data.delivery);
765
+ return;
766
+ case "session.inbox.cancelled": {
767
+ retractLocal(event.data.sessionID, event.data.inboxID);
768
+ compacting.get(event.data.sessionID)?.observed.add(event.data.inboxID);
769
+ return;
770
+ }
771
+ case "session.inbox.enqueued": {
772
+ outbox.delete(event.data.inboxID);
773
+ const item = {
774
+ id: event.data.inboxID,
775
+ sessionID: event.data.sessionID,
776
+ time: { created: event.created },
777
+ ...event.data.item
778
+ };
779
+ pendingUpdates.get(item.sessionID)?.set(item.id, item);
780
+ admitLocal(item);
781
+ if (event.data.item.type === "compaction") {
782
+ const active = compacting.get(event.data.sessionID);
783
+ active?.observed.add(event.data.inboxID);
784
+ if (active && active.id !== event.data.inboxID && outbox.delete(active.id))
785
+ removePending(event.data.sessionID, active.id);
786
+ }
787
+ return;
788
+ }
789
+ case "session.instructions.updated":
790
+ const updateText = event.data.text;
791
+ if (updateText === undefined)
792
+ return;
793
+ message.insert(event.data.sessionID, {
794
+ id: SessionMessage.ID.fromEvent(event.id),
795
+ type: "system",
796
+ text: updateText,
797
+ description: `Instructions updated: ${Object.keys(event.data.delta).join(", ")}`,
798
+ metadata: event.metadata,
799
+ time: { created: event.created }
800
+ });
801
+ return;
802
+ case "session.synthetic":
803
+ message.insert(event.data.sessionID, {
804
+ id: SessionMessage.ID.fromEvent(event.id),
805
+ type: "synthetic",
806
+ text: event.data.text,
807
+ description: event.data.description,
808
+ metadata: event.data.metadata,
809
+ time: { created: event.created }
810
+ });
811
+ return;
812
+ case "session.shell.started":
813
+ message.insert(event.data.sessionID, {
814
+ id: SessionMessage.ID.fromEvent(event.id),
815
+ type: "shell",
816
+ shellID: event.data.shell.id,
817
+ command: event.data.shell.command,
818
+ status: event.data.shell.status,
819
+ exit: event.data.shell.exit,
820
+ metadata: event.data.shell.metadata.background === true ? { ...event.metadata, background: true } : event.metadata,
821
+ time: { created: event.created }
822
+ });
823
+ return;
824
+ case "session.shell.ended":
825
+ if (!store.session.message[event.data.sessionID])
826
+ return;
827
+ message.update(event.data.sessionID, (draft) => {
828
+ const match = message.shell(draft, event.data.shell.id);
829
+ if (!match)
830
+ return;
831
+ match.status = event.data.shell.status;
832
+ match.exit = event.data.shell.exit;
833
+ match.output = event.data.output;
834
+ match.time.completed = event.created;
835
+ });
836
+ return;
837
+ case "session.step.started":
838
+ message.update(event.data.sessionID, (draft, index) => {
839
+ const position = index.get(event.data.assistantMessageID);
840
+ const existing = position === undefined ? undefined : draft[position];
841
+ if (existing?.type === "assistant") {
842
+ existing.agent = event.data.agent;
843
+ existing.model = event.data.model;
844
+ existing.retry = undefined;
845
+ existing.error = undefined;
846
+ existing.finish = undefined;
847
+ existing.rawFinish = undefined;
848
+ existing.native = undefined;
849
+ existing.time.created = event.data.started;
850
+ existing.time.firstToken = undefined;
851
+ existing.time.streamed = undefined;
852
+ existing.time.completed = undefined;
853
+ if (event.data.snapshot)
854
+ existing.snapshot = { ...existing.snapshot, start: event.data.snapshot };
855
+ return;
856
+ }
857
+ const currentAssistant = message.activeAssistant(draft);
858
+ if (currentAssistant) {
859
+ currentAssistant.retry = undefined;
860
+ currentAssistant.time.completed = event.created;
861
+ }
862
+ message.append(draft, index, {
863
+ id: event.data.assistantMessageID,
864
+ type: "assistant",
865
+ agent: event.data.agent,
866
+ model: event.data.model,
867
+ metadata: event.metadata,
868
+ content: [],
869
+ snapshot: event.data.snapshot ? { start: event.data.snapshot } : undefined,
870
+ time: { created: event.data.started }
871
+ });
872
+ });
873
+ return;
874
+ case "session.step.streamed":
875
+ message.editAssistant(event.data.sessionID, event.data.assistantMessageID, (assistant) => {
876
+ assistant.time.streamed = event.created;
877
+ });
878
+ return;
879
+ case "session.step.first-token":
880
+ message.editAssistant(event.data.sessionID, event.data.assistantMessageID, (assistant) => {
881
+ assistant.time.firstToken = event.created;
882
+ });
883
+ return;
884
+ case "session.step.ended": {
885
+ message.editAssistant(event.data.sessionID, event.data.assistantMessageID, (assistant) => {
886
+ assistant.time.completed = event.created;
887
+ assistant.finish = event.data.finish;
888
+ assistant.rawFinish = event.data.rawFinish;
889
+ assistant.native = event.data.native;
890
+ assistant.cost = event.data.cost;
891
+ assistant.tokens = event.data.tokens;
892
+ assistant.contextTokens = event.data.contextTokens;
893
+ if (event.data.snapshot)
894
+ assistant.snapshot = { ...assistant.snapshot, end: event.data.snapshot };
895
+ });
896
+ return;
897
+ }
898
+ case "session.step.failed":
899
+ if (event.location && (event.data.error.type === "provider.budget-limit" || event.data.error.type === "provider.model-budget-limit"))
900
+ refreshUsageLimits(event.location);
901
+ message.editAssistant(event.data.sessionID, event.data.assistantMessageID, (assistant) => {
902
+ assistant.time.completed = event.created;
903
+ assistant.finish = event.data.finish ?? "error";
904
+ assistant.rawFinish = event.data.rawFinish;
905
+ assistant.native = event.data.native;
906
+ assistant.error = event.data.error;
907
+ assistant.retry = undefined;
908
+ if (event.data.cost !== undefined && event.data.tokens !== undefined) {
909
+ assistant.cost = event.data.cost;
910
+ assistant.tokens = event.data.tokens;
911
+ assistant.contextTokens = event.data.contextTokens;
912
+ }
913
+ });
914
+ return;
915
+ case "session.text.started":
916
+ message.editAssistant(event.data.sessionID, event.data.assistantMessageID, (assistant) => {
917
+ assistant.content.push({ type: "text", text: "" });
918
+ });
919
+ return;
920
+ case "session.text.delta":
921
+ message.editText(event.data.sessionID, event.data.assistantMessageID, (text) => {
922
+ text.text += event.data.delta;
923
+ });
924
+ return;
925
+ case "session.text.ended":
926
+ message.editText(event.data.sessionID, event.data.assistantMessageID, (text) => {
927
+ text.text = event.data.text;
928
+ });
929
+ return;
930
+ case "session.tool.input.started":
931
+ message.editAssistant(event.data.sessionID, event.data.assistantMessageID, (assistant) => {
932
+ assistant.content.push({
933
+ type: "tool",
934
+ id: event.data.id,
935
+ name: event.data.name,
936
+ time: { created: event.created },
937
+ state: { status: "streaming", input: "" }
938
+ });
939
+ });
940
+ return;
941
+ case "session.tool.input.delta":
942
+ message.editTool(event.data.sessionID, event.data.assistantMessageID, event.data.id, (tool) => {
943
+ if (tool.state.status === "streaming")
944
+ tool.state.input += event.data.delta;
945
+ });
946
+ return;
947
+ case "session.tool.input.ended":
948
+ message.editTool(event.data.sessionID, event.data.assistantMessageID, event.data.id, (tool) => {
949
+ if (tool.state.status === "streaming")
950
+ tool.state.input = event.data.text;
951
+ });
952
+ return;
953
+ case "session.tool.called":
954
+ message.editTool(event.data.sessionID, event.data.assistantMessageID, event.data.id, (tool) => {
955
+ tool.time.ran = event.created;
956
+ tool.executed = event.data.executed;
957
+ tool.native = event.data.native;
958
+ tool.state = { status: "running", input: event.data.input, metadata: {} };
959
+ });
960
+ return;
961
+ case "session.tool.progress":
962
+ message.editTool(event.data.sessionID, event.data.assistantMessageID, event.data.id, (tool) => {
963
+ if (tool.state.status === "running")
964
+ tool.state.metadata = event.data.metadata;
965
+ });
966
+ return;
967
+ case "session.tool.success":
968
+ message.editTool(event.data.sessionID, event.data.assistantMessageID, event.data.id, (tool) => {
969
+ if (tool.state.status !== "running")
970
+ return;
971
+ tool.state = {
972
+ status: "completed",
973
+ input: tool.state.input,
974
+ metadata: event.data.metadata,
975
+ content: omitFiles() ? omitFileData(event.data.content) : [...event.data.content]
976
+ };
977
+ tool.executed = event.data.executed || tool.executed === true;
978
+ if (event.data.native)
979
+ tool.native = { ...tool.native, ...event.data.native };
980
+ tool.time.completed = event.created;
981
+ });
982
+ return;
983
+ case "session.tool.failed":
984
+ message.editTool(event.data.sessionID, event.data.assistantMessageID, event.data.id, (tool) => {
985
+ if (tool.state.status !== "streaming" && tool.state.status !== "running")
986
+ return;
987
+ tool.state = {
988
+ status: "error",
989
+ error: event.data.error,
990
+ input: typeof tool.state.input === "string" ? {} : tool.state.input,
991
+ metadata: event.data.metadata,
992
+ content: omitFiles() && event.data.content ? omitFileData(event.data.content) : event.data.content
993
+ };
994
+ tool.executed = event.data.executed || tool.executed === true;
995
+ if (event.data.native)
996
+ tool.native = { ...tool.native, ...event.data.native };
997
+ tool.time.completed = event.created;
998
+ });
999
+ return;
1000
+ case "session.reasoning.started":
1001
+ message.editAssistant(event.data.sessionID, event.data.assistantMessageID, (assistant) => {
1002
+ assistant.content.push({
1003
+ type: "reasoning",
1004
+ text: "",
1005
+ native: event.data.native,
1006
+ time: { created: event.created }
1007
+ });
1008
+ });
1009
+ return;
1010
+ case "session.reasoning.delta":
1011
+ message.editReasoning(event.data.sessionID, event.data.assistantMessageID, (reasoning) => {
1012
+ reasoning.text += event.data.delta;
1013
+ });
1014
+ return;
1015
+ case "session.reasoning.ended":
1016
+ message.editReasoning(event.data.sessionID, event.data.assistantMessageID, (reasoning) => {
1017
+ reasoning.text = event.data.text;
1018
+ reasoning.time = { created: reasoning.time?.created ?? event.created, completed: event.created };
1019
+ if (event.data.native !== undefined)
1020
+ reasoning.native = event.data.native;
1021
+ });
1022
+ return;
1023
+ case "session.retry.scheduled":
1024
+ message.editAssistant(event.data.sessionID, event.data.assistantMessageID, (assistant) => {
1025
+ assistant.retry = { attempt: event.data.attempt, at: event.data.at, error: event.data.error };
1026
+ });
1027
+ return;
1028
+ case "session.execution.started":
1029
+ setSessionActive(event.data.sessionID, "running");
1030
+ if (!store.session.info[event.data.sessionID] && !sync.has(`session:${event.data.sessionID}`))
1031
+ return;
1032
+ result.session.invalidate(event.data.sessionID);
1033
+ refresh(() => result.session.sync(event.data.sessionID));
1034
+ return;
1035
+ case "session.compaction.started":
1036
+ if (event.data.inputID)
1037
+ removePending(event.data.sessionID, event.data.inputID);
1038
+ message.insert(event.data.sessionID, {
1039
+ id: event.data.inputID ?? SessionMessage.ID.fromEvent(event.id),
1040
+ type: "compaction",
1041
+ status: "running",
1042
+ reason: event.data.reason,
1043
+ summary: "",
1044
+ time: { created: event.created }
1045
+ });
1046
+ if (event.data.inputID)
1047
+ compacting.get(event.data.sessionID)?.observed.add(event.data.inputID);
1048
+ return;
1049
+ case "session.execution.succeeded":
1050
+ case "session.execution.failed":
1051
+ case "session.execution.interrupted":
1052
+ setSessionActive(event.data.sessionID, "idle");
1053
+ message.update(event.data.sessionID, (draft) => {
1054
+ const currentAssistant = message.activeAssistant(draft);
1055
+ if (currentAssistant)
1056
+ currentAssistant.retry = undefined;
1057
+ });
1058
+ if (event.type === "session.execution.interrupted" && event.data.reason === "shutdown")
1059
+ return;
1060
+ message.insert(event.data.sessionID, {
1061
+ id: SessionMessage.ID.fromEvent(event.id),
1062
+ type: "idle",
1063
+ outcome: event.type === "session.execution.succeeded" ? "succeeded" : event.type === "session.execution.failed" ? "failed" : "interrupted",
1064
+ ...event.type === "session.execution.failed" ? { error: event.data.error } : {},
1065
+ time: { created: event.created }
1066
+ });
1067
+ if (store.session.message[event.data.sessionID]?.some((item) => item.type === "assistant" && item.content.some((part) => part.type === "tool" && (part.state.status === "streaming" || part.state.status === "running")))) {
1068
+ sync.invalidate(`session.message:${event.data.sessionID}`);
1069
+ refresh(() => result.session.message.sync(event.data.sessionID));
1070
+ }
1071
+ if (!store.session.info[event.data.sessionID] && !sync.has(`session:${event.data.sessionID}`))
1072
+ return;
1073
+ result.session.invalidate(event.data.sessionID);
1074
+ refresh(() => result.session.sync(event.data.sessionID));
1075
+ return;
1076
+ case "session.viewed":
1077
+ if (!store.session.info[event.data.sessionID] && !sync.has(`session:${event.data.sessionID}`))
1078
+ return;
1079
+ result.session.invalidate(event.data.sessionID);
1080
+ refresh(() => result.session.sync(event.data.sessionID));
1081
+ return;
1082
+ case "session.revert.staged":
1083
+ if (store.session.info[event.data.sessionID])
1084
+ setStore("session", "info", event.data.sessionID, "revert", event.data.revert);
1085
+ return;
1086
+ case "session.revert.cleared":
1087
+ if (store.session.info[event.data.sessionID])
1088
+ setStore("session", "info", event.data.sessionID, "revert", undefined);
1089
+ return;
1090
+ case "session.revert.committed":
1091
+ if (store.session.info[event.data.sessionID]) {
1092
+ setStore("session", "info", event.data.sessionID, "revert", undefined);
1093
+ }
1094
+ setStore("session", "pending", event.data.sessionID, (store.session.pending[event.data.sessionID] ?? []).filter((item) => item.id < event.data.to));
1095
+ message.update(event.data.sessionID, (draft, index) => {
1096
+ const position = draft.findIndex((item) => item.id >= event.data.to);
1097
+ if (position === -1)
1098
+ return;
1099
+ for (const item of draft.splice(position))
1100
+ index.delete(item.id);
1101
+ });
1102
+ return;
1103
+ case "session.compaction.delta":
1104
+ if (!store.session.message[event.data.sessionID])
1105
+ return;
1106
+ message.update(event.data.sessionID, (draft) => {
1107
+ const current = message.compaction(draft);
1108
+ if (current?.status === "running")
1109
+ current.summary += event.data.text;
1110
+ });
1111
+ return;
1112
+ case "session.compaction.ended":
1113
+ message.update(event.data.sessionID, (draft, index) => {
1114
+ const position = draft.findLastIndex((item) => item.type === "compaction" && item.status === "running");
1115
+ const current = draft[position];
1116
+ if (current?.type === "compaction") {
1117
+ Object.assign(current, {
1118
+ status: "completed",
1119
+ reason: event.data.reason,
1120
+ model: event.data.model,
1121
+ native: event.data.native,
1122
+ summary: event.data.text,
1123
+ cost: event.data.cost,
1124
+ tokens: event.data.tokens
1125
+ });
1126
+ return;
1127
+ }
1128
+ message.append(draft, index, {
1129
+ id: SessionMessage.ID.fromEvent(event.id),
1130
+ type: "compaction",
1131
+ status: "completed",
1132
+ reason: event.data.reason,
1133
+ model: event.data.model,
1134
+ native: event.data.native,
1135
+ summary: event.data.text,
1136
+ cost: event.data.cost,
1137
+ tokens: event.data.tokens,
1138
+ time: { created: event.created }
1139
+ });
1140
+ });
1141
+ return;
1142
+ case "session.compaction.failed":
1143
+ if (event.data.inputID)
1144
+ removePending(event.data.sessionID, event.data.inputID);
1145
+ message.update(event.data.sessionID, (draft, index) => {
1146
+ const position = draft.findLastIndex((item) => item.type === "compaction" && item.status === "running");
1147
+ const current = draft[position];
1148
+ const failed = {
1149
+ id: current?.id ?? event.data.inputID ?? SessionMessage.ID.fromEvent(event.id),
1150
+ type: "compaction",
1151
+ status: "failed",
1152
+ reason: event.data.reason,
1153
+ error: event.data.error,
1154
+ metadata: current?.type === "compaction" ? current.metadata : event.metadata,
1155
+ cost: event.data.cost,
1156
+ tokens: event.data.tokens,
1157
+ time: current?.type === "compaction" ? current.time : { created: event.created }
1158
+ };
1159
+ if (current?.type === "compaction") {
1160
+ draft[position] = failed;
1161
+ return;
1162
+ }
1163
+ message.append(draft, index, failed);
1164
+ });
1165
+ if (event.data.inputID)
1166
+ compacting.get(event.data.sessionID)?.observed.add(event.data.inputID);
1167
+ return;
1168
+ case "permission.asked":
1169
+ if (store.session.permission[event.data.sessionID]?.some((request) => request.id === event.data.id))
1170
+ return;
1171
+ setStore("session", "permission", event.data.sessionID, [
1172
+ ...store.session.permission[event.data.sessionID] ?? [],
1173
+ event.data
1174
+ ]);
1175
+ return;
1176
+ case "permission.replied":
1177
+ removePermission(event.data.sessionID, event.data.requestID);
1178
+ return;
1179
+ case "form.replied":
1180
+ case "form.cancelled":
1181
+ removeForm(event.data.sessionID, event.data.id, event.location);
1182
+ return;
1183
+ }
1184
+ if (event.type === "credential.updated" || event.type === "credential.switched") {
1185
+ Object.keys(store.location).forEach((key) => {
1186
+ const ref = JSON.parse(key);
1187
+ const location = { directory: ref[0], workspaceID: ref[1] ?? undefined };
1188
+ refreshUsageLimits(location);
1189
+ if (event.type === "credential.updated") {
1190
+ refreshLocation("integration", result.location.integration, location);
1191
+ return;
1192
+ }
1193
+ if (store.location[key]?.integration)
1194
+ setStore("location", key, (data) => ({
1195
+ integration: data?.integration?.map((integration) => {
1196
+ if (integration.id !== event.data.integrationID)
1197
+ return integration;
1198
+ const active = integration.connections.find((connection) => connection.type === "credential" && connection.id === event.data.credentialID);
1199
+ if (!active)
1200
+ return integration;
1201
+ return {
1202
+ ...integration,
1203
+ connections: [active, ...integration.connections.filter((connection) => connection !== active)]
1204
+ };
1205
+ })
1206
+ }));
1207
+ const active = hasLocation("integration", location) || hasLocation("model", location) || hasLocation("provider", location);
1208
+ result.location.model.invalidate(location);
1209
+ result.location.provider.invalidate(location);
1210
+ if (active)
1211
+ refresh(() => Promise.all([result.location.model.sync(location), result.location.provider.sync(location)]));
1212
+ });
1213
+ return;
1214
+ }
1215
+ if (!event.location) {
1216
+ const type = event.type;
1217
+ if (isCatalogEvent(type))
1218
+ Object.keys(store.location).forEach((key) => {
1219
+ const ref = JSON.parse(key);
1220
+ refreshCatalog(type, { directory: ref[0], workspaceID: ref[1] ?? undefined });
1221
+ });
1222
+ return;
1223
+ }
1224
+ const location = event.location;
1225
+ switch (event.type) {
1226
+ case "provider.updated":
1227
+ case "model.updated":
1228
+ case "agent.updated":
1229
+ case "command.updated":
1230
+ case "skill.updated":
1231
+ refreshCatalog(event.type, location);
1232
+ break;
1233
+ case "vcs.branch.updated":
1234
+ refreshLocation("vcs", result.location.vcs, location);
1235
+ break;
1236
+ case "form.created":
1237
+ if (store.session.form[event.data.form.sessionID]?.some((form) => form.id === event.data.form.id))
1238
+ break;
1239
+ setStore("session", "form", event.data.form.sessionID, [
1240
+ ...store.session.form[event.data.form.sessionID] ?? [],
1241
+ event.data.form.sessionID === "global" ? { ...event.data.form, location } : event.data.form
1242
+ ]);
1243
+ break;
1244
+ case "shell.created":
1245
+ setStore("location", locationKey2(location), (data) => ({
1246
+ shell: {
1247
+ ...data?.shell,
1248
+ [event.data.info.id]: { ...event.data.info, location }
1249
+ }
1250
+ }));
1251
+ break;
1252
+ case "shell.exited":
1253
+ case "shell.deleted":
1254
+ if (!store.location[locationKey2(location)]?.shell?.[event.data.id])
1255
+ break;
1256
+ setStore("location", locationKey2(location), (data) => ({
1257
+ shell: Object.fromEntries(Object.entries(data?.shell ?? {}).filter(([id]) => id !== event.data.id))
1258
+ }));
1259
+ break;
1260
+ case "reference.updated":
1261
+ refreshLocation("reference", result.location.reference, location);
1262
+ break;
1263
+ case "integration.updated": {
1264
+ refreshUsageLimits(location);
1265
+ const active = hasLocation("integration", location) || hasLocation("model", location) || hasLocation("provider", location);
1266
+ result.location.integration.invalidate(location);
1267
+ result.location.model.invalidate(location);
1268
+ result.location.provider.invalidate(location);
1269
+ if (active)
1270
+ refresh(() => Promise.all([
1271
+ result.location.integration.sync(location),
1272
+ result.location.model.sync(location),
1273
+ result.location.provider.sync(location)
1274
+ ]));
1275
+ break;
1276
+ }
1277
+ case "config.updated":
1278
+ refreshLocation("config", result.location.config, location);
1279
+ dormantFlags.delete(locationKey2(location));
1280
+ refreshLocation("flags", flags, location);
1281
+ if (hasLocation("websearch", location))
1282
+ refresh(() => result.location.websearch.refresh(location));
1283
+ break;
1284
+ case "websearch.updated":
1285
+ if (hasLocation("websearch", location))
1286
+ refresh(() => result.location.websearch.refresh(location));
1287
+ break;
1288
+ case "mcp.status.changed": {
1289
+ const active = hasLocation("mcpServer", location);
1290
+ result.location.mcp.server.invalidate(location);
1291
+ if (active)
1292
+ settle(`mcp.status:${locationKey2(location)}`, () => result.location.mcp.server.sync(location));
1293
+ break;
1294
+ }
1295
+ case "mcp.resources.changed":
1296
+ refreshLocation("mcpResource", result.location.mcp.resource, location);
1297
+ break;
1298
+ case "location.shutdown":
1299
+ dormantFlags.add(locationKey2(location));
1300
+ flags.invalidate(location);
1301
+ break;
1302
+ }
1303
+ }
1304
+ function hasLocation(field, ref) {
1305
+ const id = locationKey2(ref ?? defaultLocation());
1306
+ return store.location[id]?.[field] !== undefined || sync.has(`location.${field}:${id}`);
1307
+ }
1308
+ function refreshCatalog(type, location) {
1309
+ if (type === "provider.updated")
1310
+ return refreshLocation("provider", result.location.provider, location);
1311
+ if (type === "model.updated")
1312
+ return refreshLocation("model", result.location.model, location);
1313
+ if (type === "agent.updated")
1314
+ return refreshLocation("agent", result.location.agent, location);
1315
+ if (type === "command.updated")
1316
+ return refreshLocation("command", result.location.command, location);
1317
+ refreshLocation("skill", result.location.skill, location);
1318
+ }
1319
+ function refreshLocation(field, resource, location) {
1320
+ const active = hasLocation(field, location);
1321
+ resource.invalidate(location);
1322
+ if (active)
1323
+ refresh(() => resource.sync(location));
1324
+ }
1325
+ function refreshUsageLimits(location) {
1326
+ const loaded = store.location[locationKey2(location)]?.usageLimits !== undefined || sync.has(`location.usageLimits:${locationKey2(location)}`);
1327
+ usageLimits.invalidate(location);
1328
+ if (loaded)
1329
+ refresh(() => usageLimits.sync(location));
1330
+ }
1331
+ function locationResource(field, load, options) {
1332
+ const publish = (key, value) => setStore("location", key, { [field]: value });
1333
+ return {
1334
+ list: (ref) => store.location[locationKey2(ref ?? defaultLocation())]?.[field],
1335
+ sync: (ref) => {
1336
+ const location = ref ?? defaultLocation();
1337
+ const id = locationKey2(location);
1338
+ return sync.run(`location.${field}:${id}`, async () => {
1339
+ const response = await load(locationQuery(location));
1340
+ const key = locationKey2(response.location);
1341
+ publish(key, response.data);
1342
+ if (options?.alias && key !== id)
1343
+ publish(id, response.data);
1344
+ });
1345
+ },
1346
+ invalidate: (ref) => sync.invalidate(`location.${field}:${locationKey2(ref ?? defaultLocation())}`)
1347
+ };
1348
+ }
1349
+ const vcs = locationResource("vcs", (location) => api().vcs.get({ location }));
1350
+ const usageLimits = locationResource("usageLimits", (location) => api().experimental.usage.limits({ location }));
1351
+ const dormantFlags = new Set;
1352
+ const [canonicalDirectory, setCanonicalDirectory] = createStore({});
1353
+ const canonicalRef = (location) => {
1354
+ const directory = canonicalDirectory[location.directory];
1355
+ return directory ? { directory, workspaceID: location.workspaceID } : location;
1356
+ };
1357
+ const flagResource = locationResource("flags", (location) => api().experimental.flag.get({ location }).catch((error) => {
1358
+ if (!missingEndpoint(error))
1359
+ throw error;
1360
+ return { location: { directory: location.directory }, data: {} };
1361
+ }));
1362
+ const flags = {
1363
+ list: (ref) => {
1364
+ const location = ref ?? defaultLocation();
1365
+ return flagResource.list(location) ?? flagResource.list(canonicalRef(location));
1366
+ },
1367
+ sync: (ref) => {
1368
+ const location = canonicalRef(ref ?? defaultLocation());
1369
+ dormantFlags.delete(locationKey2(location));
1370
+ return flagResource.sync(location);
1371
+ },
1372
+ invalidate: (ref) => flagResource.invalidate(canonicalRef(ref ?? defaultLocation()))
1373
+ };
1374
+ const shells = locationResource("shell", async (location) => {
1375
+ const response = await api().shell.list({ location });
1376
+ const ref = { directory: response.location.directory };
1377
+ return {
1378
+ location: response.location,
1379
+ data: Object.fromEntries(response.data.map((info) => [info.id, { ...info, location: ref }]))
1380
+ };
1381
+ });
1382
+ function withinTree(sessionID, ancestorID) {
1383
+ const seen = new Set;
1384
+ let current = sessionID;
1385
+ while (current && !seen.has(current)) {
1386
+ if (current === ancestorID)
1387
+ return true;
1388
+ seen.add(current);
1389
+ current = store.session.info[current]?.parentID;
1390
+ }
1391
+ return false;
1392
+ }
1393
+ function jobWithin(job, ancestorID) {
1394
+ return withinTree(job.sessionID, ancestorID) || job.kind === "subagent" && withinTree(job.childSessionID, ancestorID);
1395
+ }
1396
+ function removeJobTree(rootID) {
1397
+ jobUpdates.delete(rootID);
1398
+ sync.invalidate(`job:${rootID}`);
1399
+ const members = store.jobTree[rootID];
1400
+ if (!members)
1401
+ return;
1402
+ setStore(produce((draft) => {
1403
+ Object.keys(members).forEach((id) => delete draft.job[id]);
1404
+ delete draft.jobTree[rootID];
1405
+ }));
1406
+ }
1407
+ const result = {
1408
+ on: config.event.on,
1409
+ listen: config.event.listen,
1410
+ session: {
1411
+ list() {
1412
+ return sessions();
1413
+ },
1414
+ get(sessionID) {
1415
+ return store.session.info[sessionID];
1416
+ },
1417
+ missing(sessionID) {
1418
+ return Boolean(store.session.missing[sessionID]);
1419
+ },
1420
+ forget(sessionID) {
1421
+ markDeleted(sessionID);
1422
+ },
1423
+ creating(sessionID) {
1424
+ return creating.has(sessionID);
1425
+ },
1426
+ remember(info) {
1427
+ batch(() => {
1428
+ clearDeleted(info.id);
1429
+ setStore("session", "info", info.id, reconcile(info));
1430
+ sync.complete(`session:${info.id}`);
1431
+ registerSession(info.id);
1432
+ });
1433
+ },
1434
+ setStatus(sessionID, status) {
1435
+ setSessionActive(sessionID, status);
1436
+ },
1437
+ root(sessionID) {
1438
+ return resolveRoot(sessionID);
1439
+ },
1440
+ family(sessionID) {
1441
+ return store.session.family[resolveRoot(sessionID)] ?? [];
1442
+ },
1443
+ evict(sessionID) {
1444
+ const root = resolveRoot(sessionID);
1445
+ batch(() => {
1446
+ for (const id of new Set([root, sessionID, ...store.session.family[root] ?? []]))
1447
+ evictSession(id);
1448
+ });
1449
+ },
1450
+ cost(sessionID) {
1451
+ const session = store.session.info[sessionID];
1452
+ if (!session)
1453
+ return 0;
1454
+ if (session.parentID)
1455
+ return session.cost;
1456
+ return (store.session.family[sessionID] ?? [sessionID]).reduce((total, id) => total + (store.session.info[id]?.cost ?? 0), 0);
1457
+ },
1458
+ status(sessionID) {
1459
+ return store.session.active[sessionID] ?? "idle";
1460
+ },
1461
+ active() {
1462
+ return Object.entries(store.session.active).flatMap(([sessionID, status]) => status === "running" ? [sessionID] : []);
1463
+ },
1464
+ input: {
1465
+ list(sessionID) {
1466
+ return (store.session.pending[sessionID] ?? []).flatMap((item) => item.type === "compaction" ? [] : [item.id]);
1467
+ },
1468
+ has(sessionID, inboxID) {
1469
+ return store.session.pending[sessionID]?.some((item) => item.id === inboxID && item.type !== "compaction") ?? false;
1470
+ }
1471
+ },
1472
+ pending: {
1473
+ list(sessionID) {
1474
+ return store.session.pending[sessionID] ?? [];
1475
+ },
1476
+ status(sessionID, inboxID) {
1477
+ const pending = store.session.pending[sessionID] ?? [];
1478
+ const item = pending.find((entry) => entry.id === inboxID && entry.type === "user");
1479
+ if (!item)
1480
+ return;
1481
+ if (item.delivery === "queue")
1482
+ return "queued";
1483
+ const messages = store.session.message[sessionID] ?? [];
1484
+ const boundary = messages.findLastIndex((entry) => entry.type === "idle");
1485
+ if ((store.session.active[sessionID] ?? "idle") === "idle")
1486
+ return boundary >= 0 && item.time.created <= messages[boundary].time.created ? "stranded" : "starting";
1487
+ return messages.slice(boundary + 1).some((entry) => entry.type === "user" && !pending.some((other) => other.id === entry.id)) ? "steering" : "starting";
1488
+ },
1489
+ sync(sessionID) {
1490
+ return sync.run(`session.pending:${sessionID}`, async () => {
1491
+ const started = deletionEpoch;
1492
+ const updates = new Map;
1493
+ pendingUpdates.set(sessionID, updates);
1494
+ try {
1495
+ const snapshot = await api().session.inbox.list({ sessionID }).catch(evictMissing);
1496
+ if ((deletedAt.get(sessionID) ?? 0) > started)
1497
+ return;
1498
+ const current = new Map(snapshot.map((item) => [item.id, item]));
1499
+ updates.forEach((item, id) => {
1500
+ if (item === undefined)
1501
+ current.delete(id);
1502
+ else if (typeof item === "string") {
1503
+ const existing = current.get(id);
1504
+ if (existing)
1505
+ current.set(id, { ...existing, delivery: item });
1506
+ } else
1507
+ current.set(id, item);
1508
+ });
1509
+ const pending = [...current.values()];
1510
+ pending.forEach((item) => outbox.delete(item.id));
1511
+ if (pending.some((item) => item.type === "compaction"))
1512
+ store.session.pending[sessionID]?.filter((item) => item.type === "compaction").forEach((item) => outbox.delete(item.id));
1513
+ const inflight = (store.session.pending[sessionID] ?? []).filter((item) => outbox.has(item.id));
1514
+ const merged = inflight.length === 0 ? pending : [...pending, ...inflight];
1515
+ const listed = new Set(merged.map((item) => item.id));
1516
+ const dropped = result.session.input.list(sessionID).filter((id) => !listed.has(id));
1517
+ if (dropped.length > 0)
1518
+ stranded.set(sessionID, new Set([...stranded.get(sessionID) ?? [], ...dropped]));
1519
+ batch(() => {
1520
+ setStore("session", "pending", sessionID, reconcile(merged));
1521
+ merged.forEach(materializeInboxMessage);
1522
+ });
1523
+ } finally {
1524
+ if (pendingUpdates.get(sessionID) === updates)
1525
+ pendingUpdates.delete(sessionID);
1526
+ }
1527
+ });
1528
+ },
1529
+ invalidate(sessionID) {
1530
+ sync.invalidate(`session.pending:${sessionID}`);
1531
+ }
1532
+ },
1533
+ create(input) {
1534
+ const { projectID, ...payload } = input;
1535
+ const id = payload.id ?? SessionID.create();
1536
+ const location = payload.location ?? defaultLocation();
1537
+ const fresh = !store.session.info[id];
1538
+ clearDeleted(id);
1539
+ if (fresh) {
1540
+ const now = Date.now();
1541
+ sessionOutbox.add(id);
1542
+ result.session.remember({
1543
+ id,
1544
+ projectID: projectID ?? store.location[locationKey2(location)]?.info?.project.id ?? "",
1545
+ agent: payload.agent,
1546
+ model: payload.model,
1547
+ cost: 0,
1548
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
1549
+ time: { created: now, updated: now },
1550
+ title: payload.title,
1551
+ location
1552
+ });
1553
+ sync.complete(`session.family:${id}`);
1554
+ sync.complete(`session.pending:${id}`);
1555
+ sync.complete(`session.message:${id}`);
1556
+ anchored.add(id);
1557
+ }
1558
+ const request = Promise.resolve().then(() => api().session.create({ ...payload, id, location })).then((info) => {
1559
+ sessionOutbox.delete(id);
1560
+ result.session.remember(info);
1561
+ return info;
1562
+ }).catch((error) => {
1563
+ if (fresh && sessionOutbox.delete(id))
1564
+ removeSession(id);
1565
+ throw error;
1566
+ });
1567
+ if (fresh)
1568
+ track(creating, id, request);
1569
+ return { id, request };
1570
+ },
1571
+ compact(input) {
1572
+ const active = compacting.get(input.sessionID);
1573
+ if (active)
1574
+ return active.request;
1575
+ const id = SessionMessage.ID.create();
1576
+ if (!store.session.pending[input.sessionID]?.some((item) => item.type === "compaction")) {
1577
+ outbox.add(id);
1578
+ admitLocal({
1579
+ id,
1580
+ sessionID: input.sessionID,
1581
+ time: { created: Date.now() },
1582
+ type: "compaction",
1583
+ delivery: "steer",
1584
+ payload: {}
1585
+ });
1586
+ }
1587
+ const observed = new Set;
1588
+ const request = sendAdmission(input.sessionID, async () => {
1589
+ if (input.model)
1590
+ await api().session.switchModel({ sessionID: input.sessionID, model: input.model });
1591
+ return api().session.compact({ sessionID: input.sessionID, id });
1592
+ }).then((item) => {
1593
+ batch(() => {
1594
+ outbox.delete(id);
1595
+ if (item.id !== id)
1596
+ removePending(input.sessionID, id);
1597
+ if (!observed.has(item.id) && !messageIndex.get(input.sessionID)?.has(item.id))
1598
+ admitLocal(item);
1599
+ });
1600
+ return item;
1601
+ }).catch((error) => {
1602
+ if (outbox.delete(id))
1603
+ removePending(input.sessionID, id);
1604
+ throw error;
1605
+ }).finally(() => {
1606
+ if (compacting.get(input.sessionID)?.request === request)
1607
+ compacting.delete(input.sessionID);
1608
+ });
1609
+ compacting.set(input.sessionID, { id, observed, request });
1610
+ return request;
1611
+ },
1612
+ sequence(sessionID, send, prepare) {
1613
+ const left = Promise.withResolvers();
1614
+ return sendAdmission(sessionID, async () => {
1615
+ await prepare?.();
1616
+ const request = send();
1617
+ left.resolve();
1618
+ return request;
1619
+ }, undefined, (request) => Promise.race([
1620
+ request,
1621
+ left.promise.then(() => new Promise((resolve) => setTimeout(resolve, SEQUENCE_HANDOFF_MS)))
1622
+ ]));
1623
+ },
1624
+ prompt(input) {
1625
+ const { gate, prepare, ...request } = input;
1626
+ const id = request.id ?? SessionMessage.ID.create();
1627
+ const fresh = !messageIndex.get(request.sessionID)?.has(id) && !store.session.pending[request.sessionID]?.some((item) => item.id === id);
1628
+ if (fresh) {
1629
+ const files = optimisticFiles(request.files);
1630
+ const payload = {
1631
+ text: request.text,
1632
+ agents: request.agents?.map((agent) => ({ ...agent })),
1633
+ metadata: request.metadata
1634
+ };
1635
+ if (files)
1636
+ payload.files = files;
1637
+ outbox.add(id);
1638
+ admitLocal({
1639
+ id,
1640
+ sessionID: request.sessionID,
1641
+ time: { created: Date.now() },
1642
+ type: "user",
1643
+ delivery: request.delivery ?? "steer",
1644
+ payload
1645
+ });
1646
+ }
1647
+ return sendAdmission(request.sessionID, async () => {
1648
+ await prepare?.();
1649
+ return api().session.prompt({ ...request, id });
1650
+ }, gate).catch((error) => {
1651
+ if (fresh && outbox.delete(id))
1652
+ retractLocal(request.sessionID, id);
1653
+ throw error;
1654
+ });
1655
+ },
1656
+ sync(sessionID, options) {
1657
+ return sync.run(options?.children ? `session.family:${sessionID}` : `session:${sessionID}`, async () => {
1658
+ const started = deletionEpoch;
1659
+ const [info, children] = await Promise.all([
1660
+ api().session.get({ sessionID }).catch(evictMissing),
1661
+ options?.children ? listChildren({ parentID: sessionID, order: "desc", limit: CHILD_PAGE }) : []
1662
+ ]);
1663
+ const sessions = [info, ...children].filter((session) => (deletedAt.get(session.id) ?? 0) <= started);
1664
+ batch(() => {
1665
+ setStore("session", "info", produce((draft) => {
1666
+ for (const session of sessions)
1667
+ draft[session.id] = session;
1668
+ }));
1669
+ for (const session of sessions) {
1670
+ clearDeleted(session.id);
1671
+ sync.complete(`session:${session.id}`);
1672
+ registerSession(session.id);
1673
+ }
1674
+ });
1675
+ });
1676
+ },
1677
+ invalidate(sessionID) {
1678
+ sync.invalidate(`session:${sessionID}`);
1679
+ },
1680
+ message: {
1681
+ list(sessionID) {
1682
+ return store.session.message[sessionID] ?? [];
1683
+ },
1684
+ get(sessionID, messageID) {
1685
+ const messages = store.session.message[sessionID];
1686
+ const position = messageIndex.get(sessionID)?.get(messageID);
1687
+ return position === undefined ? undefined : messages?.[position];
1688
+ },
1689
+ restoreFiles() {
1690
+ const sessions = Object.entries(store.session.message).flatMap(([sessionID, messages]) => {
1691
+ const ids = (messages ?? []).filter(hasDroppedFileData).map((item) => item.id);
1692
+ return ids.length === 0 ? [] : [{ sessionID, ids }];
1693
+ });
1694
+ return Promise.all(sessions.map((session) => session.ids.reduce((previous, messageID) => previous.then(() => restoreMessageFiles(session.sessionID, messageID).catch(refreshFailed)), Promise.resolve())));
1695
+ },
1696
+ sync(sessionID) {
1697
+ return sync.run(`session.message:${sessionID}`, async () => {
1698
+ const started = deletionEpoch;
1699
+ const history = () => {
1700
+ if (!anchored.has(sessionID))
1701
+ return [];
1702
+ const inputs = new Set(result.session.input.list(sessionID));
1703
+ return (store.session.message[sessionID] ?? []).filter((item) => !outbox.has(item.id) && !inputs.has(item.id) && !stranded.get(sessionID)?.has(item.id));
1704
+ };
1705
+ const newest = await api().message.list({
1706
+ sessionID,
1707
+ limit: config.initialMessageLimit?.() ?? messagePageLimit,
1708
+ order: "desc"
1709
+ }).catch(evictMissing);
1710
+ if ((deletedAt.get(sessionID) ?? 0) > started)
1711
+ return;
1712
+ const pages = [newest];
1713
+ const read = () => pages.flatMap((page) => page.data).toReversed();
1714
+ for (const limit of bridgePageLimits) {
1715
+ const next = pages.at(-1)?.cursor.next;
1716
+ if (!next || !apart(history(), read()))
1717
+ break;
1718
+ pages.push(await api().message.list({ sessionID, limit, cursor: next }).catch(evictMissing));
1719
+ if ((deletedAt.get(sessionID) ?? 0) > started)
1720
+ return;
1721
+ }
1722
+ const fetched = read().map(stored);
1723
+ const refreshed = new Map((await Promise.all((before(history(), fetched) ?? []).filter(unsettled).map((item) => api().session.message.get({ sessionID, messageID: item.id }).then(stored).catch((error) => isMessageNotFoundError2(error) ? undefined : evictMissing(error))))).flatMap((item) => item ? [[item.id, item]] : []));
1724
+ if ((deletedAt.get(sessionID) ?? 0) > started)
1725
+ return;
1726
+ const ids = new Set(fetched.map((item) => item.id));
1727
+ const admitted = new Set((store.session.pending[sessionID] ?? []).flatMap((item) => item.type === "user" || item.type === "synthetic" ? [item.id] : []));
1728
+ const local = (store.session.message[sessionID] ?? []).filter((item) => !ids.has(item.id) && (outbox.has(item.id) || admitted.has(item.id)));
1729
+ const kept = before(history(), fetched)?.map((item) => refreshed.get(item.id) ?? item);
1730
+ const messages = [...kept ?? [], ...fetched, ...local];
1731
+ const delivered = [...admitted].filter((id) => ids.has(id));
1732
+ batch(() => {
1733
+ delivered.forEach((id) => {
1734
+ outbox.delete(id);
1735
+ removePending(sessionID, id);
1736
+ });
1737
+ anchored.add(sessionID);
1738
+ stranded.delete(sessionID);
1739
+ messageIndex.set(sessionID, new Map(messages.map((message, index) => [message.id, index])));
1740
+ setStore("session", "message", sessionID, reconcile(messages));
1741
+ if (!kept)
1742
+ setStore("session", "messageCursor", sessionID, pages.at(-1)?.cursor.next ?? undefined);
1743
+ });
1744
+ });
1745
+ },
1746
+ more(sessionID) {
1747
+ return store.session.messageCursor[sessionID] !== undefined;
1748
+ },
1749
+ loading(sessionID) {
1750
+ return store.session.messageLoading[sessionID] ?? false;
1751
+ },
1752
+ async loadMore(sessionID, options) {
1753
+ const signal = options?.signal;
1754
+ if (signal?.aborted)
1755
+ return;
1756
+ while (messageLoads.has(sessionID)) {
1757
+ const published = await (() => {
1758
+ const pending = messageLoads.get(sessionID);
1759
+ if (!signal)
1760
+ return pending;
1761
+ const aborted = Promise.withResolvers();
1762
+ const cancel = () => aborted.resolve();
1763
+ signal.addEventListener("abort", cancel, { once: true });
1764
+ return Promise.race([pending, aborted.promise]).catch((error) => {
1765
+ if (!signal.aborted)
1766
+ throw error;
1767
+ }).finally(() => signal.removeEventListener("abort", cancel));
1768
+ })();
1769
+ if (!options?.all && published || signal?.aborted)
1770
+ return;
1771
+ }
1772
+ const cursor = store.session.messageCursor[sessionID];
1773
+ if (!cursor || signal?.aborted)
1774
+ return;
1775
+ setStore("session", "messageLoading", sessionID, true);
1776
+ const request = (async () => {
1777
+ const fetched = [];
1778
+ let next = cursor;
1779
+ do {
1780
+ const response = await api().message.list({
1781
+ sessionID,
1782
+ limit: options?.all ? 200 : messagePageLimit,
1783
+ cursor: next
1784
+ }, { signal });
1785
+ if (signal?.aborted)
1786
+ return;
1787
+ fetched.push(...response.data.map(stored));
1788
+ next = response.cursor.next ?? undefined;
1789
+ if (!options?.all)
1790
+ break;
1791
+ } while (next);
1792
+ if (store.session.messageCursor[sessionID] !== cursor)
1793
+ return;
1794
+ const existing = store.session.message[sessionID] ?? [];
1795
+ const ids = new Set(existing.map((item) => item.id));
1796
+ const messages = [...fetched.reverse().filter((item) => !ids.has(item.id)), ...existing];
1797
+ batch(() => {
1798
+ options?.beforePublish?.();
1799
+ messageIndex.set(sessionID, new Map(messages.map((item, position) => [item.id, position])));
1800
+ setStore("session", "message", sessionID, reconcile(messages));
1801
+ setStore("session", "messageCursor", sessionID, next);
1802
+ });
1803
+ return true;
1804
+ })().catch((error) => {
1805
+ if (!signal?.aborted)
1806
+ throw error;
1807
+ }).finally(() => setStore("session", "messageLoading", sessionID, false));
1808
+ track(messageLoads, sessionID, request);
1809
+ await request;
1810
+ },
1811
+ invalidate(sessionID) {
1812
+ sync.invalidate(`session.message:${sessionID}`);
1813
+ }
1814
+ },
1815
+ permission: {
1816
+ list(sessionID) {
1817
+ return store.session.permission[sessionID];
1818
+ },
1819
+ sessions() {
1820
+ return Object.entries(store.session.permission).flatMap(([sessionID, requests]) => requests.length > 0 ? [sessionID] : []);
1821
+ },
1822
+ sync(sessionID) {
1823
+ return sync.run(`session.permission:${sessionID}`, async () => {
1824
+ const started = deletionEpoch;
1825
+ const list = await api().permission.list({ sessionID }).catch(evictMissing);
1826
+ if ((deletedAt.get(sessionID) ?? 0) > started)
1827
+ return;
1828
+ setStore("session", "permission", sessionID, list);
1829
+ });
1830
+ },
1831
+ invalidate(sessionID) {
1832
+ sync.invalidate(`session.permission:${sessionID}`);
1833
+ },
1834
+ async reply(input) {
1835
+ await api().permission.reply(input).catch((error) => {
1836
+ if (!isPermissionNotFoundError2(error))
1837
+ throw error;
1838
+ });
1839
+ removePermission(input.sessionID, input.requestID);
1840
+ }
1841
+ },
1842
+ form: {
1843
+ list(sessionID, ref) {
1844
+ const forms = store.session.form[sessionID];
1845
+ if (sessionID !== "global")
1846
+ return forms;
1847
+ if (!ref)
1848
+ return;
1849
+ const key = locationKey2(ref);
1850
+ return forms?.filter((form) => form.location && locationKey2(form.location) === key);
1851
+ },
1852
+ sessions() {
1853
+ return Object.entries(store.session.form).flatMap(([sessionID, forms]) => sessionID !== "global" && forms.length > 0 ? [sessionID] : []);
1854
+ },
1855
+ sync(sessionID, ref) {
1856
+ const key = `session.form:${sessionID}:${sessionID === "global" ? locationKey2(ref ?? defaultLocation()) : ""}`;
1857
+ return sync.run(key, async () => {
1858
+ if (sessionID === "global") {
1859
+ const response = await api().form.list({
1860
+ location: locationQuery(ref ?? defaultLocation())
1861
+ });
1862
+ const location = {
1863
+ directory: response.location.directory
1864
+ };
1865
+ const locationID = locationKey2(location);
1866
+ setStore("session", "form", sessionID, [
1867
+ ...(store.session.form[sessionID] ?? []).filter((form) => form.location && locationKey2(form.location) !== locationID),
1868
+ ...response.data.filter((form) => form.sessionID === "global").map((form) => ({ ...form, location }))
1869
+ ]);
1870
+ return;
1871
+ }
1872
+ const started = deletionEpoch;
1873
+ const list = await api().session.form.list({ sessionID }).catch(evictMissing);
1874
+ if ((deletedAt.get(sessionID) ?? 0) > started)
1875
+ return;
1876
+ setStore("session", "form", sessionID, list);
1877
+ });
1878
+ },
1879
+ invalidate(sessionID, ref) {
1880
+ sync.invalidate(`session.form:${sessionID}:${sessionID === "global" ? locationKey2(ref ?? defaultLocation()) : ""}`);
1881
+ },
1882
+ reply(input, ref) {
1883
+ return settleForm(input, ref, api().session.form.reply(input, formRequestOptions(input.sessionID, ref)));
1884
+ },
1885
+ cancel(input, ref) {
1886
+ return settleForm(input, ref, api().session.form.cancel(input, formRequestOptions(input.sessionID, ref)));
1887
+ }
1888
+ }
1889
+ },
1890
+ project: {
1891
+ list() {
1892
+ return Object.values(store.project.info).filter((project) => project.time.archived === undefined).toSorted((a, b) => b.time.active - a.time.active);
1893
+ },
1894
+ get(projectID) {
1895
+ return store.project.info[projectID];
1896
+ },
1897
+ sync() {
1898
+ return sync.run("project", async () => {
1899
+ const projects = await api().project.list();
1900
+ setStore("project", "info", reconcile(Object.fromEntries(projects.map((project) => [project.id, project]))));
1901
+ });
1902
+ },
1903
+ invalidate() {
1904
+ sync.invalidate("project");
1905
+ },
1906
+ permission: {
1907
+ list(projectID) {
1908
+ return store.project.permission[projectID];
1909
+ },
1910
+ sync(projectID) {
1911
+ return sync.run(`project.permission:${projectID}`, async () => {
1912
+ setStore("project", "permission", projectID, await api().permission.saved.list({ projectID }));
1913
+ });
1914
+ },
1915
+ invalidate(projectID) {
1916
+ sync.invalidate(`project.permission:${projectID}`);
1917
+ }
1918
+ }
1919
+ },
1920
+ shell: {
1921
+ list(location) {
1922
+ return Object.values(shells.list(location) ?? {});
1923
+ },
1924
+ listBySession(sessionID) {
1925
+ return Object.values(store.location).flatMap((data) => Object.values(data.shell ?? {})).filter((shell) => shell.metadata.sessionID === sessionID);
1926
+ },
1927
+ get(id) {
1928
+ return Object.values(store.location).map((data) => data.shell?.[id]).find((shell) => shell !== undefined);
1929
+ },
1930
+ sync: shells.sync,
1931
+ invalidate: shells.invalidate
1932
+ },
1933
+ job: {
1934
+ list(sessionID) {
1935
+ const members = store.jobTree[sessionID];
1936
+ return Object.values(store.job).filter((job) => members?.[job.id] || jobWithin(job, sessionID));
1937
+ },
1938
+ sync(sessionID) {
1939
+ return sync.run(`job:${sessionID}`, async () => {
1940
+ const updates = new Map;
1941
+ jobUpdates.set(sessionID, updates);
1942
+ const list = await api().experimental.job.list({ sessionID, descendants: true, status: "running" }).catch((error) => {
1943
+ if (jobUpdates.get(sessionID) === updates)
1944
+ jobUpdates.delete(sessionID);
1945
+ return evictMissing(error);
1946
+ });
1947
+ if (jobUpdates.get(sessionID) !== updates)
1948
+ return;
1949
+ jobUpdates.delete(sessionID);
1950
+ const listed = new Map(list.map((job) => [job.id, job]));
1951
+ const next = new Map(listed);
1952
+ updates.forEach((info, id) => {
1953
+ if (!info)
1954
+ return next.delete(id);
1955
+ if (listed.has(id) || jobWithin(info, sessionID))
1956
+ next.set(id, info);
1957
+ });
1958
+ const previous = store.jobTree[sessionID] ?? {};
1959
+ setStore(produce((draft) => {
1960
+ Object.values(draft.job).forEach((job) => {
1961
+ if (next.has(job.id))
1962
+ return;
1963
+ if (previous[job.id] || jobWithin(job, sessionID))
1964
+ delete draft.job[job.id];
1965
+ });
1966
+ next.forEach((job, id) => draft.job[id] = job);
1967
+ draft.jobTree[sessionID] = Object.fromEntries([...next.keys()].map((id) => [id, true]));
1968
+ }));
1969
+ });
1970
+ },
1971
+ invalidate(sessionID) {
1972
+ sync.invalidate(`job:${sessionID}`);
1973
+ }
1974
+ },
1975
+ location: {
1976
+ info(ref) {
1977
+ return store.location[locationKey2(ref ?? defaultLocation())]?.info;
1978
+ },
1979
+ default() {
1980
+ return defaultLocation();
1981
+ },
1982
+ syncInfo(ref) {
1983
+ const current = ref ?? defaultLocation();
1984
+ return sync.run(`location:${locationKey2(current)}`, async () => {
1985
+ const location = await api().location.get({ location: locationQuery(current) });
1986
+ const key = locationKey2(location);
1987
+ if (!store.location[key])
1988
+ setStore("location", key, {});
1989
+ setStore("location", key, "info", location);
1990
+ if (location.directory !== current.directory)
1991
+ setCanonicalDirectory(current.directory, location.directory);
1992
+ if (!ref) {
1993
+ setDefaultLocation({ directory: location.directory });
1994
+ }
1995
+ });
1996
+ },
1997
+ async sync(ref) {
1998
+ await result.location.syncInfo(ref);
1999
+ const location = ref ?? defaultLocation();
2000
+ await Promise.all([
2001
+ flags.sync(location),
2002
+ result.location.vcs.sync(location),
2003
+ result.location.agent.sync(location),
2004
+ result.location.command.sync(location),
2005
+ result.location.integration.sync(location),
2006
+ result.location.mcp.server.sync(location),
2007
+ result.location.mcp.resource.sync(location),
2008
+ result.location.model.sync(location),
2009
+ result.location.provider.sync(location),
2010
+ result.location.reference.sync(location),
2011
+ result.location.skill.sync(location),
2012
+ result.shell.sync(location),
2013
+ result.session.form.sync("global", location)
2014
+ ]);
2015
+ },
2016
+ invalidate(ref) {
2017
+ const location = ref ?? defaultLocation();
2018
+ sync.invalidate(`location:${locationKey2(location)}`);
2019
+ result.location.vcs.invalidate(location);
2020
+ result.location.agent.invalidate(location);
2021
+ result.location.command.invalidate(location);
2022
+ result.location.config.invalidate(location);
2023
+ result.location.integration.invalidate(location);
2024
+ result.location.mcp.server.invalidate(location);
2025
+ result.location.mcp.resource.invalidate(location);
2026
+ result.location.model.invalidate(location);
2027
+ result.location.provider.invalidate(location);
2028
+ result.location.reference.invalidate(location);
2029
+ result.location.skill.invalidate(location);
2030
+ flags.invalidate(location);
2031
+ result.shell.invalidate(location);
2032
+ result.session.form.invalidate("global", location);
2033
+ },
2034
+ vcs: { info: vcs.list, sync: vcs.sync, invalidate: vcs.invalidate },
2035
+ flag(key, ref) {
2036
+ return flags.list(ref)?.[key] === true;
2037
+ },
2038
+ flags: { list: flags.list, sync: flags.sync, invalidate: flags.invalidate },
2039
+ usage: { limits: usageLimits.list, sync: usageLimits.sync, invalidate: usageLimits.invalidate },
2040
+ agent: locationResource("agent", (location) => api().agent.list({ location })),
2041
+ command: locationResource("command", (location) => api().command.list({ location })),
2042
+ config: locationResource("config", async (location) => ({
2043
+ location: { directory: location.directory },
2044
+ data: await api().config.get({ location })
2045
+ })),
2046
+ integration: locationResource("integration", (location) => api().integration.list({ location })),
2047
+ mcp: {
2048
+ server: locationResource("mcpServer", (location) => api().mcp.list({ location })),
2049
+ resource: locationResource("mcpResource", async (location) => {
2050
+ const response = await api().mcp.resource.catalog({ location });
2051
+ return { location: response.location, data: response.data.resources };
2052
+ })
2053
+ },
2054
+ model: locationResource("model", (location) => api().model.list({ location }), { alias: true }),
2055
+ provider: locationResource("provider", (location) => api().provider.list({ location }), { alias: true }),
2056
+ reference: locationResource("reference", (location) => api().reference.list({ location })),
2057
+ websearch: {
2058
+ list(location) {
2059
+ return store.location[locationKey2(location ?? defaultLocation())]?.websearch;
2060
+ },
2061
+ async refresh(ref) {
2062
+ const input = { location: locationQuery(ref ?? defaultLocation()) };
2063
+ const providers = await api().websearch.providers(input);
2064
+ const key = locationKey2(providers.location);
2065
+ setStore("location", key, { websearch: providers.data });
2066
+ }
2067
+ },
2068
+ skill: locationResource("skill", (location) => api().skill.list({ location }))
2069
+ }
2070
+ };
2071
+ createEffect(() => {
2072
+ if (config.connection?.status() === "connected")
2073
+ return;
2074
+ sync.invalidate();
2075
+ });
2076
+ onCleanup(config.event.listen(({ details }) => {
2077
+ handleEvent(details);
2078
+ }));
2079
+ return result;
2080
+ }
2081
+ function missingEndpoint(error) {
2082
+ if (!(error instanceof ClientError3))
2083
+ return false;
2084
+ if (error.reason === "UnexpectedStatus")
2085
+ return error.cause?.status === 404;
2086
+ return error.reason === "UnsupportedContentType";
2087
+ }
2088
+
2089
+ export { settleMs2, locationKey2, createData2 };