@clagentic/console 1.9.0 → 1.10.0-beta.1

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 (146) 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 +8 -2
  5. package/bin/cli.js +30 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/audit.js +3 -2
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-check.js +138 -0
  10. package/lib/cli/daemon-launch.js +17 -17
  11. package/lib/config.js +32 -20
  12. package/lib/daemon-env-settings.js +84 -0
  13. package/lib/daemon-projects.js +38 -0
  14. package/lib/daemon.js +202 -158
  15. package/lib/drain.js +74 -17
  16. package/lib/env-compat.js +61 -0
  17. package/lib/extension-commands.js +45 -0
  18. package/lib/history-visibility.js +4 -0
  19. package/lib/idle-adapter-reaper.js +71 -0
  20. package/lib/link-trap.js +78 -0
  21. package/lib/lore-attestation.js +73 -0
  22. package/lib/mcp-local.js +8 -6
  23. package/lib/mcp-tool-input.js +116 -0
  24. package/lib/mcp-tool-schema.js +179 -0
  25. package/lib/memory-limits.js +61 -5
  26. package/lib/memory-setting-validate.js +65 -0
  27. package/lib/new-work-gate.js +47 -0
  28. package/lib/os-users.js +5 -3
  29. package/lib/project-access.js +139 -0
  30. package/lib/project-connection.js +23 -22
  31. package/lib/project-external-trigger.js +103 -10
  32. package/lib/project-file-scope.js +172 -0
  33. package/lib/project-file-watch.js +86 -61
  34. package/lib/project-filesystem.js +144 -128
  35. package/lib/project-git.js +119 -0
  36. package/lib/project-http.js +44 -28
  37. package/lib/project-loop.js +12 -5
  38. package/lib/project-mcp.js +53 -72
  39. package/lib/project-message-gate.js +70 -0
  40. package/lib/project-notifications.js +31 -4
  41. package/lib/project-prompt-responses.js +216 -0
  42. package/lib/project-sessions.js +164 -302
  43. package/lib/project-user-message.js +36 -11
  44. package/lib/project.js +189 -142
  45. package/lib/projects-dir.js +90 -0
  46. package/lib/prompt-access.js +22 -0
  47. package/lib/prompt-kinds/answer-limits.js +15 -0
  48. package/lib/prompt-kinds/ask-user.js +58 -0
  49. package/lib/prompt-kinds/codecs.js +97 -0
  50. package/lib/prompt-kinds/elicitation.js +77 -0
  51. package/lib/prompt-kinds/extension.js +39 -0
  52. package/lib/prompt-kinds/index.js +68 -0
  53. package/lib/prompt-kinds/permission.js +114 -0
  54. package/lib/prompt-kinds/plan.js +79 -0
  55. package/lib/prompt-kinds/tool-call.js +38 -0
  56. package/lib/prompt-registry.js +673 -0
  57. package/lib/public/app.js +1 -1
  58. package/lib/public/css/diagnostics.css +50 -0
  59. package/lib/public/css/input.css +17 -3
  60. package/lib/public/css/menus.css +10 -0
  61. package/lib/public/css/messages.css +5 -0
  62. package/lib/public/css/rewind.css +22 -0
  63. package/lib/public/index.html +4 -12
  64. package/lib/public/modules/app-connection.js +7 -0
  65. package/lib/public/modules/app-cursors.js +7 -5
  66. package/lib/public/modules/app-messages.js +45 -45
  67. package/lib/public/modules/app-notifications.js +47 -71
  68. package/lib/public/modules/app-panels.js +61 -58
  69. package/lib/public/modules/app-projects.js +2 -1
  70. package/lib/public/modules/app-rendering.js +4 -10
  71. package/lib/public/modules/diagnostics.js +60 -16
  72. package/lib/public/modules/filebrowser.js +18 -16
  73. package/lib/public/modules/history-visibility.js +4 -0
  74. package/lib/public/modules/mention.js +3 -2
  75. package/lib/public/modules/mode-options.js +38 -0
  76. package/lib/public/modules/project-settings.js +19 -8
  77. package/lib/public/modules/prompt-banner.js +78 -0
  78. package/lib/public/modules/prompt-card.js +201 -0
  79. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  80. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  81. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  82. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  83. package/lib/public/modules/prompt-kinds/index.js +18 -0
  84. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  85. package/lib/public/modules/prompt-kinds/package.json +3 -0
  86. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  87. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  88. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  89. package/lib/public/modules/prompt-state.js +142 -0
  90. package/lib/public/modules/prompts.js +134 -0
  91. package/lib/public/modules/rewind.js +4 -1
  92. package/lib/public/modules/server-settings.js +2 -4
  93. package/lib/public/modules/sidebar-mobile.js +19 -9
  94. package/lib/public/modules/sidebar-sessions.js +21 -14
  95. package/lib/public/modules/sticky-notes.js +3 -2
  96. package/lib/public/modules/team-panel.js +5 -4
  97. package/lib/public/modules/tools.js +67 -904
  98. package/lib/public/modules/vendor-picker.js +53 -0
  99. package/lib/public/modules/vendor-registry.js +133 -0
  100. package/lib/public/sw.js +3 -1
  101. package/lib/rc-migrate.js +44 -0
  102. package/lib/runtime-env-keys.js +109 -0
  103. package/lib/runtime-env.js +236 -0
  104. package/lib/sdk-bridge.js +290 -273
  105. package/lib/sdk-message-processor.js +125 -145
  106. package/lib/server-hub-sessions.js +13 -10
  107. package/lib/server-palette.js +28 -19
  108. package/lib/server.js +141 -113
  109. package/lib/service-install.js +96 -0
  110. package/lib/session-capabilities.js +76 -0
  111. package/lib/sessions.js +45 -28
  112. package/lib/users-permissions.js +9 -6
  113. package/lib/users.js +9 -0
  114. package/lib/utils.js +4 -2
  115. package/lib/vendor-auth.js +22 -0
  116. package/lib/vendor-registry-message.js +65 -0
  117. package/lib/ws-origin.js +99 -0
  118. package/lib/ws-schema.js +33 -22
  119. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  120. package/lib/yoke/adapters/claude-vendor.js +35 -0
  121. package/lib/yoke/adapters/claude-worker.js +55 -87
  122. package/lib/yoke/adapters/claude.js +156 -62
  123. package/lib/yoke/adapters/codex-capabilities.js +37 -0
  124. package/lib/yoke/adapters/codex-vendor.js +46 -0
  125. package/lib/yoke/adapters/codex.js +347 -156
  126. package/lib/yoke/adapters/effort-control.js +34 -0
  127. package/lib/yoke/adapters/permission-relay.js +58 -0
  128. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  129. package/lib/yoke/auth-checks.js +104 -0
  130. package/lib/yoke/capabilities.js +49 -0
  131. package/lib/yoke/codex-app-server.js +23 -5
  132. package/lib/yoke/env-ownership.js +40 -0
  133. package/lib/yoke/index.js +67 -173
  134. package/lib/yoke/install-probe.js +121 -0
  135. package/lib/yoke/instructions.js +7 -11
  136. package/lib/yoke/interface.js +199 -3
  137. package/lib/yoke/package.json +1 -1
  138. package/lib/yoke/provider-credentials.js +96 -0
  139. package/lib/yoke/registry.js +340 -0
  140. package/package.json +12 -8
  141. package/scripts/check-sdk-lock-drift.js +160 -0
  142. package/scripts/check-test-count.js +76 -1
  143. package/scripts/postinstall.js +218 -136
  144. package/scripts/prompt-harness-history.js +202 -0
  145. package/scripts/verify-installed.js +67 -0
  146. package/lib/sdk-permission-ownership.js +0 -136
@@ -0,0 +1,673 @@
1
+ "use strict";
2
+
3
+ // Single owner of every operator-prompt lifecycle: tool permissions, plan
4
+ // approval, AskUserQuestion, MCP elicitation and browser-extension commands.
5
+ // A kind (lib/prompt-kinds/) only describes its payload, how a response is
6
+ // parsed and what the vendor's callback receives; everything else is here.
7
+ //
8
+ // A prompt is pending until exactly one transition settles it: an answer
9
+ // (resolved), or the end of the scope that owns it (cancelled, with a
10
+ // reason). Every path that ends a prompt - the WS and HTTP response
11
+ // handlers, the turn boundary, query end, the abort signal, worker or Codex
12
+ // side expiry, a timeout, rewind, context clear, session deletion, daemon
13
+ // shutdown - calls a transition here, so these hold by construction:
14
+ //
15
+ // - settling calls the resolver exactly once, dismisses the prompt's
16
+ // notification, and records a terminal event every client can see
17
+ // (live, or stamped on replay);
18
+ // - a pending prompt is reachable by requestId from any client;
19
+ // - ownership decides scope: a top-level prompt ends with its turn; a
20
+ // prompt owned by a sub-agent (its tool-use id belongs to a Task) is kept
21
+ // across the parent's turn and query boundaries for as long as the
22
+ // sub-agent is tracked, so the operator can still answer it, and ends
23
+ // only on an answer, its own abort, or the session ending. Its abort is
24
+ // the vendor's word that the callback is gone (the adapters abort every
25
+ // callback a closed query still had waiting); the registry never
26
+ // decides on its own that a sub-agent is dead.
27
+ //
28
+ // State lives on the objects that already carried it, so readers keep
29
+ // working: one pending map per store on the session (pendingPermissions for
30
+ // tool and plan approvals, pendingAskUser, pendingElicitations; requestId ->
31
+ // record), session.subagentToolOwners (tool-use id -> owning Task id),
32
+ // session.activeTaskToolIds (Task id -> true while running, "ending" once it
33
+ // reported completion while still owning a pending prompt), and the session
34
+ // manager's requestId -> session index. Only this module writes them.
35
+ //
36
+ // A requestId, Task id or tool-use id may name anything a client sends, so
37
+ // these maps are read only through ownValue() and written through putOwn():
38
+ // a name every object inherits (constructor, __proto__, ...) is no entry.
39
+ //
40
+ // Those lookups and the answer codecs are the browser's own modules
41
+ // (lib/prompt-kinds/codecs.js), loaded once, starting here; ready() settles
42
+ // when they are in, and the daemon awaits it before it accepts a connection.
43
+
44
+ var crypto = require("crypto");
45
+ var utils = require("./utils");
46
+ var promptKinds = require("./prompt-kinds");
47
+ var codecs = require("./prompt-kinds/codecs");
48
+ var { ownValue, putOwn, hasOwnKey } = codecs;
49
+
50
+ var KINDS = promptKinds.KINDS;
51
+ var STORES = promptKinds.sessionStores();
52
+ var codecsLoaded = codecs.load();
53
+
54
+ // An AbortSignal relayed from a worker or the Codex app-server carries reason
55
+ // "expired" when the other side gave up waiting; a plain abort does not.
56
+ function cancelReasonForAbort(signal) {
57
+ return signal && signal.reason === "expired" ? "expired" : "aborted";
58
+ }
59
+
60
+ var RESOLVED_FIELDS = ["decision", "answers", "skipped", "action"];
61
+
62
+ function deepFreeze(value) {
63
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
64
+ Object.freeze(value);
65
+ Object.keys(value).forEach(function (k) { deepFreeze(value[k]); });
66
+ }
67
+ return value;
68
+ }
69
+
70
+ function pick(obj, keys) {
71
+ var out = {};
72
+ keys.forEach(function (k) { if (obj[k] !== undefined) out[k] = obj[k]; });
73
+ return out;
74
+ }
75
+
76
+ // The terminal state a recorded history event carries, including the event
77
+ // types recorded before prompts had one shape.
78
+ function terminalOf(e) {
79
+ if (!e || typeof e.type !== "string") return null;
80
+ switch (e.type) {
81
+ case "prompt_resolved":
82
+ case "permission_resolved":
83
+ case "elicitation_resolved":
84
+ return e.requestId ? { id: e.requestId, state: Object.assign({ state: "resolved" }, pick(e, RESOLVED_FIELDS)) } : null;
85
+ case "prompt_cancel":
86
+ case "permission_cancel":
87
+ return e.requestId ? { id: e.requestId, state: { state: "cancelled", reason: e.reason || null } } : null;
88
+ case "ask_user_answered":
89
+ if (!e.toolId) return null;
90
+ if (e.answers && Object.keys(e.answers).length) return { id: e.toolId, state: { state: "resolved", answers: e.answers } };
91
+ // A recorded skip is an answer, not an ending nobody chose.
92
+ if (e.skipped === true) return { id: e.toolId, state: { state: "resolved", skipped: true } };
93
+ return { id: e.toolId, state: { state: "cancelled", reason: null } };
94
+ default:
95
+ return null;
96
+ }
97
+ }
98
+
99
+ // The prompt a recorded history event opens, if any. An AskUserQuestion card
100
+ // is drawn from its tool call, whose id is the prompt's id.
101
+ function openedBy(item) {
102
+ if (!item || typeof item.type !== "string") return null;
103
+ if (item.type === "prompt_request" || item.type === "permission_request" || item.type === "elicitation_request") {
104
+ return item.requestId || null;
105
+ }
106
+ if (item.type === "tool_executing" && item.name === "AskUserQuestion") return item.id || null;
107
+ return null;
108
+ }
109
+
110
+ /**
111
+ * @param {object} deps
112
+ * @param {object} deps.index - requestId -> session localId, shared with the
113
+ * session manager so a response can find its session from the id alone.
114
+ * @param {function(*): ?object} deps.getSession - localId -> session.
115
+ * @param {function(object, object)} deps.sendAndRecord - record + broadcast
116
+ * an event to the session's clients.
117
+ * @param {function(object)} deps.saveSessionFile - durable session meta write.
118
+ * @param {function(): ?object} [deps.getNotificationsModule]
119
+ * @param {function()} [deps.onProcessingChanged] - cross-project badge refresh.
120
+ */
121
+ function createPromptRegistry(deps) {
122
+ var index = deps.index;
123
+ var getSession = deps.getSession;
124
+ var sendAndRecord = deps.sendAndRecord;
125
+ var saveSessionFile = deps.saveSessionFile;
126
+ var getNotificationsModule = deps.getNotificationsModule || function () { return null; };
127
+ var onProcessingChanged = deps.onProcessingChanged || function () {};
128
+
129
+ // Project-scope prompts (no session): requestId -> record.
130
+ var projectPrompts = Object.create(null);
131
+ // record -> function that detaches its abort listener and timer.
132
+ var detachers = new WeakMap();
133
+ // Runs after every answer, whichever path delivered it; see onResolved().
134
+ var resolutionEffects = null;
135
+
136
+ function sessionMap(session, store) {
137
+ if (!session[store]) session[store] = Object.create(null);
138
+ return session[store];
139
+ }
140
+
141
+ function toolOwners(session) {
142
+ if (!session.subagentToolOwners) session.subagentToolOwners = Object.create(null);
143
+ return session.subagentToolOwners;
144
+ }
145
+
146
+ function trackedTasks(session) {
147
+ if (!session.activeTaskToolIds) session.activeTaskToolIds = Object.create(null);
148
+ return session.activeTaskToolIds;
149
+ }
150
+
151
+ function entryOf(store, record) {
152
+ return { store: store, record: record, kind: promptKinds.kindOfRecord(record, store) };
153
+ }
154
+
155
+ /** Every pending session prompt, across all stores. */
156
+ function entries(session) {
157
+ var out = [];
158
+ STORES.forEach(function (store) {
159
+ var map = session[store];
160
+ if (!map) return;
161
+ Object.keys(map).forEach(function (id) {
162
+ if (map[id]) out.push(Object.assign({ id: id }, entryOf(store, map[id])));
163
+ });
164
+ });
165
+ return out;
166
+ }
167
+
168
+ function findInSession(session, requestId) {
169
+ for (var i = 0; i < STORES.length; i++) {
170
+ var record = ownValue(session[STORES[i]], requestId);
171
+ if (record) return entryOf(STORES[i], record);
172
+ }
173
+ return null;
174
+ }
175
+
176
+ function dismissNotification(requestId) {
177
+ var nm = getNotificationsModule();
178
+ if (nm && typeof nm.dismissByRequestId === "function") nm.dismissByRequestId(requestId);
179
+ }
180
+
181
+ function ownerTaskOf(session, record) {
182
+ if (!record || !record.toolUseId) return null;
183
+ return ownValue(toolOwners(session), record.toolUseId) || null;
184
+ }
185
+
186
+ // A prompt owned by a tracked sub-agent outlives the parent's boundaries.
187
+ function ownedByTrackedTask(session, record) {
188
+ var taskId = ownerTaskOf(session, record);
189
+ return !!(taskId && ownValue(trackedTasks(session), taskId));
190
+ }
191
+
192
+ function taskOwnsPending(session, taskId) {
193
+ return entries(session).some(function (e) { return ownerTaskOf(session, e.record) === taskId; });
194
+ }
195
+
196
+ // Ownership records outlive their Task only while a pending prompt still
197
+ // points at them; otherwise they are dead weight.
198
+ function pruneToolOwners(session, taskId) {
199
+ var owners = toolOwners(session);
200
+ var referenced = Object.create(null);
201
+ entries(session).forEach(function (e) { if (e.record.toolUseId) referenced[e.record.toolUseId] = true; });
202
+ for (var toolUseId in owners) {
203
+ if ((taskId === undefined || owners[toolUseId] === taskId) && !referenced[toolUseId]) delete owners[toolUseId];
204
+ }
205
+ }
206
+
207
+ function finishTask(session, taskId) {
208
+ delete trackedTasks(session)[taskId];
209
+ pruneToolOwners(session, taskId);
210
+ }
211
+
212
+ // Forget every Task that no longer owns a pending prompt. Only the owning
213
+ // query's end and a new query's start call this, and a closed query takes
214
+ // its CLI process, and every sub-agent in it, down: a Task tracked without
215
+ // a prompt then has nothing left to ask. A replacement query's Tasks are
216
+ // never touched (endQuery gates on ownsSession).
217
+ function pruneTasks(session) {
218
+ var tasks = trackedTasks(session);
219
+ Object.keys(tasks).forEach(function (taskId) {
220
+ if (!taskOwnsPending(session, taskId)) delete tasks[taskId];
221
+ });
222
+ pruneToolOwners(session);
223
+ }
224
+
225
+ function settle(session, requestId, entry, value, event) {
226
+ var map = session ? session[entry.store] : projectPrompts;
227
+ if (!map || ownValue(map, requestId) !== entry.record) return false;
228
+ delete map[requestId];
229
+ if (session) delete index[requestId];
230
+ var detach = detachers.get(entry.record);
231
+ if (detach) detach();
232
+ if (entry.kind.journal) {
233
+ dismissNotification(requestId);
234
+ if (event) sendAndRecord(session, event);
235
+ onProcessingChanged();
236
+ }
237
+ entry.record.resolve(value);
238
+ if (session) {
239
+ var taskId = ownerTaskOf(session, entry.record);
240
+ if (taskId && ownValue(trackedTasks(session), taskId) === "ending" && !taskOwnsPending(session, taskId)) {
241
+ finishTask(session, taskId);
242
+ }
243
+ }
244
+ return true;
245
+ }
246
+
247
+ function cancelEntry(session, requestId, entry, reason, opts) {
248
+ var event = (entry.kind.journal && !(opts && opts.record === false))
249
+ ? { type: "prompt_cancel", requestId: requestId, kind: entry.kind.name, reason: reason }
250
+ : null;
251
+ return settle(session, requestId, entry, entry.kind.cancelled(reason), event);
252
+ }
253
+
254
+ function cancelWhere(session, reason, predicate, opts) {
255
+ entries(session).forEach(function (e) {
256
+ if (predicate(e.record)) cancelEntry(session, e.id, e, reason, opts);
257
+ });
258
+ }
259
+
260
+ // The request index is shared by every session of the project, so a
261
+ // tool-use id is reused as a request id only while no session holds a prompt
262
+ // under it; otherwise the index entry that routes the other session's
263
+ // answers would be overwritten.
264
+ function newRequestId(session, kind, toolUseId) {
265
+ if (kind.idFromToolUse && toolUseId && !findInSession(session, toolUseId) && !hasOwnKey(index, toolUseId)) return toolUseId;
266
+ return crypto.randomUUID();
267
+ }
268
+
269
+ /**
270
+ * Open a prompt. Returns its id and the promise the vendor's callback
271
+ * awaits; a journalled prompt is recorded for clients before this returns.
272
+ *
273
+ * @param {?object} session - null for a project-scope kind.
274
+ * @param {string} kindName - a key of lib/prompt-kinds.
275
+ * @param {object} req - the kind's request payload.
276
+ * @param {object} [opts]
277
+ * @param {string} [opts.toolUseId] - the tool call this prompt gates;
278
+ * decides sub-agent ownership.
279
+ * @param {AbortSignal} [opts.signal] - ends the prompt (aborted, or
280
+ * expired when the signal's reason is "expired").
281
+ * @param {number} [opts.timeoutMs] - ends the prompt as expired.
282
+ * @param {object} [opts.notification] - permission_request notification
283
+ * payload (title, body, slug, ...); dismissed when the prompt settles.
284
+ * @returns {{requestId: string, answer: Promise<*>, pending: boolean}}
285
+ * pending is false when its signal was already aborted: no prompt was
286
+ * opened or announced, and answer carries the kind's cancelled value.
287
+ */
288
+ function open(session, kindName, req, opts) {
289
+ opts = opts || {};
290
+ var kind = ownValue(KINDS, kindName);
291
+ if (!kind) throw new Error("unknown prompt kind: " + kindName);
292
+ var scoped = kind.scope === "session";
293
+ var requestId = scoped ? newRequestId(session, kind, opts.toolUseId) : crypto.randomUUID();
294
+ var signal = opts.signal;
295
+ // A callback whose signal is already aborted has no one waiting on its
296
+ // answer: it is answered as cancelled and never becomes a prompt, so no
297
+ // client is shown, or records, a request that was never answerable.
298
+ if (signal && signal.aborted) {
299
+ return { requestId: requestId, answer: Promise.resolve(kind.cancelled(cancelReasonForAbort(signal))), pending: false };
300
+ }
301
+ var resolveAnswer;
302
+ var answer = new Promise(function (resolve) { resolveAnswer = resolve; });
303
+ var record = Object.assign({
304
+ requestId: requestId,
305
+ kind: kind.name,
306
+ toolUseId: opts.toolUseId || undefined,
307
+ createdAt: Date.now(),
308
+ resolve: resolveAnswer,
309
+ }, kind.fields(req || {}));
310
+ var entry = { store: kind.store, record: record, kind: kind };
311
+ var owner = scoped ? session : null;
312
+
313
+ if (scoped) {
314
+ record.query = session.queryInstance || null;
315
+ putOwn(sessionMap(session, kind.store), requestId, record);
316
+ putOwn(index, requestId, session.localId);
317
+ } else {
318
+ projectPrompts[requestId] = record;
319
+ }
320
+ if (kind.journal) {
321
+ sendAndRecord(session, Object.assign({
322
+ type: "prompt_request",
323
+ requestId: requestId,
324
+ kind: kind.name,
325
+ toolUseId: record.toolUseId,
326
+ }, kind.requestFields(record)));
327
+ onProcessingChanged();
328
+ }
329
+
330
+ var cleanups = [];
331
+ if (signal && typeof signal.addEventListener === "function") {
332
+ var onAbort = function () { cancelEntry(owner, requestId, entry, cancelReasonForAbort(signal)); };
333
+ signal.addEventListener("abort", onAbort, { once: true });
334
+ if (typeof signal.removeEventListener === "function") {
335
+ cleanups.push(function () { signal.removeEventListener("abort", onAbort); });
336
+ }
337
+ }
338
+ var timeoutMs = opts.timeoutMs != null ? opts.timeoutMs : kind.defaultTimeoutMs;
339
+ if (timeoutMs) {
340
+ var timer = setTimeout(function () { cancelEntry(owner, requestId, entry, "expired"); }, timeoutMs);
341
+ cleanups.push(function () { clearTimeout(timer); });
342
+ }
343
+ if (cleanups.length) {
344
+ detachers.set(record, function () { cleanups.forEach(function (fn) { fn(); }); });
345
+ }
346
+
347
+ if (kind.journal && opts.notification) {
348
+ var nm = getNotificationsModule();
349
+ if (nm && typeof nm.notify === "function") {
350
+ var kindFields = typeof kind.notificationFields === "function" ? kind.notificationFields(record) : {};
351
+ nm.notify("permission_request", Object.assign({}, opts.notification, kindFields, { requestId: requestId, kind: kind.name }));
352
+ }
353
+ }
354
+ return { requestId: requestId, answer: answer, pending: true };
355
+ }
356
+
357
+ // The pending entry for requestId (its live record and kind adapter), or
358
+ // null. Internal: the record carries the resolver. requestId is whatever
359
+ // the answering client sent: only a string the registry itself stored
360
+ // names a prompt.
361
+ function find(requestId, fallbackSession) {
362
+ if (typeof requestId !== "string" || !requestId) return null;
363
+ var projectRecord = ownValue(projectPrompts, requestId);
364
+ if (projectRecord) return Object.assign({ session: null }, entryOf(null, projectRecord));
365
+ var localId = ownValue(index, requestId);
366
+ var session = (localId != null && getSession) ? getSession(localId) : null;
367
+ var entry = session ? findInSession(session, requestId) : null;
368
+ if (!entry && fallbackSession) {
369
+ session = fallbackSession;
370
+ entry = findInSession(session, requestId);
371
+ }
372
+ return entry ? Object.assign({ session: session }, entry) : null;
373
+ }
374
+
375
+ // What callers outside the registry may see of a prompt: a frozen copy of
376
+ // its request, never the record or its resolver, so nothing can settle or
377
+ // alter a prompt except through a transition here.
378
+ function publicView(requestId, entry) {
379
+ return Object.freeze({
380
+ requestId: requestId,
381
+ kind: entry.kind.name,
382
+ toolUseId: entry.record.toolUseId,
383
+ createdAt: entry.record.createdAt,
384
+ request: deepFreeze(structuredClone(entry.kind.requestFields(entry.record))),
385
+ });
386
+ }
387
+
388
+ /**
389
+ * The pending prompt for requestId, or null when it is not pending.
390
+ * @returns {?{session: ?object, prompt: object}} prompt is a frozen view.
391
+ */
392
+ function lookup(requestId, fallbackSession) {
393
+ var found = find(requestId, fallbackSession);
394
+ return found ? Object.freeze({ session: found.session, prompt: publicView(requestId, found) }) : null;
395
+ }
396
+
397
+ /**
398
+ * Apply an answer. Returns {status: "resolved", session, prompt, kind,
399
+ * response}; {status: "stale"} when the prompt is not pending (or is not
400
+ * one of opts.kinds), and a stale answer still retires any notification
401
+ * that offered it; or {status: "invalid", reason, pending} when the kind
402
+ * refuses the answer as it stands (parse returned {invalid}), in which case
403
+ * nothing settles and pending is the prompt_pending message that re-offers
404
+ * the prompt to the responder. The resolution effects (onResolved) have
405
+ * run by the time a resolved answer returns, whichever path called it.
406
+ *
407
+ * @param {string} requestId
408
+ * @param {object} msg - the kind's response fields (decision, answers,
409
+ * action, result, ...); parsed and validated by the kind.
410
+ * @param {object} [opts]
411
+ * @param {object} [opts.session] - fallback when the index has no entry.
412
+ * @param {string[]} [opts.kinds] - only answer prompts of these kinds.
413
+ * @param {string} [opts.denyMessage] - override for a plain deny.
414
+ * @param {?object} [opts.responder] - the connection that answered, if
415
+ * any; handed to the resolution effects.
416
+ */
417
+ function respond(requestId, msg, opts) {
418
+ opts = opts || {};
419
+ var found = find(requestId, opts.session);
420
+ if (!found) {
421
+ dismissNotification(requestId);
422
+ return { status: "stale" };
423
+ }
424
+ if (opts.kinds && opts.kinds.indexOf(found.kind.name) === -1) return { status: "stale" };
425
+ var kind = found.kind;
426
+ var response = kind.parse(msg || {}, found.record);
427
+ if (response.invalid) {
428
+ return { status: "invalid", reason: response.invalid, pending: kind.journal ? pendingMessage(requestId, found) : null };
429
+ }
430
+ if (kind.grantsSession(response)) grant(found.session, found.record.toolName, found.record.toolInput);
431
+ var event = kind.journal
432
+ ? Object.assign({ type: "prompt_resolved", requestId: requestId, kind: kind.name }, kind.resolvedFields(response, found.record))
433
+ : null;
434
+ var prompt = publicView(requestId, found);
435
+ settle(found.session, requestId, found, kind.outcome(found.record, response, opts), event);
436
+ var outcome = { status: "resolved", session: found.session, prompt: prompt, kind: kind.name, response: response };
437
+ if (resolutionEffects) resolutionEffects(outcome, opts.responder || null);
438
+ return outcome;
439
+ }
440
+
441
+ /**
442
+ * Install the session side effects of an answer (a plan decision's
443
+ * permission mode, fresh session or feedback message). They run inside
444
+ * respond(), so every path that answers a prompt - the WS card, the push
445
+ * notification's HTTP route, an older client's alias message - applies
446
+ * them; no path can settle a prompt and skip them. One installer per
447
+ * registry: a later call replaces the earlier one.
448
+ *
449
+ * @param {function(object, ?object)} fn - (outcome, responder)
450
+ */
451
+ function onResolved(fn) {
452
+ resolutionEffects = typeof fn === "function" ? fn : null;
453
+ }
454
+
455
+ /** Turn boundary: prompts the turn owns end; tracked sub-agents keep theirs. */
456
+ function endTurn(session) {
457
+ cancelWhere(session, "turn_ended", function (record) {
458
+ return !ownedByTrackedTask(session, record);
459
+ });
460
+ }
461
+
462
+ /**
463
+ * Query end. A prompt opened by this query ends unless a tracked
464
+ * sub-agent owns it: the operator must still be able to answer a
465
+ * backgrounded sub-agent after its parent's query closes. ownsSession is
466
+ * true when no newer query has taken the session over; only then are
467
+ * prompts opened outside any query also ended, and Tasks that own nothing
468
+ * forgotten.
469
+ */
470
+ function endQuery(session, query, ownsSession) {
471
+ cancelWhere(session, "query_ended", function (record) {
472
+ var ours = record.query ? record.query === query : !!ownsSession;
473
+ return ours && !ownedByTrackedTask(session, record);
474
+ });
475
+ if (ownsSession) pruneTasks(session);
476
+ }
477
+
478
+ /** A new query starts: Tasks of earlier queries that own nothing are gone. */
479
+ function beginQuery(session) {
480
+ pruneTasks(session);
481
+ }
482
+
483
+ /** End every prompt of a session (rewind, context clear, deletion). */
484
+ function cancelSession(session, reason, opts) {
485
+ cancelWhere(session, reason, function () { return true; }, opts);
486
+ session.activeTaskToolIds = Object.create(null);
487
+ session.subagentToolOwners = Object.create(null);
488
+ }
489
+
490
+ /**
491
+ * The daemon is going away: no resolver survives it, so every pending
492
+ * prompt ends now, recorded, instead of being found unanswerable later.
493
+ */
494
+ function shutdown() {
495
+ var localIds = new Set();
496
+ Object.keys(index).forEach(function (id) { localIds.add(index[id]); });
497
+ localIds.forEach(function (localId) {
498
+ var session = getSession ? getSession(localId) : null;
499
+ if (session) cancelWhere(session, "shutdown", function () { return true; });
500
+ });
501
+ Object.keys(projectPrompts).forEach(function (id) {
502
+ var record = projectPrompts[id];
503
+ if (record) cancelEntry(null, id, entryOf(null, record), "shutdown");
504
+ });
505
+ }
506
+
507
+ function noteSubagentTool(session, toolUseId, taskId) {
508
+ if (toolUseId && taskId) putOwn(toolOwners(session), toolUseId, taskId);
509
+ }
510
+
511
+ function taskStarted(session, taskId) {
512
+ if (taskId) putOwn(trackedTasks(session), taskId, true);
513
+ }
514
+
515
+ /** Whether a Task is tracked (running, or ending with a pending prompt). */
516
+ function isTaskTracked(session, taskId) {
517
+ return !!(taskId && ownValue(session.activeTaskToolIds, taskId));
518
+ }
519
+
520
+ // A Task's completion can arrive while its sub-agent's own prompt is still
521
+ // awaiting the operator; the prompt keeps the Task in scope until it
522
+ // settles.
523
+ function taskEnded(session, taskId) {
524
+ if (!taskId) return;
525
+ var tasks = trackedTasks(session);
526
+ if (ownValue(tasks, taskId) && taskOwnsPending(session, taskId)) {
527
+ tasks[taskId] = "ending";
528
+ pruneToolOwners(session, taskId);
529
+ return;
530
+ }
531
+ finishTask(session, taskId);
532
+ }
533
+
534
+ /** Ids of every tracked Task. */
535
+ function trackedTaskIds(session) {
536
+ var out = Object.create(null);
537
+ Object.keys(trackedTasks(session)).forEach(function (taskId) { putOwn(out, taskId, true); });
538
+ return out;
539
+ }
540
+
541
+ function isGranted(session, toolName, input) {
542
+ return ownValue(session.allowedTools, utils.permissionGrantKey(toolName, input)) === true;
543
+ }
544
+
545
+ // Flushed immediately so the grant survives a daemon restart or a resume
546
+ // that rebuilds the session from disk.
547
+ function grant(session, toolName, input) {
548
+ if (!session.allowedTools) session.allowedTools = Object.create(null);
549
+ putOwn(session.allowedTools, utils.permissionGrantKey(toolName, input), true);
550
+ saveSessionFile(session);
551
+ }
552
+
553
+ // The wire message re-presenting one pending prompt.
554
+ function pendingMessage(requestId, entry) {
555
+ return Object.assign({
556
+ type: "prompt_pending",
557
+ requestId: requestId,
558
+ kind: entry.kind.name,
559
+ toolUseId: entry.record.toolUseId,
560
+ }, entry.kind.requestFields(entry.record));
561
+ }
562
+
563
+ /** Wire messages re-presenting every pending prompt of a session. */
564
+ function pendingMessages(session) {
565
+ return entries(session).filter(function (e) { return e.kind.journal; }).map(function (e) {
566
+ return pendingMessage(e.id, e);
567
+ });
568
+ }
569
+
570
+ /** Prompts of a session awaiting the operator. */
571
+ function pendingCount(session) {
572
+ return entries(session).filter(function (e) { return e.kind.journal; }).length;
573
+ }
574
+
575
+ /**
576
+ * Returns a mapper for replayed history items that stamps every item
577
+ * opening a prompt with its authoritative promptState, so a client renders
578
+ * it correctly regardless of which page carries the request and which its
579
+ * outcome. Stored history is never mutated.
580
+ *
581
+ * history[from..] is scanned for terminal events: an outcome always
582
+ * follows its request, so any request at or after `from` finds its own.
583
+ * A prompt that is neither pending nor closed in history (its process died
584
+ * before recording an outcome) is reported cancelled/stale.
585
+ */
586
+ function replayAnnotator(session, history, from) {
587
+ var start = Math.max(0, from || 0);
588
+ var closed = Object.create(null);
589
+ for (var i = start; i < history.length; i++) {
590
+ var t = terminalOf(history[i]);
591
+ if (t && !closed[t.id]) closed[t.id] = t.state;
592
+ }
593
+ // An AskUserQuestion card is recorded at its tool call, a moment before
594
+ // the vendor opens its prompt; until its turn has ended, an unopened one
595
+ // may still open and is left unstamped rather than called stale.
596
+ var askBeforeTurnEnd = new WeakSet();
597
+ var turnEnded = false;
598
+ for (var j = history.length - 1; j >= start; j--) {
599
+ var e = history[j];
600
+ if (!e) continue;
601
+ if (e.type === "result" || e.type === "done") turnEnded = true;
602
+ else if (turnEnded && e.type === "tool_executing" && e.name === "AskUserQuestion") askBeforeTurnEnd.add(e);
603
+ }
604
+ return function (item) {
605
+ var id = openedBy(item);
606
+ if (!id) return item;
607
+ var state = findInSession(session, id) ? { state: "pending" } : closed[id];
608
+ if (!state) {
609
+ var mayStillOpen = item.type === "tool_executing" && !askBeforeTurnEnd.has(item);
610
+ if (mayStillOpen) return item;
611
+ state = { state: "cancelled", reason: "stale" };
612
+ }
613
+ return Object.assign({}, item, { promptState: state });
614
+ };
615
+ }
616
+
617
+ return {
618
+ open: open,
619
+ lookup: lookup,
620
+ respond: respond,
621
+ onResolved: onResolved,
622
+ endTurn: endTurn,
623
+ endQuery: endQuery,
624
+ beginQuery: beginQuery,
625
+ cancelSession: cancelSession,
626
+ shutdown: shutdown,
627
+ noteSubagentTool: noteSubagentTool,
628
+ taskStarted: taskStarted,
629
+ taskEnded: taskEnded,
630
+ isTaskTracked: isTaskTracked,
631
+ taskOwnsPending: taskOwnsPending,
632
+ trackedTaskIds: trackedTaskIds,
633
+ isGranted: isGranted,
634
+ grant: grant,
635
+ pendingMessages: pendingMessages,
636
+ pendingCount: pendingCount,
637
+ replayAnnotator: replayAnnotator,
638
+ };
639
+ }
640
+
641
+ /**
642
+ * The registry attached to a session manager. A full session manager is
643
+ * built with one wired to the project's notification and badge hooks; a
644
+ * lighter manager (a test double) gets one over its own transport on first
645
+ * use.
646
+ */
647
+ function promptsFor(sm) {
648
+ if (!sm.prompts) {
649
+ if (!sm.permissionRequestIndex) sm.permissionRequestIndex = Object.create(null);
650
+ sm.prompts = createPromptRegistry({
651
+ index: sm.permissionRequestIndex,
652
+ getSession: function (localId) { return sm.sessions ? sm.sessions.get(localId) : null; },
653
+ sendAndRecord: function (session, obj) { return sm.sendAndRecord(session, obj); },
654
+ saveSessionFile: function (session) { return sm.saveSessionFile(session); },
655
+ });
656
+ }
657
+ return sm.prompts;
658
+ }
659
+
660
+ /**
661
+ * Settles once the codecs every prompt is parsed and keyed by are loaded;
662
+ * rejects, loudly, when they cannot be. Await it before accepting prompts.
663
+ * @returns {Promise<void>}
664
+ */
665
+ function ready() {
666
+ return codecsLoaded.then(function () {});
667
+ }
668
+
669
+ module.exports = {
670
+ createPromptRegistry: createPromptRegistry,
671
+ promptsFor: promptsFor,
672
+ ready: ready,
673
+ };
package/lib/public/app.js CHANGED
@@ -26,7 +26,7 @@ import { initTerminal, openTerminal, closeTerminal, resetTerminals, handleTermLi
26
26
  import { initContextSources, updateTerminalList, updateBrowserTabList, handleContextSourcesState, getActiveSources, hasActiveSources } from './modules/context-sources.js';
27
27
  import { initStickyNotes, handleNotesList, handleNoteCreated, handleNoteUpdated, handleNoteDeleted, openArchive, closeArchive, isArchiveOpen, hideNotes, showNotes, isNotesVisible, createNote } from './modules/sticky-notes.js';
28
28
  import { initTheme, getThemeColor, getComputedVar, onThemeChange, getCurrentTheme, getChatLayout } from './modules/theme.js';
29
- import { initTools, resetToolState, saveToolState, restoreToolState, renderAskUserQuestion, markAskUserAnswered, renderPermissionRequest, markPermissionResolved, markPermissionCancelled, renderElicitationRequest, markElicitationResolved, renderPlanBanner, renderPlanCard, handleTodoWrite, handleTaskCreate, handleTaskUpdate, startThinking, appendThinking, stopThinking, resetThinkingGroup, createToolItem, updateToolExecuting, updateToolResult, markAllToolsDone, addTurnMeta, resetTurnMetaCost, enableMainInput, getTools, getPlanContent, setPlanContent, isPlanFilePath, getTodoTools, updateSubagentActivity, addSubagentToolEntry, markSubagentDone, updateSubagentProgress, initSubagentStop, closeToolGroup, removeToolFromGroup } from './modules/tools.js';
29
+ import { initTools, resetToolState, saveToolState, restoreToolState, renderPlanBanner, renderPlanCard, handleTodoWrite, handleTaskCreate, handleTaskUpdate, startThinking, appendThinking, stopThinking, resetThinkingGroup, createToolItem, updateToolExecuting, updateToolResult, markAllToolsDone, addTurnMeta, resetTurnMetaCost, enableMainInput, getTools, getPlanContent, setPlanContent, isPlanFilePath, getTodoTools, updateSubagentActivity, addSubagentToolEntry, markSubagentDone, updateSubagentProgress, initSubagentStop, closeToolGroup, removeToolFromGroup } from './modules/tools.js';
30
30
  import { initServerSettings, updateSettingsStats, updateSettingsModels, updateDaemonConfig, handleSetPinResult, handleKeepAwakeChanged, handleAutoContinueChanged, handleRestartResult, handleShutdownResult, handleSharedEnv, handleSharedEnvSaved, handleGlobalClaudeMdRead, handleGlobalClaudeMdWrite, isSettingsOpen, closeSettings, updateSsLiteVisibility, initSsLiteToggle } from './modules/server-settings.js';
31
31
  import { initProjectSettings, handleInstructionsRead, handleInstructionsWrite, handleProjectEnv, handleProjectEnvSaved, isProjectSettingsOpen, closeProjectSettings, handleProjectSharedEnv, handleProjectSharedEnvSaved, handleProjectOwnerChanged, updateLiteVisibility, initLiteButtons, handleLiteProjectStatus, handleLiteEnrollResult, handleLiteUnenrollResult } from './modules/project-settings.js';
32
32
  import { initSkills, handleSkillInstalled, handleSkillUninstalled } from './modules/skills.js';