@clagentic/console 1.9.0 → 1.10.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/LICENSE +117 -12
  2. package/LICENSES/MIT-legacy.txt +22 -0
  3. package/LICENSES/README.md +15 -0
  4. package/README.md +8 -2
  5. package/bin/cli.js +30 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/audit.js +3 -2
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-check.js +138 -0
  10. package/lib/cli/daemon-launch.js +17 -17
  11. package/lib/config.js +32 -20
  12. package/lib/daemon-env-settings.js +84 -0
  13. package/lib/daemon-projects.js +38 -0
  14. package/lib/daemon.js +202 -158
  15. package/lib/drain.js +74 -17
  16. package/lib/env-compat.js +61 -0
  17. package/lib/extension-commands.js +45 -0
  18. package/lib/history-visibility.js +4 -0
  19. package/lib/idle-adapter-reaper.js +71 -0
  20. package/lib/link-trap.js +78 -0
  21. package/lib/lore-attestation.js +73 -0
  22. package/lib/mcp-local.js +8 -6
  23. package/lib/mcp-tool-input.js +116 -0
  24. package/lib/mcp-tool-schema.js +179 -0
  25. package/lib/memory-limits.js +61 -5
  26. package/lib/memory-setting-validate.js +65 -0
  27. package/lib/new-work-gate.js +47 -0
  28. package/lib/os-users.js +5 -3
  29. package/lib/project-access.js +139 -0
  30. package/lib/project-connection.js +23 -22
  31. package/lib/project-external-trigger.js +103 -10
  32. package/lib/project-file-scope.js +172 -0
  33. package/lib/project-file-watch.js +86 -61
  34. package/lib/project-filesystem.js +144 -128
  35. package/lib/project-git.js +119 -0
  36. package/lib/project-http.js +44 -28
  37. package/lib/project-loop.js +12 -5
  38. package/lib/project-mcp.js +53 -72
  39. package/lib/project-message-gate.js +70 -0
  40. package/lib/project-notifications.js +31 -4
  41. package/lib/project-prompt-responses.js +216 -0
  42. package/lib/project-sessions.js +164 -302
  43. package/lib/project-user-message.js +36 -11
  44. package/lib/project.js +189 -142
  45. package/lib/projects-dir.js +90 -0
  46. package/lib/prompt-access.js +22 -0
  47. package/lib/prompt-kinds/answer-limits.js +15 -0
  48. package/lib/prompt-kinds/ask-user.js +58 -0
  49. package/lib/prompt-kinds/codecs.js +97 -0
  50. package/lib/prompt-kinds/elicitation.js +77 -0
  51. package/lib/prompt-kinds/extension.js +39 -0
  52. package/lib/prompt-kinds/index.js +68 -0
  53. package/lib/prompt-kinds/permission.js +114 -0
  54. package/lib/prompt-kinds/plan.js +79 -0
  55. package/lib/prompt-kinds/tool-call.js +38 -0
  56. package/lib/prompt-registry.js +673 -0
  57. package/lib/public/app.js +1 -1
  58. package/lib/public/css/diagnostics.css +50 -0
  59. package/lib/public/css/input.css +17 -3
  60. package/lib/public/css/menus.css +10 -0
  61. package/lib/public/css/messages.css +5 -0
  62. package/lib/public/css/rewind.css +22 -0
  63. package/lib/public/index.html +4 -12
  64. package/lib/public/modules/app-connection.js +7 -0
  65. package/lib/public/modules/app-cursors.js +7 -5
  66. package/lib/public/modules/app-messages.js +45 -45
  67. package/lib/public/modules/app-notifications.js +47 -71
  68. package/lib/public/modules/app-panels.js +61 -58
  69. package/lib/public/modules/app-projects.js +2 -1
  70. package/lib/public/modules/app-rendering.js +4 -10
  71. package/lib/public/modules/diagnostics.js +60 -16
  72. package/lib/public/modules/filebrowser.js +18 -16
  73. package/lib/public/modules/history-visibility.js +4 -0
  74. package/lib/public/modules/mention.js +3 -2
  75. package/lib/public/modules/mode-options.js +38 -0
  76. package/lib/public/modules/project-settings.js +19 -8
  77. package/lib/public/modules/prompt-banner.js +78 -0
  78. package/lib/public/modules/prompt-card.js +201 -0
  79. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  80. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  81. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  82. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  83. package/lib/public/modules/prompt-kinds/index.js +18 -0
  84. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  85. package/lib/public/modules/prompt-kinds/package.json +3 -0
  86. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  87. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  88. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  89. package/lib/public/modules/prompt-state.js +142 -0
  90. package/lib/public/modules/prompts.js +134 -0
  91. package/lib/public/modules/rewind.js +4 -1
  92. package/lib/public/modules/server-settings.js +2 -4
  93. package/lib/public/modules/sidebar-mobile.js +19 -9
  94. package/lib/public/modules/sidebar-sessions.js +21 -14
  95. package/lib/public/modules/sticky-notes.js +3 -2
  96. package/lib/public/modules/team-panel.js +5 -4
  97. package/lib/public/modules/tools.js +67 -904
  98. package/lib/public/modules/vendor-picker.js +53 -0
  99. package/lib/public/modules/vendor-registry.js +133 -0
  100. package/lib/public/sw.js +3 -1
  101. package/lib/rc-migrate.js +44 -0
  102. package/lib/runtime-env-keys.js +109 -0
  103. package/lib/runtime-env.js +236 -0
  104. package/lib/sdk-bridge.js +290 -273
  105. package/lib/sdk-message-processor.js +125 -145
  106. package/lib/server-hub-sessions.js +13 -10
  107. package/lib/server-palette.js +28 -19
  108. package/lib/server.js +141 -113
  109. package/lib/service-install.js +96 -0
  110. package/lib/session-capabilities.js +76 -0
  111. package/lib/sessions.js +45 -28
  112. package/lib/users-permissions.js +9 -6
  113. package/lib/users.js +9 -0
  114. package/lib/utils.js +4 -2
  115. package/lib/vendor-auth.js +22 -0
  116. package/lib/vendor-registry-message.js +65 -0
  117. package/lib/ws-origin.js +99 -0
  118. package/lib/ws-schema.js +33 -22
  119. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  120. package/lib/yoke/adapters/claude-vendor.js +35 -0
  121. package/lib/yoke/adapters/claude-worker.js +55 -87
  122. package/lib/yoke/adapters/claude.js +156 -62
  123. package/lib/yoke/adapters/codex-capabilities.js +37 -0
  124. package/lib/yoke/adapters/codex-vendor.js +46 -0
  125. package/lib/yoke/adapters/codex.js +347 -156
  126. package/lib/yoke/adapters/effort-control.js +34 -0
  127. package/lib/yoke/adapters/permission-relay.js +58 -0
  128. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  129. package/lib/yoke/auth-checks.js +104 -0
  130. package/lib/yoke/capabilities.js +49 -0
  131. package/lib/yoke/codex-app-server.js +23 -5
  132. package/lib/yoke/env-ownership.js +40 -0
  133. package/lib/yoke/index.js +67 -173
  134. package/lib/yoke/install-probe.js +121 -0
  135. package/lib/yoke/instructions.js +7 -11
  136. package/lib/yoke/interface.js +199 -3
  137. package/lib/yoke/package.json +1 -1
  138. package/lib/yoke/provider-credentials.js +96 -0
  139. package/lib/yoke/registry.js +340 -0
  140. package/package.json +12 -8
  141. package/scripts/check-sdk-lock-drift.js +160 -0
  142. package/scripts/check-test-count.js +76 -1
  143. package/scripts/postinstall.js +218 -136
  144. package/scripts/prompt-harness-history.js +202 -0
  145. package/scripts/verify-installed.js +67 -0
  146. package/lib/sdk-permission-ownership.js +0 -136
package/lib/drain.js CHANGED
@@ -1,23 +1,30 @@
1
- // drain.js — graceful drain state for the daemon (lr-6b30).
1
+ // drain.js — drain and memory-pressure state for the daemon (lr-6b30).
2
2
  //
3
- // Drain is entered when either:
4
- // A. The lr-de07 MemoryHigh watermark watcher fires an onCrossing callback.
5
- // B. An operator sends SIGUSR1 or SIGUSR2 (manual drain/restart signal).
3
+ // Two distinct states, deliberately not merged:
6
4
  //
7
- // While draining:
8
- // - New WebSocket session connections are rejected with a structured error.
9
- // - In-flight sessions are allowed to complete. The drain controller checks
10
- // the live query count via opts.getActiveCount() and exits once it hits zero.
11
- // - A configurable drain timeout (default 60 s) forces exit if sessions do
12
- // not complete in time.
5
+ // Drain (operator-initiated restart): entered by SIGUSR1 or SIGUSR2.
6
+ // - New WebSocket connections are rejected with a structured error.
7
+ // - In-flight sessions are allowed to complete; the controller polls
8
+ // opts.getActiveCount() and exits once it hits zero.
9
+ // - A configurable drain timeout (default 60 s) forces exit if sessions do
10
+ // not complete in time.
11
+ //
12
+ // Pressure (MemoryHigh soft limit): entered by the watermark watcher's
13
+ // onCrossing callback, left by its onRecovery callback.
14
+ // - New sessions and new agent work are refused (isRefusingNewWork).
15
+ // - Existing sessions keep running and WebSocket clients stay connected so
16
+ // the pressure report reaches the UI.
17
+ // - The daemon NEVER exits because of pressure. The memory belongs to the
18
+ // sessions' own child processes, which a daemon restart cannot free — it
19
+ // only kills them. MemoryMax and the kernel remain the hard backstop.
13
20
  //
14
21
  // The module exports createDrain(opts), which returns a controller object used
15
- // by daemon.js and the WebSocket gate in server.js.
22
+ // by daemon.js, the WebSocket gate in server.js, and the new-work gate in
23
+ // sdk-bridge.js.
16
24
  //
17
25
  // Design constraints:
18
- // - No second memory poller; consume startMemoryHighWatcher's signal only.
26
+ // - No second memory poller; consume startMemoryHighWatcher's signals only.
19
27
  // - Reuse gracefulShutdown() from daemon.js; do not invent a parallel path.
20
- // - One drain state machine; both trigger paths set the same state.
21
28
 
22
29
  'use strict';
23
30
 
@@ -40,6 +47,9 @@ var DRAIN_POLL_INTERVAL_MS = 1000;
40
47
  * @param {number} [opts.drainTimeoutMs]
41
48
  * Maximum ms to wait for in-flight sessions before forcing exit.
42
49
  * Reads from config.drainTimeoutMs if provided; defaults to 60000.
50
+ * @param {function(boolean, object): void} [opts.onPressureChange]
51
+ * Called with (underPressure, detail) on each pressure transition so the
52
+ * caller can report it (UI broadcast). Errors are swallowed.
43
53
  * @param {function(object): void} [opts.log]
44
54
  * Structured log emitter. Receives a plain object; default emits JSON to
45
55
  * stderr so journald captures it alongside other daemon output.
@@ -67,7 +77,9 @@ function createDrain(opts) {
67
77
  };
68
78
 
69
79
  // --- State ---
80
+ var onPressureChange = typeof opts.onPressureChange === 'function' ? opts.onPressureChange : null;
70
81
  var _isDraining = false;
82
+ var _underPressure = false;
71
83
  var _drainReason = null;
72
84
  var _drainTimeout = null;
73
85
  var _drainPollHandle = null;
@@ -122,7 +134,7 @@ function createDrain(opts) {
122
134
  * Enter drain state. Idempotent: subsequent calls from either trigger path
123
135
  * are no-ops — only the first crossing matters.
124
136
  *
125
- * @param {string} reason — 'memory_high_watermark' | 'signal_usr1' | 'signal_usr2'
137
+ * @param {string} reason — 'signal_usr1' | 'signal_usr2'
126
138
  * @param {object} [detail] — optional extra fields for the log event
127
139
  */
128
140
  function enterDrain(reason, detail) {
@@ -189,21 +201,66 @@ function createDrain(opts) {
189
201
  });
190
202
  }
191
203
 
204
+ function _setPressure(next, event, detail) {
205
+ if (_underPressure === next) return;
206
+ _underPressure = next;
207
+ _emitLog(Object.assign({
208
+ event: event,
209
+ activeCount: getActiveCount(),
210
+ timestamp: new Date().toISOString(),
211
+ }, detail || {}));
212
+ if (onPressureChange) {
213
+ try { onPressureChange(next, detail || {}); } catch (_) {}
214
+ }
215
+ }
216
+
192
217
  /**
193
- * Called by the MemoryHigh watcher's onCrossing callback.
194
- * Enters drain state with the watermark event detail attached to the log.
218
+ * Called by the MemoryHigh watcher's onCrossing callback. Starts refusing
219
+ * new work; never exits the daemon. Idempotent.
195
220
  *
196
221
  * @param {object} [detail] — fields from the watermark event (source, currentBytes, etc.)
197
222
  */
198
223
  function onMemoryHighCrossing(detail) {
199
- enterDrain('memory_high_watermark', detail || {});
224
+ _setPressure(true, 'pressure_enter', detail);
225
+ }
226
+
227
+ /**
228
+ * Called by the MemoryHigh watcher's onRecovery callback. Resumes accepting
229
+ * new work. Idempotent.
230
+ *
231
+ * @param {object} [detail]
232
+ */
233
+ function onMemoryHighRecovery(detail) {
234
+ _setPressure(false, 'pressure_exit', detail);
235
+ }
236
+
237
+ /**
238
+ * True while the soft memory limit is exceeded.
239
+ *
240
+ * @returns {boolean}
241
+ */
242
+ function isUnderPressure() {
243
+ return _underPressure;
244
+ }
245
+
246
+ /**
247
+ * True when new sessions and new agent work must be refused: under memory
248
+ * pressure, or draining for an operator-requested restart.
249
+ *
250
+ * @returns {boolean}
251
+ */
252
+ function isRefusingNewWork() {
253
+ return _underPressure || _isDraining;
200
254
  }
201
255
 
202
256
  return {
203
257
  isDraining: isDraining,
258
+ isUnderPressure: isUnderPressure,
259
+ isRefusingNewWork: isRefusingNewWork,
204
260
  enterDrain: enterDrain,
205
261
  registerSignals: registerSignals,
206
262
  onMemoryHighCrossing: onMemoryHighCrossing,
263
+ onMemoryHighRecovery: onMemoryHighRecovery,
207
264
  // Exposed for testing only.
208
265
  _DEFAULT_DRAIN_TIMEOUT_MS: DEFAULT_DRAIN_TIMEOUT_MS,
209
266
  _DRAIN_POLL_INTERVAL_MS: DRAIN_POLL_INTERVAL_MS,
@@ -0,0 +1,61 @@
1
+ // env-compat.js — reads Clagentic: Console environment variables.
2
+ //
3
+ // Every variable this product owns is named CLAGENTIC_CONSOLE_<NAME>, per the
4
+ // clagentic CLI Naming Standard. Earlier releases read un-scoped names, which
5
+ // collide with the other clagentic products that share the CLAGENTIC_ prefix.
6
+ // For one release the old names are still honoured, with a one-time
7
+ // deprecation warning naming the replacement. Remove ALIASES (and this file's
8
+ // legacy reads) in the release after.
9
+ //
10
+ // This table is the only place a non-CONSOLE CLAGENTIC_ name may appear; the
11
+ // env-namespace test allowlists it.
12
+
13
+ var ALIASES = {
14
+ CLAGENTIC_CONSOLE_HOME: ["CLAGENTIC_HOME", "CLAY_HOME"],
15
+ CLAGENTIC_CONSOLE_CONFIG: ["CLAGENTIC_CONFIG", "CLAY_CONFIG"],
16
+ CLAGENTIC_CONSOLE_DEV: ["CLAGENTIC_DEV", "CLAY_DEV"],
17
+ CLAGENTIC_CONSOLE_DEBUG: ["CLAGENTIC_DEBUG"],
18
+ CLAGENTIC_CONSOLE_SELF_UPDATE: ["CLAGENTIC_SELF_UPDATE"],
19
+ CLAGENTIC_CONSOLE_MAX_CONCURRENT_SESSIONS: ["CLAGENTIC_MAX_CONCURRENT_SESSIONS"],
20
+ CLAGENTIC_CONSOLE_IDLE_RUNTIME_MS: ["CLAY_CODEX_IDLE_MS"],
21
+ CLAGENTIC_CONSOLE_IDLE_REAPER_MS: ["CLAY_CODEX_REAPER_MS"],
22
+ };
23
+
24
+ var _warned = new Set();
25
+
26
+ /**
27
+ * Read a console env var by its CLAGENTIC_CONSOLE_<NAME> name.
28
+ * The new name always wins. Otherwise the first deprecated alias that is set
29
+ * (non-empty) is returned and a one-time warning is logged.
30
+ *
31
+ * @param {string} name A key of ALIASES.
32
+ * @param {object} [opts]
33
+ * @param {object} [opts.env=process.env]
34
+ * @param {function} [opts.warn=console.warn]
35
+ * @param {Set} [opts.warned] Dedup set; defaults to a module-level set.
36
+ * @returns {string|undefined}
37
+ */
38
+ function readConsoleEnv(name, opts) {
39
+ opts = opts || {};
40
+ var env = opts.env || process.env;
41
+ var warn = opts.warn || console.warn;
42
+ var warned = opts.warned || _warned;
43
+
44
+ if (env[name]) return env[name];
45
+
46
+ var legacy = ALIASES[name] || [];
47
+ for (var i = 0; i < legacy.length; i++) {
48
+ if (!env[legacy[i]]) continue;
49
+ if (!warned.has(legacy[i])) {
50
+ warned.add(legacy[i]);
51
+ warn("[config] " + legacy[i] + " is deprecated and will be removed in a future release; set " + name + " instead.");
52
+ }
53
+ return env[legacy[i]];
54
+ }
55
+ return undefined;
56
+ }
57
+
58
+ module.exports = {
59
+ ALIASES: ALIASES,
60
+ readConsoleEnv: readConsoleEnv,
61
+ };
@@ -0,0 +1,45 @@
1
+ // Commands the daemon sends to a connected browser extension, and the rule for
2
+ // who may answer them.
3
+ //
4
+ // A command is an "extension" prompt in the prompt registry; the extension
5
+ // answers with an extension_result naming the command's requestId. Any client
6
+ // of the project can send that message, so each command remembers the socket
7
+ // it went to and only that socket's answer is accepted.
8
+
9
+ var { promptsFor } = require("./prompt-registry");
10
+
11
+ /**
12
+ * @param {object} deps
13
+ * @param {function(): object} deps.getSessionManager the session manager whose
14
+ * prompt registry opens the commands (read per command: it may not exist yet
15
+ * when this is created)
16
+ * @param {function(object, object)} deps.sendTo (ws, message)
17
+ */
18
+ function createExtensionCommands(deps) {
19
+ var targets = new Map(); // requestId -> ws
20
+
21
+ // Resolves with the extension's result, or null after the timeout.
22
+ function send(ws, command, args, timeout) {
23
+ var opened = promptsFor(deps.getSessionManager()).open(null, "extension", { command: command, args: args }, { timeoutMs: timeout });
24
+ targets.set(opened.requestId, ws);
25
+ var forget = function () { targets.delete(opened.requestId); };
26
+ opened.answer.then(forget, forget);
27
+ deps.sendTo(ws, {
28
+ type: "extension_command",
29
+ command: command,
30
+ args: args,
31
+ requestId: opened.requestId,
32
+ });
33
+ return opened.answer;
34
+ }
35
+
36
+ // Whether `ws` is the socket command `requestId` was sent to. Any other
37
+ // requestId, of any type, is not.
38
+ function mayAnswer(requestId, ws) {
39
+ return targets.get(requestId) === ws;
40
+ }
41
+
42
+ return { send: send, mayAnswer: mayAnswer };
43
+ }
44
+
45
+ module.exports = { createExtensionCommands: createExtensionCommands };
@@ -52,6 +52,10 @@ var INVISIBLE_TYPES = {
52
52
  thinking_delta: 1,
53
53
  thinking_stop: 1,
54
54
  ask_user_answered: 1,
55
+ prompt_request: 1,
56
+ prompt_pending: 1,
57
+ prompt_resolved: 1,
58
+ prompt_cancel: 1,
55
59
  permission_request: 1,
56
60
  permission_request_pending: 1,
57
61
  permission_cancel: 1,
@@ -0,0 +1,71 @@
1
+ // idle-adapter-reaper.js - gives back the agent runtimes an adapter keeps
2
+ // running while nothing uses them (the Codex adapter keeps one app-server per
3
+ // environment). The daemon ticks this on a timer; each project context
4
+ // exposes reclaimIdleAdapters, which reaches its own adapters, so the timer
5
+ // never needs to know how a project holds them.
6
+
7
+ /**
8
+ * Ends the idle runtimes of every adapter in the map that can report them.
9
+ * @param {object} adapters vendor -> adapter, as a project context holds them
10
+ * @param {number} idleMs how long a runtime must have been quiet
11
+ * @returns {Promise<boolean>} true when at least one runtime was ended
12
+ */
13
+ function reclaimIdleAdapters(adapters, idleMs) {
14
+ var pending = [];
15
+ Object.keys(adapters || {}).forEach(function (vendor) {
16
+ var adapter = adapters[vendor];
17
+ if (adapter && typeof adapter.shutdownIfIdle === "function") {
18
+ pending.push(Promise.resolve(adapter.shutdownIfIdle(idleMs)));
19
+ }
20
+ });
21
+ return Promise.all(pending).then(function (results) {
22
+ return results.some(Boolean);
23
+ });
24
+ }
25
+
26
+ /**
27
+ * One reaper tick over every project of a relay.
28
+ * @param {{forEachProject: function}} relay
29
+ * @param {number} idleMs
30
+ * @returns {Promise<void>} settles when every project has been looked at
31
+ */
32
+ function reapIdleAdapters(relay, idleMs) {
33
+ if (!relay || typeof relay.forEachProject !== "function") return Promise.resolve();
34
+ var pending = [];
35
+ relay.forEachProject(function (ctx, slug) {
36
+ if (!ctx || typeof ctx.reclaimIdleAdapters !== "function") return;
37
+ var reclaimed;
38
+ try {
39
+ reclaimed = ctx.reclaimIdleAdapters(idleMs);
40
+ } catch (e) {
41
+ console.error("[daemon] Idle runtime reclaim failed for " + (slug || "a project") + ":", e && e.message ? e.message : e);
42
+ return;
43
+ }
44
+ pending.push(Promise.resolve(reclaimed).catch(function (e) {
45
+ console.error("[daemon] Idle runtime reclaim failed for " + (slug || "a project") + ":", e && e.message ? e.message : e);
46
+ }));
47
+ });
48
+ return Promise.all(pending).then(function () {});
49
+ }
50
+
51
+ /**
52
+ * Starts the periodic tick. The timer does not keep the process alive.
53
+ * @param {function(): object} getRelay the relay may not exist yet at first tick
54
+ * @param {{idleMs: number, intervalMs: number}} options
55
+ * @returns {function(): void} stop
56
+ */
57
+ function startIdleAdapterReaper(getRelay, options) {
58
+ var handle = setInterval(function () {
59
+ reapIdleAdapters(getRelay(), options.idleMs);
60
+ }, options.intervalMs);
61
+ if (handle && typeof handle.unref === "function") handle.unref();
62
+ return function stop() {
63
+ clearInterval(handle);
64
+ };
65
+ }
66
+
67
+ module.exports = {
68
+ reclaimIdleAdapters: reclaimIdleAdapters,
69
+ reapIdleAdapters: reapIdleAdapters,
70
+ startIdleAdapterReaper: startIdleAdapterReaper,
71
+ };
@@ -0,0 +1,78 @@
1
+ // link-trap.js — refuses to run a daemon from an `npm link` install.
2
+ //
3
+ // `npm link` / `npm install -g <workspace-path>` creates a symlink at the
4
+ // UNSCOPED package name next to the scoped global install
5
+ // (<node_modules>/clagentic-console beside <node_modules>/@clagentic/console).
6
+ // With that symlink present, edits in a working tree go live in the daemon
7
+ // without a pack/install step.
8
+ //
9
+ // Two places are checked, because the daemon may be reached either way:
10
+ // - beside the package dir, when it sits in a scoped global install;
11
+ // - beside the global node_modules implied by the bin path it was invoked
12
+ // through (<prefix>/bin/clagentic-console -> <prefix>/lib/node_modules),
13
+ // which is the only signal left when the bin symlink resolves into a
14
+ // working tree. A plain dev checkout matches neither and is never flagged.
15
+
16
+ var fs = require("fs");
17
+ var path = require("path");
18
+
19
+ /**
20
+ * @param {string} pkgDir Package root (the directory holding package.json).
21
+ * @param {object} [opts]
22
+ * @param {string} [opts.binPath] The path the CLI was invoked through (argv[1]).
23
+ * @param {object} [opts.fs] fs-like exposing lstatSync; for tests.
24
+ * @returns {string|null} The offending symlink path, or null.
25
+ * @throws {LinkTrapProbeError} A candidate could not be inspected for a reason
26
+ * other than not existing; callers must refuse to start.
27
+ */
28
+ function findLinkTrap(pkgDir, opts) {
29
+ opts = opts || {};
30
+ var fsImpl = opts.fs || fs;
31
+ var candidates = [];
32
+
33
+ var scopeDir = path.dirname(pkgDir);
34
+ if (path.basename(scopeDir) === "@clagentic") {
35
+ candidates.push(path.join(path.dirname(scopeDir), "clagentic-console"));
36
+ }
37
+ if (opts.binPath && path.basename(path.dirname(opts.binPath)) === "bin") {
38
+ var prefix = path.dirname(path.dirname(opts.binPath));
39
+ candidates.push(path.join(prefix, "lib", "node_modules", "clagentic-console"));
40
+ }
41
+
42
+ for (var i = 0; i < candidates.length; i++) {
43
+ var isLink;
44
+ try {
45
+ isLink = fsImpl.lstatSync(candidates[i]).isSymbolicLink();
46
+ } catch (e) {
47
+ // Only "nothing there" means no trap. Any other failure (EACCES, ELOOP,
48
+ // EIO, ...) leaves the question unanswered, and starting a daemon from a
49
+ // possibly linked working tree is the thing this guard exists to stop.
50
+ if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) continue;
51
+ throw new LinkTrapProbeError(candidates[i], e);
52
+ }
53
+ if (isLink) return candidates[i];
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /** Thrown by findLinkTrap when a candidate path cannot be inspected. */
59
+ function LinkTrapProbeError(probedPath, cause) {
60
+ var errno = cause && cause.code ? cause.code : "UNKNOWN";
61
+ this.name = "LinkTrapProbeError";
62
+ this.code = "LINK_TRAP_PROBE_FAILED";
63
+ this.path = probedPath;
64
+ this.errno = errno;
65
+ this.message = "cannot check " + probedPath + " for an npm link trap (" + errno + (cause && cause.message ? ": " + cause.message : "") + ")";
66
+ }
67
+ LinkTrapProbeError.prototype = Object.create(Error.prototype);
68
+ LinkTrapProbeError.prototype.constructor = LinkTrapProbeError;
69
+
70
+ function linkTrapMessage(trap) {
71
+ return [
72
+ "ERROR: " + trap + " is a symlink (npm link trap). Remove it before starting:",
73
+ " rm " + trap,
74
+ "Then reinstall via: npm pack --pack-destination <dir> && npm install -g <dir>/clagentic-console-*.tgz",
75
+ ].join("\n");
76
+ }
77
+
78
+ module.exports = { findLinkTrap: findLinkTrap, linkTrapMessage: linkTrapMessage, LinkTrapProbeError: LinkTrapProbeError };
@@ -0,0 +1,73 @@
1
+ // lr-f7c100 — declare human presence to LORE for a Codex session the
2
+ // operator is driving through the console.
3
+ //
4
+ // THE PRINCIPLE (operator, lore lr-df5939): a session mints iff a human is
5
+ // in it — nothing else, no launcher special-casing. The Console is the
6
+ // component that KNOWS a human is present (a person is typing into it), so
7
+ // the Console is the correct declarer.
8
+ //
9
+ // Claude (SDK) console sessions are already covered by LORE's own pulse
10
+ // hook (lore PR #1897) — Claude Code's Stop-hook lifecycle fires for an
11
+ // SDK-driven query exactly as it does for the `claude` CLI, so no console
12
+ // code is needed on that path. Codex sessions have no equivalent hook
13
+ // (Codex is a separate app-server protocol the console drives directly),
14
+ // so the console itself must call the declarer for Codex.
15
+ //
16
+ // FAIL-OPEN is load-bearing: a host without LORE installed, or any failure
17
+ // of the `lore` CLI, must never affect session create. This call is fired
18
+ // and forgotten — its result is never awaited by session-create/message
19
+ // dispatch, and any error is swallowed after a best-effort log line.
20
+ var { execFile } = require("child_process");
21
+
22
+ // Bounded so a hung/missing `lore` binary can never accumulate indefinitely
23
+ // under load — this is advisory telemetry, not something callers wait on.
24
+ var ATTEST_TIMEOUT_MS = 5000;
25
+
26
+ /**
27
+ * Declare that a human is driving the given vendor session id, via LORE's
28
+ * platform-agnostic attestation verb (`lore session attest-human <sid>`).
29
+ *
30
+ * Never throws, never returns a promise the caller needs to await for
31
+ * correctness — session create/message dispatch must proceed identically
32
+ * whether this succeeds, fails, or LORE is entirely absent from the host.
33
+ *
34
+ * @param {string} sessionId - the vendor's own session id (e.g. the Codex
35
+ * rollout/thread id) that LORE keys attestation on for that platform.
36
+ * @param {function} [onSettled] - TEST-ONLY hook, invoked with the execFile
37
+ * callback's (err) once the child process settles. Production call sites
38
+ * never pass this — attestHumanSession remains fire-and-forget for them.
39
+ * Exists so a regression test can deterministically wait for the real
40
+ * async execFile to finish instead of mutating global process state
41
+ * (e.g. process.env.PATH) and returning before the spawn it triggered
42
+ * has actually resolved, which would race the test's own cleanup and
43
+ * risk leaking an uncontrolled child process into the suite (lr-f7c100
44
+ * PEACHES fnd: verify no test path reaches the real CLI unawaited).
45
+ */
46
+ function attestHumanSession(sessionId, onSettled) {
47
+ if (!sessionId || typeof sessionId !== "string") {
48
+ if (typeof onSettled === "function") onSettled(null);
49
+ return;
50
+ }
51
+ try {
52
+ execFile("lore", ["session", "attest-human", sessionId], { timeout: ATTEST_TIMEOUT_MS }, function (err) {
53
+ if (err) {
54
+ // ENOENT (lore not installed) is the expected fail-open case on a
55
+ // host without LORE — log at a lower severity than an actual CLI
56
+ // failure so normal operation isn't noisy on hosts that never run it.
57
+ if (err.code === "ENOENT") {
58
+ console.log("[lore-attestation] lore CLI not found — skipping human-presence attestation (fail-open)");
59
+ } else {
60
+ console.error("[lore-attestation] attest-human failed for session " + sessionId + ":", err.message);
61
+ }
62
+ }
63
+ if (typeof onSettled === "function") onSettled(err);
64
+ });
65
+ } catch (e) {
66
+ // Defensive: execFile itself should not throw synchronously, but this is
67
+ // a fail-open surface — no error here may ever propagate to the caller.
68
+ console.error("[lore-attestation] Unexpected error invoking lore CLI:", e.message);
69
+ if (typeof onSettled === "function") onSettled(e);
70
+ }
71
+ }
72
+
73
+ module.exports = { attestHumanSession: attestHumanSession };
package/lib/mcp-local.js CHANGED
@@ -26,10 +26,12 @@ var CLAY_CONFIG_PATH = path.join(CONFIG_DIR, "mcp.json");
26
26
  }());
27
27
 
28
28
  function createLocalMcp() {
29
- var _configCache = {}; // name -> { command, args, env, url }
30
- var _processes = {}; // name -> { proc, buffer, ready, tools, pendingInit }
31
- var _pendingRequests = {}; // rpcId -> { callId, resolve, reject, timer }
32
- var _initCallbacks = {}; // rpcId -> { name, phase }
29
+ // Keyed by server names (from config files and clients) and by ids a child
30
+ // process echoes back, so none of these may inherit from Object.prototype.
31
+ var _configCache = Object.create(null); // name -> { command, args, env, url }
32
+ var _processes = Object.create(null); // name -> { proc, buffer, ready, tools, pendingInit }
33
+ var _pendingRequests = Object.create(null); // rpcId -> { callId, resolve, reject, timer }
34
+ var _initCallbacks = Object.create(null); // rpcId -> { name, phase }
33
35
  var _jsonRpcId = 1;
34
36
  var _initialized = false;
35
37
  var _onServersReady = null; // callback when server list changes
@@ -60,7 +62,7 @@ function createLocalMcp() {
60
62
 
61
63
  function getMergedServers() {
62
64
  var config = readConfig();
63
- var merged = Object.assign({}, config.mcpServers || {});
65
+ var merged = Object.assign(Object.create(null), config.mcpServers || {});
64
66
 
65
67
  var includes = config.include || [];
66
68
  for (var i = 0; i < includes.length; i++) {
@@ -270,7 +272,7 @@ function createLocalMcp() {
270
272
  for (var i = 0; i < names.length; i++) {
271
273
  killServer(names[i]);
272
274
  }
273
- _processes = {};
275
+ _processes = Object.create(null);
274
276
  _initialized = false;
275
277
  }
276
278
 
@@ -0,0 +1,116 @@
1
+ // mcp-tool-input.js - recreates an in-process MCP tool from a descriptor (the
2
+ // worker process, the proxies for browser-extension and local MCP servers).
3
+ //
4
+ // Two jobs, kept apart on purpose:
5
+ // - describing the parameters to the model uses a zod schema built by zod's
6
+ // own converter (z.fromJSONSchema), which never strips or alters arguments;
7
+ // - deciding whether a call's arguments are valid uses ajv on the tool's
8
+ // original JSON schema, applied to the arguments exactly as received.
9
+ // zod's converter is documented as semi-experimental and widens some schemas
10
+ // (a `required` list next to no `properties`, an enum next to a `type`,
11
+ // `uniqueItems`), so it never decides validity. A tool whose schema either
12
+ // library cannot read is left out and reported by the caller; nothing is
13
+ // registered with a looser schema than the one the tool declared.
14
+
15
+ var Ajv2020 = require("ajv/dist/2020");
16
+
17
+ function UnsupportedSchemaError(what) {
18
+ var err = new Error(what);
19
+ err.code = "UNSUPPORTED_SCHEMA";
20
+ return err;
21
+ }
22
+
23
+ // Keys that name the document, not a constraint; ajv refuses a second schema
24
+ // with the same $id and an unknown $schema, so neither is passed on.
25
+ var DOCUMENT_KEYS = ["$schema", "$id"];
26
+
27
+ /**
28
+ * The zod schema an SDK tool() call registers: one field per top-level
29
+ * property, plus a catchall so every other argument passes through unchanged.
30
+ * Built from the properties, required list and definitions only; root-level
31
+ * composition cannot be expressed and is enforced by the validator instead.
32
+ *
33
+ * It is a full zod object, not a raw shape, on purpose: the SDK wraps a raw
34
+ * shape in a plain z.object, which drops every key the shape does not name
35
+ * before the handler (and so ajv) sees the call. A zod schema is registered
36
+ * as given, so the catchall is what keeps the arguments as the model sent them.
37
+ */
38
+ function describeSchema(z, inputSchema) {
39
+ if (!inputSchema.properties) return passThrough(z, {});
40
+ if (typeof z.fromJSONSchema !== "function") {
41
+ throw UnsupportedSchemaError("the installed zod has no fromJSONSchema");
42
+ }
43
+ var described = { type: "object", properties: inputSchema.properties };
44
+ ["required", "$defs", "definitions"].forEach(function (key) {
45
+ if (inputSchema[key] !== undefined) described[key] = inputSchema[key];
46
+ });
47
+ // zod turns "format" into a check (z.url(), z.email()); the schema declares
48
+ // it as an annotation and the validator ignores it, so the description must
49
+ // not reject what the schema accepts. A string-valued "format" key is the
50
+ // keyword; an object-valued one is a property of that name and stays.
51
+ var withoutFormat = JSON.parse(JSON.stringify(described), function (key, value) {
52
+ return key === "format" && typeof value === "string" ? undefined : value;
53
+ });
54
+ var converted = z.fromJSONSchema(withoutFormat);
55
+ if (!converted || typeof converted.shape !== "object" || converted.shape === null) {
56
+ throw UnsupportedSchemaError("zod did not produce an object schema for the tool's properties");
57
+ }
58
+ return passThrough(z, converted.shape);
59
+ }
60
+
61
+ function passThrough(z, shape) {
62
+ if (typeof z.object !== "function" || typeof z.unknown !== "function") {
63
+ throw UnsupportedSchemaError("the installed zod has no object/unknown to describe the parameters");
64
+ }
65
+ return z.object(shape).catchall(z.unknown());
66
+ }
67
+
68
+ function compileValidator(inputSchema) {
69
+ var copy = Object.assign({}, inputSchema);
70
+ DOCUMENT_KEYS.forEach(function (key) { delete copy[key]; });
71
+ // format is an annotation unless a validator opts in (JSON Schema 2020-12
72
+ // section 7.2.1); strict:false lets keywords ajv does not know pass as the
73
+ // annotations they are, while a malformed schema still throws on compile.
74
+ var ajv = new Ajv2020({ strict: false, validateFormats: false });
75
+ var validate = ajv.compile(copy);
76
+ return function (args) {
77
+ if (validate(args)) return null;
78
+ return ajv.errorsText(validate.errors);
79
+ };
80
+ }
81
+
82
+ /**
83
+ * @param {object} z zod
84
+ * @param {?object} inputSchema the tool's JSON input schema (none: no parameters)
85
+ * @param {function} handler (args, extra) -> result or promise
86
+ * @returns {{inputSchema: (object), handler: function}} what to pass to the
87
+ * SDK's tool() as the input schema (a zod object that keeps every argument,
88
+ * or an empty raw shape for a tool with no parameters) and a handler that
89
+ * answers invalid arguments with an error result and otherwise calls `handler`
90
+ * @throws {Error} when either library cannot read the schema; the caller leaves
91
+ * the tool out and reports it
92
+ */
93
+ function prepareTool(z, inputSchema, handler) {
94
+ if (inputSchema === undefined || inputSchema === null) return { inputSchema: {}, handler: handler };
95
+ if (typeof inputSchema !== "object" || Array.isArray(inputSchema)) {
96
+ throw UnsupportedSchemaError("an input schema that is not an object");
97
+ }
98
+ var described = describeSchema(z, inputSchema);
99
+ var invalid = compileValidator(inputSchema);
100
+ return {
101
+ inputSchema: described,
102
+ handler: function (args, extra) {
103
+ var problem = invalid(args);
104
+ if (problem === null) return handler(args, extra);
105
+ return Promise.resolve({
106
+ isError: true,
107
+ content: [{ type: "text", text: "Invalid arguments: " + problem }],
108
+ });
109
+ },
110
+ };
111
+ }
112
+
113
+ module.exports = {
114
+ prepareTool: prepareTool,
115
+ UnsupportedSchemaError: UnsupportedSchemaError,
116
+ };