@liberseek/boft-cli-win32-arm64 0.8.4 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5374,7 +5374,8 @@ function createBackgroundUpdateManager(dependencies2 = {}) {
5374
5374
  kind: "npm",
5375
5375
  node_path: await requireRegularFile(options2.nodePath, "npm Node.js executable"),
5376
5376
  npm_cli_path: await requireRegularFile(options2.npmCliPath, "npm CLI"),
5377
- npm_launcher_path: await requireRegularFile(options2.npmLauncherPath, "npm codexhost launcher")
5377
+ npm_launcher_path: await requireRegularFile(options2.npmLauncherPath, "npm codexhost launcher"),
5378
+ npm_package_root: requireAbsolutePath(options2.packageRoot, "npm platform package root")
5378
5379
  });
5379
5380
  } catch (error51) {
5380
5381
  await writeFailedStatus(common.statusPath, common.version, "npm", error51);
@@ -8466,10 +8467,10 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
8466
8467
  const shape = def.shape;
8467
8468
  const propValues = {};
8468
8469
  for (const key in shape) {
8469
- const field = shape[key]._zod;
8470
- if (field.values) {
8470
+ const field2 = shape[key]._zod;
8471
+ if (field2.values) {
8471
8472
  propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
8472
- for (const v of field.values)
8473
+ for (const v of field2.values)
8473
8474
  propValues[key].add(v);
8474
8475
  }
8475
8476
  }
@@ -20119,6 +20120,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
20119
20120
  cachedInputTokens: count,
20120
20121
  cacheWriteInputTokens: count,
20121
20122
  cacheKnownInputTokens: count,
20123
+ cacheHitCachedInputTokens: count,
20124
+ cacheHitInputTokens: count,
20122
20125
  outputTokens: count,
20123
20126
  reasoningOutputTokens: count,
20124
20127
  /** USD at the public price, summed over the priced requests only. */
@@ -20228,6 +20231,53 @@ var THREAD_PREWARM_DISCARD_METHOD = "codexhost/thread/prewarm/discard";
20228
20231
  var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
20229
20232
  var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
20230
20233
 
20234
+ // packages/shared-contracts/dist/thread-questions.js
20235
+ var THREAD_QUESTIONS_LIST_METHOD = "codexhost/thread/questions/list";
20236
+ var THREAD_QUESTION_RESPOND_METHOD = "codexhost/thread/question/respond";
20237
+ var field = external_exports.discriminatedUnion("type", [
20238
+ external_exports.object({
20239
+ id: external_exports.string().min(1),
20240
+ type: external_exports.literal("choice"),
20241
+ prompt: external_exports.string(),
20242
+ options: external_exports.array(external_exports.object({
20243
+ value: external_exports.string().min(1),
20244
+ label: external_exports.string(),
20245
+ description: external_exports.string().optional()
20246
+ })).min(1),
20247
+ multiple: external_exports.boolean(),
20248
+ allowOther: external_exports.boolean(),
20249
+ optional: external_exports.boolean()
20250
+ }),
20251
+ external_exports.object({
20252
+ id: external_exports.string().min(1),
20253
+ type: external_exports.literal("text"),
20254
+ prompt: external_exports.string(),
20255
+ multiline: external_exports.boolean(),
20256
+ secret: external_exports.literal(false),
20257
+ optional: external_exports.boolean(),
20258
+ placeholder: external_exports.string().optional(),
20259
+ prefill: external_exports.string().optional()
20260
+ })
20261
+ ]);
20262
+ var threadQuestionSchema = external_exports.object({
20263
+ interactionId: external_exports.string().min(1),
20264
+ turnId: external_exports.string().min(1),
20265
+ title: external_exports.string().optional(),
20266
+ questions: external_exports.array(field).min(1)
20267
+ }).refine(({ questions }) => questions.some((q) => q.type === "choice" && q.multiple), {
20268
+ message: "Shared cards require at least one multi-select question"
20269
+ });
20270
+ var threadQuestionsListParamsSchema = external_exports.strictObject({ threadId: external_exports.string().min(1) });
20271
+ var threadQuestionsResultSchema = external_exports.object({ questions: external_exports.array(threadQuestionSchema) });
20272
+ var threadQuestionRespondParamsSchema = external_exports.strictObject({
20273
+ threadId: external_exports.string().min(1),
20274
+ turnId: external_exports.string().min(1),
20275
+ interactionId: external_exports.string().min(1),
20276
+ answers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
20277
+ cancelled: external_exports.boolean().default(false)
20278
+ });
20279
+ var threadQuestionRespondResultSchema = external_exports.object({ accepted: external_exports.literal(true) });
20280
+
20231
20281
  // packages/shared-contracts/dist/harness-plugins.js
20232
20282
  var HARNESS_PLUGIN_API_VERSION = 1;
20233
20283
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
@@ -21017,7 +21067,10 @@ var harnessPluginRouteSchema = external_exports.object({
21017
21067
  harnessId: harnessPluginIdSchema,
21018
21068
  model: harnessModelRefSchema.optional(),
21019
21069
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
21020
- permissionModeId: harnessPermissionModeIdSchema.optional()
21070
+ permissionModeId: harnessPermissionModeIdSchema.optional(),
21071
+ /** A draft prewarm create: stays unsubmitted until the user's first Turn.
21072
+ * Desktop forwards only the Model of a main-process prewarm to thread/start. */
21073
+ prewarm: external_exports.literal(true).optional()
21021
21074
  }).strict();
21022
21075
  function encodeHarnessPluginRoute(route) {
21023
21076
  const parsed2 = harnessPluginRouteSchema.parse(route);
@@ -22500,8 +22553,110 @@ function retainRendererHostResponses(client, hostId2, target) {
22500
22553
  };
22501
22554
  }
22502
22555
 
22556
+ // packages/desktop-control/dist/renderer-prewarm-consumption.js
22557
+ function isolateRendererPrewarmConsumption(manager, discardExternal) {
22558
+ const record5 = (value2) => value2 !== null && typeof value2 === "object";
22559
+ if (!record5(manager) || !record5(manager.threadCreation))
22560
+ return null;
22561
+ const creation = manager.threadCreation;
22562
+ const originalStart = manager.startConversation;
22563
+ const original = creation.createConversation;
22564
+ const params = creation.params;
22565
+ if (typeof originalStart !== "function" || typeof original !== "function" || !record5(params))
22566
+ return null;
22567
+ const prototype = Object.getPrototypeOf(creation);
22568
+ if (!record5(prototype) || typeof prototype.constructor !== "function")
22569
+ return null;
22570
+ if (Object.keys(creation).some((key) => key !== "params" && typeof creation[key] !== "function") || /#[A-Za-z_$]/u.test(Function.prototype.toString.call(prototype.constructor)))
22571
+ return null;
22572
+ const pool = params.prewarmedThreadManager;
22573
+ if (!record5(pool) || typeof pool.hasPrewarmedThread !== "function" || typeof pool.consumePrewarmedThread !== "function" || typeof pool.deletePrewarmedThread !== "function")
22574
+ return null;
22575
+ const consume = pool.consumePrewarmedThread;
22576
+ const hasPrewarm = pool.hasPrewarmedThread;
22577
+ const draftModels = /* @__PURE__ */ new Map();
22578
+ const draftIdentity = /* @__PURE__ */ Symbol("codexhost draft creation");
22579
+ const external = (model2) => typeof model2 === "string" && model2.startsWith("codexhost/");
22580
+ const routedStart = function(input, options2, ...args) {
22581
+ const draftId = record5(options2) ? options2.clientThreadId : null;
22582
+ const mode = record5(input) && record5(input.collaborationMode) ? input.collaborationMode : null;
22583
+ const origin = mode ? Reflect.get(mode, draftIdentity) : void 0;
22584
+ if (mode && record5(mode.settings) && external(mode.settings.model))
22585
+ return originalStart.call(this, input, options2, ...args);
22586
+ const model2 = (typeof draftId === "string" ? draftModels.get(draftId) : void 0) ?? (typeof origin === "string" ? draftModels.get(origin) : void 0);
22587
+ if (!model2)
22588
+ return originalStart.call(this, input, options2, ...args);
22589
+ if (!record5(input) || !record5(input.collaborationMode) || !record5(input.collaborationMode.settings))
22590
+ throw new Error("External draft creation is missing its native Model settings");
22591
+ const routed = {
22592
+ ...input,
22593
+ collaborationMode: {
22594
+ ...input.collaborationMode,
22595
+ settings: { ...input.collaborationMode.settings, model: model2 }
22596
+ }
22597
+ };
22598
+ return originalStart.call(this, routed, options2, ...args);
22599
+ };
22600
+ const wrapped = function(input, ...args) {
22601
+ const mode = record5(input) && record5(input.collaborationMode) ? input.collaborationMode : null;
22602
+ const expected = mode && record5(mode.settings) ? mode.settings.model : null;
22603
+ const scopedPool = Object.create(pool);
22604
+ scopedPool.hasPrewarmedThread = (...parameters) => hasPrewarm.apply(pool, parameters);
22605
+ scopedPool.consumePrewarmedThread = async (...consumeArgs) => {
22606
+ const warmed = await consume.apply(pool, consumeArgs);
22607
+ if (!record5(warmed) || !record5(warmed.response))
22608
+ return warmed;
22609
+ const response = warmed.response;
22610
+ if (!external(expected) && !external(response.model))
22611
+ return warmed;
22612
+ if (external(expected) && expected === response.model)
22613
+ return warmed;
22614
+ if (record5(response.thread) && typeof response.thread.id === "string") {
22615
+ const threadId2 = response.thread.id;
22616
+ if (external(response.model))
22617
+ discardExternal(threadId2);
22618
+ else
22619
+ void Promise.resolve().then(() => pool.deletePrewarmedThread(threadId2)).catch(() => void 0);
22620
+ }
22621
+ return null;
22622
+ };
22623
+ const invocation = Object.create(creation);
22624
+ invocation.params = { ...params, prewarmedThreadManager: scopedPool };
22625
+ return original.call(invocation, input, ...args);
22626
+ };
22627
+ creation.createConversation = wrapped;
22628
+ manager.startConversation = routedStart;
22629
+ return {
22630
+ selectDraft(draftId, model2, creationModes = []) {
22631
+ if (draftId === void 0) {
22632
+ if (model2 === null)
22633
+ draftModels.clear();
22634
+ } else if (model2 === null)
22635
+ draftModels.delete(draftId);
22636
+ else {
22637
+ if (!draftId.startsWith("client-new-thread:") || !external(model2))
22638
+ throw new Error("External draft route is missing its client Thread identity");
22639
+ draftModels.set(draftId, model2);
22640
+ for (const mode of creationModes)
22641
+ Object.defineProperty(mode, draftIdentity, {
22642
+ configurable: true,
22643
+ enumerable: true,
22644
+ value: draftId
22645
+ });
22646
+ }
22647
+ },
22648
+ dispose() {
22649
+ draftModels.clear();
22650
+ if (manager.startConversation === routedStart)
22651
+ manager.startConversation = originalStart;
22652
+ if (creation.createConversation === wrapped)
22653
+ creation.createConversation = original;
22654
+ }
22655
+ };
22656
+ }
22657
+
22503
22658
  // packages/desktop-control/dist/renderer-draft-prewarm-runtime.js
22504
- function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewarmedThreadManager, isCurrentManager, retainResponses = retainRendererHostResponses) {
22659
+ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewarmedThreadManager, isCurrentManager, retainResponses = retainRendererHostResponses, isolateConsumption = isolateRendererPrewarmConsumption) {
22505
22660
  let disposed = false;
22506
22661
  const originalSend = bridge.sendRequest;
22507
22662
  const originalPrewarm = bridge.prewarmThreadStart;
@@ -22891,25 +23046,15 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
22891
23046
  return false;
22892
23047
  return selectedModel !== null && (method.startsWith("thread/") || method.startsWith("turn/") || method.startsWith("review/"));
22893
23048
  };
22894
- const routeThreadStart = (parameters) => {
22895
- if (!isRecord20(parameters) || parameters.ephemeral === true) {
22896
- return parameters;
22897
- }
22898
- return {
22899
- ...parameters,
22900
- ...selectedModel === null ? {} : { model: selectedModel }
22901
- };
22902
- };
22903
23049
  const routedSend = (method, parameters, options2) => {
22904
23050
  if (method === "turn/start" || method === "thread/resume" || method === "codexhost/thread/command/execute") {
22905
23051
  const threadId2 = threadIdFromParameters(parameters);
22906
23052
  if (threadId2)
22907
23053
  externalPrewarms.delete(threadId2);
22908
23054
  }
22909
- const routedParameters = method === "thread/start" ? routeThreadStart(parameters) : parameters;
22910
- const sendBridged = () => initializeBridge().then(() => enqueueBridgeRequest(method, routedParameters, options2));
22911
- const sendDirect = () => options2 === void 0 ? originalSend.call(bridge, method, routedParameters) : originalSend.call(bridge, method, routedParameters, options2);
22912
- const unresolvedThreadId = shouldResolveThreadOwnership(method, routedParameters);
23055
+ const sendBridged = () => initializeBridge().then(() => enqueueBridgeRequest(method, parameters, options2));
23056
+ const sendDirect = () => options2 === void 0 ? originalSend.call(bridge, method, parameters) : originalSend.call(bridge, method, parameters, options2);
23057
+ const unresolvedThreadId = shouldResolveThreadOwnership(method, parameters);
22913
23058
  if (unresolvedThreadId) {
22914
23059
  return resolveThreadOwnership(unresolvedThreadId).then((owner) => owner === "external" ? sendBridged() : sendDirect(), (error51) => {
22915
23060
  if ((method === "thread/read" || method === "thread/resume") && isUnsupportedPosixBridgeSpawn(error51)) {
@@ -22922,7 +23067,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
22922
23067
  throw error51;
22923
23068
  });
22924
23069
  }
22925
- return shouldUseBridge(method, routedParameters) ? sendBridged() : sendDirect();
23070
+ return shouldUseBridge(method, parameters) ? sendBridged() : sendDirect();
22926
23071
  };
22927
23072
  const publishDraftWorkspace = (parameters) => {
22928
23073
  if (!isRecord20(parameters) || parameters.ephemeral === true)
@@ -22951,10 +23096,10 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
22951
23096
  for (const threadId2 of externalPrewarms)
22952
23097
  discardExternalPrewarm(threadId2);
22953
23098
  };
23099
+ const restoreConsumption = isolateConsumption(manager, discardExternalPrewarm);
22954
23100
  const routedPrewarm = (parameters, options2) => {
22955
- const routed = routeThreadStart(parameters);
22956
- const external = isRecord20(routed) && routed.ephemeral !== true && typeof routed.model === "string" && routed.model.startsWith("codexhost/");
22957
- const routedParameters = external ? { ...routed, codexhostPrewarm: true } : routed;
23101
+ const external = isRecord20(parameters) && parameters.ephemeral !== true && typeof parameters.model === "string" && parameters.model.startsWith("codexhost/");
23102
+ const routedParameters = external ? { ...parameters, codexhostPrewarm: true } : parameters;
22958
23103
  const generation = prewarmGeneration;
22959
23104
  publishDraftWorkspace(routedParameters);
22960
23105
  const pending = shouldUseBridge("thread/start", routedParameters) ? routedSend("thread/start", routedParameters, options2) : options2 === void 0 ? originalPrewarm.call(bridge, routedParameters) : originalPrewarm.call(bridge, routedParameters, options2);
@@ -23010,6 +23155,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
23010
23155
  const policy = Object.freeze({
23011
23156
  state: "ready",
23012
23157
  hostId: hostId2,
23158
+ scopedCreation: restoreConsumption !== null,
23013
23159
  owns(candidateManager, candidate, candidateHostId, candidatePrewarmedThreadManager, requiresCurrentManager) {
23014
23160
  return !disposed && candidateManager === manager && candidate === bridge && candidateHostId === hostId2 && candidatePrewarmedThreadManager === prewarmedThreadManager && requiresCurrentManager === !!isCurrentManager;
23015
23161
  },
@@ -23018,12 +23164,13 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
23018
23164
  throw new Error("Renderer request manager is retired");
23019
23165
  return manager;
23020
23166
  },
23021
- select(model2) {
23167
+ select(model2, draftId, creationModes) {
23022
23168
  if (disposed || isCurrentManager && !isCurrentManager())
23023
23169
  throw new Error("Renderer request manager is retired");
23024
23170
  if (model2 !== null && (typeof model2 !== "string" || !model2.startsWith("codexhost/"))) {
23025
23171
  throw new Error("Draft route Model must be a codexhost transport carrier");
23026
23172
  }
23173
+ restoreConsumption?.selectDraft(draftId, model2, creationModes);
23027
23174
  if (selectedModel === model2)
23028
23175
  return false;
23029
23176
  selectedModel = model2;
@@ -23046,6 +23193,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
23046
23193
  disposed = true;
23047
23194
  prewarmGeneration += 1;
23048
23195
  retireResponses();
23196
+ restoreConsumption?.dispose();
23049
23197
  if (bridge.sendRequest === routedSend)
23050
23198
  bridge.sendRequest = originalSend;
23051
23199
  if (bridge.prewarmThreadStart === routedPrewarm) {
@@ -23083,14 +23231,14 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
23083
23231
 
23084
23232
  // packages/desktop-control/dist/renderer-host-discovery.js
23085
23233
  function requestManagerFromHookState(value2, hostId2) {
23086
- const record4 = (candidate) => typeof candidate === "object" && candidate !== null;
23234
+ const record5 = (candidate) => typeof candidate === "object" && candidate !== null;
23087
23235
  const manager = (candidate) => {
23088
- if (!record4(candidate) || !record4(candidate.requestClient) || !record4(candidate.prewarmedThreadManager))
23236
+ if (!record5(candidate) || !record5(candidate.requestClient) || !record5(candidate.prewarmedThreadManager))
23089
23237
  return null;
23090
23238
  const bridge = candidate.requestClient;
23091
23239
  return typeof candidate.sendRequest === "function" && typeof bridge.sendRequest === "function" && typeof bridge.prewarmThreadStart === "function" && typeof bridge.enqueueRequest === "function" && typeof candidate.prewarmedThreadManager.discardAllPrewarmedThreads === "function" ? candidate : null;
23092
23240
  };
23093
- if (!record4(value2))
23241
+ if (!record5(value2))
23094
23242
  return null;
23095
23243
  const direct = manager(value2) ?? manager(value2.manager);
23096
23244
  if (direct)
@@ -23294,6 +23442,372 @@ function installRendererHostRouting(root, target, discover, resolve, createPolic
23294
23442
  return routing;
23295
23443
  }
23296
23444
 
23445
+ // packages/desktop-control/dist/renderer-host-rpc-discovery.js
23446
+ function findRendererAppScopeStore(root) {
23447
+ const MAX_VISITED_FIBERS = 5e4;
23448
+ const record5 = (value2) => typeof value2 === "object" && value2 !== null;
23449
+ const container = root.getElementById?.("root");
23450
+ if (!record5(container))
23451
+ return null;
23452
+ const key = Object.getOwnPropertyNames(container).find((name) => name.startsWith("__reactContainer$"));
23453
+ const first = key ? container[key] : null;
23454
+ if (!record5(first))
23455
+ return null;
23456
+ const isScopeHandle = (value2) => record5(value2) && record5(value2.node) && "chain" in value2 && "scope" in value2 && typeof value2.get === "function" && typeof value2.set === "function" && typeof value2.watch === "function";
23457
+ const stack = [first];
23458
+ const seen = /* @__PURE__ */ new Set();
23459
+ while (stack.length && seen.size < MAX_VISITED_FIBERS) {
23460
+ const fiber = stack.pop();
23461
+ if (seen.has(fiber))
23462
+ continue;
23463
+ seen.add(fiber);
23464
+ let hook = fiber.memoizedState;
23465
+ for (let index = 0; record5(hook) && "next" in hook && index < 150; index += 1) {
23466
+ const state = hook.memoizedState;
23467
+ const handle = record5(state) ? state.current : null;
23468
+ if (isScopeHandle(handle)) {
23469
+ let node = handle.node;
23470
+ const nodes = /* @__PURE__ */ new Set();
23471
+ while (record5(node.parent) && !nodes.has(node.parent)) {
23472
+ nodes.add(node);
23473
+ node = node.parent;
23474
+ }
23475
+ const bindings = node.familyBindings;
23476
+ return record5(bindings) && typeof bindings.get === "function" && typeof bindings.entries === "function" ? node : null;
23477
+ }
23478
+ hook = hook.next;
23479
+ }
23480
+ if (record5(fiber.sibling))
23481
+ stack.push(fiber.sibling);
23482
+ if (record5(fiber.child))
23483
+ stack.push(fiber.child);
23484
+ }
23485
+ return null;
23486
+ }
23487
+ function findRendererHostRpcFamily(store) {
23488
+ const record5 = (value2) => typeof value2 === "object" && value2 !== null;
23489
+ const families = /* @__PURE__ */ new Set();
23490
+ for (const [definition, members] of store.familyBindings) {
23491
+ if (!record5(definition) || definition.kind !== "signal-family")
23492
+ continue;
23493
+ if (!record5(members) || typeof members.get !== "function")
23494
+ continue;
23495
+ for (const [hostId2, member] of members) {
23496
+ if (typeof hostId2 !== "string" || !record5(member))
23497
+ continue;
23498
+ const signal = member.value;
23499
+ if (!record5(signal) || typeof signal.get !== "function")
23500
+ continue;
23501
+ let value2;
23502
+ try {
23503
+ value2 = signal.get();
23504
+ } catch {
23505
+ continue;
23506
+ }
23507
+ if (record5(value2) && Object.keys(value2).length === 2 && typeof value2.status === "string" && record5(value2.client) && value2.client.hostId === hostId2 && "rpc" in value2.client) {
23508
+ families.add(members);
23509
+ break;
23510
+ }
23511
+ }
23512
+ }
23513
+ if (families.size !== 1)
23514
+ return null;
23515
+ return { store, family: families.values().next().value };
23516
+ }
23517
+ function resolveRendererHostRpc(discovery, hostId2) {
23518
+ const record5 = (value3) => typeof value3 === "object" && value3 !== null;
23519
+ const signal = discovery.family.get(hostId2)?.value;
23520
+ if (!record5(signal) || typeof signal.get !== "function")
23521
+ return null;
23522
+ let value2;
23523
+ try {
23524
+ value2 = signal.get();
23525
+ } catch {
23526
+ return null;
23527
+ }
23528
+ if (!record5(value2) || value2.status !== "ready" || !record5(value2.client) || value2.client.hostId !== hostId2)
23529
+ return null;
23530
+ const rpc = value2.client.rpc;
23531
+ return typeof rpc === "function" || record5(rpc) ? rpc : null;
23532
+ }
23533
+ function rendererHostRpcHostIds(discovery) {
23534
+ return [...discovery.family.keys()].filter((hostId2) => typeof hostId2 === "string");
23535
+ }
23536
+
23537
+ // packages/desktop-control/dist/renderer-host-rpc-routing.js
23538
+ function installRendererHostRpcRouting(root, target, dependencies2) {
23539
+ const existing = target.__codexhostHostRoutingV1;
23540
+ if (existing)
23541
+ return existing;
23542
+ let disposed = false;
23543
+ let discovery = null;
23544
+ const routes = /* @__PURE__ */ new Map();
23545
+ const read = () => {
23546
+ if (disposed)
23547
+ return null;
23548
+ if (!discovery) {
23549
+ const store = dependencies2.findStore(root);
23550
+ discovery = store ? dependencies2.findFamily(store) : null;
23551
+ }
23552
+ return discovery;
23553
+ };
23554
+ if (!read())
23555
+ return null;
23556
+ const isRecord20 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
23557
+ const externalDrafts = /* @__PURE__ */ new Map();
23558
+ const selectedModels = /* @__PURE__ */ new Map();
23559
+ const prewarmCarrier = (carrier) => {
23560
+ const prefix = "codexhost/plugin-v1@";
23561
+ if (!carrier.startsWith(prefix))
23562
+ return null;
23563
+ try {
23564
+ const json2 = carrier.slice(prefix.length).replace(/[a-f0-9]{2}/gu, (byte) => String.fromCharCode(Number.parseInt(byte, 16)));
23565
+ const route = JSON.parse(json2);
23566
+ if (!isRecord20(route))
23567
+ return null;
23568
+ const payload = [...JSON.stringify({ ...route, prewarm: true })].map((character) => character.charCodeAt(0).toString(16).padStart(2, "0")).join("");
23569
+ return `${prefix}${payload}`;
23570
+ } catch {
23571
+ return null;
23572
+ }
23573
+ };
23574
+ const publishDraftWorkspace = (hostId2, cwd) => {
23575
+ if (typeof cwd !== "string" || cwd.length === 0)
23576
+ return;
23577
+ const drafts = isRecord20(target.__codexhostDraftWorkspacesV1) ? target.__codexhostDraftWorkspacesV1 : {};
23578
+ if (drafts[hostId2] === cwd)
23579
+ return;
23580
+ drafts[hostId2] = cwd;
23581
+ Object.defineProperty(target, "__codexhostDraftWorkspacesV1", {
23582
+ configurable: true,
23583
+ value: drafts
23584
+ });
23585
+ if (typeof target.dispatchEvent === "function" && typeof CustomEvent === "function") {
23586
+ target.dispatchEvent(new CustomEvent("codexhost:draft-workspace", { detail: { hostId: hostId2, cwd } }));
23587
+ }
23588
+ };
23589
+ const routeCreationCall = (message2) => {
23590
+ if (!Array.isArray(message2) || message2.length !== 2 || message2[0] !== "push")
23591
+ return message2;
23592
+ const expression = message2[1];
23593
+ if (!Array.isArray(expression) || expression.length !== 4 || expression[0] !== "pipeline")
23594
+ return message2;
23595
+ const [, importId, path44, args] = expression;
23596
+ if (!Array.isArray(path44) || path44.length !== 1 || !Array.isArray(args))
23597
+ return message2;
23598
+ const [input, options2] = args;
23599
+ if (!isRecord20(input) || !isRecord20(input.collaborationMode))
23600
+ return message2;
23601
+ const settings = input.collaborationMode.settings;
23602
+ if (!isRecord20(settings))
23603
+ return message2;
23604
+ let model2 = null;
23605
+ if (path44[0] === "startConversation") {
23606
+ const draftId = isRecord20(options2) ? options2.clientThreadId : null;
23607
+ model2 = typeof draftId === "string" ? externalDrafts.get(draftId)?.model ?? null : null;
23608
+ } else if (path44[0] === "prewarmConversation") {
23609
+ if (input.ephemeral !== true)
23610
+ publishDraftWorkspace("local", input.cwd);
23611
+ const selected = selectedModels.get("local");
23612
+ model2 = selected ? prewarmCarrier(selected) : null;
23613
+ }
23614
+ if (!model2)
23615
+ return message2;
23616
+ return [
23617
+ "push",
23618
+ [
23619
+ "pipeline",
23620
+ importId,
23621
+ path44,
23622
+ [
23623
+ {
23624
+ ...input,
23625
+ collaborationMode: { ...input.collaborationMode, settings: { ...settings, model: model2 } }
23626
+ },
23627
+ ...args.slice(1)
23628
+ ]
23629
+ ]
23630
+ ];
23631
+ };
23632
+ const port = dependencies2.portPrototype;
23633
+ const originalPostMessage = port.postMessage;
23634
+ const postMessage = function(message2, ...rest) {
23635
+ let routed = message2;
23636
+ try {
23637
+ routed = disposed ? message2 : routeCreationCall(message2);
23638
+ } catch {
23639
+ routed = message2;
23640
+ }
23641
+ return originalPostMessage.call(this, routed, ...rest);
23642
+ };
23643
+ port.postMessage = postMessage;
23644
+ const createRoute = (hostId2, rpc) => {
23645
+ let retired = false;
23646
+ const isCurrent = () => !retired && !disposed && routes.get(hostId2)?.rpc === rpc;
23647
+ const manager = Object.freeze({
23648
+ kind: "main-process-rpc",
23649
+ getHostId: () => hostId2,
23650
+ sendRequest(method, params, options2) {
23651
+ if (!isCurrent())
23652
+ return Promise.reject(new Error(`Renderer request manager is retired for ${hostId2}`));
23653
+ return options2 === void 0 ? rpc.sendRequest(method, params) : rpc.sendRequest(method, params, options2);
23654
+ },
23655
+ // The main process broadcasts every app-server notification to its windows,
23656
+ // including codexhost methods Desktop's own notification table drops.
23657
+ addNotificationCallback(methods, listener) {
23658
+ const accepted = new Set(typeof methods === "string" ? [methods] : methods);
23659
+ const onMessage = (event) => {
23660
+ const { source, data } = event;
23661
+ if (source != null && source !== target)
23662
+ return;
23663
+ if (!isRecord20(data) || data.type !== "mcp-notification" || data.hostId !== hostId2 || typeof data.method !== "string" || !accepted.has(data.method) || !isCurrent())
23664
+ return;
23665
+ listener({ method: data.method, params: data.params });
23666
+ };
23667
+ target.addEventListener?.("message", onMessage);
23668
+ return () => target.removeEventListener?.("message", onMessage);
23669
+ }
23670
+ });
23671
+ const clearDrafts = () => {
23672
+ for (const [draftId, draft] of externalDrafts) {
23673
+ if (draft.owner === policy)
23674
+ externalDrafts.delete(draftId);
23675
+ }
23676
+ };
23677
+ const clear = () => isCurrent() ? Promise.resolve(rpc.clearPrewarmedThreads()).then(() => void 0) : Promise.reject(new Error("Renderer request manager is retired"));
23678
+ const policy = Object.freeze({
23679
+ state: "ready",
23680
+ hostId: hostId2,
23681
+ scopedCreation: true,
23682
+ requestTarget: () => {
23683
+ if (!isCurrent())
23684
+ throw new Error("Renderer request manager is retired");
23685
+ return manager;
23686
+ },
23687
+ select(model2, draftId) {
23688
+ if (!isCurrent())
23689
+ throw new Error("Renderer request manager is retired");
23690
+ if (model2 !== null && (typeof model2 !== "string" || !model2.startsWith("codexhost/"))) {
23691
+ throw new Error("Draft route Model must be a codexhost transport carrier");
23692
+ }
23693
+ if (draftId === void 0) {
23694
+ if (model2 === null)
23695
+ clearDrafts();
23696
+ } else if (model2 === null) {
23697
+ if (externalDrafts.get(draftId)?.owner === policy)
23698
+ externalDrafts.delete(draftId);
23699
+ } else {
23700
+ if (!draftId.startsWith("client-new-thread:"))
23701
+ throw new Error("External draft route is missing its client Thread identity");
23702
+ externalDrafts.set(draftId, { model: model2, owner: policy });
23703
+ }
23704
+ if ((selectedModels.get(hostId2) ?? null) === model2)
23705
+ return false;
23706
+ if (model2 === null)
23707
+ selectedModels.delete(hostId2);
23708
+ else
23709
+ selectedModels.set(hostId2, model2);
23710
+ void clear().catch(() => void 0);
23711
+ return true;
23712
+ },
23713
+ clear,
23714
+ dispose() {
23715
+ if (retired)
23716
+ return;
23717
+ retired = true;
23718
+ clearDrafts();
23719
+ selectedModels.delete(hostId2);
23720
+ }
23721
+ });
23722
+ return { hostId: hostId2, manager, policy };
23723
+ };
23724
+ const retire = (hostId2) => {
23725
+ const entry = routes.get(hostId2);
23726
+ routes.delete(hostId2);
23727
+ entry?.route.policy.dispose();
23728
+ };
23729
+ const routeFor = (hostId2) => {
23730
+ const current = read();
23731
+ const rpc = current ? dependencies2.resolve(current, hostId2) : null;
23732
+ const previous = routes.get(hostId2);
23733
+ if (rpc && previous?.rpc === rpc)
23734
+ return previous.route;
23735
+ retire(hostId2);
23736
+ if (!rpc)
23737
+ return null;
23738
+ const route = createRoute(hostId2, rpc);
23739
+ routes.set(hostId2, { route, rpc });
23740
+ return route;
23741
+ };
23742
+ const publish = (route) => {
23743
+ const policy = route?.policy;
23744
+ if (target.__codexhostDraftPrewarmPolicyV1 === policy)
23745
+ return;
23746
+ Object.defineProperty(target, "__codexhostDraftPrewarmPolicyV1", {
23747
+ configurable: true,
23748
+ value: policy
23749
+ });
23750
+ if (typeof target.dispatchEvent === "function" && typeof CustomEvent === "function") {
23751
+ target.dispatchEvent(new CustomEvent("codexhost:draft-prewarm-policy-changed"));
23752
+ }
23753
+ };
23754
+ const composerHostId = (composer) => {
23755
+ const hostIds = new Set(dependencies2.composerHostIds(composer).hostIds);
23756
+ const hostId2 = hostIds.size === 1 ? hostIds.values().next().value : null;
23757
+ return typeof hostId2 === "string" && hostId2 ? hostId2 : null;
23758
+ };
23759
+ const routing = {
23760
+ knownHostIds() {
23761
+ const current = read();
23762
+ return current ? dependencies2.hostIds(current) : [];
23763
+ },
23764
+ forHost(hostId2) {
23765
+ return hostId2 && !disposed ? routeFor(hostId2) : null;
23766
+ },
23767
+ hostIdForComposer(composer) {
23768
+ if (disposed)
23769
+ return null;
23770
+ try {
23771
+ return composerHostId(composer);
23772
+ } catch {
23773
+ return null;
23774
+ }
23775
+ },
23776
+ forComposer(composer) {
23777
+ if (disposed)
23778
+ return null;
23779
+ let hostId2;
23780
+ try {
23781
+ hostId2 = composerHostId(composer);
23782
+ } catch {
23783
+ hostId2 = null;
23784
+ }
23785
+ const route = hostId2 ? routeFor(hostId2) : null;
23786
+ if (!composer)
23787
+ publish(route);
23788
+ return route;
23789
+ },
23790
+ dispose() {
23791
+ if (disposed)
23792
+ return;
23793
+ disposed = true;
23794
+ for (const hostId2 of [...routes.keys()])
23795
+ retire(hostId2);
23796
+ discovery = null;
23797
+ externalDrafts.clear();
23798
+ selectedModels.clear();
23799
+ if (port.postMessage === postMessage)
23800
+ port.postMessage = originalPostMessage;
23801
+ if (target.__codexhostHostRoutingV1 === routing) {
23802
+ delete target.__codexhostHostRoutingV1;
23803
+ publish(null);
23804
+ }
23805
+ }
23806
+ };
23807
+ Object.defineProperty(target, "__codexhostHostRoutingV1", { configurable: true, value: routing });
23808
+ return routing;
23809
+ }
23810
+
23297
23811
  // packages/desktop-control/dist/renderer-draft-prewarm-policy.js
23298
23812
  var REQUEST_MANAGER_WAIT_TIMEOUT_MS = 6e4;
23299
23813
  var REQUEST_MANAGER_POLL_INTERVAL_MS = 25;
@@ -23305,14 +23819,41 @@ function directRendererInstaller() {
23305
23819
  const resolveRendererHostManager = ${resolveRendererHostManager.toString()};
23306
23820
  const retainRendererHostResponses = ${retainRendererHostResponses.toString()};
23307
23821
  const createDraftPrewarmPolicyBridge = ${createDraftPrewarmPolicyBridge.toString()};
23308
- const routing = (${installRendererHostRouting.toString()})(
23309
- document, window,
23310
- (root) => discoverRendererHosts(root, committedReactAncestors, requestManagerFromHookState),
23822
+ const isolateRendererPrewarmConsumption = ${isolateRendererPrewarmConsumption.toString()};
23823
+ const discover = (root) =>
23824
+ discoverRendererHosts(root, committedReactAncestors, requestManagerFromHookState);
23825
+ const installNative = () => (${installRendererHostRouting.toString()})(
23826
+ document, window, discover,
23311
23827
  (discovery, hostId) => resolveRendererHostManager(discovery, hostId, requestManagerFromHookState),
23312
23828
  (manager, bridge, hostId, target, prewarmed, isCurrent) => createDraftPrewarmPolicyBridge(
23313
23829
  manager, bridge, hostId, target, prewarmed, isCurrent, retainRendererHostResponses,
23830
+ isolateRendererPrewarmConsumption,
23314
23831
  ),
23315
23832
  );
23833
+ const installRpc = () => typeof MessagePort !== 'function' ? null : (${installRendererHostRpcRouting.toString()})(document, window, {
23834
+ findStore: ${findRendererAppScopeStore.toString()},
23835
+ findFamily: ${findRendererHostRpcFamily.toString()},
23836
+ resolve: ${resolveRendererHostRpc.toString()},
23837
+ hostIds: ${rendererHostRpcHostIds.toString()},
23838
+ composerHostIds: (composer) => {
23839
+ const source = composer?.matches?.('[data-codex-composer], [contenteditable="true"][role="textbox"]')
23840
+ ? { querySelectorAll: () => [composer] }
23841
+ : (composer ?? document);
23842
+ return discover(source);
23843
+ },
23844
+ portPrototype: MessagePort.prototype,
23845
+ });
23846
+ // Desktop 26.1027 moved AppServerManagers to the main process. Older builds
23847
+ // expose native managers in Renderer hook state; the main-process mode only
23848
+ // applies when none is visible and its per-Host RPC store is identified.
23849
+ const routing = (() => {
23850
+ if (window.__codexhostHostRoutingV1) return window.__codexhostHostRoutingV1;
23851
+ const native = discover(document);
23852
+ if (native.managers.length || native.registries.length) return installNative();
23853
+ const rpc = installRpc();
23854
+ if (rpc) return rpc;
23855
+ throw new Error('Renderer Host request manager is unavailable');
23856
+ })();
23316
23857
  // Publish a default draft policy only when its Host is unambiguous. Host
23317
23858
  // connections can be ready even when multiple Composers coexist.
23318
23859
  const composerRoute = routing.forComposer();
@@ -23347,6 +23888,119 @@ function installRendererDraftPrewarmPolicyDirect(renderer) {
23347
23888
  // packages/desktop-control/dist/renderer-control-session.js
23348
23889
  var startupTraceStartedAt = Date.now();
23349
23890
 
23891
+ // packages/desktop-control/dist/renderer-loaded-modules.js
23892
+ var record3 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
23893
+ var MAX_MODULES = 4096;
23894
+ function nativeModuleCatalogExpression(urls, complete, owner) {
23895
+ return `Object.defineProperty(globalThis, '__codexhostLoadedModulesV1', {
23896
+ configurable: true,
23897
+ value: Object.freeze({ owner: ${JSON.stringify(owner)}, documentUrl: location.href, complete: ${complete}, urls: Object.freeze(${JSON.stringify(urls)}) })
23898
+ }); void 0`;
23899
+ }
23900
+ async function installRendererLoadedModules(renderer) {
23901
+ const owner = crypto.randomUUID();
23902
+ const contexts = /* @__PURE__ */ new Map();
23903
+ const contextIds = /* @__PURE__ */ new Map();
23904
+ const dirty = /* @__PURE__ */ new Set();
23905
+ let ready = false;
23906
+ let disposed = false;
23907
+ let timer;
23908
+ let publishing = Promise.resolve();
23909
+ const flush = () => {
23910
+ clearTimeout(timer);
23911
+ timer = void 0;
23912
+ const pending = [...dirty];
23913
+ dirty.clear();
23914
+ publishing = publishing.catch(() => void 0).then(async () => {
23915
+ for (const uniqueId of pending) {
23916
+ const context = contexts.get(uniqueId);
23917
+ if (!context || disposed)
23918
+ continue;
23919
+ const response = await renderer.command("Runtime.evaluate", {
23920
+ expression: nativeModuleCatalogExpression([...context.urls], context.complete, owner),
23921
+ uniqueContextId: uniqueId
23922
+ });
23923
+ if (record3(response) && record3(response.exceptionDetails))
23924
+ throw new Error("Loaded Renderer module catalog publication failed");
23925
+ }
23926
+ });
23927
+ return publishing;
23928
+ };
23929
+ const schedule = (uniqueId) => {
23930
+ dirty.add(uniqueId);
23931
+ if (ready && timer === void 0)
23932
+ timer = setTimeout(() => {
23933
+ void flush().catch((error51) => {
23934
+ console.error("Could not publish loaded Renderer modules", error51);
23935
+ });
23936
+ }, 10);
23937
+ };
23938
+ const remove = (id2) => {
23939
+ const uniqueId = contextIds.get(id2);
23940
+ contextIds.delete(id2);
23941
+ if (uniqueId) {
23942
+ contexts.delete(uniqueId);
23943
+ dirty.delete(uniqueId);
23944
+ }
23945
+ };
23946
+ const listeners = [
23947
+ renderer.on("Runtime.executionContextCreated", (params) => {
23948
+ const context = record3(params) ? params.context : null;
23949
+ if (!record3(context) || typeof context.id !== "number" || typeof context.uniqueId !== "string" || !record3(context.auxData) || context.auxData.isDefault !== true)
23950
+ return;
23951
+ contextIds.set(context.id, context.uniqueId);
23952
+ contexts.set(context.uniqueId, { urls: /* @__PURE__ */ new Set(), complete: true });
23953
+ schedule(context.uniqueId);
23954
+ }),
23955
+ renderer.on("Runtime.executionContextDestroyed", (params) => {
23956
+ if (record3(params) && typeof params.executionContextId === "number")
23957
+ remove(params.executionContextId);
23958
+ }),
23959
+ renderer.on("Runtime.executionContextsCleared", () => {
23960
+ contextIds.clear();
23961
+ contexts.clear();
23962
+ dirty.clear();
23963
+ }),
23964
+ renderer.on("Debugger.scriptParsed", (params) => {
23965
+ if (!record3(params) || params.isModule !== true || params.hasSourceURL === true || typeof params.url !== "string" || typeof params.executionContextId !== "number")
23966
+ return;
23967
+ const uniqueId = contextIds.get(params.executionContextId);
23968
+ const context = uniqueId ? contexts.get(uniqueId) : null;
23969
+ if (!context || !uniqueId || context.urls.has(params.url))
23970
+ return;
23971
+ if (context.urls.size >= MAX_MODULES)
23972
+ context.complete = false;
23973
+ else
23974
+ context.urls.add(params.url);
23975
+ schedule(uniqueId);
23976
+ })
23977
+ ];
23978
+ const dispose = () => {
23979
+ disposed = true;
23980
+ clearTimeout(timer);
23981
+ for (const unsubscribe of listeners)
23982
+ unsubscribe();
23983
+ for (const uniqueId of contexts.keys())
23984
+ void renderer.command("Runtime.evaluate", {
23985
+ expression: `if (globalThis.__codexhostLoadedModulesV1 === undefined || globalThis.__codexhostLoadedModulesV1?.owner === ${JSON.stringify(owner)}) { ${nativeModuleCatalogExpression([], false, owner)} }`,
23986
+ uniqueContextId: uniqueId
23987
+ }).catch(() => void 0);
23988
+ contexts.clear();
23989
+ contextIds.clear();
23990
+ dirty.clear();
23991
+ };
23992
+ try {
23993
+ await renderer.command("Runtime.enable");
23994
+ await renderer.command("Debugger.enable");
23995
+ ready = true;
23996
+ await flush();
23997
+ return dispose;
23998
+ } catch (error51) {
23999
+ dispose();
24000
+ throw error51;
24001
+ }
24002
+ }
24003
+
23350
24004
  // packages/desktop-control/dist/renderer-cdp-control-session.js
23351
24005
  function isRecord2(value2) {
23352
24006
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
@@ -23481,15 +24135,17 @@ async function waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs
23481
24135
  }
23482
24136
  async function installTarget(target, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations) {
23483
24137
  const renderer = await operations.connect(target.webSocketDebuggerUrl);
24138
+ let disposeModules;
23484
24139
  try {
23485
- await renderer.command("Runtime.enable");
24140
+ disposeModules = await installRendererLoadedModules(renderer);
23486
24141
  await renderer.command("Page.enable");
23487
24142
  await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: rendererSource });
23488
24143
  await evaluateSource(renderer, rendererSource);
23489
24144
  const draftPrewarmPolicy = await operations.installDraftPrewarmPolicy(renderer);
23490
24145
  const binding = await waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs);
23491
- return { renderer, snapshot: { target, draftPrewarmPolicy, binding } };
24146
+ return { renderer, snapshot: { target, draftPrewarmPolicy, binding }, disposeModules };
23492
24147
  } catch (error51) {
24148
+ disposeModules?.();
23493
24149
  renderer.close();
23494
24150
  throw error51;
23495
24151
  }
@@ -23503,8 +24159,9 @@ var InstalledRendererCdpControlSession = class {
23503
24159
  pollIntervalMs;
23504
24160
  operations;
23505
24161
  currentSnapshot;
24162
+ disposeModules;
23506
24163
  #closed = false;
23507
- constructor(renderer, rendererCdpEndpoint, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot) {
24164
+ constructor(renderer, rendererCdpEndpoint, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot, disposeModules) {
23508
24165
  this.renderer = renderer;
23509
24166
  this.rendererCdpEndpoint = rendererCdpEndpoint;
23510
24167
  this.rendererSource = rendererSource;
@@ -23513,6 +24170,7 @@ var InstalledRendererCdpControlSession = class {
23513
24170
  this.pollIntervalMs = pollIntervalMs;
23514
24171
  this.operations = operations;
23515
24172
  this.currentSnapshot = currentSnapshot;
24173
+ this.disposeModules = disposeModules;
23516
24174
  }
23517
24175
  get snapshot() {
23518
24176
  return this.currentSnapshot;
@@ -23523,8 +24181,10 @@ var InstalledRendererCdpControlSession = class {
23523
24181
  const target = await waitForPrimaryTarget(this.rendererCdpEndpoint, this.operations, this.timeoutMs, this.pollIntervalMs, this.currentSnapshot.target.id);
23524
24182
  if (target.id !== this.currentSnapshot.target.id) {
23525
24183
  const replacement = await installTarget(target, this.rendererSource, this.enabledAgents, this.timeoutMs, this.pollIntervalMs, this.operations);
24184
+ this.disposeModules();
23526
24185
  this.renderer.close();
23527
24186
  this.renderer = replacement.renderer;
24187
+ this.disposeModules = replacement.disposeModules;
23528
24188
  this.currentSnapshot = replacement.snapshot;
23529
24189
  return this.currentSnapshot;
23530
24190
  }
@@ -23538,8 +24198,10 @@ var InstalledRendererCdpControlSession = class {
23538
24198
  return this.currentSnapshot;
23539
24199
  } catch {
23540
24200
  const replacement = await installTarget(target, this.rendererSource, this.enabledAgents, this.timeoutMs, this.pollIntervalMs, this.operations);
24201
+ this.disposeModules();
23541
24202
  this.renderer.close();
23542
24203
  this.renderer = replacement.renderer;
24204
+ this.disposeModules = replacement.disposeModules;
23543
24205
  this.currentSnapshot = replacement.snapshot;
23544
24206
  return this.currentSnapshot;
23545
24207
  }
@@ -23559,6 +24221,7 @@ var InstalledRendererCdpControlSession = class {
23559
24221
  if (this.#closed)
23560
24222
  return;
23561
24223
  this.#closed = true;
24224
+ this.disposeModules();
23562
24225
  this.renderer.close();
23563
24226
  }
23564
24227
  };
@@ -23574,7 +24237,7 @@ async function createRendererCdpControlSession(options2) {
23574
24237
  const operations = options2.operations ?? defaultOperations;
23575
24238
  const target = await waitForPrimaryTarget(options2.rendererCdpEndpoint, operations, timeoutMs, pollIntervalMs, void 0, options2.signal);
23576
24239
  const installed = await installTarget(target, options2.rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations);
23577
- return new InstalledRendererCdpControlSession(installed.renderer, options2.rendererCdpEndpoint, options2.rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, installed.snapshot);
24240
+ return new InstalledRendererCdpControlSession(installed.renderer, options2.rendererCdpEndpoint, options2.rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, installed.snapshot, installed.disposeModules);
23578
24241
  }
23579
24242
  function installRendererCdpControlSession(options2) {
23580
24243
  return createRendererCdpControlSession(options2);
@@ -24560,9 +25223,9 @@ function parseModelPriceOverrides(value2) {
24560
25223
  if (key.length === 0 || !isRecord3(entry)) {
24561
25224
  throw new Error(`Price override '${key}' is invalid`);
24562
25225
  }
24563
- for (const field of Object.keys(entry)) {
24564
- if (!["input", "output", "cacheRead", "cacheWrite", "cacheWrite1h"].includes(field)) {
24565
- throw new Error(`Price override '${key}' contains unknown field '${field}'`);
25226
+ for (const field2 of Object.keys(entry)) {
25227
+ if (!["input", "output", "cacheRead", "cacheWrite", "cacheWrite1h"].includes(field2)) {
25228
+ throw new Error(`Price override '${key}' contains unknown field '${field2}'`);
24566
25229
  }
24567
25230
  }
24568
25231
  const input = price(entry.input);
@@ -24571,11 +25234,11 @@ function parseModelPriceOverrides(value2) {
24571
25234
  throw new Error(`Price override '${key}' needs non-negative 'input' and 'output'`);
24572
25235
  }
24573
25236
  const resolved = { input, output };
24574
- for (const field of ["cacheRead", "cacheWrite", "cacheWrite1h"]) {
24575
- if (entry[field] === void 0) continue;
24576
- const candidate = price(entry[field]);
24577
- if (candidate === null) throw new Error(`Price override '${key}' has invalid '${field}'`);
24578
- resolved[field] = candidate;
25237
+ for (const field2 of ["cacheRead", "cacheWrite", "cacheWrite1h"]) {
25238
+ if (entry[field2] === void 0) continue;
25239
+ const candidate = price(entry[field2]);
25240
+ if (candidate === null) throw new Error(`Price override '${key}' has invalid '${field2}'`);
25241
+ resolved[field2] = candidate;
24579
25242
  }
24580
25243
  overrides.set(key, resolved);
24581
25244
  }
@@ -25268,6 +25931,42 @@ function parseHarnessAccountCredits(value2) {
25268
25931
  return parsed2.success ? parsed2.data : null;
25269
25932
  }
25270
25933
 
25934
+ // packages/harness-adapter/dist/question.js
25935
+ function invalidRequest(message2) {
25936
+ return { code: "invalidRequest", message: message2, retryable: false };
25937
+ }
25938
+ function validateHostQuestionResponse(interaction, response) {
25939
+ const questionIds = new Set(interaction.questions.map(({ id: id2 }) => id2));
25940
+ if (response.cancelled) {
25941
+ return Object.keys(response.answers).length === 0 ? null : invalidRequest("Cancelled Question Response must not contain answers");
25942
+ }
25943
+ for (const answerId of Object.keys(response.answers)) {
25944
+ if (!questionIds.has(answerId)) {
25945
+ return invalidRequest("Question Response contains an unknown Question ID");
25946
+ }
25947
+ }
25948
+ for (const question of interaction.questions) {
25949
+ const answers = response.answers[question.id] ?? [];
25950
+ if (!question.optional && answers.length === 0) {
25951
+ return invalidRequest("Question Response omits a required answer");
25952
+ }
25953
+ if (question.type === "text") {
25954
+ if (answers.length > 1) {
25955
+ return invalidRequest("Text Question accepts at most one answer");
25956
+ }
25957
+ continue;
25958
+ }
25959
+ if (!question.multiple && answers.length > 1) {
25960
+ return invalidRequest("Single-choice Question accepts at most one answer");
25961
+ }
25962
+ const declared = new Set(question.options.map(({ value: value2 }) => value2));
25963
+ if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
25964
+ return invalidRequest("Question Response contains an undeclared choice");
25965
+ }
25966
+ }
25967
+ return null;
25968
+ }
25969
+
25271
25970
  // packages/harness-adapter/dist/output-channel.js
25272
25971
  var HarnessOutputChannel = class {
25273
25972
  outputs;
@@ -25374,26 +26073,26 @@ function parseHostUsage(value2) {
25374
26073
  }
25375
26074
  }
25376
26075
  const indicators = value2.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value2.composerIndicators) };
25377
- for (const field of [
26076
+ for (const field2 of [
25378
26077
  "totalCredits",
25379
26078
  "contextUsagePercent",
25380
26079
  "apiOutputTokensPerSecond"
25381
26080
  ]) {
25382
- const candidate = value2[field];
26081
+ const candidate = value2[field2];
25383
26082
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
25384
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
26083
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
25385
26084
  }
25386
26085
  }
25387
- for (const field of tokenFields) {
25388
- const candidate = value2[field];
26086
+ for (const field2 of tokenFields) {
26087
+ const candidate = value2[field2];
25389
26088
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
25390
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
26089
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
25391
26090
  }
25392
26091
  }
25393
- for (const field of safeIntegerFields) {
25394
- const candidate = value2[field];
26092
+ for (const field2 of safeIntegerFields) {
26093
+ const candidate = value2[field2];
25395
26094
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
25396
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
26095
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
25397
26096
  }
25398
26097
  }
25399
26098
  if (value2.outputTokensPerSecond !== void 0 && (typeof value2.outputTokensPerSecond !== "number" || !Number.isFinite(value2.outputTokensPerSecond) || value2.outputTokensPerSecond < 0)) {
@@ -25402,16 +26101,16 @@ function parseHostUsage(value2) {
25402
26101
  if (value2.totalCostUsd !== void 0 && (typeof value2.totalCostUsd !== "number" || !Number.isFinite(value2.totalCostUsd) || value2.totalCostUsd < 0)) {
25403
26102
  throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
25404
26103
  }
25405
- for (const field of ["totalCredits", "contextUsagePercent"]) {
25406
- const candidate = value2[field];
26104
+ for (const field2 of ["totalCredits", "contextUsagePercent"]) {
26105
+ const candidate = value2[field2];
25407
26106
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
25408
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
26107
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
25409
26108
  }
25410
26109
  }
25411
- for (const field of percentFields) {
25412
- const candidate = value2[field];
26110
+ for (const field2 of percentFields) {
26111
+ const candidate = value2[field2];
25413
26112
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
25414
- throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
26113
+ throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
25415
26114
  }
25416
26115
  }
25417
26116
  if (value2.sessionCacheUsage !== void 0) {
@@ -25482,19 +26181,19 @@ function parseHostUsageRequest(value2) {
25482
26181
  if (typeof value2.requestId !== "string" || value2.requestId.length === 0) {
25483
26182
  throw new Error("Harness Usage request 'requestId' must be a non-empty string");
25484
26183
  }
25485
- for (const field of ["model", "provider"]) {
25486
- const candidate = value2[field];
26184
+ for (const field2 of ["model", "provider"]) {
26185
+ const candidate = value2[field2];
25487
26186
  if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
25488
- throw new Error(`Harness Usage request '${field}' must be a non-empty string`);
26187
+ throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
25489
26188
  }
25490
26189
  }
25491
26190
  if (value2.historical !== void 0 && typeof value2.historical !== "boolean") {
25492
26191
  throw new Error("Harness Usage request 'historical' must be a boolean");
25493
26192
  }
25494
- for (const field of requestTokenFields) {
25495
- const candidate = value2[field];
26193
+ for (const field2 of requestTokenFields) {
26194
+ const candidate = value2[field2];
25496
26195
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
25497
- throw new Error(`Harness Usage request '${field}' must be a non-negative safe integer`);
26196
+ throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
25498
26197
  }
25499
26198
  }
25500
26199
  if (value2.inputTokens === void 0 || value2.outputTokens === void 0) {
@@ -25666,15 +26365,15 @@ var storedThreadMetadataV1Schema = external_exports.object({
25666
26365
  hostThreadId: storedHostThreadIdSchema,
25667
26366
  ...storedThreadMetadataFieldsShape
25668
26367
  }).passthrough();
25669
- function refineThreadRecord(record4, context) {
25670
- if (record4.state === "ready" && !record4.nativeSessionRef) {
26368
+ function refineThreadRecord(record5, context) {
26369
+ if (record5.state === "ready" && !record5.nativeSessionRef) {
25671
26370
  context.addIssue({
25672
26371
  code: "custom",
25673
26372
  path: ["nativeSessionRef"],
25674
26373
  message: "Ready Thread must have a Native Session Ref"
25675
26374
  });
25676
26375
  }
25677
- if (record4.nativeSessionRef && record4.nativeSessionRef.harnessId !== record4.harnessId) {
26376
+ if (record5.nativeSessionRef && record5.nativeSessionRef.harnessId !== record5.harnessId) {
25678
26377
  context.addIssue({
25679
26378
  code: "custom",
25680
26379
  path: ["nativeSessionRef", "harnessId"],
@@ -25683,7 +26382,7 @@ function refineThreadRecord(record4, context) {
25683
26382
  }
25684
26383
  const hostTurnIds = /* @__PURE__ */ new Set();
25685
26384
  const nativeTurnKeys = /* @__PURE__ */ new Set();
25686
- for (const [index, mapping] of record4.turnMappings.entries()) {
26385
+ for (const [index, mapping] of record5.turnMappings.entries()) {
25687
26386
  if (hostTurnIds.has(mapping.hostTurnId)) {
25688
26387
  context.addIssue({
25689
26388
  code: "custom",
@@ -25707,14 +26406,14 @@ function refineThreadRecord(record4, context) {
25707
26406
  ]) {
25708
26407
  if (!ref)
25709
26408
  continue;
25710
- if (ref.harnessId !== record4.harnessId) {
26409
+ if (ref.harnessId !== record5.harnessId) {
25711
26410
  context.addIssue({
25712
26411
  code: "custom",
25713
26412
  path: ["turnMappings", index, name, "harnessId"],
25714
26413
  message: "Turn Ref Harness must match the Thread Harness"
25715
26414
  });
25716
26415
  }
25717
- if (record4.nativeSessionRef && ref.nativeSessionId !== record4.nativeSessionRef.nativeSessionId) {
26416
+ if (record5.nativeSessionRef && ref.nativeSessionId !== record5.nativeSessionRef.nativeSessionId) {
25718
26417
  context.addIssue({
25719
26418
  code: "custom",
25720
26419
  path: ["turnMappings", index, name, "nativeSessionId"],
@@ -25746,7 +26445,7 @@ var storedDelegationRecordV1Schema = external_exports.object({
25746
26445
  taskDigest: external_exports.string().regex(/^[a-f0-9]{64}$/u),
25747
26446
  createdAt: isoDateSchema,
25748
26447
  updatedAt: isoDateSchema
25749
- }).strict().refine((record4) => record4.parentHostThreadId !== record4.childHostThreadId, {
26448
+ }).strict().refine((record5) => record5.parentHostThreadId !== record5.childHostThreadId, {
25750
26449
  path: ["childHostThreadId"],
25751
26450
  message: "Delegation child Thread must differ from its parent"
25752
26451
  });
@@ -25886,8 +26585,8 @@ var MappingStoreError = class extends Error {
25886
26585
  this.name = "MappingStoreError";
25887
26586
  }
25888
26587
  };
25889
- function cloneRecord(record4) {
25890
- return JSON.parse(JSON.stringify(record4));
26588
+ function cloneRecord(record5) {
26589
+ return JSON.parse(JSON.stringify(record5));
25891
26590
  }
25892
26591
  function nativeSessionKey(ref) {
25893
26592
  return `${ref.harnessId}\0${ref.nativeSessionId}`;
@@ -25930,22 +26629,22 @@ function withoutUnparsedUrlCredentials(value2) {
25930
26629
  const kept = keepUser && !userInfo.includes(":") ? `${userInfo}@` : "";
25931
26630
  return value2.slice(0, authorityStart) + kept + value2.slice(authorityStart + at + 1);
25932
26631
  }
25933
- function threadMetadataOf(record4) {
25934
- const fields = Object.fromEntries(THREAD_METADATA_FIELDS.filter((name) => record4[name] !== void 0).map((name) => [
26632
+ function threadMetadataOf(record5) {
26633
+ const fields = Object.fromEntries(THREAD_METADATA_FIELDS.filter((name) => record5[name] !== void 0).map((name) => [
25935
26634
  name,
25936
- record4[name]
26635
+ record5[name]
25937
26636
  ]));
25938
26637
  if (Object.keys(fields).length === 0)
25939
26638
  return null;
25940
- return { formatVersion: 1, hostThreadId: record4.hostThreadId, ...fields };
26639
+ return { formatVersion: 1, hostThreadId: record5.hostThreadId, ...fields };
25941
26640
  }
25942
- function withoutThreadMetadata(record4) {
25943
- const { projectId, daybreakEnabled, gitInfo, ...core } = record4;
26641
+ function withoutThreadMetadata(record5) {
26642
+ const { projectId, daybreakEnabled, gitInfo, ...core } = record5;
25944
26643
  void [projectId, daybreakEnabled, gitInfo];
25945
26644
  return core;
25946
26645
  }
25947
- function withThreadMetadata(record4, metadata) {
25948
- const core = withoutThreadMetadata(record4);
26646
+ function withThreadMetadata(record5, metadata) {
26647
+ const core = withoutThreadMetadata(record5);
25949
26648
  for (const name of THREAD_METADATA_FIELDS) {
25950
26649
  if (metadata[name] !== void 0)
25951
26650
  Object.assign(core, { [name]: metadata[name] });
@@ -26012,10 +26711,15 @@ function processIdentity(pid) {
26012
26711
  }
26013
26712
  const query = [
26014
26713
  "$ErrorActionPreference = 'Stop'",
26015
- `$process = Get-Process -Id ${pid}`,
26016
- "$process | Select-Object Path, StartTime | ConvertTo-Json -Compress"
26714
+ `$process = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${pid}'`,
26715
+ "if ($null -ne $process) { [pscustomobject]@{ Path = $process.ExecutablePath; StartTime = $(if ($null -ne $process.CreationDate) { $process.CreationDate.ToUniversalTime().ToString('o', [Globalization.CultureInfo]::InvariantCulture) } else { $null }) } | ConvertTo-Json -Compress }"
26017
26716
  ].join("; ");
26018
- const result = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", query], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }).trim();
26717
+ const result = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", query], {
26718
+ encoding: "utf8",
26719
+ stdio: ["ignore", "pipe", "ignore"],
26720
+ windowsHide: true,
26721
+ timeout: 5e3
26722
+ }).trim();
26019
26723
  if (!result)
26020
26724
  return { executablePath: null, startedAt: null };
26021
26725
  const parsed2 = JSON.parse(result);
@@ -26125,13 +26829,13 @@ var MappingStore = class {
26125
26829
  for (const name of names) {
26126
26830
  const primary = path18.join(this.#threadsDirectory, name);
26127
26831
  const backup = path18.join(this.#backupsDirectory, name);
26128
- let record4 = null;
26832
+ let record5 = null;
26129
26833
  try {
26130
- record4 = await this.#readRecord(primary, name);
26834
+ record5 = await this.#readRecord(primary, name);
26131
26835
  } catch (primaryError) {
26132
26836
  try {
26133
- record4 = await this.#readRecord(backup, name);
26134
- await this.#replaceFile(primary, record4, false);
26837
+ record5 = await this.#readRecord(backup, name);
26838
+ await this.#replaceFile(primary, record5, false);
26135
26839
  } catch (backupError) {
26136
26840
  const quarantine = path18.join(this.#quarantineDirectory, `${name}.${this.#now().getTime()}.invalid`);
26137
26841
  await rename10(primary, quarantine).catch(() => void 0);
@@ -26140,20 +26844,20 @@ var MappingStore = class {
26140
26844
  continue;
26141
26845
  }
26142
26846
  }
26143
- if (record4.state === "creating" && !record4.nativeSessionRef) {
26847
+ if (record5.state === "creating" && !record5.nativeSessionRef) {
26144
26848
  await rm10(primary, { force: true });
26145
26849
  await rm10(backup, { force: true });
26146
- await rm10(this.#metadataPath(record4.hostThreadId), { force: true });
26850
+ await rm10(this.#metadataPath(record5.hostThreadId), { force: true });
26147
26851
  continue;
26148
26852
  }
26149
- const metadata = await this.#readMetadata(record4.hostThreadId);
26853
+ const metadata = await this.#readMetadata(record5.hostThreadId);
26150
26854
  if (metadata) {
26151
- record4 = withThreadMetadata(record4, metadata);
26152
- } else if (threadMetadataOf(record4)) {
26153
- await this.#writeMetadataFile(record4.hostThreadId, threadMetadataOf(record4));
26154
- await this.#replaceFile(primary, record4, false);
26855
+ record5 = withThreadMetadata(record5, metadata);
26856
+ } else if (threadMetadataOf(record5)) {
26857
+ await this.#writeMetadataFile(record5.hostThreadId, threadMetadataOf(record5));
26858
+ await this.#replaceFile(primary, record5, false);
26155
26859
  }
26156
- this.#records.set(record4.hostThreadId, record4);
26860
+ this.#records.set(record5.hostThreadId, record5);
26157
26861
  }
26158
26862
  await Promise.all((await readdir4(this.#metadataDirectory)).filter((name) => name.endsWith(".json") && !this.#records.has(name.slice(0, -5))).map((name) => rm10(path18.join(this.#metadataDirectory, name), { force: true })));
26159
26863
  const delegationNames = (await readdir4(this.#delegationsDirectory)).filter((name) => name.endsWith(".json"));
@@ -26190,8 +26894,8 @@ var MappingStore = class {
26190
26894
  }
26191
26895
  async getThread(hostThreadId) {
26192
26896
  this.#requireInitialized();
26193
- const record4 = this.#records.get(hostThreadId);
26194
- return record4 ? cloneRecord(record4) : null;
26897
+ const record5 = this.#records.get(hostThreadId);
26898
+ return record5 ? cloneRecord(record5) : null;
26195
26899
  }
26196
26900
  async listThreads() {
26197
26901
  this.#requireInitialized();
@@ -26204,8 +26908,8 @@ var MappingStore = class {
26204
26908
  }
26205
26909
  async getDelegation(delegationId) {
26206
26910
  this.#requireInitialized();
26207
- const record4 = this.#delegations.get(delegationId);
26208
- return record4 ? cloneRecord(record4) : null;
26911
+ const record5 = this.#delegations.get(delegationId);
26912
+ return record5 ? cloneRecord(record5) : null;
26209
26913
  }
26210
26914
  async getDelegationByChild(childHostThreadId) {
26211
26915
  this.#requireInitialized();
@@ -26219,12 +26923,12 @@ var MappingStore = class {
26219
26923
  }
26220
26924
  async listDelegations(parentHostThreadId) {
26221
26925
  this.#requireInitialized();
26222
- return [...this.#delegations.values()].filter((record4) => !parentHostThreadId || record4.parentHostThreadId === parentHostThreadId).map(cloneRecord);
26926
+ return [...this.#delegations.values()].filter((record5) => !parentHostThreadId || record5.parentHostThreadId === parentHostThreadId).map(cloneRecord);
26223
26927
  }
26224
26928
  async findRecentDelegation(input) {
26225
26929
  this.#requireInitialized();
26226
26930
  const threshold = input.since.getTime();
26227
- const found = [...this.#delegations.values()].filter((record4) => record4.parentHostThreadId === input.parentHostThreadId && record4.targetHarnessId === input.targetHarnessId && record4.taskDigest === input.taskDigest && Date.parse(record4.createdAt) >= threshold).toSorted((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt))[0];
26931
+ const found = [...this.#delegations.values()].filter((record5) => record5.parentHostThreadId === input.parentHostThreadId && record5.targetHarnessId === input.targetHarnessId && record5.taskDigest === input.taskDigest && Date.parse(record5.createdAt) >= threshold).toSorted((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt))[0];
26228
26932
  return found ? cloneRecord(found) : null;
26229
26933
  }
26230
26934
  async createDelegation(input) {
@@ -26239,7 +26943,7 @@ var MappingStore = class {
26239
26943
  throw new MappingStoreError("DUPLICATE_CREATE_REQUEST", "Delegation Request ID already exists");
26240
26944
  }
26241
26945
  const timestamp = this.#now().toISOString();
26242
- const record4 = storedDelegationRecordV1Schema.parse({
26946
+ const record5 = storedDelegationRecordV1Schema.parse({
26243
26947
  formatVersion: 1,
26244
26948
  revision: 1,
26245
26949
  ...input,
@@ -26247,10 +26951,10 @@ var MappingStore = class {
26247
26951
  createdAt: timestamp,
26248
26952
  updatedAt: timestamp
26249
26953
  });
26250
- await this.#replaceDelegationFile(record4);
26251
- this.#delegations.set(record4.delegationId, record4);
26954
+ await this.#replaceDelegationFile(record5);
26955
+ this.#delegations.set(record5.delegationId, record5);
26252
26956
  this.#rebuildIndexes();
26253
- return cloneRecord(record4);
26957
+ return cloneRecord(record5);
26254
26958
  }
26255
26959
  async setDelegationStatus(delegationId, status2) {
26256
26960
  this.#requireInitialized();
@@ -26301,7 +27005,7 @@ var MappingStore = class {
26301
27005
  throw new MappingStoreError("DUPLICATE_THREAD_ID", "Host Thread ID already exists");
26302
27006
  }
26303
27007
  const timestamp = this.#now().toISOString();
26304
- const record4 = storedThreadRecordV1Schema.parse({
27008
+ const record5 = storedThreadRecordV1Schema.parse({
26305
27009
  formatVersion: 1,
26306
27010
  revision: 1,
26307
27011
  hostThreadId: input.hostThreadId,
@@ -26321,8 +27025,8 @@ var MappingStore = class {
26321
27025
  createdAt: timestamp,
26322
27026
  updatedAt: timestamp
26323
27027
  });
26324
- await this.#writeNew(record4);
26325
- result = cloneRecord(record4);
27028
+ await this.#writeNew(record5);
27029
+ result = cloneRecord(record5);
26326
27030
  });
26327
27031
  if (!result)
26328
27032
  throw new MappingStoreError("IO_ERROR", "Provisional create produced no result");
@@ -26500,8 +27204,8 @@ var MappingStore = class {
26500
27204
  async removeProvisional(hostThreadId) {
26501
27205
  this.#requireInitialized();
26502
27206
  await this.#enqueue(async () => {
26503
- const record4 = this.#records.get(hostThreadId);
26504
- if (record4?.state === "ready") {
27207
+ const record5 = this.#records.get(hostThreadId);
27208
+ if (record5?.state === "ready") {
26505
27209
  throw new MappingStoreError("MAPPING_CONFLICT", "Ready Thread cannot be removed as provisional");
26506
27210
  }
26507
27211
  await this.#remove(hostThreadId);
@@ -26539,13 +27243,17 @@ var MappingStore = class {
26539
27243
  await this.#enqueue(() => this.#remove(hostThreadId));
26540
27244
  }
26541
27245
  async #remove(hostThreadId) {
26542
- if (!this.#records.has(hostThreadId))
27246
+ const current = this.#records.get(hostThreadId);
27247
+ if (!current)
26543
27248
  return;
26544
- await Promise.all([
26545
- rm10(this.#recordPath(hostThreadId), { force: true }),
26546
- rm10(this.#backupPath(hostThreadId), { force: true }),
26547
- rm10(this.#metadataPath(hostThreadId), { force: true })
26548
- ]);
27249
+ await rm10(this.#recordPath(hostThreadId), { force: true });
27250
+ try {
27251
+ await rm10(this.#backupPath(hostThreadId), { force: true });
27252
+ await rm10(this.#metadataPath(hostThreadId), { force: true });
27253
+ } catch (error51) {
27254
+ await this.#replaceFile(this.#recordPath(hostThreadId), current, false);
27255
+ throw error51;
27256
+ }
26549
27257
  this.#records.delete(hostThreadId);
26550
27258
  this.#rebuildIndexes();
26551
27259
  }
@@ -26628,25 +27336,25 @@ var MappingStore = class {
26628
27336
  }
26629
27337
  return merged;
26630
27338
  }
26631
- async #writeNew(record4) {
26632
- this.#validateGlobal(record4, null);
26633
- await this.#replaceFile(this.#recordPath(record4.hostThreadId), record4, false);
26634
- this.#records.set(record4.hostThreadId, record4);
27339
+ async #writeNew(record5) {
27340
+ this.#validateGlobal(record5, null);
27341
+ await this.#replaceFile(this.#recordPath(record5.hostThreadId), record5, false);
27342
+ this.#records.set(record5.hostThreadId, record5);
26635
27343
  this.#rebuildIndexes();
26636
27344
  }
26637
- async #replaceFile(target, record4, preserveBackup) {
27345
+ async #replaceFile(target, record5, preserveBackup) {
26638
27346
  const temp = `${target}.tmp-${randomUUID9()}`;
26639
27347
  let handle = null;
26640
27348
  try {
26641
- await this.#beforeReplace?.(cloneRecord(record4));
27349
+ await this.#beforeReplace?.(cloneRecord(record5));
26642
27350
  handle = await open7(temp, "wx", constants3.S_IRUSR | constants3.S_IWUSR);
26643
- await handle.writeFile(`${JSON.stringify(withoutThreadMetadata(record4), null, 2)}
27351
+ await handle.writeFile(`${JSON.stringify(withoutThreadMetadata(record5), null, 2)}
26644
27352
  `, "utf8");
26645
27353
  await handle.sync();
26646
27354
  await handle.close();
26647
27355
  handle = null;
26648
27356
  if (preserveBackup && await exists(target)) {
26649
- await copyFile3(target, this.#backupPath(record4.hostThreadId));
27357
+ await copyFile3(target, this.#backupPath(record5.hostThreadId));
26650
27358
  }
26651
27359
  await rename10(temp, target);
26652
27360
  } catch (error51) {
@@ -26707,13 +27415,13 @@ var MappingStore = class {
26707
27415
  return null;
26708
27416
  }
26709
27417
  }
26710
- async #replaceDelegationFile(record4) {
26711
- const target = this.#delegationPath(record4.delegationId);
27418
+ async #replaceDelegationFile(record5) {
27419
+ const target = this.#delegationPath(record5.delegationId);
26712
27420
  const temp = `${target}.tmp-${randomUUID9()}`;
26713
27421
  let handle = null;
26714
27422
  try {
26715
27423
  handle = await open7(temp, "wx", constants3.S_IRUSR | constants3.S_IWUSR);
26716
- await handle.writeFile(`${JSON.stringify(record4, null, 2)}
27424
+ await handle.writeFile(`${JSON.stringify(record5, null, 2)}
26717
27425
  `, "utf8");
26718
27426
  await handle.sync();
26719
27427
  await handle.close();
@@ -26797,18 +27505,18 @@ var MappingStore = class {
26797
27505
  });
26798
27506
  }
26799
27507
  }
26800
- #validateGlobal(record4, replacing) {
26801
- const duplicateCreate = this.#createRequests.get(record4.createRequestId);
27508
+ #validateGlobal(record5, replacing) {
27509
+ const duplicateCreate = this.#createRequests.get(record5.createRequestId);
26802
27510
  if (duplicateCreate && duplicateCreate !== replacing) {
26803
27511
  throw new MappingStoreError("DUPLICATE_CREATE_REQUEST", "Create request is already stored");
26804
27512
  }
26805
- if (record4.nativeSessionRef && !record4.subagent) {
26806
- const duplicateSession = this.#nativeSessions.get(nativeSessionKey(record4.nativeSessionRef));
27513
+ if (record5.nativeSessionRef && !record5.subagent) {
27514
+ const duplicateSession = this.#nativeSessions.get(nativeSessionKey(record5.nativeSessionRef));
26807
27515
  if (duplicateSession && duplicateSession !== replacing) {
26808
27516
  throw new MappingStoreError("DUPLICATE_NATIVE_SESSION", "Native Session is already mapped");
26809
27517
  }
26810
27518
  }
26811
- for (const mapping of record4.turnMappings) {
27519
+ for (const mapping of record5.turnMappings) {
26812
27520
  const duplicateHostTurn = this.#hostTurns.get(mapping.hostTurnId);
26813
27521
  if (duplicateHostTurn && duplicateHostTurn !== replacing) {
26814
27522
  throw new MappingStoreError("MAPPING_CONFLICT", "Host Turn is already mapped");
@@ -26838,14 +27546,14 @@ var MappingStore = class {
26838
27546
  this.#delegationRequests.set(delegation.requestId, delegation.delegationId);
26839
27547
  }
26840
27548
  }
26841
- for (const record4 of this.#records.values()) {
26842
- this.#validateGlobal(record4, record4.hostThreadId);
26843
- this.#createRequests.set(record4.createRequestId, record4.hostThreadId);
26844
- if (record4.nativeSessionRef && !record4.subagent) {
26845
- this.#nativeSessions.set(nativeSessionKey(record4.nativeSessionRef), record4.hostThreadId);
27549
+ for (const record5 of this.#records.values()) {
27550
+ this.#validateGlobal(record5, record5.hostThreadId);
27551
+ this.#createRequests.set(record5.createRequestId, record5.hostThreadId);
27552
+ if (record5.nativeSessionRef && !record5.subagent) {
27553
+ this.#nativeSessions.set(nativeSessionKey(record5.nativeSessionRef), record5.hostThreadId);
26846
27554
  }
26847
- for (const mapping of record4.turnMappings) {
26848
- this.#hostTurns.set(mapping.hostTurnId, record4.hostThreadId);
27555
+ for (const mapping of record5.turnMappings) {
27556
+ this.#hostTurns.set(mapping.hostTurnId, record5.hostThreadId);
26849
27557
  this.#nativeTurns.set(nativeTurnKey(mapping), mapping.hostTurnId);
26850
27558
  }
26851
27559
  }
@@ -26894,17 +27602,17 @@ var ELLIPSIS = "…";
26894
27602
  function isRecord7(value2) {
26895
27603
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
26896
27604
  }
26897
- function boundedText(value2, field, maxLength) {
27605
+ function boundedText(value2, field2, maxLength) {
26898
27606
  const text2 = value2.trim();
26899
27607
  if (text2.length === 0 || text2.length > maxLength) {
26900
- throw new Error(`Host Approval ${field} must contain 1 to ${maxLength} characters`);
27608
+ throw new Error(`Host Approval ${field2} must contain 1 to ${maxLength} characters`);
26901
27609
  }
26902
27610
  return text2;
26903
27611
  }
26904
- function clampedText(value2, field, maxLength) {
27612
+ function clampedText(value2, field2, maxLength) {
26905
27613
  const text2 = value2.trim();
26906
27614
  if (text2.length === 0) {
26907
- throw new Error(`Host Approval ${field} must contain at least 1 character`);
27615
+ throw new Error(`Host Approval ${field2} must contain at least 1 character`);
26908
27616
  }
26909
27617
  const characters = [...text2];
26910
27618
  if (characters.length <= maxLength)
@@ -28129,9 +28837,9 @@ function nestedString(value2, keys, preserveText = false) {
28129
28837
  if (!isRecord10(value2))
28130
28838
  return void 0;
28131
28839
  for (const key of keys) {
28132
- const field = value2[key];
28133
- if (typeof field === "string" && (preserveText || field.trim().length > 0))
28134
- return preserveText ? field : field.trim();
28840
+ const field2 = value2[key];
28841
+ if (typeof field2 === "string" && (preserveText || field2.trim().length > 0))
28842
+ return preserveText ? field2 : field2.trim();
28135
28843
  }
28136
28844
  for (const wrapper of ["input", "arguments", "params"]) {
28137
28845
  const nested = nestedString(value2[wrapper], keys, preserveText);
@@ -28286,16 +28994,16 @@ function planFromTodoValue(value2) {
28286
28994
  return fromText;
28287
28995
  }
28288
28996
  }
28289
- const record4 = unwrapToolRecord(value2);
28290
- if (!record4)
28997
+ const record5 = unwrapToolRecord(value2);
28998
+ if (!record5)
28291
28999
  return planFromChecklistText(typeof value2 === "string" ? value2 : null);
28292
- if (isRecord10(record4.TodosUpdated)) {
28293
- const nested = planFromTodoValue(record4.TodosUpdated);
29000
+ if (isRecord10(record5.TodosUpdated)) {
29001
+ const nested = planFromTodoValue(record5.TodosUpdated);
28294
29002
  if (nested)
28295
29003
  return nested;
28296
29004
  }
28297
- const explanation = nestedString(record4, ["explanation", "message", "summary"]) ?? null;
28298
- const list = coerceTodoList(record4.todos ?? record4.items ?? record4.plan ?? record4.tasks ?? record4.entries);
29005
+ const explanation = nestedString(record5, ["explanation", "message", "summary"]) ?? null;
29006
+ const list = coerceTodoList(record5.todos ?? record5.items ?? record5.plan ?? record5.tasks ?? record5.entries);
28299
29007
  if (!list || list.length === 0)
28300
29008
  return planFromChecklistText(explanation);
28301
29009
  const plan = [];
@@ -28325,8 +29033,8 @@ function coerceTodoList(value2) {
28325
29033
  const parsed2 = JSON.parse(trimmed);
28326
29034
  if (Array.isArray(parsed2))
28327
29035
  return parsed2;
28328
- const record4 = unwrapToolRecord(parsed2);
28329
- return record4 ? coerceTodoList(record4.todos ?? record4.items ?? record4.plan ?? record4.tasks ?? record4.entries) : null;
29036
+ const record5 = unwrapToolRecord(parsed2);
29037
+ return record5 ? coerceTodoList(record5.todos ?? record5.items ?? record5.plan ?? record5.tasks ?? record5.entries) : null;
28330
29038
  } catch {
28331
29039
  return planFromChecklistText(trimmed)?.plan.map(({ step, status: status2 }) => ({ content: step, status: status2 })) ?? null;
28332
29040
  }
@@ -30103,10 +30811,12 @@ function decodeCreateRoute(request) {
30103
30811
  return null;
30104
30812
  const pluginRoute = decodeHarnessPluginRoute(request.params.model);
30105
30813
  if (pluginRoute) {
30814
+ const { prewarm, ...selection } = pluginRoute;
30106
30815
  return {
30107
30816
  harnessId: pluginRoute.harnessId,
30108
30817
  routeMode: "native",
30109
- transportModelId: request.params.model,
30818
+ transportModelId: prewarm ? encodeHarnessPluginRoute(selection) : request.params.model,
30819
+ ...prewarm ? { prewarm } : {},
30110
30820
  ...pluginRoute.model ? { model: pluginRoute.model } : {},
30111
30821
  ...pluginRoute.thinkingOptionId ? { thinkingOptionId: pluginRoute.thinkingOptionId } : {},
30112
30822
  ...pluginRoute.permissionModeId ? { permissionModeId: pluginRoute.permissionModeId } : {}
@@ -30423,7 +31133,7 @@ import { open as open8, realpath as realpath4 } from "node:fs/promises";
30423
31133
  import path21 from "node:path";
30424
31134
  var MAX_METADATA_BYTES = 1024 * 1024;
30425
31135
  var REFERENCE_READ_TIMEOUT_MS = 2e3;
30426
- var record3 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
31136
+ var record4 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
30427
31137
  async function nativeThreadSupportsReferences(input) {
30428
31138
  try {
30429
31139
  let timer;
@@ -30433,8 +31143,8 @@ async function nativeThreadSupportsReferences(input) {
30433
31143
  timer = setTimeout(() => resolve(null), REFERENCE_READ_TIMEOUT_MS);
30434
31144
  })
30435
31145
  ]).finally(() => clearTimeout(timer));
30436
- const result = record3(response) && record3(response.result) ? response.result : null;
30437
- const thread = result && record3(result.thread) ? result.thread : null;
31146
+ const result = record4(response) && record4(response.result) ? response.result : null;
31147
+ const thread = result && record4(result.thread) ? result.thread : null;
30438
31148
  if (thread?.id !== input.threadId || typeof thread.path !== "string") return false;
30439
31149
  const rollout = await realpath4(thread.path);
30440
31150
  let allowed = false;
@@ -30456,13 +31166,13 @@ async function nativeThreadSupportsReferences(input) {
30456
31166
  const newline2 = bytes.subarray(0, bytesRead).indexOf(10);
30457
31167
  if (newline2 < 0) return false;
30458
31168
  const line = JSON.parse(bytes.subarray(0, newline2).toString("utf8"));
30459
- if (!record3(line) || line.type !== "session_meta" || !record3(line.payload)) return false;
31169
+ if (!record4(line) || line.type !== "session_meta" || !record4(line.payload)) return false;
30460
31170
  const metadata = line.payload;
30461
31171
  if (metadata.id !== input.threadId || !Array.isArray(metadata.dynamic_tools)) return false;
30462
31172
  return metadata.dynamic_tools.some((tool) => {
30463
- if (!record3(tool)) return false;
31173
+ if (!record4(tool)) return false;
30464
31174
  if (tool.type === "namespace") {
30465
- return tool.name === "codex_app" && Array.isArray(tool.tools) && tool.tools.some((item) => record3(item) && item.name === "read_thread");
31175
+ return tool.name === "codex_app" && Array.isArray(tool.tools) && tool.tools.some((item) => record4(item) && item.name === "read_thread");
30466
31176
  }
30467
31177
  return tool.name === "read_thread";
30468
31178
  });
@@ -30574,7 +31284,7 @@ var HarnessAccountInspectionCache = class {
30574
31284
  };
30575
31285
 
30576
31286
  // packages/host-runtime/src/app-server-host.ts
30577
- import { createHash as createHash9, randomUUID as randomUUID16 } from "node:crypto";
31287
+ import { createHash as createHash9, randomUUID as randomUUID17 } from "node:crypto";
30578
31288
  import os8 from "node:os";
30579
31289
  import path26 from "node:path";
30580
31290
 
@@ -30601,21 +31311,21 @@ function subagentMaterializer(store, parent, previousParent) {
30601
31311
  const legacyRecords = () => legacy ??= store.listThreads().then((records) => {
30602
31312
  const byRequest = /* @__PURE__ */ new Map();
30603
31313
  const children = /* @__PURE__ */ new Map();
30604
- for (const record4 of records) {
30605
- if (!record4.subagent || record4.harnessId !== parent.harnessId || !record4.nativeSessionRef)
31314
+ for (const record5 of records) {
31315
+ if (!record5.subagent || record5.harnessId !== parent.harnessId || !record5.nativeSessionRef)
30606
31316
  continue;
30607
31317
  const owner = {
30608
- hostThreadId: record4.subagent.parentHostThreadId,
30609
- harnessId: record4.harnessId
31318
+ hostThreadId: record5.subagent.parentHostThreadId,
31319
+ harnessId: record5.harnessId
30610
31320
  };
30611
31321
  const key = childCreateRequest(
30612
31322
  owner,
30613
- record4.nativeSessionRef,
30614
- record4.subagent.nativeSubagentId
31323
+ record5.nativeSessionRef,
31324
+ record5.subagent.nativeSubagentId
30615
31325
  );
30616
- if (!byRequest.has(key) || record4.state === "ready") byRequest.set(key, record4);
31326
+ if (!byRequest.has(key) || record5.state === "ready") byRequest.set(key, record5);
30617
31327
  const siblings = children.get(owner.hostThreadId) ?? [];
30618
- siblings.push(record4);
31328
+ siblings.push(record5);
30619
31329
  children.set(owner.hostThreadId, siblings);
30620
31330
  }
30621
31331
  return { byRequest, children };
@@ -30685,11 +31395,11 @@ function subagentMaterializer(store, parent, previousParent) {
30685
31395
  async function materializeExternalSubagent(store, parent, child) {
30686
31396
  return subagentMaterializer(store, parent)(child);
30687
31397
  }
30688
- async function projectExternalSnapshot(store, record4, snapshot2, previousParent) {
30689
- const materialize = subagentMaterializer(store, record4, previousParent);
31398
+ async function projectExternalSnapshot(store, record5, snapshot2, previousParent) {
31399
+ const materialize = subagentMaterializer(store, record5, previousParent);
30690
31400
  const turns = [];
30691
31401
  for (const [index, turn] of snapshot2.turns.entries()) {
30692
- const mapping = record4.turnMappings[index];
31402
+ const mapping = record5.turnMappings[index];
30693
31403
  if (!mapping) throw new Error("External Snapshot mapping is incomplete");
30694
31404
  const items = await Promise.all(
30695
31405
  turn.items.map(async (entry) => {
@@ -30705,9 +31415,9 @@ async function projectExternalSnapshot(store, record4, snapshot2, previousParent
30705
31415
  );
30706
31416
  turns.push(
30707
31417
  projectHistoricalTurn({
30708
- threadId: record4.hostThreadId,
31418
+ threadId: record5.hostThreadId,
30709
31419
  turnId: mapping.hostTurnId,
30710
- cwd: record4.cwd,
31420
+ cwd: record5.cwd,
30711
31421
  snapshot: { ...turn, items }
30712
31422
  })
30713
31423
  );
@@ -30821,11 +31531,11 @@ var ExternalThreadRepository = class {
30821
31531
  removeThread(hostThreadId) {
30822
31532
  return this.store.removeThread(hostThreadId);
30823
31533
  }
30824
- async persistTurn(record4, hostTurnId, nativeTurnRef, nativeCheckpointRef) {
30825
- if (record4.state !== "ready" || !record4.nativeSessionRef || nativeTurnRef.harnessId !== record4.harnessId || nativeTurnRef.nativeSessionId !== record4.nativeSessionRef.nativeSessionId || nativeCheckpointRef && (nativeCheckpointRef.harnessId !== record4.harnessId || nativeCheckpointRef.nativeSessionId !== record4.nativeSessionRef.nativeSessionId)) {
31534
+ async persistTurn(record5, hostTurnId, nativeTurnRef, nativeCheckpointRef) {
31535
+ if (record5.state !== "ready" || !record5.nativeSessionRef || nativeTurnRef.harnessId !== record5.harnessId || nativeTurnRef.nativeSessionId !== record5.nativeSessionRef.nativeSessionId || nativeCheckpointRef && (nativeCheckpointRef.harnessId !== record5.harnessId || nativeCheckpointRef.nativeSessionId !== record5.nativeSessionRef.nativeSessionId)) {
30826
31536
  throw new Error("Live Turn identity does not belong to the stored Thread");
30827
31537
  }
30828
- return this.store.upsertTurnMappings(record4.hostThreadId, [
31538
+ return this.store.upsertTurnMappings(record5.hostThreadId, [
30829
31539
  {
30830
31540
  hostTurnId,
30831
31541
  nativeTurnRef,
@@ -30833,12 +31543,12 @@ var ExternalThreadRepository = class {
30833
31543
  }
30834
31544
  ]);
30835
31545
  }
30836
- async commitDerivedSnapshot(record4, nativeSessionRef, snapshot2) {
30837
- if (record4.state !== "creating" || record4.turnMappings.length !== 0) {
31546
+ async commitDerivedSnapshot(record5, nativeSessionRef, snapshot2) {
31547
+ if (record5.state !== "creating" || record5.turnMappings.length !== 0) {
30838
31548
  throw new Error("Derived Thread must be provisional before Snapshot commit");
30839
31549
  }
30840
31550
  const mappings = snapshot2.turns.map((turn) => {
30841
- if (turn.nativeTurnRef.harnessId !== record4.harnessId || turn.nativeTurnRef.nativeSessionId !== nativeSessionRef.nativeSessionId || turn.checkpoint && (turn.checkpoint.harnessId !== record4.harnessId || turn.checkpoint.nativeSessionId !== nativeSessionRef.nativeSessionId)) {
31551
+ if (turn.nativeTurnRef.harnessId !== record5.harnessId || turn.nativeTurnRef.nativeSessionId !== nativeSessionRef.nativeSessionId || turn.checkpoint && (turn.checkpoint.harnessId !== record5.harnessId || turn.checkpoint.nativeSessionId !== nativeSessionRef.nativeSessionId)) {
30842
31552
  throw new Error("Derived Snapshot identity does not belong to its Native Session");
30843
31553
  }
30844
31554
  return {
@@ -30848,7 +31558,7 @@ var ExternalThreadRepository = class {
30848
31558
  };
30849
31559
  });
30850
31560
  const nextRecord = await this.store.commitReady({
30851
- hostThreadId: record4.hostThreadId,
31561
+ hostThreadId: record5.hostThreadId,
30852
31562
  nativeSessionRef,
30853
31563
  turnMappings: mappings
30854
31564
  });
@@ -30929,8 +31639,8 @@ var ExternalThreadRepository = class {
30929
31639
  turns: await projectExternalSnapshot(this.store, nextRecord, snapshot2, current)
30930
31640
  };
30931
31641
  }
30932
- async sessionTreeId(record4) {
30933
- let current = record4;
31642
+ async sessionTreeId(record5) {
31643
+ let current = record5;
30934
31644
  const visited = /* @__PURE__ */ new Set();
30935
31645
  while (current.subagent || current.forkSource) {
30936
31646
  if (visited.has(current.hostThreadId))
@@ -30944,21 +31654,21 @@ var ExternalThreadRepository = class {
30944
31654
  }
30945
31655
  return current.hostThreadId;
30946
31656
  }
30947
- async alignSnapshot(record4, snapshot2) {
30948
- const nativeSessionRef = record4.nativeSessionRef;
30949
- if (record4.state === "creating" && !nativeSessionRef && snapshot2.turns.length === 0) {
30950
- return { record: record4, turns: [] };
31657
+ async alignSnapshot(record5, snapshot2) {
31658
+ const nativeSessionRef = record5.nativeSessionRef;
31659
+ if (record5.state === "creating" && !nativeSessionRef && snapshot2.turns.length === 0) {
31660
+ return { record: record5, turns: [] };
30951
31661
  }
30952
- if (!nativeSessionRef || record4.state !== "ready") {
31662
+ if (!nativeSessionRef || record5.state !== "ready") {
30953
31663
  throw new Error("External Thread has no committed Native Session identity");
30954
31664
  }
30955
31665
  for (const turn of snapshot2.turns) {
30956
- if (turn.nativeTurnRef.harnessId !== record4.harnessId || turn.nativeTurnRef.nativeSessionId !== nativeSessionRef.nativeSessionId || turn.checkpoint && (turn.checkpoint.harnessId !== record4.harnessId || turn.checkpoint.nativeSessionId !== nativeSessionRef.nativeSessionId)) {
31666
+ if (turn.nativeTurnRef.harnessId !== record5.harnessId || turn.nativeTurnRef.nativeSessionId !== nativeSessionRef.nativeSessionId || turn.checkpoint && (turn.checkpoint.harnessId !== record5.harnessId || turn.checkpoint.nativeSessionId !== nativeSessionRef.nativeSessionId)) {
30957
31667
  throw new Error("External Snapshot identity does not belong to the stored Thread");
30958
31668
  }
30959
31669
  }
30960
31670
  const mappingsByNative = new Map(
30961
- record4.turnMappings.map(
31671
+ record5.turnMappings.map(
30962
31672
  (mapping) => [nativeTurnKey2(mapping.nativeTurnRef), mapping]
30963
31673
  )
30964
31674
  );
@@ -30979,11 +31689,11 @@ var ExternalThreadRepository = class {
30979
31689
  };
30980
31690
  });
30981
31691
  const orderedMappings = aligned.map(({ mapping }) => mapping);
30982
- const mappingsChanged = orderedMappings.length !== record4.turnMappings.length || orderedMappings.some((mapping, index) => {
30983
- const persisted = record4.turnMappings[index];
31692
+ const mappingsChanged = orderedMappings.length !== record5.turnMappings.length || orderedMappings.some((mapping, index) => {
31693
+ const persisted = record5.turnMappings[index];
30984
31694
  return !persisted || !sameMapping(mapping, persisted);
30985
31695
  });
30986
- const nextRecord = mappingsChanged ? await this.store.reconcileTurnMappings(record4.hostThreadId, orderedMappings) : record4;
31696
+ const nextRecord = mappingsChanged ? await this.store.reconcileTurnMappings(record5.hostThreadId, orderedMappings) : record5;
30987
31697
  return {
30988
31698
  record: nextRecord,
30989
31699
  turns: await projectExternalSnapshot(this.store, nextRecord, snapshot2)
@@ -31004,10 +31714,10 @@ function createExternalThreadRecordInput(input) {
31004
31714
  ...input.subagent ? { subagent: input.subagent } : {}
31005
31715
  };
31006
31716
  }
31007
- function subagentThreadModelFields(record4) {
31008
- if (!record4.subagent) return {};
31717
+ function subagentThreadModelFields(record5) {
31718
+ if (!record5.subagent) return {};
31009
31719
  try {
31010
- const selection = decodeExternalTransportSelection(record4.harnessId, record4.transportModelId);
31720
+ const selection = decodeExternalTransportSelection(record5.harnessId, record5.transportModelId);
31011
31721
  if (!selection) return {};
31012
31722
  return {
31013
31723
  ...selection.model?.id ? { model: selection.model.id } : {},
@@ -31024,9 +31734,9 @@ function threadSectionFields(placement) {
31024
31734
  } : { section: null, sectionEnteredAt: null };
31025
31735
  }
31026
31736
  function externalThreadValue(input) {
31027
- const { record: record4 } = input;
31028
- const createdAt = Math.floor(Date.parse(record4.createdAt) / 1e3);
31029
- const updatedAt = Math.floor(Date.parse(record4.updatedAt) / 1e3);
31737
+ const { record: record5 } = input;
31738
+ const createdAt = Math.floor(Date.parse(record5.createdAt) / 1e3);
31739
+ const updatedAt = Math.floor(Date.parse(record5.updatedAt) / 1e3);
31030
31740
  const preview = input.turns.flatMap((turn) => Array.isArray(turn.items) ? turn.items : []).find(
31031
31741
  (item) => typeof item === "object" && item !== null && !Array.isArray(item) && item.type === "userMessage"
31032
31742
  );
@@ -31035,22 +31745,22 @@ function externalThreadValue(input) {
31035
31745
  (part) => typeof part === "object" && part !== null && !Array.isArray(part) && part.type === "text"
31036
31746
  ).map((part) => typeof part.text === "string" ? part.text : "").join("\n") : "";
31037
31747
  return {
31038
- id: record4.hostThreadId,
31748
+ id: record5.hostThreadId,
31039
31749
  sessionId: input.sessionId,
31040
31750
  path: null,
31041
- cwd: record4.cwd,
31042
- source: record4.subagent ? {
31751
+ cwd: record5.cwd,
31752
+ source: record5.subagent ? {
31043
31753
  subAgent: {
31044
31754
  thread_spawn: {
31045
- parent_thread_id: record4.subagent.parentHostThreadId,
31755
+ parent_thread_id: record5.subagent.parentHostThreadId,
31046
31756
  depth: 1,
31047
31757
  agent_path: null,
31048
- agent_nickname: record4.title || null,
31049
- agent_role: record4.subagent.role ?? null
31758
+ agent_nickname: record5.title || null,
31759
+ agent_role: record5.subagent.role ?? null
31050
31760
  }
31051
31761
  }
31052
31762
  } : "vscode",
31053
- threadSource: record4.subagent ? "subAgentThreadSpawn" : null,
31763
+ threadSource: record5.subagent ? "subAgentThreadSpawn" : null,
31054
31764
  modelProvider: "codexhost",
31055
31765
  cliVersion: "codexhost",
31056
31766
  createdAt,
@@ -31059,25 +31769,25 @@ function externalThreadValue(input) {
31059
31769
  status: input.loaded === false ? { type: "notLoaded" } : input.running ? { type: "active", activeFlags: [] } : { type: "idle" },
31060
31770
  turns: input.turns,
31061
31771
  preview: previewText,
31062
- name: record4.title || null,
31063
- gitInfo: record4.gitInfo ? {
31064
- branch: record4.gitInfo.branch ?? null,
31065
- originUrl: record4.gitInfo.originUrl ?? null,
31066
- sha: record4.gitInfo.sha ?? null
31772
+ name: record5.title || null,
31773
+ gitInfo: record5.gitInfo ? {
31774
+ branch: record5.gitInfo.branch ?? null,
31775
+ originUrl: record5.gitInfo.originUrl ?? null,
31776
+ sha: record5.gitInfo.sha ?? null
31067
31777
  } : null,
31068
- forkedFromId: record4.forkSource?.hostThreadId ?? null,
31069
- parentThreadId: record4.subagent?.parentHostThreadId ?? null,
31070
- ephemeral: record4.ephemeral,
31071
- canAcceptDirectInput: record4.subagent ? false : input.loaded === false ? null : true,
31072
- historyMode: record4.historyMode,
31073
- isPinned: record4.isPinned,
31074
- projectId: record4.projectId ?? null,
31075
- daybreakEnabled: record4.daybreakEnabled ?? null,
31778
+ forkedFromId: record5.forkSource?.hostThreadId ?? null,
31779
+ parentThreadId: record5.subagent?.parentHostThreadId ?? null,
31780
+ ephemeral: record5.ephemeral,
31781
+ canAcceptDirectInput: record5.subagent ? false : input.loaded === false ? null : true,
31782
+ historyMode: record5.historyMode,
31783
+ isPinned: record5.isPinned,
31784
+ projectId: record5.projectId ?? null,
31785
+ daybreakEnabled: record5.daybreakEnabled ?? null,
31076
31786
  ...threadSectionFields(input.placement),
31077
- agentNickname: record4.subagent ? record4.title || null : null,
31078
- agentRole: record4.subagent?.role ?? null,
31787
+ agentNickname: record5.subagent ? record5.title || null : null,
31788
+ agentRole: record5.subagent?.role ?? null,
31079
31789
  extra: null,
31080
- ...subagentThreadModelFields(record4)
31790
+ ...subagentThreadModelFields(record5)
31081
31791
  };
31082
31792
  }
31083
31793
 
@@ -31315,14 +32025,14 @@ async function settleExternalOutputFailure(thread, error51, project2, diagnose)
31315
32025
  function fixedError(code, message2) {
31316
32026
  return { code, message: message2 };
31317
32027
  }
31318
- function importedThread(record4) {
32028
+ function importedThread(record5) {
31319
32029
  return {
31320
32030
  ok: true,
31321
- threadId: record4.hostThreadId,
32031
+ threadId: record5.hostThreadId,
31322
32032
  thread: externalThreadValue({
31323
- record: record4,
32033
+ record: record5,
31324
32034
  turns: [],
31325
- sessionId: record4.hostThreadId,
32035
+ sessionId: record5.hostThreadId,
31326
32036
  loaded: false
31327
32037
  })
31328
32038
  };
@@ -31343,7 +32053,7 @@ var HarnessSessionImporter = class {
31343
32053
  }
31344
32054
  #mappedRecord(records, nativeSessionId) {
31345
32055
  return records.find(
31346
- (record4) => !record4.subagent && record4.state === "ready" && record4.nativeSessionRef?.harnessId === this.#harnessId && record4.nativeSessionRef.nativeSessionId === nativeSessionId
32056
+ (record5) => !record5.subagent && record5.state === "ready" && record5.nativeSessionRef?.harnessId === this.#harnessId && record5.nativeSessionRef.nativeSessionId === nativeSessionId
31347
32057
  );
31348
32058
  }
31349
32059
  #unavailable() {
@@ -31362,7 +32072,7 @@ var HarnessSessionImporter = class {
31362
32072
  }
31363
32073
  const mapped = new Set(
31364
32074
  (await this.#repository.list()).flatMap(
31365
- (record4) => !record4.subagent && record4.state === "ready" && record4.nativeSessionRef?.harnessId === this.#harnessId ? [record4.nativeSessionRef.nativeSessionId] : []
32075
+ (record5) => !record5.subagent && record5.state === "ready" && record5.nativeSessionRef?.harnessId === this.#harnessId ? [record5.nativeSessionRef.nativeSessionId] : []
31366
32076
  )
31367
32077
  );
31368
32078
  const superseded = this.#repository.supersededNativeSessionIds(this.#harnessId);
@@ -31471,8 +32181,8 @@ var HarnessSessionImporter = class {
31471
32181
  return { ok: false, error: fixedError(-32081, "Session import could not be persisted") };
31472
32182
  }
31473
32183
  try {
31474
- const record4 = await this.#repository.commitNative(provisional.hostThreadId, ref.data, []);
31475
- return importedThread(record4);
32184
+ const record5 = await this.#repository.commitNative(provisional.hostThreadId, ref.data, []);
32185
+ return importedThread(record5);
31476
32186
  } catch (error51) {
31477
32187
  await this.#repository.removeProvisional(provisional.hostThreadId).catch((cleanupError) => this.#diagnose(cleanupError));
31478
32188
  if (error51 instanceof MappingStoreError && error51.code === "DUPLICATE_NATIVE_SESSION") {
@@ -31574,6 +32284,22 @@ var SessionImportRequests = class {
31574
32284
  }
31575
32285
  };
31576
32286
 
32287
+ // packages/host-runtime/src/shared-question.ts
32288
+ function usesSharedQuestionCard(interaction) {
32289
+ return interaction.questions.some((question) => question.type === "choice" && question.multiple);
32290
+ }
32291
+ function sharedQuestion(interaction) {
32292
+ return threadQuestionSchema.parse(interaction);
32293
+ }
32294
+ function validateSharedQuestionResponse(interaction, response) {
32295
+ const error51 = validateHostQuestionResponse(interaction, response);
32296
+ if (error51) throw new Error(error51.message);
32297
+ for (const values of Object.values(response.answers)) {
32298
+ if (new Set(values).size !== values.length) throw new Error("Duplicate Question answers");
32299
+ if (values.some((value2) => !value2.trim())) throw new Error("Empty Question answer");
32300
+ }
32301
+ }
32302
+
31577
32303
  // packages/host-runtime/src/external-thread-history.ts
31578
32304
  var DEFAULT_PAGE_SIZE2 = 25;
31579
32305
  var MAX_PAGE_SIZE2 = 100;
@@ -32531,7 +33257,7 @@ var UsageMeter = class {
32531
33257
  derive(native, prices) {
32532
33258
  const usage = Object.fromEntries(
32533
33259
  Object.entries(native ?? {}).filter(
32534
- ([field]) => !hostDerivedUsageFields.includes(field)
33260
+ ([field2]) => !hostDerivedUsageFields.includes(field2)
32535
33261
  )
32536
33262
  );
32537
33263
  const sessionCacheUsage = usage.sessionCacheUsage;
@@ -32753,6 +33479,19 @@ var ExternalThreadRuntime = class {
32753
33479
  this.#threads.delete(threadId2);
32754
33480
  this.#steeredTurnIds.delete(threadId2);
32755
33481
  }
33482
+ /** Confirm release before forgetting either the Session owner or its persisted mapping. */
33483
+ async deleteThread(hostThreadId) {
33484
+ await this.#withLifecycle(hostThreadId, async () => {
33485
+ const thread = this.#threads.get(hostThreadId);
33486
+ if (thread) {
33487
+ thread.sessionUnavailable = true;
33488
+ thread.stateObserver.fault(new Error("External Thread is being deleted"));
33489
+ await this.#lifecycle.release(hostThreadId, thread.session, thread.outputTask);
33490
+ }
33491
+ this.remove(hostThreadId);
33492
+ await this.#repository.removeThread(hostThreadId);
33493
+ });
33494
+ }
32756
33495
  clear() {
32757
33496
  this.#threads.clear();
32758
33497
  this.#steeredTurnIds.clear();
@@ -32881,9 +33620,9 @@ var ExternalThreadRuntime = class {
32881
33620
  async #retireSubagents(parent, bestEffort = false) {
32882
33621
  const parentId = parent.id;
32883
33622
  const ancestors = /* @__PURE__ */ new Map();
32884
- const descendant = async (record4) => {
33623
+ const descendant = async (record5) => {
32885
33624
  const visited = /* @__PURE__ */ new Set();
32886
- let ownerId = record4?.subagent?.parentHostThreadId;
33625
+ let ownerId = record5?.subagent?.parentHostThreadId;
32887
33626
  while (ownerId && !visited.has(ownerId)) {
32888
33627
  if (ownerId === parentId) return true;
32889
33628
  visited.add(ownerId);
@@ -32931,23 +33670,23 @@ var ExternalThreadRuntime = class {
32931
33670
  if (failure) return { kind: "error", error: { code: -32075, message: failure } };
32932
33671
  return { kind: "external", record: loaded.record, thread: loaded };
32933
33672
  }
32934
- let record4;
33673
+ let record5;
32935
33674
  try {
32936
- record4 = await this.#repository.find(threadId2);
33675
+ record5 = await this.#repository.find(threadId2);
32937
33676
  } catch {
32938
33677
  return {
32939
33678
  kind: "error",
32940
33679
  error: { code: -32081, message: "External Thread ownership could not be read" }
32941
33680
  };
32942
33681
  }
32943
- if (!record4) return { kind: "official" };
32944
- if (record4.state !== "ready" || !record4.nativeSessionRef) {
33682
+ if (!record5) return { kind: "official" };
33683
+ if (record5.state !== "ready" || !record5.nativeSessionRef) {
32945
33684
  return {
32946
33685
  kind: "error",
32947
33686
  error: { code: -32079, message: "External Native Session is unavailable" }
32948
33687
  };
32949
33688
  }
32950
- return { kind: "external", record: record4, thread: null };
33689
+ return { kind: "external", record: record5, thread: null };
32951
33690
  }
32952
33691
  async resolve(threadId2) {
32953
33692
  try {
@@ -33158,16 +33897,16 @@ var ExternalThreadRuntime = class {
33158
33897
  return failure;
33159
33898
  }
33160
33899
  }
33161
- async #restore(record4) {
33162
- const harnessId = record4.harnessId;
33900
+ async #restore(record5) {
33901
+ const harnessId = record5.harnessId;
33163
33902
  const adapter = this.#adapters.get(harnessId);
33164
- if (!adapter || !record4.nativeSessionRef) {
33903
+ if (!adapter || !record5.nativeSessionRef) {
33165
33904
  throw new ExternalThreadOpenError({
33166
33905
  code: -32077,
33167
33906
  message: "External Harness is unavailable"
33168
33907
  });
33169
33908
  }
33170
- if (record4.subagent) {
33909
+ if (record5.subagent) {
33171
33910
  const subagents = adapter.subagents;
33172
33911
  if (!subagents) {
33173
33912
  throw new ExternalThreadOpenError({
@@ -33175,14 +33914,14 @@ var ExternalThreadRuntime = class {
33175
33914
  message: "External Harness Subagent history is unavailable"
33176
33915
  });
33177
33916
  }
33178
- const subagent = record4.subagent;
33179
- const parent = record4.nativeSessionRef;
33917
+ const subagent = record5.subagent;
33918
+ const parent = record5.nativeSessionRef;
33180
33919
  const snapshot2 = await subagents.readSnapshot({
33181
33920
  parent,
33182
33921
  nativeSubagentId: subagent.nativeSubagentId,
33183
- cwd: record4.cwd
33922
+ cwd: record5.cwd
33184
33923
  });
33185
- const latest = await this.#repository.find(record4.hostThreadId);
33924
+ const latest = await this.#repository.find(record5.hostThreadId);
33186
33925
  if (latest?.state === "ready" && latest.nativeSessionRef && JSON.stringify(latest.nativeSessionRef) !== JSON.stringify(parent)) {
33187
33926
  return this.#restore(latest);
33188
33927
  }
@@ -33190,16 +33929,16 @@ var ExternalThreadRuntime = class {
33190
33929
  throw new ExternalThreadOpenError(mapExternalThreadHarnessError(snapshot2.error, "read"));
33191
33930
  }
33192
33931
  const session2 = new ReadonlySnapshotSession(
33193
- record4.harnessId,
33194
- record4.nativeSessionRef,
33932
+ record5.harnessId,
33933
+ record5.nativeSessionRef,
33195
33934
  snapshot2.value,
33196
33935
  () => subagents.readSnapshot({
33197
33936
  parent,
33198
33937
  nativeSubagentId: subagent.nativeSubagentId,
33199
- cwd: record4.cwd
33938
+ cwd: record5.cwd
33200
33939
  })
33201
33940
  );
33202
- const aligned = await this.#repository.alignSnapshot(record4, snapshot2.value);
33941
+ const aligned = await this.#repository.alignSnapshot(record5, snapshot2.value);
33203
33942
  const sessionId = await this.#repository.sessionTreeId(aligned.record);
33204
33943
  return this.register({
33205
33944
  record: aligned.record,
@@ -33210,13 +33949,13 @@ var ExternalThreadRuntime = class {
33210
33949
  ...snapshot2.value.state ? { restoredState: snapshot2.value.state } : {}
33211
33950
  });
33212
33951
  }
33213
- const restoredSelection = decodeExternalTransportSelection(harnessId, record4.transportModelId);
33952
+ const restoredSelection = decodeExternalTransportSelection(harnessId, record5.transportModelId);
33214
33953
  const opened = await adapter.open({
33215
33954
  kind: "resume",
33216
- cwd: record4.cwd,
33217
- environment: { ...this.#environment, [DELEGATION_THREAD_ID_ENV]: record4.hostThreadId },
33218
- nativeRef: record4.nativeSessionRef,
33219
- knownTurnRefs: record4.turnMappings.map(({ nativeTurnRef }) => nativeTurnRef),
33955
+ cwd: record5.cwd,
33956
+ environment: { ...this.#environment, [DELEGATION_THREAD_ID_ENV]: record5.hostThreadId },
33957
+ nativeRef: record5.nativeSessionRef,
33958
+ knownTurnRefs: record5.turnMappings.map(({ nativeTurnRef }) => nativeTurnRef),
33220
33959
  ...restoredSelection?.model ? { model: restoredSelection.model } : {},
33221
33960
  ...restoredSelection?.thinkingOptionId ? { thinkingOptionId: restoredSelection.thinkingOptionId } : {},
33222
33961
  ...restoredSelection?.permissionModeId ? { permissionModeId: restoredSelection.permissionModeId } : {}
@@ -33230,7 +33969,7 @@ var ExternalThreadRuntime = class {
33230
33969
  if (!snapshot2.ok) {
33231
33970
  throw new ExternalThreadOpenError(mapExternalThreadHarnessError(snapshot2.error, "read"));
33232
33971
  }
33233
- let aligned = await this.#repository.alignSnapshot(record4, snapshot2.value);
33972
+ let aligned = await this.#repository.alignSnapshot(record5, snapshot2.value);
33234
33973
  const restoredState = snapshot2.value.state;
33235
33974
  const effectiveModel = restoredState ? restoredState.effectiveModel : restoredSelection?.model;
33236
33975
  const effectiveThinkingOptionId = restoredState ? restoredState.effectiveThinkingOptionId : restoredSelection?.thinkingOptionId;
@@ -33276,14 +34015,136 @@ var ExternalThreadRuntime = class {
33276
34015
  });
33277
34016
  } catch (error51) {
33278
34017
  if (error51 instanceof ExternalSessionReleaseError) throw error51;
33279
- await this.#lifecycle.release(record4.hostThreadId, session, Promise.resolve());
34018
+ await this.#lifecycle.release(record5.hostThreadId, session, Promise.resolve());
33280
34019
  throw error51;
33281
34020
  }
33282
34021
  }
33283
34022
  };
33284
34023
 
33285
- // packages/host-runtime/src/external-turn-steering.ts
34024
+ // packages/host-runtime/src/external-thread-queue.ts
33286
34025
  import { randomUUID as randomUUID12 } from "node:crypto";
34026
+ var ExternalQueueError = class extends Error {
34027
+ constructor(code, message2) {
34028
+ super(message2);
34029
+ this.code = code;
34030
+ }
34031
+ code;
34032
+ };
34033
+ var publicSubmission = ({
34034
+ id: id2,
34035
+ input,
34036
+ clientUserMessageId
34037
+ }) => ({
34038
+ id: id2,
34039
+ input,
34040
+ clientUserMessageId
34041
+ });
34042
+ var DEFAULT_PAGE_SIZE3 = 50;
34043
+ var ExternalThreadQueue = class {
34044
+ #queues = /* @__PURE__ */ new Map();
34045
+ #notifyChanged;
34046
+ #createId;
34047
+ constructor(options2) {
34048
+ this.#notifyChanged = options2.notifyChanged;
34049
+ this.#createId = options2.createId ?? randomUUID12;
34050
+ }
34051
+ has(threadId2) {
34052
+ return (this.#queues.get(threadId2)?.length ?? 0) > 0;
34053
+ }
34054
+ list(threadId2, params) {
34055
+ const items = this.#queues.get(threadId2) ?? [];
34056
+ const start = params.cursor == null ? 0 : Number(params.cursor);
34057
+ if (!Number.isSafeInteger(start) || start < 0 || start > items.length) {
34058
+ throw new ExternalQueueError(-32602, "Invalid thread/queue/list cursor");
34059
+ }
34060
+ const limit = typeof params.limit === "number" && Number.isSafeInteger(params.limit) && params.limit > 0 ? params.limit : DEFAULT_PAGE_SIZE3;
34061
+ const end = Math.min(items.length, start + limit);
34062
+ return {
34063
+ data: items.slice(start, end).map((item) => publicSubmission(item)),
34064
+ nextCursor: end < items.length ? String(end) : null
34065
+ };
34066
+ }
34067
+ async add(threadId2, input, clientUserMessageId, sourceHostId) {
34068
+ const submission = { id: this.#createId(), input, clientUserMessageId, sourceHostId };
34069
+ this.#items(threadId2).push(submission);
34070
+ await this.#notifyChanged(threadId2);
34071
+ return publicSubmission(submission);
34072
+ }
34073
+ async update(threadId2, id2, input) {
34074
+ const items = this.#queues.get(threadId2) ?? [];
34075
+ const index = items.findIndex((item) => item.id === id2);
34076
+ const current = items[index];
34077
+ if (!current) throw new ExternalQueueError(-32602, "Queued submission was not found");
34078
+ const submission = { ...current, input };
34079
+ items[index] = submission;
34080
+ await this.#notifyChanged(threadId2);
34081
+ return publicSubmission(submission);
34082
+ }
34083
+ async delete(threadId2, id2) {
34084
+ const items = this.#queues.get(threadId2);
34085
+ const index = items?.findIndex((item) => item.id === id2) ?? -1;
34086
+ if (!items || index === -1) return false;
34087
+ items.splice(index, 1);
34088
+ this.#prune(threadId2);
34089
+ await this.#notifyChanged(threadId2);
34090
+ return true;
34091
+ }
34092
+ /** Listed IDs move to the front in the given order; unlisted entries keep their order. */
34093
+ async reorder(threadId2, ids) {
34094
+ const items = this.#queues.get(threadId2);
34095
+ if (!items) return;
34096
+ const byId = new Map(items.map((item) => [item.id, item]));
34097
+ const ordered = ids.flatMap((id2) => {
34098
+ const item = byId.get(id2);
34099
+ byId.delete(id2);
34100
+ return item ? [item] : [];
34101
+ });
34102
+ items.splice(0, items.length, ...ordered, ...byId.values());
34103
+ await this.#notifyChanged(threadId2);
34104
+ }
34105
+ /** Removes the submission a Turn is about to start; `restore` returns it if the start fails. */
34106
+ take(threadId2, id2) {
34107
+ const items = this.#queues.get(threadId2) ?? [];
34108
+ const index = id2 == null ? 0 : items.findIndex((item) => item.id === id2);
34109
+ const submission = index === -1 ? void 0 : items[index];
34110
+ if (!submission) throw new ExternalQueueError(-32602, "Queued submission was not found");
34111
+ items.splice(index, 1);
34112
+ this.#prune(threadId2);
34113
+ return {
34114
+ submission: publicSubmission(submission),
34115
+ sourceHostId: submission.sourceHostId,
34116
+ index
34117
+ };
34118
+ }
34119
+ restore(threadId2, taken) {
34120
+ const items = this.#items(threadId2);
34121
+ if (items.some((item) => item.id === taken.submission.id)) return;
34122
+ items.splice(Math.min(taken.index, items.length), 0, {
34123
+ ...taken.submission,
34124
+ sourceHostId: taken.sourceHostId
34125
+ });
34126
+ }
34127
+ notifyChanged(threadId2) {
34128
+ return this.#notifyChanged(threadId2);
34129
+ }
34130
+ forget(threadId2) {
34131
+ this.#queues.delete(threadId2);
34132
+ }
34133
+ #items(threadId2) {
34134
+ let items = this.#queues.get(threadId2);
34135
+ if (!items) {
34136
+ items = [];
34137
+ this.#queues.set(threadId2, items);
34138
+ }
34139
+ return items;
34140
+ }
34141
+ #prune(threadId2) {
34142
+ if (this.#queues.get(threadId2)?.length === 0) this.#queues.delete(threadId2);
34143
+ }
34144
+ };
34145
+
34146
+ // packages/host-runtime/src/external-turn-steering.ts
34147
+ import { randomUUID as randomUUID13 } from "node:crypto";
33287
34148
 
33288
34149
  // packages/host-runtime/src/external-command-routing.ts
33289
34150
  var ExternalCommandError = class extends Error {
@@ -33404,7 +34265,7 @@ async function insertNativeSteer(thread, input, host) {
33404
34265
  thread.steeredTurnIds.add(input.turnId);
33405
34266
  const item = {
33406
34267
  type: "userMessage",
33407
- itemId: hostItemIdSchema.parse(randomUUID12()),
34268
+ itemId: hostItemIdSchema.parse(randomUUID13()),
33408
34269
  input: displayed
33409
34270
  };
33410
34271
  try {
@@ -33636,7 +34497,7 @@ function sameWorkspace(left, right) {
33636
34497
  }
33637
34498
 
33638
34499
  // packages/host-runtime/src/harness-delegation-coordinator.ts
33639
- import { createHash as createHash8, randomUUID as randomUUID13 } from "node:crypto";
34500
+ import { createHash as createHash8, randomUUID as randomUUID14 } from "node:crypto";
33640
34501
  import path24 from "node:path";
33641
34502
 
33642
34503
  // packages/host-runtime/src/delegation-snapshot.ts
@@ -33958,11 +34819,11 @@ var HarnessDelegationCoordinator = class {
33958
34819
  });
33959
34820
  this.#validateConfiguration(inspected.inspection, input.model, input.thinkingOptionId);
33960
34821
  }
33961
- const delegationId = hostThreadIdSchema.parse(randomUUID13());
33962
- const childThreadId = hostThreadIdSchema.parse(randomUUID13());
33963
- const turnId = hostTurnIdSchema.parse(randomUUID13());
33964
- const createRequestId = input.requestId ? `delegation:${input.requestId}` : randomUUID13();
33965
- let record4 = await this.#repository.createProvisional(
34822
+ const delegationId = hostThreadIdSchema.parse(randomUUID14());
34823
+ const childThreadId = hostThreadIdSchema.parse(randomUUID14());
34824
+ const turnId = hostTurnIdSchema.parse(randomUUID14());
34825
+ const createRequestId = input.requestId ? `delegation:${input.requestId}` : randomUUID14();
34826
+ let record5 = await this.#repository.createProvisional(
33966
34827
  createExternalThreadRecordInput({
33967
34828
  hostThreadId: childThreadId,
33968
34829
  createRequestId,
@@ -33993,7 +34854,7 @@ var HarnessDelegationCoordinator = class {
33993
34854
  });
33994
34855
  const opened = await adapter.open({
33995
34856
  kind: "create",
33996
- cwd: record4.cwd,
34857
+ cwd: record5.cwd,
33997
34858
  environment: { ...this.#environment, [DELEGATION_THREAD_ID_ENV]: childThreadId },
33998
34859
  executionPolicy: "unattended-full-access",
33999
34860
  ...input.model ? { model: input.model } : {},
@@ -34002,21 +34863,21 @@ var HarnessDelegationCoordinator = class {
34002
34863
  if (!opened.ok) throw new DelegationControlError("DELEGATION_FAILED", opened.error.message);
34003
34864
  session = opened.value;
34004
34865
  if (session.initialState.nativeRef) {
34005
- record4 = await this.#repository.commitNative(
34006
- record4.hostThreadId,
34866
+ record5 = await this.#repository.commitNative(
34867
+ record5.hostThreadId,
34007
34868
  session.initialState.nativeRef
34008
34869
  );
34009
34870
  }
34010
34871
  const threadValue = externalThreadValue({
34011
- record: record4,
34872
+ record: record5,
34012
34873
  turns: [],
34013
- sessionId: record4.hostThreadId,
34874
+ sessionId: record5.hostThreadId,
34014
34875
  running: true
34015
34876
  });
34016
34877
  const thread = this.#registerExternalThread({
34017
- record: record4,
34878
+ record: record5,
34018
34879
  session,
34019
- sessionId: record4.hostThreadId,
34880
+ sessionId: record5.hostThreadId,
34020
34881
  thread: threadValue,
34021
34882
  turns: [],
34022
34883
  ...input.model ? { requestedModel: input.model } : {},
@@ -34073,7 +34934,7 @@ var HarnessDelegationCoordinator = class {
34073
34934
  } : {}
34074
34935
  }
34075
34936
  }),
34076
- cwd: record4.cwd,
34937
+ cwd: record5.cwd,
34077
34938
  parentThreadId
34078
34939
  };
34079
34940
  } catch (error51) {
@@ -34115,7 +34976,7 @@ var HarnessDelegationCoordinator = class {
34115
34976
  if (this.#externalThreadBusy(thread) || thread.activeTurnId) {
34116
34977
  throw new DelegationControlError("THREAD_BUSY", "Thread already has an active Turn");
34117
34978
  }
34118
- const turnId = hostTurnIdSchema.parse(randomUUID13());
34979
+ const turnId = hostTurnIdSchema.parse(randomUUID14());
34119
34980
  try {
34120
34981
  await this.#startExternalTurn(thread, input.message, turnId);
34121
34982
  } catch (error51) {
@@ -34222,29 +35083,29 @@ var HarnessDelegationCoordinator = class {
34222
35083
  const parent = hostThreadIdSchema.parse(input.parentThreadId);
34223
35084
  const delegations = await this.#repository.listDelegations(parent);
34224
35085
  const records = await this.#repository.list();
34225
- const byId = new Map(records.map((record4) => [record4.hostThreadId, record4]));
35086
+ const byId = new Map(records.map((record5) => [record5.hostThreadId, record5]));
34226
35087
  const rows = delegations.map((delegation) => {
34227
- const record4 = byId.get(delegation.childHostThreadId);
35088
+ const record5 = byId.get(delegation.childHostThreadId);
34228
35089
  return {
34229
35090
  threadId: delegation.childHostThreadId,
34230
35091
  harnessId: delegation.targetHarnessId,
34231
35092
  deepLink: `codex://threads/${delegation.childHostThreadId}`,
34232
35093
  status: delegation.status,
34233
- ...record4 ? {
34234
- cwd: record4.cwd,
34235
- title: record4.title,
34236
- createdAt: record4.createdAt,
34237
- updatedAt: record4.updatedAt
35094
+ ...record5 ? {
35095
+ cwd: record5.cwd,
35096
+ title: record5.title,
35097
+ createdAt: record5.createdAt,
35098
+ updatedAt: record5.updatedAt
34238
35099
  } : {
34239
35100
  createdAt: delegation.createdAt,
34240
35101
  updatedAt: delegation.updatedAt
34241
35102
  }
34242
35103
  };
34243
35104
  });
34244
- const [field, direction] = input.sort.split("-");
35105
+ const [field2, direction] = input.sort.split("-");
34245
35106
  rows.sort((left, right) => {
34246
- const leftTimestamp = field === "created" ? left.createdAt : left.updatedAt;
34247
- const rightTimestamp = field === "created" ? right.createdAt : right.updatedAt;
35107
+ const leftTimestamp = field2 === "created" ? left.createdAt : left.updatedAt;
35108
+ const rightTimestamp = field2 === "created" ? right.createdAt : right.updatedAt;
34248
35109
  const leftTime = Date.parse(leftTimestamp ?? "");
34249
35110
  const rightTime = Date.parse(rightTimestamp ?? "");
34250
35111
  return direction === "asc" ? leftTime - rightTime : rightTime - leftTime;
@@ -34328,19 +35189,19 @@ var HarnessDelegationCoordinator = class {
34328
35189
  }
34329
35190
  }
34330
35191
  async #parentMetadata(parentThreadId) {
34331
- const record4 = await this.#repository.find(parentThreadId);
34332
- if (record4)
35192
+ const record5 = await this.#repository.find(parentThreadId);
35193
+ if (record5)
34333
35194
  return {
34334
- harnessId: record4.harnessId,
34335
- cwd: record4.cwd,
34336
- title: record4.title
35195
+ harnessId: record5.harnessId,
35196
+ cwd: record5.cwd,
35197
+ title: record5.title
34337
35198
  };
34338
35199
  const metadata = await this.#officialThreadMetadata(parentThreadId).catch(() => ({}));
34339
35200
  return { harnessId: "codex", ...metadata };
34340
35201
  }
34341
35202
  async #existingResult(delegation) {
34342
- const record4 = await this.#repository.find(delegation.childHostThreadId);
34343
- const turnId = record4?.turnMappings.at(-1)?.hostTurnId ?? "pending";
35203
+ const record5 = await this.#repository.find(delegation.childHostThreadId);
35204
+ const turnId = record5?.turnMappings.at(-1)?.hostTurnId ?? "pending";
34344
35205
  return {
34345
35206
  ...this.#result(
34346
35207
  delegation.delegationId,
@@ -34349,7 +35210,7 @@ var HarnessDelegationCoordinator = class {
34349
35210
  delegation.targetHarnessId,
34350
35211
  delegation.status
34351
35212
  ),
34352
- ...record4 ? { cwd: record4.cwd } : {},
35213
+ ...record5 ? { cwd: record5.cwd } : {},
34353
35214
  parentThreadId: delegation.parentHostThreadId
34354
35215
  };
34355
35216
  }
@@ -37069,10 +37930,10 @@ function projectCodexAccountAuth(snapshot2, homeAuth) {
37069
37930
  }
37070
37931
 
37071
37932
  // packages/host-runtime/src/codex-runtime/official-runtime-owner.ts
37072
- import { randomUUID as randomUUID15 } from "node:crypto";
37933
+ import { randomUUID as randomUUID16 } from "node:crypto";
37073
37934
 
37074
37935
  // packages/host-runtime/src/official-request-broker.ts
37075
- import { randomUUID as randomUUID14 } from "node:crypto";
37936
+ import { randomUUID as randomUUID15 } from "node:crypto";
37076
37937
  var INTERNAL_REQUEST_PREFIX = "codexhost:official:";
37077
37938
  var MAX_RETIRED_IDS = 1024;
37078
37939
  function isRecord16(value2) {
@@ -37088,7 +37949,7 @@ var OfficialRequestBroker = class {
37088
37949
  constructor(input) {
37089
37950
  this.#send = input.send;
37090
37951
  this.#timeoutMs = input.timeoutMs ?? 3e4;
37091
- this.#nextId = input.nextId ?? (() => `${INTERNAL_REQUEST_PREFIX}${randomUUID14()}`);
37952
+ this.#nextId = input.nextId ?? (() => `${INTERNAL_REQUEST_PREFIX}${randomUUID15()}`);
37092
37953
  }
37093
37954
  get pendingCount() {
37094
37955
  return this.#pending.size;
@@ -37442,7 +38303,7 @@ var OfficialRuntimeOwner = class {
37442
38303
  }
37443
38304
  #attach(role, output, onBackendStopped) {
37444
38305
  const client = {
37445
- id: randomUUID15(),
38306
+ id: randomUUID16(),
37446
38307
  role,
37447
38308
  output,
37448
38309
  ...onBackendStopped ? { onBackendStopped } : {},
@@ -37600,7 +38461,7 @@ var OfficialRuntimeOwner = class {
37600
38461
  if (!object4(value2)) return client.output(event);
37601
38462
  if (typeof value2.id === "string" || typeof value2.id === "number") {
37602
38463
  if (typeof value2.method === "string") {
37603
- const id2 = `codexhost:server:${client.id}:${event.generation}:${randomUUID15()}`;
38464
+ const id2 = `codexhost:server:${client.id}:${event.generation}:${randomUUID16()}`;
37604
38465
  client.serverRequests.set(id2, value2.id);
37605
38466
  const projected = { ...value2, id: id2 };
37606
38467
  return client.output({
@@ -37947,9 +38808,9 @@ var RequestRouteObservationTracker = class {
37947
38808
  };
37948
38809
 
37949
38810
  // packages/host-runtime/src/external-thread-list.ts
37950
- function unixTimestamp(value2, field) {
38811
+ function unixTimestamp(value2, field2) {
37951
38812
  const parsed2 = Date.parse(value2);
37952
- if (!Number.isFinite(parsed2)) throw new Error(`External Thread ${field} is invalid`);
38813
+ if (!Number.isFinite(parsed2)) throw new Error(`External Thread ${field2} is invalid`);
37953
38814
  return Math.floor(parsed2 / 1e3);
37954
38815
  }
37955
38816
  function threadId(thread) {
@@ -37959,11 +38820,11 @@ function threadId(thread) {
37959
38820
  return thread.id;
37960
38821
  }
37961
38822
  function threadListTimestamp(thread, sortKey) {
37962
- const field = sortKey === "created_at" ? thread.createdAt : sortKey === "updated_at" ? thread.updatedAt : thread.recencyAt ?? thread.updatedAt;
37963
- if (!Number.isSafeInteger(field)) {
38823
+ const field2 = sortKey === "created_at" ? thread.createdAt : sortKey === "updated_at" ? thread.updatedAt : thread.recencyAt ?? thread.updatedAt;
38824
+ if (!Number.isSafeInteger(field2)) {
37964
38825
  throw new Error(`Thread list row has no valid ${sortKey} timestamp`);
37965
38826
  }
37966
- return field;
38827
+ return field2;
37967
38828
  }
37968
38829
  function compareTimestamp(left, right, direction) {
37969
38830
  if (left === right) return 0;
@@ -37988,9 +38849,9 @@ function externalAnchor(entry) {
37988
38849
  if (entry.source !== "external") throw new Error("Expected an External Thread list entry");
37989
38850
  return { timestamp: entry.timestamp, threadId: threadId(entry.thread) };
37990
38851
  }
37991
- function includesExternalRecord(record4, query, byId, sectionId) {
37992
- if (record4.state !== "ready" || !record4.nativeSessionRef) return false;
37993
- let current = record4;
38852
+ function includesExternalRecord(record5, query, byId, sectionId) {
38853
+ if (record5.state !== "ready" || !record5.nativeSessionRef) return false;
38854
+ let current = record5;
37994
38855
  const owners = /* @__PURE__ */ new Set();
37995
38856
  while (current.subagent) {
37996
38857
  if (owners.has(current.hostThreadId)) return false;
@@ -38000,40 +38861,40 @@ function includesExternalRecord(record4, query, byId, sectionId) {
38000
38861
  return false;
38001
38862
  current = parent;
38002
38863
  }
38003
- const sourceKind = record4.subagent ? "subAgentThreadSpawn" : "vscode";
38864
+ const sourceKind = record5.subagent ? "subAgentThreadSpawn" : "vscode";
38004
38865
  const scoped = query.parentThreadId !== null || query.ancestorThreadId !== null;
38005
- if (record4.subagent && !scoped && !query.sourceKinds?.some((kind) => kind === "subAgent" || kind === "subAgentThreadSpawn"))
38866
+ if (record5.subagent && !scoped && !query.sourceKinds?.some((kind) => kind === "subAgent" || kind === "subAgentThreadSpawn"))
38006
38867
  return false;
38007
- if (query.parentThreadId !== null && record4.subagent?.parentHostThreadId !== query.parentThreadId)
38868
+ if (query.parentThreadId !== null && record5.subagent?.parentHostThreadId !== query.parentThreadId)
38008
38869
  return false;
38009
38870
  if (query.ancestorThreadId !== null) {
38010
- let parentId = record4.subagent?.parentHostThreadId;
38011
- const visited = /* @__PURE__ */ new Set([record4.hostThreadId]);
38871
+ let parentId = record5.subagent?.parentHostThreadId;
38872
+ const visited = /* @__PURE__ */ new Set([record5.hostThreadId]);
38012
38873
  while (parentId && parentId !== query.ancestorThreadId && !visited.has(parentId)) {
38013
38874
  visited.add(parentId);
38014
38875
  parentId = byId.get(parentId)?.subagent?.parentHostThreadId;
38015
38876
  }
38016
- if (record4.hostThreadId === query.ancestorThreadId || parentId !== query.ancestorThreadId)
38877
+ if (record5.hostThreadId === query.ancestorThreadId || parentId !== query.ancestorThreadId)
38017
38878
  return false;
38018
38879
  }
38019
- if (record4.archived !== query.archived) return false;
38020
- if (query.projectId !== void 0 && (record4.projectId ?? null) !== query.projectId) return false;
38021
- if (query.cwd !== null && !query.cwd.includes(record4.cwd)) return false;
38880
+ if (record5.archived !== query.archived) return false;
38881
+ if (query.projectId !== void 0 && (record5.projectId ?? null) !== query.projectId) return false;
38882
+ if (query.cwd !== null && !query.cwd.includes(record5.cwd)) return false;
38022
38883
  if (query.modelProviders !== null && query.modelProviders.length > 0 && !query.modelProviders.includes("codexhost")) {
38023
38884
  return false;
38024
38885
  }
38025
- if (query.sourceKinds !== null && query.sourceKinds.length > 0 && !query.sourceKinds.includes(sourceKind) && !(record4.subagent && query.sourceKinds.includes("subAgent"))) {
38886
+ if (query.sourceKinds !== null && query.sourceKinds.length > 0 && !query.sourceKinds.includes(sourceKind) && !(record5.subagent && query.sourceKinds.includes("subAgent"))) {
38026
38887
  return false;
38027
38888
  }
38028
- if (query.searchTerm !== null && !record4.title.toLowerCase().includes(query.searchTerm.toLowerCase())) {
38889
+ if (query.searchTerm !== null && !record5.title.toLowerCase().includes(query.searchTerm.toLowerCase())) {
38029
38890
  return false;
38030
38891
  }
38031
- if (query.isPinned !== null && record4.isPinned !== query.isPinned) return false;
38892
+ if (query.isPinned !== null && record5.isPinned !== query.isPinned) return false;
38032
38893
  if (query.sectionId !== void 0 && query.sectionId !== sectionId) return false;
38033
38894
  return true;
38034
38895
  }
38035
38896
  function resolveExternalSessionTreeIds(records) {
38036
- const byId = new Map(records.map((record4) => [record4.hostThreadId, record4]));
38897
+ const byId = new Map(records.map((record5) => [record5.hostThreadId, record5]));
38037
38898
  const resolved = /* @__PURE__ */ new Map();
38038
38899
  const resolve = (start) => {
38039
38900
  const cached2 = resolved.get(start.hostThreadId);
@@ -38044,7 +38905,7 @@ function resolveExternalSessionTreeIds(records) {
38044
38905
  while (true) {
38045
38906
  const known = resolved.get(current.hostThreadId);
38046
38907
  if (known) {
38047
- for (const record4 of path44) resolved.set(record4.hostThreadId, known);
38908
+ for (const record5 of path44) resolved.set(record5.hostThreadId, known);
38048
38909
  return known;
38049
38910
  }
38050
38911
  if (visited.has(current.hostThreadId)) {
@@ -38056,32 +38917,32 @@ function resolveExternalSessionTreeIds(records) {
38056
38917
  const source = sourceId ? byId.get(sourceId) : void 0;
38057
38918
  if (!source) {
38058
38919
  const root = current.hostThreadId;
38059
- for (const record4 of path44) resolved.set(record4.hostThreadId, root);
38920
+ for (const record5 of path44) resolved.set(record5.hostThreadId, root);
38060
38921
  return root;
38061
38922
  }
38062
38923
  current = source;
38063
38924
  }
38064
38925
  };
38065
- for (const record4 of records) resolve(record4);
38926
+ for (const record5 of records) resolve(record5);
38066
38927
  return resolved;
38067
38928
  }
38068
38929
  function externalThreadListEntries(input) {
38069
38930
  const sessionIds = resolveExternalSessionTreeIds(input.records);
38070
- const byId = new Map(input.records.map((record4) => [record4.hostThreadId, record4]));
38931
+ const byId = new Map(input.records.map((record5) => [record5.hostThreadId, record5]));
38071
38932
  return input.records.filter(
38072
- (record4) => includesExternalRecord(
38073
- record4,
38933
+ (record5) => includesExternalRecord(
38934
+ record5,
38074
38935
  input.query,
38075
38936
  byId,
38076
- input.placementOf?.(record4.hostThreadId)?.section.id ?? null
38937
+ input.placementOf?.(record5.hostThreadId)?.section.id ?? null
38077
38938
  )
38078
- ).map((record4) => {
38079
- const runtime = input.runtimeFor(record4.hostThreadId);
38080
- const sessionId = sessionIds.get(record4.hostThreadId);
38939
+ ).map((record5) => {
38940
+ const runtime = input.runtimeFor(record5.hostThreadId);
38941
+ const sessionId = sessionIds.get(record5.hostThreadId);
38081
38942
  if (!sessionId) throw new Error("External Thread Session tree could not be resolved");
38082
- const placement = input.placementOf?.(record4.hostThreadId);
38943
+ const placement = input.placementOf?.(record5.hostThreadId);
38083
38944
  const thread = externalThreadValue({
38084
- record: record4,
38945
+ record: record5,
38085
38946
  turns: [],
38086
38947
  sessionId,
38087
38948
  ...runtime ? { running: runtime.running } : { loaded: false },
@@ -38090,7 +38951,7 @@ function externalThreadListEntries(input) {
38090
38951
  return {
38091
38952
  source: "external",
38092
38953
  thread,
38093
- timestamp: input.query.sortKey === "created_at" ? unixTimestamp(record4.createdAt, "createdAt") : unixTimestamp(record4.updatedAt, "updatedAt")
38954
+ timestamp: input.query.sortKey === "created_at" ? unixTimestamp(record5.createdAt, "createdAt") : unixTimestamp(record5.updatedAt, "updatedAt")
38094
38955
  };
38095
38956
  });
38096
38957
  }
@@ -38197,7 +39058,7 @@ async function aggregateThreadList(input) {
38197
39058
  let officialIndex = 0;
38198
39059
  let firstOfficialBackwardsCursor;
38199
39060
  let officialRequestCount = 0;
38200
- const externalIds = new Set(input.records.map((record4) => record4.hostThreadId));
39061
+ const externalIds = new Set(input.records.map((record5) => record5.hostThreadId));
38201
39062
  for (const thread of input.sharedThreads ?? []) externalIds.add(String(thread.id));
38202
39063
  const requestOfficial = async (cursor, limit) => {
38203
39064
  officialRequestCount += 1;
@@ -38539,7 +39400,6 @@ async function moveThreadSection(input) {
38539
39400
  // packages/host-runtime/src/external-thread-official-defaults.ts
38540
39401
  var EMPTY_RESULTS = /* @__PURE__ */ new Map([
38541
39402
  ["thread/attachment/list", () => ({ data: [], nextCursor: null })],
38542
- ["thread/queue/list", () => ({ data: [], nextCursor: null })],
38543
39403
  ["thread/settings/update", () => ({})]
38544
39404
  ]);
38545
39405
  function externalThreadEmptyOfficialResult(method) {
@@ -38893,6 +39753,9 @@ var AppServerHost = class {
38893
39753
  #executionHosts = /* @__PURE__ */ new WeakMap();
38894
39754
  #externalPrewarms = new ExternalThreadPrewarms();
38895
39755
  #externalSteering = new ExternalTurnSteering();
39756
+ #externalQueue = new ExternalThreadQueue({
39757
+ notifyChanged: (threadId2) => this.#writer.json({ method: "thread/queue/changed", params: { threadId: threadId2 } })
39758
+ });
38896
39759
  #liveCommandCache = new LiveCommandCatalogCache();
38897
39760
  #modelPrices;
38898
39761
  #observedSessionUsage;
@@ -38919,7 +39782,7 @@ var AppServerHost = class {
38919
39782
  #sectionMoves = Promise.resolve();
38920
39783
  #writer;
38921
39784
  /** Console requests share Desktop handling; their replies return to the console. */
38922
- #consoleRequestPrefix = `codexhost-console:${randomUUID16()}:`;
39785
+ #consoleRequestPrefix = `codexhost-console:${randomUUID17()}:`;
38923
39786
  #consoleReplies = /* @__PURE__ */ new Map();
38924
39787
  #nextConsoleRequest = 0;
38925
39788
  #subagentThreadStatuses = /* @__PURE__ */ new Map();
@@ -39034,16 +39897,7 @@ var AppServerHost = class {
39034
39897
  hasRunningDescendants: (threadId2) => this.#hasRunningSubagents(threadId2),
39035
39898
  idleRelease: {
39036
39899
  queue: this.#desktopRequests,
39037
- onClosed: async (thread) => {
39038
- for (const pending of [...this.#pendingDesktopApprovals.values()]) {
39039
- if (pending.thread === thread)
39040
- await this.#resolveDesktopApproval(pending.interaction.interactionId);
39041
- }
39042
- for (const pending of [...this.#pendingDesktopQuestions.values()]) {
39043
- if (pending.thread === thread)
39044
- await this.#resolveDesktopQuestion(pending.interaction.interactionId);
39045
- }
39046
- },
39900
+ onClosed: (thread) => this.#resolveThreadInteractions(thread),
39047
39901
  canRelease: (thread) => !this.#hasRunningSubagents(thread.id) && !thread.session.hasBackgroundWork?.() && !this.#externalSteering.hasPending(thread.id) && !this.#pendingExternalCommandRequests.has(thread.id) && ![...this.#pendingDesktopApprovals.values()].some(
39048
39902
  (pending) => pending.thread === thread
39049
39903
  ) && ![...this.#pendingDesktopQuestions.values()].some((pending) => pending.thread === thread)
@@ -39233,12 +40087,12 @@ var AppServerHost = class {
39233
40087
  await this.#closeAdapters();
39234
40088
  await this.#externalRuntime.drain();
39235
40089
  for (const pending of [...this.#pendingDesktopApprovals.values()]) {
39236
- await this.#resolveDesktopApproval(pending.interaction.interactionId).catch(
40090
+ await this.#resolveDesktopApproval(pending.interaction.interactionId, pending.thread).catch(
39237
40091
  () => void 0
39238
40092
  );
39239
40093
  }
39240
40094
  for (const pending of [...this.#pendingDesktopQuestions.values()]) {
39241
- await this.#resolveDesktopQuestion(pending.interaction.interactionId).catch(
40095
+ await this.#resolveDesktopQuestion(pending.interaction.interactionId, pending.thread).catch(
39242
40096
  () => void 0
39243
40097
  );
39244
40098
  }
@@ -39824,6 +40678,15 @@ var AppServerHost = class {
39824
40678
  await this.#listThreadOwnership(request);
39825
40679
  return;
39826
40680
  }
40681
+ if (request.method === THREAD_QUESTIONS_LIST_METHOD || request.method === THREAD_QUESTION_RESPOND_METHOD) {
40682
+ const threadId2 = requestObject(request).threadId;
40683
+ this.#dispatchDesktopReply(
40684
+ request,
40685
+ () => this.#handleSharedQuestionRequest(request),
40686
+ request.method === THREAD_QUESTION_RESPOND_METHOD && typeof threadId2 === "string" ? threadId2 : void 0
40687
+ );
40688
+ return;
40689
+ }
39827
40690
  if (request.method === "codexhost/thread/steering/inspect") {
39828
40691
  await this.#inspectThreadSteering(request);
39829
40692
  return;
@@ -40184,6 +41047,18 @@ var AppServerHost = class {
40184
41047
  return;
40185
41048
  }
40186
41049
  }
41050
+ if (request.method.startsWith("thread/queue/") && isRecord19(request.params) && typeof request.params.threadId === "string") {
41051
+ const location = await this.#locateExternalThread(request.params.threadId);
41052
+ if (await this.#writeResolutionError(request, location)) return;
41053
+ if (location.kind === "external") {
41054
+ this.#dispatchDesktopReply(
41055
+ request,
41056
+ () => this.#handleExternalQueueRequest(request, location.record.hostThreadId),
41057
+ location.record.hostThreadId
41058
+ );
41059
+ return;
41060
+ }
41061
+ }
40187
41062
  if (request.method === "thread/backgroundTerminals/clean" && isRecord19(request.params) && typeof request.params.threadId === "string") {
40188
41063
  const location = await this.#locateExternalThread(request.params.threadId);
40189
41064
  if (await this.#writeResolutionError(request, location)) return;
@@ -40626,7 +41501,7 @@ var AppServerHost = class {
40626
41501
  throw error51;
40627
41502
  }
40628
41503
  this.#activeOfficialTurns.set(threadId2, turnId);
40629
- const delegationId = hostThreadIdSchema.parse(randomUUID16());
41504
+ const delegationId = hostThreadIdSchema.parse(randomUUID17());
40630
41505
  try {
40631
41506
  const source = await this.#repository.find(input.parentThreadId);
40632
41507
  const pendingTerminal = this.#pendingOfficialTerminalStatuses.get(threadId2);
@@ -40814,7 +41689,7 @@ var AppServerHost = class {
40814
41689
  async #listDelegationThreads(input) {
40815
41690
  const [sortKey, sortDirection2] = input.sort.split("-");
40816
41691
  const request = {
40817
- id: `codexhost:delegation-list:${randomUUID16()}`,
41692
+ id: `codexhost:delegation-list:${randomUUID17()}`,
40818
41693
  method: "thread/list",
40819
41694
  params: {
40820
41695
  cwd: input.cwd ? [input.cwd] : null,
@@ -40839,12 +41714,12 @@ var AppServerHost = class {
40839
41714
  return {
40840
41715
  threads: result.data.flatMap((entry) => {
40841
41716
  if (typeof entry.id !== "string") return [];
40842
- const record4 = records.find((candidate) => candidate.hostThreadId === entry.id);
41717
+ const record5 = records.find((candidate) => candidate.hostThreadId === entry.id);
40843
41718
  const status2 = isRecord19(entry.status) && entry.status.type === "active" ? "running" : "completed";
40844
41719
  return [
40845
41720
  {
40846
41721
  threadId: entry.id,
40847
- harnessId: record4 ? record4.harnessId : "codex",
41722
+ harnessId: record5 ? record5.harnessId : "codex",
40848
41723
  deepLink: `codex://threads/${entry.id}`,
40849
41724
  status: status2,
40850
41725
  ...typeof entry.cwd === "string" ? { cwd: entry.cwd } : {},
@@ -40951,7 +41826,7 @@ var AppServerHost = class {
40951
41826
  const outcome = await moveThreadSection({
40952
41827
  move,
40953
41828
  movingExternal: location.kind === "external",
40954
- externalThreadIds: new Set(records.map((record4) => record4.hostThreadId)),
41829
+ externalThreadIds: new Set(records.map((record5) => record5.hostThreadId)),
40955
41830
  placements,
40956
41831
  requestOfficial: (method, params) => this.#requestOfficial(method, params),
40957
41832
  savePlacements: (next) => this.#repository.replaceSectionPlacements(next),
@@ -41041,10 +41916,10 @@ var AppServerHost = class {
41041
41916
  /** Clear External assignments to a project official Codex reported as deleted. */
41042
41917
  async #clearDeletedProjectAssignments(projectId) {
41043
41918
  const records = await this.#repository.list();
41044
- for (const record4 of records) {
41045
- if (record4.projectId !== projectId) continue;
41919
+ for (const record5 of records) {
41920
+ if (record5.projectId !== projectId) continue;
41046
41921
  const updated = await this.#repository.updateMetadata(
41047
- record4.hostThreadId,
41922
+ record5.hostThreadId,
41048
41923
  { projectId: null },
41049
41924
  { ifProjectId: projectId }
41050
41925
  );
@@ -41057,14 +41932,14 @@ var AppServerHost = class {
41057
41932
  });
41058
41933
  }
41059
41934
  }
41060
- #syncLoadedExternalThread(thread, record4) {
41935
+ #syncLoadedExternalThread(thread, record5) {
41061
41936
  const projected = externalThreadValue({
41062
- record: record4,
41937
+ record: record5,
41063
41938
  turns: [],
41064
41939
  sessionId: thread.sessionId,
41065
41940
  running: thread.running
41066
41941
  });
41067
- thread.record = record4;
41942
+ thread.record = record5;
41068
41943
  thread.thread = { ...thread.thread, ...projected, turns: thread.thread.turns ?? [] };
41069
41944
  return projected;
41070
41945
  }
@@ -41081,15 +41956,15 @@ var AppServerHost = class {
41081
41956
  );
41082
41957
  return null;
41083
41958
  }
41084
- let record4;
41959
+ let record5;
41085
41960
  try {
41086
- record4 = await write(location.record.hostThreadId);
41961
+ record5 = await write(location.record.hostThreadId);
41087
41962
  } catch {
41088
41963
  await this.#writer.json(rpcError(request, -32081, failureMessage));
41089
41964
  return null;
41090
41965
  }
41091
- const projected = location.thread ? this.#syncLoadedExternalThread(location.thread, record4) : externalThreadValue({ record: record4, turns: [], sessionId, loaded: false });
41092
- return { record: record4, thread: await this.#withExternalSection(projected) };
41966
+ const projected = location.thread ? this.#syncLoadedExternalThread(location.thread, record5) : externalThreadValue({ record: record5, turns: [], sessionId, loaded: false });
41967
+ return { record: record5, thread: await this.#withExternalSection(projected) };
41093
41968
  }
41094
41969
  /** 持久化置顶变更,并向 Desktop 返回更新后的 External Thread 投影。 */
41095
41970
  async #setExternalThreadPinned(request, location, isPinned) {
@@ -41104,9 +41979,9 @@ var AppServerHost = class {
41104
41979
  );
41105
41980
  return;
41106
41981
  }
41107
- let record4;
41982
+ let record5;
41108
41983
  try {
41109
- record4 = await this.#repository.setPinned(location.record.hostThreadId, isPinned);
41984
+ record5 = await this.#repository.setPinned(location.record.hostThreadId, isPinned);
41110
41985
  } catch {
41111
41986
  await this.#writer.json(
41112
41987
  rpcError(request, -32081, "External Thread pin state could not be persisted")
@@ -41114,13 +41989,13 @@ var AppServerHost = class {
41114
41989
  return;
41115
41990
  }
41116
41991
  const projected = externalThreadValue({
41117
- record: record4,
41992
+ record: record5,
41118
41993
  turns: [],
41119
41994
  sessionId,
41120
41995
  ...location.thread ? { running: location.thread.running } : { loaded: false }
41121
41996
  });
41122
41997
  if (location.thread) {
41123
- location.thread.record = record4;
41998
+ location.thread.record = record5;
41124
41999
  location.thread.thread = {
41125
42000
  ...location.thread.thread,
41126
42001
  ...projected,
@@ -41405,8 +42280,8 @@ var AppServerHost = class {
41405
42280
  const sharedHarness = shared?.get(threadId2);
41406
42281
  if (sharedHarness)
41407
42282
  return { threadId: threadId2, owner: "external", harnessId: sharedHarness };
41408
- const record4 = await this.#repository.find(threadId2);
41409
- return record4 ? { threadId: threadId2, owner: "external", harnessId: record4.harnessId } : { threadId: threadId2, owner: "codex" };
42283
+ const record5 = await this.#repository.find(threadId2);
42284
+ return record5 ? { threadId: threadId2, owner: "external", harnessId: record5.harnessId } : { threadId: threadId2, owner: "codex" };
41410
42285
  })
41411
42286
  );
41412
42287
  const result = threadOwnershipListResultSchema.parse({ threads });
@@ -41602,7 +42477,7 @@ var AppServerHost = class {
41602
42477
  if (thread.running || thread.activeTurnId) {
41603
42478
  throw new ExternalCommandError(-32072, "External Thread already has an active operation");
41604
42479
  }
41605
- const turnId = requestedTurnId ?? hostTurnIdSchema.parse(randomUUID16());
42480
+ const turnId = requestedTurnId ?? hostTurnIdSchema.parse(randomUUID17());
41606
42481
  const projection = {
41607
42482
  projector: new CodexTurnProjector({
41608
42483
  threadId: thread.id,
@@ -41917,6 +42792,7 @@ var AppServerHost = class {
41917
42792
  }
41918
42793
  const params = requestObject(request);
41919
42794
  const route = decodeCreateRoute(request);
42795
+ const prewarm = params[EXTERNAL_THREAD_PREWARM_PARAM] === true || route?.prewarm === true;
41920
42796
  const requestedModel = route && route.harnessId !== "codex" ? route.model : void 0;
41921
42797
  const requestedThinkingOptionId = route && route.harnessId !== "codex" ? route.thinkingOptionId : void 0;
41922
42798
  const requestedPermissionModeId = route && route.harnessId !== "codex" ? route.permissionModeId : void 0;
@@ -41936,9 +42812,9 @@ var AppServerHost = class {
41936
42812
  ephemeral: params.ephemeral === true,
41937
42813
  historyMode: params.historyMode === "paginated" ? "paginated" : "legacy"
41938
42814
  });
41939
- let record4;
42815
+ let record5;
41940
42816
  try {
41941
- record4 = await this.#repository.createProvisional(recordInput);
42817
+ record5 = await this.#repository.createProvisional(recordInput);
41942
42818
  } catch {
41943
42819
  this.#routeObservationTracker.rejectCreate(request.id);
41944
42820
  await this.#writer.json(rpcError(request, -32081, "External Thread could not be persisted"));
@@ -41949,7 +42825,7 @@ var AppServerHost = class {
41949
42825
  cwd,
41950
42826
  environment: {
41951
42827
  ...this.#options.environment ?? process.env,
41952
- [DELEGATION_THREAD_ID_ENV]: record4.hostThreadId
42828
+ [DELEGATION_THREAD_ID_ENV]: record5.hostThreadId
41953
42829
  },
41954
42830
  ...requestedModel ? { model: requestedModel } : {},
41955
42831
  ...requestedThinkingOptionId ? { thinkingOptionId: requestedThinkingOptionId } : {},
@@ -41957,37 +42833,37 @@ var AppServerHost = class {
41957
42833
  });
41958
42834
  if (!sessionResult.ok) {
41959
42835
  this.#routeObservationTracker.rejectCreate(request.id);
41960
- await this.#repository.removeProvisional(record4.hostThreadId).catch(() => void 0);
42836
+ await this.#repository.removeProvisional(record5.hostThreadId).catch(() => void 0);
41961
42837
  const mapped = mapExternalThreadHarnessError(sessionResult.error, "create");
41962
42838
  await this.#writer.json(rpcError(request, mapped.code, mapped.message));
41963
42839
  return;
41964
42840
  }
41965
42841
  const session = sessionResult.value;
41966
- await this.#externalRuntime.idleRelease.runOperation(record4.hostThreadId, async () => {
42842
+ await this.#externalRuntime.idleRelease.runOperation(record5.hostThreadId, async () => {
41967
42843
  try {
41968
- if (session.initialState.nativeRef && params[EXTERNAL_THREAD_PREWARM_PARAM] !== true) {
41969
- record4 = await this.#repository.commitNative(
41970
- record4.hostThreadId,
42844
+ if (session.initialState.nativeRef && !prewarm) {
42845
+ record5 = await this.#repository.commitNative(
42846
+ record5.hostThreadId,
41971
42847
  session.initialState.nativeRef
41972
42848
  );
41973
42849
  }
41974
42850
  const thread = externalThreadValue({
41975
- record: record4,
42851
+ record: record5,
41976
42852
  turns: [],
41977
- sessionId: record4.hostThreadId
42853
+ sessionId: record5.hostThreadId
41978
42854
  });
41979
42855
  const externalThread = this.#registerExternalThread({
41980
- record: record4,
42856
+ record: record5,
41981
42857
  session,
41982
- unsubmittedPrewarm: params[EXTERNAL_THREAD_PREWARM_PARAM] === true,
41983
- sessionId: record4.hostThreadId,
42858
+ unsubmittedPrewarm: prewarm,
42859
+ sessionId: record5.hostThreadId,
41984
42860
  thread,
41985
42861
  turns: [],
41986
42862
  ...requestedModel ? { requestedModel } : {},
41987
42863
  ...requestedThinkingOptionId ? { requestedThinkingOptionId } : {},
41988
42864
  ...requestedPermissionModeId ? { requestedPermissionModeId } : {}
41989
42865
  });
41990
- if (params[EXTERNAL_THREAD_PREWARM_PARAM] === true) {
42866
+ if (prewarm) {
41991
42867
  this.#externalPrewarms.register(externalThread);
41992
42868
  }
41993
42869
  this.#routeObservationTracker.bindCreatedThread(request.id, externalThread.id);
@@ -42010,12 +42886,12 @@ var AppServerHost = class {
42010
42886
  }
42011
42887
  })
42012
42888
  );
42013
- if (record4.state === "ready") await this.#notifyExternalThreadStarted(thread);
42889
+ if (record5.state === "ready") await this.#notifyExternalThreadStarted(thread);
42014
42890
  } catch {
42015
- this.#externalRuntime.remove(record4.hostThreadId);
42016
- this.#routeObservationTracker.forgetThread(record4.hostThreadId);
42891
+ this.#externalRuntime.remove(record5.hostThreadId);
42892
+ this.#routeObservationTracker.forgetThread(record5.hostThreadId);
42017
42893
  await session.close().catch(() => void 0);
42018
- await this.#repository.removeProvisional(record4.hostThreadId).catch(() => void 0);
42894
+ await this.#repository.removeProvisional(record5.hostThreadId).catch(() => void 0);
42019
42895
  await this.#writer.json(
42020
42896
  rpcError(request, -32081, "External Thread could not be persisted")
42021
42897
  );
@@ -42177,9 +43053,9 @@ var AppServerHost = class {
42177
43053
  );
42178
43054
  return;
42179
43055
  }
42180
- let record4;
43056
+ let record5;
42181
43057
  try {
42182
- record4 = await this.#repository.setTitle(location.record.hostThreadId, name);
43058
+ record5 = await this.#repository.setTitle(location.record.hostThreadId, name);
42183
43059
  } catch {
42184
43060
  await this.#writer.json(
42185
43061
  rpcError(request, -32081, "External Thread title could not be persisted")
@@ -42187,7 +43063,7 @@ var AppServerHost = class {
42187
43063
  return;
42188
43064
  }
42189
43065
  if (location.thread) {
42190
- location.thread.record = record4;
43066
+ location.thread.record = record5;
42191
43067
  location.thread.thread.name = name;
42192
43068
  location.thread.thread.updatedAt = unixSeconds();
42193
43069
  }
@@ -42198,29 +43074,24 @@ var AppServerHost = class {
42198
43074
  });
42199
43075
  }
42200
43076
  async #deleteExternalThread(request, location) {
42201
- const thread = location.thread;
42202
43077
  try {
42203
- await this.#repository.removeThread(location.record.hostThreadId);
42204
- } catch {
42205
- await this.#writer.json(rpcError(request, -32081, "External Thread could not be removed"));
42206
- return;
42207
- }
42208
- this.#externalRuntime.remove(location.record.hostThreadId);
42209
- this.#routeObservationTracker.forgetThread(location.record.hostThreadId);
42210
- if (!thread) {
42211
- await this.#writer.json(rpcEnvelope(request, { result: {} }));
42212
- return;
42213
- }
42214
- thread.stateObserver.fault(new Error("External Thread was deleted"));
42215
- try {
42216
- await thread.session.close();
42217
- await thread.outputTask;
42218
- await this.#writer.json(rpcEnvelope(request, { result: {} }));
43078
+ await this.#externalRuntime.deleteThread(location.record.hostThreadId);
42219
43079
  } catch (error51) {
43080
+ if (!(error51 instanceof ExternalSessionReleaseError) && location.thread)
43081
+ await this.#resolveThreadInteractions(location.thread);
42220
43082
  await this.#writer.json(
42221
- rpcError(request, -32075, `External Thread could not close: ${errorMessage4(error51)}`)
43083
+ error51 instanceof ExternalSessionReleaseError ? rpcError(request, -32075, error51.message) : rpcError(request, -32081, "External Thread could not be removed")
42222
43084
  );
43085
+ return;
42223
43086
  }
43087
+ if (location.thread) await this.#resolveThreadInteractions(location.thread);
43088
+ this.#routeObservationTracker.forgetThread(location.record.hostThreadId);
43089
+ this.#externalQueue.forget(location.record.hostThreadId);
43090
+ await this.#writer.json(rpcEnvelope(request, { result: {} }));
43091
+ await this.#writer.json({
43092
+ method: "thread/deleted",
43093
+ params: { threadId: location.record.hostThreadId }
43094
+ });
42224
43095
  }
42225
43096
  async #readExternalThreadMetadata(request, location) {
42226
43097
  try {
@@ -42469,6 +43340,125 @@ var AppServerHost = class {
42469
43340
  );
42470
43341
  }
42471
43342
  }
43343
+ async #handleExternalQueueRequest(request, threadId2) {
43344
+ const queue = this.#externalQueue;
43345
+ try {
43346
+ const params = requestObject(request);
43347
+ const input = () => {
43348
+ requestText(params);
43349
+ return params.input;
43350
+ };
43351
+ const submissionId = () => {
43352
+ if (typeof params.queuedSubmissionId !== "string")
43353
+ throw new ExternalQueueError(-32602, "queuedSubmissionId must be a string");
43354
+ return params.queuedSubmissionId;
43355
+ };
43356
+ let result;
43357
+ switch (request.method) {
43358
+ case "thread/queue/list":
43359
+ result = queue.list(threadId2, params);
43360
+ break;
43361
+ case "thread/queue/add": {
43362
+ if (typeof params.clientUserMessageId !== "string" || !params.clientUserMessageId)
43363
+ throw new ExternalQueueError(-32602, "clientUserMessageId must be a string");
43364
+ const sourceHostId = params[THREAD_REFERENCE_SOURCE_HOST_PARAM];
43365
+ const submission = await queue.add(
43366
+ threadId2,
43367
+ input(),
43368
+ params.clientUserMessageId,
43369
+ typeof sourceHostId === "string" ? sourceHostId : void 0
43370
+ );
43371
+ result = { queuedSubmission: submission };
43372
+ break;
43373
+ }
43374
+ case "thread/queue/update": {
43375
+ const submission = await queue.update(threadId2, submissionId(), input());
43376
+ result = { queuedSubmission: submission };
43377
+ break;
43378
+ }
43379
+ case "thread/queue/delete":
43380
+ result = { deleted: await queue.delete(threadId2, submissionId()) };
43381
+ break;
43382
+ case "thread/queue/reorder": {
43383
+ const ids = params.queuedSubmissionIds;
43384
+ if (!Array.isArray(ids) || !ids.every((id2) => typeof id2 === "string"))
43385
+ throw new ExternalQueueError(-32602, "queuedSubmissionIds must be strings");
43386
+ await queue.reorder(threadId2, ids);
43387
+ result = {};
43388
+ break;
43389
+ }
43390
+ case "thread/queue/start": {
43391
+ const resolution = await this.#resolveExternalThread(threadId2);
43392
+ if (await this.#writeResolutionError(request, resolution)) return;
43393
+ if (resolution.kind !== "external")
43394
+ throw new ExternalQueueError(-32073, "External Thread is no longer available");
43395
+ const started = await this.#startQueuedSubmission(
43396
+ resolution.thread,
43397
+ params.queuedSubmissionId == null ? null : submissionId()
43398
+ );
43399
+ try {
43400
+ await this.#writer.json(rpcEnvelope(request, { result: { turn: started.turn } }));
43401
+ } finally {
43402
+ started.gate.resolve();
43403
+ }
43404
+ return;
43405
+ }
43406
+ default:
43407
+ throw new ExternalQueueError(
43408
+ -32076,
43409
+ `External Thread does not support ${request.method}`
43410
+ );
43411
+ }
43412
+ await this.#writer.json(rpcEnvelope(request, { result }));
43413
+ if (request.method === "thread/queue/add") {
43414
+ const thread = this.#externalRuntime.get(threadId2);
43415
+ const lastTurn = thread?.turns.at(-1);
43416
+ if (thread && thread.projectedTerminalTurnId === lastTurn?.id && lastTurn?.status === "completed" && isRecord19(thread.thread.status) && thread.thread.status.type === "idle") {
43417
+ void this.#drainExternalQueue(thread);
43418
+ }
43419
+ }
43420
+ } catch (error51) {
43421
+ await this.#writer.json(
43422
+ rpcError(
43423
+ request,
43424
+ error51 instanceof ExternalQueueError || error51 instanceof ExternalSteerError || error51 instanceof ExternalCommandError ? error51.code : -32602,
43425
+ errorMessage4(error51)
43426
+ )
43427
+ );
43428
+ }
43429
+ }
43430
+ /** Starts a queued follow-up as a Turn; it returns to its place when the start fails. */
43431
+ async #startQueuedSubmission(thread, submissionId) {
43432
+ if (this.#externalThreadBusy(thread) || this.#pendingExternalCommandRequests.has(thread.id))
43433
+ throw new ExternalSteerError(-32072, "External Thread already has an active Turn");
43434
+ const taken = this.#externalQueue.take(thread.id, submissionId);
43435
+ try {
43436
+ const started = await this.#beginExternalInputTurn(
43437
+ thread,
43438
+ requestText({ input: taken.submission.input }),
43439
+ void 0,
43440
+ taken.submission.clientUserMessageId,
43441
+ taken.sourceHostId,
43442
+ true
43443
+ );
43444
+ await this.#externalQueue.notifyChanged(thread.id);
43445
+ return started;
43446
+ } catch (error51) {
43447
+ this.#externalQueue.restore(thread.id, taken);
43448
+ await this.#externalQueue.notifyChanged(thread.id);
43449
+ throw error51;
43450
+ }
43451
+ }
43452
+ /** Desktop leaves queued follow-ups to the app-server once a Turn completes normally. */
43453
+ async #drainExternalQueue(thread) {
43454
+ if (!this.#externalQueue.has(thread.id) || this.#externalThreadBusy(thread) || this.#pendingExternalCommandRequests.has(thread.id))
43455
+ return;
43456
+ try {
43457
+ (await this.#startQueuedSubmission(thread)).gate.resolve();
43458
+ } catch (error51) {
43459
+ this.#diagnose(error51);
43460
+ }
43461
+ }
42472
43462
  async #steerExternalTurn(request, thread) {
42473
43463
  try {
42474
43464
  const started = await this.#externalSteering.run(
@@ -42533,12 +43523,12 @@ var AppServerHost = class {
42533
43523
  };
42534
43524
  }
42535
43525
  /** Keep command restoration and dispatch identical for start and steer submissions. */
42536
- async #beginExternalInputTurn(thread, inputText, assertActive, clientUserMessageId, sourceHostId) {
43526
+ async #beginExternalInputTurn(thread, inputText, assertActive, clientUserMessageId, sourceHostId, projectInput = false) {
42537
43527
  const text2 = restoreHarnessCommandMentions(inputText);
42538
43528
  const commands = thread.session.commands;
42539
43529
  if (!commands || !isExternalCommandCandidate(text2)) {
42540
43530
  assertActive?.();
42541
- return this.#beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId);
43531
+ return this.#beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId, projectInput);
42542
43532
  }
42543
43533
  this.#pendingExternalCommandRequests.add(thread.id);
42544
43534
  try {
@@ -42549,7 +43539,13 @@ var AppServerHost = class {
42549
43539
  assertActive?.();
42550
43540
  if (!command) {
42551
43541
  this.#pendingExternalCommandRequests.delete(thread.id);
42552
- return await this.#beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId);
43542
+ return await this.#beginExternalTurn(
43543
+ thread,
43544
+ text2,
43545
+ clientUserMessageId,
43546
+ sourceHostId,
43547
+ projectInput
43548
+ );
42553
43549
  }
42554
43550
  return await this.#beginExternalCommand(
42555
43551
  thread,
@@ -42582,14 +43578,18 @@ var AppServerHost = class {
42582
43578
  else this.#executionHosts.set(thread, previousHostId);
42583
43579
  };
42584
43580
  }
42585
- async #beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId) {
43581
+ /**
43582
+ * Desktop renders the input of its own `turn/start` locally. Other starts (Host-only clients
43583
+ * and queued follow-ups) need the user message projected with the Turn.
43584
+ */
43585
+ async #beginExternalTurn(thread, text2, clientUserMessageId, sourceHostId, projectInput = false) {
42586
43586
  if (this.#closeRequested || this.#externalRuntime.get(thread.id) !== thread) {
42587
43587
  throw new ExternalSteerError(-32073, "External Thread is no longer available");
42588
43588
  }
42589
43589
  if (thread.running || thread.activeTurnId || this.#pendingExternalCommandRequests.has(thread.id)) {
42590
43590
  throw new ExternalSteerError(-32072, "External Thread already has an active Turn");
42591
43591
  }
42592
- const turnId = hostTurnIdSchema.parse(randomUUID16());
43592
+ const turnId = hostTurnIdSchema.parse(randomUUID17());
42593
43593
  const startedAtMs = Date.now();
42594
43594
  const projection = {
42595
43595
  projector: new CodexTurnProjector({
@@ -42597,7 +43597,7 @@ var AppServerHost = class {
42597
43597
  turnId,
42598
43598
  cwd: thread.cwd,
42599
43599
  startedAtMs,
42600
- ...this.#options.externalOnly ? {
43600
+ ...this.#options.externalOnly || projectInput ? {
42601
43601
  initialInput: [{ type: "text", text: text2 }],
42602
43602
  ...clientUserMessageId ? { clientUserMessageId } : {}
42603
43603
  } : {}
@@ -42749,12 +43749,12 @@ var AppServerHost = class {
42749
43749
  try {
42750
43750
  for (const pending of [...this.#pendingDesktopApprovals.values()]) {
42751
43751
  if (pending.thread === thread && pending.interaction.turnId === turnId) {
42752
- await this.#resolveDesktopApproval(pending.interaction.interactionId);
43752
+ await this.#resolveDesktopApproval(pending.interaction.interactionId, pending.thread);
42753
43753
  }
42754
43754
  }
42755
43755
  for (const pending of [...this.#pendingDesktopQuestions.values()]) {
42756
43756
  if (pending.thread === thread && pending.interaction.turnId === turnId) {
42757
- await this.#resolveDesktopQuestion(pending.interaction.interactionId);
43757
+ await this.#resolveDesktopQuestion(pending.interaction.interactionId, pending.thread);
42758
43758
  }
42759
43759
  }
42760
43760
  await this.#writer.json({
@@ -42908,27 +43908,31 @@ var AppServerHost = class {
42908
43908
  }
42909
43909
  if (event.type === "subagent.transcript.changed") {
42910
43910
  const nativeSubagentId = event.nativeSubagentId;
42911
- const record4 = (await this.#repository.list()).find(
43911
+ const record5 = (await this.#repository.list()).find(
42912
43912
  (candidate) => candidate.subagent?.parentHostThreadId === thread.id && candidate.subagent.nativeSubagentId === nativeSubagentId && candidate.nativeSessionRef?.nativeSessionId === thread.record.nativeSessionRef?.nativeSessionId
42913
43913
  );
42914
- if (record4) await this.#refreshOpenSubagentThread(record4.hostThreadId, false);
43914
+ if (record5) await this.#refreshOpenSubagentThread(record5.hostThreadId, false);
42915
43915
  return;
42916
43916
  }
42917
43917
  if (event.type === "subagent.state.changed") {
42918
43918
  const nativeSubagentId = event.nativeSubagentId;
42919
- const record4 = (await this.#repository.list()).find(
43919
+ const record5 = (await this.#repository.list()).find(
42920
43920
  (candidate) => candidate.subagent?.parentHostThreadId === thread.id && candidate.subagent.nativeSubagentId === nativeSubagentId && candidate.nativeSessionRef?.nativeSessionId === thread.record.nativeSessionRef?.nativeSessionId
42921
43921
  );
42922
- if (!record4) return;
43922
+ if (!record5) return;
42923
43923
  const status2 = event.status === "pending" || event.status === "running" ? "active" : "idle";
42924
- this.#trackRunningSubagent(thread.id, record4.hostThreadId, status2);
42925
- await this.#setSubagentThreadStatus(record4.hostThreadId, status2);
43924
+ this.#trackRunningSubagent(thread.id, record5.hostThreadId, status2);
43925
+ await this.#setSubagentThreadStatus(record5.hostThreadId, status2);
42926
43926
  if (!thread.running && !thread.activeTurnId && !this.#hasRunningSubagents(thread.id)) {
42927
43927
  await this.#setThreadStatus(thread, { type: "idle" });
42928
43928
  }
42929
43929
  return;
42930
43930
  }
42931
43931
  if (event.type === "session.faulted") {
43932
+ for (const pending of [...this.#pendingDesktopQuestions.values()]) {
43933
+ if (pending.shared && pending.thread === thread)
43934
+ this.#retireDesktopQuestion(pending.interaction.interactionId, thread);
43935
+ }
42932
43936
  this.#externalSteering.fault(thread.id, new Error(event.error.message));
42933
43937
  thread.stateObserver.fault(new Error(event.error.message));
42934
43938
  this.#externalRuntime.markSessionUnavailable(thread);
@@ -42972,9 +43976,15 @@ var AppServerHost = class {
42972
43976
  if (event.type === "interaction.closed" && thread.ignoredInteractionIds.delete(event.interactionId)) {
42973
43977
  return;
42974
43978
  }
43979
+ if (event.type === "turn.completed") {
43980
+ for (const pending of [...this.#pendingDesktopQuestions.values()]) {
43981
+ if (pending.shared && pending.thread === thread && pending.interaction.turnId === event.turnId)
43982
+ this.#retireDesktopQuestion(pending.interaction.interactionId, thread);
43983
+ }
43984
+ }
42975
43985
  if (event.type === "interaction.closed") {
42976
- await this.#resolveDesktopApproval(event.interactionId);
42977
- await this.#resolveDesktopQuestion(event.interactionId);
43986
+ await this.#resolveDesktopApproval(event.interactionId, thread);
43987
+ await this.#resolveDesktopQuestion(event.interactionId, thread);
42978
43988
  }
42979
43989
  const ephemeralTurn = event.type === "turn.completed" && (event.ephemeral === true || thread.ephemeralTurnIds.has(event.turnId));
42980
43990
  if (event.type === "turn.completed" && !ephemeralTurn) {
@@ -43040,32 +44050,35 @@ var AppServerHost = class {
43040
44050
  this.#hasRunningSubagents(thread.id) ? { type: "active", activeFlags: [] } : { type: "idle" }
43041
44051
  );
43042
44052
  this.#externalSteering.terminal(thread.id, event.turnId, event.outcome);
44053
+ if (!ephemeralTurn && result.completedTurn?.status === "completed" && this.#externalQueue.has(thread.id)) {
44054
+ void this.#drainExternalQueue(thread);
44055
+ }
43043
44056
  }
43044
44057
  }
43045
44058
  async #materializeSubagent(parent, subagent) {
43046
44059
  if (!subagent.nativeSubagentId || !parent.record.nativeSessionRef) return subagent;
43047
44060
  const status2 = subagent.status === "pending" || subagent.status === "running" ? "active" : "idle";
43048
- const record4 = await this.#repository.materializeSubagent(parent.record, subagent);
43049
- if (!record4) return subagent;
43050
- if (this.#subagentThreadStatuses.has(record4.hostThreadId)) {
43051
- this.#trackRunningSubagent(parent.id, record4.hostThreadId, status2);
43052
- await this.#setSubagentThreadStatus(record4.hostThreadId, status2);
43053
- return { ...subagent, subagentId: record4.hostThreadId };
44061
+ const record5 = await this.#repository.materializeSubagent(parent.record, subagent);
44062
+ if (!record5) return subagent;
44063
+ if (this.#subagentThreadStatuses.has(record5.hostThreadId)) {
44064
+ this.#trackRunningSubagent(parent.id, record5.hostThreadId, status2);
44065
+ await this.#setSubagentThreadStatus(record5.hostThreadId, status2);
44066
+ return { ...subagent, subagentId: record5.hostThreadId };
43054
44067
  }
43055
44068
  const thread = externalThreadValue({
43056
- record: record4,
44069
+ record: record5,
43057
44070
  turns: [],
43058
44071
  sessionId: parent.sessionId,
43059
44072
  running: status2 === "active"
43060
44073
  });
43061
- this.#subagentThreadStatuses.set(record4.hostThreadId, status2);
43062
- this.#trackRunningSubagent(parent.id, record4.hostThreadId, status2);
44074
+ this.#subagentThreadStatuses.set(record5.hostThreadId, status2);
44075
+ this.#trackRunningSubagent(parent.id, record5.hostThreadId, status2);
43063
44076
  await this.#writer.json({
43064
44077
  method: "thread/started",
43065
44078
  emittedAtMs: Date.now(),
43066
44079
  params: { thread }
43067
44080
  });
43068
- return { ...subagent, subagentId: record4.hostThreadId };
44081
+ return { ...subagent, subagentId: record5.hostThreadId };
43069
44082
  }
43070
44083
  async #refreshOpenSubagentThread(threadId2, terminal3 = true) {
43071
44084
  await this.#desktopRequests.run(threadId2, async () => {
@@ -43231,7 +44244,7 @@ var AppServerHost = class {
43231
44244
  if (this.#externalRuntime.get(pending.thread.id) !== pending.thread || this.#externalRuntime.idleRelease.failure(pending.thread))
43232
44245
  return true;
43233
44246
  if (this.#options.externalOnly)
43234
- await this.#resolveDesktopApproval(pending.interaction.interactionId);
44247
+ await this.#resolveDesktopApproval(pending.interaction.interactionId, pending.thread);
43235
44248
  else this.#pendingDesktopApprovals.delete(requestId);
43236
44249
  let response;
43237
44250
  try {
@@ -43282,9 +44295,20 @@ var AppServerHost = class {
43282
44295
  }
43283
44296
  return denied.ok;
43284
44297
  }
43285
- async #resolveDesktopApproval(interactionId) {
44298
+ async #resolveThreadInteractions(thread) {
44299
+ for (const pending of [...this.#pendingDesktopApprovals.values()]) {
44300
+ if (pending.thread === thread)
44301
+ await this.#resolveDesktopApproval(pending.interaction.interactionId, thread);
44302
+ }
44303
+ for (const pending of [...this.#pendingDesktopQuestions.values()]) {
44304
+ if (pending.thread === thread)
44305
+ await this.#resolveDesktopQuestion(pending.interaction.interactionId, thread);
44306
+ }
44307
+ }
44308
+ async #resolveDesktopApproval(interactionId, thread) {
43286
44309
  for (const [requestId, pending] of this.#pendingDesktopApprovals) {
43287
- if (pending.interaction.interactionId !== interactionId) continue;
44310
+ if (pending.thread !== thread || pending.interaction.interactionId !== interactionId)
44311
+ continue;
43288
44312
  this.#pendingDesktopApprovals.delete(requestId);
43289
44313
  await this.#writer.json({
43290
44314
  method: "serverRequest/resolved",
@@ -43300,14 +44324,75 @@ var AppServerHost = class {
43300
44324
  this.#nextApprovalRequestId -= 1;
43301
44325
  return requestId;
43302
44326
  }
44327
+ async #handleSharedQuestionRequest(request) {
44328
+ const responding = request.method === THREAD_QUESTION_RESPOND_METHOD;
44329
+ const parsed2 = (responding ? threadQuestionRespondParamsSchema : threadQuestionsListParamsSchema).safeParse(request.params);
44330
+ if (!parsed2.success) {
44331
+ await this.#writer.json(rpcError(request, -32602, "Invalid Question params"));
44332
+ return;
44333
+ }
44334
+ const { threadId: threadId2 } = parsed2.data;
44335
+ const thread = this.#externalRuntime.get(threadId2);
44336
+ const pendingQuestions = () => [...this.#pendingDesktopQuestions.values()].filter(
44337
+ (pending) => pending.shared && pending.thread === thread && pending.interaction.turnId === thread?.activeTurnId && (!Number.isFinite(Date.parse(pending.interaction.expiresAt ?? "")) || Date.parse(pending.interaction.expiresAt ?? "") > Date.now())
44338
+ );
44339
+ if (!responding) {
44340
+ const questions = thread && !thread.sessionUnavailable && !this.#externalRuntime.idleRelease.failure(thread) ? pendingQuestions().map((pending) => sharedQuestion(pending.interaction)) : [];
44341
+ await this.#writer.json(
44342
+ rpcEnvelope(request, { result: jsonValueSchema.parse({ questions }) })
44343
+ );
44344
+ return;
44345
+ }
44346
+ const params = threadQuestionRespondParamsSchema.parse(parsed2.data);
44347
+ try {
44348
+ await this.#externalRuntime.idleRelease.runOperation(threadId2, async () => {
44349
+ const pending = pendingQuestions().find(
44350
+ ({ interaction }) => interaction.interactionId === params.interactionId && interaction.turnId === params.turnId
44351
+ );
44352
+ if (!thread || this.#externalRuntime.get(threadId2) !== thread || thread.sessionUnavailable || this.#externalRuntime.idleRelease.failure(thread) || !pending || pending.responding) {
44353
+ throw new Error("Question is no longer pending on this Thread and Turn");
44354
+ }
44355
+ const response = {
44356
+ type: "question",
44357
+ answers: params.answers,
44358
+ cancelled: params.cancelled
44359
+ };
44360
+ validateSharedQuestionResponse(pending.interaction, response);
44361
+ pending.responding = true;
44362
+ let result;
44363
+ try {
44364
+ result = await thread.session.execute({
44365
+ type: "interaction.respond",
44366
+ interactionId: pending.interaction.interactionId,
44367
+ response
44368
+ });
44369
+ } catch (error51) {
44370
+ this.#retireDesktopQuestion(pending.interaction.interactionId, thread);
44371
+ throw error51;
44372
+ }
44373
+ if (!result.ok) {
44374
+ pending.responding = false;
44375
+ if (result.error.code === "invalidState")
44376
+ this.#retireDesktopQuestion(pending.interaction.interactionId, thread);
44377
+ throw new Error(result.error.message);
44378
+ }
44379
+ this.#retireDesktopQuestion(pending.interaction.interactionId, thread);
44380
+ await this.#writer.json(rpcEnvelope(request, { result: { accepted: true } }));
44381
+ });
44382
+ } catch (error51) {
44383
+ await this.#writer.json(rpcError(request, -32602, errorMessage4(error51)));
44384
+ }
44385
+ }
43303
44386
  async #projectQuestion(thread, interaction) {
43304
44387
  const projection = this.#projectedTurn(thread, interaction.turnId);
43305
44388
  await this.#waitForTurnResponse(thread, interaction.turnId);
43306
44389
  let result;
44390
+ const shared = usesSharedQuestionCard(interaction);
43307
44391
  try {
44392
+ if (shared) sharedQuestion(interaction);
43308
44393
  result = projection.projector.projectQuestion(
43309
44394
  interaction,
43310
- hostItemIdSchema.parse(randomUUID16())
44395
+ hostItemIdSchema.parse(randomUUID17())
43311
44396
  );
43312
44397
  } catch (error51) {
43313
44398
  this.#diagnose(error51);
@@ -43328,6 +44413,8 @@ var AppServerHost = class {
43328
44413
  const expiresAtMs = interaction.expiresAt ? Date.parse(interaction.expiresAt) : Number.NaN;
43329
44414
  const timeoutMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - Date.now()) : null;
43330
44415
  const pending = {
44416
+ shared,
44417
+ responding: false,
43331
44418
  thread,
43332
44419
  interaction,
43333
44420
  projection: result.questionRequest,
@@ -43339,10 +44426,11 @@ var AppServerHost = class {
43339
44426
  }, timeoutMs);
43340
44427
  }
43341
44428
  this.#pendingDesktopQuestions.set(requestId, pending);
44429
+ if (shared) return;
43342
44430
  try {
43343
44431
  await this.#writer.json({ id: requestId, ...result.questionRequest.request });
43344
44432
  } catch (error51) {
43345
- this.#retireDesktopQuestion(interaction.interactionId);
44433
+ this.#retireDesktopQuestion(interaction.interactionId, thread);
43346
44434
  await thread.session.execute({
43347
44435
  type: "interaction.respond",
43348
44436
  interactionId: interaction.interactionId,
@@ -43355,12 +44443,12 @@ var AppServerHost = class {
43355
44443
  if (!isRecord19(value2) || !isHostQuestionRequestId(value2.id)) return false;
43356
44444
  const requestId = value2.id;
43357
44445
  const pending = this.#pendingDesktopQuestions.get(requestId);
43358
- if (!pending) return true;
44446
+ if (!pending || pending.shared) return true;
43359
44447
  return this.#externalRuntime.idleRelease.runOperation(pending.thread.id, async () => {
43360
44448
  if (this.#externalRuntime.get(pending.thread.id) !== pending.thread || this.#externalRuntime.idleRelease.failure(pending.thread))
43361
44449
  return true;
43362
44450
  if (this.#options.externalOnly)
43363
- await this.#resolveDesktopQuestion(pending.interaction.interactionId);
44451
+ await this.#resolveDesktopQuestion(pending.interaction.interactionId, pending.thread);
43364
44452
  else this.#pendingDesktopQuestions.delete(requestId);
43365
44453
  if (pending.timeout) clearTimeout(pending.timeout);
43366
44454
  let response;
@@ -43387,7 +44475,8 @@ var AppServerHost = class {
43387
44475
  await this.#externalRuntime.idleRelease.runOperation(pending.thread.id, async () => {
43388
44476
  if (this.#externalRuntime.get(pending.thread.id) !== pending.thread || this.#externalRuntime.idleRelease.failure(pending.thread))
43389
44477
  return;
43390
- await this.#resolveDesktopQuestion(pending.interaction.interactionId);
44478
+ await this.#resolveDesktopQuestion(pending.interaction.interactionId, pending.thread);
44479
+ if (pending.responding) return;
43391
44480
  const result = await pending.thread.session.execute({
43392
44481
  type: "interaction.respond",
43393
44482
  interactionId: pending.interaction.interactionId,
@@ -43398,18 +44487,21 @@ var AppServerHost = class {
43398
44487
  }
43399
44488
  });
43400
44489
  }
43401
- #retireDesktopQuestion(interactionId) {
44490
+ #retireDesktopQuestion(interactionId, thread) {
43402
44491
  for (const [requestId, pending] of this.#pendingDesktopQuestions) {
43403
- if (pending.interaction.interactionId !== interactionId) continue;
44492
+ if (pending.thread !== thread || pending.interaction.interactionId !== interactionId)
44493
+ continue;
43404
44494
  if (pending.timeout) clearTimeout(pending.timeout);
43405
44495
  this.#pendingDesktopQuestions.delete(requestId);
43406
44496
  }
43407
44497
  }
43408
- async #resolveDesktopQuestion(interactionId) {
44498
+ async #resolveDesktopQuestion(interactionId, thread) {
43409
44499
  for (const [requestId, pending] of this.#pendingDesktopQuestions) {
43410
- if (pending.interaction.interactionId !== interactionId) continue;
44500
+ if (pending.thread !== thread || pending.interaction.interactionId !== interactionId)
44501
+ continue;
43411
44502
  if (pending.timeout) clearTimeout(pending.timeout);
43412
44503
  this.#pendingDesktopQuestions.delete(requestId);
44504
+ if (pending.shared) continue;
43413
44505
  await this.#writer.json({
43414
44506
  method: "serverRequest/resolved",
43415
44507
  params: { threadId: pending.thread.id, requestId }
@@ -43546,7 +44638,7 @@ var import_websocket_server = __toESM(require_websocket_server(), 1);
43546
44638
  var wrapper_default = import_websocket.default;
43547
44639
 
43548
44640
  // packages/host-runtime/src/remote-socket-lock.ts
43549
- import { randomUUID as randomUUID17 } from "node:crypto";
44641
+ import { randomUUID as randomUUID18 } from "node:crypto";
43550
44642
  import { chmod as chmod3, lstat as lstat5, mkdir as mkdir12, open as open9, readFile as readFile17, readdir as readdir5, rename as rename11, rm as rm11 } from "node:fs/promises";
43551
44643
  import { uptime } from "node:os";
43552
44644
  import path27 from "node:path";
@@ -43560,18 +44652,18 @@ var LOCK_ENTRY_SUFFIX = ".json";
43560
44652
  function currentBootTimeSeconds() {
43561
44653
  return Math.round(Date.now() / 1e3 - uptime());
43562
44654
  }
43563
- function validOwnerFields(record4) {
43564
- return typeof record4.ownerToken === "string" && record4.ownerToken.length > 0 && typeof record4.pid === "number" && Number.isSafeInteger(record4.pid) && record4.pid > 0 && typeof record4.bootTimeSeconds === "number" && Number.isSafeInteger(record4.bootTimeSeconds);
44655
+ function validOwnerFields(record5) {
44656
+ return typeof record5.ownerToken === "string" && record5.ownerToken.length > 0 && typeof record5.pid === "number" && Number.isSafeInteger(record5.pid) && record5.pid > 0 && typeof record5.bootTimeSeconds === "number" && Number.isSafeInteger(record5.bootTimeSeconds);
43565
44657
  }
43566
44658
  function parseLockRecord(source) {
43567
44659
  try {
43568
44660
  const value2 = JSON.parse(source);
43569
44661
  if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) return null;
43570
- const record4 = value2;
43571
- if (record4.version !== 2 || !validOwnerFields(record4) || typeof record4.choosing !== "boolean" || typeof record4.ticket !== "number" || !Number.isSafeInteger(record4.ticket) || record4.ticket < 0 || (record4.choosing ? record4.ticket !== 0 : record4.ticket === 0)) {
44662
+ const record5 = value2;
44663
+ if (record5.version !== 2 || !validOwnerFields(record5) || typeof record5.choosing !== "boolean" || typeof record5.ticket !== "number" || !Number.isSafeInteger(record5.ticket) || record5.ticket < 0 || (record5.choosing ? record5.ticket !== 0 : record5.ticket === 0)) {
43572
44664
  return null;
43573
44665
  }
43574
- return record4;
44666
+ return record5;
43575
44667
  } catch {
43576
44668
  return null;
43577
44669
  }
@@ -43580,9 +44672,9 @@ function parseLegacyLockRecord(source) {
43580
44672
  try {
43581
44673
  const value2 = JSON.parse(source);
43582
44674
  if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) return null;
43583
- const record4 = value2;
43584
- if (record4.version !== 1 || !validOwnerFields(record4)) return null;
43585
- return record4;
44675
+ const record5 = value2;
44676
+ if (record5.version !== 1 || !validOwnerFields(record5)) return null;
44677
+ return record5;
43586
44678
  } catch {
43587
44679
  return null;
43588
44680
  }
@@ -43595,10 +44687,10 @@ function processIsRunning(pid) {
43595
44687
  return error51.code !== "ESRCH";
43596
44688
  }
43597
44689
  }
43598
- function ownerIsAbandoned(record4, mtimeMs) {
43599
- if (Math.abs(record4.bootTimeSeconds - currentBootTimeSeconds()) > 5) return true;
44690
+ function ownerIsAbandoned(record5, mtimeMs) {
44691
+ if (Math.abs(record5.bootTimeSeconds - currentBootTimeSeconds()) > 5) return true;
43600
44692
  if (Math.max(0, Date.now() - mtimeMs) >= LOCK_MAX_AGE_MS) return true;
43601
- return !processIsRunning(record4.pid);
44693
+ return !processIsRunning(record5.pid);
43602
44694
  }
43603
44695
  function sameUnixFileIdentity(left, right) {
43604
44696
  return left.dev === right.dev && left.ino === right.ino;
@@ -43617,13 +44709,13 @@ async function readLockEntrySnapshot(filePath) {
43617
44709
  throw error51;
43618
44710
  });
43619
44711
  if (source === null) return null;
43620
- const record4 = parseLockRecord(source);
44712
+ const record5 = parseLockRecord(source);
43621
44713
  return {
43622
44714
  filePath,
43623
44715
  source,
43624
44716
  identity: { dev: metadata.dev, ino: metadata.ino },
43625
44717
  mtimeMs: metadata.mtimeMs,
43626
- record: record4 && path27.basename(filePath) === lockEntryName(record4.ownerToken) ? record4 : null
44718
+ record: record5 && path27.basename(filePath) === lockEntryName(record5.ownerToken) ? record5 : null
43627
44719
  };
43628
44720
  }
43629
44721
  function lockEntryIsAbandoned(snapshot2) {
@@ -43671,11 +44763,11 @@ async function preparePrivateLockDirectory(lockDirectory) {
43671
44763
  }
43672
44764
  await chmod3(lockDirectory, 448);
43673
44765
  }
43674
- async function writeLockRecordAtomic(lockDirectory, entryPath, record4) {
43675
- const temporary = path27.join(lockDirectory, `.tmp-${record4.ownerToken}-${randomUUID17()}`);
44766
+ async function writeLockRecordAtomic(lockDirectory, entryPath, record5) {
44767
+ const temporary = path27.join(lockDirectory, `.tmp-${record5.ownerToken}-${randomUUID18()}`);
43676
44768
  const handle = await open9(temporary, "wx", 384);
43677
44769
  try {
43678
- await handle.writeFile(`${JSON.stringify(record4)}
44770
+ await handle.writeFile(`${JSON.stringify(record5)}
43679
44771
  `, "utf8");
43680
44772
  await handle.sync();
43681
44773
  } finally {
@@ -43705,11 +44797,11 @@ async function legacyLockState(legacyPath) {
43705
44797
  });
43706
44798
  if (source === null) return "absent";
43707
44799
  const ageMs = Math.max(0, Date.now() - metadata.mtimeMs);
43708
- const record4 = parseLegacyLockRecord(source);
43709
- if (record4 === null) return ageMs < LOCK_MALFORMED_GRACE_MS ? "blocking" : "abandoned";
43710
- return ownerIsAbandoned(record4, metadata.mtimeMs) ? "abandoned" : "blocking";
44800
+ const record5 = parseLegacyLockRecord(source);
44801
+ if (record5 === null) return ageMs < LOCK_MALFORMED_GRACE_MS ? "blocking" : "abandoned";
44802
+ return ownerIsAbandoned(record5, metadata.mtimeMs) ? "abandoned" : "blocking";
43711
44803
  }
43712
- async function tryAcquireLegacyCompatibilityGuard(legacyPath, record4) {
44804
+ async function tryAcquireLegacyCompatibilityGuard(legacyPath, record5) {
43713
44805
  const handle = await open9(legacyPath, "wx", 384).catch((error51) => {
43714
44806
  if (error51.code === "EEXIST") return null;
43715
44807
  throw error51;
@@ -43718,7 +44810,7 @@ async function tryAcquireLegacyCompatibilityGuard(legacyPath, record4) {
43718
44810
  const metadata = await handle.stat();
43719
44811
  const guard = { handle, identity: { dev: metadata.dev, ino: metadata.ino } };
43720
44812
  try {
43721
- await handle.writeFile(`${JSON.stringify(record4)}
44813
+ await handle.writeFile(`${JSON.stringify(record5)}
43722
44814
  `, "utf8");
43723
44815
  await handle.sync();
43724
44816
  return guard;
@@ -43747,7 +44839,7 @@ async function withRemoteAppServerSocketInitializationLock(socketPath, action) {
43747
44839
  const legacyPath = `${socketPath}.initializing`;
43748
44840
  const lockDirectory = `${socketPath}.initializers`;
43749
44841
  await preparePrivateLockDirectory(lockDirectory);
43750
- const ownerToken = randomUUID17();
44842
+ const ownerToken = randomUUID18();
43751
44843
  const entryPath = path27.join(lockDirectory, lockEntryName(ownerToken));
43752
44844
  const baseRecord = {
43753
44845
  version: 2,
@@ -43784,8 +44876,8 @@ async function withRemoteAppServerSocketInitializationLock(socketPath, action) {
43784
44876
  throw new Error(`Remote app-server socket lock ownership was lost at ${socketPath}`);
43785
44877
  }
43786
44878
  const blockedByBakery = catalog.entries.some((entry) => {
43787
- const record4 = entry.record;
43788
- return record4 !== null && record4.ownerToken !== ownerToken && (record4.choosing || recordHasPriority(record4, ownRecord));
44879
+ const record5 = entry.record;
44880
+ return record5 !== null && record5.ownerToken !== ownerToken && (record5.choosing || recordHasPriority(record5, ownRecord));
43789
44881
  });
43790
44882
  if (!catalog.unsettled && !blockedByBakery) {
43791
44883
  const legacyGuard = await tryAcquireLegacyCompatibilityGuard(legacyPath, {
@@ -44258,12 +45350,12 @@ function createRemoteAppServerWebSocketListener(input) {
44258
45350
 
44259
45351
  // packages/host-runtime/src/remote-official-app-server.ts
44260
45352
  import { spawn as spawn5 } from "node:child_process";
44261
- import { randomUUID as randomUUID18 } from "node:crypto";
45353
+ import { randomUUID as randomUUID19 } from "node:crypto";
44262
45354
  import { lstat as lstat7, rm as rm13, stat as stat7 } from "node:fs/promises";
44263
45355
  import path29 from "node:path";
44264
45356
  var DEFAULT_CLOSE_TIMEOUT_MS = 2e3;
44265
45357
  var DEFAULT_LISTEN_TIMEOUT_MS = 1e4;
44266
- function remoteOfficialAppServerSocketPath(desktopControlSocketPath, token = randomUUID18()) {
45358
+ function remoteOfficialAppServerSocketPath(desktopControlSocketPath, token = randomUUID19()) {
44267
45359
  if (!path29.posix.isAbsolute(desktopControlSocketPath)) {
44268
45360
  throw new Error("Desktop control socket path must be absolute");
44269
45361
  }
@@ -45189,10 +46281,10 @@ var DelegationControlRegistry = class {
45189
46281
  );
45190
46282
  }
45191
46283
  #compareThreads(left, right, sort) {
45192
- const field = sort.startsWith("created") ? "createdAt" : "updatedAt";
46284
+ const field2 = sort.startsWith("created") ? "createdAt" : "updatedAt";
45193
46285
  const direction = sort.endsWith("asc") ? 1 : -1;
45194
- const leftValue = left[field] ? Date.parse(left[field]) : 0;
45195
- const rightValue = right[field] ? Date.parse(right[field]) : 0;
46286
+ const leftValue = left[field2] ? Date.parse(left[field2]) : 0;
46287
+ const rightValue = right[field2] ? Date.parse(right[field2]) : 0;
45196
46288
  return (leftValue - rightValue) * direction || left.threadId.localeCompare(right.threadId);
45197
46289
  }
45198
46290
  async #matching(predicate) {
@@ -45323,6 +46415,17 @@ function installedHarnessPluginOptions(environment, managedRemoteHost = false, h
45323
46415
 
45324
46416
  // packages/host-runtime/src/delegation-control-server.ts
45325
46417
  import { createServer as createServer3 } from "node:http";
46418
+
46419
+ // packages/host-runtime/src/bearer-token.ts
46420
+ import { timingSafeEqual } from "node:crypto";
46421
+ function matchesBearerToken(header, token) {
46422
+ if (!header?.startsWith("Bearer ")) return false;
46423
+ const candidate = Buffer.from(header.slice("Bearer ".length));
46424
+ const expected = Buffer.from(token);
46425
+ return candidate.length === expected.length && timingSafeEqual(candidate, expected);
46426
+ }
46427
+
46428
+ // packages/host-runtime/src/delegation-control-server.ts
45326
46429
  var MAX_REQUEST_BYTES2 = 2 * 1024 * 1024;
45327
46430
  function errorBody(error51) {
45328
46431
  if (error51 instanceof DelegationControlError) {
@@ -45400,7 +46503,7 @@ async function startDelegationControlServer(input) {
45400
46503
  });
45401
46504
  return;
45402
46505
  }
45403
- if (request.headers.authorization !== `Bearer ${input.token}`) {
46506
+ if (!matchesBearerToken(request.headers.authorization, input.token)) {
45404
46507
  writeJson2(response, 401, {
45405
46508
  error: { code: "RUNTIME_UNREACHABLE", message: "Runtime token is invalid" }
45406
46509
  });
@@ -45514,11 +46617,11 @@ async function readRemoteDelegationThread(environment, input) {
45514
46617
  }
45515
46618
 
45516
46619
  // packages/host-runtime/src/shared-thread-owner.ts
45517
- import { randomUUID as randomUUID20 } from "node:crypto";
46620
+ import { randomUUID as randomUUID21 } from "node:crypto";
45518
46621
  import { PassThrough as PassThrough3 } from "node:stream";
45519
46622
 
45520
46623
  // packages/host-runtime/src/shared-thread-peer.ts
45521
- import { randomUUID as randomUUID19 } from "node:crypto";
46624
+ import { randomUUID as randomUUID20 } from "node:crypto";
45522
46625
  function object5(value2) {
45523
46626
  return value2 !== null && typeof value2 === "object" && !Array.isArray(value2);
45524
46627
  }
@@ -45532,7 +46635,7 @@ var StreamThreadPeer = class {
45532
46635
  input;
45533
46636
  output;
45534
46637
  stop;
45535
- #prefix = `shared:${randomUUID19()}:`;
46638
+ #prefix = `shared:${randomUUID20()}:`;
45536
46639
  #pending = /* @__PURE__ */ new Map();
45537
46640
  #listeners = /* @__PURE__ */ new Set();
45538
46641
  #ended = Promise.withResolvers();
@@ -45610,7 +46713,7 @@ var SharedThreadOwner = class {
45610
46713
  input = new PassThrough3();
45611
46714
  output = new PassThrough3();
45612
46715
  #peer = new StreamThreadPeer(this.output, this.input, () => this.input.end());
45613
- #prefix = `shared-interaction:${randomUUID20()}:`;
46716
+ #prefix = `shared-interaction:${randomUUID21()}:`;
45614
46717
  #interactions = /* @__PURE__ */ new Map();
45615
46718
  #listeners = /* @__PURE__ */ new Set();
45616
46719
  #receipts = /* @__PURE__ */ new Map();
@@ -45920,7 +47023,7 @@ var SharedThreadBridge = class {
45920
47023
  };
45921
47024
 
45922
47025
  // packages/host-runtime/src/remote-control-app-server.ts
45923
- import { randomUUID as randomUUID21 } from "node:crypto";
47026
+ import { randomUUID as randomUUID22 } from "node:crypto";
45924
47027
  import { mkdir as mkdir15, open as open10, rename as rename12, rm as rm14 } from "node:fs/promises";
45925
47028
  import path34 from "node:path";
45926
47029
  var REMOTE_CONTROL_BRIDGE_PIPE_ENV = "CODEXHOST_REMOTE_CONTROL_BRIDGE_PIPE";
@@ -45941,7 +47044,7 @@ function nodeCompatibleWindowsPath(value2) {
45941
47044
  if (value2.startsWith("\\\\?\\")) return value2.slice(4);
45942
47045
  return value2;
45943
47046
  }
45944
- function remoteControlBridgePipePath(processId = process.pid, instanceId = randomUUID21()) {
47047
+ function remoteControlBridgePipePath(processId = process.pid, instanceId = randomUUID22()) {
45945
47048
  const safeInstance = instanceId.replaceAll(/[^a-zA-Z0-9-]/gu, "");
45946
47049
  if (!safeInstance) throw new Error("Remote Control bridge instance ID is invalid");
45947
47050
  return `\\\\.\\pipe\\codexhost-remote-control-${processId}-${safeInstance}`;
@@ -45956,7 +47059,7 @@ async function publishRemoteControlAppServerDescriptor(plan) {
45956
47059
  await mkdir15(directory, { recursive: true, mode: 448 });
45957
47060
  const temporaryPath = path34.join(
45958
47061
  directory,
45959
- `.${REMOTE_CONTROL_BRIDGE_DESCRIPTOR_FILE}.${plan.descriptor.ownerPid}.${randomUUID21()}.tmp`
47062
+ `.${REMOTE_CONTROL_BRIDGE_DESCRIPTOR_FILE}.${plan.descriptor.ownerPid}.${randomUUID22()}.tmp`
45960
47063
  );
45961
47064
  const handle = await open10(temporaryPath, "wx", 384);
45962
47065
  try {
@@ -46080,7 +47183,7 @@ function watchRemoteListenerSupervisor(options2) {
46080
47183
  }
46081
47184
 
46082
47185
  // packages/host-runtime/src/console-control-server.ts
46083
- import { randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
47186
+ import { randomBytes as randomBytes3 } from "node:crypto";
46084
47187
  import { mkdir as mkdir16, rename as rename13, rm as rm15, writeFile as writeFile9 } from "node:fs/promises";
46085
47188
  import { createServer as createServer4 } from "node:http";
46086
47189
  import os10 from "node:os";
@@ -46091,12 +47194,6 @@ function consoleHostDescriptorDirectory(environment) {
46091
47194
  const dataDirectory = environment.CODEXHOST_DATA_DIR ? path35.resolve(environment.CODEXHOST_DATA_DIR) : path35.join(os10.homedir(), ".codexhost");
46092
47195
  return path35.join(dataDirectory, CONSOLE_HOST_DESCRIPTOR_DIRECTORY);
46093
47196
  }
46094
- function equalToken(candidate, token) {
46095
- if (!candidate?.startsWith("Bearer ")) return false;
46096
- const left = Buffer.from(candidate.slice("Bearer ".length));
46097
- const right = Buffer.from(token);
46098
- return left.length === right.length && timingSafeEqual(left, right);
46099
- }
46100
47197
  async function readBody(request) {
46101
47198
  let size = 0;
46102
47199
  const chunks = [];
@@ -46138,7 +47235,7 @@ async function startConsoleControlServer(options2) {
46138
47235
  reply(response, 404, { error: { code: -32601, message: "Not found" } });
46139
47236
  return;
46140
47237
  }
46141
- if (!equalToken(request.headers.authorization, token)) {
47238
+ if (!matchesBearerToken(request.headers.authorization, token)) {
46142
47239
  reply(response, 401, { error: { code: -32001, message: "Unauthorized" } });
46143
47240
  return;
46144
47241
  }
@@ -46149,12 +47246,12 @@ async function startConsoleControlServer(options2) {
46149
47246
  reply(response, 400, { error: { code: -32700, message: "Invalid request body" } });
46150
47247
  return;
46151
47248
  }
46152
- const record4 = typeof body === "object" && body !== null ? body : {};
46153
- if (typeof record4.method !== "string") {
47249
+ const record5 = typeof body === "object" && body !== null ? body : {};
47250
+ if (typeof record5.method !== "string") {
46154
47251
  reply(response, 400, { error: { code: -32600, message: "method is required" } });
46155
47252
  return;
46156
47253
  }
46157
- reply(response, 200, await options2.target.handleConsoleRequest(record4.method, record4.params));
47254
+ reply(response, 200, await options2.target.handleConsoleRequest(record5.method, record5.params));
46158
47255
  })().catch((error51) => {
46159
47256
  if (!response.headersSent) {
46160
47257
  reply(response, 500, {
@@ -46449,7 +47546,7 @@ function createHostUpdateCoordinator(options2) {
46449
47546
  onPrepared
46450
47547
  });
46451
47548
  }
46452
- if (platform !== "darwin") await manager.start(prepared2);
47549
+ if (platform !== "darwin" && platform !== "win32") await manager.start(prepared2);
46453
47550
  } catch (error51) {
46454
47551
  await lock.release();
46455
47552
  rejectPrepared(error51);
@@ -46478,7 +47575,7 @@ function createHostUpdateCoordinator(options2) {
46478
47575
  }
46479
47576
 
46480
47577
  // packages/host-runtime/src/usage-statistics.ts
46481
- import { randomUUID as randomUUID22 } from "node:crypto";
47578
+ import { randomUUID as randomUUID23 } from "node:crypto";
46482
47579
  import { mkdir as mkdir17, readFile as readFile18, readdir as readdir6, rename as rename14, rm as rm16, writeFile as writeFile10 } from "node:fs/promises";
46483
47580
  import path37 from "node:path";
46484
47581
  import { setImmediate as yieldToEventLoop } from "node:timers/promises";
@@ -46532,13 +47629,13 @@ function parseHarnessUsageEntry(value2) {
46532
47629
  }
46533
47630
  if (!tokenCount(entry.inputTokens) || !tokenCount(entry.outputTokens))
46534
47631
  return null;
46535
- for (const field of [
47632
+ for (const field2 of [
46536
47633
  "cachedInputTokens",
46537
47634
  "cacheWriteInputTokens",
46538
47635
  "cacheWrite1hInputTokens",
46539
47636
  "reasoningOutputTokens"
46540
47637
  ]) {
46541
- if (entry[field] !== void 0 && !tokenCount(entry[field]))
47638
+ if (entry[field2] !== void 0 && !tokenCount(entry[field2]))
46542
47639
  return null;
46543
47640
  }
46544
47641
  const cached2 = entry.cachedInputTokens ?? 0;
@@ -46573,14 +47670,14 @@ function parseHarnessUsageEntry(value2) {
46573
47670
  // packages/host-runtime/src/usage-session-titles.ts
46574
47671
  function withHostSessionTitles(result, records) {
46575
47672
  const titles = /* @__PURE__ */ new Map();
46576
- for (const record4 of records) {
46577
- const ref = record4.nativeSessionRef;
46578
- const title = usageSessionTitle(record4.title);
46579
- if (record4.state !== "ready" || !ref || ref.harnessId !== record4.harnessId || !title) continue;
46580
- const key = `${record4.harnessId}\0${ref.nativeSessionId}`;
47673
+ for (const record5 of records) {
47674
+ const ref = record5.nativeSessionRef;
47675
+ const title = usageSessionTitle(record5.title);
47676
+ if (record5.state !== "ready" || !ref || ref.harnessId !== record5.harnessId || !title) continue;
47677
+ const key = `${record5.harnessId}\0${ref.nativeSessionId}`;
46581
47678
  const previous = titles.get(key);
46582
- if (!previous || record4.updatedAt > previous.updatedAt)
46583
- titles.set(key, { title, updatedAt: record4.updatedAt });
47679
+ if (!previous || record5.updatedAt > previous.updatedAt)
47680
+ titles.set(key, { title, updatedAt: record5.updatedAt });
46584
47681
  }
46585
47682
  const decorate = (sessions) => sessions.map((session) => {
46586
47683
  const title = titles.get(`${session.harness}\0${session.sessionId}`)?.title;
@@ -46751,6 +47848,8 @@ function emptyTotals() {
46751
47848
  cachedInputTokens: 0,
46752
47849
  cacheWriteInputTokens: 0,
46753
47850
  cacheKnownInputTokens: 0,
47851
+ cacheHitCachedInputTokens: 0,
47852
+ cacheHitInputTokens: 0,
46754
47853
  outputTokens: 0,
46755
47854
  reasoningOutputTokens: 0,
46756
47855
  costUsd: 0,
@@ -46767,6 +47866,10 @@ function addEntry(totals2, entry, cost) {
46767
47866
  totals2.inputTokens += entry.inputTokens;
46768
47867
  totals2.outputTokens += entry.outputTokens;
46769
47868
  totals2.reasoningOutputTokens += entry.reasoningOutputTokens ?? 0;
47869
+ if (entry.cachedInputTokens !== void 0) {
47870
+ totals2.cacheHitCachedInputTokens += entry.cachedInputTokens;
47871
+ totals2.cacheHitInputTokens += entry.inputTokens;
47872
+ }
46770
47873
  if (entry.cachedInputTokens !== void 0 && entry.cacheWriteInputTokens !== void 0) {
46771
47874
  totals2.cachedInputTokens += entry.cachedInputTokens;
46772
47875
  totals2.cacheWriteInputTokens += entry.cacheWriteInputTokens;
@@ -47013,7 +48116,7 @@ var UsageStatistics = class {
47013
48116
  async #persist(harness2, cache) {
47014
48117
  if (!cache.dirty || this.#now() - cache.persistedAtMs < PERSIST_INTERVAL_MS) return;
47015
48118
  const file2 = this.#file(harness2);
47016
- const temporary = `${file2}.${randomUUID22()}.tmp`;
48119
+ const temporary = `${file2}.${randomUUID23()}.tmp`;
47017
48120
  try {
47018
48121
  await mkdir17(this.#directory, { recursive: true });
47019
48122
  const sources = [...cache.sources].map(([id2, source]) => [
@@ -47627,7 +48730,7 @@ async function runHostRuntime(input) {
47627
48730
  }
47628
48731
 
47629
48732
  // packages/host-runtime/src/remote-host-install.ts
47630
- import { createHash as createHash11, randomUUID as randomUUID23 } from "node:crypto";
48733
+ import { createHash as createHash11, randomUUID as randomUUID24 } from "node:crypto";
47631
48734
  import { constants as fsConstants } from "node:fs";
47632
48735
  import {
47633
48736
  access as access3,
@@ -47726,7 +48829,7 @@ async function writeAtomic(filePath, contents, mode) {
47726
48829
  await mkdir18(path39.dirname(filePath), { recursive: true, mode: 448 });
47727
48830
  const temporary = path39.join(
47728
48831
  path39.dirname(filePath),
47729
- `.${path39.basename(filePath)}.${process.pid}.${randomUUID23()}.tmp`
48832
+ `.${path39.basename(filePath)}.${process.pid}.${randomUUID24()}.tmp`
47730
48833
  );
47731
48834
  try {
47732
48835
  if (typeof contents === "string") {
@@ -47750,7 +48853,7 @@ async function writeAtomicExecutable(filePath, sourcePath) {
47750
48853
  await mkdir18(path39.dirname(filePath), { recursive: true, mode: 448 });
47751
48854
  const temporary = path39.join(
47752
48855
  path39.dirname(filePath),
47753
- `.${path39.basename(filePath)}.${process.pid}.${randomUUID23()}.tmp`
48856
+ `.${path39.basename(filePath)}.${process.pid}.${randomUUID24()}.tmp`
47754
48857
  );
47755
48858
  try {
47756
48859
  await copyFile4(sourcePath, temporary);
@@ -48608,29 +49711,6 @@ function consumeBrokerFrames(socket, onFrame, onError) {
48608
49711
  });
48609
49712
  }
48610
49713
 
48611
- // packages/harness-broker/dist/paths.js
48612
- import os11 from "node:os";
48613
- import path41 from "node:path";
48614
- var HARNESS_BROKER_DESCRIPTOR_ENV = "CODEXHOST_CLAUDE_BROKER_DESCRIPTOR";
48615
- var HARNESS_BROKER_DESCRIPTOR_FILE = "claude-code-broker-v1.json";
48616
- var HARNESS_BROKER_SOCKET_FILE = "claude-code-broker-v1.sock";
48617
- function defaultHarnessBrokerDirectory(environment = process.env) {
48618
- const home = environment.HOME || os11.homedir();
48619
- return path41.join(home, ".codexhost", "harness-broker");
48620
- }
48621
- function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId = "claude-code") {
48622
- harnessPluginIdSchema.parse(harnessId);
48623
- if (harnessId !== "claude-code")
48624
- return path41.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
48625
- return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path41.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
48626
- }
48627
- function defaultHarnessBrokerSocketPath(environment = process.env, harnessId = "claude-code") {
48628
- harnessPluginIdSchema.parse(harnessId);
48629
- if (harnessId !== "claude-code")
48630
- return path41.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.sock`);
48631
- return path41.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_SOCKET_FILE);
48632
- }
48633
-
48634
49714
  // packages/harness-broker/dist/validation.js
48635
49715
  var cwdSchema = external_exports.string().min(1).max(16384);
48636
49716
  var brokerEnvironmentSchema = external_exports.object({
@@ -48681,7 +49761,11 @@ var brokerOpenInputSchema = external_exports.discriminatedUnion("kind", [
48681
49761
  forkSchema,
48682
49762
  rollbackSchema
48683
49763
  ]);
48684
- var brokerInspectInputSchema = external_exports.object({ cwd: cwdSchema.optional(), refresh: external_exports.boolean().optional() }).strict();
49764
+ var brokerInspectInputSchema = external_exports.object({
49765
+ cwd: cwdSchema.optional(),
49766
+ refresh: external_exports.boolean().optional(),
49767
+ purpose: external_exports.literal("availability").optional()
49768
+ }).strict();
48685
49769
  var brokerSessionImportListParamsSchema = external_exports.object({
48686
49770
  offset: external_exports.number().int().nonnegative().safe(),
48687
49771
  limit: external_exports.number().int().min(1).max(HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE)
@@ -48696,10 +49780,10 @@ var brokerSessionImportSourceSchema = external_exports.object({
48696
49780
  candidate: harnessSessionImportCandidateSchema,
48697
49781
  nativeRef: nativeSessionRefSchema
48698
49782
  }).strict().superRefine((source, context) => {
48699
- if (source.nativeRef.harnessId !== "claude-code" || source.nativeRef.nativeSessionId !== source.candidate.nativeSessionId) {
49783
+ if (source.nativeRef.nativeSessionId !== source.candidate.nativeSessionId) {
48700
49784
  context.addIssue({
48701
49785
  code: "custom",
48702
- message: "Claude Session import source identity does not match"
49786
+ message: "Session import source identity does not match"
48703
49787
  });
48704
49788
  }
48705
49789
  });
@@ -48789,7 +49873,7 @@ var harnessErrorSchema = external_exports.object({
48789
49873
  var harnessSessionStateSchema = external_exports.custom((value2) => {
48790
49874
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2))
48791
49875
  return false;
48792
- const record4 = value2;
49876
+ const record5 = value2;
48793
49877
  const allowed = /* @__PURE__ */ new Set([
48794
49878
  "nativeRef",
48795
49879
  "effectiveModel",
@@ -48798,12 +49882,12 @@ var harnessSessionStateSchema = external_exports.custom((value2) => {
48798
49882
  "availableThinkingOptions",
48799
49883
  "effectivePermissionModeId"
48800
49884
  ]);
48801
- if (Object.keys(record4).some((key) => !allowed.has(key)))
49885
+ if (Object.keys(record5).some((key) => !allowed.has(key)))
48802
49886
  return false;
48803
- if (record4.nativeRef !== void 0 && !nativeSessionRefSchema.safeParse(record4.nativeRef).success) {
49887
+ if (record5.nativeRef !== void 0 && !nativeSessionRefSchema.safeParse(record5.nativeRef).success) {
48804
49888
  return false;
48805
49889
  }
48806
- const { nativeRef: _nativeRef, ...configuration } = record4;
49890
+ const { nativeRef: _nativeRef, ...configuration } = record5;
48807
49891
  void _nativeRef;
48808
49892
  return harnessConfigurationStateSchema.safeParse(configuration).success;
48809
49893
  });
@@ -48873,8 +49957,31 @@ var harnessOutputSchema = external_exports.custom((value2) => {
48873
49957
  return false;
48874
49958
  });
48875
49959
 
49960
+ // packages/harness-broker/dist/paths.js
49961
+ import os11 from "node:os";
49962
+ import path41 from "node:path";
49963
+ var HARNESS_BROKER_DESCRIPTOR_ENV = "CODEXHOST_CLAUDE_BROKER_DESCRIPTOR";
49964
+ var HARNESS_BROKER_DESCRIPTOR_FILE = "claude-code-broker-v1.json";
49965
+ var HARNESS_BROKER_SOCKET_FILE = "claude-code-broker-v1.sock";
49966
+ function defaultHarnessBrokerDirectory(environment = process.env) {
49967
+ const home = environment.HOME || os11.homedir();
49968
+ return path41.join(home, ".codexhost", "harness-broker");
49969
+ }
49970
+ function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId = "claude-code") {
49971
+ harnessPluginIdSchema.parse(harnessId);
49972
+ if (harnessId !== "claude-code")
49973
+ return path41.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
49974
+ return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path41.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
49975
+ }
49976
+ function defaultHarnessBrokerSocketPath(environment = process.env, harnessId = "claude-code") {
49977
+ harnessPluginIdSchema.parse(harnessId);
49978
+ if (harnessId !== "claude-code")
49979
+ return path41.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.sock`);
49980
+ return path41.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_SOCKET_FILE);
49981
+ }
49982
+
48876
49983
  // packages/harness-broker/dist/server.js
48877
- import { randomBytes as randomBytes5, randomUUID as randomUUID24 } from "node:crypto";
49984
+ import { randomBytes as randomBytes5, randomUUID as randomUUID25 } from "node:crypto";
48878
49985
  import { chmod as chmod6, lstat as lstat10, mkdir as mkdir19, open as open11, readFile as readFile20, rename as rename16, rm as rm18 } from "node:fs/promises";
48879
49986
  import net4, {} from "node:net";
48880
49987
  import path42 from "node:path";
@@ -48933,7 +50040,7 @@ async function assertNoLiveDescriptor(descriptorPath) {
48933
50040
  }
48934
50041
  }
48935
50042
  async function publishDescriptor(descriptorPath, descriptor) {
48936
- const temporary = `${descriptorPath}.${process.pid}.${randomUUID24()}.tmp`;
50043
+ const temporary = `${descriptorPath}.${process.pid}.${randomUUID25()}.tmp`;
48937
50044
  const handle = await open11(temporary, "wx", 384);
48938
50045
  try {
48939
50046
  await handle.writeFile(`${JSON.stringify(descriptor)}
@@ -48946,28 +50053,28 @@ async function publishDescriptor(descriptorPath, descriptor) {
48946
50053
  if (process.platform !== "win32")
48947
50054
  await chmod6(descriptorPath, 384);
48948
50055
  }
48949
- function sessionMetadata(record4) {
48950
- const initialState = { ...record4.session.initialState };
48951
- if (record4.selection.model && initialState.effectiveModel?.id !== record4.selection.model.id) {
50056
+ function sessionMetadata(record5) {
50057
+ const initialState = { ...record5.session.initialState };
50058
+ if (record5.selection.model && initialState.effectiveModel?.id !== record5.selection.model.id) {
48952
50059
  delete initialState.resolvedModelLabel;
48953
50060
  }
48954
- if (record4.selection.thinkingOptionId && initialState.effectiveThinkingOptionId !== record4.selection.thinkingOptionId) {
50061
+ if (record5.selection.thinkingOptionId && initialState.effectiveThinkingOptionId !== record5.selection.thinkingOptionId) {
48955
50062
  delete initialState.availableThinkingOptions;
48956
50063
  }
48957
50064
  return {
48958
- sessionId: record4.id,
48959
- sessionGeneration: record4.generation,
48960
- capabilities: record4.session.capabilities,
50065
+ sessionId: record5.id,
50066
+ sessionGeneration: record5.generation,
50067
+ capabilities: record5.session.capabilities,
48961
50068
  readCapabilities: true,
48962
50069
  initialState: {
48963
50070
  ...initialState,
48964
- ...record4.nativeRef ? { nativeRef: record4.nativeRef } : {},
48965
- ...record4.selection.model ? { effectiveModel: record4.selection.model } : {},
48966
- ...record4.selection.thinkingOptionId ? { effectiveThinkingOptionId: record4.selection.thinkingOptionId } : {},
48967
- ...record4.selection.permissionModeId ? { effectivePermissionModeId: record4.selection.permissionModeId } : {}
50071
+ ...record5.nativeRef ? { nativeRef: record5.nativeRef } : {},
50072
+ ...record5.selection.model ? { effectiveModel: record5.selection.model } : {},
50073
+ ...record5.selection.thinkingOptionId ? { effectiveThinkingOptionId: record5.selection.thinkingOptionId } : {},
50074
+ ...record5.selection.permissionModeId ? { effectivePermissionModeId: record5.selection.permissionModeId } : {}
48968
50075
  },
48969
- initialUsage: record4.session.initialUsage,
48970
- commands: record4.session.commands !== void 0
50076
+ initialUsage: record5.session.initialUsage,
50077
+ commands: record5.session.commands !== void 0
48971
50078
  };
48972
50079
  }
48973
50080
  async function socketAcceptsConnections(socketPath) {
@@ -49011,7 +50118,7 @@ async function startHarnessBrokerServer(input) {
49011
50118
  await assertNoLiveDescriptor(input.descriptorPath);
49012
50119
  if (process.platform !== "win32")
49013
50120
  await prepareUnixSocketPath(input.socketPath);
49014
- const generation = input.generation ?? randomUUID24();
50121
+ const generation = input.generation ?? randomUUID25();
49015
50122
  const token = input.token ?? randomBytes5(32).toString("hex");
49016
50123
  const descriptor = {
49017
50124
  schemaVersion: 1,
@@ -49052,7 +50159,7 @@ async function startHarnessBrokerServer(input) {
49052
50159
  };
49053
50160
  const server = net4.createServer((socket) => {
49054
50161
  const state = {
49055
- id: randomUUID24(),
50162
+ id: randomUUID25(),
49056
50163
  socket,
49057
50164
  authenticated: false,
49058
50165
  inputSequence: 0,
@@ -49079,15 +50186,15 @@ async function startHarnessBrokerServer(input) {
49079
50186
  const respond2 = async (request, result) => {
49080
50187
  await send({ kind: "response", id: request.id, ...result });
49081
50188
  };
49082
- const releaseProvisionalWriter = (record4) => {
49083
- if (record4.provisionalWriterLease && provisionalNativeWriter === record4.id) {
50189
+ const releaseProvisionalWriter = (record5) => {
50190
+ if (record5.provisionalWriterLease && provisionalNativeWriter === record5.id) {
49084
50191
  provisionalNativeWriter = void 0;
49085
50192
  }
49086
- record4.provisionalWriterLease = false;
49087
- record4.awaitingNativeIdentity = false;
50193
+ record5.provisionalWriterLease = false;
50194
+ record5.awaitingNativeIdentity = false;
49088
50195
  };
49089
- const forwardOutputs = async (record4, nativeSession, sessionGeneration, forwarderEpoch) => {
49090
- const isCurrent = () => sessions.get(record4.id) === record4 && record4.session === nativeSession && record4.generation === sessionGeneration && record4.forwarderEpoch === forwarderEpoch;
50196
+ const forwardOutputs = async (record5, nativeSession, sessionGeneration, forwarderEpoch) => {
50197
+ const isCurrent = () => sessions.get(record5.id) === record5 && record5.session === nativeSession && record5.generation === sessionGeneration && record5.forwarderEpoch === forwarderEpoch;
49091
50198
  try {
49092
50199
  for await (const output of nativeSession.outputs) {
49093
50200
  if (!isCurrent())
@@ -49095,13 +50202,13 @@ async function startHarnessBrokerServer(input) {
49095
50202
  if (output.kind === "event" && output.event.type === "session.state.changed") {
49096
50203
  const state2 = output.event.state;
49097
50204
  const observedNativeId = state2.nativeRef?.nativeSessionId;
49098
- const expectedRef = record4.nativeWriterRef ?? record4.nativeRef;
50205
+ const expectedRef = record5.nativeWriterRef ?? record5.nativeRef;
49099
50206
  if (state2.nativeRef && (state2.nativeRef.harnessId !== input.adapter.harnessId || expectedRef && (expectedRef.harnessId !== state2.nativeRef.harnessId || expectedRef.nativeSessionId !== state2.nativeRef.nativeSessionId || expectedRef.formatVersion !== state2.nativeRef.formatVersion))) {
49100
- record4.faulted = true;
49101
- releaseProvisionalWriter(record4);
50207
+ record5.faulted = true;
50208
+ releaseProvisionalWriter(record5);
49102
50209
  await send({
49103
50210
  kind: "output",
49104
- sessionId: record4.id,
50211
+ sessionId: record5.id,
49105
50212
  sessionGeneration,
49106
50213
  output: {
49107
50214
  kind: "event",
@@ -49119,15 +50226,15 @@ async function startHarnessBrokerServer(input) {
49119
50226
  await nativeSession.close().catch(() => void 0);
49120
50227
  break;
49121
50228
  }
49122
- if (observedNativeId && !record4.writerKey) {
50229
+ if (observedNativeId && !record5.writerKey) {
49123
50230
  const writerKey = nativeWriterKey(observedNativeId);
49124
50231
  const owner = nativeWriters.get(writerKey);
49125
- if (owner && owner !== record4.id) {
49126
- record4.faulted = true;
49127
- releaseProvisionalWriter(record4);
50232
+ if (owner && owner !== record5.id) {
50233
+ record5.faulted = true;
50234
+ releaseProvisionalWriter(record5);
49128
50235
  await send({
49129
50236
  kind: "output",
49130
- sessionId: record4.id,
50237
+ sessionId: record5.id,
49131
50238
  sessionGeneration,
49132
50239
  output: {
49133
50240
  kind: "event",
@@ -49145,38 +50252,38 @@ async function startHarnessBrokerServer(input) {
49145
50252
  await nativeSession.close().catch(() => void 0);
49146
50253
  break;
49147
50254
  }
49148
- nativeWriters.set(writerKey, record4.id);
49149
- record4.nativeId = observedNativeId;
49150
- record4.nativeRef = state2.nativeRef;
49151
- record4.writerKey = writerKey;
49152
- releaseProvisionalWriter(record4);
50255
+ nativeWriters.set(writerKey, record5.id);
50256
+ record5.nativeId = observedNativeId;
50257
+ record5.nativeRef = state2.nativeRef;
50258
+ record5.writerKey = writerKey;
50259
+ releaseProvisionalWriter(record5);
49153
50260
  }
49154
50261
  if (state2.nativeRef) {
49155
- record4.nativeId = state2.nativeRef.nativeSessionId;
49156
- record4.nativeRef = state2.nativeRef;
49157
- releaseProvisionalWriter(record4);
50262
+ record5.nativeId = state2.nativeRef.nativeSessionId;
50263
+ record5.nativeRef = state2.nativeRef;
50264
+ releaseProvisionalWriter(record5);
49158
50265
  }
49159
50266
  if (state2.effectiveModel)
49160
- record4.selection.model = state2.effectiveModel;
50267
+ record5.selection.model = state2.effectiveModel;
49161
50268
  if (state2.effectiveThinkingOptionId) {
49162
- record4.selection.thinkingOptionId = state2.effectiveThinkingOptionId;
50269
+ record5.selection.thinkingOptionId = state2.effectiveThinkingOptionId;
49163
50270
  }
49164
50271
  if (state2.effectivePermissionModeId) {
49165
- record4.selection.permissionModeId = state2.effectivePermissionModeId;
50272
+ record5.selection.permissionModeId = state2.effectivePermissionModeId;
49166
50273
  }
49167
50274
  }
49168
50275
  const authenticationTerminal = isAuthenticationTerminal(output);
49169
50276
  if (output.kind === "event" && output.event.type === "session.faulted") {
49170
- record4.faulted = true;
49171
- releaseProvisionalWriter(record4);
50277
+ record5.faulted = true;
50278
+ releaseProvisionalWriter(record5);
49172
50279
  }
49173
50280
  if (authenticationTerminal) {
49174
- record4.faulted = true;
49175
- releaseProvisionalWriter(record4);
50281
+ record5.faulted = true;
50282
+ releaseProvisionalWriter(record5);
49176
50283
  }
49177
50284
  await send({
49178
50285
  kind: "output",
49179
- sessionId: record4.id,
50286
+ sessionId: record5.id,
49180
50287
  sessionGeneration,
49181
50288
  output
49182
50289
  });
@@ -49187,26 +50294,26 @@ async function startHarnessBrokerServer(input) {
49187
50294
  }
49188
50295
  } catch {
49189
50296
  if (isCurrent()) {
49190
- record4.faulted = true;
49191
- releaseProvisionalWriter(record4);
50297
+ record5.faulted = true;
50298
+ releaseProvisionalWriter(record5);
49192
50299
  }
49193
50300
  }
49194
50301
  };
49195
- const closeRecord = async (record4) => {
49196
- if (sessions.get(record4.id) !== record4)
50302
+ const closeRecord = async (record5) => {
50303
+ if (sessions.get(record5.id) !== record5)
49197
50304
  return;
49198
- sessions.delete(record4.id);
50305
+ sessions.delete(record5.id);
49199
50306
  scheduleIdle();
49200
- state.sessions.delete(record4.id);
49201
- record4.forwarderEpoch += 1;
49202
- const nativeSession = record4.session;
49203
- const outputTask = record4.outputTask;
50307
+ state.sessions.delete(record5.id);
50308
+ record5.forwarderEpoch += 1;
50309
+ const nativeSession = record5.session;
50310
+ const outputTask = record5.outputTask;
49204
50311
  await nativeSession.close().catch(() => void 0);
49205
50312
  await outputTask.catch(() => void 0);
49206
- if (record4.writerKey && nativeWriters.get(record4.writerKey) === record4.id) {
49207
- nativeWriters.delete(record4.writerKey);
50313
+ if (record5.writerKey && nativeWriters.get(record5.writerKey) === record5.id) {
50314
+ nativeWriters.delete(record5.writerKey);
49208
50315
  }
49209
- releaseProvisionalWriter(record4);
50316
+ releaseProvisionalWriter(record5);
49210
50317
  };
49211
50318
  const requireSession = (params) => {
49212
50319
  const candidate = params;
@@ -49214,13 +50321,13 @@ async function startHarnessBrokerServer(input) {
49214
50321
  sessionId: candidate.sessionId,
49215
50322
  sessionGeneration: candidate.sessionGeneration
49216
50323
  });
49217
- const record4 = sessions.get(parsed2.sessionId);
49218
- if (!record4 || record4.owner !== state.id)
50324
+ const record5 = sessions.get(parsed2.sessionId);
50325
+ if (!record5 || record5.owner !== state.id)
49219
50326
  throw new Error("Harness broker Session is unavailable");
49220
- if (record4.generation !== parsed2.sessionGeneration) {
50327
+ if (record5.generation !== parsed2.sessionGeneration) {
49221
50328
  throw new Error("Harness broker Session generation is stale");
49222
50329
  }
49223
- return record4;
50330
+ return record5;
49224
50331
  };
49225
50332
  const handleRequest = async (request) => {
49226
50333
  if (closed || state.closed)
@@ -49243,31 +50350,28 @@ async function startHarnessBrokerServer(input) {
49243
50350
  const parsed2 = brokerInspectInputSchema.parse(request.params);
49244
50351
  const inspection = await input.adapter.inspect({
49245
50352
  ...parsed2.cwd ? { cwd: parsed2.cwd } : {},
49246
- ...parsed2.refresh !== void 0 ? { refresh: parsed2.refresh } : {}
50353
+ ...parsed2.refresh !== void 0 ? { refresh: parsed2.refresh } : {},
50354
+ ...parsed2.purpose !== void 0 ? { purpose: parsed2.purpose } : {}
49247
50355
  });
49248
50356
  retireWhenIdle = inspection.status !== "ready";
49249
50357
  return inspection;
49250
50358
  }
49251
- if (request.method === "adapter.subagent.readSnapshot") {
49252
- const subagents = input.adapter.subagents;
49253
- if (!subagents)
49254
- return { ok: false, error: harnessError("Harness subagents are unavailable", false) };
49255
- const params = subagentReadSnapshotSchema.parse(request.params);
49256
- if (params.parent.harnessId !== input.adapter.harnessId)
49257
- return { ok: false, error: protocolError("Subagent parent belongs to another Harness") };
49258
- return subagents.readSnapshot(params);
49259
- }
49260
50359
  if (request.method === "adapter.sessionImport.list") {
49261
50360
  const { limit, offset } = brokerSessionImportListParamsSchema.parse(request.params);
49262
- const sessionImport = input.adapter.sessionImport;
49263
- if (!sessionImport?.resolveCandidate) {
50361
+ const capability = input.adapter.sessionImport;
50362
+ if (!capability?.resolveCandidate) {
49264
50363
  return {
49265
50364
  ok: false,
49266
- error: harnessError("Claude Session import is unavailable", false)
50365
+ error: {
50366
+ code: "unsupported",
50367
+ message: "Harness Session import is unavailable",
50368
+ retryable: false
50369
+ }
49267
50370
  };
49268
50371
  }
49269
50372
  if (offset === 0) {
49270
- const result = await sessionImport.listCandidates();
50373
+ delete state.sessionImportCandidates;
50374
+ const result = await capability.listCandidates();
49271
50375
  if (!result.ok)
49272
50376
  return result;
49273
50377
  state.sessionImportCandidates = result.value.map((candidate) => harnessSessionImportCandidateSchema.parse(candidate));
@@ -49278,9 +50382,8 @@ async function startHarnessBrokerServer(input) {
49278
50382
  ok: false,
49279
50383
  error: {
49280
50384
  code: "invalidState",
49281
- message: "Claude Session import page snapshot is unavailable",
49282
- retryable: true,
49283
- stage: "harnessBroker.sessionImport"
50385
+ message: "Session import snapshot is unavailable; refresh the list",
50386
+ retryable: true
49284
50387
  }
49285
50388
  };
49286
50389
  }
@@ -49292,14 +50395,37 @@ async function startHarnessBrokerServer(input) {
49292
50395
  }
49293
50396
  if (request.method === "adapter.sessionImport.resolve") {
49294
50397
  const { nativeSessionId } = brokerSessionImportResolveParamsSchema.parse(request.params);
49295
- const resolveCandidate = input.adapter.sessionImport?.resolveCandidate;
49296
- if (!resolveCandidate) {
50398
+ const capability = input.adapter.sessionImport;
50399
+ if (!capability?.resolveCandidate) {
50400
+ return {
50401
+ ok: false,
50402
+ error: {
50403
+ code: "unsupported",
50404
+ message: "Harness Session import is unavailable",
50405
+ retryable: false
50406
+ }
50407
+ };
50408
+ }
50409
+ const result = await capability.resolveCandidate(nativeSessionId);
50410
+ if (!result.ok)
50411
+ return result;
50412
+ const source = brokerSessionImportSourceSchema.safeParse(result.value);
50413
+ if (!source.success || source.data.nativeRef.harnessId !== input.adapter.harnessId || source.data.candidate.nativeSessionId !== nativeSessionId) {
49297
50414
  return {
49298
50415
  ok: false,
49299
- error: harnessError("Claude Session import is unavailable", false)
50416
+ error: protocolError("Session import source identity does not match")
49300
50417
  };
49301
50418
  }
49302
- return resolveCandidate(nativeSessionId);
50419
+ return { ok: true, value: source.data };
50420
+ }
50421
+ if (request.method === "adapter.subagent.readSnapshot") {
50422
+ const subagents = input.adapter.subagents;
50423
+ if (!subagents)
50424
+ return { ok: false, error: harnessError("Harness subagents are unavailable", false) };
50425
+ const params = subagentReadSnapshotSchema.parse(request.params);
50426
+ if (params.parent.harnessId !== input.adapter.harnessId)
50427
+ return { ok: false, error: protocolError("Subagent parent belongs to another Harness") };
50428
+ return subagents.readSnapshot(params);
49303
50429
  }
49304
50430
  if (request.method === "adapter.open") {
49305
50431
  while (openingCreate)
@@ -49334,7 +50460,7 @@ async function startHarnessBrokerServer(input) {
49334
50460
  }
49335
50461
  };
49336
50462
  }
49337
- const openReservation = randomUUID24();
50463
+ const openReservation = randomUUID25();
49338
50464
  if (sourceKey)
49339
50465
  nativeWriters.set(sourceKey, openReservation);
49340
50466
  const provisionalReservation = openInput.kind === "create" ? openReservation : void 0;
@@ -49414,7 +50540,7 @@ async function startHarnessBrokerServer(input) {
49414
50540
  };
49415
50541
  }
49416
50542
  const delayedCreateIdentity = openInput.kind === "create" && !nativeKey;
49417
- const record5 = {
50543
+ const record6 = {
49418
50544
  id: openReservation,
49419
50545
  generation: 1,
49420
50546
  owner: state.id,
@@ -49435,18 +50561,18 @@ async function startHarnessBrokerServer(input) {
49435
50561
  ...opened.value.initialState.effectivePermissionModeId ? { permissionModeId: opened.value.initialState.effectivePermissionModeId } : {}
49436
50562
  }
49437
50563
  };
49438
- sessions.set(record5.id, record5);
49439
- state.sessions.add(record5.id);
50564
+ sessions.set(record6.id, record6);
50565
+ state.sessions.add(record6.id);
49440
50566
  if (nativeKey)
49441
- nativeWriters.set(nativeKey, record5.id);
49442
- if (sourceKey && sourceKey !== nativeKey && nativeWriters.get(sourceKey) === record5.id) {
50567
+ nativeWriters.set(nativeKey, record6.id);
50568
+ if (sourceKey && sourceKey !== nativeKey && nativeWriters.get(sourceKey) === record6.id) {
49443
50569
  nativeWriters.delete(sourceKey);
49444
50570
  }
49445
- if (!record5.provisionalWriterLease && provisionalNativeWriter === provisionalReservation) {
50571
+ if (!record6.provisionalWriterLease && provisionalNativeWriter === provisionalReservation) {
49446
50572
  provisionalNativeWriter = void 0;
49447
50573
  }
49448
- record5.outputTask = forwardOutputs(record5, opened.value, record5.generation, record5.forwarderEpoch);
49449
- return { ok: true, value: sessionMetadata(record5) };
50574
+ record6.outputTask = forwardOutputs(record6, opened.value, record6.generation, record6.forwarderEpoch);
50575
+ return { ok: true, value: sessionMetadata(record6) };
49450
50576
  } finally {
49451
50577
  if (createSettled) {
49452
50578
  openingCreate = void 0;
@@ -49456,11 +50582,11 @@ async function startHarnessBrokerServer(input) {
49456
50582
  }
49457
50583
  if (request.method === "session.execute") {
49458
50584
  const parsed2 = sessionExecuteParamsSchema.parse(request.params);
49459
- const record5 = requireSession(parsed2);
50585
+ const record6 = requireSession(parsed2);
49460
50586
  const command = brokerHostCommandSchema.parse(parsed2.command);
49461
- if (record5.awaitingNativeIdentity && !record5.writerKey) {
49462
- const isBootstrapTurn = command.type === "turn.start" && record5.provisionalWriterLease && record5.bootstrapTurnId === void 0;
49463
- const isBootstrapTurnContinuation = record5.bootstrapTurnId !== void 0 && (command.type === "turn.cancel" && command.turnId === record5.bootstrapTurnId || command.type === "interaction.respond");
50587
+ if (record6.awaitingNativeIdentity && !record6.writerKey) {
50588
+ const isBootstrapTurn = command.type === "turn.start" && record6.provisionalWriterLease && record6.bootstrapTurnId === void 0;
50589
+ const isBootstrapTurnContinuation = record6.bootstrapTurnId !== void 0 && (command.type === "turn.cancel" && command.turnId === record6.bootstrapTurnId || command.type === "interaction.respond");
49464
50590
  if (!isBootstrapTurn && !isBootstrapTurnContinuation) {
49465
50591
  return {
49466
50592
  ok: false,
@@ -49473,17 +50599,17 @@ async function startHarnessBrokerServer(input) {
49473
50599
  };
49474
50600
  }
49475
50601
  if (command.type === "turn.start")
49476
- record5.bootstrapTurnId = command.turnId;
50602
+ record6.bootstrapTurnId = command.turnId;
49477
50603
  }
49478
50604
  let result;
49479
50605
  if (command.type === "turn.start")
49480
- result = await record5.session.execute(command);
50606
+ result = await record6.session.execute(command);
49481
50607
  else if (command.type === "turn.steer")
49482
- result = await record5.session.execute(command);
50608
+ result = await record6.session.execute(command);
49483
50609
  else if (command.type === "turn.cancel")
49484
- result = await record5.session.execute(command);
50610
+ result = await record6.session.execute(command);
49485
50611
  else if (command.type === "interaction.respond") {
49486
- result = await record5.session.execute({
50612
+ result = await record6.session.execute({
49487
50613
  type: command.type,
49488
50614
  interactionId: command.interactionId,
49489
50615
  response: command.response.type === "question" ? {
@@ -49493,21 +50619,21 @@ async function startHarnessBrokerServer(input) {
49493
50619
  } : command.response
49494
50620
  });
49495
50621
  } else if (command.type === "model.select")
49496
- result = await record5.session.execute(command);
50622
+ result = await record6.session.execute(command);
49497
50623
  else if (command.type === "thinking.select")
49498
- result = await record5.session.execute(command);
50624
+ result = await record6.session.execute(command);
49499
50625
  else
49500
- result = await record5.session.execute(command);
49501
- if (!result.ok && command.type === "turn.start" && record5.awaitingNativeIdentity && record5.bootstrapTurnId === command.turnId) {
49502
- delete record5.bootstrapTurnId;
50626
+ result = await record6.session.execute(command);
50627
+ if (!result.ok && command.type === "turn.start" && record6.awaitingNativeIdentity && record6.bootstrapTurnId === command.turnId) {
50628
+ delete record6.bootstrapTurnId;
49503
50629
  }
49504
50630
  if (result.ok) {
49505
50631
  if (command.type === "model.select")
49506
- record5.selection.model = command.model;
50632
+ record6.selection.model = command.model;
49507
50633
  if (command.type === "thinking.select")
49508
- record5.selection.thinkingOptionId = command.thinkingOptionId;
50634
+ record6.selection.thinkingOptionId = command.thinkingOptionId;
49509
50635
  if (command.type === "permissionMode.select")
49510
- record5.selection.permissionModeId = command.permissionModeId;
50636
+ record6.selection.permissionModeId = command.permissionModeId;
49511
50637
  }
49512
50638
  return result;
49513
50639
  }
@@ -49519,10 +50645,10 @@ async function startHarnessBrokerServer(input) {
49519
50645
  return requireSession(request.params).session.readSnapshot();
49520
50646
  }
49521
50647
  if (request.method === "session.refreshUsage") {
49522
- const record5 = requireSession(request.params);
49523
- const refreshUsage = record5.session.refreshUsage;
50648
+ const record6 = requireSession(request.params);
50649
+ const refreshUsage = record6.session.refreshUsage;
49524
50650
  if (refreshUsage)
49525
- await refreshUsage.call(record5.session);
50651
+ await refreshUsage.call(record6.session);
49526
50652
  return null;
49527
50653
  }
49528
50654
  if (request.method === "session.commands.list") {
@@ -49540,11 +50666,11 @@ async function startHarnessBrokerServer(input) {
49540
50666
  }) : { ok: false, error: harnessError("Commands unavailable", false) };
49541
50667
  }
49542
50668
  if (request.method === "session.reopen") {
49543
- const record5 = requireSession(request.params);
49544
- if (!record5.faulted) {
49545
- return { ok: true, value: sessionMetadata(record5) };
50669
+ const record6 = requireSession(request.params);
50670
+ if (!record6.faulted) {
50671
+ return { ok: true, value: sessionMetadata(record6) };
49546
50672
  }
49547
- if (!record5.nativeRef) {
50673
+ if (!record6.nativeRef) {
49548
50674
  return {
49549
50675
  ok: false,
49550
50676
  error: {
@@ -49555,17 +50681,17 @@ async function startHarnessBrokerServer(input) {
49555
50681
  }
49556
50682
  };
49557
50683
  }
49558
- const nativeRef = record5.nativeRef;
49559
- const oldSession = record5.session;
49560
- const oldOutputTask = record5.outputTask;
49561
- record5.forwarderEpoch += 1;
50684
+ const nativeRef = record6.nativeRef;
50685
+ const oldSession = record6.session;
50686
+ const oldOutputTask = record6.outputTask;
50687
+ record6.forwarderEpoch += 1;
49562
50688
  await oldSession.close().catch(() => void 0);
49563
50689
  await oldOutputTask.catch(() => void 0);
49564
50690
  const reopened = await input.adapter.open({
49565
50691
  kind: "resume",
49566
- cwd: record5.cwd,
50692
+ cwd: record6.cwd,
49567
50693
  nativeRef,
49568
- ...record5.environment ? { environment: record5.environment } : {}
50694
+ ...record6.environment ? { environment: record6.environment } : {}
49569
50695
  });
49570
50696
  if (!reopened.ok)
49571
50697
  return reopened;
@@ -49582,44 +50708,44 @@ async function startHarnessBrokerServer(input) {
49582
50708
  }
49583
50709
  };
49584
50710
  }
49585
- if (record5.selection.model && reopened.value.capabilities.configuration.selectModel) {
50711
+ if (record6.selection.model && reopened.value.capabilities.configuration.selectModel) {
49586
50712
  const selected = await reopened.value.execute({
49587
50713
  type: "model.select",
49588
- model: record5.selection.model
50714
+ model: record6.selection.model
49589
50715
  });
49590
50716
  if (!selected.ok) {
49591
50717
  await reopened.value.close().catch(() => void 0);
49592
50718
  return selected;
49593
50719
  }
49594
50720
  }
49595
- if (record5.selection.thinkingOptionId && reopened.value.capabilities.configuration.selectThinkingOption) {
50721
+ if (record6.selection.thinkingOptionId && reopened.value.capabilities.configuration.selectThinkingOption) {
49596
50722
  const selected = await reopened.value.execute({
49597
50723
  type: "thinking.select",
49598
- thinkingOptionId: record5.selection.thinkingOptionId
50724
+ thinkingOptionId: record6.selection.thinkingOptionId
49599
50725
  });
49600
50726
  if (!selected.ok) {
49601
50727
  await reopened.value.close().catch(() => void 0);
49602
50728
  return selected;
49603
50729
  }
49604
50730
  }
49605
- if (record5.selection.permissionModeId && reopened.value.capabilities.configuration.selectPermissionMode) {
50731
+ if (record6.selection.permissionModeId && reopened.value.capabilities.configuration.selectPermissionMode) {
49606
50732
  const selected = await reopened.value.execute({
49607
50733
  type: "permissionMode.select",
49608
- permissionModeId: record5.selection.permissionModeId
50734
+ permissionModeId: record6.selection.permissionModeId
49609
50735
  });
49610
50736
  if (!selected.ok) {
49611
50737
  await reopened.value.close().catch(() => void 0);
49612
50738
  return selected;
49613
50739
  }
49614
50740
  }
49615
- record5.session = reopened.value;
49616
- record5.generation += 1;
49617
- record5.faulted = false;
49618
- record5.outputTask = forwardOutputs(record5, reopened.value, record5.generation, record5.forwarderEpoch);
49619
- return { ok: true, value: sessionMetadata(record5) };
50741
+ record6.session = reopened.value;
50742
+ record6.generation += 1;
50743
+ record6.faulted = false;
50744
+ record6.outputTask = forwardOutputs(record6, reopened.value, record6.generation, record6.forwarderEpoch);
50745
+ return { ok: true, value: sessionMetadata(record6) };
49620
50746
  }
49621
- const record4 = requireSession(request.params);
49622
- await closeRecord(record4);
50747
+ const record5 = requireSession(request.params);
50748
+ await closeRecord(record5);
49623
50749
  return null;
49624
50750
  };
49625
50751
  consumeBrokerFrames(socket, (raw) => {
@@ -49641,7 +50767,7 @@ async function startHarnessBrokerServer(input) {
49641
50767
  }
49642
50768
  state.authenticated = true;
49643
50769
  state.inputSequence = 1;
49644
- await send({ kind: "response", id: randomUUID24(), ok: true, value: { ready: true } });
50770
+ await send({ kind: "response", id: randomUUID25(), ok: true, value: { ready: true } });
49645
50771
  return;
49646
50772
  }
49647
50773
  const parsed2 = harnessBrokerRequestSchema.safeParse(raw);
@@ -49681,9 +50807,9 @@ async function startHarnessBrokerServer(input) {
49681
50807
  state.closed = true;
49682
50808
  connections.delete(state);
49683
50809
  for (const sessionId of [...state.sessions]) {
49684
- const record4 = sessions.get(sessionId);
49685
- if (record4)
49686
- void closeRecord(record4);
50810
+ const record5 = sessions.get(sessionId);
50811
+ if (record5)
50812
+ void closeRecord(record5);
49687
50813
  }
49688
50814
  scheduleIdle();
49689
50815
  });
@@ -49715,10 +50841,10 @@ async function startHarnessBrokerServer(input) {
49715
50841
  clearTimeout(idleTimer);
49716
50842
  for (const connection of connections)
49717
50843
  connection.socket.destroy();
49718
- for (const record4 of sessions.values())
49719
- record4.forwarderEpoch += 1;
49720
- await Promise.all([...sessions.values()].map((record4) => record4.session.close().catch(() => void 0)));
49721
- await Promise.all([...sessions.values()].map((record4) => record4.outputTask.catch(() => void 0)));
50844
+ for (const record5 of sessions.values())
50845
+ record5.forwarderEpoch += 1;
50846
+ await Promise.all([...sessions.values()].map((record5) => record5.session.close().catch(() => void 0)));
50847
+ await Promise.all([...sessions.values()].map((record5) => record5.outputTask.catch(() => void 0)));
49722
50848
  await input.adapter.close().catch(() => void 0);
49723
50849
  await new Promise((resolve) => server.close(() => resolve()));
49724
50850
  if (process.platform !== "win32")