@liberseek/boft-cli-win32-arm64 0.8.4 → 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 (40) 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 +129 -28
  5. package/app/console-web.js +336 -78
  6. package/app/desktop-controller.mjs +1741 -60
  7. package/app/host-runtime.mjs +4983 -2002
  8. package/app/plugins/antigravity/plugin.mjs +423 -63
  9. package/app/plugins/claude-code/plugin.mjs +417 -264
  10. package/app/plugins/codebuddy/plugin.mjs +256 -134
  11. package/app/plugins/codex-usage/plugin.mjs +97 -32
  12. package/app/plugins/copilot/plugin.mjs +122 -57
  13. package/app/plugins/cursor-cli/plugin.mjs +236 -139
  14. package/app/plugins/deepseek-harness/plugin.mjs +584 -86
  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 +839 -500
  20. package/app/plugins/hermes/plugin.mjs +522 -200
  21. package/app/plugins/kimi-code/plugin.mjs +134 -22
  22. package/app/plugins/kiro-cli/plugin.mjs +84 -19
  23. package/app/plugins/muse/plugin.mjs +74 -9
  24. package/app/plugins/omp/plugin.mjs +104 -39
  25. package/app/plugins/opencode/plugin.mjs +126 -61
  26. package/app/plugins/pi/plugin.mjs +1769 -468
  27. package/app/plugins/qoder/plugin.mjs +9617 -8682
  28. package/app/plugins/qoder-cn/plugin.mjs +9617 -8682
  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 +256 -134
  33. package/app/plugins/zcode/plugin.mjs +265 -42
  34. package/app/renderer-extension.js +3286 -528
  35. package/bin/boft.exe +0 -0
  36. package/libexec/boft-node-repl.exe +0 -0
  37. package/libexec/boft-shim.exe +0 -0
  38. package/libexec/boft-updater.exe +0 -0
  39. package/licenses/Qwen-Code-SDK-LICENSE.txt +203 -0
  40. 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")
@@ -3401,10 +3401,10 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
3401
3401
  const shape = def.shape;
3402
3402
  const propValues = {};
3403
3403
  for (const key in shape) {
3404
- const field = shape[key]._zod;
3405
- if (field.values) {
3404
+ const field2 = shape[key]._zod;
3405
+ if (field2.values) {
3406
3406
  propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
3407
- for (const v of field.values)
3407
+ for (const v of field2.values)
3408
3408
  propValues[key].add(v);
3409
3409
  }
3410
3410
  }
@@ -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
  }
@@ -15044,6 +15044,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
15044
15044
  cachedInputTokens: count,
15045
15045
  cacheWriteInputTokens: count,
15046
15046
  cacheKnownInputTokens: count,
15047
+ cacheHitCachedInputTokens: count,
15048
+ cacheHitInputTokens: count,
15047
15049
  outputTokens: count,
15048
15050
  reasoningOutputTokens: count,
15049
15051
  /** USD at the public price, summed over the priced requests only. */
@@ -15151,6 +15153,51 @@ var hostInteractionIdSchema = opaqueIdSchema.brand();
15151
15153
  var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
15152
15154
  var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
15153
15155
 
15156
+ // ../../shared-contracts/dist/thread-questions.js
15157
+ var field = external_exports.discriminatedUnion("type", [
15158
+ external_exports.object({
15159
+ id: external_exports.string().min(1),
15160
+ type: external_exports.literal("choice"),
15161
+ prompt: external_exports.string(),
15162
+ options: external_exports.array(external_exports.object({
15163
+ value: external_exports.string().min(1),
15164
+ label: external_exports.string(),
15165
+ description: external_exports.string().optional()
15166
+ })).min(1),
15167
+ multiple: external_exports.boolean(),
15168
+ allowOther: external_exports.boolean(),
15169
+ optional: external_exports.boolean()
15170
+ }),
15171
+ external_exports.object({
15172
+ id: external_exports.string().min(1),
15173
+ type: external_exports.literal("text"),
15174
+ prompt: external_exports.string(),
15175
+ multiline: external_exports.boolean(),
15176
+ secret: external_exports.literal(false),
15177
+ optional: external_exports.boolean(),
15178
+ placeholder: external_exports.string().optional(),
15179
+ prefill: external_exports.string().optional()
15180
+ })
15181
+ ]);
15182
+ var threadQuestionSchema = external_exports.object({
15183
+ interactionId: external_exports.string().min(1),
15184
+ turnId: external_exports.string().min(1),
15185
+ title: external_exports.string().optional(),
15186
+ questions: external_exports.array(field).min(1)
15187
+ }).refine(({ questions }) => questions.some((q) => q.type === "choice" && q.multiple), {
15188
+ message: "Shared cards require at least one multi-select question"
15189
+ });
15190
+ var threadQuestionsListParamsSchema = external_exports.strictObject({ threadId: external_exports.string().min(1) });
15191
+ var threadQuestionsResultSchema = external_exports.object({ questions: external_exports.array(threadQuestionSchema) });
15192
+ var threadQuestionRespondParamsSchema = external_exports.strictObject({
15193
+ threadId: external_exports.string().min(1),
15194
+ turnId: external_exports.string().min(1),
15195
+ interactionId: external_exports.string().min(1),
15196
+ answers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
15197
+ cancelled: external_exports.boolean().default(false)
15198
+ });
15199
+ var threadQuestionRespondResultSchema = external_exports.object({ accepted: external_exports.literal(true) });
15200
+
15154
15201
  // ../../shared-contracts/dist/harness-plugins.js
15155
15202
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15156
15203
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -15910,6 +15957,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
15910
15957
  /** The text about to be steered; a Harness command always stops and restarts. */
15911
15958
  text: external_exports.string().optional()
15912
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);
15913
15975
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15914
15976
  var threadSteeringInspectResultSchema = external_exports.object({
15915
15977
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -15920,7 +15982,10 @@ var harnessPluginRouteSchema = external_exports.object({
15920
15982
  harnessId: harnessPluginIdSchema,
15921
15983
  model: harnessModelRefSchema.optional(),
15922
15984
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
15923
- permissionModeId: harnessPermissionModeIdSchema.optional()
15985
+ permissionModeId: harnessPermissionModeIdSchema.optional(),
15986
+ /** A draft prewarm create: stays unsubmitted until the user's first Turn.
15987
+ * Desktop forwards only the Model of a main-process prewarm to thread/start. */
15988
+ prewarm: external_exports.literal(true).optional()
15924
15989
  }).strict();
15925
15990
 
15926
15991
  // ../../shared-contracts/dist/harness-launch-settings.js
@@ -16617,7 +16682,35 @@ import path4 from "node:path";
16617
16682
 
16618
16683
  // dist/hermes-runtime.js
16619
16684
  import { execFile as execFile2 } from "node:child_process";
16685
+ import { statSync } from "node:fs";
16620
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
+ }
16621
16714
  function legacyHermesPythonCommand(python, script) {
16622
16715
  return {
16623
16716
  command: python,
@@ -16633,22 +16726,12 @@ ${script}`
16633
16726
  };
16634
16727
  }
16635
16728
  async function nativeHermesPythonCommand(launcher, script, environment, timeoutMs = 2e4, platform = process.platform) {
16636
- const invocation = commandInvocation(launcher, [
16637
- "--print-runtime-command",
16638
- "--module",
16639
- "timeit",
16640
- "--",
16641
- "-n",
16642
- "1",
16643
- "-r",
16644
- "1",
16645
- "-s",
16646
- // timeit is a stdlib entry point supported by the native launcher. After
16647
- // the operation returns, redirect its timing footer, preserving normal
16648
- // native cleanup and exit status without contaminating JSON/RPC stdout.
16649
- `exec(${JSON.stringify(script)}, {}); import sys, io; sys.stdout = io.StringIO()`,
16650
- "pass"
16651
- ], 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);
16652
16735
  let stdout;
16653
16736
  try {
16654
16737
  ({ stdout } = await promisify(execFile2)(invocation.command, invocation.arguments, {
@@ -16668,6 +16751,9 @@ async function nativeHermesPythonCommand(launcher, script, environment, timeoutM
16668
16751
  if (!Array.isArray(value) || value.length === 0 || !value.every((arg) => typeof arg === "string") || !value[0]) {
16669
16752
  throw new Error("Hermes launcher returned an invalid runtime command");
16670
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));
16671
16757
  return { command: value[0], arguments: value.slice(1) };
16672
16758
  }
16673
16759
  async function hermesPythonCommand(runtime, script, environment, timeoutMs = 2e4) {
@@ -16980,9 +17066,6 @@ function catalogModelsFromInventory(inventory) {
16980
17066
  }
16981
17067
 
16982
17068
  // dist/gateway-delegation.js
16983
- import { mkdtemp as mkdtemp2, writeFile as writeFile2, rm as rm2 } from "node:fs/promises";
16984
- import os2 from "node:os";
16985
- import path5 from "node:path";
16986
17069
  var HERMES_DELEGATION_GUIDANCE = `This Session runs inside codexhost.
16987
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.`;
16988
17071
  var required2 = [
@@ -16993,48 +17076,40 @@ var required2 = [
16993
17076
  ];
16994
17077
  async function prepareGatewayDelegation(environment) {
16995
17078
  if (!required2.every((key) => environment[key]))
16996
- return { environment, bootstrap: "", dispose: async () => {
17079
+ return { environment, bootstrap: "", guidance: null, dispose: async () => {
16997
17080
  } };
16998
- const directory = await mkdtemp2(path5.join(os2.tmpdir(), "codexhost-hermes-delegation-"));
16999
- const file2 = path5.join(directory, "SKILL.md");
17000
- try {
17001
- await writeFile2(file2, `---
17002
- name: delegation
17003
- description: Discover authorized codexhost agent collaboration.
17004
- ---
17005
-
17006
- ${HERMES_DELEGATION_GUIDANCE}
17007
- `, { mode: 384 });
17008
- return {
17009
- environment: {
17010
- ...environment,
17011
- HERMES_TUI_SKILLS: [environment.HERMES_TUI_SKILLS, "codexhost-runtime:delegation"].filter(Boolean).join(",")
17012
- },
17013
- // Reserve RPC stdout before native plugin imports. The registration is
17014
- // process-local; no plugin is installed and no user config is changed.
17015
- //
17016
- // ``hermes_bootstrap`` must run before ``tui_gateway.server`` is imported:
17017
- // the gateway spawn uses ``python -I``, so PYTHONPATH and the launcher's
17018
- // activation are stripped. Hermes's own entry point (``tui_gateway/entry.py``)
17019
- // imports this module first to put the selected dependency environment on
17020
- // ``sys.path``; skipping it makes bare third-party imports (e.g.
17021
- // ``hermes_yaml`` -> ``ruamel``) fail on interpreters whose site-packages
17022
- // do not already carry Hermes's dependencies. ``hermes_bootstrap`` is
17023
- // import-safe here for the same reason entry.py relies on it: stdlib-only
17024
- // at import time, so nothing can shadow it from the launch directory.
17025
- 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
17026
17097
  from tui_gateway import server
17027
- from pathlib import Path
17028
- from hermes_cli.plugins import PluginContext, PluginManifest, get_plugin_manager
17029
- PluginContext(PluginManifest(name="codexhost-runtime"), get_plugin_manager()).register_skill(
17030
- "delegation", Path(${JSON.stringify(file2)}))
17098
+ sys.stdout = _stdout
17031
17099
  `,
17032
- dispose: () => rm2(directory, { recursive: true, force: true })
17033
- };
17034
- } catch (error51) {
17035
- await rm2(directory, { recursive: true, force: true });
17036
- throw error51;
17037
- }
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
+ };
17038
17113
  }
17039
17114
 
17040
17115
  // dist/hermes-transport.js
@@ -17068,8 +17143,87 @@ function gatewayRecord(value) {
17068
17143
  function gatewayString(value) {
17069
17144
  return typeof value === "string" ? value : "";
17070
17145
  }
17071
- var GATEWAY_LAUNCH = `import runpy
17072
- 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
+ `;
17073
17227
  var HermesGatewayTransport = class _HermesGatewayTransport {
17074
17228
  runtime;
17075
17229
  cwd;
@@ -17096,6 +17250,18 @@ var HermesGatewayTransport = class _HermesGatewayTransport {
17096
17250
  this.environment = environment;
17097
17251
  this.timeoutMs = timeoutMs;
17098
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
+ }
17099
17265
  static async probe(executable, cwd, environment) {
17100
17266
  const override = environment.CODEXHOST_HERMES_GATEWAY_PYTHON;
17101
17267
  if (override) {
@@ -17608,7 +17774,7 @@ async function resolveHermesSessionCandidate(input) {
17608
17774
  }
17609
17775
 
17610
17776
  // dist/command.js
17611
- import path6 from "node:path";
17777
+ import path5 from "node:path";
17612
17778
  var HermesExecutableError = class extends Error {
17613
17779
  code = "HERMES_NOT_FOUND";
17614
17780
  };
@@ -17631,7 +17797,62 @@ function resolveHermesExecutable(input = {}) {
17631
17797
  });
17632
17798
  if (!resolution)
17633
17799
  throw new HermesExecutableError("Hermes CLI is not installed");
17634
- 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;
17635
17856
  }
17636
17857
 
17637
17858
  // dist/gateway-history.js
@@ -17721,21 +17942,24 @@ def capture(db):
17721
17942
  boundaries[str(row['id'])] = {'count': end, 'digest': digest(active[:end])}
17722
17943
  return exported, {'rows': rows, 'derivable': derivable, 'boundaries': boundaries, 'physicalSessionId': sid}
17723
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
+
17724
17958
  try:
17725
17959
  if p['operation'] == 'ensure':
17726
17960
  db = SessionDB()
17727
17961
  try:
17728
- if db.get_session(sid) is None:
17729
- from hermes_constants import parse_reasoning_effort
17730
- initial = {}
17731
- if isinstance(p.get('provider'), str) and p['provider']: initial['provider'] = p['provider']
17732
- if isinstance(p.get('model'), str) and p['model']: initial['model'] = p['model']
17733
- if isinstance(p.get('reasoningEffort'), str):
17734
- reasoning = parse_reasoning_effort(p['reasoningEffort'])
17735
- if reasoning is not None: initial['reasoning_config'] = reasoning
17736
- if isinstance(p.get('yolo'), bool): initial['yolo_mode'] = p['yolo']
17737
- db.create_session(session_id=sid, source='cli', cwd=p['cwd'], model=p.get('model'), model_config=initial)
17738
- result = {'created': True}
17962
+ result = ensure_session_row(db)
17739
17963
  finally: db.close()
17740
17964
  elif p['operation'] == 'discard':
17741
17965
  child = p['derivedSessionId']
@@ -18103,28 +18327,6 @@ var HermesUsage = class {
18103
18327
  }
18104
18328
  };
18105
18329
 
18106
- // dist/gateway-configuration.js
18107
- import { execFile as execFile4 } from "node:child_process";
18108
- import { promisify as promisify3 } from "node:util";
18109
- async function resolveGatewayModel(transport, modelId) {
18110
- if (/\s/u.test(modelId) || modelId.startsWith("-"))
18111
- throw new Error("Invalid Hermes Model identifier");
18112
- const command = await hermesPythonCommand(transport.runtime, `import json
18113
- from hermes_cli.models import parse_model_input
18114
- p,m=parse_model_input(${JSON.stringify(modelId)}, '')
18115
- print(json.dumps({'provider':p,'model':m}))`, { ...process.env, ...transport.environment });
18116
- const result = await promisify3(execFile4)(command.command, command.arguments, {
18117
- cwd: transport.cwd,
18118
- env: { ...process.env, ...transport.environment },
18119
- timeout: 2e4,
18120
- maxBuffer: 1024 * 1024
18121
- });
18122
- const value = JSON.parse(result.stdout.trim());
18123
- if (!value || typeof value !== "object" || !("provider" in value) || !("model" in value) || typeof value.provider !== "string" || typeof value.model !== "string")
18124
- throw new Error("Hermes returned an invalid Model choice");
18125
- return { provider: value.provider, model: value.model };
18126
- }
18127
-
18128
18330
  // dist/gateway-session-transport.js
18129
18331
  var hermesGatewayThinkingOptions = [
18130
18332
  "none",
@@ -18156,14 +18358,14 @@ function gatewayDiff(text2) {
18156
18358
  if (!text2 || text2.length > 1024 * 1024)
18157
18359
  return [];
18158
18360
  const result = [];
18159
- let path9 = "";
18361
+ let path8 = "";
18160
18362
  let inHunk = false;
18161
18363
  let oldLines = [], newLines = [];
18162
18364
  const flush = () => {
18163
- if (path9)
18365
+ if (path8)
18164
18366
  result.push({
18165
18367
  type: "diff",
18166
- path: path9,
18368
+ path: path8,
18167
18369
  oldText: oldLines.join("\n"),
18168
18370
  newText: newLines.join("\n")
18169
18371
  });
@@ -18176,24 +18378,24 @@ function gatewayDiff(text2) {
18176
18378
  if (header) {
18177
18379
  flush();
18178
18380
  inHunk = false;
18179
- 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, "");
18180
18382
  continue;
18181
18383
  }
18182
18384
  if (line.startsWith("--- ") && !inHunk) {
18183
18385
  flush();
18184
- path9 = line.slice(4).replace(/^a\//u, "");
18386
+ path8 = line.slice(4).replace(/^a\//u, "");
18185
18387
  } else if (line.startsWith("+++ ") && !inHunk) {
18186
18388
  const next = line.slice(4);
18187
18389
  if (next !== "/dev/null")
18188
- path9 = next.replace(/^b\//u, "");
18390
+ path8 = next.replace(/^b\//u, "");
18189
18391
  } else if (line.startsWith("@@")) {
18190
18392
  inHunk = true;
18191
18393
  continue;
18192
- } else if (path9 && line.startsWith("-"))
18394
+ } else if (path8 && line.startsWith("-"))
18193
18395
  oldLines.push(line.slice(1));
18194
- else if (path9 && line.startsWith("+"))
18396
+ else if (path8 && line.startsWith("+"))
18195
18397
  newLines.push(line.slice(1));
18196
- else if (path9 && line.startsWith(" ")) {
18398
+ else if (path8 && line.startsWith(" ")) {
18197
18399
  oldLines.push(line.slice(1));
18198
18400
  newLines.push(line.slice(1));
18199
18401
  }
@@ -18217,7 +18419,7 @@ var HermesGatewaySessionTransport = class {
18217
18419
  return this.#commands;
18218
18420
  }
18219
18421
  async getCommands() {
18220
- const params = { session_id: this.sessionId, cwd: this.transport.cwd };
18422
+ const params = { session_id: this.sessionId };
18221
18423
  const [response, catalog] = await Promise.all([
18222
18424
  this.transport.request("complete.slash", { ...params, text: "/" }, this.transport.timeoutMs, false),
18223
18425
  this.transport.request("commands.catalog", params, this.transport.timeoutMs, false)
@@ -18242,13 +18444,29 @@ var HermesGatewaySessionTransport = class {
18242
18444
  history;
18243
18445
  #active = null;
18244
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 = [];
18245
18451
  #closed = false;
18246
18452
  #info;
18247
- 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) {
18248
18459
  this.transport = transport;
18249
18460
  this.sessionId = sessionId;
18250
18461
  this.nativeSessionId = nativeSessionId;
18251
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;
18252
18470
  this.history = new HermesGatewayHistory({
18253
18471
  python: transport.runtime,
18254
18472
  cwd: transport.cwd,
@@ -18309,17 +18527,24 @@ var HermesGatewaySessionTransport = class {
18309
18527
  return optionId;
18310
18528
  }
18311
18529
  async setModel(modelId) {
18312
- const choice = await resolveGatewayModel(this.transport, modelId);
18313
- const result = await this.transport.request("config.set", {
18314
- key: "model",
18315
- value: choice.provider ? `${choice.model} --provider ${choice.provider}` : modelId,
18316
- scope: "session",
18317
- 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 }
18318
18541
  });
18319
- if (result.confirm_required === true)
18320
- throw new Error(gatewayString(result.confirm_message) || "Hermes requires confirmation for this Model");
18321
- const actualModel = gatewayString(this.#info.model);
18322
- 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);
18323
18548
  if (modelId !== actualModel && modelId !== `${actualProvider}:${actualModel}`)
18324
18549
  throw new Error("Hermes did not confirm the requested Model");
18325
18550
  }
@@ -18329,11 +18554,11 @@ var HermesGatewaySessionTransport = class {
18329
18554
  const result = await this.transport.request("config.set", {
18330
18555
  key: "yolo",
18331
18556
  value: modeId === "dont_ask" ? "on" : "off",
18332
- scope: "session",
18333
18557
  session_id: this.sessionId
18334
18558
  });
18335
- if (result.value !== (modeId === "dont_ask" ? "1" : "0") || this.#info.yolo !== (modeId === "dont_ask"))
18559
+ if (result.value !== (modeId === "dont_ask" ? "1" : "0"))
18336
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" };
18337
18562
  }
18338
18563
  nativeCommandName(text2) {
18339
18564
  return hermesGatewayCommandName(text2, this.#commands);
@@ -18356,9 +18581,11 @@ var HermesGatewaySessionTransport = class {
18356
18581
  reject: rejectResult,
18357
18582
  streamed: "",
18358
18583
  reasoning: "",
18359
- toolIds: /* @__PURE__ */ new Set()
18584
+ toolIds: /* @__PURE__ */ new Set(),
18585
+ admissionId: null
18360
18586
  };
18361
18587
  this.#active = active;
18588
+ void this.#adoptedPrompts.splice(0).map((prompt) => void this.#respondAdoptedApproval(prompt, active).catch(() => void 0));
18362
18589
  const commandText = text2.trim();
18363
18590
  const nativeCommand = this.nativeCommandName(text2);
18364
18591
  try {
@@ -18397,12 +18624,21 @@ var HermesGatewaySessionTransport = class {
18397
18624
  emit({ type: "agent.text", text: response.output });
18398
18625
  active.resolve({ stopReason: "end_turn" });
18399
18626
  } else {
18627
+ const guidance = this.#delegationGuidance;
18628
+ this.#delegationGuidance = null;
18400
18629
  const submitted = await this.transport.request("prompt.submit", {
18401
18630
  session_id: this.sessionId,
18402
- 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}` } : {}
18403
18637
  });
18404
- if (submitted.status !== "streaming")
18405
- 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;
18406
18642
  }
18407
18643
  } catch (error51) {
18408
18644
  active.reject(error51 instanceof Error ? error51 : new Error(String(error51)));
@@ -18418,7 +18654,12 @@ var HermesGatewaySessionTransport = class {
18418
18654
  }
18419
18655
  }
18420
18656
  async cancel() {
18421
- 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
+ });
18422
18663
  }
18423
18664
  async close() {
18424
18665
  if (this.#closed)
@@ -18429,10 +18670,13 @@ var HermesGatewaySessionTransport = class {
18429
18670
  this.#requests.clear();
18430
18671
  this.#active?.reject(new Error("Hermes gateway Session closed"));
18431
18672
  try {
18432
- 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
+ });
18433
18678
  } catch {
18434
18679
  }
18435
- await this.transport.close();
18436
18680
  }
18437
18681
  #fault(error51) {
18438
18682
  if (this.#closed)
@@ -18452,6 +18696,10 @@ var HermesGatewaySessionTransport = class {
18452
18696
  const payload = gatewayRecord(event.payload);
18453
18697
  if (event.type === "session.info") {
18454
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;
18455
18703
  return;
18456
18704
  }
18457
18705
  if (event.type === "session.usage") {
@@ -18463,12 +18711,26 @@ var HermesGatewaySessionTransport = class {
18463
18711
  controller?.abort(payload.reason === "timeout" ? "expired" : "cancelled");
18464
18712
  return;
18465
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
+ }
18466
18722
  const active = this.#active;
18467
18723
  if (!active) {
18468
18724
  if (event.type === "error")
18469
18725
  this.#fault(new Error(gatewayString(payload.message)));
18470
18726
  return;
18471
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
+ }
18472
18734
  const text2 = gatewayString(payload.text);
18473
18735
  if (event.type === "message.delta") {
18474
18736
  active.streamed += text2;
@@ -18599,27 +18861,80 @@ var HermesGatewaySessionTransport = class {
18599
18861
  label: choice === "session" ? "Allow for this session" : "Always allow"
18600
18862
  }
18601
18863
  ] : choice === "deny" ? [{ id: "deny", effect: "deny", label: "Deny" }] : []);
18602
- const response = await active.permission({
18603
- signal: controller.signal,
18604
- title: gatewayString(params.description) || gatewayString(params.command),
18605
- description: gatewayString(params.command) || gatewayString(params.description),
18606
- options
18607
- });
18608
- if (!controller.signal.aborted)
18609
- this.transport.respond(id, {
18610
- 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
18611
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
+ }
18612
18882
  } else
18613
18883
  this.transport.rejectRequest(id);
18614
18884
  } finally {
18615
18885
  this.#requests.delete(id);
18616
18886
  }
18617
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
+ }
18618
18933
  };
18619
18934
 
18620
18935
  // dist/usage-statistics.js
18621
- import os3 from "node:os";
18622
- import path7 from "node:path";
18936
+ import os2 from "node:os";
18937
+ import path6 from "node:path";
18623
18938
  import { lstat } from "node:fs/promises";
18624
18939
 
18625
18940
  // ../../harness-adapter/dist/usage-statistics.js
@@ -18679,9 +18994,9 @@ function usageEntryFromRequest(request, occurredAtMs) {
18679
18994
 
18680
18995
  // dist/usage-statistics.js
18681
18996
  function hermesStateDatabasePath(environment) {
18682
- const home = environment.HOME || environment.USERPROFILE || os3.homedir();
18997
+ const home = environment.HOME || environment.USERPROFILE || os2.homedir();
18683
18998
  const configured = environment.HERMES_HOME;
18684
- 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"));
18685
19000
  }
18686
19001
  async function fingerprint(file2) {
18687
19002
  const info = await lstat(file2).catch(() => null);
@@ -18763,7 +19078,7 @@ function createHermesUsageStatistics(environment) {
18763
19078
  }
18764
19079
 
18765
19080
  // dist/gateway-open.js
18766
- import path8 from "node:path";
19081
+ import path7 from "node:path";
18767
19082
  import { realpath } from "node:fs/promises";
18768
19083
 
18769
19084
  // dist/hermes-session.js
@@ -18973,16 +19288,16 @@ var Diff = class {
18973
19288
  }
18974
19289
  }
18975
19290
  }
18976
- addToPath(path9, added, removed, oldPosInc, options) {
18977
- const last = path9.lastComponent;
19291
+ addToPath(path8, added, removed, oldPosInc, options) {
19292
+ const last = path8.lastComponent;
18978
19293
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
18979
19294
  return {
18980
- oldPos: path9.oldPos + oldPosInc,
19295
+ oldPos: path8.oldPos + oldPosInc,
18981
19296
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
18982
19297
  };
18983
19298
  } else {
18984
19299
  return {
18985
- oldPos: path9.oldPos + oldPosInc,
19300
+ oldPos: path8.oldPos + oldPosInc,
18986
19301
  lastComponent: { count: 1, added, removed, previousComponent: last }
18987
19302
  };
18988
19303
  }
@@ -19297,8 +19612,8 @@ function hermesFileChanges(update) {
19297
19612
  for (const block of update.content ?? []) {
19298
19613
  if (block.type !== "diff")
19299
19614
  continue;
19300
- const { path: path9, oldText, newText } = block;
19301
- 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")
19302
19617
  continue;
19303
19618
  if (oldText === newText)
19304
19619
  continue;
@@ -19306,10 +19621,10 @@ function hermesFileChanges(update) {
19306
19621
  if (bytes > MAX_DIFF_BYTES || changes.length === MAX_DIFFS)
19307
19622
  return [];
19308
19623
  changes.push({
19309
- path: path9,
19624
+ path: path8,
19310
19625
  kind: "update",
19311
19626
  diffScope: "fragment",
19312
- unifiedDiff: createTwoFilesPatch(path9, path9, oldText ?? "", newText, "", "", {
19627
+ unifiedDiff: createTwoFilesPatch(path8, path8, oldText ?? "", newText, "", "", {
19313
19628
  context: 3
19314
19629
  })
19315
19630
  });
@@ -20114,7 +20429,7 @@ ${reason}` }
20114
20429
 
20115
20430
  // dist/gateway-open.js
20116
20431
  async function sameDirectory(left, right) {
20117
- 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));
20118
20433
  }
20119
20434
  var gatewayCapabilities = {
20120
20435
  configuration: {
@@ -20176,8 +20491,10 @@ async function openGatewaySession(input, transport, onSettle, inheritedPermissio
20176
20491
  let nativeRef = source;
20177
20492
  let sourceHistory;
20178
20493
  try {
20179
- await transport.prepareSession();
20180
- await transport.start();
20494
+ if (!transport.started) {
20495
+ await transport.prepareSession();
20496
+ await transport.start();
20497
+ }
20181
20498
  if (source && (input.kind === "fork" || input.kind === "rollbackLastTurn")) {
20182
20499
  sourceHistory = new HermesGatewayHistory({
20183
20500
  python: transport.runtime,
@@ -20187,34 +20504,33 @@ async function openGatewaySession(input, transport, onSettle, inheritedPermissio
20187
20504
  });
20188
20505
  nativeRef = await sourceHistory.derive(input.kind === "fork" ? { checkpoint: input.checkpoint } : { rollbackLastTurn: true });
20189
20506
  }
20190
- const choice = model2 ? await resolveGatewayModel(transport, model2) : null;
20191
- const response = await transport.request(nativeRef ? "session.resume" : "session.create", nativeRef ? { session_id: nativeRef.nativeSessionId, eager_build: true, omit_messages: true } : {
20192
- cwd: input.cwd,
20193
- close_on_disconnect: true,
20194
- ...choice ? choice : {},
20195
- ...input.kind === "create" && input.thinkingOptionId ? { reasoning_effort: input.thinkingOptionId } : {}
20196
- });
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
+ );
20197
20517
  const runtimeId = gatewayString(response.session_id);
20198
20518
  const storedId = nativeRef?.nativeSessionId || gatewayString(response.stored_session_id);
20199
20519
  if (!runtimeId || !storedId)
20200
20520
  throw new Error("Hermes gateway did not return Session identity");
20201
- let info = gatewayRecord(response.info);
20202
- if (info.lazy === true)
20203
- info = await transport.waitForSession(runtimeId);
20521
+ const info = gatewayRecord(response.info);
20204
20522
  const nativeCwd = gatewayString(info.cwd);
20205
20523
  if (nativeCwd && !await sameDirectory(nativeCwd, input.cwd))
20206
20524
  throw new HermesGatewayHistoryError("unsupported", "Hermes resumed a different native working directory");
20207
- const bridge = new HermesGatewaySessionTransport(transport, runtimeId, storedId, info);
20208
- if (!nativeRef)
20209
- await bridge.history.ensureCreated({
20210
- cwd: input.cwd,
20211
- model: gatewayString(info.model),
20212
- provider: gatewayString(info.provider),
20213
- reasoningEffort: gatewayString(info.reasoning_effort)
20214
- });
20215
- const physicalId = await bridge.history.resolvePhysicalSessionId();
20216
- if (gatewayString(info.stored_session_id) !== physicalId)
20217
- 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
+ }
20218
20534
  if (model2)
20219
20535
  await bridge.setModel(model2);
20220
20536
  if (input.kind !== "fork" && input.thinkingOptionId)
@@ -20266,6 +20582,7 @@ var HermesAdapter = class {
20266
20582
  #importReads = /* @__PURE__ */ new Map();
20267
20583
  #closed = false;
20268
20584
  #gatewayTransports = /* @__PURE__ */ new Set();
20585
+ #gatewayPool = new GatewayTransportPool(2);
20269
20586
  #gatewayProbes = /* @__PURE__ */ new Map();
20270
20587
  #openingNativeIds = /* @__PURE__ */ new Set();
20271
20588
  usageStatistics;
@@ -20381,9 +20698,10 @@ var HermesAdapter = class {
20381
20698
  return failure("sessionBusy", "This Hermes Session already has an owner", true);
20382
20699
  if (ref)
20383
20700
  this.#openingNativeIds.add(ref.nativeSessionId);
20384
- const transport = new HermesGatewayTransport(runtime, input.cwd, environment, this.#options.commandTimeoutMs);
20385
- this.#gatewayTransports.add(transport);
20701
+ let transport;
20386
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);
20387
20705
  let inheritedMode;
20388
20706
  if (input.kind === "fork") {
20389
20707
  const source = [...this.#sessions].find((s) => s.initialState.nativeRef?.nativeSessionId === input.sourceRef.nativeSessionId);
@@ -20394,6 +20712,7 @@ var HermesAdapter = class {
20394
20712
  const session = await openGatewaySession(input, transport, (settled) => {
20395
20713
  this.#sessions.delete(settled);
20396
20714
  this.#gatewayTransports.delete(transport);
20715
+ this.#gatewayPool.release(transport);
20397
20716
  }, inheritedMode);
20398
20717
  if (this.#closed) {
20399
20718
  await session.close();
@@ -20402,8 +20721,10 @@ var HermesAdapter = class {
20402
20721
  this.#sessions.add(session);
20403
20722
  return { ok: true, value: session };
20404
20723
  } catch (error51) {
20405
- await transport.close().catch(() => void 0);
20406
- this.#gatewayTransports.delete(transport);
20724
+ if (transport) {
20725
+ await transport.close().catch(() => void 0);
20726
+ this.#gatewayTransports.delete(transport);
20727
+ }
20407
20728
  return failure(error51 instanceof HermesGatewayHistoryError ? error51.code : "nativeFailure", error51 instanceof Error ? error51.message : "Hermes gateway open failed");
20408
20729
  } finally {
20409
20730
  if (ref)
@@ -20427,6 +20748,7 @@ var HermesAdapter = class {
20427
20748
  await Promise.all(sessions.map((session) => session.close().catch(() => void 0)));
20428
20749
  await Promise.all([...this.#gatewayTransports].map((transport) => transport.close()));
20429
20750
  this.#gatewayTransports.clear();
20751
+ await this.#gatewayPool.close();
20430
20752
  }
20431
20753
  #effectiveEnvironment(environment) {
20432
20754
  return { ...this.#options.environment ?? process.env, ...environment ?? {} };