@liberseek/boft-cli-linux-x64 0.8.5 → 0.8.6

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 (39) hide show
  1. package/README.md +2 -2
  2. package/THIRD_PARTY_NOTICES.txt +6 -2
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +70 -20
  5. package/app/console-web.js +61 -18
  6. package/app/desktop-controller.mjs +1142 -69
  7. package/app/host-runtime.mjs +3804 -1949
  8. package/app/plugins/antigravity/plugin.mjs +77 -9
  9. package/app/plugins/claude-code/plugin.mjs +27 -6
  10. package/app/plugins/codebuddy/plugin.mjs +25 -0
  11. package/app/plugins/codex-usage/plugin.mjs +15 -0
  12. package/app/plugins/copilot/plugin.mjs +15 -0
  13. package/app/plugins/cursor-cli/plugin.mjs +43 -8
  14. package/app/plugins/deepseek-harness/plugin.mjs +472 -44
  15. package/app/plugins/devin/assets/icon.svg +1 -0
  16. package/app/plugins/devin/manifest.json +30 -0
  17. package/app/plugins/devin/plugin.mjs +23425 -0
  18. package/app/plugins/enabled.json +2 -0
  19. package/app/plugins/grok/plugin.mjs +470 -387
  20. package/app/plugins/hermes/plugin.mjs +468 -196
  21. package/app/plugins/kimi-code/plugin.mjs +65 -3
  22. package/app/plugins/kiro-cli/plugin.mjs +15 -0
  23. package/app/plugins/muse/plugin.mjs +15 -0
  24. package/app/plugins/omp/plugin.mjs +15 -0
  25. package/app/plugins/opencode/plugin.mjs +15 -0
  26. package/app/plugins/pi/plugin.mjs +1595 -411
  27. package/app/plugins/qoder/plugin.mjs +9539 -8654
  28. package/app/plugins/qoder-cn/plugin.mjs +9539 -8654
  29. package/app/plugins/qwen-code/assets/icon.svg +1 -0
  30. package/app/plugins/qwen-code/manifest.json +29 -0
  31. package/app/plugins/qwen-code/plugin.mjs +29366 -0
  32. package/app/plugins/workbuddy/plugin.mjs +25 -0
  33. package/app/plugins/zcode/plugin.mjs +157 -9
  34. package/app/renderer-extension.js +727 -274
  35. package/bin/boft +0 -0
  36. package/libexec/boft-shim +0 -0
  37. package/libexec/boft-updater +0 -0
  38. package/licenses/Qwen-Code-SDK-LICENSE.txt +203 -0
  39. package/package.json +2 -2
@@ -1138,10 +1138,10 @@ function mergeDefs(...defs) {
1138
1138
  function cloneDef(schema) {
1139
1139
  return mergeDefs(schema._zod.def);
1140
1140
  }
1141
- function getElementAtPath(obj, path9) {
1142
- if (!path9)
1141
+ function getElementAtPath(obj, path8) {
1142
+ if (!path8)
1143
1143
  return obj;
1144
- return path9.reduce((acc, key) => acc?.[key], obj);
1144
+ return path8.reduce((acc, key) => acc?.[key], obj);
1145
1145
  }
1146
1146
  function promiseAllObject(promisesObj) {
1147
1147
  const keys = Object.keys(promisesObj);
@@ -1550,11 +1550,11 @@ function explicitlyAborted(x, startIndex = 0) {
1550
1550
  }
1551
1551
  return false;
1552
1552
  }
1553
- function prefixIssues(path9, issues) {
1553
+ function prefixIssues(path8, issues) {
1554
1554
  return issues.map((iss) => {
1555
1555
  var _a3;
1556
1556
  (_a3 = iss).path ?? (_a3.path = []);
1557
- iss.path.unshift(path9);
1557
+ iss.path.unshift(path8);
1558
1558
  return iss;
1559
1559
  });
1560
1560
  }
@@ -1701,16 +1701,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1701
1701
  }
1702
1702
  function formatError(error51, mapper = (issue2) => issue2.message) {
1703
1703
  const fieldErrors = { _errors: [] };
1704
- const processError = (error52, path9 = []) => {
1704
+ const processError = (error52, path8 = []) => {
1705
1705
  for (const issue2 of error52.issues) {
1706
1706
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1707
- issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
1707
+ issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path]));
1708
1708
  } else if (issue2.code === "invalid_key") {
1709
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1709
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
1710
1710
  } else if (issue2.code === "invalid_element") {
1711
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1711
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
1712
1712
  } else {
1713
- const fullpath = [...path9, ...issue2.path];
1713
+ const fullpath = [...path8, ...issue2.path];
1714
1714
  if (fullpath.length === 0) {
1715
1715
  fieldErrors._errors.push(mapper(issue2));
1716
1716
  } else {
@@ -1737,17 +1737,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1737
1737
  }
1738
1738
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1739
1739
  const result = { errors: [] };
1740
- const processError = (error52, path9 = []) => {
1740
+ const processError = (error52, path8 = []) => {
1741
1741
  var _a3, _b;
1742
1742
  for (const issue2 of error52.issues) {
1743
1743
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1744
- issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
1744
+ issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path]));
1745
1745
  } else if (issue2.code === "invalid_key") {
1746
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1746
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
1747
1747
  } else if (issue2.code === "invalid_element") {
1748
- processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
1748
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
1749
1749
  } else {
1750
- const fullpath = [...path9, ...issue2.path];
1750
+ const fullpath = [...path8, ...issue2.path];
1751
1751
  if (fullpath.length === 0) {
1752
1752
  result.errors.push(mapper(issue2));
1753
1753
  continue;
@@ -1779,8 +1779,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1779
1779
  }
1780
1780
  function toDotPath(_path) {
1781
1781
  const segs = [];
1782
- const path9 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1783
- for (const seg of path9) {
1782
+ const path8 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1783
+ for (const seg of path8) {
1784
1784
  if (typeof seg === "number")
1785
1785
  segs.push(`[${seg}]`);
1786
1786
  else if (typeof seg === "symbol")
@@ -14472,13 +14472,13 @@ function resolveRef(ref, ctx) {
14472
14472
  if (!ref.startsWith("#")) {
14473
14473
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14474
14474
  }
14475
- const path9 = ref.slice(1).split("/").filter(Boolean);
14476
- if (path9.length === 0) {
14475
+ const path8 = ref.slice(1).split("/").filter(Boolean);
14476
+ if (path8.length === 0) {
14477
14477
  return ctx.rootSchema;
14478
14478
  }
14479
14479
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14480
- if (path9[0] === defsKey) {
14481
- const key = path9[1];
14480
+ if (path8[0] === defsKey) {
14481
+ const key = path8[1];
14482
14482
  if (!key || !ctx.defs[key]) {
14483
14483
  throw new Error(`Reference not found: ${ref}`);
14484
14484
  }
@@ -15957,6 +15957,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
15957
15957
  /** The text about to be steered; a Harness command always stops and restarts. */
15958
15958
  text: external_exports.string().optional()
15959
15959
  }).strict();
15960
+ var threadSteeringContextSchema = external_exports.object({
15961
+ kind: external_exports.literal("application"),
15962
+ value: external_exports.string().transform((text2, context) => {
15963
+ try {
15964
+ return JSON.parse(text2);
15965
+ } catch {
15966
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
15967
+ return external_exports.NEVER;
15968
+ }
15969
+ }).pipe(external_exports.object({
15970
+ expectedTurnId: hostTurnIdSchema,
15971
+ clientUserMessageId: external_exports.string().min(1),
15972
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
15973
+ }).strict())
15974
+ }).strict().transform((context) => context.value);
15960
15975
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15961
15976
  var threadSteeringInspectResultSchema = external_exports.object({
15962
15977
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -16667,7 +16682,35 @@ import path4 from "node:path";
16667
16682
 
16668
16683
  // dist/hermes-runtime.js
16669
16684
  import { execFile as execFile2 } from "node:child_process";
16685
+ import { statSync } from "node:fs";
16670
16686
  import { promisify } from "node:util";
16687
+ var launcherPrefixCache = /* @__PURE__ */ new Map();
16688
+ function launcherCacheKey(launcher, environment) {
16689
+ let stat;
16690
+ try {
16691
+ stat = statSync(launcher);
16692
+ } catch {
16693
+ return null;
16694
+ }
16695
+ return [
16696
+ launcher,
16697
+ stat.mtimeMs,
16698
+ stat.size,
16699
+ environment.HERMES_HOME ?? "",
16700
+ environment.PATH ?? ""
16701
+ ].join("\0");
16702
+ }
16703
+ function timeitPassthrough(script) {
16704
+ return [
16705
+ "-n",
16706
+ "1",
16707
+ "-r",
16708
+ "1",
16709
+ "-s",
16710
+ `exec(${JSON.stringify(script)}, {}); import sys, io; sys.stdout = io.StringIO()`,
16711
+ "pass"
16712
+ ];
16713
+ }
16671
16714
  function legacyHermesPythonCommand(python, script) {
16672
16715
  return {
16673
16716
  command: python,
@@ -16683,22 +16726,12 @@ ${script}`
16683
16726
  };
16684
16727
  }
16685
16728
  async function nativeHermesPythonCommand(launcher, script, environment, timeoutMs = 2e4, platform = process.platform) {
16686
- const invocation = commandInvocation(launcher, [
16687
- "--print-runtime-command",
16688
- "--module",
16689
- "timeit",
16690
- "--",
16691
- "-n",
16692
- "1",
16693
- "-r",
16694
- "1",
16695
- "-s",
16696
- // timeit is a stdlib entry point supported by the native launcher. After
16697
- // the operation returns, redirect its timing footer, preserving normal
16698
- // native cleanup and exit status without contaminating JSON/RPC stdout.
16699
- `exec(${JSON.stringify(script)}, {}); import sys, io; sys.stdout = io.StringIO()`,
16700
- "pass"
16701
- ], environment, platform);
16729
+ const passthrough = timeitPassthrough(script);
16730
+ const cacheKey = launcherCacheKey(launcher, environment);
16731
+ const cached2 = cacheKey !== null ? launcherPrefixCache.get(cacheKey) : void 0;
16732
+ if (cached2 !== void 0 && cached2.length > 0 && cached2[0])
16733
+ return { command: cached2[0], arguments: [...cached2.slice(1), ...passthrough] };
16734
+ const invocation = commandInvocation(launcher, ["--print-runtime-command", "--module", "timeit", "--", ...passthrough], environment, platform);
16702
16735
  let stdout;
16703
16736
  try {
16704
16737
  ({ stdout } = await promisify(execFile2)(invocation.command, invocation.arguments, {
@@ -16718,6 +16751,9 @@ async function nativeHermesPythonCommand(launcher, script, environment, timeoutM
16718
16751
  if (!Array.isArray(value) || value.length === 0 || !value.every((arg) => typeof arg === "string") || !value[0]) {
16719
16752
  throw new Error("Hermes launcher returned an invalid runtime command");
16720
16753
  }
16754
+ const passthroughStart = value.length - passthrough.length;
16755
+ if (cacheKey !== null && passthroughStart >= 1 && value.slice(passthroughStart).every((arg, index) => arg === passthrough[index]))
16756
+ launcherPrefixCache.set(cacheKey, value.slice(0, passthroughStart));
16721
16757
  return { command: value[0], arguments: value.slice(1) };
16722
16758
  }
16723
16759
  async function hermesPythonCommand(runtime, script, environment, timeoutMs = 2e4) {
@@ -17030,9 +17066,6 @@ function catalogModelsFromInventory(inventory) {
17030
17066
  }
17031
17067
 
17032
17068
  // dist/gateway-delegation.js
17033
- import { mkdtemp as mkdtemp2, writeFile as writeFile2, rm as rm2 } from "node:fs/promises";
17034
- import os2 from "node:os";
17035
- import path5 from "node:path";
17036
17069
  var HERMES_DELEGATION_GUIDANCE = `This Session runs inside codexhost.
17037
17070
  When the user authorizes cross-Harness delegation, discover the executable named by CODEXHOST_CLI_PATH through your native terminal tool. Read its --help and harness list, then use delegate start and thread send/read/wait/cancel as documented. Prefer --format compact. Preserve CODEXHOST_RUNTIME_ENDPOINT, CODEXHOST_RUNTIME_TOKEN and CODEXHOST_THREAD_ID in these calls: they identify the Runtime and parent Thread. Never print their values or substitute another executable. Native Hermes delegate_task remains available for Hermes subagents.`;
17038
17071
  var required2 = [
@@ -17043,48 +17076,40 @@ var required2 = [
17043
17076
  ];
17044
17077
  async function prepareGatewayDelegation(environment) {
17045
17078
  if (!required2.every((key) => environment[key]))
17046
- return { environment, bootstrap: "", dispose: async () => {
17079
+ return { environment, bootstrap: "", guidance: null, dispose: async () => {
17047
17080
  } };
17048
- const directory = await mkdtemp2(path5.join(os2.tmpdir(), "codexhost-hermes-delegation-"));
17049
- const file2 = path5.join(directory, "SKILL.md");
17050
- try {
17051
- await writeFile2(file2, `---
17052
- name: delegation
17053
- description: Discover authorized codexhost agent collaboration.
17054
- ---
17055
-
17056
- ${HERMES_DELEGATION_GUIDANCE}
17057
- `, { mode: 384 });
17058
- return {
17059
- environment: {
17060
- ...environment,
17061
- HERMES_TUI_SKILLS: [environment.HERMES_TUI_SKILLS, "codexhost-runtime:delegation"].filter(Boolean).join(",")
17062
- },
17063
- // Reserve RPC stdout before native plugin imports. The registration is
17064
- // process-local; no plugin is installed and no user config is changed.
17065
- //
17066
- // ``hermes_bootstrap`` must run before ``tui_gateway.server`` is imported:
17067
- // the gateway spawn uses ``python -I``, so PYTHONPATH and the launcher's
17068
- // activation are stripped. Hermes's own entry point (``tui_gateway/entry.py``)
17069
- // imports this module first to put the selected dependency environment on
17070
- // ``sys.path``; skipping it makes bare third-party imports (e.g.
17071
- // ``hermes_yaml`` -> ``ruamel``) fail on interpreters whose site-packages
17072
- // do not already carry Hermes's dependencies. ``hermes_bootstrap`` is
17073
- // import-safe here for the same reason entry.py relies on it: stdlib-only
17074
- // at import time, so nothing can shadow it from the launch directory.
17075
- bootstrap: `import hermes_bootstrap
17081
+ return {
17082
+ environment,
17083
+ // Reserve RPC stdout before native plugin imports.
17084
+ //
17085
+ // ``hermes_bootstrap`` must run before ``tui_gateway.server`` is imported:
17086
+ // the gateway spawn uses ``python -I``, so PYTHONPATH and the launcher's
17087
+ // activation are stripped. Hermes's own entry point (``tui_gateway/entry.py``)
17088
+ // imports this module first to put the selected dependency environment on
17089
+ // ``sys.path``; skipping it makes bare third-party imports (e.g.
17090
+ // ``hermes_yaml`` -> ``ruamel``) fail on interpreters whose site-packages
17091
+ // do not already carry Hermes's dependencies. ``hermes_bootstrap`` is
17092
+ // import-safe here for the same reason entry.py relies on it: stdlib-only
17093
+ // at import time, so nothing can shadow it from the launch directory.
17094
+ bootstrap: `import sys
17095
+ import hermes_bootstrap
17096
+ _stdout = sys.stdout # tui_gateway.server redirects sys.stdout to sys.stderr at import (stdio-entry protection); this bridge owns stdout as its RPC channel to the host
17076
17097
  from tui_gateway import server
17077
- from pathlib import Path
17078
- from hermes_cli.plugins import PluginContext, PluginManifest, get_plugin_manager
17079
- PluginContext(PluginManifest(name="codexhost-runtime"), get_plugin_manager()).register_skill(
17080
- "delegation", Path(${JSON.stringify(file2)}))
17098
+ sys.stdout = _stdout
17081
17099
  `,
17082
- dispose: () => rm2(directory, { recursive: true, force: true })
17083
- };
17084
- } catch (error51) {
17085
- await rm2(directory, { recursive: true, force: true });
17086
- throw error51;
17087
- }
17100
+ guidance: `${HERMES_DELEGATION_GUIDANCE}
17101
+
17102
+ Runtime identity for this Thread:
17103
+
17104
+ - CODEXHOST_CLI_PATH: ${environment.CODEXHOST_CLI_PATH}
17105
+ - CODEXHOST_RUNTIME_ENDPOINT: ${environment.CODEXHOST_RUNTIME_ENDPOINT}
17106
+ - CODEXHOST_RUNTIME_TOKEN: ${environment.CODEXHOST_RUNTIME_TOKEN}
17107
+ - CODEXHOST_THREAD_ID: ${environment.CODEXHOST_THREAD_ID}
17108
+
17109
+ (end of codexhost delegation note; the user's message follows)`,
17110
+ dispose: async () => {
17111
+ }
17112
+ };
17088
17113
  }
17089
17114
 
17090
17115
  // dist/hermes-transport.js
@@ -17118,8 +17143,87 @@ function gatewayRecord(value) {
17118
17143
  function gatewayString(value) {
17119
17144
  return typeof value === "string" ? value : "";
17120
17145
  }
17121
- var GATEWAY_LAUNCH = `import runpy
17122
- runpy.run_module('tui_gateway.entry', run_name='__main__')`;
17146
+ var GATEWAY_LAUNCH = `import asyncio
17147
+ import sys
17148
+
17149
+
17150
+ async def _bridge():
17151
+ from hermes_constants import get_hermes_home
17152
+ from hermes_cli.gateway_client import _session_ticket, gateway_ws_target
17153
+ from hermes_cli.gateway_runtime import (
17154
+ attachable,
17155
+ ensure_gateway_runtime,
17156
+ gateway_profile_home,
17157
+ )
17158
+ from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL
17159
+ from websockets.asyncio.client import connect
17160
+
17161
+ home = gateway_profile_home(get_hermes_home())
17162
+ result = await asyncio.to_thread(ensure_gateway_runtime, home, idle_exit=True)
17163
+ if not attachable(result):
17164
+ detail = f" ({result.detail})" if result.detail else ""
17165
+ raise SystemExit(
17166
+ f"[bridge-exit] gateway not attachable: {result.state} "
17167
+ f"{result.reason_code or 'not ready'}{detail}"
17168
+ )
17169
+ endpoint = result.endpoint
17170
+ ticket = await asyncio.to_thread(_session_ticket, home, endpoint)
17171
+ url, protocols = gateway_ws_target(endpoint, ticket)
17172
+
17173
+ async with connect(
17174
+ url, subprotocols=protocols, open_timeout=10, max_size=8 * 1024 * 1024, proxy=None
17175
+ ) as ws:
17176
+ if protocols and ws.subprotocol != CANONICAL_GATEWAY_PROTOCOL:
17177
+ raise SystemExit("[bridge-exit] gateway protocol mismatch; update/restart required")
17178
+
17179
+ loop = asyncio.get_running_loop()
17180
+ # A full prompt rides on ONE JSON-RPC line; StreamReader's default 64 KiB
17181
+ # line limit aborts the bridge on large pastes (LimitOverrunError), so the
17182
+ # stdin side matches the WebSocket side's 8 MiB frame ceiling.
17183
+ reader = asyncio.StreamReader(limit=8 * 1024 * 1024)
17184
+ await loop.connect_read_pipe(
17185
+ lambda: asyncio.StreamReaderProtocol(reader), sys.stdin
17186
+ )
17187
+
17188
+ async def pump_in():
17189
+ async for raw in reader:
17190
+ line = raw.decode("utf-8", "replace").strip()
17191
+ if line:
17192
+ await ws.send(line)
17193
+
17194
+ async def pump_out():
17195
+ async for raw in ws:
17196
+ if isinstance(raw, bytes):
17197
+ raw = raw.decode("utf-8", "replace")
17198
+ sys.stdout.write(raw + "\\n")
17199
+ sys.stdout.flush()
17200
+
17201
+ pump_out_task = asyncio.create_task(pump_out())
17202
+ pump_in_task = asyncio.create_task(pump_in())
17203
+ # stdin EOF (host closed us) or socket close (gateway went away): end both.
17204
+ done, _pending = await asyncio.wait(
17205
+ {pump_in_task, pump_out_task}, return_when=asyncio.FIRST_COMPLETED
17206
+ )
17207
+ for task in (pump_in_task, pump_out_task):
17208
+ task.cancel()
17209
+ for task in done:
17210
+ if task.cancelled():
17211
+ continue
17212
+ exc = task.exception()
17213
+ if exc is not None:
17214
+ raise exc
17215
+
17216
+
17217
+ # No __main__ guard: the native launcher spawns this through exec(script, {})
17218
+ # whose fresh globals lack __name__; top-level code runs in both the legacy
17219
+ # (-c) and native (exec) spawn forms.
17220
+ try:
17221
+ asyncio.run(_bridge())
17222
+ except SystemExit:
17223
+ raise
17224
+ except Exception as exc:
17225
+ raise SystemExit(f"[bridge-exit] bridge failed: {type(exc).__name__}: {exc}")
17226
+ `;
17123
17227
  var HermesGatewayTransport = class _HermesGatewayTransport {
17124
17228
  runtime;
17125
17229
  cwd;
@@ -17146,6 +17250,18 @@ var HermesGatewayTransport = class _HermesGatewayTransport {
17146
17250
  this.environment = environment;
17147
17251
  this.timeoutMs = timeoutMs;
17148
17252
  }
17253
+ /** Model-facing delegation guidance for this Thread, or null without delegation. */
17254
+ get delegationGuidance() {
17255
+ return this.#delegation?.guidance ?? null;
17256
+ }
17257
+ /** Whether start() already ran (a warm transport skips prepare/start on reuse). */
17258
+ get started() {
17259
+ return this.#startRequested;
17260
+ }
17261
+ /** Whether the bridge child is gone; a closed transport cannot be reused. */
17262
+ get closed() {
17263
+ return this.#closed;
17264
+ }
17149
17265
  static async probe(executable, cwd, environment) {
17150
17266
  const override = environment.CODEXHOST_HERMES_GATEWAY_PYTHON;
17151
17267
  if (override) {
@@ -17658,7 +17774,7 @@ async function resolveHermesSessionCandidate(input) {
17658
17774
  }
17659
17775
 
17660
17776
  // dist/command.js
17661
- import path6 from "node:path";
17777
+ import path5 from "node:path";
17662
17778
  var HermesExecutableError = class extends Error {
17663
17779
  code = "HERMES_NOT_FOUND";
17664
17780
  };
@@ -17681,7 +17797,62 @@ function resolveHermesExecutable(input = {}) {
17681
17797
  });
17682
17798
  if (!resolution)
17683
17799
  throw new HermesExecutableError("Hermes CLI is not installed");
17684
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path6.resolve(resolution.executable);
17800
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path5.resolve(resolution.executable);
17801
+ }
17802
+
17803
+ // dist/gateway-transport-pool.js
17804
+ function sameRuntime(a, b) {
17805
+ if (typeof a === "string" || typeof b === "string")
17806
+ return a === b;
17807
+ return a.launcher === b.launcher;
17808
+ }
17809
+ var ENVIRONMENT_IDENTITY_KEYS = ["HERMES_HOME", "HERMES_TUI_SKILLS"];
17810
+ function environmentIdentity(environment) {
17811
+ return ENVIRONMENT_IDENTITY_KEYS.map((key) => `${key}=${environment[key] ?? ""}`).join("\0");
17812
+ }
17813
+ function sameBridge(transport, runtime, cwd, environment) {
17814
+ return sameRuntime(transport.runtime, runtime) && transport.cwd === cwd && environmentIdentity(transport.environment) === environmentIdentity(environment);
17815
+ }
17816
+ var GatewayTransportPool = class {
17817
+ #idle = [];
17818
+ #capacity;
17819
+ #closed = false;
17820
+ constructor(capacity = 2) {
17821
+ this.#capacity = Math.max(1, capacity);
17822
+ }
17823
+ /** A healthy started bridge equivalent to a fresh spawn for these inputs, or null. */
17824
+ acquire(runtime, cwd, environment) {
17825
+ while (this.#idle.length > 0) {
17826
+ const index = this.#idle.findIndex((transport2) => sameBridge(transport2, runtime, cwd, environment));
17827
+ const transport = index >= 0 ? this.#idle.splice(index, 1)[0] : void 0;
17828
+ if (transport === void 0)
17829
+ return null;
17830
+ if (!transport.closed && transport.started)
17831
+ return transport;
17832
+ void transport.close().catch(() => void 0);
17833
+ }
17834
+ return null;
17835
+ }
17836
+ /** Return a bridge after its session settled; unhealthy or late ones are discarded. */
17837
+ release(transport) {
17838
+ if (transport.closed || this.#closed || this.#idle.length >= this.#capacity) {
17839
+ void transport.close().catch(() => void 0);
17840
+ return;
17841
+ }
17842
+ this.#idle.push(transport);
17843
+ }
17844
+ async close() {
17845
+ this.#closed = true;
17846
+ const transports = this.#idle;
17847
+ this.#idle = [];
17848
+ await Promise.all(transports.map((transport) => transport.close().catch(() => void 0)));
17849
+ }
17850
+ };
17851
+ async function startGatewayTransport(runtime, cwd, environment, timeoutMs) {
17852
+ const transport = new HermesGatewayTransport(runtime, cwd, environment, timeoutMs);
17853
+ await transport.prepareSession();
17854
+ await transport.start();
17855
+ return transport;
17685
17856
  }
17686
17857
 
17687
17858
  // dist/gateway-history.js
@@ -17771,21 +17942,24 @@ def capture(db):
17771
17942
  boundaries[str(row['id'])] = {'count': end, 'digest': digest(active[:end])}
17772
17943
  return exported, {'rows': rows, 'derivable': derivable, 'boundaries': boundaries, 'physicalSessionId': sid}
17773
17944
 
17945
+ def ensure_session_row(db):
17946
+ if db.get_session(sid) is None:
17947
+ from hermes_constants import parse_reasoning_effort
17948
+ initial = {}
17949
+ if isinstance(p.get('provider'), str) and p['provider']: initial['provider'] = p['provider']
17950
+ if isinstance(p.get('model'), str) and p['model']: initial['model'] = p['model']
17951
+ if isinstance(p.get('reasoningEffort'), str):
17952
+ reasoning = parse_reasoning_effort(p['reasoningEffort'])
17953
+ if reasoning is not None: initial['reasoning_config'] = reasoning
17954
+ if isinstance(p.get('yolo'), bool): initial['yolo_mode'] = p['yolo']
17955
+ db.create_session(session_id=sid, source='cli', cwd=p['cwd'], model=p.get('model'), model_config=initial)
17956
+ return {'created': True}
17957
+
17774
17958
  try:
17775
17959
  if p['operation'] == 'ensure':
17776
17960
  db = SessionDB()
17777
17961
  try:
17778
- if db.get_session(sid) is None:
17779
- from hermes_constants import parse_reasoning_effort
17780
- initial = {}
17781
- if isinstance(p.get('provider'), str) and p['provider']: initial['provider'] = p['provider']
17782
- if isinstance(p.get('model'), str) and p['model']: initial['model'] = p['model']
17783
- if isinstance(p.get('reasoningEffort'), str):
17784
- reasoning = parse_reasoning_effort(p['reasoningEffort'])
17785
- if reasoning is not None: initial['reasoning_config'] = reasoning
17786
- if isinstance(p.get('yolo'), bool): initial['yolo_mode'] = p['yolo']
17787
- db.create_session(session_id=sid, source='cli', cwd=p['cwd'], model=p.get('model'), model_config=initial)
17788
- result = {'created': True}
17962
+ result = ensure_session_row(db)
17789
17963
  finally: db.close()
17790
17964
  elif p['operation'] == 'discard':
17791
17965
  child = p['derivedSessionId']
@@ -18153,28 +18327,6 @@ var HermesUsage = class {
18153
18327
  }
18154
18328
  };
18155
18329
 
18156
- // dist/gateway-configuration.js
18157
- import { execFile as execFile4 } from "node:child_process";
18158
- import { promisify as promisify3 } from "node:util";
18159
- async function resolveGatewayModel(transport, modelId) {
18160
- if (/\s/u.test(modelId) || modelId.startsWith("-"))
18161
- throw new Error("Invalid Hermes Model identifier");
18162
- const command = await hermesPythonCommand(transport.runtime, `import json
18163
- from hermes_cli.models import parse_model_input
18164
- p,m=parse_model_input(${JSON.stringify(modelId)}, '')
18165
- print(json.dumps({'provider':p,'model':m}))`, { ...process.env, ...transport.environment });
18166
- const result = await promisify3(execFile4)(command.command, command.arguments, {
18167
- cwd: transport.cwd,
18168
- env: { ...process.env, ...transport.environment },
18169
- timeout: 2e4,
18170
- maxBuffer: 1024 * 1024
18171
- });
18172
- const value = JSON.parse(result.stdout.trim());
18173
- if (!value || typeof value !== "object" || !("provider" in value) || !("model" in value) || typeof value.provider !== "string" || typeof value.model !== "string")
18174
- throw new Error("Hermes returned an invalid Model choice");
18175
- return { provider: value.provider, model: value.model };
18176
- }
18177
-
18178
18330
  // dist/gateway-session-transport.js
18179
18331
  var hermesGatewayThinkingOptions = [
18180
18332
  "none",
@@ -18206,14 +18358,14 @@ function gatewayDiff(text2) {
18206
18358
  if (!text2 || text2.length > 1024 * 1024)
18207
18359
  return [];
18208
18360
  const result = [];
18209
- let path9 = "";
18361
+ let path8 = "";
18210
18362
  let inHunk = false;
18211
18363
  let oldLines = [], newLines = [];
18212
18364
  const flush = () => {
18213
- if (path9)
18365
+ if (path8)
18214
18366
  result.push({
18215
18367
  type: "diff",
18216
- path: path9,
18368
+ path: path8,
18217
18369
  oldText: oldLines.join("\n"),
18218
18370
  newText: newLines.join("\n")
18219
18371
  });
@@ -18226,24 +18378,24 @@ function gatewayDiff(text2) {
18226
18378
  if (header) {
18227
18379
  flush();
18228
18380
  inHunk = false;
18229
- path9 = (header[2] === "/dev/null" ? header[1] ?? "" : header[2] ?? "").replace(/^[ab]\//u, "");
18381
+ path8 = (header[2] === "/dev/null" ? header[1] ?? "" : header[2] ?? "").replace(/^[ab]\//u, "");
18230
18382
  continue;
18231
18383
  }
18232
18384
  if (line.startsWith("--- ") && !inHunk) {
18233
18385
  flush();
18234
- path9 = line.slice(4).replace(/^a\//u, "");
18386
+ path8 = line.slice(4).replace(/^a\//u, "");
18235
18387
  } else if (line.startsWith("+++ ") && !inHunk) {
18236
18388
  const next = line.slice(4);
18237
18389
  if (next !== "/dev/null")
18238
- path9 = next.replace(/^b\//u, "");
18390
+ path8 = next.replace(/^b\//u, "");
18239
18391
  } else if (line.startsWith("@@")) {
18240
18392
  inHunk = true;
18241
18393
  continue;
18242
- } else if (path9 && line.startsWith("-"))
18394
+ } else if (path8 && line.startsWith("-"))
18243
18395
  oldLines.push(line.slice(1));
18244
- else if (path9 && line.startsWith("+"))
18396
+ else if (path8 && line.startsWith("+"))
18245
18397
  newLines.push(line.slice(1));
18246
- else if (path9 && line.startsWith(" ")) {
18398
+ else if (path8 && line.startsWith(" ")) {
18247
18399
  oldLines.push(line.slice(1));
18248
18400
  newLines.push(line.slice(1));
18249
18401
  }
@@ -18267,7 +18419,7 @@ var HermesGatewaySessionTransport = class {
18267
18419
  return this.#commands;
18268
18420
  }
18269
18421
  async getCommands() {
18270
- const params = { session_id: this.sessionId, cwd: this.transport.cwd };
18422
+ const params = { session_id: this.sessionId };
18271
18423
  const [response, catalog] = await Promise.all([
18272
18424
  this.transport.request("complete.slash", { ...params, text: "/" }, this.transport.timeoutMs, false),
18273
18425
  this.transport.request("commands.catalog", params, this.transport.timeoutMs, false)
@@ -18292,13 +18444,29 @@ var HermesGatewaySessionTransport = class {
18292
18444
  history;
18293
18445
  #active = null;
18294
18446
  #requests = /* @__PURE__ */ new Map();
18447
+ /** Open approval server requests by their payload request_id, for approval.cancelled. */
18448
+ #approvalRequests = /* @__PURE__ */ new Map();
18449
+ /** Pending approval prompts adopted from the create/resume snapshot. */
18450
+ #adoptedPrompts = [];
18295
18451
  #closed = false;
18296
18452
  #info;
18297
- constructor(transport, sessionId, nativeSessionId, info) {
18453
+ #revision = null;
18454
+ #generation = null;
18455
+ #subscriptionId = null;
18456
+ /** Thread's delegation guidance, injected as api_text on the first turn only. */
18457
+ #delegationGuidance;
18458
+ constructor(transport, sessionId, nativeSessionId, info, bookkeeping = {}, delegationGuidance = null) {
18298
18459
  this.transport = transport;
18299
18460
  this.sessionId = sessionId;
18300
18461
  this.nativeSessionId = nativeSessionId;
18301
18462
  this.#info = info;
18463
+ this.#delegationGuidance = delegationGuidance;
18464
+ if (typeof bookkeeping.revision === "number")
18465
+ this.#revision = bookkeeping.revision;
18466
+ if (typeof bookkeeping.generation === "number")
18467
+ this.#generation = bookkeeping.generation;
18468
+ if (typeof bookkeeping.subscriptionId === "string")
18469
+ this.#subscriptionId = bookkeeping.subscriptionId;
18302
18470
  this.history = new HermesGatewayHistory({
18303
18471
  python: transport.runtime,
18304
18472
  cwd: transport.cwd,
@@ -18359,17 +18527,24 @@ var HermesGatewaySessionTransport = class {
18359
18527
  return optionId;
18360
18528
  }
18361
18529
  async setModel(modelId) {
18362
- const choice = await resolveGatewayModel(this.transport, modelId);
18363
- const result = await this.transport.request("config.set", {
18364
- key: "model",
18365
- value: choice.provider ? `${choice.model} --provider ${choice.provider}` : modelId,
18366
- scope: "session",
18367
- session_id: this.sessionId
18530
+ const revision = this.#revision;
18531
+ const generation = this.#generation;
18532
+ if (revision === null || generation === null)
18533
+ throw new Error("Hermes gateway Session revision is not known yet");
18534
+ const result = await this.transport.request("session.mutate", {
18535
+ session_id: this.sessionId,
18536
+ request_id: `codexhost-model-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
18537
+ expected_revision: revision,
18538
+ expected_generation: generation,
18539
+ operation: "model",
18540
+ payload: { model: modelId }
18368
18541
  });
18369
- if (result.confirm_required === true)
18370
- throw new Error(gatewayString(result.confirm_message) || "Hermes requires confirmation for this Model");
18371
- const actualModel = gatewayString(this.#info.model);
18372
- const actualProvider = gatewayString(this.#info.provider);
18542
+ if (typeof result.revision === "number")
18543
+ this.#revision = result.revision;
18544
+ if (typeof result.execution_generation === "number")
18545
+ this.#generation = result.execution_generation;
18546
+ const actualModel = gatewayString(result.model);
18547
+ const actualProvider = gatewayString(result.provider);
18373
18548
  if (modelId !== actualModel && modelId !== `${actualProvider}:${actualModel}`)
18374
18549
  throw new Error("Hermes did not confirm the requested Model");
18375
18550
  }
@@ -18379,11 +18554,11 @@ var HermesGatewaySessionTransport = class {
18379
18554
  const result = await this.transport.request("config.set", {
18380
18555
  key: "yolo",
18381
18556
  value: modeId === "dont_ask" ? "on" : "off",
18382
- scope: "session",
18383
18557
  session_id: this.sessionId
18384
18558
  });
18385
- if (result.value !== (modeId === "dont_ask" ? "1" : "0") || this.#info.yolo !== (modeId === "dont_ask"))
18559
+ if (result.value !== (modeId === "dont_ask" ? "1" : "0"))
18386
18560
  throw new Error("Hermes effective approval policy differs from the requested mode; check native global approvals policy");
18561
+ this.#info = { ...this.#info, yolo: modeId === "dont_ask" };
18387
18562
  }
18388
18563
  nativeCommandName(text2) {
18389
18564
  return hermesGatewayCommandName(text2, this.#commands);
@@ -18406,9 +18581,11 @@ var HermesGatewaySessionTransport = class {
18406
18581
  reject: rejectResult,
18407
18582
  streamed: "",
18408
18583
  reasoning: "",
18409
- toolIds: /* @__PURE__ */ new Set()
18584
+ toolIds: /* @__PURE__ */ new Set(),
18585
+ admissionId: null
18410
18586
  };
18411
18587
  this.#active = active;
18588
+ void this.#adoptedPrompts.splice(0).map((prompt) => void this.#respondAdoptedApproval(prompt, active).catch(() => void 0));
18412
18589
  const commandText = text2.trim();
18413
18590
  const nativeCommand = this.nativeCommandName(text2);
18414
18591
  try {
@@ -18447,12 +18624,21 @@ var HermesGatewaySessionTransport = class {
18447
18624
  emit({ type: "agent.text", text: response.output });
18448
18625
  active.resolve({ stopReason: "end_turn" });
18449
18626
  } else {
18627
+ const guidance = this.#delegationGuidance;
18628
+ this.#delegationGuidance = null;
18450
18629
  const submitted = await this.transport.request("prompt.submit", {
18451
18630
  session_id: this.sessionId,
18452
- text: text2
18631
+ text: text2,
18632
+ submission_id: `codexhost-turn-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
18633
+ clarify_batch: true,
18634
+ ...guidance ? { api_text: `${guidance}
18635
+
18636
+ ${text2}` } : {}
18453
18637
  });
18454
- if (submitted.status !== "streaming")
18455
- this.#fault(new Error(`Hermes did not start an exclusive turn (${String(submitted.status)})`));
18638
+ if (submitted.status !== "queued" && submitted.status !== "started")
18639
+ this.#fault(new Error(`Hermes did not accept the turn (${String(submitted.status)})`));
18640
+ else if (active.admissionId === null && typeof submitted.admission_id === "string")
18641
+ active.admissionId = submitted.admission_id;
18456
18642
  }
18457
18643
  } catch (error51) {
18458
18644
  active.reject(error51 instanceof Error ? error51 : new Error(String(error51)));
@@ -18468,7 +18654,12 @@ var HermesGatewaySessionTransport = class {
18468
18654
  }
18469
18655
  }
18470
18656
  async cancel() {
18471
- await this.transport.request("session.interrupt", { session_id: this.sessionId });
18657
+ if (this.#generation === null)
18658
+ return;
18659
+ await this.transport.request("session.interrupt", {
18660
+ session_id: this.sessionId,
18661
+ execution_generation: this.#generation
18662
+ });
18472
18663
  }
18473
18664
  async close() {
18474
18665
  if (this.#closed)
@@ -18479,10 +18670,13 @@ var HermesGatewaySessionTransport = class {
18479
18670
  this.#requests.clear();
18480
18671
  this.#active?.reject(new Error("Hermes gateway Session closed"));
18481
18672
  try {
18482
- await this.transport.request("session.close", { session_id: this.sessionId });
18673
+ if (this.#subscriptionId !== null)
18674
+ await this.transport.request("session.detach", {
18675
+ session_id: this.sessionId,
18676
+ subscription_id: this.#subscriptionId
18677
+ });
18483
18678
  } catch {
18484
18679
  }
18485
- await this.transport.close();
18486
18680
  }
18487
18681
  #fault(error51) {
18488
18682
  if (this.#closed)
@@ -18502,6 +18696,10 @@ var HermesGatewaySessionTransport = class {
18502
18696
  const payload = gatewayRecord(event.payload);
18503
18697
  if (event.type === "session.info") {
18504
18698
  this.#info = payload;
18699
+ if (typeof payload.revision === "number")
18700
+ this.#revision = payload.revision;
18701
+ if (typeof payload.execution_generation === "number")
18702
+ this.#generation = payload.execution_generation;
18505
18703
  return;
18506
18704
  }
18507
18705
  if (event.type === "session.usage") {
@@ -18513,12 +18711,26 @@ var HermesGatewaySessionTransport = class {
18513
18711
  controller?.abort(payload.reason === "timeout" ? "expired" : "cancelled");
18514
18712
  return;
18515
18713
  }
18714
+ if (event.type === "approval.cancelled") {
18715
+ const ids = Array.isArray(payload.request_ids) ? payload.request_ids.filter((id) => typeof id === "string") : [];
18716
+ for (const id of ids) {
18717
+ this.#approvalRequests.get(id)?.abort("cancelled");
18718
+ this.#approvalRequests.delete(id);
18719
+ }
18720
+ return;
18721
+ }
18516
18722
  const active = this.#active;
18517
18723
  if (!active) {
18518
18724
  if (event.type === "error")
18519
18725
  this.#fault(new Error(gatewayString(payload.message)));
18520
18726
  return;
18521
18727
  }
18728
+ const eventAdmission = gatewayString(event.admission_id);
18729
+ const eventType = gatewayString(event.type);
18730
+ if (eventAdmission && active.admissionId && eventAdmission !== active.admissionId) {
18731
+ if (eventType.startsWith("message.") || eventType.startsWith("reasoning."))
18732
+ return;
18733
+ }
18522
18734
  const text2 = gatewayString(payload.text);
18523
18735
  if (event.type === "message.delta") {
18524
18736
  active.streamed += text2;
@@ -18649,27 +18861,80 @@ var HermesGatewaySessionTransport = class {
18649
18861
  label: choice === "session" ? "Allow for this session" : "Always allow"
18650
18862
  }
18651
18863
  ] : choice === "deny" ? [{ id: "deny", effect: "deny", label: "Deny" }] : []);
18652
- const response = await active.permission({
18653
- signal: controller.signal,
18654
- title: gatewayString(params.description) || gatewayString(params.command),
18655
- description: gatewayString(params.command) || gatewayString(params.description),
18656
- options
18657
- });
18658
- if (!controller.signal.aborted)
18659
- this.transport.respond(id, {
18660
- choice: response ?? "deny"
18864
+ const payloadRequestId = gatewayString(params.request_id);
18865
+ if (payloadRequestId)
18866
+ this.#approvalRequests.set(payloadRequestId, controller);
18867
+ try {
18868
+ const response = await active.permission({
18869
+ signal: controller.signal,
18870
+ title: gatewayString(params.description) || gatewayString(params.command),
18871
+ description: gatewayString(params.command) || gatewayString(params.description),
18872
+ options
18661
18873
  });
18874
+ if (!controller.signal.aborted)
18875
+ this.transport.respond(id, {
18876
+ choice: response ?? "deny"
18877
+ });
18878
+ } finally {
18879
+ if (payloadRequestId)
18880
+ this.#approvalRequests.delete(payloadRequestId);
18881
+ }
18662
18882
  } else
18663
18883
  this.transport.rejectRequest(id);
18664
18884
  } finally {
18665
18885
  this.#requests.delete(id);
18666
18886
  }
18667
18887
  }
18888
+ /** Keep approval prompts from the create/resume snapshot for the next turn. */
18889
+ adoptPendingPrompts(prompts) {
18890
+ if (!Array.isArray(prompts))
18891
+ return;
18892
+ for (const entry of prompts) {
18893
+ const prompt = gatewayRecord(entry);
18894
+ if (gatewayString(prompt.kind) === "approval" && gatewayString(prompt.prompt_id))
18895
+ this.#adoptedPrompts.push(prompt);
18896
+ }
18897
+ }
18898
+ /**
18899
+ * Answer a snapshot-adopted approval through canonical `approval.respond`.
18900
+ * Clarify prompts are deliberately not answered here: a live clarify
18901
+ * question is served by the `clarify` server request (batch mode), and the
18902
+ * gateway re-issues still-open server requests to an attaching client.
18903
+ */
18904
+ async #respondAdoptedApproval(prompt, active) {
18905
+ if (this.#closed)
18906
+ return;
18907
+ const promptId = gatewayString(prompt.prompt_id);
18908
+ const generation = prompt.execution_generation;
18909
+ const choices = Array.isArray(prompt.choices) ? prompt.choices.filter((choice) => typeof choice === "string") : ["once", "deny"];
18910
+ const options = choices.flatMap((choice) => choice === "once" ? [{ id: "once", effect: "allowOnce", label: "Allow once" }] : choice === "session" || choice === "always" ? [
18911
+ {
18912
+ id: choice,
18913
+ effect: choice === "session" ? "allowForSession" : "allowAlways",
18914
+ label: choice === "session" ? "Allow for this session" : "Always allow"
18915
+ }
18916
+ ] : choice === "deny" ? [{ id: "deny", effect: "deny", label: "Deny" }] : []);
18917
+ const response = await active.permission({
18918
+ signal: new AbortController().signal,
18919
+ title: gatewayString(prompt.description) || gatewayString(prompt.command) || "Hermes approval requested before this Session attached",
18920
+ description: gatewayString(prompt.command) || gatewayString(prompt.description),
18921
+ options
18922
+ });
18923
+ if (this.#closed)
18924
+ return;
18925
+ if (typeof generation === "number")
18926
+ await this.transport.request("approval.respond", {
18927
+ session_id: this.sessionId,
18928
+ execution_generation: generation,
18929
+ prompt_id: promptId,
18930
+ choice: response ?? "deny"
18931
+ }, this.transport.timeoutMs, false);
18932
+ }
18668
18933
  };
18669
18934
 
18670
18935
  // dist/usage-statistics.js
18671
- import os3 from "node:os";
18672
- import path7 from "node:path";
18936
+ import os2 from "node:os";
18937
+ import path6 from "node:path";
18673
18938
  import { lstat } from "node:fs/promises";
18674
18939
 
18675
18940
  // ../../harness-adapter/dist/usage-statistics.js
@@ -18729,9 +18994,9 @@ function usageEntryFromRequest(request, occurredAtMs) {
18729
18994
 
18730
18995
  // dist/usage-statistics.js
18731
18996
  function hermesStateDatabasePath(environment) {
18732
- const home = environment.HOME || environment.USERPROFILE || os3.homedir();
18997
+ const home = environment.HOME || environment.USERPROFILE || os2.homedir();
18733
18998
  const configured = environment.HERMES_HOME;
18734
- return path7.resolve(configured ? path7.join(configured, "state.db") : path7.join(home, ".hermes", "state.db"));
18999
+ return path6.resolve(configured ? path6.join(configured, "state.db") : path6.join(home, ".hermes", "state.db"));
18735
19000
  }
18736
19001
  async function fingerprint(file2) {
18737
19002
  const info = await lstat(file2).catch(() => null);
@@ -18813,7 +19078,7 @@ function createHermesUsageStatistics(environment) {
18813
19078
  }
18814
19079
 
18815
19080
  // dist/gateway-open.js
18816
- import path8 from "node:path";
19081
+ import path7 from "node:path";
18817
19082
  import { realpath } from "node:fs/promises";
18818
19083
 
18819
19084
  // dist/hermes-session.js
@@ -19023,16 +19288,16 @@ var Diff = class {
19023
19288
  }
19024
19289
  }
19025
19290
  }
19026
- addToPath(path9, added, removed, oldPosInc, options) {
19027
- const last = path9.lastComponent;
19291
+ addToPath(path8, added, removed, oldPosInc, options) {
19292
+ const last = path8.lastComponent;
19028
19293
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
19029
19294
  return {
19030
- oldPos: path9.oldPos + oldPosInc,
19295
+ oldPos: path8.oldPos + oldPosInc,
19031
19296
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
19032
19297
  };
19033
19298
  } else {
19034
19299
  return {
19035
- oldPos: path9.oldPos + oldPosInc,
19300
+ oldPos: path8.oldPos + oldPosInc,
19036
19301
  lastComponent: { count: 1, added, removed, previousComponent: last }
19037
19302
  };
19038
19303
  }
@@ -19347,8 +19612,8 @@ function hermesFileChanges(update) {
19347
19612
  for (const block of update.content ?? []) {
19348
19613
  if (block.type !== "diff")
19349
19614
  continue;
19350
- const { path: path9, oldText, newText } = block;
19351
- if (!path9.trim() || /[\0\r\n]/u.test(path9) || typeof newText !== "string")
19615
+ const { path: path8, oldText, newText } = block;
19616
+ if (!path8.trim() || /[\0\r\n]/u.test(path8) || typeof newText !== "string")
19352
19617
  continue;
19353
19618
  if (oldText === newText)
19354
19619
  continue;
@@ -19356,10 +19621,10 @@ function hermesFileChanges(update) {
19356
19621
  if (bytes > MAX_DIFF_BYTES || changes.length === MAX_DIFFS)
19357
19622
  return [];
19358
19623
  changes.push({
19359
- path: path9,
19624
+ path: path8,
19360
19625
  kind: "update",
19361
19626
  diffScope: "fragment",
19362
- unifiedDiff: createTwoFilesPatch(path9, path9, oldText ?? "", newText, "", "", {
19627
+ unifiedDiff: createTwoFilesPatch(path8, path8, oldText ?? "", newText, "", "", {
19363
19628
  context: 3
19364
19629
  })
19365
19630
  });
@@ -20164,7 +20429,7 @@ ${reason}` }
20164
20429
 
20165
20430
  // dist/gateway-open.js
20166
20431
  async function sameDirectory(left, right) {
20167
- return await realpath(left).catch(() => path8.resolve(left)) === await realpath(right).catch(() => path8.resolve(right));
20432
+ return await realpath(left).catch(() => path7.resolve(left)) === await realpath(right).catch(() => path7.resolve(right));
20168
20433
  }
20169
20434
  var gatewayCapabilities = {
20170
20435
  configuration: {
@@ -20226,8 +20491,10 @@ async function openGatewaySession(input, transport, onSettle, inheritedPermissio
20226
20491
  let nativeRef = source;
20227
20492
  let sourceHistory;
20228
20493
  try {
20229
- await transport.prepareSession();
20230
- await transport.start();
20494
+ if (!transport.started) {
20495
+ await transport.prepareSession();
20496
+ await transport.start();
20497
+ }
20231
20498
  if (source && (input.kind === "fork" || input.kind === "rollbackLastTurn")) {
20232
20499
  sourceHistory = new HermesGatewayHistory({
20233
20500
  python: transport.runtime,
@@ -20237,34 +20504,33 @@ async function openGatewaySession(input, transport, onSettle, inheritedPermissio
20237
20504
  });
20238
20505
  nativeRef = await sourceHistory.derive(input.kind === "fork" ? { checkpoint: input.checkpoint } : { rollbackLastTurn: true });
20239
20506
  }
20240
- const choice = model2 ? await resolveGatewayModel(transport, model2) : null;
20241
- const response = await transport.request(nativeRef ? "session.resume" : "session.create", nativeRef ? { session_id: nativeRef.nativeSessionId, eager_build: true, omit_messages: true } : {
20242
- cwd: input.cwd,
20243
- close_on_disconnect: true,
20244
- ...choice ? choice : {},
20245
- ...input.kind === "create" && input.thinkingOptionId ? { reasoning_effort: input.thinkingOptionId } : {}
20246
- });
20507
+ const response = await transport.request(
20508
+ nativeRef ? "session.resume" : "session.create",
20509
+ // Canonical wire (hermes-gateway-v1, CanonicalCreateParams/CanonicalResumeParams):
20510
+ // no close_on_disconnect / eager_build keys, and the effort key is "reasoning".
20511
+ nativeRef ? { session_id: nativeRef.nativeSessionId, omit_messages: true } : {
20512
+ cwd: input.cwd,
20513
+ ...model2 ? { model: model2 } : {},
20514
+ ...input.kind === "create" && input.thinkingOptionId ? { reasoning: input.thinkingOptionId } : {}
20515
+ }
20516
+ );
20247
20517
  const runtimeId = gatewayString(response.session_id);
20248
20518
  const storedId = nativeRef?.nativeSessionId || gatewayString(response.stored_session_id);
20249
20519
  if (!runtimeId || !storedId)
20250
20520
  throw new Error("Hermes gateway did not return Session identity");
20251
- let info = gatewayRecord(response.info);
20252
- if (info.lazy === true)
20253
- info = await transport.waitForSession(runtimeId);
20521
+ const info = gatewayRecord(response.info);
20254
20522
  const nativeCwd = gatewayString(info.cwd);
20255
20523
  if (nativeCwd && !await sameDirectory(nativeCwd, input.cwd))
20256
20524
  throw new HermesGatewayHistoryError("unsupported", "Hermes resumed a different native working directory");
20257
- const bridge = new HermesGatewaySessionTransport(transport, runtimeId, storedId, info);
20258
- if (!nativeRef)
20259
- await bridge.history.ensureCreated({
20260
- cwd: input.cwd,
20261
- model: gatewayString(info.model),
20262
- provider: gatewayString(info.provider),
20263
- reasoningEffort: gatewayString(info.reasoning_effort)
20264
- });
20265
- const physicalId = await bridge.history.resolvePhysicalSessionId();
20266
- if (gatewayString(info.stored_session_id) !== physicalId)
20267
- throw new Error("Hermes live Session and persisted history identities differ");
20525
+ const bridge = new HermesGatewaySessionTransport(transport, runtimeId, storedId, info, {
20526
+ revision: response.revision,
20527
+ generation: response.execution_generation,
20528
+ subscriptionId: response.subscription_id
20529
+ }, transport.delegationGuidance);
20530
+ bridge.adoptPendingPrompts(response.prompts);
20531
+ if (nativeRef) {
20532
+ await bridge.history.resolvePhysicalSessionId();
20533
+ }
20268
20534
  if (model2)
20269
20535
  await bridge.setModel(model2);
20270
20536
  if (input.kind !== "fork" && input.thinkingOptionId)
@@ -20316,6 +20582,7 @@ var HermesAdapter = class {
20316
20582
  #importReads = /* @__PURE__ */ new Map();
20317
20583
  #closed = false;
20318
20584
  #gatewayTransports = /* @__PURE__ */ new Set();
20585
+ #gatewayPool = new GatewayTransportPool(2);
20319
20586
  #gatewayProbes = /* @__PURE__ */ new Map();
20320
20587
  #openingNativeIds = /* @__PURE__ */ new Set();
20321
20588
  usageStatistics;
@@ -20431,9 +20698,10 @@ var HermesAdapter = class {
20431
20698
  return failure("sessionBusy", "This Hermes Session already has an owner", true);
20432
20699
  if (ref)
20433
20700
  this.#openingNativeIds.add(ref.nativeSessionId);
20434
- const transport = new HermesGatewayTransport(runtime, input.cwd, environment, this.#options.commandTimeoutMs);
20435
- this.#gatewayTransports.add(transport);
20701
+ let transport;
20436
20702
  try {
20703
+ transport = this.#gatewayPool.acquire(runtime, input.cwd, environment) ?? await startGatewayTransport(runtime, input.cwd, environment, this.#options.commandTimeoutMs);
20704
+ this.#gatewayTransports.add(transport);
20437
20705
  let inheritedMode;
20438
20706
  if (input.kind === "fork") {
20439
20707
  const source = [...this.#sessions].find((s) => s.initialState.nativeRef?.nativeSessionId === input.sourceRef.nativeSessionId);
@@ -20444,6 +20712,7 @@ var HermesAdapter = class {
20444
20712
  const session = await openGatewaySession(input, transport, (settled) => {
20445
20713
  this.#sessions.delete(settled);
20446
20714
  this.#gatewayTransports.delete(transport);
20715
+ this.#gatewayPool.release(transport);
20447
20716
  }, inheritedMode);
20448
20717
  if (this.#closed) {
20449
20718
  await session.close();
@@ -20452,8 +20721,10 @@ var HermesAdapter = class {
20452
20721
  this.#sessions.add(session);
20453
20722
  return { ok: true, value: session };
20454
20723
  } catch (error51) {
20455
- await transport.close().catch(() => void 0);
20456
- this.#gatewayTransports.delete(transport);
20724
+ if (transport) {
20725
+ await transport.close().catch(() => void 0);
20726
+ this.#gatewayTransports.delete(transport);
20727
+ }
20457
20728
  return failure(error51 instanceof HermesGatewayHistoryError ? error51.code : "nativeFailure", error51 instanceof Error ? error51.message : "Hermes gateway open failed");
20458
20729
  } finally {
20459
20730
  if (ref)
@@ -20477,6 +20748,7 @@ var HermesAdapter = class {
20477
20748
  await Promise.all(sessions.map((session) => session.close().catch(() => void 0)));
20478
20749
  await Promise.all([...this.#gatewayTransports].map((transport) => transport.close()));
20479
20750
  this.#gatewayTransports.clear();
20751
+ await this.#gatewayPool.close();
20480
20752
  }
20481
20753
  #effectiveEnvironment(environment) {
20482
20754
  return { ...this.#options.environment ?? process.env, ...environment ?? {} };