@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/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,11 @@ 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 mcpToolSchema = require("./mcp-tool-schema");
38
+ var { reclaimIdleAdapters } = require("./idle-adapter-reaper");
39
+ var sessionCapabilities = require("./session-capabilities");
40
+ var { buildVendorRegistryMessage } = require("./vendor-registry-message");
29
41
  // project-notifications is attached globally in server.js, passed via opts.notificationsModule
30
42
 
31
43
  // --- Context Sources persistence ---
@@ -56,30 +68,10 @@ function saveContextSources(slug, sessionId, activeIds) {
56
68
  }
57
69
  }
58
70
 
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
- }
71
+ // Validate an environment variable text (KEY=VALUE per line) before it is saved.
72
+ // Returns null if valid, or the message to show the user. Also refuses the
73
+ // variables Settings may not set (lib/runtime-env-keys.js).
74
+ var validateEnvString = runtimeEnv.validateEnvText;
83
75
 
84
76
  // YOKE adapter (replaces direct SDK access)
85
77
  var yoke = require("./yoke");
@@ -97,46 +89,6 @@ var BINARY_EXTS = new Set([
97
89
  ]);
98
90
  var IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".ico"]);
99
91
  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
92
 
141
93
  /**
142
94
  * Create a project context — per-project state and handlers.
@@ -182,8 +134,24 @@ function createProjectContext(opts) {
182
134
  var updateChannel = opts.updateChannel || "stable";
183
135
  var onSetUpdateChannel = opts.onSetUpdateChannel || null;
184
136
  var osUsers = opts.osUsers || false;
137
+ // server.js wires the daemon's resolver for every real project. A context
138
+ // built without one (unit harnesses) has no user system behind it, so it is
139
+ // single-user: a connection with no user record is its implicit owner.
140
+ var projectAccess = opts.projectAccess || createProjectAccess({
141
+ users: usersModule,
142
+ onGetProjectAccess: null,
143
+ isMultiUser: function () { return false; },
144
+ });
185
145
  var projectOwnerId = opts.projectOwnerId || null;
186
146
  var worktreeMeta = opts.worktreeMeta || null; // { parentSlug, branch, accessible }
147
+ // A worktree has no environment settings of its own: it runs with its
148
+ // parent project's, under the same ownership rule, and the daemon's access
149
+ // lookup answers for it with the parent's record (and so the parent's owner).
150
+ var envSlug = worktreeMeta && worktreeMeta.parentSlug ? worktreeMeta.parentSlug : slug;
151
+ function getEnvOwnerId() {
152
+ var access = projectAccess.resolve(slug);
153
+ return (access && access.ownerId) || null;
154
+ }
187
155
  var onCreateWorktree = opts.onCreateWorktree || null;
188
156
  var serverPort = opts.port || 2633;
189
157
  var serverTls = opts.tls || false;
@@ -200,7 +168,8 @@ function createProjectContext(opts) {
200
168
  // --- YOKE adapters (multi-vendor, lazy init) ---
201
169
  var _yokeState = yoke.createAdapters({ cwd: cwd, slug: slug });
202
170
  var adapters = _yokeState.adapters;
203
- var defaultVendor = adapters.claude ? "claude" : Object.keys(adapters)[0] || "claude";
171
+ // The project starts on the most preferred registered agent that is available.
172
+ var defaultVendor = yoke.registry.defaultVendorId(Object.keys(adapters));
204
173
  var adapter = adapters[defaultVendor] || null;
205
174
 
206
175
  // Browser MCP server runs in-process via createSdkMcpServer (no child process spawn).
@@ -273,29 +242,22 @@ function createProjectContext(opts) {
273
242
 
274
243
  // --- Browser extension state (shared mutable object) ---
275
244
  var _extToken = crypto.randomUUID(); // Auth token for MCP server bridge
245
+ // The tab list is keyed by tab ids the extension reports, so it has no
246
+ // prototype to inherit from; it is only ever updated in place so every
247
+ // holder of the reference sees the current tabs.
276
248
  var browserState = {
277
- _browserTabList: {},
249
+ _browserTabList: Object.create(null),
278
250
  _extensionWs: null,
279
- pendingExtensionRequests: {}
280
251
  };
281
252
 
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
- }
253
+ // The extension answers with extension_result (project-user-message.js);
254
+ // an unanswered command resolves to null after its timeout. Only the socket a
255
+ // command was sent to may answer it (lib/extension-commands.js).
256
+ var extensionCommands = createExtensionCommands({
257
+ getSessionManager: function () { return sm; },
258
+ sendTo: sendTo,
259
+ });
260
+ var sendExtensionCommand = extensionCommands.send;
299
261
 
300
262
  // Send extension command via the tracked extension client (for MCP bridge)
301
263
  function sendExtensionCommandAny(command, args, timeout) {
@@ -342,6 +304,14 @@ function createProjectContext(opts) {
342
304
  if (ws.readyState === 1) ws.send(JSON.stringify(obj));
343
305
  }
344
306
 
307
+ // The agent registry to every client, each with the install state of its own
308
+ // OS identity: what one user has installed says nothing about another's.
309
+ function sendVendorRegistry() {
310
+ for (var ws of clients) {
311
+ sendTo(ws, buildVendorRegistryMessage(sm, getLinuxUserForWs(ws)));
312
+ }
313
+ }
314
+
345
315
  function sendToAdmins(obj) {
346
316
  var data = JSON.stringify(obj);
347
317
  for (var ws of clients) {
@@ -404,6 +374,15 @@ function createProjectContext(opts) {
404
374
  }
405
375
  }
406
376
 
377
+ // getHubSchedules(userId) returns only the schedules of projects that user
378
+ // may see, so a schedule list is never sent to a client unfiltered.
379
+ function broadcastHubSchedules() {
380
+ for (var hws of clients) {
381
+ if (hws.readyState !== 1) continue;
382
+ sendTo(hws, { type: "loop_registry_updated", records: getHubSchedules(hws._clagenticUser ? hws._clagenticUser.id : null, projectAccess.authOf(hws)) });
383
+ }
384
+ }
385
+
407
386
  // --- Knowledge engine (delegated to project-knowledge.js) ---
408
387
  var _knowledge = attachKnowledge({
409
388
  cwd: cwd,
@@ -412,19 +391,30 @@ function createProjectContext(opts) {
412
391
  });
413
392
 
414
393
  // --- File/directory watcher engine (delegated to project-file-watch.js) ---
394
+ // One file policy for the WS file messages and the watchers.
395
+ var fileAccess = createFileAccess({
396
+ osUsers: osUsers,
397
+ usersModule: usersModule,
398
+ projectAccess: projectAccess,
399
+ fsAsUser: fsAsUser,
400
+ getOsUserInfoForWs: getOsUserInfoForWs,
401
+ binaryExts: BINARY_EXTS,
402
+ maxSize: FS_MAX_SIZE,
403
+ });
415
404
  var _fileWatch = attachFileWatch({
416
405
  cwd: cwd,
417
- send: send,
406
+ sendTo: sendTo,
418
407
  safePath: safePath,
419
- BINARY_EXTS: BINARY_EXTS,
420
- FS_MAX_SIZE: FS_MAX_SIZE,
408
+ authorize: fileAccess.authorize,
409
+ readFile: fileAccess.readFile,
410
+ listDir: fileAccess.listDir,
421
411
  IGNORED_DIRS: IGNORED_DIRS,
422
412
  });
423
413
  var startFileWatch = _fileWatch.startFileWatch;
424
414
  var stopFileWatch = _fileWatch.stopFileWatch;
425
415
  var startDirWatch = _fileWatch.startDirWatch;
426
- var stopDirWatch = _fileWatch.stopDirWatch;
427
416
  var stopAllDirWatches = _fileWatch.stopAllDirWatches;
417
+ var stopAllWatches = _fileWatch.stopAll;
428
418
 
429
419
  // --- Session manager ---
430
420
  var sm = createSessionManager({
@@ -448,6 +438,8 @@ function createProjectContext(opts) {
448
438
  onSessionDone: onSessionDone,
449
439
  onSessionDeleted: onSessionDeleted,
450
440
  historyInMemMax: historyInMemMax,
441
+ getNotificationsModule: function () { return _notifications; },
442
+ onProcessingChanged: onProcessingChanged,
451
443
  });
452
444
  sm.availableVendors = Object.keys(adapters);
453
445
  sm.defaultVendor = defaultVendor;
@@ -587,6 +579,7 @@ function createProjectContext(opts) {
587
579
  slug: slug,
588
580
  sessionManager: sm,
589
581
  send: send,
582
+ sendVendorRegistry: sendVendorRegistry,
590
583
  pushModule: pushModule,
591
584
  adapter: adapter,
592
585
  adapters: adapters,
@@ -618,6 +611,24 @@ function createProjectContext(opts) {
618
611
  }
619
612
  return {};
620
613
  },
614
+ // The environment texts saved in Settings, read on every runtime start so
615
+ // a change reaches the next one. The shared text goes to every runtime. The
616
+ // project's text goes to a runtime only if projectEnvApplies says so for
617
+ // the session it starts for (none: a warmup that serves every user, which
618
+ // takes the project's text in single-user mode only).
619
+ getRuntimeEnvSettings: function (session) {
620
+ var shared = typeof opts.onGetSharedEnv === "function" ? opts.onGetSharedEnv() : null;
621
+ var projectText;
622
+ if (typeof opts.onGetProjectEnv === "function" && runtimeEnv.projectEnvApplies({
623
+ multiUser: typeof projectAccess.isMultiUser === "function" ? projectAccess.isMultiUser() : true,
624
+ projectOwnerId: getEnvOwnerId(),
625
+ sessionOwnerId: (session && session.ownerId) || null,
626
+ })) {
627
+ var project = opts.onGetProjectEnv(envSlug);
628
+ projectText = project && project.envrc;
629
+ }
630
+ return { shared: shared && shared.envrc, project: projectText };
631
+ },
621
632
  });
622
633
 
623
634
  // --- Loop engine (delegated to project-loop.js) ---
@@ -635,6 +646,7 @@ function createProjectContext(opts) {
635
646
  pushModule: pushModule,
636
647
  notificationsModule: _notifications,
637
648
  getHubSchedules: getHubSchedules,
649
+ broadcastHubSchedules: broadcastHubSchedules,
638
650
  getAllProjectSessions: getAllProjectSessions,
639
651
  getSessionUnread: getSessionUnread,
640
652
  getStatus: getStatus,
@@ -740,15 +752,28 @@ function createProjectContext(opts) {
740
752
  }
741
753
  }
742
754
 
755
+ // opts.canAccessProject(userId, slug, proof) is wired by server.js for every real
756
+ // project; a context built without it (unit harnesses) has no access policy
757
+ // to apply to its own slug but still refuses to forward to another project.
758
+ var _messageGate = createMessageGate({
759
+ slug: slug,
760
+ canAccess: typeof opts.canAccessProject === "function" ? opts.canAccessProject : null,
761
+ getProject: opts.getProject,
762
+ });
763
+
743
764
  function handleMessage(ws, msg) {
765
+ // --- Access gate: every message is authorized before any handler runs ---
766
+ var gate = _messageGate.authorize(ws, msg);
767
+ if (!gate.allowed) {
768
+ if (gate.error) sendTo(ws, { type: "error", text: gate.error });
769
+ return;
770
+ }
744
771
  // --- 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
- }
772
+ if (gate.target) {
773
+ gate.target.handleMessage(ws, gate.message);
774
+ return;
751
775
  }
776
+ msg = gate.message;
752
777
 
753
778
  // --- Team activity messages (delegated to project-team.js) ---
754
779
  if (_team.handleClientMsg(ws, msg)) return;
@@ -769,39 +794,50 @@ function createProjectContext(opts) {
769
794
 
770
795
  // --- Vendor model switching ---
771
796
  if (msg.type === "get_vendor_models") {
797
+ // The vendor is a client-supplied name: only a known vendor is ever
798
+ // used as a key, and every lookup reads own properties only.
799
+ var requestedVendor = isKnownVendor(msg.vendor) ? msg.vendor : null;
772
800
  (async function() {
773
- if (msg.vendor) {
801
+ if (requestedVendor) {
774
802
  try {
775
- var vendorAdapter = adapters[msg.vendor] || null;
803
+ // What the adapter's live session advertises narrows its
804
+ // declaration; it is recorded for this vendor and the clients told.
805
+ var recordInit = function (initResult) {
806
+ sessionCapabilities.recordCapabilities(sm, requestedVendor, initResult && initResult.capabilities);
807
+ sendVendorRegistry();
808
+ };
809
+ var vendorAdapter = ownValue(adapters, requestedVendor) || null;
776
810
  if (!vendorAdapter) {
777
- vendorAdapter = await yoke.lazyCreateAdapter(adapters, msg.vendor, {
811
+ vendorAdapter = await yoke.lazyCreateAdapter(adapters, requestedVendor, {
778
812
  cwd: cwd,
779
813
  clayPort: serverPort,
780
814
  clayTls: serverTls,
781
815
  clayAuthToken: serverAuthToken,
782
816
  slug: slug,
783
- });
784
- } else if ((!sm.modelsByVendor || !sm.modelsByVendor[msg.vendor]) && typeof vendorAdapter.init === "function") {
785
- await vendorAdapter.init({
817
+ runtimeEnv: sdk.getRuntimeEnvOverlay(),
818
+ }, recordInit);
819
+ } else if ((!sm.modelsByVendor || !ownValue(sm.modelsByVendor, requestedVendor)) && typeof vendorAdapter.init === "function") {
820
+ recordInit(await vendorAdapter.init({
786
821
  cwd: cwd,
787
822
  clayPort: serverPort,
788
823
  clayTls: serverTls,
789
824
  clayAuthToken: serverAuthToken,
790
825
  slug: slug,
791
- });
826
+ runtimeEnv: sdk.getRuntimeEnvOverlay(),
827
+ }));
792
828
  }
793
829
  if (vendorAdapter) {
794
830
  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();
831
+ sm.modelsByVendor = sm.modelsByVendor || Object.create(null);
832
+ if (!ownValue(sm.modelsByVendor, requestedVendor) && typeof vendorAdapter.supportedModels === "function") {
833
+ putOwn(sm.modelsByVendor, requestedVendor, await vendorAdapter.supportedModels({ runtimeEnv: sdk.getRuntimeEnvOverlay() }));
798
834
  }
799
835
  }
800
836
  } catch (e) {
801
- console.error("[project] get_vendor_models lazy init failed for " + msg.vendor + ":", e.message || e);
837
+ console.error("[project] get_vendor_models lazy init failed for " + requestedVendor + ":", e.message || e);
802
838
  }
803
839
  }
804
- var vendorModels = (sm.modelsByVendor && sm.modelsByVendor[msg.vendor]) || [];
840
+ var vendorModels = (sm.modelsByVendor && ownValue(sm.modelsByVendor, requestedVendor)) || [];
805
841
  var firstModel = vendorModels[0] || "";
806
842
  // model value can be string or {value, displayName} object
807
843
  var defaultModel = typeof firstModel === "string" ? firstModel : (firstModel.value || "");
@@ -817,7 +853,7 @@ function createProjectContext(opts) {
817
853
  }
818
854
  }
819
855
  }
820
- sendTo(ws, { type: "model_info", model: modelToSend, models: vendorModels, vendor: msg.vendor, availableVendors: sm.availableVendors || [], installedVendors: sm.installedVendors || [] });
856
+ sendTo(ws, { type: "model_info", model: modelToSend, models: vendorModels, vendor: typeof msg.vendor === "string" ? msg.vendor : "", availableVendors: sm.availableVendors || [] });
821
857
  })();
822
858
  return;
823
859
  }
@@ -918,6 +954,7 @@ function createProjectContext(opts) {
918
954
  sdk: sdk,
919
955
  tm: tm,
920
956
  clients: clients,
957
+ getNotificationsModule: function () { return _notifications; },
921
958
  send: send,
922
959
  sendTo: sendTo,
923
960
  sendToAdmins: sendToAdmins,
@@ -925,6 +962,7 @@ function createProjectContext(opts) {
925
962
  sendToSessionOthers: sendToSessionOthers,
926
963
  opts: opts,
927
964
  usersModule: usersModule,
965
+ projectAccess: projectAccess,
928
966
  userPresence: userPresence,
929
967
  pushModule: pushModule,
930
968
  getSessionForWs: getSessionForWs,
@@ -941,6 +979,7 @@ function createProjectContext(opts) {
941
979
  moveScheduleToProject: moveScheduleToProject,
942
980
  moveAllSchedulesToProject: moveAllSchedulesToProject,
943
981
  getHubSchedules: getHubSchedules,
982
+ broadcastHubSchedules: broadcastHubSchedules,
944
983
  fetchVersion: fetchVersion,
945
984
  isNewer: isNewer,
946
985
  scheduleMessage: scheduleMessage,
@@ -986,6 +1025,7 @@ function createProjectContext(opts) {
986
1025
  onProcessingChanged: onProcessingChanged,
987
1026
  _loop: _loop,
988
1027
  browserState: browserState,
1028
+ mayAnswerExtensionCommand: extensionCommands.mayAnswer,
989
1029
  sendExtensionCommandAny: sendExtensionCommandAny,
990
1030
  requestTabContext: requestTabContext,
991
1031
  scheduleMessage: scheduleMessage,
@@ -1006,21 +1046,20 @@ function createProjectContext(opts) {
1006
1046
  sm: sm,
1007
1047
  send: send,
1008
1048
  sendTo: sendTo,
1009
- safePath: safePath,
1010
- safeAbsPath: safeAbsPath,
1011
- safeClaudePath: safeClaudePath,
1049
+ fileAccess: fileAccess,
1012
1050
  getOsUserInfoForWs: getOsUserInfoForWs,
1013
1051
  startFileWatch: startFileWatch,
1014
1052
  stopFileWatch: stopFileWatch,
1015
1053
  startDirWatch: startDirWatch,
1016
1054
  usersModule: usersModule,
1055
+ projectAccess: projectAccess,
1017
1056
  fsAsUser: fsAsUser,
1018
1057
  validateEnvString: validateEnvString,
1058
+ envSlug: envSlug,
1059
+ getEnvOwnerId: getEnvOwnerId,
1019
1060
  opts: opts,
1020
1061
  IGNORED_DIRS: IGNORED_DIRS,
1021
- BINARY_EXTS: BINARY_EXTS,
1022
1062
  IMAGE_EXTS: IMAGE_EXTS,
1023
- FS_MAX_SIZE: FS_MAX_SIZE,
1024
1063
  });
1025
1064
 
1026
1065
  // --- MCP bridge handler for Codex (Track 2) ---
@@ -1041,26 +1080,20 @@ function createProjectContext(opts) {
1041
1080
  return {
1042
1081
  listTools: function () {
1043
1082
  var tools = [];
1044
- var toJSONSchema;
1045
- try { toJSONSchema = require("zod").toJSONSchema; } catch (e) { /* fallback */ }
1083
+ var toJSONSchema = mcpToolSchema.loadToJSONSchema();
1046
1084
 
1047
- // Helper to extract tools from an SDK MCP server object
1085
+ // Helper to extract tools from an SDK MCP server object. A tool whose
1086
+ // schema cannot be converted is left out and reported, never listed
1087
+ // with no parameters.
1048
1088
  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 */ }
1089
+ mcpToolSchema.listServerTools(serverName, server, toJSONSchema, send).forEach(function (tool) {
1057
1090
  tools.push({
1058
1091
  server: serverName,
1059
- name: toolNames[j],
1060
- description: toolDef.description || toolNames[j],
1061
- inputSchema: inputSchema,
1092
+ name: tool.name,
1093
+ description: tool.description,
1094
+ inputSchema: tool.inputSchema,
1062
1095
  });
1063
- }
1096
+ });
1064
1097
  }
1065
1098
 
1066
1099
  // In-app MCP servers (browser tools).
@@ -1121,12 +1154,12 @@ function createProjectContext(opts) {
1121
1154
  slug: slug,
1122
1155
  project: title || project,
1123
1156
  sm: sm,
1157
+ getNotificationsModule: function () { return _notifications; },
1124
1158
  send: send,
1125
1159
  imagesDir: imagesDir,
1126
1160
  osUsers: osUsers,
1127
1161
  pushModule: pushModule,
1128
- safePath: safePath,
1129
- safeAbsPath: safeAbsPath,
1162
+ projectAccess: projectAccess,
1130
1163
  getOsUserInfoForReq: getOsUserInfoForReq,
1131
1164
  sendExtensionCommandAny: sendExtensionCommandAny,
1132
1165
  _extToken: _extToken,
@@ -1191,8 +1224,7 @@ function createProjectContext(opts) {
1191
1224
  // --- Destroy ---
1192
1225
  function destroy() {
1193
1226
  _loop.stopTimer();
1194
- stopFileWatch();
1195
- stopAllDirWatches();
1227
+ stopAllWatches();
1196
1228
  // Abort all active sessions and clean up mention sessions
1197
1229
  sm.sessions.forEach(function (session) {
1198
1230
  session.destroying = true;
@@ -1241,26 +1273,33 @@ function createProjectContext(opts) {
1241
1273
  fs.rmSync(tmpDir, { recursive: true, force: true });
1242
1274
  } catch (e) {}
1243
1275
 
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);
1276
+ // An adapter whose runtime belongs to this project (perProjectRuntime trait) is
1277
+ // shut down with it; one shared across projects is left running.
1278
+ var shutdowns = [];
1279
+ Object.keys(adapters || {}).forEach(function (vendor) {
1280
+ var owned = adapters[vendor];
1281
+ if (!owned || typeof owned.shutdown !== "function") return;
1282
+ if (!yoke.registry.traitOf(vendor, "perProjectRuntime")) return;
1283
+ shutdowns.push(Promise.resolve(owned.shutdown()).catch(function(err) {
1284
+ console.error("[project] " + vendor + " shutdown failed for " + slug + ":", err && err.message ? err.message : err);
1248
1285
  return false;
1249
- });
1250
- }
1251
- return codexShutdown;
1286
+ }));
1287
+ });
1288
+ return Promise.all(shutdowns).then(function (results) {
1289
+ return results.every(function (ok) { return ok !== false; });
1290
+ });
1252
1291
  }
1253
1292
 
1254
1293
  // --- Status info ---
1255
1294
  function getStatus() {
1256
1295
  var sessionCount = sm.sessions.size;
1257
1296
  var hasProcessing = false;
1297
+ // Every prompt awaiting the operator, of any kind, flags the project.
1258
1298
  var pendingPermCount = 0;
1299
+ var prompts = promptsFor(sm);
1259
1300
  sm.sessions.forEach(function (s) {
1260
1301
  if (s.isProcessing) hasProcessing = true;
1261
- if (s.pendingPermissions) {
1262
- pendingPermCount += Object.keys(s.pendingPermissions).length;
1263
- }
1302
+ pendingPermCount += prompts.pendingCount(s);
1264
1303
  });
1265
1304
  var status = {
1266
1305
  slug: slug,
@@ -1305,7 +1344,11 @@ function createProjectContext(opts) {
1305
1344
 
1306
1345
  function setTitle(newTitle) {
1307
1346
  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 });
1347
+ // Each client is sent the project list it is allowed to see.
1348
+ for (var ws of clients) {
1349
+ var visibleProjects = getProjectList(ws._clagenticUser ? ws._clagenticUser.id : null, projectAccess.authOf(ws));
1350
+ 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 });
1351
+ }
1309
1352
  }
1310
1353
 
1311
1354
  function setIcon(newIcon) {
@@ -1364,6 +1407,10 @@ function createProjectContext(opts) {
1364
1407
  },
1365
1408
  onProcessingChanged: onProcessingChanged,
1366
1409
  getLinuxUserForSession: getLinuxUserForSession,
1410
+ // Ends the adapters' runtimes that nothing is using (see idle-adapter-reaper.js).
1411
+ reclaimIdleAdapters: function (idleMs) {
1412
+ return reclaimIdleAdapters(adapters, idleMs);
1413
+ },
1367
1414
  destroy: function () {
1368
1415
  sdk.stopIdleReaper();
1369
1416
  return destroy();