@clagentic/console 1.10.0 → 1.11.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 (97) hide show
  1. package/README.md +14 -1
  2. package/bin/cli.js +38 -16
  3. package/lib/agents.js +1 -55
  4. package/lib/bash-auto-approve.js +133 -0
  5. package/lib/build-identity.js +23 -5
  6. package/lib/build-sha.json +2 -2
  7. package/lib/build-update-check.js +0 -62
  8. package/lib/build-update-offer.js +23 -13
  9. package/lib/build-update-restart.js +59 -43
  10. package/lib/cli/arg-validation.js +50 -0
  11. package/lib/cli/daemon-launch.js +5 -4
  12. package/lib/cli/menus.js +2 -2
  13. package/lib/cli/schedule-input-subcommands.js +327 -0
  14. package/lib/cli/session-subcommands.js +101 -17
  15. package/lib/client-build-id.js +56 -0
  16. package/lib/daemon.js +38 -6
  17. package/lib/identity/index.js +9 -4
  18. package/lib/injected-sender.js +225 -0
  19. package/lib/message-sender-record.js +133 -0
  20. package/lib/pending-prompts.js +55 -0
  21. package/lib/permission-mode-policy.js +63 -0
  22. package/lib/permission-settings.js +96 -0
  23. package/lib/permission-summary.js +67 -0
  24. package/lib/project-connection.js +10 -11
  25. package/lib/project-external-trigger.js +9 -1
  26. package/lib/project-loop.js +50 -23
  27. package/lib/project-permission-settings.js +59 -0
  28. package/lib/project-prompt-responses.js +25 -15
  29. package/lib/project-sessions.js +164 -60
  30. package/lib/project-user-message.js +18 -47
  31. package/lib/project.js +46 -74
  32. package/lib/public/app.js +4 -7
  33. package/lib/public/css/channel-layout.css +20 -0
  34. package/lib/public/css/diagnostics.css +7 -0
  35. package/lib/public/css/input.css +78 -0
  36. package/lib/public/css/menus.css +17 -0
  37. package/lib/public/css/overlays.css +0 -3
  38. package/lib/public/css/scheduler-modal.css +5 -0
  39. package/lib/public/index.html +44 -8
  40. package/lib/public/modules/app-connection.js +18 -1
  41. package/lib/public/modules/app-loop-ui.js +11 -1
  42. package/lib/public/modules/app-messages.js +23 -30
  43. package/lib/public/modules/app-panels.js +10 -3
  44. package/lib/public/modules/app-rate-limit.js +64 -88
  45. package/lib/public/modules/app-rendering.js +37 -6
  46. package/lib/public/modules/approve-tools-toggle.js +33 -0
  47. package/lib/public/modules/at-agents.js +8 -0
  48. package/lib/public/modules/build-guard.js +61 -0
  49. package/lib/public/modules/build-update-detail.js +1 -4
  50. package/lib/public/modules/diagnostics.js +98 -9
  51. package/lib/public/modules/injected-identity.js +78 -0
  52. package/lib/public/modules/injected-label.js +62 -0
  53. package/lib/public/modules/input.js +64 -114
  54. package/lib/public/modules/loop-hooks-warning.js +20 -0
  55. package/lib/public/modules/mode-options.js +35 -16
  56. package/lib/public/modules/permission-settings.js +56 -0
  57. package/lib/public/modules/project-settings.js +3 -0
  58. package/lib/public/modules/rate-limit-state.js +47 -22
  59. package/lib/public/modules/schedule-panel.js +234 -0
  60. package/lib/public/modules/schedule-time.js +193 -0
  61. package/lib/public/modules/scheduled-input-actions.js +19 -0
  62. package/lib/public/modules/scheduler-config.js +12 -0
  63. package/lib/public/modules/scheduler.js +8 -0
  64. package/lib/public/modules/server-settings.js +5 -9
  65. package/lib/public/modules/settings-defaults.js +18 -4
  66. package/lib/runtime-env.js +4 -0
  67. package/lib/scheduled-input/ipc.js +92 -0
  68. package/lib/scheduled-input/rate-limit-resume.js +53 -0
  69. package/lib/scheduled-input/records.js +350 -0
  70. package/lib/scheduled-input/service.js +743 -0
  71. package/lib/scheduled-input/store.js +132 -0
  72. package/lib/scheduled-input/ws.js +194 -0
  73. package/lib/scheduler.js +4 -0
  74. package/lib/sdk-bridge.js +194 -175
  75. package/lib/sdk-message-processor.js +13 -5
  76. package/lib/sdk-skill-discovery.js +17 -0
  77. package/lib/sender-ref.js +109 -0
  78. package/lib/server.js +37 -11
  79. package/lib/session-directory.js +224 -0
  80. package/lib/session-file-scan.js +55 -0
  81. package/lib/session-input-ipc.js +21 -0
  82. package/lib/session-input.js +396 -23
  83. package/lib/session-name-holder.js +82 -0
  84. package/lib/session-resume.js +3 -0
  85. package/lib/sessions.js +111 -2
  86. package/lib/turn-initiator.js +6 -2
  87. package/lib/updater.js +8 -2
  88. package/lib/ws-schema.js +20 -9
  89. package/lib/yoke/adapters/claude-worker.js +3 -1
  90. package/lib/yoke/adapters/claude.js +13 -17
  91. package/lib/yoke/adapters/codex.js +18 -5
  92. package/lib/yoke/adapters/permission-relay.js +9 -0
  93. package/lib/yoke/interface.js +7 -1
  94. package/package.json +1 -1
  95. package/scripts/check-test-count.js +1 -1
  96. package/scripts/install-local-test.js +45 -1
  97. package/scripts/postinstall.js +1 -0
package/lib/sdk-bridge.js CHANGED
@@ -4,10 +4,11 @@ var execSync = require("child_process").execSync;
4
4
  var execFileSync = require("child_process").execFileSync;
5
5
  var usersModule = require("./users");
6
6
  var { getCodexConfig } = require("./codex-defaults");
7
- var { splitShellSegments, attachSkillDiscovery, discoverSkillsWithMeta, mergeSkillsWithMeta } = require("./sdk-skill-discovery");
7
+ var { isAutoApprovableSegment } = require("./bash-auto-approve");
8
+ var { splitShellSegments, hasUnapprovableShellSyntax, attachSkillDiscovery, discoverSkillsWithMeta, mergeSkillsWithMeta } = require("./sdk-skill-discovery");
8
9
  var { createMessageQueue } = require("./sdk-message-queue");
9
10
  var { attachMessageProcessor } = require("./sdk-message-processor");
10
- var { readAgentToolsFromFile, parseFrontmatter, slugifyAgentName, AGENTS_SOURCE_DIR } = require("./agents");
11
+ var { parseFrontmatter, slugifyAgentName, AGENTS_SOURCE_DIR } = require("./agents");
11
12
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
12
13
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
13
14
  var { runPreflight } = require("./settings-preflight");
@@ -17,6 +18,7 @@ var sessionActivity = require("./session-activity");
17
18
  var sessionReclaim = require("./session-reclaim");
18
19
  var { withPromptLabel } = require("./prompt-label");
19
20
  var { isAgentDispatchTool } = require("./agent-dispatch-tool");
21
+ var permissionSummary = require("./permission-summary");
20
22
  var { getNewWorkRefusal } = require("./new-work-gate");
21
23
  var runtimeEnv = require("./runtime-env");
22
24
  var mcpToolSchema = require("./mcp-tool-schema");
@@ -26,6 +28,8 @@ var { buildVendorRegistryMessage, recordInstallState } = require("./vendor-regis
26
28
  var { authRequiredFacts } = require("./vendor-auth");
27
29
  var { bumpLastActivity } = require("./activity-clock");
28
30
  var { logField } = require("./log-field");
31
+ var { checkPermissionMode } = require("./permission-mode-policy");
32
+ var { reserveNameOnRevival } = require("./session-name-holder");
29
33
  var { createAiTitleRefresher } = require("./session-ai-title");
30
34
 
31
35
  // --- lr-29f9: Global concurrent-session ceiling ---
@@ -388,7 +392,6 @@ function createSDKBridge(opts) {
388
392
  var getNotificationsModule = opts.getNotificationsModule || function () { return null; };
389
393
  var adapter = opts.adapter;
390
394
  var adapters = opts.adapters || {};
391
- var dangerouslySkipPermissions = opts.dangerouslySkipPermissions || false;
392
395
  // Whether the daemon isolates users at the OS level. An agent that does not
393
396
  // support that (Codex) is disabled then: never created, never started.
394
397
  var osUsersMode = !!opts.osUsers;
@@ -401,6 +404,19 @@ function createSDKBridge(opts) {
401
404
  return _mcpServersSrc;
402
405
  }
403
406
  var getRemoteMcpServers = opts.getRemoteMcpServers || null;
407
+ // The server's permission settings, read at each decision so a change needs
408
+ // no restart. Absent means the defaults (nothing turned off).
409
+ function autoApproveReadOnlyOn() {
410
+ var settings = typeof opts.getPermissionSettings === "function" ? opts.getPermissionSettings() : null;
411
+ return !settings || settings.autoApproveReadOnly !== false;
412
+ }
413
+ // The mode a client is shown for a session: its own, else the project default
414
+ // (sessions.js effectiveSessionMode). A session manager without the helper
415
+ // (a test double) gets the same fallback inline.
416
+ function shownMode(session) {
417
+ if (typeof sm.effectiveSessionMode === "function") return sm.effectiveSessionMode(session);
418
+ return (session && session.permissionMode) || sm.currentPermissionMode || "default";
419
+ }
404
420
  var clayPort = opts.clayPort || 2633;
405
421
  var clayTls = opts.clayTls || false;
406
422
  var clayAuthToken = opts.clayAuthToken || null;
@@ -918,7 +934,12 @@ function createSDKBridge(opts) {
918
934
  // Check if a tool should be auto-approved based on whitelist rules.
919
935
  // Returns { behavior: "allow", updatedInput } if whitelisted, or null if not.
920
936
  // Shared by handleCanUseTool and mate mention canUseTool handlers.
921
- function checkToolWhitelist(toolName, input) {
937
+ function checkToolWhitelist(toolName, input, toolOpts) {
938
+ // The "Auto-approve read-only tools" setting. Off sends every item below
939
+ // (read-only built-ins, the safe Bash list, browser watch/unwatch, the MCP
940
+ // servers the person enabled) to the normal prompt.
941
+ if (!autoApproveReadOnlyOn()) return null;
942
+
922
943
  // Auto-approve read-only tools for ALL sessions.
923
944
  // These tools only inspect files and fetch data — no side effects.
924
945
  var readOnlyTools = { Read: true, Glob: true, Grep: true, WebFetch: true, WebSearch: true };
@@ -926,34 +947,34 @@ function createSDKBridge(opts) {
926
947
  return { behavior: "allow", updatedInput: input };
927
948
  }
928
949
 
929
- // Auto-approve safe browser MCP tools.
950
+ // MCP auto-approval keys on the SDK's report of which server serves the
951
+ // tool (toolOpts.mcpServer), never on the tool-name prefix: a configured
952
+ // server can be named anything, so a same-named tool from it would
953
+ // otherwise borrow the approval. Only source "sdk" (an in-process server
954
+ // this host registered) is trusted. No report (Codex approvals, older
955
+ // CLIs) means no auto-approval and the call falls through to the prompt.
956
+ var mcpSource = toolName.indexOf("mcp__") === 0 && toolOpts && toolOpts.mcpServer;
957
+ var trustedMcpName = mcpSource && mcpSource.source === "sdk" && typeof mcpSource.name === "string"
958
+ ? mcpSource.name : null;
959
+
960
+ // Auto-approve safe browser MCP tools, only from the console's own
961
+ // in-process browser server.
930
962
  // Only watch/unwatch: user explicitly chose which tab to share.
931
963
  // Everything else (screenshot, read_page, list_tabs, etc.) can expose
932
964
  // content from tabs the user didn't intend to share, so require approval.
933
965
  var safeBrowserTools = { browser_watch_tab: true, browser_unwatch_tab: true };
934
- if (toolName.indexOf("mcp__") === 0 && toolName.indexOf("__browser_") !== -1) {
935
- var mcpToolName = toolName.substring(toolName.lastIndexOf("__") + 2);
936
- if (safeBrowserTools[mcpToolName]) {
966
+ if (trustedMcpName === "clay-browser" && toolName.indexOf("mcp__clay-browser__") === 0) {
967
+ if (safeBrowserTools[toolName.substring("mcp__clay-browser__".length)]) {
937
968
  return { behavior: "allow", updatedInput: input };
938
969
  }
939
970
  }
940
971
 
941
- // Auto-approve Mate datastore tools. These are scoped to the active Mate
942
- // project and already enforce SQL policy server-side.
943
- if (toolName.indexOf("mcp__clay-datastore__") === 0) {
944
- return { behavior: "allow", updatedInput: input };
945
- }
946
-
947
972
  // Auto-approve remote MCP tools that the user explicitly enabled in project settings.
948
973
  // These are user-owned local MCP servers, so no additional permission prompt needed.
949
- if (toolName.indexOf("mcp__") === 0 && getRemoteMcpServers) {
974
+ if (trustedMcpName && toolName.indexOf("mcp__" + trustedMcpName + "__") === 0 && getRemoteMcpServers) {
950
975
  var _rmcp = getRemoteMcpServers();
951
- if (_rmcp) {
952
- var _mcpParts = toolName.split("__");
953
- var _mcpServerName = _mcpParts.length >= 2 ? _mcpParts[1] : "";
954
- if (_rmcp[_mcpServerName]) {
955
- return { behavior: "allow", updatedInput: input };
956
- }
976
+ if (_rmcp && Object.prototype.hasOwnProperty.call(_rmcp, trustedMcpName)) {
977
+ return { behavior: "allow", updatedInput: input };
957
978
  }
958
979
  }
959
980
 
@@ -975,81 +996,16 @@ function createSDKBridge(opts) {
975
996
  // fall through to the normal user permission prompt.
976
997
  if (toolName === "Bash" && input && input.command) {
977
998
  var cmd = input.command.trim();
978
- var safeBashCommands = {
979
- // Navigation (harmless on its own, checked in compound commands below)
980
- cd: true, pushd: true, popd: true,
981
- // File/dir inspection
982
- ls: true, cat: true, head: true, tail: true, wc: true, file: true,
983
- stat: true, tree: true, du: true, df: true,
984
- readlink: true, realpath: true, basename: true, dirname: true,
985
- // Search
986
- grep: true, rg: true, ag: true, ack: true, fgrep: true, egrep: true,
987
- // Lookup
988
- which: true, type: true, whereis: true, hash: true,
989
- // Environment/system info
990
- // lr-74c8 (BOBBIE follow-up): `env` and `command` are execution
991
- // primitives, not read-only inspection — `env rm -rf /` and
992
- // `command rm -rf /` launder an arbitrary tail command past a
993
- // first-word-only check with no argument validator. Removed
994
- // outright rather than gated: neither has a read-only-only form
995
- // worth trusting to a first-word check (contrast `printenv`,
996
- // which genuinely can only print).
997
- echo: true, printf: true, printenv: true, pwd: true,
998
- whoami: true, id: true, groups: true,
999
- date: true, uname: true, hostname: true, uptime: true, arch: true,
1000
- nproc: true, free: true, lsb_release: true, sw_vers: true,
1001
- locale: true, timedatectl: true,
1002
- // Text processing (pure stdin/stdout, no side effects)
1003
- jq: true, yq: true, sort: true, uniq: true, cut: true, tr: true,
1004
- paste: true, column: true, fold: true,
1005
- rev: true, tac: true, nl: true, expand: true, unexpand: true,
1006
- fmt: true, pr: true, csplit: true, comm: true, join: true,
1007
- // Comparison/hashing
1008
- diff: true, cmp: true, md5sum: true, sha256sum: true, sha1sum: true,
1009
- shasum: true, cksum: true, sum: true, b2sum: true, base64: true,
1010
- xxd: true, od: true, hexdump: true,
1011
- // Misc read-only
1012
- test: true, true: true, false: true, seq: true, yes: true,
1013
- sleep: true, time: true,
1014
- man: true, help: true, info: true, apropos: true,
1015
- cal: true, bc: true, expr: true, factor: true,
1016
- lsof: true, ps: true, top: true, htop: true, pgrep: true,
1017
- netstat: true, ss: true, ifconfig: true, ip: true, dig: true,
1018
- nslookup: true, host: true, ping: true, traceroute: true,
1019
- };
1020
- // Multi-purpose tools retained in the whitelist but restricted to a
1021
- // read-only subcommand/flag allowlist (lr-74c8). Each validator
1022
- // receives the segment's argv (excluding the command word itself)
1023
- // and returns true only for forms that cannot mutate state.
1024
- var validatedCommands = {
1025
- // Only the explicitly read-only git subcommands from the lr-74c8
1026
- // spec are allowed. Deliberately narrow: no `remote`, `tag`,
1027
- // `branch`, etc. — those have mutating forms (`branch -D`,
1028
- // `remote add`, `tag <name>`) that a subcommand-only check cannot
1029
- // safely distinguish from their read-only forms.
1030
- git: function (args) {
1031
- if (args.length === 0) return false;
1032
- var readOnlySubcommands = {
1033
- status: true, log: true, diff: true, show: true, "--version": true,
1034
- };
1035
- if (!readOnlySubcommands[args[0]]) return false;
1036
- // lr-74c8 (BOBBIE follow-up): the subcommand allowlist above only
1037
- // checked args[0] and ignored everything after it. `git show
1038
- // --output=<path>` / `git log --output=<path>` (and the `-o`
1039
- // short form) inherit diff/log's file-write flag, turning a
1040
- // "read-only" subcommand into an unprompted arbitrary file write.
1041
- // `-c <config>` can inject a pager/external-diff/exec config
1042
- // (core.pager, diff.external) that runs an arbitrary command;
1043
- // `--exec`, `--ext-diff`, `--textconv`, `-O`/`--output-indicator-*`
1044
- // extend the same file-write/exec surface. Any of these flags on
1045
- // an otherwise-allowed subcommand falls through to the prompt.
1046
- var dangerousFlagRe = /^(-o|--output(=.*)?|-O|--output-indicator.*|-c|--exec(=.*)?|--ext-diff|--textconv|--upload-pack(=.*)?|--receive-pack(=.*)?)$/;
1047
- for (var gi = 1; gi < args.length; gi++) {
1048
- if (dangerousFlagRe.test(args[gi])) return false;
1049
- }
1050
- return true;
1051
- },
1052
- };
999
+ // Redirection, newlines, a lone "&" and command substitution turn a
1000
+ // listed command into a write or a second command. Refuse them before
1001
+ // any splitting, quotes included; the call then reaches the prompt.
1002
+ if (hasUnapprovableShellSyntax(cmd)) return null;
1003
+ // Which commands are read-only, and which option tokens each accepts,
1004
+ // is declared in lib/bash-auto-approve.js. Commands that can write,
1005
+ // execute or hang (time, sort, uniq, csplit, xxd, yq, tree, ag/ack,
1006
+ // yes, ping, man, info, top, htop, timedatectl, tail, ss, file, sleep) are not
1007
+ // listed: a dropped entry only costs a prompt. `env` and `command` are
1008
+ // execution primitives and stay out for the same reason.
1053
1009
  // Split compound commands on operators (&&, ||, ;, |) while respecting
1054
1010
  // quoted strings and subshells so that e.g. grep -E "(a|b)" is not split
1055
1011
  var segments = splitShellSegments(cmd);
@@ -1074,13 +1030,12 @@ function createSDKBridge(opts) {
1074
1030
  allSafe = false;
1075
1031
  break;
1076
1032
  }
1077
- // Strip leading env assignments (FOO=bar cmd) only. A leading sudo
1078
- // is intentionally NOT stripped — `sudo <anything>` always falls
1079
- // through to the normal permission prompt (lr-74c8).
1080
- var segTokens = seg.replace(/^(?:\w+=\S*\s+)*/, "").split(/\s+/).filter(Boolean);
1033
+ // Nothing is stripped before the first-word check: a leading env
1034
+ // assignment is refused up front ("=" in hasUnapprovableShellSyntax)
1035
+ // and a leading sudo always falls through to the prompt (lr-74c8).
1036
+ var segTokens = seg.split(/\s+/).filter(Boolean);
1081
1037
  var firstWord = segTokens[0];
1082
- if (safeBashCommands[firstWord]) continue;
1083
- if (validatedCommands[firstWord] && validatedCommands[firstWord](segTokens.slice(1))) continue;
1038
+ if (isAutoApprovableSegment(segTokens)) continue;
1084
1039
  allSafe = false;
1085
1040
  break;
1086
1041
  }
@@ -1092,6 +1047,25 @@ function createSDKBridge(opts) {
1092
1047
  return null; // Not whitelisted
1093
1048
  }
1094
1049
 
1050
+ // Whether a mode may be applied to this session, by the shared policy
1051
+ // (lib/permission-mode-policy.js). checkVendor adds the session's vendor
1052
+ // capability list to the check. A refusal is logged.
1053
+ function checkModeFor(session, mode, checkVendor) {
1054
+ var vendor = sessionCapabilities.effectiveVendorId(sm, session, adapter && adapter.vendor);
1055
+ return checkPermissionMode(mode, {
1056
+ supportedModes: checkVendor ? sessionCapabilities.capabilitiesFor(sm, vendor).permissionModes : null,
1057
+ });
1058
+ }
1059
+
1060
+ // checkModeFor, with a refusal logged under `what`; true when the mode is allowed.
1061
+ function modeAllowed(session, mode, what, checkVendor) {
1062
+ var verdict = checkModeFor(session, mode, checkVendor);
1063
+ if (!verdict.ok) {
1064
+ console.warn("[sdk-bridge] refused " + what + " " + logField(mode) + " in " + slug + ": " + verdict.error);
1065
+ }
1066
+ return verdict.ok;
1067
+ }
1068
+
1095
1069
  function handleCanUseTool(session, toolName, input, opts) {
1096
1070
  opts = opts || {};
1097
1071
  // An ask the user's own ask rule forced is a human prompt by the user's
@@ -1102,7 +1076,10 @@ function createSDKBridge(opts) {
1102
1076
 
1103
1077
  // Full-auto mode: auto-approve everything except AskUserQuestion
1104
1078
  // (which still needs to go through the user interaction flow).
1105
- if (!ruleForced && sm.currentPermissionMode === "bypassPermissions" && toolName !== "AskUserQuestion") {
1079
+ // The mode is this session's own (falling back to the project default only
1080
+ // where the session has none, as at query start), never another session's.
1081
+ var sessionMode = session.permissionMode || sm.currentPermissionMode;
1082
+ if (!ruleForced && sessionMode === "bypassPermissions" && toolName !== "AskUserQuestion") {
1106
1083
  return Promise.resolve({ behavior: "allow", updatedInput: input });
1107
1084
  }
1108
1085
 
@@ -1115,11 +1092,16 @@ function createSDKBridge(opts) {
1115
1092
  if (toolName === "EnterPlanMode") {
1116
1093
  return Promise.resolve({ behavior: "deny", message: "Do not enter plan mode. Execute directly." });
1117
1094
  }
1118
- return Promise.resolve({ behavior: "allow", updatedInput: input });
1095
+ // The loop's "Approve tools automatically" setting. A record that never
1096
+ // carried it approves, as every loop did before it existed. Off sends the
1097
+ // call down the normal path below (read-only list, then a prompt).
1098
+ if (session.loop.approveTools !== false) {
1099
+ return Promise.resolve({ behavior: "allow", updatedInput: input });
1100
+ }
1119
1101
  }
1120
1102
 
1121
1103
  // Check shared whitelist (read-only tools, safe browser tools, safe bash commands)
1122
- var whitelisted = ruleForced ? null : checkToolWhitelist(toolName, input);
1104
+ var whitelisted = ruleForced ? null : checkToolWhitelist(toolName, input, opts);
1123
1105
  if (whitelisted) {
1124
1106
  return Promise.resolve(whitelisted);
1125
1107
  }
@@ -1306,15 +1288,27 @@ function createSDKBridge(opts) {
1306
1288
  // reply (project-sessions.js's set_model/switch_session).
1307
1289
  session.model = metaData.model;
1308
1290
  sendModelInfoToSession(session, session.vendor || (adapter && adapter.vendor) || "claude", metaData.model);
1309
- sendToSession(session, { type: "config_state", model: metaData.model, mode: sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [] });
1291
+ sendToSession(session, { type: "config_state", model: metaData.model, mode: shownMode(session), effort: sm.currentEffort || "medium", betas: sm.currentBetas || [] });
1310
1292
  break;
1311
1293
  case "effort_changed":
1312
1294
  sm.currentEffort = metaData.effort;
1313
- send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort, betas: sm.currentBetas || [] });
1295
+ // A broadcast about the effort carries no mode: the project's
1296
+ // default is not any viewer's session mode, and a push without a
1297
+ // mode leaves every chip as it is.
1298
+ send({ type: "config_state", model: sm.currentModel || "", effort: sm.currentEffort, betas: sm.currentBetas || [] });
1314
1299
  break;
1315
1300
  case "permission_mode_changed":
1316
- sm.currentPermissionMode = metaData.mode;
1317
- send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode, effort: sm.currentEffort || "medium", betas: sm.currentBetas || [] });
1301
+ // One session's worker changed its own mode (plan entered or
1302
+ // left, say). That is this session's mode and no one else's:
1303
+ // writing it to sm.currentPermissionMode made it the
1304
+ // project-wide mode every other session starts from.
1305
+ // The worker is not a trusted source: the mode passes the same
1306
+ // check as any other entry point, and a refused one leaves the
1307
+ // session on its previous mode.
1308
+ if (!modeAllowed(session, metaData.mode, "worker permission mode", true)) break;
1309
+ session.permissionMode = metaData.mode;
1310
+ sm.saveSessionFile(session);
1311
+ sendToSession(session, { type: "config_state", model: session.model || sm.currentModel || "", mode: metaData.mode, effort: sm.currentEffort || "medium", betas: sm.currentBetas || [] });
1318
1312
  break;
1319
1313
  case "worker_error":
1320
1314
  send({ type: "error", text: metaData.error });
@@ -1541,9 +1535,9 @@ function createSDKBridge(opts) {
1541
1535
  session.rateLimitResetsAt = null;
1542
1536
  session.rateLimitAutoContinuePending = true;
1543
1537
  didScheduleAutoContinue = true;
1544
- console.log("[sdk-bridge] Rate limited, scheduling auto-continue via scheduleMessage for session " + session.localId);
1545
- if (typeof opts.scheduleMessage === "function") {
1546
- opts.scheduleMessage(session, "continue", acResetsAt);
1538
+ console.log("[sdk-bridge] Rate limited, scheduling the rate-limit resume for session " + session.localId);
1539
+ if (typeof opts.scheduleRateLimitResume === "function") {
1540
+ opts.scheduleRateLimitResume(session, acResetsAt);
1547
1541
  }
1548
1542
  } else if (acEnabled && !session.destroying) {
1549
1543
  // Log why auto-continue was not scheduled (for debugging)
@@ -1669,8 +1663,32 @@ function createSDKBridge(opts) {
1669
1663
 
1670
1664
  // `initiator` (turn-initiator.js INITIATORS) is who started this turn. It is
1671
1665
  // per turn: it stamps the first message and says nothing about later turns
1672
- // of the session or about the process's environment.
1673
- async function startQuery(session, text, images, linuxUser, initiator) {
1666
+ // of the session or about the process's environment. `messageId` is the id
1667
+ // the message's history entry carries (injected-sender.js stampRecord); it is
1668
+ // sent to the vendor with the message so the vendor transcript and the
1669
+ // published sender record name the same message.
1670
+ // `leadMessages` ([{ text, initiator, messageId }]) are further user messages
1671
+ // of their own, sent before the first one: a message the operator typed while
1672
+ // a loop iteration was running reaches the vendor as itself, with its own
1673
+ // initiator and id, never inside the message the loop composed.
1674
+ async function startQuery(session, text, images, linuxUser, initiator, messageId, leadMessages) {
1675
+ // Every path that gives a reaped session a runtime again (send-input, the
1676
+ // browser, a loop or scheduled turn) comes through here, so the name rule
1677
+ // for a session coming back to life is enforced once. The name is reserved
1678
+ // synchronously, before the first await, and released when the start ends.
1679
+ var reservation = sm.sessions ? reserveNameOnRevival(sm.sessions, session) : null;
1680
+ if (reservation && reservation.holder) {
1681
+ if (typeof sm.saveSessionFile === "function") sm.saveSessionFile(session);
1682
+ if (typeof sm.broadcastSessionList === "function") sm.broadcastSessionList();
1683
+ }
1684
+ try {
1685
+ return await startQueryRuntime(session, text, images, linuxUser, initiator, messageId, leadMessages);
1686
+ } finally {
1687
+ if (reservation) reservation.release();
1688
+ }
1689
+ }
1690
+
1691
+ async function startQueryRuntime(session, text, images, linuxUser, initiator, messageId, leadMessages) {
1674
1692
  async function ensureVendorReady(vendor) {
1675
1693
  if (!vendor) return null;
1676
1694
  // What the adapter's live session advertises narrows its declaration; the
@@ -1689,7 +1707,6 @@ function createSDKBridge(opts) {
1689
1707
  vendorAdapter = await yoke.lazyCreateAdapter(adapters, vendor, withRuntimeEnv({
1690
1708
  cwd: cwd,
1691
1709
  osUsers: osUsersMode,
1692
- dangerouslySkipPermissions: dangerouslySkipPermissions,
1693
1710
  linuxUser: linuxUser || undefined,
1694
1711
  clayPort: clayPort,
1695
1712
  clayTls: clayTls,
@@ -1699,7 +1716,6 @@ function createSDKBridge(opts) {
1699
1716
  } else if ((!sm.modelsByVendor || !sm.modelsByVendor[vendor]) && typeof vendorAdapter.init === "function") {
1700
1717
  recordInit(await vendorAdapter.init(withRuntimeEnv({
1701
1718
  cwd: cwd,
1702
- dangerouslySkipPermissions: dangerouslySkipPermissions,
1703
1719
  linuxUser: linuxUser || undefined,
1704
1720
  clayPort: clayPort,
1705
1721
  clayTls: clayTls,
@@ -2023,11 +2039,6 @@ function createSDKBridge(opts) {
2023
2039
  // belt-and-suspenders for sessions that carry agentName from a prior
2024
2040
  // vendor switch or a direct ws message.
2025
2041
  //
2026
- // lr-4c90 — belt-and-suspenders tool enforcement: the SDK's `agent` option
2027
- // should apply tool restrictions, but only does so when the agent file uses
2028
- // JSON array syntax for the tools field. We read the tools list directly
2029
- // from disk and set claudeOpts.tools explicitly so restriction is enforced
2030
- // even if the SDK's parsing path has any quirks.
2031
2042
  // lr-5bd7 — declared outside the agent block so the model override can be
2032
2043
  // applied when queryModel is computed below (after loop-settings resolution).
2033
2044
  var _agentDeclaredModel = null;
@@ -2043,18 +2054,12 @@ function createSDKBridge(opts) {
2043
2054
  var effectiveHome = resolveEffectiveHome(linuxUser);
2044
2055
  var effectiveAgentsDir = effectiveHome ? path.join(effectiveHome, ".claude", "agents") : AGENTS_SOURCE_DIR;
2045
2056
 
2046
- var agentTools = readAgentToolsFromFile(session.agentName, effectiveAgentsDir);
2047
- if (agentTools) {
2048
- claudeOpts.tools = agentTools;
2049
- console.log("[sdk-bridge] agent tools enforced for " + session.agentName + ": " + agentTools.join(", "));
2050
- }
2051
-
2052
2057
  // lr-5bd7 — inject AGENT.md body as systemPrompt on the main thread.
2053
2058
  // The `agents` map approach (PR #264) only applies to subagent invocations
2054
2059
  // via the Agent tool; it does not deliver the body to the main conversation.
2055
2060
  // Setting claudeOpts.systemPrompt bypasses settingSources/agents-map resolution
2056
2061
  // and ensures the model receives the agent persona directly.
2057
- // We keep claudeOpts.agent set — it still applies tool restrictions via settingSources.
2062
+ // We keep claudeOpts.agent set; the console passes no tool list of its own.
2058
2063
  var agentSlug = slugifyAgentName(session.agentName);
2059
2064
  var agentFilePath = path.join(effectiveAgentsDir, agentSlug + ".md");
2060
2065
  var agentRaw;
@@ -2094,7 +2099,10 @@ function createSDKBridge(opts) {
2094
2099
  if (budgetTokens) claudeOpts.thinking = { type: "enabled", budgetTokens: budgetTokens };
2095
2100
  }
2096
2101
 
2097
- if (ls.permissionMode) {
2102
+ // A loop's mode (LOOP.json is a file, not a trusted client) passes the same
2103
+ // check as a mode a client asks for; a refused one is ignored and the
2104
+ // session's own mode applies.
2105
+ if (ls.permissionMode && modeAllowed(session, ls.permissionMode, "loop permissionMode", true)) {
2098
2106
  session._loopPermissionMode = ls.permissionMode;
2099
2107
  }
2100
2108
 
@@ -2103,22 +2111,32 @@ function createSDKBridge(opts) {
2103
2111
  claudeOpts.settings = Object.assign({}, claudeOpts.settings || {}, { disableAllHooks: ls.disableAllHooks });
2104
2112
  }
2105
2113
 
2106
- if (dangerouslySkipPermissions) {
2107
- claudeOpts.allowDangerouslySkipPermissions = true;
2108
- claudeOpts.permissionMode = "bypassPermissions";
2109
- } else {
2110
- var globalMode = session.permissionMode || sm.currentPermissionMode || "default";
2111
- var effectiveDefault;
2112
- if (globalMode === "bypassPermissions") effectiveDefault = "bypassPermissions";
2113
- else if (session.acceptEditsAfterStart) effectiveDefault = "acceptEdits";
2114
- else effectiveDefault = globalMode;
2115
- var modeToApply = session._loopPermissionMode || effectiveDefault;
2116
- if (modeToApply && modeToApply !== "default") {
2117
- claudeOpts.permissionMode = modeToApply;
2114
+ var globalMode = session.permissionMode || sm.currentPermissionMode || "default";
2115
+ // A stored mode (session file, saved default) is checked again here: a
2116
+ // bypassPermissions written by an older build or by hand must not start
2117
+ // a query while the server does not allow it.
2118
+ // The vendor is known here, so a mode the session's vendor lacks (auto
2119
+ // after a switch to a vendor without it) falls back too.
2120
+ if (!modeAllowed(session, globalMode, "stored permission mode", true)) {
2121
+ globalMode = "default";
2122
+ // The session's own mode too, so the bypass branch of canUseTool
2123
+ // (which reads it) agrees with what this query starts with.
2124
+ if (session.permissionMode) {
2125
+ session.permissionMode = "default";
2126
+ // The saved value too, or the next load reads the refused mode back.
2127
+ sm.saveSessionFile(session);
2118
2128
  }
2119
2129
  }
2120
- // Clear one-shot acceptEditsAfterStart regardless of which branch ran above,
2121
- // so the flag does not linger into subsequent turns.
2130
+ var effectiveDefault;
2131
+ if (globalMode === "bypassPermissions") effectiveDefault = "bypassPermissions";
2132
+ else if (session.acceptEditsAfterStart) effectiveDefault = "acceptEdits";
2133
+ else effectiveDefault = globalMode;
2134
+ var modeToApply = session._loopPermissionMode || effectiveDefault;
2135
+ if (modeToApply && modeToApply !== "default") {
2136
+ claudeOpts.permissionMode = modeToApply;
2137
+ }
2138
+ // Clear one-shot acceptEditsAfterStart so the flag does not linger into
2139
+ // subsequent turns.
2122
2140
  if (session.acceptEditsAfterStart) delete session.acceptEditsAfterStart;
2123
2141
  if (session.cliSessionId && session.lastRewindUuid) {
2124
2142
  claudeOpts.resumeSessionAt = session.lastRewindUuid;
@@ -2219,6 +2237,13 @@ function createSDKBridge(opts) {
2219
2237
  // The variables Settings add to this runtime's environment, as of now.
2220
2238
  withRuntimeEnv(queryOpts, session);
2221
2239
 
2240
+ // The console's own reference to this session, in the process environment
2241
+ // whatever identity provider is configured (lib/sender-ref.js). Claude only:
2242
+ // one Codex app-server serves many threads, so it cannot carry a per-thread one.
2243
+ if (sessionAdapter.vendor === "claude" && slug) {
2244
+ queryOpts.sessionRef = { project: slug, sessionId: session.localId };
2245
+ }
2246
+
2222
2247
  // The identity of this agent process, when a provider is configured. Its
2223
2248
  // directory is delivered in the process's environment and removed when the
2224
2249
  // query ends (processQueryStream) or fails to start (below).
@@ -2280,7 +2305,13 @@ function createSDKBridge(opts) {
2280
2305
 
2281
2306
  // Push initial user message through the QueryHandle
2282
2307
  console.log("[sdk-bridge] pushing initial message via handle.pushMessage...");
2283
- handle.pushMessage(text, images, initiator);
2308
+ if (Array.isArray(leadMessages)) {
2309
+ for (var li = 0; li < leadMessages.length; li++) {
2310
+ var lead = leadMessages[li];
2311
+ handle.pushMessage(lead.text, undefined, lead.initiator, lead.messageId);
2312
+ }
2313
+ }
2314
+ handle.pushMessage(text, images, initiator, messageId);
2284
2315
 
2285
2316
  // lr-b61b: Flush any messages that arrived between turns (after the previous
2286
2317
  // finally block nulled queryInstance and before this startQuery call).
@@ -2288,7 +2319,7 @@ function createSDKBridge(opts) {
2288
2319
  console.log("[sdk-bridge] startQuery: flushing " + session.pendingMessages.length + " buffered pending message(s) for project " + slug + " session " + session.localId);
2289
2320
  for (var pi = 0; pi < session.pendingMessages.length; pi++) {
2290
2321
  var pm = session.pendingMessages[pi];
2291
- handle.pushMessage(pm.text, pm.images, pm.initiator);
2322
+ handle.pushMessage(pm.text, pm.images, pm.initiator, pm.messageId);
2292
2323
  }
2293
2324
  session.pendingMessages = [];
2294
2325
  }
@@ -2327,11 +2358,11 @@ function createSDKBridge(opts) {
2327
2358
  }
2328
2359
  }
2329
2360
 
2330
- function pushMessage(session, text, images, initiator) {
2361
+ function pushMessage(session, text, images, initiator, messageId) {
2331
2362
  bumpLastActivity(session, "push-message", slug);
2332
2363
  // Route through QueryHandle (works for both in-process and worker paths)
2333
2364
  if (session.queryInstance && typeof session.queryInstance.pushMessage === "function") {
2334
- session.queryInstance.pushMessage(text, images, initiator);
2365
+ session.queryInstance.pushMessage(text, images, initiator, messageId);
2335
2366
  } else {
2336
2367
  // lr-b61b: queryInstance is null between turns (finally block has run but
2337
2368
  // startQuery has not been called yet). Buffer the message so it is not
@@ -2347,7 +2378,7 @@ function createSDKBridge(opts) {
2347
2378
  // so any candidate cause that lands a message here is visible.
2348
2379
  var wasFull = session.pendingMessages.length >= MAX_PENDING_MESSAGES;
2349
2380
  if (wasFull) session.pendingMessages.shift();
2350
- session.pendingMessages.push({ text: text, images: images, initiator: initiator });
2381
+ session.pendingMessages.push({ text: text, images: images, initiator: initiator, messageId: messageId });
2351
2382
  console.log("[sdk-bridge] pushMessage: queryInstance null, buffered message for session " + session.localId + " (pending=" + session.pendingMessages.length + ")");
2352
2383
  sendAndRecord(session, {
2353
2384
  type: "diagnostic",
@@ -2378,29 +2409,7 @@ function createSDKBridge(opts) {
2378
2409
  }
2379
2410
 
2380
2411
  function permissionPushBody(toolName, input) {
2381
- if (!input) return "";
2382
- var text = "";
2383
- if (toolName === "Bash" && input.command) {
2384
- text = input.command;
2385
- } else if (toolName === "Edit" && input.file_path) {
2386
- text = input.file_path.split(/[/\\]/).pop() + ": " + (input.old_string || "").substring(0, 40) + " \u2192 " + (input.new_string || "").substring(0, 40);
2387
- } else if (toolName === "Write" && input.file_path) {
2388
- text = input.file_path;
2389
- } else if (input.file_path) {
2390
- text = input.file_path;
2391
- } else if (input.command) {
2392
- text = input.command;
2393
- } else if (input.url) {
2394
- text = input.url;
2395
- } else if (input.query) {
2396
- text = input.query;
2397
- } else if (input.pattern) {
2398
- text = input.pattern;
2399
- } else if (input.description) {
2400
- text = input.description;
2401
- }
2402
- if (text.length > 120) text = text.substring(0, 120) + "...";
2403
- return text;
2412
+ return permissionSummary.pushBody(toolName, input);
2404
2413
  }
2405
2414
 
2406
2415
  // Detect which vendor binaries are installed for an OS identity and record
@@ -2442,7 +2451,6 @@ function createSDKBridge(opts) {
2442
2451
  try {
2443
2452
  var result = await adapter.init(withRuntimeEnv({
2444
2453
  cwd: cwd,
2445
- dangerouslySkipPermissions: dangerouslySkipPermissions,
2446
2454
  linuxUser: linuxUser || undefined,
2447
2455
  clayPort: clayPort,
2448
2456
  clayTls: clayTls,
@@ -2579,7 +2587,7 @@ function createSDKBridge(opts) {
2579
2587
  async function setEffort(session, effort) {
2580
2588
  if (!session.queryInstance) {
2581
2589
  sm.currentEffort = effort;
2582
- send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort, betas: sm.currentBetas || [] });
2590
+ send({ type: "config_state", model: sm.currentModel || "", effort: sm.currentEffort, betas: sm.currentBetas || [] });
2583
2591
  return { ok: true };
2584
2592
  }
2585
2593
  try {
@@ -2591,24 +2599,34 @@ function createSDKBridge(opts) {
2591
2599
  return { ok: false, error: errMsg };
2592
2600
  }
2593
2601
  sm.currentEffort = effort;
2594
- send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort, betas: sm.currentBetas || [] });
2602
+ send({ type: "config_state", model: sm.currentModel || "", effort: sm.currentEffort, betas: sm.currentBetas || [] });
2595
2603
  return { ok: true };
2596
2604
  }
2597
2605
 
2606
+ // Returns true when the session now has the mode (and it is saved, so a
2607
+ // resume or restart keeps it), false when it was refused or the running query
2608
+ // would not take it.
2598
2609
  async function setPermissionMode(session, mode) {
2610
+ // The handlers check first; this keeps any other caller (a prompt answer,
2611
+ // a loop) from handing the session a mode the server does not allow.
2612
+ if (!modeAllowed(session, mode, "setPermissionMode", true)) return false;
2599
2613
  if (!session.queryInstance) {
2600
2614
  // No active query — store on session only (not sm — that's for project defaults).
2601
2615
  // config_state sent targeted by caller (project-sessions.js).
2602
2616
  session.permissionMode = mode;
2603
- return;
2617
+ sm.saveSessionFile(session);
2618
+ return true;
2604
2619
  }
2605
2620
  try {
2606
2621
  // Route through QueryHandle (works for both in-process and worker paths)
2607
2622
  await session.queryInstance.setPermissionMode(mode);
2608
2623
  session.permissionMode = mode;
2624
+ sm.saveSessionFile(session);
2609
2625
  // config_state sent targeted by caller — no broadcast here.
2626
+ return true;
2610
2627
  } catch (e) {
2611
2628
  send({ type: "error", text: "Failed to set permission mode: " + (e.message || e) });
2629
+ return false;
2612
2630
  }
2613
2631
  }
2614
2632
 
@@ -2666,6 +2684,7 @@ function createSDKBridge(opts) {
2666
2684
  setModel: setModel,
2667
2685
  setEffort: setEffort,
2668
2686
  setPermissionMode: setPermissionMode,
2687
+ checkModeFor: checkModeFor,
2669
2688
  isClaudeProcess: isClaudeProcess,
2670
2689
  permissionPushTitle: permissionPushTitle,
2671
2690
  permissionPushBody: permissionPushBody,