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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +10 -0
  3. package/lib/activity-clock.js +23 -0
  4. package/lib/agent-dispatch-tool.js +20 -0
  5. package/lib/build-changes.js +79 -0
  6. package/lib/build-identity.js +192 -0
  7. package/lib/build-monitor.js +125 -0
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-offer.js +141 -0
  10. package/lib/build-update-restart.js +142 -0
  11. package/lib/build-update-standing.js +184 -0
  12. package/lib/cli/daemon-launch.js +8 -5
  13. package/lib/cli/ipc-subcommands.js +6 -0
  14. package/lib/cli/session-subcommands.js +122 -0
  15. package/lib/cli-sessions.js +8 -1
  16. package/lib/cli-transcript-title.js +131 -0
  17. package/lib/codex-defaults.js +8 -2
  18. package/lib/daemon-projects.js +19 -0
  19. package/lib/daemon.js +166 -127
  20. package/lib/debug-log.js +17 -0
  21. package/lib/exit-flush.js +44 -0
  22. package/lib/grant-keys.js +179 -0
  23. package/lib/log-field.js +34 -0
  24. package/lib/memory-shed.js +13 -32
  25. package/lib/project-connection.js +14 -0
  26. package/lib/project-external-trigger.js +91 -123
  27. package/lib/project-http.js +2 -0
  28. package/lib/project-loop.js +5 -4
  29. package/lib/project-notifications.js +4 -0
  30. package/lib/project-prompt-responses.js +7 -5
  31. package/lib/project-session-grants.js +73 -0
  32. package/lib/project-sessions.js +55 -68
  33. package/lib/project-user-message.js +13 -25
  34. package/lib/project.js +25 -5
  35. package/lib/prompt-kinds/permission.js +18 -0
  36. package/lib/prompt-label.js +60 -0
  37. package/lib/prompt-registry.js +123 -13
  38. package/lib/prompt-source.js +65 -0
  39. package/lib/public/css/diagnostics.css +30 -0
  40. package/lib/public/css/notifications-center.css +15 -0
  41. package/lib/public/css/overlays.css +18 -0
  42. package/lib/public/css/rewind.css +8 -0
  43. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  44. package/lib/public/modules/app-messages.js +10 -2
  45. package/lib/public/modules/app-notifications.js +9 -1
  46. package/lib/public/modules/app-panels.js +0 -1
  47. package/lib/public/modules/build-update-detail.js +54 -0
  48. package/lib/public/modules/diagnostics.js +126 -20
  49. package/lib/public/modules/prompt-banner.js +12 -0
  50. package/lib/public/modules/prompt-kinds/permission-choices.js +6 -1
  51. package/lib/public/modules/prompt-kinds/permission.js +15 -0
  52. package/lib/public/modules/prompt-label.js +44 -0
  53. package/lib/public/modules/prompts.js +9 -0
  54. package/lib/public/modules/session-grants.js +131 -0
  55. package/lib/public/modules/sidebar-sessions.js +11 -0
  56. package/lib/public/modules/tools.js +14 -2
  57. package/lib/public/modules/vendor-picker.js +2 -2
  58. package/lib/public/modules/vendor-registry.js +11 -2
  59. package/lib/runtime-env.js +1 -1
  60. package/lib/sdk-bridge.js +114 -115
  61. package/lib/sdk-message-processor.js +25 -87
  62. package/lib/sdk-skill-discovery.js +65 -60
  63. package/lib/server.js +15 -2
  64. package/lib/session-ai-title.js +80 -0
  65. package/lib/session-id.js +33 -0
  66. package/lib/session-input-ipc.js +32 -0
  67. package/lib/session-input.js +409 -0
  68. package/lib/session-reclaim.js +284 -0
  69. package/lib/session-resume.js +172 -0
  70. package/lib/sessions.js +31 -21
  71. package/lib/supervisor.js +39 -0
  72. package/lib/turn-initiator.js +108 -0
  73. package/lib/utils.js +9 -47
  74. package/lib/vendor-registry-message.js +1 -0
  75. package/lib/ws-schema.js +9 -4
  76. package/lib/yoke/adapters/claude-vendor.js +0 -1
  77. package/lib/yoke/adapters/claude-worker.js +6 -4
  78. package/lib/yoke/adapters/claude.js +29 -86
  79. package/lib/yoke/adapters/codex-capabilities.js +9 -6
  80. package/lib/yoke/adapters/codex-vendor.js +15 -15
  81. package/lib/yoke/adapters/codex.js +125 -136
  82. package/lib/yoke/auth-checks.js +8 -21
  83. package/lib/yoke/codex-app-server.js +27 -71
  84. package/lib/yoke/codex-binary.js +254 -0
  85. package/lib/yoke/codex-command.js +122 -0
  86. package/lib/yoke/codex-protocol.js +96 -0
  87. package/lib/yoke/codex-version.js +135 -0
  88. package/lib/yoke/index.js +20 -4
  89. package/lib/yoke/install-probe.js +21 -6
  90. package/lib/yoke/interface.js +14 -12
  91. package/lib/yoke/registry.js +41 -4
  92. package/package.json +1 -2
  93. package/scripts/verify-installed-build.js +59 -17
  94. package/lib/lore-attestation.js +0 -73
@@ -75,6 +75,10 @@ var formatters = {
75
75
  // So the banner offers the answers the card does (see prompt-banner.js).
76
76
  suppressAlwaysAllowRule: data.suppressAlwaysAllowRule === true ? true : undefined,
77
77
  defaultToNo: data.defaultToNo === true ? true : undefined,
78
+ // Who asked and what Allow for session would grant: a banner reaches
79
+ // every client whatever project it is viewing.
80
+ label: data.label || null,
81
+ grantScope: typeof data.grantScope === "string" ? data.grantScope : null,
78
82
  },
79
83
  };
80
84
  },
@@ -15,6 +15,8 @@ var { promptsFor } = require("./prompt-registry");
15
15
  var promptKinds = require("./prompt-kinds");
16
16
  var { mayAnswerPrompt } = require("./prompt-access");
17
17
  var { ownValue } = require("./prompt-kinds/codecs");
18
+ var { INITIATORS } = require("./turn-initiator");
19
+ var promptSource = require("./prompt-source");
18
20
 
19
21
  // alias type -> { toPrompt(msg), kinds it may answer, stale reply type }
20
22
  var LEGACY_RESPONSES = {
@@ -75,7 +77,7 @@ function attachPromptResponses(ctx) {
75
77
  sm.appendToSessionFile(session, userMsg);
76
78
  sendToSession(session.localId, userMsg);
77
79
  if (session.isProcessing) {
78
- sdk.pushMessage(session, text);
80
+ sdk.pushMessage(session, text, undefined, INITIATORS.HUMAN);
79
81
  return;
80
82
  }
81
83
  session.isProcessing = true;
@@ -83,9 +85,9 @@ function attachPromptResponses(ctx) {
83
85
  session.sentToolResults = {};
84
86
  sendToSession(session.localId, { type: "status", status: "processing" });
85
87
  if (!session.queryInstance && !session.worker) {
86
- sdk.startQuery(session, text, undefined, ensureProjectAccessForSession(session));
88
+ sdk.startQuery(session, text, undefined, ensureProjectAccessForSession(session), INITIATORS.HUMAN);
87
89
  } else {
88
- sdk.pushMessage(session, text);
90
+ sdk.pushMessage(session, text, undefined, INITIATORS.HUMAN);
89
91
  }
90
92
  }
91
93
 
@@ -136,7 +138,7 @@ function attachPromptResponses(ctx) {
136
138
  newSession.sentToolResults = {};
137
139
  sendToSession(newSession.localId, { type: "status", status: "processing" });
138
140
  newSession.acceptEditsAfterStart = true;
139
- sdk.startQuery(newSession, planPrompt, undefined, ensureProjectAccessForSession(newSession));
141
+ sdk.startQuery(newSession, planPrompt, undefined, ensureProjectAccessForSession(newSession), INITIATORS.HUMAN);
140
142
  } catch (e) {
141
143
  console.error("[project] Error starting plan execution:", e);
142
144
  if (ws) sendTo(ws, { type: "error", text: "Failed to start plan execution: " + (e.message || e) });
@@ -177,7 +179,7 @@ function attachPromptResponses(ctx) {
177
179
  function answer(ws, msg, kinds, staleReplyType) {
178
180
  var answerable = kinds.every(promptKinds.operatorMayAnswer) && mayAnswer(ws, msg.requestId);
179
181
  var outcome = answerable
180
- ? promptsFor(sm).respond(msg.requestId, msg, { session: getSessionForWs(ws), kinds: kinds, responder: ws })
182
+ ? promptsFor(sm).respond(msg.requestId, msg, { session: getSessionForWs(ws), kinds: kinds, responder: ws, source: promptSource.fromWs(ws) })
181
183
  : { status: "stale" };
182
184
  if (outcome.status === "resolved") return;
183
185
  // Refused as it stands: still pending, so re-offer it to the responder,
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+
3
+ // WS entry point for a session's "Allow for Session" grants: list them and
4
+ // revoke one. The grants themselves live in the prompt registry
5
+ // (lib/prompt-registry.js, session.allowedTools); this module only maps the
6
+ // wire messages onto it and applies the same access rule as answering a
7
+ // prompt (lib/prompt-access.js), because revoking is the operator's decision
8
+ // about that session and listing shows what its agent may do unasked.
9
+
10
+ var { promptsFor } = require("./prompt-registry");
11
+ var { mayAnswerPrompt } = require("./prompt-access");
12
+
13
+ /**
14
+ * ctx fields: sm, sendTo, sendToSessionOthers, getSessionForWs
15
+ */
16
+ function attachSessionGrants(ctx) {
17
+ var sm = ctx.sm;
18
+ var sendTo = ctx.sendTo;
19
+ var sendToSessionOthers = ctx.sendToSessionOthers;
20
+ var getSessionForWs = ctx.getSessionForWs;
21
+
22
+ // The session a message names (the connection's own when it names none), if
23
+ // the connection may act on it.
24
+ function sessionFor(ws, msg) {
25
+ var session = msg.sessionId === undefined || msg.sessionId === null
26
+ ? getSessionForWs(ws)
27
+ : (typeof msg.sessionId === "number" && sm.sessions ? sm.sessions.get(msg.sessionId) : null);
28
+ if (!session || !mayAnswerPrompt(ws && ws._clagenticUser, session)) return null;
29
+ return session;
30
+ }
31
+
32
+ function grantsMessage(session) {
33
+ return { type: "session_grants", sessionId: session.localId, grants: promptsFor(sm).listGrants(session) };
34
+ }
35
+
36
+ // Said, not dropped, so the client can re-enable its button. It names nothing
37
+ // about the session, which this user may not see.
38
+ function unavailableMessage(msg) {
39
+ return { type: "session_grants", sessionId: msg.sessionId, error: "that session is not available to you" };
40
+ }
41
+
42
+ /** Returns true when msg was a grants message (handled). */
43
+ function handleGrantMessage(ws, msg) {
44
+ if (msg.type === "list_session_grants") {
45
+ var listed = sessionFor(ws, msg);
46
+ if (!listed) {
47
+ sendTo(ws, unavailableMessage(msg));
48
+ return true;
49
+ }
50
+ sendTo(ws, grantsMessage(listed));
51
+ return true;
52
+ }
53
+ if (msg.type === "revoke_session_grant") {
54
+ var session = sessionFor(ws, msg);
55
+ if (!session) {
56
+ sendTo(ws, unavailableMessage(msg));
57
+ return true;
58
+ }
59
+ promptsFor(sm).revokeGrant(session, msg.key);
60
+ // Every client viewing the session sees the list as it now is, whether
61
+ // or not the key was still there.
62
+ var now = grantsMessage(session);
63
+ sendTo(ws, now);
64
+ sendToSessionOthers(ws, session.localId, now);
65
+ return true;
66
+ }
67
+ return false;
68
+ }
69
+
70
+ return { handleGrantMessage: handleGrantMessage };
71
+ }
72
+
73
+ module.exports = { attachSessionGrants: attachSessionGrants };
@@ -11,7 +11,9 @@ var agentsFavorites = require("./agents-favorites");
11
11
  var sessionActivity = require("./session-activity");
12
12
  var { promptsFor } = require("./prompt-registry");
13
13
  var { attachPromptResponses } = require("./project-prompt-responses");
14
+ var { attachSessionGrants } = require("./project-session-grants");
14
15
  var { ownValue } = require("./prompt-kinds/codecs");
16
+ var { logField, logText } = require("./log-field");
15
17
  var { isKnownVendor } = require("./yoke");
16
18
  var sessionCapabilities = require("./session-capabilities");
17
19
  // Kick off SDK agent discovery in the background at module load.
@@ -149,6 +151,12 @@ function attachSessions(ctx) {
149
151
  onProcessingChanged: onProcessingChanged,
150
152
  ensureProjectAccessForSession: ensureProjectAccessForSession,
151
153
  });
154
+ var sessionGrants = attachSessionGrants({
155
+ sm: sm,
156
+ sendTo: sendTo,
157
+ sendToSessionOthers: sendToSessionOthers,
158
+ getSessionForWs: getSessionForWs,
159
+ });
152
160
 
153
161
  function sessionAcceptsMode(session, mode) {
154
162
  if (!ownValue(CAPABILITY_GATED_MODES, mode)) return true;
@@ -159,6 +167,7 @@ function attachSessions(ctx) {
159
167
  function handleSessionsMessage(ws, msg) {
160
168
 
161
169
  if (promptResponses.handlePromptMessage(ws, msg)) return true;
170
+ if (sessionGrants.handleGrantMessage(ws, msg)) return true;
162
171
 
163
172
  if (msg.type === "push_subscribe") {
164
173
  var _pushUserId = ws._clagenticUser ? ws._clagenticUser.id : null;
@@ -488,60 +497,16 @@ function attachSessions(ctx) {
488
497
 
489
498
  if (msg.type === "resume_session") {
490
499
  if (!msg.cliSessionId) return true;
491
- var cliSess = require("./cli-sessions");
492
-
493
- // If Clay already has a persisted meta file for this cliSessionId, read
494
- // its vendor so resumeSession doesn't silently default to the project's
495
- // primary vendor (which would break codex sessions after server restart).
496
- // Also read allowedTools (lr-8b2e) so a previously-granted "allow for
497
- // session" decision survives this rehydration path instead of
498
- // re-prompting — resumeSession() itself defaults to {} when absent.
499
- var persistedVendor = null;
500
- var persistedAllowedTools = null;
501
- try {
502
- var _fsResume = require("fs");
503
- var _pathResume = require("path");
504
- var metaPath = _pathResume.join(sm.sessionsDir, msg.cliSessionId + ".jsonl");
505
- if (_fsResume.existsSync(metaPath)) {
506
- var firstLine = _fsResume.readFileSync(metaPath, "utf8").split("\n", 1)[0];
507
- try {
508
- var metaObj = JSON.parse(firstLine);
509
- if (metaObj && metaObj.type === "meta" && metaObj.vendor) persistedVendor = metaObj.vendor;
510
- // Sanitize before it ever reaches resumeSession() (lr-8b2e
511
- // hardening) — a crafted meta record must not be able to
512
- // auto-approve a tool with no operator click.
513
- if (metaObj && metaObj.type === "meta" && metaObj.allowedTools) {
514
- persistedAllowedTools = utils.sanitizeAllowedTools(metaObj.allowedTools);
515
- }
516
- } catch (e) {}
517
- }
518
- } catch (e) {}
519
-
520
- // Try SDK for title first, then fall back to manual parsing
521
- var titlePromise = adapter.getSessionInfo(msg.cliSessionId, { dir: cwd }).then(function(info) {
522
- return (info && info.summary) ? info.summary.substring(0, 100) : null;
523
- }).catch(function() { return null; });
524
-
525
- Promise.all([
526
- cliSess.readCliSessionHistory(cwd, msg.cliSessionId),
527
- titlePromise
528
- ]).then(function(results) {
529
- var history = results[0];
530
- var sdkTitle = results[1];
531
- var title = sdkTitle || "Resumed session";
532
- if (!sdkTitle) {
533
- for (var i = 0; i < history.length; i++) {
534
- if (history[i].type === "user_message" && history[i].text) {
535
- title = history[i].text.substring(0, 50);
536
- break;
537
- }
538
- }
539
- }
540
- var resumed = sm.resumeSession(msg.cliSessionId, { history: history, title: title, vendor: persistedVendor || undefined, allowedTools: persistedAllowedTools || undefined }, ws);
541
- if (resumed) ws._clagenticActiveSession = resumed.localId;
542
- }).catch(function() {
543
- var resumed = sm.resumeSession(msg.cliSessionId, (persistedVendor || persistedAllowedTools) ? { vendor: persistedVendor, allowedTools: persistedAllowedTools } : undefined, ws);
500
+ // The resume that injected input uses too (session-resume.js): vendor,
501
+ // agent and granted tools come from the stored meta record, so a resume
502
+ // never silently falls back to the project's default vendor.
503
+ require("./session-resume").resumeStoredSession({ sm: sm, adapter: adapter, cwd: cwd }, msg.cliSessionId, { ws: ws }).then(function (resumed) {
544
504
  if (resumed) ws._clagenticActiveSession = resumed.localId;
505
+ }, function (err) {
506
+ console.error("[project-sessions] resume_session failed: project=" + logField(slug)
507
+ + " session=" + logField(msg.cliSessionId) + " reason="
508
+ + logText(err && err.message ? err.message : err));
509
+ sendTo(ws, { type: "error", text: "Could not resume this session: " + (err && err.message ? err.message : err) });
545
510
  });
546
511
  return true;
547
512
  }
@@ -1182,7 +1147,7 @@ function attachSessions(ctx) {
1182
1147
  }
1183
1148
  }
1184
1149
 
1185
- // Notify adapter of conversation rollback (e.g. Codex thread/rollback)
1150
+ // Notify adapter of conversation rollback (e.g. Codex, which refuses)
1186
1151
  // BEFORE trimming: when the adapter cannot roll its thread back, the
1187
1152
  // rewind fails (the catch below reports it) and the local history is
1188
1153
  // left as it was, so the two never disagree.
@@ -1840,23 +1805,45 @@ function attachSessions(ctx) {
1840
1805
  return true;
1841
1806
  }
1842
1807
 
1843
- // lr-e85fec: operator-initiated adoption of an installed-but-not-yet-
1844
- // running build (the "Restart to apply update" action offered by the
1845
- // build-update diagnostic). Same admin gate and same in-process wiring
1846
- // pattern as restart_server above — the only difference is
1847
- // onRestartForBuildUpdate waits for in-flight sessions to finish (bounded)
1848
- // before restarting, since this restart is a maintenance action the
1849
- // operator chose at a moment of their own choosing, not an emergency.
1808
+ // Operator-initiated adoption of an installed-but-not-yet-running build.
1809
+ // Same admin gate as restart_server above, but two steps, because this
1810
+ // restart ends sessions the operator may not be thinking about. A message
1811
+ // without confirmToken only asks for the offer: the reply names both
1812
+ // builds, the commits between them and the live sessions and background
1813
+ // agents a restart would end, and nothing restarts. The restart is
1814
+ // scheduled only by a message carrying the token of an offer the daemon
1815
+ // issued, and only if that offer is still true (lib/build-update-restart.js).
1850
1816
  if (msg.type === "restart_for_build_update") {
1851
- if (typeof opts.onRestartForBuildUpdate === "function") {
1852
- sendTo(ws, { type: "restart_for_build_update_result", ok: true });
1853
- send({ type: "toast", level: "info", message: "Restarting to apply the installed update..." });
1854
- setTimeout(function () {
1855
- opts.onRestartForBuildUpdate();
1856
- }, 500);
1857
- } else {
1817
+ if (typeof opts.onRestartForBuildUpdate !== "function") {
1858
1818
  sendTo(ws, { type: "restart_for_build_update_result", ok: false, error: "Restart not supported" });
1819
+ return true;
1859
1820
  }
1821
+ var buildToken = typeof msg.confirmToken === "string" ? msg.confirmToken : null;
1822
+ Promise.resolve(opts.onRestartForBuildUpdate(buildToken)).then(function (outcome) {
1823
+ if (outcome.status === "not_stale") {
1824
+ var nothingToApply = "No newer build is installed, so there is nothing to apply.";
1825
+ sendTo(ws, { type: "restart_for_build_update_result", ok: false, error: nothingToApply });
1826
+ sendTo(ws, { type: "error", text: nothingToApply });
1827
+ } else if (outcome.status === "confirm") {
1828
+ var offer = outcome.offer;
1829
+ sendTo(ws, { type: "restart_for_build_update_result", ok: false, needsConfirmation: true });
1830
+ sendTo(ws, {
1831
+ type: "diagnostic",
1832
+ severity: "warning",
1833
+ source: "build-update",
1834
+ message: (outcome.note ? outcome.note + "\n" : "") + offer.interruptionText,
1835
+ buildUpdate: offer,
1836
+ actionable: { label: "Restart now", action: "confirm_build_update_restart" },
1837
+ });
1838
+ } else {
1839
+ sendTo(ws, { type: "restart_for_build_update_result", ok: true });
1840
+ send({ type: "toast", level: "info", message: "Restarting to apply the installed update. Running turns get up to " + (outcome.waitSeconds || 60) + " seconds to finish first." });
1841
+ }
1842
+ }).catch(function (e) {
1843
+ console.error("[project] restart_for_build_update failed:", e && e.message ? e.message : e);
1844
+ sendTo(ws, { type: "restart_for_build_update_result", ok: false, error: "Could not prepare the restart offer" });
1845
+ sendTo(ws, { type: "error", text: "Could not prepare the restart offer. Nothing was restarted." });
1846
+ });
1860
1847
  return true;
1861
1848
  }
1862
1849
 
@@ -3,6 +3,8 @@ var fs = require("fs");
3
3
  var { promptsFor } = require("./prompt-registry");
4
4
  var { putOwn } = require("./prompt-kinds/codecs");
5
5
  var { isKnownVendor } = require("./yoke");
6
+ var { INITIATORS } = require("./turn-initiator");
7
+ var promptSource = require("./prompt-source");
6
8
 
7
9
  /**
8
10
  * Attach user-message handler and remaining small handlers
@@ -48,7 +50,7 @@ function truncateCodePointSafe(str, maxLen) {
48
50
  }
49
51
 
50
52
  // lr-62157d: pure helper — derives the FIRST-message provisional title
51
- // (before any turn has completed / before autoGenerateTitle can run).
53
+ // (before any turn has completed / before the CLI has written its own title).
52
54
  // Prefers real message text; falls back to the first paste when text is
53
55
  // empty (a >=500-char paste is diverted server-side into msg.pastes[] with
54
56
  // msg.text empty by the client's paste-chip handling — see input.js — so
@@ -297,7 +299,7 @@ function attachUserMessage(ctx) {
297
299
  // authenticated client's extension_result is ignored.
298
300
  if (msg.type === "extension_result") {
299
301
  if (!mayAnswerExtensionCommand(msg.requestId, ws)) return true;
300
- promptsFor(sm).respond(msg.requestId, { result: msg.result }, { kinds: ["extension"] });
302
+ promptsFor(sm).respond(msg.requestId, { result: msg.result }, { kinds: ["extension"], source: promptSource.fromWs(ws) });
301
303
  return true;
302
304
  }
303
305
 
@@ -338,10 +340,6 @@ function attachUserMessage(ctx) {
338
340
  if (msg.type === "send_scheduled_now") {
339
341
  var nowSession = getSessionForWs(ws);
340
342
  if (!nowSession || !nowSession.scheduledMessage) return true;
341
- // lr-f7c100: reachable only via a live WS client explicitly forcing a
342
- // scheduled send — same human-presence rationale as the "message"
343
- // handler above.
344
- nowSession.humanOriginated = true;
345
343
  var schedText = nowSession.scheduledMessage.text;
346
344
  clearTimeout(nowSession.scheduledMessage.timer);
347
345
  nowSession.scheduledMessage = null;
@@ -357,7 +355,9 @@ function attachUserMessage(ctx) {
357
355
  nowSession.isProcessing = true;
358
356
  onProcessingChanged();
359
357
  sendToSession(nowSession.localId, { type: "status", status: "processing" });
360
- sdk.startQuery(nowSession, schedText, null, ensureProjectAccessForSession(nowSession));
358
+ // A person forced the send, but the text is the one scheduled earlier:
359
+ // it is a scheduled turn that fired manually, not typed text.
360
+ sdk.startQuery(nowSession, schedText, null, ensureProjectAccessForSession(nowSession), INITIATORS.SCHEDULED_NOW);
361
361
  sm.broadcastSessionList();
362
362
  return true;
363
363
  }
@@ -380,18 +380,6 @@ function attachUserMessage(ctx) {
380
380
  return true;
381
381
  }
382
382
 
383
- // lr-f7c100: this handler is reachable ONLY via a live WebSocket client
384
- // sending a {type:"message"} frame — headless session drivers
385
- // (project-loop.js's Ralph Loop iterations, project-external-trigger.js,
386
- // scheduler.js) build their own history entries and call sdk.startQuery
387
- // directly, never through here. That makes this the one structural (not
388
- // heuristic) point in the codebase where "a human is in this session" is
389
- // true by construction, independent of session state that a headless
390
- // caller could otherwise set. Sticky once set — later processing (e.g. a
391
- // scheduled message firing for the same session) never has a chance to
392
- // clear it, matching the "a session mints iff a human is in it" rule.
393
- session.humanOriginated = true;
394
-
395
383
  // Bind vendor to session on first message (if not already set)
396
384
  if (!session.vendor && isKnownVendor(msg.vendor)) {
397
385
  session.vendor = msg.vendor;
@@ -442,9 +430,9 @@ function attachUserMessage(ctx) {
442
430
 
443
431
  if (!session.title) {
444
432
  session.title = deriveProvisionalTitle(msg);
445
- // This is only a provisional title — autoGenerateTitle (sdk-bridge.js)
446
- // is allowed to overwrite it once a real LLM-generated title is ready,
447
- // as long as the user hasn't manually renamed the session since.
433
+ // This is only a provisional title — session-ai-title.js replaces it
434
+ // once the CLI has written its own title, as long as the user hasn't
435
+ // manually renamed the session since.
448
436
  session.titleProvisional = true;
449
437
  sm.saveSessionFile(session);
450
438
  sm.broadcastSessionList();
@@ -580,12 +568,12 @@ function attachUserMessage(ctx) {
580
568
  // No active query (or worker idle between queries): start a new query
581
569
  session._queryStartTs = Date.now();
582
570
  console.log("[PERF] project.js: startQuery called, localId=" + session.localId + " t=0ms");
583
- sdk.startQuery(session, finalText, msg.images, ensureProjectAccessForSession(session));
571
+ sdk.startQuery(session, finalText, msg.images, ensureProjectAccessForSession(session), INITIATORS.HUMAN);
584
572
  } else {
585
- sdk.pushMessage(session, finalText, msg.images);
573
+ sdk.pushMessage(session, finalText, msg.images, INITIATORS.HUMAN);
586
574
  }
587
575
  } else {
588
- sdk.pushMessage(session, finalText, msg.images);
576
+ sdk.pushMessage(session, finalText, msg.images, INITIATORS.HUMAN);
589
577
  }
590
578
  sm.broadcastSessionList();
591
579
  }
package/lib/project.js CHANGED
@@ -34,9 +34,11 @@ var { attachMcp } = require("./project-mcp");
34
34
  var { createLocalMcp } = require("./mcp-local");
35
35
  var { attachTeam } = require("./project-team");
36
36
  var runtimeEnv = require("./runtime-env");
37
+ var { INITIATORS } = require("./turn-initiator");
37
38
  var mcpToolSchema = require("./mcp-tool-schema");
38
39
  var { reclaimIdleAdapters } = require("./idle-adapter-reaper");
39
40
  var sessionCapabilities = require("./session-capabilities");
41
+ var sessionReclaim = require("./session-reclaim");
40
42
  var { buildVendorRegistryMessage } = require("./vendor-registry-message");
41
43
  // project-notifications is attached globally in server.js, passed via opts.notificationsModule
42
44
 
@@ -166,7 +168,7 @@ function createProjectContext(opts) {
166
168
  var _liteStatus = detectLite();
167
169
 
168
170
  // --- YOKE adapters (multi-vendor, lazy init) ---
169
- var _yokeState = yoke.createAdapters({ cwd: cwd, slug: slug });
171
+ var _yokeState = yoke.createAdapters({ cwd: cwd, slug: slug, osUsers: osUsers });
170
172
  var adapters = _yokeState.adapters;
171
173
  // The project starts on the most preferred registered agent that is available.
172
174
  var defaultVendor = yoke.registry.defaultVendorId(Object.keys(adapters));
@@ -440,9 +442,13 @@ function createProjectContext(opts) {
440
442
  historyInMemMax: historyInMemMax,
441
443
  getNotificationsModule: function () { return _notifications; },
442
444
  onProcessingChanged: onProcessingChanged,
445
+ getProjectName: function () { return title || project; },
446
+ getProjectSlug: function () { return slug; },
443
447
  });
444
448
  sm.availableVendors = Object.keys(adapters);
445
449
  sm.defaultVendor = defaultVendor;
450
+ // Sessions the previous shutdown ended with background agents running.
451
+ sessionReclaim.surfaceRestartReclaims({ sm: sm });
446
452
 
447
453
  var _projMode = typeof opts.onGetProjectDefaultMode === "function" ? opts.onGetProjectDefaultMode(slug) : null;
448
454
  var _srvMode = typeof opts.onGetServerDefaultMode === "function" ? opts.onGetServerDefaultMode() : null;
@@ -577,6 +583,7 @@ function createProjectContext(opts) {
577
583
  var sdk = createSDKBridge({
578
584
  cwd: cwd,
579
585
  slug: slug,
586
+ osUsers: osUsers,
580
587
  sessionManager: sm,
581
588
  send: send,
582
589
  sendVendorRegistry: sendVendorRegistry,
@@ -736,7 +743,7 @@ function createProjectContext(opts) {
736
743
  session.isProcessing = true;
737
744
  onProcessingChanged();
738
745
  sendToSession(session.localId, { type: "status", status: "processing" });
739
- sdk.startQuery(session, text, null, ensureProjectAccessForSession(session));
746
+ sdk.startQuery(session, text, null, ensureProjectAccessForSession(session), INITIATORS.SCHEDULED);
740
747
  sm.broadcastSessionList();
741
748
  }, schedDelay),
742
749
  };
@@ -810,6 +817,7 @@ function createProjectContext(opts) {
810
817
  if (!vendorAdapter) {
811
818
  vendorAdapter = await yoke.lazyCreateAdapter(adapters, requestedVendor, {
812
819
  cwd: cwd,
820
+ osUsers: osUsers,
813
821
  clayPort: serverPort,
814
822
  clayTls: serverTls,
815
823
  clayAuthToken: serverAuthToken,
@@ -1222,11 +1230,23 @@ function createProjectContext(opts) {
1222
1230
  });
1223
1231
 
1224
1232
  // --- Destroy ---
1225
- function destroy() {
1233
+ // opts.reason says why the project is going away. Only a daemon shutdown
1234
+ // (sessionReclaim.RESTART_REASON) records its live background agents as
1235
+ // resumable: removing a project is a deliberate operator act, and its
1236
+ // sessions are not expected to come back. opts.tally, when given, collects
1237
+ // the announcement results so the caller logs one summary per shutdown.
1238
+ function destroy(opts) {
1239
+ var daemonShutdown = !!opts && opts.reason === sessionReclaim.RESTART_REASON;
1240
+ var tally = opts && opts.tally;
1226
1241
  _loop.stopTimer();
1227
1242
  stopAllWatches();
1228
1243
  // Abort all active sessions and clean up mention sessions
1229
1244
  sm.sessions.forEach(function (session) {
1245
+ // Before the abort below drops the agents' registration: the shutdown
1246
+ // kills them, so the session is recorded as resumable.
1247
+ if (daemonShutdown) {
1248
+ sessionReclaim.countShutdownReclaim(tally, sessionReclaim.announceShutdownReclaim(session, sm));
1249
+ }
1230
1250
  session.destroying = true;
1231
1251
  if (session.autoContinueTimer) {
1232
1252
  clearTimeout(session.autoContinueTimer);
@@ -1411,9 +1431,9 @@ function createProjectContext(opts) {
1411
1431
  reclaimIdleAdapters: function (idleMs) {
1412
1432
  return reclaimIdleAdapters(adapters, idleMs);
1413
1433
  },
1414
- destroy: function () {
1434
+ destroy: function (opts) {
1415
1435
  sdk.stopIdleReaper();
1416
- return destroy();
1436
+ return destroy(opts);
1417
1437
  },
1418
1438
  };
1419
1439
  }
@@ -15,6 +15,7 @@
15
15
  // An ask without hints (Codex approvals, older CLIs) is unchanged.
16
16
 
17
17
  var toolCall = require("./tool-call");
18
+ var grantKeys = require("../grant-keys");
18
19
  var { hasOwnKey } = require("./codecs");
19
20
 
20
21
  var DECISIONS = { allow: true, allow_always: true, deny: true };
@@ -54,12 +55,17 @@ module.exports = {
54
55
  store: "pendingPermissions",
55
56
  journal: true,
56
57
 
58
+ // grantScope is what Allow for Session would grant for this very call, as a
59
+ // sentence, or null when the call cannot be granted for the session. It is
60
+ // computed once, here, so the card, the banner and the check that settles
61
+ // the answer all read the same scope.
57
62
  fields: function (req) {
58
63
  return Object.assign({
59
64
  toolName: req.toolName,
60
65
  toolInput: req.toolInput,
61
66
  decisionReason: req.decisionReason || "",
62
67
  vendor: req.vendor,
68
+ grantScope: grantKeys.grantScopeText(req.toolName, req.toolInput),
63
69
  }, hintsOf(req));
64
70
  },
65
71
 
@@ -69,6 +75,7 @@ module.exports = {
69
75
  toolInput: record.toolInput,
70
76
  decisionReason: record.decisionReason || "",
71
77
  vendor: record.vendor,
78
+ grantScope: record.grantScope === undefined ? null : record.grantScope,
72
79
  }, hintsOf(record));
73
80
  },
74
81
 
@@ -78,6 +85,7 @@ module.exports = {
78
85
  return {
79
86
  suppressAlwaysAllowRule: hints.suppressAlwaysAllowRule,
80
87
  defaultToNo: hints.defaultToNo,
88
+ grantScope: record.grantScope === undefined ? null : record.grantScope,
81
89
  };
82
90
  },
83
91
 
@@ -91,6 +99,16 @@ module.exports = {
91
99
  if (decision === "allow_always" && record && record.suppressAlwaysAllowRule === true) {
92
100
  return { invalid: "always_allow_not_offered" };
93
101
  }
102
+ // A file tool never produces a session grant. An old client may still send
103
+ // Allow for Session for one: it is answered as this call only, nothing is
104
+ // stored.
105
+ if (decision === "allow_always" && record && grantKeys.isFileTool(record.toolName)) {
106
+ return { decision: "allow" };
107
+ }
108
+ // A call with nothing narrow enough to grant is never granted wider.
109
+ if (decision === "allow_always" && record && record.grantScope === null) {
110
+ return { invalid: "grant_scope_unavailable" };
111
+ }
94
112
  return { decision: decision };
95
113
  },
96
114
 
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+
3
+ // Who a prompt is from: the project, the session and, when a background agent
4
+ // raised it, that agent. Every surface that shows a prompt (card, banner, push
5
+ // notification) shows these, because a banner reaches every connected client
6
+ // whatever project it is viewing, and a tool request alone does not say whose
7
+ // it is.
8
+
9
+ var FIELD_MAX = 80;
10
+ var UNTITLED = "(untitled session)";
11
+
12
+ // Titles and agent descriptions are authored outside the console (a session
13
+ // title is typed or model-generated, a Task description comes from the model),
14
+ // so each is reduced to one bounded line.
15
+ function oneLine(raw) {
16
+ if (typeof raw !== "string") return "";
17
+ var one = raw.replace(/\s+/g, " ").trim();
18
+ return one.length > FIELD_MAX ? one.slice(0, FIELD_MAX - 3) + "..." : one;
19
+ }
20
+
21
+ /**
22
+ * @param {{project: ?string, sessionTitle: ?string, agent: ?string}} parts
23
+ * @returns {{project: string, session: string, agent: string}} agent is ""
24
+ * when the prompt belongs to the session itself.
25
+ */
26
+ function promptLabel(parts) {
27
+ var p = parts || {};
28
+ return {
29
+ project: oneLine(p.project),
30
+ session: oneLine(p.sessionTitle) || UNTITLED,
31
+ agent: oneLine(p.agent),
32
+ };
33
+ }
34
+
35
+ /**
36
+ * The label as one line for a push notification.
37
+ * @param {?{project: string, session: string, agent: string}} label
38
+ * @returns {string} "" for no label.
39
+ */
40
+ function formatPromptLabel(label) {
41
+ if (!label) return "";
42
+ var out = [];
43
+ if (label.project) out.push("Project: " + label.project);
44
+ if (label.session) out.push("Session: " + label.session);
45
+ if (label.agent) out.push("Agent: " + label.agent);
46
+ return out.join(" | ");
47
+ }
48
+
49
+ /**
50
+ * A push body that says whose prompt it is on its first line.
51
+ * @param {?object} label
52
+ * @param {string} body
53
+ */
54
+ function withPromptLabel(label, body) {
55
+ var line = formatPromptLabel(label);
56
+ if (!line) return body || "";
57
+ return body ? line + "\n" + body : line;
58
+ }
59
+
60
+ module.exports = { promptLabel: promptLabel, formatPromptLabel: formatPromptLabel, withPromptLabel: withPromptLabel };