@clagentic/console 1.9.0 → 1.10.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/LICENSE +117 -12
  2. package/LICENSES/MIT-legacy.txt +22 -0
  3. package/LICENSES/README.md +15 -0
  4. package/README.md +9 -3
  5. package/bin/cli.js +40 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/agent-dispatch-tool.js +20 -0
  8. package/lib/audit.js +3 -2
  9. package/lib/build-changes.js +79 -0
  10. package/lib/build-identity.js +192 -0
  11. package/lib/build-monitor.js +125 -0
  12. package/lib/build-sha.json +2 -2
  13. package/lib/build-update-check.js +138 -0
  14. package/lib/build-update-offer.js +141 -0
  15. package/lib/build-update-restart.js +142 -0
  16. package/lib/build-update-standing.js +184 -0
  17. package/lib/cli/daemon-launch.js +25 -22
  18. package/lib/cli/ipc-subcommands.js +6 -0
  19. package/lib/cli/session-subcommands.js +122 -0
  20. package/lib/cli-sessions.js +8 -1
  21. package/lib/codex-defaults.js +8 -2
  22. package/lib/config.js +32 -20
  23. package/lib/daemon-env-settings.js +84 -0
  24. package/lib/daemon-projects.js +57 -0
  25. package/lib/daemon.js +288 -205
  26. package/lib/drain.js +74 -17
  27. package/lib/env-compat.js +61 -0
  28. package/lib/extension-commands.js +45 -0
  29. package/lib/history-visibility.js +4 -0
  30. package/lib/idle-adapter-reaper.js +71 -0
  31. package/lib/link-trap.js +78 -0
  32. package/lib/mcp-local.js +8 -6
  33. package/lib/mcp-tool-input.js +116 -0
  34. package/lib/mcp-tool-schema.js +179 -0
  35. package/lib/memory-limits.js +61 -5
  36. package/lib/memory-setting-validate.js +65 -0
  37. package/lib/memory-shed.js +13 -32
  38. package/lib/new-work-gate.js +47 -0
  39. package/lib/os-users.js +5 -3
  40. package/lib/project-access.js +139 -0
  41. package/lib/project-connection.js +37 -22
  42. package/lib/project-external-trigger.js +166 -105
  43. package/lib/project-file-scope.js +172 -0
  44. package/lib/project-file-watch.js +86 -61
  45. package/lib/project-filesystem.js +144 -128
  46. package/lib/project-git.js +119 -0
  47. package/lib/project-http.js +44 -28
  48. package/lib/project-loop.js +17 -9
  49. package/lib/project-mcp.js +53 -72
  50. package/lib/project-message-gate.js +70 -0
  51. package/lib/project-notifications.js +31 -4
  52. package/lib/project-prompt-responses.js +217 -0
  53. package/lib/project-sessions.js +192 -355
  54. package/lib/project-user-message.js +27 -15
  55. package/lib/project.js +212 -147
  56. package/lib/projects-dir.js +90 -0
  57. package/lib/prompt-access.js +22 -0
  58. package/lib/prompt-kinds/answer-limits.js +15 -0
  59. package/lib/prompt-kinds/ask-user.js +58 -0
  60. package/lib/prompt-kinds/codecs.js +97 -0
  61. package/lib/prompt-kinds/elicitation.js +77 -0
  62. package/lib/prompt-kinds/extension.js +39 -0
  63. package/lib/prompt-kinds/index.js +68 -0
  64. package/lib/prompt-kinds/permission.js +114 -0
  65. package/lib/prompt-kinds/plan.js +79 -0
  66. package/lib/prompt-kinds/tool-call.js +38 -0
  67. package/lib/prompt-registry.js +680 -0
  68. package/lib/public/app.js +1 -1
  69. package/lib/public/css/diagnostics.css +80 -0
  70. package/lib/public/css/input.css +17 -3
  71. package/lib/public/css/menus.css +10 -0
  72. package/lib/public/css/messages.css +5 -0
  73. package/lib/public/css/rewind.css +22 -0
  74. package/lib/public/index.html +4 -12
  75. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  76. package/lib/public/modules/app-connection.js +7 -0
  77. package/lib/public/modules/app-cursors.js +7 -5
  78. package/lib/public/modules/app-messages.js +52 -47
  79. package/lib/public/modules/app-notifications.js +47 -71
  80. package/lib/public/modules/app-panels.js +61 -59
  81. package/lib/public/modules/app-projects.js +2 -1
  82. package/lib/public/modules/app-rendering.js +4 -10
  83. package/lib/public/modules/build-update-detail.js +54 -0
  84. package/lib/public/modules/diagnostics.js +170 -20
  85. package/lib/public/modules/filebrowser.js +18 -16
  86. package/lib/public/modules/history-visibility.js +4 -0
  87. package/lib/public/modules/mention.js +3 -2
  88. package/lib/public/modules/mode-options.js +38 -0
  89. package/lib/public/modules/project-settings.js +19 -8
  90. package/lib/public/modules/prompt-banner.js +78 -0
  91. package/lib/public/modules/prompt-card.js +201 -0
  92. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  93. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  94. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  95. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  96. package/lib/public/modules/prompt-kinds/index.js +18 -0
  97. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  98. package/lib/public/modules/prompt-kinds/package.json +3 -0
  99. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  100. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  101. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  102. package/lib/public/modules/prompt-state.js +142 -0
  103. package/lib/public/modules/prompts.js +134 -0
  104. package/lib/public/modules/rewind.js +4 -1
  105. package/lib/public/modules/server-settings.js +2 -4
  106. package/lib/public/modules/sidebar-mobile.js +19 -9
  107. package/lib/public/modules/sidebar-sessions.js +21 -14
  108. package/lib/public/modules/sticky-notes.js +3 -2
  109. package/lib/public/modules/team-panel.js +5 -4
  110. package/lib/public/modules/tools.js +81 -906
  111. package/lib/public/modules/vendor-picker.js +53 -0
  112. package/lib/public/modules/vendor-registry.js +142 -0
  113. package/lib/public/sw.js +3 -1
  114. package/lib/rc-migrate.js +44 -0
  115. package/lib/runtime-env-keys.js +109 -0
  116. package/lib/runtime-env.js +236 -0
  117. package/lib/sdk-bridge.js +348 -284
  118. package/lib/sdk-message-processor.js +117 -146
  119. package/lib/sdk-skill-discovery.js +65 -60
  120. package/lib/server-hub-sessions.js +13 -10
  121. package/lib/server-palette.js +28 -19
  122. package/lib/server.js +156 -115
  123. package/lib/service-install.js +96 -0
  124. package/lib/session-capabilities.js +76 -0
  125. package/lib/session-id.js +33 -0
  126. package/lib/session-input-ipc.js +32 -0
  127. package/lib/session-input.js +379 -0
  128. package/lib/session-reclaim.js +284 -0
  129. package/lib/session-resume.js +172 -0
  130. package/lib/sessions.js +61 -30
  131. package/lib/supervisor.js +39 -0
  132. package/lib/turn-initiator.js +108 -0
  133. package/lib/users-permissions.js +9 -6
  134. package/lib/users.js +9 -0
  135. package/lib/utils.js +4 -2
  136. package/lib/vendor-auth.js +22 -0
  137. package/lib/vendor-registry-message.js +66 -0
  138. package/lib/ws-origin.js +99 -0
  139. package/lib/ws-schema.js +36 -23
  140. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  141. package/lib/yoke/adapters/claude-vendor.js +34 -0
  142. package/lib/yoke/adapters/claude-worker.js +57 -87
  143. package/lib/yoke/adapters/claude.js +182 -88
  144. package/lib/yoke/adapters/codex-capabilities.js +40 -0
  145. package/lib/yoke/adapters/codex-vendor.js +46 -0
  146. package/lib/yoke/adapters/codex.js +462 -211
  147. package/lib/yoke/adapters/effort-control.js +34 -0
  148. package/lib/yoke/adapters/permission-relay.js +58 -0
  149. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  150. package/lib/yoke/auth-checks.js +91 -0
  151. package/lib/yoke/capabilities.js +49 -0
  152. package/lib/yoke/codex-app-server.js +30 -56
  153. package/lib/yoke/codex-binary.js +254 -0
  154. package/lib/yoke/codex-command.js +122 -0
  155. package/lib/yoke/codex-protocol.js +96 -0
  156. package/lib/yoke/codex-version.js +135 -0
  157. package/lib/yoke/env-ownership.js +40 -0
  158. package/lib/yoke/index.js +84 -174
  159. package/lib/yoke/install-probe.js +136 -0
  160. package/lib/yoke/instructions.js +7 -11
  161. package/lib/yoke/interface.js +206 -4
  162. package/lib/yoke/package.json +1 -1
  163. package/lib/yoke/provider-credentials.js +96 -0
  164. package/lib/yoke/registry.js +377 -0
  165. package/package.json +12 -9
  166. package/scripts/check-sdk-lock-drift.js +160 -0
  167. package/scripts/check-test-count.js +76 -1
  168. package/scripts/postinstall.js +218 -136
  169. package/scripts/prompt-harness-history.js +202 -0
  170. package/scripts/verify-installed-build.js +59 -17
  171. package/scripts/verify-installed.js +67 -0
  172. package/lib/sdk-permission-ownership.js +0 -136
@@ -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
+ };
@@ -0,0 +1,172 @@
1
+ // session-resume.js - bring a stored session back into a project's session
2
+ // manager on its own vendor and agent. One implementation for the browser's
3
+ // resume_session message and for input injected from outside (session-input.js).
4
+ //
5
+ // A failure is reported as a failure: every function here either answers
6
+ // positively (a session, or a verified absence) or rejects with an Error whose
7
+ // `retryable` says whether trying again can help. An unreadable store and a
8
+ // history that cannot be loaded are never read as "no such session" or as an
9
+ // empty history.
10
+
11
+ var fs = require("fs");
12
+ var utils = require("./utils");
13
+ var sessionIdGuard = require("./session-id");
14
+
15
+ var isSafeSessionId = sessionIdGuard.isSafeSessionId;
16
+
17
+ function messageOf(err) {
18
+ return err && err.message ? err.message : String(err);
19
+ }
20
+
21
+ function resumeError(message, retryable) {
22
+ var err = new Error(message);
23
+ err.retryable = retryable;
24
+ return err;
25
+ }
26
+
27
+ // An unsafe id is refused, never read as "no such session" and passed on.
28
+ function assertSafeSessionId(cliSessionId) {
29
+ if (!isSafeSessionId(cliSessionId)) {
30
+ throw resumeError("unsafe session id " + JSON.stringify(String(cliSessionId).slice(0, 64)) + " refused", false);
31
+ }
32
+ }
33
+
34
+ // A record is a JSON object; null, numbers, strings and arrays are not.
35
+ function isRecord(value) {
36
+ return value !== null && typeof value === "object" && !Array.isArray(value);
37
+ }
38
+
39
+ // Reads the console's own record of a session: its meta line and its history.
40
+ // Returns null only when there is no such file. An unsafe id, a file that is
41
+ // there but cannot be read, or one whose records are damaged, throws (see
42
+ // resumeError).
43
+ //
44
+ // Every history line must parse to a JSON object, wherever it is: skipping or
45
+ // accepting anything else would hand the vendor a history with a hole in it.
46
+ // The only thing tolerated besides records is the single newline that ends the
47
+ // file, which the console's writer always adds.
48
+ function readStoredSession(sessionsDir, cliSessionId) {
49
+ assertSafeSessionId(cliSessionId);
50
+ if (!sessionsDir) return null;
51
+ var file;
52
+ try { file = sessionIdGuard.sessionPathWithin(sessionsDir, cliSessionId, ".jsonl"); }
53
+ catch (e) { throw resumeError(messageOf(e), false); }
54
+ var raw;
55
+ try { raw = fs.readFileSync(file, "utf8"); }
56
+ catch (e) {
57
+ if (e && e.code === "ENOENT") return null;
58
+ throw resumeError("cannot read stored session " + cliSessionId + ": " + messageOf(e), true);
59
+ }
60
+ var lines = (raw.endsWith("\n") ? raw.slice(0, -1) : raw).split("\n");
61
+ var meta;
62
+ try { meta = JSON.parse(lines[0]); }
63
+ catch (e) { throw resumeError("stored session " + cliSessionId + " is damaged: its meta record is not valid JSON", false); }
64
+ if (!isRecord(meta) || meta.type !== "meta") {
65
+ throw resumeError("stored session " + cliSessionId + " is damaged: its first record is not a meta record", false);
66
+ }
67
+ var history = [];
68
+ for (var i = 1; i < lines.length; i++) {
69
+ var record;
70
+ try { record = JSON.parse(lines[i]); }
71
+ catch (e) {
72
+ throw resumeError("stored session " + cliSessionId + " is damaged: line " + (i + 1) + " is malformed", false);
73
+ }
74
+ if (!isRecord(record)) {
75
+ throw resumeError("stored session " + cliSessionId + " is damaged: line " + (i + 1) + " is not a JSON object", false);
76
+ }
77
+ history.push(record);
78
+ }
79
+ return { meta: meta, history: history };
80
+ }
81
+
82
+ // Whether the console's own store holds a session. Sessions the vendor holds
83
+ // but the console never recorded are not addressable by injected input.
84
+ // Rejects when the record is there but unreadable or damaged.
85
+ function sessionExistsInStore(sm, cliSessionId) {
86
+ return Promise.resolve().then(function () {
87
+ return readStoredSession(sm.sessionsDir, cliSessionId) !== null;
88
+ });
89
+ }
90
+
91
+ function titleFromHistory(history) {
92
+ for (var i = 0; i < history.length; i++) {
93
+ if (history[i].type === "user_message" && history[i].text) return history[i].text.substring(0, 50);
94
+ }
95
+ return "Resumed session";
96
+ }
97
+
98
+ function defaultReadHistory(cwd, cliSessionId) {
99
+ return require("./cli-sessions").readCliSessionHistory(cwd, cliSessionId);
100
+ }
101
+
102
+ // Resumes cliSessionId into deps.sm and resolves the session (null when the
103
+ // session manager declines). Rejects, with `retryable` set, when the stored
104
+ // record or the vendor's history cannot be loaded: a session is never resumed
105
+ // on a history that failed to load.
106
+ // Vendor, agent, owner, visibility and granted tools come from the stored
107
+ // meta record so the session continues as what it was, not as the project's
108
+ // default. Without a console record the vendor's own history is used.
109
+ //
110
+ // deps: { sm, adapter, cwd, readHistory? } readHistory(cwd, id) -> Promise<history[]>
111
+ // opts: { ws, activate } ws is the requesting browser connection, if any;
112
+ // activate:false keeps every connected client on the session it is viewing.
113
+ function resumeStoredSession(deps, cliSessionId, opts) {
114
+ var sm = deps.sm;
115
+ var ws = (opts && opts.ws) || undefined;
116
+ var activate = !(opts && opts.activate === false);
117
+
118
+ return Promise.resolve().then(function () {
119
+ // First, before the id reaches the store, the adapter or the vendor's files.
120
+ assertSafeSessionId(cliSessionId);
121
+ var stored = readStoredSession(sm.sessionsDir, cliSessionId);
122
+ var meta = stored && stored.meta;
123
+ var resumeOpts = { activate: activate };
124
+ if (meta) {
125
+ if (meta.vendor) resumeOpts.vendor = meta.vendor;
126
+ if (meta.agentName) resumeOpts.agentName = meta.agentName;
127
+ if (meta.ownerId) resumeOpts.ownerId = meta.ownerId;
128
+ if (meta.sessionVisibility) resumeOpts.sessionVisibility = meta.sessionVisibility;
129
+ // Sanitized so a crafted meta record cannot auto-approve a tool.
130
+ if (meta.allowedTools) resumeOpts.allowedTools = utils.sanitizeAllowedTools(meta.allowedTools);
131
+ }
132
+
133
+ function finish(extra) {
134
+ var session = sm.resumeSession(cliSessionId, Object.assign(resumeOpts, extra), ws);
135
+ if (session && typeof sm.retrimHistory === "function") sm.retrimHistory(session);
136
+ return session || null;
137
+ }
138
+
139
+ if (stored) {
140
+ return finish({
141
+ history: stored.history,
142
+ title: meta.title || titleFromHistory(stored.history),
143
+ });
144
+ }
145
+
146
+ var readHistory = deps.readHistory || defaultReadHistory;
147
+ // The summary only names the resumed session; a lookup that fails leaves
148
+ // the title taken from the history instead and does not affect delivery.
149
+ var titlePromise = Promise.resolve()
150
+ .then(function () { return deps.adapter.getSessionInfo(cliSessionId, { dir: deps.cwd }); })
151
+ .then(function (info) { return (info && info.summary) ? info.summary.substring(0, 100) : null; })
152
+ .catch(function () { return null; });
153
+
154
+ var historyPromise = Promise.resolve()
155
+ .then(function () { return readHistory(deps.cwd, cliSessionId); })
156
+ .catch(function (err) {
157
+ throw resumeError("could not load the history of session " + cliSessionId + ": " + messageOf(err), true);
158
+ });
159
+
160
+ return Promise.all([historyPromise, titlePromise]).then(function (results) {
161
+ var history = results[0];
162
+ return finish({ history: history, title: results[1] || titleFromHistory(history) });
163
+ });
164
+ });
165
+ }
166
+
167
+ module.exports = {
168
+ isSafeSessionId: isSafeSessionId,
169
+ readStoredSession: readStoredSession,
170
+ sessionExistsInStore: sessionExistsInStore,
171
+ resumeStoredSession: resumeStoredSession,
172
+ };
package/lib/sessions.js CHANGED
@@ -2,9 +2,12 @@ var fs = require("fs");
2
2
  var path = require("path");
3
3
  var config = require("./config");
4
4
  var utils = require("./utils");
5
+ var sessionIdGuard = require("./session-id");
5
6
  var users = require("./users");
6
7
  var { CODEX_DEFAULTS } = require("./codex-defaults");
7
8
  var { isVisibleHistoryEvent } = require("./history-visibility");
9
+ var { createPromptRegistry } = require("./prompt-registry");
10
+ var sessionReclaim = require("./session-reclaim");
8
11
 
9
12
  // lr-2ea2a7: hard cap on how many history entries a session may hold in the
10
13
  // heap array, regardless of isProcessing state. On-disk JSONL remains the
@@ -94,7 +97,20 @@ function createSessionManager(opts) {
94
97
  var slashCommands = null; // shared across sessions (deprecated, use slashCommandsByVendor)
95
98
  var slashCommandsByVendor = {}; // vendor -> array of slash commands
96
99
  var skillNames = null; // Claude-only skills to filter from slash menu
97
- var permissionRequestIndex = {}; // requestId -> sessionLocalId (O(1) lookup)
100
+ // requestId -> sessionLocalId (O(1) lookup). Keyed by ids that arrive from
101
+ // clients, so it has no prototype to answer for "constructor" or "__proto__".
102
+ var permissionRequestIndex = Object.create(null);
103
+ // Sole writer of every session's operator-prompt state; see
104
+ // lib/prompt-registry.js. Built before any session exists because
105
+ // construction itself may create and switch to one.
106
+ var prompts = createPromptRegistry({
107
+ index: permissionRequestIndex,
108
+ getSession: function (localId) { return sessions.get(localId) || null; },
109
+ sendAndRecord: function (session, obj) { return doSendAndRecord(session, obj); },
110
+ saveSessionFile: function (session) { return saveSessionFile(session); },
111
+ getNotificationsModule: opts.getNotificationsModule,
112
+ onProcessingChanged: opts.onProcessingChanged,
113
+ });
98
114
  var capabilitiesByVendor = null; // set by sdk-bridge after adapter init
99
115
  var defaultVendor = null; // set by sdk-bridge
100
116
  var codexApproval = CODEX_DEFAULTS.approval;
@@ -108,7 +124,7 @@ function createSessionManager(opts) {
108
124
  fs.mkdirSync(sessionsDir, { recursive: true });
109
125
 
110
126
  function sessionFilePath(cliSessionId) {
111
- return path.join(sessionsDir, cliSessionId + ".jsonl");
127
+ return sessionIdGuard.sessionPathWithin(sessionsDir, cliSessionId, ".jsonl");
112
128
  }
113
129
 
114
130
  function buildMetaLine(session) {
@@ -149,6 +165,10 @@ function createSessionManager(opts) {
149
165
  if (session.pendingAutoResume) {
150
166
  metaObj.pendingAutoResume = true;
151
167
  if (session.pendingAutoResumeReason) metaObj.pendingAutoResumeReason = session.pendingAutoResumeReason;
168
+ // Names of the agents a daemon shutdown interrupted, for the notice at
169
+ // the next startup (lib/session-reclaim.js).
170
+ var resumeAgents = sessionReclaim.sanitizeAgentLabels(session.pendingAutoResumeAgents);
171
+ if (resumeAgents) metaObj.pendingAutoResumeAgents = resumeAgents;
152
172
  }
153
173
  // lr-62157d: durable auto-title state. Without this, titleAutoGenerated
154
174
  // and titleManuallySet lived in memory only — every daemon restart reset
@@ -717,8 +737,8 @@ function createSessionManager(opts) {
717
737
  cliSessionId: m.cliSessionId,
718
738
  blocks: {},
719
739
  sentToolResults: {},
720
- pendingPermissions: {},
721
- pendingAskUser: {},
740
+ pendingPermissions: Object.create(null),
741
+ pendingAskUser: Object.create(null),
722
742
  // Hydrate previously-granted "allow for session" tool decisions from
723
743
  // durable state (lr-8b2e); default to {} only when none was saved so
724
744
  // grants that were never given remain empty, not re-prompted.
@@ -758,6 +778,7 @@ function createSessionManager(opts) {
758
778
  if (m.pendingAutoResume) {
759
779
  session.pendingAutoResume = true;
760
780
  session.pendingAutoResumeReason = m.pendingAutoResumeReason || null;
781
+ session.pendingAutoResumeAgents = sessionReclaim.sanitizeAgentLabels(m.pendingAutoResumeAgents);
761
782
  }
762
783
  // lr-62157d: restore auto-title state across a daemon restart — see
763
784
  // buildMetaLine's write side for why this must persist. Without this,
@@ -863,9 +884,9 @@ function createSessionManager(opts) {
863
884
  cliSessionId: null,
864
885
  blocks: {},
865
886
  sentToolResults: {},
866
- pendingPermissions: {},
867
- pendingAskUser: {},
868
- allowedTools: {},
887
+ pendingPermissions: Object.create(null),
888
+ pendingAskUser: Object.create(null),
889
+ allowedTools: Object.create(null),
869
890
  isProcessing: false,
870
891
  title: "",
871
892
  titleAutoGenerated: false,
@@ -898,9 +919,9 @@ function createSessionManager(opts) {
898
919
  cliSessionId: null,
899
920
  blocks: {},
900
921
  sentToolResults: {},
901
- pendingPermissions: {},
902
- pendingAskUser: {},
903
- allowedTools: {},
922
+ pendingPermissions: Object.create(null),
923
+ pendingAskUser: Object.create(null),
924
+ allowedTools: Object.create(null),
904
925
  isProcessing: false,
905
926
  title: "",
906
927
  titleAutoGenerated: false,
@@ -1031,10 +1052,12 @@ function createSessionManager(opts) {
1031
1052
 
1032
1053
  _send({ type: "history_meta", total: total, from: baseIndex + heapFrom });
1033
1054
 
1055
+ var annotatePrompt = prompts.replayAnnotator(session, session.history, heapFrom);
1034
1056
  for (var i = heapFrom; i < heapLen; i++) {
1035
1057
  var _item = session.history[i];
1036
1058
  // Skip internal bookkeeping entries not meant for the UI
1037
1059
  if (_item && _item.type === "digest_checkpoint") continue;
1060
+ _item = annotatePrompt(_item);
1038
1061
  _send(transform ? transform(_item) : _item);
1039
1062
  }
1040
1063
 
@@ -1129,19 +1152,8 @@ function createSessionManager(opts) {
1129
1152
  _send({ type: "status", status: "processing" });
1130
1153
  }
1131
1154
 
1132
- // Re-send any pending permission requests
1133
- var pendingIds = Object.keys(session.pendingPermissions);
1134
- for (var i = 0; i < pendingIds.length; i++) {
1135
- var p = session.pendingPermissions[pendingIds[i]];
1136
- _send({
1137
- type: "permission_request_pending",
1138
- requestId: p.requestId,
1139
- toolName: p.toolName,
1140
- toolInput: p.toolInput,
1141
- toolUseId: p.toolUseId,
1142
- decisionReason: p.decisionReason,
1143
- });
1144
- }
1155
+ // Re-present every prompt still awaiting the operator.
1156
+ prompts.pendingMessages(session).forEach(_send);
1145
1157
 
1146
1158
  // Re-send active mention indicator so returning clients restore the mate avatar state
1147
1159
  if (session._mentionInProgress && session._mentionActiveMateId) {
@@ -1181,6 +1193,9 @@ function createSessionManager(opts) {
1181
1193
  _lruRemove(localId);
1182
1194
 
1183
1195
  cleanupMentionSessions(session);
1196
+ // Settled before the abort below so no abort listener records an event
1197
+ // into a history that is about to be deleted.
1198
+ prompts.cancelSession(session, "session_deleted", { record: false });
1184
1199
 
1185
1200
  if (session.abortController) {
1186
1201
  try { session.abortController.abort(); } catch(e) {}
@@ -1228,6 +1243,7 @@ function createSessionManager(opts) {
1228
1243
  _lruRemove(localId);
1229
1244
 
1230
1245
  cleanupMentionSessions(session);
1246
+ prompts.cancelSession(session, "session_deleted", { record: false });
1231
1247
  if (session.abortController) {
1232
1248
  try { session.abortController.abort(); } catch(e) {}
1233
1249
  }
@@ -1357,6 +1373,9 @@ function createSessionManager(opts) {
1357
1373
  }
1358
1374
 
1359
1375
  function resumeSession(cliSessionId, opts, targetWs) {
1376
+ // The id names a file under sessionsDir; declining here keeps an unvalidated
1377
+ // id from reaching saveSessionFile for any caller.
1378
+ if (!sessionIdGuard.isSafeSessionId(cliSessionId)) return null;
1360
1379
  // If a session with this cliSessionId already exists, just switch to it
1361
1380
  var existing = null;
1362
1381
  sessions.forEach(function (s) {
@@ -1378,8 +1397,8 @@ function createSessionManager(opts) {
1378
1397
  cliSessionId: cliSessionId,
1379
1398
  blocks: {},
1380
1399
  sentToolResults: {},
1381
- pendingPermissions: {},
1382
- pendingAskUser: {},
1400
+ pendingPermissions: Object.create(null),
1401
+ pendingAskUser: Object.create(null),
1383
1402
  // Hydrate previously-granted "allow for session" tool decisions from
1384
1403
  // durable state (lr-8b2e); default to {} only when none was saved.
1385
1404
  // Sanitized (lr-8b2e hardening) so a malformed/injected persisted
@@ -1400,10 +1419,14 @@ function createSessionManager(opts) {
1400
1419
  favoriteOrder: null,
1401
1420
  };
1402
1421
  if (opts && opts.vendor) session.vendor = opts.vendor;
1422
+ if (opts && opts.agentName) session.agentName = opts.agentName;
1423
+ if (opts && opts.sessionVisibility) session.sessionVisibility = opts.sessionVisibility;
1403
1424
  if (opts && opts.ownerId) session.ownerId = opts.ownerId;
1404
1425
  sessions.set(localId, session);
1405
1426
  saveSessionFile(session);
1406
- switchSession(localId, targetWs);
1427
+ // activate:false is for a resume nobody asked to look at (injected input):
1428
+ // switching would move every connected client off the session it is on.
1429
+ if (!(opts && opts.activate === false)) switchSession(localId, targetWs);
1407
1430
  return session;
1408
1431
  }
1409
1432
 
@@ -1438,11 +1461,14 @@ function createSessionManager(opts) {
1438
1461
  return _parseSessionFileLines(session).lines;
1439
1462
  }
1440
1463
 
1441
- function searchSessions(query) {
1464
+ // canSee (optional): predicate over a session; a session it rejects is
1465
+ // skipped before its title or any of its content is examined.
1466
+ function searchSessions(query, canSee) {
1442
1467
  if (!query) return [];
1443
1468
  var q = query.toLowerCase();
1444
1469
  var results = [];
1445
1470
  sessions.forEach(function (session) {
1471
+ if (canSee && !canSee(session)) return;
1446
1472
  var titleMatch = (session.title || "New Session").toLowerCase().indexOf(q) !== -1;
1447
1473
  var contentMatch = false;
1448
1474
  if (titleMatch) {
@@ -1806,13 +1832,18 @@ function createSessionManager(opts) {
1806
1832
  // `sm.effectiveSessionModel(session)` without importing this module
1807
1833
  // separately.
1808
1834
  effectiveSessionModel: function (session) { return effectiveSessionModel(session, _instance); },
1809
- // Remove the process-level exit listener registered above.
1810
- // Must be called when the project owning this session manager is destroyed
1811
- // so listeners do not accumulate across project open/close cycles (lr-daca).
1835
+ // Called when the project owning this session manager is torn down. No
1836
+ // prompt resolver outlives it, so every pending prompt ends here and its
1837
+ // outcome is flushed to disk; then the process-level exit listener
1838
+ // registered above is removed so listeners do not accumulate across
1839
+ // project open/close cycles.
1812
1840
  destroy: function() {
1841
+ prompts.shutdown();
1842
+ _onProcessExit();
1813
1843
  process.removeListener("exit", _onProcessExit);
1814
1844
  },
1815
1845
  };
1846
+ _instance.prompts = prompts;
1816
1847
  return _instance;
1817
1848
  }
1818
1849