@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
@@ -7,51 +7,37 @@ var path = require("path");
7
7
  var fs = require("fs");
8
8
  var { CodexAppServer } = require("../codex-app-server");
9
9
  var { discoverWorkflows } = require("../../sdk-workflow-discovery");
10
- var { discoverSkillsWithMeta, resolveContainedSkillDir } = require("../../sdk-skill-discovery");
10
+ var { discoverSkillsWithMeta, collectSkillDirs } = require("../../sdk-skill-discovery");
11
11
  var codexLocalImage = require("../codex-local-image");
12
-
13
- // --- Claude skill discovery ---
14
- // Finds Claude skills in ~/.claude/skills/ and <cwd>/.claude/skills/
15
- // so Codex can recognize $<skill-name> in user input.
12
+ var runtimeEnv = require("../../runtime-env");
13
+ var codexCapabilities = require("./codex-capabilities").codexCapabilities;
14
+ var codexProtocol = require("../codex-protocol");
15
+ var codexVersion = require("../codex-version");
16
+
17
+ // --- Skill discovery ---
18
+ // Finds the skills of both agents: the user's and the project's .claude/skills
19
+ // and .agents/skills (sdk-skill-discovery.js owns where they live and how a
20
+ // directory entry is contained). Codex takes a skill as an input item carrying
21
+ // the path of its SKILL.md, so a $<skill-name> in the user's text is matched
22
+ // against this list whichever agent's directory the skill sits in.
16
23
  //
17
24
  // homeOverride: optional. On a shared multi-user daemon, the caller resolves
18
25
  // the SESSION OWNER's home (os-users.getLinuxUserHome(linuxUser)) and passes
19
- // it here so the global skills dir is the invoking user's own ~/.claude/skills,
20
- // not the daemon process's REAL_HOME (lr-3ccc78). Falls back to REAL_HOME
21
- // (config.js) / os.homedir() when absent — single-user case, unchanged.
22
- function discoverClaudeSkills(cwd, homeOverride) {
23
- var skills = {};
26
+ // it here so the global skills dir is the invoking user's own, not the daemon
27
+ // process's REAL_HOME. Falls back to REAL_HOME (config.js) / os.homedir() when
28
+ // absent — single-user case, unchanged.
29
+ function discoverSkillFiles(cwd, homeOverride) {
24
30
  var globalHome = homeOverride;
25
31
  if (!globalHome) {
26
32
  try { globalHome = require("../../config").REAL_HOME; } catch (e) { globalHome = require("os").homedir(); }
27
33
  }
28
- var dirs = [
29
- path.join(globalHome, ".claude", "skills"),
30
- path.join(cwd || "", ".claude", "skills"),
31
- ];
32
- for (var d = 0; d < dirs.length; d++) {
33
- var base = dirs[d];
34
- if (!base) continue;
35
- var entries;
36
- try { entries = fs.readdirSync(path.resolve(base), { withFileTypes: true }); } catch (e) { continue; }
37
- for (var i = 0; i < entries.length; i++) {
38
- var entry = entries[i];
39
- if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
40
- // Two-stage containment (lexical + realpath) — see
41
- // sdk-skill-discovery.js's resolveContainedSkillDir doc comment.
42
- // entry.name comes from readdirSync and may be a symlink; a lexical
43
- // check alone does not stop fs.accessSync below from following a
44
- // symlinked entry outside base.
45
- var skillDir = resolveContainedSkillDir(base, entry.name);
46
- if (!skillDir) continue;
47
- var skillMd = path.join(skillDir, "SKILL.md");
48
- try {
49
- fs.accessSync(skillMd, fs.constants.R_OK);
50
- // project skills override global skills
51
- skills[entry.name] = skillMd;
52
- } catch (e) {}
53
- }
54
- }
34
+ // A session of this agent reads .agents/skills natively, so a same-named
35
+ // skill there beats the one in .claude/skills.
36
+ var dirs = collectSkillDirs(cwd, globalHome, true);
37
+ var skills = Object.create(null);
38
+ Object.keys(dirs).forEach(function(name) {
39
+ skills[name] = path.join(dirs[name], "SKILL.md");
40
+ });
55
41
  return skills;
56
42
  }
57
43
 
@@ -166,6 +152,12 @@ function waitForProcessExit(proc, timeoutMs) {
166
152
  });
167
153
  }
168
154
 
155
+ function codexError(code, message) {
156
+ var err = new Error("[yoke/codex] " + message);
157
+ err.code = code;
158
+ return err;
159
+ }
160
+
169
161
  function createShutdownError() {
170
162
  var err = new Error("Codex adapter is shutting down, retry shortly");
171
163
  err.code = "CODEX_ADAPTER_SHUTTING_DOWN";
@@ -644,7 +636,7 @@ function _test_resolveModel(queryOpts) {
644
636
  // Selects the model used for background title generation.
645
637
  //
646
638
  // The live "model/list" RPC's Model objects (see the model/list handler
647
- // below, and _cachedModels' shape) carry no cost-tier field — only
639
+ // below, and the shape of an instance's models) carry no cost-tier field — only
648
640
  // value/displayName/supportedEffortLevels/isLatest ("isLatest" means "not
649
641
  // superseded by an upgrade", not "cheap"). There is no robust signal in the
650
642
  // live catalog to identify a mini/small-tier model, and this codebase does
@@ -652,8 +644,8 @@ function _test_resolveModel(queryOpts) {
652
644
  // string matching was deliberately removed elsewhere — see the Context
653
645
  // meter section of docs/guides/architecture.md).
654
646
  //
655
- // So titling — a trivial 3-8 word job — falls back to _defaultModel, the
656
- // adapter's only non-staling model identifier (refreshed from the live
647
+ // So titling — a trivial 3-8 word job — falls back to the server's default
648
+ // model, the adapter's only non-staling model identifier (refreshed from the live
657
649
  // model/list response). This is a deliberate cost/staleness tradeoff: every
658
650
  // auto-title now runs on the user's main model instead of a cheaper
659
651
  // mini-tier one, in exchange for auto-titling never breaking silently when
@@ -668,6 +660,9 @@ function createCodexQueryHandle(appServer, queryOpts) {
668
660
  var canUseTool = queryOpts.canUseTool || null;
669
661
  var onElicitation = queryOpts.onElicitation || null;
670
662
  var onFinished = queryOpts.onFinished || null;
663
+ // What the running Codex accepts (codex-protocol.js). A handle made without
664
+ // one is taken to run the oldest supported Codex.
665
+ var features = queryOpts.features || codexProtocol.protocolFeatures(null);
671
666
 
672
667
  // Check if the query was cancelled (either via handle.abort() or direct signal abort)
673
668
  function isCancelled() {
@@ -757,7 +752,17 @@ function createCodexQueryHandle(appServer, queryOpts) {
757
752
  }
758
753
  }
759
754
 
755
+ // JSON-RPC request id -> AbortController for an approval still awaiting
756
+ // the operator. The daemon-side prompt ends with it when the app-server
757
+ // clears the request without our answer (serverRequest/resolved for an id
758
+ // we never answered: turn start, completion or interruption) or the query
759
+ // ends.
760
+ var approvalAborts = {};
761
+
760
762
  function endIterator() {
763
+ // The query is over: no approval still awaiting the operator can be
764
+ // delivered to the app-server any more.
765
+ Object.keys(approvalAborts).forEach(function (key) { approvalAborts[key].abort(); });
761
766
  iteratorDone = true;
762
767
  if (eventWaiting) {
763
768
  var resolve = eventWaiting;
@@ -792,6 +797,26 @@ function createCodexQueryHandle(appServer, queryOpts) {
792
797
  // Track whether this turn is still active (waiting for turn/completed or turn/failed)
793
798
  var turnResolve = null;
794
799
 
800
+ // Asks the daemon about one server request and answers it; a request the
801
+ // app-server already cleared takes no answer.
802
+ function awaitApproval(rpcId, ask, onAnswer, onError) {
803
+ var key = String(rpcId);
804
+ var ac = new AbortController();
805
+ approvalAborts[key] = ac;
806
+ var pending;
807
+ try {
808
+ pending = Promise.resolve(ask(ac.signal));
809
+ } catch (e) {
810
+ pending = Promise.reject(e);
811
+ }
812
+ pending
813
+ .then(function (value) { if (!ac.signal.aborted) onAnswer(value); })
814
+ .catch(function (err) { if (!ac.signal.aborted) onError(err); })
815
+ .finally(function () {
816
+ if (approvalAborts[key] === ac) delete approvalAborts[key];
817
+ });
818
+ }
819
+
795
820
  // --- App-server event handler ---
796
821
  function handleServerEvent(msg) {
797
822
  var method = msg.method;
@@ -800,6 +825,11 @@ function createCodexQueryHandle(appServer, queryOpts) {
800
825
  // Ignore events from other threads (app-server is shared across sessions)
801
826
  if (params.threadId && state.threadId && params.threadId !== state.threadId) return;
802
827
 
828
+ if (method === "serverRequest/resolved" && params.requestId != null) {
829
+ var cleared = approvalAborts[String(params.requestId)];
830
+ if (cleared) cleared.abort();
831
+ }
832
+
803
833
  // After abort, only let turn-ending events through
804
834
  if (isCancelled() && method !== "turn/completed" && method !== "turn/failed" && method !== "serverRequest/resolved" && method !== "thread/status/changed") return;
805
835
 
@@ -829,11 +859,13 @@ function createCodexQueryHandle(appServer, queryOpts) {
829
859
  if (isAllowAll()) {
830
860
  appServer.respond(msg.id, { decision: "accept" });
831
861
  } else if (canUseTool) {
832
- canUseTool("Bash", { command: cmdParams.command }, {}).then(function(decision) {
862
+ awaitApproval(msg.id, function (signal) {
863
+ return canUseTool("Bash", { command: cmdParams.command }, { signal: signal });
864
+ }, function (decision) {
833
865
  var approved = isApproved(decision);
834
866
  // Response must be wrapped in { decision: ... } object per app-server protocol
835
867
  appServer.respond(msg.id, { decision: approved ? "accept" : "decline" });
836
- }).catch(function(err) {
868
+ }, function (err) {
837
869
  console.error("[yoke/codex] canUseTool error:", err.message);
838
870
  appServer.respond(msg.id, { decision: "decline" });
839
871
  });
@@ -855,9 +887,11 @@ function createCodexQueryHandle(appServer, queryOpts) {
855
887
  appServer.respond(msg.id, { decision: "accept" });
856
888
  } else if (canUseTool) {
857
889
  var changeInfo = (fcParams.changes || []).map(function(c) { return c.kind + " " + c.path; }).join(", ");
858
- canUseTool("Edit", { changes: changeInfo, path: fcParams.path }, {}).then(function(decision) {
890
+ awaitApproval(msg.id, function (signal) {
891
+ return canUseTool("Edit", { changes: changeInfo, path: fcParams.path }, { signal: signal });
892
+ }, function (decision) {
859
893
  appServer.respond(msg.id, { decision: isApproved(decision) ? "accept" : "decline" });
860
- }).catch(function(err) {
894
+ }, function (err) {
861
895
  console.error("[yoke/codex] canUseTool error:", err.message);
862
896
  appServer.respond(msg.id, { decision: "decline" });
863
897
  });
@@ -905,18 +939,20 @@ function createCodexQueryHandle(appServer, queryOpts) {
905
939
  }
906
940
  request.requestedSchema = schema;
907
941
  }
908
- onElicitation(request, {
909
- signal: { addEventListener: function() {} },
910
- }).then(function(result) {
942
+ awaitApproval(msg.id, function (signal) {
943
+ return onElicitation(request, { signal: signal });
944
+ }, function (result) {
911
945
  appServer.respond(msg.id, result || { action: "reject" });
912
- }).catch(function(err) {
946
+ }, function (err) {
913
947
  console.error("[yoke/codex] elicitation_response send failed:", err.message || err);
914
948
  appServer.respond(msg.id, { action: "reject" });
915
949
  });
916
950
  } else if (canUseTool) {
917
- canUseTool("mcp__" + (mcpParams.serverName || "unknown") + "__" + (mcpMeta.tool || "call"), mcpParams, {}).then(function(decision) {
951
+ awaitApproval(msg.id, function (signal) {
952
+ return canUseTool("mcp__" + (mcpParams.serverName || "unknown") + "__" + (mcpMeta.tool || "call"), mcpParams, { signal: signal });
953
+ }, function (decision) {
918
954
  appServer.respond(msg.id, { action: isApproved(decision) ? "accept" : "decline" });
919
- }).catch(function(err) {
955
+ }, function (err) {
920
956
  console.error("[yoke/codex] MCP canUseTool error:", err.message);
921
957
  appServer.respond(msg.id, { action: "decline" });
922
958
  });
@@ -947,7 +983,9 @@ function createCodexQueryHandle(appServer, queryOpts) {
947
983
  }
948
984
 
949
985
  // --- Main query loop ---
950
- async function runQueryLoop(initialMessage) {
986
+ async function runQueryLoop(initialMessage, initialInitiator) {
987
+ // Who started the turn being sent, per turn (turn-initiator.js).
988
+ var currentInitiator = initialInitiator;
951
989
  // Prepend system prompt (project instructions from YOKE layer) to first message.
952
990
  // initialMessage may be a string (text-only) or an array of content items
953
991
  // (e.g. [{ type: "text", text: "..." }, ...] when images/attachments are present).
@@ -991,7 +1029,7 @@ function createCodexQueryHandle(appServer, queryOpts) {
991
1029
  var threadParams = {
992
1030
  model: _test_resolveModel(queryOpts),
993
1031
  sandbox: queryOpts.sandboxMode || "workspace-write",
994
- approvalPolicy: queryOpts.approvalPolicy || "on-failure",
1032
+ approvalPolicy: codexProtocol.normalizeApprovalPolicy(queryOpts.approvalPolicy),
995
1033
  cwd: queryOpts.cwd,
996
1034
  skipGitRepoCheck: true,
997
1035
  };
@@ -1064,7 +1102,7 @@ function createCodexQueryHandle(appServer, queryOpts) {
1064
1102
  // was wired (e.g. warmup/init queries), while this newer site failed
1065
1103
  // closed in the same situation — an inconsistency BOBBIE flagged on
1066
1104
  // the lr-4a13c3 PR. All four sites now fail closed identically.
1067
- var availableSkills = discoverClaudeSkills(queryOpts.cwd, queryOpts.homeOverride);
1105
+ var availableSkills = discoverSkillFiles(queryOpts.cwd, queryOpts.homeOverride);
1068
1106
  var skillItemsToInject = [];
1069
1107
  var candidateSkills = [];
1070
1108
  var seenSkillNames = {};
@@ -1105,7 +1143,7 @@ function createCodexQueryHandle(appServer, queryOpts) {
1105
1143
  }
1106
1144
  }
1107
1145
  if (skillItemsToInject.length > 0) {
1108
- console.log("[yoke/codex] injecting Claude skills:", skillItemsToInject.map(function(s) { return s.name; }).join(", "));
1146
+ console.log("[yoke/codex] injecting skills:", skillItemsToInject.map(function(s) { return s.name; }).join(", "));
1109
1147
  input = input.concat(skillItemsToInject);
1110
1148
  }
1111
1149
 
@@ -1117,6 +1155,10 @@ function createCodexQueryHandle(appServer, queryOpts) {
1117
1155
  if (state.modelReasoningEffort) {
1118
1156
  turnParams.effort = state.modelReasoningEffort;
1119
1157
  }
1158
+ // Codex tells an automated turn from a typed one by this field alone,
1159
+ // and only a Codex that has it is sent it.
1160
+ var turnTrigger = features.turnTrigger ? codexProtocol.turnTriggerFor(currentInitiator) : null;
1161
+ if (turnTrigger) turnParams.turnTrigger = turnTrigger;
1120
1162
  await appServer.send("turn/start", turnParams, 60000);
1121
1163
 
1122
1164
  // Wait for turn to complete
@@ -1135,7 +1177,8 @@ function createCodexQueryHandle(appServer, queryOpts) {
1135
1177
  // Wait for next message (multi-turn)
1136
1178
  var nextMsg = await waitForMessage();
1137
1179
  if (nextMsg === null) break;
1138
- currentMessage = nextMsg;
1180
+ currentMessage = nextMsg.input;
1181
+ currentInitiator = nextMsg.initiator;
1139
1182
  }
1140
1183
  } catch (e) {
1141
1184
  // Suppress AbortError when the user stopped the query.
@@ -1178,7 +1221,7 @@ function createCodexQueryHandle(appServer, queryOpts) {
1178
1221
  };
1179
1222
  },
1180
1223
 
1181
- pushMessage: function(text, images) {
1224
+ pushMessage: function(text, images, initiator) {
1182
1225
  var input;
1183
1226
  if (images && images.length > 0) {
1184
1227
  input = [];
@@ -1211,9 +1254,9 @@ function createCodexQueryHandle(appServer, queryOpts) {
1211
1254
 
1212
1255
  if (!state.loopStarted) {
1213
1256
  state.loopStarted = true;
1214
- runQueryLoop(input);
1257
+ runQueryLoop(input, initiator);
1215
1258
  } else {
1216
- pushMessageToQueue(input);
1259
+ pushMessageToQueue({ input: input, initiator: initiator });
1217
1260
  }
1218
1261
  },
1219
1262
 
@@ -1332,6 +1375,8 @@ var CODEX_EFFORT_LEVELS_STANDARD = ["low", "medium", "high"]; // models without
1332
1375
  // nothing is hidden behind the older-models disclosure when we have no basis
1333
1376
  // to tier it (lr-e03635: absence of signal must never manifest as a hidden
1334
1377
  // model).
1378
+ var FALLBACK_DEFAULT_MODEL = "gpt-5.5";
1379
+
1335
1380
  var CODEX_DEFAULT_MODELS = [
1336
1381
  {
1337
1382
  value: "gpt-5.5",
@@ -1383,56 +1428,141 @@ var CODEX_DEFAULT_MODELS = [
1383
1428
  },
1384
1429
  ];
1385
1430
 
1431
+ // --- Running version ---
1432
+
1433
+ // Config objects merged key by key; where both name a leaf, the later one wins.
1434
+ function mergeConfig(base, over) {
1435
+ var out = Object.assign({}, base);
1436
+ Object.keys(over || {}).forEach(function(key) {
1437
+ var a = out[key];
1438
+ var b = over[key];
1439
+ var plain = function(v) { return v && typeof v === "object" && !Array.isArray(v); };
1440
+ out[key] = plain(a) && plain(b) ? mergeConfig(a, b) : b;
1441
+ });
1442
+ return out;
1443
+ }
1444
+
1445
+ // The version of the Codex that is running: what the app-server's userAgent
1446
+ // reports, else what the binary reported when it was resolved. initialize has
1447
+ // no version field of its own, so a userAgent that cannot be read is no reason
1448
+ // to refuse a server whose binary reported one.
1449
+ function settleRunningVersion(binaryVersion, initializeResult) {
1450
+ var reported = codexVersion.versionFromUserAgent(initializeResult && initializeResult.userAgent);
1451
+ var binary = codexVersion.parseVersion(typeof binaryVersion === "string" ? binaryVersion : "");
1452
+ if (reported && binary && codexVersion.compareVersions(reported, binary) !== 0) {
1453
+ console.warn("[codex] the app-server reports " + reported.text + " but the binary reported " + binary.text + "; using the app-server's");
1454
+ }
1455
+ return reported || binary || null;
1456
+ }
1457
+
1386
1458
  // --- Adapter factory ---
1387
1459
 
1388
1460
  function createCodexAdapter(opts) {
1461
+ // Fail closed: under per-user OS isolation no Codex app-server is ever started
1462
+ // (it would run as the daemon's user). The registry keeps the agent from being
1463
+ // created in that mode; this refuses a caller that got here anyway.
1464
+ if (opts && opts.osUsers) {
1465
+ throw codexError("CODEX_OS_USERS_UNSUPPORTED", "Codex is not yet isolated per OS user");
1466
+ }
1389
1467
  var _cwd = (opts && opts.cwd) || process.cwd();
1390
1468
  var _slug = (opts && opts.slug) || "";
1391
1469
  var _defaultInitOpts = Object.assign({}, opts || {});
1392
- var _cachedModels = [];
1393
- // Fallback-only (lr-d91ecf): the initial value before init()/warmup
1394
- // populates _cachedModels from the live model/list RPC or
1395
- // CODEX_DEFAULT_MODELS. Overwritten as soon as either succeeds.
1396
- var _defaultModel = "gpt-5.5";
1397
- var _appServer = null;
1398
- var _initPromise = null;
1470
+ // One app-server per effective environment. Everything that depends on the
1471
+ // environment (the process, its model list and default model, the threads it
1472
+ // holds, its init) lives on the instance, so an operation is served only by
1473
+ // the server started with the environment the caller names, and one user's
1474
+ // variables (an endpoint, a credential) or endpoint models never reach
1475
+ // another user's turn. Keyed by a digest of that environment (never logged,
1476
+ // values are secrets); "" is the daemon's own environment with nothing added.
1477
+ var _instances = new Map();
1399
1478
  var _shutdownPromise = null;
1400
- var _refCount = 0;
1401
- var _lastActiveAt = Date.now();
1402
- var _shuttingDown = false;
1403
- var _activeQueries = [];
1479
+ var _shuttingDown = false; // shutdown() of the whole adapter is running
1480
+
1481
+ function createInstance(fingerprint) {
1482
+ return {
1483
+ fingerprint: fingerprint,
1484
+ appServer: null,
1485
+ initPromise: null,
1486
+ retirePromise: null,
1487
+ refCount: 0,
1488
+ lastActiveAt: Date.now(),
1489
+ activeQueries: [],
1490
+ models: [],
1491
+ // Fallback-only (lr-d91ecf): the value before init() reads the live
1492
+ // model/list RPC; overwritten as soon as that succeeds.
1493
+ defaultModel: FALLBACK_DEFAULT_MODEL,
1494
+ // What the running Codex accepts (codex-protocol.js), and which version
1495
+ // that is; both are settled when the server has started.
1496
+ features: codexProtocol.protocolFeatures(null),
1497
+ version: null,
1498
+ };
1499
+ }
1500
+
1501
+ // The environment the app-server process is started with, or undefined when
1502
+ // it is to inherit the daemon's own: the daemon's environment with the
1503
+ // Settings variables laid over it, then the adapter options' credentials.
1504
+ function serverEnvFor(effectiveOpts) {
1505
+ var env;
1506
+ if (runtimeEnv.hasOverlay(effectiveOpts.runtimeEnv)) {
1507
+ env = runtimeEnv.composeRuntimeEnv(process.env, effectiveOpts.runtimeEnv);
1508
+ }
1509
+ var co = effectiveOpts.adapterOptions && effectiveOpts.adapterOptions.CODEX;
1510
+ if (co && co.apiKey) env = Object.assign({}, env || {}, { OPENAI_API_KEY: co.apiKey });
1511
+ if (co && co.baseUrl) env = Object.assign({}, env || {}, { OPENAI_BASE_URL: co.baseUrl });
1512
+ return env;
1513
+ }
1514
+
1515
+ function fingerprintOf(serverEnv) {
1516
+ return serverEnv ? runtimeEnv.envSignature(serverEnv) : "";
1517
+ }
1518
+
1519
+ // The one lookup of the server an operation runs on, used by init, queries,
1520
+ // model lists, titles, forks and rollbacks. The caller always states its
1521
+ // environment: runtimeEnv is the settings overlay, or null for none (the
1522
+ // daemon's own environment). Absent is an error, never a guess at another
1523
+ // caller's environment.
1524
+ function fingerprintFor(callerOpts, operation) {
1525
+ if (!callerOpts || callerOpts.runtimeEnv === undefined) {
1526
+ throw new Error("[yoke/codex] " + operation + " needs runtimeEnv (null when no settings apply)");
1527
+ }
1528
+ return fingerprintOf(serverEnvFor(Object.assign({}, _defaultInitOpts, callerOpts)));
1529
+ }
1404
1530
 
1405
- function updateLastActiveAt() {
1406
- _lastActiveAt = Date.now();
1531
+ function updateLastActiveAt(inst) {
1532
+ inst.lastActiveAt = Date.now();
1407
1533
  }
1408
1534
 
1409
- function registerActiveQuery(entry) {
1410
- _activeQueries.push(entry);
1535
+ function registerActiveQuery(inst, entry) {
1536
+ inst.activeQueries.push(entry);
1411
1537
  }
1412
1538
 
1413
- function removeActiveQuery(entry) {
1539
+ function removeActiveQuery(inst, entry) {
1414
1540
  var next = [];
1415
- for (var i = 0; i < _activeQueries.length; i++) {
1416
- if (_activeQueries[i] !== entry) next.push(_activeQueries[i]);
1541
+ for (var i = 0; i < inst.activeQueries.length; i++) {
1542
+ if (inst.activeQueries[i] !== entry) next.push(inst.activeQueries[i]);
1417
1543
  }
1418
- _activeQueries = next;
1544
+ inst.activeQueries = next;
1419
1545
  }
1420
1546
 
1421
- function decrementRefCount() {
1422
- if (_refCount > 0) {
1423
- _refCount--;
1547
+ function decrementRefCount(inst) {
1548
+ if (inst.refCount > 0) {
1549
+ inst.refCount--;
1424
1550
  } else {
1425
1551
  console.error("[yoke/codex] refCount negative, bug!");
1426
- _refCount = 0;
1552
+ inst.refCount = 0;
1427
1553
  }
1428
- updateLastActiveAt();
1554
+ updateLastActiveAt(inst);
1555
+ }
1556
+
1557
+ function isStarted(inst) {
1558
+ return !!(inst && inst.appServer && inst.appServer.started);
1429
1559
  }
1430
1560
 
1431
1561
  // Build the enriched slash_commands array from skill names and workflow discovery.
1432
1562
  // Returns {name, desc, type}[] with skills first (type:'skill'), then workflows
1433
1563
  // (type:'workflow'), deduplicated by name. This mirrors the enrichment done in
1434
1564
  // sdk-message-processor for the Claude adapter path.
1435
- // homeOverride (lr-3ccc78): session owner's home, see discoverClaudeSkills doc comment.
1565
+ // homeOverride: session owner's home, see discoverSkillFiles doc comment.
1436
1566
  function buildEnrichedSlashCommands(skillNames, cwd, homeOverride) {
1437
1567
  var effectiveCwd = cwd || _cwd;
1438
1568
  var seen = {};
@@ -1441,7 +1571,7 @@ function createCodexAdapter(opts) {
1441
1571
  // Skills: enrich with descriptions from SKILL.md where available
1442
1572
  var fsSkillsMeta;
1443
1573
  try {
1444
- fsSkillsMeta = discoverSkillsWithMeta(effectiveCwd, homeOverride);
1574
+ fsSkillsMeta = discoverSkillsWithMeta(effectiveCwd, homeOverride, true);
1445
1575
  } catch (e) {
1446
1576
  fsSkillsMeta = [];
1447
1577
  }
@@ -1476,41 +1606,32 @@ function createCodexAdapter(opts) {
1476
1606
  return combined;
1477
1607
  }
1478
1608
 
1479
- function buildReadyResponse(skillNames, cwd, homeOverride) {
1609
+ function buildReadyResponse(inst, skillNames, cwd, homeOverride) {
1480
1610
  return {
1481
- models: _cachedModels,
1482
- defaultModel: _defaultModel,
1611
+ models: inst.models.slice(),
1612
+ defaultModel: inst.defaultModel,
1483
1613
  skills: skillNames || [],
1484
1614
  slashCommands: buildEnrichedSlashCommands(skillNames, cwd, homeOverride),
1485
1615
  fastModeState: null,
1486
- capabilities: {
1487
- thinking: true,
1488
- betas: false,
1489
- rewind: false,
1490
- sessionResume: true,
1491
- promptSuggestions: true,
1492
- elicitation: true,
1493
- fileCheckpointing: false,
1494
- contextCompacting: false,
1495
- toolPolicy: ["ask", "allow-all"],
1496
- },
1616
+ capabilities: codexCapabilities(),
1497
1617
  };
1498
1618
  }
1499
1619
 
1500
- function clearRuntimeState() {
1501
- _appServer = null;
1502
- _initPromise = null;
1503
- _cachedModels = [];
1504
- _refCount = 0;
1505
- _activeQueries = [];
1506
- updateLastActiveAt();
1620
+ function dropInstance(inst) {
1621
+ if (_instances.get(inst.fingerprint) === inst) _instances.delete(inst.fingerprint);
1622
+ inst.appServer = null;
1623
+ inst.initPromise = null;
1624
+ inst.refCount = 0;
1625
+ inst.activeQueries = [];
1626
+ inst.models = [];
1627
+ updateLastActiveAt(inst);
1507
1628
  }
1508
1629
 
1509
- function waitForRefCount(targetCount, timeoutMs) {
1630
+ function waitForRefCount(inst, targetCount, timeoutMs) {
1510
1631
  var deadline = Date.now() + (timeoutMs || 5000);
1511
1632
  return new Promise(function(resolve) {
1512
1633
  function tick() {
1513
- if (_refCount <= targetCount) {
1634
+ if (inst.refCount <= targetCount) {
1514
1635
  resolve(true);
1515
1636
  return;
1516
1637
  }
@@ -1524,11 +1645,11 @@ function createCodexAdapter(opts) {
1524
1645
  });
1525
1646
  }
1526
1647
 
1527
- function stopAppServer(deadlineMs) {
1528
- var proc = _appServer && _appServer.proc ? _appServer.proc : null;
1529
- if (!_appServer) return Promise.resolve(true);
1648
+ function stopAppServer(appServer, deadlineMs) {
1649
+ var proc = appServer && appServer.proc ? appServer.proc : null;
1650
+ if (!appServer) return Promise.resolve(true);
1530
1651
  try {
1531
- _appServer.stop();
1652
+ appServer.stop();
1532
1653
  } catch (e) {
1533
1654
  console.error("[yoke/codex] App-server stop error:", e.message || e);
1534
1655
  }
@@ -1538,59 +1659,124 @@ function createCodexAdapter(opts) {
1538
1659
  if (!exited) {
1539
1660
  try {
1540
1661
  proc.kill("SIGKILL");
1541
- } catch (e) {}
1662
+ } catch (e) {
1663
+ console.error("[yoke/codex] Could not kill the app-server process:", e.message || e);
1664
+ }
1542
1665
  }
1543
1666
  return exited;
1544
1667
  });
1545
1668
  }
1546
1669
 
1547
- function beginShutdown(force, idleMs) {
1548
- if (_shutdownPromise) return _shutdownPromise;
1549
- if (_shuttingDown) return null;
1550
-
1551
- _shuttingDown = true;
1670
+ // Ends one app-server. force aborts the queries still using it; without it
1671
+ // the caller has already established that none is. Resolves once the process
1672
+ // is gone and the instance has been dropped.
1673
+ function retireInstance(inst, force) {
1674
+ if (inst.retirePromise) return inst.retirePromise;
1552
1675
 
1553
- _shutdownPromise = (async function() {
1676
+ inst.retirePromise = (async function() {
1554
1677
  var deadline = Date.now() + 5000;
1555
- var shouldAbort = !!force;
1556
1678
 
1557
- if (_initPromise) {
1558
- try {
1559
- await Promise.race([
1560
- _initPromise.catch(function() { return null; }),
1561
- waitMs(Math.max(0, deadline - Date.now())),
1562
- ]);
1563
- } catch (e) {}
1679
+ if (inst.initPromise) {
1680
+ await Promise.race([
1681
+ inst.initPromise.then(null, function(err) {
1682
+ console.error("[yoke/codex] App-server init failed while it was being retired:", err && err.message || err);
1683
+ return null;
1684
+ }),
1685
+ waitMs(Math.max(0, deadline - Date.now())),
1686
+ ]);
1564
1687
  }
1565
1688
 
1566
- if (shouldAbort && _activeQueries.length > 0) {
1567
- var active = _activeQueries.slice();
1689
+ if (force && inst.activeQueries.length > 0) {
1690
+ var active = inst.activeQueries.slice();
1568
1691
  for (var i = 0; i < active.length; i++) {
1569
1692
  try {
1570
1693
  if (active[i] && active[i].abort) active[i].abort();
1571
- } catch (e) {}
1694
+ } catch (e) {
1695
+ console.error("[yoke/codex] Could not abort a query:", e.message || e);
1696
+ }
1572
1697
  }
1573
- await waitForRefCount(0, Math.max(0, deadline - Date.now()));
1698
+ await waitForRefCount(inst, 0, Math.max(0, deadline - Date.now()));
1574
1699
  }
1575
1700
 
1576
- if (_appServer) {
1577
- await stopAppServer(deadline);
1701
+ if (inst.appServer) {
1702
+ await stopAppServer(inst.appServer, deadline);
1578
1703
  }
1579
1704
 
1580
- clearRuntimeState();
1581
- _shuttingDown = false;
1582
- _shutdownPromise = null;
1705
+ dropInstance(inst);
1583
1706
  return true;
1584
1707
  })().catch(function(err) {
1585
- clearRuntimeState();
1586
- _shuttingDown = false;
1587
- _shutdownPromise = null;
1708
+ dropInstance(inst);
1588
1709
  throw err;
1589
1710
  });
1590
1711
 
1712
+ return inst.retirePromise;
1713
+ }
1714
+
1715
+ // Waits for an instance that is being retired, so the caller can start a
1716
+ // fresh one. A failed retirement is reported where it was started.
1717
+ function afterRetire(inst) {
1718
+ return inst.retirePromise.then(null, function(err) {
1719
+ console.error("[yoke/codex] Retiring an app-server failed:", err && err.message || err);
1720
+ });
1721
+ }
1722
+
1723
+ // The adapter-wide shutdown: every instance.
1724
+ function beginShutdown(force) {
1725
+ if (_shutdownPromise) return _shutdownPromise;
1726
+
1727
+ _shuttingDown = true;
1728
+
1729
+ _shutdownPromise = (async function() {
1730
+ try {
1731
+ var results = await Promise.allSettled(Array.from(_instances.values()).map(function(inst) {
1732
+ return retireInstance(inst, force);
1733
+ }));
1734
+ var failed = results.filter(function(r) { return r.status === "rejected"; })[0];
1735
+ if (failed) throw failed.reason;
1736
+ return true;
1737
+ } finally {
1738
+ _shuttingDown = false;
1739
+ _shutdownPromise = null;
1740
+ }
1741
+ })();
1742
+
1591
1743
  return _shutdownPromise;
1592
1744
  }
1593
1745
 
1746
+ // The started, initialized instance for a fingerprint, starting (or waiting
1747
+ // out the retirement of) one when there is none. Never hands back a server
1748
+ // that was started with a different environment.
1749
+ async function acquireInstance(queryOpts, fingerprint) {
1750
+ for (var attempt = 0; attempt < 3; attempt++) {
1751
+ if (_shuttingDown) throw createShutdownError();
1752
+ var inst = _instances.get(fingerprint);
1753
+ if (inst && inst.retirePromise) {
1754
+ await afterRetire(inst);
1755
+ continue;
1756
+ }
1757
+ if (isStarted(inst) && !inst.initPromise) return inst;
1758
+ await adapter.init(queryOpts);
1759
+ }
1760
+ throw new Error("[yoke/codex] Adapter not initialized. Call init() first.");
1761
+ }
1762
+
1763
+ // Runs a thread operation (fork, rollback) on the server for the environment
1764
+ // the caller states, started if it was reaped: the same lookup as every other
1765
+ // entry point. A caller that states no environment is refused, and a server
1766
+ // that cannot operate on the thread makes the operation throw.
1767
+ // The server counts as in use meanwhile, so the idle reclaim leaves it alone.
1768
+ async function runOnCallerInstance(callerOpts, operation, run) {
1769
+ var wanted = fingerprintFor(callerOpts, operation);
1770
+ var inst = await acquireInstance(callerOpts, wanted);
1771
+ inst.refCount++;
1772
+ try {
1773
+ return await run(inst);
1774
+ } finally {
1775
+ // A server dropped meanwhile has already had its count reset.
1776
+ if (inst.refCount > 0) decrementRefCount(inst);
1777
+ }
1778
+ }
1779
+
1594
1780
  var adapter = {
1595
1781
  vendor: "codex",
1596
1782
 
@@ -1599,24 +1785,44 @@ function createCodexAdapter(opts) {
1599
1785
  return Promise.reject(createShutdownError());
1600
1786
  }
1601
1787
 
1602
- var effectiveInitOpts = Object.assign({}, _defaultInitOpts, initOpts || {});
1788
+ var fingerprint;
1789
+ try {
1790
+ fingerprint = fingerprintFor(initOpts, "init");
1791
+ } catch (e) {
1792
+ return Promise.reject(e);
1793
+ }
1794
+ var effectiveInitOpts = Object.assign({}, _defaultInitOpts, initOpts);
1795
+ var serverEnv = serverEnvFor(effectiveInitOpts);
1796
+ var inst = _instances.get(fingerprint);
1797
+
1798
+ if (inst && inst.retirePromise) {
1799
+ return afterRetire(inst).then(function() { return adapter.init(initOpts); });
1800
+ }
1603
1801
 
1604
- // Already initialized - return cached result
1605
- if (_appServer && _appServer.started && _cachedModels.length > 0) {
1606
- return Promise.resolve(buildReadyResponse([], _cwd));
1802
+ // Already initialized: this server's own models and default model
1803
+ if (isStarted(inst) && !inst.initPromise && inst.models.length > 0) {
1804
+ return Promise.resolve(buildReadyResponse(inst, [], _cwd));
1607
1805
  }
1608
1806
 
1609
1807
  // Deduplicate concurrent init calls
1610
- if (_initPromise) return _initPromise;
1808
+ if (inst && inst.initPromise) return inst.initPromise;
1611
1809
 
1612
- _initPromise = (async function() {
1810
+ if (!inst) {
1811
+ inst = createInstance(fingerprint);
1812
+ _instances.set(fingerprint, inst);
1813
+ }
1814
+
1815
+ var initPromise = (async function() {
1613
1816
  var serverOpts = { cwd: _cwd };
1614
1817
 
1818
+ // The app-server is started with the complete environment: the
1819
+ // daemon's own with the Settings variables laid over it.
1820
+ if (serverEnv) serverOpts.env = serverEnv;
1821
+
1615
1822
  // Extract adapter options
1823
+ var co = null;
1616
1824
  if (effectiveInitOpts && effectiveInitOpts.adapterOptions && effectiveInitOpts.adapterOptions.CODEX) {
1617
- var co = effectiveInitOpts.adapterOptions.CODEX;
1618
- if (co.apiKey) serverOpts.env = Object.assign({}, serverOpts.env || {}, { OPENAI_API_KEY: co.apiKey });
1619
- if (co.baseUrl) serverOpts.env = Object.assign({}, serverOpts.env || {}, { OPENAI_BASE_URL: co.baseUrl });
1825
+ co = effectiveInitOpts.adapterOptions.CODEX;
1620
1826
  if (co.config) serverOpts.config = co.config;
1621
1827
  }
1622
1828
 
@@ -1676,18 +1882,36 @@ function createCodexAdapter(opts) {
1676
1882
  } catch (e) {}
1677
1883
  }
1678
1884
 
1679
- // Spawn and initialize app-server
1680
- _appServer = new CodexAppServer(null, serverOpts);
1681
- await _appServer.start();
1682
-
1683
- await _appServer.send("initialize", {
1684
- clientInfo: { name: "clagentic", title: "Clagentic: Console", version: "1.0.0" },
1885
+ // Spawn and initialize app-server. Constructing it resolves the Codex
1886
+ // the user installed, which fixes the version, and the version decides
1887
+ // which config keys exist: so the console's own keys are added to the
1888
+ // config after the binary is known and before the process starts.
1889
+ var server = new CodexAppServer(null, serverOpts);
1890
+ var binaryVersion = server.resolution && server.resolution.version;
1891
+ var spawnFeatures = codexProtocol.protocolFeatures(binaryVersion);
1892
+ serverOpts.config = mergeConfig(codexProtocol.sessionConfig(spawnFeatures), serverOpts.config);
1893
+ inst.appServer = server;
1894
+ await server.start();
1895
+
1896
+ var initializeResult = await server.send("initialize", {
1897
+ clientInfo: { name: "clagentic-console", title: "Clagentic: Console", version: require("../../../package.json").version },
1685
1898
  capabilities: { experimentalApi: true },
1686
1899
  });
1687
- _appServer.notify("initialized", {});
1900
+ server.notify("initialized", {});
1901
+
1902
+ var running = settleRunningVersion(binaryVersion, initializeResult);
1903
+ if (running && codexVersion.compareVersions(running, codexVersion.MIN_CODEX_VERSION) < 0) {
1904
+ await stopAppServer(server, Date.now() + 1000);
1905
+ throw codexError("CODEX_TOO_OLD", "Codex " + running.text + " is too old; Clagentic: Console needs " + codexVersion.MIN_CODEX_VERSION + " or newer");
1906
+ }
1907
+ inst.version = running ? running.text : null;
1908
+ inst.features = codexProtocol.protocolFeatures(running);
1909
+ if (JSON.stringify(inst.features) !== JSON.stringify(spawnFeatures)) {
1910
+ console.warn("[codex] the running app-server (" + inst.version + ") differs from the binary that was resolved (" + binaryVersion + "); its config was set for the binary");
1911
+ }
1688
1912
 
1689
- if (_shuttingDown) {
1690
- await stopAppServer(Date.now() + 1000);
1913
+ if (_shuttingDown || inst.retirePromise) {
1914
+ await stopAppServer(server, Date.now() + 1000);
1691
1915
  throw createShutdownError();
1692
1916
  }
1693
1917
 
@@ -1696,10 +1920,10 @@ function createCodexAdapter(opts) {
1696
1920
  // supportedReasoningEfforts, and upgrade (non-null when a newer model exists).
1697
1921
  // Fall back to CODEX_DEFAULT_MODELS if the call fails or returns nothing.
1698
1922
  try {
1699
- var modelListResult = await _appServer.send("model/list", {}, 10000);
1923
+ var modelListResult = await server.send("model/list", {}, 10000);
1700
1924
  // Response shape: { data: [Model, ...], nextCursor }
1701
1925
  if (modelListResult && Array.isArray(modelListResult.data) && modelListResult.data.length > 0) {
1702
- _cachedModels = modelListResult.data
1926
+ inst.models = modelListResult.data
1703
1927
  .filter(function(m) { return !m.hidden; })
1704
1928
  .map(function(m) {
1705
1929
  var efforts = Array.isArray(m.supportedReasoningEfforts)
@@ -1722,17 +1946,17 @@ function createCodexAdapter(opts) {
1722
1946
  break;
1723
1947
  }
1724
1948
  }
1725
- _defaultModel = (defaultEntry && (defaultEntry.model || defaultEntry.id)) || _defaultModel;
1726
- console.log("[codex] model/list: " + _cachedModels.length + " models, default=" + _defaultModel);
1949
+ inst.defaultModel = (defaultEntry && (defaultEntry.model || defaultEntry.id)) || inst.defaultModel;
1950
+ console.log("[codex] model/list: " + inst.models.length + " models, default=" + inst.defaultModel);
1727
1951
  } else {
1728
1952
  throw new Error("empty or missing data");
1729
1953
  }
1730
1954
  } catch (e) {
1731
1955
  console.warn("[codex] model/list failed (" + e.message + "); using built-in model table");
1732
- _cachedModels = CODEX_DEFAULT_MODELS.slice();
1733
- // _defaultModel stays "gpt-5.5" (set at init)
1956
+ inst.models = CODEX_DEFAULT_MODELS.slice();
1957
+ // inst.defaultModel stays FALLBACK_DEFAULT_MODEL (set at creation)
1734
1958
  }
1735
- console.log("[codex] App-server initialized, models: " + _cachedModels.map(function(m) { return m.value; }).join(", "));
1959
+ console.log("[codex] App-server initialized, models: " + inst.models.map(function(m) { return m.value; }).join(", "));
1736
1960
 
1737
1961
  // Discover skills: built-in Codex skills + Claude skills
1738
1962
  // lr-3ccc78 — resolve the session owner's home so a shared
@@ -1748,7 +1972,7 @@ function createCodexAdapter(opts) {
1748
1972
  }
1749
1973
  var claudeSkillsDir = require("path").join(claudeSkillsHome, ".claude", "skills");
1750
1974
  var extraRoots = _cwd ? [{ cwd: _cwd, extraUserRoots: [claudeSkillsDir] }] : [];
1751
- var skillsResult = await _appServer.send("skills/list", {
1975
+ var skillsResult = await server.send("skills/list", {
1752
1976
  cwds: _cwd ? [_cwd] : [],
1753
1977
  forceReload: true,
1754
1978
  perCwdExtraUserRoots: extraRoots,
@@ -1769,7 +1993,7 @@ function createCodexAdapter(opts) {
1769
1993
  }
1770
1994
  }
1771
1995
  // Also discover Claude skills directly as fallback
1772
- var claudeSkills = discoverClaudeSkills(_cwd, initHomeOverride);
1996
+ var claudeSkills = discoverSkillFiles(_cwd, initHomeOverride);
1773
1997
  var claudeSkillNames = Object.keys(claudeSkills);
1774
1998
  for (var csn = 0; csn < claudeSkillNames.length; csn++) {
1775
1999
  if (skillNames.indexOf(claudeSkillNames[csn]) === -1) skillNames.push(claudeSkillNames[csn]);
@@ -1779,22 +2003,36 @@ function createCodexAdapter(opts) {
1779
2003
  console.error("[codex] Failed to discover skills:", e.message);
1780
2004
  }
1781
2005
 
1782
- if (_shuttingDown) {
1783
- await stopAppServer(Date.now() + 1000);
2006
+ if (_shuttingDown || inst.retirePromise) {
2007
+ await stopAppServer(server, Date.now() + 1000);
1784
2008
  throw createShutdownError();
1785
2009
  }
1786
2010
 
1787
- _initPromise = null;
1788
- updateLastActiveAt();
2011
+ inst.initPromise = null;
2012
+ updateLastActiveAt(inst);
1789
2013
 
1790
- return buildReadyResponse(skillNames, _cwd, initHomeOverride);
2014
+ return buildReadyResponse(inst, skillNames, _cwd, initHomeOverride);
1791
2015
  })();
1792
2016
 
1793
- return _initPromise;
2017
+ // A start that fails leaves nothing behind, so the next call starts again
2018
+ // instead of being handed this rejection.
2019
+ inst.initPromise = initPromise.then(null, function(err) {
2020
+ if (_instances.get(fingerprint) === inst && !inst.retirePromise) {
2021
+ var failedServer = inst.appServer;
2022
+ dropInstance(inst);
2023
+ return stopAppServer(failedServer, Date.now() + 1000).then(function() { throw err; });
2024
+ }
2025
+ throw err;
2026
+ });
2027
+ return inst.initPromise;
1794
2028
  },
1795
2029
 
1796
- supportedModels: function() {
1797
- return Promise.resolve(_cachedModels.slice());
2030
+ // The model list of the server for the caller's environment (started when
2031
+ // there is none). callerOpts.runtimeEnv is required, null meaning no
2032
+ // settings; a list is never served to an environment it was not read for.
2033
+ supportedModels: async function(callerOpts) {
2034
+ var inst = await acquireInstance(callerOpts, fingerprintFor(callerOpts, "supportedModels"));
2035
+ return inst.models.slice();
1798
2036
  },
1799
2037
 
1800
2038
  createToolServer: function(def) {
@@ -1808,20 +2046,13 @@ function createCodexAdapter(opts) {
1808
2046
  if (_shuttingDown) {
1809
2047
  throw createShutdownError();
1810
2048
  }
2049
+ queryOpts = queryOpts || {};
1811
2050
 
1812
- if (!_appServer || !_appServer.started) {
1813
- await adapter.init(queryOpts || {});
1814
- }
1815
-
1816
- if (_shuttingDown) {
1817
- throw createShutdownError();
1818
- }
1819
-
1820
- if (!_appServer || !_appServer.started) {
1821
- throw new Error("[yoke/codex] Adapter not initialized. Call init() first.");
1822
- }
2051
+ // The query runs on the app-server started with its own environment:
2052
+ // another query's server, with another environment, is never borrowed.
2053
+ var inst = await acquireInstance(queryOpts, fingerprintFor(queryOpts, "createQuery"));
1823
2054
 
1824
- var model = queryOpts.model || _defaultModel;
2055
+ var model = queryOpts.model || inst.defaultModel;
1825
2056
  var ac = queryOpts.abortController || new AbortController();
1826
2057
  var activeEntry = {
1827
2058
  abort: function() {
@@ -1836,17 +2067,19 @@ function createCodexAdapter(opts) {
1836
2067
 
1837
2068
  var handleOpts = {
1838
2069
  model: model,
1839
- defaultModel: _defaultModel,
2070
+ defaultModel: inst.defaultModel,
1840
2071
  cwd: queryOpts.cwd || _cwd,
1841
2072
  systemPrompt: queryOpts.systemPrompt || "",
1842
2073
  abortController: ac,
1843
2074
  canUseTool: queryOpts.canUseTool || null,
1844
2075
  onElicitation: queryOpts.onElicitation || null,
1845
2076
  resumeSessionId: queryOpts.resumeSessionId || null,
1846
- // lr-3ccc78 — session owner's home for discoverClaudeSkills below,
2077
+ // Session owner's home for discoverSkillFiles below,
1847
2078
  // resolved once per query so a shared multi-user daemon shows each
1848
2079
  // user their own ~/.claude/skills, not the daemon operator's.
1849
2080
  homeOverride: resolveLinuxUserHome(codexOpts.linuxUser),
2081
+ // What the Codex this query runs on accepts.
2082
+ features: inst.features,
1850
2083
  };
1851
2084
 
1852
2085
  // Reasoning effort
@@ -1862,7 +2095,7 @@ function createCodexAdapter(opts) {
1862
2095
  if (queryOpts.toolPolicy === "allow-all") {
1863
2096
  handleOpts.approvalPolicy = "never";
1864
2097
  } else {
1865
- handleOpts.approvalPolicy = codexOpts.approvalPolicy || "on-failure";
2098
+ handleOpts.approvalPolicy = codexProtocol.normalizeApprovalPolicy(codexOpts.approvalPolicy);
1866
2099
  }
1867
2100
 
1868
2101
  // Sandbox mode
@@ -1875,19 +2108,19 @@ function createCodexAdapter(opts) {
1875
2108
 
1876
2109
  console.log("[yoke/codex] createQuery: model=" + model + " approval=" + handleOpts.approvalPolicy + " sandbox=" + handleOpts.sandboxMode);
1877
2110
 
1878
- _refCount++;
1879
- registerActiveQuery(activeEntry);
2111
+ inst.refCount++;
2112
+ registerActiveQuery(inst, activeEntry);
1880
2113
 
1881
2114
  var handle;
1882
2115
  try {
1883
2116
  handleOpts.onFinished = function() {
1884
- removeActiveQuery(activeEntry);
1885
- decrementRefCount();
2117
+ removeActiveQuery(inst, activeEntry);
2118
+ decrementRefCount(inst);
1886
2119
  };
1887
- handle = createCodexQueryHandle(_appServer, handleOpts);
2120
+ handle = createCodexQueryHandle(inst.appServer, handleOpts);
1888
2121
  } catch (e) {
1889
- removeActiveQuery(activeEntry);
1890
- decrementRefCount();
2122
+ removeActiveQuery(inst, activeEntry);
2123
+ decrementRefCount(inst);
1891
2124
  throw e;
1892
2125
  }
1893
2126
 
@@ -1913,12 +2146,17 @@ function createCodexAdapter(opts) {
1913
2146
  prompt += "User message " + (i + 1) + ": " + messages[i] + "\n";
1914
2147
  }
1915
2148
  var ac = new AbortController();
2149
+ // The title is generated on the server of the caller's environment, and
2150
+ // with that server's own default model.
2151
+ var envOpts = { runtimeEnv: opts && opts.runtimeEnv };
2152
+ var titleInst = await acquireInstance(envOpts, fingerprintFor(envOpts, "generateTitle"));
1916
2153
  var handle = await adapter.createQuery({
1917
2154
  cwd: (opts && opts.cwd) || _cwd,
1918
2155
  systemPrompt: systemPrompt,
1919
- model: resolveTitleModel(_defaultModel),
2156
+ model: resolveTitleModel(titleInst.defaultModel),
1920
2157
  abortController: ac,
1921
2158
  canUseTool: function() { return Promise.resolve({ behavior: "deny", message: "No tools." }); },
2159
+ runtimeEnv: envOpts.runtimeEnv,
1922
2160
  });
1923
2161
  handle.pushMessage(prompt);
1924
2162
  var title = "";
@@ -1953,17 +2191,23 @@ function createCodexAdapter(opts) {
1953
2191
  },
1954
2192
  listSessions: function() { return Promise.resolve([]); },
1955
2193
  renameSession: function() { return Promise.resolve(); },
1956
- forkSession: function(threadId, opts) {
1957
- if (!_appServer || !_appServer.started) return Promise.resolve(null);
1958
- return _appServer.send("thread/fork", { threadId: threadId }, 30000).then(function(result) {
1959
- var newThreadId = (result && result.thread) ? result.thread.id : null;
1960
- if (!newThreadId) throw new Error("thread/fork did not return a new thread id");
1961
- return { sessionId: newThreadId };
2194
+ forkSession: function(threadId, callerOpts) {
2195
+ return runOnCallerInstance(callerOpts, "forkSession", function(inst) {
2196
+ return inst.appServer.send("thread/fork", { threadId: threadId }, 30000).then(function(result) {
2197
+ var newThreadId = (result && result.thread) ? result.thread.id : null;
2198
+ if (!newThreadId) throw new Error("thread/fork did not return a new thread id");
2199
+ return { sessionId: newThreadId };
2200
+ });
1962
2201
  });
1963
2202
  },
1964
- rollbackThread: function(threadId, numTurns) {
1965
- if (!_appServer || !_appServer.started) return Promise.resolve(null);
1966
- return _appServer.send("thread/rollback", { threadId: threadId, numTurns: numTurns }, 30000);
2203
+ // Rewinding a Codex thread in place is not offered: the app-server's
2204
+ // thread/rollback is gone from the supported releases, and its replacement
2205
+ // cannot be made safe against a turn appended while it runs. The method
2206
+ // stays because callers read it as "this adapter keeps its own threads";
2207
+ // it always rejects, so the caller leaves its own history as it was, and it
2208
+ // sends the server nothing.
2209
+ rollbackThread: function() {
2210
+ return Promise.reject(codexError("CODEX_REWIND_UNAVAILABLE", "Rewind is not available for Codex sessions yet"));
1967
2211
  },
1968
2212
 
1969
2213
  // Shutdown the app-server process
@@ -1971,13 +2215,19 @@ function createCodexAdapter(opts) {
1971
2215
  return beginShutdown(true);
1972
2216
  },
1973
2217
 
2218
+ // Ends every app-server that nothing is using and that has been quiet for
2219
+ // idleMs. Resolves true when at least one was ended.
1974
2220
  shutdownIfIdle: function(idleMs) {
1975
2221
  if (_shuttingDown || _shutdownPromise) return Promise.resolve(false);
1976
- if (_initPromise) return Promise.resolve(false);
1977
- if (!_appServer) return Promise.resolve(false);
1978
- if (_refCount > 0) return Promise.resolve(false);
1979
- if (Date.now() - _lastActiveAt < (idleMs || 0)) return Promise.resolve(false);
1980
- return beginShutdown(false).then(function() {
2222
+ var idle = [];
2223
+ _instances.forEach(function(inst) {
2224
+ if (inst.initPromise || inst.retirePromise || !inst.appServer) return;
2225
+ if (inst.refCount > 0) return;
2226
+ if (Date.now() - inst.lastActiveAt < (idleMs || 0)) return;
2227
+ idle.push(inst);
2228
+ });
2229
+ if (idle.length === 0) return Promise.resolve(false);
2230
+ return Promise.all(idle.map(function(inst) { return retireInstance(inst, false); })).then(function() {
1981
2231
  console.log("[yoke/codex] Reclaimed idle adapter for project " + (_slug || _cwd));
1982
2232
  return true;
1983
2233
  });
@@ -2001,5 +2251,6 @@ module.exports = {
2001
2251
  // lr-3ccc78 — exported so tests can exercise the real per-user home
2002
2252
  // resolution in discoverClaudeSkills directly, rather than driving it
2003
2253
  // indirectly through a full query/init round trip.
2004
- _test_discoverClaudeSkills: discoverClaudeSkills,
2254
+ _test_discoverClaudeSkills: discoverSkillFiles,
2255
+ _test_mergeConfig: mergeConfig,
2005
2256
  };