@codexhost/cli-darwin-x64 0.14.0 → 0.16.0

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.
@@ -777,10 +777,10 @@ function mergeDefs(...defs) {
777
777
  function cloneDef(schema) {
778
778
  return mergeDefs(schema._zod.def);
779
779
  }
780
- function getElementAtPath(obj, path19) {
781
- if (!path19)
780
+ function getElementAtPath(obj, path18) {
781
+ if (!path18)
782
782
  return obj;
783
- return path19.reduce((acc, key) => acc?.[key], obj);
783
+ return path18.reduce((acc, key) => acc?.[key], obj);
784
784
  }
785
785
  function promiseAllObject(promisesObj) {
786
786
  const keys = Object.keys(promisesObj);
@@ -1189,11 +1189,11 @@ function explicitlyAborted(x, startIndex = 0) {
1189
1189
  }
1190
1190
  return false;
1191
1191
  }
1192
- function prefixIssues(path19, issues) {
1192
+ function prefixIssues(path18, issues) {
1193
1193
  return issues.map((iss) => {
1194
1194
  var _a4;
1195
1195
  (_a4 = iss).path ?? (_a4.path = []);
1196
- iss.path.unshift(path19);
1196
+ iss.path.unshift(path18);
1197
1197
  return iss;
1198
1198
  });
1199
1199
  }
@@ -1340,16 +1340,16 @@ function flattenError(error52, mapper = (issue2) => issue2.message) {
1340
1340
  }
1341
1341
  function formatError(error52, mapper = (issue2) => issue2.message) {
1342
1342
  const fieldErrors = { _errors: [] };
1343
- const processError = (error53, path19 = []) => {
1343
+ const processError = (error53, path18 = []) => {
1344
1344
  for (const issue2 of error53.issues) {
1345
1345
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1346
- issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1346
+ issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
1347
1347
  } else if (issue2.code === "invalid_key") {
1348
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1348
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1349
1349
  } else if (issue2.code === "invalid_element") {
1350
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1350
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1351
1351
  } else {
1352
- const fullpath = [...path19, ...issue2.path];
1352
+ const fullpath = [...path18, ...issue2.path];
1353
1353
  if (fullpath.length === 0) {
1354
1354
  fieldErrors._errors.push(mapper(issue2));
1355
1355
  } else {
@@ -1376,17 +1376,17 @@ function formatError(error52, mapper = (issue2) => issue2.message) {
1376
1376
  }
1377
1377
  function treeifyError(error52, mapper = (issue2) => issue2.message) {
1378
1378
  const result = { errors: [] };
1379
- const processError = (error53, path19 = []) => {
1379
+ const processError = (error53, path18 = []) => {
1380
1380
  var _a4, _b2;
1381
1381
  for (const issue2 of error53.issues) {
1382
1382
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1383
- issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1383
+ issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
1384
1384
  } else if (issue2.code === "invalid_key") {
1385
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1385
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1386
1386
  } else if (issue2.code === "invalid_element") {
1387
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1387
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1388
1388
  } else {
1389
- const fullpath = [...path19, ...issue2.path];
1389
+ const fullpath = [...path18, ...issue2.path];
1390
1390
  if (fullpath.length === 0) {
1391
1391
  result.errors.push(mapper(issue2));
1392
1392
  continue;
@@ -1418,8 +1418,8 @@ function treeifyError(error52, mapper = (issue2) => issue2.message) {
1418
1418
  }
1419
1419
  function toDotPath(_path) {
1420
1420
  const segs = [];
1421
- const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1422
- for (const seg of path19) {
1421
+ const path18 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1422
+ for (const seg of path18) {
1423
1423
  if (typeof seg === "number")
1424
1424
  segs.push(`[${seg}]`);
1425
1425
  else if (typeof seg === "symbol")
@@ -3040,10 +3040,10 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
3040
3040
  const shape = def.shape;
3041
3041
  const propValues = {};
3042
3042
  for (const key in shape) {
3043
- const field = shape[key]._zod;
3044
- if (field.values) {
3043
+ const field2 = shape[key]._zod;
3044
+ if (field2.values) {
3045
3045
  propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
3046
- for (const v of field.values)
3046
+ for (const v of field2.values)
3047
3047
  propValues[key].add(v);
3048
3048
  }
3049
3049
  }
@@ -14111,13 +14111,13 @@ function resolveRef(ref, ctx) {
14111
14111
  if (!ref.startsWith("#")) {
14112
14112
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14113
14113
  }
14114
- const path19 = ref.slice(1).split("/").filter(Boolean);
14115
- if (path19.length === 0) {
14114
+ const path18 = ref.slice(1).split("/").filter(Boolean);
14115
+ if (path18.length === 0) {
14116
14116
  return ctx.rootSchema;
14117
14117
  }
14118
14118
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14119
- if (path19[0] === defsKey) {
14120
- const key = path19[1];
14119
+ if (path18[0] === defsKey) {
14120
+ const key = path18[1];
14121
14121
  if (!key || !ctx.defs[key]) {
14122
14122
  throw new Error(`Reference not found: ${ref}`);
14123
14123
  }
@@ -14683,6 +14683,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
14683
14683
  cachedInputTokens: count,
14684
14684
  cacheWriteInputTokens: count,
14685
14685
  cacheKnownInputTokens: count,
14686
+ cacheHitCachedInputTokens: count,
14687
+ cacheHitInputTokens: count,
14686
14688
  outputTokens: count,
14687
14689
  reasoningOutputTokens: count,
14688
14690
  /** USD at the public price, summed over the priced requests only. */
@@ -14790,6 +14792,51 @@ var hostInteractionIdSchema = opaqueIdSchema.brand();
14790
14792
  var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
14791
14793
  var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
14792
14794
 
14795
+ // ../../shared-contracts/dist/thread-questions.js
14796
+ var field = external_exports.discriminatedUnion("type", [
14797
+ external_exports.object({
14798
+ id: external_exports.string().min(1),
14799
+ type: external_exports.literal("choice"),
14800
+ prompt: external_exports.string(),
14801
+ options: external_exports.array(external_exports.object({
14802
+ value: external_exports.string().min(1),
14803
+ label: external_exports.string(),
14804
+ description: external_exports.string().optional()
14805
+ })).min(1),
14806
+ multiple: external_exports.boolean(),
14807
+ allowOther: external_exports.boolean(),
14808
+ optional: external_exports.boolean()
14809
+ }),
14810
+ external_exports.object({
14811
+ id: external_exports.string().min(1),
14812
+ type: external_exports.literal("text"),
14813
+ prompt: external_exports.string(),
14814
+ multiline: external_exports.boolean(),
14815
+ secret: external_exports.literal(false),
14816
+ optional: external_exports.boolean(),
14817
+ placeholder: external_exports.string().optional(),
14818
+ prefill: external_exports.string().optional()
14819
+ })
14820
+ ]);
14821
+ var threadQuestionSchema = external_exports.object({
14822
+ interactionId: external_exports.string().min(1),
14823
+ turnId: external_exports.string().min(1),
14824
+ title: external_exports.string().optional(),
14825
+ questions: external_exports.array(field).min(1)
14826
+ }).refine(({ questions }) => questions.some((q) => q.type === "choice" && q.multiple), {
14827
+ message: "Shared cards require at least one multi-select question"
14828
+ });
14829
+ var threadQuestionsListParamsSchema = external_exports.strictObject({ threadId: external_exports.string().min(1) });
14830
+ var threadQuestionsResultSchema = external_exports.object({ questions: external_exports.array(threadQuestionSchema) });
14831
+ var threadQuestionRespondParamsSchema = external_exports.strictObject({
14832
+ threadId: external_exports.string().min(1),
14833
+ turnId: external_exports.string().min(1),
14834
+ interactionId: external_exports.string().min(1),
14835
+ answers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
14836
+ cancelled: external_exports.boolean().default(false)
14837
+ });
14838
+ var threadQuestionRespondResultSchema = external_exports.object({ accepted: external_exports.literal(true) });
14839
+
14793
14840
  // ../../shared-contracts/dist/console.js
14794
14841
  var consoleAnnouncementSchema = external_exports.strictObject({
14795
14842
  title: external_exports.string().trim().min(1).max(200),
@@ -16111,26 +16158,26 @@ function parseHostUsage(value) {
16111
16158
  }
16112
16159
  }
16113
16160
  const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
16114
- for (const field of [
16161
+ for (const field2 of [
16115
16162
  "totalCredits",
16116
16163
  "contextUsagePercent",
16117
16164
  "apiOutputTokensPerSecond"
16118
16165
  ]) {
16119
- const candidate = value[field];
16166
+ const candidate = value[field2];
16120
16167
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16121
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16168
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
16122
16169
  }
16123
16170
  }
16124
- for (const field of tokenFields) {
16125
- const candidate = value[field];
16171
+ for (const field2 of tokenFields) {
16172
+ const candidate = value[field2];
16126
16173
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16127
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16174
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
16128
16175
  }
16129
16176
  }
16130
- for (const field of safeIntegerFields) {
16131
- const candidate = value[field];
16177
+ for (const field2 of safeIntegerFields) {
16178
+ const candidate = value[field2];
16132
16179
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16133
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16180
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
16134
16181
  }
16135
16182
  }
16136
16183
  if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
@@ -16139,10 +16186,10 @@ function parseHostUsage(value) {
16139
16186
  if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
16140
16187
  throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
16141
16188
  }
16142
- for (const field of percentFields) {
16143
- const candidate = value[field];
16189
+ for (const field2 of percentFields) {
16190
+ const candidate = value[field2];
16144
16191
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
16145
- throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
16192
+ throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
16146
16193
  }
16147
16194
  }
16148
16195
  if (value.sessionCacheUsage !== void 0) {
@@ -16213,19 +16260,19 @@ function parseHostUsageRequest(value) {
16213
16260
  if (typeof value.requestId !== "string" || value.requestId.length === 0) {
16214
16261
  throw new Error("Harness Usage request 'requestId' must be a non-empty string");
16215
16262
  }
16216
- for (const field of ["model", "provider"]) {
16217
- const candidate = value[field];
16263
+ for (const field2 of ["model", "provider"]) {
16264
+ const candidate = value[field2];
16218
16265
  if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
16219
- throw new Error(`Harness Usage request '${field}' must be a non-empty string`);
16266
+ throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
16220
16267
  }
16221
16268
  }
16222
16269
  if (value.historical !== void 0 && typeof value.historical !== "boolean") {
16223
16270
  throw new Error("Harness Usage request 'historical' must be a boolean");
16224
16271
  }
16225
- for (const field of requestTokenFields) {
16226
- const candidate = value[field];
16272
+ for (const field2 of requestTokenFields) {
16273
+ const candidate = value[field2];
16227
16274
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16228
- throw new Error(`Harness Usage request '${field}' must be a non-negative safe integer`);
16275
+ throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
16229
16276
  }
16230
16277
  }
16231
16278
  if (value.inputTokens === void 0 || value.outputTokens === void 0) {
@@ -16373,6 +16420,7 @@ var HARNESS_BROKER_PROTOCOL_VERSION = 1;
16373
16420
  var HARNESS_BROKER_MAX_FRAME_BYTES = 8 * 1024 * 1024;
16374
16421
  var HARNESS_BROKER_MAX_PENDING_REQUESTS = 32;
16375
16422
  var HARNESS_BROKER_REQUEST_TIMEOUT_MS = 15e3;
16423
+ var HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE = 100;
16376
16424
  var HARNESS_BROKER_IDLE_TIMEOUT_MS = 60 * 60 * 1e3;
16377
16425
  var HARNESS_BROKER_RETIRING_ERROR_CODE = "brokerRetiring";
16378
16426
  var harnessBrokerMethodSchema = external_exports.enum([
@@ -16380,6 +16428,8 @@ var harnessBrokerMethodSchema = external_exports.enum([
16380
16428
  "adapter.inspectAccount",
16381
16429
  "adapter.credits",
16382
16430
  "adapter.open",
16431
+ "adapter.sessionImport.list",
16432
+ "adapter.sessionImport.resolve",
16383
16433
  "adapter.subagent.readSnapshot",
16384
16434
  "session.readSnapshot",
16385
16435
  "session.readCapabilities",
@@ -16482,30 +16532,6 @@ function consumeBrokerFrames(socket, onFrame, onError) {
16482
16532
  });
16483
16533
  }
16484
16534
 
16485
- // ../../harness-broker/dist/paths.js
16486
- import os from "node:os";
16487
- import path from "node:path";
16488
- var HARNESS_BROKER_DESCRIPTOR_ENV = "CODEXHOST_CLAUDE_BROKER_DESCRIPTOR";
16489
- var HARNESS_BROKER_DESCRIPTOR_FILE = "claude-code-broker-v1.json";
16490
- function defaultHarnessBrokerDirectory(environment = process.env) {
16491
- const home = environment.HOME || os.homedir();
16492
- return path.join(home, ".codexhost", "harness-broker");
16493
- }
16494
- function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId = "claude-code") {
16495
- harnessPluginIdSchema.parse(harnessId);
16496
- if (harnessId !== "claude-code")
16497
- return path.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
16498
- return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
16499
- }
16500
- function harnessBrokerLaunchAgentLabel(harnessId = "claude-code") {
16501
- harnessPluginIdSchema.parse(harnessId);
16502
- return harnessId === "claude-code" ? "ai.bytepioneer.codexhost.native-harness-broker" : `ai.bytepioneer.codexhost.${harnessId}-broker`;
16503
- }
16504
- function harnessBrokerLaunchAgentPlistPath(environment = process.env, harnessId = "claude-code") {
16505
- const home = environment.HOME || os.homedir();
16506
- return path.join(home, "Library", "LaunchAgents", `${harnessBrokerLaunchAgentLabel(harnessId)}.plist`);
16507
- }
16508
-
16509
16535
  // ../../harness-broker/dist/validation.js
16510
16536
  var cwdSchema = external_exports.string().min(1).max(16384);
16511
16537
  var brokerEnvironmentSchema = external_exports.object({
@@ -16556,7 +16582,31 @@ var brokerOpenInputSchema = external_exports.discriminatedUnion("kind", [
16556
16582
  forkSchema,
16557
16583
  rollbackSchema
16558
16584
  ]);
16559
- var brokerInspectInputSchema = external_exports.object({ cwd: cwdSchema.optional(), refresh: external_exports.boolean().optional() }).strict();
16585
+ var brokerInspectInputSchema = external_exports.object({
16586
+ cwd: cwdSchema.optional(),
16587
+ refresh: external_exports.boolean().optional(),
16588
+ purpose: external_exports.literal("availability").optional()
16589
+ }).strict();
16590
+ var brokerSessionImportListParamsSchema = external_exports.object({
16591
+ offset: external_exports.number().int().nonnegative().safe(),
16592
+ limit: external_exports.number().int().min(1).max(HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE)
16593
+ }).strict();
16594
+ var brokerSessionImportResolveParamsSchema = external_exports.object({ nativeSessionId: harnessSessionImportIdSchema }).strict();
16595
+ var brokerSessionImportPageSchema = external_exports.object({
16596
+ candidates: external_exports.array(harnessSessionImportCandidateSchema).max(HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE),
16597
+ total: external_exports.number().int().nonnegative().safe()
16598
+ }).strict();
16599
+ var brokerSessionImportSourceSchema = external_exports.object({
16600
+ candidate: harnessSessionImportCandidateSchema,
16601
+ nativeRef: nativeSessionRefSchema
16602
+ }).strict().superRefine((source, context) => {
16603
+ if (source.nativeRef.nativeSessionId !== source.candidate.nativeSessionId) {
16604
+ context.addIssue({
16605
+ code: "custom",
16606
+ message: "Session import source identity does not match"
16607
+ });
16608
+ }
16609
+ });
16560
16610
  var textInputSchema = external_exports.object({ type: external_exports.literal("text"), text: external_exports.string().max(4e6) }).strict();
16561
16611
  var turnStartSchema = external_exports.object({
16562
16612
  type: external_exports.literal("turn.start"),
@@ -16727,6 +16777,107 @@ var harnessOutputSchema = external_exports.custom((value) => {
16727
16777
  return false;
16728
16778
  });
16729
16779
 
16780
+ // ../../harness-broker/dist/session-import-client.js
16781
+ function createBrokerSessionImportCapability(input) {
16782
+ let listing = null;
16783
+ const closed = () => ({
16784
+ ok: false,
16785
+ error: { code: "invalidState", message: "Harness broker adapter is closed", retryable: false }
16786
+ });
16787
+ const invalid = () => ({
16788
+ ok: false,
16789
+ error: {
16790
+ code: "protocolError",
16791
+ message: "Harness broker returned invalid Session import metadata",
16792
+ retryable: false
16793
+ }
16794
+ });
16795
+ const list = async () => {
16796
+ try {
16797
+ const candidates = [];
16798
+ const identities = /* @__PURE__ */ new Set();
16799
+ let total;
16800
+ for (; ; ) {
16801
+ if (input.isClosed())
16802
+ return closed();
16803
+ const result = await input.request("adapter.sessionImport.list", {
16804
+ offset: candidates.length,
16805
+ limit: HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE
16806
+ });
16807
+ if (input.isClosed())
16808
+ return closed();
16809
+ if (!result.ok)
16810
+ return result;
16811
+ const page = brokerSessionImportPageSchema.safeParse(result.value);
16812
+ if (!page.success || total !== void 0 && total !== page.data.total || page.data.total < candidates.length + page.data.candidates.length || page.data.candidates.length === 0 && candidates.length < page.data.total)
16813
+ return invalid();
16814
+ total = page.data.total;
16815
+ for (const candidate of page.data.candidates) {
16816
+ if (identities.has(candidate.nativeSessionId))
16817
+ return invalid();
16818
+ identities.add(candidate.nativeSessionId);
16819
+ candidates.push(candidate);
16820
+ }
16821
+ if (candidates.length === total)
16822
+ return { ok: true, value: candidates };
16823
+ }
16824
+ } catch (error52) {
16825
+ return { ok: false, error: input.error(error52) };
16826
+ }
16827
+ };
16828
+ return {
16829
+ listCandidates() {
16830
+ if (input.isClosed())
16831
+ return Promise.resolve(closed());
16832
+ listing ??= list().finally(() => {
16833
+ listing = null;
16834
+ });
16835
+ return listing;
16836
+ },
16837
+ async resolveCandidate(nativeSessionId) {
16838
+ if (input.isClosed())
16839
+ return closed();
16840
+ try {
16841
+ const result = await input.request("adapter.sessionImport.resolve", { nativeSessionId });
16842
+ if (input.isClosed())
16843
+ return closed();
16844
+ if (!result.ok)
16845
+ return result;
16846
+ const source = brokerSessionImportSourceSchema.safeParse(result.value);
16847
+ if (!source.success || source.data.nativeRef.harnessId !== input.harnessId || source.data.candidate.nativeSessionId !== nativeSessionId)
16848
+ return invalid();
16849
+ return { ok: true, value: source.data };
16850
+ } catch (error52) {
16851
+ return { ok: false, error: input.error(error52) };
16852
+ }
16853
+ }
16854
+ };
16855
+ }
16856
+
16857
+ // ../../harness-broker/dist/paths.js
16858
+ import os from "node:os";
16859
+ import path from "node:path";
16860
+ var HARNESS_BROKER_DESCRIPTOR_ENV = "CODEXHOST_CLAUDE_BROKER_DESCRIPTOR";
16861
+ var HARNESS_BROKER_DESCRIPTOR_FILE = "claude-code-broker-v1.json";
16862
+ function defaultHarnessBrokerDirectory(environment = process.env) {
16863
+ const home = environment.HOME || os.homedir();
16864
+ return path.join(home, ".codexhost", "harness-broker");
16865
+ }
16866
+ function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId = "claude-code") {
16867
+ harnessPluginIdSchema.parse(harnessId);
16868
+ if (harnessId !== "claude-code")
16869
+ return path.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
16870
+ return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
16871
+ }
16872
+ function harnessBrokerLaunchAgentLabel(harnessId = "claude-code") {
16873
+ harnessPluginIdSchema.parse(harnessId);
16874
+ return harnessId === "claude-code" ? "ai.bytepioneer.codexhost.native-harness-broker" : `ai.bytepioneer.codexhost.${harnessId}-broker`;
16875
+ }
16876
+ function harnessBrokerLaunchAgentPlistPath(environment = process.env, harnessId = "claude-code") {
16877
+ const home = environment.HOME || os.homedir();
16878
+ return path.join(home, "Library", "LaunchAgents", `${harnessBrokerLaunchAgentLabel(harnessId)}.plist`);
16879
+ }
16880
+
16730
16881
  // ../../harness-broker/dist/client.js
16731
16882
  function unavailable(message, retryable = true) {
16732
16883
  return { code: "unavailable", message, retryable, stage: "harnessBroker" };
@@ -17263,6 +17414,7 @@ var BrokeredHarnessAdapter = class {
17263
17414
  commandCatalog;
17264
17415
  liveCommandCatalog;
17265
17416
  harnessId;
17417
+ sessionImport;
17266
17418
  credits;
17267
17419
  refreshCredits;
17268
17420
  #descriptorPath;
@@ -17285,6 +17437,14 @@ var BrokeredHarnessAdapter = class {
17285
17437
  };
17286
17438
  constructor(input = {}) {
17287
17439
  this.harnessId = harnessPluginIdSchema.parse(input.harnessId ?? "claude-code");
17440
+ if (input.sessionImport) {
17441
+ this.sessionImport = createBrokerSessionImportCapability({
17442
+ harnessId: this.harnessId,
17443
+ request: async (method, params) => parseHarnessResult(await this.#request(method, params, method === "adapter.sessionImport.resolve")),
17444
+ isClosed: () => this.#closed,
17445
+ error: (error52) => this.#error(error52)
17446
+ });
17447
+ }
17288
17448
  if (input.accountCredits !== false) {
17289
17449
  this.credits = () => this.#credits;
17290
17450
  this.refreshCredits = () => this.#refreshAccountCredits();
@@ -17748,7 +17908,7 @@ function claudePromptCacheIndicators(accountCreditsSupported, lastResponseAtUnix
17748
17908
 
17749
17909
  // dist/claude-code-adapter.js
17750
17910
  import { randomUUID as randomUUID5 } from "node:crypto";
17751
- import path16 from "node:path";
17911
+ import path15 from "node:path";
17752
17912
 
17753
17913
  // ../../../node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs
17754
17914
  import { createRequire as jre } from "node:module";
@@ -54388,7 +54548,6 @@ var ClaudePendingSessions = class {
54388
54548
  };
54389
54549
 
54390
54550
  // dist/claude-fork.js
54391
- import path12 from "node:path";
54392
54551
  import { isDeepStrictEqual } from "node:util";
54393
54552
 
54394
54553
  // dist/file-change.js
@@ -54530,6 +54689,17 @@ function targetedSubagentId(argumentsValue) {
54530
54689
  return void 0;
54531
54690
  return boundedString(argumentsValue.to ?? argumentsValue.recipient ?? argumentsValue.agentId, SUBAGENT_DESCRIPTION_LIMIT);
54532
54691
  }
54692
+ function claudeSendMessageFailed(nativeResult, outputText) {
54693
+ if (isRecord7(nativeResult) && typeof nativeResult.success === "boolean") {
54694
+ return nativeResult.success === false;
54695
+ }
54696
+ try {
54697
+ const parsed = JSON.parse(outputText ?? "");
54698
+ return isRecord7(parsed) && parsed.success === false;
54699
+ } catch {
54700
+ return false;
54701
+ }
54702
+ }
54533
54703
  function includesAuthenticationFailure(errors) {
54534
54704
  return errors.some((error52) => AUTHENTICATION_ERRORS.has(error52));
54535
54705
  }
@@ -55260,7 +55430,7 @@ var ClaudeNativeTurnAccumulator = class {
55260
55430
  events.push({
55261
55431
  type: "subagent.completed",
55262
55432
  callId,
55263
- isError,
55433
+ isError: isError || tool.name === "SendMessage" && claudeSendMessageFailed(nativeResult, outputText),
55264
55434
  ...subagentContinuesInBackground(nativeResult, outputText) ? { continuesInBackground: true } : {},
55265
55435
  ...agentId ? { nativeSubagentId: agentId } : {},
55266
55436
  ...resultSummary ? { resultSummary } : {}
@@ -55393,7 +55563,7 @@ function conversationMessages(values, sessionId) {
55393
55563
  let promptId = null;
55394
55564
  const occupancy = new ClaudeBackgroundOccupancy();
55395
55565
  let accumulator = new ClaudeNativeTurnAccumulator();
55396
- const sends = /* @__PURE__ */ new Set();
55566
+ const sends = /* @__PURE__ */ new Map();
55397
55567
  let pendingNotification = false;
55398
55568
  for (const value of values) {
55399
55569
  if (!isRecord8(value))
@@ -55426,17 +55596,19 @@ function conversationMessages(values, sessionId) {
55426
55596
  for (const event of accumulator.consume(value).events) {
55427
55597
  if (event.type === "subagent.started") {
55428
55598
  if (event.operation === "send") {
55429
- sends.add(event.callId);
55430
- if (event.nativeSubagentId)
55431
- occupancy.occupyAgent(event.nativeSubagentId);
55599
+ sends.set(event.callId, event.nativeSubagentId);
55432
55600
  } else if (event.background)
55433
55601
  occupancy.occupySpawn(event.callId, event.nativeSubagentId);
55434
55602
  } else if (event.type === "subagent.completed") {
55435
- if (!event.isError && (event.continuesInBackground || sends.has(event.callId))) {
55603
+ if (sends.has(event.callId)) {
55604
+ const agentId = event.nativeSubagentId ?? sends.get(event.callId);
55605
+ if (!event.isError && agentId)
55606
+ occupancy.occupyAgent(agentId);
55607
+ sends.delete(event.callId);
55608
+ } else if (!event.isError && event.continuesInBackground) {
55436
55609
  occupancy.occupySpawn(event.callId, event.nativeSubagentId);
55437
55610
  } else
55438
55611
  occupancy.release(event.callId, event.nativeSubagentId);
55439
- sends.delete(event.callId);
55440
55612
  } else if (event.type === "workflow.launched" && event.background && !event.isError) {
55441
55613
  occupancy.occupySpawn(event.callId, event.taskId);
55442
55614
  } else if (event.type === "subagent.settled") {
@@ -55613,7 +55785,7 @@ function mapClaudeSnapshot(values, sessionId) {
55613
55785
  if (!result)
55614
55786
  continue;
55615
55787
  const output = toolResultOutput(result);
55616
- const failed = result.is_error === true;
55788
+ const failed = result.is_error === true || block.name === "SendMessage" && claudeSendMessageFailed(void 0, output);
55617
55789
  const toolOutcome = failed ? {
55618
55790
  status: "failed",
55619
55791
  error: {
@@ -55908,12 +56080,6 @@ async function forkClaudeSession(input) {
55908
56080
  error: error51("protocolError", "Claude Code Session working directory is unavailable", false)
55909
56081
  };
55910
56082
  }
55911
- if (path12.resolve(sourceInfo.cwd) !== input.cwd) {
55912
- return {
55913
- ok: false,
55914
- error: error51("unsupported", "Claude Code cannot Fork across working directories", false)
55915
- };
55916
- }
55917
56083
  const source = await readSnapshot(input.dependencies, input.cwd, sourceRef.data.nativeSessionId);
55918
56084
  if (!source.ok)
55919
56085
  return source;
@@ -56013,13 +56179,13 @@ import { readFile as readFile6, rename as rename4, rm as rm5, stat as stat5, wri
56013
56179
 
56014
56180
  // dist/claude-transcript.js
56015
56181
  import os6 from "node:os";
56016
- import path13 from "node:path";
56182
+ import path12 from "node:path";
56017
56183
  import { readFile as readFile5, readdir as readdir3, stat as stat4 } from "node:fs/promises";
56018
56184
  function projectDirectoryName(cwd) {
56019
56185
  return cwd.replace(/[^A-Za-z0-9]/gu, "-");
56020
56186
  }
56021
56187
  function configDirectory(environment) {
56022
- return environment.CLAUDE_CONFIG_DIR ? path13.resolve(environment.CLAUDE_CONFIG_DIR) : path13.join(os6.homedir(), ".claude");
56188
+ return environment.CLAUDE_CONFIG_DIR ? path12.resolve(environment.CLAUDE_CONFIG_DIR) : path12.join(os6.homedir(), ".claude");
56023
56189
  }
56024
56190
  async function existingFile(file2) {
56025
56191
  try {
@@ -56029,9 +56195,9 @@ async function existingFile(file2) {
56029
56195
  }
56030
56196
  }
56031
56197
  async function findClaudeTranscript(input) {
56032
- const projectsDirectory = path13.join(configDirectory(input.environment), "projects");
56198
+ const projectsDirectory = path12.join(configDirectory(input.environment), "projects");
56033
56199
  const name = `${input.sessionId}.jsonl`;
56034
- const expected = path13.join(projectsDirectory, projectDirectoryName(input.cwd), name);
56200
+ const expected = path12.join(projectsDirectory, projectDirectoryName(input.cwd), name);
56035
56201
  if (await existingFile(expected))
56036
56202
  return expected;
56037
56203
  let projects;
@@ -56041,7 +56207,7 @@ async function findClaudeTranscript(input) {
56041
56207
  return null;
56042
56208
  }
56043
56209
  for (const project2 of projects) {
56044
- const candidate = path13.join(projectsDirectory, project2, name);
56210
+ const candidate = path12.join(projectsDirectory, project2, name);
56045
56211
  if (await existingFile(candidate))
56046
56212
  return candidate;
56047
56213
  }
@@ -56151,7 +56317,7 @@ async function remapForkedSessionReferences(input) {
56151
56317
  import { Buffer as Buffer2 } from "node:buffer";
56152
56318
  import { readFile as readFile7 } from "node:fs/promises";
56153
56319
  import os7 from "node:os";
56154
- import path14 from "node:path";
56320
+ import path13 from "node:path";
56155
56321
 
56156
56322
  // dist/thinking-options.js
56157
56323
  var option = (id2, label) => ({
@@ -56244,7 +56410,7 @@ function decodeClaudeModelRef(ref) {
56244
56410
  return value === "default" ? void 0 : value;
56245
56411
  }
56246
56412
  function resolveClaudeConfigDirectory(environment = process.env) {
56247
- return path14.resolve(environment.CLAUDE_CONFIG_DIR ?? path14.join(os7.homedir(), ".claude"));
56413
+ return path13.resolve(environment.CLAUDE_CONFIG_DIR ?? path13.join(os7.homedir(), ".claude"));
56248
56414
  }
56249
56415
  function parseModelPickerOptions(value) {
56250
56416
  if (!Array.isArray(value))
@@ -56286,7 +56452,7 @@ function parseClaudeModelPickerSettings(value) {
56286
56452
  };
56287
56453
  }
56288
56454
  async function readClaudeUserModelPicker(environment = process.env) {
56289
- const settingsPath = path14.join(resolveClaudeConfigDirectory(environment), "settings.json");
56455
+ const settingsPath = path13.join(resolveClaudeConfigDirectory(environment), "settings.json");
56290
56456
  let raw;
56291
56457
  try {
56292
56458
  raw = await readFile7(settingsPath, "utf8");
@@ -56632,7 +56798,7 @@ function projectClaudeAccountUsage(usage, account) {
56632
56798
 
56633
56799
  // dist/process-fence.js
56634
56800
  import { execFile as execFile3 } from "node:child_process";
56635
- import path15 from "node:path";
56801
+ import path14 from "node:path";
56636
56802
  import { setTimeout as setTimeout2 } from "node:timers/promises";
56637
56803
  import { promisify } from "node:util";
56638
56804
  var executeFile = promisify(execFile3);
@@ -56656,9 +56822,9 @@ async function closeClaudeProcessGroup(child, timeoutMs) {
56656
56822
  if (child.exitCode !== null || child.signalCode !== null)
56657
56823
  throw new Error("Claude process tree cannot be confirmed after its Windows root exited");
56658
56824
  const root = process.env.SystemRoot ?? process.env.SYSTEMROOT;
56659
- if (!root || !path15.win32.isAbsolute(root))
56825
+ if (!root || !path14.win32.isAbsolute(root))
56660
56826
  throw new Error("Windows SystemRoot is unavailable");
56661
- await executeFile(path15.win32.join(root, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], {
56827
+ await executeFile(path14.win32.join(root, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], {
56662
56828
  timeout: timeoutMs,
56663
56829
  windowsHide: true
56664
56830
  });
@@ -56958,6 +57124,8 @@ var ClaudeSdkTransport = class {
56958
57124
  /** Root tool calls of the requested Turn that have started and not yet returned a result. */
56959
57125
  #rootToolCalls = /* @__PURE__ */ new Set();
56960
57126
  #pendingSteers = /* @__PURE__ */ new Map();
57127
+ /** Written steers Claude has not yet drained into a native turn, by message ID. */
57128
+ #steerTakeovers = /* @__PURE__ */ new Map();
56961
57129
  #autonomous = null;
56962
57130
  #autonomousTurnHandler = null;
56963
57131
  #idleHandler = null;
@@ -57081,9 +57249,16 @@ var ClaudeSdkTransport = class {
57081
57249
  * `priority: "next"` joins after the current tool call, and a tool result is always followed by
57082
57250
  * another model request. So a steer written while a root tool call runs folds into this Turn;
57083
57251
  * one written while Claude streams its final text may instead run as the next Turn.
57252
+ *
57253
+ * A held Turn's continuation steers as well: while its idle stream is live, the pushed input
57254
+ * runs as that Turn's next Segment, and the background work the Turn waits on keeps running.
57084
57255
  */
57085
57256
  canSteerActiveTurn() {
57086
- return this.#nativeSteer && this.#active !== null && this.#rootToolCalls.size > 0;
57257
+ if (!this.#nativeSteer)
57258
+ return false;
57259
+ if (this.#active !== null)
57260
+ return this.#rootToolCalls.size > 0;
57261
+ return this.#idleLive && this.#idleHandler !== null;
57087
57262
  }
57088
57263
  #observeRootToolCalls(message) {
57089
57264
  if (!isRecord11(message) || message.parent_tool_use_id != null)
@@ -57117,11 +57292,11 @@ var ClaudeSdkTransport = class {
57117
57292
  this.#slashCommands = parseClaudeSlashCommands(message.commands);
57118
57293
  }
57119
57294
  }
57120
- async getContextUsage() {
57295
+ async getContextUsage(detail = "full") {
57121
57296
  const activeQuery = this.#query;
57122
57297
  if (!this.#started || !activeQuery)
57123
57298
  return null;
57124
- return parseContextUsage(await activeQuery.getContextUsage());
57299
+ return parseContextUsage(await activeQuery.getContextUsage({ detail }));
57125
57300
  }
57126
57301
  getPermissionMode() {
57127
57302
  if (!this.#started || !this.#query)
@@ -57259,7 +57434,7 @@ var ClaudeSdkTransport = class {
57259
57434
  * The Turn ending first therefore does not reject it, and a missing `queued` receipt resolves
57260
57435
  * after a bounded wait so callers that serialize requests are never held indefinitely.
57261
57436
  */
57262
- steer(text2, messageId) {
57437
+ steer(text2, messageId, onTakeover) {
57263
57438
  if (this.#closePromise || !this.#started || !this.#query || !this.canSteerActiveTurn()) {
57264
57439
  return Promise.reject(new ClaudeSteerMissedTurnError());
57265
57440
  }
@@ -57280,9 +57455,14 @@ var ClaudeSdkTransport = class {
57280
57455
  this.#pendingSteers.delete(messageId);
57281
57456
  return Promise.reject(new ClaudeSteerMissedTurnError());
57282
57457
  }
57458
+ if (onTakeover)
57459
+ this.#steerTakeovers.set(messageId, onTakeover);
57283
57460
  const pending = this.#pendingSteers.get(messageId);
57284
57461
  if (pending) {
57285
- pending.timer = setTimeout(() => this.#acceptSteer(messageId), this.#steerQueuedTimeoutMs);
57462
+ pending.timer = setTimeout(() => {
57463
+ this.#acceptSteer(messageId);
57464
+ this.#takeOverSteer(messageId, false);
57465
+ }, this.#steerQueuedTimeoutMs);
57286
57466
  pending.timer.unref?.();
57287
57467
  }
57288
57468
  return promise2;
@@ -57295,6 +57475,13 @@ var ClaudeSdkTransport = class {
57295
57475
  clearTimeout(pending.timer);
57296
57476
  pending.resolve();
57297
57477
  }
57478
+ #takeOverSteer(messageId, started) {
57479
+ const onTakeover = this.#steerTakeovers.get(messageId);
57480
+ if (!onTakeover)
57481
+ return;
57482
+ this.#steerTakeovers.delete(messageId);
57483
+ onTakeover(started);
57484
+ }
57298
57485
  respondToInteraction(response) {
57299
57486
  const pending = this.#interactions.get(response.requestId);
57300
57487
  if (!pending) {
@@ -57576,6 +57763,9 @@ var ClaudeSdkTransport = class {
57576
57763
  }
57577
57764
  }
57578
57765
  #rejectPendingSteers() {
57766
+ for (const messageId of [...this.#steerTakeovers.keys()]) {
57767
+ this.#takeOverSteer(messageId, false);
57768
+ }
57579
57769
  const pending = [...this.#pendingSteers.values()];
57580
57770
  this.#pendingSteers.clear();
57581
57771
  const error52 = new Error("Claude Code steer receipt was lost after input was written");
@@ -57584,16 +57774,24 @@ var ClaudeSdkTransport = class {
57584
57774
  entry.reject(error52);
57585
57775
  }
57586
57776
  }
57587
- /** `queued` is Claude's acceptance of this message into the running Session. */
57777
+ /**
57778
+ * `queued` is Claude's acceptance of this message into the running Session. `started` is its
57779
+ * drain into a native turn, folded into the running one or run as the next; a terminal state
57780
+ * without `started` means no native turn takes it over.
57781
+ */
57588
57782
  #observeSteer(message) {
57589
- if (this.#pendingSteers.size === 0 || !isRecord11(message) || message.type !== "command_lifecycle") {
57783
+ if (this.#pendingSteers.size === 0 && this.#steerTakeovers.size === 0 || !isRecord11(message) || message.type !== "command_lifecycle") {
57590
57784
  return;
57591
57785
  }
57592
- if (message.state !== "queued")
57593
- return;
57594
57786
  if (typeof message.command_uuid !== "string" || message.command_uuid.length === 0)
57595
57787
  return;
57596
- this.#acceptSteer(message.command_uuid);
57788
+ if (message.state === "queued") {
57789
+ this.#acceptSteer(message.command_uuid);
57790
+ return;
57791
+ }
57792
+ if (["started", "completed", "cancelled", "discarded", "refused"].includes(String(message.state))) {
57793
+ this.#takeOverSteer(message.command_uuid, message.state === "started");
57794
+ }
57597
57795
  }
57598
57796
  #observeBackgroundTasks(message) {
57599
57797
  if (!isRecord11(message) || message.type !== "system")
@@ -57706,13 +57904,13 @@ var ClaudeSdkTransport = class {
57706
57904
  throw new Error("Claude SDK Query ended unexpectedly");
57707
57905
  } catch (error52) {
57708
57906
  const active = this.#active;
57907
+ if (!this.#closePromise)
57908
+ this.#onFault(error52);
57709
57909
  this.#closeInteractions("all", "cancelled");
57710
57910
  this.#rejectPendingSteers();
57711
57911
  this.#rootToolCalls.clear();
57712
57912
  this.#active = null;
57713
57913
  active?.reject(error52);
57714
- if (!this.#closePromise)
57715
- this.#onFault(error52);
57716
57914
  }
57717
57915
  }
57718
57916
  #spawn(options) {
@@ -58009,7 +58207,7 @@ var ClaudeSubagentLifecycle = class {
58009
58207
  });
58010
58208
  const outcome = cancellationRequested ? { status: "cancelled", reason: "Cancelled by user" } : event.isError ? { status: "failed", error: subagentFailure() } : { status: "succeeded" };
58011
58209
  this.#emit({ type: "item.completed", turnId, snapshot: { item, outcome } });
58012
- return subagent;
58210
+ return { operation: active.item.operation, subagent };
58013
58211
  }
58014
58212
  finalize(turnId, outcome) {
58015
58213
  for (const [callId, active] of this.#delegations) {
@@ -58217,9 +58415,9 @@ function stringField(value, keys) {
58217
58415
  if (!isRecord12(value))
58218
58416
  return void 0;
58219
58417
  for (const key of keys) {
58220
- const field = value[key];
58221
- if (typeof field === "string" && field.length > 0)
58222
- return field;
58418
+ const field2 = value[key];
58419
+ if (typeof field2 === "string" && field2.length > 0)
58420
+ return field2;
58223
58421
  }
58224
58422
  return void 0;
58225
58423
  }
@@ -58905,10 +59103,12 @@ var ClaudeHarnessSession = class {
58905
59103
  },
58906
59104
  history: { fork: true, forkAcrossCwd: false, rollbackLastTurn: true },
58907
59105
  subagents: { observe: true, readTranscript: true },
58908
- // Read live: native delivery joins this Turn only while a requested Turn runs a root tool call
58909
- // on a CLI that confirms steers (`msg_lifecycle_v1`). Otherwise the Host stops and restarts.
59106
+ // Read live: native delivery joins this Turn while a root tool call runs, or while a held
59107
+ // Turn's continuation waits on background work, on a CLI that confirms steers
59108
+ // (`msg_lifecycle_v1`). A Turn whose cancellation is in flight must not take more input;
59109
+ // every other case stops and restarts.
58910
59110
  get steer() {
58911
- return session.#transport?.canSteerActiveTurn?.() === true;
59111
+ return session.#transport?.canSteerActiveTurn?.() === true && session.#active?.cancellationRequested !== true;
58912
59112
  }
58913
59113
  }))(this);
58914
59114
  commands;
@@ -58955,7 +59155,6 @@ var ClaudeHarnessSession = class {
58955
59155
  #lastAssistantResponseAtUnix;
58956
59156
  #accountCreditsSupported;
58957
59157
  #minimumContextUsedTokens = null;
58958
- #latestRequestModel = null;
58959
59158
  #calibratedInputTokens = 0;
58960
59159
  #calibratedOutputTokens = 0;
58961
59160
  #calibratedCostUsd = 0;
@@ -59235,6 +59434,7 @@ var ClaudeHarnessSession = class {
59235
59434
  nativeTurnKey,
59236
59435
  nativeTurnRef: null,
59237
59436
  cancellationRequested: false,
59437
+ steersAwaitingNative: /* @__PURE__ */ new Set(),
59238
59438
  usageRequestIds: /* @__PURE__ */ new Set(),
59239
59439
  estimatedInputTokens: 0,
59240
59440
  estimatedOutputTokens: 0,
@@ -59271,9 +59471,13 @@ var ClaudeHarnessSession = class {
59271
59471
  return { ok: true, value: { turnId: command.turnId } };
59272
59472
  }
59273
59473
  async #steer(command) {
59274
- if (!this.#active || this.#active.command.turnId !== command.turnId) {
59474
+ const active = this.#active;
59475
+ if (!active || active.command.turnId !== command.turnId) {
59275
59476
  return { ok: false, error: invalidState("Claude Code steer target is not the active Turn") };
59276
59477
  }
59478
+ if (active.cancellationRequested) {
59479
+ return { ok: false, error: invalidState("Claude Code steer target is being cancelled") };
59480
+ }
59277
59481
  const text2 = command.input.map((input) => input.text).join("\n");
59278
59482
  if (text2.length === 0) {
59279
59483
  return {
@@ -59299,10 +59503,13 @@ var ClaudeHarnessSession = class {
59299
59503
  }
59300
59504
  };
59301
59505
  }
59506
+ const messageId = this.#randomUUID();
59507
+ active.steersAwaitingNative.add(messageId);
59302
59508
  try {
59303
- await transport.steer(text2, this.#randomUUID());
59509
+ await transport.steer(text2, messageId, (started) => this.#takeOverSteer(active, messageId, started));
59304
59510
  } catch (error52) {
59305
59511
  if (error52 instanceof ClaudeSteerMissedTurnError) {
59512
+ this.#takeOverSteer(active, messageId, false);
59306
59513
  return { ok: false, error: invalidState("Claude Code steer missed the active Turn") };
59307
59514
  }
59308
59515
  throw error52;
@@ -59405,6 +59612,7 @@ var ClaudeHarnessSession = class {
59405
59612
  nativeTurnKey,
59406
59613
  nativeTurnRef: null,
59407
59614
  cancellationRequested: false,
59615
+ steersAwaitingNative: /* @__PURE__ */ new Set(),
59408
59616
  usageRequestIds: /* @__PURE__ */ new Set(),
59409
59617
  estimatedInputTokens: 0,
59410
59618
  estimatedOutputTokens: 0,
@@ -59453,15 +59661,16 @@ var ClaudeHarnessSession = class {
59453
59661
  };
59454
59662
  }
59455
59663
  }
59456
- refreshUsage() {
59664
+ async refreshUsage() {
59665
+ await this.#contextRefreshInFlight;
59457
59666
  if (this.#phase !== "open" || !this.#transport)
59458
- return Promise.resolve();
59667
+ return;
59459
59668
  const now = Date.now();
59460
59669
  if (now < this.#contextUsageFreshUntilMs || now < this.#contextUsageCooldownUntilMs) {
59461
- return Promise.resolve();
59670
+ return;
59462
59671
  }
59463
59672
  this.#requestContextUsage(this.#transport, this.#active?.command.turnId, CONTEXT_USAGE_RETRY_DELAYS_MS);
59464
- return this.#contextRefreshInFlight ?? Promise.resolve();
59673
+ await this.#contextRefreshInFlight;
59465
59674
  }
59466
59675
  blocksRollback(sessionId) {
59467
59676
  return this.#sessionId === sessionId && (this.#phase !== "open" || this.#active !== null || this.#acceptingTurn || this.#configurationTask !== null || this.#readingHistory);
@@ -59766,7 +59975,7 @@ var ClaudeHarnessSession = class {
59766
59975
  active.cancellationRequested = true;
59767
59976
  const transport = this.#transport;
59768
59977
  const taskIds = this.#backgroundTaskIds(active);
59769
- if (transport && (taskIds.length > 0 || active.held && (active.rootSegmentActive || this.#occupancy.awaitingContinuation))) {
59978
+ if (transport && (taskIds.length > 0 || active.held && (active.rootSegmentActive || this.#occupancy.awaitingContinuation || active.steersAwaitingNative.size > 0))) {
59770
59979
  await this.#cancelBackgroundWork(active, transport, taskIds);
59771
59980
  return { ok: true, value: { cancellationRequested: true } };
59772
59981
  }
@@ -59841,6 +60050,11 @@ var ClaudeHarnessSession = class {
59841
60050
  return;
59842
60051
  if (cancellation.stopping || cancellation.interrupting || active.rootSegmentActive)
59843
60052
  return;
60053
+ if (active.steersAwaitingNative.size > 0) {
60054
+ this.#armCancelEscalation(active);
60055
+ return;
60056
+ }
60057
+ this.#clearCancelEscalation();
59844
60058
  this.#clearCancellationQuiet(cancellation);
59845
60059
  const quiet = setTimeout(() => {
59846
60060
  cancellation.quiet = null;
@@ -60120,10 +60334,7 @@ var ClaudeHarnessSession = class {
60120
60334
  }
60121
60335
  this.#completeAgentItem(active, { status: "succeeded" }, false);
60122
60336
  active.subagents.start(active.command.turnId, event);
60123
- if (event.operation === "send") {
60124
- if (event.nativeSubagentId)
60125
- this.#occupancy.occupyAgent(event.nativeSubagentId);
60126
- } else if (event.background) {
60337
+ if (event.operation === "spawn" && event.background) {
60127
60338
  this.#occupancy.occupySpawn(event.callId, event.nativeSubagentId);
60128
60339
  }
60129
60340
  return;
@@ -60142,7 +60353,13 @@ var ClaudeHarnessSession = class {
60142
60353
  }
60143
60354
  return;
60144
60355
  case "subagent.completed": {
60145
- const subagent = active.subagents.complete(active.command.turnId, event, active.cancellationRequested);
60356
+ const { operation, subagent } = active.subagents.complete(active.command.turnId, event, active.cancellationRequested);
60357
+ if (operation === "send") {
60358
+ if (subagent.status === "running" && subagent.nativeSubagentId) {
60359
+ this.#occupancy.occupyAgent(subagent.nativeSubagentId);
60360
+ }
60361
+ return;
60362
+ }
60146
60363
  if (subagent.status === "running") {
60147
60364
  this.#occupancy.occupySpawn(event.callId, subagent.nativeSubagentId);
60148
60365
  return;
@@ -60454,6 +60671,7 @@ var ClaudeHarnessSession = class {
60454
60671
  const active = {
60455
60672
  command: { type: "turn.start", turnId, input: [] },
60456
60673
  compactionItem: null,
60674
+ steersAwaitingNative: /* @__PURE__ */ new Set(),
60457
60675
  item,
60458
60676
  agentMessageOrdinal: 1,
60459
60677
  assistantMessageId: null,
@@ -60586,7 +60804,7 @@ var ClaudeHarnessSession = class {
60586
60804
  this.#finishFailed(active, transportFailure(result.kind));
60587
60805
  }
60588
60806
  }
60589
- #requestContextUsage(transport, turnId, retryDelaysMs) {
60807
+ #requestContextUsage(transport, turnId, retryDelaysMs, detail = "full") {
60590
60808
  if (this.#phase !== "open" || this.#transport !== transport)
60591
60809
  return;
60592
60810
  if (this.#contextRefreshInFlight)
@@ -60595,7 +60813,8 @@ var ClaudeHarnessSession = class {
60595
60813
  transport,
60596
60814
  ...turnId !== void 0 ? { turnId } : {},
60597
60815
  generation: this.#usageGeneration,
60598
- retryDelaysMs
60816
+ retryDelaysMs,
60817
+ detail
60599
60818
  };
60600
60819
  this.#contextRefreshInFlight = this.#drainContextUsage();
60601
60820
  }
@@ -60621,14 +60840,16 @@ var ClaudeHarnessSession = class {
60621
60840
  return;
60622
60841
  }
60623
60842
  try {
60624
- const context = await request.transport.getContextUsage();
60843
+ const context = await request.transport.getContextUsage(request.detail);
60625
60844
  if (this.#phase !== "open" || this.#transport !== request.transport || this.#usageGeneration !== request.generation || this.#contextRefreshPending !== null) {
60626
60845
  return;
60627
60846
  }
60628
60847
  if (context === null)
60629
60848
  continue;
60630
- this.#contextUsageFreshUntilMs = Date.now() + CONTEXT_USAGE_TTL_MS;
60631
- this.#contextUsageCooldownUntilMs = 0;
60849
+ if (request.detail === "full") {
60850
+ this.#contextUsageFreshUntilMs = Date.now() + CONTEXT_USAGE_TTL_MS;
60851
+ this.#contextUsageCooldownUntilMs = 0;
60852
+ }
60632
60853
  this.#mergeAndPublishUsage({
60633
60854
  contextUsedTokens: Math.max(context.usedTokens, this.#minimumContextUsedTokens ?? 0),
60634
60855
  contextWindowTokens: context.maxTokens
@@ -60637,7 +60858,7 @@ var ClaudeHarnessSession = class {
60637
60858
  } catch {
60638
60859
  }
60639
60860
  }
60640
- if (this.#phase === "open" && this.#transport === request.transport && this.#usageGeneration === request.generation) {
60861
+ if (request.detail === "full" && this.#phase === "open" && this.#transport === request.transport && this.#usageGeneration === request.generation) {
60641
60862
  this.#contextUsageCooldownUntilMs = Date.now() + CONTEXT_USAGE_FAILURE_COOLDOWN_MS;
60642
60863
  }
60643
60864
  }
@@ -60703,8 +60924,6 @@ var ClaudeHarnessSession = class {
60703
60924
  const promptTokens = usage.inputTokens + usage.cacheCreationInputTokens + usage.cacheReadInputTokens;
60704
60925
  if (promptTokens > 0)
60705
60926
  this.#minimumContextUsedTokens = promptTokens;
60706
- if (usage.model)
60707
- this.#latestRequestModel = usage.model;
60708
60927
  const cacheHitRatePercent = claudeCacheHitRatePercent(usage);
60709
60928
  const contextWindowTokens = this.#latestUsage?.contextWindowTokens;
60710
60929
  this.#mergeAndPublishUsage({
@@ -60746,24 +60965,11 @@ var ClaudeHarnessSession = class {
60746
60965
  if (cacheHitRatePercent !== void 0)
60747
60966
  delta.cacheHitRatePercent = cacheHitRatePercent;
60748
60967
  }
60749
- if (this.#latestUsage?.contextWindowTokens === void 0 && this.#minimumContextUsedTokens !== null) {
60750
- const contextWindowTokens = this.#resultContextWindow(event.modelUsage);
60751
- if (contextWindowTokens !== void 0) {
60752
- delta.contextUsedTokens = this.#minimumContextUsedTokens;
60753
- delta.contextWindowTokens = contextWindowTokens;
60754
- }
60968
+ if (this.#transport && this.#minimumContextUsedTokens !== null && event.modelUsage?.some(({ contextWindowTokens }) => contextWindowTokens !== void 0)) {
60969
+ this.#requestContextUsage(this.#transport, active.command.turnId, [0], "summary");
60755
60970
  }
60756
60971
  this.#mergeAndPublishUsage(delta, active.command.turnId);
60757
60972
  }
60758
- /** The latest request's Model, else the Model that carried the most prompt tokens. */
60759
- #resultContextWindow(modelUsage) {
60760
- if (!modelUsage?.length)
60761
- return void 0;
60762
- const latest = this.#latestRequestModel;
60763
- const matched = latest ? modelUsage.find(({ model: model2 }) => model2 === latest) : void 0;
60764
- const main = matched ?? modelUsage.reduce((best, entry) => (entry.promptTokens ?? entry.inputTokens) > (best.promptTokens ?? best.inputTokens) ? entry : best);
60765
- return main.contextWindowTokens;
60766
- }
60767
60973
  /**
60768
60974
  * Plan usage is account-wide, not Thread-scoped, so every observation is
60769
60975
  * offered to the Adapter's shared cache regardless of this Session's own
@@ -60842,7 +61048,7 @@ var ClaudeHarnessSession = class {
60842
61048
  this.#clearContinuationQuiescence();
60843
61049
  const quiescence = setTimeout(() => {
60844
61050
  this.#continuationQuiescence = null;
60845
- if (this.#active !== active || !active.held || active.rootSegmentActive || this.#phase !== "open") {
61051
+ if (this.#active !== active || !active.held || active.rootSegmentActive || active.steersAwaitingNative.size > 0 || this.#phase !== "open") {
60846
61052
  return;
60847
61053
  }
60848
61054
  this.#occupancy.releaseContinuations();
@@ -60863,6 +61069,30 @@ var ClaudeHarnessSession = class {
60863
61069
  active.rootSegmentActive = true;
60864
61070
  this.#clearContinuationQuiescence();
60865
61071
  }
61072
+ /**
61073
+ * A drained steer runs in a native turn whose result still reaches this Turn, folded into the
61074
+ * running Root Segment or as the held Turn's next one. A steer that ends without one releases
61075
+ * its keep-open, so a Turn held only for it settles as if the steer had never been written.
61076
+ */
61077
+ #takeOverSteer(active, messageId, started) {
61078
+ if (!active.steersAwaitingNative.delete(messageId) || this.#active !== active)
61079
+ return;
61080
+ if (started) {
61081
+ this.#handleTurnEvent(active, { type: "segment.started" });
61082
+ return;
61083
+ }
61084
+ if (active.cancellation) {
61085
+ this.#settleCancellation(active);
61086
+ return;
61087
+ }
61088
+ if (!active.held || active.rootSegmentActive || active.steersAwaitingNative.size > 0 || this.#phase !== "open") {
61089
+ return;
61090
+ }
61091
+ if (this.#occupancy.awaitingContinuation)
61092
+ this.#armContinuationQuiescence(active);
61093
+ else if (!this.#occupancy.unsettled)
61094
+ this.#finish(active, { status: "succeeded" });
61095
+ }
60866
61096
  #finish(active, outcome) {
60867
61097
  if (this.#active !== active)
60868
61098
  return;
@@ -60873,7 +61103,7 @@ var ClaudeHarnessSession = class {
60873
61103
  active.cancellation = null;
60874
61104
  }
60875
61105
  this.#clearContinuationQuiescence();
60876
- const hold = outcome.status === "succeeded" && !active.cancellationRequested && this.#occupancy.unsettled;
61106
+ const hold = outcome.status === "succeeded" && !active.cancellationRequested && (this.#occupancy.unsettled || active.steersAwaitingNative.size > 0);
60877
61107
  this.#closeActiveInteractions(active, outcome.status === "succeeded" ? "superseded" : "cancelled", hold);
60878
61108
  const itemOutcome2 = outcome;
60879
61109
  if (active.compactionItem)
@@ -61139,7 +61369,7 @@ var ClaudeCodeAdapter = class {
61139
61369
  error: invalidState("Claude Code Adapter is closing")
61140
61370
  };
61141
61371
  }
61142
- const cwd = path16.resolve(input.cwd ?? process.cwd());
61372
+ const cwd = path15.resolve(input.cwd ?? process.cwd());
61143
61373
  if (!input.refresh) {
61144
61374
  const cached2 = this.#inspectionCache.get(cwd);
61145
61375
  if (cached2)
@@ -61343,7 +61573,7 @@ var ClaudeCodeAdapter = class {
61343
61573
  }
61344
61574
  requestedPermissionModeId = CLAUDE_DEFAULT_PERMISSION_MODE_ID;
61345
61575
  }
61346
- const cwd = path16.resolve(input.cwd);
61576
+ const cwd = path15.resolve(input.cwd);
61347
61577
  if (input.kind === "rollbackLastTurn") {
61348
61578
  for (const source of this.#sessions) {
61349
61579
  const ready = await source.prepareRollback(input.sourceRef.nativeSessionId);
@@ -61503,7 +61733,7 @@ var ClaudeCodeAdapter = class {
61503
61733
  // dist/installation.js
61504
61734
  import { readFile as readFile8, realpath as realpath5 } from "node:fs/promises";
61505
61735
  import { homedir as homedir2 } from "node:os";
61506
- import path17 from "node:path";
61736
+ import path16 from "node:path";
61507
61737
  async function readSettings(file2) {
61508
61738
  const text2 = await readFile8(file2, "utf8").catch((error52) => {
61509
61739
  if (error52.code === "ENOENT")
@@ -61524,9 +61754,9 @@ function createClaudeInstallation(environment, command) {
61524
61754
  ...command ? { command } : {}
61525
61755
  });
61526
61756
  const home = environment.HOME ?? environment.USERPROFILE ?? homedir2();
61527
- const config2 = environment.CLAUDE_CONFIG_DIR ? path17.resolve(home, environment.CLAUDE_CONFIG_DIR) : path17.join(home, ".claude");
61528
- const managedFile = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : process.platform === "win32" ? path17.join(environment.ProgramFiles ?? "C:\\Program Files", "ClaudeCode", "managed-settings.json") : "/etc/claude-code/managed-settings.json";
61529
- const user = await readSettings(path17.join(config2, "settings.json"));
61757
+ const config2 = environment.CLAUDE_CONFIG_DIR ? path16.resolve(home, environment.CLAUDE_CONFIG_DIR) : path16.join(home, ".claude");
61758
+ const managedFile = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : process.platform === "win32" ? path16.join(environment.ProgramFiles ?? "C:\\Program Files", "ClaudeCode", "managed-settings.json") : "/etc/claude-code/managed-settings.json";
61759
+ const user = await readSettings(path16.join(config2, "settings.json"));
61530
61760
  const managed = await readSettings(managedFile);
61531
61761
  const settings = { ...user, ...managed, env: { ...user.env, ...managed.env } };
61532
61762
  const env = { ...environment, ...settings.env };
@@ -61539,10 +61769,10 @@ function createClaudeInstallation(environment, command) {
61539
61769
  throw new Error("Unknown Claude release channel");
61540
61770
  const latestVersion = installationVersion(await fetchInstallationText(`https://downloads.claude.ai/claude-code-releases/${channel}`));
61541
61771
  const npm = await npmInstallation(executable, ["@anthropic-ai/claude-code"], env);
61542
- const launcher = path17.join(home, ".local", "bin", process.platform === "win32" ? "claude.exe" : "claude");
61772
+ const launcher = path16.join(home, ".local", "bin", process.platform === "win32" ? "claude.exe" : "claude");
61543
61773
  const selected = await realpath5(executable);
61544
- const versions = path17.join(home, ".local", "share", "claude", "versions") + path17.sep;
61545
- const native = path17.resolve(executable) === launcher && (selected.startsWith(versions) || process.platform === "win32" && selected === launcher);
61774
+ const versions = path16.join(home, ".local", "share", "claude", "versions") + path16.sep;
61775
+ const native = path16.resolve(executable) === launcher && (selected.startsWith(versions) || process.platform === "win32" && selected === launcher);
61546
61776
  const blocked = !!env.DISABLE_UPDATES && env.DISABLE_UPDATES !== "0" || !!settings.minimumVersion && newerInstallationVersion(latestVersion, installationVersion(settings.minimumVersion)) || !!settings.requiredMaximumVersion && newerInstallationVersion(installationVersion(settings.requiredMaximumVersion), latestVersion);
61547
61777
  const canUpdate = !blocked && (npm?.canUpdate ?? native);
61548
61778
  update = async () => {
@@ -61573,7 +61803,7 @@ function createClaudeInstallation(environment, command) {
61573
61803
  }
61574
61804
 
61575
61805
  // dist/user-shell-environment.js
61576
- import path18 from "node:path";
61806
+ import path17 from "node:path";
61577
61807
  import { execFile as execFile4 } from "node:child_process";
61578
61808
  var ENVIRONMENT_MARKER = Buffer.from("\0CODEXHOST_USER_SHELL_ENV_V1\0");
61579
61809
  var ENVIRONMENT_COMMAND = "printf '\\0CODEXHOST_USER_SHELL_ENV_V1\\0'; /usr/bin/env -0";
@@ -61616,7 +61846,7 @@ async function withUserShellEnvironment(environment, dependencies) {
61616
61846
  if (platform === "win32" || !environment.HOME)
61617
61847
  return environment;
61618
61848
  const shell = environment.SHELL?.trim() || defaultShell(platform);
61619
- if (!shell || !SUPPORTED_SHELLS.has(path18.basename(shell)))
61849
+ if (!shell || !SUPPORTED_SHELLS.has(path17.basename(shell)))
61620
61850
  return environment;
61621
61851
  const cacheKey = `${platform}\0${shell}\0${environment.HOME}`;
61622
61852
  const cached2 = dependencies ? void 0 : shellEnvironmentCache.get(cacheKey);
@@ -61654,6 +61884,7 @@ async function createHarnessAdapter(context) {
61654
61884
  const environment = await withUserShellEnvironment({ ...context.environment });
61655
61885
  if (context.platform === "darwin" && context.managedRemoteHost) {
61656
61886
  return new BrokeredHarnessAdapter({
61887
+ sessionImport: true,
61657
61888
  forwardDelegationEnvironment: true,
61658
61889
  commandCatalog: claudeCommandCatalog,
61659
61890
  liveCommandCatalog: true,