@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
@@ -0,0 +1,172 @@
1
+ // session-resume.js - bring a stored session back into a project's session
2
+ // manager on its own vendor and agent. One implementation for the browser's
3
+ // resume_session message and for input injected from outside (session-input.js).
4
+ //
5
+ // A failure is reported as a failure: every function here either answers
6
+ // positively (a session, or a verified absence) or rejects with an Error whose
7
+ // `retryable` says whether trying again can help. An unreadable store and a
8
+ // history that cannot be loaded are never read as "no such session" or as an
9
+ // empty history.
10
+
11
+ var fs = require("fs");
12
+ var utils = require("./utils");
13
+ var sessionIdGuard = require("./session-id");
14
+
15
+ var isSafeSessionId = sessionIdGuard.isSafeSessionId;
16
+
17
+ function messageOf(err) {
18
+ return err && err.message ? err.message : String(err);
19
+ }
20
+
21
+ function resumeError(message, retryable) {
22
+ var err = new Error(message);
23
+ err.retryable = retryable;
24
+ return err;
25
+ }
26
+
27
+ // An unsafe id is refused, never read as "no such session" and passed on.
28
+ function assertSafeSessionId(cliSessionId) {
29
+ if (!isSafeSessionId(cliSessionId)) {
30
+ throw resumeError("unsafe session id " + JSON.stringify(String(cliSessionId).slice(0, 64)) + " refused", false);
31
+ }
32
+ }
33
+
34
+ // A record is a JSON object; null, numbers, strings and arrays are not.
35
+ function isRecord(value) {
36
+ return value !== null && typeof value === "object" && !Array.isArray(value);
37
+ }
38
+
39
+ // Reads the console's own record of a session: its meta line and its history.
40
+ // Returns null only when there is no such file. An unsafe id, a file that is
41
+ // there but cannot be read, or one whose records are damaged, throws (see
42
+ // resumeError).
43
+ //
44
+ // Every history line must parse to a JSON object, wherever it is: skipping or
45
+ // accepting anything else would hand the vendor a history with a hole in it.
46
+ // The only thing tolerated besides records is the single newline that ends the
47
+ // file, which the console's writer always adds.
48
+ function readStoredSession(sessionsDir, cliSessionId) {
49
+ assertSafeSessionId(cliSessionId);
50
+ if (!sessionsDir) return null;
51
+ var file;
52
+ try { file = sessionIdGuard.sessionPathWithin(sessionsDir, cliSessionId, ".jsonl"); }
53
+ catch (e) { throw resumeError(messageOf(e), false); }
54
+ var raw;
55
+ try { raw = fs.readFileSync(file, "utf8"); }
56
+ catch (e) {
57
+ if (e && e.code === "ENOENT") return null;
58
+ throw resumeError("cannot read stored session " + cliSessionId + ": " + messageOf(e), true);
59
+ }
60
+ var lines = (raw.endsWith("\n") ? raw.slice(0, -1) : raw).split("\n");
61
+ var meta;
62
+ try { meta = JSON.parse(lines[0]); }
63
+ catch (e) { throw resumeError("stored session " + cliSessionId + " is damaged: its meta record is not valid JSON", false); }
64
+ if (!isRecord(meta) || meta.type !== "meta") {
65
+ throw resumeError("stored session " + cliSessionId + " is damaged: its first record is not a meta record", false);
66
+ }
67
+ var history = [];
68
+ for (var i = 1; i < lines.length; i++) {
69
+ var record;
70
+ try { record = JSON.parse(lines[i]); }
71
+ catch (e) {
72
+ throw resumeError("stored session " + cliSessionId + " is damaged: line " + (i + 1) + " is malformed", false);
73
+ }
74
+ if (!isRecord(record)) {
75
+ throw resumeError("stored session " + cliSessionId + " is damaged: line " + (i + 1) + " is not a JSON object", false);
76
+ }
77
+ history.push(record);
78
+ }
79
+ return { meta: meta, history: history };
80
+ }
81
+
82
+ // Whether the console's own store holds a session. Sessions the vendor holds
83
+ // but the console never recorded are not addressable by injected input.
84
+ // Rejects when the record is there but unreadable or damaged.
85
+ function sessionExistsInStore(sm, cliSessionId) {
86
+ return Promise.resolve().then(function () {
87
+ return readStoredSession(sm.sessionsDir, cliSessionId) !== null;
88
+ });
89
+ }
90
+
91
+ function titleFromHistory(history) {
92
+ for (var i = 0; i < history.length; i++) {
93
+ if (history[i].type === "user_message" && history[i].text) return history[i].text.substring(0, 50);
94
+ }
95
+ return "Resumed session";
96
+ }
97
+
98
+ function defaultReadHistory(cwd, cliSessionId) {
99
+ return require("./cli-sessions").readCliSessionHistory(cwd, cliSessionId);
100
+ }
101
+
102
+ // Resumes cliSessionId into deps.sm and resolves the session (null when the
103
+ // session manager declines). Rejects, with `retryable` set, when the stored
104
+ // record or the vendor's history cannot be loaded: a session is never resumed
105
+ // on a history that failed to load.
106
+ // Vendor, agent, owner, visibility and granted tools come from the stored
107
+ // meta record so the session continues as what it was, not as the project's
108
+ // default. Without a console record the vendor's own history is used.
109
+ //
110
+ // deps: { sm, adapter, cwd, readHistory? } readHistory(cwd, id) -> Promise<history[]>
111
+ // opts: { ws, activate } ws is the requesting browser connection, if any;
112
+ // activate:false keeps every connected client on the session it is viewing.
113
+ function resumeStoredSession(deps, cliSessionId, opts) {
114
+ var sm = deps.sm;
115
+ var ws = (opts && opts.ws) || undefined;
116
+ var activate = !(opts && opts.activate === false);
117
+
118
+ return Promise.resolve().then(function () {
119
+ // First, before the id reaches the store, the adapter or the vendor's files.
120
+ assertSafeSessionId(cliSessionId);
121
+ var stored = readStoredSession(sm.sessionsDir, cliSessionId);
122
+ var meta = stored && stored.meta;
123
+ var resumeOpts = { activate: activate };
124
+ if (meta) {
125
+ if (meta.vendor) resumeOpts.vendor = meta.vendor;
126
+ if (meta.agentName) resumeOpts.agentName = meta.agentName;
127
+ if (meta.ownerId) resumeOpts.ownerId = meta.ownerId;
128
+ if (meta.sessionVisibility) resumeOpts.sessionVisibility = meta.sessionVisibility;
129
+ // Sanitized so a crafted meta record cannot auto-approve a tool.
130
+ if (meta.allowedTools) resumeOpts.allowedTools = utils.sanitizeAllowedTools(meta.allowedTools);
131
+ }
132
+
133
+ function finish(extra) {
134
+ var session = sm.resumeSession(cliSessionId, Object.assign(resumeOpts, extra), ws);
135
+ if (session && typeof sm.retrimHistory === "function") sm.retrimHistory(session);
136
+ return session || null;
137
+ }
138
+
139
+ if (stored) {
140
+ return finish({
141
+ history: stored.history,
142
+ title: meta.title || titleFromHistory(stored.history),
143
+ });
144
+ }
145
+
146
+ var readHistory = deps.readHistory || defaultReadHistory;
147
+ // The summary only names the resumed session; a lookup that fails leaves
148
+ // the title taken from the history instead and does not affect delivery.
149
+ var titlePromise = Promise.resolve()
150
+ .then(function () { return deps.adapter.getSessionInfo(cliSessionId, { dir: deps.cwd }); })
151
+ .then(function (info) { return (info && info.summary) ? info.summary.substring(0, 100) : null; })
152
+ .catch(function () { return null; });
153
+
154
+ var historyPromise = Promise.resolve()
155
+ .then(function () { return readHistory(deps.cwd, cliSessionId); })
156
+ .catch(function (err) {
157
+ throw resumeError("could not load the history of session " + cliSessionId + ": " + messageOf(err), true);
158
+ });
159
+
160
+ return Promise.all([historyPromise, titlePromise]).then(function (results) {
161
+ var history = results[0];
162
+ return finish({ history: history, title: results[1] || titleFromHistory(history) });
163
+ });
164
+ });
165
+ }
166
+
167
+ module.exports = {
168
+ isSafeSessionId: isSafeSessionId,
169
+ readStoredSession: readStoredSession,
170
+ sessionExistsInStore: sessionExistsInStore,
171
+ resumeStoredSession: resumeStoredSession,
172
+ };
package/lib/sessions.js CHANGED
@@ -2,10 +2,13 @@ var fs = require("fs");
2
2
  var path = require("path");
3
3
  var config = require("./config");
4
4
  var utils = require("./utils");
5
+ var sessionIdGuard = require("./session-id");
5
6
  var users = require("./users");
6
7
  var { CODEX_DEFAULTS } = require("./codex-defaults");
7
8
  var { isVisibleHistoryEvent } = require("./history-visibility");
8
9
  var { createPromptRegistry } = require("./prompt-registry");
10
+ var { registerExitFlush } = require("./exit-flush");
11
+ var sessionReclaim = require("./session-reclaim");
9
12
 
10
13
  // lr-2ea2a7: hard cap on how many history entries a session may hold in the
11
14
  // heap array, regardless of isProcessing state. On-disk JSONL remains the
@@ -108,6 +111,8 @@ function createSessionManager(opts) {
108
111
  saveSessionFile: function (session) { return saveSessionFile(session); },
109
112
  getNotificationsModule: opts.getNotificationsModule,
110
113
  onProcessingChanged: opts.onProcessingChanged,
114
+ getProjectName: opts.getProjectName,
115
+ getProjectSlug: opts.getProjectSlug,
111
116
  });
112
117
  var capabilitiesByVendor = null; // set by sdk-bridge after adapter init
113
118
  var defaultVendor = null; // set by sdk-bridge
@@ -122,7 +127,7 @@ function createSessionManager(opts) {
122
127
  fs.mkdirSync(sessionsDir, { recursive: true });
123
128
 
124
129
  function sessionFilePath(cliSessionId) {
125
- return path.join(sessionsDir, cliSessionId + ".jsonl");
130
+ return sessionIdGuard.sessionPathWithin(sessionsDir, cliSessionId, ".jsonl");
126
131
  }
127
132
 
128
133
  function buildMetaLine(session) {
@@ -163,19 +168,16 @@ function createSessionManager(opts) {
163
168
  if (session.pendingAutoResume) {
164
169
  metaObj.pendingAutoResume = true;
165
170
  if (session.pendingAutoResumeReason) metaObj.pendingAutoResumeReason = session.pendingAutoResumeReason;
166
- }
167
- // lr-62157d: durable auto-title state. Without this, titleAutoGenerated
168
- // and titleManuallySet lived in memory only — every daemon restart reset
169
- // both to false, so the "already auto-titled" / "user renamed it" guards
170
- // at sdk-message-processor.js and sdk-bridge.js were guarding against
171
- // state that could never actually be true after a restart. turnCount is
172
- // persisted alongside them because the turn-threshold gate (see the
173
- // '>=' fix at sdk-message-processor.js) depends on it surviving too —
174
- // a restarted session that lost its turn count would silently miss the
175
- // auto-title window forever instead of catching up on a later turn.
171
+ // Names of the agents a daemon shutdown interrupted, for the notice at
172
+ // the next startup (lib/session-reclaim.js).
173
+ var resumeAgents = sessionReclaim.sanitizeAgentLabels(session.pendingAutoResumeAgents);
174
+ if (resumeAgents) metaObj.pendingAutoResumeAgents = resumeAgents;
175
+ }
176
+ // Durable title state: titleManuallySet (the operator renamed the session,
177
+ // which always wins) and titleAutoGenerated (the title is the CLI's own,
178
+ // see session-ai-title.js) must survive a daemon restart.
176
179
  // titleProvisional marks a title set from the raw first-message
177
- // truncation (project-user-message.js) so autoGenerateTitle knows it is
178
- // safe to overwrite even though the flags above look "not yet set".
180
+ // truncation (project-user-message.js).
179
181
  if (session.titleAutoGenerated) metaObj.titleAutoGenerated = true;
180
182
  if (session.titleManuallySet) metaObj.titleManuallySet = true;
181
183
  if (session.titleProvisional) metaObj.titleProvisional = true;
@@ -772,6 +774,7 @@ function createSessionManager(opts) {
772
774
  if (m.pendingAutoResume) {
773
775
  session.pendingAutoResume = true;
774
776
  session.pendingAutoResumeReason = m.pendingAutoResumeReason || null;
777
+ session.pendingAutoResumeAgents = sessionReclaim.sanitizeAgentLabels(m.pendingAutoResumeAgents);
775
778
  }
776
779
  // lr-62157d: restore auto-title state across a daemon restart — see
777
780
  // buildMetaLine's write side for why this must persist. Without this,
@@ -790,14 +793,15 @@ function createSessionManager(opts) {
790
793
 
791
794
  // Drain all write buffers synchronously on process exit to prevent trailing
792
795
  // event loss when the daemon shuts down cleanly.
793
- // Named so it can be deregistered via sm.destroy() when the project is torn
794
- // down — avoids accumulating one listener per project open (lr-daca).
796
+ // Registered with the shared exit flusher, not as a listener of its own:
797
+ // one process listener per project tripped the MaxListeners warning at
798
+ // startup. sm.destroy() unregisters it when the project is torn down.
795
799
  function _onProcessExit() {
796
800
  sessions.forEach(function(session) {
797
801
  flushSessionBuffer(session);
798
802
  });
799
803
  }
800
- process.on("exit", _onProcessExit);
804
+ var unregisterExitFlush = registerExitFlush(_onProcessExit);
801
805
 
802
806
  function getActiveSession() {
803
807
  return sessions.get(activeSessionId) || null;
@@ -1366,6 +1370,9 @@ function createSessionManager(opts) {
1366
1370
  }
1367
1371
 
1368
1372
  function resumeSession(cliSessionId, opts, targetWs) {
1373
+ // The id names a file under sessionsDir; declining here keeps an unvalidated
1374
+ // id from reaching saveSessionFile for any caller.
1375
+ if (!sessionIdGuard.isSafeSessionId(cliSessionId)) return null;
1369
1376
  // If a session with this cliSessionId already exists, just switch to it
1370
1377
  var existing = null;
1371
1378
  sessions.forEach(function (s) {
@@ -1409,10 +1416,14 @@ function createSessionManager(opts) {
1409
1416
  favoriteOrder: null,
1410
1417
  };
1411
1418
  if (opts && opts.vendor) session.vendor = opts.vendor;
1419
+ if (opts && opts.agentName) session.agentName = opts.agentName;
1420
+ if (opts && opts.sessionVisibility) session.sessionVisibility = opts.sessionVisibility;
1412
1421
  if (opts && opts.ownerId) session.ownerId = opts.ownerId;
1413
1422
  sessions.set(localId, session);
1414
1423
  saveSessionFile(session);
1415
- switchSession(localId, targetWs);
1424
+ // activate:false is for a resume nobody asked to look at (injected input):
1425
+ // switching would move every connected client off the session it is on.
1426
+ if (!(opts && opts.activate === false)) switchSession(localId, targetWs);
1416
1427
  return session;
1417
1428
  }
1418
1429
 
@@ -1820,13 +1831,12 @@ function createSessionManager(opts) {
1820
1831
  effectiveSessionModel: function (session) { return effectiveSessionModel(session, _instance); },
1821
1832
  // Called when the project owning this session manager is torn down. No
1822
1833
  // prompt resolver outlives it, so every pending prompt ends here and its
1823
- // outcome is flushed to disk; then the process-level exit listener
1824
- // registered above is removed so listeners do not accumulate across
1825
- // project open/close cycles.
1834
+ // outcome is flushed to disk; then the exit flusher registered above is
1835
+ // unregistered so nothing accumulates across project open/close cycles.
1826
1836
  destroy: function() {
1827
1837
  prompts.shutdown();
1828
1838
  _onProcessExit();
1829
- process.removeListener("exit", _onProcessExit);
1839
+ unregisterExitFlush();
1830
1840
  },
1831
1841
  };
1832
1842
  _instance.prompts = prompts;
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+
3
+ // supervisor.js — is a service manager responsible for this daemon's lifetime?
4
+ //
5
+ // Under systemd the unit restarts the daemon after it exits (Restart=always),
6
+ // and KillMode=mixed removes every other process in the unit's cgroup when the
7
+ // main process exits. A daemon that spawned its own replacement before exiting
8
+ // therefore had the replacement killed with the rest of the cgroup, and the
9
+ // restart worked only because the unit started another one. A supervised
10
+ // restart is an exit with RESTART_EXIT_CODE and nothing else.
11
+
12
+ // Also the code the dev watcher (lib/cli/daemon-launch.js) respawns on.
13
+ var RESTART_EXIT_CODE = 120;
14
+
15
+ // Set by systemd for every process it starts as part of a unit.
16
+ var SUPERVISOR_ENV = ['INVOCATION_ID', 'NOTIFY_SOCKET'];
17
+
18
+ function isSupervised(env) {
19
+ var e = env || process.env;
20
+ return SUPERVISOR_ENV.some(function (name) { return !!e[name]; });
21
+ }
22
+
23
+ /**
24
+ * The environment for a daemon this process starts itself (the CLI's detached
25
+ * start, a self-spawned replacement). That daemon is not the unit's main
26
+ * process, so it must not read the unit's variables, which it would inherit
27
+ * when the CLI itself was run from inside a service.
28
+ */
29
+ function unsupervisedEnv(env) {
30
+ var copy = Object.assign({}, env || process.env);
31
+ SUPERVISOR_ENV.forEach(function (name) { delete copy[name]; });
32
+ return copy;
33
+ }
34
+
35
+ module.exports = {
36
+ RESTART_EXIT_CODE: RESTART_EXIT_CODE,
37
+ isSupervised: isSupervised,
38
+ unsupervisedEnv: unsupervisedEnv,
39
+ };
@@ -0,0 +1,108 @@
1
+ // turn-initiator.js - who started a turn, carried per turn from the entry point
2
+ // that created it to the agent adapter that delivers it.
3
+ //
4
+ // The initiator is a property of ONE turn, never of a session: a session can
5
+ // take a typed turn, then a scheduled one, then a typed one again. Each entry
6
+ // point (the WebSocket "message" handler, the scheduled-message timer, a Ralph
7
+ // loop iteration, an external trigger) names its initiator and passes it with
8
+ // the turn; an adapter maps it to the vendor's own provenance field. A turn
9
+ // whose entry point names none is delivered unstamped.
10
+ //
11
+ // This module owns the console-side vocabulary and the Claude mapping. Where a
12
+ // vendor carries provenance in a different place (the Codex adapter), the
13
+ // adapter maps from the same vocabulary.
14
+
15
+ var pkg = require("../package.json");
16
+ var runtimeEnv = require("./runtime-env");
17
+
18
+ var INITIATORS = Object.freeze({
19
+ // Text a person typed into the console.
20
+ HUMAN: "human",
21
+ // A message the console sent at the time the person scheduled it.
22
+ SCHEDULED: "scheduled",
23
+ // A scheduled message the person chose to send now.
24
+ SCHEDULED_NOW: "scheduled-now",
25
+ // One iteration of an automated loop.
26
+ LOOP: "loop",
27
+ // A turn delivered by an external trigger.
28
+ TRIGGER: "trigger",
29
+ });
30
+
31
+ var KNOWN = Object.keys(INITIATORS).map(function (k) { return INITIATORS[k]; });
32
+
33
+ function isInitiator(value) {
34
+ return KNOWN.indexOf(value) !== -1;
35
+ }
36
+
37
+ // The Claude Agent SDK's SDKMessageOrigin for a turn. Undefined when the turn
38
+ // names no initiator: the SDK treats an absent origin as unattributed, so only
39
+ // a turn the console knows the source of is stamped.
40
+ function claudeOrigin(initiator) {
41
+ switch (initiator) {
42
+ case INITIATORS.HUMAN:
43
+ return { kind: "human" };
44
+ case INITIATORS.SCHEDULED:
45
+ return { kind: "task-notification", subkind: "scheduled-trigger", fireReason: "scheduled" };
46
+ case INITIATORS.SCHEDULED_NOW:
47
+ return { kind: "task-notification", subkind: "scheduled-trigger", fireReason: "manual" };
48
+ case INITIATORS.LOOP:
49
+ return { kind: "task-notification", subkind: "scheduled-trigger", fireReason: "loop" };
50
+ case INITIATORS.TRIGGER:
51
+ return { kind: "task-notification", subkind: "scheduled-trigger", fireReason: "trigger" };
52
+ default:
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ // Whether the CLI must deliver the turn's text as written (no @path expansion,
58
+ // no slash-command dispatch): true for every turn a person did not type.
59
+ function isClientComposed(initiator) {
60
+ return isInitiator(initiator) && initiator !== INITIATORS.HUMAN;
61
+ }
62
+
63
+ // The CLI keeps a host-declared origin only when it is human, or the
64
+ // scheduled-trigger kind in a process started with this variable. Every
65
+ // automated turn uses the latter, so a process whose first turn is anything but
66
+ // a typed one gets it.
67
+ function isScheduledInitiator(initiator) {
68
+ return isClientComposed(initiator);
69
+ }
70
+
71
+ // Identifies this product to the Claude Agent SDK ("<app>/<version>").
72
+ function clientAppId() {
73
+ return "clagentic-console/" + pkg.version;
74
+ }
75
+
76
+ // The environment additions the console always makes for a Claude process.
77
+ // Laid over the process's own environment by the caller, never in place of it.
78
+ function claudeHostEnv(initiator) {
79
+ var env = { CLAUDE_AGENT_SDK_CLIENT_APP: clientAppId() };
80
+ if (isScheduledInitiator(initiator)) env.CLAUDE_CODE_HOST_SCHEDULED_RUN = "1";
81
+ return env;
82
+ }
83
+
84
+ // The complete environment for a Claude process: the process's own, then the
85
+ // Settings overlay, then the console's additions. The SDK replaces the CLI's
86
+ // environment with options.env, so this is always the whole environment.
87
+ function claudeProcessEnv(base, overlay, initiator) {
88
+ return Object.assign(runtimeEnv.composeRuntimeEnv(base, overlay), claudeHostEnv(initiator));
89
+ }
90
+
91
+ // A streamed Claude user message for a turn, with its provenance stamped.
92
+ function stampClaudeUserMessage(message, initiator) {
93
+ var origin = claudeOrigin(initiator);
94
+ if (origin) message.origin = origin;
95
+ if (isClientComposed(initiator)) message.client_composed = true;
96
+ return message;
97
+ }
98
+
99
+ module.exports = {
100
+ INITIATORS: INITIATORS,
101
+ isInitiator: isInitiator,
102
+ claudeOrigin: claudeOrigin,
103
+ isClientComposed: isClientComposed,
104
+ clientAppId: clientAppId,
105
+ claudeHostEnv: claudeHostEnv,
106
+ claudeProcessEnv: claudeProcessEnv,
107
+ stampClaudeUserMessage: stampClaudeUserMessage,
108
+ };
package/lib/utils.js CHANGED
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  var fs = require("fs");
6
+ var grantKeys = require("./grant-keys");
6
7
 
7
8
  /**
8
9
  * Encode a cwd path into a filesystem-safe directory/file name.
@@ -66,64 +67,25 @@ function resolveEncodedFile(baseDir, cwd, ext) {
66
67
  * handleCanUseTool check (lib/sdk-bridge.js:691).
67
68
  *
68
69
  * Keeps only entries whose key is a string and whose value is strictly
69
- * boolean `true`; drops everything else. A non-object input (including
70
+ * boolean `true` and not scoped to a file (a persisted Write:<path> key is
71
+ * dropped: file tools never hold a session grant); drops everything else. A non-object input (including
70
72
  * null/undefined/arrays) yields an empty map rather than throwing. The map
71
73
  * has no prototype: its keys are tool names, and a name like "constructor"
72
- * must not be found as an inherited entry.
74
+ * must not be found as an inherited entry. A key longer than a grant can be,
75
+ * or beyond the number a session record has room for, is dropped: grants are
76
+ * persisted in a bounded part of the meta record (lib/grant-keys.js).
73
77
  */
74
78
  function sanitizeAllowedTools(value) {
75
79
  var out = Object.create(null);
76
80
  if (!value || typeof value !== "object" || Array.isArray(value)) return out;
77
81
  for (var key in value) {
78
82
  if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
79
- if (typeof key === "string" && value[key] === true) out[key] = true;
83
+ if (typeof key === "string" && key.length <= grantKeys.MAX_KEY_LENGTH && grantKeys.isGrantValue(key, value[key])
84
+ && Object.keys(out).length < grantKeys.MAX_GRANTS) out[key] = value[key];
80
85
  }
81
86
  return out;
82
87
  }
83
88
 
84
- /**
85
- * Compute the key used to index a session's "allow for session" grant map
86
- * (session.allowedTools) for a given tool call (lr-f969dc).
87
- *
88
- * Most tools are correctly discriminated by bare tool name alone — MCP tools
89
- * already fold server + tool identity into the name itself (e.g.
90
- * "mcp__browser__navigate" vs "mcp__browser__screenshot" are already
91
- * distinct keys), so approving one MCP tool must not silently approve a
92
- * different one, and bare-name keying already gives that.
93
- *
94
- * The Claude `Skill` tool is the one exception found so far: every distinct
95
- * skill invocation arrives as the SAME toolName "Skill" with a different
96
- * `input.skill` discriminator. Keying on bare "Skill" means granting one
97
- * skill silently authorizes every other skill for the rest of the session —
98
- * a security regression, not the "doesn't stick" fix the grant was meant to
99
- * provide. Fold the discriminator into the key so a grant is scoped to the
100
- * specific skill that was actually approved.
101
- *
102
- * This repo is vendor-agnostic via the YOKE adapter layer (lib/yoke/), so a
103
- * bare "Skill" literal here is a deliberate, checked exception, not a
104
- * default pattern for future tools. Verified (lr-f969dc): Codex's approval
105
- * RPCs (exec/file/MCP, lib/yoke/adapters/codex.js) route through this same
106
- * function via the identical vendor-neutral canUseTool wiring, and all of
107
- * them already send correctly-flat tool names — Codex has no tool today
108
- * whose identity fans out under one shared name the way Skill does, so no
109
- * generalization is needed for vendor parity right now. If a second vendor
110
- * or a renamed/restructured tool introduces another input-discriminated
111
- * tool, extend this with another explicit branch (or a small declarative
112
- * toolName -> discriminator-field table if a third case appears) rather
113
- * than reaching for a config knob nobody would otherwise set.
114
- *
115
- * Falls back to the bare tool name when the expected discriminator is
116
- * missing or not a string (fails closed to the pre-existing per-tool grant
117
- * rather than throwing or producing an unstable key). Never hardcodes an
118
- * individual skill name — only the shared "Skill" tool identifier.
119
- */
120
- function permissionGrantKey(toolName, input) {
121
- if (toolName === "Skill" && input && typeof input.skill === "string" && input.skill) {
122
- return "Skill:" + input.skill;
123
- }
124
- return toolName;
125
- }
126
-
127
89
  /**
128
90
  * Default hard cap for readCappedBody() call sites that don't pass their own
129
91
  * maxBytes: these are small JSON-only pre-auth endpoints (login, PIN
@@ -183,7 +145,7 @@ module.exports = {
183
145
  resolveEncodedDir: resolveEncodedDir,
184
146
  resolveEncodedFile: resolveEncodedFile,
185
147
  sanitizeAllowedTools: sanitizeAllowedTools,
186
- permissionGrantKey: permissionGrantKey,
148
+ permissionGrantKey: grantKeys.permissionGrantKey,
187
149
  readCappedBody: readCappedBody,
188
150
  DEFAULT_BODY_CAP_BYTES: DEFAULT_BODY_CAP_BYTES,
189
151
  };
@@ -51,6 +51,7 @@ function buildVendorRegistryMessage(sm, linuxUser) {
51
51
  vendors: registry.describeForClient({
52
52
  installed: state.installed,
53
53
  probeFailures: state.failures,
54
+ details: state.details,
54
55
  available: sm.availableVendors || [],
55
56
  capabilities: sm.capabilitiesByVendor || {},
56
57
  }),
package/lib/ws-schema.js CHANGED
@@ -78,7 +78,9 @@ var schema = {
78
78
  // were live, sent types with no documentation entry.
79
79
  "plan_content": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Plan-mode content for the plan card" },
80
80
  "sdk_notification": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Informational notification surfaced from the vendor SDK" },
81
- "diagnostic": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Session-scoped diagnostic toast (settings preflight, memory shedding, adapter warnings)" },
81
+ "diagnostic": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Session-scoped diagnostic toast (settings preflight, memory shedding, adapter warnings). A message with refresh:true updates the entry the client already holds for the same source and action, and is ignored when the client holds none" },
82
+
83
+ "diagnostic_retract": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Withdraws every diagnostic of one source (source) because its condition no longer holds; sent when the installed build is adopted while an update offer is shown, and to a client that connects while no offer stands" },
82
84
 
83
85
  // -----------------------------------------------------------------------
84
86
  // Thinking
@@ -120,10 +122,10 @@ var schema = {
120
122
  // suppressAlwaysAllowRule, defaultToNo, matchedAskRule; ask_user: input; elicitation: serverName,
121
123
  // message, mode, url, elicitationId, requestedSchema).
122
124
  // -----------------------------------------------------------------------
123
- "prompt_request": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "A prompt awaits the operator: {requestId, kind, toolUseId, ...kind fields}. On history replay it carries promptState {state: pending|resolved|cancelled, decision|answers|skipped|action, reason}, the server's authoritative state for the prompt at replay time" },
125
+ "prompt_request": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "A prompt awaits the operator: {requestId, kind, toolUseId, label: {project, session, agent}, ...kind fields} (label names whose prompt it is; agent is empty unless a background agent raised it; a permission prompt also carries grantScope, the sentence saying what Allow for Session would grant, or null when it cannot be granted). On history replay it carries promptState {state: pending|resolved|cancelled, decision|answers|skipped|action, reason}, the server's authoritative state for the prompt at replay time" },
124
126
  "prompt_pending": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "A prompt still awaiting the operator, re-presented on connect and session switch; same fields as prompt_request" },
125
- "prompt_response": { direction: "c2s", handler: "lib/project-prompt-responses.js", description: "The operator's answer: {requestId, kind, ...} with decision (+ feedback, planContent) for permission/plan, answers or decision:\"skip\" for ask_user (answers keyed by question index; each a label or text, or for a multi-select question the list of chosen labels), action (+ content, held to the requested schema) for elicitation. The kind is required and must match the prompt's. Decision allow_always to a permission prompt that carries suppressAlwaysAllowRule settles nothing: the prompt is sent again as prompt_pending. A prompt of the extension kind is never answered this way" },
126
- "prompt_resolved": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "A prompt was answered: {requestId, kind, decision|answers|skipped|action}; a permission prompt forced by a user ask rule also carries matchedAskRule" },
127
+ "prompt_response": { direction: "c2s", handler: "lib/project-prompt-responses.js", description: "The operator's answer: {requestId, kind, ...} with decision (+ feedback, planContent) for permission/plan, answers or decision:\"skip\" for ask_user (answers keyed by question index; each a label or text, or for a multi-select question the list of chosen labels), action (+ content, held to the requested schema) for elicitation. The kind is required and must match the prompt's. Decision allow_always grants only what the prompt's grantScope says, and to a permission prompt that carries suppressAlwaysAllowRule, or whose grantScope is null (nothing narrow enough to grant), settles nothing: the prompt is sent again as prompt_pending. A prompt of the extension kind is never answered this way" },
128
+ "prompt_resolved": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "A prompt was answered: {requestId, kind, decision|answers|skipped|action, source?}; a permission prompt forced by a user ask rule also carries matchedAskRule. source says who answered, as {kind:\"ws\", clientId, user} for a browser connection (clientId is a per-connection label, user the user id or null) or {kind:\"push\", action, user} for a push notification answer; it is absent when the answering path named none. The same source is written to the journal line the settle logs. Prompt content is never part of a source" },
127
129
  "prompt_cancel": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "A prompt ended without an answer: {requestId, kind, reason}; reason is aborted, expired, turn_ended, query_ended, rewind, cleared or shutdown. Reason \"stale\" is sent only to a client whose prompt_response named a prompt the server no longer holds, and is not recorded in history" },
128
130
 
129
131
  // Aliases kept for compatibility: the s2c types appear in history recorded
@@ -132,6 +134,9 @@ var schema = {
132
134
  // before an upgrade. Nothing records or sends the s2c aliases any more,
133
135
  // except permission_cancel {reason: "stale"} in reply to a
134
136
  // permission_response.
137
+ "list_session_grants": { direction: "c2s", handler: "lib/project-session-grants.js", description: "Ask for a session's Allow for Session grants: {sessionId?} (the connection's own session when absent). Answered with session_grants to the asker; refused silently for a session the user may not see" },
138
+ "revoke_session_grant": { direction: "c2s", handler: "lib/project-session-grants.js", description: "Revoke one Allow for Session grant: {sessionId?, key}. Persisted at once and in force on the session's next tool call; every client viewing the session gets the resulting session_grants. Authorized by mayAnswerPrompt (lib/prompt-access.js), the rule that lets a user answer the session's prompts. For a session that rule refuses, the asker alone gets session_grants with an error string and no grants" },
139
+ "session_grants": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "A session's grants as {sessionId, grants: [{key, tool, wholeTool, text}]}; wholeTool marks a grant that covers every call of the tool (older sessions). A refused revoke is {sessionId, error} with no grants" },
135
140
  "permission_request": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Alias of prompt_request (kind permission or plan); history carries permissionState or promptState" },
136
141
  "permission_request_pending": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Alias of prompt_pending (kind permission or plan)" },
137
142
  "permission_response": { direction: "c2s", handler: "lib/project-prompt-responses.js", description: "Alias of prompt_response for kinds permission and plan: {requestId, decision, feedback, planContent}" },
@@ -24,7 +24,6 @@ registry.register({
24
24
  needsRuntimeEnv: false,
25
25
  perProjectRuntime: false,
26
26
  activityTokens: false,
27
- attestsHumanSessions: false,
28
27
  ownedEnvNames: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"].concat(providerCredentials.allCredentialNames()),
29
28
  ownedEnvPrefixes: providerCredentials.allCredentialPrefixes(),
30
29
  credentialGroups: providerCredentials.CREDENTIAL_GROUPS,
@@ -21,7 +21,7 @@ var os = require("os");
21
21
  var parseDiagnosticLine = require("./diagnostic-patterns").parseDiagnosticLine;
22
22
  var permissionRelay = require("./permission-relay");
23
23
  var effortControl = require("./effort-control");
24
- var runtimeEnv = require("../../runtime-env");
24
+ var turnInitiator = require("../../turn-initiator");
25
25
  var workerMcpServers = require("./worker-mcp-servers");
26
26
 
27
27
  var socketPath = process.argv[2];
@@ -105,10 +105,12 @@ function applyWorkerClaudeBinary(options) {
105
105
  function applyRuntimeEnv(options) {
106
106
  if (!options) return options;
107
107
  var overlay = options.runtimeEnv;
108
+ var initiator = options.initiator;
108
109
  delete options.runtimeEnv;
109
- if (runtimeEnv.hasOverlay(overlay)) {
110
- options.env = runtimeEnv.composeRuntimeEnv(process.env, overlay);
111
- }
110
+ delete options.initiator;
111
+ // Always built: the product identity is part of every Claude process's
112
+ // environment, with the initiator of the turn that starts the query.
113
+ options.env = turnInitiator.claudeProcessEnv(process.env, overlay, initiator);
112
114
  return options;
113
115
  }
114
116