@clagentic/console 1.12.0-beta.1 → 1.12.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/LICENSES/README.md +5 -0
  2. package/README.md +1 -0
  3. package/bin/cli.js +5 -2
  4. package/lib/agent-roster-ws.js +84 -0
  5. package/lib/agent-roster.js +312 -0
  6. package/lib/auth-required-notify.js +42 -0
  7. package/lib/build-changes.js +8 -2
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-notify.js +45 -0
  10. package/lib/build-update-offer.js +34 -11
  11. package/lib/build-update-standing.js +34 -14
  12. package/lib/claude-settings-env.js +142 -0
  13. package/lib/cli/duration.js +27 -0
  14. package/lib/cli/schedule-input-subcommands.js +1 -22
  15. package/lib/cli/session-subcommands.js +60 -11
  16. package/lib/client-address.js +44 -0
  17. package/lib/daemon.js +31 -10
  18. package/lib/idle-compaction-setting.js +203 -0
  19. package/lib/mcp-bridge-credential.js +41 -0
  20. package/lib/notification-prefs.js +18 -22
  21. package/lib/notify/core.js +210 -0
  22. package/lib/notify/index.js +31 -0
  23. package/lib/notify/live-prompts.js +36 -0
  24. package/lib/notify/payload.js +62 -0
  25. package/lib/notify/target.js +5 -0
  26. package/lib/notify/type-registry.js +81 -0
  27. package/lib/notify/types.js +57 -0
  28. package/lib/open-sockets.js +27 -0
  29. package/lib/outbound-access.js +85 -0
  30. package/lib/outbound-entry.js +116 -0
  31. package/lib/outbound-ledger.js +306 -0
  32. package/lib/outbound-query.js +153 -0
  33. package/lib/pending-prompts.js +31 -16
  34. package/lib/project-connection.js +48 -8
  35. package/lib/project-filesystem.js +43 -5
  36. package/lib/project-http.js +9 -1
  37. package/lib/project-loop.js +38 -26
  38. package/lib/project-notifications.js +122 -39
  39. package/lib/project-prompt-responses.js +1 -1
  40. package/lib/project-sessions.js +11 -1
  41. package/lib/project-user-mention.js +22 -34
  42. package/lib/project-user-message.js +208 -4
  43. package/lib/project-user-shell.js +298 -0
  44. package/lib/project.js +41 -5
  45. package/lib/prompt-answer.js +145 -0
  46. package/lib/prompt-expiry.js +50 -0
  47. package/lib/prompt-registry.js +98 -25
  48. package/lib/prompt-reminders.js +38 -33
  49. package/lib/prompt-source.js +59 -8
  50. package/lib/public/app.js +32 -2
  51. package/lib/public/css/agent-messages.css +96 -0
  52. package/lib/public/css/agent-roster.css +93 -0
  53. package/lib/public/css/diagnostics.css +29 -1
  54. package/lib/public/css/home-hub.css +12 -0
  55. package/lib/public/css/icon-strip.css +9 -0
  56. package/lib/public/css/input.css +20 -141
  57. package/lib/public/css/login-panel.css +73 -0
  58. package/lib/public/css/menus.css +2 -2
  59. package/lib/public/css/mobile-nav.css +11 -0
  60. package/lib/public/css/sidebar.css +18 -0
  61. package/lib/public/css/team-panel.css +1 -6
  62. package/lib/public/css/team-view.css +101 -0
  63. package/lib/public/css/title-bar.css +10 -0
  64. package/lib/public/css/user-shell.css +144 -0
  65. package/lib/public/index.html +44 -7
  66. package/lib/public/modules/activity-state.js +20 -4
  67. package/lib/public/modules/agent-avatar-picker.js +162 -0
  68. package/lib/public/modules/agent-avatar.js +153 -0
  69. package/lib/public/modules/agent-messages.js +285 -0
  70. package/lib/public/modules/agent-roster.js +157 -0
  71. package/lib/public/modules/app-connection.js +34 -5
  72. package/lib/public/modules/app-messages.js +55 -16
  73. package/lib/public/modules/app-notifications.js +104 -75
  74. package/lib/public/modules/app-panels.js +26 -3
  75. package/lib/public/modules/app-projects.js +3 -1
  76. package/lib/public/modules/app-rate-limit.js +8 -165
  77. package/lib/public/modules/app-rendering.js +32 -7
  78. package/lib/public/modules/build-update-sessions.js +81 -0
  79. package/lib/public/modules/collapsible-text.js +33 -18
  80. package/lib/public/modules/compaction-state.js +34 -0
  81. package/lib/public/modules/custom-icons.js +23 -5
  82. package/lib/public/modules/diagnostics.js +61 -57
  83. package/lib/public/modules/env-shadow-notice.js +34 -0
  84. package/lib/public/modules/injected-identity.js +24 -21
  85. package/lib/public/modules/input.js +176 -15
  86. package/lib/public/modules/login-panel.js +136 -0
  87. package/lib/public/modules/login-parser.js +73 -0
  88. package/lib/public/modules/login-tab.js +66 -0
  89. package/lib/public/modules/notifications.js +9 -1
  90. package/lib/public/modules/notify-client.js +246 -0
  91. package/lib/public/modules/pending-term-request.js +30 -0
  92. package/lib/public/modules/project-icon.js +22 -2
  93. package/lib/public/modules/project-settings.js +5 -0
  94. package/lib/public/modules/prompt-state.js +3 -3
  95. package/lib/public/modules/prompts.js +1 -1
  96. package/lib/public/modules/queued-button.js +11 -0
  97. package/lib/public/modules/scheduled-input-actions.js +12 -4
  98. package/lib/public/modules/scheduled-outbox.js +230 -0
  99. package/lib/public/modules/send-now.js +200 -0
  100. package/lib/public/modules/server-settings.js +50 -1
  101. package/lib/public/modules/shell-card.js +76 -0
  102. package/lib/public/modules/shell-line.js +49 -0
  103. package/lib/public/modules/shell-queue.js +253 -0
  104. package/lib/public/modules/shell-settings-controls.js +76 -0
  105. package/lib/public/modules/sidebar-mobile.js +3 -3
  106. package/lib/public/modules/sidebar-sessions.js +8 -0
  107. package/lib/public/modules/sidebar-users.js +5 -7
  108. package/lib/public/modules/team-panel.js +30 -88
  109. package/lib/public/modules/team-view.js +211 -0
  110. package/lib/public/modules/terminal-links.js +193 -0
  111. package/lib/public/modules/terminal.js +84 -107
  112. package/lib/public/modules/tools.js +19 -0
  113. package/lib/public/modules/user-shell.js +824 -0
  114. package/lib/public/notify-sw-logic.js +252 -0
  115. package/lib/public/notify-target.js +157 -0
  116. package/lib/public/style.css +5 -0
  117. package/lib/public/sw.js +20 -69
  118. package/lib/push.js +63 -19
  119. package/lib/queued-chat.js +392 -0
  120. package/lib/runtime-env.js +1 -0
  121. package/lib/scheduled-input/ws.js +67 -9
  122. package/lib/sdk-bridge.js +184 -73
  123. package/lib/sdk-message-processor.js +124 -76
  124. package/lib/server-auth.js +6 -4
  125. package/lib/server-dm.js +11 -20
  126. package/lib/server-settings.js +39 -1
  127. package/lib/server.js +112 -16
  128. package/lib/session-directory.js +39 -12
  129. package/lib/session-end.js +97 -0
  130. package/lib/session-input-ipc.js +37 -1
  131. package/lib/session-input.js +263 -21
  132. package/lib/session-liveness.js +53 -0
  133. package/lib/session-reclaim.js +37 -2
  134. package/lib/session-resume.js +1 -0
  135. package/lib/session-settings-file.js +53 -0
  136. package/lib/sessions.js +80 -9
  137. package/lib/team-traffic-ws.js +68 -0
  138. package/lib/team-traffic.js +318 -0
  139. package/lib/usage-store.js +36 -7
  140. package/lib/user-shell-settings.js +105 -0
  141. package/lib/vendor-auth.js +33 -2
  142. package/lib/ws-schema.js +33 -5
  143. package/lib/yoke/adapters/claude-capabilities.js +2 -0
  144. package/lib/yoke/adapters/claude-vendor.js +17 -1
  145. package/lib/yoke/adapters/claude-worker.js +39 -11
  146. package/lib/yoke/adapters/claude.js +225 -6
  147. package/lib/yoke/adapters/codex-capabilities.js +6 -1
  148. package/lib/yoke/adapters/codex-user-shell.js +265 -0
  149. package/lib/yoke/adapters/codex-vendor.js +7 -0
  150. package/lib/yoke/adapters/codex.js +186 -52
  151. package/lib/yoke/auth-checks.js +17 -2
  152. package/lib/yoke/codex-app-server.js +8 -2
  153. package/lib/yoke/index.js +21 -3
  154. package/lib/yoke/interface.js +54 -1
  155. package/lib/yoke/mcp-bridge-server.js +12 -8
  156. package/lib/yoke/provider-credentials.js +24 -0
  157. package/lib/yoke/registry.js +40 -1
  158. package/lib/yoke/user-shell.js +224 -0
  159. package/package.json +2 -2
  160. package/scripts/check-test-count.js +14 -0
  161. package/lib/public/modules/build-notice-gate.js +0 -73
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");
@@ -31,6 +32,7 @@ var { savedModeOrDefault } = require("./permission-mode-policy");
31
32
  var { logField } = require("./log-field");
32
33
  var { attachSessions } = require("./project-sessions");
33
34
  var { attachUserMessage } = require("./project-user-message");
35
+ var { attachUserShell } = require("./project-user-shell");
34
36
  var { attachConnection } = require("./project-connection");
35
37
  var { detectLite } = require("./lite-detect");
36
38
  var { attachMcp } = require("./project-mcp");
@@ -154,7 +156,6 @@ function createProjectContext(opts) {
154
156
  var onCreateWorktree = opts.onCreateWorktree || null;
155
157
  var serverPort = opts.port || 2633;
156
158
  var serverTls = opts.tls || false;
157
- var serverAuthToken = opts.authToken || null;
158
159
  // lr-2ea2a7: daemon.json knob overriding the in-heap session-history tail
159
160
  // cap (default HISTORY_INMEM_MAX_DEFAULT=1000 in lib/sessions.js).
160
161
  var historyInMemMax = opts.historyInMemMax;
@@ -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;
@@ -614,11 +616,11 @@ function createProjectContext(opts) {
614
616
  getRemoteMcpServers: function () { return _mcp.getMcpServers(); },
615
617
  clayPort: serverPort,
616
618
  clayTls: serverTls,
617
- clayAuthToken: serverAuthToken,
618
619
  onProcessingChanged: onProcessingChanged,
619
620
  onTurnDone: null,
620
621
  onTeamCreate: function (teamId, cliSessionId, cwd) { _team.onTeamCreate(teamId, cliSessionId, cwd); },
621
622
  onTeamDelete: function () { _team.onTeamDelete(); },
623
+ onAgentSeen: opts.onAgentSeen || null,
622
624
  scheduleRateLimitResume: function (session, resetsAt) { rateLimitResume.schedule(session, resetsAt); },
623
625
  hasRateLimitResume: function (session) { return rateLimitResume.has(session); },
624
626
  getAutoContinueSetting: function (session) {
@@ -731,6 +733,8 @@ function createProjectContext(opts) {
731
733
  // agent's alike; this project only hands it the rate-limit resume. A context
732
734
  // built without one (unit harnesses) schedules nothing.
733
735
  var scheduledInput = opts.scheduledInput || null;
736
+ // The Team view's agent-messages query (lib/team-traffic.js); null in a bare harness.
737
+ var teamTraffic = opts.teamTraffic || null;
734
738
 
735
739
  // The automatic "continue" after a rate limit: one once record on the session,
736
740
  // timed after the limit resets. This is the only caller that adds the
@@ -798,7 +802,6 @@ function createProjectContext(opts) {
798
802
  osUsers: osUsers,
799
803
  clayPort: serverPort,
800
804
  clayTls: serverTls,
801
- clayAuthToken: serverAuthToken,
802
805
  slug: slug,
803
806
  runtimeEnv: sdk.getRuntimeEnvOverlay(),
804
807
  }, recordInit);
@@ -807,7 +810,6 @@ function createProjectContext(opts) {
807
810
  cwd: cwd,
808
811
  clayPort: serverPort,
809
812
  clayTls: serverTls,
810
- clayAuthToken: serverAuthToken,
811
813
  slug: slug,
812
814
  runtimeEnv: sdk.getRuntimeEnvOverlay(),
813
815
  }));
@@ -854,6 +856,9 @@ function createProjectContext(opts) {
854
856
  // --- Notifications (delegated to project-notifications.js) ---
855
857
  if (_notifications.handleNotificationMessage(ws, msg)) return;
856
858
 
859
+ // --- The ! command line (delegated to project-user-shell.js) ---
860
+ if (_userShell.handleUserShellMessage(ws, msg)) return;
861
+
857
862
  // --- Sessions, config, project mgmt (delegated to project-sessions.js) ---
858
863
  if (_sessions.handleSessionsMessage(ws, msg)) return;
859
864
 
@@ -1012,6 +1017,8 @@ function createProjectContext(opts) {
1012
1017
  sendExtensionCommandAny: sendExtensionCommandAny,
1013
1018
  requestTabContext: requestTabContext,
1014
1019
  scheduledInput: scheduledInput,
1020
+ teamTraffic: teamTraffic,
1021
+ agentRoster: opts.agentRoster || null,
1015
1022
  loadContextSources: loadContextSources,
1016
1023
  saveContextSources: saveContextSources,
1017
1024
  escapeRegex: escapeRegex,
@@ -1020,6 +1027,21 @@ function createProjectContext(opts) {
1020
1027
  getProjectOwnerId: function () { return projectOwnerId; },
1021
1028
  });
1022
1029
 
1030
+ // --- The ! command line (delegated to project-user-shell.js) ---
1031
+ var _userShell = attachUserShell({
1032
+ slug: slug,
1033
+ cwd: cwd,
1034
+ osUsers: osUsers,
1035
+ sm: sm,
1036
+ sdk: sdk,
1037
+ send: send,
1038
+ sendTo: sendTo,
1039
+ usersModule: usersModule,
1040
+ projectAccess: projectAccess,
1041
+ opts: opts,
1042
+ getSessionForWs: getSessionForWs,
1043
+ });
1044
+
1023
1045
  // --- Filesystem handler (delegated to project-filesystem.js) ---
1024
1046
  var _filesystem = attachFilesystem({
1025
1047
  cwd: cwd,
@@ -1187,7 +1209,6 @@ function createProjectContext(opts) {
1187
1209
  // adapters for this project (see project-connection handleConnection).
1188
1210
  warmup: function () {
1189
1211
  sdk.warmup();
1190
- sdk.startIdleReaper();
1191
1212
  if (!osUsers && !sessionTitleMigrationScheduled) {
1192
1213
  sessionTitleMigrationScheduled = true;
1193
1214
  setTimeout(function () {
@@ -1201,6 +1222,12 @@ function createProjectContext(opts) {
1201
1222
  },
1202
1223
  });
1203
1224
 
1225
+ // The idle reaper runs from attach, not from the first WebSocket: a project
1226
+ // reached only over IPC (open-session, send-input, scheduled input, external
1227
+ // trigger, loop) would otherwise never reap its idle sessions. A repeated
1228
+ // start is a no-op in the bridge, and destroy() stops the timer.
1229
+ sdk.startIdleReaper();
1230
+
1204
1231
  // --- Destroy ---
1205
1232
  // opts.reason says why the project is going away. Only a daemon shutdown
1206
1233
  // (sessionReclaim.RESTART_REASON) records its live background agents as
@@ -1210,6 +1237,9 @@ function createProjectContext(opts) {
1210
1237
  function destroy(opts) {
1211
1238
  var daemonShutdown = !!opts && opts.reason === sessionReclaim.RESTART_REASON;
1212
1239
  var tally = opts && opts.tally;
1240
+ // Ended before the aborts below, which would otherwise record the
1241
+ // daemon going away as each session's own abort.
1242
+ if (daemonShutdown) promptsFor(sm).shutdown();
1213
1243
  _loop.stopTimer();
1214
1244
  stopAllWatches();
1215
1245
  // Abort all active sessions and clean up mention sessions
@@ -1251,6 +1281,7 @@ function createProjectContext(opts) {
1251
1281
  try { _localMcp.shutdown(); } catch (e) {}
1252
1282
  }
1253
1283
  for (var ws of clients) {
1284
+ _connection.recordDisconnect(ws);
1254
1285
  try { ws.close(); } catch (e) {}
1255
1286
  }
1256
1287
  clients.clear();
@@ -1282,11 +1313,13 @@ function createProjectContext(opts) {
1282
1313
  function getStatus() {
1283
1314
  var sessionCount = sm.sessions.size;
1284
1315
  var hasProcessing = false;
1316
+ var hasWaiting = false;
1285
1317
  // Every prompt awaiting the operator, of any kind, flags the project.
1286
1318
  var pendingPermCount = 0;
1287
1319
  var prompts = promptsFor(sm);
1288
1320
  sm.sessions.forEach(function (s) {
1289
1321
  if (s.isProcessing) hasProcessing = true;
1322
+ if (sessionLiveness.activityOf(s) === sessionLiveness.ACTIVITY.WAITING) hasWaiting = true;
1290
1323
  pendingPermCount += prompts.pendingCount(s);
1291
1324
  });
1292
1325
  var status = {
@@ -1300,6 +1333,7 @@ function createProjectContext(opts) {
1300
1333
  clients: clients.size,
1301
1334
  sessions: sessionCount,
1302
1335
  isProcessing: hasProcessing,
1336
+ waiting: hasWaiting,
1303
1337
  pendingPermissions: pendingPermCount,
1304
1338
  projectOwnerId: projectOwnerId,
1305
1339
  };
@@ -1399,6 +1433,8 @@ function createProjectContext(opts) {
1399
1433
  // The shared mode check for a session on its vendor, for a caller outside
1400
1434
  // the WebSocket handlers (session-input.js, which opens sessions).
1401
1435
  checkPermissionModeFor: function (session, mode) { return sdk.checkModeFor(session, mode, true); },
1436
+ // Whether the session's vendor takes an additive settings file.
1437
+ supportsSettingsFileFor: function (session) { return sdk.supportsSettingsFile(session); },
1402
1438
  // Ends the adapters' runtimes that nothing is using (see idle-adapter-reaper.js).
1403
1439
  reclaimIdleAdapters: function (idleMs) {
1404
1440
  return reclaimIdleAdapters(adapters, idleMs);
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+
3
+ // prompt-answer.js - answers one pending operator prompt for the answer-prompt
4
+ // verb. The answer goes through the prompt registry's respond(), the call a
5
+ // browser answer takes, so the kind validates it, the resolution effects run
6
+ // and the settle is recorded with its source; this module only finds the
7
+ // prompt and shapes the decision into the message the browser would have sent
8
+ // for that kind.
9
+ //
10
+ // Exactly once is the registry's: respond() settles a prompt or reports it
11
+ // stale, and it runs without yielding, so a browser answer and this one cannot
12
+ // both win.
13
+
14
+ var { promptsFor } = require("./prompt-registry");
15
+ var promptKinds = require("./prompt-kinds");
16
+ var codecs = require("./prompt-kinds/codecs");
17
+
18
+ var RESULT = Object.freeze({
19
+ ANSWERED: "answered",
20
+ NOT_FOUND: "not-found",
21
+ ALREADY_SETTLED: "already-settled",
22
+ INVALID: "invalid",
23
+ });
24
+
25
+ // Words that are verbs about a prompt, never the text of an answer.
26
+ var VERBS = ["allow", "allow_always", "deny"];
27
+
28
+ // History events that end a prompt, by the field that names its request.
29
+ var SETTLED_EVENTS = {
30
+ prompt_resolved: "requestId",
31
+ permission_resolved: "requestId",
32
+ elicitation_resolved: "requestId",
33
+ prompt_cancel: "requestId",
34
+ permission_cancel: "requestId",
35
+ ask_user_answered: "toolId",
36
+ };
37
+
38
+ function invalid(reason) {
39
+ return { invalid: reason };
40
+ }
41
+
42
+ // The message the browser sends for a decision on this kind of prompt, or
43
+ // { invalid } when the kind does not accept the decision. The registry's own
44
+ // parse() is more forgiving (an unknown permission decision reads as a deny), so
45
+ // the words are checked here: a typo must leave the prompt pending, not deny it.
46
+ function shapeDecision(prompt, decision) {
47
+ switch (prompt.kind) {
48
+ case "permission":
49
+ if (VERBS.indexOf(decision) === -1) return invalid("a permission prompt takes allow, allow_always or deny");
50
+ return { decision: decision };
51
+ case "plan": {
52
+ var planKind = promptKinds.KINDS.plan;
53
+ if (decision === "deny_with_feedback") return invalid("a plan rejected with feedback needs the feedback text, which this verb does not carry; use deny");
54
+ if (VERBS.indexOf(decision) === -1 && planKind.decisions.indexOf(decision) === -1) {
55
+ return invalid("a plan takes " + planKind.decisions.filter(function (d) { return d !== "deny_with_feedback"; }).concat(["allow_always"]).join(", "));
56
+ }
57
+ return { decision: decision };
58
+ }
59
+ case "ask_user": {
60
+ if (decision === "skip") return { decision: "skip" };
61
+ if (VERBS.indexOf(decision) !== -1) return invalid("a question takes the answer text, or skip");
62
+ var input = prompt.request && prompt.request.input;
63
+ if (!input || !Array.isArray(input.questions) || input.questions.length !== 1) {
64
+ return invalid("this prompt asks several questions at once; this verb answers a single question, or skips");
65
+ }
66
+ var answers = { 0: decision };
67
+ if (!Object.keys(codecs.askUser().normalizeAnswers(input, answers)).length) {
68
+ return invalid("the answer is empty or too long");
69
+ }
70
+ return { answers: answers };
71
+ }
72
+ case "elicitation":
73
+ if (decision === "allow") return { action: "accept" };
74
+ if (decision === "deny") return { action: "reject" };
75
+ return invalid("a request for input takes allow or deny");
76
+ default:
77
+ return invalid("this kind of prompt is not answered with a decision");
78
+ }
79
+ }
80
+
81
+ // Whether the session's recorded history shows the prompt as settled, and by
82
+ // whom: { settled, source }. A prompt that is not pending and was never
83
+ // recorded is unknown, not settled.
84
+ function settledInHistory(session, requestId) {
85
+ var history = session && Array.isArray(session.history) ? session.history : [];
86
+ for (var i = history.length - 1; i >= 0; i--) {
87
+ var e = history[i];
88
+ var field = e && SETTLED_EVENTS[e.type];
89
+ if (field && e[field] === requestId) return { settled: true, source: e.source || null };
90
+ }
91
+ return { settled: false, source: null };
92
+ }
93
+
94
+ function outcome(result, requestId, kind, source, extra) {
95
+ var out = Object.assign({ ok: result === RESULT.ANSWERED, result: result, requestId: requestId, kind: kind || null, source: source }, extra || {});
96
+ return out;
97
+ }
98
+
99
+ // req: { session, requestId, decision, source }
100
+ // session is the live session the request names. Returns the outcome object:
101
+ // { ok, result, requestId, kind, source, reason? }. Never resolves a prompt of
102
+ // another session, and never throws for a request that cannot be answered.
103
+ function answerPrompt(req) {
104
+ var session = req.session;
105
+ var registry = promptsFor(req.sm);
106
+ var found = registry.lookup(req.requestId, session);
107
+
108
+ if (!found || found.session !== session) {
109
+ var history = settledInHistory(session, req.requestId);
110
+ if (history.settled) {
111
+ return outcome(RESULT.ALREADY_SETTLED, req.requestId, null, req.source, {
112
+ reason: "the request is already settled",
113
+ settledBy: history.source,
114
+ });
115
+ }
116
+ return outcome(RESULT.NOT_FOUND, req.requestId, null, req.source, { reason: "no pending request with this id in the session" });
117
+ }
118
+
119
+ var kind = found.prompt.kind;
120
+ if (!promptKinds.operatorMayAnswer(kind)) {
121
+ return outcome(RESULT.NOT_FOUND, req.requestId, kind, req.source, { reason: "a request of kind " + kind + " is not answered by an operator" });
122
+ }
123
+ var shaped = shapeDecision(found.prompt, req.decision);
124
+ if (shaped.invalid) return outcome(RESULT.INVALID, req.requestId, kind, req.source, { reason: shaped.invalid });
125
+
126
+ var settled = registry.respond(req.requestId, shaped, {
127
+ session: session,
128
+ kinds: [kind],
129
+ responder: null,
130
+ source: req.source,
131
+ });
132
+ if (settled.status === "resolved") return outcome(RESULT.ANSWERED, req.requestId, kind, req.source);
133
+ if (settled.status === "invalid") {
134
+ return outcome(RESULT.INVALID, req.requestId, kind, req.source, { reason: String(settled.reason) });
135
+ }
136
+ // Settled between the lookup and the answer: the prompt is gone and its
137
+ // settle is in the history.
138
+ var after = settledInHistory(session, req.requestId);
139
+ return outcome(RESULT.ALREADY_SETTLED, req.requestId, kind, req.source, {
140
+ reason: "the request is already settled",
141
+ settledBy: after.source,
142
+ });
143
+ }
144
+
145
+ module.exports = { answerPrompt: answerPrompt, shapeDecision: shapeDecision, RESULT: RESULT };
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+
3
+ // The registry-wide bound on an unanswered operator prompt: daemon.json
4
+ // `promptExpiryMinutes`. Read at each open(), so an edit applies to the next
5
+ // prompt; a prompt already open keeps the deadline it was given.
6
+ //
7
+ // absent -> 1440 (24 hours)
8
+ // 0 -> no expiry
9
+ // positive number -> that many minutes
10
+ // anything else -> the default, with one warning naming the key
11
+ //
12
+ // Malformed means: not a number, negative, not finite, or beyond what a timer
13
+ // can hold (a larger value would make setTimeout fire at once).
14
+
15
+ var KEY = "promptExpiryMinutes";
16
+ var DEFAULT_MINUTES = 1440;
17
+ var MAX_TIMER_MS = 2147483647;
18
+
19
+ /**
20
+ * @returns {function(?object): number} (daemon config) -> expiry in ms, 0 for
21
+ * none. One reader per registry: it warns once per malformed value.
22
+ */
23
+ function createExpiryReader() {
24
+ var warned = Object.create(null);
25
+
26
+ function warnOnce(value) {
27
+ var id = typeof value + ":" + String(value);
28
+ if (warned[id]) return;
29
+ warned[id] = true;
30
+ console.warn("[prompt-registry] " + KEY + " must be 0 (no expiry) or a positive number of minutes; using the default of " + DEFAULT_MINUTES);
31
+ }
32
+
33
+ return function expiryMs(cfg) {
34
+ var v = cfg ? cfg[KEY] : undefined;
35
+ if (v === undefined || v === null) return DEFAULT_MINUTES * 60000;
36
+ if (typeof v !== "number" || !isFinite(v) || v < 0) {
37
+ warnOnce(v);
38
+ return DEFAULT_MINUTES * 60000;
39
+ }
40
+ if (v === 0) return 0;
41
+ var ms = Math.max(1, Math.round(v * 60000));
42
+ if (ms > MAX_TIMER_MS) {
43
+ warnOnce(v);
44
+ return DEFAULT_MINUTES * 60000;
45
+ }
46
+ return ms;
47
+ };
48
+ }
49
+
50
+ module.exports = { createExpiryReader: createExpiryReader, KEY: KEY, DEFAULT_MINUTES: DEFAULT_MINUTES };
@@ -49,7 +49,10 @@ var grantKeys = require("./grant-keys");
49
49
  var sessionReclaim = require("./session-reclaim");
50
50
  var { promptLabel } = require("./prompt-label");
51
51
  var promptSource = require("./prompt-source");
52
+ var { createExpiryReader } = require("./prompt-expiry");
52
53
  var { logField } = require("./log-field");
54
+ var { notifyFor } = require("./notify");
55
+ var { withPromptLabel } = require("./prompt-label");
53
56
  var { ownValue, putOwn, hasOwnKey } = codecs;
54
57
 
55
58
  var KINDS = promptKinds.KINDS;
@@ -62,6 +65,13 @@ function cancelReasonForAbort(signal) {
62
65
  return signal && signal.reason === "expired" ? "expired" : "aborted";
63
66
  }
64
67
 
68
+ // Who ended a prompt through its signal: the worker or app-server that gave up
69
+ // waiting ("expired"), otherwise the session's own abort, close or query end,
70
+ // which is what cancels every callback a query still has out.
71
+ function cancelSourceForAbort(signal) {
72
+ return signal && signal.reason === "expired" ? promptSource.CANCEL.WORKER : promptSource.CANCEL.SESSION_END;
73
+ }
74
+
65
75
  var RESOLVED_FIELDS = ["decision", "answers", "skipped", "action"];
66
76
 
67
77
  function deepFreeze(value) {
@@ -89,13 +99,13 @@ function terminalOf(e) {
89
99
  return e.requestId ? { id: e.requestId, state: Object.assign({ state: "resolved" }, pick(e, RESOLVED_FIELDS)) } : null;
90
100
  case "prompt_cancel":
91
101
  case "permission_cancel":
92
- return e.requestId ? { id: e.requestId, state: { state: "cancelled", reason: e.reason || null } } : null;
102
+ return e.requestId ? { id: e.requestId, state: { state: "cancelled", reason: e.reason || null, source: e.source || promptSource.CANCEL.UNSPECIFIED } } : null;
93
103
  case "ask_user_answered":
94
104
  if (!e.toolId) return null;
95
105
  if (e.answers && Object.keys(e.answers).length) return { id: e.toolId, state: { state: "resolved", answers: e.answers } };
96
106
  // A recorded skip is an answer, not an ending nobody chose.
97
107
  if (e.skipped === true) return { id: e.toolId, state: { state: "resolved", skipped: true } };
98
- return { id: e.toolId, state: { state: "cancelled", reason: null } };
108
+ return { id: e.toolId, state: { state: "cancelled", reason: null, source: promptSource.CANCEL.UNSPECIFIED } };
99
109
  default:
100
110
  return null;
101
111
  }
@@ -124,6 +134,8 @@ function openedBy(item) {
124
134
  * @param {function()} [deps.onProcessingChanged] - cross-project badge refresh.
125
135
  * @param {function(): string} [deps.getProjectName] - the project's display
126
136
  * name, read at each prompt so a rename shows on the next one.
137
+ * @param {function(): ?object} [deps.getConfig] - daemon.json, read at each
138
+ * open() for the unanswered-prompt bound (lib/prompt-expiry.js).
127
139
  * @param {function(): string} [deps.getProjectSlug] - the project's slug, which
128
140
  * the lifecycle log lines carry because console session ids repeat across
129
141
  * projects.
@@ -137,6 +149,10 @@ function createPromptRegistry(deps) {
137
149
  var onProcessingChanged = deps.onProcessingChanged || function () {};
138
150
  var getProjectName = deps.getProjectName || function () { return ""; };
139
151
  var getProjectSlug = deps.getProjectSlug || function () { return ""; };
152
+ var getPushModule = deps.getPushModule || function () { return null; };
153
+ // daemon.json, read at each open(); null when there is none.
154
+ var getConfig = deps.getConfig || function () { return null; };
155
+ var expiryMs = createExpiryReader();
140
156
 
141
157
  // Project-scope prompts (no session): requestId -> record.
142
158
  var projectPrompts = Object.create(null);
@@ -185,9 +201,30 @@ function createPromptRegistry(deps) {
185
201
  return null;
186
202
  }
187
203
 
188
- function dismissNotification(requestId) {
204
+ // The one close for a settled prompt: the core closes its banner and its
205
+ // push on every surface. The keys come from the target alone, so this holds
206
+ // after a restart and during the shutdown settle. A question's notification
207
+ // is keyed by its tool-use id, which is its request id unless another prompt
208
+ // already held that id. With no session to name (a project-level prompt, or a
209
+ // stale answer no session claims) only the request's banners are retired.
210
+ function closeNotifications(session, requestId, record) {
211
+ // A request id that is no string (a malformed client message) names no
212
+ // prompt, and must not widen the close to the session's own notification.
213
+ if (typeof requestId !== "string") return;
214
+ var core = notifyFor(getPushModule(), getNotificationsModule());
215
+ var slug = getProjectSlug();
216
+ if (!session) {
217
+ core.resolve({ slug: slug, requestId: requestId });
218
+ return;
219
+ }
220
+ var audience = { ownerId: session.ownerId };
221
+ var scope = { slug: slug, sessionId: session.localId };
222
+ var ids = [requestId];
223
+ if (record && record.toolUseId && record.toolUseId !== requestId) ids.push(record.toolUseId);
224
+ core.resolve(ids.map(function (id) { return Object.assign({ requestId: id }, scope); }), audience);
225
+ // A reminder that names this prompt is now wrong, or gone.
189
226
  var nm = getNotificationsModule();
190
- if (nm && typeof nm.dismissByRequestId === "function") nm.dismissByRequestId(requestId);
227
+ if (nm && typeof nm.reconcileReminders === "function") nm.reconcileReminders();
191
228
  }
192
229
 
193
230
  function ownerTaskOf(session, record) {
@@ -271,7 +308,7 @@ function createPromptRegistry(deps) {
271
308
  var detach = detachers.get(entry.record);
272
309
  if (detach) detach();
273
310
  if (entry.kind.journal) {
274
- dismissNotification(requestId);
311
+ closeNotifications(session, requestId, entry.record);
275
312
  if (event) sendAndRecord(session, event);
276
313
  onProcessingChanged();
277
314
  if (info) logSettled(session, requestId, entry, info);
@@ -286,14 +323,17 @@ function createPromptRegistry(deps) {
286
323
  return true;
287
324
  }
288
325
 
326
+ // opts.source is one of lib/prompt-source.js's cancel sources; a missing or
327
+ // unknown one is recorded as "unspecified" with a warning.
289
328
  function cancelEntry(session, requestId, entry, reason, opts) {
329
+ var source = promptSource.cancelSource(opts && opts.source, reason);
290
330
  var event = (entry.kind.journal && !(opts && opts.record === false))
291
- ? { type: "prompt_cancel", requestId: requestId, kind: entry.kind.name, reason: reason }
331
+ ? { type: "prompt_cancel", requestId: requestId, kind: entry.kind.name, reason: reason, source: source }
292
332
  : null;
293
333
  return settle(session, requestId, entry, entry.kind.cancelled(reason), event, {
294
334
  status: "cancelled",
295
335
  reason: reason,
296
- source: (opts && opts.source) || promptSource.fromCancel(reason),
336
+ source: source,
297
337
  });
298
338
  }
299
339
 
@@ -324,9 +364,12 @@ function createPromptRegistry(deps) {
324
364
  * decides sub-agent ownership.
325
365
  * @param {AbortSignal} [opts.signal] - ends the prompt (aborted, or
326
366
  * expired when the signal's reason is "expired").
327
- * @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.
367
+ * @param {number} [opts.timeoutMs] - ends the prompt as expired. A prompt
368
+ * with neither this nor a kind default that a person answers is bounded
369
+ * by daemon.json promptExpiryMinutes instead.
370
+ * @param {object} [opts.notification] - permission_request banner
371
+ * content (title, body, slug, ...), delivered through the notification
372
+ * core and closed with it when the prompt settles.
330
373
  * @returns {{requestId: string, answer: Promise<*>, pending: boolean}}
331
374
  * pending is false when its signal was already aborted: no prompt was
332
375
  * opened or announced, and answer carries the kind's cancelled value.
@@ -377,29 +420,54 @@ function createPromptRegistry(deps) {
377
420
 
378
421
  var cleanups = [];
379
422
  if (signal && typeof signal.addEventListener === "function") {
380
- var onAbort = function () { cancelEntry(owner, requestId, entry, cancelReasonForAbort(signal)); };
423
+ var onAbort = function () { cancelEntry(owner, requestId, entry, cancelReasonForAbort(signal), { source: cancelSourceForAbort(signal) }); };
381
424
  signal.addEventListener("abort", onAbort, { once: true });
382
425
  if (typeof signal.removeEventListener === "function") {
383
426
  cleanups.push(function () { signal.removeEventListener("abort", onAbort); });
384
427
  }
385
428
  }
386
429
  var timeoutMs = opts.timeoutMs != null ? opts.timeoutMs : kind.defaultTimeoutMs;
430
+ // The deadline is fixed here, from the opening, and nothing later (a
431
+ // reconnect, a replay, a history page) touches the timer. A kind's own
432
+ // timeout wins; the setting bounds only a prompt a person answers.
433
+ var bounded = timeoutMs != null;
434
+ if (!bounded && kind.journal) timeoutMs = expiryMs(getConfig());
387
435
  if (timeoutMs) {
388
436
  var timer = setTimeout(function () {
389
- cancelEntry(owner, requestId, entry, "expired", { source: promptSource.fromTimeout() });
437
+ cancelEntry(owner, requestId, entry, "expired", { source: promptSource.CANCEL.TIMEOUT });
390
438
  }, timeoutMs);
439
+ // The long default must not hold a process open; a kind's own short
440
+ // timeout keeps its existing behaviour.
441
+ if (!bounded && typeof timer.unref === "function") timer.unref();
391
442
  cleanups.push(function () { clearTimeout(timer); });
392
443
  }
393
444
  if (cleanups.length) {
394
445
  detachers.set(record, function () { cleanups.forEach(function (fn) { fn(); }); });
395
446
  }
396
447
 
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
- }
448
+ // No banner for a sessionless prompt, by design and symmetrically with the
449
+ // close: a prompt without a session is a project-scope kind (the browser
450
+ // extension's commands), which a program answers, never a person, and is
451
+ // not journalled. There is nothing to alert, so nothing is created that a
452
+ // later close would have to retire. A journalled kind is always scoped to
453
+ // a session, so this guard never withholds a banner from a prompt a person
454
+ // answers.
455
+ if (kind.journal && opts.notification && session) {
456
+ var kindFields = typeof kind.notificationFields === "function" ? kind.notificationFields(record) : {};
457
+ var pushText = opts.notification.push || null;
458
+ var banner = Object.assign({}, opts.notification, kindFields, labelFields(record), { kind: kind.name });
459
+ delete banner.push;
460
+ // One notify() per prompt: the emitter supplies the text of each surface
461
+ // and the core picks the surfaces from the type's registration. The
462
+ // audience is the session's own, for the push and the banner alike.
463
+ notifyFor(getPushModule(), getNotificationsModule()).notify("permission_request", {
464
+ slug: getProjectSlug(),
465
+ sessionId: session.localId,
466
+ requestId: requestId,
467
+ }, {
468
+ push: pushText ? { title: pushText.title, body: withPromptLabel(record.label, pushText.body) } : null,
469
+ banner: banner,
470
+ }, { ownerId: session.ownerId || null });
403
471
  }
404
472
  return { requestId: requestId, answer: answer, pending: true, label: record.label || null };
405
473
  }
@@ -471,7 +539,7 @@ function createPromptRegistry(deps) {
471
539
  opts = opts || {};
472
540
  var found = find(requestId, opts.session);
473
541
  if (!found) {
474
- dismissNotification(requestId);
542
+ closeNotifications(opts.session || null, requestId, null);
475
543
  return { status: "stale" };
476
544
  }
477
545
  if (opts.kinds && opts.kinds.indexOf(found.kind.name) === -1) return { status: "stale" };
@@ -517,7 +585,7 @@ function createPromptRegistry(deps) {
517
585
  function endTurn(session) {
518
586
  cancelWhere(session, "turn_ended", function (record) {
519
587
  return !ownedByTrackedTask(session, record);
520
- });
588
+ }, { source: promptSource.CANCEL.SESSION_END });
521
589
  }
522
590
 
523
591
  /**
@@ -532,7 +600,7 @@ function createPromptRegistry(deps) {
532
600
  cancelWhere(session, "query_ended", function (record) {
533
601
  var ours = record.query ? record.query === query : !!ownsSession;
534
602
  return ours && !ownedByTrackedTask(session, record);
535
- });
603
+ }, { source: promptSource.CANCEL.SESSION_END });
536
604
  if (ownsSession) pruneTasks(session);
537
605
  }
538
606
 
@@ -541,7 +609,11 @@ function createPromptRegistry(deps) {
541
609
  pruneTasks(session);
542
610
  }
543
611
 
544
- /** End every prompt of a session (rewind, context clear, deletion). */
612
+ /**
613
+ * End every prompt of a session (rewind, context clear, deletion).
614
+ * opts.source names who ended them (lib/prompt-source.js); opts.record false
615
+ * keeps the ending out of history.
616
+ */
545
617
  function cancelSession(session, reason, opts) {
546
618
  cancelWhere(session, reason, function () { return true; }, opts);
547
619
  session.activeTaskToolIds = Object.create(null);
@@ -557,11 +629,11 @@ function createPromptRegistry(deps) {
557
629
  Object.keys(index).forEach(function (id) { localIds.add(index[id]); });
558
630
  localIds.forEach(function (localId) {
559
631
  var session = getSession ? getSession(localId) : null;
560
- if (session) cancelWhere(session, "shutdown", function () { return true; });
632
+ if (session) cancelWhere(session, "shutdown", function () { return true; }, { source: promptSource.CANCEL.DAEMON_RESTART });
561
633
  });
562
634
  Object.keys(projectPrompts).forEach(function (id) {
563
635
  var record = projectPrompts[id];
564
- if (record) cancelEntry(null, id, entryOf(null, record), "shutdown");
636
+ if (record) cancelEntry(null, id, entryOf(null, record), "shutdown", { source: promptSource.CANCEL.DAEMON_RESTART });
565
637
  });
566
638
  }
567
639
 
@@ -679,6 +751,7 @@ function createPromptRegistry(deps) {
679
751
  return entries(session).filter(function (e) { return e.kind.journal; }).map(function (e) {
680
752
  return {
681
753
  requestId: e.id,
754
+ toolUseId: typeof e.record.toolUseId === "string" ? e.record.toolUseId : null,
682
755
  kind: e.kind.name,
683
756
  toolName: typeof e.record.toolName === "string" ? e.record.toolName : null,
684
757
  agent: (e.record.label && e.record.label.agent) || "",
@@ -723,7 +796,7 @@ function createPromptRegistry(deps) {
723
796
  if (!state) {
724
797
  var mayStillOpen = item.type === "tool_executing" && !askBeforeTurnEnd.has(item);
725
798
  if (mayStillOpen) return item;
726
- state = { state: "cancelled", reason: "stale" };
799
+ state = { state: "cancelled", reason: "stale", source: promptSource.CANCEL.UNSPECIFIED };
727
800
  }
728
801
  return Object.assign({}, item, { promptState: state });
729
802
  };