@clagentic/console 1.9.0 → 1.10.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) 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 +9 -3
  5. package/bin/cli.js +40 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/agent-dispatch-tool.js +20 -0
  8. package/lib/audit.js +3 -2
  9. package/lib/build-changes.js +79 -0
  10. package/lib/build-identity.js +192 -0
  11. package/lib/build-monitor.js +125 -0
  12. package/lib/build-sha.json +2 -2
  13. package/lib/build-update-check.js +138 -0
  14. package/lib/build-update-offer.js +141 -0
  15. package/lib/build-update-restart.js +142 -0
  16. package/lib/build-update-standing.js +184 -0
  17. package/lib/cli/daemon-launch.js +25 -22
  18. package/lib/cli/ipc-subcommands.js +6 -0
  19. package/lib/cli/session-subcommands.js +122 -0
  20. package/lib/cli-sessions.js +8 -1
  21. package/lib/codex-defaults.js +8 -2
  22. package/lib/config.js +32 -20
  23. package/lib/daemon-env-settings.js +84 -0
  24. package/lib/daemon-projects.js +57 -0
  25. package/lib/daemon.js +288 -205
  26. package/lib/drain.js +74 -17
  27. package/lib/env-compat.js +61 -0
  28. package/lib/extension-commands.js +45 -0
  29. package/lib/history-visibility.js +4 -0
  30. package/lib/idle-adapter-reaper.js +71 -0
  31. package/lib/link-trap.js +78 -0
  32. package/lib/mcp-local.js +8 -6
  33. package/lib/mcp-tool-input.js +116 -0
  34. package/lib/mcp-tool-schema.js +179 -0
  35. package/lib/memory-limits.js +61 -5
  36. package/lib/memory-setting-validate.js +65 -0
  37. package/lib/memory-shed.js +13 -32
  38. package/lib/new-work-gate.js +47 -0
  39. package/lib/os-users.js +5 -3
  40. package/lib/project-access.js +139 -0
  41. package/lib/project-connection.js +37 -22
  42. package/lib/project-external-trigger.js +166 -105
  43. package/lib/project-file-scope.js +172 -0
  44. package/lib/project-file-watch.js +86 -61
  45. package/lib/project-filesystem.js +144 -128
  46. package/lib/project-git.js +119 -0
  47. package/lib/project-http.js +44 -28
  48. package/lib/project-loop.js +17 -9
  49. package/lib/project-mcp.js +53 -72
  50. package/lib/project-message-gate.js +70 -0
  51. package/lib/project-notifications.js +31 -4
  52. package/lib/project-prompt-responses.js +217 -0
  53. package/lib/project-sessions.js +192 -355
  54. package/lib/project-user-message.js +27 -15
  55. package/lib/project.js +212 -147
  56. package/lib/projects-dir.js +90 -0
  57. package/lib/prompt-access.js +22 -0
  58. package/lib/prompt-kinds/answer-limits.js +15 -0
  59. package/lib/prompt-kinds/ask-user.js +58 -0
  60. package/lib/prompt-kinds/codecs.js +97 -0
  61. package/lib/prompt-kinds/elicitation.js +77 -0
  62. package/lib/prompt-kinds/extension.js +39 -0
  63. package/lib/prompt-kinds/index.js +68 -0
  64. package/lib/prompt-kinds/permission.js +114 -0
  65. package/lib/prompt-kinds/plan.js +79 -0
  66. package/lib/prompt-kinds/tool-call.js +38 -0
  67. package/lib/prompt-registry.js +680 -0
  68. package/lib/public/app.js +1 -1
  69. package/lib/public/css/diagnostics.css +80 -0
  70. package/lib/public/css/input.css +17 -3
  71. package/lib/public/css/menus.css +10 -0
  72. package/lib/public/css/messages.css +5 -0
  73. package/lib/public/css/rewind.css +22 -0
  74. package/lib/public/index.html +4 -12
  75. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  76. package/lib/public/modules/app-connection.js +7 -0
  77. package/lib/public/modules/app-cursors.js +7 -5
  78. package/lib/public/modules/app-messages.js +52 -47
  79. package/lib/public/modules/app-notifications.js +47 -71
  80. package/lib/public/modules/app-panels.js +61 -59
  81. package/lib/public/modules/app-projects.js +2 -1
  82. package/lib/public/modules/app-rendering.js +4 -10
  83. package/lib/public/modules/build-update-detail.js +54 -0
  84. package/lib/public/modules/diagnostics.js +170 -20
  85. package/lib/public/modules/filebrowser.js +18 -16
  86. package/lib/public/modules/history-visibility.js +4 -0
  87. package/lib/public/modules/mention.js +3 -2
  88. package/lib/public/modules/mode-options.js +38 -0
  89. package/lib/public/modules/project-settings.js +19 -8
  90. package/lib/public/modules/prompt-banner.js +78 -0
  91. package/lib/public/modules/prompt-card.js +201 -0
  92. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  93. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  94. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  95. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  96. package/lib/public/modules/prompt-kinds/index.js +18 -0
  97. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  98. package/lib/public/modules/prompt-kinds/package.json +3 -0
  99. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  100. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  101. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  102. package/lib/public/modules/prompt-state.js +142 -0
  103. package/lib/public/modules/prompts.js +134 -0
  104. package/lib/public/modules/rewind.js +4 -1
  105. package/lib/public/modules/server-settings.js +2 -4
  106. package/lib/public/modules/sidebar-mobile.js +19 -9
  107. package/lib/public/modules/sidebar-sessions.js +21 -14
  108. package/lib/public/modules/sticky-notes.js +3 -2
  109. package/lib/public/modules/team-panel.js +5 -4
  110. package/lib/public/modules/tools.js +81 -906
  111. package/lib/public/modules/vendor-picker.js +53 -0
  112. package/lib/public/modules/vendor-registry.js +142 -0
  113. package/lib/public/sw.js +3 -1
  114. package/lib/rc-migrate.js +44 -0
  115. package/lib/runtime-env-keys.js +109 -0
  116. package/lib/runtime-env.js +236 -0
  117. package/lib/sdk-bridge.js +348 -284
  118. package/lib/sdk-message-processor.js +117 -146
  119. package/lib/sdk-skill-discovery.js +65 -60
  120. package/lib/server-hub-sessions.js +13 -10
  121. package/lib/server-palette.js +28 -19
  122. package/lib/server.js +156 -115
  123. package/lib/service-install.js +96 -0
  124. package/lib/session-capabilities.js +76 -0
  125. package/lib/session-id.js +33 -0
  126. package/lib/session-input-ipc.js +32 -0
  127. package/lib/session-input.js +379 -0
  128. package/lib/session-reclaim.js +284 -0
  129. package/lib/session-resume.js +172 -0
  130. package/lib/sessions.js +61 -30
  131. package/lib/supervisor.js +39 -0
  132. package/lib/turn-initiator.js +108 -0
  133. package/lib/users-permissions.js +9 -6
  134. package/lib/users.js +9 -0
  135. package/lib/utils.js +4 -2
  136. package/lib/vendor-auth.js +22 -0
  137. package/lib/vendor-registry-message.js +66 -0
  138. package/lib/ws-origin.js +99 -0
  139. package/lib/ws-schema.js +36 -23
  140. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  141. package/lib/yoke/adapters/claude-vendor.js +34 -0
  142. package/lib/yoke/adapters/claude-worker.js +57 -87
  143. package/lib/yoke/adapters/claude.js +182 -88
  144. package/lib/yoke/adapters/codex-capabilities.js +40 -0
  145. package/lib/yoke/adapters/codex-vendor.js +46 -0
  146. package/lib/yoke/adapters/codex.js +462 -211
  147. package/lib/yoke/adapters/effort-control.js +34 -0
  148. package/lib/yoke/adapters/permission-relay.js +58 -0
  149. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  150. package/lib/yoke/auth-checks.js +91 -0
  151. package/lib/yoke/capabilities.js +49 -0
  152. package/lib/yoke/codex-app-server.js +30 -56
  153. package/lib/yoke/codex-binary.js +254 -0
  154. package/lib/yoke/codex-command.js +122 -0
  155. package/lib/yoke/codex-protocol.js +96 -0
  156. package/lib/yoke/codex-version.js +135 -0
  157. package/lib/yoke/env-ownership.js +40 -0
  158. package/lib/yoke/index.js +84 -174
  159. package/lib/yoke/install-probe.js +136 -0
  160. package/lib/yoke/instructions.js +7 -11
  161. package/lib/yoke/interface.js +206 -4
  162. package/lib/yoke/package.json +1 -1
  163. package/lib/yoke/provider-credentials.js +96 -0
  164. package/lib/yoke/registry.js +377 -0
  165. package/package.json +12 -9
  166. package/scripts/check-sdk-lock-drift.js +160 -0
  167. package/scripts/check-test-count.js +76 -1
  168. package/scripts/postinstall.js +218 -136
  169. package/scripts/prompt-harness-history.js +202 -0
  170. package/scripts/verify-installed-build.js +59 -17
  171. package/scripts/verify-installed.js +67 -0
  172. package/lib/sdk-permission-ownership.js +0 -136
package/lib/project.js CHANGED
@@ -3,6 +3,7 @@ var path = require("path");
3
3
  var os = require("os");
4
4
  var crypto = require("crypto");
5
5
  var { createSessionManager, stampActivityLocalId } = require("./sessions");
6
+ var { promptsFor } = require("./prompt-registry");
6
7
  var { createSDKBridge, createMessageQueue } = require("./sdk-bridge");
7
8
  var { createTerminalManager } = require("./terminal-manager");
8
9
  var { createNotesManager } = require("./notes");
@@ -19,6 +20,12 @@ var { attachHTTP } = require("./project-http");
19
20
  var { attachImage } = require("./project-image");
20
21
  var { attachKnowledge } = require("./project-knowledge");
21
22
  var { attachFilesystem } = require("./project-filesystem");
23
+ var { safePath, safeClaudePath, createFileAccess } = require("./project-file-scope");
24
+ var { createMessageGate } = require("./project-message-gate");
25
+ var { createProjectAccess } = require("./project-access");
26
+ var { createExtensionCommands } = require("./extension-commands");
27
+ var { ownValue, putOwn } = require("./prompt-kinds/codecs");
28
+ var { isKnownVendor } = require("./yoke");
22
29
  var { attachSessions } = require("./project-sessions");
23
30
  var { attachUserMessage } = require("./project-user-message");
24
31
  var { attachConnection } = require("./project-connection");
@@ -26,6 +33,13 @@ var { detectLite } = require("./lite-detect");
26
33
  var { attachMcp } = require("./project-mcp");
27
34
  var { createLocalMcp } = require("./mcp-local");
28
35
  var { attachTeam } = require("./project-team");
36
+ var runtimeEnv = require("./runtime-env");
37
+ var { INITIATORS } = require("./turn-initiator");
38
+ var mcpToolSchema = require("./mcp-tool-schema");
39
+ var { reclaimIdleAdapters } = require("./idle-adapter-reaper");
40
+ var sessionCapabilities = require("./session-capabilities");
41
+ var sessionReclaim = require("./session-reclaim");
42
+ var { buildVendorRegistryMessage } = require("./vendor-registry-message");
29
43
  // project-notifications is attached globally in server.js, passed via opts.notificationsModule
30
44
 
31
45
  // --- Context Sources persistence ---
@@ -56,30 +70,10 @@ function saveContextSources(slug, sessionId, activeIds) {
56
70
  }
57
71
  }
58
72
 
59
- // Validate environment variable string (KEY=VALUE per line)
60
- // Returns null if valid, or an error string if invalid
61
- function validateEnvString(str) {
62
- if (!str || !str.trim()) return null;
63
- var lines = str.split("\n");
64
- for (var i = 0; i < lines.length; i++) {
65
- var line = lines[i].trim();
66
- if (!line || line.charAt(0) === "#") continue;
67
- // Must be KEY=VALUE format
68
- var eqIdx = line.indexOf("=");
69
- if (eqIdx < 1) return "Invalid format at line " + (i + 1) + ": expected KEY=VALUE";
70
- var key = line.substring(0, eqIdx);
71
- // Key must be valid env var name (no shell metacharacters)
72
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
73
- return "Invalid variable name at line " + (i + 1) + ": " + key;
74
- }
75
- // Value must not contain shell injection characters
76
- var value = line.substring(eqIdx + 1);
77
- if (/[`$\\;|&><(){}\n]/.test(value) && !/^["'].*["']$/.test(value)) {
78
- return "Potentially unsafe value at line " + (i + 1) + ": shell metacharacters detected";
79
- }
80
- }
81
- return null;
82
- }
73
+ // Validate an environment variable text (KEY=VALUE per line) before it is saved.
74
+ // Returns null if valid, or the message to show the user. Also refuses the
75
+ // variables Settings may not set (lib/runtime-env-keys.js).
76
+ var validateEnvString = runtimeEnv.validateEnvText;
83
77
 
84
78
  // YOKE adapter (replaces direct SDK access)
85
79
  var yoke = require("./yoke");
@@ -97,46 +91,6 @@ var BINARY_EXTS = new Set([
97
91
  ]);
98
92
  var IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".ico"]);
99
93
  var FS_MAX_SIZE = 512 * 1024;
100
- function safePath(base, requested) {
101
- var resolved = path.resolve(base, requested);
102
- if (resolved !== base && !resolved.startsWith(base + path.sep)) return null;
103
- try {
104
- var real = fs.realpathSync(resolved);
105
- if (real !== base && !real.startsWith(base + path.sep)) return null;
106
- return real;
107
- } catch (e) {
108
- return null;
109
- }
110
- }
111
-
112
- // Resolve an absolute path without requiring it to be within cwd.
113
- // Used as fallback in OS user mode where ACL enforces access at the OS level.
114
- function safeAbsPath(requested) {
115
- if (!requested) return null;
116
- var resolved = path.resolve(requested);
117
- try {
118
- return fs.realpathSync(resolved);
119
- } catch (e) {
120
- return null;
121
- }
122
- }
123
-
124
- // Resolve an absolute path within the Claude Code data directory (~/.claude/).
125
- // Used as read-only fallback so plan files and other Claude-owned paths that live
126
- // outside the project cwd (e.g. ~/.claude/plans/) can be previewed in the file viewer.
127
- function safeClaudePath(requested) {
128
- if (!requested) return null;
129
- var claudeDir = path.join(require("./config").REAL_HOME, ".claude");
130
- var resolved = path.resolve(requested);
131
- if (resolved !== claudeDir && !resolved.startsWith(claudeDir + path.sep)) return null;
132
- try {
133
- var real = fs.realpathSync(resolved);
134
- if (real !== claudeDir && !real.startsWith(claudeDir + path.sep)) return null;
135
- return real;
136
- } catch (e) {
137
- return null;
138
- }
139
- }
140
94
 
141
95
  /**
142
96
  * Create a project context — per-project state and handlers.
@@ -182,8 +136,24 @@ function createProjectContext(opts) {
182
136
  var updateChannel = opts.updateChannel || "stable";
183
137
  var onSetUpdateChannel = opts.onSetUpdateChannel || null;
184
138
  var osUsers = opts.osUsers || false;
139
+ // server.js wires the daemon's resolver for every real project. A context
140
+ // built without one (unit harnesses) has no user system behind it, so it is
141
+ // single-user: a connection with no user record is its implicit owner.
142
+ var projectAccess = opts.projectAccess || createProjectAccess({
143
+ users: usersModule,
144
+ onGetProjectAccess: null,
145
+ isMultiUser: function () { return false; },
146
+ });
185
147
  var projectOwnerId = opts.projectOwnerId || null;
186
148
  var worktreeMeta = opts.worktreeMeta || null; // { parentSlug, branch, accessible }
149
+ // A worktree has no environment settings of its own: it runs with its
150
+ // parent project's, under the same ownership rule, and the daemon's access
151
+ // lookup answers for it with the parent's record (and so the parent's owner).
152
+ var envSlug = worktreeMeta && worktreeMeta.parentSlug ? worktreeMeta.parentSlug : slug;
153
+ function getEnvOwnerId() {
154
+ var access = projectAccess.resolve(slug);
155
+ return (access && access.ownerId) || null;
156
+ }
187
157
  var onCreateWorktree = opts.onCreateWorktree || null;
188
158
  var serverPort = opts.port || 2633;
189
159
  var serverTls = opts.tls || false;
@@ -198,9 +168,10 @@ function createProjectContext(opts) {
198
168
  var _liteStatus = detectLite();
199
169
 
200
170
  // --- YOKE adapters (multi-vendor, lazy init) ---
201
- var _yokeState = yoke.createAdapters({ cwd: cwd, slug: slug });
171
+ var _yokeState = yoke.createAdapters({ cwd: cwd, slug: slug, osUsers: osUsers });
202
172
  var adapters = _yokeState.adapters;
203
- var defaultVendor = adapters.claude ? "claude" : Object.keys(adapters)[0] || "claude";
173
+ // The project starts on the most preferred registered agent that is available.
174
+ var defaultVendor = yoke.registry.defaultVendorId(Object.keys(adapters));
204
175
  var adapter = adapters[defaultVendor] || null;
205
176
 
206
177
  // Browser MCP server runs in-process via createSdkMcpServer (no child process spawn).
@@ -273,29 +244,22 @@ function createProjectContext(opts) {
273
244
 
274
245
  // --- Browser extension state (shared mutable object) ---
275
246
  var _extToken = crypto.randomUUID(); // Auth token for MCP server bridge
247
+ // The tab list is keyed by tab ids the extension reports, so it has no
248
+ // prototype to inherit from; it is only ever updated in place so every
249
+ // holder of the reference sees the current tabs.
276
250
  var browserState = {
277
- _browserTabList: {},
251
+ _browserTabList: Object.create(null),
278
252
  _extensionWs: null,
279
- pendingExtensionRequests: {}
280
253
  };
281
254
 
282
- function sendExtensionCommand(ws, command, args, timeout) {
283
- return new Promise(function(resolve) {
284
- var requestId = crypto.randomUUID();
285
- var ms = timeout || 3000;
286
- var timer = setTimeout(function() {
287
- delete browserState.pendingExtensionRequests[requestId];
288
- resolve(null);
289
- }, ms);
290
- browserState.pendingExtensionRequests[requestId] = { resolve: resolve, timer: timer };
291
- sendTo(ws, {
292
- type: "extension_command",
293
- command: command,
294
- args: args,
295
- requestId: requestId
296
- });
297
- });
298
- }
255
+ // The extension answers with extension_result (project-user-message.js);
256
+ // an unanswered command resolves to null after its timeout. Only the socket a
257
+ // command was sent to may answer it (lib/extension-commands.js).
258
+ var extensionCommands = createExtensionCommands({
259
+ getSessionManager: function () { return sm; },
260
+ sendTo: sendTo,
261
+ });
262
+ var sendExtensionCommand = extensionCommands.send;
299
263
 
300
264
  // Send extension command via the tracked extension client (for MCP bridge)
301
265
  function sendExtensionCommandAny(command, args, timeout) {
@@ -342,6 +306,14 @@ function createProjectContext(opts) {
342
306
  if (ws.readyState === 1) ws.send(JSON.stringify(obj));
343
307
  }
344
308
 
309
+ // The agent registry to every client, each with the install state of its own
310
+ // OS identity: what one user has installed says nothing about another's.
311
+ function sendVendorRegistry() {
312
+ for (var ws of clients) {
313
+ sendTo(ws, buildVendorRegistryMessage(sm, getLinuxUserForWs(ws)));
314
+ }
315
+ }
316
+
345
317
  function sendToAdmins(obj) {
346
318
  var data = JSON.stringify(obj);
347
319
  for (var ws of clients) {
@@ -404,6 +376,15 @@ function createProjectContext(opts) {
404
376
  }
405
377
  }
406
378
 
379
+ // getHubSchedules(userId) returns only the schedules of projects that user
380
+ // may see, so a schedule list is never sent to a client unfiltered.
381
+ function broadcastHubSchedules() {
382
+ for (var hws of clients) {
383
+ if (hws.readyState !== 1) continue;
384
+ sendTo(hws, { type: "loop_registry_updated", records: getHubSchedules(hws._clagenticUser ? hws._clagenticUser.id : null, projectAccess.authOf(hws)) });
385
+ }
386
+ }
387
+
407
388
  // --- Knowledge engine (delegated to project-knowledge.js) ---
408
389
  var _knowledge = attachKnowledge({
409
390
  cwd: cwd,
@@ -412,19 +393,30 @@ function createProjectContext(opts) {
412
393
  });
413
394
 
414
395
  // --- File/directory watcher engine (delegated to project-file-watch.js) ---
396
+ // One file policy for the WS file messages and the watchers.
397
+ var fileAccess = createFileAccess({
398
+ osUsers: osUsers,
399
+ usersModule: usersModule,
400
+ projectAccess: projectAccess,
401
+ fsAsUser: fsAsUser,
402
+ getOsUserInfoForWs: getOsUserInfoForWs,
403
+ binaryExts: BINARY_EXTS,
404
+ maxSize: FS_MAX_SIZE,
405
+ });
415
406
  var _fileWatch = attachFileWatch({
416
407
  cwd: cwd,
417
- send: send,
408
+ sendTo: sendTo,
418
409
  safePath: safePath,
419
- BINARY_EXTS: BINARY_EXTS,
420
- FS_MAX_SIZE: FS_MAX_SIZE,
410
+ authorize: fileAccess.authorize,
411
+ readFile: fileAccess.readFile,
412
+ listDir: fileAccess.listDir,
421
413
  IGNORED_DIRS: IGNORED_DIRS,
422
414
  });
423
415
  var startFileWatch = _fileWatch.startFileWatch;
424
416
  var stopFileWatch = _fileWatch.stopFileWatch;
425
417
  var startDirWatch = _fileWatch.startDirWatch;
426
- var stopDirWatch = _fileWatch.stopDirWatch;
427
418
  var stopAllDirWatches = _fileWatch.stopAllDirWatches;
419
+ var stopAllWatches = _fileWatch.stopAll;
428
420
 
429
421
  // --- Session manager ---
430
422
  var sm = createSessionManager({
@@ -448,9 +440,13 @@ function createProjectContext(opts) {
448
440
  onSessionDone: onSessionDone,
449
441
  onSessionDeleted: onSessionDeleted,
450
442
  historyInMemMax: historyInMemMax,
443
+ getNotificationsModule: function () { return _notifications; },
444
+ onProcessingChanged: onProcessingChanged,
451
445
  });
452
446
  sm.availableVendors = Object.keys(adapters);
453
447
  sm.defaultVendor = defaultVendor;
448
+ // Sessions the previous shutdown ended with background agents running.
449
+ sessionReclaim.surfaceRestartReclaims({ sm: sm });
454
450
 
455
451
  var _projMode = typeof opts.onGetProjectDefaultMode === "function" ? opts.onGetProjectDefaultMode(slug) : null;
456
452
  var _srvMode = typeof opts.onGetServerDefaultMode === "function" ? opts.onGetServerDefaultMode() : null;
@@ -585,8 +581,10 @@ function createProjectContext(opts) {
585
581
  var sdk = createSDKBridge({
586
582
  cwd: cwd,
587
583
  slug: slug,
584
+ osUsers: osUsers,
588
585
  sessionManager: sm,
589
586
  send: send,
587
+ sendVendorRegistry: sendVendorRegistry,
590
588
  pushModule: pushModule,
591
589
  adapter: adapter,
592
590
  adapters: adapters,
@@ -618,6 +616,24 @@ function createProjectContext(opts) {
618
616
  }
619
617
  return {};
620
618
  },
619
+ // The environment texts saved in Settings, read on every runtime start so
620
+ // a change reaches the next one. The shared text goes to every runtime. The
621
+ // project's text goes to a runtime only if projectEnvApplies says so for
622
+ // the session it starts for (none: a warmup that serves every user, which
623
+ // takes the project's text in single-user mode only).
624
+ getRuntimeEnvSettings: function (session) {
625
+ var shared = typeof opts.onGetSharedEnv === "function" ? opts.onGetSharedEnv() : null;
626
+ var projectText;
627
+ if (typeof opts.onGetProjectEnv === "function" && runtimeEnv.projectEnvApplies({
628
+ multiUser: typeof projectAccess.isMultiUser === "function" ? projectAccess.isMultiUser() : true,
629
+ projectOwnerId: getEnvOwnerId(),
630
+ sessionOwnerId: (session && session.ownerId) || null,
631
+ })) {
632
+ var project = opts.onGetProjectEnv(envSlug);
633
+ projectText = project && project.envrc;
634
+ }
635
+ return { shared: shared && shared.envrc, project: projectText };
636
+ },
621
637
  });
622
638
 
623
639
  // --- Loop engine (delegated to project-loop.js) ---
@@ -635,6 +651,7 @@ function createProjectContext(opts) {
635
651
  pushModule: pushModule,
636
652
  notificationsModule: _notifications,
637
653
  getHubSchedules: getHubSchedules,
654
+ broadcastHubSchedules: broadcastHubSchedules,
638
655
  getAllProjectSessions: getAllProjectSessions,
639
656
  getSessionUnread: getSessionUnread,
640
657
  getStatus: getStatus,
@@ -724,7 +741,7 @@ function createProjectContext(opts) {
724
741
  session.isProcessing = true;
725
742
  onProcessingChanged();
726
743
  sendToSession(session.localId, { type: "status", status: "processing" });
727
- sdk.startQuery(session, text, null, ensureProjectAccessForSession(session));
744
+ sdk.startQuery(session, text, null, ensureProjectAccessForSession(session), INITIATORS.SCHEDULED);
728
745
  sm.broadcastSessionList();
729
746
  }, schedDelay),
730
747
  };
@@ -740,15 +757,28 @@ function createProjectContext(opts) {
740
757
  }
741
758
  }
742
759
 
760
+ // opts.canAccessProject(userId, slug, proof) is wired by server.js for every real
761
+ // project; a context built without it (unit harnesses) has no access policy
762
+ // to apply to its own slug but still refuses to forward to another project.
763
+ var _messageGate = createMessageGate({
764
+ slug: slug,
765
+ canAccess: typeof opts.canAccessProject === "function" ? opts.canAccessProject : null,
766
+ getProject: opts.getProject,
767
+ });
768
+
743
769
  function handleMessage(ws, msg) {
770
+ // --- Access gate: every message is authorized before any handler runs ---
771
+ var gate = _messageGate.authorize(ws, msg);
772
+ if (!gate.allowed) {
773
+ if (gate.error) sendTo(ws, { type: "error", text: gate.error });
774
+ return;
775
+ }
744
776
  // --- Cross-project routing (e.g. permission_response from notification banner) ---
745
- if (msg.targetSlug && msg.targetSlug !== slug && opts.getProject) {
746
- var targetCtx = opts.getProject(msg.targetSlug);
747
- if (targetCtx) {
748
- targetCtx.handleMessage(ws, msg);
749
- return;
750
- }
777
+ if (gate.target) {
778
+ gate.target.handleMessage(ws, gate.message);
779
+ return;
751
780
  }
781
+ msg = gate.message;
752
782
 
753
783
  // --- Team activity messages (delegated to project-team.js) ---
754
784
  if (_team.handleClientMsg(ws, msg)) return;
@@ -769,39 +799,51 @@ function createProjectContext(opts) {
769
799
 
770
800
  // --- Vendor model switching ---
771
801
  if (msg.type === "get_vendor_models") {
802
+ // The vendor is a client-supplied name: only a known vendor is ever
803
+ // used as a key, and every lookup reads own properties only.
804
+ var requestedVendor = isKnownVendor(msg.vendor) ? msg.vendor : null;
772
805
  (async function() {
773
- if (msg.vendor) {
806
+ if (requestedVendor) {
774
807
  try {
775
- var vendorAdapter = adapters[msg.vendor] || null;
808
+ // What the adapter's live session advertises narrows its
809
+ // declaration; it is recorded for this vendor and the clients told.
810
+ var recordInit = function (initResult) {
811
+ sessionCapabilities.recordCapabilities(sm, requestedVendor, initResult && initResult.capabilities);
812
+ sendVendorRegistry();
813
+ };
814
+ var vendorAdapter = ownValue(adapters, requestedVendor) || null;
776
815
  if (!vendorAdapter) {
777
- vendorAdapter = await yoke.lazyCreateAdapter(adapters, msg.vendor, {
816
+ vendorAdapter = await yoke.lazyCreateAdapter(adapters, requestedVendor, {
778
817
  cwd: cwd,
818
+ osUsers: osUsers,
779
819
  clayPort: serverPort,
780
820
  clayTls: serverTls,
781
821
  clayAuthToken: serverAuthToken,
782
822
  slug: slug,
783
- });
784
- } else if ((!sm.modelsByVendor || !sm.modelsByVendor[msg.vendor]) && typeof vendorAdapter.init === "function") {
785
- await vendorAdapter.init({
823
+ runtimeEnv: sdk.getRuntimeEnvOverlay(),
824
+ }, recordInit);
825
+ } else if ((!sm.modelsByVendor || !ownValue(sm.modelsByVendor, requestedVendor)) && typeof vendorAdapter.init === "function") {
826
+ recordInit(await vendorAdapter.init({
786
827
  cwd: cwd,
787
828
  clayPort: serverPort,
788
829
  clayTls: serverTls,
789
830
  clayAuthToken: serverAuthToken,
790
831
  slug: slug,
791
- });
832
+ runtimeEnv: sdk.getRuntimeEnvOverlay(),
833
+ }));
792
834
  }
793
835
  if (vendorAdapter) {
794
836
  sm.availableVendors = Object.keys(adapters);
795
- sm.modelsByVendor = sm.modelsByVendor || {};
796
- if (!sm.modelsByVendor[msg.vendor] && typeof vendorAdapter.supportedModels === "function") {
797
- sm.modelsByVendor[msg.vendor] = await vendorAdapter.supportedModels();
837
+ sm.modelsByVendor = sm.modelsByVendor || Object.create(null);
838
+ if (!ownValue(sm.modelsByVendor, requestedVendor) && typeof vendorAdapter.supportedModels === "function") {
839
+ putOwn(sm.modelsByVendor, requestedVendor, await vendorAdapter.supportedModels({ runtimeEnv: sdk.getRuntimeEnvOverlay() }));
798
840
  }
799
841
  }
800
842
  } catch (e) {
801
- console.error("[project] get_vendor_models lazy init failed for " + msg.vendor + ":", e.message || e);
843
+ console.error("[project] get_vendor_models lazy init failed for " + requestedVendor + ":", e.message || e);
802
844
  }
803
845
  }
804
- var vendorModels = (sm.modelsByVendor && sm.modelsByVendor[msg.vendor]) || [];
846
+ var vendorModels = (sm.modelsByVendor && ownValue(sm.modelsByVendor, requestedVendor)) || [];
805
847
  var firstModel = vendorModels[0] || "";
806
848
  // model value can be string or {value, displayName} object
807
849
  var defaultModel = typeof firstModel === "string" ? firstModel : (firstModel.value || "");
@@ -817,7 +859,7 @@ function createProjectContext(opts) {
817
859
  }
818
860
  }
819
861
  }
820
- sendTo(ws, { type: "model_info", model: modelToSend, models: vendorModels, vendor: msg.vendor, availableVendors: sm.availableVendors || [], installedVendors: sm.installedVendors || [] });
862
+ sendTo(ws, { type: "model_info", model: modelToSend, models: vendorModels, vendor: typeof msg.vendor === "string" ? msg.vendor : "", availableVendors: sm.availableVendors || [] });
821
863
  })();
822
864
  return;
823
865
  }
@@ -918,6 +960,7 @@ function createProjectContext(opts) {
918
960
  sdk: sdk,
919
961
  tm: tm,
920
962
  clients: clients,
963
+ getNotificationsModule: function () { return _notifications; },
921
964
  send: send,
922
965
  sendTo: sendTo,
923
966
  sendToAdmins: sendToAdmins,
@@ -925,6 +968,7 @@ function createProjectContext(opts) {
925
968
  sendToSessionOthers: sendToSessionOthers,
926
969
  opts: opts,
927
970
  usersModule: usersModule,
971
+ projectAccess: projectAccess,
928
972
  userPresence: userPresence,
929
973
  pushModule: pushModule,
930
974
  getSessionForWs: getSessionForWs,
@@ -941,6 +985,7 @@ function createProjectContext(opts) {
941
985
  moveScheduleToProject: moveScheduleToProject,
942
986
  moveAllSchedulesToProject: moveAllSchedulesToProject,
943
987
  getHubSchedules: getHubSchedules,
988
+ broadcastHubSchedules: broadcastHubSchedules,
944
989
  fetchVersion: fetchVersion,
945
990
  isNewer: isNewer,
946
991
  scheduleMessage: scheduleMessage,
@@ -986,6 +1031,7 @@ function createProjectContext(opts) {
986
1031
  onProcessingChanged: onProcessingChanged,
987
1032
  _loop: _loop,
988
1033
  browserState: browserState,
1034
+ mayAnswerExtensionCommand: extensionCommands.mayAnswer,
989
1035
  sendExtensionCommandAny: sendExtensionCommandAny,
990
1036
  requestTabContext: requestTabContext,
991
1037
  scheduleMessage: scheduleMessage,
@@ -1006,21 +1052,20 @@ function createProjectContext(opts) {
1006
1052
  sm: sm,
1007
1053
  send: send,
1008
1054
  sendTo: sendTo,
1009
- safePath: safePath,
1010
- safeAbsPath: safeAbsPath,
1011
- safeClaudePath: safeClaudePath,
1055
+ fileAccess: fileAccess,
1012
1056
  getOsUserInfoForWs: getOsUserInfoForWs,
1013
1057
  startFileWatch: startFileWatch,
1014
1058
  stopFileWatch: stopFileWatch,
1015
1059
  startDirWatch: startDirWatch,
1016
1060
  usersModule: usersModule,
1061
+ projectAccess: projectAccess,
1017
1062
  fsAsUser: fsAsUser,
1018
1063
  validateEnvString: validateEnvString,
1064
+ envSlug: envSlug,
1065
+ getEnvOwnerId: getEnvOwnerId,
1019
1066
  opts: opts,
1020
1067
  IGNORED_DIRS: IGNORED_DIRS,
1021
- BINARY_EXTS: BINARY_EXTS,
1022
1068
  IMAGE_EXTS: IMAGE_EXTS,
1023
- FS_MAX_SIZE: FS_MAX_SIZE,
1024
1069
  });
1025
1070
 
1026
1071
  // --- MCP bridge handler for Codex (Track 2) ---
@@ -1041,26 +1086,20 @@ function createProjectContext(opts) {
1041
1086
  return {
1042
1087
  listTools: function () {
1043
1088
  var tools = [];
1044
- var toJSONSchema;
1045
- try { toJSONSchema = require("zod").toJSONSchema; } catch (e) { /* fallback */ }
1089
+ var toJSONSchema = mcpToolSchema.loadToJSONSchema();
1046
1090
 
1047
- // Helper to extract tools from an SDK MCP server object
1091
+ // Helper to extract tools from an SDK MCP server object. A tool whose
1092
+ // schema cannot be converted is left out and reported, never listed
1093
+ // with no parameters.
1048
1094
  function extractServerTools(serverName, server) {
1049
- if (!server || !server.instance || !server.instance._registeredTools) return;
1050
- var toolNames = Object.keys(server.instance._registeredTools);
1051
- for (var j = 0; j < toolNames.length; j++) {
1052
- var toolDef = server.instance._registeredTools[toolNames[j]];
1053
- var inputSchema = { type: "object", properties: {} };
1054
- try {
1055
- if (toJSONSchema && toolDef.inputSchema) inputSchema = toJSONSchema(toolDef.inputSchema);
1056
- } catch (e) { /* fallback */ }
1095
+ mcpToolSchema.listServerTools(serverName, server, toJSONSchema, send).forEach(function (tool) {
1057
1096
  tools.push({
1058
1097
  server: serverName,
1059
- name: toolNames[j],
1060
- description: toolDef.description || toolNames[j],
1061
- inputSchema: inputSchema,
1098
+ name: tool.name,
1099
+ description: tool.description,
1100
+ inputSchema: tool.inputSchema,
1062
1101
  });
1063
- }
1102
+ });
1064
1103
  }
1065
1104
 
1066
1105
  // In-app MCP servers (browser tools).
@@ -1121,12 +1160,12 @@ function createProjectContext(opts) {
1121
1160
  slug: slug,
1122
1161
  project: title || project,
1123
1162
  sm: sm,
1163
+ getNotificationsModule: function () { return _notifications; },
1124
1164
  send: send,
1125
1165
  imagesDir: imagesDir,
1126
1166
  osUsers: osUsers,
1127
1167
  pushModule: pushModule,
1128
- safePath: safePath,
1129
- safeAbsPath: safeAbsPath,
1168
+ projectAccess: projectAccess,
1130
1169
  getOsUserInfoForReq: getOsUserInfoForReq,
1131
1170
  sendExtensionCommandAny: sendExtensionCommandAny,
1132
1171
  _extToken: _extToken,
@@ -1189,12 +1228,23 @@ function createProjectContext(opts) {
1189
1228
  });
1190
1229
 
1191
1230
  // --- Destroy ---
1192
- function destroy() {
1231
+ // opts.reason says why the project is going away. Only a daemon shutdown
1232
+ // (sessionReclaim.RESTART_REASON) records its live background agents as
1233
+ // resumable: removing a project is a deliberate operator act, and its
1234
+ // sessions are not expected to come back. opts.tally, when given, collects
1235
+ // the announcement results so the caller logs one summary per shutdown.
1236
+ function destroy(opts) {
1237
+ var daemonShutdown = !!opts && opts.reason === sessionReclaim.RESTART_REASON;
1238
+ var tally = opts && opts.tally;
1193
1239
  _loop.stopTimer();
1194
- stopFileWatch();
1195
- stopAllDirWatches();
1240
+ stopAllWatches();
1196
1241
  // Abort all active sessions and clean up mention sessions
1197
1242
  sm.sessions.forEach(function (session) {
1243
+ // Before the abort below drops the agents' registration: the shutdown
1244
+ // kills them, so the session is recorded as resumable.
1245
+ if (daemonShutdown) {
1246
+ sessionReclaim.countShutdownReclaim(tally, sessionReclaim.announceShutdownReclaim(session, sm));
1247
+ }
1198
1248
  session.destroying = true;
1199
1249
  if (session.autoContinueTimer) {
1200
1250
  clearTimeout(session.autoContinueTimer);
@@ -1241,26 +1291,33 @@ function createProjectContext(opts) {
1241
1291
  fs.rmSync(tmpDir, { recursive: true, force: true });
1242
1292
  } catch (e) {}
1243
1293
 
1244
- var codexShutdown = Promise.resolve(true);
1245
- if (adapters && adapters.codex && typeof adapters.codex.shutdown === "function") {
1246
- codexShutdown = adapters.codex.shutdown().catch(function(err) {
1247
- console.error("[project] Codex shutdown failed for " + slug + ":", err && err.message ? err.message : err);
1294
+ // An adapter whose runtime belongs to this project (perProjectRuntime trait) is
1295
+ // shut down with it; one shared across projects is left running.
1296
+ var shutdowns = [];
1297
+ Object.keys(adapters || {}).forEach(function (vendor) {
1298
+ var owned = adapters[vendor];
1299
+ if (!owned || typeof owned.shutdown !== "function") return;
1300
+ if (!yoke.registry.traitOf(vendor, "perProjectRuntime")) return;
1301
+ shutdowns.push(Promise.resolve(owned.shutdown()).catch(function(err) {
1302
+ console.error("[project] " + vendor + " shutdown failed for " + slug + ":", err && err.message ? err.message : err);
1248
1303
  return false;
1249
- });
1250
- }
1251
- return codexShutdown;
1304
+ }));
1305
+ });
1306
+ return Promise.all(shutdowns).then(function (results) {
1307
+ return results.every(function (ok) { return ok !== false; });
1308
+ });
1252
1309
  }
1253
1310
 
1254
1311
  // --- Status info ---
1255
1312
  function getStatus() {
1256
1313
  var sessionCount = sm.sessions.size;
1257
1314
  var hasProcessing = false;
1315
+ // Every prompt awaiting the operator, of any kind, flags the project.
1258
1316
  var pendingPermCount = 0;
1317
+ var prompts = promptsFor(sm);
1259
1318
  sm.sessions.forEach(function (s) {
1260
1319
  if (s.isProcessing) hasProcessing = true;
1261
- if (s.pendingPermissions) {
1262
- pendingPermCount += Object.keys(s.pendingPermissions).length;
1263
- }
1320
+ pendingPermCount += prompts.pendingCount(s);
1264
1321
  });
1265
1322
  var status = {
1266
1323
  slug: slug,
@@ -1305,7 +1362,11 @@ function createProjectContext(opts) {
1305
1362
 
1306
1363
  function setTitle(newTitle) {
1307
1364
  title = newTitle || null;
1308
- send({ type: "info", cwd: cwd, slug: slug, project: title || project, version: currentVersion, debug: !!debug, osUsers: osUsers, lanHost: lanHost, projectCount: getProjectCount(), projects: getProjectList(), projectOwnerId: projectOwnerId });
1365
+ // Each client is sent the project list it is allowed to see.
1366
+ for (var ws of clients) {
1367
+ var visibleProjects = getProjectList(ws._clagenticUser ? ws._clagenticUser.id : null, projectAccess.authOf(ws));
1368
+ sendTo(ws, { type: "info", cwd: cwd, slug: slug, project: title || project, version: currentVersion, debug: !!debug, osUsers: osUsers, lanHost: lanHost, projectCount: visibleProjects.length, projects: visibleProjects, projectOwnerId: projectOwnerId });
1369
+ }
1309
1370
  }
1310
1371
 
1311
1372
  function setIcon(newIcon) {
@@ -1364,9 +1425,13 @@ function createProjectContext(opts) {
1364
1425
  },
1365
1426
  onProcessingChanged: onProcessingChanged,
1366
1427
  getLinuxUserForSession: getLinuxUserForSession,
1367
- destroy: function () {
1428
+ // Ends the adapters' runtimes that nothing is using (see idle-adapter-reaper.js).
1429
+ reclaimIdleAdapters: function (idleMs) {
1430
+ return reclaimIdleAdapters(adapters, idleMs);
1431
+ },
1432
+ destroy: function (opts) {
1368
1433
  sdk.stopIdleReaper();
1369
- return destroy();
1434
+ return destroy(opts);
1370
1435
  },
1371
1436
  };
1372
1437
  }