@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/sdk-bridge.js CHANGED
@@ -1,4 +1,3 @@
1
- const crypto = require("crypto");
2
1
  var fs = require("fs");
3
2
  var path = require("path");
4
3
  var execSync = require("child_process").execSync;
@@ -12,18 +11,27 @@ var { readAgentToolsFromFile, parseFrontmatter, slugifyAgentName, AGENTS_SOURCE_
12
11
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
13
12
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
14
13
  var { runPreflight } = require("./settings-preflight");
15
- var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping, sweepClearedPermissionIndex } = require("./sdk-permission-ownership");
16
- var { permissionGrantKey } = require("./utils");
14
+ var { promptsFor } = require("./prompt-registry");
15
+ var { toolApprovalKind } = require("./prompt-kinds");
17
16
  var sessionActivity = require("./session-activity");
17
+ var sessionReclaim = require("./session-reclaim");
18
+ var { isAgentDispatchTool } = require("./agent-dispatch-tool");
19
+ var { getNewWorkRefusal } = require("./new-work-gate");
20
+ var runtimeEnv = require("./runtime-env");
21
+ var mcpToolSchema = require("./mcp-tool-schema");
22
+ var { registry: yokeRegistry } = require("./yoke");
23
+ var sessionCapabilities = require("./session-capabilities");
24
+ var { buildVendorRegistryMessage, recordInstallState } = require("./vendor-registry-message");
25
+ var { authRequiredFacts } = require("./vendor-auth");
18
26
 
19
27
  // --- lr-29f9: Global concurrent-session ceiling ---
20
28
  // Counts queries that are actively running (startQuery entered, processQueryStream
21
29
  // finally not yet reached) across ALL project bridge instances in this daemon process.
22
30
  // Each project's sdk-bridge instance shares this module-level counter.
23
- // Env override: CLAGENTIC_MAX_CONCURRENT_SESSIONS (must be a positive integer).
31
+ // Env override: CLAGENTIC_CONSOLE_MAX_CONCURRENT_SESSIONS (must be a positive integer).
24
32
  var _activeLiveCount = 0;
25
33
  var MAX_CONCURRENT_SESSIONS = (function () {
26
- var env = parseInt(process.env.CLAGENTIC_MAX_CONCURRENT_SESSIONS, 10);
34
+ var env = parseInt(require("./env-compat").readConsoleEnv("CLAGENTIC_CONSOLE_MAX_CONCURRENT_SESSIONS"), 10);
27
35
  return (env > 0) ? env : 50;
28
36
  })();
29
37
 
@@ -294,31 +302,16 @@ function resolveEffectiveHome(linuxUser) {
294
302
 
295
303
  // Extract serializable tool descriptors from MCP server instances.
296
304
  // Used for IPC to worker processes (McpSdkServerConfigWithInstance is not serializable).
297
- function extractMcpDescriptors(mcpServers) {
305
+ // A tool whose input schema cannot be converted is left out and reported
306
+ // through onSkipped; it is never registered with an empty schema.
307
+ function extractMcpDescriptors(mcpServers, onSkipped, toJSONSchema) {
298
308
  if (!mcpServers) return null;
299
- var toJSONSchema;
300
- try { toJSONSchema = require("zod").toJSONSchema; } catch (e) { return null; }
309
+ if (toJSONSchema === undefined) toJSONSchema = mcpToolSchema.loadToJSONSchema();
301
310
  var descriptors = [];
302
311
  var names = Object.keys(mcpServers);
303
312
  for (var i = 0; i < names.length; i++) {
304
313
  var serverName = names[i];
305
- var server = mcpServers[serverName];
306
- if (!server || !server.instance || !server.instance._registeredTools) continue;
307
- var tools = [];
308
- var toolNames = Object.keys(server.instance._registeredTools);
309
- for (var j = 0; j < toolNames.length; j++) {
310
- var toolName = toolNames[j];
311
- var toolDef = server.instance._registeredTools[toolName];
312
- var inputSchema = { type: "object", properties: {} };
313
- try {
314
- if (toolDef.inputSchema) inputSchema = toJSONSchema(toolDef.inputSchema);
315
- } catch (e) { /* fallback to empty schema */ }
316
- tools.push({
317
- name: toolName,
318
- description: toolDef.description || toolName,
319
- inputSchema: inputSchema,
320
- });
321
- }
314
+ var tools = mcpToolSchema.listServerTools(serverName, mcpServers[serverName], toJSONSchema, onSkipped);
322
315
  if (tools.length > 0) descriptors.push({ serverName: serverName, tools: tools });
323
316
  }
324
317
  return descriptors.length > 0 ? descriptors : null;
@@ -384,11 +377,17 @@ function createSDKBridge(opts) {
384
377
  var slug = opts.slug || "";
385
378
  var sm = opts.sessionManager; // session manager instance
386
379
  var send = opts.send; // broadcast to all clients
380
+ // Every registered agent has a recorded capability set from the first moment,
381
+ // so a query that starts before warmup finishes is still gated on its agent.
382
+ sessionCapabilities.seedCapabilities(sm);
387
383
  var pushModule = opts.pushModule;
388
384
  var getNotificationsModule = opts.getNotificationsModule || function () { return null; };
389
385
  var adapter = opts.adapter;
390
386
  var adapters = opts.adapters || {};
391
387
  var dangerouslySkipPermissions = opts.dangerouslySkipPermissions || false;
388
+ // Whether the daemon isolates users at the OS level. An agent that does not
389
+ // support that (Codex) is disabled then: never created, never started.
390
+ var osUsersMode = !!opts.osUsers;
392
391
  // mcpServers may be either a static object or a getter function. The
393
392
  // getter form lets callers gate individual servers at call time (e.g.
394
393
  // clay-browser is only exposed while the Chrome extension is connected).
@@ -402,6 +401,46 @@ function createSDKBridge(opts) {
402
401
  var clayTls = opts.clayTls || false;
403
402
  var clayAuthToken = opts.clayAuthToken || null;
404
403
  var onProcessingChanged = opts.onProcessingChanged || function () {};
404
+
405
+ // --- Environment saved in Settings ---
406
+ // The variables Settings add to the environment of an agent runtime, read
407
+ // fresh at every runtime start, so a change reaches the runtimes started
408
+ // after it; a runtime already running keeps the environment it started with.
409
+ // Null when there are none (no settings source, or nothing saved): the
410
+ // runtime then has the daemon's own environment. `session` is the session the
411
+ // runtime is for: which settings reach it depends on who owns it (see
412
+ // getRuntimeEnvSettings in lib/project.js). No session is a runtime that
413
+ // serves everyone, such as a model-list warmup.
414
+ function getRuntimeEnvOverlay(session) {
415
+ if (typeof opts.getRuntimeEnvSettings !== "function") return null;
416
+ var settings = opts.getRuntimeEnvSettings(session) || {};
417
+ var overlay = runtimeEnv.buildRuntimeEnvOverlay([
418
+ { label: "shared", text: settings.shared },
419
+ { label: "project " + slug, text: settings.project },
420
+ ]);
421
+ return runtimeEnv.hasOverlay(overlay) ? overlay : null;
422
+ }
423
+
424
+ // queryOptions with runtimeEnv set: the settings' variables, or null for
425
+ // none. Always set, because an adapter that keeps a server per environment
426
+ // (Codex) refuses a caller that does not say which one it is.
427
+ function withRuntimeEnv(queryOptions, session) {
428
+ queryOptions.runtimeEnv = getRuntimeEnvOverlay(session);
429
+ return queryOptions;
430
+ }
431
+
432
+ // Tells each connected client the agent registry again, after something
433
+ // changed what it holds (a vendor's live capabilities were recorded). Install
434
+ // state is per OS identity, so the project supplies a sender that gives every
435
+ // client its own; the default is a single broadcast for a daemon account.
436
+ function sendVendorRegistry() {
437
+ if (typeof opts.sendVendorRegistry === "function") {
438
+ opts.sendVendorRegistry();
439
+ return;
440
+ }
441
+ send(buildVendorRegistryMessage(sm, null));
442
+ }
443
+
405
444
  var _cachedFreshAuthState = null;
406
445
  var _cachedFreshAuthAt = 0;
407
446
 
@@ -428,10 +467,17 @@ function createSDKBridge(opts) {
428
467
  || errLower.indexOf("please login") !== -1;
429
468
  }
430
469
 
431
- function getLoginCommand(vendor) {
432
- if (vendor === "codex") return "codex login --device-auth";
433
- if (vendor === "claude") return "claude login";
434
- return (vendor || "claude") + " login";
470
+ // The vendor a session runs on: its own, else the project's default adapter's.
471
+ function sessionVendorId(session) {
472
+ return session.vendor || (adapter && adapter.vendor) || yokeRegistry.ids()[0];
473
+ }
474
+
475
+ // Message shown when the user stops a turn; each agent words it itself.
476
+ function interruptMessageFor(session) {
477
+ var vendor = sessionVendorId(session);
478
+ return yokeRegistry.isKnown(vendor)
479
+ ? yokeRegistry.get(vendor).interruptMessage
480
+ : "Interrupted.";
435
481
  }
436
482
 
437
483
  function notifyAuthRequired(session, title, body, authLinuxUser, canAutoLogin, loginCommand) {
@@ -504,7 +550,6 @@ function createSDKBridge(opts) {
504
550
  models: getModelsForVendor(vendor),
505
551
  vendor: vendor || (adapter && adapter.vendor) || "claude",
506
552
  availableVendors: sm.availableVendors || [],
507
- installedVendors: sm.installedVendors || [],
508
553
  });
509
554
  }
510
555
 
@@ -526,7 +571,6 @@ function createSDKBridge(opts) {
526
571
  models: getModelsForVendor(vendor),
527
572
  vendor: vendor || (adapter && adapter.vendor) || "claude",
528
573
  availableVendors: sm.availableVendors || [],
529
- installedVendors: sm.installedVendors || [],
530
574
  });
531
575
  }
532
576
  var onTurnDone = opts.onTurnDone || null;
@@ -557,10 +601,14 @@ function createSDKBridge(opts) {
557
601
  // no activity at all, or a leaked child registration would pin the
558
602
  // session (and its process) alive forever. Because that case was never
559
603
  // "live" at the moment of reap (no activity for the full timeout window),
560
- // it emits no notification here — only the pressure path in
561
- // lib/memory-shed.js, which can reclaim a still-progressing session as a
562
- // deliberate last resort, notifies both UI surfaces (see its
563
- // liveChildReclaims handling).
604
+ // it is reaped; the reap and the pressure path in lib/memory-shed.js both
605
+ // announce it through lib/session-reclaim.js.
606
+ //
607
+ // A session with ANY open operator prompt is never reaped (see the
608
+ // pendingCount check in startIdleReaper): a background agent blocked on a
609
+ // permission prompt emits nothing, so its silence is the operator's to
610
+ // break, not evidence that it died. When a silent child IS reaped, the
611
+ // operator is told which agents were interrupted.
564
612
  var IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
565
613
  var IDLE_CHECK_INTERVAL_MS = 60 * 1000; // check every 60 seconds
566
614
  // lr-5450ef: BACKSTOP staleness window for the activity registry's leak
@@ -617,11 +665,30 @@ function createSDKBridge(opts) {
617
665
  if (!session.queryInstance) return;
618
666
  if (session.singleTurn) return;
619
667
 
668
+ // A session with an open prompt (its own, or a background agent's) is
669
+ // waiting on the operator, not idle: an agent blocked on a prompt
670
+ // emits no stream events, so the activity clock cannot tell. Ending
671
+ // it would abort the pending tool call and destroy the agent's work.
672
+ // Memory pressure is handled by lib/memory-shed.js, not this timer.
673
+ if (promptsFor(sm).pendingCount(session) > 0) return;
674
+
620
675
  var lastActivity = session.lastActivityAt || 0;
621
676
  if (now - lastActivity > IDLE_TIMEOUT_MS) {
622
677
  console.log("[sdk-bridge] Reaping idle session " + session.localId +
623
678
  " (idle " + Math.round((now - lastActivity) / 60000) + "min)" +
624
679
  (session.title ? " title=" + JSON.stringify(session.title) : ""));
680
+ // Never silent when background agents are still registered: name
681
+ // them and mark the session as expected to resume.
682
+ sessionReclaim.announceLiveAgentReclaim({
683
+ session: session,
684
+ sm: sm,
685
+ send: send,
686
+ slug: slug,
687
+ reason: "idle_reap",
688
+ source: "idle-reap",
689
+ cause: "Clagentic: Console ended this session after " + Math.round(IDLE_TIMEOUT_MS / 60000)
690
+ + " minutes without activity.",
691
+ });
625
692
  // End the query so the for-await loop in processQueryStream
626
693
  // exits naturally, triggering the finally block cleanup.
627
694
  // Works for both in-process (messageQueue.end) and worker (handle.close) paths.
@@ -699,7 +766,7 @@ function createSDKBridge(opts) {
699
766
  // real onAutoTitle callers (sdk-message-processor.js) call this
700
767
  // fire-and-forget already and are unaffected by a function now
701
768
  // returning a value they don't use.
702
- return sessionAdapter.generateTitle(userMessages, { cwd: cwd }).then(function(title) {
769
+ return sessionAdapter.generateTitle(userMessages, withRuntimeEnv({ cwd: cwd }, session)).then(function(title) {
703
770
  if (!title || title.length < 2) return;
704
771
  title = title.substring(0, 100);
705
772
  // lr-62157d: overwrite whenever the current title is provisional (the
@@ -767,47 +834,26 @@ function createSDKBridge(opts) {
767
834
  return Promise.resolve({ action: "reject" });
768
835
  }
769
836
 
770
- return new Promise(function(resolve) {
771
- var requestId = crypto.randomUUID();
772
- if (!session.pendingElicitations) session.pendingElicitations = {};
773
- session.pendingElicitations[requestId] = {
774
- resolve: resolve,
775
- request: request,
776
- };
777
- sendAndRecord(session, {
778
- type: "elicitation_request",
779
- requestId: requestId,
780
- serverName: request.serverName,
781
- message: request.message,
782
- mode: request.mode || "form",
783
- url: request.url || null,
784
- elicitationId: request.elicitationId || null,
785
- requestedSchema: request.requestedSchema || null,
786
- });
837
+ var opened = promptsFor(sm).open(session, "elicitation", request, { signal: opts && opts.signal });
787
838
 
788
- if (pushModule) {
789
- var _elicitPayload = {
790
- type: "elicitation",
791
- slug: slug,
792
- title: (request.serverName || "MCP Server") + " needs input",
793
- body: request.message || "Waiting for your response",
794
- tag: "claude-elicitation",
795
- };
796
- // Route to session owner only — body carries MCP message text.
797
- if (session.ownerId && pushModule.sendPushToUser) {
798
- pushModule.sendPushToUser(session.ownerId, _elicitPayload);
799
- } else {
800
- pushModule.sendPush(_elicitPayload);
801
- }
839
+ // No push for a prompt that ended at once (its signal was already aborted).
840
+ if (pushModule && opened.pending) {
841
+ var _elicitPayload = {
842
+ type: "elicitation",
843
+ slug: slug,
844
+ title: (request.serverName || "MCP Server") + " needs input",
845
+ body: request.message || "Waiting for your response",
846
+ tag: "claude-elicitation",
847
+ };
848
+ // Route to session owner only — body carries MCP message text.
849
+ if (session.ownerId && pushModule.sendPushToUser) {
850
+ pushModule.sendPushToUser(session.ownerId, _elicitPayload);
851
+ } else {
852
+ pushModule.sendPush(_elicitPayload);
802
853
  }
854
+ }
803
855
 
804
- if (opts.signal) {
805
- opts.signal.addEventListener("abort", function() {
806
- delete session.pendingElicitations[requestId];
807
- resolve({ action: "reject" });
808
- });
809
- }
810
- });
856
+ return opened.answer;
811
857
  }
812
858
 
813
859
 
@@ -1034,15 +1080,22 @@ function createSDKBridge(opts) {
1034
1080
  }
1035
1081
 
1036
1082
  function handleCanUseTool(session, toolName, input, opts) {
1083
+ opts = opts || {};
1084
+ // An ask the user's own ask rule forced is a human prompt by the user's
1085
+ // stated intent (the SDK's matchedAskRule): none of the host-side
1086
+ // auto-approvals below - full auto, an autonomous loop, the read-only
1087
+ // whitelist, an earlier Allow for session - may answer it.
1088
+ var ruleForced = !!opts.matchedAskRule;
1089
+
1037
1090
  // Full-auto mode: auto-approve everything except AskUserQuestion
1038
1091
  // (which still needs to go through the user interaction flow).
1039
- if (sm.currentPermissionMode === "bypassPermissions" && toolName !== "AskUserQuestion") {
1092
+ if (!ruleForced && sm.currentPermissionMode === "bypassPermissions" && toolName !== "AskUserQuestion") {
1040
1093
  return Promise.resolve({ behavior: "allow", updatedInput: input });
1041
1094
  }
1042
1095
 
1043
1096
  // Ralph Loop execution: auto-approve all tools, deny interactive ones.
1044
1097
  // Crafting sessions are interactive — user and Claude collaborate to build PROMPT.md / JUDGE.md.
1045
- if (session.loop && session.loop.active && session.loop.role !== "crafting") {
1098
+ if (!ruleForced && session.loop && session.loop.active && session.loop.role !== "crafting") {
1046
1099
  if (toolName === "AskUserQuestion") {
1047
1100
  return Promise.resolve({ behavior: "deny", message: "Autonomous mode. Make your own decision." });
1048
1101
  }
@@ -1053,32 +1106,36 @@ function createSDKBridge(opts) {
1053
1106
  }
1054
1107
 
1055
1108
  // Check shared whitelist (read-only tools, safe browser tools, safe bash commands)
1056
- var whitelisted = checkToolWhitelist(toolName, input);
1109
+ var whitelisted = ruleForced ? null : checkToolWhitelist(toolName, input);
1057
1110
  if (whitelisted) {
1058
1111
  return Promise.resolve(whitelisted);
1059
1112
  }
1060
1113
 
1061
- // AskUserQuestion: wait for user answers via WebSocket
1062
- if (toolName === "AskUserQuestion") {
1063
- return new Promise(function(resolve) {
1064
- session.pendingAskUser[opts.toolUseID] = {
1065
- resolve: resolve,
1066
- input: input,
1067
- };
1068
- if (opts.signal) {
1069
- opts.signal.addEventListener("abort", function() {
1070
- delete session.pendingAskUser[opts.toolUseID];
1071
- sendAndRecord(session, { type: "ask_user_answered", toolId: opts.toolUseID });
1072
- resolve({ behavior: "deny", message: "Cancelled" });
1073
- });
1074
- }
1075
- });
1076
- }
1114
+ var prompts = promptsFor(sm);
1077
1115
 
1078
- // Auto-approve if tool was previously allowed for session (lr-f969dc:
1079
- // keyed on toolName + input discriminator, not bare toolName — see
1080
- // permissionGrantKey doc comment for why the Skill tool needs this).
1081
- if (session.allowedTools && session.allowedTools[permissionGrantKey(toolName, input)]) {
1116
+ // AskUserQuestion: the operator's answers become the tool's input.
1117
+ if (toolName === "AskUserQuestion") {
1118
+ return prompts.open(session, "ask_user", { input: input }, {
1119
+ toolUseId: opts.toolUseID,
1120
+ signal: opts.signal,
1121
+ }).answer;
1122
+ }
1123
+
1124
+ var kind = toolApprovalKind(toolName);
1125
+
1126
+ // Auto-approve if tool was previously allowed for session (keyed on
1127
+ // toolName + input discriminator, not bare toolName — see
1128
+ // permissionGrantKey's doc comment for why the Skill tool needs this).
1129
+ // An Allow-for-session grant is a standing rule for every later call with
1130
+ // the same key. The SDK forbids that for an ask marked
1131
+ // suppressAlwaysAllowRule (a rule would grant more than this ask's own
1132
+ // action), so such an ask is never answered by an earlier grant. An ask
1133
+ // marked defaultToNo must open on No, which a silent approval would
1134
+ // bypass; that is the stricter, safe reading of the hint. A rule-forced ask
1135
+ // (matched_ask_rule) was put to the operator on purpose and is never
1136
+ // auto-approved either.
1137
+ var needsOwnAnswer = ruleForced || opts.suppressAlwaysAllowRule === true || opts.defaultToNo === true;
1138
+ if (kind === "permission" && !needsOwnAnswer && prompts.isGranted(session, toolName, input)) {
1082
1139
  return Promise.resolve({ behavior: "allow", updatedInput: input });
1083
1140
  }
1084
1141
 
@@ -1093,70 +1150,55 @@ function createSDKBridge(opts) {
1093
1150
  // this hang-fix should bundle silently. Needs a design pass (e.g. scope
1094
1151
  // the timeout to sub-agent-owned entries only, or make it operator-
1095
1152
  // configurable) rather than copying the worker's blanket 30s.
1096
- return new Promise(function(resolve) {
1097
- var requestId = crypto.randomUUID();
1098
- sm.permissionRequestIndex[requestId] = session.localId;
1099
- session.pendingPermissions[requestId] = {
1100
- resolve: resolve,
1101
- requestId: requestId,
1153
+ // The registry creates the notification and dismisses it when the
1154
+ // prompt settles.
1155
+ // A prompt raised by a background agent says so, on the card, the banner
1156
+ // and the push: otherwise it reads as the parent's own call and is easy
1157
+ // to miss while the parent sits idle.
1158
+ var agentLabel = sessionReclaim.ownerLabelOfTool(session, prompts, opts.toolUseID);
1159
+ var agentPrefix = agentLabel ? 'Background agent "' + agentLabel + '": ' : "";
1160
+ var opened = prompts.open(session, kind, {
1161
+ toolName: toolName,
1162
+ toolInput: input,
1163
+ decisionReason: agentLabel
1164
+ ? 'Requested by background agent "' + agentLabel + '". ' + (opts.decisionReason || "")
1165
+ : (opts.decisionReason || ""),
1166
+ vendor: session.vendor || (adapter && adapter.vendor) || "claude",
1167
+ suppressAlwaysAllowRule: opts.suppressAlwaysAllowRule,
1168
+ defaultToNo: opts.defaultToNo,
1169
+ matchedAskRule: opts.matchedAskRule,
1170
+ }, {
1171
+ toolUseId: opts.toolUseID,
1172
+ signal: opts.signal,
1173
+ notification: {
1174
+ title: agentPrefix + permissionPushTitle(toolName, input),
1175
+ body: permissionPushBody(toolName, input),
1176
+ slug: slug,
1177
+ sessionId: session.localId,
1178
+ ownerId: session.ownerId || null,
1102
1179
  toolName: toolName,
1103
1180
  toolInput: input,
1104
- toolUseId: opts.toolUseID,
1105
- decisionReason: opts.decisionReason || "",
1106
- };
1181
+ },
1182
+ });
1107
1183
 
1108
- var permMsg = {
1184
+ // No push for a prompt that ended at once (its signal was already aborted).
1185
+ if (pushModule && opened.pending) {
1186
+ var _permPayload = {
1109
1187
  type: "permission_request",
1110
- requestId: requestId,
1111
- toolName: toolName,
1112
- toolInput: input,
1113
- toolUseId: opts.toolUseID,
1114
- decisionReason: opts.decisionReason || "",
1115
- vendor: session.vendor || (adapter && adapter.vendor) || "claude",
1188
+ slug: slug,
1189
+ requestId: opened.requestId,
1190
+ title: agentPrefix + permissionPushTitle(toolName, input),
1191
+ body: permissionPushBody(toolName, input),
1116
1192
  };
1117
- sendAndRecord(session, permMsg);
1118
- onProcessingChanged(); // update cross-project permission badge
1119
-
1120
- if (pushModule) {
1121
- var _permPayload = {
1122
- type: "permission_request",
1123
- slug: slug,
1124
- requestId: requestId,
1125
- title: permissionPushTitle(toolName, input),
1126
- body: permissionPushBody(toolName, input),
1127
- };
1128
- // Route to session owner only — body carries tool name and input (may contain paths/code).
1129
- if (session.ownerId && pushModule.sendPushToUser) {
1130
- pushModule.sendPushToUser(session.ownerId, _permPayload);
1131
- } else {
1132
- pushModule.sendPush(_permPayload);
1133
- }
1134
- }
1135
-
1136
- var _nm = getNotificationsModule();
1137
- if (_nm) {
1138
- _nm.notify("permission_request", {
1139
- title: permissionPushTitle(toolName, input),
1140
- body: permissionPushBody(toolName, input),
1141
- slug: slug,
1142
- sessionId: session.localId,
1143
- ownerId: session.ownerId || null,
1144
- requestId: requestId,
1145
- toolName: toolName,
1146
- toolInput: input,
1147
- });
1193
+ // Route to session owner only — body carries tool name and input (may contain paths/code).
1194
+ if (session.ownerId && pushModule.sendPushToUser) {
1195
+ pushModule.sendPushToUser(session.ownerId, _permPayload);
1196
+ } else {
1197
+ pushModule.sendPush(_permPayload);
1148
1198
  }
1199
+ }
1149
1200
 
1150
- if (opts.signal) {
1151
- opts.signal.addEventListener("abort", function() {
1152
- delete session.pendingPermissions[requestId];
1153
- delete sm.permissionRequestIndex[requestId];
1154
- sendAndRecord(session, { type: "permission_cancel", requestId: requestId });
1155
- onProcessingChanged(); // update cross-project permission badge
1156
- resolve({ behavior: "deny", message: "Request cancelled" });
1157
- });
1158
- }
1159
- });
1201
+ return opened.answer;
1160
1202
  }
1161
1203
 
1162
1204
  /**
@@ -1289,10 +1331,7 @@ function createSDKBridge(opts) {
1289
1331
  sessionActivity.bumpGeneration(session);
1290
1332
  send({ type: "status", processing: false });
1291
1333
  sendAndRecord(session, { type: "thinking_stop" });
1292
- var interruptMsg = (session.vendor === "codex")
1293
- ? "\u25a0 Conversation interrupted - tell the model what to do differently."
1294
- : "Interrupted \u00b7 What should Claude do instead?";
1295
- sendAndRecord(session, { type: "info", text: interruptMsg });
1334
+ sendAndRecord(session, { type: "info", text: interruptMessageFor(session) });
1296
1335
  sendAndRecord(session, { type: "done", code: 0 });
1297
1336
  sm.broadcastSessionList();
1298
1337
  }
@@ -1308,10 +1347,7 @@ function createSDKBridge(opts) {
1308
1347
  if (err.name === "AbortError" || (myAbortController && myAbortController.signal.aborted) || session.taskStopRequested) {
1309
1348
  if (!session.destroying) {
1310
1349
  sendAndRecord(session, { type: "thinking_stop" });
1311
- var interruptMsg2 = (session.vendor === "codex")
1312
- ? "\u25a0 Conversation interrupted - tell the model what to do differently."
1313
- : "Interrupted \u00b7 What should Claude do instead?";
1314
- sendAndRecord(session, { type: "info", text: interruptMsg2 });
1350
+ sendAndRecord(session, { type: "info", text: interruptMessageFor(session) });
1315
1351
  sendAndRecord(session, { type: "done", code: 0 });
1316
1352
  }
1317
1353
  } else if (session.destroying) {
@@ -1361,23 +1397,23 @@ function createSDKBridge(opts) {
1361
1397
  var authLinuxUser = authUser && authUser.linuxUser ? authUser.linuxUser : null;
1362
1398
  var canAutoLogin = !!authLinuxUser
1363
1399
  || (authUser && authUser.role === "admin");
1364
- var authTitle = (session.vendor === "codex" ? "Codex" : "Claude Code") + " is not logged in.";
1400
+ var authFacts = authRequiredFacts(sessionVendorId(session));
1365
1401
  var authMsg = {
1366
1402
  type: "auth_required",
1367
- text: authTitle,
1368
- vendor: session.vendor || (adapter && adapter.vendor) || "claude",
1369
- loginCommand: getLoginCommand(session.vendor || (adapter && adapter.vendor) || "claude"),
1403
+ text: authFacts.title,
1404
+ vendor: authFacts.vendor,
1405
+ loginCommand: authFacts.loginCommand,
1370
1406
  linuxUser: authLinuxUser,
1371
1407
  canAutoLogin: canAutoLogin,
1372
1408
  };
1373
1409
  sendAndRecord(session, authMsg);
1374
1410
  if (!notifyAuthRequired(
1375
1411
  session,
1376
- authTitle,
1412
+ authFacts.title,
1377
1413
  "Open a terminal, then click the URL and follow the instructions.",
1378
1414
  authLinuxUser,
1379
1415
  canAutoLogin,
1380
- getLoginCommand(session.vendor || (adapter && adapter.vendor) || "claude")
1416
+ authFacts.loginCommand
1381
1417
  )) {
1382
1418
  // chat message already sent above
1383
1419
  }
@@ -1451,50 +1487,20 @@ function createSDKBridge(opts) {
1451
1487
  // unwinding (e.g. rewind_execute nulls session.queryInstance, then the
1452
1488
  // user immediately sends a message, starting a fresh query). If that
1453
1489
  // happened, session.queryInstance now points at the newer query's
1454
- // instance, not ours. Resetting pendingPermissions/pendingAskUser/
1455
- // pendingElicitations/isProcessing here would wipe the NEW query's
1456
- // in-flight state out from under it (approval clicks silently ignored,
1457
- // turn hangs forever) and flip isProcessing=false while the new query
1458
- // is still live. Only run the reset when we still own the session
1459
- // (queryInstance is unchanged or has already been nulled by our own
1460
- // completion path above) — never when a newer query has taken over.
1461
- if (session.queryInstance === myQueryInstance || session.queryInstance === null) {
1462
- // lr-9d4b: This finally block runs on EVERY ordinary (non-superseded)
1463
- // turn completion — including the common case where a backgrounded
1464
- // sub-agent's own permission request (e.g. Bash) is still awaiting
1465
- // the operator's click when the parent turn ends normally. This is a
1466
- // second wipe of pendingPermissions on the SAME turn as the 'result'
1467
- // message's own reset (sdk-message-processor.js), microseconds later
1468
- // once the for-await loop drains. Unconditionally clearing here would
1469
- // re-orphan the resolver the result handler just preserved. Use the
1470
- // same shared keep-decision as that handler (see
1471
- // lib/sdk-permission-ownership.js) rather than duplicating it.
1472
- var _perm9d4b = partitionSubagentOwnedPermissions(session);
1473
- // lr-f940 (N3): sweep sm.permissionRequestIndex for every entry this
1474
- // pass is about to drop (everything not in keptPermissions) — this is
1475
- // the ONLY cleanup that runs for the worker path, whose fake abort
1476
- // signal (yoke/adapters/claude.js) never fires the normal
1477
- // abort-listener deletion. Must run against the PRE-reassignment map.
1478
- sweepClearedPermissionIndex(sm, session.pendingPermissions, _perm9d4b.keptPermissions);
1479
- session.pendingPermissions = _perm9d4b.keptPermissions;
1480
- // Preserve MCP-mode AskUserQuestion entries across turn boundaries.
1481
- // The MCP path is intentionally stateless: ask_user returns immediately
1482
- // ("card posted, end your turn") and the answer arrives as a new
1483
- // user_message on the next turn. Those entries MUST survive this finally
1484
- // block so ask_user_response can find the toolId and inject the answer.
1485
- // canUseTool-mode entries hold an open SDK callback that dies with the
1486
- // query anyway, so those are correctly cleared here.
1487
- var _keepAskUser = {};
1488
- for (var _tid in session.pendingAskUser) {
1489
- var _pau = session.pendingAskUser[_tid];
1490
- if (_pau && _pau.mode === "mcp") _keepAskUser[_tid] = _pau;
1491
- }
1492
- session.pendingAskUser = _keepAskUser;
1493
- session.pendingElicitations = {};
1494
- // lr-9d4b: keep activeTaskToolIds/taskIdMap bookkeeping in sync with
1495
- // whichever Task ids just had a permission preserved above — mirrors
1496
- // the same reconciliation the 'result' handler performs.
1497
- retainPreservedTaskBookkeeping(session, _perm9d4b.preservedTaskIds);
1490
+ // instance, not ours. Ending the session's prompts or resetting
1491
+ // isProcessing here would wipe the NEW query's in-flight state out
1492
+ // from under it (approval clicks silently ignored, turn hangs forever)
1493
+ // and flip isProcessing=false while the new query is still live. Only
1494
+ // run the reset when we still own the session (queryInstance is
1495
+ // unchanged or has already been nulled by our own completion path
1496
+ // above) — never when a newer query has taken over.
1497
+ var ownsSession = session.queryInstance === myQueryInstance || session.queryInstance === null;
1498
+ // The registry ends the prompts OUR query opened, except those of a
1499
+ // tracked backgrounded sub-agent, which the operator can still answer;
1500
+ // a replacement query's prompts are never touched.
1501
+ promptsFor(sm).endQuery(session, myQueryInstance, ownsSession);
1502
+ if (ownsSession) {
1503
+ msgProcessor.retainTaskIdMap(session);
1498
1504
 
1499
1505
  // Auto-continue on rate limit (scheduler sessions, or user setting)
1500
1506
  // Mark session as done processing so the late rate_limit_event handler
@@ -1545,7 +1551,7 @@ function createSDKBridge(opts) {
1545
1551
 
1546
1552
  var handle;
1547
1553
  try {
1548
- handle = await adapter.createQuery({
1554
+ handle = await adapter.createQuery(withRuntimeEnv({
1549
1555
  cwd: cwd,
1550
1556
  resumeSessionId: session.cliSessionId,
1551
1557
  adapterOptions: {
@@ -1554,7 +1560,7 @@ function createSDKBridge(opts) {
1554
1560
  enableFileCheckpointing: true,
1555
1561
  },
1556
1562
  },
1557
- });
1563
+ }, session));
1558
1564
  } catch (e) {
1559
1565
  sendAndRecord(session, { type: "error", text: "Failed to load Claude SDK: " + (e.message || e) });
1560
1566
  throw e;
@@ -1616,7 +1622,7 @@ function createSDKBridge(opts) {
1616
1622
  async function rollbackConversation(session, numTurns) {
1617
1623
  var sessionAdapter = getAdapterForSession(session);
1618
1624
  if (sessionAdapter && typeof sessionAdapter.rollbackThread === "function") {
1619
- await sessionAdapter.rollbackThread(session.cliSessionId, numTurns);
1625
+ await sessionAdapter.rollbackThread(session.cliSessionId, numTurns, withRuntimeEnv({}, session));
1620
1626
  }
1621
1627
  // Claude: conversation rollback is handled by rewindFiles + local history trim
1622
1628
  }
@@ -1628,7 +1634,12 @@ function createSDKBridge(opts) {
1628
1634
 
1629
1635
  async function forkSessionUnified(session, uuid) {
1630
1636
  var sessionAdapter = getAdapterForSession(session);
1631
- var result = await sessionAdapter.forkSession(session.cliSessionId, { upToMessageId: uuid, dir: cwd });
1637
+ var forkOpts = { upToMessageId: uuid, dir: cwd };
1638
+ // Only an adapter that keeps its own servers (rollbackThread marks it) is
1639
+ // told whose environment the thread ran under; the Claude SDK would take
1640
+ // the extra key as one of its own options.
1641
+ if (typeof sessionAdapter.rollbackThread === "function") withRuntimeEnv(forkOpts, session);
1642
+ var result = await sessionAdapter.forkSession(session.cliSessionId, forkOpts);
1632
1643
  if (!result || !result.sessionId) throw new Error("Fork returned no session id");
1633
1644
 
1634
1645
  // Adapters with rollbackThread (e.g. Codex) use local history copy
@@ -1639,23 +1650,37 @@ function createSDKBridge(opts) {
1639
1650
  return { sessionId: result.sessionId, useLocalHistory: false };
1640
1651
  }
1641
1652
 
1642
- async function startQuery(session, text, images, linuxUser) {
1653
+ // `initiator` (turn-initiator.js INITIATORS) is who started this turn. It is
1654
+ // per turn: it stamps the first message and decides the new process's
1655
+ // environment, and says nothing about later turns of the session.
1656
+ async function startQuery(session, text, images, linuxUser, initiator) {
1643
1657
  async function ensureVendorReady(vendor) {
1644
1658
  if (!vendor) return null;
1659
+ // What the adapter's live session advertises narrows its declaration; the
1660
+ // result is recorded for this vendor and the browser is told.
1661
+ function recordInit(initResult) {
1662
+ sessionCapabilities.recordCapabilities(sm, vendor, initResult && initResult.capabilities);
1663
+ sendVendorRegistry();
1664
+ }
1645
1665
  var vendorAdapter = adapters[vendor] || null;
1646
1666
  if (!vendorAdapter) {
1647
1667
  var yoke = require("./yoke");
1648
- vendorAdapter = await yoke.lazyCreateAdapter(adapters, vendor, {
1668
+ // The shared model list is read in the environment no session adds to
1669
+ // (as the warmup and the vendor switch do), never a session's own: one
1670
+ // user's endpoint must not decide the models other users are shown. A
1671
+ // session's own server is started for it when its query begins.
1672
+ vendorAdapter = await yoke.lazyCreateAdapter(adapters, vendor, withRuntimeEnv({
1649
1673
  cwd: cwd,
1674
+ osUsers: osUsersMode,
1650
1675
  dangerouslySkipPermissions: dangerouslySkipPermissions,
1651
1676
  linuxUser: linuxUser || undefined,
1652
1677
  clayPort: clayPort,
1653
1678
  clayTls: clayTls,
1654
1679
  clayAuthToken: clayAuthToken,
1655
1680
  slug: slug,
1656
- });
1681
+ }), recordInit);
1657
1682
  } else if ((!sm.modelsByVendor || !sm.modelsByVendor[vendor]) && typeof vendorAdapter.init === "function") {
1658
- await vendorAdapter.init({
1683
+ recordInit(await vendorAdapter.init(withRuntimeEnv({
1659
1684
  cwd: cwd,
1660
1685
  dangerouslySkipPermissions: dangerouslySkipPermissions,
1661
1686
  linuxUser: linuxUser || undefined,
@@ -1663,18 +1688,32 @@ function createSDKBridge(opts) {
1663
1688
  clayTls: clayTls,
1664
1689
  clayAuthToken: clayAuthToken,
1665
1690
  slug: slug,
1666
- });
1691
+ })));
1667
1692
  }
1668
1693
  if (vendorAdapter) {
1669
1694
  sm.availableVendors = Object.keys(adapters);
1670
1695
  sm.modelsByVendor = sm.modelsByVendor || {};
1671
1696
  if (!sm.modelsByVendor[vendor] && typeof vendorAdapter.supportedModels === "function") {
1672
- sm.modelsByVendor[vendor] = await vendorAdapter.supportedModels();
1697
+ sm.modelsByVendor[vendor] = await vendorAdapter.supportedModels(withRuntimeEnv({}));
1673
1698
  }
1674
1699
  }
1675
1700
  return vendorAdapter;
1676
1701
  }
1677
1702
 
1703
+ // A vendor that is not registered cannot be started, logged into or
1704
+ // looked up: say so by name instead of falling through to a default.
1705
+ if (session.vendor && !yokeRegistry.isKnown(session.vendor)) {
1706
+ sendAndRecord(session, { type: "error", text: "Unknown agent: " + String(session.vendor) });
1707
+ sendAndRecord(session, { type: "done", code: 1 });
1708
+ return;
1709
+ }
1710
+ // An agent that per-user OS isolation rules out is refused with its reason,
1711
+ // not offered a login, and nothing of it is started.
1712
+ if (session.vendor && yokeRegistry.disabledByOsUsers(session.vendor, osUsersMode)) {
1713
+ sendAndRecord(session, { type: "error", text: yokeRegistry.osUsersReasonFor(session.vendor) });
1714
+ sendAndRecord(session, { type: "done", code: 1 });
1715
+ return;
1716
+ }
1678
1717
  // If vendor is set but adapter not ready, try lazy creation (user may have logged in)
1679
1718
  if (session.vendor && !adapters[session.vendor]) {
1680
1719
  var lazyAdapter = await ensureVendorReady(session.vendor);
@@ -1696,7 +1735,8 @@ function createSDKBridge(opts) {
1696
1735
  }
1697
1736
  // If still not available after lazy check, send auth_required
1698
1737
  if (session.vendor && !adapters[session.vendor]) {
1699
- var vendorName = session.vendor.charAt(0).toUpperCase() + session.vendor.slice(1);
1738
+ var authFacts2 = authRequiredFacts(session.vendor);
1739
+ var vendorName = authFacts2.displayName;
1700
1740
  var authUser = session.ownerId ? usersModule.findUserById(session.ownerId) : null;
1701
1741
  var authLinuxUser = authUser && authUser.linuxUser ? authUser.linuxUser : null;
1702
1742
  var canAutoLogin = !!authLinuxUser
@@ -1713,20 +1753,20 @@ function createSDKBridge(opts) {
1713
1753
  }
1714
1754
  var authMsg2 = {
1715
1755
  type: "auth_required",
1716
- text: vendorName + " is not logged in.",
1717
- vendor: session.vendor,
1718
- loginCommand: getLoginCommand(session.vendor),
1756
+ text: authFacts2.title,
1757
+ vendor: authFacts2.vendor,
1758
+ loginCommand: authFacts2.loginCommand,
1719
1759
  linuxUser: authLinuxUser,
1720
1760
  canAutoLogin: canAutoLogin,
1721
1761
  };
1722
1762
  sendAndRecord(session, authMsg2);
1723
1763
  if (!notifyAuthRequired(
1724
1764
  session,
1725
- vendorName + " is not logged in.",
1765
+ authFacts2.title,
1726
1766
  "Open a terminal, then click the URL and follow the instructions.",
1727
1767
  authLinuxUser,
1728
1768
  canAutoLogin,
1729
- getLoginCommand(session.vendor)
1769
+ authFacts2.loginCommand
1730
1770
  )) {
1731
1771
  // chat message already sent above
1732
1772
  }
@@ -1758,6 +1798,20 @@ function createSDKBridge(opts) {
1758
1798
  return;
1759
1799
  }
1760
1800
 
1801
+ // Soft-limit pressure / drain: refuse new query processes but leave
1802
+ // sessions that already hold a live query untouched. Checked before the
1803
+ // slot is claimed so a refusal never increments the live counter.
1804
+ var newWorkRefusal = isNewQuery ? getNewWorkRefusal() : null;
1805
+ if (newWorkRefusal) {
1806
+ console.warn("[sdk-bridge] New-work gate closed — refusing new query for session " + session.localId);
1807
+ session.isProcessing = false;
1808
+ onProcessingChanged();
1809
+ sendAndRecord(session, { type: "error", text: newWorkRefusal });
1810
+ sendAndRecord(session, { type: "done", code: 1 });
1811
+ sm.broadcastSessionList();
1812
+ return;
1813
+ }
1814
+
1761
1815
  // lr-2d91: MemAvailable gate — check before claiming a slot so a rejected
1762
1816
  // query never increments the live counter.
1763
1817
  if (isNewQuery) {
@@ -1907,12 +1961,13 @@ function createSDKBridge(opts) {
1907
1961
 
1908
1962
  session.blocks = {};
1909
1963
  session.sentToolResults = {};
1910
- session.activeTaskToolIds = {};
1911
- session.pendingElicitations = {};
1964
+ // Tasks of earlier queries are gone, except one whose prompt the
1965
+ // operator can still answer.
1966
+ promptsFor(sm).beginQuery(session);
1912
1967
  session.streamedText = false;
1913
1968
  // lr-9bcd7b: PRIMARY leak-resistance layer — bump the activity
1914
1969
  // generation at every startQuery call (turn boundary), same spot
1915
- // activeTaskToolIds is reset above. Any token from a prior generation
1970
+ // Task tracking is reset above. Any token from a prior generation
1916
1971
  // (e.g. a subagent that died silently mid-turn without ever releasing)
1917
1972
  // becomes invisible to isSessionActive immediately, with no explicit
1918
1973
  // release or timer needed — see lib/session-activity.js header.
@@ -1941,9 +1996,11 @@ function createSDKBridge(opts) {
1941
1996
  // settingSources catalog it uses internally — no in-band AgentDefinition
1942
1997
  // map is needed (that was a workaround for the old CLI-parse path).
1943
1998
  //
1944
- // Agent injection is Claude Code-only. The Codex adapter has no equivalent
1945
- // API surface, so we skip this block for Codex sessions. The UI already
1946
- // hides the Agent Chat entry point for Codex projects; this guard is
1999
+ // Agent injection needs the agentInjection capability, as RESOLVED for the
2000
+ // session's vendor (declaration narrowed by what its live session
2001
+ // advertised), never the declaration alone. An adapter that
2002
+ // lacks it (Codex has no equivalent API surface) skips this block. The UI
2003
+ // disables the Agent Chat entry point for such an agent; this guard is
1947
2004
  // belt-and-suspenders for sessions that carry agentName from a prior
1948
2005
  // vendor switch or a direct ws message.
1949
2006
  //
@@ -1956,7 +2013,8 @@ function createSDKBridge(opts) {
1956
2013
  // applied when queryModel is computed below (after loop-settings resolution).
1957
2014
  var _agentDeclaredModel = null;
1958
2015
 
1959
- if (session.agentName && sessionAdapter.vendor !== 'codex') {
2016
+ var _injectionVendor = sessionCapabilities.effectiveVendorId(sm, session, sessionAdapter.vendor);
2017
+ if (session.agentName && sessionCapabilities.capabilitiesFor(sm, _injectionVendor).agentInjection) {
1960
2018
  claudeOpts.agent = session.agentName;
1961
2019
 
1962
2020
  // lr-3ccc78 — on a shared multi-user daemon (linuxUser set), read the
@@ -2097,10 +2155,13 @@ function createSDKBridge(opts) {
2097
2155
  var mergedMcpServers = mergeMcpServers(getMcpServers(), getRemoteMcpServers) || undefined;
2098
2156
  var queryOpts = {
2099
2157
  cwd: cwd,
2158
+ initiator: initiator,
2100
2159
  model: queryModel,
2101
2160
  effort: ls.effort || sm.currentEffort || undefined,
2102
2161
  toolServers: mergedMcpServers,
2103
- toolServerDescriptors: extractMcpDescriptors(mergedMcpServers) || undefined,
2162
+ toolServerDescriptors: extractMcpDescriptors(mergedMcpServers, function (diagnostic) {
2163
+ sendAndRecord(session, diagnostic);
2164
+ }) || undefined,
2104
2165
  resumeSessionId: session.cliSessionId || undefined,
2105
2166
  abortController: linuxUser ? undefined : session.abortController,
2106
2167
  canUseTool: function(toolName, input, toolOpts) {
@@ -2137,6 +2198,9 @@ function createSDKBridge(opts) {
2137
2198
  },
2138
2199
  };
2139
2200
 
2201
+ // The variables Settings add to this runtime's environment, as of now.
2202
+ withRuntimeEnv(queryOpts, session);
2203
+
2140
2204
  var handle;
2141
2205
  console.log("[sdk-bridge] calling adapter.createQuery... vendor=" + sessionAdapter.vendor);
2142
2206
  try {
@@ -2181,7 +2245,7 @@ function createSDKBridge(opts) {
2181
2245
 
2182
2246
  // Push initial user message through the QueryHandle
2183
2247
  console.log("[sdk-bridge] pushing initial message via handle.pushMessage...");
2184
- handle.pushMessage(text, images);
2248
+ handle.pushMessage(text, images, initiator);
2185
2249
 
2186
2250
  // lr-b61b: Flush any messages that arrived between turns (after the previous
2187
2251
  // finally block nulled queryInstance and before this startQuery call).
@@ -2189,7 +2253,7 @@ function createSDKBridge(opts) {
2189
2253
  console.log("[sdk-bridge] startQuery: flushing " + session.pendingMessages.length + " buffered pending message(s) for session " + session.localId);
2190
2254
  for (var pi = 0; pi < session.pendingMessages.length; pi++) {
2191
2255
  var pm = session.pendingMessages[pi];
2192
- handle.pushMessage(pm.text, pm.images);
2256
+ handle.pushMessage(pm.text, pm.images, pm.initiator);
2193
2257
  }
2194
2258
  session.pendingMessages = [];
2195
2259
  }
@@ -2227,11 +2291,11 @@ function createSDKBridge(opts) {
2227
2291
  }
2228
2292
  }
2229
2293
 
2230
- function pushMessage(session, text, images) {
2294
+ function pushMessage(session, text, images, initiator) {
2231
2295
  session.lastActivityAt = Date.now();
2232
2296
  // Route through QueryHandle (works for both in-process and worker paths)
2233
2297
  if (session.queryInstance && typeof session.queryInstance.pushMessage === "function") {
2234
- session.queryInstance.pushMessage(text, images);
2298
+ session.queryInstance.pushMessage(text, images, initiator);
2235
2299
  } else {
2236
2300
  // lr-b61b: queryInstance is null between turns (finally block has run but
2237
2301
  // startQuery has not been called yet). Buffer the message so it is not
@@ -2247,7 +2311,7 @@ function createSDKBridge(opts) {
2247
2311
  // so any candidate cause that lands a message here is visible.
2248
2312
  var wasFull = session.pendingMessages.length >= MAX_PENDING_MESSAGES;
2249
2313
  if (wasFull) session.pendingMessages.shift();
2250
- session.pendingMessages.push({ text: text, images: images });
2314
+ session.pendingMessages.push({ text: text, images: images, initiator: initiator });
2251
2315
  console.log("[sdk-bridge] pushMessage: queryInstance null, buffered message for session " + session.localId + " (pending=" + session.pendingMessages.length + ")");
2252
2316
  sendAndRecord(session, {
2253
2317
  type: "diagnostic",
@@ -2263,6 +2327,7 @@ function createSDKBridge(opts) {
2263
2327
  function permissionPushTitle(toolName, input) {
2264
2328
  if (!input) return "Claude wants to use " + toolName;
2265
2329
  var file = input.file_path ? input.file_path.split(/[/\\]/).pop() : "";
2330
+ if (isAgentDispatchTool(toolName)) return "Claude wants to launch an agent";
2266
2331
  switch (toolName) {
2267
2332
  case "Bash": return "Claude wants to run a command";
2268
2333
  case "Edit": return "Claude wants to edit " + (file || "a file");
@@ -2272,7 +2337,6 @@ function createSDKBridge(opts) {
2272
2337
  case "Glob": return "Claude wants to find files";
2273
2338
  case "WebFetch": return "Claude wants to fetch a URL";
2274
2339
  case "WebSearch": return "Claude wants to search the web";
2275
- case "Task": return "Claude wants to launch an agent";
2276
2340
  default: return "Claude wants to use " + toolName;
2277
2341
  }
2278
2342
  }
@@ -2303,40 +2367,25 @@ function createSDKBridge(opts) {
2303
2367
  return text;
2304
2368
  }
2305
2369
 
2306
- // Detect which vendor binaries are installed for this user.
2307
- // In multi-user mode, runs checks as the specific Linux user.
2370
+ // Detect which vendor binaries are installed for an OS identity and record
2371
+ // the result for it. In multi-user mode the lookup runs as that Linux user;
2372
+ // a null user is the daemon's own account.
2308
2373
  function detectInstalledVendors(linuxUser) {
2309
- var execFileSync = require("child_process").execFileSync;
2310
- var fs = require("fs");
2311
- var result = [];
2312
-
2313
- function tryLookup(name) {
2314
- // name MUST be a value from the allowlist below — shell injection risk if dynamic
2315
- if (!["claude", "codex"].includes(name)) throw new Error("Disallowed binary name: " + name);
2316
- try {
2317
- if (linuxUser) {
2318
- execFileSync("su", ["-", linuxUser, "-c", "which " + name], { timeout: 3000, stdio: ["pipe", "pipe", "pipe"] });
2319
- } else {
2320
- if (process.platform === "win32") execFileSync("where", [name], { timeout: 3000, stdio: ["pipe", "pipe", "pipe"] });
2321
- else execFileSync("which", [name], { timeout: 3000, stdio: ["pipe", "pipe", "pipe"] });
2322
- }
2323
- return true;
2324
- } catch (e) {
2325
- return false;
2326
- }
2327
- }
2328
-
2329
- // Claude: check if binary is in PATH
2330
- if (tryLookup("claude")) result.push("claude");
2331
-
2332
- // Codex: check bundled binary or PATH
2333
- var codexBin = null;
2334
- try {
2335
- codexBin = require("./yoke/codex-app-server").findCodexPath();
2336
- } catch (e) {}
2337
- if ((codexBin && fs.existsSync(codexBin)) || tryLookup("codex")) result.push("codex");
2374
+ // The registry owns the probes and the allowlist of executable names.
2375
+ var state = require("./yoke").detectVendorInstallState(linuxUser || null, { osUsers: osUsersMode });
2376
+ recordInstallState(sm, linuxUser || null, state);
2377
+ return state.installed;
2378
+ }
2338
2379
 
2339
- return result;
2380
+ // The user installed or signed in to an agent after the daemon started: look
2381
+ // again, as the requesting OS identity (null: the daemon's account). The
2382
+ // caller sends the refreshed registry to the clients of that same identity;
2383
+ // install state is per identity, so nobody else receives it.
2384
+ function recheckVendors(linuxUser) {
2385
+ require("./yoke").invalidateAuthCache();
2386
+ _cachedFreshAuthState = null;
2387
+ detectInstalledVendors(linuxUser || null);
2388
+ return buildVendorRegistryMessage(sm, linuxUser || null);
2340
2389
  }
2341
2390
 
2342
2391
  // SDK warmup: initialize all available adapters and collect models.
@@ -2346,10 +2395,16 @@ function createSDKBridge(opts) {
2346
2395
  var defaultVendor = adapter ? adapter.vendor : "claude";
2347
2396
  sm.defaultVendor = defaultVendor;
2348
2397
 
2398
+ // Every registered vendor's declared capabilities are known up front, so a
2399
+ // session on a vendor other than the project default is gated on what its
2400
+ // own agent can do. The default vendor's entry is narrowed below by what
2401
+ // its live session advertises.
2402
+ sessionCapabilities.seedCapabilities(sm);
2403
+
2349
2404
  // Initialize default adapter first (provides skills, slash commands, etc.)
2350
2405
  if (adapter) {
2351
2406
  try {
2352
- var result = await adapter.init({
2407
+ var result = await adapter.init(withRuntimeEnv({
2353
2408
  cwd: cwd,
2354
2409
  dangerouslySkipPermissions: dangerouslySkipPermissions,
2355
2410
  linuxUser: linuxUser || undefined,
@@ -2357,7 +2412,7 @@ function createSDKBridge(opts) {
2357
2412
  clayTls: clayTls,
2358
2413
  clayAuthToken: clayAuthToken,
2359
2414
  slug: slug,
2360
- });
2415
+ }));
2361
2416
 
2362
2417
  // lr-3ccc78 — resolve the session owner's own home on a shared
2363
2418
  // multi-user daemon so global skill discovery isn't the daemon's
@@ -2385,8 +2440,7 @@ function createSDKBridge(opts) {
2385
2440
  // Store per-vendor models and capabilities
2386
2441
  sm.modelsByVendor = sm.modelsByVendor || {};
2387
2442
  sm.modelsByVendor[defaultVendor] = result.models || [];
2388
- sm.capabilitiesByVendor = sm.capabilitiesByVendor || {};
2389
- sm.capabilitiesByVendor[defaultVendor] = result.capabilities || {};
2443
+ sessionCapabilities.recordCapabilities(sm, defaultVendor, result.capabilities);
2390
2444
 
2391
2445
  // lr-1a26: Console-side settings preflight (epic lr-1a52 stage 5/5).
2392
2446
  // Non-blocking: runs after warmup succeeds, errors are swallowed so
@@ -2418,8 +2472,9 @@ function createSDKBridge(opts) {
2418
2472
  sm.modelsByVendor = sm.modelsByVendor || {};
2419
2473
 
2420
2474
  // Detect installed vendors per-user (binary existence check)
2421
- sm.installedVendors = detectInstalledVendors(linuxUser);
2475
+ detectInstalledVendors(linuxUser);
2422
2476
  sm.availableVendors = Object.keys(adapters);
2477
+ send(buildVendorRegistryMessage(sm, linuxUser || null));
2423
2478
 
2424
2479
  // Send initial state to client
2425
2480
  send({
@@ -2428,7 +2483,6 @@ function createSDKBridge(opts) {
2428
2483
  models: getModelsForVendor(defaultVendor),
2429
2484
  vendor: defaultVendor,
2430
2485
  availableVendors: sm.availableVendors,
2431
- installedVendors: sm.installedVendors,
2432
2486
  });
2433
2487
  }
2434
2488
 
@@ -2483,18 +2537,26 @@ function createSDKBridge(opts) {
2483
2537
  }
2484
2538
  }
2485
2539
 
2540
+ // Returns { ok: true } or { ok: false, error } like setModel: the effort is
2541
+ // recorded and announced only once the running query has taken it, and a
2542
+ // failure is shown to the operator instead of reading as a change.
2486
2543
  async function setEffort(session, effort) {
2487
2544
  if (!session.queryInstance) {
2488
2545
  sm.currentEffort = effort;
2489
2546
  send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort, betas: sm.currentBetas || [] });
2490
- return;
2547
+ return { ok: true };
2491
2548
  }
2492
- // Route through QueryHandle (works for both in-process and worker paths)
2493
- if (typeof session.queryInstance.setEffort === "function") {
2549
+ try {
2550
+ // Route through QueryHandle (works for both in-process and worker paths)
2494
2551
  await session.queryInstance.setEffort(effort);
2552
+ } catch (e) {
2553
+ var errMsg = (e && e.message) || String(e);
2554
+ send({ type: "error", text: "Failed to change effort: " + errMsg });
2555
+ return { ok: false, error: errMsg };
2495
2556
  }
2496
2557
  sm.currentEffort = effort;
2497
2558
  send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort, betas: sm.currentBetas || [] });
2559
+ return { ok: true };
2498
2560
  }
2499
2561
 
2500
2562
  async function setPermissionMode(session, mode) {
@@ -2572,9 +2634,11 @@ function createSDKBridge(opts) {
2572
2634
  permissionPushTitle: permissionPushTitle,
2573
2635
  permissionPushBody: permissionPushBody,
2574
2636
  warmup: warmup,
2637
+ recheckVendors: recheckVendors,
2575
2638
  stopTask: stopTask,
2576
2639
  startIdleReaper: startIdleReaper,
2577
2640
  stopIdleReaper: stopIdleReaper,
2641
+ getRuntimeEnvOverlay: getRuntimeEnvOverlay,
2578
2642
  getMemoryStats: getMemoryStats,
2579
2643
  // lr-62157d: exposed for direct unit testing of the provisional-title
2580
2644
  // overwrite guard, following the _test_-prefixed exposure convention
@@ -2591,5 +2655,5 @@ function getActiveLiveCount() {
2591
2655
  return _activeLiveCount;
2592
2656
  }
2593
2657
 
2594
- module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, readCgroupHeadroomMB, resolveMemAvailableThresholdMB, computeCgroupBlockCauseMessage, DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount, getActivityDivergenceStats, buildActivityDiagnosticsResponse };
2658
+ module.exports = { createSDKBridge, createMessageQueue, extractMcpDescriptors, readMemAvailableMB, readCgroupHeadroomMB, resolveMemAvailableThresholdMB, computeCgroupBlockCauseMessage, DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount, getActivityDivergenceStats, buildActivityDiagnosticsResponse };
2595
2659