@codexhost/cli-darwin-x64 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -776,10 +776,10 @@ function mergeDefs(...defs) {
776
776
  function cloneDef(schema) {
777
777
  return mergeDefs(schema._zod.def);
778
778
  }
779
- function getElementAtPath(obj, path14) {
780
- if (!path14)
779
+ function getElementAtPath(obj, path17) {
780
+ if (!path17)
781
781
  return obj;
782
- return path14.reduce((acc, key) => acc?.[key], obj);
782
+ return path17.reduce((acc, key) => acc?.[key], obj);
783
783
  }
784
784
  function promiseAllObject(promisesObj) {
785
785
  const keys = Object.keys(promisesObj);
@@ -1188,11 +1188,11 @@ function explicitlyAborted(x2, startIndex = 0) {
1188
1188
  }
1189
1189
  return false;
1190
1190
  }
1191
- function prefixIssues(path14, issues) {
1191
+ function prefixIssues(path17, issues) {
1192
1192
  return issues.map((iss) => {
1193
1193
  var _a4;
1194
1194
  (_a4 = iss).path ?? (_a4.path = []);
1195
- iss.path.unshift(path14);
1195
+ iss.path.unshift(path17);
1196
1196
  return iss;
1197
1197
  });
1198
1198
  }
@@ -1339,16 +1339,16 @@ function flattenError(error52, mapper = (issue2) => issue2.message) {
1339
1339
  }
1340
1340
  function formatError(error52, mapper = (issue2) => issue2.message) {
1341
1341
  const fieldErrors = { _errors: [] };
1342
- const processError = (error53, path14 = []) => {
1342
+ const processError = (error53, path17 = []) => {
1343
1343
  for (const issue2 of error53.issues) {
1344
1344
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1345
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1345
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
1346
1346
  } else if (issue2.code === "invalid_key") {
1347
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1347
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1348
1348
  } else if (issue2.code === "invalid_element") {
1349
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1349
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1350
1350
  } else {
1351
- const fullpath = [...path14, ...issue2.path];
1351
+ const fullpath = [...path17, ...issue2.path];
1352
1352
  if (fullpath.length === 0) {
1353
1353
  fieldErrors._errors.push(mapper(issue2));
1354
1354
  } else {
@@ -1375,17 +1375,17 @@ function formatError(error52, mapper = (issue2) => issue2.message) {
1375
1375
  }
1376
1376
  function treeifyError(error52, mapper = (issue2) => issue2.message) {
1377
1377
  const result = { errors: [] };
1378
- const processError = (error53, path14 = []) => {
1378
+ const processError = (error53, path17 = []) => {
1379
1379
  var _a4, _b2;
1380
1380
  for (const issue2 of error53.issues) {
1381
1381
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1382
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1382
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
1383
1383
  } else if (issue2.code === "invalid_key") {
1384
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1384
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1385
1385
  } else if (issue2.code === "invalid_element") {
1386
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1386
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1387
1387
  } else {
1388
- const fullpath = [...path14, ...issue2.path];
1388
+ const fullpath = [...path17, ...issue2.path];
1389
1389
  if (fullpath.length === 0) {
1390
1390
  result.errors.push(mapper(issue2));
1391
1391
  continue;
@@ -1417,8 +1417,8 @@ function treeifyError(error52, mapper = (issue2) => issue2.message) {
1417
1417
  }
1418
1418
  function toDotPath(_path) {
1419
1419
  const segs = [];
1420
- const path14 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1421
- for (const seg of path14) {
1420
+ const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1421
+ for (const seg of path17) {
1422
1422
  if (typeof seg === "number")
1423
1423
  segs.push(`[${seg}]`);
1424
1424
  else if (typeof seg === "symbol")
@@ -14110,13 +14110,13 @@ function resolveRef(ref, ctx) {
14110
14110
  if (!ref.startsWith("#")) {
14111
14111
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14112
14112
  }
14113
- const path14 = ref.slice(1).split("/").filter(Boolean);
14114
- if (path14.length === 0) {
14113
+ const path17 = ref.slice(1).split("/").filter(Boolean);
14114
+ if (path17.length === 0) {
14115
14115
  return ctx.rootSchema;
14116
14116
  }
14117
14117
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14118
- if (path14[0] === defsKey) {
14119
- const key = path14[1];
14118
+ if (path17[0] === defsKey) {
14119
+ const key = path17[1];
14120
14120
  if (!key || !ctx.defs[key]) {
14121
14121
  throw new Error(`Reference not found: ${ref}`);
14122
14122
  }
@@ -14579,6 +14579,55 @@ var credentialImportsParamsSchema = external_exports.object({
14579
14579
  request: credentialImportsRequestSchema
14580
14580
  }).strict();
14581
14581
 
14582
+ // ../../shared-contracts/dist/harness-display-settings.js
14583
+ var harnessDisplayEntriesSchema = external_exports.array(external_exports.strictObject({
14584
+ agent: external_exports.string().min(1).max(128),
14585
+ section: external_exports.enum(["main", "more", "auto"])
14586
+ })).max(256).refine((entries) => new Set(entries.map((entry) => entry.agent)).size === entries.length, "Duplicate Harness IDs");
14587
+ var harnessDisplaySettingsSchema = external_exports.strictObject({
14588
+ entries: harnessDisplayEntriesSchema.nullable()
14589
+ });
14590
+ var harnessDisplayGetSchema = external_exports.strictObject({});
14591
+ var harnessDisplaySetSchema = external_exports.strictObject({
14592
+ entries: harnessDisplayEntriesSchema,
14593
+ /** Import legacy Desktop preferences only if no shared settings exist yet. */
14594
+ initializeOnly: external_exports.boolean().optional()
14595
+ });
14596
+
14597
+ // ../../shared-contracts/dist/console.js
14598
+ var consoleAnnouncementSchema = external_exports.strictObject({
14599
+ title: external_exports.string().trim().min(1).max(200),
14600
+ type: external_exports.enum(["info", "warning", "danger"]),
14601
+ body: external_exports.string().trim().min(1).max(16 * 1024)
14602
+ });
14603
+ var consoleOpenParamsSchema = external_exports.strictObject({});
14604
+ var consoleOpenResultSchema = external_exports.strictObject({
14605
+ /** The console address. */
14606
+ url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
14607
+ });
14608
+ var CONSOLE_HOST_METHODS = Object.freeze([
14609
+ "codexhost/harness/plugins/list",
14610
+ "codexhost/harness/display-settings/get",
14611
+ "codexhost/harness/display-settings/set",
14612
+ "codexhost/harness/inspect",
14613
+ "codexhost/harness/launch-settings/get",
14614
+ "codexhost/harness/launch-settings/set",
14615
+ "codexhost/harness/web-ui/open",
14616
+ "codexhost/harness/accounts/sources",
14617
+ "codexhost/harness/accounts/list",
14618
+ "codexhost/harness/accounts/inspect",
14619
+ "codexhost/harness/credential-imports",
14620
+ "codexhost/harness/session-import/sources",
14621
+ "codexhost/harness/session-import/list",
14622
+ "codexhost/harness/session-import/import",
14623
+ "codexhost/account/list",
14624
+ "codexhost/account/refresh",
14625
+ "codexhost/account/usage/inspect",
14626
+ "codexhost/update/check",
14627
+ "codexhost/update/start",
14628
+ "codexhost/update/status"
14629
+ ]);
14630
+
14582
14631
  // ../../shared-contracts/dist/version.js
14583
14632
  var WORKSPACE_CONTRACT_VERSION = 1;
14584
14633
 
@@ -14632,6 +14681,12 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
14632
14681
  var hostItemIdSchema = opaqueIdSchema.brand();
14633
14682
  var hostInteractionIdSchema = opaqueIdSchema.brand();
14634
14683
 
14684
+ // ../../shared-contracts/dist/manual-compaction.js
14685
+ var threadManualCompactionStartedSchema = external_exports.strictObject({
14686
+ threadId: hostThreadIdSchema,
14687
+ turnId: hostTurnIdSchema
14688
+ });
14689
+
14635
14690
  // ../../shared-contracts/dist/thread-usage.js
14636
14691
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
14637
14692
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -14692,6 +14747,10 @@ var threadUsageSnapshotSchema = external_exports.object({
14692
14747
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
14693
14748
  var accountCreditsProductUsageSchema = external_exports.object({
14694
14749
  product: external_exports.string().min(1),
14750
+ used: external_exports.number().finite().nonnegative().optional(),
14751
+ // Zero is a real empty cap, not an absent field.
14752
+ limit: external_exports.number().finite().nonnegative().optional(),
14753
+ unit: external_exports.string().min(1).max(32).optional(),
14695
14754
  usagePercent: usagePercentSchema,
14696
14755
  resetsAt: external_exports.string().min(1).optional()
14697
14756
  }).strict();
@@ -14701,6 +14760,10 @@ var accountResetCreditsSchema = external_exports.object({
14701
14760
  expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(32).optional()
14702
14761
  }).strict();
14703
14762
  var accountCreditsSnapshotSchema = external_exports.object({
14763
+ used: external_exports.number().finite().nonnegative().optional(),
14764
+ // Zero is a real empty cap, not an absent field.
14765
+ limit: external_exports.number().finite().nonnegative().optional(),
14766
+ unit: external_exports.string().min(1).max(32).optional(),
14704
14767
  /** Native label when the primary limit is scoped to a model or product group. */
14705
14768
  label: external_exports.string().min(1).optional(),
14706
14769
  usedPercent: usagePercentSchema,
@@ -14720,12 +14783,27 @@ var threadUsageInspectionSchema = external_exports.object({
14720
14783
  }).strict();
14721
14784
 
14722
14785
  // ../../shared-contracts/dist/harness-accounts.js
14723
- var harnessAccountSnapshotSchema = external_exports.object({
14786
+ var accountBalanceSnapshotSchema = external_exports.object({
14787
+ amount: external_exports.number().finite().nonnegative(),
14788
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
14789
+ currency: external_exports.string().trim().min(1).max(8),
14790
+ /** Native label when the Harness exposes several Billing Sources. */
14791
+ label: external_exports.string().trim().min(1).max(128).optional()
14792
+ }).strict();
14793
+ var harnessAccountSnapshotObject = external_exports.object({
14724
14794
  email: external_exports.string().trim().min(1).max(320).optional(),
14725
14795
  label: external_exports.string().trim().min(1).max(256).optional(),
14726
14796
  plan: external_exports.string().trim().min(1).max(128).optional(),
14727
- credits: accountCreditsSnapshotSchema
14797
+ credits: accountCreditsSnapshotSchema.optional(),
14798
+ balance: accountBalanceSnapshotSchema.optional()
14728
14799
  }).strict();
14800
+ function requireReportedQuota(schema) {
14801
+ return schema.refine((value) => {
14802
+ const reported = value;
14803
+ return reported.credits !== void 0 || reported.balance !== void 0;
14804
+ }, { message: "Account must report either credits or a balance" });
14805
+ }
14806
+ var harnessAccountSnapshotSchema = requireReportedQuota(harnessAccountSnapshotObject);
14729
14807
  var harnessAccountIdentityShape = {
14730
14808
  harnessId: harnessIdSchema,
14731
14809
  harnessName: external_exports.string().trim().min(1).max(128)
@@ -14736,11 +14814,13 @@ var harnessAccountSourceListResultSchema = external_exports.object({ sources: ex
14736
14814
  var harnessAccountInspectParamsSchema = external_exports.object({ harnessId: harnessIdSchema, refresh: external_exports.boolean().optional() }).strict();
14737
14815
  var harnessAccountInspectResultSchema = external_exports.object({
14738
14816
  ...harnessAccountIdentityShape,
14739
- account: harnessAccountSnapshotSchema.nullable()
14817
+ account: harnessAccountSnapshotSchema.nullable(),
14818
+ /** Every Billing Source from one Harness; `account` remains the first for older clients. */
14819
+ accounts: external_exports.array(harnessAccountSnapshotSchema).max(8).optional()
14740
14820
  }).strict();
14741
14821
  var harnessAccountListParamsSchema = external_exports.object({ refresh: external_exports.boolean().optional() }).strict();
14742
14822
  var harnessAccountListResultSchema = external_exports.object({
14743
- accounts: external_exports.array(harnessAccountSnapshotSchema.extend(harnessAccountIdentityShape)).max(128)
14823
+ accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
14744
14824
  }).strict();
14745
14825
 
14746
14826
  // ../../shared-contracts/dist/json-value.js
@@ -14878,6 +14958,8 @@ var harnessModelSchema = external_exports.object({
14878
14958
  ref: harnessModelRefSchema,
14879
14959
  label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
14880
14960
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
14961
+ /** Optional opaque selection for this same Model with priority processing enabled. */
14962
+ fastModel: harnessModelRefSchema.optional(),
14881
14963
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
14882
14964
  }).strict();
14883
14965
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
@@ -14910,6 +14992,16 @@ var harnessModelCatalogSchema = external_exports.object({
14910
14992
  });
14911
14993
  }
14912
14994
  refs.add(model.ref.id);
14995
+ if (model.fastModel) {
14996
+ if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
14997
+ context.addIssue({
14998
+ code: "custom",
14999
+ message: "Fast Model refs must be distinct and unique",
15000
+ path: ["models", index, "fastModel"]
15001
+ });
15002
+ }
15003
+ refs.add(model.fastModel.id);
15004
+ }
14913
15005
  const supportedThinkingIds = /* @__PURE__ */ new Set();
14914
15006
  for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
14915
15007
  if (supportedThinkingIds.has(optionId)) {
@@ -15029,11 +15121,13 @@ var threadThinkingSelectParamsSchema = external_exports.object({
15029
15121
  thinkingOptionId: harnessThinkingOptionIdSchema
15030
15122
  }).strict();
15031
15123
  var threadInspectionParamsSchema = external_exports.object({
15032
- threadId: hostThreadIdSchema
15124
+ threadId: hostThreadIdSchema,
15125
+ includeReferenceCapability: external_exports.boolean().optional()
15033
15126
  }).strict();
15034
15127
  var codexThreadInspectionSchema = external_exports.object({
15035
15128
  owner: external_exports.literal("codex"),
15036
- locked: external_exports.literal(true)
15129
+ locked: external_exports.literal(true),
15130
+ supportsThreadReferences: external_exports.literal(true).optional()
15037
15131
  }).strict();
15038
15132
  var externalThreadInspectionSchema = external_exports.object({
15039
15133
  owner: external_exports.literal("external"),
@@ -15159,6 +15253,19 @@ var harnessLaunchSettingsSchema = external_exports.object({
15159
15253
  restartRequired: external_exports.boolean()
15160
15254
  }).strict();
15161
15255
 
15256
+ // ../../shared-contracts/dist/harness-installation.js
15257
+ var harnessInstallationParamsSchema = external_exports.object({
15258
+ harnessId: harnessIdSchema,
15259
+ action: external_exports.enum(["check", "update"])
15260
+ }).strict();
15261
+ var harnessInstallationStateSchema = external_exports.object({
15262
+ currentVersion: external_exports.string().min(1).max(128),
15263
+ latestVersion: external_exports.string().min(1).max(128),
15264
+ updateAvailable: external_exports.boolean(),
15265
+ canUpdate: external_exports.boolean(),
15266
+ message: external_exports.string().max(2048).optional()
15267
+ }).strict();
15268
+
15162
15269
  // ../../shared-contracts/dist/codex-accounts.js
15163
15270
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
15164
15271
  var nonBlankTextSchema3 = external_exports.string().trim().min(1);
@@ -15901,6 +16008,7 @@ function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId
15901
16008
  var cwdSchema = external_exports.string().min(1).max(16384);
15902
16009
  var brokerEnvironmentSchema = external_exports.object({
15903
16010
  CODEXHOST_CLI_PATH: external_exports.string().max(16384).optional(),
16011
+ CODEXHOST_CLI_NODE_PATH: external_exports.string().max(16384).optional(),
15904
16012
  CODEXHOST_RUNTIME_ENDPOINT: external_exports.string().max(16384).optional(),
15905
16013
  CODEXHOST_RUNTIME_TOKEN: external_exports.string().max(16384).optional(),
15906
16014
  CODEXHOST_THREAD_ID: external_exports.string().max(256).optional()
@@ -16055,6 +16163,7 @@ var eventKeys = /* @__PURE__ */ new Map([
16055
16163
  ["item.started", /* @__PURE__ */ new Set(["type", "turnId", "item"])],
16056
16164
  ["item.updated", /* @__PURE__ */ new Set(["type", "turnId", "itemId", "update"])],
16057
16165
  ["item.completed", /* @__PURE__ */ new Set(["type", "turnId", "snapshot"])],
16166
+ ["item.detached", /* @__PURE__ */ new Set(["type", "turnId", "itemId"])],
16058
16167
  ["interaction.closed", /* @__PURE__ */ new Set(["type", "interactionId", "turnId", "reason"])],
16059
16168
  ["turn.completed", /* @__PURE__ */ new Set(["type", "turnId", "nativeTurnRef", "outcome"])],
16060
16169
  ["session.faulted", /* @__PURE__ */ new Set(["type", "error"])]
@@ -16623,6 +16732,7 @@ var BrokeredHarnessAdapter = class {
16623
16732
  if (this.#forwardEnvironment && input.environment) {
16624
16733
  const allowed2 = [
16625
16734
  "CODEXHOST_CLI_PATH",
16735
+ "CODEXHOST_CLI_NODE_PATH",
16626
16736
  "CODEXHOST_RUNTIME_ENDPOINT",
16627
16737
  "CODEXHOST_RUNTIME_TOKEN",
16628
16738
  "CODEXHOST_THREAD_ID"
@@ -16680,7 +16790,7 @@ var BrokeredHarnessAdapter = class {
16680
16790
 
16681
16791
  // dist/claude-code-adapter.js
16682
16792
  import { randomUUID as randomUUID3 } from "node:crypto";
16683
- import path12 from "node:path";
16793
+ import path14 from "node:path";
16684
16794
 
16685
16795
  // ../../../node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs
16686
16796
  import { createRequire as DW } from "node:module";
@@ -42583,7 +42693,7 @@ var ClaudeSessionImportIndex = class {
42583
42693
  };
42584
42694
 
42585
42695
  // dist/command.js
42586
- import path5 from "node:path";
42696
+ import path7 from "node:path";
42587
42697
 
42588
42698
  // ../../harness-discovery/dist/environment.js
42589
42699
  import fs from "node:fs";
@@ -42631,12 +42741,28 @@ function newestFirst(names) {
42631
42741
  return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
42632
42742
  }
42633
42743
 
42634
- // ../../harness-discovery/dist/node-runtime.js
42744
+ // ../../harness-discovery/dist/invocation.js
42635
42745
  import path4 from "node:path";
42746
+ function commandInvocation(command, arguments_, environment, platform = process.platform) {
42747
+ const extension = path4.win32.extname(command).toLowerCase();
42748
+ if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
42749
+ return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
42750
+ }
42751
+ const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
42752
+ const commandLine = [command, ...arguments_].map(quote).join(" ");
42753
+ return {
42754
+ command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
42755
+ arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
42756
+ windowsVerbatimArguments: true
42757
+ };
42758
+ }
42759
+
42760
+ // ../../harness-discovery/dist/node-runtime.js
42761
+ import path5 from "node:path";
42636
42762
  function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
42637
42763
  const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
42638
42764
  const delimiter = platform === "win32" ? ";" : ":";
42639
- const runtimeDirectory = path4.dirname(runtimeExecutable);
42765
+ const runtimeDirectory = path5.dirname(runtimeExecutable);
42640
42766
  const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
42641
42767
  const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
42642
42768
  if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
@@ -42808,6 +42934,195 @@ function resolveHarnessExecutable(spec, input, dependencies = {}) {
42808
42934
  return void 0;
42809
42935
  }
42810
42936
 
42937
+ // ../../harness-discovery/dist/installation.js
42938
+ import { execFile } from "node:child_process";
42939
+ import { homedir } from "node:os";
42940
+ function runInstallationCommand(command, args, environment, timeout = 3e4) {
42941
+ const env = withNodeRuntimeOnPath(environment);
42942
+ const invocation = /\.[cm]?js$/i.test(command) ? commandInvocation(process.execPath, [command, ...args], env) : commandInvocation(command, args, env);
42943
+ return new Promise((resolve2, reject) => {
42944
+ const child = execFile(invocation.command, invocation.arguments, {
42945
+ env,
42946
+ cwd: env.HOME ?? env.USERPROFILE ?? homedir(),
42947
+ encoding: "utf8",
42948
+ timeout,
42949
+ killSignal: "SIGKILL",
42950
+ maxBuffer: 1024 * 1024,
42951
+ windowsHide: true,
42952
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
42953
+ }, (error52, stdout, stderr) => {
42954
+ if (error52)
42955
+ reject(new Error(error52.killed ? "Harness command timed out" : "Harness command failed; check the native installation and retry"));
42956
+ else
42957
+ resolve2((stdout || stderr).trim());
42958
+ });
42959
+ child.stdin?.end();
42960
+ });
42961
+ }
42962
+ function installationVersion(value) {
42963
+ if (typeof value !== "string" || !/^v?\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.trim()))
42964
+ throw new Error("Harness returned an invalid version");
42965
+ return value.trim().replace(/^v/, "");
42966
+ }
42967
+ function versionFromOutput(output) {
42968
+ return installationVersion(output.match(/\b\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?\b/)?.[0]);
42969
+ }
42970
+ function newerInstallationVersion(current, latest) {
42971
+ const a = installationVersion(current).replace(/\+.*/, "");
42972
+ const b = installationVersion(latest).replace(/\+.*/, "");
42973
+ const coreA = a.replace(/-.*/, "").split(".").map(BigInt);
42974
+ const coreB = b.replace(/-.*/, "").split(".").map(BigInt);
42975
+ for (let i = 0; i < Math.max(coreA.length, coreB.length); i++) {
42976
+ if ((coreA[i] ?? 0n) !== (coreB[i] ?? 0n))
42977
+ return (coreB[i] ?? 0n) > (coreA[i] ?? 0n);
42978
+ }
42979
+ const preA = a.includes("-") ? a.slice(a.indexOf("-") + 1).split(".") : [];
42980
+ const preB = b.includes("-") ? b.slice(b.indexOf("-") + 1).split(".") : [];
42981
+ if (!preA.length || !preB.length)
42982
+ return !!preA.length && !preB.length;
42983
+ for (let i = 0; i < Math.max(preA.length, preB.length); i++) {
42984
+ const x2 = preA[i];
42985
+ const y = preB[i];
42986
+ if (x2 === y)
42987
+ continue;
42988
+ if (x2 === void 0 || y === void 0)
42989
+ return x2 === void 0;
42990
+ const numericX = /^\d+$/.test(x2);
42991
+ const numericY = /^\d+$/.test(y);
42992
+ if (numericX && numericY) {
42993
+ if (BigInt(x2) === BigInt(y))
42994
+ continue;
42995
+ return BigInt(y) > BigInt(x2);
42996
+ }
42997
+ if (numericX !== numericY)
42998
+ return numericX;
42999
+ return y > x2;
43000
+ }
43001
+ return false;
43002
+ }
43003
+ function createInstallationManager(options) {
43004
+ let checking;
43005
+ let updating;
43006
+ const check2 = () => checking ??= options.check().finally(() => {
43007
+ checking = void 0;
43008
+ });
43009
+ return (action) => {
43010
+ if (updating)
43011
+ return updating;
43012
+ if (action === "check")
43013
+ return check2();
43014
+ updating = (async () => {
43015
+ const before = await check2();
43016
+ if (!before.updateAvailable)
43017
+ return before;
43018
+ if (!before.canUpdate)
43019
+ throw new Error(before.message ?? "This installation cannot be updated automatically");
43020
+ await options.update(before);
43021
+ const after = await check2();
43022
+ if (after.currentVersion === before.currentVersion)
43023
+ throw new Error("The Harness version did not change; check the native updater and retry");
43024
+ return after;
43025
+ })().finally(() => {
43026
+ updating = void 0;
43027
+ });
43028
+ return updating;
43029
+ };
43030
+ }
43031
+ async function fetchInstallationText(url2) {
43032
+ const request = async () => {
43033
+ const response = await fetch(url2, { signal: AbortSignal.timeout(15e3) });
43034
+ if (!response.ok)
43035
+ throw new Error("Could not check the latest Harness version");
43036
+ return response.text();
43037
+ };
43038
+ try {
43039
+ return await request();
43040
+ } catch (error52) {
43041
+ if (error52 instanceof DOMException && (error52.name === "AbortError" || error52.name === "TimeoutError"))
43042
+ throw error52;
43043
+ return request();
43044
+ }
43045
+ }
43046
+
43047
+ // ../../harness-discovery/dist/npm-installation.js
43048
+ import { readFile as readFile2, realpath as realpath2 } from "node:fs/promises";
43049
+ import path6 from "node:path";
43050
+ function referencesNpmBin(shim, name, bin) {
43051
+ if (bin.includes(".."))
43052
+ return false;
43053
+ const target = `node_modules/${name}/${bin.replace(/^\.\//, "")}`.toLowerCase();
43054
+ const text = shim.replaceAll("\\", "/").toLowerCase();
43055
+ return text.includes(`%dp0%/${target}"`) || text.includes(`%~dp0/${target}"`);
43056
+ }
43057
+ async function npmInstallation(command, packages, environment) {
43058
+ let selected = await realpath2(command);
43059
+ if (process.platform === "win32" && /\.(cmd|bat)$/i.test(selected)) {
43060
+ const shim = (await readFile2(selected, "utf8")).replaceAll("\\", "/");
43061
+ const root = path6.dirname(selected);
43062
+ for (const name of packages) {
43063
+ const directory2 = path6.join(root, "node_modules", ...name.split("/"));
43064
+ const metadata = await readFile2(path6.join(directory2, "package.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
43065
+ const bins = typeof metadata?.bin === "string" ? [metadata.bin] : Object.values(metadata?.bin ?? {});
43066
+ const bin = bins.find((entry) => referencesNpmBin(shim, name, entry));
43067
+ if (bin) {
43068
+ selected = await realpath2(path6.join(directory2, bin));
43069
+ break;
43070
+ }
43071
+ }
43072
+ }
43073
+ let directory = path6.dirname(selected);
43074
+ for (let depth = 0; depth < 8; depth++) {
43075
+ const metadata = await readFile2(path6.join(directory, "package.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
43076
+ if (metadata?.name && packages.includes(metadata.name)) {
43077
+ const name = metadata.name;
43078
+ const currentVersion = installationVersion(metadata.version);
43079
+ const segments = name.split("/");
43080
+ let modules = directory;
43081
+ for (let index = 0; index < segments.length; index++)
43082
+ modules = path6.dirname(modules);
43083
+ const prefix = process.platform === "win32" ? path6.dirname(modules) : path6.dirname(path6.dirname(modules));
43084
+ const globalRoot = process.platform === "win32" ? path6.join(prefix, "node_modules") : path6.join(prefix, "lib", "node_modules");
43085
+ const env = withNodeRuntimeOnPath(environment);
43086
+ const npm = resolveHarnessExecutable({ id: "npm", command: "npm", installRoots: { posix: [], windows: [] } }, { environment: env });
43087
+ let globalInstall = modules === globalRoot;
43088
+ if (process.platform === "win32") {
43089
+ const project = (await Promise.all(["package.json", "package-lock.json", "npm-shrinkwrap.json"].map((file2) => readFile2(path6.join(prefix, file2), "utf8").then(() => true, (error52) => error52.code !== "ENOENT")))).some(Boolean);
43090
+ const bins = typeof metadata.bin === "string" ? { [name.split("/").at(-1) ?? name]: metadata.bin } : metadata.bin ?? {};
43091
+ const launchers = await Promise.all(Object.entries(bins).map(async ([bin, entry]) => {
43092
+ if (path6.basename(bin) !== bin || entry.includes(".."))
43093
+ return false;
43094
+ const target = await realpath2(path6.join(directory, entry)).catch(() => "");
43095
+ if (target.toLowerCase() !== selected.toLowerCase())
43096
+ return false;
43097
+ const shim = await readFile2(path6.join(prefix, `${bin}.cmd`), "utf8").catch(() => "");
43098
+ return referencesNpmBin(shim, name, entry);
43099
+ }));
43100
+ globalInstall = globalInstall && !project && launchers.some(Boolean);
43101
+ }
43102
+ const canUpdate = globalInstall && !!npm;
43103
+ return {
43104
+ prefix,
43105
+ currentVersion,
43106
+ canUpdate,
43107
+ latest: async () => {
43108
+ const data = JSON.parse(await fetchInstallationText(`https://registry.npmjs.org/${encodeURIComponent(name)}/latest`));
43109
+ return installationVersion(data.version);
43110
+ },
43111
+ update: async (version2) => {
43112
+ if (!canUpdate || !npm)
43113
+ throw new Error("Use the original package manager to update this installation");
43114
+ await runInstallationCommand(npm.executable, ["install", "--global", "--prefix", prefix, `${name}@${installationVersion(version2)}`], env, 3e5);
43115
+ }
43116
+ };
43117
+ }
43118
+ const parent = path6.dirname(directory);
43119
+ if (parent === directory)
43120
+ break;
43121
+ directory = parent;
43122
+ }
43123
+ return null;
43124
+ }
43125
+
42811
43126
  // dist/command.js
42812
43127
  var ClaudeCodeExecutableError = class extends Error {
42813
43128
  code = "CLAUDE_NOT_FOUND";
@@ -42854,14 +43169,14 @@ function resolveClaudeCodeExecutable(input = {}, dependencies = {}) {
42854
43169
  }, dependencies);
42855
43170
  if (!resolution)
42856
43171
  throw new ClaudeCodeExecutableError("Claude Code is not installed");
42857
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path5.resolve(resolution.executable);
43172
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path7.resolve(resolution.executable);
42858
43173
  }
42859
43174
 
42860
43175
  // dist/pending-session.js
42861
43176
  import { randomUUID as randomUUID2 } from "node:crypto";
42862
- import { mkdir, open, readFile as readFile2, rename, rm as rm2, stat as stat2, unlink } from "node:fs/promises";
43177
+ import { mkdir, open, readFile as readFile3, rename, rm as rm2, stat as stat2, unlink } from "node:fs/promises";
42863
43178
  import os4 from "node:os";
42864
- import path6 from "node:path";
43179
+ import path8 from "node:path";
42865
43180
  var reservationSchema = external_exports.strictObject({
42866
43181
  version: external_exports.literal(1),
42867
43182
  sessionId: external_exports.uuid(),
@@ -42874,13 +43189,13 @@ function isPendingClaudeSession(ref) {
42874
43189
  var ClaudePendingSessions = class {
42875
43190
  #directory;
42876
43191
  constructor(environment) {
42877
- this.#directory = path6.join(path6.resolve(environment.CLAUDE_CONFIG_DIR ?? path6.join(os4.homedir(), ".claude")), "codexhost", "pending-sessions");
43192
+ this.#directory = path8.join(path8.resolve(environment.CLAUDE_CONFIG_DIR ?? path8.join(os4.homedir(), ".claude")), "codexhost", "pending-sessions");
42878
43193
  }
42879
43194
  #path(ref, cwd) {
42880
- if (ref.harnessId !== "claude-code" || !external_exports.uuid().safeParse(ref.nativeSessionId).success || !external_exports.strictObject({ pendingSession: external_exports.literal(1) }).safeParse(ref.locator).success || !path6.isAbsolute(cwd)) {
43195
+ if (ref.harnessId !== "claude-code" || !external_exports.uuid().safeParse(ref.nativeSessionId).success || !external_exports.strictObject({ pendingSession: external_exports.literal(1) }).safeParse(ref.locator).success || !path8.isAbsolute(cwd)) {
42881
43196
  throw new Error("Claude Code pending Session identity is invalid");
42882
43197
  }
42883
- return path6.join(this.#directory, ref.nativeSessionId);
43198
+ return path8.join(this.#directory, ref.nativeSessionId);
42884
43199
  }
42885
43200
  async create(cwd, configuration) {
42886
43201
  const ref = nativeSessionRefSchema.parse({
@@ -42899,7 +43214,7 @@ var ClaudePendingSessions = class {
42899
43214
  await mkdir(this.#directory, { recursive: true, mode: 448 });
42900
43215
  await mkdir(directory, { mode: 448 });
42901
43216
  try {
42902
- const file2 = await open(path6.join(directory, "session.json"), "wx", 384);
43217
+ const file2 = await open(path8.join(directory, "session.json"), "wx", 384);
42903
43218
  try {
42904
43219
  await file2.writeFile(JSON.stringify(reservation));
42905
43220
  await file2.sync();
@@ -42916,13 +43231,13 @@ var ClaudePendingSessions = class {
42916
43231
  }
42917
43232
  async read(ref, cwd) {
42918
43233
  const directory = this.#path(ref, cwd);
42919
- const reservation = reservationSchema.parse(JSON.parse(await readFile2(path6.join(directory, "session.json"), "utf8")));
43234
+ const reservation = reservationSchema.parse(JSON.parse(await readFile3(path8.join(directory, "session.json"), "utf8")));
42920
43235
  if (reservation.sessionId !== ref.nativeSessionId || reservation.cwd !== cwd) {
42921
43236
  throw new Error("Claude Code pending Session does not belong to this working directory");
42922
43237
  }
42923
43238
  let started = false;
42924
43239
  try {
42925
- const claim = await stat2(path6.join(directory, "started"));
43240
+ const claim = await stat2(path8.join(directory, "started"));
42926
43241
  if (!claim.isFile())
42927
43242
  throw new Error("Claude Code pending Session claim is invalid");
42928
43243
  started = true;
@@ -42935,7 +43250,7 @@ var ClaudePendingSessions = class {
42935
43250
  async saveConfiguration(ref, cwd, configuration) {
42936
43251
  await this.read(ref, cwd);
42937
43252
  const directory = this.#path(ref, cwd);
42938
- const temporary = path6.join(directory, `${randomUUID2()}.tmp`);
43253
+ const temporary = path8.join(directory, `${randomUUID2()}.tmp`);
42939
43254
  try {
42940
43255
  const file2 = await open(temporary, "wx", 384);
42941
43256
  try {
@@ -42949,7 +43264,7 @@ var ClaudePendingSessions = class {
42949
43264
  } finally {
42950
43265
  await file2.close();
42951
43266
  }
42952
- await rename(temporary, path6.join(directory, "session.json"));
43267
+ await rename(temporary, path8.join(directory, "session.json"));
42953
43268
  await this.#sync(directory);
42954
43269
  } finally {
42955
43270
  await rm2(temporary, { force: true });
@@ -42967,7 +43282,7 @@ var ClaudePendingSessions = class {
42967
43282
  }
42968
43283
  async claim(ref, cwd) {
42969
43284
  await this.read(ref, cwd);
42970
- const claim = await open(path6.join(this.#path(ref, cwd), "started"), "wx", 384);
43285
+ const claim = await open(path8.join(this.#path(ref, cwd), "started"), "wx", 384);
42971
43286
  try {
42972
43287
  await claim.sync();
42973
43288
  } finally {
@@ -42977,7 +43292,7 @@ var ClaudePendingSessions = class {
42977
43292
  }
42978
43293
  /** Only the claim owner may release, after proven close and before submitting any native input. */
42979
43294
  async release(ref, cwd) {
42980
- await unlink(path6.join(this.#path(ref, cwd), "started"));
43295
+ await unlink(path8.join(this.#path(ref, cwd), "started"));
42981
43296
  await this.#sync(this.#path(ref, cwd));
42982
43297
  }
42983
43298
  async discard(ref, cwd) {
@@ -42986,338 +43301,1099 @@ var ClaudePendingSessions = class {
42986
43301
  };
42987
43302
 
42988
43303
  // dist/claude-fork.js
42989
- import path7 from "node:path";
43304
+ import path10 from "node:path";
42990
43305
  import { isDeepStrictEqual } from "node:util";
42991
43306
 
42992
- // dist/item-identity.js
42993
- function claudeTranscriptItemId(nativeTurnKey, kind, ordinal) {
42994
- return hostItemIdSchema.parse(`claude-item-v2-${nativeTurnKey}-${kind}-${ordinal}`);
42995
- }
42996
-
42997
- // dist/claude-history.js
42998
- var claudeCodeHarnessId = harnessIdSchema.parse("claude-code");
43307
+ // dist/file-change.js
43308
+ import path9 from "node:path";
43309
+ var hunkSchema = external_exports.object({
43310
+ oldStart: external_exports.number().int().nonnegative(),
43311
+ oldLines: external_exports.number().int().nonnegative(),
43312
+ newStart: external_exports.number().int().nonnegative(),
43313
+ newLines: external_exports.number().int().nonnegative(),
43314
+ lines: external_exports.array(external_exports.string())
43315
+ }).strict();
42999
43316
  function isRecord3(value) {
43000
43317
  return typeof value === "object" && value !== null && !Array.isArray(value);
43001
43318
  }
43002
- function textParts(value) {
43003
- if (typeof value === "string")
43004
- return value.length > 0 ? [value] : [];
43005
- if (!Array.isArray(value))
43006
- return [];
43007
- return value.flatMap((part) => isRecord3(part) && part.type === "text" && typeof part.text === "string" ? [part.text] : []);
43319
+ function validNativePath(value) {
43320
+ return typeof value === "string" && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
43008
43321
  }
43009
- function thinkingParts(value) {
43010
- if (!Array.isArray(value))
43011
- return [];
43012
- return value.flatMap((part) => isRecord3(part) && part.type === "thinking" && typeof part.thinking === "string" ? [part.thinking] : []);
43322
+ function countLines(lines, prefixes) {
43323
+ return lines.filter((line) => line.length > 0 && prefixes.has(line[0])).length;
43013
43324
  }
43014
- var localCommandRecordPattern = /^\s*<(local-command-(?:stdout|caveat))>[\s\S]*<\/\1>\s*$/u;
43015
- var taskNotificationRecordPattern = /^\s*<task-notification>[\s\S]*<\/task-notification>\s*$/u;
43016
- var commandEnvelopePattern = /^\s*(?:<(command-(?:message|name|args))>[\s\S]*?<\/\1>\s*)+$/u;
43017
- var controlCommandNamePattern = /<command-name>\s*\/(?:model|compact)\s*<\/command-name>/u;
43018
- var recapCommandNamePattern = /<command-name>\s*\/recap\s*<\/command-name>/u;
43019
- var initCommandNamePattern = /<command-name>\s*\/init\s*<\/command-name>/u;
43020
- var localCommandStdoutPattern = /^\s*<local-command-stdout>([\s\S]*)<\/local-command-stdout>\s*$/u;
43021
- function isLocalCommandRecord(text) {
43022
- return localCommandRecordPattern.test(text);
43325
+ function validHunk(value) {
43326
+ const parsed = hunkSchema.safeParse(value);
43327
+ if (!parsed.success)
43328
+ return null;
43329
+ const hunk = parsed.data;
43330
+ if (hunk.lines.some((line) => line.length === 0 || ![" ", "+", "-", "\\"].includes(line[0]))) {
43331
+ return null;
43332
+ }
43333
+ if (countLines(hunk.lines, /* @__PURE__ */ new Set([" ", "-"])) !== hunk.oldLines)
43334
+ return null;
43335
+ if (countLines(hunk.lines, /* @__PURE__ */ new Set([" ", "+"])) !== hunk.newLines)
43336
+ return null;
43337
+ return hunk;
43023
43338
  }
43024
- function isTaskNotificationRecord(text) {
43025
- return taskNotificationRecordPattern.test(text);
43339
+ function parseClaudeNativeFileChange(toolName, value) {
43340
+ if (toolName !== "Edit" && toolName !== "Write" || !isRecord3(value))
43341
+ return null;
43342
+ if (!validNativePath(value.filePath) || !Array.isArray(value.structuredPatch))
43343
+ return null;
43344
+ const hunks = value.structuredPatch.map(validHunk);
43345
+ if (hunks.length === 0 || hunks.some((hunk) => hunk === null))
43346
+ return null;
43347
+ if (toolName === "Write" && value.type !== "create" && value.type !== "update")
43348
+ return null;
43349
+ return {
43350
+ path: value.filePath,
43351
+ kind: toolName === "Write" && value.type === "create" ? "add" : "update",
43352
+ hunks
43353
+ };
43026
43354
  }
43027
- function isControlCommandEnvelope(text) {
43028
- return commandEnvelopePattern.test(text) && controlCommandNamePattern.test(text);
43355
+ function displayPath(nativePath, cwd) {
43356
+ const resolvedCwd = path9.resolve(cwd);
43357
+ const resolvedPath = path9.isAbsolute(nativePath) ? path9.resolve(nativePath) : path9.resolve(cwd, nativePath);
43358
+ const relative = path9.relative(resolvedCwd, resolvedPath);
43359
+ const selected = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path9.sep}`) ? relative : resolvedPath;
43360
+ const normalized = selected.replaceAll("\\", "/");
43361
+ return validNativePath(normalized) && normalized !== "." ? normalized : null;
43029
43362
  }
43030
- function isNamedCommandEnvelope(text, namePattern) {
43031
- return commandEnvelopePattern.test(text) && namePattern.test(text);
43363
+ function projectClaudeFileChange(value, cwd) {
43364
+ const normalizedPath = displayPath(value.path, cwd);
43365
+ if (!normalizedPath)
43366
+ return null;
43367
+ const body = value.hunks.flatMap((hunk) => [
43368
+ `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,
43369
+ ...hunk.lines
43370
+ ]);
43371
+ const absoluteDisplayPath = path9.posix.isAbsolute(normalizedPath);
43372
+ const oldHeader = value.kind === "add" ? "/dev/null" : absoluteDisplayPath ? normalizedPath : `a/${normalizedPath}`;
43373
+ const newHeader = absoluteDisplayPath ? normalizedPath : `b/${normalizedPath}`;
43374
+ const unifiedDiff = [`--- ${oldHeader}`, `+++ ${newHeader}`, ...body, ""].join("\n");
43375
+ return { path: normalizedPath, kind: value.kind, unifiedDiff };
43032
43376
  }
43033
- function displayedUserText(text) {
43034
- if (isNamedCommandEnvelope(text, initCommandNamePattern))
43035
- return "/init";
43036
- if (isNamedCommandEnvelope(text, recapCommandNamePattern))
43037
- return "/recap";
43038
- return text;
43377
+
43378
+ // dist/native-message.js
43379
+ var ABORTED_TERMINALS = /* @__PURE__ */ new Set(["aborted_streaming", "aborted_tools"]);
43380
+ var AUTHENTICATION_ERRORS = /* @__PURE__ */ new Set(["authentication_failed", "oauth_org_not_allowed"]);
43381
+ var CLAUDE_SUBAGENT_TOOLS = /* @__PURE__ */ new Set(["Agent", "Task", "SendMessage"]);
43382
+ var BACKGROUND_OUTPUT_FILE_PATTERN = /Output is being written to: (.+?\.output)\./u;
43383
+ var SUBAGENT_DESCRIPTION_LIMIT = 500;
43384
+ var SUBAGENT_SUMMARY_LIMIT = 2e3;
43385
+ function isRecord4(value) {
43386
+ return typeof value === "object" && value !== null && !Array.isArray(value);
43039
43387
  }
43040
- function localCommandStdoutText(text) {
43041
- const match = localCommandStdoutPattern.exec(text);
43042
- if (!match)
43388
+ function nativeUuid(message) {
43389
+ return typeof message.uuid === "string" && message.uuid.length > 0 ? message.uuid : null;
43390
+ }
43391
+ function parentToolUseId(message) {
43392
+ return typeof message.parent_tool_use_id === "string" && message.parent_tool_use_id.length > 0 ? message.parent_tool_use_id : null;
43393
+ }
43394
+ function assistantNativeMessageId(message) {
43395
+ if (!isRecord4(message.message))
43043
43396
  return null;
43044
- return match[1] ?? "";
43397
+ return typeof message.message.id === "string" && message.message.id.length > 0 ? message.message.id : null;
43045
43398
  }
43046
- function isTaskNotificationOrigin(value) {
43047
- return isRecord3(value.origin) && value.origin.kind === "task-notification";
43399
+ function assistantContent(message) {
43400
+ if (message.type !== "assistant" || !isRecord4(message.message))
43401
+ return null;
43402
+ return Array.isArray(message.message.content) ? message.message.content : null;
43048
43403
  }
43049
- function visibleUserTextParts(message) {
43050
- if (message.type !== "user" || message.syntheticUser)
43051
- return [];
43052
- const parts = textParts(message.message.content);
43053
- if (parts.some(isControlCommandEnvelope))
43054
- return [];
43055
- return parts.filter((part) => !isLocalCommandRecord(part) && !isTaskNotificationRecord(part));
43404
+ function assistantText(message) {
43405
+ const content = assistantContent(message);
43406
+ if (!content)
43407
+ return null;
43408
+ return content.flatMap((block) => isRecord4(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("");
43056
43409
  }
43057
- function isInterruptionRecord(value, promptId) {
43058
- if (value.type !== "user" || promptId === null || value.promptId !== promptId || value.promptSource !== void 0 || !isRecord3(value.message))
43059
- return false;
43060
- const content = value.message.content;
43061
- if (!Array.isArray(content) || content.length !== 1)
43062
- return false;
43063
- const part = content[0];
43064
- return isRecord3(part) && part.type === "text" && (part.text === "[Request interrupted by user]" || part.text === "[Request interrupted by user for tool use]");
43410
+ function assistantError(message) {
43411
+ return isRecord4(message) && message.type === "assistant" && typeof message.error === "string" ? message.error : null;
43065
43412
  }
43066
- function conversationMessages(values, sessionId) {
43067
- const messages = [];
43068
- const ids = /* @__PURE__ */ new Set();
43069
- let promptId = null;
43070
- for (const value of values) {
43071
- if (!isRecord3(value))
43072
- throw new Error("Claude history contains a malformed message");
43073
- if (value.type === "system")
43074
- continue;
43075
- if (value.type !== "user" && value.type !== "assistant" || typeof value.uuid !== "string" || value.uuid.length === 0 || value.session_id !== sessionId || !isRecord3(value.message) || value.message.role !== value.type) {
43076
- throw new Error("Claude history contains an invalid message identity");
43077
- }
43078
- if (ids.has(value.uuid))
43079
- throw new Error("Claude history contains duplicate message IDs");
43080
- ids.add(value.uuid);
43081
- const interrupted = isInterruptionRecord(value, promptId);
43082
- const message = {
43083
- type: value.type,
43084
- uuid: value.uuid,
43085
- message: value.message,
43086
- interrupted,
43087
- syntheticUser: value.type === "user" && (interrupted || value.isSynthetic === true || value.isMeta === true || isTaskNotificationOrigin(value) || value.toolUseResult !== void 0 && value.toolUseResult !== null)
43088
- };
43089
- messages.push(message);
43090
- if (isHumanUser(message)) {
43091
- promptId = typeof value.promptId === "string" && value.promptId.length > 0 ? value.promptId : null;
43092
- }
43093
- }
43094
- return messages;
43413
+ function boundedString(value, limit) {
43414
+ if (typeof value !== "string")
43415
+ return void 0;
43416
+ const trimmed = value.trim();
43417
+ if (trimmed.length === 0)
43418
+ return void 0;
43419
+ return trimmed.slice(0, limit);
43095
43420
  }
43096
- function isHumanUser(message) {
43097
- return visibleUserTextParts(message).length > 0;
43421
+ function subagentDescription(argumentsValue, toolName) {
43422
+ if (!isRecord4(argumentsValue))
43423
+ return `${toolName} delegation`;
43424
+ return boundedString(argumentsValue.description, SUBAGENT_DESCRIPTION_LIMIT) ?? boundedString(argumentsValue.summary, SUBAGENT_DESCRIPTION_LIMIT) ?? boundedString(argumentsValue.name, SUBAGENT_DESCRIPTION_LIMIT) ?? `${toolName} delegation`;
43098
43425
  }
43099
- function turnOutcome(messages) {
43100
- if (messages.some(({ interrupted }) => interrupted))
43101
- return { status: "cancelled", reason: "Cancelled by user" };
43102
- const assistants = messages.filter(({ type }) => type === "assistant");
43103
- const failed = assistants.some(({ message }) => typeof message.error === "string");
43104
- if (failed) {
43105
- return {
43106
- status: "failed",
43107
- error: {
43108
- code: "nativeFailure",
43109
- message: "Claude Assistant failed",
43110
- retryable: false
43111
- }
43112
- };
43113
- }
43114
- const final = assistants.at(-1);
43115
- if (!final)
43116
- return { status: "unknown", reason: "Claude history has no Assistant terminal" };
43117
- return {
43118
- status: "unknown",
43119
- reason: "Claude history does not include complete Result terminal evidence"
43120
- };
43426
+ function subagentPrompt(argumentsValue) {
43427
+ if (!isRecord4(argumentsValue))
43428
+ return void 0;
43429
+ return boundedString(argumentsValue.prompt ?? argumentsValue.message, SUBAGENT_SUMMARY_LIMIT);
43121
43430
  }
43122
- function itemOutcome(outcome) {
43123
- if (outcome.status === "failed")
43124
- return { status: "failed", error: outcome.error };
43125
- if (outcome.status === "cancelled") {
43126
- return {
43127
- status: "cancelled",
43128
- ...outcome.reason ? { reason: outcome.reason } : {}
43129
- };
43130
- }
43131
- return { status: "succeeded" };
43431
+ function subagentRole(argumentsValue) {
43432
+ if (!isRecord4(argumentsValue))
43433
+ return void 0;
43434
+ return boundedString(argumentsValue.subagent_type ?? argumentsValue.agent_type, SUBAGENT_DESCRIPTION_LIMIT);
43132
43435
  }
43133
- function mapClaudeSnapshot(values, sessionId) {
43134
- const messages = conversationMessages(values, sessionId);
43135
- const turns = [];
43136
- for (let index = 0; index < messages.length; ) {
43137
- const user = messages[index];
43138
- if (!user || !isHumanUser(user)) {
43139
- index += 1;
43140
- continue;
43436
+ function subagentBackground(argumentsValue) {
43437
+ return isRecord4(argumentsValue) && argumentsValue.run_in_background === true;
43438
+ }
43439
+ function targetedSubagentId(argumentsValue) {
43440
+ if (!isRecord4(argumentsValue))
43441
+ return void 0;
43442
+ return boundedString(argumentsValue.to ?? argumentsValue.recipient ?? argumentsValue.agentId, SUBAGENT_DESCRIPTION_LIMIT);
43443
+ }
43444
+ function includesAuthenticationFailure(errors) {
43445
+ return errors.some((error52) => AUTHENTICATION_ERRORS.has(error52));
43446
+ }
43447
+ function failure(kind) {
43448
+ return { status: "failed", kind };
43449
+ }
43450
+ function safeNonNegativeInteger(value) {
43451
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
43452
+ }
43453
+ function finiteNonNegativeNumber(value) {
43454
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
43455
+ }
43456
+ function parseResultModelUsage(value) {
43457
+ if (!isRecord4(value))
43458
+ return void 0;
43459
+ const usage = [];
43460
+ for (const entry of Object.values(value)) {
43461
+ if (!isRecord4(entry) || !safeNonNegativeInteger(entry.inputTokens) || !safeNonNegativeInteger(entry.outputTokens)) {
43462
+ return void 0;
43141
43463
  }
43142
- let end = index + 1;
43143
- while (end < messages.length && !isHumanUser(messages[end]))
43144
- end += 1;
43145
- const turnMessages = messages.slice(index, end);
43146
- const outcome = turnOutcome(turnMessages);
43147
- const results = toolResultBlocks(turnMessages);
43148
- const checkpointMessage = turnMessages.findLast(({ type, interrupted }) => type === "assistant" || interrupted);
43149
- let agentMessageOrdinal = 0;
43150
- let reasoningOrdinal = 0;
43151
- turns.push({
43152
- nativeTurnRef: nativeTurnRefSchema.parse({
43153
- harnessId: claudeCodeHarnessId,
43154
- nativeSessionId: sessionId,
43155
- nativeTurnKey: user.uuid,
43156
- formatVersion: 1
43157
- }),
43158
- ...checkpointMessage ? {
43159
- checkpoint: nativeCheckpointRefSchema.parse({
43160
- harnessId: claudeCodeHarnessId,
43161
- nativeSessionId: sessionId,
43162
- checkpointId: checkpointMessage.uuid,
43163
- formatVersion: 1
43164
- })
43165
- } : {},
43166
- input: visibleUserTextParts(user).map((text) => ({
43167
- type: "text",
43168
- text: displayedUserText(text)
43169
- })),
43170
- items: turnMessages.flatMap((message) => {
43171
- if (message.type === "user") {
43172
- const recapOutput = visibleUserTextParts(user).some((text2) => isNamedCommandEnvelope(text2, recapCommandNamePattern)) ? textParts(message.message.content).map(localCommandStdoutText).find((text2) => text2 !== null && text2.length > 0) : void 0;
43173
- if (!recapOutput)
43174
- return [];
43175
- return [
43176
- {
43177
- item: {
43178
- type: "agentMessage",
43179
- itemId: claudeTranscriptItemId(user.uuid, "agentMessage", agentMessageOrdinal += 1),
43180
- text: recapOutput
43181
- },
43182
- outcome: itemOutcome(outcome)
43183
- }
43184
- ];
43185
- }
43186
- if (message.type !== "assistant")
43187
- return [];
43188
- const content = message.message.content;
43189
- const text = textParts(content).join("");
43190
- const reasoning = thinkingParts(content).join("");
43191
- if (!Array.isArray(content)) {
43192
- return text.length > 0 ? [
43193
- {
43194
- item: {
43195
- type: "agentMessage",
43196
- itemId: claudeTranscriptItemId(user.uuid, "agentMessage", agentMessageOrdinal += 1),
43197
- text
43198
- },
43199
- outcome: itemOutcome(outcome)
43200
- }
43201
- ] : [];
43202
- }
43203
- const items = [];
43204
- let projectedReasoning = false;
43205
- let projectedText = false;
43206
- for (const [blockIndex, block] of content.entries()) {
43207
- if (!isRecord3(block))
43208
- continue;
43209
- if (block.type === "thinking" && !projectedReasoning && reasoning.length > 0) {
43210
- items.push({
43211
- item: {
43212
- type: "reasoning",
43213
- itemId: claudeTranscriptItemId(user.uuid, "reasoning", reasoningOrdinal += 1),
43214
- text: reasoning
43215
- },
43216
- outcome: itemOutcome(outcome)
43217
- });
43218
- projectedReasoning = true;
43219
- continue;
43220
- }
43221
- if (block.type === "text" && !projectedText && text.length > 0) {
43222
- items.push({
43223
- item: {
43224
- type: "agentMessage",
43225
- itemId: claudeTranscriptItemId(user.uuid, "agentMessage", agentMessageOrdinal += 1),
43226
- text
43227
- },
43228
- outcome: itemOutcome(outcome)
43229
- });
43230
- projectedText = true;
43231
- continue;
43232
- }
43233
- if (block.type !== "tool_use" || typeof block.id !== "string" || typeof block.name !== "string") {
43234
- continue;
43235
- }
43236
- const result = results.get(block.id);
43237
- if (!result)
43238
- continue;
43239
- const output = toolResultOutput(result);
43240
- const failed = result.is_error === true;
43241
- const toolOutcome = failed ? {
43242
- status: "failed",
43243
- error: {
43244
- code: "nativeFailure",
43245
- message: `${block.name} failed`,
43246
- retryable: false
43247
- }
43248
- } : { status: "succeeded" };
43249
- const itemId = hostItemIdSchema.parse(`claude-item-v1-${message.uuid}-tool-${blockIndex}`);
43250
- if (block.name === "Bash" && isRecord3(block.input) && typeof block.input.command === "string") {
43251
- items.push({
43252
- item: {
43253
- type: "commandExecution",
43254
- itemId,
43255
- command: block.input.command,
43256
- ...output ? { output } : {}
43257
- },
43258
- outcome: toolOutcome
43259
- });
43260
- continue;
43261
- }
43262
- const argumentsResult = jsonValueSchema.safeParse(block.input);
43263
- items.push({
43264
- item: {
43265
- type: "toolExecution",
43266
- itemId,
43267
- toolName: block.name,
43268
- arguments: argumentsResult.success ? argumentsResult.data : null,
43269
- ...output ? { output: { content: [{ type: "text", text: output }] } } : {}
43270
- },
43271
- outcome: toolOutcome
43272
- });
43273
- }
43274
- return items;
43275
- }),
43276
- outcome
43277
- });
43278
- index = end;
43464
+ usage.push({ inputTokens: entry.inputTokens, outputTokens: entry.outputTokens });
43279
43465
  }
43280
- return { turns };
43466
+ return usage;
43281
43467
  }
43282
- function toolResultBlocks(messages) {
43283
- const results = /* @__PURE__ */ new Map();
43284
- for (const message of messages) {
43285
- if (message.type !== "user" || !Array.isArray(message.message.content))
43286
- continue;
43287
- for (const block of message.message.content) {
43288
- if (isRecord3(block) && block.type === "tool_result" && typeof block.tool_use_id === "string") {
43289
- results.set(block.tool_use_id, block);
43290
- }
43291
- }
43468
+ function parseLastRequestUsage(value, attribution = {}) {
43469
+ if (!isRecord4(value))
43470
+ return void 0;
43471
+ const inputTokens = value.input_tokens;
43472
+ const outputTokens = value.output_tokens;
43473
+ const cacheCreationInputTokens = value.cache_creation_input_tokens;
43474
+ const cacheReadInputTokens = value.cache_read_input_tokens;
43475
+ if (!safeNonNegativeInteger(inputTokens) || !safeNonNegativeInteger(outputTokens) || !safeNonNegativeInteger(cacheCreationInputTokens) || !safeNonNegativeInteger(cacheReadInputTokens)) {
43476
+ return void 0;
43292
43477
  }
43293
- return results;
43478
+ const requestId = boundedString(attribution.requestId, 500);
43479
+ const model = boundedString(attribution.model, 500);
43480
+ const provider = boundedString(attribution.provider, 100);
43481
+ return {
43482
+ ...requestId ? { requestId } : {},
43483
+ ...model ? { model } : {},
43484
+ ...provider ? { provider } : {},
43485
+ inputTokens,
43486
+ outputTokens,
43487
+ cacheCreationInputTokens,
43488
+ cacheReadInputTokens
43489
+ };
43294
43490
  }
43295
- function toolResultOutput(block) {
43296
- if (!block)
43491
+ function assistantRequestUsage(message, provider) {
43492
+ if (!isRecord4(message.message))
43297
43493
  return void 0;
43298
- const text = textParts(block.content).join("");
43299
- return text.length > 0 ? text : void 0;
43494
+ return parseLastRequestUsage(message.message.usage, {
43495
+ requestId: message.message.id ?? message.request_id,
43496
+ model: message.message.model,
43497
+ provider: message.provider ?? message.message.provider ?? provider
43498
+ });
43300
43499
  }
43301
- function resultSubagentId(value, block) {
43302
- const nativeResult = value.tool_use_result;
43303
- if (isRecord3(nativeResult)) {
43304
- const structured = nativeResult.agentId ?? nativeResult.agent_id ?? nativeResult.task_id;
43305
- if (typeof structured === "string" && structured.length > 0)
43306
- return structured;
43500
+ function parseResultUsageEvent(message) {
43501
+ const totalCostUsd = finiteNonNegativeNumber(message.total_cost_usd) ? message.total_cost_usd : void 0;
43502
+ const modelUsage = parseResultModelUsage(message.modelUsage);
43503
+ const lastRequestUsage = parseLastRequestUsage(message.usage);
43504
+ if (totalCostUsd === void 0 && modelUsage === void 0 && lastRequestUsage === void 0) {
43505
+ return null;
43307
43506
  }
43308
- const match = /agentId:\s*([A-Za-z0-9_-]+)/u.exec(textParts(block.content).join(""));
43309
- return match?.[1];
43310
- }
43311
- function subagentPrompt(values, nativeSubagentId2) {
43312
- const toolUses = /* @__PURE__ */ new Map();
43313
- for (const value of values) {
43314
- if (!isRecord3(value) || !isRecord3(value.message) || !Array.isArray(value.message.content)) {
43507
+ return {
43508
+ type: "usage.result",
43509
+ ...totalCostUsd !== void 0 ? { totalCostUsd } : {},
43510
+ ...modelUsage !== void 0 ? { modelUsage } : {},
43511
+ ...lastRequestUsage ? { lastRequestUsage } : {}
43512
+ };
43513
+ }
43514
+ function parsePlanLimitWindow(value) {
43515
+ if (!isRecord4(value))
43516
+ return void 0;
43517
+ const utilization = value.utilization;
43518
+ if (typeof utilization !== "number" || !Number.isFinite(utilization) || utilization < 0) {
43519
+ return void 0;
43520
+ }
43521
+ const utilizationPercent = Math.min(100, Math.max(0, Math.round(utilization * 1e4) / 100));
43522
+ const resetsAt = value.resetsAt;
43523
+ const resetsAtUnix = safeNonNegativeInteger(resetsAt) ? resetsAt : void 0;
43524
+ return { utilizationPercent, ...resetsAtUnix !== void 0 ? { resetsAtUnix } : {} };
43525
+ }
43526
+ function parseClaudePlanLimitEvent(message) {
43527
+ if (!isRecord4(message) || message.type !== "rate_limit_event")
43528
+ return null;
43529
+ const info = message.rate_limit_info;
43530
+ if (!isRecord4(info))
43531
+ return null;
43532
+ const windows = isRecord4(info.unifiedWindows) ? info.unifiedWindows : void 0;
43533
+ let fiveHour = parsePlanLimitWindow(windows?.five_hour);
43534
+ let sevenDay = parsePlanLimitWindow(windows?.seven_day);
43535
+ if (!fiveHour && !sevenDay) {
43536
+ const flatWindow = parsePlanLimitWindow(info);
43537
+ if (flatWindow && info.rateLimitType === "five_hour")
43538
+ fiveHour = flatWindow;
43539
+ else if (flatWindow && info.rateLimitType === "seven_day")
43540
+ sevenDay = flatWindow;
43541
+ }
43542
+ if (!fiveHour && !sevenDay)
43543
+ return null;
43544
+ return {
43545
+ ...fiveHour ? { fiveHour } : {},
43546
+ ...sevenDay ? { sevenDay } : {}
43547
+ };
43548
+ }
43549
+ function nativeSubagentId(nativeResult, outputText) {
43550
+ if (isRecord4(nativeResult)) {
43551
+ const structured = boundedString(nativeResult.agentId ?? nativeResult.agent_id ?? nativeResult.task_id, SUBAGENT_DESCRIPTION_LIMIT);
43552
+ if (structured)
43553
+ return structured;
43554
+ }
43555
+ return boundedString(/agentId:\s*([A-Za-z0-9_-]+)/u.exec(outputText ?? "")?.[1], SUBAGENT_DESCRIPTION_LIMIT);
43556
+ }
43557
+ function subagentContinuesInBackground(nativeResult, outputText) {
43558
+ if (isRecord4(nativeResult)) {
43559
+ if (nativeResult.isAsync === true || nativeResult.is_async === true)
43560
+ return true;
43561
+ if (nativeResult.status === "async_launched")
43562
+ return true;
43563
+ }
43564
+ return outputText?.includes("The agent is working in the background.") ?? false;
43565
+ }
43566
+ function resultText(content, nativeResult) {
43567
+ let text = "";
43568
+ if (typeof content === "string") {
43569
+ text = content;
43570
+ } else if (Array.isArray(content)) {
43571
+ text = content.flatMap((block) => isRecord4(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("");
43572
+ }
43573
+ if (text.length > 0)
43574
+ return text;
43575
+ if (!isRecord4(nativeResult))
43576
+ return void 0;
43577
+ const stdout = typeof nativeResult.stdout === "string" ? nativeResult.stdout : "";
43578
+ const stderr = typeof nativeResult.stderr === "string" ? nativeResult.stderr : "";
43579
+ const combined = stdout + stderr;
43580
+ return combined.length > 0 ? combined : void 0;
43581
+ }
43582
+ function userMessageText(content) {
43583
+ if (typeof content === "string")
43584
+ return content;
43585
+ if (!Array.isArray(content))
43586
+ return null;
43587
+ const text = content.flatMap((block) => isRecord4(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("");
43588
+ return text.length > 0 ? text : null;
43589
+ }
43590
+ function parseClaudeTaskNotification(message) {
43591
+ if (!isRecord4(message) || message.type !== "user" || !isRecord4(message.message))
43592
+ return null;
43593
+ if (isRecord4(message.origin) && message.origin.kind !== "task-notification")
43594
+ return null;
43595
+ const content = userMessageText(message.message.content);
43596
+ if (!content || !content.includes("<task-notification>"))
43597
+ return null;
43598
+ const taskId = content.match(/<task-id>([^<]+)<\/task-id>/u)?.[1]?.trim();
43599
+ if (!taskId)
43600
+ return null;
43601
+ const xmlStatus = content.match(/<status>([^<]+)<\/status>/u)?.[1]?.trim();
43602
+ const status = taskStatus(xmlStatus ?? "completed");
43603
+ if (status !== "completed" && status !== "failed" && status !== "interrupted")
43604
+ return null;
43605
+ const summary = content.match(/<summary>([\s\S]*?)<\/summary>/u)?.[1]?.trim();
43606
+ const callId = content.match(/<tool-use-id>([^<]+)<\/tool-use-id>/u)?.[1]?.trim();
43607
+ const outputFile = content.match(/<output-file>([^<]+)<\/output-file>/u)?.[1]?.trim();
43608
+ return {
43609
+ type: "subagent.settled",
43610
+ nativeSubagentId: taskId,
43611
+ status,
43612
+ ...callId ? { callId } : {},
43613
+ ...summary ? { resultSummary: summary.slice(0, SUBAGENT_SUMMARY_LIMIT) } : {},
43614
+ ...outputFile ? { outputFile } : {}
43615
+ };
43616
+ }
43617
+ function taskStatus(value) {
43618
+ switch (value) {
43619
+ case "pending":
43620
+ return "pending";
43621
+ case "running":
43622
+ return "running";
43623
+ case "completed":
43624
+ return "completed";
43625
+ case "failed":
43626
+ return "failed";
43627
+ case "killed":
43628
+ case "stopped":
43629
+ return "interrupted";
43630
+ default:
43631
+ return null;
43632
+ }
43633
+ }
43634
+ var ClaudeNativeTurnAccumulator = class {
43635
+ #provider;
43636
+ #activeRootStreamMessageId = null;
43637
+ #assistantErrors = [];
43638
+ #cancelRequested = false;
43639
+ #compactionState = "idle";
43640
+ #completed = false;
43641
+ #completedToolIds = /* @__PURE__ */ new Set();
43642
+ #messageOrdinal = 0;
43643
+ #messages = /* @__PURE__ */ new Map();
43644
+ #protocolConflict = false;
43645
+ #textConflict = false;
43646
+ #tools = /* @__PURE__ */ new Map();
43647
+ constructor(options = {}) {
43648
+ this.#provider = options.provider;
43649
+ }
43650
+ requestCancel() {
43651
+ this.#cancelRequested = true;
43652
+ }
43653
+ consume(message) {
43654
+ if (this.#completed || !isRecord4(message))
43655
+ return { events: [] };
43656
+ const events = [];
43657
+ this.#consumeSegmentLevel(message, events);
43658
+ this.#consumeTaskLifecycle(message, events);
43659
+ const parentCallId = parentToolUseId(message);
43660
+ const nested = parentCallId !== null;
43661
+ if (parentCallId && this.#tools.get(parentCallId)?.subagent === true && (message.type === "assistant" || message.type === "user")) {
43662
+ events.push({ type: "subagent.transcript.changed", callId: parentCallId });
43663
+ }
43664
+ if (!nested) {
43665
+ this.#consumeCompaction(message, events);
43666
+ this.#consumeLocalCommandOutput(message, events);
43667
+ }
43668
+ if (message.type === "stream_event" && isRecord4(message.event)) {
43669
+ if (!nested)
43670
+ this.#consumeStreamEvent(message, events);
43671
+ } else if (message.type === "tool_progress") {
43672
+ this.#consumeToolProgress(message, events);
43673
+ }
43674
+ if (!nested) {
43675
+ const error52 = assistantError(message);
43676
+ if (error52 !== null)
43677
+ this.#assistantErrors.push(error52);
43678
+ }
43679
+ if (message.type === "assistant") {
43680
+ if (!nested)
43681
+ this.#consumeAssistantMessage(message, events);
43682
+ } else if (message.type === "user") {
43683
+ this.#consumeTaskNotification(message, events);
43684
+ this.#consumeToolResults(message, events, nested);
43685
+ }
43686
+ if (message.type !== "result")
43687
+ return { events };
43688
+ const usageEvent = parseResultUsageEvent(message);
43689
+ if (usageEvent)
43690
+ events.push(usageEvent);
43691
+ this.#completed = true;
43692
+ const terminalReason = typeof message.terminal_reason === "string" ? message.terminal_reason : "missing";
43693
+ const nativeSuccess = message.subtype === "success" && message.is_error === false && (terminalReason === "completed" || terminalReason === "missing") && this.#assistantErrors.length === 0;
43694
+ if (nativeSuccess && this.#tools.size > 0)
43695
+ this.#protocolConflict = true;
43696
+ let terminal;
43697
+ if (this.#protocolConflict) {
43698
+ terminal = failure("protocol");
43699
+ } else if (this.#textConflict) {
43700
+ terminal = failure("textConflict");
43701
+ } else if (includesAuthenticationFailure(this.#assistantErrors)) {
43702
+ terminal = failure("authentication");
43703
+ } else if (this.#cancelRequested && ABORTED_TERMINALS.has(terminalReason)) {
43704
+ terminal = { status: "cancelled", reason: terminalReason };
43705
+ } else if (this.#cancelRequested) {
43706
+ terminal = failure("cancellationUnproven");
43707
+ } else if (nativeSuccess) {
43708
+ terminal = { status: "succeeded" };
43709
+ } else {
43710
+ terminal = failure("native");
43711
+ }
43712
+ return { events, terminal };
43713
+ }
43714
+ #consumeCompaction(message, events) {
43715
+ if (message.type !== "system")
43716
+ return;
43717
+ if (message.subtype === "status") {
43718
+ if (message.status === "compacting" && this.#compactionState !== "active") {
43719
+ this.#compactionState = "active";
43720
+ events.push({ type: "compaction.started" });
43721
+ }
43722
+ if (message.compact_result === "success" || message.compact_result === "failed") {
43723
+ if (this.#compactionState === "settled")
43724
+ return;
43725
+ if (this.#compactionState === "idle")
43726
+ events.push({ type: "compaction.started" });
43727
+ this.#compactionState = "settled";
43728
+ events.push({
43729
+ type: "compaction.completed",
43730
+ outcome: message.compact_result === "success" ? "succeeded" : "failed"
43731
+ });
43732
+ }
43733
+ return;
43734
+ }
43735
+ if (message.subtype !== "compact_boundary" || this.#compactionState === "settled")
43736
+ return;
43737
+ if (this.#compactionState === "idle")
43738
+ events.push({ type: "compaction.started" });
43739
+ this.#compactionState = "settled";
43740
+ events.push({ type: "compaction.completed", outcome: "succeeded" });
43741
+ }
43742
+ #consumeLocalCommandOutput(message, events) {
43743
+ if (message.type !== "system" || message.subtype !== "local_command_output")
43744
+ return;
43745
+ if (typeof message.content !== "string" || message.content.length === 0)
43746
+ return;
43747
+ const checkpointId = nativeUuid(message);
43748
+ const messageId = checkpointId ?? this.#nextMessageId();
43749
+ const state = this.#messageState(messageId);
43750
+ if (state.completed)
43751
+ return;
43752
+ state.text += message.content;
43753
+ events.push({ type: "text.delta", messageId, delta: message.content });
43754
+ state.completed = true;
43755
+ events.push({
43756
+ type: "message.completed",
43757
+ messageId,
43758
+ ...checkpointId ? { checkpointId } : {}
43759
+ });
43760
+ }
43761
+ /**
43762
+ * Claude opens one native Segment per Root execution and reports its live
43763
+ * background tasks as a level whose membership replaces the previous set.
43764
+ */
43765
+ #consumeSegmentLevel(message, events) {
43766
+ if (message.type !== "system")
43767
+ return;
43768
+ if (message.subtype === "init") {
43769
+ events.push({ type: "segment.started" });
43770
+ return;
43771
+ }
43772
+ if (message.subtype !== "background_tasks_changed" || !Array.isArray(message.tasks))
43773
+ return;
43774
+ const nativeSubagentIds = message.tasks.flatMap((task) => {
43775
+ if (!isRecord4(task))
43776
+ return [];
43777
+ const taskId = boundedString(task.task_id, SUBAGENT_DESCRIPTION_LIMIT);
43778
+ return taskId ? [taskId] : [];
43779
+ });
43780
+ events.push({ type: "subagents.live", nativeSubagentIds });
43781
+ }
43782
+ #consumeTaskLifecycle(message, events) {
43783
+ if (message.type !== "system")
43784
+ return;
43785
+ if (message.subtype === "task_notification") {
43786
+ const agentId = boundedString(message.task_id, SUBAGENT_DESCRIPTION_LIMIT);
43787
+ const status = taskStatus(message.status);
43788
+ if (!agentId || status !== "completed" && status !== "failed" && status !== "interrupted") {
43789
+ return;
43790
+ }
43791
+ const resultSummary = boundedString(message.summary, SUBAGENT_SUMMARY_LIMIT);
43792
+ const callId2 = boundedString(message.tool_use_id, SUBAGENT_DESCRIPTION_LIMIT);
43793
+ const outputFile = typeof message.output_file === "string" && message.output_file.length > 0 ? message.output_file : void 0;
43794
+ events.push({
43795
+ type: "subagent.settled",
43796
+ nativeSubagentId: agentId,
43797
+ status,
43798
+ ...callId2 ? { callId: callId2 } : {},
43799
+ ...resultSummary ? { resultSummary } : {},
43800
+ ...outputFile ? { outputFile } : {}
43801
+ });
43802
+ return;
43803
+ }
43804
+ const callId = typeof message.tool_use_id === "string" ? message.tool_use_id : null;
43805
+ if (!callId || !this.#tools.get(callId)?.subagent)
43806
+ return;
43807
+ if (message.subtype === "task_started") {
43808
+ const description = boundedString(message.description, SUBAGENT_DESCRIPTION_LIMIT);
43809
+ const role = boundedString(message.subagent_type, SUBAGENT_DESCRIPTION_LIMIT);
43810
+ const agentId = boundedString(message.task_id, SUBAGENT_DESCRIPTION_LIMIT);
43811
+ events.push({
43812
+ type: "subagent.updated",
43813
+ callId,
43814
+ status: "running",
43815
+ ...description ? { description } : {},
43816
+ ...role ? { role } : {},
43817
+ ...agentId ? { nativeSubagentId: agentId } : {}
43818
+ });
43819
+ return;
43820
+ }
43821
+ if (message.subtype === "task_progress") {
43822
+ const description = boundedString(message.description, SUBAGENT_DESCRIPTION_LIMIT);
43823
+ const role = boundedString(message.subagent_type, SUBAGENT_DESCRIPTION_LIMIT);
43824
+ const resultSummary = boundedString(message.summary, SUBAGENT_SUMMARY_LIMIT);
43825
+ const agentId = boundedString(message.task_id, SUBAGENT_DESCRIPTION_LIMIT);
43826
+ events.push({
43827
+ type: "subagent.updated",
43828
+ callId,
43829
+ status: "running",
43830
+ ...description ? { description } : {},
43831
+ ...role ? { role } : {},
43832
+ ...agentId ? { nativeSubagentId: agentId } : {},
43833
+ ...resultSummary ? { resultSummary } : {}
43834
+ });
43835
+ return;
43836
+ }
43837
+ if (message.subtype === "task_updated" && isRecord4(message.patch)) {
43838
+ const status = taskStatus(message.patch.status);
43839
+ if (!status)
43840
+ return;
43841
+ const description = boundedString(message.patch.description, SUBAGENT_DESCRIPTION_LIMIT);
43842
+ const resultSummary = boundedString(message.patch.error, SUBAGENT_SUMMARY_LIMIT);
43843
+ const agentId = boundedString(message.task_id, SUBAGENT_DESCRIPTION_LIMIT);
43844
+ events.push({
43845
+ type: "subagent.updated",
43846
+ callId,
43847
+ status,
43848
+ ...description ? { description } : {},
43849
+ ...agentId ? { nativeSubagentId: agentId } : {},
43850
+ ...resultSummary ? { resultSummary } : {}
43851
+ });
43852
+ }
43853
+ }
43854
+ #consumeStreamEvent(message, events) {
43855
+ const event = message.event;
43856
+ if (!isRecord4(event))
43857
+ return;
43858
+ if (event.type === "message_start" && isRecord4(event.message) && typeof event.message.id === "string" && event.message.id.length > 0) {
43859
+ this.#activeRootStreamMessageId = event.message.id;
43860
+ this.#messageState(event.message.id);
43861
+ return;
43862
+ }
43863
+ if (event.type !== "content_block_delta" || !isRecord4(event.delta))
43864
+ return;
43865
+ const messageId = this.#activeRootStreamMessageId ?? nativeUuid(message) ?? this.#nextMessageId();
43866
+ if (!this.#activeRootStreamMessageId)
43867
+ this.#activeRootStreamMessageId = messageId;
43868
+ const state = this.#messageState(messageId);
43869
+ if (state.completed) {
43870
+ if (event.delta.type === "text_delta")
43871
+ this.#textConflict = true;
43872
+ return;
43873
+ }
43874
+ if (event.delta.type === "text_delta" && typeof event.delta.text === "string") {
43875
+ if (event.delta.text.length === 0)
43876
+ return;
43877
+ state.text += event.delta.text;
43878
+ events.push({ type: "text.delta", messageId, delta: event.delta.text });
43879
+ return;
43880
+ }
43881
+ if (event.delta.type === "thinking_delta" && typeof event.delta.thinking === "string") {
43882
+ if (event.delta.thinking.length === 0)
43883
+ return;
43884
+ state.reasoning += event.delta.thinking;
43885
+ events.push({ type: "reasoning.delta", messageId, delta: event.delta.thinking });
43886
+ }
43887
+ }
43888
+ #consumeAssistantMessage(message, events) {
43889
+ const checkpointId = nativeUuid(message);
43890
+ const nativeMessageId = assistantNativeMessageId(message);
43891
+ const messageId = this.#activeRootStreamMessageId ?? nativeMessageId ?? checkpointId ?? this.#nextMessageId();
43892
+ const state = this.#messageState(messageId);
43893
+ if (state.completed) {
43894
+ this.#consumeToolUseBlocks(message, events, true);
43895
+ const usage = assistantRequestUsage(message, this.#provider);
43896
+ if (usage && !state.usagePublished) {
43897
+ state.usagePublished = true;
43898
+ events.push({
43899
+ type: "message.completed",
43900
+ messageId,
43901
+ ...checkpointId ? { checkpointId } : {},
43902
+ lastRequestUsage: usage
43903
+ });
43904
+ }
43905
+ return;
43906
+ }
43907
+ if (state.reasoning.length > 0) {
43908
+ events.push({ type: "reasoning.completed", messageId });
43909
+ }
43910
+ const completeText = assistantText(message);
43911
+ if (completeText !== null && completeText.length > 0) {
43912
+ if (completeText.startsWith(state.text)) {
43913
+ const suffix = completeText.slice(state.text.length);
43914
+ if (suffix.length > 0) {
43915
+ state.text += suffix;
43916
+ events.push({ type: "text.delta", messageId, delta: suffix });
43917
+ }
43918
+ } else if (completeText !== state.text) {
43919
+ this.#textConflict = true;
43920
+ }
43921
+ }
43922
+ this.#consumeToolUseBlocks(message, events, false);
43923
+ if (!this.#protocolConflict && !this.#textConflict) {
43924
+ const usage = assistantRequestUsage(message, this.#provider);
43925
+ state.usagePublished = usage !== void 0;
43926
+ events.push({
43927
+ type: "message.completed",
43928
+ messageId,
43929
+ ...checkpointId ? { checkpointId } : {},
43930
+ ...usage ? { lastRequestUsage: usage } : {}
43931
+ });
43932
+ }
43933
+ state.completed = true;
43934
+ if (this.#activeRootStreamMessageId === messageId)
43935
+ this.#activeRootStreamMessageId = null;
43936
+ }
43937
+ #consumeToolUseBlocks(message, events, ignoreKnownIds) {
43938
+ for (const block of assistantContent(message) ?? []) {
43939
+ if (!isRecord4(block) || block.type !== "tool_use")
43940
+ continue;
43941
+ const argumentsResult = jsonValueSchema.safeParse(block.input);
43942
+ if (typeof block.id !== "string" || block.id.length === 0 || typeof block.name !== "string" || block.name.length === 0 || !argumentsResult.success) {
43943
+ this.#protocolConflict = true;
43944
+ continue;
43945
+ }
43946
+ if (this.#tools.has(block.id) || this.#completedToolIds.has(block.id)) {
43947
+ if (!ignoreKnownIds)
43948
+ this.#protocolConflict = true;
43949
+ continue;
43950
+ }
43951
+ const subagent = CLAUDE_SUBAGENT_TOOLS.has(block.name);
43952
+ this.#tools.set(block.id, { name: block.name, subagent });
43953
+ if (subagent) {
43954
+ const prompt = subagentPrompt(argumentsResult.data);
43955
+ const role = subagentRole(argumentsResult.data);
43956
+ const agentId = targetedSubagentId(argumentsResult.data);
43957
+ events.push({
43958
+ type: "subagent.started",
43959
+ callId: block.id,
43960
+ operation: block.name === "SendMessage" ? "send" : "spawn",
43961
+ description: subagentDescription(argumentsResult.data, block.name),
43962
+ ...prompt ? { prompt } : {},
43963
+ ...role ? { role } : {},
43964
+ background: block.name === "SendMessage" || subagentBackground(argumentsResult.data),
43965
+ ...agentId ? { nativeSubagentId: agentId } : {}
43966
+ });
43967
+ } else {
43968
+ events.push({
43969
+ type: "tool.started",
43970
+ callId: block.id,
43971
+ toolName: block.name,
43972
+ arguments: argumentsResult.data
43973
+ });
43974
+ }
43975
+ }
43976
+ }
43977
+ #consumeToolProgress(message, events) {
43978
+ const callId = message.tool_use_id;
43979
+ const elapsedSeconds = message.elapsed_time_seconds;
43980
+ if (typeof callId !== "string" || this.#tools.get(callId)?.subagent !== false || typeof elapsedSeconds !== "number" || !Number.isFinite(elapsedSeconds) || elapsedSeconds < 0) {
43981
+ return;
43982
+ }
43983
+ events.push({ type: "tool.progress", callId, elapsedMs: Math.round(elapsedSeconds * 1e3) });
43984
+ }
43985
+ #consumeTaskNotification(message, events) {
43986
+ const settled = parseClaudeTaskNotification(message);
43987
+ if (settled)
43988
+ events.push(settled);
43989
+ }
43990
+ #consumeToolResults(message, events, ignoreUnknown) {
43991
+ if (!isRecord4(message.message) || !Array.isArray(message.message.content))
43992
+ return;
43993
+ const resultBlocks = message.message.content.filter((block) => isRecord4(block) && block.type === "tool_result");
43994
+ if (resultBlocks.length === 0)
43995
+ return;
43996
+ if (resultBlocks.length > 1 && message.tool_use_result !== void 0) {
43997
+ this.#protocolConflict = true;
43998
+ }
43999
+ for (const block of resultBlocks) {
44000
+ const callId = block.tool_use_id;
44001
+ if (typeof callId !== "string" || callId.length === 0) {
44002
+ this.#protocolConflict = true;
44003
+ continue;
44004
+ }
44005
+ const tool = this.#tools.get(callId);
44006
+ if (!tool || this.#completedToolIds.has(callId)) {
44007
+ if (!ignoreUnknown)
44008
+ this.#protocolConflict = true;
44009
+ continue;
44010
+ }
44011
+ if (block.is_error !== void 0 && typeof block.is_error !== "boolean") {
44012
+ this.#protocolConflict = true;
44013
+ continue;
44014
+ }
44015
+ this.#tools.delete(callId);
44016
+ this.#completedToolIds.add(callId);
44017
+ const isError = block.is_error === true;
44018
+ const nativeResult = resultBlocks.length === 1 ? message.tool_use_result ?? message.toolUseResult : void 0;
44019
+ const outputText = resultText(block.content, nativeResult);
44020
+ const structuredResult = tool.name === "TaskCreate" || tool.name === "TaskUpdate" || tool.name === "TaskList" ? jsonValueSchema.safeParse(nativeResult) : null;
44021
+ if (tool.subagent) {
44022
+ const resultSummary = boundedString(outputText, SUBAGENT_SUMMARY_LIMIT);
44023
+ const agentId = nativeSubagentId(nativeResult, outputText);
44024
+ events.push({
44025
+ type: "subagent.completed",
44026
+ callId,
44027
+ isError,
44028
+ ...subagentContinuesInBackground(nativeResult, outputText) ? { continuesInBackground: true } : {},
44029
+ ...agentId ? { nativeSubagentId: agentId } : {},
44030
+ ...resultSummary ? { resultSummary } : {}
44031
+ });
44032
+ continue;
44033
+ }
44034
+ const fileChange = isError ? null : parseClaudeNativeFileChange(tool.name, nativeResult);
44035
+ const backgroundTaskId = tool.name === "Bash" && !isError && isRecord4(nativeResult) && typeof nativeResult.backgroundTaskId === "string" && nativeResult.backgroundTaskId.length > 0 ? nativeResult.backgroundTaskId : void 0;
44036
+ const outputFile = backgroundTaskId !== void 0 ? BACKGROUND_OUTPUT_FILE_PATTERN.exec(outputText ?? "")?.[1] : void 0;
44037
+ const backgroundOutputFile = typeof outputFile === "string" && outputFile.length > 0 ? outputFile : void 0;
44038
+ events.push({
44039
+ type: "tool.completed",
44040
+ callId,
44041
+ toolName: tool.name,
44042
+ ...outputText ? { outputText } : {},
44043
+ ...structuredResult?.success ? { structuredResult: structuredResult.data } : {},
44044
+ isError,
44045
+ ...fileChange ? { fileChange } : {},
44046
+ ...backgroundTaskId ? { backgroundTaskId } : {},
44047
+ ...backgroundOutputFile ? { backgroundOutputFile } : {}
44048
+ });
44049
+ }
44050
+ }
44051
+ #messageState(messageId) {
44052
+ const existing = this.#messages.get(messageId);
44053
+ if (existing)
44054
+ return existing;
44055
+ const created = { completed: false, reasoning: "", text: "", usagePublished: false };
44056
+ this.#messages.set(messageId, created);
44057
+ return created;
44058
+ }
44059
+ #nextMessageId() {
44060
+ this.#messageOrdinal += 1;
44061
+ return `claude-assistant-${this.#messageOrdinal}`;
44062
+ }
44063
+ };
44064
+
44065
+ // dist/item-identity.js
44066
+ function claudeTranscriptItemId(nativeTurnKey, kind, ordinal) {
44067
+ return hostItemIdSchema.parse(`claude-item-v2-${nativeTurnKey}-${kind}-${ordinal}`);
44068
+ }
44069
+
44070
+ // dist/claude-history.js
44071
+ var claudeCodeHarnessId = harnessIdSchema.parse("claude-code");
44072
+ function isRecord5(value) {
44073
+ return typeof value === "object" && value !== null && !Array.isArray(value);
44074
+ }
44075
+ function textParts(value) {
44076
+ if (typeof value === "string")
44077
+ return value.length > 0 ? [value] : [];
44078
+ if (!Array.isArray(value))
44079
+ return [];
44080
+ return value.flatMap((part) => isRecord5(part) && part.type === "text" && typeof part.text === "string" ? [part.text] : []);
44081
+ }
44082
+ function thinkingParts(value) {
44083
+ if (!Array.isArray(value))
44084
+ return [];
44085
+ return value.flatMap((part) => isRecord5(part) && part.type === "thinking" && typeof part.thinking === "string" ? [part.thinking] : []);
44086
+ }
44087
+ var localCommandRecordPattern = /^\s*<(local-command-(?:stdout|caveat))>[\s\S]*<\/\1>\s*$/u;
44088
+ var taskNotificationRecordPattern = /^\s*<task-notification>[\s\S]*<\/task-notification>\s*$/u;
44089
+ var commandEnvelopePattern = /^\s*(?:<(command-(?:message|name|args))>[\s\S]*?<\/\1>\s*)+$/u;
44090
+ var controlCommandNamePattern = /<command-name>\s*\/(?:model|compact)\s*<\/command-name>/u;
44091
+ var recapCommandNamePattern = /<command-name>\s*\/recap\s*<\/command-name>/u;
44092
+ var initCommandNamePattern = /<command-name>\s*\/init\s*<\/command-name>/u;
44093
+ var localCommandStdoutPattern = /^\s*<local-command-stdout>([\s\S]*)<\/local-command-stdout>\s*$/u;
44094
+ function isLocalCommandRecord(text) {
44095
+ return localCommandRecordPattern.test(text);
44096
+ }
44097
+ function isTaskNotificationRecord(text) {
44098
+ return taskNotificationRecordPattern.test(text);
44099
+ }
44100
+ function isControlCommandEnvelope(text) {
44101
+ return commandEnvelopePattern.test(text) && controlCommandNamePattern.test(text);
44102
+ }
44103
+ function isNamedCommandEnvelope(text, namePattern) {
44104
+ return commandEnvelopePattern.test(text) && namePattern.test(text);
44105
+ }
44106
+ function displayedUserText(text) {
44107
+ if (isNamedCommandEnvelope(text, initCommandNamePattern))
44108
+ return "/init";
44109
+ if (isNamedCommandEnvelope(text, recapCommandNamePattern))
44110
+ return "/recap";
44111
+ return text;
44112
+ }
44113
+ function localCommandStdoutText(text) {
44114
+ const match = localCommandStdoutPattern.exec(text);
44115
+ if (!match)
44116
+ return null;
44117
+ return match[1] ?? "";
44118
+ }
44119
+ function isTaskNotificationOrigin(value) {
44120
+ return isRecord5(value.origin) && value.origin.kind === "task-notification";
44121
+ }
44122
+ function visibleUserTextParts(message) {
44123
+ if (message.type !== "user" || message.syntheticUser)
44124
+ return [];
44125
+ const parts = textParts(message.message.content);
44126
+ if (parts.some(isControlCommandEnvelope))
44127
+ return [];
44128
+ return parts.filter((part) => !isLocalCommandRecord(part) && !isTaskNotificationRecord(part));
44129
+ }
44130
+ function isInterruptionRecord(value, promptId) {
44131
+ if (value.type !== "user" || promptId === null || value.promptId !== promptId || value.promptSource !== void 0 || !isRecord5(value.message))
44132
+ return false;
44133
+ const content = value.message.content;
44134
+ if (!Array.isArray(content) || content.length !== 1)
44135
+ return false;
44136
+ const part = content[0];
44137
+ return isRecord5(part) && part.type === "text" && (part.text === "[Request interrupted by user]" || part.text === "[Request interrupted by user for tool use]");
44138
+ }
44139
+ function conversationMessages(values, sessionId) {
44140
+ const messages = [];
44141
+ const ids = /* @__PURE__ */ new Set();
44142
+ let promptId = null;
44143
+ for (const value of values) {
44144
+ if (!isRecord5(value))
44145
+ throw new Error("Claude history contains a malformed message");
44146
+ if (value.type === "system")
44147
+ continue;
44148
+ if (value.type !== "user" && value.type !== "assistant" || typeof value.uuid !== "string" || value.uuid.length === 0 || value.session_id !== sessionId || !isRecord5(value.message) || value.message.role !== value.type) {
44149
+ throw new Error("Claude history contains an invalid message identity");
44150
+ }
44151
+ if (ids.has(value.uuid))
44152
+ throw new Error("Claude history contains duplicate message IDs");
44153
+ ids.add(value.uuid);
44154
+ const interrupted = isInterruptionRecord(value, promptId);
44155
+ const message = {
44156
+ type: value.type,
44157
+ uuid: value.uuid,
44158
+ message: value.message,
44159
+ nested: typeof value.parent_tool_use_id === "string" && value.parent_tool_use_id.length > 0,
44160
+ interrupted,
44161
+ syntheticUser: value.type === "user" && (interrupted || value.isSynthetic === true || value.isMeta === true || isTaskNotificationOrigin(value) || value.toolUseResult !== void 0 && value.toolUseResult !== null)
44162
+ };
44163
+ messages.push(message);
44164
+ if (isHumanUser(message)) {
44165
+ promptId = typeof value.promptId === "string" && value.promptId.length > 0 ? value.promptId : null;
44166
+ }
44167
+ }
44168
+ return messages;
44169
+ }
44170
+ function isHumanUser(message) {
44171
+ return visibleUserTextParts(message).length > 0;
44172
+ }
44173
+ function turnOutcome(messages) {
44174
+ if (messages.some(({ interrupted }) => interrupted))
44175
+ return { status: "cancelled", reason: "Cancelled by user" };
44176
+ const assistants = messages.filter(({ type }) => type === "assistant");
44177
+ const failed = assistants.some(({ message }) => typeof message.error === "string");
44178
+ if (failed) {
44179
+ return {
44180
+ status: "failed",
44181
+ error: {
44182
+ code: "nativeFailure",
44183
+ message: "Claude Assistant failed",
44184
+ retryable: false
44185
+ }
44186
+ };
44187
+ }
44188
+ const final = assistants.at(-1);
44189
+ if (!final)
44190
+ return { status: "unknown", reason: "Claude history has no Assistant terminal" };
44191
+ return {
44192
+ status: "unknown",
44193
+ reason: "Claude history does not include complete Result terminal evidence"
44194
+ };
44195
+ }
44196
+ function itemOutcome(outcome) {
44197
+ if (outcome.status === "failed")
44198
+ return { status: "failed", error: outcome.error };
44199
+ if (outcome.status === "cancelled") {
44200
+ return {
44201
+ status: "cancelled",
44202
+ ...outcome.reason ? { reason: outcome.reason } : {}
44203
+ };
44204
+ }
44205
+ return { status: "succeeded" };
44206
+ }
44207
+ function mapClaudeSnapshot(values, sessionId) {
44208
+ const messages = conversationMessages(values, sessionId);
44209
+ const turns = [];
44210
+ for (let index = 0; index < messages.length; ) {
44211
+ const user = messages[index];
44212
+ if (!user || !isHumanUser(user)) {
44213
+ index += 1;
44214
+ continue;
44215
+ }
44216
+ let end = index + 1;
44217
+ while (end < messages.length && !isHumanUser(messages[end]))
44218
+ end += 1;
44219
+ const turnMessages = messages.slice(index, end);
44220
+ const outcome = turnOutcome(turnMessages);
44221
+ const results = toolResultBlocks(turnMessages);
44222
+ const checkpointMessage = turnMessages.findLast(({ type, interrupted }) => type === "assistant" || interrupted);
44223
+ let agentMessageOrdinal = 0;
44224
+ let reasoningOrdinal = 0;
44225
+ let toolOrdinal = 0;
44226
+ turns.push({
44227
+ nativeTurnRef: nativeTurnRefSchema.parse({
44228
+ harnessId: claudeCodeHarnessId,
44229
+ nativeSessionId: sessionId,
44230
+ nativeTurnKey: user.uuid,
44231
+ formatVersion: 1
44232
+ }),
44233
+ ...checkpointMessage ? {
44234
+ checkpoint: nativeCheckpointRefSchema.parse({
44235
+ harnessId: claudeCodeHarnessId,
44236
+ nativeSessionId: sessionId,
44237
+ checkpointId: checkpointMessage.uuid,
44238
+ formatVersion: 1
44239
+ })
44240
+ } : {},
44241
+ input: visibleUserTextParts(user).map((text) => ({
44242
+ type: "text",
44243
+ text: displayedUserText(text)
44244
+ })),
44245
+ items: turnMessages.flatMap((message) => {
44246
+ if (message.type === "user") {
44247
+ const recapOutput = visibleUserTextParts(user).some((text2) => isNamedCommandEnvelope(text2, recapCommandNamePattern)) ? textParts(message.message.content).map(localCommandStdoutText).find((text2) => text2 !== null && text2.length > 0) : void 0;
44248
+ if (!recapOutput)
44249
+ return [];
44250
+ return [
44251
+ {
44252
+ item: {
44253
+ type: "agentMessage",
44254
+ itemId: claudeTranscriptItemId(user.uuid, "agentMessage", agentMessageOrdinal += 1),
44255
+ text: recapOutput
44256
+ },
44257
+ outcome: itemOutcome(outcome)
44258
+ }
44259
+ ];
44260
+ }
44261
+ if (message.type !== "assistant")
44262
+ return [];
44263
+ const content = message.message.content;
44264
+ const text = textParts(content).join("");
44265
+ const reasoning = thinkingParts(content).join("");
44266
+ if (!Array.isArray(content)) {
44267
+ return text.length > 0 ? [
44268
+ {
44269
+ item: {
44270
+ type: "agentMessage",
44271
+ itemId: claudeTranscriptItemId(user.uuid, "agentMessage", agentMessageOrdinal += 1),
44272
+ text
44273
+ },
44274
+ outcome: itemOutcome(outcome)
44275
+ }
44276
+ ] : [];
44277
+ }
44278
+ const items = [];
44279
+ let projectedReasoning = false;
44280
+ let projectedText = false;
44281
+ for (const [blockIndex, block] of content.entries()) {
44282
+ if (!isRecord5(block))
44283
+ continue;
44284
+ if (block.type === "thinking" && !projectedReasoning && reasoning.length > 0) {
44285
+ items.push({
44286
+ item: {
44287
+ type: "reasoning",
44288
+ itemId: claudeTranscriptItemId(user.uuid, "reasoning", reasoningOrdinal += 1),
44289
+ text: reasoning
44290
+ },
44291
+ outcome: itemOutcome(outcome)
44292
+ });
44293
+ projectedReasoning = true;
44294
+ continue;
44295
+ }
44296
+ if (block.type === "text" && !projectedText && text.length > 0) {
44297
+ items.push({
44298
+ item: {
44299
+ type: "agentMessage",
44300
+ itemId: claudeTranscriptItemId(user.uuid, "agentMessage", agentMessageOrdinal += 1),
44301
+ text
44302
+ },
44303
+ outcome: itemOutcome(outcome)
44304
+ });
44305
+ projectedText = true;
44306
+ continue;
44307
+ }
44308
+ if (block.type !== "tool_use" || typeof block.id !== "string" || typeof block.name !== "string") {
44309
+ continue;
44310
+ }
44311
+ const toolItem = !message.nested && !CLAUDE_SUBAGENT_TOOLS.has(block.name) ? toolOrdinal += 1 : null;
44312
+ const result = results.get(block.id);
44313
+ if (!result)
44314
+ continue;
44315
+ const output = toolResultOutput(result);
44316
+ const failed = result.is_error === true;
44317
+ const toolOutcome = failed ? {
44318
+ status: "failed",
44319
+ error: {
44320
+ code: "nativeFailure",
44321
+ message: `${block.name} failed`,
44322
+ retryable: false
44323
+ }
44324
+ } : { status: "succeeded" };
44325
+ const itemId = toolItem !== null ? claudeTranscriptItemId(user.uuid, "tool", toolItem) : hostItemIdSchema.parse(`claude-item-v1-${message.uuid}-tool-${blockIndex}`);
44326
+ if (block.name === "Bash" && isRecord5(block.input) && typeof block.input.command === "string") {
44327
+ items.push({
44328
+ item: {
44329
+ type: "commandExecution",
44330
+ itemId,
44331
+ command: block.input.command,
44332
+ ...output ? { output } : {}
44333
+ },
44334
+ outcome: toolOutcome
44335
+ });
44336
+ continue;
44337
+ }
44338
+ const argumentsResult = jsonValueSchema.safeParse(block.input);
44339
+ items.push({
44340
+ item: {
44341
+ type: "toolExecution",
44342
+ itemId,
44343
+ toolName: block.name,
44344
+ arguments: argumentsResult.success ? argumentsResult.data : null,
44345
+ ...output ? { output: { content: [{ type: "text", text: output }] } } : {}
44346
+ },
44347
+ outcome: toolOutcome
44348
+ });
44349
+ }
44350
+ return items;
44351
+ }),
44352
+ outcome
44353
+ });
44354
+ index = end;
44355
+ }
44356
+ return { turns };
44357
+ }
44358
+ function toolResultBlocks(messages) {
44359
+ const results = /* @__PURE__ */ new Map();
44360
+ for (const message of messages) {
44361
+ if (message.type !== "user" || !Array.isArray(message.message.content))
44362
+ continue;
44363
+ for (const block of message.message.content) {
44364
+ if (isRecord5(block) && block.type === "tool_result" && typeof block.tool_use_id === "string") {
44365
+ results.set(block.tool_use_id, block);
44366
+ }
44367
+ }
44368
+ }
44369
+ return results;
44370
+ }
44371
+ function toolResultOutput(block) {
44372
+ if (!block)
44373
+ return void 0;
44374
+ const text = textParts(block.content).join("");
44375
+ return text.length > 0 ? text : void 0;
44376
+ }
44377
+ function resultSubagentId(value, block) {
44378
+ const nativeResult = value.tool_use_result;
44379
+ if (isRecord5(nativeResult)) {
44380
+ const structured = nativeResult.agentId ?? nativeResult.agent_id ?? nativeResult.task_id;
44381
+ if (typeof structured === "string" && structured.length > 0)
44382
+ return structured;
44383
+ }
44384
+ const match = /agentId:\s*([A-Za-z0-9_-]+)/u.exec(textParts(block.content).join(""));
44385
+ return match?.[1];
44386
+ }
44387
+ function subagentPrompt2(values, nativeSubagentId2) {
44388
+ const toolUses = /* @__PURE__ */ new Map();
44389
+ for (const value of values) {
44390
+ if (!isRecord5(value) || !isRecord5(value.message) || !Array.isArray(value.message.content)) {
43315
44391
  continue;
43316
44392
  }
43317
44393
  for (const block of value.message.content) {
43318
- if (!isRecord3(block))
44394
+ if (!isRecord5(block))
43319
44395
  continue;
43320
- if (block.type === "tool_use" && typeof block.id === "string" && (block.name === "Agent" || block.name === "Task") && isRecord3(block.input) && typeof block.input.prompt === "string" && block.input.prompt.length > 0) {
44396
+ if (block.type === "tool_use" && typeof block.id === "string" && (block.name === "Agent" || block.name === "Task") && isRecord5(block.input) && typeof block.input.prompt === "string" && block.input.prompt.length > 0) {
43321
44397
  toolUses.set(block.id, block.input.prompt);
43322
44398
  continue;
43323
44399
  }
@@ -43331,7 +44407,7 @@ function subagentPrompt(values, nativeSubagentId2) {
43331
44407
  return void 0;
43332
44408
  }
43333
44409
  function mapClaudeSubagentSnapshot(values, parentSessionId, nativeSubagentId2, parentValues = []) {
43334
- const messages = conversationMessages(values.map((value) => isRecord3(value) ? { ...value, session_id: parentSessionId } : value), parentSessionId);
44410
+ const messages = conversationMessages(values.map((value) => isRecord5(value) ? { ...value, session_id: parentSessionId } : value), parentSessionId);
43335
44411
  const turns = [];
43336
44412
  for (let index = 0; index < messages.length; ) {
43337
44413
  const first = messages[index];
@@ -43358,7 +44434,7 @@ function mapClaudeSubagentSnapshot(values, parentSessionId, nativeSubagentId2, p
43358
44434
  const content = Array.isArray(message.message.content) ? message.message.content : [{ type: "text", text: message.message.content }];
43359
44435
  for (let blockIndex = 0; blockIndex < content.length; blockIndex += 1) {
43360
44436
  const block = content[blockIndex];
43361
- if (!isRecord3(block))
44437
+ if (!isRecord5(block))
43362
44438
  continue;
43363
44439
  const itemId = hostItemIdSchema.parse(`claude-subagent-item-v2-${nativeSubagentId2}-${message.uuid}-${blockIndex}`);
43364
44440
  if (block.type === "thinking" && typeof block.thinking === "string") {
@@ -43395,7 +44471,7 @@ function mapClaudeSubagentSnapshot(values, parentSessionId, nativeSubagentId2, p
43395
44471
  retryable: false
43396
44472
  }
43397
44473
  } : { status: "succeeded" };
43398
- if (block.name === "Bash" && isRecord3(block.input) && typeof block.input.command === "string") {
44474
+ if (block.name === "Bash" && isRecord5(block.input) && typeof block.input.command === "string") {
43399
44475
  items.push({
43400
44476
  item: {
43401
44477
  type: "commandExecution",
@@ -43437,7 +44513,7 @@ function mapClaudeSubagentSnapshot(values, parentSessionId, nativeSubagentId2, p
43437
44513
  formatVersion: 1
43438
44514
  })
43439
44515
  } : {},
43440
- input: user ? visibleUserTextParts(user).map((text) => ({ type: "text", text })) : turns.length === 0 ? [subagentPrompt(parentValues, nativeSubagentId2)].filter((text) => text !== void 0).map((text) => ({ type: "text", text })) : [],
44516
+ input: user ? visibleUserTextParts(user).map((text) => ({ type: "text", text })) : turns.length === 0 ? [subagentPrompt2(parentValues, nativeSubagentId2)].filter((text) => text !== void 0).map((text) => ({ type: "text", text })) : [],
43441
44517
  items,
43442
44518
  outcome
43443
44519
  });
@@ -43525,7 +44601,7 @@ async function forkClaudeSession(input) {
43525
44601
  error: error51("protocolError", "Claude Code Session working directory is unavailable", false)
43526
44602
  };
43527
44603
  }
43528
- if (path7.resolve(sourceInfo.cwd) !== input.cwd) {
44604
+ if (path10.resolve(sourceInfo.cwd) !== input.cwd) {
43529
44605
  return {
43530
44606
  ok: false,
43531
44607
  error: error51("unsupported", "Claude Code cannot Fork across working directories", false)
@@ -43626,13 +44702,13 @@ async function forkClaudeSession(input) {
43626
44702
 
43627
44703
  // dist/claude-transcript.js
43628
44704
  import os5 from "node:os";
43629
- import path8 from "node:path";
43630
- import { readFile as readFile3, readdir, stat as stat3 } from "node:fs/promises";
44705
+ import path11 from "node:path";
44706
+ import { readFile as readFile4, readdir, stat as stat3 } from "node:fs/promises";
43631
44707
  function projectDirectoryName(cwd) {
43632
44708
  return cwd.replace(/[^A-Za-z0-9]/gu, "-");
43633
44709
  }
43634
44710
  function configDirectory(environment) {
43635
- return environment.CLAUDE_CONFIG_DIR ? path8.resolve(environment.CLAUDE_CONFIG_DIR) : path8.join(os5.homedir(), ".claude");
44711
+ return environment.CLAUDE_CONFIG_DIR ? path11.resolve(environment.CLAUDE_CONFIG_DIR) : path11.join(os5.homedir(), ".claude");
43636
44712
  }
43637
44713
  async function existingFile(file2) {
43638
44714
  try {
@@ -43642,9 +44718,9 @@ async function existingFile(file2) {
43642
44718
  }
43643
44719
  }
43644
44720
  async function findTranscript(input) {
43645
- const projectsDirectory = path8.join(configDirectory(input.environment), "projects");
44721
+ const projectsDirectory = path11.join(configDirectory(input.environment), "projects");
43646
44722
  const name = `${input.sessionId}.jsonl`;
43647
- const expected = path8.join(projectsDirectory, projectDirectoryName(input.cwd), name);
44723
+ const expected = path11.join(projectsDirectory, projectDirectoryName(input.cwd), name);
43648
44724
  if (await existingFile(expected))
43649
44725
  return expected;
43650
44726
  let projects;
@@ -43654,20 +44730,20 @@ async function findTranscript(input) {
43654
44730
  return null;
43655
44731
  }
43656
44732
  for (const project of projects) {
43657
- const candidate = path8.join(projectsDirectory, project, name);
44733
+ const candidate = path11.join(projectsDirectory, project, name);
43658
44734
  if (await existingFile(candidate))
43659
44735
  return candidate;
43660
44736
  }
43661
44737
  return null;
43662
44738
  }
43663
- function isRecord4(value) {
44739
+ function isRecord6(value) {
43664
44740
  return typeof value === "object" && value !== null && !Array.isArray(value);
43665
44741
  }
43666
44742
  async function readClaudeTranscript(input) {
43667
44743
  const transcript = await findTranscript(input);
43668
44744
  if (!transcript)
43669
44745
  return null;
43670
- const contents = await readFile3(transcript, "utf8");
44746
+ const contents = await readFile4(transcript, "utf8");
43671
44747
  const messages = [];
43672
44748
  for (const line of contents.split("\n")) {
43673
44749
  if (line.trim().length === 0)
@@ -43678,7 +44754,7 @@ async function readClaudeTranscript(input) {
43678
44754
  } catch {
43679
44755
  continue;
43680
44756
  }
43681
- if (!isRecord4(entry) || entry.type !== "user" && entry.type !== "assistant" || typeof entry.uuid !== "string" || !isRecord4(entry.message)) {
44757
+ if (!isRecord6(entry) || entry.type !== "user" && entry.type !== "assistant" || typeof entry.uuid !== "string" || !isRecord6(entry.message)) {
43682
44758
  continue;
43683
44759
  }
43684
44760
  messages.push({ ...entry, session_id: input.sessionId });
@@ -43688,9 +44764,9 @@ async function readClaudeTranscript(input) {
43688
44764
 
43689
44765
  // dist/model-catalog.js
43690
44766
  import { Buffer as Buffer2 } from "node:buffer";
43691
- import { readFile as readFile4 } from "node:fs/promises";
44767
+ import { readFile as readFile5 } from "node:fs/promises";
43692
44768
  import os6 from "node:os";
43693
- import path9 from "node:path";
44769
+ import path12 from "node:path";
43694
44770
 
43695
44771
  // dist/thinking-options.js
43696
44772
  var option = (id, label) => ({
@@ -43771,1116 +44847,383 @@ function decodeClaudeModelRef(ref) {
43771
44847
  }
43772
44848
  return value === "default" ? void 0 : value;
43773
44849
  }
43774
- function resolveClaudeConfigDirectory(environment = process.env) {
43775
- return path9.resolve(environment.CLAUDE_CONFIG_DIR ?? path9.join(os6.homedir(), ".claude"));
43776
- }
43777
- function parseModelPickerOptions(value) {
43778
- if (!Array.isArray(value))
43779
- return [];
43780
- const options = [];
43781
- const seen = /* @__PURE__ */ new Set();
43782
- for (const entry of value) {
43783
- const parsed = modelPickerOptionSchema.safeParse(entry);
43784
- if (!parsed.success)
43785
- continue;
43786
- if (seen.has(parsed.data.model))
43787
- continue;
43788
- seen.add(parsed.data.model);
43789
- options.push({
43790
- model: parsed.data.model,
43791
- ...parsed.data.label ? { label: parsed.data.label } : {},
43792
- ...parsed.data.description ? { description: parsed.data.description } : {},
43793
- ...parsed.data.behavesAs ? { behavesAs: parsed.data.behavesAs } : {}
43794
- });
43795
- }
43796
- return options;
43797
- }
43798
- function parseClaudeModelPickerSettings(value) {
43799
- if (value === void 0 || value === null)
43800
- return void 0;
43801
- const parsed = modelPickerSettingsSchema.safeParse(value);
43802
- if (!parsed.success)
43803
- return void 0;
43804
- if (parsed.data.options === void 0 && parsed.data.replaceBuiltInOptions === void 0) {
43805
- return void 0;
43806
- }
43807
- const options = parseModelPickerOptions(parsed.data.options);
43808
- if (Array.isArray(parsed.data.options) && parsed.data.options.length > 0 && options.length === 0) {
43809
- return void 0;
43810
- }
43811
- return {
43812
- options,
43813
- replaceBuiltInOptions: parsed.data.replaceBuiltInOptions === true
43814
- };
43815
- }
43816
- async function readClaudeUserModelPicker(environment = process.env) {
43817
- const settingsPath = path9.join(resolveClaudeConfigDirectory(environment), "settings.json");
43818
- let raw;
43819
- try {
43820
- raw = await readFile4(settingsPath, "utf8");
43821
- } catch {
43822
- return void 0;
43823
- }
43824
- let document2;
43825
- try {
43826
- document2 = JSON.parse(raw);
43827
- } catch {
43828
- return void 0;
43829
- }
43830
- if (document2 === null || typeof document2 !== "object" || Array.isArray(document2)) {
43831
- return void 0;
43832
- }
43833
- return parseClaudeModelPickerSettings(document2.modelPicker);
43834
- }
43835
- function optionToModelInfo(option2) {
43836
- return {
43837
- value: option2.model,
43838
- displayName: option2.label ?? option2.model,
43839
- ...option2.description ? { description: option2.description } : {},
43840
- ...option2.behavesAs ? { resolvedModel: option2.behavesAs } : {}
43841
- };
43842
- }
43843
- function readModelValue(row) {
43844
- if (row === null || typeof row !== "object" || Array.isArray(row))
43845
- return void 0;
43846
- const value = row.value;
43847
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
43848
- }
43849
- function mergeOptionOntoSdkRow(sdkRow, option2) {
43850
- const base = sdkRow !== null && typeof sdkRow === "object" && !Array.isArray(sdkRow) ? { ...sdkRow } : {};
43851
- const overlay = optionToModelInfo(option2);
43852
- return { ...base, ...overlay };
43853
- }
43854
- function mergeClaudeModelPickerOptions(sdkModels, modelPicker) {
43855
- if (!modelPicker)
43856
- return sdkModels;
43857
- const sdkRows = Array.isArray(sdkModels) ? [...sdkModels] : [];
43858
- const sdkByValue = /* @__PURE__ */ new Map();
43859
- for (const row of sdkRows) {
43860
- const value = readModelValue(row);
43861
- if (value && !sdkByValue.has(value))
43862
- sdkByValue.set(value, row);
43863
- }
43864
- if (modelPicker.replaceBuiltInOptions) {
43865
- const defaultSdk = sdkByValue.get("default");
43866
- const merged2 = [
43867
- defaultSdk !== void 0 ? defaultSdk : { value: "default", displayName: "Default" }
43868
- ];
43869
- const included2 = /* @__PURE__ */ new Set(["default"]);
43870
- for (const option2 of modelPicker.options) {
43871
- if (included2.has(option2.model)) {
43872
- if (option2.model === "default") {
43873
- merged2[0] = mergeOptionOntoSdkRow(merged2[0], option2);
43874
- }
43875
- continue;
43876
- }
43877
- merged2.push(mergeOptionOntoSdkRow(sdkByValue.get(option2.model), option2));
43878
- included2.add(option2.model);
43879
- }
43880
- return merged2;
43881
- }
43882
- const merged = [...sdkRows];
43883
- const included = new Set(sdkRows.flatMap((row) => {
43884
- const value = readModelValue(row);
43885
- return value ? [value] : [];
43886
- }));
43887
- for (const option2 of modelPicker.options) {
43888
- if (included.has(option2.model))
43889
- continue;
43890
- merged.push(mergeOptionOntoSdkRow(void 0, option2));
43891
- included.add(option2.model);
43892
- }
43893
- return merged;
43894
- }
43895
- function uniqueDisplayLabels(rows) {
43896
- const groups = /* @__PURE__ */ new Map();
43897
- for (const row of rows) {
43898
- const group = groups.get(row.displayName) ?? [];
43899
- group.push(row);
43900
- groups.set(row.displayName, group);
43901
- }
43902
- const labels = /* @__PURE__ */ new Map();
43903
- for (const [displayName, group] of groups) {
43904
- const sorted = [...group].sort((left, right) => left.value.localeCompare(right.value));
43905
- for (const [index, row] of sorted.entries()) {
43906
- if (sorted.length === 1) {
43907
- labels.set(row.value, displayName);
43908
- continue;
43909
- }
43910
- const nativeSuffix = ` (${row.value})`;
43911
- const suffix = displayName.length + nativeSuffix.length <= HARNESS_MODEL_LABEL_MAX_LENGTH ? nativeSuffix : ` (alias ${index + 1})`;
43912
- labels.set(row.value, `${displayName.slice(0, HARNESS_MODEL_LABEL_MAX_LENGTH - suffix.length)}${suffix}`);
43913
- }
43914
- }
43915
- return labels;
43916
- }
43917
- function normalizeRows(value) {
43918
- if (!Array.isArray(value))
43919
- throw new Error("Claude Code Model catalog is not an array");
43920
- const byValue = /* @__PURE__ */ new Map();
43921
- for (const nativeRow of value) {
43922
- const row = modelInfoSchema.parse(nativeRow);
43923
- const existing = byValue.get(row.value);
43924
- if (existing && JSON.stringify(existing) !== JSON.stringify(row)) {
43925
- throw new Error("Claude Code Model catalog contains conflicting selectable values");
43926
- }
43927
- if (!existing)
43928
- byValue.set(row.value, row);
43929
- }
43930
- if (byValue.size === 0)
43931
- throw new Error("Claude Code Model catalog is empty");
43932
- if (!byValue.has("default")) {
43933
- byValue.set("default", { value: "default", displayName: "Default" });
43934
- }
43935
- return [...byValue.values()];
43936
- }
43937
- function normalizeClaudeModelCatalog(snapshot) {
43938
- if (!snapshot.canSelectModel)
43939
- throw new Error("Claude Code Model selection is unavailable");
43940
- const rows = normalizeRows(snapshot.models);
43941
- const labels = uniqueDisplayLabels(rows);
43942
- const models = rows.map((row) => {
43943
- return {
43944
- ref: encodeClaudeModelRef(row.value),
43945
- label: labels.get(row.value) ?? row.displayName,
43946
- ...row.resolvedModel ? { resolvedModelLabel: row.resolvedModel } : {},
43947
- supportedThinkingOptionIds: [...CLAUDE_THINKING_OPTION_IDS]
43948
- };
43949
- });
43950
- models.sort((left, right) => {
43951
- if (left.ref.id === CLAUDE_DEFAULT_MODEL_REF.id)
43952
- return -1;
43953
- if (right.ref.id === CLAUDE_DEFAULT_MODEL_REF.id)
43954
- return 1;
43955
- return left.label.localeCompare(right.label) || left.ref.id.localeCompare(right.ref.id);
43956
- });
43957
- const catalog = harnessModelCatalogSchema.parse({
43958
- models,
43959
- defaultModel: CLAUDE_DEFAULT_MODEL_REF,
43960
- thinkingOptions: [...CLAUDE_THINKING_OPTIONS],
43961
- defaultThinkingOptionId: CLAUDE_DEFAULT_THINKING_OPTION_ID
43962
- });
43963
- return { catalog, defaultModel: CLAUDE_DEFAULT_MODEL_REF };
43964
- }
43965
-
43966
- // dist/permission-modes.js
43967
- var nativePermissionModes = /* @__PURE__ */ new Set([
43968
- "plan",
43969
- "default",
43970
- "acceptEdits",
43971
- "auto",
43972
- "bypassPermissions"
43973
- ]);
43974
- var CLAUDE_DEFAULT_PERMISSION_MODE_ID = harnessPermissionModeIdSchema.parse("default");
43975
- var claudePermissionModes = [
43976
- {
43977
- id: "plan",
43978
- label: "Plan mode",
43979
- description: "Explore and prepare a plan; approval exits planning and resumes the previous permission mode."
43980
- },
43981
- {
43982
- id: "default",
43983
- label: "Default",
43984
- description: "Ask before edits and other protected actions."
43985
- },
43986
- {
43987
- id: "acceptEdits",
43988
- label: "Accept edits",
43989
- description: "Allow file edits and ask for other protected actions."
43990
- },
43991
- {
43992
- id: "auto",
43993
- label: "Auto mode",
43994
- description: "Let Claude classify permission requests."
43995
- },
43996
- {
43997
- id: "bypassPermissions",
43998
- label: "Bypass permissions",
43999
- description: "Skip Claude Code permission checks.",
44000
- dangerous: true
44001
- }
44002
- ];
44003
- function createPermissionModeCatalog(includeAuto) {
44004
- return harnessPermissionModeCatalogSchema.parse({
44005
- modes: includeAuto ? claudePermissionModes : claudePermissionModes.filter(({ id }) => id !== "auto"),
44006
- defaultModeId: CLAUDE_DEFAULT_PERMISSION_MODE_ID
44007
- });
44008
- }
44009
- var CLAUDE_PERMISSION_MODE_CATALOG = createPermissionModeCatalog(true);
44010
- var CLAUDE_PERMISSION_MODE_CATALOG_WITHOUT_AUTO = createPermissionModeCatalog(false);
44011
- var autoModeModelInfoSchema = external_exports.object({ supportsAutoMode: external_exports.literal(true) });
44012
- function claudePermissionModeCatalogForModels(models) {
44013
- const supportsAutoMode = Array.isArray(models) && models.some((model) => autoModeModelInfoSchema.safeParse(model).success);
44014
- return supportsAutoMode ? CLAUDE_PERMISSION_MODE_CATALOG : CLAUDE_PERMISSION_MODE_CATALOG_WITHOUT_AUTO;
44015
- }
44016
- function decodeClaudePermissionModeId(permissionModeId) {
44017
- const parsed = harnessPermissionModeIdSchema.parse(permissionModeId);
44018
- if (!nativePermissionModes.has(parsed)) {
44019
- throw new Error("Claude Code Permission Mode belongs to another Adapter");
44020
- }
44021
- return parsed;
44022
- }
44023
- function encodeClaudePermissionModeId(permissionMode) {
44024
- if (!nativePermissionModes.has(permissionMode)) {
44025
- throw new Error("Claude Code returned an unsupported Permission Mode");
44026
- }
44027
- return harnessPermissionModeIdSchema.parse(permissionMode);
44028
- }
44029
- function isClaudePermissionMode(value) {
44030
- return typeof value === "string" && nativePermissionModes.has(value);
44031
- }
44032
-
44033
- // dist/sdk-transport.js
44034
- import { spawn } from "node:child_process";
44035
-
44036
- // dist/slash-commands.js
44037
- var DYNAMIC_ID_PREFIX = "claude.slash.";
44038
- var CLAUDE_EXCLUDED_COMMANDS = [
44039
- "advisor",
44040
- "agents",
44041
- "design-consent",
44042
- "design-revoke",
44043
- "doctor",
44044
- "extra-usage",
44045
- "import",
44046
- "team-onboarding",
44047
- "ultrareview",
44048
- "usage-credits",
44049
- "workflow-launch-exec"
44050
- ];
44051
- function parseClaudeSlashCommands(value) {
44052
- if (!Array.isArray(value))
44053
- return [];
44054
- return value.flatMap((entry) => {
44055
- if (typeof entry !== "object" || entry === null)
44056
- return [];
44057
- const record2 = entry;
44058
- const name = typeof record2.name === "string" ? record2.name.trim().replace(/^\//u, "") : "";
44059
- if (!name)
44060
- return [];
44061
- return [
44062
- {
44063
- name,
44064
- description: typeof record2.description === "string" ? record2.description : "",
44065
- argumentHint: typeof record2.argumentHint === "string" ? record2.argumentHint : ""
44066
- }
44067
- ];
44068
- });
44069
- }
44070
- function claudeLiveCommandCatalog(builtIns, snapshot) {
44071
- return mergeLiveHarnessCommands(builtIns, DYNAMIC_ID_PREFIX, snapshot?.commands.map((command) => ({
44072
- name: command.name,
44073
- description: command.description,
44074
- kind: snapshot.skillNames.has(command.name) ? "skill" : "command"
44075
- })) ?? null, { names: CLAUDE_EXCLUDED_COMMANDS });
44076
- }
44077
- function claudeDynamicCommandPrompt(catalog, commandId, argumentText) {
44078
- return liveHarnessCommandPrompt(catalog, DYNAMIC_ID_PREFIX, commandId, argumentText);
44079
- }
44080
-
44081
- // dist/account-usage.js
44082
- function projectClaudeAccountUsage(usage, account) {
44083
- if (!usage.rate_limits_available || !usage.rate_limits)
44084
- return null;
44085
- const limits = usage.rate_limits;
44086
- const windows = [];
44087
- const add = (product, periodType, value) => {
44088
- if (!value || typeof value.utilization !== "number" || !Number.isFinite(value.utilization) || value.utilization < 0 || value.utilization > 100)
44089
- return;
44090
- windows.push({
44091
- product,
44092
- periodType,
44093
- usagePercent: value.utilization,
44094
- ...value.resets_at && Number.isFinite(Date.parse(value.resets_at)) ? { resetsAt: value.resets_at } : {}
44095
- });
44096
- };
44097
- add("5-hour window", "five_hour", limits.five_hour);
44098
- add("7-day window", "seven_day", limits.seven_day);
44099
- add("OAuth apps · 7-day", "seven_day", limits.seven_day_oauth_apps);
44100
- add("Opus · 7-day", "seven_day", limits.seven_day_opus);
44101
- add("Sonnet · 7-day", "seven_day", limits.seven_day_sonnet);
44102
- for (const window2 of limits.model_scoped ?? [])
44103
- add(`${window2.display_name} · 7-day`, "seven_day", window2);
44104
- const [primary, ...others] = windows;
44105
- if (!primary)
44106
- return null;
44107
- const genericPrimary = primary.product === "5-hour window" || primary.product === "7-day window";
44108
- return {
44109
- ...account.email ? { email: account.email } : {},
44110
- ...usage.subscription_type ? { plan: usage.subscription_type } : {},
44111
- credits: {
44112
- usedPercent: primary.usagePercent,
44113
- periodType: primary.periodType,
44114
- ...!genericPrimary ? { label: primary.product } : {},
44115
- ...primary.resetsAt ? { resetsAt: primary.resetsAt } : {},
44116
- ...others.length ? {
44117
- productUsage: others.map(({ product, usagePercent, resetsAt }) => ({
44118
- product,
44119
- usagePercent,
44120
- ...resetsAt ? { resetsAt } : {}
44121
- }))
44122
- } : {}
44123
- }
44124
- };
44125
- }
44126
-
44127
- // dist/file-change.js
44128
- import path10 from "node:path";
44129
- var hunkSchema = external_exports.object({
44130
- oldStart: external_exports.number().int().nonnegative(),
44131
- oldLines: external_exports.number().int().nonnegative(),
44132
- newStart: external_exports.number().int().nonnegative(),
44133
- newLines: external_exports.number().int().nonnegative(),
44134
- lines: external_exports.array(external_exports.string())
44135
- }).strict();
44136
- function isRecord5(value) {
44137
- return typeof value === "object" && value !== null && !Array.isArray(value);
44138
- }
44139
- function validNativePath(value) {
44140
- return typeof value === "string" && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
44141
- }
44142
- function countLines(lines, prefixes) {
44143
- return lines.filter((line) => line.length > 0 && prefixes.has(line[0])).length;
44144
- }
44145
- function validHunk(value) {
44146
- const parsed = hunkSchema.safeParse(value);
44147
- if (!parsed.success)
44148
- return null;
44149
- const hunk = parsed.data;
44150
- if (hunk.lines.some((line) => line.length === 0 || ![" ", "+", "-", "\\"].includes(line[0]))) {
44151
- return null;
44152
- }
44153
- if (countLines(hunk.lines, /* @__PURE__ */ new Set([" ", "-"])) !== hunk.oldLines)
44154
- return null;
44155
- if (countLines(hunk.lines, /* @__PURE__ */ new Set([" ", "+"])) !== hunk.newLines)
44156
- return null;
44157
- return hunk;
44158
- }
44159
- function parseClaudeNativeFileChange(toolName, value) {
44160
- if (toolName !== "Edit" && toolName !== "Write" || !isRecord5(value))
44161
- return null;
44162
- if (!validNativePath(value.filePath) || !Array.isArray(value.structuredPatch))
44163
- return null;
44164
- const hunks = value.structuredPatch.map(validHunk);
44165
- if (hunks.length === 0 || hunks.some((hunk) => hunk === null))
44166
- return null;
44167
- if (toolName === "Write" && value.type !== "create" && value.type !== "update")
44168
- return null;
44169
- return {
44170
- path: value.filePath,
44171
- kind: toolName === "Write" && value.type === "create" ? "add" : "update",
44172
- hunks
44173
- };
44174
- }
44175
- function displayPath(nativePath, cwd) {
44176
- const resolvedCwd = path10.resolve(cwd);
44177
- const resolvedPath = path10.isAbsolute(nativePath) ? path10.resolve(nativePath) : path10.resolve(cwd, nativePath);
44178
- const relative = path10.relative(resolvedCwd, resolvedPath);
44179
- const selected = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`) ? relative : resolvedPath;
44180
- const normalized = selected.replaceAll("\\", "/");
44181
- return validNativePath(normalized) && normalized !== "." ? normalized : null;
44182
- }
44183
- function projectClaudeFileChange(value, cwd) {
44184
- const normalizedPath = displayPath(value.path, cwd);
44185
- if (!normalizedPath)
44186
- return null;
44187
- const body = value.hunks.flatMap((hunk) => [
44188
- `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,
44189
- ...hunk.lines
44190
- ]);
44191
- const absoluteDisplayPath = path10.posix.isAbsolute(normalizedPath);
44192
- const oldHeader = value.kind === "add" ? "/dev/null" : absoluteDisplayPath ? normalizedPath : `a/${normalizedPath}`;
44193
- const newHeader = absoluteDisplayPath ? normalizedPath : `b/${normalizedPath}`;
44194
- const unifiedDiff = [`--- ${oldHeader}`, `+++ ${newHeader}`, ...body, ""].join("\n");
44195
- return { path: normalizedPath, kind: value.kind, unifiedDiff };
44196
- }
44197
-
44198
- // dist/native-message.js
44199
- var ABORTED_TERMINALS = /* @__PURE__ */ new Set(["aborted_streaming", "aborted_tools"]);
44200
- var AUTHENTICATION_ERRORS = /* @__PURE__ */ new Set(["authentication_failed", "oauth_org_not_allowed"]);
44201
- var SUBAGENT_TOOLS = /* @__PURE__ */ new Set(["Agent", "Task", "SendMessage"]);
44202
- var SUBAGENT_DESCRIPTION_LIMIT = 500;
44203
- var SUBAGENT_SUMMARY_LIMIT = 2e3;
44204
- function isRecord6(value) {
44205
- return typeof value === "object" && value !== null && !Array.isArray(value);
44206
- }
44207
- function nativeUuid(message) {
44208
- return typeof message.uuid === "string" && message.uuid.length > 0 ? message.uuid : null;
44209
- }
44210
- function parentToolUseId(message) {
44211
- return typeof message.parent_tool_use_id === "string" && message.parent_tool_use_id.length > 0 ? message.parent_tool_use_id : null;
44212
- }
44213
- function assistantNativeMessageId(message) {
44214
- if (!isRecord6(message.message))
44215
- return null;
44216
- return typeof message.message.id === "string" && message.message.id.length > 0 ? message.message.id : null;
44217
- }
44218
- function assistantContent(message) {
44219
- if (message.type !== "assistant" || !isRecord6(message.message))
44220
- return null;
44221
- return Array.isArray(message.message.content) ? message.message.content : null;
44222
- }
44223
- function assistantText(message) {
44224
- const content = assistantContent(message);
44225
- if (!content)
44226
- return null;
44227
- return content.flatMap((block) => isRecord6(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("");
44228
- }
44229
- function assistantError(message) {
44230
- return isRecord6(message) && message.type === "assistant" && typeof message.error === "string" ? message.error : null;
44231
- }
44232
- function boundedString(value, limit) {
44233
- if (typeof value !== "string")
44234
- return void 0;
44235
- const trimmed = value.trim();
44236
- if (trimmed.length === 0)
44237
- return void 0;
44238
- return trimmed.slice(0, limit);
44239
- }
44240
- function subagentDescription(argumentsValue, toolName) {
44241
- if (!isRecord6(argumentsValue))
44242
- return `${toolName} delegation`;
44243
- return boundedString(argumentsValue.description, SUBAGENT_DESCRIPTION_LIMIT) ?? boundedString(argumentsValue.summary, SUBAGENT_DESCRIPTION_LIMIT) ?? boundedString(argumentsValue.name, SUBAGENT_DESCRIPTION_LIMIT) ?? `${toolName} delegation`;
44850
+ function resolveClaudeConfigDirectory(environment = process.env) {
44851
+ return path12.resolve(environment.CLAUDE_CONFIG_DIR ?? path12.join(os6.homedir(), ".claude"));
44244
44852
  }
44245
- function subagentPrompt2(argumentsValue) {
44246
- if (!isRecord6(argumentsValue))
44247
- return void 0;
44248
- return boundedString(argumentsValue.prompt ?? argumentsValue.message, SUBAGENT_SUMMARY_LIMIT);
44853
+ function parseModelPickerOptions(value) {
44854
+ if (!Array.isArray(value))
44855
+ return [];
44856
+ const options = [];
44857
+ const seen = /* @__PURE__ */ new Set();
44858
+ for (const entry of value) {
44859
+ const parsed = modelPickerOptionSchema.safeParse(entry);
44860
+ if (!parsed.success)
44861
+ continue;
44862
+ if (seen.has(parsed.data.model))
44863
+ continue;
44864
+ seen.add(parsed.data.model);
44865
+ options.push({
44866
+ model: parsed.data.model,
44867
+ ...parsed.data.label ? { label: parsed.data.label } : {},
44868
+ ...parsed.data.description ? { description: parsed.data.description } : {},
44869
+ ...parsed.data.behavesAs ? { behavesAs: parsed.data.behavesAs } : {}
44870
+ });
44871
+ }
44872
+ return options;
44249
44873
  }
44250
- function subagentRole(argumentsValue) {
44251
- if (!isRecord6(argumentsValue))
44874
+ function parseClaudeModelPickerSettings(value) {
44875
+ if (value === void 0 || value === null)
44252
44876
  return void 0;
44253
- return boundedString(argumentsValue.subagent_type ?? argumentsValue.agent_type, SUBAGENT_DESCRIPTION_LIMIT);
44254
- }
44255
- function subagentBackground(argumentsValue) {
44256
- return isRecord6(argumentsValue) && argumentsValue.run_in_background === true;
44257
- }
44258
- function targetedSubagentId(argumentsValue) {
44259
- if (!isRecord6(argumentsValue))
44877
+ const parsed = modelPickerSettingsSchema.safeParse(value);
44878
+ if (!parsed.success)
44260
44879
  return void 0;
44261
- return boundedString(argumentsValue.to ?? argumentsValue.recipient ?? argumentsValue.agentId, SUBAGENT_DESCRIPTION_LIMIT);
44262
- }
44263
- function includesAuthenticationFailure(message, errors) {
44264
- if (errors.some((error52) => AUTHENTICATION_ERRORS.has(error52)))
44265
- return true;
44266
- const text = [message.result, ...Array.isArray(message.errors) ? message.errors : []].filter((value) => typeof value === "string").join(" ").toLowerCase();
44267
- return text.includes("not logged in") || text.includes("invalid api key") || text.includes("oauth");
44268
- }
44269
- function failure(kind) {
44270
- return { status: "failed", kind };
44271
- }
44272
- function safeNonNegativeInteger(value) {
44273
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
44274
- }
44275
- function finiteNonNegativeNumber(value) {
44276
- return typeof value === "number" && Number.isFinite(value) && value >= 0;
44277
- }
44278
- function parseResultModelUsage(value) {
44279
- if (!isRecord6(value))
44880
+ if (parsed.data.options === void 0 && parsed.data.replaceBuiltInOptions === void 0) {
44280
44881
  return void 0;
44281
- const usage = [];
44282
- for (const entry of Object.values(value)) {
44283
- if (!isRecord6(entry) || !safeNonNegativeInteger(entry.inputTokens) || !safeNonNegativeInteger(entry.outputTokens)) {
44284
- return void 0;
44285
- }
44286
- usage.push({ inputTokens: entry.inputTokens, outputTokens: entry.outputTokens });
44287
44882
  }
44288
- return usage;
44289
- }
44290
- function parseLastRequestUsage(value, attribution = {}) {
44291
- if (!isRecord6(value))
44292
- return void 0;
44293
- const inputTokens = value.input_tokens;
44294
- const outputTokens = value.output_tokens;
44295
- const cacheCreationInputTokens = value.cache_creation_input_tokens;
44296
- const cacheReadInputTokens = value.cache_read_input_tokens;
44297
- if (!safeNonNegativeInteger(inputTokens) || !safeNonNegativeInteger(outputTokens) || !safeNonNegativeInteger(cacheCreationInputTokens) || !safeNonNegativeInteger(cacheReadInputTokens)) {
44883
+ const options = parseModelPickerOptions(parsed.data.options);
44884
+ if (Array.isArray(parsed.data.options) && parsed.data.options.length > 0 && options.length === 0) {
44298
44885
  return void 0;
44299
44886
  }
44300
- const requestId = boundedString(attribution.requestId, 500);
44301
- const model = boundedString(attribution.model, 500);
44302
- const provider = boundedString(attribution.provider, 100);
44303
44887
  return {
44304
- ...requestId ? { requestId } : {},
44305
- ...model ? { model } : {},
44306
- ...provider ? { provider } : {},
44307
- inputTokens,
44308
- outputTokens,
44309
- cacheCreationInputTokens,
44310
- cacheReadInputTokens
44888
+ options,
44889
+ replaceBuiltInOptions: parsed.data.replaceBuiltInOptions === true
44311
44890
  };
44312
44891
  }
44313
- function assistantRequestUsage(message, provider) {
44314
- if (!isRecord6(message.message))
44892
+ async function readClaudeUserModelPicker(environment = process.env) {
44893
+ const settingsPath = path12.join(resolveClaudeConfigDirectory(environment), "settings.json");
44894
+ let raw;
44895
+ try {
44896
+ raw = await readFile5(settingsPath, "utf8");
44897
+ } catch {
44315
44898
  return void 0;
44316
- return parseLastRequestUsage(message.message.usage, {
44317
- requestId: message.message.id ?? message.request_id,
44318
- model: message.message.model,
44319
- provider: message.provider ?? message.message.provider ?? provider
44320
- });
44321
- }
44322
- function parseResultUsageEvent(message) {
44323
- const totalCostUsd = finiteNonNegativeNumber(message.total_cost_usd) ? message.total_cost_usd : void 0;
44324
- const modelUsage = parseResultModelUsage(message.modelUsage);
44325
- const lastRequestUsage = parseLastRequestUsage(message.usage);
44326
- if (totalCostUsd === void 0 && modelUsage === void 0 && lastRequestUsage === void 0) {
44327
- return null;
44328
44899
  }
44329
- return {
44330
- type: "usage.result",
44331
- ...totalCostUsd !== void 0 ? { totalCostUsd } : {},
44332
- ...modelUsage !== void 0 ? { modelUsage } : {},
44333
- ...lastRequestUsage ? { lastRequestUsage } : {}
44334
- };
44335
- }
44336
- function parsePlanLimitWindow(value) {
44337
- if (!isRecord6(value))
44900
+ let document2;
44901
+ try {
44902
+ document2 = JSON.parse(raw);
44903
+ } catch {
44338
44904
  return void 0;
44339
- const utilization = value.utilization;
44340
- if (typeof utilization !== "number" || !Number.isFinite(utilization) || utilization < 0) {
44905
+ }
44906
+ if (document2 === null || typeof document2 !== "object" || Array.isArray(document2)) {
44341
44907
  return void 0;
44342
44908
  }
44343
- const utilizationPercent = Math.min(100, Math.max(0, Math.round(utilization * 1e4) / 100));
44344
- const resetsAt = value.resetsAt;
44345
- const resetsAtUnix = safeNonNegativeInteger(resetsAt) ? resetsAt : void 0;
44346
- return { utilizationPercent, ...resetsAtUnix !== void 0 ? { resetsAtUnix } : {} };
44909
+ return parseClaudeModelPickerSettings(document2.modelPicker);
44347
44910
  }
44348
- function parseClaudePlanLimitEvent(message) {
44349
- if (!isRecord6(message) || message.type !== "rate_limit_event")
44350
- return null;
44351
- const info = message.rate_limit_info;
44352
- if (!isRecord6(info))
44353
- return null;
44354
- const windows = isRecord6(info.unifiedWindows) ? info.unifiedWindows : void 0;
44355
- let fiveHour = parsePlanLimitWindow(windows?.five_hour);
44356
- let sevenDay = parsePlanLimitWindow(windows?.seven_day);
44357
- if (!fiveHour && !sevenDay) {
44358
- const flatWindow = parsePlanLimitWindow(info);
44359
- if (flatWindow && info.rateLimitType === "five_hour")
44360
- fiveHour = flatWindow;
44361
- else if (flatWindow && info.rateLimitType === "seven_day")
44362
- sevenDay = flatWindow;
44363
- }
44364
- if (!fiveHour && !sevenDay)
44365
- return null;
44911
+ function optionToModelInfo(option2) {
44366
44912
  return {
44367
- ...fiveHour ? { fiveHour } : {},
44368
- ...sevenDay ? { sevenDay } : {}
44913
+ value: option2.model,
44914
+ displayName: option2.label ?? option2.model,
44915
+ ...option2.description ? { description: option2.description } : {},
44916
+ ...option2.behavesAs ? { resolvedModel: option2.behavesAs } : {}
44369
44917
  };
44370
44918
  }
44371
- function nativeSubagentId(nativeResult, outputText) {
44372
- if (isRecord6(nativeResult)) {
44373
- const structured = boundedString(nativeResult.agentId ?? nativeResult.agent_id ?? nativeResult.task_id, SUBAGENT_DESCRIPTION_LIMIT);
44374
- if (structured)
44375
- return structured;
44376
- }
44377
- return boundedString(/agentId:\s*([A-Za-z0-9_-]+)/u.exec(outputText ?? "")?.[1], SUBAGENT_DESCRIPTION_LIMIT);
44378
- }
44379
- function subagentContinuesInBackground(nativeResult, outputText) {
44380
- if (isRecord6(nativeResult)) {
44381
- if (nativeResult.isAsync === true || nativeResult.is_async === true)
44382
- return true;
44383
- if (nativeResult.status === "async_launched")
44384
- return true;
44385
- }
44386
- return outputText?.includes("The agent is working in the background.") ?? false;
44387
- }
44388
- function resultText(content, nativeResult) {
44389
- let text = "";
44390
- if (typeof content === "string") {
44391
- text = content;
44392
- } else if (Array.isArray(content)) {
44393
- text = content.flatMap((block) => isRecord6(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("");
44394
- }
44395
- if (text.length > 0)
44396
- return text;
44397
- if (!isRecord6(nativeResult))
44919
+ function readModelValue(row) {
44920
+ if (row === null || typeof row !== "object" || Array.isArray(row))
44398
44921
  return void 0;
44399
- const stdout = typeof nativeResult.stdout === "string" ? nativeResult.stdout : "";
44400
- const stderr = typeof nativeResult.stderr === "string" ? nativeResult.stderr : "";
44401
- const combined = stdout + stderr;
44402
- return combined.length > 0 ? combined : void 0;
44403
- }
44404
- function userMessageText(content) {
44405
- if (typeof content === "string")
44406
- return content;
44407
- if (!Array.isArray(content))
44408
- return null;
44409
- const text = content.flatMap((block) => isRecord6(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("");
44410
- return text.length > 0 ? text : null;
44411
- }
44412
- function parseClaudeTaskNotification(message) {
44413
- if (!isRecord6(message) || message.type !== "user" || !isRecord6(message.message))
44414
- return null;
44415
- if (isRecord6(message.origin) && message.origin.kind !== "task-notification")
44416
- return null;
44417
- const content = userMessageText(message.message.content);
44418
- if (!content || !content.includes("<task-notification>"))
44419
- return null;
44420
- const taskId = content.match(/<task-id>([^<]+)<\/task-id>/u)?.[1]?.trim();
44421
- if (!taskId)
44422
- return null;
44423
- const xmlStatus = content.match(/<status>([^<]+)<\/status>/u)?.[1]?.trim();
44424
- const status = taskStatus(xmlStatus ?? "completed");
44425
- if (status !== "completed" && status !== "failed" && status !== "interrupted")
44426
- return null;
44427
- const summary = content.match(/<summary>([\s\S]*?)<\/summary>/u)?.[1]?.trim();
44428
- const callId = content.match(/<tool-use-id>([^<]+)<\/tool-use-id>/u)?.[1]?.trim();
44429
- return {
44430
- type: "subagent.settled",
44431
- nativeSubagentId: taskId,
44432
- status,
44433
- ...callId ? { callId } : {},
44434
- ...summary ? { resultSummary: summary.slice(0, SUBAGENT_SUMMARY_LIMIT) } : {}
44435
- };
44922
+ const value = row.value;
44923
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
44436
44924
  }
44437
- function taskStatus(value) {
44438
- switch (value) {
44439
- case "pending":
44440
- return "pending";
44441
- case "running":
44442
- return "running";
44443
- case "completed":
44444
- return "completed";
44445
- case "failed":
44446
- return "failed";
44447
- case "killed":
44448
- case "stopped":
44449
- return "interrupted";
44450
- default:
44451
- return null;
44452
- }
44925
+ function mergeOptionOntoSdkRow(sdkRow, option2) {
44926
+ const base = sdkRow !== null && typeof sdkRow === "object" && !Array.isArray(sdkRow) ? { ...sdkRow } : {};
44927
+ const overlay = optionToModelInfo(option2);
44928
+ return { ...base, ...overlay };
44453
44929
  }
44454
- var ClaudeNativeTurnAccumulator = class {
44455
- #provider;
44456
- #activeRootStreamMessageId = null;
44457
- #assistantErrors = [];
44458
- #cancelRequested = false;
44459
- #compactionState = "idle";
44460
- #completed = false;
44461
- #completedToolIds = /* @__PURE__ */ new Set();
44462
- #messageOrdinal = 0;
44463
- #messages = /* @__PURE__ */ new Map();
44464
- #protocolConflict = false;
44465
- #textConflict = false;
44466
- #tools = /* @__PURE__ */ new Map();
44467
- constructor(options = {}) {
44468
- this.#provider = options.provider;
44469
- }
44470
- requestCancel() {
44471
- this.#cancelRequested = true;
44472
- }
44473
- consume(message) {
44474
- if (this.#completed || !isRecord6(message))
44475
- return { events: [] };
44476
- const events = [];
44477
- this.#consumeSegmentLevel(message, events);
44478
- this.#consumeTaskLifecycle(message, events);
44479
- const parentCallId = parentToolUseId(message);
44480
- const nested = parentCallId !== null;
44481
- if (parentCallId && this.#tools.get(parentCallId)?.subagent === true && (message.type === "assistant" || message.type === "user")) {
44482
- events.push({ type: "subagent.transcript.changed", callId: parentCallId });
44483
- }
44484
- if (!nested) {
44485
- this.#consumeCompaction(message, events);
44486
- this.#consumeLocalCommandOutput(message, events);
44487
- }
44488
- if (message.type === "stream_event" && isRecord6(message.event)) {
44489
- if (!nested)
44490
- this.#consumeStreamEvent(message, events);
44491
- } else if (message.type === "tool_progress") {
44492
- this.#consumeToolProgress(message, events);
44493
- }
44494
- if (!nested) {
44495
- const error52 = assistantError(message);
44496
- if (error52 !== null)
44497
- this.#assistantErrors.push(error52);
44498
- }
44499
- if (message.type === "assistant") {
44500
- if (!nested)
44501
- this.#consumeAssistantMessage(message, events);
44502
- } else if (message.type === "user") {
44503
- this.#consumeTaskNotification(message, events);
44504
- this.#consumeToolResults(message, events, nested);
44505
- }
44506
- if (message.type !== "result")
44507
- return { events };
44508
- const usageEvent = parseResultUsageEvent(message);
44509
- if (usageEvent)
44510
- events.push(usageEvent);
44511
- this.#completed = true;
44512
- const terminalReason = typeof message.terminal_reason === "string" ? message.terminal_reason : "missing";
44513
- const nativeSuccess = message.subtype === "success" && message.is_error === false && (terminalReason === "completed" || terminalReason === "missing") && this.#assistantErrors.length === 0;
44514
- if (nativeSuccess && this.#tools.size > 0)
44515
- this.#protocolConflict = true;
44516
- let terminal;
44517
- if (this.#protocolConflict) {
44518
- terminal = failure("protocol");
44519
- } else if (this.#textConflict) {
44520
- terminal = failure("textConflict");
44521
- } else if (includesAuthenticationFailure(message, this.#assistantErrors)) {
44522
- terminal = failure("authentication");
44523
- } else if (this.#cancelRequested && ABORTED_TERMINALS.has(terminalReason)) {
44524
- terminal = { status: "cancelled", reason: terminalReason };
44525
- } else if (this.#cancelRequested) {
44526
- terminal = failure("cancellationUnproven");
44527
- } else if (nativeSuccess) {
44528
- terminal = { status: "succeeded" };
44529
- } else {
44530
- terminal = failure("native");
44531
- }
44532
- return { events, terminal };
44533
- }
44534
- #consumeCompaction(message, events) {
44535
- if (message.type !== "system")
44536
- return;
44537
- if (message.subtype === "status") {
44538
- if (message.status === "compacting" && this.#compactionState !== "active") {
44539
- this.#compactionState = "active";
44540
- events.push({ type: "compaction.started" });
44541
- }
44542
- if (message.compact_result === "success" || message.compact_result === "failed") {
44543
- if (this.#compactionState === "settled")
44544
- return;
44545
- if (this.#compactionState === "idle")
44546
- events.push({ type: "compaction.started" });
44547
- this.#compactionState = "settled";
44548
- events.push({
44549
- type: "compaction.completed",
44550
- outcome: message.compact_result === "success" ? "succeeded" : "failed"
44551
- });
44552
- }
44553
- return;
44554
- }
44555
- if (message.subtype !== "compact_boundary" || this.#compactionState === "settled")
44556
- return;
44557
- if (this.#compactionState === "idle")
44558
- events.push({ type: "compaction.started" });
44559
- this.#compactionState = "settled";
44560
- events.push({ type: "compaction.completed", outcome: "succeeded" });
44561
- }
44562
- #consumeLocalCommandOutput(message, events) {
44563
- if (message.type !== "system" || message.subtype !== "local_command_output")
44564
- return;
44565
- if (typeof message.content !== "string" || message.content.length === 0)
44566
- return;
44567
- const checkpointId = nativeUuid(message);
44568
- const messageId = checkpointId ?? this.#nextMessageId();
44569
- const state = this.#messageState(messageId);
44570
- if (state.completed)
44571
- return;
44572
- state.text += message.content;
44573
- events.push({ type: "text.delta", messageId, delta: message.content });
44574
- state.completed = true;
44575
- events.push({
44576
- type: "message.completed",
44577
- messageId,
44578
- ...checkpointId ? { checkpointId } : {}
44579
- });
44580
- }
44581
- /**
44582
- * Claude opens one native Segment per Root execution and reports its live
44583
- * background tasks as a level whose membership replaces the previous set.
44584
- */
44585
- #consumeSegmentLevel(message, events) {
44586
- if (message.type !== "system")
44587
- return;
44588
- if (message.subtype === "init") {
44589
- events.push({ type: "segment.started" });
44590
- return;
44591
- }
44592
- if (message.subtype !== "background_tasks_changed" || !Array.isArray(message.tasks))
44593
- return;
44594
- const nativeSubagentIds = message.tasks.flatMap((task) => {
44595
- if (!isRecord6(task))
44596
- return [];
44597
- const taskId = boundedString(task.task_id, SUBAGENT_DESCRIPTION_LIMIT);
44598
- return taskId ? [taskId] : [];
44599
- });
44600
- events.push({ type: "subagents.live", nativeSubagentIds });
44601
- }
44602
- #consumeTaskLifecycle(message, events) {
44603
- if (message.type !== "system")
44604
- return;
44605
- if (message.subtype === "task_notification") {
44606
- const agentId = boundedString(message.task_id, SUBAGENT_DESCRIPTION_LIMIT);
44607
- const status = taskStatus(message.status);
44608
- if (!agentId || status !== "completed" && status !== "failed" && status !== "interrupted") {
44609
- return;
44610
- }
44611
- const resultSummary = boundedString(message.summary, SUBAGENT_SUMMARY_LIMIT);
44612
- const callId2 = boundedString(message.tool_use_id, SUBAGENT_DESCRIPTION_LIMIT);
44613
- events.push({
44614
- type: "subagent.settled",
44615
- nativeSubagentId: agentId,
44616
- status,
44617
- ...callId2 ? { callId: callId2 } : {},
44618
- ...resultSummary ? { resultSummary } : {}
44619
- });
44620
- return;
44621
- }
44622
- const callId = typeof message.tool_use_id === "string" ? message.tool_use_id : null;
44623
- if (!callId || !this.#tools.get(callId)?.subagent)
44624
- return;
44625
- if (message.subtype === "task_started") {
44626
- const description = boundedString(message.description, SUBAGENT_DESCRIPTION_LIMIT);
44627
- const role = boundedString(message.subagent_type, SUBAGENT_DESCRIPTION_LIMIT);
44628
- const agentId = boundedString(message.task_id, SUBAGENT_DESCRIPTION_LIMIT);
44629
- events.push({
44630
- type: "subagent.updated",
44631
- callId,
44632
- status: "running",
44633
- ...description ? { description } : {},
44634
- ...role ? { role } : {},
44635
- ...agentId ? { nativeSubagentId: agentId } : {}
44636
- });
44637
- return;
44638
- }
44639
- if (message.subtype === "task_progress") {
44640
- const description = boundedString(message.description, SUBAGENT_DESCRIPTION_LIMIT);
44641
- const role = boundedString(message.subagent_type, SUBAGENT_DESCRIPTION_LIMIT);
44642
- const resultSummary = boundedString(message.summary, SUBAGENT_SUMMARY_LIMIT);
44643
- const agentId = boundedString(message.task_id, SUBAGENT_DESCRIPTION_LIMIT);
44644
- events.push({
44645
- type: "subagent.updated",
44646
- callId,
44647
- status: "running",
44648
- ...description ? { description } : {},
44649
- ...role ? { role } : {},
44650
- ...agentId ? { nativeSubagentId: agentId } : {},
44651
- ...resultSummary ? { resultSummary } : {}
44652
- });
44653
- return;
44654
- }
44655
- if (message.subtype === "task_updated" && isRecord6(message.patch)) {
44656
- const status = taskStatus(message.patch.status);
44657
- if (!status)
44658
- return;
44659
- const description = boundedString(message.patch.description, SUBAGENT_DESCRIPTION_LIMIT);
44660
- const resultSummary = boundedString(message.patch.error, SUBAGENT_SUMMARY_LIMIT);
44661
- const agentId = boundedString(message.task_id, SUBAGENT_DESCRIPTION_LIMIT);
44662
- events.push({
44663
- type: "subagent.updated",
44664
- callId,
44665
- status,
44666
- ...description ? { description } : {},
44667
- ...agentId ? { nativeSubagentId: agentId } : {},
44668
- ...resultSummary ? { resultSummary } : {}
44669
- });
44670
- }
44671
- }
44672
- #consumeStreamEvent(message, events) {
44673
- const event = message.event;
44674
- if (!isRecord6(event))
44675
- return;
44676
- if (event.type === "message_start" && isRecord6(event.message) && typeof event.message.id === "string" && event.message.id.length > 0) {
44677
- this.#activeRootStreamMessageId = event.message.id;
44678
- this.#messageState(event.message.id);
44679
- return;
44680
- }
44681
- if (event.type !== "content_block_delta" || !isRecord6(event.delta))
44682
- return;
44683
- const messageId = this.#activeRootStreamMessageId ?? nativeUuid(message) ?? this.#nextMessageId();
44684
- if (!this.#activeRootStreamMessageId)
44685
- this.#activeRootStreamMessageId = messageId;
44686
- const state = this.#messageState(messageId);
44687
- if (state.completed) {
44688
- if (event.delta.type === "text_delta")
44689
- this.#textConflict = true;
44690
- return;
44691
- }
44692
- if (event.delta.type === "text_delta" && typeof event.delta.text === "string") {
44693
- if (event.delta.text.length === 0)
44694
- return;
44695
- state.text += event.delta.text;
44696
- events.push({ type: "text.delta", messageId, delta: event.delta.text });
44697
- return;
44698
- }
44699
- if (event.delta.type === "thinking_delta" && typeof event.delta.thinking === "string") {
44700
- if (event.delta.thinking.length === 0)
44701
- return;
44702
- state.reasoning += event.delta.thinking;
44703
- events.push({ type: "reasoning.delta", messageId, delta: event.delta.thinking });
44704
- }
44705
- }
44706
- #consumeAssistantMessage(message, events) {
44707
- const checkpointId = nativeUuid(message);
44708
- const nativeMessageId = assistantNativeMessageId(message);
44709
- const messageId = this.#activeRootStreamMessageId ?? nativeMessageId ?? checkpointId ?? this.#nextMessageId();
44710
- const state = this.#messageState(messageId);
44711
- if (state.completed) {
44712
- this.#consumeToolUseBlocks(message, events, true);
44713
- const usage = assistantRequestUsage(message, this.#provider);
44714
- if (usage && !state.usagePublished) {
44715
- state.usagePublished = true;
44716
- events.push({
44717
- type: "message.completed",
44718
- messageId,
44719
- ...checkpointId ? { checkpointId } : {},
44720
- lastRequestUsage: usage
44721
- });
44722
- }
44723
- return;
44724
- }
44725
- if (state.reasoning.length > 0) {
44726
- events.push({ type: "reasoning.completed", messageId });
44727
- }
44728
- const completeText = assistantText(message);
44729
- if (completeText !== null && completeText.length > 0) {
44730
- if (completeText.startsWith(state.text)) {
44731
- const suffix = completeText.slice(state.text.length);
44732
- if (suffix.length > 0) {
44733
- state.text += suffix;
44734
- events.push({ type: "text.delta", messageId, delta: suffix });
44735
- }
44736
- } else if (completeText !== state.text) {
44737
- this.#textConflict = true;
44738
- }
44739
- }
44740
- this.#consumeToolUseBlocks(message, events, false);
44741
- if (!this.#protocolConflict && !this.#textConflict) {
44742
- const usage = assistantRequestUsage(message, this.#provider);
44743
- state.usagePublished = usage !== void 0;
44744
- events.push({
44745
- type: "message.completed",
44746
- messageId,
44747
- ...checkpointId ? { checkpointId } : {},
44748
- ...usage ? { lastRequestUsage: usage } : {}
44749
- });
44750
- }
44751
- state.completed = true;
44752
- if (this.#activeRootStreamMessageId === messageId)
44753
- this.#activeRootStreamMessageId = null;
44930
+ function mergeClaudeModelPickerOptions(sdkModels, modelPicker) {
44931
+ if (!modelPicker)
44932
+ return sdkModels;
44933
+ const sdkRows = Array.isArray(sdkModels) ? [...sdkModels] : [];
44934
+ const sdkByValue = /* @__PURE__ */ new Map();
44935
+ for (const row of sdkRows) {
44936
+ const value = readModelValue(row);
44937
+ if (value && !sdkByValue.has(value))
44938
+ sdkByValue.set(value, row);
44754
44939
  }
44755
- #consumeToolUseBlocks(message, events, ignoreKnownIds) {
44756
- for (const block of assistantContent(message) ?? []) {
44757
- if (!isRecord6(block) || block.type !== "tool_use")
44758
- continue;
44759
- const argumentsResult = jsonValueSchema.safeParse(block.input);
44760
- if (typeof block.id !== "string" || block.id.length === 0 || typeof block.name !== "string" || block.name.length === 0 || !argumentsResult.success) {
44761
- this.#protocolConflict = true;
44762
- continue;
44763
- }
44764
- if (this.#tools.has(block.id) || this.#completedToolIds.has(block.id)) {
44765
- if (!ignoreKnownIds)
44766
- this.#protocolConflict = true;
44940
+ if (modelPicker.replaceBuiltInOptions) {
44941
+ const defaultSdk = sdkByValue.get("default");
44942
+ const merged2 = [
44943
+ defaultSdk !== void 0 ? defaultSdk : { value: "default", displayName: "Default" }
44944
+ ];
44945
+ const included2 = /* @__PURE__ */ new Set(["default"]);
44946
+ for (const option2 of modelPicker.options) {
44947
+ if (included2.has(option2.model)) {
44948
+ if (option2.model === "default") {
44949
+ merged2[0] = mergeOptionOntoSdkRow(merged2[0], option2);
44950
+ }
44767
44951
  continue;
44768
44952
  }
44769
- const subagent = SUBAGENT_TOOLS.has(block.name);
44770
- this.#tools.set(block.id, { name: block.name, subagent });
44771
- if (subagent) {
44772
- const prompt = subagentPrompt2(argumentsResult.data);
44773
- const role = subagentRole(argumentsResult.data);
44774
- const agentId = targetedSubagentId(argumentsResult.data);
44775
- events.push({
44776
- type: "subagent.started",
44777
- callId: block.id,
44778
- operation: block.name === "SendMessage" ? "send" : "spawn",
44779
- description: subagentDescription(argumentsResult.data, block.name),
44780
- ...prompt ? { prompt } : {},
44781
- ...role ? { role } : {},
44782
- background: block.name === "SendMessage" || subagentBackground(argumentsResult.data),
44783
- ...agentId ? { nativeSubagentId: agentId } : {}
44784
- });
44785
- } else {
44786
- events.push({
44787
- type: "tool.started",
44788
- callId: block.id,
44789
- toolName: block.name,
44790
- arguments: argumentsResult.data
44791
- });
44792
- }
44953
+ merged2.push(mergeOptionOntoSdkRow(sdkByValue.get(option2.model), option2));
44954
+ included2.add(option2.model);
44793
44955
  }
44956
+ return merged2;
44794
44957
  }
44795
- #consumeToolProgress(message, events) {
44796
- const callId = message.tool_use_id;
44797
- const elapsedSeconds = message.elapsed_time_seconds;
44798
- if (typeof callId !== "string" || this.#tools.get(callId)?.subagent !== false || typeof elapsedSeconds !== "number" || !Number.isFinite(elapsedSeconds) || elapsedSeconds < 0) {
44799
- return;
44800
- }
44801
- events.push({ type: "tool.progress", callId, elapsedMs: Math.round(elapsedSeconds * 1e3) });
44958
+ const merged = [...sdkRows];
44959
+ const included = new Set(sdkRows.flatMap((row) => {
44960
+ const value = readModelValue(row);
44961
+ return value ? [value] : [];
44962
+ }));
44963
+ for (const option2 of modelPicker.options) {
44964
+ if (included.has(option2.model))
44965
+ continue;
44966
+ merged.push(mergeOptionOntoSdkRow(void 0, option2));
44967
+ included.add(option2.model);
44802
44968
  }
44803
- #consumeTaskNotification(message, events) {
44804
- const settled = parseClaudeTaskNotification(message);
44805
- if (settled)
44806
- events.push(settled);
44969
+ return merged;
44970
+ }
44971
+ function uniqueDisplayLabels(rows) {
44972
+ const groups = /* @__PURE__ */ new Map();
44973
+ for (const row of rows) {
44974
+ const group = groups.get(row.displayName) ?? [];
44975
+ group.push(row);
44976
+ groups.set(row.displayName, group);
44807
44977
  }
44808
- #consumeToolResults(message, events, ignoreUnknown) {
44809
- if (!isRecord6(message.message) || !Array.isArray(message.message.content))
44810
- return;
44811
- const resultBlocks = message.message.content.filter((block) => isRecord6(block) && block.type === "tool_result");
44812
- if (resultBlocks.length === 0)
44813
- return;
44814
- if (resultBlocks.length > 1 && message.tool_use_result !== void 0) {
44815
- this.#protocolConflict = true;
44816
- }
44817
- for (const block of resultBlocks) {
44818
- const callId = block.tool_use_id;
44819
- if (typeof callId !== "string" || callId.length === 0) {
44820
- this.#protocolConflict = true;
44821
- continue;
44822
- }
44823
- const tool = this.#tools.get(callId);
44824
- if (!tool || this.#completedToolIds.has(callId)) {
44825
- if (!ignoreUnknown)
44826
- this.#protocolConflict = true;
44827
- continue;
44828
- }
44829
- if (block.is_error !== void 0 && typeof block.is_error !== "boolean") {
44830
- this.#protocolConflict = true;
44831
- continue;
44832
- }
44833
- this.#tools.delete(callId);
44834
- this.#completedToolIds.add(callId);
44835
- const isError = block.is_error === true;
44836
- const nativeResult = resultBlocks.length === 1 ? message.tool_use_result ?? message.toolUseResult : void 0;
44837
- const outputText = resultText(block.content, nativeResult);
44838
- const structuredResult = tool.name === "TaskCreate" || tool.name === "TaskUpdate" || tool.name === "TaskList" ? jsonValueSchema.safeParse(nativeResult) : null;
44839
- if (tool.subagent) {
44840
- const resultSummary = boundedString(outputText, SUBAGENT_SUMMARY_LIMIT);
44841
- const agentId = nativeSubagentId(nativeResult, outputText);
44842
- events.push({
44843
- type: "subagent.completed",
44844
- callId,
44845
- isError,
44846
- ...subagentContinuesInBackground(nativeResult, outputText) ? { continuesInBackground: true } : {},
44847
- ...agentId ? { nativeSubagentId: agentId } : {},
44848
- ...resultSummary ? { resultSummary } : {}
44849
- });
44978
+ const labels = /* @__PURE__ */ new Map();
44979
+ for (const [displayName, group] of groups) {
44980
+ const sorted = [...group].sort((left, right) => left.value.localeCompare(right.value));
44981
+ for (const [index, row] of sorted.entries()) {
44982
+ if (sorted.length === 1) {
44983
+ labels.set(row.value, displayName);
44850
44984
  continue;
44851
44985
  }
44852
- const fileChange = isError ? null : parseClaudeNativeFileChange(tool.name, nativeResult);
44853
- events.push({
44854
- type: "tool.completed",
44855
- callId,
44856
- toolName: tool.name,
44857
- ...outputText ? { outputText } : {},
44858
- ...structuredResult?.success ? { structuredResult: structuredResult.data } : {},
44859
- isError,
44860
- ...fileChange ? { fileChange } : {}
44861
- });
44986
+ const nativeSuffix = ` (${row.value})`;
44987
+ const suffix = displayName.length + nativeSuffix.length <= HARNESS_MODEL_LABEL_MAX_LENGTH ? nativeSuffix : ` (alias ${index + 1})`;
44988
+ labels.set(row.value, `${displayName.slice(0, HARNESS_MODEL_LABEL_MAX_LENGTH - suffix.length)}${suffix}`);
44862
44989
  }
44863
44990
  }
44864
- #messageState(messageId) {
44865
- const existing = this.#messages.get(messageId);
44866
- if (existing)
44867
- return existing;
44868
- const created = { completed: false, reasoning: "", text: "", usagePublished: false };
44869
- this.#messages.set(messageId, created);
44870
- return created;
44991
+ return labels;
44992
+ }
44993
+ function normalizeRows(value) {
44994
+ if (!Array.isArray(value))
44995
+ throw new Error("Claude Code Model catalog is not an array");
44996
+ const byValue = /* @__PURE__ */ new Map();
44997
+ for (const nativeRow of value) {
44998
+ const row = modelInfoSchema.parse(nativeRow);
44999
+ const existing = byValue.get(row.value);
45000
+ if (existing && JSON.stringify(existing) !== JSON.stringify(row)) {
45001
+ throw new Error("Claude Code Model catalog contains conflicting selectable values");
45002
+ }
45003
+ if (!existing)
45004
+ byValue.set(row.value, row);
44871
45005
  }
44872
- #nextMessageId() {
44873
- this.#messageOrdinal += 1;
44874
- return `claude-assistant-${this.#messageOrdinal}`;
45006
+ if (byValue.size === 0)
45007
+ throw new Error("Claude Code Model catalog is empty");
45008
+ if (!byValue.has("default")) {
45009
+ byValue.set("default", { value: "default", displayName: "Default" });
45010
+ }
45011
+ return [...byValue.values()];
45012
+ }
45013
+ function normalizeClaudeModelCatalog(snapshot) {
45014
+ if (!snapshot.canSelectModel)
45015
+ throw new Error("Claude Code Model selection is unavailable");
45016
+ const rows = normalizeRows(snapshot.models);
45017
+ const labels = uniqueDisplayLabels(rows);
45018
+ const models = rows.map((row) => {
45019
+ return {
45020
+ ref: encodeClaudeModelRef(row.value),
45021
+ label: labels.get(row.value) ?? row.displayName,
45022
+ ...row.resolvedModel ? { resolvedModelLabel: row.resolvedModel } : {},
45023
+ supportedThinkingOptionIds: [...CLAUDE_THINKING_OPTION_IDS]
45024
+ };
45025
+ });
45026
+ models.sort((left, right) => {
45027
+ if (left.ref.id === CLAUDE_DEFAULT_MODEL_REF.id)
45028
+ return -1;
45029
+ if (right.ref.id === CLAUDE_DEFAULT_MODEL_REF.id)
45030
+ return 1;
45031
+ return left.label.localeCompare(right.label) || left.ref.id.localeCompare(right.ref.id);
45032
+ });
45033
+ const catalog = harnessModelCatalogSchema.parse({
45034
+ models,
45035
+ defaultModel: CLAUDE_DEFAULT_MODEL_REF,
45036
+ thinkingOptions: [...CLAUDE_THINKING_OPTIONS],
45037
+ defaultThinkingOptionId: CLAUDE_DEFAULT_THINKING_OPTION_ID
45038
+ });
45039
+ return { catalog, defaultModel: CLAUDE_DEFAULT_MODEL_REF };
45040
+ }
45041
+
45042
+ // dist/permission-modes.js
45043
+ var nativePermissionModes = /* @__PURE__ */ new Set([
45044
+ "plan",
45045
+ "default",
45046
+ "acceptEdits",
45047
+ "auto",
45048
+ "bypassPermissions"
45049
+ ]);
45050
+ var CLAUDE_DEFAULT_PERMISSION_MODE_ID = harnessPermissionModeIdSchema.parse("default");
45051
+ var claudePermissionModes = [
45052
+ {
45053
+ id: "plan",
45054
+ label: "Plan mode",
45055
+ description: "Explore and prepare a plan; approval exits planning and resumes the previous permission mode."
45056
+ },
45057
+ {
45058
+ id: "default",
45059
+ label: "Default",
45060
+ description: "Ask before edits and other protected actions."
45061
+ },
45062
+ {
45063
+ id: "acceptEdits",
45064
+ label: "Accept edits",
45065
+ description: "Allow file edits and ask for other protected actions."
45066
+ },
45067
+ {
45068
+ id: "auto",
45069
+ label: "Auto mode",
45070
+ description: "Let Claude classify permission requests."
45071
+ },
45072
+ {
45073
+ id: "bypassPermissions",
45074
+ label: "Bypass permissions",
45075
+ description: "Skip Claude Code permission checks.",
45076
+ dangerous: true
44875
45077
  }
45078
+ ];
45079
+ function createPermissionModeCatalog(includeAuto, includeBypassPermissions) {
45080
+ return harnessPermissionModeCatalogSchema.parse({
45081
+ modes: claudePermissionModes.filter(({ id }) => (includeAuto || id !== "auto") && (includeBypassPermissions || id !== "bypassPermissions")),
45082
+ defaultModeId: CLAUDE_DEFAULT_PERMISSION_MODE_ID
45083
+ });
45084
+ }
45085
+ var CLAUDE_PERMISSION_MODE_CATALOG = createPermissionModeCatalog(true, true);
45086
+ var CLAUDE_PERMISSION_MODE_CATALOGS = {
45087
+ auto: CLAUDE_PERMISSION_MODE_CATALOG,
45088
+ autoWithoutBypass: createPermissionModeCatalog(true, false),
45089
+ withoutAuto: createPermissionModeCatalog(false, true),
45090
+ withoutAutoOrBypass: createPermissionModeCatalog(false, false)
44876
45091
  };
45092
+ var autoModeModelInfoSchema = external_exports.object({ supportsAutoMode: external_exports.literal(true) });
45093
+ function claudePermissionModeCatalogForModels(models, bypassPermissionsAvailable = true) {
45094
+ const supportsAutoMode = Array.isArray(models) && models.some((model) => autoModeModelInfoSchema.safeParse(model).success);
45095
+ if (supportsAutoMode) {
45096
+ return bypassPermissionsAvailable ? CLAUDE_PERMISSION_MODE_CATALOGS.auto : CLAUDE_PERMISSION_MODE_CATALOGS.autoWithoutBypass;
45097
+ }
45098
+ return bypassPermissionsAvailable ? CLAUDE_PERMISSION_MODE_CATALOGS.withoutAuto : CLAUDE_PERMISSION_MODE_CATALOGS.withoutAutoOrBypass;
45099
+ }
45100
+ function claudeBypassPermissionsAvailable(environment, platform = process) {
45101
+ const uid = platform.getuid?.();
45102
+ if (uid === void 0 || uid !== 0)
45103
+ return true;
45104
+ return environment.IS_SANDBOX === "1" || isNativeTruthyFlag(environment.CLAUDE_CODE_BUBBLEWRAP);
45105
+ }
45106
+ function isNativeTruthyFlag(value) {
45107
+ return ["1", "true", "yes", "on"].includes(value?.trim().toLowerCase() ?? "");
45108
+ }
45109
+ var CLAUDE_BYPASS_PERMISSIONS_UNAVAILABLE_MESSAGE = "Bypass permissions is unavailable because Claude Code runs as root without a declared sandbox; set IS_SANDBOX=1 for the codexhost Host and restart it";
45110
+ function decodeClaudePermissionModeId(permissionModeId) {
45111
+ const parsed = harnessPermissionModeIdSchema.parse(permissionModeId);
45112
+ if (!nativePermissionModes.has(parsed)) {
45113
+ throw new Error("Claude Code Permission Mode belongs to another Adapter");
45114
+ }
45115
+ return parsed;
45116
+ }
45117
+ function encodeClaudePermissionModeId(permissionMode) {
45118
+ if (!nativePermissionModes.has(permissionMode)) {
45119
+ throw new Error("Claude Code returned an unsupported Permission Mode");
45120
+ }
45121
+ return harnessPermissionModeIdSchema.parse(permissionMode);
45122
+ }
45123
+ function isClaudePermissionMode(value) {
45124
+ return typeof value === "string" && nativePermissionModes.has(value);
45125
+ }
45126
+
45127
+ // dist/sdk-transport.js
45128
+ import { spawn } from "node:child_process";
45129
+
45130
+ // dist/slash-commands.js
45131
+ var DYNAMIC_ID_PREFIX = "claude.slash.";
45132
+ var CLAUDE_EXCLUDED_COMMANDS = [
45133
+ "advisor",
45134
+ "agents",
45135
+ "design-consent",
45136
+ "design-revoke",
45137
+ "doctor",
45138
+ "extra-usage",
45139
+ "import",
45140
+ "team-onboarding",
45141
+ "ultrareview",
45142
+ "usage-credits",
45143
+ "workflow-launch-exec"
45144
+ ];
45145
+ function parseClaudeSlashCommands(value) {
45146
+ if (!Array.isArray(value))
45147
+ return [];
45148
+ return value.flatMap((entry) => {
45149
+ if (typeof entry !== "object" || entry === null)
45150
+ return [];
45151
+ const record2 = entry;
45152
+ const name = typeof record2.name === "string" ? record2.name.trim().replace(/^\//u, "") : "";
45153
+ if (!name)
45154
+ return [];
45155
+ return [
45156
+ {
45157
+ name,
45158
+ description: typeof record2.description === "string" ? record2.description : "",
45159
+ argumentHint: typeof record2.argumentHint === "string" ? record2.argumentHint : ""
45160
+ }
45161
+ ];
45162
+ });
45163
+ }
45164
+ function claudeLiveCommandCatalog(builtIns, snapshot) {
45165
+ return mergeLiveHarnessCommands(builtIns, DYNAMIC_ID_PREFIX, snapshot?.commands.map((command) => ({
45166
+ name: command.name,
45167
+ description: command.description,
45168
+ kind: snapshot.skillNames.has(command.name) ? "skill" : "command"
45169
+ })) ?? null, { names: CLAUDE_EXCLUDED_COMMANDS });
45170
+ }
45171
+ function claudeDynamicCommandPrompt(catalog, commandId, argumentText) {
45172
+ return liveHarnessCommandPrompt(catalog, DYNAMIC_ID_PREFIX, commandId, argumentText);
45173
+ }
45174
+
45175
+ // dist/account-usage.js
45176
+ function projectClaudeAccountUsage(usage, account) {
45177
+ if (!usage.rate_limits_available || !usage.rate_limits)
45178
+ return null;
45179
+ const limits = usage.rate_limits;
45180
+ const windows = [];
45181
+ const add = (product, periodType, value) => {
45182
+ if (!value || typeof value.utilization !== "number" || !Number.isFinite(value.utilization) || value.utilization < 0 || value.utilization > 100)
45183
+ return;
45184
+ windows.push({
45185
+ product,
45186
+ periodType,
45187
+ usagePercent: value.utilization,
45188
+ ...value.resets_at && Number.isFinite(Date.parse(value.resets_at)) ? { resetsAt: value.resets_at } : {}
45189
+ });
45190
+ };
45191
+ add("5-hour window", "five_hour", limits.five_hour);
45192
+ add("7-day window", "seven_day", limits.seven_day);
45193
+ add("OAuth apps · 7-day", "seven_day", limits.seven_day_oauth_apps);
45194
+ add("Opus · 7-day", "seven_day", limits.seven_day_opus);
45195
+ add("Sonnet · 7-day", "seven_day", limits.seven_day_sonnet);
45196
+ for (const window2 of limits.model_scoped ?? [])
45197
+ add(`${window2.display_name} · 7-day`, "seven_day", window2);
45198
+ const [primary, ...others] = windows;
45199
+ if (!primary)
45200
+ return null;
45201
+ const genericPrimary = primary.product === "5-hour window" || primary.product === "7-day window";
45202
+ return {
45203
+ ...account.email ? { email: account.email } : {},
45204
+ ...usage.subscription_type ? { plan: usage.subscription_type } : {},
45205
+ credits: {
45206
+ usedPercent: primary.usagePercent,
45207
+ periodType: primary.periodType,
45208
+ ...!genericPrimary ? { label: primary.product } : {},
45209
+ ...primary.resetsAt ? { resetsAt: primary.resetsAt } : {},
45210
+ ...others.length ? {
45211
+ productUsage: others.map(({ product, usagePercent, resetsAt }) => ({
45212
+ product,
45213
+ usagePercent,
45214
+ ...resetsAt ? { resetsAt } : {}
45215
+ }))
45216
+ } : {}
45217
+ }
45218
+ };
45219
+ }
44877
45220
 
44878
45221
  // dist/process-fence.js
44879
- import { execFile } from "node:child_process";
44880
- import path11 from "node:path";
45222
+ import { execFile as execFile2 } from "node:child_process";
45223
+ import path13 from "node:path";
44881
45224
  import { setTimeout as setTimeout2 } from "node:timers/promises";
44882
45225
  import { promisify } from "node:util";
44883
- var executeFile = promisify(execFile);
45226
+ var executeFile = promisify(execFile2);
44884
45227
  function signalGroup(pid, signal) {
44885
45228
  try {
44886
45229
  process.kill(-pid, signal);
@@ -44901,9 +45244,9 @@ async function closeClaudeProcessGroup(child, timeoutMs) {
44901
45244
  if (child.exitCode !== null || child.signalCode !== null)
44902
45245
  throw new Error("Claude process tree cannot be confirmed after its Windows root exited");
44903
45246
  const root = process.env.SystemRoot ?? process.env.SYSTEMROOT;
44904
- if (!root || !path11.win32.isAbsolute(root))
45247
+ if (!root || !path13.win32.isAbsolute(root))
44905
45248
  throw new Error("Windows SystemRoot is unavailable");
44906
- await executeFile(path11.win32.join(root, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], {
45249
+ await executeFile(path13.win32.join(root, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], {
44907
45250
  timeout: timeoutMs,
44908
45251
  windowsHide: true
44909
45252
  });
@@ -44984,9 +45327,6 @@ function rejectAfter(milliseconds, message) {
44984
45327
  }
44985
45328
  };
44986
45329
  }
44987
- function allowsDangerouslySkipPermissions(getuid = process.getuid) {
44988
- return getuid === void 0 || getuid() !== 0;
44989
- }
44990
45330
  function processExited(child) {
44991
45331
  return child.exitCode !== null || child.signalCode !== null;
44992
45332
  }
@@ -45124,6 +45464,9 @@ function canDeliverSettlementImmediately(event, pendingEvents) {
45124
45464
  if (event.type !== "subagent.settled")
45125
45465
  return false;
45126
45466
  return !pendingEvents.some((pending) => {
45467
+ if (pending.type === "tool.completed") {
45468
+ return event.callId !== void 0 && pending.callId === event.callId;
45469
+ }
45127
45470
  if (pending.type !== "subagent.started" && pending.type !== "subagent.updated" && pending.type !== "subagent.completed") {
45128
45471
  return false;
45129
45472
  }
@@ -45145,6 +45488,7 @@ var ClaudeSdkTransport = class {
45145
45488
  #onPlanLimit;
45146
45489
  #openMode;
45147
45490
  #permissionMode;
45491
+ #allowDangerouslySkipPermissions;
45148
45492
  #queryFactory;
45149
45493
  #thinkingOptionId;
45150
45494
  #active = null;
@@ -45177,6 +45521,7 @@ var ClaudeSdkTransport = class {
45177
45521
  this.#onPlanLimit = options.onPlanLimit;
45178
45522
  this.#openMode = options.openMode;
45179
45523
  this.#permissionMode = options.permissionMode;
45524
+ this.#allowDangerouslySkipPermissions = options.allowDangerouslySkipPermissions ?? false;
45180
45525
  this.#queryFactory = options.queryFactory ?? Okt;
45181
45526
  this.#thinkingOptionId = parseClaudeThinkingOptionId(options.thinkingOptionId);
45182
45527
  }
@@ -45219,7 +45564,7 @@ var ClaudeSdkTransport = class {
45219
45564
  pathToClaudeCodeExecutable: executable,
45220
45565
  settingSources: ["user"],
45221
45566
  permissionMode: this.#permissionMode,
45222
- ...allowsDangerouslySkipPermissions() ? { allowDangerouslySkipPermissions: true } : {},
45567
+ ...this.#allowDangerouslySkipPermissions ? { allowDangerouslySkipPermissions: true } : {},
45223
45568
  canUseTool: (toolName, input, options) => this.#canUseTool(toolName, input, options),
45224
45569
  persistSession: true,
45225
45570
  includePartialMessages: true,
@@ -45381,12 +45726,18 @@ var ClaudeSdkTransport = class {
45381
45726
  if (!active || !activeQuery)
45382
45727
  throw new Error("Claude SDK transport has no active Turn");
45383
45728
  active.accumulator.requestCancel();
45384
- const timeout = rejectAfter(this.#abortTimeoutMs, INTERRUPT_TIMEOUT_MESSAGE);
45385
45729
  try {
45386
- await Promise.race([activeQuery.interrupt(), timeout.promise]);
45730
+ await this.#stopRequest(activeQuery.interrupt(), INTERRUPT_TIMEOUT_MESSAGE);
45387
45731
  } catch (error52) {
45388
45732
  await this.close();
45389
45733
  throw error52 instanceof Error ? error52 : new Error(INTERRUPT_TIMEOUT_MESSAGE);
45734
+ }
45735
+ }
45736
+ /** A user stop must answer: native stop requests share the abort timeout. */
45737
+ async #stopRequest(request, timeoutMessage) {
45738
+ const timeout = rejectAfter(this.#abortTimeoutMs, timeoutMessage);
45739
+ try {
45740
+ await Promise.race([request, timeout.promise]);
45390
45741
  } finally {
45391
45742
  timeout.cancel();
45392
45743
  }
@@ -45518,6 +45869,15 @@ var ClaudeSdkTransport = class {
45518
45869
  if (failures.length > 0)
45519
45870
  throw new AggregateError(failures, "Claude SDK shutdown could not be confirmed");
45520
45871
  }
45872
+ hasBackgroundTasks() {
45873
+ return this.#backgroundTasks.size > 0;
45874
+ }
45875
+ /** The native `task_notification` that follows reports the stopped task. */
45876
+ async stopBackgroundTask(taskId) {
45877
+ if (!this.#query)
45878
+ throw new Error("Claude SDK transport is not running");
45879
+ await this.#stopRequest(this.#query.stopTask(taskId), "Claude background task stop timed out");
45880
+ }
45521
45881
  async #stopBackgroundTasks() {
45522
45882
  const requested = /* @__PURE__ */ new Set();
45523
45883
  const deadline = Date.now() + this.#closeTimeoutMs;
@@ -46029,6 +46389,146 @@ var ClaudeTaskTracker = class {
46029
46389
  }
46030
46390
  };
46031
46391
 
46392
+ // dist/background-command-items.js
46393
+ import { open as open2 } from "node:fs/promises";
46394
+ import { StringDecoder } from "node:string_decoder";
46395
+ var POLL_INTERVAL_MS = 1e3;
46396
+ var READ_CHUNK_BYTES = 64 * 1024;
46397
+ var UNAVAILABLE_OUTPUT = "Native output is unavailable.";
46398
+ function notificationOutcome(status) {
46399
+ if (status === "completed")
46400
+ return { status: "succeeded" };
46401
+ if (status === "failed") {
46402
+ return {
46403
+ status: "failed",
46404
+ error: {
46405
+ code: "nativeFailure",
46406
+ message: "Claude Code background command failed",
46407
+ retryable: false
46408
+ }
46409
+ };
46410
+ }
46411
+ return { status: "cancelled", reason: "Background command stopped" };
46412
+ }
46413
+ var ClaudeBackgroundCommandItems = class {
46414
+ /** Keyed by the Bash `tool_use` id. */
46415
+ #commands = /* @__PURE__ */ new Map();
46416
+ #emit;
46417
+ #outputLimit;
46418
+ constructor(options) {
46419
+ this.#emit = options.emit;
46420
+ this.#outputLimit = options.outputLimit;
46421
+ }
46422
+ taskIds() {
46423
+ return [...this.#commands.values()].map(({ command }) => command.taskId);
46424
+ }
46425
+ follow(command) {
46426
+ const followed = {
46427
+ command,
46428
+ outputFile: command.outputFile,
46429
+ offset: 0,
46430
+ decoder: new StringDecoder("utf8"),
46431
+ output: "",
46432
+ opened: false,
46433
+ truncated: false,
46434
+ timer: null,
46435
+ reading: Promise.resolve(),
46436
+ completed: false
46437
+ };
46438
+ this.#commands.set(command.callId, followed);
46439
+ if (followed.outputFile) {
46440
+ followed.timer = setInterval(() => void this.#poll(followed), POLL_INTERVAL_MS);
46441
+ followed.timer.unref();
46442
+ }
46443
+ }
46444
+ /** Returns whether the notification settles a followed command. */
46445
+ settle(notification) {
46446
+ const followed = notification.callId ? this.#commands.get(notification.callId) : void 0;
46447
+ if (!followed)
46448
+ return false;
46449
+ this.#commands.delete(followed.command.callId);
46450
+ if (followed.timer)
46451
+ clearInterval(followed.timer);
46452
+ followed.outputFile ??= notification.outputFile;
46453
+ void this.#poll(followed).then(() => this.#complete(followed, notificationOutcome(notification.status)));
46454
+ return true;
46455
+ }
46456
+ /** The native process is gone; no notification can arrive any more. */
46457
+ abandonAll(reason) {
46458
+ for (const followed of this.#commands.values()) {
46459
+ if (followed.timer)
46460
+ clearInterval(followed.timer);
46461
+ this.#complete(followed, { status: "cancelled", reason });
46462
+ }
46463
+ this.#commands.clear();
46464
+ }
46465
+ #poll(followed) {
46466
+ followed.reading = followed.reading.then(() => this.#read(followed));
46467
+ return followed.reading;
46468
+ }
46469
+ async #read(followed) {
46470
+ if (!followed.outputFile || followed.truncated)
46471
+ return;
46472
+ let handle;
46473
+ try {
46474
+ handle = await open2(followed.outputFile, "r");
46475
+ } catch {
46476
+ return;
46477
+ }
46478
+ followed.opened = true;
46479
+ try {
46480
+ const buffer = Buffer.alloc(READ_CHUNK_BYTES);
46481
+ for (; ; ) {
46482
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, followed.offset);
46483
+ if (bytesRead === 0)
46484
+ return;
46485
+ followed.offset += bytesRead;
46486
+ this.#append(followed, followed.decoder.write(buffer.subarray(0, bytesRead)));
46487
+ if (followed.truncated)
46488
+ return;
46489
+ }
46490
+ } catch {
46491
+ return;
46492
+ } finally {
46493
+ await handle.close().catch(() => void 0);
46494
+ }
46495
+ }
46496
+ #append(followed, text) {
46497
+ if (text.length === 0 || followed.completed)
46498
+ return;
46499
+ const room = this.#outputLimit - followed.output.length;
46500
+ const accepted = text.length > room ? text.slice(0, Math.max(0, room)) : text;
46501
+ if (text.length > room)
46502
+ followed.truncated = true;
46503
+ if (accepted.length === 0)
46504
+ return;
46505
+ followed.output += accepted;
46506
+ this.#emit({
46507
+ type: "item.updated",
46508
+ turnId: followed.command.turnId,
46509
+ itemId: followed.command.item.itemId,
46510
+ update: { type: "output.append", text: accepted }
46511
+ });
46512
+ }
46513
+ #complete(followed, outcome) {
46514
+ const { command } = followed;
46515
+ followed.completed = true;
46516
+ const output = followed.output.length > 0 ? followed.output : followed.opened ? void 0 : UNAVAILABLE_OUTPUT;
46517
+ this.#emit({
46518
+ type: "item.completed",
46519
+ turnId: command.turnId,
46520
+ snapshot: {
46521
+ item: {
46522
+ ...command.item,
46523
+ ...output !== void 0 ? { output, outputTruncated: followed.truncated } : {},
46524
+ durationMs: Math.max(0, Date.now() - command.startedAtMs)
46525
+ },
46526
+ outcome
46527
+ }
46528
+ });
46529
+ }
46530
+ };
46531
+
46032
46532
  // dist/tool-lifecycle.js
46033
46533
  function isRecord9(value) {
46034
46534
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -46059,15 +46559,20 @@ var ClaudeToolLifecycle = class {
46059
46559
  #cwd;
46060
46560
  #emit;
46061
46561
  #newItemId;
46562
+ #onDetached;
46062
46563
  #outputLimit;
46063
46564
  #taskTracker;
46565
+ #nativeTurnKey;
46064
46566
  #tools = /* @__PURE__ */ new Map();
46567
+ #toolOrdinal = 0;
46065
46568
  constructor(options) {
46066
46569
  this.#cwd = options.cwd;
46067
46570
  this.#emit = options.emit;
46068
46571
  this.#newItemId = options.newItemId;
46572
+ this.#onDetached = options.onDetached;
46069
46573
  this.#outputLimit = options.outputLimit;
46070
46574
  this.#taskTracker = options.taskTracker;
46575
+ this.#nativeTurnKey = options.nativeTurnKey;
46071
46576
  }
46072
46577
  get size() {
46073
46578
  return this.#tools.size;
@@ -46075,15 +46580,16 @@ var ClaudeToolLifecycle = class {
46075
46580
  start(turnId, event) {
46076
46581
  if (this.#tools.has(event.callId))
46077
46582
  throw new Error("Claude Code Tool started more than once");
46583
+ const itemId = claudeTranscriptItemId(this.#nativeTurnKey, "tool", this.#toolOrdinal += 1);
46078
46584
  const command = event.toolName === "Bash" ? stringField2(event.arguments, "command") : void 0;
46079
46585
  const item = command ? {
46080
46586
  type: "commandExecution",
46081
- itemId: this.#newItemId(),
46587
+ itemId,
46082
46588
  command,
46083
46589
  cwd: this.#cwd
46084
46590
  } : {
46085
46591
  type: "toolExecution",
46086
- itemId: this.#newItemId(),
46592
+ itemId,
46087
46593
  toolName: isClaudeTaskTool(event.toolName) ? "Todo" : event.toolName,
46088
46594
  arguments: isClaudeTaskTool(event.toolName) ? {} : event.arguments
46089
46595
  };
@@ -46108,6 +46614,18 @@ var ClaudeToolLifecycle = class {
46108
46614
  throw new Error("Claude Code Tool completion references an unknown Tool");
46109
46615
  }
46110
46616
  this.#tools.delete(event.callId);
46617
+ if (tool.item.type === "commandExecution" && event.backgroundTaskId && !event.isError && !cancellationRequested) {
46618
+ this.#emit({ type: "item.detached", turnId, itemId: tool.item.itemId });
46619
+ this.#onDetached({
46620
+ turnId,
46621
+ callId: event.callId,
46622
+ taskId: event.backgroundTaskId,
46623
+ item: tool.item,
46624
+ startedAtMs: tool.startedAtMs,
46625
+ ...event.backgroundOutputFile ? { outputFile: event.backgroundOutputFile } : {}
46626
+ });
46627
+ return;
46628
+ }
46111
46629
  const output = boundedToolOutput(event.outputText, this.#outputLimit);
46112
46630
  const durationMs = Math.max(tool.elapsedMs, Date.now() - tool.startedAtMs, 0);
46113
46631
  if (tool.item.type === "commandExecution") {
@@ -46361,6 +46879,37 @@ function faultError() {
46361
46879
  retryable: true
46362
46880
  };
46363
46881
  }
46882
+ function claudePermissionModeSelectionFailure(permissionMode, error52) {
46883
+ const nativeMessage = error52 instanceof Error ? error52.message.toLowerCase() : "";
46884
+ if (permissionMode === "auto" && nativeMessage.includes("auto mode unavailable")) {
46885
+ return {
46886
+ code: "nativeFailure",
46887
+ message: "Auto mode is unavailable for the current Claude Code Model",
46888
+ retryable: true
46889
+ };
46890
+ }
46891
+ if (permissionMode === "bypassPermissions") {
46892
+ if (nativeMessage.includes("not launched with --dangerously-skip-permissions")) {
46893
+ return {
46894
+ code: "nativeFailure",
46895
+ message: "Claude Code started this Session without bypass permissions support; when running as root, set IS_SANDBOX=1 for the codexhost Host, restart it, and reopen the Session",
46896
+ retryable: false
46897
+ };
46898
+ }
46899
+ if (nativeMessage.includes("disabled by settings or configuration")) {
46900
+ return {
46901
+ code: "nativeFailure",
46902
+ message: "Bypass permissions is disabled by Claude Code settings (permissions.disableBypassPermissionsMode) or organization policy",
46903
+ retryable: false
46904
+ };
46905
+ }
46906
+ }
46907
+ return {
46908
+ code: "nativeFailure",
46909
+ message: "Claude Code rejected the Permission Mode selection",
46910
+ retryable: true
46911
+ };
46912
+ }
46364
46913
  function delay2(milliseconds) {
46365
46914
  return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
46366
46915
  }
@@ -46432,6 +46981,7 @@ var ClaudeHarnessSession = class {
46432
46981
  #cancelTimeoutMs;
46433
46982
  #closeTimeoutMs;
46434
46983
  #createTransport;
46984
+ #bypassPermissionsAvailable;
46435
46985
  #cwd;
46436
46986
  #nativeRef;
46437
46987
  #onClosed;
@@ -46448,6 +46998,7 @@ var ClaudeHarnessSession = class {
46448
46998
  #readSessionMessages;
46449
46999
  #sessionId;
46450
47000
  #toolOutputLimit;
47001
+ #backgroundCommands;
46451
47002
  #continuationQuiescenceMs;
46452
47003
  #taskTracker = new ClaudeTaskTracker();
46453
47004
  #acceptingTurn = false;
@@ -46482,6 +47033,7 @@ var ClaudeHarnessSession = class {
46482
47033
  this.#pendingSessions = options.pendingSessions;
46483
47034
  const environment = options.environment;
46484
47035
  this.#createTransport = environment ? (input) => dependencies.createTransport({ ...input, environment }) : dependencies.createTransport;
47036
+ this.#bypassPermissionsAvailable = options.bypassPermissionsAvailable;
46485
47037
  this.#randomUUID = dependencies.randomUUID;
46486
47038
  this.#readSessionMessages = dependencies.readSessionMessages;
46487
47039
  this.#cancelTimeoutMs = options.cancelTimeoutMs;
@@ -46494,6 +47046,10 @@ var ClaudeHarnessSession = class {
46494
47046
  this.#requestedThinkingOptionId = options.requestedThinkingOptionId;
46495
47047
  this.#sessionId = options.sessionId;
46496
47048
  this.#toolOutputLimit = options.toolOutputLimit;
47049
+ this.#backgroundCommands = new ClaudeBackgroundCommandItems({
47050
+ outputLimit: options.toolOutputLimit,
47051
+ emit: (event) => this.#event(event)
47052
+ });
46497
47053
  this.#continuationQuiescenceMs = options.continuationQuiescenceMs;
46498
47054
  this.#nativeRef = options.nativeRef ?? nativeSessionRefSchema.parse({
46499
47055
  harnessId: this.harnessId,
@@ -46695,8 +47251,10 @@ var ClaudeHarnessSession = class {
46695
47251
  cwd: this.#cwd,
46696
47252
  outputLimit: this.#toolOutputLimit,
46697
47253
  taskTracker: this.#taskTracker,
47254
+ nativeTurnKey,
46698
47255
  newItemId: () => hostItemIdSchema.parse(this.#randomUUID()),
46699
- emit: (event) => this.#event(event)
47256
+ emit: (event) => this.#event(event),
47257
+ onDetached: (command2) => this.#backgroundCommands.follow(command2)
46700
47258
  }),
46701
47259
  interactions: /* @__PURE__ */ new Map(),
46702
47260
  interactionByRequestId: /* @__PURE__ */ new Map(),
@@ -46806,8 +47364,10 @@ var ClaudeHarnessSession = class {
46806
47364
  cwd: this.#cwd,
46807
47365
  outputLimit: this.#toolOutputLimit,
46808
47366
  taskTracker: this.#taskTracker,
47367
+ nativeTurnKey,
46809
47368
  newItemId: () => hostItemIdSchema.parse(this.#randomUUID()),
46810
- emit: (event) => this.#event(event)
47369
+ emit: (event) => this.#event(event),
47370
+ onDetached: (command2) => this.#backgroundCommands.follow(command2)
46811
47371
  }),
46812
47372
  interactions: /* @__PURE__ */ new Map(),
46813
47373
  interactionByRequestId: /* @__PURE__ */ new Map(),
@@ -46840,6 +47400,28 @@ var ClaudeHarnessSession = class {
46840
47400
  }
46841
47401
  return { ok: true, value: { turnId: command.turnId } };
46842
47402
  }
47403
+ /** Closing the native process stops its background tasks, so they keep the Session. */
47404
+ hasBackgroundWork() {
47405
+ return this.#transport?.hasBackgroundTasks() ?? false;
47406
+ }
47407
+ async stopBackgroundWork() {
47408
+ const transport = this.#transport;
47409
+ if (!transport)
47410
+ return { ok: true, value: void 0 };
47411
+ try {
47412
+ await Promise.all(this.#backgroundCommands.taskIds().map((taskId) => transport.stopBackgroundTask(taskId)));
47413
+ return { ok: true, value: void 0 };
47414
+ } catch (error52) {
47415
+ return {
47416
+ ok: false,
47417
+ error: {
47418
+ code: "nativeFailure",
47419
+ message: error52 instanceof Error ? error52.message : String(error52),
47420
+ retryable: true
47421
+ }
47422
+ };
47423
+ }
47424
+ }
46843
47425
  refreshUsage() {
46844
47426
  if (this.#phase !== "open" || !this.#transport)
46845
47427
  return Promise.resolve();
@@ -47001,6 +47583,21 @@ var ClaudeHarnessSession = class {
47001
47583
  }
47002
47584
  };
47003
47585
  }
47586
+ let permissionModeId = command.permissionModeId;
47587
+ if (permissionMode === "bypassPermissions" && !this.#bypassPermissionsAvailable) {
47588
+ if (this.#transport || this.#startupTask) {
47589
+ return {
47590
+ ok: false,
47591
+ error: {
47592
+ code: "unsupported",
47593
+ message: CLAUDE_BYPASS_PERMISSIONS_UNAVAILABLE_MESSAGE,
47594
+ retryable: false
47595
+ }
47596
+ };
47597
+ }
47598
+ permissionMode = "default";
47599
+ permissionModeId = CLAUDE_DEFAULT_PERMISSION_MODE_ID;
47600
+ }
47004
47601
  this.#usageGeneration += 1;
47005
47602
  this.#contextUsageFreshUntilMs = 0;
47006
47603
  this.#contextUsageCooldownUntilMs = 0;
@@ -47014,18 +47611,13 @@ var ClaudeHarnessSession = class {
47014
47611
  try {
47015
47612
  await transport.setPermissionMode(permissionMode);
47016
47613
  } catch (error52) {
47017
- const nativeMessage = error52 instanceof Error ? error52.message.toLowerCase() : "";
47018
47614
  return {
47019
47615
  ok: false,
47020
- error: {
47021
- code: "nativeFailure",
47022
- message: permissionMode === "auto" && nativeMessage.includes("auto mode unavailable") ? "Auto mode is unavailable for the current Claude Code Model" : "Claude Code rejected the Permission Mode selection",
47023
- retryable: true
47024
- }
47616
+ error: claudePermissionModeSelectionFailure(permissionMode, error52)
47025
47617
  };
47026
47618
  }
47027
47619
  }
47028
- this.#requestedPermissionModeId = transport ? encodeClaudePermissionModeId(transport.getPermissionMode()) : command.permissionModeId;
47620
+ this.#requestedPermissionModeId = transport ? encodeClaudePermissionModeId(transport.getPermissionMode()) : permissionModeId;
47029
47621
  const persistenceError = await this.#savePendingConfiguration();
47030
47622
  if (persistenceError)
47031
47623
  return { ok: false, error: persistenceError };
@@ -47195,6 +47787,7 @@ var ClaudeHarnessSession = class {
47195
47787
  const active = this.#active;
47196
47788
  if (active)
47197
47789
  this.#finishFailed(active, invalidState("Claude Code Session closed during active Turn"));
47790
+ this.#backgroundCommands.abandonAll("Claude Code Session closed");
47198
47791
  this.#phase = "closed";
47199
47792
  this.#channel.end();
47200
47793
  this.#onClosed();
@@ -47235,6 +47828,7 @@ var ClaudeHarnessSession = class {
47235
47828
  ...model ? { model } : {},
47236
47829
  thinkingOptionId: this.#requestedThinkingOptionId,
47237
47830
  permissionMode,
47831
+ allowDangerouslySkipPermissions: this.#bypassPermissionsAvailable,
47238
47832
  onPermissionModeChanged: (mode) => this.#handlePermissionModeChanged(mode),
47239
47833
  onFault: () => this.#fault(faultError()),
47240
47834
  onPlanLimit: (planLimit) => this.#handlePlanLimit(planLimit)
@@ -47242,9 +47836,8 @@ var ClaudeHarnessSession = class {
47242
47836
  this.#transport = transport;
47243
47837
  transport.setAutonomousTurnHandler((turn) => this.#handleAutonomousTurn(turn));
47244
47838
  transport.setThreadEventHandler((event) => {
47245
- if (event.type === "subagent.settled") {
47246
- this.#settleBackgroundSubagent(event.status, event.nativeSubagentId, event.callId, event.resultSummary);
47247
- }
47839
+ if (event.type === "subagent.settled")
47840
+ this.#settleNativeTask(event);
47248
47841
  });
47249
47842
  transport.setIdleTurnHandler({
47250
47843
  onEvent: (event) => {
@@ -47253,9 +47846,8 @@ var ClaudeHarnessSession = class {
47253
47846
  this.#handleTurnEvent(active, event);
47254
47847
  return;
47255
47848
  }
47256
- if (event.type === "subagent.settled") {
47257
- this.#settleBackgroundSubagent(event.status, event.nativeSubagentId, event.callId, event.resultSummary);
47258
- }
47849
+ if (event.type === "subagent.settled")
47850
+ this.#settleNativeTask(event);
47259
47851
  },
47260
47852
  onTerminal: (result) => {
47261
47853
  const active = this.#active;
@@ -47435,7 +48027,7 @@ var ClaudeHarnessSession = class {
47435
48027
  return;
47436
48028
  }
47437
48029
  case "subagent.settled":
47438
- this.#settleBackgroundSubagent(event.status, event.nativeSubagentId, event.callId, event.resultSummary);
48030
+ this.#settleNativeTask(event);
47439
48031
  return;
47440
48032
  case "subagent.transcript.changed": {
47441
48033
  const nativeSubagentId2 = active.subagents.nativeSubagentId(event.callId);
@@ -47702,8 +48294,10 @@ var ClaudeHarnessSession = class {
47702
48294
  cwd: this.#cwd,
47703
48295
  outputLimit: this.#toolOutputLimit,
47704
48296
  taskTracker: this.#taskTracker,
48297
+ nativeTurnKey,
47705
48298
  newItemId: () => hostItemIdSchema.parse(this.#randomUUID()),
47706
- emit: (event) => this.#event(event)
48299
+ emit: (event) => this.#event(event),
48300
+ onDetached: (command) => this.#backgroundCommands.follow(command)
47707
48301
  }),
47708
48302
  interactions: /* @__PURE__ */ new Map(),
47709
48303
  interactionByRequestId: /* @__PURE__ */ new Map(),
@@ -47741,6 +48335,15 @@ var ClaudeHarnessSession = class {
47741
48335
  this.#handleTurnEvent(active, event);
47742
48336
  this.#finishResult(active, turn.result);
47743
48337
  }
48338
+ /**
48339
+ * A native `task_notification` names the tool call that started its task: a
48340
+ * followed background command settles here, anything else is a Subagent.
48341
+ */
48342
+ #settleNativeTask(event) {
48343
+ if (this.#backgroundCommands.settle(event))
48344
+ return;
48345
+ this.#settleBackgroundSubagent(event.status, event.nativeSubagentId, event.callId, event.resultSummary);
48346
+ }
47744
48347
  #settleBackgroundSubagent(status, nativeSubagentId2, callId, resultSummary) {
47745
48348
  this.#occupancy.notify(callId, nativeSubagentId2);
47746
48349
  const active = this.#active;
@@ -48130,6 +48733,7 @@ var ClaudeHarnessSession = class {
48130
48733
  const active = this.#active;
48131
48734
  if (active)
48132
48735
  this.#finishFailed(active, error52);
48736
+ this.#backgroundCommands.abandonAll("Claude Code Session faulted");
48133
48737
  this.#phase = "faulted";
48134
48738
  this.#event({ type: "session.faulted", error: error52 });
48135
48739
  this.#channel.end();
@@ -48237,6 +48841,7 @@ var ClaudeCodeAdapter = class {
48237
48841
  }
48238
48842
  this.#dependencies = dependencies ?? {
48239
48843
  randomUUID: randomUUID3,
48844
+ bypassPermissionsAvailable: (environment2) => claudeBypassPermissionsAvailable(environment2 ?? options.environment ?? process.env),
48240
48845
  inspectInstallation: () => {
48241
48846
  resolveClaudeCodeExecutable({
48242
48847
  ...options.command ? { command: options.command } : {},
@@ -48300,7 +48905,7 @@ var ClaudeCodeAdapter = class {
48300
48905
  error: invalidState("Claude Code Adapter is closing")
48301
48906
  };
48302
48907
  }
48303
- const cwd = path12.resolve(input.cwd ?? process.cwd());
48908
+ const cwd = path14.resolve(input.cwd ?? process.cwd());
48304
48909
  if (!input.refresh) {
48305
48910
  const cached2 = this.#inspectionCache.get(cwd);
48306
48911
  if (cached2)
@@ -48359,7 +48964,7 @@ var ClaudeCodeAdapter = class {
48359
48964
  this.#inspectors.add(inspector);
48360
48965
  stage = "model-catalog";
48361
48966
  const snapshot = await inspector.inspect();
48362
- const permissionModes = snapshot.canSelectPermissionMode ? claudePermissionModeCatalogForModels(snapshot.models) : void 0;
48967
+ const permissionModes = snapshot.canSelectPermissionMode ? claudePermissionModeCatalogForModels(snapshot.models, this.#dependencies.bypassPermissionsAvailable()) : void 0;
48363
48968
  if (!snapshot.canSelectModel) {
48364
48969
  return {
48365
48970
  status: "unavailable",
@@ -48481,7 +49086,21 @@ var ClaudeCodeAdapter = class {
48481
49086
  }
48482
49087
  };
48483
49088
  }
48484
- const cwd = path12.resolve(input.cwd);
49089
+ const bypassPermissionsAvailable = this.#dependencies.bypassPermissionsAvailable(input.environment);
49090
+ if (!bypassPermissionsAvailable && requestedPermissionModeId === "bypassPermissions") {
49091
+ if (input.kind === "create") {
49092
+ return {
49093
+ ok: false,
49094
+ error: {
49095
+ code: "unsupported",
49096
+ message: CLAUDE_BYPASS_PERMISSIONS_UNAVAILABLE_MESSAGE,
49097
+ retryable: false
49098
+ }
49099
+ };
49100
+ }
49101
+ requestedPermissionModeId = CLAUDE_DEFAULT_PERMISSION_MODE_ID;
49102
+ }
49103
+ const cwd = path14.resolve(input.cwd);
48485
49104
  if (input.kind === "rollbackLastTurn") {
48486
49105
  for (const source of this.#sessions) {
48487
49106
  const ready = await source.prepareRollback(input.sourceRef.nativeSessionId);
@@ -48540,7 +49159,10 @@ var ClaudeCodeAdapter = class {
48540
49159
  decodeClaudePermissionModeId(pending.configuration.effectivePermissionModeId);
48541
49160
  requestedModel = pending.configuration.effectiveModel ?? requestedModel;
48542
49161
  requestedThinkingOptionId = pending.configuration.effectiveThinkingOptionId ?? requestedThinkingOptionId;
48543
- requestedPermissionModeId = input.kind === "resume" && input.permissionModeId ? input.permissionModeId : pending.configuration.effectivePermissionModeId ?? requestedPermissionModeId;
49162
+ requestedPermissionModeId = input.kind === "resume" && input.permissionModeId ? requestedPermissionModeId : pending.configuration.effectivePermissionModeId ?? requestedPermissionModeId;
49163
+ if (!bypassPermissionsAvailable && requestedPermissionModeId === "bypassPermissions") {
49164
+ requestedPermissionModeId = CLAUDE_DEFAULT_PERMISSION_MODE_ID;
49165
+ }
48544
49166
  } catch {
48545
49167
  return {
48546
49168
  ok: false,
@@ -48554,6 +49176,7 @@ var ClaudeCodeAdapter = class {
48554
49176
  }
48555
49177
  const session = new ClaudeHarnessSession(cwd, this.#dependencies, this.#closeTimeoutMs, () => this.#sessions.delete(session), (planLimit) => this.#recordPlanLimit(session, planLimit), {
48556
49178
  ...input.environment ? { environment: input.environment } : {},
49179
+ bypassPermissionsAvailable,
48557
49180
  openMode,
48558
49181
  pendingSessions: this.#pendingSessions,
48559
49182
  knownConfiguration: input.kind === "rollbackLastTurn" || input.kind === "resume" && Boolean(input.model || input.thinkingOptionId) || Boolean(durableRef && isPendingClaudeSession(durableRef)),
@@ -48603,9 +49226,74 @@ var ClaudeCodeAdapter = class {
48603
49226
  }
48604
49227
  };
48605
49228
 
49229
+ // dist/installation.js
49230
+ import { readFile as readFile6, realpath as realpath3 } from "node:fs/promises";
49231
+ import { homedir as homedir2 } from "node:os";
49232
+ import path15 from "node:path";
49233
+ async function readSettings(file2) {
49234
+ const text = await readFile6(file2, "utf8").catch((error52) => {
49235
+ if (error52.code === "ENOENT")
49236
+ return "{}";
49237
+ throw error52;
49238
+ });
49239
+ const settings = JSON.parse(text);
49240
+ if (!settings || typeof settings !== "object" || Array.isArray(settings))
49241
+ throw new Error("Claude update settings are invalid");
49242
+ return settings;
49243
+ }
49244
+ function createClaudeInstallation(environment, command) {
49245
+ let update;
49246
+ return createInstallationManager({
49247
+ async check() {
49248
+ const executable = resolveClaudeCodeExecutable({
49249
+ environment,
49250
+ ...command ? { command } : {}
49251
+ });
49252
+ const home = environment.HOME ?? environment.USERPROFILE ?? homedir2();
49253
+ const config2 = environment.CLAUDE_CONFIG_DIR ? path15.resolve(home, environment.CLAUDE_CONFIG_DIR) : path15.join(home, ".claude");
49254
+ const managedFile = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : process.platform === "win32" ? path15.join(environment.ProgramFiles ?? "C:\\Program Files", "ClaudeCode", "managed-settings.json") : "/etc/claude-code/managed-settings.json";
49255
+ const user = await readSettings(path15.join(config2, "settings.json"));
49256
+ const managed = await readSettings(managedFile);
49257
+ const settings = { ...user, ...managed, env: { ...user.env, ...managed.env } };
49258
+ const env = { ...environment, ...settings.env };
49259
+ const currentVersion = versionFromOutput(await runInstallationCommand(executable, ["--version"], {
49260
+ ...env,
49261
+ DISABLE_AUTOUPDATER: "1"
49262
+ }));
49263
+ const channel = settings.autoUpdatesChannel ?? "latest";
49264
+ if (channel !== "latest" && channel !== "stable")
49265
+ throw new Error("Unknown Claude release channel");
49266
+ const latestVersion = installationVersion(await fetchInstallationText(`https://downloads.claude.ai/claude-code-releases/${channel}`));
49267
+ const npm = await npmInstallation(executable, ["@anthropic-ai/claude-code"], env);
49268
+ const launcher = path15.join(home, ".local", "bin", process.platform === "win32" ? "claude.exe" : "claude");
49269
+ const selected = await realpath3(executable);
49270
+ const versions = path15.join(home, ".local", "share", "claude", "versions") + path15.sep;
49271
+ const native = path15.resolve(executable) === launcher && (selected.startsWith(versions) || process.platform === "win32" && selected === launcher);
49272
+ const blocked = !!env.DISABLE_UPDATES && env.DISABLE_UPDATES !== "0" || !!settings.minimumVersion && newerInstallationVersion(latestVersion, installationVersion(settings.minimumVersion)) || !!settings.requiredMaximumVersion && newerInstallationVersion(installationVersion(settings.requiredMaximumVersion), latestVersion);
49273
+ const canUpdate = !blocked && (npm?.canUpdate ?? native);
49274
+ update = async () => {
49275
+ const updateEnv = npm ? { ...env, npm_config_prefix: npm.prefix, NPM_CONFIG_PREFIX: npm.prefix } : env;
49276
+ await runInstallationCommand(executable, ["update"], updateEnv, 3e5);
49277
+ };
49278
+ return {
49279
+ currentVersion,
49280
+ latestVersion,
49281
+ updateAvailable: newerInstallationVersion(currentVersion, latestVersion),
49282
+ canUpdate,
49283
+ ...!canUpdate ? {
49284
+ message: blocked ? "Claude updates are restricted by the installation's settings or policy." : "Use the original installer or package manager for this Claude installation."
49285
+ } : {}
49286
+ };
49287
+ },
49288
+ async update() {
49289
+ await update();
49290
+ }
49291
+ });
49292
+ }
49293
+
48606
49294
  // dist/user-shell-environment.js
48607
- import path13 from "node:path";
48608
- import { execFile as execFile2 } from "node:child_process";
49295
+ import path16 from "node:path";
49296
+ import { execFile as execFile3 } from "node:child_process";
48609
49297
  var ENVIRONMENT_MARKER = Buffer.from("\0CODEXHOST_USER_SHELL_ENV_V1\0");
48610
49298
  var ENVIRONMENT_COMMAND = "printf '\\0CODEXHOST_USER_SHELL_ENV_V1\\0'; /usr/bin/env -0";
48611
49299
  var SHELL_ENVIRONMENT_TIMEOUT_MS = 3e3;
@@ -48647,14 +49335,14 @@ async function withUserShellEnvironment(environment, dependencies) {
48647
49335
  if (platform === "win32" || !environment.HOME)
48648
49336
  return environment;
48649
49337
  const shell = environment.SHELL?.trim() || defaultShell(platform);
48650
- if (!shell || !SUPPORTED_SHELLS.has(path13.basename(shell)))
49338
+ if (!shell || !SUPPORTED_SHELLS.has(path16.basename(shell)))
48651
49339
  return environment;
48652
49340
  const cacheKey = `${platform}\0${shell}\0${environment.HOME}`;
48653
49341
  const cached2 = dependencies ? void 0 : shellEnvironmentCache.get(cacheKey);
48654
49342
  if (cached2)
48655
49343
  return mergeMissingEnvironment(environment, cached2);
48656
49344
  const run = dependencies?.run ?? ((command, arguments_, options) => new Promise((resolve2) => {
48657
- const child = execFile2(command, arguments_, {
49345
+ const child = execFile3(command, arguments_, {
48658
49346
  ...options,
48659
49347
  encoding: "buffer",
48660
49348
  killSignal: "SIGKILL"
@@ -48691,10 +49379,10 @@ async function createHarnessAdapter(context) {
48691
49379
  ...context.brokerDescriptorPath ? { descriptorPath: context.brokerDescriptorPath } : {}
48692
49380
  });
48693
49381
  }
48694
- return new ClaudeCodeAdapter({
49382
+ return Object.assign(new ClaudeCodeAdapter({
48695
49383
  ...environment[CLAUDE_CODE_COMMAND_ENV] ? { command: environment[CLAUDE_CODE_COMMAND_ENV] } : {},
48696
49384
  environment
48697
- });
49385
+ }), { installation: createClaudeInstallation(environment, environment[CLAUDE_CODE_COMMAND_ENV]) });
48698
49386
  }
48699
49387
  async function warmup(adapter) {
48700
49388
  try {