@clagentic/console 1.10.0-beta.1 → 1.10.0-beta.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 (94) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +10 -0
  3. package/lib/activity-clock.js +23 -0
  4. package/lib/agent-dispatch-tool.js +20 -0
  5. package/lib/build-changes.js +79 -0
  6. package/lib/build-identity.js +192 -0
  7. package/lib/build-monitor.js +125 -0
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-offer.js +141 -0
  10. package/lib/build-update-restart.js +142 -0
  11. package/lib/build-update-standing.js +184 -0
  12. package/lib/cli/daemon-launch.js +8 -5
  13. package/lib/cli/ipc-subcommands.js +6 -0
  14. package/lib/cli/session-subcommands.js +122 -0
  15. package/lib/cli-sessions.js +8 -1
  16. package/lib/cli-transcript-title.js +131 -0
  17. package/lib/codex-defaults.js +8 -2
  18. package/lib/daemon-projects.js +19 -0
  19. package/lib/daemon.js +166 -127
  20. package/lib/debug-log.js +17 -0
  21. package/lib/exit-flush.js +44 -0
  22. package/lib/grant-keys.js +179 -0
  23. package/lib/log-field.js +34 -0
  24. package/lib/memory-shed.js +13 -32
  25. package/lib/project-connection.js +14 -0
  26. package/lib/project-external-trigger.js +91 -123
  27. package/lib/project-http.js +2 -0
  28. package/lib/project-loop.js +5 -4
  29. package/lib/project-notifications.js +4 -0
  30. package/lib/project-prompt-responses.js +7 -5
  31. package/lib/project-session-grants.js +73 -0
  32. package/lib/project-sessions.js +55 -68
  33. package/lib/project-user-message.js +13 -25
  34. package/lib/project.js +25 -5
  35. package/lib/prompt-kinds/permission.js +18 -0
  36. package/lib/prompt-label.js +60 -0
  37. package/lib/prompt-registry.js +123 -13
  38. package/lib/prompt-source.js +65 -0
  39. package/lib/public/css/diagnostics.css +30 -0
  40. package/lib/public/css/notifications-center.css +15 -0
  41. package/lib/public/css/overlays.css +18 -0
  42. package/lib/public/css/rewind.css +8 -0
  43. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  44. package/lib/public/modules/app-messages.js +10 -2
  45. package/lib/public/modules/app-notifications.js +9 -1
  46. package/lib/public/modules/app-panels.js +0 -1
  47. package/lib/public/modules/build-update-detail.js +54 -0
  48. package/lib/public/modules/diagnostics.js +126 -20
  49. package/lib/public/modules/prompt-banner.js +12 -0
  50. package/lib/public/modules/prompt-kinds/permission-choices.js +6 -1
  51. package/lib/public/modules/prompt-kinds/permission.js +15 -0
  52. package/lib/public/modules/prompt-label.js +44 -0
  53. package/lib/public/modules/prompts.js +9 -0
  54. package/lib/public/modules/session-grants.js +131 -0
  55. package/lib/public/modules/sidebar-sessions.js +11 -0
  56. package/lib/public/modules/tools.js +14 -2
  57. package/lib/public/modules/vendor-picker.js +2 -2
  58. package/lib/public/modules/vendor-registry.js +11 -2
  59. package/lib/runtime-env.js +1 -1
  60. package/lib/sdk-bridge.js +114 -115
  61. package/lib/sdk-message-processor.js +25 -87
  62. package/lib/sdk-skill-discovery.js +65 -60
  63. package/lib/server.js +15 -2
  64. package/lib/session-ai-title.js +80 -0
  65. package/lib/session-id.js +33 -0
  66. package/lib/session-input-ipc.js +32 -0
  67. package/lib/session-input.js +409 -0
  68. package/lib/session-reclaim.js +284 -0
  69. package/lib/session-resume.js +172 -0
  70. package/lib/sessions.js +31 -21
  71. package/lib/supervisor.js +39 -0
  72. package/lib/turn-initiator.js +108 -0
  73. package/lib/utils.js +9 -47
  74. package/lib/vendor-registry-message.js +1 -0
  75. package/lib/ws-schema.js +9 -4
  76. package/lib/yoke/adapters/claude-vendor.js +0 -1
  77. package/lib/yoke/adapters/claude-worker.js +6 -4
  78. package/lib/yoke/adapters/claude.js +29 -86
  79. package/lib/yoke/adapters/codex-capabilities.js +9 -6
  80. package/lib/yoke/adapters/codex-vendor.js +15 -15
  81. package/lib/yoke/adapters/codex.js +125 -136
  82. package/lib/yoke/auth-checks.js +8 -21
  83. package/lib/yoke/codex-app-server.js +27 -71
  84. package/lib/yoke/codex-binary.js +254 -0
  85. package/lib/yoke/codex-command.js +122 -0
  86. package/lib/yoke/codex-protocol.js +96 -0
  87. package/lib/yoke/codex-version.js +135 -0
  88. package/lib/yoke/index.js +20 -4
  89. package/lib/yoke/install-probe.js +21 -6
  90. package/lib/yoke/interface.js +14 -12
  91. package/lib/yoke/registry.js +41 -4
  92. package/package.json +1 -2
  93. package/scripts/verify-installed-build.js +59 -17
  94. package/lib/lore-attestation.js +0 -73
@@ -0,0 +1,409 @@
1
+ // session-input.js - open a session, or send input to one, on behalf of a
2
+ // caller that is not the authenticated browser: an external-trigger file
3
+ // (project-external-trigger.js) or the daemon IPC verbs (lib/daemon.js).
4
+ // One implementation behind both, so the same request gets the same result.
5
+ //
6
+ // Any caller, any session kind: the vendor and agent come from the request on
7
+ // open, and from the stored session on send. Input never counts as a human
8
+ // turn: an initiator of "human" (or anything unknown) is refused, and an absent
9
+ // one is "trigger". Human turns come only from the browser's WebSocket path.
10
+ //
11
+ // Security is unchanged from the external trigger: the callers that reach this
12
+ // are the OS user that owns the config directory (file drop; daemon.sock is
13
+ // chmod 0700). Routing per user in multi-user mode remains future work.
14
+
15
+ var { INITIATORS } = require("./turn-initiator");
16
+ var { isKnownVendor } = require("./yoke");
17
+ var { getNewWorkRefusal } = require("./new-work-gate");
18
+ var agentsModule = require("./agents");
19
+ var sessionResume = require("./session-resume");
20
+ var { logField, logText } = require("./log-field");
21
+
22
+ // The result vocabulary reported to the caller. "error" is not a verdict on
23
+ // the request: delivery was attempted and failed, so a caller may retry.
24
+ var RESULT = Object.freeze({
25
+ DELIVERED: "delivered",
26
+ RESUMED: "resumed-and-delivered",
27
+ OPENED: "opened",
28
+ NOT_FOUND: "not-found",
29
+ REFUSED: "refused",
30
+ ERROR: "error",
31
+ });
32
+
33
+ // Initiators injected input may name. HUMAN is deliberately absent.
34
+ var ACCEPTED_INITIATORS = Object.freeze([
35
+ INITIATORS.TRIGGER,
36
+ INITIATORS.SCHEDULED,
37
+ INITIATORS.SCHEDULED_NOW,
38
+ INITIATORS.LOOP,
39
+ ]);
40
+
41
+ var VISIBILITIES = Object.freeze(["shared", "private"]);
42
+
43
+ function shown(value) {
44
+ return JSON.stringify(String(value).slice(0, 64));
45
+ }
46
+
47
+ function refused(reason) {
48
+ return { ok: false, result: RESULT.REFUSED, reason: reason };
49
+ }
50
+
51
+ // The daemon is shedding new work (memory pressure). Not a verdict on the
52
+ // request, so a file-drop caller keeps its trigger and tries again later.
53
+ function refusedForLoad(reason) {
54
+ return { ok: false, result: RESULT.REFUSED, reason: reason, retryable: true };
55
+ }
56
+
57
+ // Returns { initiator } or { refusal }.
58
+ function resolveInitiator(raw) {
59
+ if (raw === undefined || raw === null) return { initiator: INITIATORS.TRIGGER };
60
+ if (typeof raw === "string" && ACCEPTED_INITIATORS.indexOf(raw) !== -1) return { initiator: raw };
61
+ var why = raw === INITIATORS.HUMAN
62
+ ? "human turns come only from the authenticated browser"
63
+ : "unknown initiator";
64
+ return {
65
+ refusal: refused("initiator " + shown(raw) + " refused: " + why + " (accepted: " + ACCEPTED_INITIATORS.join(", ") + ")"),
66
+ };
67
+ }
68
+
69
+ // A session in memory is addressed by the id its vendor assigned or by the
70
+ // console's own session id (what open-session returns, always present).
71
+ function findSession(sm, id) {
72
+ var byVendorId = null;
73
+ var byConsoleId = null;
74
+ sm.sessions.forEach(function (s) {
75
+ if (!byVendorId && s.cliSessionId === id) byVendorId = s;
76
+ if (!byConsoleId && String(s.localId) === id) byConsoleId = s;
77
+ });
78
+ return byVendorId || byConsoleId;
79
+ }
80
+
81
+ function messageOf(err) {
82
+ return err && err.message ? err.message : String(err);
83
+ }
84
+
85
+ // The query did not start, so the input was not delivered and sending it again
86
+ // cannot deliver it twice.
87
+ function sendStartFailure(project, session, label, err) {
88
+ session.isProcessing = false;
89
+ project.onProcessingChanged();
90
+ console.error("[session-input] turn start failed for " + label + ":", messageOf(err));
91
+ return { ok: false, result: RESULT.ERROR, retryable: true, reason: "turn start failed: " + messageOf(err) };
92
+ }
93
+
94
+ // A session this request created whose first turn did not start is removed, so
95
+ // a failed open leaves nothing behind, and is not retried: the caller opens
96
+ // again if it wants to.
97
+ function openStartFailure(project, session, label, err) {
98
+ session.isProcessing = false;
99
+ project.onProcessingChanged();
100
+ console.error("[session-input] open failed for " + label + ":", messageOf(err));
101
+ try { project.sm.deleteSession(session.localId); }
102
+ catch (e) { console.error("[session-input] could not remove " + label + ":", messageOf(e)); }
103
+ return { ok: false, result: RESULT.ERROR, retryable: false, reason: "open failed: " + messageOf(err) };
104
+ }
105
+
106
+ // Starts the session's query and answers when it has actually started: a
107
+ // rejection (or a synchronous throw) is a failed delivery, never a delivered
108
+ // one. Returns the value of onStarted(), or a Promise of it when the start is
109
+ // asynchronous. onFailed(project, session, label, err) makes the failure result.
110
+ function startThen(project, session, label, start, onStarted, onFailed) {
111
+ var started;
112
+ try { started = start(); }
113
+ catch (e) { return onFailed(project, session, label, e); }
114
+ if (started && typeof started.then === "function") {
115
+ return started.then(onStarted, function (err) { return onFailed(project, session, label, err); });
116
+ }
117
+ return onStarted();
118
+ }
119
+
120
+ // A caller on the daemon's IPC or the trigger watcher must always get a
121
+ // result, so an unexpected throw is reported as an error, not propagated.
122
+ function neverThrows(fn) {
123
+ return function (req) {
124
+ try { return fn(req); }
125
+ catch (e) {
126
+ console.error("[session-input] unexpected failure:", messageOf(e));
127
+ return { ok: false, result: RESULT.ERROR, reason: "unexpected failure: " + messageOf(e) };
128
+ }
129
+ };
130
+ }
131
+
132
+ // One line per request, whichever caller made it (IPC verb or file drop): the
133
+ // project, the console session and the result, with the reason when the
134
+ // request was refused or failed. The prompt, the context note and the request
135
+ // body are never part of it; a reason only quotes a bounded identifier.
136
+ function logResult(verb, req, out) {
137
+ req = req || {};
138
+ out = out || {};
139
+ var line = "[session-input] " + verb + ": project=" + logField(req.projectSlug)
140
+ + " session=" + logField(out.consoleSessionId || req.sessionId)
141
+ + " result=" + logField(out.result);
142
+ if (out.retryable === true) line += " retryable=true";
143
+ // Last, because it is free text.
144
+ if (out.reason) line += " reason=" + logText(out.reason);
145
+ console.log(line);
146
+ }
147
+
148
+ function logged(verb, fn) {
149
+ return function (req) {
150
+ var out = fn(req);
151
+ if (out && typeof out.then === "function") {
152
+ return out.then(function (result) { logResult(verb, req, result); return result; });
153
+ }
154
+ logResult(verb, req, out);
155
+ return out;
156
+ };
157
+ }
158
+
159
+ // deps:
160
+ // getProject(slug) -> project context | null
161
+ // agentCatalog(project) -> [{ name }] named agents on offer (default: the picker's catalog)
162
+ function createSessionInput(deps) {
163
+ var getProject = deps.getProject;
164
+
165
+ function defaultAgentCatalog(project) {
166
+ // Neither lookup throws: both answer [] when discovery has not run or the
167
+ // directory is absent.
168
+ return agentsModule.getAll().concat(agentsModule.readProjectAgents(project.cwd));
169
+ }
170
+ var agentCatalog = deps.agentCatalog || defaultAgentCatalog;
171
+
172
+ function resolveProject(slug) {
173
+ var project = typeof slug === "string" && slug ? getProject(slug) : null;
174
+ if (!project) return { refusal: refused("unknown project " + shown(slug)) };
175
+ if (!project.sm || !project.sdk) {
176
+ return { refusal: { ok: false, result: RESULT.ERROR, reason: "project " + shown(slug) + " is not ready" } };
177
+ }
178
+ return { project: project };
179
+ }
180
+
181
+ function checkPrompt(prompt) {
182
+ return typeof prompt === "string" && prompt ? null : refused("prompt must be a non-empty string");
183
+ }
184
+
185
+ // History entry that marks the turn as injected, not typed. The input is
186
+ // already delivered when this runs, so a failure to record is logged and does
187
+ // not turn a delivered turn into an error a caller would retry.
188
+ function recordInjected(project, session, req, initiator) {
189
+ var entry = {
190
+ type: "user_message",
191
+ text: req.prompt,
192
+ source: "external-trigger",
193
+ initiator: initiator,
194
+ };
195
+ if (req.triggerId) entry.triggerId = req.triggerId;
196
+ if (req.contextNote) entry.contextNote = req.contextNote;
197
+ try {
198
+ project.sm.recordHistoryEntry(session, entry, true);
199
+ project.sm.appendToSessionFile(session, entry);
200
+ } catch (e) {
201
+ console.error("[session-input] failed to record injected message:", e.message || e);
202
+ }
203
+ }
204
+
205
+ function describe(project, session) {
206
+ return {
207
+ consoleSessionId: String(session.localId),
208
+ sessionId: session.cliSessionId || null,
209
+ localId: session.localId,
210
+ vendor: session.vendor || project.sm.defaultVendor || null,
211
+ agent: session.agentName || null,
212
+ };
213
+ }
214
+
215
+ // Delivers req.prompt as the session's next turn: into the running query,
216
+ // or by starting one (the session's runtime was ended) on the session's own
217
+ // vendor and agent.
218
+ function deliver(project, session, req, initiator, resumed) {
219
+ var sdk = project.sdk;
220
+ var processing = !!session.isProcessing;
221
+ var needsStart = !processing && !session.queryInstance && (!session.worker || session.messageQueue !== "worker");
222
+
223
+ if (needsStart) {
224
+ var refusal = getNewWorkRefusal();
225
+ if (refusal) return refusedForLoad(refusal);
226
+ }
227
+
228
+ function delivered() {
229
+ recordInjected(project, session, req, initiator);
230
+ var out = describe(project, session);
231
+ out.ok = true;
232
+ out.result = (resumed || needsStart) ? RESULT.RESUMED : RESULT.DELIVERED;
233
+ return out;
234
+ }
235
+
236
+ function pushFailure(e) {
237
+ console.error("[session-input] delivery failed:", messageOf(e));
238
+ return { ok: false, result: RESULT.ERROR, reason: "delivery failed: " + messageOf(e) };
239
+ }
240
+
241
+ if (processing) {
242
+ try { sdk.pushMessage(session, req.prompt, null, initiator); }
243
+ catch (e) { return pushFailure(e); }
244
+ return delivered();
245
+ }
246
+
247
+ session.isProcessing = true;
248
+ project.onProcessingChanged();
249
+ session.sentToolResults = {};
250
+ if (needsStart) {
251
+ return startThen(project, session, "session " + String(session.cliSessionId), function () {
252
+ return sdk.startQuery(session, req.prompt, undefined, project.getLinuxUserForSession(session), initiator);
253
+ }, delivered, sendStartFailure);
254
+ }
255
+ try { sdk.pushMessage(session, req.prompt, null, initiator); }
256
+ catch (e) {
257
+ session.isProcessing = false;
258
+ project.onProcessingChanged();
259
+ return pushFailure(e);
260
+ }
261
+ return delivered();
262
+ }
263
+
264
+ // req: { projectSlug, sessionId, prompt, initiator?, contextNote?, triggerId? }
265
+ // Returns the result, or a Promise of it when the session must be read from
266
+ // the store first (see settle()).
267
+ function sendInput(req) {
268
+ req = req || {};
269
+ var init = resolveInitiator(req.initiator);
270
+ if (init.refusal) return init.refusal;
271
+ var promptRefusal = checkPrompt(req.prompt);
272
+ if (promptRefusal) return promptRefusal;
273
+ if (typeof req.sessionId !== "string" || !req.sessionId) {
274
+ return refused("sessionId must be a non-empty string");
275
+ }
276
+ // An id names files in the store; one that is not a plain id is refused, not
277
+ // looked up and not reported as absent.
278
+ if (!sessionResume.isSafeSessionId(req.sessionId)) {
279
+ return refused("unsafe session id " + shown(req.sessionId) + " refused");
280
+ }
281
+ var resolved = resolveProject(req.projectSlug);
282
+ if (resolved.refusal) return resolved.refusal;
283
+ var project = resolved.project;
284
+
285
+ var live = findSession(project.sm, req.sessionId);
286
+ if (live) return deliver(project, live, req, init.initiator, false);
287
+
288
+ // Only the console's own store is asked: a session started outside the
289
+ // console is not addressable, and its absence here is positive.
290
+ var storeDeps = { sm: project.sm, cwd: project.cwd };
291
+ function notFound() {
292
+ return { ok: false, result: RESULT.NOT_FOUND, reason: "no session " + shown(req.sessionId) + " in project " + shown(req.projectSlug) };
293
+ }
294
+ return sessionResume.sessionExistsInStore(project.sm, req.sessionId).then(function (exists) {
295
+ if (!exists) return notFound();
296
+ var gate = getNewWorkRefusal();
297
+ if (gate) return refusedForLoad(gate);
298
+ // activate:false: nobody asked to look at this session.
299
+ return sessionResume.resumeStoredSession(storeDeps, req.sessionId, { activate: false }).then(function (session) {
300
+ // The session was found in the store, so a manager that declines to
301
+ // bring it back is a failure to resume, not an absence.
302
+ if (!session) {
303
+ return { ok: false, result: RESULT.ERROR, retryable: false, reason: "session " + shown(req.sessionId) + " exists but could not be resumed" };
304
+ }
305
+ return deliver(project, session, req, init.initiator, true);
306
+ });
307
+ }).catch(function (err) {
308
+ // Lookup and resume failures carry whether trying again can help
309
+ // (session-resume.js); the input was not delivered either way.
310
+ console.error("[session-input] send failed:", messageOf(err));
311
+ return { ok: false, result: RESULT.ERROR, retryable: !!(err && err.retryable), reason: "send failed: " + messageOf(err) };
312
+ });
313
+ }
314
+
315
+ // Checks an open request's session kind; returns { options } for
316
+ // sm.createSession (the options the browser's new_session passes) or { refusal }.
317
+ function resolveSessionKind(project, req) {
318
+ var options = {};
319
+ if (req.vendor !== undefined && req.vendor !== null) {
320
+ if (typeof req.vendor !== "string" || !isKnownVendor(req.vendor)) {
321
+ return { refusal: refused("unknown vendor " + shown(req.vendor)) };
322
+ }
323
+ options.vendor = req.vendor;
324
+ }
325
+ if (req.agentName !== undefined && req.agentName !== null) {
326
+ var known = typeof req.agentName === "string" && agentCatalog(project).some(function (a) {
327
+ return a && a.name === req.agentName;
328
+ });
329
+ if (!known) return { refusal: refused("unknown agent " + shown(req.agentName)) };
330
+ options.agentName = req.agentName;
331
+ }
332
+ if (req.sessionVisibility !== undefined && req.sessionVisibility !== null) {
333
+ if (VISIBILITIES.indexOf(req.sessionVisibility) === -1) {
334
+ return { refusal: refused("unknown sessionVisibility " + shown(req.sessionVisibility) + " (accepted: " + VISIBILITIES.join(", ") + ")") };
335
+ }
336
+ options.sessionVisibility = req.sessionVisibility;
337
+ }
338
+ return { options: options };
339
+ }
340
+
341
+ // req: { projectSlug, prompt, vendor?, agentName?, sessionVisibility?,
342
+ // initiator?, contextNote?, cwd?, triggerId? }
343
+ // Returns the result, or a Promise of it when the first turn starts
344
+ // asynchronously (see settle()).
345
+ function openSession(req) {
346
+ req = req || {};
347
+ var init = resolveInitiator(req.initiator);
348
+ if (init.refusal) return init.refusal;
349
+ var promptRefusal = checkPrompt(req.prompt);
350
+ if (promptRefusal) return promptRefusal;
351
+ var resolved = resolveProject(req.projectSlug);
352
+ if (resolved.refusal) return resolved.refusal;
353
+ var project = resolved.project;
354
+ var kind = resolveSessionKind(project, req);
355
+ if (kind.refusal) return kind.refusal;
356
+ var gate = getNewWorkRefusal();
357
+ if (gate) return refusedForLoad(gate);
358
+
359
+ var sm = project.sm;
360
+ var sess = sm.createSession(kind.options);
361
+ var label = req.triggerId ? " — " + String(req.triggerId).substring(0, 12) : "";
362
+ sess.title = (req.contextNote || "External trigger") + label;
363
+ if (req.cwd) sess.cwd = req.cwd;
364
+ sm.saveSessionFile(sess);
365
+ sm.broadcastSessionList();
366
+
367
+ sess.isProcessing = true;
368
+ project.onProcessingChanged();
369
+ sess.sentToolResults = {};
370
+ // The session stays open for follow-up from a person.
371
+ sess.acceptEditsAfterStart = true;
372
+
373
+ function opened() {
374
+ var out = describe(project, sess);
375
+ out.ok = true;
376
+ out.result = RESULT.OPENED;
377
+ return out;
378
+ }
379
+ return startThen(project, sess, "local session " + sess.localId, function () {
380
+ return project.sdk.startQuery(sess, req.prompt, undefined, project.getLinuxUserForSession(sess), init.initiator);
381
+ }, function () {
382
+ // Recorded once, only now that the query has started: a rejected start
383
+ // leaves no history entry for a prompt that never ran.
384
+ recordInjected(project, sess, req, init.initiator);
385
+ return opened();
386
+ }, openStartFailure);
387
+ }
388
+
389
+ return {
390
+ openSession: logged("open_session", neverThrows(openSession)),
391
+ sendInput: logged("send_session_input", neverThrows(sendInput)),
392
+ };
393
+ }
394
+
395
+ // sendInput and openSession answer synchronously when nothing has to wait and
396
+ // with a Promise otherwise, so a caller that can act at once (the trigger
397
+ // watcher on a live session) does. settle() runs fn on either.
398
+ function settle(valueOrPromise, fn) {
399
+ if (valueOrPromise && typeof valueOrPromise.then === "function") return valueOrPromise.then(fn);
400
+ return fn(valueOrPromise);
401
+ }
402
+
403
+ module.exports = {
404
+ createSessionInput: createSessionInput,
405
+ settle: settle,
406
+ resolveInitiator: resolveInitiator,
407
+ RESULT: RESULT,
408
+ ACCEPTED_INITIATORS: ACCEPTED_INITIATORS,
409
+ };
@@ -0,0 +1,284 @@
1
+ "use strict";
2
+
3
+ // Shared bookkeeping for ending a session that still has live background
4
+ // agents (Task dispatches). Two paths end such a session without the operator
5
+ // asking: the idle reaper (lib/sdk-bridge.js) and memory shedding
6
+ // (lib/memory-shed.js). Neither may do it silently, so both announce through
7
+ // announceLiveAgentReclaim: the agents are named, the session is marked as
8
+ // expected to resume, and both UI surfaces are told.
9
+
10
+ var LABEL_MAX = 80;
11
+ var FALLBACK_LABEL = "background agent";
12
+
13
+ function labelTable(session) {
14
+ if (!session.taskLabels) session.taskLabels = Object.create(null);
15
+ return session.taskLabels;
16
+ }
17
+
18
+ // A Task's description or subagent type comes from the model, so it is bound
19
+ // and reduced to one line before it is shown to the operator.
20
+ function cleanLabel(raw) {
21
+ if (typeof raw !== "string") return FALLBACK_LABEL;
22
+ var one = raw.replace(/\s+/g, " ").trim();
23
+ if (!one) return FALLBACK_LABEL;
24
+ return one.length > LABEL_MAX ? one.slice(0, LABEL_MAX - 3) + "..." : one;
25
+ }
26
+
27
+ /** Remember how to name a Task for the operator. */
28
+ function noteTaskLabel(session, taskId, input) {
29
+ if (typeof taskId !== "string" || !taskId) return;
30
+ var src = input && typeof input === "object" ? input : {};
31
+ // Bounds the table: a Task that left tracking via a settled prompt has no
32
+ // other forget event.
33
+ pruneTaskLabels(session);
34
+ labelTable(session)[taskId] = cleanLabel(src.description || src.subagent_type);
35
+ }
36
+
37
+ /**
38
+ * Drop the label of every Task the session no longer tracks. A label lives
39
+ * exactly as long as its Task: a Task that completed while its sub-agent's
40
+ * prompt is still open stays tracked, and a reclaim must still name it. The
41
+ * prompt registry decides when a Task leaves tracking, so this follows its
42
+ * answer instead of guessing at the end event.
43
+ */
44
+ function pruneTaskLabels(session) {
45
+ var table = session && session.taskLabels;
46
+ if (!table) return;
47
+ var tracked = session.activeTaskToolIds || {};
48
+ Object.keys(table).forEach(function (id) {
49
+ if (!Object.prototype.hasOwnProperty.call(tracked, id) || !tracked[id]) delete table[id];
50
+ });
51
+ }
52
+
53
+ function labelOf(session, taskId) {
54
+ var table = session.taskLabels;
55
+ return (table && Object.prototype.hasOwnProperty.call(table, taskId) && table[taskId]) || FALLBACK_LABEL;
56
+ }
57
+
58
+ /**
59
+ * Every Task the session still tracks, as [{id, label}]. The one reader of
60
+ * session.activeTaskToolIds for operator-facing lists: the reclaim announcer
61
+ * and the build-update offer both go through it.
62
+ */
63
+ function liveAgentTasks(session) {
64
+ var tasks = session && session.activeTaskToolIds;
65
+ if (!tasks) return [];
66
+ return Object.keys(tasks).filter(function (id) { return tasks[id]; }).map(function (id) {
67
+ return { id: id, label: cleanLabel(labelOf(session, id)) };
68
+ });
69
+ }
70
+
71
+ /** Operator-facing names of every Task the session still tracks. */
72
+ function liveAgentLabels(session) {
73
+ return liveAgentTasks(session).map(function (t) { return t.label; });
74
+ }
75
+
76
+ /** Name of the Task that owns a tool call raised by a sub-agent, or null. */
77
+ function ownerLabelOfTool(session, prompts, toolUseId) {
78
+ var owner = prompts.ownerTaskOfTool(session, toolUseId);
79
+ return owner ? labelOf(session, owner) : null;
80
+ }
81
+
82
+ function describeAgents(labels) {
83
+ return labels.length === 1
84
+ ? 'background agent "' + labels[0] + '"'
85
+ : labels.length + " background agents (" + labels.map(function (l) { return '"' + l + '"'; }).join(", ") + ")";
86
+ }
87
+
88
+ function reclaimMessage(cause, labels) {
89
+ return cause + " Interrupted: " + describeAgents(labels) + ". "
90
+ + "The session will resume on your next message; if it does not, resume it manually.";
91
+ }
92
+
93
+ // A daemon shutdown ends every session at once and nobody is connected to hear
94
+ // it, so the agents are written to the session file and told to the operator
95
+ // at the next startup (surfaceRestartReclaims / restartNoticeMessages).
96
+ var RESTART_REASON = "daemon_restart";
97
+ var RESTART_CAUSE = "Clagentic: Console shut down or restarted while this session had background agents running.";
98
+ // Bounds the meta line of the session file, which is read back from a 4 KiB chunk.
99
+ var PERSISTED_AGENTS_MAX = 8;
100
+
101
+ /** Validate a persisted agent-label list read back from a session file. */
102
+ function sanitizeAgentLabels(raw) {
103
+ if (!Array.isArray(raw)) return null;
104
+ var out = raw.filter(function (l) { return typeof l === "string"; })
105
+ .slice(0, PERSISTED_AGENTS_MAX).map(cleanLabel);
106
+ return out.length ? out : null;
107
+ }
108
+
109
+ function errText(e) {
110
+ return e && e.message ? e.message : String(e);
111
+ }
112
+
113
+ // A failure here is never silent: the journal names the session, the agents
114
+ // and the error, so a lost resume marker or notice can be traced afterwards.
115
+ function logReclaimFailure(what, session, labels, e) {
116
+ console.error("[session-reclaim] " + what + " for session " + session.localId
117
+ + " (agents: " + labels.map(function (l) { return JSON.stringify(l); }).join(", ") + "): " + errText(e));
118
+ }
119
+
120
+ /**
121
+ * Tell the operator a session with live background agents was ended, and
122
+ * record that it is expected to resume. Never throws: the caller is ending a
123
+ * session (or the process) and must proceed whatever happens here.
124
+ *
125
+ * Returns { labels, persisted }. labels are the agents announced (empty when
126
+ * the session had none, in which case nothing is sent or written and
127
+ * persisted is true). persisted is false when the resume marker could not be
128
+ * written to the session file, so a caller can count the failures.
129
+ *
130
+ * @param {object} o
131
+ * @param {object} o.session
132
+ * @param {object} o.sm - session manager (saveSessionFile, sendAndRecord)
133
+ * @param {?function(object)} o.send - project-wide broadcast
134
+ * @param {?string} o.slug
135
+ * @param {string} o.reason - durable marker stored on the session
136
+ * @param {string} o.source - diagnostic source shown in the Diagnostics panel
137
+ * @param {string} o.cause - sentence naming why the session was ended
138
+ * @param {boolean} [o.deferNotice] - persist the marker and the agent names but
139
+ * send nothing now (the process is exiting; the notice goes out at startup)
140
+ */
141
+ function announceLiveAgentReclaim(o) {
142
+ var session = o.session;
143
+ if (!session) return { labels: [], persisted: true };
144
+ var labels = liveAgentLabels(session);
145
+ if (labels.length === 0) return { labels: labels, persisted: true };
146
+
147
+ var persisted = true;
148
+ try {
149
+ session.pendingAutoResume = true;
150
+ session.pendingAutoResumeReason = o.reason;
151
+ // Only a deferred notice needs the names to outlive the process.
152
+ if (o.deferNotice) session.pendingAutoResumeAgents = labels.slice(0, PERSISTED_AGENTS_MAX);
153
+ if (o.sm && typeof o.sm.saveSessionFile === "function") o.sm.saveSessionFile(session);
154
+ } catch (e) {
155
+ // The notification below still has to go out if the marker cannot be written.
156
+ persisted = false;
157
+ logReclaimFailure("Could not persist the resume marker (" + o.reason + ")", session, labels, e);
158
+ }
159
+
160
+ if (o.deferNotice) return { labels: labels, persisted: persisted };
161
+
162
+ var message = reclaimMessage(o.cause, labels);
163
+ if (typeof o.send === "function") {
164
+ try {
165
+ o.send({
166
+ type: "diagnostic",
167
+ severity: "warning",
168
+ source: o.source,
169
+ message: (o.slug ? "[" + o.slug + "] " : "") + message,
170
+ });
171
+ } catch (e) {
172
+ logReclaimFailure("Could not broadcast the reclaim notice", session, labels, e);
173
+ }
174
+ }
175
+ if (o.sm && typeof o.sm.sendAndRecord === "function") {
176
+ try {
177
+ o.sm.sendAndRecord(session, { type: "error", text: message });
178
+ } catch (e) {
179
+ logReclaimFailure("Could not record the inline reclaim notice", session, labels, e);
180
+ }
181
+ }
182
+ return { labels: labels, persisted: persisted };
183
+ }
184
+
185
+ /**
186
+ * Daemon shutdown, called per session before its query is aborted. A session
187
+ * whose query is running and still tracks background agents is announced
188
+ * through the same helper as the reap and the shed; a session without one is
189
+ * left untouched. Synchronous, because the process is exiting.
190
+ */
191
+ function announceShutdownReclaim(session, sm) {
192
+ if (!session || !(session.queryInstance || session.worker)) return { labels: [], persisted: true };
193
+ return announceLiveAgentReclaim({
194
+ session: session,
195
+ sm: sm,
196
+ reason: RESTART_REASON,
197
+ source: "daemon-shutdown",
198
+ cause: RESTART_CAUSE,
199
+ deferNotice: true,
200
+ });
201
+ }
202
+
203
+ /** Counts one daemon shutdown's announcements, across every project. */
204
+ function createShutdownTally() {
205
+ return { sessions: 0, failed: 0 };
206
+ }
207
+
208
+ /** Fold one announceShutdownReclaim result into the tally. */
209
+ function countShutdownReclaim(tally, result) {
210
+ if (!tally || !result || result.labels.length === 0) return;
211
+ tally.sessions += 1;
212
+ if (!result.persisted) tally.failed += 1;
213
+ }
214
+
215
+ /** The one journal line per shutdown; an error line when any marker was lost. */
216
+ function logShutdownSummary(tally) {
217
+ var line = "[session-reclaim] Shutdown: " + tally.sessions + " session(s) with background agents recorded as resumable, "
218
+ + tally.failed + " could not be persisted";
219
+ if (tally.failed > 0) console.error(line);
220
+ else console.log(line);
221
+ }
222
+
223
+ function restartAgents(session) {
224
+ return session.pendingAutoResume && session.pendingAutoResumeReason === RESTART_REASON
225
+ ? sanitizeAgentLabels(session.pendingAutoResumeAgents) : null;
226
+ }
227
+
228
+ /**
229
+ * First startup after a shutdown that interrupted background agents: record
230
+ * the inline notice in each such session (it replays to every client that
231
+ * opens it) and keep the names in memory for the diagnostic that
232
+ * restartDiagnostics sends to each connecting client. The persisted names are
233
+ * dropped so a second restart does not repeat the notice.
234
+ */
235
+ function surfaceRestartReclaims(o) {
236
+ var sm = o.sm;
237
+ sm.sessions.forEach(function (session) {
238
+ var labels = restartAgents(session);
239
+ if (!labels) return;
240
+ session.pendingAutoResumeAgents = null;
241
+ session.restartNoticeAgents = labels;
242
+ try {
243
+ sm.sendAndRecord(session, { type: "error", text: reclaimMessage(RESTART_CAUSE, labels) });
244
+ if (typeof sm.saveSessionFile === "function") sm.saveSessionFile(session);
245
+ } catch (e) {
246
+ console.error("[session-reclaim] Could not record the restart notice:", e && e.message ? e.message : e);
247
+ }
248
+ });
249
+ }
250
+
251
+ /** Diagnostic messages for a client that connects while a restart notice is unread. */
252
+ function restartDiagnostics(sm, slug, canSee) {
253
+ var out = [];
254
+ // Agent names are session content: without a visibility check nobody gets them.
255
+ if (typeof canSee !== "function") return out;
256
+ sm.sessions.forEach(function (session) {
257
+ if (!session.restartNoticeAgents) return;
258
+ if (!canSee(session)) return;
259
+ out.push({
260
+ type: "diagnostic",
261
+ severity: "warning",
262
+ source: "daemon-restart",
263
+ message: (slug ? "[" + slug + "] " : "") + reclaimMessage(RESTART_CAUSE, session.restartNoticeAgents),
264
+ });
265
+ });
266
+ return out;
267
+ }
268
+
269
+ module.exports = {
270
+ RESTART_REASON: RESTART_REASON,
271
+ sanitizeAgentLabels: sanitizeAgentLabels,
272
+ announceShutdownReclaim: announceShutdownReclaim,
273
+ createShutdownTally: createShutdownTally,
274
+ countShutdownReclaim: countShutdownReclaim,
275
+ logShutdownSummary: logShutdownSummary,
276
+ surfaceRestartReclaims: surfaceRestartReclaims,
277
+ restartDiagnostics: restartDiagnostics,
278
+ noteTaskLabel: noteTaskLabel,
279
+ pruneTaskLabels: pruneTaskLabels,
280
+ liveAgentLabels: liveAgentLabels,
281
+ liveAgentTasks: liveAgentTasks,
282
+ ownerLabelOfTool: ownerLabelOfTool,
283
+ announceLiveAgentReclaim: announceLiveAgentReclaim,
284
+ };