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

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 (33) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +117 -13
  4. package/app/console-web.js +713 -129
  5. package/app/desktop-controller.mjs +713 -42
  6. package/app/host-runtime.mjs +2535 -855
  7. package/app/plugins/antigravity/plugin.mjs +437 -67
  8. package/app/plugins/claude-code/plugin.mjs +758 -248
  9. package/app/plugins/codebuddy/plugin.mjs +348 -156
  10. package/app/plugins/codex-usage/plugin.mjs +258 -106
  11. package/app/plugins/copilot/assets/icon.png +0 -0
  12. package/app/plugins/copilot/manifest.json +26 -0
  13. package/app/plugins/copilot/plugin.mjs +34651 -0
  14. package/app/plugins/cursor-cli/plugin.mjs +20905 -44961
  15. package/app/plugins/deepseek-harness/plugin.mjs +195 -53
  16. package/app/plugins/enabled.json +1 -0
  17. package/app/plugins/grok/plugin.mjs +584 -138
  18. package/app/plugins/hermes/plugin.mjs +134 -13
  19. package/app/plugins/kimi-code/plugin.mjs +145 -26
  20. package/app/plugins/kiro-cli/plugin.mjs +145 -26
  21. package/app/plugins/muse/plugin.mjs +132 -14
  22. package/app/plugins/omp/plugin.mjs +2245 -2040
  23. package/app/plugins/opencode/plugin.mjs +196 -72
  24. package/app/plugins/pi/plugin.mjs +2643 -2309
  25. package/app/plugins/qoder/plugin.mjs +162 -40
  26. package/app/plugins/qoder-cn/plugin.mjs +162 -40
  27. package/app/plugins/workbuddy/plugin.mjs +609 -180
  28. package/app/plugins/zcode/plugin.mjs +192 -44
  29. package/app/renderer-extension.js +3405 -429
  30. package/bin/boft +0 -0
  31. package/libexec/boft-shim +0 -0
  32. package/libexec/boft-updater +0 -0
  33. package/package.json +1 -1
@@ -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, path21) {
781
- if (!path21)
780
+ function getElementAtPath(obj, path20) {
781
+ if (!path20)
782
782
  return obj;
783
- return path21.reduce((acc, key) => acc?.[key], obj);
783
+ return path20.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(path21, issues) {
1192
+ function prefixIssues(path20, issues) {
1193
1193
  return issues.map((iss) => {
1194
1194
  var _a4;
1195
1195
  (_a4 = iss).path ?? (_a4.path = []);
1196
- iss.path.unshift(path21);
1196
+ iss.path.unshift(path20);
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, path21 = []) => {
1343
+ const processError = (error53, path20 = []) => {
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 }, [...path21, ...issue2.path]));
1346
+ issue2.errors.map((issues) => processError({ issues }, [...path20, ...issue2.path]));
1347
1347
  } else if (issue2.code === "invalid_key") {
1348
- processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
1348
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1349
1349
  } else if (issue2.code === "invalid_element") {
1350
- processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
1350
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1351
1351
  } else {
1352
- const fullpath = [...path21, ...issue2.path];
1352
+ const fullpath = [...path20, ...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, path21 = []) => {
1379
+ const processError = (error53, path20 = []) => {
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 }, [...path21, ...issue2.path]));
1383
+ issue2.errors.map((issues) => processError({ issues }, [...path20, ...issue2.path]));
1384
1384
  } else if (issue2.code === "invalid_key") {
1385
- processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
1385
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1386
1386
  } else if (issue2.code === "invalid_element") {
1387
- processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
1387
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1388
1388
  } else {
1389
- const fullpath = [...path21, ...issue2.path];
1389
+ const fullpath = [...path20, ...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 path21 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1422
- for (const seg of path21) {
1421
+ const path20 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1422
+ for (const seg of path20) {
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 path21 = ref.slice(1).split("/").filter(Boolean);
14115
- if (path21.length === 0) {
14114
+ const path20 = ref.slice(1).split("/").filter(Boolean);
14115
+ if (path20.length === 0) {
14116
14116
  return ctx.rootSchema;
14117
14117
  }
14118
14118
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14119
- if (path21[0] === defsKey) {
14120
- const key = path21[1];
14119
+ if (path20[0] === defsKey) {
14120
+ const key = path20[1];
14121
14121
  if (!key || !ctx.defs[key]) {
14122
14122
  throw new Error(`Reference not found: ${ref}`);
14123
14123
  }
@@ -14662,10 +14662,19 @@ var model = external_exports.string().min(1).max(512);
14662
14662
  var project = external_exports.string().min(1).max(4096);
14663
14663
  var usageStatisticsParamsSchema = external_exports.strictObject({
14664
14664
  range: external_exports.enum(USAGE_STATISTICS_RANGES),
14665
+ /** Display timezone for ranges, dates and hourly buckets; omitted means the Host's local zone. */
14666
+ timeZone: external_exports.string().min(1).max(128).refine((value) => {
14667
+ try {
14668
+ new Intl.DateTimeFormat("en", { timeZone: value });
14669
+ return true;
14670
+ } catch {
14671
+ return false;
14672
+ }
14673
+ }, "Unsupported usage statistics timezone").optional(),
14665
14674
  harness: harness.optional(),
14666
14675
  model: model.nullable().optional(),
14667
14676
  project: project.nullable().optional(),
14668
- /** One local date inside the range. */
14677
+ /** One date in the query timezone inside the range. */
14669
14678
  date: localDate.optional()
14670
14679
  });
14671
14680
  var usageStatisticsTotalsSchema = external_exports.strictObject({
@@ -14674,6 +14683,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
14674
14683
  cachedInputTokens: count,
14675
14684
  cacheWriteInputTokens: count,
14676
14685
  cacheKnownInputTokens: count,
14686
+ cacheHitCachedInputTokens: count,
14687
+ cacheHitInputTokens: count,
14677
14688
  outputTokens: count,
14678
14689
  reasoningOutputTokens: count,
14679
14690
  /** USD at the public price, summed over the priced requests only. */
@@ -14701,7 +14712,7 @@ var usageStatisticsSessionSchema = external_exports.strictObject({
14701
14712
  });
14702
14713
  var usageStatisticsResultSchema = external_exports.strictObject({
14703
14714
  range: external_exports.enum(USAGE_STATISTICS_RANGES),
14704
- /** First local date of the range; null for all time. */
14715
+ /** First date in the query timezone (Host local when omitted); null for all time. */
14705
14716
  from: localDate.nullable(),
14706
14717
  to: localDate,
14707
14718
  /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
@@ -14741,7 +14752,7 @@ var usageStatisticsResultSchema = external_exports.strictObject({
14741
14752
  totals: usageStatisticsTotalsSchema,
14742
14753
  /** Each date and Harness of the range: every filter except the day. */
14743
14754
  daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
14744
- /** Local weekday (0 = Sunday) and hour, all filters applied. */
14755
+ /** Weekday (0 = Sunday) and hour in the query timezone, all filters applied. */
14745
14756
  hourly: external_exports.array(external_exports.strictObject({
14746
14757
  weekday: external_exports.number().int().min(0).max(6),
14747
14758
  hour: external_exports.number().int().min(0).max(23),
@@ -14781,6 +14792,51 @@ var hostInteractionIdSchema = opaqueIdSchema.brand();
14781
14792
  var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
14782
14793
  var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
14783
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
+
14784
14840
  // ../../shared-contracts/dist/harness-plugins.js
14785
14841
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
14786
14842
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -14883,6 +14939,8 @@ var CONSOLE_HOST_METHODS = Object.freeze([
14883
14939
  "codexhost/harness/display-settings/set",
14884
14940
  "codexhost/harness/inspect",
14885
14941
  "codexhost/harness/installation",
14942
+ "codexhost/harness/installation/start",
14943
+ "codexhost/harness/installation/status",
14886
14944
  "codexhost/harness/launch-settings/get",
14887
14945
  "codexhost/harness/launch-settings/set",
14888
14946
  HARNESS_LONG_CONTEXT_GET_METHOD,
@@ -14960,7 +15018,18 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
14960
15018
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
14961
15019
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
14962
15020
  var cacheHitRatePercentSchema = external_exports.number().finite().min(0).max(100);
15021
+ var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text2) => text2.length <= maximum));
15022
+ var composerIndicatorsSchema = external_exports.array(external_exports.object({
15023
+ kind: external_exports.literal("countdown"),
15024
+ id: external_exports.string().min(1).max(64),
15025
+ expiresAtUnix: nonNegativeSafeIntegerSchema,
15026
+ label: indicatorTextSchema(256).optional(),
15027
+ tooltip: indicatorTextSchema(1024).optional()
15028
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, {
15029
+ message: "Composer indicator IDs must be unique"
15030
+ });
14963
15031
  var threadUsageSnapshotSchema = external_exports.object({
15032
+ composerIndicators: composerIndicatorsSchema.optional(),
14964
15033
  inputTokens: nonNegativeSafeIntegerSchema.optional(),
14965
15034
  cachedInputTokens: nonNegativeSafeIntegerSchema.optional(),
14966
15035
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
@@ -15386,7 +15455,9 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15386
15455
  }).strict().optional(),
15387
15456
  input: external_exports.object({
15388
15457
  image: external_exports.boolean()
15389
- }).strict().optional()
15458
+ }).strict().optional(),
15459
+ /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
15460
+ steer: external_exports.boolean().optional()
15390
15461
  }).strict();
15391
15462
  var harnessConfigurationStateSchema = external_exports.object({
15392
15463
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15433,7 +15504,9 @@ var harnessInspectionSchema = external_exports.union([
15433
15504
  var harnessInspectParamsSchema = external_exports.object({
15434
15505
  harnessId: harnessIdSchema,
15435
15506
  cwd: nonBlankTextSchema2.max(16384).optional(),
15436
- refresh: external_exports.boolean().optional()
15507
+ refresh: external_exports.boolean().optional(),
15508
+ /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15509
+ purpose: external_exports.literal("availability").optional()
15437
15510
  }).strict();
15438
15511
  var harnessWebUiOpenParamsSchema = external_exports.object({
15439
15512
  harnessId: harnessIdSchema
@@ -15518,13 +15591,25 @@ var threadOwnershipListResultSchema = external_exports.object({
15518
15591
  seen.add(thread.threadId);
15519
15592
  }
15520
15593
  });
15594
+ var threadSteeringInspectParamsSchema = external_exports.object({
15595
+ threadId: hostThreadIdSchema,
15596
+ /** The text about to be steered; a Harness command always stops and restarts. */
15597
+ text: external_exports.string().optional()
15598
+ }).strict();
15599
+ var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15600
+ var threadSteeringInspectResultSchema = external_exports.object({
15601
+ delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15602
+ }).strict();
15521
15603
 
15522
15604
  // ../../shared-contracts/dist/harness-route.js
15523
15605
  var harnessPluginRouteSchema = external_exports.object({
15524
15606
  harnessId: harnessPluginIdSchema,
15525
15607
  model: harnessModelRefSchema.optional(),
15526
15608
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
15527
- permissionModeId: harnessPermissionModeIdSchema.optional()
15609
+ permissionModeId: harnessPermissionModeIdSchema.optional(),
15610
+ /** A draft prewarm create: stays unsubmitted until the user's first Turn.
15611
+ * Desktop forwards only the Model of a main-process prewarm to thread/start. */
15612
+ prewarm: external_exports.literal(true).optional()
15528
15613
  }).strict();
15529
15614
 
15530
15615
  // ../../shared-contracts/dist/harness-launch-settings.js
@@ -15550,6 +15635,10 @@ var harnessInstallationStateSchema = external_exports.object({
15550
15635
  latestVersion: external_exports.string().min(1).max(128),
15551
15636
  updateAvailable: external_exports.boolean(),
15552
15637
  canUpdate: external_exports.boolean(),
15638
+ /** Defaults to CLI; some Harnesses ship only inside a desktop application. */
15639
+ versionKind: external_exports.enum(["cli", "application"]).optional(),
15640
+ /** Official download opened by the user; does not imply an automatic installation. */
15641
+ manualUpdateUrl: external_exports.url().max(2048).refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Manual updates require a credential-free HTTPS URL").optional(),
15553
15642
  // Adapter-owned diagnostic text; UI uses messageCode rather than displaying it verbatim.
15554
15643
  message: external_exports.string().max(2048).optional(),
15555
15644
  messageCode: external_exports.string().min(1).max(128).optional(),
@@ -15557,6 +15646,20 @@ var harnessInstallationStateSchema = external_exports.object({
15557
15646
  notice: harnessLocalizedTextSchema.optional(),
15558
15647
  latestVersionKind: external_exports.enum(["unknown", "tracking-branch"]).optional()
15559
15648
  }).strict();
15649
+ var harnessInstallationTaskParamsSchema = external_exports.object({ taskId: external_exports.string().uuid() }).strict();
15650
+ var harnessInstallationTaskSchema = external_exports.discriminatedUnion("status", [
15651
+ external_exports.object({ taskId: external_exports.string().uuid(), status: external_exports.literal("running") }).strict(),
15652
+ external_exports.object({
15653
+ taskId: external_exports.string().uuid(),
15654
+ status: external_exports.literal("succeeded"),
15655
+ result: harnessInstallationStateSchema
15656
+ }).strict(),
15657
+ external_exports.object({
15658
+ taskId: external_exports.string().uuid(),
15659
+ status: external_exports.literal("failed"),
15660
+ error: external_exports.object({ code: external_exports.number().int(), message: external_exports.string().min(1).max(2048) }).strict()
15661
+ }).strict()
15662
+ ]);
15560
15663
 
15561
15664
  // ../../shared-contracts/dist/codex-accounts.js
15562
15665
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
@@ -16081,6 +16184,7 @@ var usageFields = /* @__PURE__ */ new Set([
16081
16184
  ...safeIntegerFields,
16082
16185
  ...percentFields,
16083
16186
  "sessionCacheUsage",
16187
+ "composerIndicators",
16084
16188
  "totalCostUsd",
16085
16189
  "totalCredits",
16086
16190
  "contextUsagePercent",
@@ -16103,26 +16207,27 @@ function parseHostUsage(value) {
16103
16207
  throw new Error(`Harness Usage contains unknown field '${key}'`);
16104
16208
  }
16105
16209
  }
16106
- for (const field of [
16210
+ const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
16211
+ for (const field2 of [
16107
16212
  "totalCredits",
16108
16213
  "contextUsagePercent",
16109
16214
  "apiOutputTokensPerSecond"
16110
16215
  ]) {
16111
- const candidate = value[field];
16216
+ const candidate = value[field2];
16112
16217
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16113
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16218
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
16114
16219
  }
16115
16220
  }
16116
- for (const field of tokenFields) {
16117
- const candidate = value[field];
16221
+ for (const field2 of tokenFields) {
16222
+ const candidate = value[field2];
16118
16223
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16119
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16224
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
16120
16225
  }
16121
16226
  }
16122
- for (const field of safeIntegerFields) {
16123
- const candidate = value[field];
16227
+ for (const field2 of safeIntegerFields) {
16228
+ const candidate = value[field2];
16124
16229
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16125
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
16230
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
16126
16231
  }
16127
16232
  }
16128
16233
  if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
@@ -16131,16 +16236,16 @@ function parseHostUsage(value) {
16131
16236
  if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
16132
16237
  throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
16133
16238
  }
16134
- for (const field of ["totalCredits", "contextUsagePercent"]) {
16135
- const candidate = value[field];
16239
+ for (const field2 of ["totalCredits", "contextUsagePercent"]) {
16240
+ const candidate = value[field2];
16136
16241
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
16137
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
16242
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
16138
16243
  }
16139
16244
  }
16140
- for (const field of percentFields) {
16141
- const candidate = value[field];
16245
+ for (const field2 of percentFields) {
16246
+ const candidate = value[field2];
16142
16247
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
16143
- throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
16248
+ throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
16144
16249
  }
16145
16250
  }
16146
16251
  if (value.sessionCacheUsage !== void 0) {
@@ -16179,9 +16284,9 @@ function parseHostUsage(value) {
16179
16284
  if (value.costSource !== "publicPrice") {
16180
16285
  throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
16181
16286
  }
16182
- return { ...value, unpricedModels: [...models] };
16287
+ return { ...value, ...indicators, unpricedModels: [...models] };
16183
16288
  }
16184
- return { ...value };
16289
+ return { ...value, ...indicators };
16185
16290
  }
16186
16291
  var requestTokenFields = [
16187
16292
  "inputTokens",
@@ -16211,19 +16316,19 @@ function parseHostUsageRequest(value) {
16211
16316
  if (typeof value.requestId !== "string" || value.requestId.length === 0) {
16212
16317
  throw new Error("Harness Usage request 'requestId' must be a non-empty string");
16213
16318
  }
16214
- for (const field of ["model", "provider"]) {
16215
- const candidate = value[field];
16319
+ for (const field2 of ["model", "provider"]) {
16320
+ const candidate = value[field2];
16216
16321
  if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
16217
- throw new Error(`Harness Usage request '${field}' must be a non-empty string`);
16322
+ throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
16218
16323
  }
16219
16324
  }
16220
16325
  if (value.historical !== void 0 && typeof value.historical !== "boolean") {
16221
16326
  throw new Error("Harness Usage request 'historical' must be a boolean");
16222
16327
  }
16223
- for (const field of requestTokenFields) {
16224
- const candidate = value[field];
16328
+ for (const field2 of requestTokenFields) {
16329
+ const candidate = value[field2];
16225
16330
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
16226
- throw new Error(`Harness Usage request '${field}' must be a non-negative safe integer`);
16331
+ throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
16227
16332
  }
16228
16333
  }
16229
16334
  if (value.inputTokens === void 0 || value.outputTokens === void 0) {
@@ -16383,6 +16488,7 @@ var harnessBrokerMethodSchema = external_exports.enum([
16383
16488
  "adapter.sessionImport.resolve",
16384
16489
  "adapter.subagent.readSnapshot",
16385
16490
  "session.readSnapshot",
16491
+ "session.readCapabilities",
16386
16492
  "session.refreshUsage",
16387
16493
  "session.execute",
16388
16494
  "session.commands.list",
@@ -16482,30 +16588,6 @@ function consumeBrokerFrames(socket, onFrame, onError) {
16482
16588
  });
16483
16589
  }
16484
16590
 
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
16591
  // ../../harness-broker/dist/validation.js
16510
16592
  var cwdSchema = external_exports.string().min(1).max(16384);
16511
16593
  var brokerEnvironmentSchema = external_exports.object({
@@ -16556,7 +16638,11 @@ var brokerOpenInputSchema = external_exports.discriminatedUnion("kind", [
16556
16638
  forkSchema,
16557
16639
  rollbackSchema
16558
16640
  ]);
16559
- var brokerInspectInputSchema = external_exports.object({ cwd: cwdSchema.optional(), refresh: external_exports.boolean().optional() }).strict();
16641
+ var brokerInspectInputSchema = external_exports.object({
16642
+ cwd: cwdSchema.optional(),
16643
+ refresh: external_exports.boolean().optional(),
16644
+ purpose: external_exports.literal("availability").optional()
16645
+ }).strict();
16560
16646
  var brokerSessionImportListParamsSchema = external_exports.object({
16561
16647
  offset: external_exports.number().int().nonnegative().safe(),
16562
16648
  limit: external_exports.number().int().min(1).max(HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE)
@@ -16571,10 +16657,10 @@ var brokerSessionImportSourceSchema = external_exports.object({
16571
16657
  candidate: harnessSessionImportCandidateSchema,
16572
16658
  nativeRef: nativeSessionRefSchema
16573
16659
  }).strict().superRefine((source, context) => {
16574
- if (source.nativeRef.harnessId !== "claude-code" || source.nativeRef.nativeSessionId !== source.candidate.nativeSessionId) {
16660
+ if (source.nativeRef.nativeSessionId !== source.candidate.nativeSessionId) {
16575
16661
  context.addIssue({
16576
16662
  code: "custom",
16577
- message: "Claude Session import source identity does not match"
16663
+ message: "Session import source identity does not match"
16578
16664
  });
16579
16665
  }
16580
16666
  });
@@ -16584,6 +16670,11 @@ var turnStartSchema = external_exports.object({
16584
16670
  turnId: hostTurnIdSchema,
16585
16671
  input: external_exports.array(textInputSchema)
16586
16672
  }).strict();
16673
+ var turnSteerSchema = external_exports.object({
16674
+ type: external_exports.literal("turn.steer"),
16675
+ turnId: hostTurnIdSchema,
16676
+ input: external_exports.array(textInputSchema)
16677
+ }).strict();
16587
16678
  var turnCancelSchema = external_exports.object({ type: external_exports.literal("turn.cancel"), turnId: hostTurnIdSchema }).strict();
16588
16679
  var interactionResponseSchema = external_exports.union([
16589
16680
  external_exports.object({
@@ -16609,6 +16700,7 @@ var permissionSelectSchema = external_exports.object({
16609
16700
  }).strict();
16610
16701
  var brokerHostCommandSchema = external_exports.discriminatedUnion("type", [
16611
16702
  turnStartSchema,
16703
+ turnSteerSchema,
16612
16704
  turnCancelSchema,
16613
16705
  interactionRespondSchema,
16614
16706
  modelSelectSchema,
@@ -16742,6 +16834,107 @@ var harnessOutputSchema = external_exports.custom((value) => {
16742
16834
  return false;
16743
16835
  });
16744
16836
 
16837
+ // ../../harness-broker/dist/session-import-client.js
16838
+ function createBrokerSessionImportCapability(input) {
16839
+ let listing = null;
16840
+ const closed = () => ({
16841
+ ok: false,
16842
+ error: { code: "invalidState", message: "Harness broker adapter is closed", retryable: false }
16843
+ });
16844
+ const invalid = () => ({
16845
+ ok: false,
16846
+ error: {
16847
+ code: "protocolError",
16848
+ message: "Harness broker returned invalid Session import metadata",
16849
+ retryable: false
16850
+ }
16851
+ });
16852
+ const list = async () => {
16853
+ try {
16854
+ const candidates = [];
16855
+ const identities = /* @__PURE__ */ new Set();
16856
+ let total;
16857
+ for (; ; ) {
16858
+ if (input.isClosed())
16859
+ return closed();
16860
+ const result = await input.request("adapter.sessionImport.list", {
16861
+ offset: candidates.length,
16862
+ limit: HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE
16863
+ });
16864
+ if (input.isClosed())
16865
+ return closed();
16866
+ if (!result.ok)
16867
+ return result;
16868
+ const page = brokerSessionImportPageSchema.safeParse(result.value);
16869
+ 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)
16870
+ return invalid();
16871
+ total = page.data.total;
16872
+ for (const candidate of page.data.candidates) {
16873
+ if (identities.has(candidate.nativeSessionId))
16874
+ return invalid();
16875
+ identities.add(candidate.nativeSessionId);
16876
+ candidates.push(candidate);
16877
+ }
16878
+ if (candidates.length === total)
16879
+ return { ok: true, value: candidates };
16880
+ }
16881
+ } catch (error52) {
16882
+ return { ok: false, error: input.error(error52) };
16883
+ }
16884
+ };
16885
+ return {
16886
+ listCandidates() {
16887
+ if (input.isClosed())
16888
+ return Promise.resolve(closed());
16889
+ listing ??= list().finally(() => {
16890
+ listing = null;
16891
+ });
16892
+ return listing;
16893
+ },
16894
+ async resolveCandidate(nativeSessionId) {
16895
+ if (input.isClosed())
16896
+ return closed();
16897
+ try {
16898
+ const result = await input.request("adapter.sessionImport.resolve", { nativeSessionId });
16899
+ if (input.isClosed())
16900
+ return closed();
16901
+ if (!result.ok)
16902
+ return result;
16903
+ const source = brokerSessionImportSourceSchema.safeParse(result.value);
16904
+ if (!source.success || source.data.nativeRef.harnessId !== input.harnessId || source.data.candidate.nativeSessionId !== nativeSessionId)
16905
+ return invalid();
16906
+ return { ok: true, value: source.data };
16907
+ } catch (error52) {
16908
+ return { ok: false, error: input.error(error52) };
16909
+ }
16910
+ }
16911
+ };
16912
+ }
16913
+
16914
+ // ../../harness-broker/dist/paths.js
16915
+ import os from "node:os";
16916
+ import path from "node:path";
16917
+ var HARNESS_BROKER_DESCRIPTOR_ENV = "CODEXHOST_CLAUDE_BROKER_DESCRIPTOR";
16918
+ var HARNESS_BROKER_DESCRIPTOR_FILE = "claude-code-broker-v1.json";
16919
+ function defaultHarnessBrokerDirectory(environment = process.env) {
16920
+ const home = environment.HOME || os.homedir();
16921
+ return path.join(home, ".codexhost", "harness-broker");
16922
+ }
16923
+ function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId = "claude-code") {
16924
+ harnessPluginIdSchema.parse(harnessId);
16925
+ if (harnessId !== "claude-code")
16926
+ return path.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
16927
+ return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
16928
+ }
16929
+ function harnessBrokerLaunchAgentLabel(harnessId = "claude-code") {
16930
+ harnessPluginIdSchema.parse(harnessId);
16931
+ return harnessId === "claude-code" ? "ai.bytepioneer.codexhost.native-harness-broker" : `ai.bytepioneer.codexhost.${harnessId}-broker`;
16932
+ }
16933
+ function harnessBrokerLaunchAgentPlistPath(environment = process.env, harnessId = "claude-code") {
16934
+ const home = environment.HOME || os.homedir();
16935
+ return path.join(home, "Library", "LaunchAgents", `${harnessBrokerLaunchAgentLabel(harnessId)}.plist`);
16936
+ }
16937
+
16745
16938
  // ../../harness-broker/dist/client.js
16746
16939
  function unavailable(message, retryable = true) {
16747
16940
  return { code: "unavailable", message, retryable, stage: "harnessBroker" };
@@ -16801,6 +16994,7 @@ function parseSessionMetadata(value) {
16801
16994
  sessionId: candidate.sessionId,
16802
16995
  sessionGeneration: candidate.sessionGeneration,
16803
16996
  capabilities: harnessSessionCapabilitiesSchema.parse(candidate.capabilities),
16997
+ readCapabilities: candidate.readCapabilities === true,
16804
16998
  initialState: state,
16805
16999
  initialUsage: candidate.initialUsage === null ? null : parseHostUsage(candidate.initialUsage),
16806
17000
  commands: candidate.commands === true
@@ -17152,6 +17346,11 @@ var BrokeredHarnessSession = class {
17152
17346
  event: { type: "session.faulted", error: unavailable(error52.message) }
17153
17347
  });
17154
17348
  }
17349
+ async readCapabilities() {
17350
+ if (!this.#metadata.readCapabilities)
17351
+ return { ...this.capabilities, steer: false };
17352
+ return harnessSessionCapabilitiesSchema.parse(await this.#request("session.readCapabilities", {}));
17353
+ }
17155
17354
  async refreshUsage() {
17156
17355
  await this.#request("session.refreshUsage", {});
17157
17356
  }
@@ -17183,6 +17382,8 @@ var BrokeredHarnessSession = class {
17183
17382
  try {
17184
17383
  return parseHarnessResult(await this.#request("session.execute", { command }));
17185
17384
  } catch (error52) {
17385
+ if (command.type === "turn.steer")
17386
+ throw error52;
17186
17387
  return {
17187
17388
  ok: false,
17188
17389
  error: unavailable(error52 instanceof Error ? error52.message : String(error52))
@@ -17270,6 +17471,7 @@ var BrokeredHarnessAdapter = class {
17270
17471
  commandCatalog;
17271
17472
  liveCommandCatalog;
17272
17473
  harnessId;
17474
+ sessionImport;
17273
17475
  credits;
17274
17476
  refreshCredits;
17275
17477
  #descriptorPath;
@@ -17279,7 +17481,6 @@ var BrokeredHarnessAdapter = class {
17279
17481
  #startTimeoutMs;
17280
17482
  #connection = null;
17281
17483
  #closed = false;
17282
- #sessionImportListing = null;
17283
17484
  #credits = null;
17284
17485
  #creditsRefresh = null;
17285
17486
  subagents = {
@@ -17291,86 +17492,16 @@ var BrokeredHarnessAdapter = class {
17291
17492
  }
17292
17493
  }
17293
17494
  };
17294
- sessionImport = Object.freeze({
17295
- listCandidates: () => {
17296
- this.#sessionImportListing ??= this.#listSessionImportCandidates().finally(() => {
17297
- this.#sessionImportListing = null;
17298
- });
17299
- return this.#sessionImportListing;
17300
- },
17301
- resolveCandidate: async (nativeSessionId) => {
17302
- if (this.#closed) {
17303
- return {
17304
- ok: false,
17305
- error: unavailable("Claude Aqua broker adapter is closed", false)
17306
- };
17307
- }
17308
- try {
17309
- const result = parseHarnessResult(await (await this.#connect()).request("adapter.sessionImport.resolve", {
17310
- nativeSessionId
17311
- }));
17312
- if (!result.ok)
17313
- return result;
17314
- const parsed = brokerSessionImportSourceSchema.safeParse(result.value);
17315
- if (!parsed.success || parsed.data.candidate.nativeSessionId !== nativeSessionId) {
17316
- return {
17317
- ok: false,
17318
- error: {
17319
- ...unavailable("Harness broker returned an invalid Session source", false),
17320
- code: "protocolError"
17321
- }
17322
- };
17323
- }
17324
- return { ok: true, value: parsed.data };
17325
- } catch (error52) {
17326
- this.#connection = null;
17327
- return {
17328
- ok: false,
17329
- error: unavailable(error52 instanceof Error ? error52.message : String(error52))
17330
- };
17331
- }
17332
- }
17333
- });
17334
- async #listSessionImportCandidates() {
17335
- if (this.#closed) {
17336
- return {
17337
- ok: false,
17338
- error: unavailable("Claude Aqua broker adapter is closed", false)
17339
- };
17340
- }
17341
- try {
17342
- const candidates = [];
17343
- for (; ; ) {
17344
- const result = parseHarnessResult(await (await this.#connect()).request("adapter.sessionImport.list", {
17345
- offset: candidates.length,
17346
- limit: HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE
17347
- }));
17348
- if (!result.ok)
17349
- return result;
17350
- const parsed = brokerSessionImportPageSchema.safeParse(result.value);
17351
- if (!parsed.success || parsed.data.total < candidates.length + parsed.data.candidates.length || parsed.data.candidates.length === 0 && candidates.length < parsed.data.total) {
17352
- return {
17353
- ok: false,
17354
- error: {
17355
- ...unavailable("Harness broker returned invalid Session candidates", false),
17356
- code: "protocolError"
17357
- }
17358
- };
17359
- }
17360
- candidates.push(...parsed.data.candidates);
17361
- if (candidates.length === parsed.data.total)
17362
- return { ok: true, value: candidates };
17363
- }
17364
- } catch (error52) {
17365
- this.#connection = null;
17366
- return {
17367
- ok: false,
17368
- error: unavailable(error52 instanceof Error ? error52.message : String(error52))
17369
- };
17370
- }
17371
- }
17372
17495
  constructor(input = {}) {
17373
17496
  this.harnessId = harnessPluginIdSchema.parse(input.harnessId ?? "claude-code");
17497
+ if (input.sessionImport) {
17498
+ this.sessionImport = createBrokerSessionImportCapability({
17499
+ harnessId: this.harnessId,
17500
+ request: async (method, params) => parseHarnessResult(await this.#request(method, params, method === "adapter.sessionImport.resolve")),
17501
+ isClosed: () => this.#closed,
17502
+ error: (error52) => this.#error(error52)
17503
+ });
17504
+ }
17374
17505
  if (input.accountCredits !== false) {
17375
17506
  this.credits = () => this.#credits;
17376
17507
  this.refreshCredits = () => this.#refreshAccountCredits();
@@ -17648,10 +17779,13 @@ function usageSessionTitle(value) {
17648
17779
  return void 0;
17649
17780
  if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
17650
17781
  return normalized;
17651
- const characters = [...normalized];
17652
- if (characters.length <= MAX_SESSION_TITLE_LENGTH)
17653
- return normalized;
17654
- return `${characters.slice(0, MAX_SESSION_TITLE_LENGTH - 1).join("").trimEnd()}…`;
17782
+ let title = "";
17783
+ for (const character of normalized) {
17784
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
17785
+ break;
17786
+ title += character;
17787
+ }
17788
+ return `${title.trimEnd()}…`;
17655
17789
  }
17656
17790
  function sessionIdOk(value) {
17657
17791
  return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
@@ -17804,9 +17938,34 @@ function createClaudeUsageStatistics(environment) {
17804
17938
  });
17805
17939
  }
17806
17940
 
17941
+ // dist/claude-prompt-cache.js
17942
+ function lastClaudeAssistantResponseUnix(messages) {
17943
+ let latest;
17944
+ for (const entry of messages) {
17945
+ if (typeof entry !== "object" || entry === null || !("type" in entry) || entry.type !== "assistant" || "isSidechain" in entry && entry.isSidechain === true || "parent_tool_use_id" in entry && entry.parent_tool_use_id != null || !("timestamp" in entry) || typeof entry.timestamp !== "string")
17946
+ continue;
17947
+ const time3 = Math.floor(Date.parse(entry.timestamp) / 1e3);
17948
+ if (Number.isSafeInteger(time3) && time3 >= 0)
17949
+ latest = Math.max(latest ?? 0, time3);
17950
+ }
17951
+ return latest;
17952
+ }
17953
+ function claudePromptCacheIndicators(accountCreditsSupported, lastResponseAtUnix) {
17954
+ if (!accountCreditsSupported || lastResponseAtUnix === void 0)
17955
+ return [];
17956
+ return [
17957
+ {
17958
+ kind: "countdown",
17959
+ id: "prompt-cache",
17960
+ expiresAtUnix: lastResponseAtUnix + 3600,
17961
+ label: { en: "Prompt cache", "zh-CN": "提示词缓存" }
17962
+ }
17963
+ ];
17964
+ }
17965
+
17807
17966
  // dist/claude-code-adapter.js
17808
17967
  import { randomUUID as randomUUID6 } from "node:crypto";
17809
- import path18 from "node:path";
17968
+ import path17 from "node:path";
17810
17969
 
17811
17970
  // ../../../node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs
17812
17971
  import { createRequire as jre } from "node:module";
@@ -54566,7 +54725,6 @@ var ClaudePendingSessions = class {
54566
54725
  };
54567
54726
 
54568
54727
  // dist/claude-fork.js
54569
- import path11 from "node:path";
54570
54728
  import { isDeepStrictEqual } from "node:util";
54571
54729
 
54572
54730
  // dist/file-change.js
@@ -54708,6 +54866,17 @@ function targetedSubagentId(argumentsValue) {
54708
54866
  return void 0;
54709
54867
  return boundedString(argumentsValue.to ?? argumentsValue.recipient ?? argumentsValue.agentId, SUBAGENT_DESCRIPTION_LIMIT);
54710
54868
  }
54869
+ function claudeSendMessageFailed(nativeResult, outputText) {
54870
+ if (isRecord6(nativeResult) && typeof nativeResult.success === "boolean") {
54871
+ return nativeResult.success === false;
54872
+ }
54873
+ try {
54874
+ const parsed = JSON.parse(outputText ?? "");
54875
+ return isRecord6(parsed) && parsed.success === false;
54876
+ } catch {
54877
+ return false;
54878
+ }
54879
+ }
54711
54880
  function includesAuthenticationFailure(errors) {
54712
54881
  return errors.some((error52) => AUTHENTICATION_ERRORS.has(error52));
54713
54882
  }
@@ -54724,17 +54893,21 @@ function parseResultModelUsage(value) {
54724
54893
  if (!isRecord6(value))
54725
54894
  return void 0;
54726
54895
  const usage = [];
54727
- for (const entry of Object.values(value)) {
54896
+ for (const [model2, entry] of Object.entries(value)) {
54728
54897
  if (!isRecord6(entry) || !safeNonNegativeInteger(entry.inputTokens) || !safeNonNegativeInteger(entry.outputTokens)) {
54729
54898
  return void 0;
54730
54899
  }
54900
+ const cacheRead = safeNonNegativeInteger(entry.cacheReadInputTokens) ? entry.cacheReadInputTokens : 0;
54901
+ const cacheWrite = safeNonNegativeInteger(entry.cacheCreationInputTokens) ? entry.cacheCreationInputTokens : 0;
54902
+ const promptTokens = entry.inputTokens + cacheRead + cacheWrite;
54731
54903
  usage.push({
54904
+ model: model2,
54732
54905
  inputTokens: entry.inputTokens,
54733
54906
  outputTokens: entry.outputTokens,
54734
- // Cache totals are optional in older payloads; default to zero so the
54735
- // session-cumulative cache hit rate can still be derived per entry.
54736
- cacheReadInputTokens: safeNonNegativeInteger(entry.cacheReadInputTokens) ? entry.cacheReadInputTokens : 0,
54737
- cacheCreationInputTokens: safeNonNegativeInteger(entry.cacheCreationInputTokens) ? entry.cacheCreationInputTokens : 0
54907
+ cacheReadInputTokens: cacheRead,
54908
+ cacheCreationInputTokens: cacheWrite,
54909
+ ...Number.isSafeInteger(promptTokens) ? { promptTokens } : {},
54910
+ ...safeNonNegativeInteger(entry.contextWindow) && entry.contextWindow > 0 ? { contextWindowTokens: entry.contextWindow } : {}
54738
54911
  });
54739
54912
  }
54740
54913
  return usage;
@@ -55086,6 +55259,7 @@ var ClaudeNativeTurnAccumulator = class {
55086
55259
  events.push({
55087
55260
  type: "message.completed",
55088
55261
  messageId,
55262
+ localCommand: true,
55089
55263
  ...checkpointId ? { checkpointId } : {}
55090
55264
  });
55091
55265
  }
@@ -55435,7 +55609,7 @@ var ClaudeNativeTurnAccumulator = class {
55435
55609
  events.push({
55436
55610
  type: "subagent.completed",
55437
55611
  callId,
55438
- isError,
55612
+ isError: isError || tool.name === "SendMessage" && claudeSendMessageFailed(nativeResult, outputText),
55439
55613
  ...subagentContinuesInBackground(nativeResult, outputText) ? { continuesInBackground: true } : {},
55440
55614
  ...agentId ? { nativeSubagentId: agentId } : {},
55441
55615
  ...resultSummary ? { resultSummary } : {}
@@ -55588,6 +55762,10 @@ function conversationMessages(values, sessionId) {
55588
55762
  const messages = [];
55589
55763
  const ids = /* @__PURE__ */ new Set();
55590
55764
  let promptId = null;
55765
+ const occupancy = new ClaudeBackgroundOccupancy();
55766
+ let accumulator = new ClaudeNativeTurnAccumulator();
55767
+ const sends = /* @__PURE__ */ new Map();
55768
+ let pendingNotification = false;
55591
55769
  for (const value of values) {
55592
55770
  if (!isRecord7(value))
55593
55771
  throw new Error("Claude history contains a malformed message");
@@ -55607,8 +55785,48 @@ function conversationMessages(values, sessionId) {
55607
55785
  timestampMs: isoToMs(value.timestamp),
55608
55786
  nested: typeof value.parent_tool_use_id === "string" && value.parent_tool_use_id.length > 0,
55609
55787
  interrupted,
55788
+ startsTurn: false,
55610
55789
  syntheticUser: value.type === "user" && (interrupted || value.isSynthetic === true || value.isMeta === true || isTaskNotificationOrigin(value) || value.toolUseResult !== void 0 && value.toolUseResult !== null)
55611
55790
  };
55791
+ const notification = message.type === "user" && !message.nested && (isTaskNotificationOrigin(value) || textParts(message.message.content).some(isTaskNotificationRecord));
55792
+ message.startsTurn = isHumanUser(message) || notification && !occupancy.unsettled && !pendingNotification;
55793
+ if (message.startsTurn) {
55794
+ occupancy.clear();
55795
+ sends.clear();
55796
+ accumulator = new ClaudeNativeTurnAccumulator();
55797
+ }
55798
+ for (const event of accumulator.consume(value).events) {
55799
+ if (event.type === "subagent.started") {
55800
+ if (event.operation === "send") {
55801
+ sends.set(event.callId, event.nativeSubagentId);
55802
+ } else if (event.background)
55803
+ occupancy.occupySpawn(event.callId, event.nativeSubagentId);
55804
+ } else if (event.type === "subagent.completed") {
55805
+ if (sends.has(event.callId)) {
55806
+ const agentId = event.nativeSubagentId ?? sends.get(event.callId);
55807
+ if (!event.isError && agentId)
55808
+ occupancy.occupyAgent(agentId);
55809
+ sends.delete(event.callId);
55810
+ } else if (!event.isError && event.continuesInBackground) {
55811
+ occupancy.occupySpawn(event.callId, event.nativeSubagentId);
55812
+ } else
55813
+ occupancy.release(event.callId, event.nativeSubagentId);
55814
+ } else if (event.type === "workflow.launched" && event.background && !event.isError) {
55815
+ occupancy.occupySpawn(event.callId, event.taskId);
55816
+ } else if (event.type === "subagent.settled") {
55817
+ occupancy.notify(event.callId, event.nativeSubagentId);
55818
+ }
55819
+ }
55820
+ if (notification)
55821
+ pendingNotification = true;
55822
+ if (message.type === "assistant" && !message.nested) {
55823
+ pendingNotification = false;
55824
+ if (["end_turn", "stop_sequence", "max_tokens"].includes(String(message.message.stop_reason))) {
55825
+ occupancy.releaseContinuations();
55826
+ }
55827
+ }
55828
+ if (interrupted)
55829
+ occupancy.clear();
55612
55830
  messages.push(message);
55613
55831
  if (isHumanUser(message)) {
55614
55832
  promptId = typeof value.promptId === "string" && value.promptId.length > 0 ? value.promptId : null;
@@ -55666,17 +55884,17 @@ function mapClaudeSnapshot(values, sessionId) {
55666
55884
  const turns = [];
55667
55885
  for (let index = 0; index < messages.length; ) {
55668
55886
  const user = messages[index];
55669
- if (!user || !isHumanUser(user)) {
55887
+ if (!user || !user.startsTurn) {
55670
55888
  index += 1;
55671
55889
  continue;
55672
55890
  }
55673
55891
  let end = index + 1;
55674
- while (end < messages.length && !isHumanUser(messages[end]))
55892
+ while (end < messages.length && !messages[end]?.startsTurn)
55675
55893
  end += 1;
55676
55894
  const turnMessages = messages.slice(index, end);
55677
55895
  const outcome = turnOutcome(turnMessages);
55678
55896
  const results = toolResultBlocks(turnMessages);
55679
- const checkpointMessage = turnMessages.findLast(({ type, interrupted }) => type === "assistant" || interrupted);
55897
+ const checkpointMessage = turnMessages.findLast(({ type, interrupted, nested }) => !nested && (type === "assistant" || interrupted));
55680
55898
  const startedAtMs = turnMessages[0]?.timestampMs;
55681
55899
  const completedAtMs = turnMessages.at(-1)?.timestampMs;
55682
55900
  let agentMessageOrdinal = 0;
@@ -55779,7 +55997,7 @@ function mapClaudeSnapshot(values, sessionId) {
55779
55997
  if (!result)
55780
55998
  continue;
55781
55999
  const output = toolResultOutput(result.block);
55782
- const failed = result.block.is_error === true;
56000
+ const failed = result.block.is_error === true || block.name === "SendMessage" && claudeSendMessageFailed(void 0, output);
55783
56001
  const toolDurationMs = elapsedMs(message.timestampMs, result.timestampMs);
55784
56002
  const toolOutcome = failed ? {
55785
56003
  status: "failed",
@@ -56096,12 +56314,6 @@ async function forkClaudeSession(input) {
56096
56314
  error: error51("protocolError", "Claude Code Session working directory is unavailable", false)
56097
56315
  };
56098
56316
  }
56099
- if (path11.resolve(sourceInfo.cwd) !== input.cwd) {
56100
- return {
56101
- ok: false,
56102
- error: error51("unsupported", "Claude Code cannot Fork across working directories", false)
56103
- };
56104
- }
56105
56317
  const source = await readSnapshot(input.dependencies, input.cwd, sourceRef.data.nativeSessionId);
56106
56318
  if (!source.ok)
56107
56319
  return source;
@@ -56197,7 +56409,7 @@ async function forkClaudeSession(input) {
56197
56409
 
56198
56410
  // dist/claude-session-import.js
56199
56411
  import { realpath as realpath4, stat as stat3 } from "node:fs/promises";
56200
- import path12 from "node:path";
56412
+ import path11 from "node:path";
56201
56413
  function titleFromMetadata(metadata) {
56202
56414
  for (const value of [metadata.customTitle, metadata.summary, metadata.firstPrompt]) {
56203
56415
  if (typeof value !== "string")
@@ -56219,7 +56431,7 @@ async function sourceFromMetadata(metadata, isRunning, signal, canonicalCwds, pr
56219
56431
  ];
56220
56432
  let cwd = null;
56221
56433
  for (const candidate2 of new Set(candidates)) {
56222
- if (!path12.isAbsolute(candidate2))
56434
+ if (!path11.isAbsolute(candidate2))
56223
56435
  continue;
56224
56436
  let canonical = canonicalCwds.get(candidate2);
56225
56437
  if (!canonical) {
@@ -56296,7 +56508,7 @@ var ClaudeSessionImportIndex = class {
56296
56508
  if (!metadata || metadata.sessionId !== nativeSessionId)
56297
56509
  return null;
56298
56510
  const preferredCwds = [];
56299
- if (typeof metadata.cwd === "string" && path12.isAbsolute(metadata.cwd)) {
56511
+ if (typeof metadata.cwd === "string" && path11.isAbsolute(metadata.cwd)) {
56300
56512
  try {
56301
56513
  const messages = await this.#dependencies.readSessionMessages({
56302
56514
  cwd: metadata.cwd,
@@ -56311,7 +56523,7 @@ var ClaudeSessionImportIndex = class {
56311
56523
  continue;
56312
56524
  }
56313
56525
  const cwd = message.cwd;
56314
- if (path12.isAbsolute(cwd) && !preferredCwds.includes(cwd))
56526
+ if (path11.isAbsolute(cwd) && !preferredCwds.includes(cwd))
56315
56527
  preferredCwds.push(cwd);
56316
56528
  }
56317
56529
  } catch {
@@ -56327,13 +56539,13 @@ import { readFile as readFile6, rename as rename4, rm as rm5, stat as stat5, wri
56327
56539
 
56328
56540
  // dist/claude-transcript.js
56329
56541
  import os5 from "node:os";
56330
- import path13 from "node:path";
56542
+ import path12 from "node:path";
56331
56543
  import { readFile as readFile5, readdir as readdir3, stat as stat4 } from "node:fs/promises";
56332
56544
  function projectDirectoryName(cwd) {
56333
56545
  return cwd.replace(/[^A-Za-z0-9]/gu, "-");
56334
56546
  }
56335
56547
  function configDirectory(environment) {
56336
- return environment.CLAUDE_CONFIG_DIR ? path13.resolve(environment.CLAUDE_CONFIG_DIR) : path13.join(os5.homedir(), ".claude");
56548
+ return environment.CLAUDE_CONFIG_DIR ? path12.resolve(environment.CLAUDE_CONFIG_DIR) : path12.join(os5.homedir(), ".claude");
56337
56549
  }
56338
56550
  async function existingFile(file2) {
56339
56551
  try {
@@ -56343,8 +56555,8 @@ async function existingFile(file2) {
56343
56555
  }
56344
56556
  }
56345
56557
  async function findTranscriptFile(environment, cwd, relativeName) {
56346
- const projectsDirectory = path13.join(configDirectory(environment), "projects");
56347
- const expected = path13.join(projectsDirectory, projectDirectoryName(cwd), relativeName);
56558
+ const projectsDirectory = path12.join(configDirectory(environment), "projects");
56559
+ const expected = path12.join(projectsDirectory, projectDirectoryName(cwd), relativeName);
56348
56560
  if (await existingFile(expected))
56349
56561
  return expected;
56350
56562
  let projects;
@@ -56354,7 +56566,7 @@ async function findTranscriptFile(environment, cwd, relativeName) {
56354
56566
  return null;
56355
56567
  }
56356
56568
  for (const project2 of projects) {
56357
- const candidate = path13.join(projectsDirectory, project2, relativeName);
56569
+ const candidate = path12.join(projectsDirectory, project2, relativeName);
56358
56570
  if (await existingFile(candidate))
56359
56571
  return candidate;
56360
56572
  }
@@ -56391,7 +56603,7 @@ async function readClaudeTranscript(input) {
56391
56603
  return parseTranscriptRecords(await readFile5(transcript, "utf8"), input.sessionId);
56392
56604
  }
56393
56605
  async function readClaudeSubagentTranscript(input) {
56394
- const relativeName = path13.join(input.sessionId, "subagents", `agent-${input.nativeSubagentId}.jsonl`);
56606
+ const relativeName = path12.join(input.sessionId, "subagents", `agent-${input.nativeSubagentId}.jsonl`);
56395
56607
  const transcript = await findTranscriptFile(input.environment, input.cwd, relativeName);
56396
56608
  if (!transcript)
56397
56609
  return null;
@@ -56476,13 +56688,13 @@ async function remapForkedSessionReferences(input) {
56476
56688
  import { randomUUID as randomUUID5 } from "node:crypto";
56477
56689
  import { mkdir as mkdir4, readFile as readFile7, rename as rename5, rm as rm6, writeFile as writeFile3 } from "node:fs/promises";
56478
56690
  import os6 from "node:os";
56479
- import path14 from "node:path";
56691
+ import path13 from "node:path";
56480
56692
  var MILLION_CONTEXT_MODELS = [{ id: "claude-opus-5-5", aliases: ["claude-opus-5.5"] }];
56481
56693
  var MILLION_CONTEXT_MODEL_IDS = new Set(MILLION_CONTEXT_MODELS.flatMap((model2) => [model2.id, ...model2.aliases]));
56482
56694
  var MILLION_CONTEXT_SUFFIX = /\[1m\]$/iu;
56483
56695
  function claudeLongContextFile(environment) {
56484
- const root = environment.CODEXHOST_DATA_DIR ? path14.resolve(environment.CODEXHOST_DATA_DIR) : path14.join(os6.homedir(), ".codexhost");
56485
- return path14.join(root, "claude-code-long-context.json");
56696
+ const root = environment.CODEXHOST_DATA_DIR ? path13.resolve(environment.CODEXHOST_DATA_DIR) : path13.join(os6.homedir(), ".codexhost");
56697
+ return path13.join(root, "claude-code-long-context.json");
56486
56698
  }
56487
56699
  async function readClaudeLongContext(environment) {
56488
56700
  try {
@@ -56496,7 +56708,7 @@ async function readClaudeLongContext(environment) {
56496
56708
  }
56497
56709
  async function writeClaudeLongContext(environment, enabled) {
56498
56710
  const file2 = claudeLongContextFile(environment);
56499
- await mkdir4(path14.dirname(file2), { recursive: true, mode: 448 });
56711
+ await mkdir4(path13.dirname(file2), { recursive: true, mode: 448 });
56500
56712
  const temporary = `${file2}.${randomUUID5()}.tmp`;
56501
56713
  try {
56502
56714
  await writeFile3(temporary, `${JSON.stringify({ enabled })}
@@ -56520,7 +56732,7 @@ function claudeSessionModel(model2, enabled) {
56520
56732
  import { Buffer as Buffer2 } from "node:buffer";
56521
56733
  import { readFile as readFile8 } from "node:fs/promises";
56522
56734
  import os7 from "node:os";
56523
- import path15 from "node:path";
56735
+ import path14 from "node:path";
56524
56736
 
56525
56737
  // dist/thinking-options.js
56526
56738
  var option = (id2, label) => ({
@@ -56613,7 +56825,7 @@ function decodeClaudeModelRef(ref) {
56613
56825
  return value === "default" ? void 0 : value;
56614
56826
  }
56615
56827
  function resolveClaudeConfigDirectory(environment = process.env) {
56616
- return path15.resolve(environment.CLAUDE_CONFIG_DIR ?? path15.join(os7.homedir(), ".claude"));
56828
+ return path14.resolve(environment.CLAUDE_CONFIG_DIR ?? path14.join(os7.homedir(), ".claude"));
56617
56829
  }
56618
56830
  function parseModelPickerOptions(value) {
56619
56831
  if (!Array.isArray(value))
@@ -56655,7 +56867,7 @@ function parseClaudeModelPickerSettings(value) {
56655
56867
  };
56656
56868
  }
56657
56869
  async function readClaudeUserModelPicker(environment = process.env) {
56658
- const settingsPath = path15.join(resolveClaudeConfigDirectory(environment), "settings.json");
56870
+ const settingsPath = path14.join(resolveClaudeConfigDirectory(environment), "settings.json");
56659
56871
  let raw;
56660
56872
  try {
56661
56873
  raw = await readFile8(settingsPath, "utf8");
@@ -57001,7 +57213,7 @@ function projectClaudeAccountUsage(usage, account) {
57001
57213
 
57002
57214
  // dist/gateway-models.js
57003
57215
  import { readFile as readFile9 } from "node:fs/promises";
57004
- import path16 from "node:path";
57216
+ import path15 from "node:path";
57005
57217
  var GATEWAY_MODELS_TIMEOUT_MS = 3e3;
57006
57218
  var GATEWAY_MODELS_MAX_BYTES = 2 * 1024 * 1024;
57007
57219
  var OFFICIAL_ANTHROPIC_HOST = "api.anthropic.com";
@@ -57043,14 +57255,14 @@ function claudeConfigDirectory(environment) {
57043
57255
  if (configured)
57044
57256
  return configured;
57045
57257
  const home = trimmedEnv(environment, "HOME") ?? trimmedEnv(environment, "USERPROFILE");
57046
- return home ? path16.join(home, ".claude") : void 0;
57258
+ return home ? path15.join(home, ".claude") : void 0;
57047
57259
  }
57048
57260
  async function readClaudeUserSettingsEnv(environment) {
57049
57261
  const configDir = claudeConfigDirectory(environment);
57050
57262
  if (!configDir)
57051
57263
  return {};
57052
57264
  try {
57053
- const raw = await readFile9(path16.join(configDir, "settings.json"), "utf8");
57265
+ const raw = await readFile9(path15.join(configDir, "settings.json"), "utf8");
57054
57266
  const parsed = JSON.parse(raw);
57055
57267
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
57056
57268
  return {};
@@ -57183,7 +57395,7 @@ async function applyGatewayModelCatalog(snapshot, environment, dependencies = {}
57183
57395
 
57184
57396
  // dist/process-fence.js
57185
57397
  import { execFile as execFile3 } from "node:child_process";
57186
- import path17 from "node:path";
57398
+ import path16 from "node:path";
57187
57399
  import { setTimeout as setTimeout2 } from "node:timers/promises";
57188
57400
  import { promisify } from "node:util";
57189
57401
  var executeFile = promisify(execFile3);
@@ -57207,9 +57419,9 @@ async function closeClaudeProcessGroup(child, timeoutMs) {
57207
57419
  if (child.exitCode !== null || child.signalCode !== null)
57208
57420
  throw new Error("Claude process tree cannot be confirmed after its Windows root exited");
57209
57421
  const root = process.env.SystemRoot ?? process.env.SYSTEMROOT;
57210
- if (!root || !path17.win32.isAbsolute(root))
57422
+ if (!root || !path16.win32.isAbsolute(root))
57211
57423
  throw new Error("Windows SystemRoot is unavailable");
57212
- await executeFile(path17.win32.join(root, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], {
57424
+ await executeFile(path16.win32.join(root, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], {
57213
57425
  timeout: timeoutMs,
57214
57426
  windowsHide: true
57215
57427
  });
@@ -57234,12 +57446,21 @@ async function closeClaudeProcessGroup(child, timeoutMs) {
57234
57446
  throw new Error("Claude SDK process group did not exit");
57235
57447
  }
57236
57448
 
57449
+ // dist/transport.js
57450
+ var ClaudeSteerMissedTurnError = class extends Error {
57451
+ constructor() {
57452
+ super("Claude Code steer missed the active Turn");
57453
+ this.name = "ClaudeSteerMissedTurnError";
57454
+ }
57455
+ };
57456
+
57237
57457
  // dist/sdk-transport.js
57238
57458
  var CLIENT_APP = "codexhost-claude-code-adapter/0.0.0";
57239
57459
  var SESSION_ENTRYPOINT = "codexhost-sdk";
57240
57460
  var APPROVAL_TITLE_MAX_LENGTH = 120;
57241
57461
  var APPROVAL_DESCRIPTION_MAX_LENGTH = 500;
57242
57462
  var DEFAULT_ABORT_TIMEOUT_MS = 2e3;
57463
+ var DEFAULT_STEER_QUEUED_TIMEOUT_MS = 5e3;
57243
57464
  var WORKFLOW_AGENT_LABEL_LIMIT = 1e3;
57244
57465
  var INTERRUPT_TIMEOUT_MESSAGE = "Claude SDK interrupt timed out";
57245
57466
  var PushableInput = class {
@@ -57524,6 +57745,13 @@ var ClaudeSdkTransport = class {
57524
57745
  #queryFactory;
57525
57746
  #thinkingOptionId;
57526
57747
  #active = null;
57748
+ #steerQueuedTimeoutMs;
57749
+ #nativeSteer = false;
57750
+ /** Root tool calls of the requested Turn that have started and not yet returned a result. */
57751
+ #rootToolCalls = /* @__PURE__ */ new Set();
57752
+ #pendingSteers = /* @__PURE__ */ new Map();
57753
+ /** Written steers Claude has not yet drained into a native turn, by message ID. */
57754
+ #steerTakeovers = /* @__PURE__ */ new Map();
57527
57755
  #autonomous = null;
57528
57756
  #autonomousTurnHandler = null;
57529
57757
  #idleHandler = null;
@@ -57547,6 +57775,7 @@ var ClaudeSdkTransport = class {
57547
57775
  this.sessionId = options.sessionId;
57548
57776
  this.#cwd = options.cwd;
57549
57777
  this.#abortTimeoutMs = options.abortTimeoutMs ?? DEFAULT_ABORT_TIMEOUT_MS;
57778
+ this.#steerQueuedTimeoutMs = options.steerQueuedTimeoutMs ?? DEFAULT_STEER_QUEUED_TIMEOUT_MS;
57550
57779
  this.#closeTimeoutMs = options.closeTimeoutMs;
57551
57780
  this.#command = options.command;
57552
57781
  this.#environment = options.environment ?? process.env;
@@ -57601,7 +57830,8 @@ var ClaudeSdkTransport = class {
57601
57830
  thinking: thinking.enabled ? { type: "adaptive", display: "summarized" } : { type: "disabled" },
57602
57831
  ...thinking.effort ? { effort: thinking.effort } : {},
57603
57832
  pathToClaudeCodeExecutable: executable,
57604
- settingSources: ["user"],
57833
+ // Omitted settingSources loads user, project and local settings like the
57834
+ // Claude Code CLI, so project CLAUDE.md and .claude/skills apply.
57605
57835
  permissionMode: this.#permissionMode,
57606
57836
  ...this.#allowDangerouslySkipPermissions ? { allowDangerouslySkipPermissions: true } : {},
57607
57837
  canUseTool: (toolName, input, options) => this.#canUseTool(toolName, input, options),
@@ -57638,6 +57868,47 @@ var ClaudeSdkTransport = class {
57638
57868
  return null;
57639
57869
  return { commands: this.#slashCommands, skillNames: this.#skillNames };
57640
57870
  }
57871
+ supportsNativeSteer() {
57872
+ return this.#nativeSteer;
57873
+ }
57874
+ /**
57875
+ * `priority: "next"` joins after the current tool call, and a tool result is always followed by
57876
+ * another model request. So a steer written while a root tool call runs folds into this Turn;
57877
+ * one written while Claude streams its final text may instead run as the next Turn.
57878
+ *
57879
+ * A held Turn's continuation steers as well: while its idle stream is live, the pushed input
57880
+ * runs as that Turn's next Segment, and the background work the Turn waits on keeps running.
57881
+ */
57882
+ canSteerActiveTurn() {
57883
+ if (!this.#nativeSteer)
57884
+ return false;
57885
+ if (this.#active !== null)
57886
+ return this.#rootToolCalls.size > 0;
57887
+ return this.#idleLive && this.#idleHandler !== null;
57888
+ }
57889
+ #observeRootToolCalls(message) {
57890
+ if (!isRecord10(message) || message.parent_tool_use_id != null)
57891
+ return;
57892
+ if (message.type !== "assistant" && message.type !== "user")
57893
+ return;
57894
+ const body = message.message;
57895
+ if (!isRecord10(body) || !Array.isArray(body.content))
57896
+ return;
57897
+ for (const block of body.content) {
57898
+ if (!isRecord10(block))
57899
+ continue;
57900
+ if (message.type === "assistant" && block.type === "tool_use" && typeof block.id === "string") {
57901
+ this.#rootToolCalls.add(block.id);
57902
+ } else if (message.type === "user" && block.type === "tool_result" && typeof block.tool_use_id === "string") {
57903
+ this.#rootToolCalls.delete(block.tool_use_id);
57904
+ }
57905
+ }
57906
+ }
57907
+ #observeNativeCapabilities(message) {
57908
+ if (!isRecord10(message) || message.type !== "system" || message.subtype !== "init")
57909
+ return;
57910
+ this.#nativeSteer = Array.isArray(message.capabilities) && message.capabilities.includes("msg_lifecycle_v1");
57911
+ }
57641
57912
  #observeSlashCommands(message) {
57642
57913
  if (!isRecord10(message) || message.type !== "system")
57643
57914
  return;
@@ -57647,11 +57918,11 @@ var ClaudeSdkTransport = class {
57647
57918
  this.#slashCommands = parseClaudeSlashCommands(message.commands);
57648
57919
  }
57649
57920
  }
57650
- async getContextUsage() {
57921
+ async getContextUsage(detail = "full") {
57651
57922
  const activeQuery = this.#query;
57652
57923
  if (!this.#started || !activeQuery)
57653
57924
  return null;
57654
- return parseContextUsage(await activeQuery.getContextUsage());
57925
+ return parseContextUsage(await activeQuery.getContextUsage({ detail }));
57655
57926
  }
57656
57927
  getPermissionMode() {
57657
57928
  if (!this.#started || !this.#query)
@@ -57760,6 +58031,7 @@ var ClaudeSdkTransport = class {
57760
58031
  const unclaimed = this.#autonomous?.events ?? [];
57761
58032
  this.#autonomous = null;
57762
58033
  const promise2 = new Promise((resolve5, reject) => {
58034
+ this.#rootToolCalls.clear();
57763
58035
  this.#active = {
57764
58036
  accumulator: new ClaudeNativeTurnAccumulator(this.#provider ? { provider: this.#provider } : {}),
57765
58037
  onEvent,
@@ -57779,6 +58051,63 @@ var ClaudeSdkTransport = class {
57779
58051
  });
57780
58052
  return promise2;
57781
58053
  }
58054
+ /**
58055
+ * Claude accepts the input with `queued`; Claude Code 2.1.280 then emits `started` after the
58056
+ * current tool call, when `priority: "next"` joins the running Turn. Waiting for `started` would
58057
+ * hold the caller for a whole tool call.
58058
+ *
58059
+ * Once written, the input cannot be recalled: Claude delivers it in this Turn or runs it next.
58060
+ * The Turn ending first therefore does not reject it, and a missing `queued` receipt resolves
58061
+ * after a bounded wait so callers that serialize requests are never held indefinitely.
58062
+ */
58063
+ steer(text2, messageId, onTakeover) {
58064
+ if (this.#closePromise || !this.#started || !this.#query || !this.canSteerActiveTurn()) {
58065
+ return Promise.reject(new ClaudeSteerMissedTurnError());
58066
+ }
58067
+ const promise2 = new Promise((resolve5, reject) => {
58068
+ this.#pendingSteers.set(messageId, { resolve: resolve5, reject, timer: void 0 });
58069
+ });
58070
+ try {
58071
+ this.#input.push({
58072
+ type: "user",
58073
+ message: { role: "user", content: text2 },
58074
+ parent_tool_use_id: null,
58075
+ session_id: this.sessionId,
58076
+ uuid: messageId,
58077
+ origin: { kind: "human" },
58078
+ priority: "next"
58079
+ });
58080
+ } catch {
58081
+ this.#pendingSteers.delete(messageId);
58082
+ return Promise.reject(new ClaudeSteerMissedTurnError());
58083
+ }
58084
+ if (onTakeover)
58085
+ this.#steerTakeovers.set(messageId, onTakeover);
58086
+ const pending = this.#pendingSteers.get(messageId);
58087
+ if (pending) {
58088
+ pending.timer = setTimeout(() => {
58089
+ this.#acceptSteer(messageId);
58090
+ this.#takeOverSteer(messageId, false);
58091
+ }, this.#steerQueuedTimeoutMs);
58092
+ pending.timer.unref?.();
58093
+ }
58094
+ return promise2;
58095
+ }
58096
+ #acceptSteer(messageId) {
58097
+ const pending = this.#pendingSteers.get(messageId);
58098
+ if (!pending)
58099
+ return;
58100
+ this.#pendingSteers.delete(messageId);
58101
+ clearTimeout(pending.timer);
58102
+ pending.resolve();
58103
+ }
58104
+ #takeOverSteer(messageId, started) {
58105
+ const onTakeover = this.#steerTakeovers.get(messageId);
58106
+ if (!onTakeover)
58107
+ return;
58108
+ this.#steerTakeovers.delete(messageId);
58109
+ onTakeover(started);
58110
+ }
57782
58111
  respondToInteraction(response) {
57783
58112
  const pending = this.#interactions.get(response.requestId);
57784
58113
  if (!pending) {
@@ -57950,6 +58279,7 @@ var ClaudeSdkTransport = class {
57950
58279
  }
57951
58280
  }
57952
58281
  async #close() {
58282
+ this.#rejectPendingSteers();
57953
58283
  const failures = [];
57954
58284
  this.#closeInteractions("all", "cancelled");
57955
58285
  try {
@@ -58003,6 +58333,7 @@ var ClaudeSdkTransport = class {
58003
58333
  }
58004
58334
  this.#query = null;
58005
58335
  const active = this.#active;
58336
+ this.#rootToolCalls.clear();
58006
58337
  this.#active = null;
58007
58338
  this.#autonomous = null;
58008
58339
  this.#idleAccumulator = null;
@@ -58057,6 +58388,37 @@ var ClaudeSdkTransport = class {
58057
58388
  await delay(10);
58058
58389
  }
58059
58390
  }
58391
+ #rejectPendingSteers() {
58392
+ for (const messageId of [...this.#steerTakeovers.keys()]) {
58393
+ this.#takeOverSteer(messageId, false);
58394
+ }
58395
+ const pending = [...this.#pendingSteers.values()];
58396
+ this.#pendingSteers.clear();
58397
+ const error52 = new Error("Claude Code steer receipt was lost after input was written");
58398
+ for (const entry of pending) {
58399
+ clearTimeout(entry.timer);
58400
+ entry.reject(error52);
58401
+ }
58402
+ }
58403
+ /**
58404
+ * `queued` is Claude's acceptance of this message into the running Session. `started` is its
58405
+ * drain into a native turn, folded into the running one or run as the next; a terminal state
58406
+ * without `started` means no native turn takes it over.
58407
+ */
58408
+ #observeSteer(message) {
58409
+ if (this.#pendingSteers.size === 0 && this.#steerTakeovers.size === 0 || !isRecord10(message) || message.type !== "command_lifecycle") {
58410
+ return;
58411
+ }
58412
+ if (typeof message.command_uuid !== "string" || message.command_uuid.length === 0)
58413
+ return;
58414
+ if (message.state === "queued") {
58415
+ this.#acceptSteer(message.command_uuid);
58416
+ return;
58417
+ }
58418
+ if (["started", "completed", "cancelled", "discarded", "refused"].includes(String(message.state))) {
58419
+ this.#takeOverSteer(message.command_uuid, message.state === "started");
58420
+ }
58421
+ }
58060
58422
  #observeBackgroundTasks(message) {
58061
58423
  if (!isRecord10(message) || message.type !== "system")
58062
58424
  return;
@@ -58097,6 +58459,7 @@ var ClaudeSdkTransport = class {
58097
58459
  this.#observeBackgroundTasks(message);
58098
58460
  this.#observeWorkflowAgents(message);
58099
58461
  this.#observeSlashCommands(message);
58462
+ this.#observeNativeCapabilities(message);
58100
58463
  const permissionMode = permissionModeFromMessage(message);
58101
58464
  if (permissionMode && permissionMode !== this.#permissionMode) {
58102
58465
  this.#permissionMode = permissionMode;
@@ -58105,13 +58468,16 @@ var ClaudeSdkTransport = class {
58105
58468
  const planLimit = parseClaudePlanLimitEvent(message);
58106
58469
  if (planLimit)
58107
58470
  this.#onPlanLimit(planLimit);
58471
+ this.#observeSteer(message);
58108
58472
  const active = this.#active;
58109
58473
  if (active) {
58474
+ this.#observeRootToolCalls(message);
58110
58475
  const interpreted2 = active.accumulator.consume(message);
58111
58476
  for (const event of interpreted2.events)
58112
58477
  active.onEvent(event);
58113
58478
  if (interpreted2.terminal) {
58114
58479
  this.#closeInteractions("root", "superseded");
58480
+ this.#rootToolCalls.clear();
58115
58481
  this.#active = null;
58116
58482
  active.resolve(interpreted2.terminal);
58117
58483
  }
@@ -58164,11 +58530,13 @@ var ClaudeSdkTransport = class {
58164
58530
  throw new Error("Claude SDK Query ended unexpectedly");
58165
58531
  } catch (error52) {
58166
58532
  const active = this.#active;
58533
+ if (!this.#closePromise)
58534
+ this.#onFault(error52);
58167
58535
  this.#closeInteractions("all", "cancelled");
58536
+ this.#rejectPendingSteers();
58537
+ this.#rootToolCalls.clear();
58168
58538
  this.#active = null;
58169
58539
  active?.reject(error52);
58170
- if (!this.#closePromise)
58171
- this.#onFault(error52);
58172
58540
  }
58173
58541
  }
58174
58542
  #spawn(options) {
@@ -58469,7 +58837,7 @@ var ClaudeSubagentLifecycle = class {
58469
58837
  });
58470
58838
  const outcome = cancellationRequested ? { status: "cancelled", reason: "Cancelled by user" } : event.isError ? { status: "failed", error: subagentFailure() } : { status: "succeeded" };
58471
58839
  this.#emit({ type: "item.completed", turnId, snapshot: { item, outcome } });
58472
- return subagent;
58840
+ return { operation: active.item.operation, subagent };
58473
58841
  }
58474
58842
  finalize(turnId, outcome) {
58475
58843
  for (const [callId, active] of this.#delegations) {
@@ -58677,9 +59045,9 @@ function stringField(value, keys) {
58677
59045
  if (!isRecord11(value))
58678
59046
  return void 0;
58679
59047
  for (const key of keys) {
58680
- const field = value[key];
58681
- if (typeof field === "string" && field.length > 0)
58682
- return field;
59048
+ const field2 = value[key];
59049
+ if (typeof field2 === "string" && field2.length > 0)
59050
+ return field2;
58683
59051
  }
58684
59052
  return void 0;
58685
59053
  }
@@ -59356,7 +59724,7 @@ function projectClaudePlanLimitToCredits(planLimit) {
59356
59724
  }
59357
59725
  var ClaudeHarnessSession = class {
59358
59726
  harnessId = claudeCodeHarnessId2;
59359
- capabilities = {
59727
+ capabilities = /* @__PURE__ */ ((session) => ({
59360
59728
  configuration: {
59361
59729
  selectModel: true,
59362
59730
  selectThinkingOption: true,
@@ -59365,11 +59733,18 @@ var ClaudeHarnessSession = class {
59365
59733
  },
59366
59734
  input: { image: true },
59367
59735
  history: { fork: true, forkAcrossCwd: false, rollbackLastTurn: true },
59368
- subagents: { observe: true, readTranscript: true }
59369
- };
59736
+ subagents: { observe: true, readTranscript: true },
59737
+ // Read live: native delivery joins this Turn while a root tool call runs, or while a held
59738
+ // Turn's continuation waits on background work, on a CLI that confirms steers
59739
+ // (`msg_lifecycle_v1`). A Turn whose cancellation is in flight must not take more input;
59740
+ // every other case stops and restarts.
59741
+ get steer() {
59742
+ return session.#transport?.canSteerActiveTurn?.() === true && session.#active?.cancellationRequested !== true;
59743
+ }
59744
+ }))(this);
59370
59745
  commands;
59371
59746
  initialState;
59372
- initialUsage = null;
59747
+ initialUsage;
59373
59748
  outputs;
59374
59749
  get nativeSessionId() {
59375
59750
  return this.#sessionId;
@@ -59413,6 +59788,8 @@ var ClaudeHarnessSession = class {
59413
59788
  #hardCancelTask = null;
59414
59789
  #usageGeneration = 0;
59415
59790
  #latestUsage = null;
59791
+ #lastAssistantResponseAtUnix;
59792
+ #accountCreditsSupported;
59416
59793
  #minimumContextUsedTokens = null;
59417
59794
  #calibratedInputTokens = 0;
59418
59795
  #calibratedCachedInputTokens = 0;
@@ -59433,6 +59810,11 @@ var ClaudeHarnessSession = class {
59433
59810
  #continuationQuiescence = null;
59434
59811
  constructor(cwd, dependencies, closeTimeoutMs, onClosed, onPlanLimitObserved, options) {
59435
59812
  this.#cwd = cwd;
59813
+ this.#lastAssistantResponseAtUnix = options.usageHistory.lastResponseAtUnix;
59814
+ this.#accountCreditsSupported = options.accountCreditsSupported;
59815
+ const composerIndicators = claudePromptCacheIndicators(this.#accountCreditsSupported, this.#lastAssistantResponseAtUnix);
59816
+ this.initialUsage = composerIndicators.length ? { composerIndicators } : null;
59817
+ this.#latestUsage = this.initialUsage;
59436
59818
  this.#pendingSessions = options.pendingSessions;
59437
59819
  const environment = options.environment;
59438
59820
  this.#createTransport = environment ? (input) => dependencies.createTransport({ ...input, environment }) : dependencies.createTransport;
@@ -59588,6 +59970,8 @@ var ClaudeHarnessSession = class {
59588
59970
  }
59589
59971
  if (command.type === "turn.cancel")
59590
59972
  return this.#cancel(command);
59973
+ if (command.type === "turn.steer")
59974
+ return this.#steer(command);
59591
59975
  if (command.type === "interaction.respond")
59592
59976
  return this.#respond(command);
59593
59977
  if (command.type === "model.select")
@@ -59699,6 +60083,7 @@ var ClaudeHarnessSession = class {
59699
60083
  nativeTurnKey,
59700
60084
  nativeTurnRef: null,
59701
60085
  cancellationRequested: false,
60086
+ steersAwaitingNative: /* @__PURE__ */ new Set(),
59702
60087
  usageRequestIds: /* @__PURE__ */ new Set(),
59703
60088
  estimatedInputTokens: 0,
59704
60089
  estimatedCachedInputTokens: 0,
@@ -59738,6 +60123,52 @@ var ClaudeHarnessSession = class {
59738
60123
  }
59739
60124
  return { ok: true, value: { turnId: command.turnId } };
59740
60125
  }
60126
+ async #steer(command) {
60127
+ const active = this.#active;
60128
+ if (!active || active.command.turnId !== command.turnId) {
60129
+ return { ok: false, error: invalidState("Claude Code steer target is not the active Turn") };
60130
+ }
60131
+ if (active.cancellationRequested) {
60132
+ return { ok: false, error: invalidState("Claude Code steer target is being cancelled") };
60133
+ }
60134
+ const text2 = command.input.map((input) => input.text).join("\n");
60135
+ if (text2.length === 0) {
60136
+ return {
60137
+ ok: false,
60138
+ error: {
60139
+ code: "invalidRequest",
60140
+ message: "Claude Code steer text must not be empty",
60141
+ retryable: false
60142
+ }
60143
+ };
60144
+ }
60145
+ const transport = this.#transport;
60146
+ if (!transport) {
60147
+ return { ok: false, error: invalidState("Claude Code steer missed the active Turn") };
60148
+ }
60149
+ if (transport.supportsNativeSteer?.() !== true) {
60150
+ return {
60151
+ ok: false,
60152
+ error: {
60153
+ code: "unsupported",
60154
+ message: "This Claude Code version does not confirm native steering",
60155
+ retryable: false
60156
+ }
60157
+ };
60158
+ }
60159
+ const messageId = this.#randomUUID();
60160
+ active.steersAwaitingNative.add(messageId);
60161
+ try {
60162
+ await transport.steer(text2, messageId, (started) => this.#takeOverSteer(active, messageId, started));
60163
+ } catch (error52) {
60164
+ if (error52 instanceof ClaudeSteerMissedTurnError) {
60165
+ this.#takeOverSteer(active, messageId, false);
60166
+ return { ok: false, error: invalidState("Claude Code steer missed the active Turn") };
60167
+ }
60168
+ throw error52;
60169
+ }
60170
+ return { ok: true, value: { accepted: true } };
60171
+ }
59741
60172
  /** Built-ins plus the live commands and skills of the started native Session. */
59742
60173
  #liveCommandCatalog() {
59743
60174
  return claudeLiveCommandCatalog(claudeCommandCatalog, this.#transport?.slashCommands?.() ?? null);
@@ -59834,6 +60265,7 @@ var ClaudeHarnessSession = class {
59834
60265
  nativeTurnKey,
59835
60266
  nativeTurnRef: null,
59836
60267
  cancellationRequested: false,
60268
+ steersAwaitingNative: /* @__PURE__ */ new Set(),
59837
60269
  usageRequestIds: /* @__PURE__ */ new Set(),
59838
60270
  estimatedInputTokens: 0,
59839
60271
  estimatedCachedInputTokens: 0,
@@ -59909,15 +60341,16 @@ var ClaudeHarnessSession = class {
59909
60341
  this.#contextUsageCooldownUntilMs = 0;
59910
60342
  this.#requestContextUsage(transport, void 0, CONTEXT_USAGE_RETRY_DELAYS_MS);
59911
60343
  }
59912
- refreshUsage() {
60344
+ async refreshUsage() {
60345
+ await this.#contextRefreshInFlight;
59913
60346
  if (this.#phase !== "open" || !this.#transport)
59914
- return Promise.resolve();
60347
+ return;
59915
60348
  const now = Date.now();
59916
60349
  if (now < this.#contextUsageFreshUntilMs || now < this.#contextUsageCooldownUntilMs) {
59917
- return Promise.resolve();
60350
+ return;
59918
60351
  }
59919
60352
  this.#requestContextUsage(this.#transport, this.#active?.command.turnId, CONTEXT_USAGE_RETRY_DELAYS_MS);
59920
- return this.#contextRefreshInFlight ?? Promise.resolve();
60353
+ await this.#contextRefreshInFlight;
59921
60354
  }
59922
60355
  blocksRollback(sessionId) {
59923
60356
  return this.#sessionId === sessionId && (this.#phase !== "open" || this.#active !== null || this.#acceptingTurn || this.#configurationTask !== null || this.#readingHistory);
@@ -60224,7 +60657,7 @@ var ClaudeHarnessSession = class {
60224
60657
  active.cancellationRequested = true;
60225
60658
  const transport = this.#transport;
60226
60659
  const taskIds = this.#backgroundTaskIds(active);
60227
- if (transport && (taskIds.length > 0 || active.held && (active.rootSegmentActive || this.#occupancy.awaitingContinuation))) {
60660
+ if (transport && (taskIds.length > 0 || active.held && (active.rootSegmentActive || this.#occupancy.awaitingContinuation || active.steersAwaitingNative.size > 0))) {
60228
60661
  await this.#cancelBackgroundWork(active, transport, taskIds);
60229
60662
  return { ok: true, value: { cancellationRequested: true } };
60230
60663
  }
@@ -60299,6 +60732,11 @@ var ClaudeHarnessSession = class {
60299
60732
  return;
60300
60733
  if (cancellation.stopping || cancellation.interrupting || active.rootSegmentActive)
60301
60734
  return;
60735
+ if (active.steersAwaitingNative.size > 0) {
60736
+ this.#armCancelEscalation(active);
60737
+ return;
60738
+ }
60739
+ this.#clearCancelEscalation();
60302
60740
  this.#clearCancellationQuiet(cancellation);
60303
60741
  const quiet = setTimeout(() => {
60304
60742
  cancellation.quiet = null;
@@ -60538,6 +60976,10 @@ var ClaudeHarnessSession = class {
60538
60976
  this.#completeReasoning(active, event.messageId, { status: "succeeded" });
60539
60977
  return;
60540
60978
  case "message.completed": {
60979
+ if (!event.localCommand) {
60980
+ this.#lastAssistantResponseAtUnix = Math.floor(Date.now() / 1e3);
60981
+ this.publishAccountCreditsSupport(this.#accountCreditsSupported);
60982
+ }
60541
60983
  this.#observeRootOutput(active);
60542
60984
  if (event.lastRequestUsage) {
60543
60985
  this.#requestUsageBoundary += 1;
@@ -60575,10 +61017,7 @@ var ClaudeHarnessSession = class {
60575
61017
  }
60576
61018
  this.#completeAgentItem(active, { status: "succeeded" }, false);
60577
61019
  active.subagents.start(active.command.turnId, event);
60578
- if (event.operation === "send") {
60579
- if (event.nativeSubagentId)
60580
- this.#occupancy.occupyAgent(event.nativeSubagentId);
60581
- } else if (event.background) {
61020
+ if (event.operation === "spawn" && event.background) {
60582
61021
  this.#occupancy.occupySpawn(event.callId, event.nativeSubagentId);
60583
61022
  }
60584
61023
  return;
@@ -60597,7 +61036,13 @@ var ClaudeHarnessSession = class {
60597
61036
  }
60598
61037
  return;
60599
61038
  case "subagent.completed": {
60600
- const subagent = active.subagents.complete(active.command.turnId, event, active.cancellationRequested);
61039
+ const { operation, subagent } = active.subagents.complete(active.command.turnId, event, active.cancellationRequested);
61040
+ if (operation === "send") {
61041
+ if (subagent.status === "running" && subagent.nativeSubagentId) {
61042
+ this.#occupancy.occupyAgent(subagent.nativeSubagentId);
61043
+ }
61044
+ return;
61045
+ }
60601
61046
  if (subagent.status === "running") {
60602
61047
  this.#occupancy.occupySpawn(event.callId, subagent.nativeSubagentId);
60603
61048
  return;
@@ -60927,6 +61372,7 @@ var ClaudeHarnessSession = class {
60927
61372
  const active = {
60928
61373
  command: { type: "turn.start", turnId, input: [] },
60929
61374
  compactionItem: null,
61375
+ steersAwaitingNative: /* @__PURE__ */ new Set(),
60930
61376
  item,
60931
61377
  agentMessageOrdinal: 1,
60932
61378
  assistantMessageId: null,
@@ -61068,7 +61514,7 @@ var ClaudeHarnessSession = class {
61068
61514
  this.#finishFailed(active, transportFailure(result.kind));
61069
61515
  }
61070
61516
  }
61071
- #requestContextUsage(transport, turnId, retryDelaysMs) {
61517
+ #requestContextUsage(transport, turnId, retryDelaysMs, detail = "full") {
61072
61518
  if (this.#phase !== "open" || this.#transport !== transport)
61073
61519
  return;
61074
61520
  if (this.#contextRefreshInFlight)
@@ -61077,7 +61523,8 @@ var ClaudeHarnessSession = class {
61077
61523
  transport,
61078
61524
  ...turnId !== void 0 ? { turnId } : {},
61079
61525
  generation: this.#usageGeneration,
61080
- retryDelaysMs
61526
+ retryDelaysMs,
61527
+ detail
61081
61528
  };
61082
61529
  this.#contextRefreshInFlight = this.#drainContextUsage();
61083
61530
  }
@@ -61103,14 +61550,16 @@ var ClaudeHarnessSession = class {
61103
61550
  return;
61104
61551
  }
61105
61552
  try {
61106
- const context = await request.transport.getContextUsage();
61553
+ const context = await request.transport.getContextUsage(request.detail);
61107
61554
  if (this.#phase !== "open" || this.#transport !== request.transport || this.#usageGeneration !== request.generation || this.#contextRefreshPending !== null) {
61108
61555
  return;
61109
61556
  }
61110
61557
  if (context === null)
61111
61558
  continue;
61112
- this.#contextUsageFreshUntilMs = Date.now() + CONTEXT_USAGE_TTL_MS;
61113
- this.#contextUsageCooldownUntilMs = 0;
61559
+ if (request.detail === "full") {
61560
+ this.#contextUsageFreshUntilMs = Date.now() + CONTEXT_USAGE_TTL_MS;
61561
+ this.#contextUsageCooldownUntilMs = 0;
61562
+ }
61114
61563
  const delta = {
61115
61564
  contextUsedTokens: Math.max(context.usedTokens, this.#minimumContextUsedTokens ?? 0),
61116
61565
  contextWindowTokens: context.maxTokens
@@ -61125,7 +61574,7 @@ var ClaudeHarnessSession = class {
61125
61574
  } catch {
61126
61575
  }
61127
61576
  }
61128
- if (this.#phase === "open" && this.#transport === request.transport && this.#usageGeneration === request.generation) {
61577
+ if (request.detail === "full" && this.#phase === "open" && this.#transport === request.transport && this.#usageGeneration === request.generation) {
61129
61578
  this.#contextUsageCooldownUntilMs = Date.now() + CONTEXT_USAGE_FAILURE_COOLDOWN_MS;
61130
61579
  }
61131
61580
  }
@@ -61270,6 +61719,9 @@ var ClaudeHarnessSession = class {
61270
61719
  if (cacheHitRatePercent !== void 0)
61271
61720
  delta.cacheHitRatePercent = cacheHitRatePercent;
61272
61721
  }
61722
+ if (this.#transport && this.#minimumContextUsedTokens !== null && event.modelUsage?.some(({ contextWindowTokens }) => contextWindowTokens !== void 0)) {
61723
+ this.#requestContextUsage(this.#transport, active.command.turnId, [0], "summary");
61724
+ }
61273
61725
  this.#mergeAndPublishUsage(delta, active.command.turnId);
61274
61726
  }
61275
61727
  /**
@@ -61284,6 +61736,15 @@ var ClaudeHarnessSession = class {
61284
61736
  if (effective)
61285
61737
  this.publishPlanLimit(effective);
61286
61738
  }
61739
+ publishAccountCreditsSupport(supported) {
61740
+ if (this.#phase !== "open")
61741
+ return;
61742
+ this.#accountCreditsSupported = supported;
61743
+ const composerIndicators = claudePromptCacheIndicators(supported, this.#lastAssistantResponseAtUnix);
61744
+ if (composerIndicators[0]?.expiresAtUnix === this.#latestUsage?.composerIndicators?.[0]?.expiresAtUnix)
61745
+ return;
61746
+ this.#mergeAndPublishUsage({ composerIndicators }, this.#active?.command.turnId);
61747
+ }
61287
61748
  publishPlanLimit(planLimit) {
61288
61749
  if (this.#phase !== "open")
61289
61750
  return;
@@ -61341,7 +61802,7 @@ var ClaudeHarnessSession = class {
61341
61802
  this.#clearContinuationQuiescence();
61342
61803
  const quiescence = setTimeout(() => {
61343
61804
  this.#continuationQuiescence = null;
61344
- if (this.#active !== active || !active.held || active.rootSegmentActive || this.#phase !== "open") {
61805
+ if (this.#active !== active || !active.held || active.rootSegmentActive || active.steersAwaitingNative.size > 0 || this.#phase !== "open") {
61345
61806
  return;
61346
61807
  }
61347
61808
  this.#occupancy.releaseContinuations();
@@ -61362,6 +61823,30 @@ var ClaudeHarnessSession = class {
61362
61823
  active.rootSegmentActive = true;
61363
61824
  this.#clearContinuationQuiescence();
61364
61825
  }
61826
+ /**
61827
+ * A drained steer runs in a native turn whose result still reaches this Turn, folded into the
61828
+ * running Root Segment or as the held Turn's next one. A steer that ends without one releases
61829
+ * its keep-open, so a Turn held only for it settles as if the steer had never been written.
61830
+ */
61831
+ #takeOverSteer(active, messageId, started) {
61832
+ if (!active.steersAwaitingNative.delete(messageId) || this.#active !== active)
61833
+ return;
61834
+ if (started) {
61835
+ this.#handleTurnEvent(active, { type: "segment.started" });
61836
+ return;
61837
+ }
61838
+ if (active.cancellation) {
61839
+ this.#settleCancellation(active);
61840
+ return;
61841
+ }
61842
+ if (!active.held || active.rootSegmentActive || active.steersAwaitingNative.size > 0 || this.#phase !== "open") {
61843
+ return;
61844
+ }
61845
+ if (this.#occupancy.awaitingContinuation)
61846
+ this.#armContinuationQuiescence(active);
61847
+ else if (!this.#occupancy.unsettled)
61848
+ this.#finish(active, { status: "succeeded" });
61849
+ }
61365
61850
  #finish(active, outcome) {
61366
61851
  if (this.#active !== active)
61367
61852
  return;
@@ -61372,7 +61857,7 @@ var ClaudeHarnessSession = class {
61372
61857
  active.cancellation = null;
61373
61858
  }
61374
61859
  this.#clearContinuationQuiescence();
61375
- const hold = outcome.status === "succeeded" && !active.cancellationRequested && this.#occupancy.unsettled;
61860
+ const hold = outcome.status === "succeeded" && !active.cancellationRequested && (this.#occupancy.unsettled || active.steersAwaitingNative.size > 0);
61376
61861
  this.#closeActiveInteractions(active, outcome.status === "succeeded" ? "superseded" : "cancelled", hold);
61377
61862
  const itemOutcome2 = outcome;
61378
61863
  if (active.compactionItem)
@@ -61560,6 +62045,7 @@ var ClaudeCodeAdapter = class {
61560
62045
  #closePromise = null;
61561
62046
  #latestPlanLimit = null;
61562
62047
  #accountInspection = null;
62048
+ #accountCreditsSupported = false;
61563
62049
  constructor(options = {}, dependencies) {
61564
62050
  const environment = options.environment ?? process.env;
61565
62051
  this.#environment = environment;
@@ -61653,7 +62139,7 @@ var ClaudeCodeAdapter = class {
61653
62139
  error: invalidState("Claude Code Adapter is closing")
61654
62140
  };
61655
62141
  }
61656
- const cwd = path18.resolve(input.cwd ?? process.cwd());
62142
+ const cwd = path17.resolve(input.cwd ?? process.cwd());
61657
62143
  if (!input.refresh) {
61658
62144
  const cached2 = this.#inspectionCache.get(cwd);
61659
62145
  if (cached2)
@@ -61686,12 +62172,20 @@ var ClaudeCodeAdapter = class {
61686
62172
  return this.#accountInspection;
61687
62173
  }
61688
62174
  async #readAccount() {
62175
+ const planLimitAtStart = this.#latestPlanLimit;
61689
62176
  let inspector;
61690
62177
  try {
61691
62178
  this.#dependencies.inspectInstallation();
61692
62179
  inspector = this.#dependencies.createInspector({ cwd: process.cwd() });
61693
62180
  this.#inspectors.add(inspector);
61694
- return await inspector.inspectAccount?.() ?? null;
62181
+ const account = await inspector.inspectAccount?.() ?? null;
62182
+ if (this.#latestPlanLimit === planLimitAtStart) {
62183
+ this.#accountCreditsSupported = account?.credits !== void 0;
62184
+ for (const session of this.#sessions) {
62185
+ session.publishAccountCreditsSupport(this.#accountCreditsSupported);
62186
+ }
62187
+ }
62188
+ return account;
61695
62189
  } catch {
61696
62190
  return null;
61697
62191
  } finally {
@@ -61850,7 +62344,7 @@ var ClaudeCodeAdapter = class {
61850
62344
  }
61851
62345
  requestedPermissionModeId = CLAUDE_DEFAULT_PERMISSION_MODE_ID;
61852
62346
  }
61853
- const cwd = path18.resolve(input.cwd);
62347
+ const cwd = path17.resolve(input.cwd);
61854
62348
  if (input.kind === "rollbackLastTurn") {
61855
62349
  for (const source of this.#sessions) {
61856
62350
  const ready = await source.prepareRollback(input.sourceRef.nativeSessionId);
@@ -61935,6 +62429,7 @@ var ClaudeCodeAdapter = class {
61935
62429
  ...durableRef ? { nativeRef: durableRef } : {},
61936
62430
  sessionId,
61937
62431
  usageHistory,
62432
+ accountCreditsSupported: this.#accountCreditsSupported,
61938
62433
  ...requestedModel ? { requestedModel } : {},
61939
62434
  longContextEnabled: () => readClaudeLongContext(this.#environment),
61940
62435
  requestedPermissionModeId,
@@ -61955,7 +62450,13 @@ var ClaudeCodeAdapter = class {
61955
62450
  return { requests: [], complete: true };
61956
62451
  try {
61957
62452
  const messages = await this.#dependencies.readSessionMessages({ cwd, sessionId });
61958
- return messages === null ? { requests: [], complete: false } : claudeUsageHistory(messages);
62453
+ if (messages === null)
62454
+ return { requests: [], complete: false };
62455
+ const lastResponseAtUnix = lastClaudeAssistantResponseUnix(messages);
62456
+ return {
62457
+ ...claudeUsageHistory(messages),
62458
+ ...lastResponseAtUnix !== void 0 ? { lastResponseAtUnix } : {}
62459
+ };
61959
62460
  } catch {
61960
62461
  return { requests: [], complete: false };
61961
62462
  }
@@ -61967,9 +62468,17 @@ var ClaudeCodeAdapter = class {
61967
62468
  next.fiveHour = planLimit.fiveHour;
61968
62469
  if (planLimit.sevenDay)
61969
62470
  next.sevenDay = planLimit.sevenDay;
62471
+ try {
62472
+ if (!accountCreditsSnapshotSchema.safeParse(projectClaudePlanLimitToCredits(next)).success)
62473
+ return null;
62474
+ } catch {
62475
+ return null;
62476
+ }
61970
62477
  this.#latestPlanLimit = next.fiveHour || next.sevenDay ? next : null;
61971
62478
  if (this.#latestPlanLimit) {
62479
+ this.#accountCreditsSupported = true;
61972
62480
  for (const session of this.#sessions) {
62481
+ session.publishAccountCreditsSupport(true);
61973
62482
  if (session !== origin)
61974
62483
  session.publishPlanLimit(this.#latestPlanLimit);
61975
62484
  }
@@ -62004,7 +62513,7 @@ var ClaudeCodeAdapter = class {
62004
62513
  // dist/installation.js
62005
62514
  import { readFile as readFile10, realpath as realpath5 } from "node:fs/promises";
62006
62515
  import { homedir as homedir2 } from "node:os";
62007
- import path19 from "node:path";
62516
+ import path18 from "node:path";
62008
62517
  async function readSettings(file2) {
62009
62518
  const text2 = await readFile10(file2, "utf8").catch((error52) => {
62010
62519
  if (error52.code === "ENOENT")
@@ -62025,9 +62534,9 @@ function createClaudeInstallation(environment, command) {
62025
62534
  ...command ? { command } : {}
62026
62535
  });
62027
62536
  const home = environment.HOME ?? environment.USERPROFILE ?? homedir2();
62028
- const config2 = environment.CLAUDE_CONFIG_DIR ? path19.resolve(home, environment.CLAUDE_CONFIG_DIR) : path19.join(home, ".claude");
62029
- const managedFile = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : process.platform === "win32" ? path19.join(environment.ProgramFiles ?? "C:\\Program Files", "ClaudeCode", "managed-settings.json") : "/etc/claude-code/managed-settings.json";
62030
- const user = await readSettings(path19.join(config2, "settings.json"));
62537
+ const config2 = environment.CLAUDE_CONFIG_DIR ? path18.resolve(home, environment.CLAUDE_CONFIG_DIR) : path18.join(home, ".claude");
62538
+ const managedFile = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : process.platform === "win32" ? path18.join(environment.ProgramFiles ?? "C:\\Program Files", "ClaudeCode", "managed-settings.json") : "/etc/claude-code/managed-settings.json";
62539
+ const user = await readSettings(path18.join(config2, "settings.json"));
62031
62540
  const managed = await readSettings(managedFile);
62032
62541
  const settings = { ...user, ...managed, env: { ...user.env, ...managed.env } };
62033
62542
  const env = { ...environment, ...settings.env };
@@ -62040,10 +62549,10 @@ function createClaudeInstallation(environment, command) {
62040
62549
  throw new Error("Unknown Claude release channel");
62041
62550
  const latestVersion = installationVersion(await fetchInstallationText(`https://downloads.claude.ai/claude-code-releases/${channel}`));
62042
62551
  const npm = await npmInstallation(executable, ["@anthropic-ai/claude-code"], env);
62043
- const launcher = path19.join(home, ".local", "bin", process.platform === "win32" ? "claude.exe" : "claude");
62552
+ const launcher = path18.join(home, ".local", "bin", process.platform === "win32" ? "claude.exe" : "claude");
62044
62553
  const selected = await realpath5(executable);
62045
- const versions = path19.join(home, ".local", "share", "claude", "versions") + path19.sep;
62046
- const native = path19.resolve(executable) === launcher && (selected.startsWith(versions) || process.platform === "win32" && selected === launcher);
62554
+ const versions = path18.join(home, ".local", "share", "claude", "versions") + path18.sep;
62555
+ const native = path18.resolve(executable) === launcher && (selected.startsWith(versions) || process.platform === "win32" && selected === launcher);
62047
62556
  const blocked = !!env.DISABLE_UPDATES && env.DISABLE_UPDATES !== "0" || !!settings.minimumVersion && newerInstallationVersion(latestVersion, installationVersion(settings.minimumVersion)) || !!settings.requiredMaximumVersion && newerInstallationVersion(installationVersion(settings.requiredMaximumVersion), latestVersion);
62048
62557
  const canUpdate = !blocked && (npm?.canUpdate ?? native);
62049
62558
  update = async () => {
@@ -62074,7 +62583,7 @@ function createClaudeInstallation(environment, command) {
62074
62583
  }
62075
62584
 
62076
62585
  // dist/user-shell-environment.js
62077
- import path20 from "node:path";
62586
+ import path19 from "node:path";
62078
62587
  import { execFile as execFile4 } from "node:child_process";
62079
62588
  var ENVIRONMENT_MARKER = Buffer.from("\0CODEXHOST_USER_SHELL_ENV_V1\0");
62080
62589
  var ENVIRONMENT_COMMAND = "printf '\\0CODEXHOST_USER_SHELL_ENV_V1\\0'; /usr/bin/env -0";
@@ -62117,7 +62626,7 @@ async function withUserShellEnvironment(environment, dependencies) {
62117
62626
  if (platform === "win32" || !environment.HOME)
62118
62627
  return environment;
62119
62628
  const shell = environment.SHELL?.trim() || defaultShell(platform);
62120
- if (!shell || !SUPPORTED_SHELLS.has(path20.basename(shell)))
62629
+ if (!shell || !SUPPORTED_SHELLS.has(path19.basename(shell)))
62121
62630
  return environment;
62122
62631
  const cacheKey = `${platform}\0${shell}\0${environment.HOME}`;
62123
62632
  const cached2 = dependencies ? void 0 : shellEnvironmentCache.get(cacheKey);
@@ -62155,6 +62664,7 @@ async function createHarnessAdapter(context) {
62155
62664
  const environment = await withUserShellEnvironment({ ...context.environment });
62156
62665
  if (context.platform === "darwin" && context.managedRemoteHost) {
62157
62666
  return new BrokeredHarnessAdapter({
62667
+ sessionImport: true,
62158
62668
  forwardDelegationEnvironment: true,
62159
62669
  commandCatalog: claudeCommandCatalog,
62160
62670
  liveCommandCatalog: true,