@clagentic/console 1.9.0 → 1.10.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/LICENSE +117 -12
  2. package/LICENSES/MIT-legacy.txt +22 -0
  3. package/LICENSES/README.md +15 -0
  4. package/README.md +8 -2
  5. package/bin/cli.js +30 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/audit.js +3 -2
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-check.js +138 -0
  10. package/lib/cli/daemon-launch.js +17 -17
  11. package/lib/config.js +32 -20
  12. package/lib/daemon-env-settings.js +84 -0
  13. package/lib/daemon-projects.js +38 -0
  14. package/lib/daemon.js +202 -158
  15. package/lib/drain.js +74 -17
  16. package/lib/env-compat.js +61 -0
  17. package/lib/extension-commands.js +45 -0
  18. package/lib/history-visibility.js +4 -0
  19. package/lib/idle-adapter-reaper.js +71 -0
  20. package/lib/link-trap.js +78 -0
  21. package/lib/lore-attestation.js +73 -0
  22. package/lib/mcp-local.js +8 -6
  23. package/lib/mcp-tool-input.js +116 -0
  24. package/lib/mcp-tool-schema.js +179 -0
  25. package/lib/memory-limits.js +61 -5
  26. package/lib/memory-setting-validate.js +65 -0
  27. package/lib/new-work-gate.js +47 -0
  28. package/lib/os-users.js +5 -3
  29. package/lib/project-access.js +139 -0
  30. package/lib/project-connection.js +23 -22
  31. package/lib/project-external-trigger.js +103 -10
  32. package/lib/project-file-scope.js +172 -0
  33. package/lib/project-file-watch.js +86 -61
  34. package/lib/project-filesystem.js +144 -128
  35. package/lib/project-git.js +119 -0
  36. package/lib/project-http.js +44 -28
  37. package/lib/project-loop.js +12 -5
  38. package/lib/project-mcp.js +53 -72
  39. package/lib/project-message-gate.js +70 -0
  40. package/lib/project-notifications.js +31 -4
  41. package/lib/project-prompt-responses.js +216 -0
  42. package/lib/project-sessions.js +164 -302
  43. package/lib/project-user-message.js +36 -11
  44. package/lib/project.js +189 -142
  45. package/lib/projects-dir.js +90 -0
  46. package/lib/prompt-access.js +22 -0
  47. package/lib/prompt-kinds/answer-limits.js +15 -0
  48. package/lib/prompt-kinds/ask-user.js +58 -0
  49. package/lib/prompt-kinds/codecs.js +97 -0
  50. package/lib/prompt-kinds/elicitation.js +77 -0
  51. package/lib/prompt-kinds/extension.js +39 -0
  52. package/lib/prompt-kinds/index.js +68 -0
  53. package/lib/prompt-kinds/permission.js +114 -0
  54. package/lib/prompt-kinds/plan.js +79 -0
  55. package/lib/prompt-kinds/tool-call.js +38 -0
  56. package/lib/prompt-registry.js +673 -0
  57. package/lib/public/app.js +1 -1
  58. package/lib/public/css/diagnostics.css +50 -0
  59. package/lib/public/css/input.css +17 -3
  60. package/lib/public/css/menus.css +10 -0
  61. package/lib/public/css/messages.css +5 -0
  62. package/lib/public/css/rewind.css +22 -0
  63. package/lib/public/index.html +4 -12
  64. package/lib/public/modules/app-connection.js +7 -0
  65. package/lib/public/modules/app-cursors.js +7 -5
  66. package/lib/public/modules/app-messages.js +45 -45
  67. package/lib/public/modules/app-notifications.js +47 -71
  68. package/lib/public/modules/app-panels.js +61 -58
  69. package/lib/public/modules/app-projects.js +2 -1
  70. package/lib/public/modules/app-rendering.js +4 -10
  71. package/lib/public/modules/diagnostics.js +60 -16
  72. package/lib/public/modules/filebrowser.js +18 -16
  73. package/lib/public/modules/history-visibility.js +4 -0
  74. package/lib/public/modules/mention.js +3 -2
  75. package/lib/public/modules/mode-options.js +38 -0
  76. package/lib/public/modules/project-settings.js +19 -8
  77. package/lib/public/modules/prompt-banner.js +78 -0
  78. package/lib/public/modules/prompt-card.js +201 -0
  79. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  80. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  81. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  82. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  83. package/lib/public/modules/prompt-kinds/index.js +18 -0
  84. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  85. package/lib/public/modules/prompt-kinds/package.json +3 -0
  86. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  87. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  88. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  89. package/lib/public/modules/prompt-state.js +142 -0
  90. package/lib/public/modules/prompts.js +134 -0
  91. package/lib/public/modules/rewind.js +4 -1
  92. package/lib/public/modules/server-settings.js +2 -4
  93. package/lib/public/modules/sidebar-mobile.js +19 -9
  94. package/lib/public/modules/sidebar-sessions.js +21 -14
  95. package/lib/public/modules/sticky-notes.js +3 -2
  96. package/lib/public/modules/team-panel.js +5 -4
  97. package/lib/public/modules/tools.js +67 -904
  98. package/lib/public/modules/vendor-picker.js +53 -0
  99. package/lib/public/modules/vendor-registry.js +133 -0
  100. package/lib/public/sw.js +3 -1
  101. package/lib/rc-migrate.js +44 -0
  102. package/lib/runtime-env-keys.js +109 -0
  103. package/lib/runtime-env.js +236 -0
  104. package/lib/sdk-bridge.js +290 -273
  105. package/lib/sdk-message-processor.js +125 -145
  106. package/lib/server-hub-sessions.js +13 -10
  107. package/lib/server-palette.js +28 -19
  108. package/lib/server.js +141 -113
  109. package/lib/service-install.js +96 -0
  110. package/lib/session-capabilities.js +76 -0
  111. package/lib/sessions.js +45 -28
  112. package/lib/users-permissions.js +9 -6
  113. package/lib/users.js +9 -0
  114. package/lib/utils.js +4 -2
  115. package/lib/vendor-auth.js +22 -0
  116. package/lib/vendor-registry-message.js +65 -0
  117. package/lib/ws-origin.js +99 -0
  118. package/lib/ws-schema.js +33 -22
  119. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  120. package/lib/yoke/adapters/claude-vendor.js +35 -0
  121. package/lib/yoke/adapters/claude-worker.js +55 -87
  122. package/lib/yoke/adapters/claude.js +156 -62
  123. package/lib/yoke/adapters/codex-capabilities.js +37 -0
  124. package/lib/yoke/adapters/codex-vendor.js +46 -0
  125. package/lib/yoke/adapters/codex.js +347 -156
  126. package/lib/yoke/adapters/effort-control.js +34 -0
  127. package/lib/yoke/adapters/permission-relay.js +58 -0
  128. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  129. package/lib/yoke/auth-checks.js +104 -0
  130. package/lib/yoke/capabilities.js +49 -0
  131. package/lib/yoke/codex-app-server.js +23 -5
  132. package/lib/yoke/env-ownership.js +40 -0
  133. package/lib/yoke/index.js +67 -173
  134. package/lib/yoke/install-probe.js +121 -0
  135. package/lib/yoke/instructions.js +7 -11
  136. package/lib/yoke/interface.js +199 -3
  137. package/lib/yoke/package.json +1 -1
  138. package/lib/yoke/provider-credentials.js +96 -0
  139. package/lib/yoke/registry.js +340 -0
  140. package/package.json +12 -8
  141. package/scripts/check-sdk-lock-drift.js +160 -0
  142. package/scripts/check-test-count.js +76 -1
  143. package/scripts/postinstall.js +218 -136
  144. package/scripts/prompt-harness-history.js +202 -0
  145. package/scripts/verify-installed.js +67 -0
  146. package/lib/sdk-permission-ownership.js +0 -136
@@ -9,6 +9,8 @@ var { CodexAppServer } = require("../codex-app-server");
9
9
  var { discoverWorkflows } = require("../../sdk-workflow-discovery");
10
10
  var { discoverSkillsWithMeta, resolveContainedSkillDir } = require("../../sdk-skill-discovery");
11
11
  var codexLocalImage = require("../codex-local-image");
12
+ var runtimeEnv = require("../../runtime-env");
13
+ var codexCapabilities = require("./codex-capabilities").codexCapabilities;
12
14
 
13
15
  // --- Claude skill discovery ---
14
16
  // Finds Claude skills in ~/.claude/skills/ and <cwd>/.claude/skills/
@@ -644,7 +646,7 @@ function _test_resolveModel(queryOpts) {
644
646
  // Selects the model used for background title generation.
645
647
  //
646
648
  // The live "model/list" RPC's Model objects (see the model/list handler
647
- // below, and _cachedModels' shape) carry no cost-tier field — only
649
+ // below, and the shape of an instance's models) carry no cost-tier field — only
648
650
  // value/displayName/supportedEffortLevels/isLatest ("isLatest" means "not
649
651
  // superseded by an upgrade", not "cheap"). There is no robust signal in the
650
652
  // live catalog to identify a mini/small-tier model, and this codebase does
@@ -652,8 +654,8 @@ function _test_resolveModel(queryOpts) {
652
654
  // string matching was deliberately removed elsewhere — see the Context
653
655
  // meter section of docs/guides/architecture.md).
654
656
  //
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
657
+ // So titling — a trivial 3-8 word job — falls back to the server's default
658
+ // model, the adapter's only non-staling model identifier (refreshed from the live
657
659
  // model/list response). This is a deliberate cost/staleness tradeoff: every
658
660
  // auto-title now runs on the user's main model instead of a cheaper
659
661
  // mini-tier one, in exchange for auto-titling never breaking silently when
@@ -757,7 +759,17 @@ function createCodexQueryHandle(appServer, queryOpts) {
757
759
  }
758
760
  }
759
761
 
762
+ // JSON-RPC request id -> AbortController for an approval still awaiting
763
+ // the operator. The daemon-side prompt ends with it when the app-server
764
+ // clears the request without our answer (serverRequest/resolved for an id
765
+ // we never answered: turn start, completion or interruption) or the query
766
+ // ends.
767
+ var approvalAborts = {};
768
+
760
769
  function endIterator() {
770
+ // The query is over: no approval still awaiting the operator can be
771
+ // delivered to the app-server any more.
772
+ Object.keys(approvalAborts).forEach(function (key) { approvalAborts[key].abort(); });
761
773
  iteratorDone = true;
762
774
  if (eventWaiting) {
763
775
  var resolve = eventWaiting;
@@ -792,6 +804,26 @@ function createCodexQueryHandle(appServer, queryOpts) {
792
804
  // Track whether this turn is still active (waiting for turn/completed or turn/failed)
793
805
  var turnResolve = null;
794
806
 
807
+ // Asks the daemon about one server request and answers it; a request the
808
+ // app-server already cleared takes no answer.
809
+ function awaitApproval(rpcId, ask, onAnswer, onError) {
810
+ var key = String(rpcId);
811
+ var ac = new AbortController();
812
+ approvalAborts[key] = ac;
813
+ var pending;
814
+ try {
815
+ pending = Promise.resolve(ask(ac.signal));
816
+ } catch (e) {
817
+ pending = Promise.reject(e);
818
+ }
819
+ pending
820
+ .then(function (value) { if (!ac.signal.aborted) onAnswer(value); })
821
+ .catch(function (err) { if (!ac.signal.aborted) onError(err); })
822
+ .finally(function () {
823
+ if (approvalAborts[key] === ac) delete approvalAborts[key];
824
+ });
825
+ }
826
+
795
827
  // --- App-server event handler ---
796
828
  function handleServerEvent(msg) {
797
829
  var method = msg.method;
@@ -800,6 +832,11 @@ function createCodexQueryHandle(appServer, queryOpts) {
800
832
  // Ignore events from other threads (app-server is shared across sessions)
801
833
  if (params.threadId && state.threadId && params.threadId !== state.threadId) return;
802
834
 
835
+ if (method === "serverRequest/resolved" && params.requestId != null) {
836
+ var cleared = approvalAborts[String(params.requestId)];
837
+ if (cleared) cleared.abort();
838
+ }
839
+
803
840
  // After abort, only let turn-ending events through
804
841
  if (isCancelled() && method !== "turn/completed" && method !== "turn/failed" && method !== "serverRequest/resolved" && method !== "thread/status/changed") return;
805
842
 
@@ -829,11 +866,13 @@ function createCodexQueryHandle(appServer, queryOpts) {
829
866
  if (isAllowAll()) {
830
867
  appServer.respond(msg.id, { decision: "accept" });
831
868
  } else if (canUseTool) {
832
- canUseTool("Bash", { command: cmdParams.command }, {}).then(function(decision) {
869
+ awaitApproval(msg.id, function (signal) {
870
+ return canUseTool("Bash", { command: cmdParams.command }, { signal: signal });
871
+ }, function (decision) {
833
872
  var approved = isApproved(decision);
834
873
  // Response must be wrapped in { decision: ... } object per app-server protocol
835
874
  appServer.respond(msg.id, { decision: approved ? "accept" : "decline" });
836
- }).catch(function(err) {
875
+ }, function (err) {
837
876
  console.error("[yoke/codex] canUseTool error:", err.message);
838
877
  appServer.respond(msg.id, { decision: "decline" });
839
878
  });
@@ -855,9 +894,11 @@ function createCodexQueryHandle(appServer, queryOpts) {
855
894
  appServer.respond(msg.id, { decision: "accept" });
856
895
  } else if (canUseTool) {
857
896
  var changeInfo = (fcParams.changes || []).map(function(c) { return c.kind + " " + c.path; }).join(", ");
858
- canUseTool("Edit", { changes: changeInfo, path: fcParams.path }, {}).then(function(decision) {
897
+ awaitApproval(msg.id, function (signal) {
898
+ return canUseTool("Edit", { changes: changeInfo, path: fcParams.path }, { signal: signal });
899
+ }, function (decision) {
859
900
  appServer.respond(msg.id, { decision: isApproved(decision) ? "accept" : "decline" });
860
- }).catch(function(err) {
901
+ }, function (err) {
861
902
  console.error("[yoke/codex] canUseTool error:", err.message);
862
903
  appServer.respond(msg.id, { decision: "decline" });
863
904
  });
@@ -905,18 +946,20 @@ function createCodexQueryHandle(appServer, queryOpts) {
905
946
  }
906
947
  request.requestedSchema = schema;
907
948
  }
908
- onElicitation(request, {
909
- signal: { addEventListener: function() {} },
910
- }).then(function(result) {
949
+ awaitApproval(msg.id, function (signal) {
950
+ return onElicitation(request, { signal: signal });
951
+ }, function (result) {
911
952
  appServer.respond(msg.id, result || { action: "reject" });
912
- }).catch(function(err) {
953
+ }, function (err) {
913
954
  console.error("[yoke/codex] elicitation_response send failed:", err.message || err);
914
955
  appServer.respond(msg.id, { action: "reject" });
915
956
  });
916
957
  } else if (canUseTool) {
917
- canUseTool("mcp__" + (mcpParams.serverName || "unknown") + "__" + (mcpMeta.tool || "call"), mcpParams, {}).then(function(decision) {
958
+ awaitApproval(msg.id, function (signal) {
959
+ return canUseTool("mcp__" + (mcpParams.serverName || "unknown") + "__" + (mcpMeta.tool || "call"), mcpParams, { signal: signal });
960
+ }, function (decision) {
918
961
  appServer.respond(msg.id, { action: isApproved(decision) ? "accept" : "decline" });
919
- }).catch(function(err) {
962
+ }, function (err) {
920
963
  console.error("[yoke/codex] MCP canUseTool error:", err.message);
921
964
  appServer.respond(msg.id, { action: "decline" });
922
965
  });
@@ -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",
@@ -1389,43 +1434,91 @@ function createCodexAdapter(opts) {
1389
1434
  var _cwd = (opts && opts.cwd) || process.cwd();
1390
1435
  var _slug = (opts && opts.slug) || "";
1391
1436
  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;
1437
+ // One app-server per effective environment. Everything that depends on the
1438
+ // environment (the process, its model list and default model, the threads it
1439
+ // holds, its init) lives on the instance, so an operation is served only by
1440
+ // the server started with the environment the caller names, and one user's
1441
+ // variables (an endpoint, a credential) or endpoint models never reach
1442
+ // another user's turn. Keyed by a digest of that environment (never logged,
1443
+ // values are secrets); "" is the daemon's own environment with nothing added.
1444
+ var _instances = new Map();
1399
1445
  var _shutdownPromise = null;
1400
- var _refCount = 0;
1401
- var _lastActiveAt = Date.now();
1402
- var _shuttingDown = false;
1403
- var _activeQueries = [];
1446
+ var _shuttingDown = false; // shutdown() of the whole adapter is running
1447
+
1448
+ function createInstance(fingerprint) {
1449
+ return {
1450
+ fingerprint: fingerprint,
1451
+ appServer: null,
1452
+ initPromise: null,
1453
+ retirePromise: null,
1454
+ refCount: 0,
1455
+ lastActiveAt: Date.now(),
1456
+ activeQueries: [],
1457
+ models: [],
1458
+ // Fallback-only (lr-d91ecf): the value before init() reads the live
1459
+ // model/list RPC; overwritten as soon as that succeeds.
1460
+ defaultModel: FALLBACK_DEFAULT_MODEL,
1461
+ };
1462
+ }
1463
+
1464
+ // The environment the app-server process is started with, or undefined when
1465
+ // it is to inherit the daemon's own: the daemon's environment with the
1466
+ // Settings variables laid over it, then the adapter options' credentials.
1467
+ function serverEnvFor(effectiveOpts) {
1468
+ var env;
1469
+ if (runtimeEnv.hasOverlay(effectiveOpts.runtimeEnv)) {
1470
+ env = runtimeEnv.composeRuntimeEnv(process.env, effectiveOpts.runtimeEnv);
1471
+ }
1472
+ var co = effectiveOpts.adapterOptions && effectiveOpts.adapterOptions.CODEX;
1473
+ if (co && co.apiKey) env = Object.assign({}, env || {}, { OPENAI_API_KEY: co.apiKey });
1474
+ if (co && co.baseUrl) env = Object.assign({}, env || {}, { OPENAI_BASE_URL: co.baseUrl });
1475
+ return env;
1476
+ }
1477
+
1478
+ function fingerprintOf(serverEnv) {
1479
+ return serverEnv ? runtimeEnv.envSignature(serverEnv) : "";
1480
+ }
1481
+
1482
+ // The one lookup of the server an operation runs on, used by init, queries,
1483
+ // model lists, titles, forks and rollbacks. The caller always states its
1484
+ // environment: runtimeEnv is the settings overlay, or null for none (the
1485
+ // daemon's own environment). Absent is an error, never a guess at another
1486
+ // caller's environment.
1487
+ function fingerprintFor(callerOpts, operation) {
1488
+ if (!callerOpts || callerOpts.runtimeEnv === undefined) {
1489
+ throw new Error("[yoke/codex] " + operation + " needs runtimeEnv (null when no settings apply)");
1490
+ }
1491
+ return fingerprintOf(serverEnvFor(Object.assign({}, _defaultInitOpts, callerOpts)));
1492
+ }
1404
1493
 
1405
- function updateLastActiveAt() {
1406
- _lastActiveAt = Date.now();
1494
+ function updateLastActiveAt(inst) {
1495
+ inst.lastActiveAt = Date.now();
1407
1496
  }
1408
1497
 
1409
- function registerActiveQuery(entry) {
1410
- _activeQueries.push(entry);
1498
+ function registerActiveQuery(inst, entry) {
1499
+ inst.activeQueries.push(entry);
1411
1500
  }
1412
1501
 
1413
- function removeActiveQuery(entry) {
1502
+ function removeActiveQuery(inst, entry) {
1414
1503
  var next = [];
1415
- for (var i = 0; i < _activeQueries.length; i++) {
1416
- if (_activeQueries[i] !== entry) next.push(_activeQueries[i]);
1504
+ for (var i = 0; i < inst.activeQueries.length; i++) {
1505
+ if (inst.activeQueries[i] !== entry) next.push(inst.activeQueries[i]);
1417
1506
  }
1418
- _activeQueries = next;
1507
+ inst.activeQueries = next;
1419
1508
  }
1420
1509
 
1421
- function decrementRefCount() {
1422
- if (_refCount > 0) {
1423
- _refCount--;
1510
+ function decrementRefCount(inst) {
1511
+ if (inst.refCount > 0) {
1512
+ inst.refCount--;
1424
1513
  } else {
1425
1514
  console.error("[yoke/codex] refCount negative, bug!");
1426
- _refCount = 0;
1515
+ inst.refCount = 0;
1427
1516
  }
1428
- updateLastActiveAt();
1517
+ updateLastActiveAt(inst);
1518
+ }
1519
+
1520
+ function isStarted(inst) {
1521
+ return !!(inst && inst.appServer && inst.appServer.started);
1429
1522
  }
1430
1523
 
1431
1524
  // Build the enriched slash_commands array from skill names and workflow discovery.
@@ -1476,41 +1569,32 @@ function createCodexAdapter(opts) {
1476
1569
  return combined;
1477
1570
  }
1478
1571
 
1479
- function buildReadyResponse(skillNames, cwd, homeOverride) {
1572
+ function buildReadyResponse(inst, skillNames, cwd, homeOverride) {
1480
1573
  return {
1481
- models: _cachedModels,
1482
- defaultModel: _defaultModel,
1574
+ models: inst.models.slice(),
1575
+ defaultModel: inst.defaultModel,
1483
1576
  skills: skillNames || [],
1484
1577
  slashCommands: buildEnrichedSlashCommands(skillNames, cwd, homeOverride),
1485
1578
  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
- },
1579
+ capabilities: codexCapabilities(),
1497
1580
  };
1498
1581
  }
1499
1582
 
1500
- function clearRuntimeState() {
1501
- _appServer = null;
1502
- _initPromise = null;
1503
- _cachedModels = [];
1504
- _refCount = 0;
1505
- _activeQueries = [];
1506
- updateLastActiveAt();
1583
+ function dropInstance(inst) {
1584
+ if (_instances.get(inst.fingerprint) === inst) _instances.delete(inst.fingerprint);
1585
+ inst.appServer = null;
1586
+ inst.initPromise = null;
1587
+ inst.refCount = 0;
1588
+ inst.activeQueries = [];
1589
+ inst.models = [];
1590
+ updateLastActiveAt(inst);
1507
1591
  }
1508
1592
 
1509
- function waitForRefCount(targetCount, timeoutMs) {
1593
+ function waitForRefCount(inst, targetCount, timeoutMs) {
1510
1594
  var deadline = Date.now() + (timeoutMs || 5000);
1511
1595
  return new Promise(function(resolve) {
1512
1596
  function tick() {
1513
- if (_refCount <= targetCount) {
1597
+ if (inst.refCount <= targetCount) {
1514
1598
  resolve(true);
1515
1599
  return;
1516
1600
  }
@@ -1524,11 +1608,11 @@ function createCodexAdapter(opts) {
1524
1608
  });
1525
1609
  }
1526
1610
 
1527
- function stopAppServer(deadlineMs) {
1528
- var proc = _appServer && _appServer.proc ? _appServer.proc : null;
1529
- if (!_appServer) return Promise.resolve(true);
1611
+ function stopAppServer(appServer, deadlineMs) {
1612
+ var proc = appServer && appServer.proc ? appServer.proc : null;
1613
+ if (!appServer) return Promise.resolve(true);
1530
1614
  try {
1531
- _appServer.stop();
1615
+ appServer.stop();
1532
1616
  } catch (e) {
1533
1617
  console.error("[yoke/codex] App-server stop error:", e.message || e);
1534
1618
  }
@@ -1538,59 +1622,124 @@ function createCodexAdapter(opts) {
1538
1622
  if (!exited) {
1539
1623
  try {
1540
1624
  proc.kill("SIGKILL");
1541
- } catch (e) {}
1625
+ } catch (e) {
1626
+ console.error("[yoke/codex] Could not kill the app-server process:", e.message || e);
1627
+ }
1542
1628
  }
1543
1629
  return exited;
1544
1630
  });
1545
1631
  }
1546
1632
 
1547
- function beginShutdown(force, idleMs) {
1548
- if (_shutdownPromise) return _shutdownPromise;
1549
- if (_shuttingDown) return null;
1550
-
1551
- _shuttingDown = true;
1633
+ // Ends one app-server. force aborts the queries still using it; without it
1634
+ // the caller has already established that none is. Resolves once the process
1635
+ // is gone and the instance has been dropped.
1636
+ function retireInstance(inst, force) {
1637
+ if (inst.retirePromise) return inst.retirePromise;
1552
1638
 
1553
- _shutdownPromise = (async function() {
1639
+ inst.retirePromise = (async function() {
1554
1640
  var deadline = Date.now() + 5000;
1555
- var shouldAbort = !!force;
1556
1641
 
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) {}
1642
+ if (inst.initPromise) {
1643
+ await Promise.race([
1644
+ inst.initPromise.then(null, function(err) {
1645
+ console.error("[yoke/codex] App-server init failed while it was being retired:", err && err.message || err);
1646
+ return null;
1647
+ }),
1648
+ waitMs(Math.max(0, deadline - Date.now())),
1649
+ ]);
1564
1650
  }
1565
1651
 
1566
- if (shouldAbort && _activeQueries.length > 0) {
1567
- var active = _activeQueries.slice();
1652
+ if (force && inst.activeQueries.length > 0) {
1653
+ var active = inst.activeQueries.slice();
1568
1654
  for (var i = 0; i < active.length; i++) {
1569
1655
  try {
1570
1656
  if (active[i] && active[i].abort) active[i].abort();
1571
- } catch (e) {}
1657
+ } catch (e) {
1658
+ console.error("[yoke/codex] Could not abort a query:", e.message || e);
1659
+ }
1572
1660
  }
1573
- await waitForRefCount(0, Math.max(0, deadline - Date.now()));
1661
+ await waitForRefCount(inst, 0, Math.max(0, deadline - Date.now()));
1574
1662
  }
1575
1663
 
1576
- if (_appServer) {
1577
- await stopAppServer(deadline);
1664
+ if (inst.appServer) {
1665
+ await stopAppServer(inst.appServer, deadline);
1578
1666
  }
1579
1667
 
1580
- clearRuntimeState();
1581
- _shuttingDown = false;
1582
- _shutdownPromise = null;
1668
+ dropInstance(inst);
1583
1669
  return true;
1584
1670
  })().catch(function(err) {
1585
- clearRuntimeState();
1586
- _shuttingDown = false;
1587
- _shutdownPromise = null;
1671
+ dropInstance(inst);
1588
1672
  throw err;
1589
1673
  });
1590
1674
 
1675
+ return inst.retirePromise;
1676
+ }
1677
+
1678
+ // Waits for an instance that is being retired, so the caller can start a
1679
+ // fresh one. A failed retirement is reported where it was started.
1680
+ function afterRetire(inst) {
1681
+ return inst.retirePromise.then(null, function(err) {
1682
+ console.error("[yoke/codex] Retiring an app-server failed:", err && err.message || err);
1683
+ });
1684
+ }
1685
+
1686
+ // The adapter-wide shutdown: every instance.
1687
+ function beginShutdown(force) {
1688
+ if (_shutdownPromise) return _shutdownPromise;
1689
+
1690
+ _shuttingDown = true;
1691
+
1692
+ _shutdownPromise = (async function() {
1693
+ try {
1694
+ var results = await Promise.allSettled(Array.from(_instances.values()).map(function(inst) {
1695
+ return retireInstance(inst, force);
1696
+ }));
1697
+ var failed = results.filter(function(r) { return r.status === "rejected"; })[0];
1698
+ if (failed) throw failed.reason;
1699
+ return true;
1700
+ } finally {
1701
+ _shuttingDown = false;
1702
+ _shutdownPromise = null;
1703
+ }
1704
+ })();
1705
+
1591
1706
  return _shutdownPromise;
1592
1707
  }
1593
1708
 
1709
+ // The started, initialized instance for a fingerprint, starting (or waiting
1710
+ // out the retirement of) one when there is none. Never hands back a server
1711
+ // that was started with a different environment.
1712
+ async function acquireInstance(queryOpts, fingerprint) {
1713
+ for (var attempt = 0; attempt < 3; attempt++) {
1714
+ if (_shuttingDown) throw createShutdownError();
1715
+ var inst = _instances.get(fingerprint);
1716
+ if (inst && inst.retirePromise) {
1717
+ await afterRetire(inst);
1718
+ continue;
1719
+ }
1720
+ if (isStarted(inst) && !inst.initPromise) return inst;
1721
+ await adapter.init(queryOpts);
1722
+ }
1723
+ throw new Error("[yoke/codex] Adapter not initialized. Call init() first.");
1724
+ }
1725
+
1726
+ // Runs a thread operation (fork, rollback) on the server for the environment
1727
+ // the caller states, started if it was reaped: the same lookup as every other
1728
+ // entry point. A caller that states no environment is refused, and a server
1729
+ // that cannot operate on the thread makes the operation throw.
1730
+ // The server counts as in use meanwhile, so the idle reclaim leaves it alone.
1731
+ async function runOnCallerInstance(callerOpts, operation, run) {
1732
+ var wanted = fingerprintFor(callerOpts, operation);
1733
+ var inst = await acquireInstance(callerOpts, wanted);
1734
+ inst.refCount++;
1735
+ try {
1736
+ return await run(inst);
1737
+ } finally {
1738
+ // A server dropped meanwhile has already had its count reset.
1739
+ if (inst.refCount > 0) decrementRefCount(inst);
1740
+ }
1741
+ }
1742
+
1594
1743
  var adapter = {
1595
1744
  vendor: "codex",
1596
1745
 
@@ -1599,24 +1748,43 @@ function createCodexAdapter(opts) {
1599
1748
  return Promise.reject(createShutdownError());
1600
1749
  }
1601
1750
 
1602
- var effectiveInitOpts = Object.assign({}, _defaultInitOpts, initOpts || {});
1751
+ var fingerprint;
1752
+ try {
1753
+ fingerprint = fingerprintFor(initOpts, "init");
1754
+ } catch (e) {
1755
+ return Promise.reject(e);
1756
+ }
1757
+ var effectiveInitOpts = Object.assign({}, _defaultInitOpts, initOpts);
1758
+ var serverEnv = serverEnvFor(effectiveInitOpts);
1759
+ var inst = _instances.get(fingerprint);
1760
+
1761
+ if (inst && inst.retirePromise) {
1762
+ return afterRetire(inst).then(function() { return adapter.init(initOpts); });
1763
+ }
1603
1764
 
1604
- // Already initialized - return cached result
1605
- if (_appServer && _appServer.started && _cachedModels.length > 0) {
1606
- return Promise.resolve(buildReadyResponse([], _cwd));
1765
+ // Already initialized: this server's own models and default model
1766
+ if (isStarted(inst) && !inst.initPromise && inst.models.length > 0) {
1767
+ return Promise.resolve(buildReadyResponse(inst, [], _cwd));
1607
1768
  }
1608
1769
 
1609
1770
  // Deduplicate concurrent init calls
1610
- if (_initPromise) return _initPromise;
1771
+ if (inst && inst.initPromise) return inst.initPromise;
1611
1772
 
1612
- _initPromise = (async function() {
1773
+ if (!inst) {
1774
+ inst = createInstance(fingerprint);
1775
+ _instances.set(fingerprint, inst);
1776
+ }
1777
+
1778
+ var initPromise = (async function() {
1613
1779
  var serverOpts = { cwd: _cwd };
1614
1780
 
1781
+ // The app-server is started with the complete environment: the
1782
+ // daemon's own with the Settings variables laid over it.
1783
+ if (serverEnv) serverOpts.env = serverEnv;
1784
+
1615
1785
  // Extract adapter options
1616
1786
  if (effectiveInitOpts && effectiveInitOpts.adapterOptions && effectiveInitOpts.adapterOptions.CODEX) {
1617
1787
  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 });
1620
1788
  if (co.config) serverOpts.config = co.config;
1621
1789
  }
1622
1790
 
@@ -1677,17 +1845,18 @@ function createCodexAdapter(opts) {
1677
1845
  }
1678
1846
 
1679
1847
  // Spawn and initialize app-server
1680
- _appServer = new CodexAppServer(null, serverOpts);
1681
- await _appServer.start();
1848
+ var server = new CodexAppServer(null, serverOpts);
1849
+ inst.appServer = server;
1850
+ await server.start();
1682
1851
 
1683
- await _appServer.send("initialize", {
1852
+ await server.send("initialize", {
1684
1853
  clientInfo: { name: "clagentic", title: "Clagentic: Console", version: "1.0.0" },
1685
1854
  capabilities: { experimentalApi: true },
1686
1855
  });
1687
- _appServer.notify("initialized", {});
1856
+ server.notify("initialized", {});
1688
1857
 
1689
- if (_shuttingDown) {
1690
- await stopAppServer(Date.now() + 1000);
1858
+ if (_shuttingDown || inst.retirePromise) {
1859
+ await stopAppServer(server, Date.now() + 1000);
1691
1860
  throw createShutdownError();
1692
1861
  }
1693
1862
 
@@ -1696,10 +1865,10 @@ function createCodexAdapter(opts) {
1696
1865
  // supportedReasoningEfforts, and upgrade (non-null when a newer model exists).
1697
1866
  // Fall back to CODEX_DEFAULT_MODELS if the call fails or returns nothing.
1698
1867
  try {
1699
- var modelListResult = await _appServer.send("model/list", {}, 10000);
1868
+ var modelListResult = await server.send("model/list", {}, 10000);
1700
1869
  // Response shape: { data: [Model, ...], nextCursor }
1701
1870
  if (modelListResult && Array.isArray(modelListResult.data) && modelListResult.data.length > 0) {
1702
- _cachedModels = modelListResult.data
1871
+ inst.models = modelListResult.data
1703
1872
  .filter(function(m) { return !m.hidden; })
1704
1873
  .map(function(m) {
1705
1874
  var efforts = Array.isArray(m.supportedReasoningEfforts)
@@ -1722,17 +1891,17 @@ function createCodexAdapter(opts) {
1722
1891
  break;
1723
1892
  }
1724
1893
  }
1725
- _defaultModel = (defaultEntry && (defaultEntry.model || defaultEntry.id)) || _defaultModel;
1726
- console.log("[codex] model/list: " + _cachedModels.length + " models, default=" + _defaultModel);
1894
+ inst.defaultModel = (defaultEntry && (defaultEntry.model || defaultEntry.id)) || inst.defaultModel;
1895
+ console.log("[codex] model/list: " + inst.models.length + " models, default=" + inst.defaultModel);
1727
1896
  } else {
1728
1897
  throw new Error("empty or missing data");
1729
1898
  }
1730
1899
  } catch (e) {
1731
1900
  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)
1901
+ inst.models = CODEX_DEFAULT_MODELS.slice();
1902
+ // inst.defaultModel stays FALLBACK_DEFAULT_MODEL (set at creation)
1734
1903
  }
1735
- console.log("[codex] App-server initialized, models: " + _cachedModels.map(function(m) { return m.value; }).join(", "));
1904
+ console.log("[codex] App-server initialized, models: " + inst.models.map(function(m) { return m.value; }).join(", "));
1736
1905
 
1737
1906
  // Discover skills: built-in Codex skills + Claude skills
1738
1907
  // lr-3ccc78 — resolve the session owner's home so a shared
@@ -1748,7 +1917,7 @@ function createCodexAdapter(opts) {
1748
1917
  }
1749
1918
  var claudeSkillsDir = require("path").join(claudeSkillsHome, ".claude", "skills");
1750
1919
  var extraRoots = _cwd ? [{ cwd: _cwd, extraUserRoots: [claudeSkillsDir] }] : [];
1751
- var skillsResult = await _appServer.send("skills/list", {
1920
+ var skillsResult = await server.send("skills/list", {
1752
1921
  cwds: _cwd ? [_cwd] : [],
1753
1922
  forceReload: true,
1754
1923
  perCwdExtraUserRoots: extraRoots,
@@ -1779,22 +1948,36 @@ function createCodexAdapter(opts) {
1779
1948
  console.error("[codex] Failed to discover skills:", e.message);
1780
1949
  }
1781
1950
 
1782
- if (_shuttingDown) {
1783
- await stopAppServer(Date.now() + 1000);
1951
+ if (_shuttingDown || inst.retirePromise) {
1952
+ await stopAppServer(server, Date.now() + 1000);
1784
1953
  throw createShutdownError();
1785
1954
  }
1786
1955
 
1787
- _initPromise = null;
1788
- updateLastActiveAt();
1956
+ inst.initPromise = null;
1957
+ updateLastActiveAt(inst);
1789
1958
 
1790
- return buildReadyResponse(skillNames, _cwd, initHomeOverride);
1959
+ return buildReadyResponse(inst, skillNames, _cwd, initHomeOverride);
1791
1960
  })();
1792
1961
 
1793
- return _initPromise;
1962
+ // A start that fails leaves nothing behind, so the next call starts again
1963
+ // instead of being handed this rejection.
1964
+ inst.initPromise = initPromise.then(null, function(err) {
1965
+ if (_instances.get(fingerprint) === inst && !inst.retirePromise) {
1966
+ var failedServer = inst.appServer;
1967
+ dropInstance(inst);
1968
+ return stopAppServer(failedServer, Date.now() + 1000).then(function() { throw err; });
1969
+ }
1970
+ throw err;
1971
+ });
1972
+ return inst.initPromise;
1794
1973
  },
1795
1974
 
1796
- supportedModels: function() {
1797
- return Promise.resolve(_cachedModels.slice());
1975
+ // The model list of the server for the caller's environment (started when
1976
+ // there is none). callerOpts.runtimeEnv is required, null meaning no
1977
+ // settings; a list is never served to an environment it was not read for.
1978
+ supportedModels: async function(callerOpts) {
1979
+ var inst = await acquireInstance(callerOpts, fingerprintFor(callerOpts, "supportedModels"));
1980
+ return inst.models.slice();
1798
1981
  },
1799
1982
 
1800
1983
  createToolServer: function(def) {
@@ -1808,20 +1991,13 @@ function createCodexAdapter(opts) {
1808
1991
  if (_shuttingDown) {
1809
1992
  throw createShutdownError();
1810
1993
  }
1994
+ queryOpts = queryOpts || {};
1811
1995
 
1812
- if (!_appServer || !_appServer.started) {
1813
- await adapter.init(queryOpts || {});
1814
- }
1815
-
1816
- if (_shuttingDown) {
1817
- throw createShutdownError();
1818
- }
1996
+ // The query runs on the app-server started with its own environment:
1997
+ // another query's server, with another environment, is never borrowed.
1998
+ var inst = await acquireInstance(queryOpts, fingerprintFor(queryOpts, "createQuery"));
1819
1999
 
1820
- if (!_appServer || !_appServer.started) {
1821
- throw new Error("[yoke/codex] Adapter not initialized. Call init() first.");
1822
- }
1823
-
1824
- var model = queryOpts.model || _defaultModel;
2000
+ var model = queryOpts.model || inst.defaultModel;
1825
2001
  var ac = queryOpts.abortController || new AbortController();
1826
2002
  var activeEntry = {
1827
2003
  abort: function() {
@@ -1836,7 +2012,7 @@ function createCodexAdapter(opts) {
1836
2012
 
1837
2013
  var handleOpts = {
1838
2014
  model: model,
1839
- defaultModel: _defaultModel,
2015
+ defaultModel: inst.defaultModel,
1840
2016
  cwd: queryOpts.cwd || _cwd,
1841
2017
  systemPrompt: queryOpts.systemPrompt || "",
1842
2018
  abortController: ac,
@@ -1875,19 +2051,19 @@ function createCodexAdapter(opts) {
1875
2051
 
1876
2052
  console.log("[yoke/codex] createQuery: model=" + model + " approval=" + handleOpts.approvalPolicy + " sandbox=" + handleOpts.sandboxMode);
1877
2053
 
1878
- _refCount++;
1879
- registerActiveQuery(activeEntry);
2054
+ inst.refCount++;
2055
+ registerActiveQuery(inst, activeEntry);
1880
2056
 
1881
2057
  var handle;
1882
2058
  try {
1883
2059
  handleOpts.onFinished = function() {
1884
- removeActiveQuery(activeEntry);
1885
- decrementRefCount();
2060
+ removeActiveQuery(inst, activeEntry);
2061
+ decrementRefCount(inst);
1886
2062
  };
1887
- handle = createCodexQueryHandle(_appServer, handleOpts);
2063
+ handle = createCodexQueryHandle(inst.appServer, handleOpts);
1888
2064
  } catch (e) {
1889
- removeActiveQuery(activeEntry);
1890
- decrementRefCount();
2065
+ removeActiveQuery(inst, activeEntry);
2066
+ decrementRefCount(inst);
1891
2067
  throw e;
1892
2068
  }
1893
2069
 
@@ -1913,12 +2089,17 @@ function createCodexAdapter(opts) {
1913
2089
  prompt += "User message " + (i + 1) + ": " + messages[i] + "\n";
1914
2090
  }
1915
2091
  var ac = new AbortController();
2092
+ // The title is generated on the server of the caller's environment, and
2093
+ // with that server's own default model.
2094
+ var envOpts = { runtimeEnv: opts && opts.runtimeEnv };
2095
+ var titleInst = await acquireInstance(envOpts, fingerprintFor(envOpts, "generateTitle"));
1916
2096
  var handle = await adapter.createQuery({
1917
2097
  cwd: (opts && opts.cwd) || _cwd,
1918
2098
  systemPrompt: systemPrompt,
1919
- model: resolveTitleModel(_defaultModel),
2099
+ model: resolveTitleModel(titleInst.defaultModel),
1920
2100
  abortController: ac,
1921
2101
  canUseTool: function() { return Promise.resolve({ behavior: "deny", message: "No tools." }); },
2102
+ runtimeEnv: envOpts.runtimeEnv,
1922
2103
  });
1923
2104
  handle.pushMessage(prompt);
1924
2105
  var title = "";
@@ -1953,17 +2134,21 @@ function createCodexAdapter(opts) {
1953
2134
  },
1954
2135
  listSessions: function() { return Promise.resolve([]); },
1955
2136
  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 };
2137
+ forkSession: function(threadId, callerOpts) {
2138
+ return runOnCallerInstance(callerOpts, "forkSession", function(inst) {
2139
+ return inst.appServer.send("thread/fork", { threadId: threadId }, 30000).then(function(result) {
2140
+ var newThreadId = (result && result.thread) ? result.thread.id : null;
2141
+ if (!newThreadId) throw new Error("thread/fork did not return a new thread id");
2142
+ return { sessionId: newThreadId };
2143
+ });
1962
2144
  });
1963
2145
  },
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);
2146
+ // Rejects when the thread could not be rolled back; the caller must not
2147
+ // trim its own history in that case.
2148
+ rollbackThread: function(threadId, numTurns, callerOpts) {
2149
+ return runOnCallerInstance(callerOpts, "rollbackThread", function(inst) {
2150
+ return inst.appServer.send("thread/rollback", { threadId: threadId, numTurns: numTurns }, 30000);
2151
+ });
1967
2152
  },
1968
2153
 
1969
2154
  // Shutdown the app-server process
@@ -1971,13 +2156,19 @@ function createCodexAdapter(opts) {
1971
2156
  return beginShutdown(true);
1972
2157
  },
1973
2158
 
2159
+ // Ends every app-server that nothing is using and that has been quiet for
2160
+ // idleMs. Resolves true when at least one was ended.
1974
2161
  shutdownIfIdle: function(idleMs) {
1975
2162
  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() {
2163
+ var idle = [];
2164
+ _instances.forEach(function(inst) {
2165
+ if (inst.initPromise || inst.retirePromise || !inst.appServer) return;
2166
+ if (inst.refCount > 0) return;
2167
+ if (Date.now() - inst.lastActiveAt < (idleMs || 0)) return;
2168
+ idle.push(inst);
2169
+ });
2170
+ if (idle.length === 0) return Promise.resolve(false);
2171
+ return Promise.all(idle.map(function(inst) { return retireInstance(inst, false); })).then(function() {
1981
2172
  console.log("[yoke/codex] Reclaimed idle adapter for project " + (_slug || _cwd));
1982
2173
  return true;
1983
2174
  });