@clagentic/console 1.12.0-beta.1 → 1.12.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 (82) hide show
  1. package/README.md +1 -0
  2. package/bin/cli.js +2 -1
  3. package/lib/build-changes.js +8 -2
  4. package/lib/build-sha.json +2 -2
  5. package/lib/build-update-offer.js +31 -7
  6. package/lib/claude-settings-env.js +142 -0
  7. package/lib/cli/duration.js +27 -0
  8. package/lib/cli/schedule-input-subcommands.js +1 -22
  9. package/lib/cli/session-subcommands.js +38 -7
  10. package/lib/daemon.js +6 -0
  11. package/lib/notification-prefs.js +2 -0
  12. package/lib/notify/core.js +175 -0
  13. package/lib/notify/index.js +31 -0
  14. package/lib/notify/live-prompts.js +36 -0
  15. package/lib/notify/payload.js +63 -0
  16. package/lib/notify/target.js +5 -0
  17. package/lib/notify/type-registry.js +64 -0
  18. package/lib/notify/types.js +20 -0
  19. package/lib/open-sockets.js +27 -0
  20. package/lib/outbound-access.js +74 -0
  21. package/lib/outbound-entry.js +109 -0
  22. package/lib/outbound-ledger.js +306 -0
  23. package/lib/outbound-query.js +153 -0
  24. package/lib/pending-prompts.js +31 -16
  25. package/lib/project-connection.js +40 -1
  26. package/lib/project-filesystem.js +20 -5
  27. package/lib/project-http.js +9 -1
  28. package/lib/project-loop.js +22 -7
  29. package/lib/project-notifications.js +54 -32
  30. package/lib/project-prompt-responses.js +1 -1
  31. package/lib/project-sessions.js +2 -1
  32. package/lib/project.js +15 -1
  33. package/lib/prompt-registry.js +74 -24
  34. package/lib/prompt-reminders.js +38 -33
  35. package/lib/prompt-source.js +43 -8
  36. package/lib/public/app.js +1 -0
  37. package/lib/public/css/diagnostics.css +28 -0
  38. package/lib/public/css/home-hub.css +12 -0
  39. package/lib/public/css/icon-strip.css +9 -0
  40. package/lib/public/css/mobile-nav.css +11 -0
  41. package/lib/public/css/sidebar.css +7 -0
  42. package/lib/public/index.html +3 -0
  43. package/lib/public/modules/activity-state.js +20 -4
  44. package/lib/public/modules/app-connection.js +22 -5
  45. package/lib/public/modules/app-notifications.js +47 -48
  46. package/lib/public/modules/app-projects.js +3 -1
  47. package/lib/public/modules/app-rendering.js +10 -0
  48. package/lib/public/modules/build-update-sessions.js +81 -0
  49. package/lib/public/modules/diagnostics.js +9 -2
  50. package/lib/public/modules/env-shadow-notice.js +34 -0
  51. package/lib/public/modules/notify-client.js +153 -0
  52. package/lib/public/modules/project-settings.js +5 -0
  53. package/lib/public/modules/prompt-state.js +3 -3
  54. package/lib/public/modules/prompts.js +1 -1
  55. package/lib/public/modules/server-settings.js +3 -0
  56. package/lib/public/modules/terminal-links.js +175 -0
  57. package/lib/public/modules/terminal.js +19 -103
  58. package/lib/public/notify-sw-logic.js +300 -0
  59. package/lib/public/notify-target.js +97 -0
  60. package/lib/public/sw.js +15 -68
  61. package/lib/push.js +63 -19
  62. package/lib/runtime-env.js +1 -0
  63. package/lib/sdk-bridge.js +62 -30
  64. package/lib/sdk-message-processor.js +78 -37
  65. package/lib/server.js +34 -2
  66. package/lib/session-directory.js +6 -4
  67. package/lib/session-input-ipc.js +11 -1
  68. package/lib/session-input.js +89 -14
  69. package/lib/session-liveness.js +53 -0
  70. package/lib/session-reclaim.js +37 -2
  71. package/lib/sessions.js +31 -4
  72. package/lib/usage-store.js +29 -7
  73. package/lib/vendor-auth.js +33 -2
  74. package/lib/ws-schema.js +6 -1
  75. package/lib/yoke/adapters/claude-vendor.js +11 -1
  76. package/lib/yoke/adapters/claude.js +7 -0
  77. package/lib/yoke/auth-checks.js +17 -2
  78. package/lib/yoke/index.js +21 -3
  79. package/lib/yoke/provider-credentials.js +24 -0
  80. package/lib/yoke/registry.js +8 -1
  81. package/package.json +2 -2
  82. package/scripts/check-test-count.js +14 -0
@@ -205,7 +205,15 @@ function attachHTTP(ctx) {
205
205
  if (req.method === "POST" && urlPath === "/api/push-subscribe") {
206
206
  parseJsonBody(req).then(function (body) {
207
207
  var sub = body.subscription || body;
208
- if (pushModule) pushModule.addSubscription(sub, body.replaceEndpoint);
208
+ // The user is resolved as the top-level route resolves it (the login
209
+ // cookie, set on req by lib/server.js); a subscription stored without
210
+ // one reaches no user-targeted push.
211
+ var pushUser = req._clagenticUser || null;
212
+ if (pushModule && pushModule.addSubscription(sub, body.replaceEndpoint, pushUser ? pushUser.id : null) === false && sub && sub.endpoint) {
213
+ res.writeHead(401, { "Content-Type": "application/json" });
214
+ res.end('{"error":"sign in to enable push notifications"}');
215
+ return;
216
+ }
209
217
  res.writeHead(200, { "Content-Type": "application/json" });
210
218
  res.end('{"ok":true}');
211
219
  }).catch(function () {
@@ -3,6 +3,7 @@ var path = require("path");
3
3
  var crypto = require("crypto");
4
4
  var { execFileSync } = require("child_process");
5
5
  var { createLoopRegistry } = require("./scheduler");
6
+ var sessionLiveness = require("./session-liveness");
6
7
  var store = require("./store");
7
8
  var usersModule = require("./users");
8
9
  var { pushForSession } = require("./push-audience");
@@ -102,8 +103,21 @@ function attachLoop(ctx) {
102
103
  // runNextIteration(), and on stop/finish so nothing leaks into a
103
104
  // future run.
104
105
  pendingUserMessages: [],
106
+ // The browser tab that sent loop_start. In memory only, never persisted:
107
+ // a cron, schedule, rerun or resume has no starter. Runner sessions switch
108
+ // only this tab, and only while it is still connected.
109
+ starterWs: null,
105
110
  };
106
111
 
112
+ // createSession arguments for a session the runner creates (iteration or
113
+ // judge). A connected starter tab is the one tab that follows the loop;
114
+ // with no starter, or one that has gone, nothing switches.
115
+ function runnerSessionArgs() {
116
+ var starter = loopState.starterWs;
117
+ if (starter && starter.readyState === 1) return [undefined, starter];
118
+ return [{ activate: false }];
119
+ }
120
+
107
121
  function loopDir() {
108
122
  var id = loopState.loopFilesId || loopState.loopId;
109
123
  if (!id) return null;
@@ -460,6 +474,7 @@ function attachLoop(ctx) {
460
474
  loopState.settings = loopConfig.settings || null;
461
475
  loopState.startedAt = Date.now();
462
476
  loopState.pendingUserMessages = [];
477
+ loopState.starterWs = loopOpts.starterWs || null;
463
478
  saveLoopState();
464
479
 
465
480
  stopClaudeDirWatch();
@@ -490,7 +505,7 @@ function attachLoop(ctx) {
490
505
  return;
491
506
  }
492
507
 
493
- var session = sm.createSession();
508
+ var session = sm.createSession.apply(sm, runnerSessionArgs());
494
509
  var loopSource = loopRegistry.getById(loopState.loopId);
495
510
  var loopName = (loopState.wizardData && loopState.wizardData.name) || (loopSource && loopSource.name) || "";
496
511
  var loopSourceTag = (loopSource && loopSource.source) || null;
@@ -671,7 +686,7 @@ function attachLoop(ctx) {
671
686
  "- PASS: [brief explanation]\n" +
672
687
  "- FAIL: [brief explanation of what is still missing]";
673
688
 
674
- var judgeSession = sm.createSession();
689
+ var judgeSession = sm.createSession.apply(sm, runnerSessionArgs());
675
690
  var judgeSource = loopRegistry.getById(loopState.loopId);
676
691
  var judgeName = (loopState.wizardData && loopState.wizardData.name) || (judgeSource && judgeSource.name) || "";
677
692
  var judgeSourceTag = (judgeSource && judgeSource.source) || null;
@@ -823,6 +838,7 @@ function attachLoop(ctx) {
823
838
  loopState.stopping = false;
824
839
  loopState.currentSessionId = null;
825
840
  loopState.judgeSessionId = null;
841
+ loopState.starterWs = null;
826
842
  // Drop any messages queued but never delivered to an iteration — the loop
827
843
  // is done, so there is no future boundary to deliver them at (lr-e31b).
828
844
  var _hadUndelivered = loopState.pendingUserMessages && loopState.pendingUserMessages.length > 0;
@@ -989,7 +1005,7 @@ function attachLoop(ctx) {
989
1005
  fs.writeFileSync(ljPath, JSON.stringify(lj, null, 2), "utf8");
990
1006
  }
991
1007
  }
992
- startLoop({ maxIterations: msg.maxIterations });
1008
+ startLoop({ maxIterations: msg.maxIterations, starterWs: ws });
993
1009
  return true;
994
1010
  }
995
1011
 
@@ -1155,12 +1171,11 @@ function attachLoop(ctx) {
1155
1171
  "## Task\n" + (wData.task || "") +
1156
1172
  "\n\n## Loop Directory\n" + lDir;
1157
1173
 
1158
- var judgeCraftSession = sm.createSession();
1174
+ var judgeCraftSession = sm.createSession(undefined, ws);
1159
1175
  judgeCraftSession.title = (isRalphCraft ? "Ralph" : "Task") + (craftName ? " " + craftName : "") + " Crafting";
1160
1176
  judgeCraftSession.ralphCraftingMode = true;
1161
1177
  judgeCraftSession.loop = { active: true, iteration: 0, role: "crafting", loopId: newLoopId, name: craftName, source: recordSource, startedAt: loopState.startedAt };
1162
1178
  sm.saveSessionFile(judgeCraftSession);
1163
- sm.switchSession(judgeCraftSession.localId, null, hydrateImageRefs);
1164
1179
  loopState.craftingSessionId = judgeCraftSession.localId;
1165
1180
 
1166
1181
  loopRegistry.updateRecord(newLoopId, { craftingSessionId: judgeCraftSession.localId });
@@ -1231,12 +1246,11 @@ function attachLoop(ctx) {
1231
1246
  }
1232
1247
 
1233
1248
  // Create a new session for crafting
1234
- var craftingSession = sm.createSession();
1249
+ var craftingSession = sm.createSession(undefined, ws);
1235
1250
  craftingSession.title = (isRalphCraft ? "Ralph" : "Task") + (craftName ? " " + craftName : "") + " Crafting";
1236
1251
  craftingSession.ralphCraftingMode = true;
1237
1252
  craftingSession.loop = { active: true, iteration: 0, role: "crafting", loopId: newLoopId, name: craftName, source: recordSource, startedAt: loopState.startedAt };
1238
1253
  sm.saveSessionFile(craftingSession);
1239
- sm.switchSession(craftingSession.localId, null, hydrateImageRefs);
1240
1254
  loopState.craftingSessionId = craftingSession.localId;
1241
1255
 
1242
1256
  // Store crafting session ID in the registry record
@@ -1463,6 +1477,7 @@ function attachLoop(ctx) {
1463
1477
  // needs it to distinguish "my activity" from "another user's
1464
1478
  // activity" the same way session_list already does.
1465
1479
  ownerId: s.ownerId || null,
1480
+ waiting: sessionLiveness.activityOf(s) === sessionLiveness.ACTIVITY.WAITING,
1466
1481
  };
1467
1482
  });
1468
1483
  sendTo(ws, { type: "hub_recent_sessions", sessions: mapped });
@@ -34,6 +34,8 @@ var formatters = {
34
34
  loginCommand: data.loginCommand || "",
35
35
  linuxUser: data.linuxUser || null,
36
36
  canAutoLogin: !!data.canAutoLogin,
37
+ // Stays until acted on; the banner reads this flag, not a type list.
38
+ persistent: true,
37
39
  },
38
40
  };
39
41
  },
@@ -92,7 +94,6 @@ var formatters = {
92
94
  title: data.title || "Prompts waiting",
93
95
  body: data.body || "",
94
96
  meta: {
95
- reminderKey: data.reminderKey || null,
96
97
  requestIds: data.requestIds || [],
97
98
  count: data.count || 0,
98
99
  ageMs: data.ageMs || 0,
@@ -203,7 +204,15 @@ function attachNotifications(ctx) {
203
204
 
204
205
  // --- Core API ---
205
206
 
206
- function notify(event, data) {
207
+ // meta, set by the notification core when it delivers a banner (lib/notify/):
208
+ // key the collapse identity; a banner under the same key replaces
209
+ // the earlier one, and a resolve closes the banners under it.
210
+ // collapse "request" | "session", the key's rule.
211
+ // persistent the registry says the banner is not auto-dismissed.
212
+ // liveInState the page may check the banner against the live prompts.
213
+ // They travel on the notification (key, collapse, persistent, liveInState).
214
+ function notify(event, data, meta) {
215
+ meta = meta || {};
207
216
  data = data || {};
208
217
  var formatter = formatters[event];
209
218
  if (!formatter) {
@@ -237,6 +246,10 @@ function attachNotifications(ctx) {
237
246
  targetUserId: data.targetUserId || null,
238
247
  targetUserIds: Array.isArray(data.targetUserIds) ? data.targetUserIds : null,
239
248
  createdAt: Date.now(),
249
+ key: meta.key || null,
250
+ collapse: meta.collapse || null,
251
+ persistent: meta.persistent === true,
252
+ liveInState: meta.liveInState === true,
240
253
  meta: formatted.meta || {},
241
254
  };
242
255
  notifications.unshift(notif);
@@ -271,17 +284,41 @@ function attachNotifications(ctx) {
271
284
  }
272
285
  }
273
286
 
287
+ // The core's banner surface (lib/notify/): a banner under a key the
288
+ // notification just collapsed to replaces the earlier one on every client,
289
+ // the dismissal and the new banner travelling together.
290
+ function show(event, data, meta) {
291
+ var key = meta && meta.key;
292
+ if (key) {
293
+ var old = idsByKey([key]);
294
+ if (old.length) dismiss(old);
295
+ }
296
+ return notify(event, data, meta);
297
+ }
298
+
299
+ function idsByKey(keys) {
300
+ return notifications.filter(function (n) {
301
+ return n.key && keys.indexOf(n.key) !== -1;
302
+ }).map(function (n) { return n.id; });
303
+ }
304
+
274
305
  // A prompt notification is only actionable while its prompt is pending; the
275
- // prompt registry calls this on every transition that ends one, so the
276
- // banner buttons never outlive it.
277
- function dismissByRequestId(requestId) {
278
- if (!requestId) return;
306
+ // core calls this when a target resolves, so the banner buttons never
307
+ // outlive the prompt.
308
+ function dismissKeys(keys) {
309
+ var ids = idsByKey(keys || []);
310
+ if (ids.length) dismiss(ids);
311
+ }
312
+
313
+ // The banners of one prompt, when only its request id is known (a stale
314
+ // answer no session claims). The slug scopes it to the prompt's project and
315
+ // is required: a request id alone names nothing, so no slug dismisses nothing.
316
+ function dismissRequest(slug, requestId) {
317
+ if (!slug || !requestId) return;
279
318
  var ids = notifications.filter(function (n) {
280
- return n.type === "permission_request" && n.meta && n.meta.requestId === requestId;
319
+ return n.collapse === "request" && n.meta && n.meta.requestId === requestId && n.slug === slug;
281
320
  }).map(function (n) { return n.id; });
282
321
  if (ids.length) dismiss(ids);
283
- // A reminder that names this prompt is now wrong, or gone.
284
- reconcileRemindersNow();
285
322
  }
286
323
 
287
324
  function dismissAll() {
@@ -294,25 +331,6 @@ function attachNotifications(ctx) {
294
331
 
295
332
  // --- Prompt reminders (scheduling lives in lib/prompt-reminders.js) ---
296
333
 
297
- function reminderIds(key) {
298
- return notifications.filter(function (n) {
299
- return n.type === "permission_reminder" && n.meta && n.meta.reminderKey === key;
300
- }).map(function (n) { return n.id; });
301
- }
302
-
303
- // A session has at most one live reminder: the new one replaces the old on
304
- // every surface (the dismissal and the new notification travel together).
305
- function replaceReminder(key, data) {
306
- var old = reminderIds(key);
307
- if (old.length) dismiss(old);
308
- return notify("permission_reminder", Object.assign({}, data, { reminderKey: key }));
309
- }
310
-
311
- function dismissReminder(key) {
312
- var ids = reminderIds(key);
313
- if (ids.length) dismiss(ids);
314
- }
315
-
316
334
  function setReminderReconciler(fn) {
317
335
  reconcileReminders = typeof fn === "function" ? fn : null;
318
336
  }
@@ -339,7 +357,10 @@ function attachNotifications(ctx) {
339
357
 
340
358
  // --- Connection state (called per-client with sendTo) ---
341
359
 
342
- function sendConnectionState(ws, sendTo) {
360
+ // livePrompts: the prompts awaiting the operator in this project when the
361
+ // client connected (lib/notify/live-prompts.js); the page checks the
362
+ // notifications on the device against it.
363
+ function sendConnectionState(ws, sendTo, livePrompts) {
343
364
  if (!sendTo) return;
344
365
  // A notification aimed at admins only, or a prompt banner aimed at its
345
366
  // owner, is not handed to anyone else on connect, as it is not live.
@@ -348,6 +369,7 @@ function attachNotifications(ctx) {
348
369
  type: "notifications_state",
349
370
  notifications: notifications.filter(function (n) { return visibleTo(n, viewer); }),
350
371
  unreadCount: unreadCountFor(viewer),
372
+ livePrompts: livePrompts || null,
351
373
  });
352
374
  if (prefsStore) sendTo(ws, prefsMessage(userIdOf(ws)));
353
375
  }
@@ -410,9 +432,9 @@ function attachNotifications(ctx) {
410
432
 
411
433
  return {
412
434
  notify: notify,
413
- dismissByRequestId: dismissByRequestId,
414
- replaceReminder: replaceReminder,
415
- dismissReminder: dismissReminder,
435
+ show: show,
436
+ dismissKeys: dismissKeys,
437
+ dismissRequest: dismissRequest,
416
438
  setReminderReconciler: setReminderReconciler,
417
439
  reconcileReminders: reconcileRemindersNow,
418
440
  getUnreadCount: getUnreadCount,
@@ -104,7 +104,7 @@ function attachPromptResponses(ctx) {
104
104
  // synchronously kills the subprocess mid-write ("Operation aborted").
105
105
  session.isProcessing = false;
106
106
  onProcessingChanged();
107
- promptsFor(sm).cancelSession(session, "cleared");
107
+ promptsFor(sm).cancelSession(session, "cleared", { source: promptSource.CANCEL.USER });
108
108
  sm.broadcastSessionList();
109
109
  setImmediate(function () {
110
110
  if (session.abortController) session.abortController.abort();
@@ -10,6 +10,7 @@ var agentsModule = require("./agents");
10
10
  var agentsFavorites = require("./agents-favorites");
11
11
  var sessionActivity = require("./session-activity");
12
12
  var { promptsFor } = require("./prompt-registry");
13
+ var promptSource = require("./prompt-source");
13
14
  var { attachPromptResponses } = require("./project-prompt-responses");
14
15
  var { attachSessionGrants } = require("./project-session-grants");
15
16
  var { ownValue } = require("./prompt-kinds/codecs");
@@ -1321,7 +1322,7 @@ function attachSessions(ctx) {
1321
1322
  session.abortController = null;
1322
1323
  session.blocks = {};
1323
1324
  session.sentToolResults = {};
1324
- promptsFor(sm).cancelSession(session, "rewind");
1325
+ promptsFor(sm).cancelSession(session, "rewind", { source: promptSource.CANCEL.USER });
1325
1326
  // lr-9bcd7b: a rewind destroys the in-flight query outright (the
1326
1327
  // queryInstance null-out above), so nothing can genuinely still be
1327
1328
  // running for this session afterward. Unlike the reconciliation
package/lib/project.js CHANGED
@@ -3,6 +3,7 @@ var path = require("path");
3
3
  var os = require("os");
4
4
  var crypto = require("crypto");
5
5
  var { createSessionManager, stampActivityLocalId } = require("./sessions");
6
+ var sessionLiveness = require("./session-liveness");
6
7
  var { promptsFor } = require("./prompt-registry");
7
8
  var { createSDKBridge, createMessageQueue } = require("./sdk-bridge");
8
9
  var { createTerminalManager } = require("./terminal-manager");
@@ -449,6 +450,7 @@ function createProjectContext(opts) {
449
450
  onProcessingChanged: onProcessingChanged,
450
451
  getProjectName: function () { return title || project; },
451
452
  getProjectSlug: function () { return slug; },
453
+ getPushModule: function () { return pushModule; },
452
454
  });
453
455
  sm.availableVendors = Object.keys(adapters);
454
456
  sm.defaultVendor = defaultVendor;
@@ -1187,7 +1189,6 @@ function createProjectContext(opts) {
1187
1189
  // adapters for this project (see project-connection handleConnection).
1188
1190
  warmup: function () {
1189
1191
  sdk.warmup();
1190
- sdk.startIdleReaper();
1191
1192
  if (!osUsers && !sessionTitleMigrationScheduled) {
1192
1193
  sessionTitleMigrationScheduled = true;
1193
1194
  setTimeout(function () {
@@ -1201,6 +1202,12 @@ function createProjectContext(opts) {
1201
1202
  },
1202
1203
  });
1203
1204
 
1205
+ // The idle reaper runs from attach, not from the first WebSocket: a project
1206
+ // reached only over IPC (open-session, send-input, scheduled input, external
1207
+ // trigger, loop) would otherwise never reap its idle sessions. A repeated
1208
+ // start is a no-op in the bridge, and destroy() stops the timer.
1209
+ sdk.startIdleReaper();
1210
+
1204
1211
  // --- Destroy ---
1205
1212
  // opts.reason says why the project is going away. Only a daemon shutdown
1206
1213
  // (sessionReclaim.RESTART_REASON) records its live background agents as
@@ -1210,6 +1217,9 @@ function createProjectContext(opts) {
1210
1217
  function destroy(opts) {
1211
1218
  var daemonShutdown = !!opts && opts.reason === sessionReclaim.RESTART_REASON;
1212
1219
  var tally = opts && opts.tally;
1220
+ // Ended before the aborts below, which would otherwise record the
1221
+ // daemon going away as each session's own abort.
1222
+ if (daemonShutdown) promptsFor(sm).shutdown();
1213
1223
  _loop.stopTimer();
1214
1224
  stopAllWatches();
1215
1225
  // Abort all active sessions and clean up mention sessions
@@ -1251,6 +1261,7 @@ function createProjectContext(opts) {
1251
1261
  try { _localMcp.shutdown(); } catch (e) {}
1252
1262
  }
1253
1263
  for (var ws of clients) {
1264
+ _connection.recordDisconnect(ws);
1254
1265
  try { ws.close(); } catch (e) {}
1255
1266
  }
1256
1267
  clients.clear();
@@ -1282,11 +1293,13 @@ function createProjectContext(opts) {
1282
1293
  function getStatus() {
1283
1294
  var sessionCount = sm.sessions.size;
1284
1295
  var hasProcessing = false;
1296
+ var hasWaiting = false;
1285
1297
  // Every prompt awaiting the operator, of any kind, flags the project.
1286
1298
  var pendingPermCount = 0;
1287
1299
  var prompts = promptsFor(sm);
1288
1300
  sm.sessions.forEach(function (s) {
1289
1301
  if (s.isProcessing) hasProcessing = true;
1302
+ if (sessionLiveness.activityOf(s) === sessionLiveness.ACTIVITY.WAITING) hasWaiting = true;
1290
1303
  pendingPermCount += prompts.pendingCount(s);
1291
1304
  });
1292
1305
  var status = {
@@ -1300,6 +1313,7 @@ function createProjectContext(opts) {
1300
1313
  clients: clients.size,
1301
1314
  sessions: sessionCount,
1302
1315
  isProcessing: hasProcessing,
1316
+ waiting: hasWaiting,
1303
1317
  pendingPermissions: pendingPermCount,
1304
1318
  projectOwnerId: projectOwnerId,
1305
1319
  };
@@ -50,6 +50,8 @@ var sessionReclaim = require("./session-reclaim");
50
50
  var { promptLabel } = require("./prompt-label");
51
51
  var promptSource = require("./prompt-source");
52
52
  var { logField } = require("./log-field");
53
+ var { notifyFor } = require("./notify");
54
+ var { withPromptLabel } = require("./prompt-label");
53
55
  var { ownValue, putOwn, hasOwnKey } = codecs;
54
56
 
55
57
  var KINDS = promptKinds.KINDS;
@@ -62,6 +64,13 @@ function cancelReasonForAbort(signal) {
62
64
  return signal && signal.reason === "expired" ? "expired" : "aborted";
63
65
  }
64
66
 
67
+ // Who ended a prompt through its signal: the worker or app-server that gave up
68
+ // waiting ("expired"), otherwise the session's own abort, close or query end,
69
+ // which is what cancels every callback a query still has out.
70
+ function cancelSourceForAbort(signal) {
71
+ return signal && signal.reason === "expired" ? promptSource.CANCEL.WORKER : promptSource.CANCEL.SESSION_END;
72
+ }
73
+
65
74
  var RESOLVED_FIELDS = ["decision", "answers", "skipped", "action"];
66
75
 
67
76
  function deepFreeze(value) {
@@ -89,13 +98,13 @@ function terminalOf(e) {
89
98
  return e.requestId ? { id: e.requestId, state: Object.assign({ state: "resolved" }, pick(e, RESOLVED_FIELDS)) } : null;
90
99
  case "prompt_cancel":
91
100
  case "permission_cancel":
92
- return e.requestId ? { id: e.requestId, state: { state: "cancelled", reason: e.reason || null } } : null;
101
+ return e.requestId ? { id: e.requestId, state: { state: "cancelled", reason: e.reason || null, source: e.source || promptSource.CANCEL.UNSPECIFIED } } : null;
93
102
  case "ask_user_answered":
94
103
  if (!e.toolId) return null;
95
104
  if (e.answers && Object.keys(e.answers).length) return { id: e.toolId, state: { state: "resolved", answers: e.answers } };
96
105
  // A recorded skip is an answer, not an ending nobody chose.
97
106
  if (e.skipped === true) return { id: e.toolId, state: { state: "resolved", skipped: true } };
98
- return { id: e.toolId, state: { state: "cancelled", reason: null } };
107
+ return { id: e.toolId, state: { state: "cancelled", reason: null, source: promptSource.CANCEL.UNSPECIFIED } };
99
108
  default:
100
109
  return null;
101
110
  }
@@ -137,6 +146,7 @@ function createPromptRegistry(deps) {
137
146
  var onProcessingChanged = deps.onProcessingChanged || function () {};
138
147
  var getProjectName = deps.getProjectName || function () { return ""; };
139
148
  var getProjectSlug = deps.getProjectSlug || function () { return ""; };
149
+ var getPushModule = deps.getPushModule || function () { return null; };
140
150
 
141
151
  // Project-scope prompts (no session): requestId -> record.
142
152
  var projectPrompts = Object.create(null);
@@ -185,9 +195,30 @@ function createPromptRegistry(deps) {
185
195
  return null;
186
196
  }
187
197
 
188
- function dismissNotification(requestId) {
198
+ // The one close for a settled prompt: the core closes its banner and its
199
+ // push on every surface. The keys come from the target alone, so this holds
200
+ // after a restart and during the shutdown settle. A question's notification
201
+ // is keyed by its tool-use id, which is its request id unless another prompt
202
+ // already held that id. With no session to name (a project-level prompt, or a
203
+ // stale answer no session claims) only the request's banners are retired.
204
+ function closeNotifications(session, requestId, record) {
205
+ // A request id that is no string (a malformed client message) names no
206
+ // prompt, and must not widen the close to the session's own notification.
207
+ if (typeof requestId !== "string") return;
208
+ var core = notifyFor(getPushModule(), getNotificationsModule());
209
+ var slug = getProjectSlug();
210
+ if (!session) {
211
+ core.resolve({ slug: slug, requestId: requestId });
212
+ return;
213
+ }
214
+ var audience = { ownerId: session.ownerId };
215
+ var scope = { slug: slug, sessionId: session.localId };
216
+ var ids = [requestId];
217
+ if (record && record.toolUseId && record.toolUseId !== requestId) ids.push(record.toolUseId);
218
+ core.resolve(ids.map(function (id) { return Object.assign({ requestId: id }, scope); }), audience);
219
+ // A reminder that names this prompt is now wrong, or gone.
189
220
  var nm = getNotificationsModule();
190
- if (nm && typeof nm.dismissByRequestId === "function") nm.dismissByRequestId(requestId);
221
+ if (nm && typeof nm.reconcileReminders === "function") nm.reconcileReminders();
191
222
  }
192
223
 
193
224
  function ownerTaskOf(session, record) {
@@ -271,7 +302,7 @@ function createPromptRegistry(deps) {
271
302
  var detach = detachers.get(entry.record);
272
303
  if (detach) detach();
273
304
  if (entry.kind.journal) {
274
- dismissNotification(requestId);
305
+ closeNotifications(session, requestId, entry.record);
275
306
  if (event) sendAndRecord(session, event);
276
307
  onProcessingChanged();
277
308
  if (info) logSettled(session, requestId, entry, info);
@@ -286,14 +317,17 @@ function createPromptRegistry(deps) {
286
317
  return true;
287
318
  }
288
319
 
320
+ // opts.source is one of lib/prompt-source.js's cancel sources; a missing or
321
+ // unknown one is recorded as "unspecified" with a warning.
289
322
  function cancelEntry(session, requestId, entry, reason, opts) {
323
+ var source = promptSource.cancelSource(opts && opts.source, reason);
290
324
  var event = (entry.kind.journal && !(opts && opts.record === false))
291
- ? { type: "prompt_cancel", requestId: requestId, kind: entry.kind.name, reason: reason }
325
+ ? { type: "prompt_cancel", requestId: requestId, kind: entry.kind.name, reason: reason, source: source }
292
326
  : null;
293
327
  return settle(session, requestId, entry, entry.kind.cancelled(reason), event, {
294
328
  status: "cancelled",
295
329
  reason: reason,
296
- source: (opts && opts.source) || promptSource.fromCancel(reason),
330
+ source: source,
297
331
  });
298
332
  }
299
333
 
@@ -325,8 +359,9 @@ function createPromptRegistry(deps) {
325
359
  * @param {AbortSignal} [opts.signal] - ends the prompt (aborted, or
326
360
  * expired when the signal's reason is "expired").
327
361
  * @param {number} [opts.timeoutMs] - ends the prompt as expired.
328
- * @param {object} [opts.notification] - permission_request notification
329
- * payload (title, body, slug, ...); dismissed when the prompt settles.
362
+ * @param {object} [opts.notification] - permission_request banner
363
+ * content (title, body, slug, ...), delivered through the notification
364
+ * core and closed with it when the prompt settles.
330
365
  * @returns {{requestId: string, answer: Promise<*>, pending: boolean}}
331
366
  * pending is false when its signal was already aborted: no prompt was
332
367
  * opened or announced, and answer carries the kind's cancelled value.
@@ -377,7 +412,7 @@ function createPromptRegistry(deps) {
377
412
 
378
413
  var cleanups = [];
379
414
  if (signal && typeof signal.addEventListener === "function") {
380
- var onAbort = function () { cancelEntry(owner, requestId, entry, cancelReasonForAbort(signal)); };
415
+ var onAbort = function () { cancelEntry(owner, requestId, entry, cancelReasonForAbort(signal), { source: cancelSourceForAbort(signal) }); };
381
416
  signal.addEventListener("abort", onAbort, { once: true });
382
417
  if (typeof signal.removeEventListener === "function") {
383
418
  cleanups.push(function () { signal.removeEventListener("abort", onAbort); });
@@ -386,7 +421,7 @@ function createPromptRegistry(deps) {
386
421
  var timeoutMs = opts.timeoutMs != null ? opts.timeoutMs : kind.defaultTimeoutMs;
387
422
  if (timeoutMs) {
388
423
  var timer = setTimeout(function () {
389
- cancelEntry(owner, requestId, entry, "expired", { source: promptSource.fromTimeout() });
424
+ cancelEntry(owner, requestId, entry, "expired", { source: promptSource.CANCEL.TIMEOUT });
390
425
  }, timeoutMs);
391
426
  cleanups.push(function () { clearTimeout(timer); });
392
427
  }
@@ -394,12 +429,22 @@ function createPromptRegistry(deps) {
394
429
  detachers.set(record, function () { cleanups.forEach(function (fn) { fn(); }); });
395
430
  }
396
431
 
397
- if (kind.journal && opts.notification) {
398
- var nm = getNotificationsModule();
399
- if (nm && typeof nm.notify === "function") {
400
- var kindFields = typeof kind.notificationFields === "function" ? kind.notificationFields(record) : {};
401
- nm.notify("permission_request", Object.assign({}, opts.notification, kindFields, labelFields(record), { requestId: requestId, kind: kind.name }));
402
- }
432
+ if (kind.journal && opts.notification && session) {
433
+ var kindFields = typeof kind.notificationFields === "function" ? kind.notificationFields(record) : {};
434
+ var pushText = opts.notification.push || null;
435
+ var banner = Object.assign({}, opts.notification, kindFields, labelFields(record), { kind: kind.name });
436
+ delete banner.push;
437
+ // One notify() per prompt: the emitter supplies the text of each surface
438
+ // and the core picks the surfaces from the type's registration. The
439
+ // audience is the session's own, for the push and the banner alike.
440
+ notifyFor(getPushModule(), getNotificationsModule()).notify("permission_request", {
441
+ slug: getProjectSlug(),
442
+ sessionId: session.localId,
443
+ requestId: requestId,
444
+ }, {
445
+ push: pushText ? { title: pushText.title, body: withPromptLabel(record.label, pushText.body) } : null,
446
+ banner: banner,
447
+ }, { ownerId: session.ownerId || null });
403
448
  }
404
449
  return { requestId: requestId, answer: answer, pending: true, label: record.label || null };
405
450
  }
@@ -471,7 +516,7 @@ function createPromptRegistry(deps) {
471
516
  opts = opts || {};
472
517
  var found = find(requestId, opts.session);
473
518
  if (!found) {
474
- dismissNotification(requestId);
519
+ closeNotifications(opts.session || null, requestId, null);
475
520
  return { status: "stale" };
476
521
  }
477
522
  if (opts.kinds && opts.kinds.indexOf(found.kind.name) === -1) return { status: "stale" };
@@ -517,7 +562,7 @@ function createPromptRegistry(deps) {
517
562
  function endTurn(session) {
518
563
  cancelWhere(session, "turn_ended", function (record) {
519
564
  return !ownedByTrackedTask(session, record);
520
- });
565
+ }, { source: promptSource.CANCEL.SESSION_END });
521
566
  }
522
567
 
523
568
  /**
@@ -532,7 +577,7 @@ function createPromptRegistry(deps) {
532
577
  cancelWhere(session, "query_ended", function (record) {
533
578
  var ours = record.query ? record.query === query : !!ownsSession;
534
579
  return ours && !ownedByTrackedTask(session, record);
535
- });
580
+ }, { source: promptSource.CANCEL.SESSION_END });
536
581
  if (ownsSession) pruneTasks(session);
537
582
  }
538
583
 
@@ -541,7 +586,11 @@ function createPromptRegistry(deps) {
541
586
  pruneTasks(session);
542
587
  }
543
588
 
544
- /** End every prompt of a session (rewind, context clear, deletion). */
589
+ /**
590
+ * End every prompt of a session (rewind, context clear, deletion).
591
+ * opts.source names who ended them (lib/prompt-source.js); opts.record false
592
+ * keeps the ending out of history.
593
+ */
545
594
  function cancelSession(session, reason, opts) {
546
595
  cancelWhere(session, reason, function () { return true; }, opts);
547
596
  session.activeTaskToolIds = Object.create(null);
@@ -557,11 +606,11 @@ function createPromptRegistry(deps) {
557
606
  Object.keys(index).forEach(function (id) { localIds.add(index[id]); });
558
607
  localIds.forEach(function (localId) {
559
608
  var session = getSession ? getSession(localId) : null;
560
- if (session) cancelWhere(session, "shutdown", function () { return true; });
609
+ if (session) cancelWhere(session, "shutdown", function () { return true; }, { source: promptSource.CANCEL.DAEMON_RESTART });
561
610
  });
562
611
  Object.keys(projectPrompts).forEach(function (id) {
563
612
  var record = projectPrompts[id];
564
- if (record) cancelEntry(null, id, entryOf(null, record), "shutdown");
613
+ if (record) cancelEntry(null, id, entryOf(null, record), "shutdown", { source: promptSource.CANCEL.DAEMON_RESTART });
565
614
  });
566
615
  }
567
616
 
@@ -679,6 +728,7 @@ function createPromptRegistry(deps) {
679
728
  return entries(session).filter(function (e) { return e.kind.journal; }).map(function (e) {
680
729
  return {
681
730
  requestId: e.id,
731
+ toolUseId: typeof e.record.toolUseId === "string" ? e.record.toolUseId : null,
682
732
  kind: e.kind.name,
683
733
  toolName: typeof e.record.toolName === "string" ? e.record.toolName : null,
684
734
  agent: (e.record.label && e.record.label.agent) || "",
@@ -723,7 +773,7 @@ function createPromptRegistry(deps) {
723
773
  if (!state) {
724
774
  var mayStillOpen = item.type === "tool_executing" && !askBeforeTurnEnd.has(item);
725
775
  if (mayStillOpen) return item;
726
- state = { state: "cancelled", reason: "stale" };
776
+ state = { state: "cancelled", reason: "stale", source: promptSource.CANCEL.UNSPECIFIED };
727
777
  }
728
778
  return Object.assign({}, item, { promptState: state });
729
779
  };