@clagentic/console 1.10.0 → 1.11.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +14 -0
  2. package/bin/cli.js +15 -3
  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/schedule-input-subcommands.js +327 -0
  11. package/lib/cli/session-subcommands.js +100 -17
  12. package/lib/client-build-id.js +56 -0
  13. package/lib/daemon.js +20 -5
  14. package/lib/injected-sender.js +225 -0
  15. package/lib/message-sender-record.js +133 -0
  16. package/lib/pending-prompts.js +55 -0
  17. package/lib/permission-mode-policy.js +63 -0
  18. package/lib/permission-summary.js +67 -0
  19. package/lib/project-connection.js +2 -1
  20. package/lib/project-external-trigger.js +9 -1
  21. package/lib/project-loop.js +26 -20
  22. package/lib/project-prompt-responses.js +20 -14
  23. package/lib/project-sessions.js +73 -21
  24. package/lib/project-user-message.js +18 -47
  25. package/lib/project.js +36 -62
  26. package/lib/public/app.js +3 -5
  27. package/lib/public/css/channel-layout.css +20 -0
  28. package/lib/public/css/diagnostics.css +7 -0
  29. package/lib/public/css/input.css +78 -0
  30. package/lib/public/css/menus.css +17 -0
  31. package/lib/public/modules/app-connection.js +18 -1
  32. package/lib/public/modules/app-messages.js +19 -17
  33. package/lib/public/modules/app-panels.js +9 -2
  34. package/lib/public/modules/app-rate-limit.js +63 -87
  35. package/lib/public/modules/app-rendering.js +37 -6
  36. package/lib/public/modules/at-agents.js +8 -0
  37. package/lib/public/modules/build-guard.js +61 -0
  38. package/lib/public/modules/build-update-detail.js +1 -4
  39. package/lib/public/modules/diagnostics.js +98 -9
  40. package/lib/public/modules/injected-identity.js +78 -0
  41. package/lib/public/modules/injected-label.js +62 -0
  42. package/lib/public/modules/input.js +64 -114
  43. package/lib/public/modules/mode-options.js +19 -16
  44. package/lib/public/modules/rate-limit-state.js +47 -22
  45. package/lib/public/modules/schedule-panel.js +234 -0
  46. package/lib/public/modules/schedule-time.js +193 -0
  47. package/lib/public/modules/scheduled-input-actions.js +19 -0
  48. package/lib/runtime-env.js +4 -0
  49. package/lib/scheduled-input/ipc.js +92 -0
  50. package/lib/scheduled-input/rate-limit-resume.js +53 -0
  51. package/lib/scheduled-input/records.js +350 -0
  52. package/lib/scheduled-input/service.js +743 -0
  53. package/lib/scheduled-input/store.js +132 -0
  54. package/lib/scheduled-input/ws.js +194 -0
  55. package/lib/sdk-bridge.js +137 -152
  56. package/lib/sdk-message-processor.js +13 -5
  57. package/lib/sdk-skill-discovery.js +17 -0
  58. package/lib/sender-ref.js +109 -0
  59. package/lib/server.js +28 -8
  60. package/lib/session-directory.js +224 -0
  61. package/lib/session-file-scan.js +55 -0
  62. package/lib/session-input-ipc.js +20 -0
  63. package/lib/session-input.js +355 -19
  64. package/lib/session-name-holder.js +82 -0
  65. package/lib/session-resume.js +1 -0
  66. package/lib/sessions.js +44 -0
  67. package/lib/turn-initiator.js +6 -2
  68. package/lib/ws-schema.js +15 -7
  69. package/lib/yoke/adapters/claude-worker.js +3 -1
  70. package/lib/yoke/adapters/claude.js +13 -7
  71. package/lib/yoke/adapters/codex.js +18 -5
  72. package/lib/yoke/adapters/permission-relay.js +9 -0
  73. package/lib/yoke/interface.js +7 -1
  74. package/package.json +1 -1
  75. package/scripts/check-test-count.js +1 -1
  76. package/scripts/install-local-test.js +45 -1
  77. 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 ---
@@ -918,7 +922,7 @@ function createSDKBridge(opts) {
918
922
  // Check if a tool should be auto-approved based on whitelist rules.
919
923
  // Returns { behavior: "allow", updatedInput } if whitelisted, or null if not.
920
924
  // Shared by handleCanUseTool and mate mention canUseTool handlers.
921
- function checkToolWhitelist(toolName, input) {
925
+ function checkToolWhitelist(toolName, input, toolOpts) {
922
926
  // Auto-approve read-only tools for ALL sessions.
923
927
  // These tools only inspect files and fetch data — no side effects.
924
928
  var readOnlyTools = { Read: true, Glob: true, Grep: true, WebFetch: true, WebSearch: true };
@@ -926,34 +930,34 @@ function createSDKBridge(opts) {
926
930
  return { behavior: "allow", updatedInput: input };
927
931
  }
928
932
 
929
- // Auto-approve safe browser MCP tools.
933
+ // MCP auto-approval keys on the SDK's report of which server serves the
934
+ // tool (toolOpts.mcpServer), never on the tool-name prefix: a configured
935
+ // server can be named anything, so a same-named tool from it would
936
+ // otherwise borrow the approval. Only source "sdk" (an in-process server
937
+ // this host registered) is trusted. No report (Codex approvals, older
938
+ // CLIs) means no auto-approval and the call falls through to the prompt.
939
+ var mcpSource = toolName.indexOf("mcp__") === 0 && toolOpts && toolOpts.mcpServer;
940
+ var trustedMcpName = mcpSource && mcpSource.source === "sdk" && typeof mcpSource.name === "string"
941
+ ? mcpSource.name : null;
942
+
943
+ // Auto-approve safe browser MCP tools, only from the console's own
944
+ // in-process browser server.
930
945
  // Only watch/unwatch: user explicitly chose which tab to share.
931
946
  // Everything else (screenshot, read_page, list_tabs, etc.) can expose
932
947
  // content from tabs the user didn't intend to share, so require approval.
933
948
  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]) {
949
+ if (trustedMcpName === "clay-browser" && toolName.indexOf("mcp__clay-browser__") === 0) {
950
+ if (safeBrowserTools[toolName.substring("mcp__clay-browser__".length)]) {
937
951
  return { behavior: "allow", updatedInput: input };
938
952
  }
939
953
  }
940
954
 
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
955
  // Auto-approve remote MCP tools that the user explicitly enabled in project settings.
948
956
  // These are user-owned local MCP servers, so no additional permission prompt needed.
949
- if (toolName.indexOf("mcp__") === 0 && getRemoteMcpServers) {
957
+ if (trustedMcpName && toolName.indexOf("mcp__" + trustedMcpName + "__") === 0 && getRemoteMcpServers) {
950
958
  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
- }
959
+ if (_rmcp && Object.prototype.hasOwnProperty.call(_rmcp, trustedMcpName)) {
960
+ return { behavior: "allow", updatedInput: input };
957
961
  }
958
962
  }
959
963
 
@@ -975,81 +979,16 @@ function createSDKBridge(opts) {
975
979
  // fall through to the normal user permission prompt.
976
980
  if (toolName === "Bash" && input && input.command) {
977
981
  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
- };
982
+ // Redirection, newlines, a lone "&" and command substitution turn a
983
+ // listed command into a write or a second command. Refuse them before
984
+ // any splitting, quotes included; the call then reaches the prompt.
985
+ if (hasUnapprovableShellSyntax(cmd)) return null;
986
+ // Which commands are read-only, and which option tokens each accepts,
987
+ // is declared in lib/bash-auto-approve.js. Commands that can write,
988
+ // execute or hang (time, sort, uniq, csplit, xxd, yq, tree, ag/ack,
989
+ // yes, ping, man, info, top, htop, timedatectl, tail, ss, file) are not
990
+ // listed: a dropped entry only costs a prompt. `env` and `command` are
991
+ // execution primitives and stay out for the same reason.
1053
992
  // Split compound commands on operators (&&, ||, ;, |) while respecting
1054
993
  // quoted strings and subshells so that e.g. grep -E "(a|b)" is not split
1055
994
  var segments = splitShellSegments(cmd);
@@ -1074,13 +1013,12 @@ function createSDKBridge(opts) {
1074
1013
  allSafe = false;
1075
1014
  break;
1076
1015
  }
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);
1016
+ // Nothing is stripped before the first-word check: a leading env
1017
+ // assignment is refused up front ("=" in hasUnapprovableShellSyntax)
1018
+ // and a leading sudo always falls through to the prompt (lr-74c8).
1019
+ var segTokens = seg.split(/\s+/).filter(Boolean);
1081
1020
  var firstWord = segTokens[0];
1082
- if (safeBashCommands[firstWord]) continue;
1083
- if (validatedCommands[firstWord] && validatedCommands[firstWord](segTokens.slice(1))) continue;
1021
+ if (isAutoApprovableSegment(segTokens)) continue;
1084
1022
  allSafe = false;
1085
1023
  break;
1086
1024
  }
@@ -1092,6 +1030,21 @@ function createSDKBridge(opts) {
1092
1030
  return null; // Not whitelisted
1093
1031
  }
1094
1032
 
1033
+ // Whether a mode may be applied to this session, by the shared policy
1034
+ // (lib/permission-mode-policy.js). checkVendor adds the session's vendor
1035
+ // capability list to the check. A refusal is logged.
1036
+ function modeAllowed(session, mode, what, checkVendor) {
1037
+ var vendor = sessionCapabilities.effectiveVendorId(sm, session, adapter && adapter.vendor);
1038
+ var verdict = checkPermissionMode(mode, {
1039
+ skipPermissionsAllowed: dangerouslySkipPermissions === true,
1040
+ supportedModes: checkVendor ? sessionCapabilities.capabilitiesFor(sm, vendor).permissionModes : null,
1041
+ });
1042
+ if (!verdict.ok) {
1043
+ console.warn("[sdk-bridge] refused " + what + " " + logField(mode) + " in " + slug + ": " + verdict.error);
1044
+ }
1045
+ return verdict.ok;
1046
+ }
1047
+
1095
1048
  function handleCanUseTool(session, toolName, input, opts) {
1096
1049
  opts = opts || {};
1097
1050
  // An ask the user's own ask rule forced is a human prompt by the user's
@@ -1102,7 +1055,10 @@ function createSDKBridge(opts) {
1102
1055
 
1103
1056
  // Full-auto mode: auto-approve everything except AskUserQuestion
1104
1057
  // (which still needs to go through the user interaction flow).
1105
- if (!ruleForced && sm.currentPermissionMode === "bypassPermissions" && toolName !== "AskUserQuestion") {
1058
+ // The mode is this session's own (falling back to the project default only
1059
+ // where the session has none, as at query start), never another session's.
1060
+ var sessionMode = session.permissionMode || sm.currentPermissionMode;
1061
+ if (!ruleForced && sessionMode === "bypassPermissions" && toolName !== "AskUserQuestion") {
1106
1062
  return Promise.resolve({ behavior: "allow", updatedInput: input });
1107
1063
  }
1108
1064
 
@@ -1119,7 +1075,7 @@ function createSDKBridge(opts) {
1119
1075
  }
1120
1076
 
1121
1077
  // Check shared whitelist (read-only tools, safe browser tools, safe bash commands)
1122
- var whitelisted = ruleForced ? null : checkToolWhitelist(toolName, input);
1078
+ var whitelisted = ruleForced ? null : checkToolWhitelist(toolName, input, opts);
1123
1079
  if (whitelisted) {
1124
1080
  return Promise.resolve(whitelisted);
1125
1081
  }
@@ -1306,15 +1262,23 @@ function createSDKBridge(opts) {
1306
1262
  // reply (project-sessions.js's set_model/switch_session).
1307
1263
  session.model = metaData.model;
1308
1264
  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 || [] });
1265
+ sendToSession(session, { type: "config_state", model: metaData.model, mode: session.permissionMode || sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [] });
1310
1266
  break;
1311
1267
  case "effort_changed":
1312
1268
  sm.currentEffort = metaData.effort;
1313
1269
  send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort, betas: sm.currentBetas || [] });
1314
1270
  break;
1315
1271
  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 || [] });
1272
+ // One session's worker changed its own mode (plan entered or
1273
+ // left, say). That is this session's mode and no one else's:
1274
+ // writing it to sm.currentPermissionMode made it the
1275
+ // project-wide mode every other session starts from.
1276
+ // The worker is not a trusted source: the mode passes the same
1277
+ // check as any other entry point, and a refused one leaves the
1278
+ // session on its previous mode.
1279
+ if (!modeAllowed(session, metaData.mode, "worker permission mode", true)) break;
1280
+ session.permissionMode = metaData.mode;
1281
+ sendToSession(session, { type: "config_state", model: session.model || sm.currentModel || "", mode: metaData.mode, effort: sm.currentEffort || "medium", betas: sm.currentBetas || [] });
1318
1282
  break;
1319
1283
  case "worker_error":
1320
1284
  send({ type: "error", text: metaData.error });
@@ -1541,9 +1505,9 @@ function createSDKBridge(opts) {
1541
1505
  session.rateLimitResetsAt = null;
1542
1506
  session.rateLimitAutoContinuePending = true;
1543
1507
  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);
1508
+ console.log("[sdk-bridge] Rate limited, scheduling the rate-limit resume for session " + session.localId);
1509
+ if (typeof opts.scheduleRateLimitResume === "function") {
1510
+ opts.scheduleRateLimitResume(session, acResetsAt);
1547
1511
  }
1548
1512
  } else if (acEnabled && !session.destroying) {
1549
1513
  // Log why auto-continue was not scheduled (for debugging)
@@ -1669,8 +1633,32 @@ function createSDKBridge(opts) {
1669
1633
 
1670
1634
  // `initiator` (turn-initiator.js INITIATORS) is who started this turn. It is
1671
1635
  // 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) {
1636
+ // of the session or about the process's environment. `messageId` is the id
1637
+ // the message's history entry carries (injected-sender.js stampRecord); it is
1638
+ // sent to the vendor with the message so the vendor transcript and the
1639
+ // published sender record name the same message.
1640
+ // `leadMessages` ([{ text, initiator, messageId }]) are further user messages
1641
+ // of their own, sent before the first one: a message the operator typed while
1642
+ // a loop iteration was running reaches the vendor as itself, with its own
1643
+ // initiator and id, never inside the message the loop composed.
1644
+ async function startQuery(session, text, images, linuxUser, initiator, messageId, leadMessages) {
1645
+ // Every path that gives a reaped session a runtime again (send-input, the
1646
+ // browser, a loop or scheduled turn) comes through here, so the name rule
1647
+ // for a session coming back to life is enforced once. The name is reserved
1648
+ // synchronously, before the first await, and released when the start ends.
1649
+ var reservation = sm.sessions ? reserveNameOnRevival(sm.sessions, session) : null;
1650
+ if (reservation && reservation.holder) {
1651
+ if (typeof sm.saveSessionFile === "function") sm.saveSessionFile(session);
1652
+ if (typeof sm.broadcastSessionList === "function") sm.broadcastSessionList();
1653
+ }
1654
+ try {
1655
+ return await startQueryRuntime(session, text, images, linuxUser, initiator, messageId, leadMessages);
1656
+ } finally {
1657
+ if (reservation) reservation.release();
1658
+ }
1659
+ }
1660
+
1661
+ async function startQueryRuntime(session, text, images, linuxUser, initiator, messageId, leadMessages) {
1674
1662
  async function ensureVendorReady(vendor) {
1675
1663
  if (!vendor) return null;
1676
1664
  // What the adapter's live session advertises narrows its declaration; the
@@ -2023,11 +2011,6 @@ function createSDKBridge(opts) {
2023
2011
  // belt-and-suspenders for sessions that carry agentName from a prior
2024
2012
  // vendor switch or a direct ws message.
2025
2013
  //
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
2014
  // lr-5bd7 — declared outside the agent block so the model override can be
2032
2015
  // applied when queryModel is computed below (after loop-settings resolution).
2033
2016
  var _agentDeclaredModel = null;
@@ -2043,18 +2026,12 @@ function createSDKBridge(opts) {
2043
2026
  var effectiveHome = resolveEffectiveHome(linuxUser);
2044
2027
  var effectiveAgentsDir = effectiveHome ? path.join(effectiveHome, ".claude", "agents") : AGENTS_SOURCE_DIR;
2045
2028
 
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
2029
  // lr-5bd7 — inject AGENT.md body as systemPrompt on the main thread.
2053
2030
  // The `agents` map approach (PR #264) only applies to subagent invocations
2054
2031
  // via the Agent tool; it does not deliver the body to the main conversation.
2055
2032
  // Setting claudeOpts.systemPrompt bypasses settingSources/agents-map resolution
2056
2033
  // and ensures the model receives the agent persona directly.
2057
- // We keep claudeOpts.agent set — it still applies tool restrictions via settingSources.
2034
+ // We keep claudeOpts.agent set; the console passes no tool list of its own.
2058
2035
  var agentSlug = slugifyAgentName(session.agentName);
2059
2036
  var agentFilePath = path.join(effectiveAgentsDir, agentSlug + ".md");
2060
2037
  var agentRaw;
@@ -2094,7 +2071,10 @@ function createSDKBridge(opts) {
2094
2071
  if (budgetTokens) claudeOpts.thinking = { type: "enabled", budgetTokens: budgetTokens };
2095
2072
  }
2096
2073
 
2097
- if (ls.permissionMode) {
2074
+ // A loop's mode (LOOP.json is a file, not a trusted client) passes the same
2075
+ // check as a mode a client asks for; a refused one is ignored and the
2076
+ // session's own mode applies.
2077
+ if (ls.permissionMode && modeAllowed(session, ls.permissionMode, "loop permissionMode", true)) {
2098
2078
  session._loopPermissionMode = ls.permissionMode;
2099
2079
  }
2100
2080
 
@@ -2108,6 +2088,17 @@ function createSDKBridge(opts) {
2108
2088
  claudeOpts.permissionMode = "bypassPermissions";
2109
2089
  } else {
2110
2090
  var globalMode = session.permissionMode || sm.currentPermissionMode || "default";
2091
+ // A stored mode (session file, saved default) is checked again here: a
2092
+ // bypassPermissions written by an older build or by hand must not start
2093
+ // a query while the server does not allow it.
2094
+ // The vendor is known here, so a mode the session's vendor lacks (auto
2095
+ // after a switch to a vendor without it) falls back too.
2096
+ if (!modeAllowed(session, globalMode, "stored permission mode", true)) {
2097
+ globalMode = "default";
2098
+ // The session's own mode too, so the bypass branch of canUseTool
2099
+ // (which reads it) agrees with what this query starts with.
2100
+ if (session.permissionMode) session.permissionMode = "default";
2101
+ }
2111
2102
  var effectiveDefault;
2112
2103
  if (globalMode === "bypassPermissions") effectiveDefault = "bypassPermissions";
2113
2104
  else if (session.acceptEditsAfterStart) effectiveDefault = "acceptEdits";
@@ -2219,6 +2210,13 @@ function createSDKBridge(opts) {
2219
2210
  // The variables Settings add to this runtime's environment, as of now.
2220
2211
  withRuntimeEnv(queryOpts, session);
2221
2212
 
2213
+ // The console's own reference to this session, in the process environment
2214
+ // whatever identity provider is configured (lib/sender-ref.js). Claude only:
2215
+ // one Codex app-server serves many threads, so it cannot carry a per-thread one.
2216
+ if (sessionAdapter.vendor === "claude" && slug) {
2217
+ queryOpts.sessionRef = { project: slug, sessionId: session.localId };
2218
+ }
2219
+
2222
2220
  // The identity of this agent process, when a provider is configured. Its
2223
2221
  // directory is delivered in the process's environment and removed when the
2224
2222
  // query ends (processQueryStream) or fails to start (below).
@@ -2280,7 +2278,13 @@ function createSDKBridge(opts) {
2280
2278
 
2281
2279
  // Push initial user message through the QueryHandle
2282
2280
  console.log("[sdk-bridge] pushing initial message via handle.pushMessage...");
2283
- handle.pushMessage(text, images, initiator);
2281
+ if (Array.isArray(leadMessages)) {
2282
+ for (var li = 0; li < leadMessages.length; li++) {
2283
+ var lead = leadMessages[li];
2284
+ handle.pushMessage(lead.text, undefined, lead.initiator, lead.messageId);
2285
+ }
2286
+ }
2287
+ handle.pushMessage(text, images, initiator, messageId);
2284
2288
 
2285
2289
  // lr-b61b: Flush any messages that arrived between turns (after the previous
2286
2290
  // finally block nulled queryInstance and before this startQuery call).
@@ -2288,7 +2292,7 @@ function createSDKBridge(opts) {
2288
2292
  console.log("[sdk-bridge] startQuery: flushing " + session.pendingMessages.length + " buffered pending message(s) for project " + slug + " session " + session.localId);
2289
2293
  for (var pi = 0; pi < session.pendingMessages.length; pi++) {
2290
2294
  var pm = session.pendingMessages[pi];
2291
- handle.pushMessage(pm.text, pm.images, pm.initiator);
2295
+ handle.pushMessage(pm.text, pm.images, pm.initiator, pm.messageId);
2292
2296
  }
2293
2297
  session.pendingMessages = [];
2294
2298
  }
@@ -2327,11 +2331,11 @@ function createSDKBridge(opts) {
2327
2331
  }
2328
2332
  }
2329
2333
 
2330
- function pushMessage(session, text, images, initiator) {
2334
+ function pushMessage(session, text, images, initiator, messageId) {
2331
2335
  bumpLastActivity(session, "push-message", slug);
2332
2336
  // Route through QueryHandle (works for both in-process and worker paths)
2333
2337
  if (session.queryInstance && typeof session.queryInstance.pushMessage === "function") {
2334
- session.queryInstance.pushMessage(text, images, initiator);
2338
+ session.queryInstance.pushMessage(text, images, initiator, messageId);
2335
2339
  } else {
2336
2340
  // lr-b61b: queryInstance is null between turns (finally block has run but
2337
2341
  // startQuery has not been called yet). Buffer the message so it is not
@@ -2347,7 +2351,7 @@ function createSDKBridge(opts) {
2347
2351
  // so any candidate cause that lands a message here is visible.
2348
2352
  var wasFull = session.pendingMessages.length >= MAX_PENDING_MESSAGES;
2349
2353
  if (wasFull) session.pendingMessages.shift();
2350
- session.pendingMessages.push({ text: text, images: images, initiator: initiator });
2354
+ session.pendingMessages.push({ text: text, images: images, initiator: initiator, messageId: messageId });
2351
2355
  console.log("[sdk-bridge] pushMessage: queryInstance null, buffered message for session " + session.localId + " (pending=" + session.pendingMessages.length + ")");
2352
2356
  sendAndRecord(session, {
2353
2357
  type: "diagnostic",
@@ -2378,29 +2382,7 @@ function createSDKBridge(opts) {
2378
2382
  }
2379
2383
 
2380
2384
  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;
2385
+ return permissionSummary.pushBody(toolName, input);
2404
2386
  }
2405
2387
 
2406
2388
  // Detect which vendor binaries are installed for an OS identity and record
@@ -2596,6 +2578,9 @@ function createSDKBridge(opts) {
2596
2578
  }
2597
2579
 
2598
2580
  async function setPermissionMode(session, mode) {
2581
+ // The handlers check first; this keeps any other caller (a prompt answer,
2582
+ // a loop) from handing the session a mode the server does not allow.
2583
+ if (!modeAllowed(session, mode, "setPermissionMode", false)) return;
2599
2584
  if (!session.queryInstance) {
2600
2585
  // No active query — store on session only (not sm — that's for project defaults).
2601
2586
  // config_state sent targeted by caller (project-sessions.js).
@@ -263,6 +263,8 @@ function attachMessageProcessor(ctx) {
263
263
  var _isNewSessionId = !session.cliSessionId;
264
264
  session.cliSessionId = parsed.sessionId;
265
265
  sm.saveSessionFile(session);
266
+ // Messages sent before the vendor named the session were held until now.
267
+ if (typeof sm.flushSenderRecords === "function") sm.flushSenderRecords(session);
266
268
  if (_isNewSessionId) {
267
269
  sendAndRecord(session, { type: "session_id", cliSessionId: session.cliSessionId });
268
270
  }
@@ -331,6 +333,11 @@ function attachMessageProcessor(ctx) {
331
333
  if (parsed.inputTokens) {
332
334
  session.lastStreamInputTokens = parsed.inputTokens;
333
335
  }
336
+ // A vendor that numbers its own turns (Codex) names the turn the message
337
+ // started: published beside the message's sender record.
338
+ if (parsed.messageId && parsed.turnId && typeof sm.bindSenderTurn === "function") {
339
+ sm.bindSenderTurn(session, parsed.messageId, parsed.turnId);
340
+ }
334
341
 
335
342
  } else if (parsed.yokeType === "tool_start" || parsed.yokeType === "thinking_start" || parsed.yokeType === "text_start") {
336
343
  var idx = parsed.blockId;
@@ -938,7 +945,8 @@ function attachMessageProcessor(ctx) {
938
945
 
939
946
  // Schedule auto-continue immediately on rejection (don't wait for
940
947
  // query completion which has timing issues with worker/non-worker paths).
941
- if (!session.scheduledMessage && !session.destroying) {
948
+ var resumeArmed = typeof opts.hasRateLimitResume === "function" && opts.hasRateLimitResume(session);
949
+ if (!resumeArmed && !session.destroying) {
942
950
  var acEnabled = session.onQueryComplete ||
943
951
  (typeof opts.getAutoContinueSetting === "function" && opts.getAutoContinueSetting(session));
944
952
  console.log("[sdk-bridge] rate_limit rejected: acEnabled=" + acEnabled + " overage=" + !!info.isUsingOverage + " session=" + session.localId);
@@ -948,16 +956,16 @@ function attachMessageProcessor(ctx) {
948
956
  // Extra usage available: send continue immediately (5s delay for query to finish)
949
957
  console.log("[sdk-bridge] Overage available, sending immediate continue for session " + session.localId);
950
958
  session.rateLimitResetsAt = null;
951
- if (typeof opts.scheduleMessage === "function") {
952
- opts.scheduleMessage(session, "continue", Date.now());
959
+ if (typeof opts.scheduleRateLimitResume === "function") {
960
+ opts.scheduleRateLimitResume(session, Date.now());
953
961
  }
954
962
  } else {
955
963
  // No overage: schedule after rate limit resets
956
964
  var acResetsAt = session.rateLimitResetsAt;
957
965
  session.rateLimitResetsAt = null;
958
966
  console.log("[sdk-bridge] Scheduling auto-continue on rate limit rejection for session " + session.localId);
959
- if (typeof opts.scheduleMessage === "function") {
960
- opts.scheduleMessage(session, "continue", acResetsAt);
967
+ if (typeof opts.scheduleRateLimitResume === "function") {
968
+ opts.scheduleRateLimitResume(session, acResetsAt);
961
969
  }
962
970
  }
963
971
  }
@@ -24,6 +24,22 @@ function resolveContainedSkillDir(base, entryName) {
24
24
  }
25
25
  }
26
26
 
27
+ // The only characters a command may hold and still be auto-approved: letters,
28
+ // digits, space, tab and . _ / : @ ^ ~ + , % - | ; and "&" (only as "&&").
29
+ // This is an allowlist because every denylist of shell syntax kept missing a
30
+ // shape that builds a word after the check (${X:---output}, {--output,f},
31
+ // -\-output, "--out""put", a glob matching a file named like a flag). With no
32
+ // quote, escape, expansion, brace, glob, redirection, assignment or newline in
33
+ // the text, each token is exactly what the command receives, so the per-command
34
+ // argument checks see the real arguments. Anything else costs a prompt.
35
+ var AUTO_APPROVABLE_SHELL_RE = /^[A-Za-z0-9 \t._\/:@^~+,%|;&-]*$/;
36
+
37
+ function hasUnapprovableShellSyntax(cmd) {
38
+ if (typeof cmd !== "string" || !AUTO_APPROVABLE_SHELL_RE.test(cmd)) return true;
39
+ // A "&" that is not half of "&&" is a background job.
40
+ return cmd.replace(/&&/g, "").indexOf("&") !== -1;
41
+ }
42
+
27
43
  // Split shell command on operators (&&, ||, ;, |) while respecting quotes
28
44
  // and parentheses. Returns array of command segments.
29
45
  function splitShellSegments(cmd) {
@@ -360,6 +376,7 @@ function attachSkillDiscovery(ctx) {
360
376
 
361
377
  module.exports = {
362
378
  splitShellSegments: splitShellSegments,
379
+ hasUnapprovableShellSyntax: hasUnapprovableShellSyntax,
363
380
  attachSkillDiscovery: attachSkillDiscovery,
364
381
  extractDescriptionFromContent: extractDescriptionFromContent,
365
382
  extractSkillDescription: extractSkillDescription,