@codexhost/cli-darwin-x64 0.2.1 → 0.2.3

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.
@@ -773,10 +773,10 @@ function mergeDefs(...defs) {
773
773
  function cloneDef(schema) {
774
774
  return mergeDefs(schema._zod.def);
775
775
  }
776
- function getElementAtPath(obj, path18) {
777
- if (!path18)
776
+ function getElementAtPath(obj, path19) {
777
+ if (!path19)
778
778
  return obj;
779
- return path18.reduce((acc, key) => acc?.[key], obj);
779
+ return path19.reduce((acc, key) => acc?.[key], obj);
780
780
  }
781
781
  function promiseAllObject(promisesObj) {
782
782
  const keys = Object.keys(promisesObj);
@@ -1185,11 +1185,11 @@ function explicitlyAborted(x2, startIndex = 0) {
1185
1185
  }
1186
1186
  return false;
1187
1187
  }
1188
- function prefixIssues(path18, issues) {
1188
+ function prefixIssues(path19, issues) {
1189
1189
  return issues.map((iss) => {
1190
1190
  var _a4;
1191
1191
  (_a4 = iss).path ?? (_a4.path = []);
1192
- iss.path.unshift(path18);
1192
+ iss.path.unshift(path19);
1193
1193
  return iss;
1194
1194
  });
1195
1195
  }
@@ -1336,16 +1336,16 @@ function flattenError(error52, mapper = (issue2) => issue2.message) {
1336
1336
  }
1337
1337
  function formatError(error52, mapper = (issue2) => issue2.message) {
1338
1338
  const fieldErrors = { _errors: [] };
1339
- const processError = (error53, path18 = []) => {
1339
+ const processError = (error53, path19 = []) => {
1340
1340
  for (const issue2 of error53.issues) {
1341
1341
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1342
- issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
1342
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1343
1343
  } else if (issue2.code === "invalid_key") {
1344
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1344
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1345
1345
  } else if (issue2.code === "invalid_element") {
1346
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1346
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1347
1347
  } else {
1348
- const fullpath = [...path18, ...issue2.path];
1348
+ const fullpath = [...path19, ...issue2.path];
1349
1349
  if (fullpath.length === 0) {
1350
1350
  fieldErrors._errors.push(mapper(issue2));
1351
1351
  } else {
@@ -1372,17 +1372,17 @@ function formatError(error52, mapper = (issue2) => issue2.message) {
1372
1372
  }
1373
1373
  function treeifyError(error52, mapper = (issue2) => issue2.message) {
1374
1374
  const result = { errors: [] };
1375
- const processError = (error53, path18 = []) => {
1375
+ const processError = (error53, path19 = []) => {
1376
1376
  var _a4, _b2;
1377
1377
  for (const issue2 of error53.issues) {
1378
1378
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1379
- issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
1379
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1380
1380
  } else if (issue2.code === "invalid_key") {
1381
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1381
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1382
1382
  } else if (issue2.code === "invalid_element") {
1383
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1383
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1384
1384
  } else {
1385
- const fullpath = [...path18, ...issue2.path];
1385
+ const fullpath = [...path19, ...issue2.path];
1386
1386
  if (fullpath.length === 0) {
1387
1387
  result.errors.push(mapper(issue2));
1388
1388
  continue;
@@ -1414,8 +1414,8 @@ function treeifyError(error52, mapper = (issue2) => issue2.message) {
1414
1414
  }
1415
1415
  function toDotPath(_path) {
1416
1416
  const segs = [];
1417
- const path18 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1418
- for (const seg of path18) {
1417
+ const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1418
+ for (const seg of path19) {
1419
1419
  if (typeof seg === "number")
1420
1420
  segs.push(`[${seg}]`);
1421
1421
  else if (typeof seg === "symbol")
@@ -14107,13 +14107,13 @@ function resolveRef(ref, ctx) {
14107
14107
  if (!ref.startsWith("#")) {
14108
14108
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14109
14109
  }
14110
- const path18 = ref.slice(1).split("/").filter(Boolean);
14111
- if (path18.length === 0) {
14110
+ const path19 = ref.slice(1).split("/").filter(Boolean);
14111
+ if (path19.length === 0) {
14112
14112
  return ctx.rootSchema;
14113
14113
  }
14114
14114
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14115
- if (path18[0] === defsKey) {
14116
- const key = path18[1];
14115
+ if (path19[0] === defsKey) {
14116
+ const key = path19[1];
14117
14117
  if (!key || !ctx.defs[key]) {
14118
14118
  throw new Error(`Reference not found: ${ref}`);
14119
14119
  }
@@ -44838,16 +44838,16 @@ var AbstractApiClient = class {
44838
44838
  * Shared POST leg of both C→S carriers (callUnary/respond): JSON body,
44839
44839
  * optional default timeout merged with the caller's external signal, non-2xx → transport throw.
44840
44840
  */
44841
- async postJson(path18, body, signal, timeoutPolicy = "default") {
44841
+ async postJson(path19, body, signal, timeoutPolicy = "default") {
44842
44842
  const requestSignal = timeoutPolicy === "default" ? signal === void 0 ? AbortSignal.timeout(this.timeoutMs) : AbortSignal.any([AbortSignal.timeout(this.timeoutMs), signal]) : signal;
44843
- const response = await this.doFetch(new URL(path18, this.resolveBase()), {
44843
+ const response = await this.doFetch(new URL(path19, this.resolveBase()), {
44844
44844
  method: "POST",
44845
44845
  headers: { "content-type": "application/json" },
44846
44846
  body: JSON.stringify(body),
44847
44847
  ...requestSignal === void 0 ? {} : { signal: requestSignal }
44848
44848
  });
44849
44849
  if (!response.ok)
44850
- throw new Error(`transport failure for ${path18}: HTTP ${response.status}`);
44850
+ throw new Error(`transport failure for ${path19}: HTTP ${response.status}`);
44851
44851
  return response;
44852
44852
  }
44853
44853
  /**
@@ -44883,10 +44883,10 @@ var AbstractApiClient = class {
44883
44883
  * either parse level is reported and skipped (one corrupt frame must not kill the stream; the
44884
44884
  * client's gap detection covers whatever the frame carried).
44885
44885
  */
44886
- async *readSse(path18, signal, frameSchema, onOpen) {
44887
- const response = await this.doFetch(new URL(path18, this.resolveBase()), { signal });
44886
+ async *readSse(path19, signal, frameSchema, onOpen) {
44887
+ const response = await this.doFetch(new URL(path19, this.resolveBase()), { signal });
44888
44888
  if (!response.ok || response.body === null)
44889
- throw new Error(`transport failure for ${path18}: HTTP ${response.status}`);
44889
+ throw new Error(`transport failure for ${path19}: HTTP ${response.status}`);
44890
44890
  onOpen?.();
44891
44891
  const reader = response.body.getReader();
44892
44892
  const decoder2 = new TextDecoder();
@@ -44910,7 +44910,7 @@ var AbstractApiClient = class {
44910
44910
  full = serverRequestSchema.parse(JSON.parse(data));
44911
44911
  frame = frameSchema.parse(full.payload);
44912
44912
  } catch (error52) {
44913
- console.error(`[apiproxy] dropping malformed SSE frame on ${path18}:`, error52);
44913
+ console.error(`[apiproxy] dropping malformed SSE frame on ${path19}:`, error52);
44914
44914
  continue;
44915
44915
  }
44916
44916
  this.onEnvelope(full);
@@ -45485,16 +45485,16 @@ var Diff = class {
45485
45485
  }
45486
45486
  }
45487
45487
  }
45488
- addToPath(path18, added, removed, oldPosInc, options) {
45489
- const last = path18.lastComponent;
45488
+ addToPath(path19, added, removed, oldPosInc, options) {
45489
+ const last = path19.lastComponent;
45490
45490
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
45491
45491
  return {
45492
- oldPos: path18.oldPos + oldPosInc,
45492
+ oldPos: path19.oldPos + oldPosInc,
45493
45493
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
45494
45494
  };
45495
45495
  } else {
45496
45496
  return {
45497
- oldPos: path18.oldPos + oldPosInc,
45497
+ oldPos: path19.oldPos + oldPosInc,
45498
45498
  lastComponent: { count: 1, added, removed, previousComponent: last }
45499
45499
  };
45500
45500
  }
@@ -47246,7 +47246,7 @@ var packageMetadata3 = {
47246
47246
 
47247
47247
  // packages/adapters/grok/dist/grok-adapter.js
47248
47248
  import { randomUUID as randomUUID3 } from "node:crypto";
47249
- import path10 from "node:path";
47249
+ import path11 from "node:path";
47250
47250
 
47251
47251
  // packages/adapters/grok/dist/acp-transport.js
47252
47252
  import { spawn as spawn3, spawnSync } from "node:child_process";
@@ -51877,6 +51877,81 @@ var GrokAcpTransport = class {
51877
51877
  }
51878
51878
  };
51879
51879
 
51880
+ // packages/adapters/grok/dist/grok-file-change.js
51881
+ import { Buffer as Buffer4 } from "node:buffer";
51882
+ import path9 from "node:path";
51883
+ var DEFAULT_GROK_FILE_CHANGE_TEXT_LIMIT = 4 * 1024 * 1024;
51884
+ var MAX_GROK_FILE_CHANGES_PER_TOOL = 32;
51885
+ function isRecord10(value) {
51886
+ return typeof value === "object" && value !== null && !Array.isArray(value);
51887
+ }
51888
+ function validAbsolutePath(value) {
51889
+ return typeof value === "string" && path9.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
51890
+ }
51891
+ function displayPath2(nativePath, cwd) {
51892
+ const resolvedCwd = path9.resolve(cwd);
51893
+ const resolvedPath = path9.resolve(nativePath);
51894
+ const relative = path9.relative(resolvedCwd, resolvedPath);
51895
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path9.sep}`);
51896
+ const selected = inside ? relative : resolvedPath;
51897
+ const normalized = selected.replaceAll("\\", "/");
51898
+ if (normalized.length === 0 || normalized === ".")
51899
+ return null;
51900
+ return { path: normalized, absolute: !inside };
51901
+ }
51902
+ function projectDiff(value, cwd, remainingTextBytes) {
51903
+ if (!validAbsolutePath(value.path) || typeof value.oldText !== "string" && value.oldText !== null || typeof value.newText !== "string") {
51904
+ return null;
51905
+ }
51906
+ const oldText = value.oldText;
51907
+ const newText = value.newText;
51908
+ if (typeof oldText === "string" && oldText === newText || oldText === null && newText === "") {
51909
+ return null;
51910
+ }
51911
+ const textBytes = Buffer4.byteLength(oldText ?? "", "utf8") + Buffer4.byteLength(newText, "utf8");
51912
+ if (textBytes > remainingTextBytes)
51913
+ return null;
51914
+ const displayed = displayPath2(value.path, cwd);
51915
+ if (!displayed)
51916
+ return null;
51917
+ const kind = oldText === null ? "add" : "update";
51918
+ const oldHeader = kind === "add" ? "/dev/null" : displayed.absolute ? displayed.path : `a/${displayed.path}`;
51919
+ const newHeader = displayed.absolute ? displayed.path : `b/${displayed.path}`;
51920
+ return {
51921
+ change: {
51922
+ path: displayed.path,
51923
+ kind,
51924
+ unifiedDiff: createTwoFilesPatch(oldHeader, newHeader, oldText ?? "", newText, "", "", {
51925
+ context: 3
51926
+ })
51927
+ },
51928
+ textBytes
51929
+ };
51930
+ }
51931
+ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHANGE_TEXT_LIMIT) {
51932
+ if (!Number.isSafeInteger(textLimit) || textLimit <= 0 || !Array.isArray(content))
51933
+ return null;
51934
+ const candidates2 = [];
51935
+ for (const entry of content) {
51936
+ if (isRecord10(entry) && entry.type === "diff")
51937
+ candidates2.push(entry);
51938
+ }
51939
+ if (candidates2.length === 0 || candidates2.length > MAX_GROK_FILE_CHANGES_PER_TOOL)
51940
+ return null;
51941
+ const changes = [];
51942
+ const paths = /* @__PURE__ */ new Set();
51943
+ let textBytes = 0;
51944
+ for (const candidate of candidates2) {
51945
+ const projected = projectDiff(candidate, cwd, textLimit - textBytes);
51946
+ if (!projected || paths.has(projected.change.path))
51947
+ return null;
51948
+ textBytes += projected.textBytes;
51949
+ paths.add(projected.change.path);
51950
+ changes.push(projected.change);
51951
+ }
51952
+ return changes;
51953
+ }
51954
+
51880
51955
  // packages/adapters/grok/dist/grok-history.js
51881
51956
  function jsonValue(value) {
51882
51957
  try {
@@ -51910,7 +51985,8 @@ function isSyntheticGrokUserText(text) {
51910
51985
  function isSyntheticGrokTurnKey(nativeTurnKey3) {
51911
51986
  return taskCompletedTurnKeyPattern.test(nativeTurnKey3);
51912
51987
  }
51913
- function mapGrokReplay(replay, harnessId, sessionId, knownTurnRefs = []) {
51988
+ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = []) {
51989
+ const knownByNativeKey = new Map(knownTurnRefs.filter((ref) => ref.harnessId === harnessId && ref.nativeSessionId === sessionId).map((ref) => [ref.nativeTurnKey, ref]));
51914
51990
  const turns = [];
51915
51991
  let input = "";
51916
51992
  let items = [];
@@ -51938,16 +52014,40 @@ function mapGrokReplay(replay, harnessId, sessionId, knownTurnRefs = []) {
51938
52014
  }
51939
52015
  tools.clear();
51940
52016
  };
52017
+ const completeTool = (callId, status, content) => {
52018
+ const tool = tools.get(callId);
52019
+ if (!tool)
52020
+ return;
52021
+ tools.delete(callId);
52022
+ const outcome = status === "failed" ? {
52023
+ status: "failed",
52024
+ error: {
52025
+ code: "nativeFailure",
52026
+ message: `Grok Tool '${tool.toolName}' failed`,
52027
+ retryable: false
52028
+ }
52029
+ } : { status: "succeeded" };
52030
+ items.push({ item: tool, outcome });
52031
+ if (status !== "completed")
52032
+ return;
52033
+ const changes = projectGrokFileChanges(content, cwd);
52034
+ if (!changes)
52035
+ return;
52036
+ const fileItem = {
52037
+ type: "fileChange",
52038
+ itemId: stableId("file-change", turnIndex, ++messageIndex),
52039
+ changes
52040
+ };
52041
+ items.push({ item: fileItem, outcome: { status: "succeeded" } });
52042
+ };
51941
52043
  const completeTurn = (outcome, terminalKey) => {
51942
52044
  if (input.length === 0)
51943
52045
  return;
51944
- const known = knownTurnRefs[turnIndex];
51945
- if (known && (known.harnessId !== harnessId || known.nativeSessionId !== sessionId)) {
51946
- throw new Error("Known Grok Turn identity does not belong to the Native Session");
51947
- }
51948
- const stableKey = known?.nativeTurnKey ?? terminalKey ?? nativeTurnKey3;
51949
- if (!stableKey)
52046
+ const reconstructedKey = terminalKey ?? nativeTurnKey3;
52047
+ if (!reconstructedKey)
51950
52048
  throw new Error("Grok Native history Turn has no stable identity");
52049
+ const known = knownByNativeKey.get(reconstructedKey);
52050
+ const stableKey = known?.nativeTurnKey ?? reconstructedKey;
51951
52051
  completeReasoning();
51952
52052
  completeAgent();
51953
52053
  completeTools();
@@ -52022,6 +52122,9 @@ function mapGrokReplay(replay, harnessId, sessionId, knownTurnRefs = []) {
52022
52122
  namespace: "grok",
52023
52123
  arguments: jsonValue(event.rawInput)
52024
52124
  });
52125
+ if (event.status === "completed" || event.status === "failed") {
52126
+ completeTool(event.callId, event.status, event.content);
52127
+ }
52025
52128
  } else if (event.type === "tool.update") {
52026
52129
  const tool = tools.get(event.callId);
52027
52130
  if (tool && event.rawOutput !== void 0) {
@@ -52030,17 +52133,17 @@ function mapGrokReplay(replay, harnessId, sessionId, knownTurnRefs = []) {
52030
52133
  output: { content: [{ type: "text", text: String(event.rawOutput) }] }
52031
52134
  });
52032
52135
  }
52136
+ if (event.status === "completed" || event.status === "failed") {
52137
+ completeTool(event.callId, event.status, event.content);
52138
+ }
52033
52139
  }
52034
52140
  }
52035
52141
  completeTurn({ status: "unknown", reason: "Grok Native history has no terminal signal" });
52036
- if (knownTurnRefs.length > turns.length) {
52037
- throw new Error("Grok Native history is missing persisted Turns");
52038
- }
52039
52142
  return { turns };
52040
52143
  }
52041
52144
 
52042
52145
  // packages/adapters/grok/dist/grok-models.js
52043
- function isRecord10(value) {
52146
+ function isRecord11(value) {
52044
52147
  return typeof value === "object" && value !== null && !Array.isArray(value);
52045
52148
  }
52046
52149
  function nonBlank(value) {
@@ -52052,7 +52155,7 @@ function thinkingOptions(value) {
52052
52155
  const seen = /* @__PURE__ */ new Set();
52053
52156
  const options = [];
52054
52157
  for (const candidate of value) {
52055
- if (!isRecord10(candidate) || !nonBlank(candidate.label))
52158
+ if (!isRecord11(candidate) || !nonBlank(candidate.label))
52056
52159
  continue;
52057
52160
  const id2 = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
52058
52161
  if (!id2.success || seen.has(id2.data))
@@ -52063,7 +52166,7 @@ function thinkingOptions(value) {
52063
52166
  return options;
52064
52167
  }
52065
52168
  function parseGrokModelState(value) {
52066
- if (!isRecord10(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
52169
+ if (!isRecord11(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
52067
52170
  return null;
52068
52171
  }
52069
52172
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -52074,12 +52177,12 @@ function parseGrokModelState(value) {
52074
52177
  const models = [];
52075
52178
  let currentThinkingOptionId;
52076
52179
  for (const candidate of value.availableModels) {
52077
- if (!isRecord10(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
52180
+ if (!isRecord11(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
52078
52181
  continue;
52079
52182
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
52080
52183
  if (!ref.success)
52081
52184
  continue;
52082
- const metadata = isRecord10(candidate._meta) ? candidate._meta : {};
52185
+ const metadata = isRecord11(candidate._meta) ? candidate._meta : {};
52083
52186
  const options2 = thinkingOptions(metadata.reasoningEfforts);
52084
52187
  if (typeof metadata.totalContextTokens === "number" && Number.isSafeInteger(metadata.totalContextTokens) && metadata.totalContextTokens > 0) {
52085
52188
  contextWindowTokensByModel.set(ref.data.id, metadata.totalContextTokens);
@@ -52114,10 +52217,10 @@ function parseGrokModelState(value) {
52114
52217
  };
52115
52218
  }
52116
52219
  function modelStateFromInitialize(response) {
52117
- return parseGrokModelState(isRecord10(response._meta) ? response._meta.modelState : void 0);
52220
+ return parseGrokModelState(isRecord11(response._meta) ? response._meta.modelState : void 0);
52118
52221
  }
52119
52222
  function modelStateFromSessionResponse(response) {
52120
- return parseGrokModelState(isRecord10(response) ? response.models : void 0);
52223
+ return parseGrokModelState(isRecord11(response) ? response.models : void 0);
52121
52224
  }
52122
52225
  function stateForGrokModel(modelState, nativeState, model = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId) {
52123
52226
  const selectedModel = model;
@@ -52137,10 +52240,10 @@ function stateForGrokModel(modelState, nativeState, model = modelState.currentMo
52137
52240
  // packages/adapters/grok/dist/grok-credits.js
52138
52241
  import { readFile as readFile2 } from "node:fs/promises";
52139
52242
  import os4 from "node:os";
52140
- import path9 from "node:path";
52243
+ import path10 from "node:path";
52141
52244
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
52142
52245
  var REQUEST_TIMEOUT_MS = 15e3;
52143
- function isRecord11(value) {
52246
+ function isRecord12(value) {
52144
52247
  return typeof value === "object" && value !== null && !Array.isArray(value);
52145
52248
  }
52146
52249
  function finitePercent(value) {
@@ -52154,7 +52257,7 @@ function nonNegativeNumber(value) {
52154
52257
  return value;
52155
52258
  }
52156
52259
  function grokHome(environment) {
52157
- return environment.GROK_HOME ?? path9.join(environment.HOME ?? environment.USERPROFILE ?? os4.homedir(), ".grok");
52260
+ return environment.GROK_HOME ?? path10.join(environment.HOME ?? environment.USERPROFILE ?? os4.homedir(), ".grok");
52158
52261
  }
52159
52262
  function periodTypeFrom(value) {
52160
52263
  if (typeof value !== "string")
@@ -52170,7 +52273,7 @@ function productUsageFrom(value) {
52170
52273
  if (!Array.isArray(value))
52171
52274
  return void 0;
52172
52275
  const products = value.flatMap((entry) => {
52173
- if (!isRecord11(entry) || typeof entry.product !== "string")
52276
+ if (!isRecord12(entry) || typeof entry.product !== "string")
52174
52277
  return [];
52175
52278
  const usagePercent = finitePercent(entry.usagePercent);
52176
52279
  return usagePercent === void 0 ? [] : [{ product: entry.product, usagePercent }];
@@ -52178,13 +52281,13 @@ function productUsageFrom(value) {
52178
52281
  return products.length > 0 ? products : void 0;
52179
52282
  }
52180
52283
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
52181
- if (!isRecord11(value) || !isRecord11(value.config))
52284
+ if (!isRecord12(value) || !isRecord12(value.config))
52182
52285
  return null;
52183
52286
  const config2 = value.config;
52184
- const period = isRecord11(config2.currentPeriod) ? config2.currentPeriod : void 0;
52287
+ const period = isRecord12(config2.currentPeriod) ? config2.currentPeriod : void 0;
52185
52288
  const resetsAt = (typeof period?.end === "string" && period.end.length > 0 ? period.end : void 0) ?? (typeof config2.billingPeriodEnd === "string" && config2.billingPeriodEnd.length > 0 ? config2.billingPeriodEnd : void 0);
52186
- const onDemandCap = isRecord11(config2.onDemandCap) ? nonNegativeNumber(config2.onDemandCap.val) : void 0;
52187
- const onDemandUsed = isRecord11(config2.onDemandUsed) ? nonNegativeNumber(config2.onDemandUsed.val) : void 0;
52289
+ const onDemandCap = isRecord12(config2.onDemandCap) ? nonNegativeNumber(config2.onDemandCap.val) : void 0;
52290
+ const onDemandUsed = isRecord12(config2.onDemandUsed) ? nonNegativeNumber(config2.onDemandUsed.val) : void 0;
52188
52291
  const usedPercent = finitePercent(config2.creditUsagePercent) ?? (onDemandCap !== void 0 && onDemandCap > 0 && onDemandUsed !== void 0 ? Math.min(100, Math.max(0, onDemandUsed / onDemandCap * 100)) : resetsAt ? 0 : void 0);
52189
52292
  if (usedPercent === void 0)
52190
52293
  return null;
@@ -52198,11 +52301,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
52198
52301
  };
52199
52302
  }
52200
52303
  function selectAccessToken(auth, now) {
52201
- if (!isRecord11(auth))
52304
+ if (!isRecord12(auth))
52202
52305
  return null;
52203
- const entries = Object.entries(auth).filter(([, value]) => isRecord11(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
52306
+ const entries = Object.entries(auth).filter(([, value]) => isRecord12(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
52204
52307
  for (const [, value] of entries) {
52205
- if (!isRecord11(value) || typeof value.key !== "string")
52308
+ if (!isRecord12(value) || typeof value.key !== "string")
52206
52309
  continue;
52207
52310
  if (typeof value.expires_at === "string") {
52208
52311
  const expiresAt = Date.parse(value.expires_at);
@@ -52217,7 +52320,7 @@ async function fetchGrokCredits(input = {}) {
52217
52320
  try {
52218
52321
  const environment = input.environment ?? process.env;
52219
52322
  const now = input.now ?? /* @__PURE__ */ new Date();
52220
- const authPath = path9.join(grokHome(environment), "auth.json");
52323
+ const authPath = path10.join(grokHome(environment), "auth.json");
52221
52324
  const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile2(authPath, "utf8");
52222
52325
  const token = selectAccessToken(JSON.parse(raw), now);
52223
52326
  if (!token)
@@ -52242,7 +52345,7 @@ async function fetchGrokCredits(input = {}) {
52242
52345
 
52243
52346
  // packages/adapters/grok/dist/grok-usage.js
52244
52347
  var USD_TICKS_PER_DOLLAR = 1e10;
52245
- function isRecord12(value) {
52348
+ function isRecord13(value) {
52246
52349
  return typeof value === "object" && value !== null && !Array.isArray(value);
52247
52350
  }
52248
52351
  function optionalToken(value) {
@@ -52259,7 +52362,7 @@ function combineUsage(base, next) {
52259
52362
  return base === null ? next : parseHostUsage({ ...base, ...next });
52260
52363
  }
52261
52364
  function usageFromNative(value) {
52262
- if (!isRecord12(value))
52365
+ if (!isRecord13(value))
52263
52366
  return null;
52264
52367
  const inputTokens = optionalToken(value.inputTokens);
52265
52368
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -52286,7 +52389,7 @@ function usageFromPrompt(response) {
52286
52389
  return response.usage ? usageFromNative(response.usage) : null;
52287
52390
  }
52288
52391
  function usageFromSignals(value) {
52289
- if (!isRecord12(value))
52392
+ if (!isRecord13(value))
52290
52393
  return null;
52291
52394
  try {
52292
52395
  return parseHostUsage({
@@ -52297,21 +52400,80 @@ function usageFromSignals(value) {
52297
52400
  return null;
52298
52401
  }
52299
52402
  }
52300
- function lastTurnUsage(events) {
52301
- for (let index = events.length - 1; index >= 0; index -= 1) {
52302
- const event = events[index];
52403
+ var summedUsageFields = [
52404
+ "inputTokens",
52405
+ "cachedInputTokens",
52406
+ "cacheWriteInputTokens",
52407
+ "outputTokens",
52408
+ "reasoningOutputTokens",
52409
+ "totalTokens"
52410
+ ];
52411
+ function nativeCostTicks(value) {
52412
+ if (!isRecord13(value))
52413
+ return void 0;
52414
+ const ticks = value.costUsdTicks;
52415
+ if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
52416
+ return void 0;
52417
+ return ticks;
52418
+ }
52419
+ function historyTurnKey(event, index) {
52420
+ const key = event.nativeTurnKey;
52421
+ if (typeof key === "string" && key.startsWith("task-completed-"))
52422
+ return null;
52423
+ return typeof key === "string" && key.length > 0 ? key : `anon-${index}`;
52424
+ }
52425
+ function sessionUsageFromHistory(events) {
52426
+ const latestByKey = /* @__PURE__ */ new Map();
52427
+ let lastCacheHitRatePercent;
52428
+ let index = 0;
52429
+ for (const event of events) {
52303
52430
  if (event?.type !== "turn.completed")
52304
52431
  continue;
52432
+ const key = historyTurnKey(event, index);
52433
+ index += 1;
52434
+ if (key === null)
52435
+ continue;
52305
52436
  const usage = usageFromNative(event.usage);
52306
- if (usage)
52307
- return usage;
52437
+ if (!usage)
52438
+ continue;
52439
+ const ticks2 = nativeCostTicks(event.usage);
52440
+ latestByKey.set(key, ticks2 === void 0 ? { usage } : { usage, ticks: ticks2 });
52441
+ if (usage.cacheHitRatePercent !== void 0) {
52442
+ lastCacheHitRatePercent = usage.cacheHitRatePercent;
52443
+ }
52444
+ }
52445
+ if (latestByKey.size === 0)
52446
+ return null;
52447
+ const totals = {};
52448
+ let ticks = 0;
52449
+ let hasTicks = false;
52450
+ for (const entry of latestByKey.values()) {
52451
+ for (const field of summedUsageFields) {
52452
+ const value = entry.usage[field];
52453
+ if (value === void 0)
52454
+ continue;
52455
+ totals[field] = (totals[field] ?? 0) + value;
52456
+ }
52457
+ if (entry.ticks === void 0)
52458
+ continue;
52459
+ ticks += entry.ticks;
52460
+ hasTicks = true;
52461
+ }
52462
+ const totalCostUsd = hasTicks ? optionalCostUsd(ticks) : void 0;
52463
+ try {
52464
+ return parseHostUsage({
52465
+ ...totals,
52466
+ ...totalCostUsd !== void 0 ? { totalCostUsd } : {},
52467
+ ...lastCacheHitRatePercent !== void 0 ? { cacheHitRatePercent: lastCacheHitRatePercent } : {}
52468
+ });
52469
+ } catch {
52470
+ return null;
52308
52471
  }
52309
- return null;
52310
52472
  }
52311
52473
  function usageFromUpdate(update, metadata, contextWindowTokens) {
52312
52474
  try {
52313
52475
  if (update?.sessionUpdate === "usage_update") {
52314
- const cost = isRecord12(update.cost) ? update.cost : null;
52476
+ const cost = isRecord13(update.cost) ? update.cost : null;
52315
52477
  return parseHostUsage({
52316
52478
  contextUsedTokens: update.used,
52317
52479
  contextWindowTokens: update.size,
@@ -52345,7 +52507,7 @@ function capabilitiesForModels(modelState) {
52345
52507
  }
52346
52508
  var DEFAULT_CLOSE_TIMEOUT_MS3 = 2e3;
52347
52509
  var DEFAULT_TOOL_OUTPUT_LIMIT3 = 64e3;
52348
- function isRecord13(value) {
52510
+ function isRecord14(value) {
52349
52511
  return typeof value === "object" && value !== null && !Array.isArray(value);
52350
52512
  }
52351
52513
  function invalidState3(message3) {
@@ -52377,10 +52539,10 @@ function jsonValue2(value) {
52377
52539
  return parsed.success ? parsed.data : {};
52378
52540
  }
52379
52541
  function contentText2(content) {
52380
- if (!content)
52542
+ if (!Array.isArray(content))
52381
52543
  return "";
52382
52544
  return content.flatMap((entry) => {
52383
- if (!isRecord13(entry) || entry.type !== "content" || !isRecord13(entry.content))
52545
+ if (!isRecord14(entry) || entry.type !== "content" || !isRecord14(entry.content))
52384
52546
  return [];
52385
52547
  return entry.content.type === "text" && typeof entry.content.text === "string" ? [entry.content.text] : [];
52386
52548
  }).join("\n");
@@ -52434,6 +52596,7 @@ var GrokHarnessSession = class {
52434
52596
  #cwd;
52435
52597
  #modelState;
52436
52598
  #onClosed;
52599
+ #refreshCredits;
52437
52600
  #randomUUID;
52438
52601
  #snapshot;
52439
52602
  #toolOutputLimit;
@@ -52449,6 +52612,7 @@ var GrokHarnessSession = class {
52449
52612
  this.#transport = transport;
52450
52613
  this.#modelState = modelState;
52451
52614
  this.#onClosed = onClosed;
52615
+ this.#refreshCredits = options.refreshCredits;
52452
52616
  this.#closeTimeoutMs = options.closeTimeoutMs;
52453
52617
  this.#randomUUID = options.randomUUID;
52454
52618
  this.#toolOutputLimit = options.toolOutputLimit;
@@ -52458,7 +52622,7 @@ var GrokHarnessSession = class {
52458
52622
  this.#state = stateForGrokModel(modelState, { nativeRef: nativeRef(opened.sessionId) });
52459
52623
  this.initialState = this.#state;
52460
52624
  this.#snapshot = {
52461
- ...mapGrokReplay(options.history, this.harnessId, opened.sessionId, options.knownTurnRefs),
52625
+ ...mapGrokReplay(options.history, this.harnessId, opened.sessionId, cwd, options.knownTurnRefs),
52462
52626
  state: this.#state
52463
52627
  };
52464
52628
  this.outputs = this.#channel.outputs;
@@ -52568,7 +52732,7 @@ var GrokHarnessSession = class {
52568
52732
  async #refreshSnapshot() {
52569
52733
  const history = await this.#transport.getHistory();
52570
52734
  const knownTurnRefs = this.#snapshot.turns.map((turn) => turn.nativeTurnRef);
52571
- const refreshed = mapGrokReplay(history, this.harnessId, this.#transport.sessionId, knownTurnRefs);
52735
+ const refreshed = mapGrokReplay(history, this.harnessId, this.#transport.sessionId, this.#cwd, knownTurnRefs);
52572
52736
  this.#snapshot.turns = refreshed.turns;
52573
52737
  return history;
52574
52738
  }
@@ -52715,11 +52879,7 @@ var GrokHarnessSession = class {
52715
52879
  this.#startTool(active, event);
52716
52880
  else if (event.type === "tool.update")
52717
52881
  this.#updateTool(active, event);
52718
- else if (event.type === "turn.completed") {
52719
- const usage = usageFromNative(event.usage);
52720
- if (usage)
52721
- this.#publishUsage(usage, active.command.turnId);
52722
- } else if (event.type === "usage")
52882
+ else if (event.type === "usage" || event.type === "turn.completed")
52723
52883
  return;
52724
52884
  }
52725
52885
  #appendAgent(active, text, messageId) {
@@ -52781,8 +52941,9 @@ var GrokHarnessSession = class {
52781
52941
  };
52782
52942
  active.tools.set(event.callId, { item, ...event.status ? { status: event.status } : {} });
52783
52943
  this.#event({ type: "item.started", turnId: active.command.turnId, item });
52784
- if (event.status === "completed" || event.status === "failed")
52785
- this.#completeTool(active, event.callId, event.status);
52944
+ if (event.status === "completed" || event.status === "failed") {
52945
+ this.#completeTool(active, event.callId, event.status, event.content);
52946
+ }
52786
52947
  }
52787
52948
  #updateTool(active, event) {
52788
52949
  const tool = active.tools.get(event.callId);
@@ -52800,10 +52961,11 @@ var GrokHarnessSession = class {
52800
52961
  }
52801
52962
  if (event.status)
52802
52963
  tool.status = event.status;
52803
- if (event.status === "completed" || event.status === "failed")
52804
- this.#completeTool(active, event.callId, event.status);
52964
+ if (event.status === "completed" || event.status === "failed") {
52965
+ this.#completeTool(active, event.callId, event.status, event.content);
52966
+ }
52805
52967
  }
52806
- #completeTool(active, callId, status) {
52968
+ #completeTool(active, callId, status, content) {
52807
52969
  const tool = active.tools.get(callId);
52808
52970
  if (!tool)
52809
52971
  return;
@@ -52817,6 +52979,18 @@ var GrokHarnessSession = class {
52817
52979
  }
52818
52980
  } : { status: "succeeded" };
52819
52981
  this.#completeItem(active, tool.item, outcome);
52982
+ if (status !== "completed")
52983
+ return;
52984
+ const changes = projectGrokFileChanges(content, this.#cwd);
52985
+ if (!changes)
52986
+ return;
52987
+ const fileItem = {
52988
+ type: "fileChange",
52989
+ itemId: hostItemIdSchema.parse(this.#randomUUID()),
52990
+ changes
52991
+ };
52992
+ this.#event({ type: "item.started", turnId: active.command.turnId, item: fileItem });
52993
+ this.#completeItem(active, fileItem, { status: "succeeded" });
52820
52994
  }
52821
52995
  #completeAgent(active, outcome) {
52822
52996
  const item = active.agent;
@@ -52856,7 +53030,8 @@ var GrokHarnessSession = class {
52856
53030
  outcome = { status: "failed", error: normalizeError(error52, "protocolError") };
52857
53031
  }
52858
53032
  }
52859
- this.#finish(active, outcome, lastTurnUsage(history) ?? (response ? usageFromPrompt(response) : null), nativeTurnRef2);
53033
+ await this.#refreshCredits().catch(() => void 0);
53034
+ this.#finish(active, outcome, sessionUsageFromHistory(history) ?? (response ? usageFromPrompt(response) : null), nativeTurnRef2);
52860
53035
  }
52861
53036
  #finish(active, outcome, usage = null, nativeTurnRef2) {
52862
53037
  if (this.#active !== active)
@@ -52989,7 +53164,7 @@ var GrokAdapter = class {
52989
53164
  async inspect(input = {}) {
52990
53165
  if (this.#closePromise)
52991
53166
  return { status: "unavailable", error: invalidState3("Grok Adapter is closed") };
52992
- const cwd = path10.resolve(input.cwd ?? process.cwd());
53167
+ const cwd = path11.resolve(input.cwd ?? process.cwd());
52993
53168
  if (!input.refresh) {
52994
53169
  const cached2 = this.#inspectionCache.get(cwd);
52995
53170
  if (cached2)
@@ -53048,7 +53223,7 @@ var GrokAdapter = class {
53048
53223
  }
53049
53224
  };
53050
53225
  }
53051
- const cwd = path10.resolve(input.cwd);
53226
+ const cwd = path11.resolve(input.cwd);
53052
53227
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
53053
53228
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
53054
53229
  return {
@@ -53086,13 +53261,14 @@ var GrokAdapter = class {
53086
53261
  }
53087
53262
  }
53088
53263
  const history = await transport.getHistory();
53089
- const initialUsage = input.kind === "resume" ? combineUsage(lastTurnUsage(history), usageFromSignals(opened.signals)) : null;
53264
+ const initialUsage = input.kind === "resume" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
53090
53265
  const openedSession = new GrokHarnessSession(cwd, transport, opened, modelState, () => this.#sessions.delete(openedSession), {
53091
53266
  closeTimeoutMs: this.#closeTimeoutMs,
53092
53267
  history,
53093
53268
  initialUsage,
53094
53269
  ...input.kind === "resume" && input.knownTurnRefs ? { knownTurnRefs: input.knownTurnRefs } : {},
53095
53270
  randomUUID: this.#dependencies.randomUUID,
53271
+ refreshCredits: () => this.refreshCredits(),
53096
53272
  toolOutputLimit: this.#toolOutputLimit
53097
53273
  });
53098
53274
  session = openedSession;
@@ -53235,7 +53411,7 @@ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, e
53235
53411
 
53236
53412
  // packages/adapters/pi/dist/pi-history.js
53237
53413
  var piHarnessId = harnessIdSchema.parse("pi");
53238
- function isRecord14(value) {
53414
+ function isRecord15(value) {
53239
53415
  return typeof value === "object" && value !== null && !Array.isArray(value);
53240
53416
  }
53241
53417
  function textContent(value) {
@@ -53243,12 +53419,12 @@ function textContent(value) {
53243
53419
  return value;
53244
53420
  if (!Array.isArray(value))
53245
53421
  return "";
53246
- return value.filter((part) => isRecord14(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
53422
+ return value.filter((part) => isRecord15(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
53247
53423
  }
53248
53424
  function thinkingContent(value) {
53249
53425
  if (!Array.isArray(value))
53250
53426
  return "";
53251
- return value.filter((part) => isRecord14(part) && part.type === "thinking" && typeof part.thinking === "string").map((part) => part.thinking).join("");
53427
+ return value.filter((part) => isRecord15(part) && part.type === "thinking" && typeof part.thinking === "string").map((part) => part.thinking).join("");
53252
53428
  }
53253
53429
  function validatedEntry(value) {
53254
53430
  if (typeof value.id !== "string" || value.id.length === 0 || value.parentId !== null && typeof value.parentId !== "string" || typeof value.type !== "string") {
@@ -53279,7 +53455,7 @@ function activePiEntries(history) {
53279
53455
  return reversed.reverse();
53280
53456
  }
53281
53457
  function message(entry) {
53282
- return entry.type === "message" && isRecord14(entry.message) ? entry.message : null;
53458
+ return entry.type === "message" && isRecord15(entry.message) ? entry.message : null;
53283
53459
  }
53284
53460
  function messageRole(entry) {
53285
53461
  const value = message(entry)?.role;
@@ -53341,7 +53517,7 @@ function snapshotItems(entries, outcome) {
53341
53517
  let projectedText = false;
53342
53518
  let projectedReasoning = false;
53343
53519
  for (const [ordinal, part] of content.entries()) {
53344
- if (!isRecord14(part))
53520
+ if (!isRecord15(part))
53345
53521
  continue;
53346
53522
  if (part.type === "thinking" && !projectedReasoning && reasoning.length > 0) {
53347
53523
  const item2 = {
@@ -53533,12 +53709,12 @@ async function rollbackPiLastTurn(transport, sourceSessionId, cwd) {
53533
53709
  // packages/adapters/pi/dist/pi-rpc-session.js
53534
53710
  import { spawn as spawn4, spawnSync as spawnSync2 } from "node:child_process";
53535
53711
  import { randomUUID as randomUUID4 } from "node:crypto";
53536
- import path12 from "node:path";
53712
+ import path13 from "node:path";
53537
53713
 
53538
53714
  // packages/adapters/pi/dist/command.js
53539
53715
  import { accessSync as accessSync2, constants as constants2, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
53540
53716
  import os5 from "node:os";
53541
- import path11 from "node:path";
53717
+ import path12 from "node:path";
53542
53718
  function environmentValue2(environment, name) {
53543
53719
  return Object.entries(environment).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
53544
53720
  }
@@ -53551,34 +53727,35 @@ function isExecutable3(filePath, platform) {
53551
53727
  }
53552
53728
  }
53553
53729
  function pathCandidates(command, platform, environment) {
53554
- const targetPath = platform === "win32" ? path11.win32 : path11.posix;
53730
+ const targetPath = platform === "win32" ? path12.win32 : path12.posix;
53555
53731
  if (targetPath.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
53556
53732
  return [command];
53557
53733
  }
53558
53734
  const extensions = platform === "win32" && targetPath.extname(command) === "" ? (environmentValue2(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean) : [""];
53559
53735
  return (environmentValue2(environment, "PATH") ?? "").split(targetPath.delimiter).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean).flatMap((directory) => extensions.map((extension) => targetPath.join(directory, command + extension)));
53560
53736
  }
53561
- function nvmCandidates2(homeDirectory, executableName) {
53562
- const versionsDirectory = path11.join(homeDirectory, ".nvm", "versions", "node");
53737
+ function nvmCandidates2(homeDirectory, executableName, targetPath) {
53738
+ const versionsDirectory = targetPath.join(homeDirectory, ".nvm", "versions", "node");
53563
53739
  try {
53564
- return readdirSync2(versionsDirectory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((left, right) => right.localeCompare(left, void 0, { numeric: true })).map((version2) => path11.join(versionsDirectory, version2, "bin", executableName));
53740
+ return readdirSync2(versionsDirectory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((left, right) => right.localeCompare(left, void 0, { numeric: true })).map((version2) => targetPath.join(versionsDirectory, version2, "bin", executableName));
53565
53741
  } catch {
53566
53742
  return [];
53567
53743
  }
53568
53744
  }
53569
53745
  function userInstallCandidates2(platform, environment, homeDirectory) {
53746
+ const targetPath = platform === "win32" ? path12.win32 : path12.posix;
53570
53747
  if (platform === "win32") {
53571
- const appData = environment.APPDATA ?? path11.join(homeDirectory, "AppData", "Roaming");
53748
+ const appData = environment.APPDATA ?? targetPath.join(homeDirectory, "AppData", "Roaming");
53572
53749
  return [
53573
- path11.join(appData, "npm", "pi.cmd"),
53574
- path11.join(homeDirectory, ".local", "bin", "pi.exe"),
53575
- path11.join(homeDirectory, ".local", "bin", "pi.cmd")
53750
+ targetPath.join(appData, "npm", "pi.cmd"),
53751
+ targetPath.join(homeDirectory, ".local", "bin", "pi.exe"),
53752
+ targetPath.join(homeDirectory, ".local", "bin", "pi.cmd")
53576
53753
  ];
53577
53754
  }
53578
53755
  return [
53579
- path11.join(homeDirectory, ".npm-global", "bin", "pi"),
53580
- path11.join(homeDirectory, ".local", "bin", "pi"),
53581
- ...nvmCandidates2(homeDirectory, "pi"),
53756
+ targetPath.join(homeDirectory, ".npm-global", "bin", "pi"),
53757
+ targetPath.join(homeDirectory, ".local", "bin", "pi"),
53758
+ ...nvmCandidates2(homeDirectory, "pi", targetPath),
53582
53759
  "/opt/homebrew/bin/pi",
53583
53760
  "/usr/local/bin/pi"
53584
53761
  ];
@@ -53598,7 +53775,7 @@ function resolvePiExecutable(input, dependencies = {}) {
53598
53775
  function withNodeRuntimeOnPath2(environment, runtimeExecutable = process.execPath, platform = process.platform) {
53599
53776
  const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
53600
53777
  const delimiter = platform === "win32" ? ";" : ":";
53601
- const runtimeDirectory = path11.dirname(runtimeExecutable);
53778
+ const runtimeDirectory = path12.dirname(runtimeExecutable);
53602
53779
  const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
53603
53780
  const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
53604
53781
  if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
@@ -53608,14 +53785,14 @@ function withNodeRuntimeOnPath2(environment, runtimeExecutable = process.execPat
53608
53785
  }
53609
53786
 
53610
53787
  // packages/adapters/pi/dist/pi-usage.js
53611
- function isRecord15(value) {
53788
+ function isRecord16(value) {
53612
53789
  return typeof value === "object" && value !== null && !Array.isArray(value);
53613
53790
  }
53614
53791
  function nonNegativeSafeInteger2(value) {
53615
53792
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
53616
53793
  }
53617
53794
  function optionalPiCacheHitRatePercent(value) {
53618
- if (!isRecord15(value) || value.role !== "assistant" || !isRecord15(value.usage))
53795
+ if (!isRecord16(value) || value.role !== "assistant" || !isRecord16(value.usage))
53619
53796
  return null;
53620
53797
  const input = nonNegativeSafeInteger2(value.usage.input);
53621
53798
  const cacheRead = nonNegativeSafeInteger2(value.usage.cacheRead);
@@ -53628,20 +53805,20 @@ function optionalPiCacheHitRatePercent(value) {
53628
53805
  function latestPiCacheHitRatePercent(history) {
53629
53806
  let latest = null;
53630
53807
  for (const entry of activePiEntries(history)) {
53631
- if (entry.type === "message" && isRecord15(entry.message) && entry.message.role === "assistant") {
53808
+ if (entry.type === "message" && isRecord16(entry.message) && entry.message.role === "assistant") {
53632
53809
  latest = optionalPiCacheHitRatePercent(entry.message);
53633
53810
  }
53634
53811
  }
53635
53812
  return latest;
53636
53813
  }
53637
53814
  function responseData(response, operation) {
53638
- if (!isRecord15(response.data)) {
53815
+ if (!isRecord16(response.data)) {
53639
53816
  throw new Error(`Pi RPC ${operation} response has no data`);
53640
53817
  }
53641
53818
  return response.data;
53642
53819
  }
53643
53820
  function contextUsage(value) {
53644
- if (!isRecord15(value))
53821
+ if (!isRecord16(value))
53645
53822
  throw new Error("Pi RPC context Usage is invalid");
53646
53823
  return parseHostUsage({
53647
53824
  contextUsedTokens: value.tokens,
@@ -53651,15 +53828,15 @@ function contextUsage(value) {
53651
53828
  function parsePiSessionUsage(response) {
53652
53829
  const data = responseData(response, "Session stats");
53653
53830
  const tokens = data.tokens;
53654
- if (tokens !== void 0 && !isRecord15(tokens)) {
53831
+ if (tokens !== void 0 && !isRecord16(tokens)) {
53655
53832
  throw new Error("Pi RPC Session stats tokens are invalid");
53656
53833
  }
53657
53834
  return parseHostUsage({
53658
- ...isRecord15(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
53659
- ...isRecord15(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
53660
- ...isRecord15(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
53661
- ...isRecord15(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
53662
- ...isRecord15(tokens) && tokens.total !== void 0 ? { totalTokens: tokens.total } : {},
53835
+ ...isRecord16(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
53836
+ ...isRecord16(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
53837
+ ...isRecord16(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
53838
+ ...isRecord16(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
53839
+ ...isRecord16(tokens) && tokens.total !== void 0 ? { totalTokens: tokens.total } : {},
53663
53840
  ...data.cost !== void 0 ? { totalCostUsd: data.cost } : {},
53664
53841
  ...data.contextUsage !== void 0 ? contextUsage(data.contextUsage) : {}
53665
53842
  });
@@ -53682,7 +53859,7 @@ function optionalPiStateContextUsage(value) {
53682
53859
  import { open, realpath } from "node:fs/promises";
53683
53860
  var MAX_SESSION_HEADER_BYTES = 64 * 1024;
53684
53861
  var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
53685
- function isRecord16(value) {
53862
+ function isRecord17(value) {
53686
53863
  return typeof value === "object" && value !== null && !Array.isArray(value);
53687
53864
  }
53688
53865
  async function readPiSessionHeader(sessionFile) {
@@ -53702,7 +53879,7 @@ async function readPiSessionHeader(sessionFile) {
53702
53879
  } catch {
53703
53880
  throw new Error("Pi Session header is not valid JSON");
53704
53881
  }
53705
- if (!isRecord16(parsed) || parsed.type !== "session" || typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
53882
+ if (!isRecord17(parsed) || parsed.type !== "session" || typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
53706
53883
  throw new Error("Pi Session header is invalid");
53707
53884
  }
53708
53885
  return { type: "session", id: parsed.id, cwd: parsed.cwd };
@@ -53744,7 +53921,7 @@ var PiRpcUnsupportedCommandError = class extends Error {
53744
53921
  }
53745
53922
  };
53746
53923
  var textDecoder = new TextDecoder("utf-8", { fatal: true });
53747
- function isRecord17(value) {
53924
+ function isRecord18(value) {
53748
53925
  return typeof value === "object" && value !== null && !Array.isArray(value);
53749
53926
  }
53750
53927
  function message2(value) {
@@ -53756,13 +53933,13 @@ function nonBlankString2(value) {
53756
53933
  function parseNativeModel(value, context) {
53757
53934
  if (value === null || value === void 0)
53758
53935
  return null;
53759
- if (!isRecord17(value) || !nonBlankString2(value.provider) || !nonBlankString2(value.id)) {
53936
+ if (!isRecord18(value) || !nonBlankString2(value.provider) || !nonBlankString2(value.id)) {
53760
53937
  throw new PiRpcFaultError("protocolError", `Pi RPC returned an invalid ${context} Model`);
53761
53938
  }
53762
53939
  return { provider: value.provider, id: value.id };
53763
53940
  }
53764
53941
  function sessionStateData(response) {
53765
- const data = isRecord17(response.data) ? response.data : null;
53942
+ const data = isRecord18(response.data) ? response.data : null;
53766
53943
  if (!data)
53767
53944
  throw new PiRpcFaultError("protocolError", "Pi RPC state response has no data");
53768
53945
  return data;
@@ -53794,13 +53971,13 @@ function parseSessionStreaming(response) {
53794
53971
  return isStreaming;
53795
53972
  }
53796
53973
  function parseSessionHistory(response) {
53797
- const data = isRecord17(response.data) ? response.data : null;
53974
+ const data = isRecord18(response.data) ? response.data : null;
53798
53975
  if (!data || !Array.isArray(data.entries)) {
53799
53976
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response has no Entries");
53800
53977
  }
53801
53978
  const entries = data.entries.map((entry) => {
53802
53979
  const parsed = jsonValueSchema.safeParse(entry);
53803
- if (!parsed.success || !isRecord17(parsed.data)) {
53980
+ if (!parsed.success || !isRecord18(parsed.data)) {
53804
53981
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response contains an invalid Entry");
53805
53982
  }
53806
53983
  return parsed.data;
@@ -53811,7 +53988,7 @@ function parseSessionHistory(response) {
53811
53988
  return { entries, leafId: data.leafId };
53812
53989
  }
53813
53990
  function parseAvailableThinkingLevels(response) {
53814
- const data = isRecord17(response.data) ? response.data : null;
53991
+ const data = isRecord18(response.data) ? response.data : null;
53815
53992
  if (!data || !Array.isArray(data.levels) || data.levels.length === 0) {
53816
53993
  throw new PiRpcFaultError("protocolError", "Pi RPC Thinking catalog response has no levels");
53817
53994
  }
@@ -53828,35 +54005,35 @@ function parseAvailableThinkingLevels(response) {
53828
54005
  return levels;
53829
54006
  }
53830
54007
  function parseAvailableModels(response) {
53831
- const data = isRecord17(response.data) ? response.data : null;
54008
+ const data = isRecord18(response.data) ? response.data : null;
53832
54009
  if (!data || !Array.isArray(data.models)) {
53833
54010
  throw new PiRpcFaultError("protocolError", "Pi RPC Model catalog response has no models");
53834
54011
  }
53835
54012
  return data.models.map((model) => {
53836
54013
  const parsed = parseNativeModel(model, "catalog");
53837
- if (!parsed || !isRecord17(model) || typeof model.reasoning !== "boolean") {
54014
+ if (!parsed || !isRecord18(model) || typeof model.reasoning !== "boolean") {
53838
54015
  throw new PiRpcFaultError("protocolError", "Pi RPC catalog contains a Model without reasoning capability");
53839
54016
  }
53840
54017
  return { ...parsed, reasoning: model.reasoning };
53841
54018
  });
53842
54019
  }
53843
54020
  function assistantText2(value) {
53844
- if (!isRecord17(value) || value.role !== "assistant" || !Array.isArray(value.content))
54021
+ if (!isRecord18(value) || value.role !== "assistant" || !Array.isArray(value.content))
53845
54022
  return null;
53846
- return value.content.filter((content) => isRecord17(content) && content.type === "text" && typeof content.text === "string").map((content) => content.text).join("");
54023
+ return value.content.filter((content) => isRecord18(content) && content.type === "text" && typeof content.text === "string").map((content) => content.text).join("");
53847
54024
  }
53848
54025
  function assistantMessageId(value) {
53849
- if (!isRecord17(value) || value.role !== "assistant")
54026
+ if (!isRecord18(value) || value.role !== "assistant")
53850
54027
  return null;
53851
54028
  return nonBlankString2(value.responseId) ? value.responseId : null;
53852
54029
  }
53853
54030
  function assistantReasoning(value) {
53854
- if (!isRecord17(value) || value.role !== "assistant" || !Array.isArray(value.content))
54031
+ if (!isRecord18(value) || value.role !== "assistant" || !Array.isArray(value.content))
53855
54032
  return null;
53856
- return value.content.filter((content) => isRecord17(content) && content.type === "thinking" && typeof content.thinking === "string").map((content) => content.thinking).join("");
54033
+ return value.content.filter((content) => isRecord18(content) && content.type === "thinking" && typeof content.thinking === "string").map((content) => content.thinking).join("");
53857
54034
  }
53858
54035
  function assistantFailure(value) {
53859
- if (!isRecord17(value) || value.role !== "assistant")
54036
+ if (!isRecord18(value) || value.role !== "assistant")
53860
54037
  return void 0;
53861
54038
  if (value.stopReason !== "error" && value.stopReason !== "aborted")
53862
54039
  return null;
@@ -53876,7 +54053,7 @@ function signalProcessTree2(child, signal) {
53876
54053
  try {
53877
54054
  process.kill(-child.pid, signal);
53878
54055
  } catch (error52) {
53879
- if (!isRecord17(error52) || error52.code !== "ESRCH")
54056
+ if (!isRecord18(error52) || error52.code !== "ESRCH")
53880
54057
  throw error52;
53881
54058
  }
53882
54059
  }
@@ -53907,7 +54084,7 @@ function piRpcProcessCommand(options, dependencies = {}) {
53907
54084
  const sessionArguments = options.forkSessionFile ? ["--fork", options.forkSessionFile] : options.sessionFile ? ["--session", options.sessionFile] : [];
53908
54085
  const modelArguments = options.model ? ["--provider", options.model.provider, "--model", options.model.id] : [];
53909
54086
  const arguments_2 = ["--mode", "rpc", ...modelArguments, ...sessionArguments];
53910
- const extension = path12.win32.extname(command).toLowerCase();
54087
+ const extension = path13.win32.extname(command).toLowerCase();
53911
54088
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
53912
54089
  return { command, arguments: arguments_2, windowsVerbatimArguments: false };
53913
54090
  }
@@ -53990,7 +54167,7 @@ var PiRpcSession = class {
53990
54167
  });
53991
54168
  child.stderr.resume();
53992
54169
  child.once("error", (error52) => {
53993
- const kind = isRecord17(error52) && error52.code === "ENOENT" ? "notInstalled" : "unavailable";
54170
+ const kind = isRecord18(error52) && error52.code === "ENOENT" ? "notInstalled" : "unavailable";
53994
54171
  this.#fail(new PiRpcFaultError(kind, `Pi RPC failed to start: ${error52.message}`));
53995
54172
  });
53996
54173
  child.once("exit", (code, signal) => {
@@ -54242,7 +54419,7 @@ var PiRpcSession = class {
54242
54419
  this.#buffer = this.#buffer.subarray(newline3 + 1);
54243
54420
  try {
54244
54421
  const value = JSON.parse(textDecoder.decode(frame));
54245
- if (!isRecord17(value) || typeof value.type !== "string") {
54422
+ if (!isRecord18(value) || typeof value.type !== "string") {
54246
54423
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid envelope");
54247
54424
  }
54248
54425
  this.#handle(value);
@@ -54281,7 +54458,7 @@ var PiRpcSession = class {
54281
54458
  }
54282
54459
  compactionTurn?.onEvent({
54283
54460
  type: "compaction.completed",
54284
- outcome: value.aborted === true ? "cancelled" : isRecord17(value.result) ? "succeeded" : "failed",
54461
+ outcome: value.aborted === true ? "cancelled" : isRecord18(value.result) ? "succeeded" : "failed",
54285
54462
  ...nonBlankString2(value.errorMessage) ? { errorMessage: value.errorMessage } : {}
54286
54463
  });
54287
54464
  return;
@@ -54301,7 +54478,7 @@ var PiRpcSession = class {
54301
54478
  this.#startAssistantMessage(active, value.message);
54302
54479
  return;
54303
54480
  }
54304
- if (value.type === "message_update" && isRecord17(value.assistantMessageEvent)) {
54481
+ if (value.type === "message_update" && isRecord18(value.assistantMessageEvent)) {
54305
54482
  const event = value.assistantMessageEvent;
54306
54483
  if (event.type === "text_delta" && typeof event.delta === "string") {
54307
54484
  const messageId = this.#ensureAssistantMessage(active, value.message);
@@ -54695,7 +54872,7 @@ var PiRpcSession = class {
54695
54872
  // packages/adapters/pi/dist/pi-adapter.js
54696
54873
  var piHarnessId2 = harnessIdSchema.parse("pi");
54697
54874
  var DEFAULT_TOOL_OUTPUT_LIMIT4 = 64e3;
54698
- function isRecord18(value) {
54875
+ function isRecord19(value) {
54699
54876
  return typeof value === "object" && value !== null && !Array.isArray(value);
54700
54877
  }
54701
54878
  function errorMessage(error52) {
@@ -54769,7 +54946,7 @@ function nativeModelForHistory(state) {
54769
54946
  return nativeModelFromState(state);
54770
54947
  }
54771
54948
  function sessionFileFromRef(ref) {
54772
- if (ref.harnessId !== piHarnessId2 || !isRecord18(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
54949
+ if (ref.harnessId !== piHarnessId2 || !isRecord19(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
54773
54950
  throw new Error("Pi Native Session Ref has no resumable Session file");
54774
54951
  }
54775
54952
  return ref.locator.sessionFile;
@@ -54784,9 +54961,9 @@ function toolFailure2(toolName) {
54784
54961
  function nativeText(value) {
54785
54962
  if (typeof value === "string")
54786
54963
  return value;
54787
- if (!isRecord18(value) || !Array.isArray(value.content))
54964
+ if (!isRecord19(value) || !Array.isArray(value.content))
54788
54965
  return "";
54789
- return value.content.filter((content) => isRecord18(content) && content.type === "text" && typeof content.text === "string").map(({ text }) => text).join("");
54966
+ return value.content.filter((content) => isRecord19(content) && content.type === "text" && typeof content.text === "string").map(({ text }) => text).join("");
54790
54967
  }
54791
54968
  function boundedOutput(value, limit) {
54792
54969
  const text = nativeText(value);
@@ -54802,19 +54979,19 @@ function outputText2(output) {
54802
54979
  return output?.content.filter((content) => content.type === "text").map(({ text }) => text).join("") ?? "";
54803
54980
  }
54804
54981
  function stringField2(value, key) {
54805
- return isRecord18(value) && typeof value[key] === "string" ? value[key] : void 0;
54982
+ return isRecord19(value) && typeof value[key] === "string" ? value[key] : void 0;
54806
54983
  }
54807
54984
  function numberField(value, key) {
54808
- if (!isRecord18(value))
54985
+ if (!isRecord19(value))
54809
54986
  return void 0;
54810
54987
  const field = value[key];
54811
54988
  return typeof field === "number" || field === null ? field : void 0;
54812
54989
  }
54813
- function stripDiffPrefix(path18) {
54814
- return path18.startsWith("a/") || path18.startsWith("b/") ? path18.slice(2) : path18;
54990
+ function stripDiffPrefix(path19) {
54991
+ return path19.startsWith("a/") || path19.startsWith("b/") ? path19.slice(2) : path19;
54815
54992
  }
54816
54993
  function reliableFileChange(result) {
54817
- if (!isRecord18(result) || !isRecord18(result.details) || typeof result.details.patch !== "string") {
54994
+ if (!isRecord19(result) || !isRecord19(result.details) || typeof result.details.patch !== "string") {
54818
54995
  return null;
54819
54996
  }
54820
54997
  const patch = result.details.patch;
@@ -54830,10 +55007,10 @@ function reliableFileChange(result) {
54830
55007
  const oldFile = file2.oldFileName;
54831
55008
  const newFile = file2.newFileName;
54832
55009
  const kind = oldFile === "/dev/null" ? "add" : newFile === "/dev/null" ? "delete" : "update";
54833
- const path18 = stripDiffPrefix(kind === "delete" ? oldFile : newFile);
54834
- if (!path18 || path18 === "/dev/null")
55010
+ const path19 = stripDiffPrefix(kind === "delete" ? oldFile : newFile);
55011
+ if (!path19 || path19 === "/dev/null")
54835
55012
  return null;
54836
- return [{ path: path18, kind, unifiedDiff: patch }];
55013
+ return [{ path: path19, kind, unifiedDiff: patch }];
54837
55014
  }
54838
55015
  function delay3(milliseconds) {
54839
55016
  return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
@@ -56077,7 +56254,7 @@ import { execFileSync } from "node:child_process";
56077
56254
  import { randomUUID as randomUUID6 } from "node:crypto";
56078
56255
  import { constants as constants3 } from "node:fs";
56079
56256
  import { copyFile, mkdir, open as open2, readFile as readFile3, readdir, rename, rm as rm2, stat } from "node:fs/promises";
56080
- import path13 from "node:path";
56257
+ import path14 from "node:path";
56081
56258
 
56082
56259
  // packages/mapping-store/dist/records.js
56083
56260
  var nonBlankTextSchema3 = external_exports.string().refine((value) => value.trim().length > 0, {
@@ -56244,6 +56421,18 @@ function isNodeExecutable(value) {
56244
56421
  function lockOwnerIsLive(lock) {
56245
56422
  if (typeof lock.pid !== "number")
56246
56423
  return false;
56424
+ if (lock.pid === process.pid) {
56425
+ if (lock.executablePath && normalizeExecutablePath(lock.executablePath) !== normalizeExecutablePath(process.execPath)) {
56426
+ return false;
56427
+ }
56428
+ if (lock.processStartedAt) {
56429
+ const expected = Date.parse(lock.processStartedAt);
56430
+ const actual = Date.now() - process.uptime() * 1e3;
56431
+ if (Number.isFinite(expected) && Math.abs(actual - expected) > 5e3)
56432
+ return false;
56433
+ }
56434
+ return true;
56435
+ }
56247
56436
  const identity = processIdentity(lock.pid);
56248
56437
  if (!identity)
56249
56438
  return false;
@@ -56282,11 +56471,11 @@ var MappingStore = class {
56282
56471
  #initialized = false;
56283
56472
  #lockHandle = null;
56284
56473
  constructor(options) {
56285
- this.#directory = path13.resolve(options.directory);
56286
- this.#threadsDirectory = path13.join(this.#directory, "threads");
56287
- this.#backupsDirectory = path13.join(this.#directory, "backups");
56288
- this.#quarantineDirectory = path13.join(this.#directory, "quarantine");
56289
- this.#lockPath = path13.join(this.#directory, "store.lock");
56474
+ this.#directory = path14.resolve(options.directory);
56475
+ this.#threadsDirectory = path14.join(this.#directory, "threads");
56476
+ this.#backupsDirectory = path14.join(this.#directory, "backups");
56477
+ this.#quarantineDirectory = path14.join(this.#directory, "quarantine");
56478
+ this.#lockPath = path14.join(this.#directory, "store.lock");
56290
56479
  this.#instanceId = options.instanceId ?? randomUUID6();
56291
56480
  this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
56292
56481
  this.#beforeReplace = options.beforeReplace;
@@ -56304,8 +56493,8 @@ var MappingStore = class {
56304
56493
  await this.#cleanupTemps();
56305
56494
  const names = (await readdir(this.#threadsDirectory)).filter((name) => name.endsWith(".json"));
56306
56495
  for (const name of names) {
56307
- const primary = path13.join(this.#threadsDirectory, name);
56308
- const backup = path13.join(this.#backupsDirectory, name);
56496
+ const primary = path14.join(this.#threadsDirectory, name);
56497
+ const backup = path14.join(this.#backupsDirectory, name);
56309
56498
  let record3 = null;
56310
56499
  try {
56311
56500
  record3 = await this.#readRecord(primary, name);
@@ -56314,7 +56503,7 @@ var MappingStore = class {
56314
56503
  record3 = await this.#readRecord(backup, name);
56315
56504
  await this.#replaceFile(primary, record3, false);
56316
56505
  } catch (backupError) {
56317
- const quarantine = path13.join(this.#quarantineDirectory, `${name}.${this.#now().getTime()}.invalid`);
56506
+ const quarantine = path14.join(this.#quarantineDirectory, `${name}.${this.#now().getTime()}.invalid`);
56318
56507
  await rename(primary, quarantine).catch(() => void 0);
56319
56508
  void primaryError;
56320
56509
  void backupError;
@@ -56423,27 +56612,29 @@ var MappingStore = class {
56423
56612
  if (current.state !== "ready" || !current.nativeSessionRef) {
56424
56613
  throw new MappingStoreError("MAPPING_CONFLICT", "Only a ready Thread can reconcile Snapshot mappings");
56425
56614
  }
56426
- const merged = this.#mergeMappings(current.turnMappings, mappings);
56427
- if (merged.length !== mappings.length) {
56428
- throw new MappingStoreError("MAPPING_CONFLICT", "Snapshot reconciliation must retain every existing Turn mapping");
56429
- }
56430
- const mergedByHost = new Map(merged.map((mapping) => [mapping.hostTurnId, mapping]));
56431
- const ordered = mappings.map(({ hostTurnId }) => {
56432
- const mapping = mergedByHost.get(hostTurnId);
56433
- if (!mapping) {
56615
+ const byHost = new Map(current.turnMappings.map((mapping) => [mapping.hostTurnId, mapping]));
56616
+ const byNative = new Map(current.turnMappings.map((mapping) => [nativeTurnKey(mapping), mapping]));
56617
+ const seenHost = /* @__PURE__ */ new Set();
56618
+ const seenNative = /* @__PURE__ */ new Set();
56619
+ const ordered = mappings.map((update) => {
56620
+ const hostMatch = byHost.get(update.hostTurnId);
56621
+ const nativeMatch = byNative.get(nativeTurnKey(update));
56622
+ if (hostMatch && nativeMatch && hostMatch !== nativeMatch) {
56623
+ throw new MappingStoreError("MAPPING_CONFLICT", "Turn identity mapping conflicts");
56624
+ }
56625
+ if (hostMatch && !sameJson(hostMatch.nativeTurnRef, update.nativeTurnRef)) {
56626
+ throw new MappingStoreError("MAPPING_CONFLICT", "Host Turn maps to another Native Turn");
56627
+ }
56628
+ if (nativeMatch && nativeMatch.hostTurnId !== update.hostTurnId) {
56629
+ throw new MappingStoreError("MAPPING_CONFLICT", "Native Turn maps to another Host Turn");
56630
+ }
56631
+ if (seenHost.has(update.hostTurnId) || seenNative.has(nativeTurnKey(update))) {
56434
56632
  throw new MappingStoreError("MAPPING_CONFLICT", "Snapshot reconciliation contains a duplicate Turn mapping");
56435
56633
  }
56436
- return mapping;
56634
+ seenHost.add(update.hostTurnId);
56635
+ seenNative.add(nativeTurnKey(update));
56636
+ return { ...update };
56437
56637
  });
56438
- const orderedIndexByHost = new Map(ordered.map(({ hostTurnId }, index) => [hostTurnId, index]));
56439
- let previousIndex = -1;
56440
- for (const existing of current.turnMappings) {
56441
- const nextIndex = orderedIndexByHost.get(existing.hostTurnId);
56442
- if (nextIndex === void 0 || nextIndex <= previousIndex) {
56443
- throw new MappingStoreError("MAPPING_CONFLICT", "Snapshot reconciliation reordered an existing Turn mapping");
56444
- }
56445
- previousIndex = nextIndex;
56446
- }
56447
56638
  return sameJson(current.turnMappings, ordered) ? null : { ...current, turnMappings: ordered };
56448
56639
  });
56449
56640
  }
@@ -56595,7 +56786,7 @@ var MappingStore = class {
56595
56786
  }
56596
56787
  async #cleanupTemps() {
56597
56788
  const names = await readdir(this.#threadsDirectory);
56598
- await Promise.all(names.filter((name) => name.includes(".tmp-")).map((name) => rm2(path13.join(this.#threadsDirectory, name), { force: true })));
56789
+ await Promise.all(names.filter((name) => name.includes(".tmp-")).map((name) => rm2(path14.join(this.#threadsDirectory, name), { force: true })));
56599
56790
  }
56600
56791
  async #acquireLock() {
56601
56792
  const attempt = async () => {
@@ -56688,10 +56879,10 @@ var MappingStore = class {
56688
56879
  }
56689
56880
  }
56690
56881
  #recordPath(hostThreadId) {
56691
- return path13.join(this.#threadsDirectory, `${hostThreadId}.json`);
56882
+ return path14.join(this.#threadsDirectory, `${hostThreadId}.json`);
56692
56883
  }
56693
56884
  #backupPath(hostThreadId) {
56694
- return path13.join(this.#backupsDirectory, `${hostThreadId}.json`);
56885
+ return path14.join(this.#backupsDirectory, `${hostThreadId}.json`);
56695
56886
  }
56696
56887
  #requireInitialized() {
56697
56888
  if (!this.#initialized) {
@@ -56710,7 +56901,7 @@ var packageMetadata5 = {
56710
56901
  var TITLE_MAX_LENGTH = 120;
56711
56902
  var DESCRIPTION_MAX_LENGTH = 500;
56712
56903
  var SERVER_NAME_MAX_LENGTH = 80;
56713
- function isRecord19(value) {
56904
+ function isRecord20(value) {
56714
56905
  return typeof value === "object" && value !== null && !Array.isArray(value);
56715
56906
  }
56716
56907
  function boundedText(value, field, maxLength) {
@@ -56754,7 +56945,7 @@ function responseError(message3) {
56754
56945
  function responsePersist(value) {
56755
56946
  if (value === void 0 || value === null)
56756
56947
  return null;
56757
- if (!isRecord19(value) || Object.keys(value).length !== 1 || value.persist !== "session" && value.persist !== "always") {
56948
+ if (!isRecord20(value) || Object.keys(value).length !== 1 || value.persist !== "session" && value.persist !== "always") {
56758
56949
  throw responseError("contains malformed persist metadata");
56759
56950
  }
56760
56951
  return value.persist;
@@ -56797,7 +56988,7 @@ function projectCodexApprovalRequest(input) {
56797
56988
  },
56798
56989
  denyResponse,
56799
56990
  parseResponse(result) {
56800
- if (!isRecord19(result) || typeof result.action !== "string") {
56991
+ if (!isRecord20(result) || typeof result.action !== "string") {
56801
56992
  throw responseError("missing action");
56802
56993
  }
56803
56994
  if (Object.keys(result).some((key) => key !== "action" && key !== "content" && key !== "_meta")) {
@@ -56805,7 +56996,7 @@ function projectCodexApprovalRequest(input) {
56805
56996
  }
56806
56997
  const selectedPersist = responsePersist(result._meta);
56807
56998
  if (result.action === "accept") {
56808
- if ("content" in result && (!isRecord19(result.content) || Object.keys(result.content).length !== 0)) {
56999
+ if ("content" in result && (!isRecord20(result.content) || Object.keys(result.content).length !== 0)) {
56809
57000
  throw responseError("contains non-empty accepted content");
56810
57001
  }
56811
57002
  if (selectedPersist === "session") {
@@ -56832,7 +57023,7 @@ function projectCodexApprovalRequest(input) {
56832
57023
  }
56833
57024
 
56834
57025
  // packages/protocol-core/dist/codex-question.js
56835
- function isRecord20(value) {
57026
+ function isRecord21(value) {
56836
57027
  return typeof value === "object" && value !== null && !Array.isArray(value);
56837
57028
  }
56838
57029
  function responseError2(message3) {
@@ -56901,7 +57092,7 @@ function projectCodexQuestionRequest(input) {
56901
57092
  }
56902
57093
  },
56903
57094
  parseResponse(result) {
56904
- if (!isRecord20(result) || !isRecord20(result.answers)) {
57095
+ if (!isRecord21(result) || !isRecord21(result.answers)) {
56905
57096
  throw responseError2("missing answers object");
56906
57097
  }
56907
57098
  const rawAnswers = result.answers;
@@ -56914,7 +57105,7 @@ function projectCodexQuestionRequest(input) {
56914
57105
  const question = interaction.questions.find(({ id: id2 }) => id2 === questionId);
56915
57106
  if (!question)
56916
57107
  throw responseError2("contains an unknown Question ID");
56917
- if (!isRecord20(answerValue) || !Array.isArray(answerValue.answers)) {
57108
+ if (!isRecord21(answerValue) || !Array.isArray(answerValue.answers)) {
56918
57109
  throw responseError2("answer entry has no answers array");
56919
57110
  }
56920
57111
  const values = answerValue.answers;
@@ -57060,8 +57251,8 @@ function projectItem(item, outcome, defaultCwd, includeCommandOutput = true) {
57060
57251
  return {
57061
57252
  id: item.itemId,
57062
57253
  type: "fileChange",
57063
- changes: item.changes.map(({ path: path18, kind, unifiedDiff }) => ({
57064
- path: path18,
57254
+ changes: item.changes.map(({ path: path19, kind, unifiedDiff }) => ({
57255
+ path: path19,
57065
57256
  kind,
57066
57257
  diff: unifiedDiff
57067
57258
  })),
@@ -57478,8 +57669,8 @@ var CodexTurnProjector = class {
57478
57669
  return messages;
57479
57670
  }
57480
57671
  #fileChangeUpdates(itemId3, changes) {
57481
- const projectedChanges = changes.map(({ path: path18, kind, unifiedDiff }) => ({
57482
- path: path18,
57672
+ const projectedChanges = changes.map(({ path: path19, kind, unifiedDiff }) => ({
57673
+ path: path19,
57483
57674
  kind,
57484
57675
  diff: unifiedDiff
57485
57676
  }));
@@ -57524,7 +57715,7 @@ var CodexTurnProjector = class {
57524
57715
  };
57525
57716
 
57526
57717
  // packages/protocol-core/dist/thread-fork.js
57527
- function isRecord21(value) {
57718
+ function isRecord22(value) {
57528
57719
  return typeof value === "object" && value !== null && !Array.isArray(value);
57529
57720
  }
57530
57721
  function optionalText(params, name, options = {}) {
@@ -57547,7 +57738,7 @@ function optionalBoolean(params, name) {
57547
57738
  function decodeThreadForkRequest(request) {
57548
57739
  if (request.method !== "thread/fork")
57549
57740
  return null;
57550
- if (!isRecord21(request.params))
57741
+ if (!isRecord22(request.params))
57551
57742
  throw new Error("thread/fork params must be an object");
57552
57743
  const params = request.params;
57553
57744
  const threadId2 = optionalText(params, "threadId");
@@ -57562,13 +57753,13 @@ function decodeThreadForkRequest(request) {
57562
57753
  if (runtimeWorkspaceRoots !== void 0 && runtimeWorkspaceRoots !== null && (!Array.isArray(runtimeWorkspaceRoots) || runtimeWorkspaceRoots.some((root) => typeof root !== "string" || root.length === 0))) {
57563
57754
  throw new Error("thread/fork params.runtimeWorkspaceRoots must be text paths or null");
57564
57755
  }
57565
- const path18 = optionalText(params, "path", { allowEmpty: true });
57756
+ const path19 = optionalText(params, "path", { allowEmpty: true });
57566
57757
  const ephemeral = optionalBoolean(params, "ephemeral");
57567
57758
  return {
57568
57759
  threadId: threadId2,
57569
57760
  ...lastTurnText ? { lastTurnId: hostTurnIdSchema.parse(lastTurnText) } : {},
57570
57761
  ...beforeTurnText ? { beforeTurnId: hostTurnIdSchema.parse(beforeTurnText) } : {},
57571
- ...path18 ? { path: path18 } : {},
57762
+ ...path19 ? { path: path19 } : {},
57572
57763
  ...optionalField(params, "model"),
57573
57764
  ...optionalField(params, "modelProvider"),
57574
57765
  ...optionalField(params, "cwd"),
@@ -57583,7 +57774,7 @@ function decodeThreadForkRequest(request) {
57583
57774
  function decodeThreadRollbackRequest(request) {
57584
57775
  if (request.method !== "thread/rollback")
57585
57776
  return null;
57586
- if (!isRecord21(request.params))
57777
+ if (!isRecord22(request.params))
57587
57778
  throw new Error("thread/rollback params must be an object");
57588
57779
  const { threadId: threadId2, numTurns } = request.params;
57589
57780
  if (typeof threadId2 !== "string" || threadId2.length === 0) {
@@ -57677,13 +57868,13 @@ var THREAD_SOURCE_KINDS = /* @__PURE__ */ new Set([
57677
57868
  "subAgentOther",
57678
57869
  "unknown"
57679
57870
  ]);
57680
- function isRecord22(value) {
57871
+ function isRecord23(value) {
57681
57872
  return typeof value === "object" && value !== null && !Array.isArray(value);
57682
57873
  }
57683
57874
  function paramsObject(request, method) {
57684
57875
  if (request.params === void 0 && method === "thread/list")
57685
57876
  return {};
57686
- if (!isRecord22(request.params))
57877
+ if (!isRecord23(request.params))
57687
57878
  throw new Error(`${method} params must be an object`);
57688
57879
  return request.params;
57689
57880
  }
@@ -57755,7 +57946,7 @@ function cursorPayload(value) {
57755
57946
  };
57756
57947
  }
57757
57948
  function parseCursorPayload(value) {
57758
- if (!isRecord22(value) || value.formatVersion !== 1)
57949
+ if (!isRecord23(value) || value.formatVersion !== 1)
57759
57950
  throw new Error("Host cursor is invalid");
57760
57951
  const { queryFingerprint: fingerprint, sortDirection: sortDirection2, officialCursor, officialDone } = value;
57761
57952
  const { externalAnchor: externalAnchor2, externalDone } = value;
@@ -57764,7 +57955,7 @@ function parseCursorPayload(value) {
57764
57955
  }
57765
57956
  let anchor = null;
57766
57957
  if (externalAnchor2 !== null) {
57767
- if (!isRecord22(externalAnchor2) || !Number.isSafeInteger(externalAnchor2.timestamp) || typeof externalAnchor2.threadId !== "string" || externalAnchor2.threadId.length === 0) {
57958
+ if (!isRecord23(externalAnchor2) || !Number.isSafeInteger(externalAnchor2.timestamp) || typeof externalAnchor2.threadId !== "string" || externalAnchor2.threadId.length === 0) {
57768
57959
  throw new Error("Host cursor is invalid");
57769
57960
  }
57770
57961
  anchor = {
@@ -57884,7 +58075,7 @@ function decodeThreadMetadataUpdateRequest(request) {
57884
58075
  if (params.gitInfo === null) {
57885
58076
  gitInfo = null;
57886
58077
  } else if (params.gitInfo !== void 0) {
57887
- if (!isRecord22(params.gitInfo)) {
58078
+ if (!isRecord23(params.gitInfo)) {
57888
58079
  throw new Error("thread/metadata/update params.gitInfo must be an object or null");
57889
58080
  }
57890
58081
  gitInfo = {};
@@ -57912,7 +58103,7 @@ function optionalCursor(value, name) {
57912
58103
  return value;
57913
58104
  }
57914
58105
  function decodeOfficialThreadListPage(value) {
57915
- if (!isRecord22(value) || !Array.isArray(value.data) || value.data.some((row) => !isRecord22(row))) {
58106
+ if (!isRecord23(value) || !Array.isArray(value.data) || value.data.some((row) => !isRecord23(row))) {
57916
58107
  throw new Error("Official thread/list response is invalid");
57917
58108
  }
57918
58109
  return {
@@ -58234,7 +58425,7 @@ var packageMetadata6 = {
58234
58425
  // packages/host-runtime/src/external-thread-repository.ts
58235
58426
  import { randomUUID as randomUUID7 } from "node:crypto";
58236
58427
  import os6 from "node:os";
58237
- import path14 from "node:path";
58428
+ import path15 from "node:path";
58238
58429
  function nativeTurnKey2(ref) {
58239
58430
  return `${ref.harnessId}\0${ref.nativeSessionId}\0${ref.nativeTurnKey}\0${ref.formatVersion}`;
58240
58431
  }
@@ -58243,8 +58434,8 @@ function sameMapping(left, right) {
58243
58434
  }
58244
58435
  function defaultMappingStoreDirectory(environment) {
58245
58436
  const dataDirectory = environment.CODEXHOST_DATA_DIR;
58246
- return path14.join(
58247
- dataDirectory ? path14.resolve(dataDirectory) : path14.join(os6.homedir(), ".codexhost"),
58437
+ return path15.join(
58438
+ dataDirectory ? path15.resolve(dataDirectory) : path15.join(os6.homedir(), ".codexhost"),
58248
58439
  "mapping-store"
58249
58440
  );
58250
58441
  }
@@ -58454,25 +58645,14 @@ var ExternalThreadRepository = class {
58454
58645
  ...turn.checkpoint ? { nativeCheckpointRef: turn.checkpoint } : {}
58455
58646
  };
58456
58647
  return {
58457
- existing,
58458
58648
  snapshot: turn,
58459
58649
  mapping: {
58460
58650
  ...mapping,
58651
+ nativeTurnRef: turn.nativeTurnRef,
58461
58652
  ...turn.checkpoint ? { nativeCheckpointRef: turn.checkpoint } : {}
58462
58653
  }
58463
58654
  };
58464
58655
  });
58465
- let existingIndex = 0;
58466
- for (const { existing } of aligned) {
58467
- if (!existing) continue;
58468
- if (existing.hostTurnId !== record3.turnMappings[existingIndex]?.hostTurnId) {
58469
- throw new Error("Persisted Turn mappings do not match the Native Snapshot order");
58470
- }
58471
- existingIndex += 1;
58472
- }
58473
- if (existingIndex !== record3.turnMappings.length) {
58474
- throw new Error("Persisted Turn mappings do not match the Native Snapshot order");
58475
- }
58476
58656
  const orderedMappings = aligned.map(({ mapping }) => mapping);
58477
58657
  const mappingsChanged = orderedMappings.length !== record3.turnMappings.length || orderedMappings.some((mapping, index) => {
58478
58658
  const persisted = record3.turnMappings[index];
@@ -59329,7 +59509,7 @@ var ExternalThreadRuntime = class {
59329
59509
  import { randomUUID as randomUUID8 } from "node:crypto";
59330
59510
  var INTERNAL_REQUEST_PREFIX = "codexhost:official:";
59331
59511
  var MAX_RETIRED_IDS = 1024;
59332
- function isRecord23(value) {
59512
+ function isRecord24(value) {
59333
59513
  return typeof value === "object" && value !== null && !Array.isArray(value);
59334
59514
  }
59335
59515
  var OfficialRequestBroker = class {
@@ -59372,7 +59552,7 @@ var OfficialRequestBroker = class {
59372
59552
  });
59373
59553
  }
59374
59554
  handle(value) {
59375
- if (!isRecord23(value) || typeof value.id !== "string") return false;
59555
+ if (!isRecord24(value) || typeof value.id !== "string") return false;
59376
59556
  const pending = this.#pending.get(value.id);
59377
59557
  if (!pending) return this.#retired.has(value.id);
59378
59558
  clearTimeout(pending.timeout);
@@ -59401,11 +59581,11 @@ var OfficialRequestBroker = class {
59401
59581
  };
59402
59582
 
59403
59583
  // packages/host-runtime/src/route-observation.ts
59404
- function isRecord24(value) {
59584
+ function isRecord25(value) {
59405
59585
  return typeof value === "object" && value !== null && !Array.isArray(value);
59406
59586
  }
59407
59587
  function classifyThreadPurpose(request) {
59408
- return isRecord24(request.params) && request.params.ephemeral === true ? "ephemeral" : "conversation";
59588
+ return isRecord25(request.params) && request.params.ephemeral === true ? "ephemeral" : "conversation";
59409
59589
  }
59410
59590
  var RequestRouteObservationTracker = class {
59411
59591
  #nextCreateOrdinal = 0;
@@ -59430,13 +59610,13 @@ var RequestRouteObservationTracker = class {
59430
59610
  this.#createByThreadId.set(threadId2, tracked);
59431
59611
  }
59432
59612
  bindOfficialResponse(response) {
59433
- if (!isRecord24(response) || !("id" in response)) return;
59613
+ if (!isRecord25(response) || !("id" in response)) return;
59434
59614
  const tracked = this.#pendingByRequestId.get(response.id);
59435
59615
  if (!tracked) return;
59436
59616
  this.#pendingByRequestId.delete(response.id);
59437
59617
  const result = response.result;
59438
- const thread = isRecord24(result) ? result.thread : null;
59439
- if (isRecord24(thread) && typeof thread.id === "string") {
59618
+ const thread = isRecord25(result) ? result.thread : null;
59619
+ if (isRecord25(thread) && typeof thread.id === "string") {
59440
59620
  this.#createByThreadId.set(thread.id, tracked);
59441
59621
  }
59442
59622
  }
@@ -59533,25 +59713,25 @@ function resolveExternalSessionTreeIds(records) {
59533
59713
  const resolve2 = (start) => {
59534
59714
  const cached2 = resolved.get(start.hostThreadId);
59535
59715
  if (cached2) return cached2;
59536
- const path18 = [];
59716
+ const path19 = [];
59537
59717
  const visited = /* @__PURE__ */ new Set();
59538
59718
  let current = start;
59539
59719
  while (true) {
59540
59720
  const known = resolved.get(current.hostThreadId);
59541
59721
  if (known) {
59542
- for (const record3 of path18) resolved.set(record3.hostThreadId, known);
59722
+ for (const record3 of path19) resolved.set(record3.hostThreadId, known);
59543
59723
  return known;
59544
59724
  }
59545
59725
  if (visited.has(current.hostThreadId)) {
59546
59726
  throw new Error("External Thread Fork tree contains a cycle");
59547
59727
  }
59548
59728
  visited.add(current.hostThreadId);
59549
- path18.push(current);
59729
+ path19.push(current);
59550
59730
  const sourceId = current.forkSource?.hostThreadId;
59551
59731
  const source = sourceId ? byId.get(sourceId) : void 0;
59552
59732
  if (!source) {
59553
59733
  const root = current.hostThreadId;
59554
- for (const record3 of path18) resolved.set(record3.hostThreadId, root);
59734
+ for (const record3 of path19) resolved.set(record3.hostThreadId, root);
59555
59735
  return root;
59556
59736
  }
59557
59737
  current = source;
@@ -59602,11 +59782,11 @@ var OfficialThreadListError = class extends Error {
59602
59782
  }
59603
59783
  rpcError;
59604
59784
  };
59605
- function isRecord25(value) {
59785
+ function isRecord26(value) {
59606
59786
  return typeof value === "object" && value !== null && !Array.isArray(value);
59607
59787
  }
59608
59788
  function officialThreadListPageFromResponse(response) {
59609
- if (isRecord25(response.error)) {
59789
+ if (isRecord26(response.error)) {
59610
59790
  if (!Number.isSafeInteger(response.error.code) || typeof response.error.message !== "string") {
59611
59791
  throw new Error("Official thread/list error response is invalid");
59612
59792
  }
@@ -59766,14 +59946,14 @@ async function aggregateThreadList(input) {
59766
59946
  }
59767
59947
 
59768
59948
  // packages/host-runtime/src/app-server-host.ts
59769
- function isRecord26(value) {
59949
+ function isRecord27(value) {
59770
59950
  return typeof value === "object" && value !== null && !Array.isArray(value);
59771
59951
  }
59772
59952
  function isCreditsAdapter(adapter) {
59773
59953
  return typeof adapter.credits === "function" && typeof adapter.refreshCredits === "function";
59774
59954
  }
59775
59955
  function projectAccountCredits(value) {
59776
- if (!isRecord26(value)) return null;
59956
+ if (!isRecord27(value)) return null;
59777
59957
  const rest = { ...value };
59778
59958
  delete rest.fetchedAt;
59779
59959
  const parsed = accountCreditsSnapshotSchema.safeParse(rest);
@@ -59795,6 +59975,7 @@ function officialEnvironment(source) {
59795
59975
  "CODEXHOST_STOCK_CODEX_PATH",
59796
59976
  "CODEXHOST_LAUNCHER_PID",
59797
59977
  "CODEXHOST_LAUNCHER_EXECUTABLE",
59978
+ "CODEXHOST_RUNTIME_DESCRIPTOR_PATH",
59798
59979
  "CODEXHOST_CONTROL_PORT",
59799
59980
  "CODEXHOST_CONTROL_NONCE",
59800
59981
  "CODEXHOST_NPM_NODE_PATH",
@@ -59872,12 +60053,12 @@ function classifyCreateRequestRoute(request, defaultAgent2) {
59872
60053
  };
59873
60054
  }
59874
60055
  function requestObject(request) {
59875
- if (!isRecord26(request.params)) throw new Error(`${request.method} params must be an object`);
60056
+ if (!isRecord27(request.params)) throw new Error(`${request.method} params must be an object`);
59876
60057
  return request.params;
59877
60058
  }
59878
60059
  function requestText(params) {
59879
60060
  if (!Array.isArray(params.input)) throw new Error("turn/start input must be an array");
59880
- const text = params.input.filter((item) => isRecord26(item) && item.type === "text").map((item) => item.text).filter((value) => typeof value === "string").join("\n");
60061
+ const text = params.input.filter((item) => isRecord27(item) && item.type === "text").map((item) => item.text).filter((value) => typeof value === "string").join("\n");
59881
60062
  if (!text) throw new Error("turn/start must contain text input");
59882
60063
  return text;
59883
60064
  }
@@ -60151,7 +60332,7 @@ var AppServerHost = class {
60151
60332
  continue;
60152
60333
  }
60153
60334
  if (request.method === "thread/fork") {
60154
- const params = isRecord26(request.params) ? request.params : {};
60335
+ const params = isRecord27(request.params) ? request.params : {};
60155
60336
  const resolution = typeof params.threadId === "string" ? await this.#resolveExternalThread(params.threadId) : { kind: "official" };
60156
60337
  if (resolution.kind === "error") {
60157
60338
  await this.#writer.json(
@@ -60174,7 +60355,7 @@ var AppServerHost = class {
60174
60355
  }
60175
60356
  }
60176
60357
  if (request.method === "thread/rollback") {
60177
- const params = isRecord26(request.params) ? request.params : {};
60358
+ const params = isRecord27(request.params) ? request.params : {};
60178
60359
  const resolution = typeof params.threadId === "string" ? await this.#resolveExternalThread(params.threadId) : { kind: "official" };
60179
60360
  if (resolution.kind === "error") {
60180
60361
  await this.#writer.json(
@@ -60314,7 +60495,7 @@ var AppServerHost = class {
60314
60495
  continue;
60315
60496
  }
60316
60497
  }
60317
- if (request.method.startsWith("thread/") && !EXPLICIT_EXTERNAL_THREAD_METHODS.has(request.method) && isRecord26(request.params) && typeof request.params.threadId === "string") {
60498
+ if (request.method.startsWith("thread/") && !EXPLICIT_EXTERNAL_THREAD_METHODS.has(request.method) && isRecord27(request.params) && typeof request.params.threadId === "string") {
60318
60499
  const location = await this.#locateExternalThread(request.params.threadId);
60319
60500
  if (await this.#writeResolutionError(request, location)) continue;
60320
60501
  if (location.kind === "external") {
@@ -61137,10 +61318,10 @@ var AppServerHost = class {
61137
61318
  ...typeof params.serviceTier === "string" ? { serviceTier: params.serviceTier } : {}
61138
61319
  });
61139
61320
  try {
61140
- if (params.initialTurnsPage !== void 0 && params.initialTurnsPage !== null && !isRecord26(params.initialTurnsPage)) {
61321
+ if (params.initialTurnsPage !== void 0 && params.initialTurnsPage !== null && !isRecord27(params.initialTurnsPage)) {
61141
61322
  throw new ExternalHistoryRequestError("initialTurnsPage must be an object");
61142
61323
  }
61143
- const initialPageParams = isRecord26(params.initialTurnsPage) ? params.initialTurnsPage : null;
61324
+ const initialPageParams = isRecord27(params.initialTurnsPage) ? params.initialTurnsPage : null;
61144
61325
  const initialTurnsPage = initialPageParams ? listExternalTurns(turns, initialPageParams) : null;
61145
61326
  const paginated = thread.record.historyMode === "paginated";
61146
61327
  const turnsBackwardsCursor = paginated ? listExternalTurns(turns, { limit: 1, itemsView: "notLoaded" }).backwardsCursor : null;
@@ -61392,7 +61573,7 @@ var AppServerHost = class {
61392
61573
  }
61393
61574
  }
61394
61575
  async #handleDesktopApprovalResponse(value) {
61395
- if (!isRecord26(value) || !isHostApprovalRequestId(value.id)) return false;
61576
+ if (!isRecord27(value) || !isHostApprovalRequestId(value.id)) return false;
61396
61577
  const pending = this.#pendingDesktopApprovals.get(value.id);
61397
61578
  if (!pending) return true;
61398
61579
  this.#pendingDesktopApprovals.delete(value.id);
@@ -61514,7 +61695,7 @@ var AppServerHost = class {
61514
61695
  }
61515
61696
  }
61516
61697
  async #handleDesktopQuestionResponse(value) {
61517
- if (!isRecord26(value) || !isHostQuestionRequestId(value.id)) return false;
61698
+ if (!isRecord27(value) || !isHostQuestionRequestId(value.id)) return false;
61518
61699
  const pending = this.#pendingDesktopQuestions.get(value.id);
61519
61700
  if (!pending) return true;
61520
61701
  this.#pendingDesktopQuestions.delete(value.id);
@@ -61626,7 +61807,7 @@ var AppServerHost = class {
61626
61807
 
61627
61808
  // packages/update-manager/dist/distribution.js
61628
61809
  import { lstat, readFile as readFile4 } from "node:fs/promises";
61629
- import path15 from "node:path";
61810
+ import path16 from "node:path";
61630
61811
 
61631
61812
  // packages/update-manager/dist/status.js
61632
61813
  var STATUS_SCHEMA_VERSION = 1;
@@ -61681,6 +61862,7 @@ function parseUpdateStatus(value) {
61681
61862
  var UPDATE_RUNTIME_ENV = Object.freeze({
61682
61863
  launcherPid: "CODEXHOST_LAUNCHER_PID",
61683
61864
  launcherExecutable: "CODEXHOST_LAUNCHER_EXECUTABLE",
61865
+ runtimeDescriptorPath: "CODEXHOST_RUNTIME_DESCRIPTOR_PATH",
61684
61866
  controllerPort: "CODEXHOST_CONTROL_PORT",
61685
61867
  controllerNonce: "CODEXHOST_CONTROL_NONCE",
61686
61868
  npmNodePath: "CODEXHOST_NPM_NODE_PATH",
@@ -61700,7 +61882,7 @@ function parseDistributionMetadata(value) {
61700
61882
  if (Object.keys(metadata).some((key) => !allowed2.includes(key))) {
61701
61883
  throw new Error("distribution metadata contains unknown fields");
61702
61884
  }
61703
- if (metadata.schemaVersion !== 1 || metadata.distribution !== "npm" && metadata.distribution !== "installer" || !["macos-arm64", "macos-x64", "windows-x64", "windows-arm64"].includes(String(metadata.target)) || typeof metadata.version !== "string") {
61885
+ if (metadata.schemaVersion !== 1 || metadata.distribution !== "npm" && metadata.distribution !== "installer" || !["macos-arm64", "macos-x64", "windows-x64", "windows-arm64", "linux-x64"].includes(String(metadata.target)) || typeof metadata.version !== "string") {
61704
61886
  throw new Error("distribution metadata is invalid");
61705
61887
  }
61706
61888
  return {
@@ -61712,9 +61894,9 @@ function parseDistributionMetadata(value) {
61712
61894
  }
61713
61895
  function absoluteEnvironmentPath(environment, name) {
61714
61896
  const value = environment[name];
61715
- if (!value || !path15.isAbsolute(value))
61897
+ if (!value || !path16.isAbsolute(value))
61716
61898
  throw new Error(`${name} must be an absolute path`);
61717
- return path15.normalize(value);
61899
+ return path16.normalize(value);
61718
61900
  }
61719
61901
  function positiveEnvironmentInteger(environment, name) {
61720
61902
  const value = Number(environment[name]);
@@ -61731,48 +61913,52 @@ function expectedTarget(platform, architecture) {
61731
61913
  return "windows-arm64";
61732
61914
  if (platform === "win32" && architecture === "x64")
61733
61915
  return "windows-x64";
61916
+ if (platform === "linux" && architecture === "x64")
61917
+ return "linux-x64";
61734
61918
  throw new Error(`unsupported update host ${platform}/${architecture}`);
61735
61919
  }
61736
61920
  function defaultUpdateStateDirectory(platform = process.platform, environment = process.env) {
61737
61921
  if (platform === "win32") {
61738
61922
  const root = environment.LOCALAPPDATA;
61739
- if (!root || !path15.isAbsolute(root))
61923
+ if (!root || !path16.isAbsolute(root))
61740
61924
  throw new Error("LOCALAPPDATA is unavailable");
61741
- return path15.join(root, "codexhost", "updates");
61925
+ return path16.join(root, "codexhost", "updates");
61742
61926
  }
61743
61927
  const home = environment.HOME;
61744
- if (!home || !path15.isAbsolute(home))
61928
+ if (!home || !path16.isAbsolute(home))
61745
61929
  throw new Error("HOME is unavailable");
61746
- return platform === "darwin" ? path15.join(home, "Library", "Application Support", "codexhost", "updates") : path15.join(home, ".codexhost", "updates");
61930
+ return platform === "darwin" ? path16.join(home, "Library", "Application Support", "codexhost", "updates") : path16.join(home, ".codexhost", "updates");
61747
61931
  }
61748
61932
  async function resolveInstalledUpdateContext(options) {
61749
61933
  const environment = options.environment ?? process.env;
61750
61934
  const platform = options.platform ?? process.platform;
61751
61935
  const architecture = options.architecture ?? process.arch;
61752
- if (!path15.isAbsolute(options.hostRuntimePath)) {
61936
+ if (!path16.isAbsolute(options.hostRuntimePath)) {
61753
61937
  throw new Error("Host Runtime path must be absolute");
61754
61938
  }
61755
- const hostRuntimePath = path15.normalize(options.hostRuntimePath);
61939
+ const hostRuntimePath = path16.normalize(options.hostRuntimePath);
61756
61940
  const runtimeMetadata = await lstat(hostRuntimePath);
61757
61941
  if (!runtimeMetadata.isFile() || runtimeMetadata.isSymbolicLink()) {
61758
61942
  throw new Error("Host Runtime must be a regular file");
61759
61943
  }
61760
- const appDirectory = path15.dirname(hostRuntimePath);
61761
- const metadata = parseDistributionMetadata(JSON.parse(await readFile4(path15.join(appDirectory, "codexhost-distribution.json"), "utf8")));
61944
+ const appDirectory = path16.dirname(hostRuntimePath);
61945
+ const metadata = parseDistributionMetadata(JSON.parse(await readFile4(path16.join(appDirectory, "codexhost-distribution.json"), "utf8")));
61762
61946
  const target = expectedTarget(platform, architecture);
61763
61947
  if (metadata.target !== target) {
61764
61948
  throw new Error(`installed target ${metadata.target} does not match ${target}`);
61765
61949
  }
61766
61950
  const launcherPid = positiveEnvironmentInteger(environment, UPDATE_RUNTIME_ENV.launcherPid);
61767
61951
  const launcherExecutable = absoluteEnvironmentPath(environment, UPDATE_RUNTIME_ENV.launcherExecutable);
61768
- const stateDirectory = path15.normalize(options.stateDirectory ?? defaultUpdateStateDirectory(platform, environment));
61769
- const resourcesRoot = path15.dirname(appDirectory);
61770
- const installationRoot = platform === "darwin" ? path15.dirname(path15.dirname(resourcesRoot)) : resourcesRoot;
61771
- const updaterExecutable = path15.join(resourcesRoot, "libexec", platform === "win32" ? "codexhost-updater.exe" : "codexhost-updater");
61952
+ const runtimeDescriptorPath = absoluteEnvironmentPath(environment, UPDATE_RUNTIME_ENV.runtimeDescriptorPath);
61953
+ const stateDirectory = path16.normalize(options.stateDirectory ?? defaultUpdateStateDirectory(platform, environment));
61954
+ const resourcesRoot = path16.dirname(appDirectory);
61955
+ const installationRoot = platform === "darwin" ? path16.dirname(path16.dirname(resourcesRoot)) : resourcesRoot;
61956
+ const updaterExecutable = path16.join(resourcesRoot, "libexec", platform === "win32" ? "codexhost-updater.exe" : "codexhost-updater");
61772
61957
  const common = {
61773
61958
  version: metadata.version,
61774
61959
  launcherPid,
61775
61960
  launcherExecutable,
61961
+ runtimeDescriptorPath,
61776
61962
  updaterExecutable,
61777
61963
  stateDirectory
61778
61964
  };
@@ -61791,7 +61977,7 @@ async function resolveInstalledUpdateContext(options) {
61791
61977
  npmLauncherPath: absoluteEnvironmentPath(environment, UPDATE_RUNTIME_ENV.npmLauncherPath),
61792
61978
  packageRoot: absoluteEnvironmentPath(environment, UPDATE_RUNTIME_ENV.npmPackageRoot)
61793
61979
  };
61794
- if (path15.normalize(npmOptions.packageRoot) !== resourcesRoot) {
61980
+ if (path16.normalize(npmOptions.packageRoot) !== resourcesRoot) {
61795
61981
  throw new Error("npm platform package root does not own the Host Runtime");
61796
61982
  }
61797
61983
  return { metadata, common, controller, installation: { kind: "npm", options: npmOptions } };
@@ -61954,7 +62140,7 @@ function selectInstallerReleaseArtifact(release, target) {
61954
62140
 
61955
62141
  // packages/update-manager/dist/operation-state.js
61956
62142
  import { lstat as lstat2, mkdir as mkdir2, open as open3, readFile as readFile5, readdir as readdir2, rm as rm3, writeFile } from "node:fs/promises";
61957
- import path16 from "node:path";
62143
+ import path17 from "node:path";
61958
62144
  var LOCK_FILE = "active-update-v1.lock";
61959
62145
  var STATUS_FILE = "status-v1.json";
61960
62146
  var TERMINAL_PHASES = /* @__PURE__ */ new Set(["succeeded", "failed"]);
@@ -61969,12 +62155,12 @@ async function regularFile(filePath) {
61969
62155
  }
61970
62156
  }
61971
62157
  async function isUpdateOperationActive(stateDirectory) {
61972
- if (!path16.isAbsolute(stateDirectory))
62158
+ if (!path17.isAbsolute(stateDirectory))
61973
62159
  throw new Error("update state directory must be absolute");
61974
- return regularFile(path16.join(stateDirectory, LOCK_FILE));
62160
+ return regularFile(path17.join(stateDirectory, LOCK_FILE));
61975
62161
  }
61976
62162
  async function discoverLatestUpdateStatus(stateDirectory) {
61977
- if (!path16.isAbsolute(stateDirectory))
62163
+ if (!path17.isAbsolute(stateDirectory))
61978
62164
  throw new Error("update state directory must be absolute");
61979
62165
  let entries;
61980
62166
  try {
@@ -61988,7 +62174,7 @@ async function discoverLatestUpdateStatus(stateDirectory) {
61988
62174
  for (const entry of entries) {
61989
62175
  if (!entry.isDirectory() || entry.isSymbolicLink() || !entry.name.startsWith("update-"))
61990
62176
  continue;
61991
- const statusPath = path16.join(stateDirectory, entry.name, STATUS_FILE);
62177
+ const statusPath = path17.join(stateDirectory, entry.name, STATUS_FILE);
61992
62178
  if (!await regularFile(statusPath))
61993
62179
  continue;
61994
62180
  try {
@@ -62016,8 +62202,8 @@ async function cleanupTerminalUpdateState(stateDirectory, options = {}) {
62016
62202
  for (const entry of entries) {
62017
62203
  if (!entry.isDirectory() || entry.isSymbolicLink() || !entry.name.startsWith("update-"))
62018
62204
  continue;
62019
- const directory = path16.join(stateDirectory, entry.name);
62020
- const statusPath = path16.join(directory, STATUS_FILE);
62205
+ const directory = path17.join(stateDirectory, entry.name);
62206
+ const statusPath = path17.join(directory, STATUS_FILE);
62021
62207
  try {
62022
62208
  const status = parseUpdateStatus(JSON.parse(await readFile5(statusPath, "utf8")));
62023
62209
  if (TERMINAL_PHASES.has(status.phase) && now - status.updatedAt > retentionSeconds) {
@@ -62028,10 +62214,10 @@ async function cleanupTerminalUpdateState(stateDirectory, options = {}) {
62028
62214
  }
62029
62215
  }
62030
62216
  async function acquireUpdateOperationLock(stateDirectory) {
62031
- if (!path16.isAbsolute(stateDirectory))
62217
+ if (!path17.isAbsolute(stateDirectory))
62032
62218
  throw new Error("update state directory must be absolute");
62033
62219
  await mkdir2(stateDirectory, { recursive: true, mode: 448 });
62034
- const lockPath = path16.join(stateDirectory, LOCK_FILE);
62220
+ const lockPath = path17.join(stateDirectory, LOCK_FILE);
62035
62221
  let handle;
62036
62222
  try {
62037
62223
  handle = await open3(lockPath, "wx", 384);
@@ -62050,9 +62236,9 @@ async function acquireUpdateOperationLock(stateDirectory) {
62050
62236
  async setStatusPath(statusPath) {
62051
62237
  if (released)
62052
62238
  throw new Error("update operation lock is released");
62053
- if (!path16.isAbsolute(statusPath))
62239
+ if (!path17.isAbsolute(statusPath))
62054
62240
  throw new Error("update status path must be absolute");
62055
- await writeFile(lockPath, `${JSON.stringify({ ownerPid: process.pid, statusPath: path16.normalize(statusPath) })}
62241
+ await writeFile(lockPath, `${JSON.stringify({ ownerPid: process.pid, statusPath: path17.normalize(statusPath) })}
62056
62242
  `, { encoding: "utf8", mode: 384 });
62057
62243
  },
62058
62244
  async release() {
@@ -62074,7 +62260,7 @@ function processIsAlive(processId) {
62074
62260
  }
62075
62261
  }
62076
62262
  async function recoverUpdateOperationLock(stateDirectory) {
62077
- const lockPath = path16.join(stateDirectory, LOCK_FILE);
62263
+ const lockPath = path17.join(stateDirectory, LOCK_FILE);
62078
62264
  if (!await regularFile(lockPath))
62079
62265
  return;
62080
62266
  let ownerPid;
@@ -62086,7 +62272,7 @@ async function recoverUpdateOperationLock(stateDirectory) {
62086
62272
  } catch {
62087
62273
  return;
62088
62274
  }
62089
- if (typeof statusPath !== "string" || !path16.isAbsolute(statusPath))
62275
+ if (typeof statusPath !== "string" || !path17.isAbsolute(statusPath))
62090
62276
  return;
62091
62277
  try {
62092
62278
  const status = parseUpdateStatus(JSON.parse(await readFile5(statusPath, "utf8")));
@@ -62101,7 +62287,7 @@ async function recoverUpdateOperationLock(stateDirectory) {
62101
62287
  import { spawn as spawn6 } from "node:child_process";
62102
62288
  import { randomUUID as randomUUID10 } from "node:crypto";
62103
62289
  import { chmod, copyFile as copyFile2, lstat as lstat4, mkdir as mkdir3, readFile as readFile6, rename as rename2, rm as rm4, writeFile as writeFile2 } from "node:fs/promises";
62104
- import path17 from "node:path";
62290
+ import path18 from "node:path";
62105
62291
 
62106
62292
  // packages/update-manager/dist/artifact.js
62107
62293
  import { createHash as createHash2 } from "node:crypto";
@@ -62194,13 +62380,37 @@ async function verifyDownloadedArtifact(source, filePath, result) {
62194
62380
 
62195
62381
  // packages/update-manager/dist/update-manager.js
62196
62382
  var REQUEST_SCHEMA_VERSION = 1;
62383
+ var WINDOWS_RENAME_RETRY_DELAYS_MS = [10, 30, 70, 150, 300];
62197
62384
  function errorMessage4(error52) {
62198
62385
  return error52 instanceof Error ? error52.message : String(error52);
62199
62386
  }
62387
+ function systemErrorCode2(error52) {
62388
+ return typeof error52 === "object" && error52 !== null && "code" in error52 ? String(error52.code) : null;
62389
+ }
62390
+ function delay4(milliseconds) {
62391
+ return new Promise((resolve2) => setTimeout(resolve2, milliseconds));
62392
+ }
62393
+ async function replaceStatusFile(temporaryPath, statusPath) {
62394
+ let retryIndex = 0;
62395
+ for (; ; ) {
62396
+ try {
62397
+ await rename2(temporaryPath, statusPath);
62398
+ return;
62399
+ } catch (error52) {
62400
+ const retryDelay = WINDOWS_RENAME_RETRY_DELAYS_MS[retryIndex];
62401
+ const code = systemErrorCode2(error52);
62402
+ if (process.platform !== "win32" || retryDelay === void 0 || code !== "EACCES" && code !== "EBUSY" && code !== "EPERM") {
62403
+ throw error52;
62404
+ }
62405
+ retryIndex += 1;
62406
+ await delay4(retryDelay);
62407
+ }
62408
+ }
62409
+ }
62200
62410
  function requireAbsolutePath(value, label) {
62201
- if (!path17.isAbsolute(value))
62411
+ if (!path18.isAbsolute(value))
62202
62412
  throw new Error(`${label} must be an absolute path`);
62203
- return path17.normalize(value);
62413
+ return path18.normalize(value);
62204
62414
  }
62205
62415
  async function requireRegularFile(value, label) {
62206
62416
  const filePath = requireAbsolutePath(value, label);
@@ -62243,7 +62453,7 @@ function createBackgroundUpdateManager(dependencies = {}) {
62243
62453
  const now = dependencies.now ?? Date.now;
62244
62454
  const preparedRequests = /* @__PURE__ */ new Set();
62245
62455
  async function writeStatusSnapshot(statusPath, status) {
62246
- const temporaryPath = path17.join(path17.dirname(statusPath), `.update-status-${randomId()}.tmp`);
62456
+ const temporaryPath = path18.join(path18.dirname(statusPath), `.update-status-${randomId()}.tmp`);
62247
62457
  try {
62248
62458
  await writeFile2(temporaryPath, `${JSON.stringify(status)}
62249
62459
  `, {
@@ -62251,7 +62461,7 @@ function createBackgroundUpdateManager(dependencies = {}) {
62251
62461
  mode: 384,
62252
62462
  flag: "wx"
62253
62463
  });
62254
- await rename2(temporaryPath, statusPath);
62464
+ await replaceStatusFile(temporaryPath, statusPath);
62255
62465
  } catch (error52) {
62256
62466
  await rm4(temporaryPath, { force: true });
62257
62467
  throw error52;
@@ -62299,24 +62509,26 @@ function createBackgroundUpdateManager(dependencies = {}) {
62299
62509
  const version2 = requireSemanticVersion(options.version);
62300
62510
  const launcherPid = requireLauncherPid(options.launcherPid);
62301
62511
  const launcherExecutable = await requireRegularFile(options.launcherExecutable, "Launcher executable");
62512
+ const runtimeDescriptorPath = requireAbsolutePath(options.runtimeDescriptorPath, "runtime descriptor path");
62302
62513
  const updaterExecutable = await requireRegularFile(options.updaterExecutable, "Updater executable");
62303
62514
  const stateDirectory = requireAbsolutePath(options.stateDirectory, "update state directory");
62304
62515
  await mkdir3(stateDirectory, { recursive: true, mode: 448 });
62305
- const workDirectory = path17.join(stateDirectory, `update-${version2}-${randomId()}`);
62516
+ const workDirectory = path18.join(stateDirectory, `update-${version2}-${randomId()}`);
62306
62517
  await mkdir3(workDirectory, { recursive: false, mode: 448 });
62307
62518
  const executableSuffix = platform === "win32" ? ".exe" : "";
62308
- const helperPath = path17.join(workDirectory, `codexhost-updater${executableSuffix}`);
62519
+ const helperPath = path18.join(workDirectory, `codexhost-updater${executableSuffix}`);
62309
62520
  await copyFile2(updaterExecutable, helperPath);
62310
62521
  if (platform !== "win32")
62311
62522
  await chmod(helperPath, 448);
62312
- const requestPath = path17.join(workDirectory, "request-v1.json");
62313
- const statusPath = path17.join(workDirectory, "status-v1.json");
62523
+ const requestPath = path18.join(workDirectory, "request-v1.json");
62524
+ const statusPath = path18.join(workDirectory, "status-v1.json");
62314
62525
  await writePrivateJson(statusPath, preparedStatus(version2, installation, now()));
62315
62526
  await options.onPrepared?.({ version: version2, installation, statusPath });
62316
62527
  return {
62317
62528
  version: version2,
62318
62529
  launcherPid,
62319
62530
  launcherExecutable,
62531
+ runtimeDescriptorPath,
62320
62532
  workDirectory,
62321
62533
  helperPath,
62322
62534
  requestPath,
@@ -62325,8 +62537,8 @@ function createBackgroundUpdateManager(dependencies = {}) {
62325
62537
  }
62326
62538
  async function prepareArtifact(common, installation, sourceValue, fileName) {
62327
62539
  const source = validateArtifact(sourceValue);
62328
- const temporaryPath = path17.join(common.workDirectory, `.${fileName}.download`);
62329
- const artifactPath = path17.join(common.workDirectory, fileName);
62540
+ const temporaryPath = path18.join(common.workDirectory, `.${fileName}.download`);
62541
+ const artifactPath = path18.join(common.workDirectory, fileName);
62330
62542
  const progress = progressReporter(common.statusPath, common.version, installation, source.size);
62331
62543
  try {
62332
62544
  const result = await download(source, temporaryPath, progress.update);
@@ -62352,6 +62564,7 @@ function createBackgroundUpdateManager(dependencies = {}) {
62352
62564
  version: common.version,
62353
62565
  wait_pid: common.launcherPid,
62354
62566
  wait_executable: common.launcherExecutable,
62567
+ runtime_descriptor_path: common.runtimeDescriptorPath,
62355
62568
  status_path: common.statusPath,
62356
62569
  installation
62357
62570
  };
@@ -62399,7 +62612,7 @@ function createBackgroundUpdateManager(dependencies = {}) {
62399
62612
  throw new Error("macOS DMG updates require macOS");
62400
62613
  const common = await prepareCommon(options, "macos-dmg");
62401
62614
  const appPath = requireAbsolutePath(options.appPath, "macOS application path");
62402
- if (path17.extname(appPath) !== ".app") {
62615
+ if (path18.extname(appPath) !== ".app") {
62403
62616
  throw new Error("macOS application path must end in .app");
62404
62617
  }
62405
62618
  const artifact = await prepareArtifact(common, "macos-dmg", options.artifact, "update.dmg");
@@ -62469,9 +62682,11 @@ function createHostUpdateCoordinator(options) {
62469
62682
  return publicStatus(discovered.status);
62470
62683
  }
62471
62684
  async function installable(context, release) {
62472
- if (context.metadata.distribution === "npm") return true;
62685
+ if (context.installation.kind === "npm") return true;
62686
+ const target = context.metadata.target;
62687
+ if (target === "linux-x64") return false;
62473
62688
  try {
62474
- selectInstallerReleaseArtifact(release, context.metadata.target);
62689
+ selectInstallerReleaseArtifact(release, target);
62475
62690
  return true;
62476
62691
  } catch {
62477
62692
  return false;
@@ -62569,10 +62784,11 @@ function createHostUpdateCoordinator(options) {
62569
62784
  onPrepared
62570
62785
  });
62571
62786
  } else {
62572
- const artifact = selectInstallerReleaseArtifact(
62573
- release,
62574
- context.metadata.target
62575
- ).source;
62787
+ const target = context.metadata.target;
62788
+ if (target === "linux-x64") {
62789
+ throw new Error("Linux installer updates are unsupported");
62790
+ }
62791
+ const artifact = selectInstallerReleaseArtifact(release, target).source;
62576
62792
  prepared2 = context.installation.kind === "windows-installer" ? await manager.prepareWindowsInstaller({
62577
62793
  ...context.installation.options,
62578
62794
  version: release.version,