@corca-org/ceal-host-win32-x64 1.0.24 → 1.0.25

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.
@@ -277,6 +277,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
277
277
  // (never connected, revoked, or expired). The caller runs that exact
278
278
  // Operation, completes the consent it hands back, and retries the same call.
279
279
  "connect_personal_account",
280
+ // The refusal names the caller's own preferences update step: the read
281
+ // needs a personal connection the caller holds but has not selected in
282
+ // Ceal preferences, or has not confirmed through the initial review. The
283
+ // caller reads personal.preferences.get, runs personal.preferences.update
284
+ // at the current revision to select it, and retries the same call.
285
+ "update_personal_preferences",
280
286
  // The provider or Gateway named a bounded wait; the caller waits that long
281
287
  // and submits the same read again.
282
288
  "retry_after",
@@ -831,9 +837,11 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
831
837
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
832
838
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
833
839
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
834
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
840
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
841
+ var CLIENT_HOST_RELEASE_MISMATCH = `Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry. Update with \`${CEAL_CLIENT_UPGRADE_COMMAND}\`.`;
835
842
  var HOST_INSTALL_REPAIR = "The local Host or Relay is missing, stale, or unavailable. Run `ceal-host install`, then `ceal-host discovery sync`, and retry from a new producer conversation.";
836
- var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
843
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn right now; the Host may be restarting. Wait briefly and retry the same command. If you know you are in an ephemeral side conversation, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions without Host session/turn correlation. Otherwise return to the original regular conversation. Host refusal never switches modes. If the retry still fails, report intended Host calls as a gap.";
844
+ var HOST_RELAY_RESTARTING = "The Host Relay is temporarily unavailable while the Host restarts; wait briefly and retry the same command. If the retry still fails, report this as a gap.";
837
845
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
838
846
  var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
839
847
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
@@ -863,6 +871,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
863
871
  person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Person, then retry this same session refresh.", "ask_admin", 403),
864
872
  principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Principal, then retry this same session refresh.", "ask_admin", 403),
865
873
  authority_replaced: guidance("The Gateway authority has been replaced; this session is no longer valid here. Run `ceal session adopt --gateway <origin> --email <email>` against the current Gateway to complete mailbox-confirmed recovery.", "repair_or_adopt_session", 409),
874
+ // A stored session that predates the authority-epoch commitment carries no
875
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
876
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
866
877
  refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
867
878
  refresh_recovery_unavailable: guidance("The Gateway's durable refresh-recovery key is unavailable. Retry the same refresh attempt after the key is available.", "retry", 503, true),
868
879
  refresh_recovery_outcome_unavailable: guidance("The Gateway could not safely recover the outcome of a prior refresh. Ask an administrator to inspect the Gateway session state before retrying or adopting this session.", "ask_admin", 503),
@@ -987,7 +998,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
987
998
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
988
999
  // The bounded Host reason does not prove ephemerality. A Host refusal never
989
1000
  // changes mode; standalone remains the separate Client authority path.
990
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
1001
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
991
1002
  host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
992
1003
  host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
993
1004
  host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
@@ -1004,7 +1015,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1004
1015
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
1005
1016
  // sandboxed Relay socket names the run-alone retry.
1006
1017
  host_relay_permission_denied: guidance("An agent sandbox denied the Host Relay socket; run `ceal` as the only command, with no pipe, redirect, or `&&`, so the Host allow rule runs it outside the sandbox.", "rerun_outside_agent_sandbox", 403),
1007
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1018
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
1008
1019
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
1009
1020
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
1010
1021
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1269,7 +1280,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
1269
1280
  max_literal_nodes: 512
1270
1281
  });
1271
1282
 
1272
- // packages/ceal-client-protocol/src/operation-json-schema.ts
1283
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
1273
1284
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1274
1285
 
1275
1286
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -1419,7 +1430,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
1419
1430
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
1420
1431
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
1421
1432
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
1422
- var CEAL_MODEL_INPUT_SOURCE_GUIDANCE = `For caller-owned fields, add ${CEAL_OPERATION_INPUT_FLAG} ${shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)}. Use inline JSON for short input; for longer or generated input, put exactly one JSON object in a caller-owned regular non-symlink UTF-8 JSON file and pass --input @path; relative paths resolve from the command working directory.`;
1433
+ var CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE = `For caller-owned fields, add ${CEAL_OPERATION_INPUT_FLAG} ${shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)}. Use inline JSON for short input; for longer or generated input, put exactly one JSON object in a caller-owned regular non-symlink UTF-8 JSON file and pass --input @path; relative paths resolve from the command working directory.`;
1434
+ var CEAL_MODEL_INPUT_SOURCE_GUIDANCE = `${CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE} On Windows, write the JSON file first; use the program's .cmd launcher with --input and only one quoted @path argument.`;
1423
1435
  function shellSingleQuoted(value) {
1424
1436
  return `'${value.replaceAll("'", "'\\''")}'`;
1425
1437
  }
@@ -2455,9 +2467,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2455
2467
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
2456
2468
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
2457
2469
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2458
- // This reason cannot distinguish a Codex side conversation from a missing
2459
- // context in a regular session, so guidance must leave that choice to the caller.
2460
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2470
+ // A missing turn right after a Host restart clears by itself once the
2471
+ // watcher reactivates the turn, so the caller waits briefly and retries;
2472
+ // a caller that knows it is in an ephemeral side conversation keeps the
2473
+ // standalone fallback the guidance names second.
2474
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
2461
2475
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2462
2476
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2463
2477
  // `no_binding` now means the producer has no real current Host session. The
@@ -2474,7 +2488,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2474
2488
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2475
2489
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2476
2490
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2477
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2491
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
2478
2492
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2479
2493
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2480
2494
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2958,6 +2972,7 @@ function hostClientProbeRefusal(probe, subject) {
2958
2972
  }
2959
2973
 
2960
2974
  // host/invocation-authentication-command.ts
2975
+ import { createHash as createHash7 } from "node:crypto";
2961
2976
  import { performance } from "node:perf_hooks";
2962
2977
 
2963
2978
  // host/relay/src/producer-frame.ts
@@ -2976,13 +2991,86 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2976
2991
 
2977
2992
  // host/relay/src/host-producer-core.ts
2978
2993
  import { createHash as createHash4 } from "node:crypto";
2994
+ import { readdir } from "node:fs/promises";
2979
2995
 
2980
2996
  // host/secure-file.ts
2981
2997
  import { execFile } from "node:child_process";
2982
2998
  import { constants } from "node:fs";
2983
2999
  import { lstat, open } from "node:fs/promises";
2984
- import { dirname, join as join2, win32 } from "node:path";
3000
+ import { dirname, join as join3, win32 } from "node:path";
2985
3001
  import { fileURLToPath } from "node:url";
3002
+
3003
+ // host/spawn-working-directory.ts
3004
+ import { mkdirSync } from "node:fs";
3005
+ import { tmpdir } from "node:os";
3006
+ import { isAbsolute, join as join2, normalize, parse, sep } from "node:path";
3007
+ function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
3008
+ const candidates = [];
3009
+ const explicit = candidateDir(stateRoot);
3010
+ if (explicit !== void 0) candidates.push(explicit);
3011
+ const fallback = defaultHostStateRoot();
3012
+ if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
3013
+ const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
3014
+ if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
3015
+ for (const dir of candidates) {
3016
+ if (!keptOutside(dir, keepOutside)) continue;
3017
+ try {
3018
+ mkdirSync(dir, { recursive: true, mode: 448 });
3019
+ return dir;
3020
+ } catch {
3021
+ continue;
3022
+ }
3023
+ }
3024
+ return tmpdir();
3025
+ }
3026
+ function candidateDir(dir) {
3027
+ if (dir === void 0 || dir === "") return void 0;
3028
+ if (!isAbsolute(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
3029
+ return normalize(dir);
3030
+ }
3031
+ function defaultHostStateRoot() {
3032
+ if (process.platform === "win32") {
3033
+ const localAppData = nonEmptyEnv("LOCALAPPDATA");
3034
+ if (localAppData === void 0) return void 0;
3035
+ return candidateDir(join2(localAppData, "Ceal", "Host"));
3036
+ }
3037
+ if (process.platform === "darwin") {
3038
+ const home2 = nonEmptyEnv("HOME");
3039
+ if (home2 === void 0) return void 0;
3040
+ return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
3041
+ }
3042
+ const xdg = nonEmptyEnv("XDG_STATE_HOME");
3043
+ if (xdg !== void 0) {
3044
+ const root = candidateDir(join2(xdg, "ceal", "host"));
3045
+ if (root !== void 0) return root;
3046
+ }
3047
+ const home = nonEmptyEnv("HOME");
3048
+ if (home === void 0) return void 0;
3049
+ return candidateDir(join2(home, ".local", "state", "ceal", "host"));
3050
+ }
3051
+ function nonEmptyEnv(name) {
3052
+ const value = process.env[name];
3053
+ return value === void 0 || value === "" ? void 0 : value;
3054
+ }
3055
+ function keptOutside(dir, keepOutside) {
3056
+ for (const tree of keepOutside) {
3057
+ const clean = candidateDir(tree);
3058
+ if (clean === void 0) continue;
3059
+ if (insideDir(dir, clean)) return false;
3060
+ }
3061
+ return true;
3062
+ }
3063
+ function insideDir(dir, tree) {
3064
+ if (sameDir(dir, tree)) return true;
3065
+ if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
3066
+ return dir.startsWith(tree + sep);
3067
+ }
3068
+ function sameDir(left, right) {
3069
+ if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
3070
+ return left === right;
3071
+ }
3072
+
3073
+ // host/secure-file.ts
2986
3074
  var SecureFileCustodyError = class extends Error {
2987
3075
  name = "SecureFileCustodyError";
2988
3076
  reason;
@@ -3090,7 +3178,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
3090
3178
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
3091
3179
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
3092
3180
  return await new Promise((resolve, reject) => {
3093
- const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
3181
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: resolveCealSpawnWorkingDirectory() }, (error, stdout, stderr) => {
3094
3182
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
3095
3183
  if (exitCode === null) {
3096
3184
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -3119,7 +3207,7 @@ function securefsRefusal(stderr) {
3119
3207
  }
3120
3208
  function resolveInstalledHostExecutable(platform) {
3121
3209
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
3122
- return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3210
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3123
3211
  }
3124
3212
  function isRecord(value) {
3125
3213
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -3143,7 +3231,7 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
3143
3231
 
3144
3232
  // host/service-log.ts
3145
3233
  import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
3146
- import { dirname as dirname2, isAbsolute, posix, win32 as win322 } from "node:path";
3234
+ import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win322 } from "node:path";
3147
3235
 
3148
3236
  // host/service-log-delivery.ts
3149
3237
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -3302,7 +3390,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
3302
3390
  await appendHostServiceLogLine(path, line).catch(() => void 0);
3303
3391
  }
3304
3392
  async function appendHostServiceLogLine(path, line) {
3305
- if (!isAbsolute(path)) return;
3393
+ if (!isAbsolute2(path)) return;
3306
3394
  await ensureHostServiceLogDirectory(path);
3307
3395
  await appendFile(path, line);
3308
3396
  }
@@ -3583,6 +3671,14 @@ var HostTranscriptWatcher = class {
3583
3671
  return transcriptCursorBoundsReason(handle, cursor, size);
3584
3672
  }
3585
3673
  };
3674
+ async function listHostOutboxDirectoryNames(directory) {
3675
+ try {
3676
+ return await readdir(directory);
3677
+ } catch (error) {
3678
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
3679
+ throw error;
3680
+ }
3681
+ }
3586
3682
  var HostProducerDrainCore = class {
3587
3683
  host;
3588
3684
  now;
@@ -3744,7 +3840,7 @@ function errorCode2(error) {
3744
3840
  import { createHash as createHash5 } from "node:crypto";
3745
3841
  import { constants as constants2 } from "node:fs";
3746
3842
  import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3747
- import { dirname as dirname4, join as join3 } from "node:path";
3843
+ import { dirname as dirname4, join as join4 } from "node:path";
3748
3844
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3749
3845
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3750
3846
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -3764,9 +3860,9 @@ var HostUsageFactsStore = class {
3764
3860
  afterBatchPublish;
3765
3861
  sessionDirectoryCursor;
3766
3862
  constructor(options) {
3767
- this.root = join3(options.outbox_dir, "usage-facts");
3768
- this.sessions = join3(this.root, "sessions");
3769
- this.batches = join3(this.root, "batches");
3863
+ this.root = join4(options.outbox_dir, "usage-facts");
3864
+ this.sessions = join4(this.root, "sessions");
3865
+ this.batches = join4(this.root, "batches");
3770
3866
  this.platform = options.platform ?? process.platform;
3771
3867
  this.custody = options.secure_file_custody ?? {};
3772
3868
  this.afterPendingWrite = options.afterPendingWrite;
@@ -3783,7 +3879,6 @@ var HostUsageFactsStore = class {
3783
3879
  await cursor?.close();
3784
3880
  }
3785
3881
  async readState(producer, hostSourceRef, hostSessionRef) {
3786
- await this.prepare();
3787
3882
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3788
3883
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3789
3884
  if (value === null) return null;
@@ -3841,11 +3936,15 @@ var HostUsageFactsStore = class {
3841
3936
  }
3842
3937
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3843
3938
  async sweepOrphanedBatches(state) {
3844
- await this.prepare();
3845
3939
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3846
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3847
3940
  const expected = expectedBatchNames(state);
3848
- const directory = await opendir(directoryPath);
3941
+ let directory;
3942
+ try {
3943
+ directory = await opendir(directoryPath);
3944
+ } catch (error) {
3945
+ if (errorCode3(error) === "ENOENT") return 0;
3946
+ throw error;
3947
+ }
3849
3948
  let inspected = 0;
3850
3949
  let deleted = 0;
3851
3950
  try {
@@ -3854,7 +3953,7 @@ var HostUsageFactsStore = class {
3854
3953
  if (entry === null) break;
3855
3954
  inspected += 1;
3856
3955
  if (!isOrphanBatchEntry(entry, expected)) continue;
3857
- await unlink2(join3(directoryPath, entry.name));
3956
+ await unlink2(join4(directoryPath, entry.name));
3858
3957
  deleted += 1;
3859
3958
  }
3860
3959
  } finally {
@@ -3882,10 +3981,9 @@ var HostUsageFactsStore = class {
3882
3981
  });
3883
3982
  }
3884
3983
  async nextUploadCandidate(producer, hostSourceRef) {
3885
- await this.prepare();
3886
3984
  const names = await this.readNextSessionNames();
3887
3985
  for (const name of names) {
3888
- const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3986
+ const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3889
3987
  if (state === null) continue;
3890
3988
  validateStateOwner(state, producer, hostSourceRef);
3891
3989
  let validated = state;
@@ -3900,7 +3998,14 @@ var HostUsageFactsStore = class {
3900
3998
  return null;
3901
3999
  }
3902
4000
  async readNextSessionNames() {
3903
- this.sessionDirectoryCursor ??= await opendir(this.sessions);
4001
+ if (this.sessionDirectoryCursor === void 0) {
4002
+ try {
4003
+ this.sessionDirectoryCursor = await opendir(this.sessions);
4004
+ } catch (error) {
4005
+ if (errorCode3(error) === "ENOENT") return [];
4006
+ throw error;
4007
+ }
4008
+ }
3904
4009
  const names = [];
3905
4010
  let inspected = 0;
3906
4011
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -4066,14 +4171,14 @@ var HostUsageFactsStore = class {
4066
4171
  }
4067
4172
  }
4068
4173
  sessionPath(producer, hostSourceRef, hostSessionRef) {
4069
- return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
4174
+ return join4(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
4070
4175
  }
4071
4176
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
4072
4177
  const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
4073
- return join3(this.batches, sessionName.slice(0, -5));
4178
+ return join4(this.batches, sessionName.slice(0, -5));
4074
4179
  }
4075
4180
  batchPath(state, batchRef) {
4076
- return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
4181
+ return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
4077
4182
  }
4078
4183
  };
4079
4184
  function serializeBatch(batch) {
@@ -4642,6 +4747,10 @@ var HostUsageFactsUploader = class {
4642
4747
  async close() {
4643
4748
  await this.store.close();
4644
4749
  }
4750
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
4751
+ async prepare() {
4752
+ await this.store.prepare();
4753
+ }
4645
4754
  async uploadOne(signal) {
4646
4755
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4647
4756
  if (candidate === null) return false;
@@ -4664,6 +4773,11 @@ var HostUsageFactsUploader = class {
4664
4773
  };
4665
4774
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4666
4775
  const uploader = new HostUsageFactsUploader(options);
4776
+ try {
4777
+ await uploader.prepare();
4778
+ } catch {
4779
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4780
+ }
4667
4781
  let delay = 500;
4668
4782
  let failures = 0;
4669
4783
  try {
@@ -4753,7 +4867,7 @@ import { createConnection, createServer } from "node:net";
4753
4867
  import { createHmac, randomBytes } from "node:crypto";
4754
4868
  import { constants as constants5 } from "node:fs";
4755
4869
  import { link, unlink as unlink4 } from "node:fs/promises";
4756
- import { dirname as dirname7, join as join4 } from "node:path";
4870
+ import { dirname as dirname7, join as join5 } from "node:path";
4757
4871
  var RELAY_PIPE_HANDSHAKE_TIMEOUT_MS = 5e3;
4758
4872
  var RELAY_PIPE_KEY_BYTES = 32;
4759
4873
  var RELAY_PIPE_KEY_FILENAME = "relay-pipe.key";
@@ -4773,10 +4887,10 @@ var RelayPipeHandshakeError = class extends Error {
4773
4887
  }
4774
4888
  };
4775
4889
  function relayPipeStateRootForOutboxDir(outboxDir) {
4776
- return join4(dirname7(dirname7(dirname7(outboxDir))), "relay");
4890
+ return join5(dirname7(dirname7(dirname7(outboxDir))), "relay");
4777
4891
  }
4778
4892
  function relayPipeKeyPath(relayStateRoot) {
4779
- return join4(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
4893
+ return join5(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
4780
4894
  }
4781
4895
  async function loadRelayPipeKey(relayStateRoot, platform = process.platform, custody = {}) {
4782
4896
  const path = relayPipeKeyPath(relayStateRoot);
@@ -5286,17 +5400,133 @@ async function authenticateHostInvocation(descriptor, input, options) {
5286
5400
  const request2 = decodeCealHostInvocationAuthenticationRequest({ schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA, client_nonce: input[2] });
5287
5401
  const config = validateOptions(options);
5288
5402
  const now = config.now ?? (() => /* @__PURE__ */ new Date());
5289
- const { store, current } = await currentInvocation(descriptor, config, now);
5403
+ const store = descriptor.create_store(config.outbox_dir);
5404
+ const resolved = resolveIdentity(descriptor, config);
5405
+ if (resolved.status === "session_unavailable") throw new TypeError("no_binding");
5406
+ const toolCallId = resolveToolCallId(descriptor, config);
5407
+ const selection = await readHookSelection(store, resolved.identity);
5408
+ if (selection === null) {
5409
+ const callTime = await trySelectionlessCallTimeBinding(descriptor, store, resolved.identity, config, toolCallId);
5410
+ if (callTime !== null) return authenticateCallTimeBinding(descriptor, store, callTime, request2.client_nonce, config, now);
5411
+ } else if (!waitPossible(config) && !await hasLiveInvocationContext(store, resolved.identity, now)) {
5412
+ const direct = await tryDirectCallTimeBinding(descriptor, store, resolved.identity, selection, config, toolCallId);
5413
+ if (direct !== null) return authenticateCallTimeBinding(descriptor, store, direct, request2.client_nonce, config, now);
5414
+ }
5415
+ return authenticateHookGated(descriptor, store, request2.client_nonce, config, now, toolCallId);
5416
+ }
5417
+ function selectCallTimeBinding(window, toolCallId) {
5418
+ const newest = window.messages[0];
5419
+ if (newest === void 0) return null;
5420
+ return { message: newest, mode: toolCallId === void 0 ? "newest_message" : "tool_call" };
5421
+ }
5422
+ async function authenticateCallTimeBinding(descriptor, store, callTime, clientNonce, config, now) {
5290
5423
  if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
5291
- const query = await invocationMintQuery(descriptor, store, current, request2.client_nonce, config);
5424
+ const query = await invocationMintQuery(descriptor, store, { identity: callTime.binding, expires_at: callTime.expires_at }, clientNonce, config, callTime.window);
5425
+ const response2 = await mintedResult(config.mint_invocation_context, query);
5426
+ const completedAt = now();
5427
+ const newest = await rereadCallTimeNewest(descriptor, store, callTime.binding, config);
5428
+ if (newest === null || newest.host_turn_ref !== callTime.binding.host_turn_ref || newest.host_input_ref !== callTime.window.messages[0]?.host_input_ref) throw new TypeError("context_replaced");
5429
+ return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
5430
+ }
5431
+ async function authenticateHookGated(descriptor, store, clientNonce, config, now, toolCallId) {
5432
+ const { current } = await currentInvocation(descriptor, config, now, store);
5433
+ if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
5434
+ const window = await readCallTimeWindow(descriptor, store, current.identity, config);
5435
+ const selected = selectCallTimeBinding(window, toolCallId);
5436
+ if (selected !== null && selected.message.host_turn_ref !== current.identity.host_turn_ref) {
5437
+ const selection = await readHookSelection(store, current.identity);
5438
+ if (selection === null || transcriptCatchesHookSelection(selection, selected.message)) {
5439
+ return authenticateCallTimeBinding(descriptor, store, {
5440
+ binding: { ...current.identity, host_turn_ref: selected.message.host_turn_ref },
5441
+ expires_at: current.expires_at,
5442
+ window,
5443
+ mode: selected.mode
5444
+ }, clientNonce, config, now);
5445
+ }
5446
+ }
5447
+ const query = await invocationMintQuery(descriptor, store, current, clientNonce, config, window);
5292
5448
  const response2 = await mintedResult(config.mint_invocation_context, query);
5293
5449
  const completedAt = now();
5294
5450
  const rechecked = await store.readInvocationContext(current.identity.host_source_ref, current.identity.host_session_ref, completedAt);
5295
5451
  if (rechecked === null || !sameTurn(current, rechecked)) throw new TypeError("context_replaced");
5296
5452
  return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
5297
5453
  }
5298
- async function invocationMintQuery(descriptor, store, current, clientNonce, options) {
5299
- const readWindow = options.read_human_message_window?.(current.identity) ?? descriptor.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false });
5454
+ async function trySelectionlessCallTimeBinding(descriptor, store, identity, config, toolCallId) {
5455
+ const registration = await liveTranscriptRegistration(store, identity);
5456
+ if (registration === null) return null;
5457
+ let window;
5458
+ try {
5459
+ window = await readCallTimeWindow(descriptor, store, identity, config);
5460
+ } catch {
5461
+ throw new TypeError("transient_retryable");
5462
+ }
5463
+ const selected = selectCallTimeBinding(window, toolCallId);
5464
+ if (selected === null) return null;
5465
+ return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
5466
+ }
5467
+ async function tryDirectCallTimeBinding(descriptor, store, identity, selection, config, toolCallId) {
5468
+ let window;
5469
+ try {
5470
+ window = await readCallTimeWindow(descriptor, store, identity, config);
5471
+ } catch {
5472
+ return null;
5473
+ }
5474
+ const selected = selectCallTimeBinding(window, toolCallId);
5475
+ if (selected === null || !transcriptCatchesHookSelection(selection, selected.message)) return null;
5476
+ const registration = await liveTranscriptRegistration(store, identity);
5477
+ if (registration === null) return null;
5478
+ return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
5479
+ }
5480
+ async function readCallTimeWindow(descriptor, store, identity, config) {
5481
+ return await (config.read_human_message_window?.(identity) ?? descriptor.read_human_message_window?.({ store, identity }) ?? Promise.resolve({ messages: [], truncated: false }));
5482
+ }
5483
+ function transcriptCatchesHookSelection(selection, newest) {
5484
+ if (newest.text_truncated === true) return false;
5485
+ return hostProducerPromptRef(createHash7("sha256").update(newest.text, "utf8").digest("hex")) === selection.prompt_ref;
5486
+ }
5487
+ async function readHookSelection(store, identity) {
5488
+ try {
5489
+ return await store.readInvocationTurnSelection?.(identity.host_source_ref, identity.host_session_ref) ?? null;
5490
+ } catch {
5491
+ return null;
5492
+ }
5493
+ }
5494
+ async function hasLiveInvocationContext(store, identity, now) {
5495
+ try {
5496
+ return await store.readInvocationContext(identity.host_source_ref, identity.host_session_ref, now()) !== null;
5497
+ } catch {
5498
+ return false;
5499
+ }
5500
+ }
5501
+ function waitPossible(config) {
5502
+ return (config.context_activation_wait_ms ?? 0) > 0;
5503
+ }
5504
+ async function liveTranscriptRegistration(store, identity) {
5505
+ try {
5506
+ const registration = await store.readTranscriptRegistration?.(identity.host_source_ref, identity.host_session_ref) ?? null;
5507
+ if (registration !== null && Date.parse(registration.expires_at) > Date.now()) return registration;
5508
+ } catch {
5509
+ }
5510
+ return null;
5511
+ }
5512
+ async function rereadCallTimeNewest(descriptor, store, identity, config) {
5513
+ try {
5514
+ return (await readCallTimeWindow(descriptor, store, identity, config)).messages[0] ?? null;
5515
+ } catch {
5516
+ return null;
5517
+ }
5518
+ }
5519
+ function resolveToolCallId(descriptor, options) {
5520
+ if (options.tool_call_id !== void 0) return validToolCallId(options.tool_call_id) ? options.tool_call_id : void 0;
5521
+ if (descriptor.tool_call_id_env === void 0) return void 0;
5522
+ const value = process.env[descriptor.tool_call_id_env];
5523
+ return validToolCallId(value) ? value : void 0;
5524
+ }
5525
+ function validToolCallId(value) {
5526
+ return typeof value === "string" && value.length > 0 && value.length <= 256 && !value.includes("\0");
5527
+ }
5528
+ async function invocationMintQuery(descriptor, store, current, clientNonce, options, windowOverride) {
5529
+ const readWindow = windowOverride === void 0 ? options.read_human_message_window?.(current.identity) ?? descriptor.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false }) : Promise.resolve(windowOverride);
5300
5530
  return {
5301
5531
  producer_id: descriptor.producer_id,
5302
5532
  producer_installation_ref: options.producer_installation_ref,
@@ -5328,8 +5558,7 @@ async function mintedResult(mint, query) {
5328
5558
  function validGenericGatewayRefusalStatus2(value) {
5329
5559
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 400 && value < 500 && value !== 401 && value !== 429;
5330
5560
  }
5331
- async function currentInvocation(descriptor, config, now) {
5332
- const store = descriptor.create_store(config.outbox_dir);
5561
+ async function currentInvocation(descriptor, config, now, store) {
5333
5562
  const identity = resolveIdentity(descriptor, config);
5334
5563
  if (identity.status === "session_unavailable") throw new TypeError("no_binding");
5335
5564
  const waitBudgetMs = config.context_activation_wait_ms ?? 0;
@@ -5346,7 +5575,7 @@ async function currentInvocation(descriptor, config, now) {
5346
5575
  const current = await readLiveSessionContext(store, identity.identity.host_source_ref, identity.identity.host_session_ref, observedAt);
5347
5576
  if (current !== null) {
5348
5577
  recordActivationWaitCompletion(descriptor.producer_id, waitEngaged, config.diagnostic_sink);
5349
- return { store, current };
5578
+ return { current };
5350
5579
  }
5351
5580
  await rejectWhenActivationWaitIsUnavailable(descriptor, store, identity.identity, waitEngaged, waitBudgetMs, config.diagnostic_sink);
5352
5581
  const remainingMs = deadline - monotonicNow();
@@ -5420,7 +5649,7 @@ function waitForContextActivation(milliseconds) {
5420
5649
  });
5421
5650
  }
5422
5651
  function validateOptions(options) {
5423
- if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || !validOptionalSession(options.session_id)) {
5652
+ if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || options.tool_call_id !== void 0 && typeof options.tool_call_id !== "string" || !validOptionalSession(options.session_id)) {
5424
5653
  throw new TypeError("options_invalid");
5425
5654
  }
5426
5655
  return options;
@@ -5673,7 +5902,7 @@ function boundedMilliseconds(value) {
5673
5902
  }
5674
5903
 
5675
5904
  // host/claude/src/claude-decoder.ts
5676
- import { createHash as createHash7 } from "node:crypto";
5905
+ import { createHash as createHash8 } from "node:crypto";
5677
5906
 
5678
5907
  // host/claude/src/claude-types.ts
5679
5908
  var CLAUDE_SESSION_ID_ENVIRONMENT = "CLAUDE_CODE_SESSION_ID";
@@ -5770,7 +5999,7 @@ function queuedRowIdentity(row) {
5770
5999
  return { uuid: row.uuid, timestamp: row.timestamp };
5771
6000
  }
5772
6001
  function queueEnqueueTurnId(sessionId, timestamp4, content) {
5773
- return `queue-enqueue:${createHash7("sha256").update(`${sessionId}
6002
+ return `queue-enqueue:${createHash8("sha256").update(`${sessionId}
5774
6003
  ${timestamp4}
5775
6004
  ${content}`, "utf8").digest("hex").slice(0, 32)}`;
5776
6005
  }
@@ -5784,15 +6013,15 @@ function claudeLocalInputRef(sessionId, turnId) {
5784
6013
  return `claude-input:${cealRequestSha256({ session_id: sessionId, prompt_id: turnId })}`;
5785
6014
  }
5786
6015
  function digest(value) {
5787
- return createHash7("sha256").update(value, "utf8").digest("hex");
6016
+ return createHash8("sha256").update(value, "utf8").digest("hex");
5788
6017
  }
5789
6018
  function record3(value) {
5790
6019
  return value !== null && typeof value === "object" && !Array.isArray(value);
5791
6020
  }
5792
6021
 
5793
6022
  // host/claude/src/claude-outbox.ts
5794
- import { mkdir as mkdir5, readdir, readFile, unlink as unlink5 } from "node:fs/promises";
5795
- import { isAbsolute as isAbsolute3, join as join5 } from "node:path";
6023
+ import { mkdir as mkdir5, readFile, unlink as unlink5 } from "node:fs/promises";
6024
+ import { isAbsolute as isAbsolute4, join as join6 } from "node:path";
5796
6025
 
5797
6026
  // host/invocation-context.ts
5798
6027
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -5846,7 +6075,7 @@ function safeRef2(value) {
5846
6075
  }
5847
6076
 
5848
6077
  // host/claude/src/claude-invocation-context.ts
5849
- import { isAbsolute as isAbsolute2 } from "node:path";
6078
+ import { isAbsolute as isAbsolute3 } from "node:path";
5850
6079
  function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
5851
6080
  return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
5852
6081
  }
@@ -5875,7 +6104,7 @@ function optionalSafeRef(value) {
5875
6104
  return value === void 0 || safeRef3(value);
5876
6105
  }
5877
6106
  function optionalDirectory(value) {
5878
- return value === void 0 || typeof value === "string" && isAbsolute2(value) && !value.includes("\0") && value.length <= 4096;
6107
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && !value.includes("\0") && value.length <= 4096;
5879
6108
  }
5880
6109
  function safeRef3(value) {
5881
6110
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
@@ -5900,14 +6129,14 @@ var ClaudeOutboxStore = class {
5900
6129
  activeContexts;
5901
6130
  turnSelections;
5902
6131
  constructor(directory) {
5903
- if (!isAbsolute3(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
6132
+ if (!isAbsolute4(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
5904
6133
  this.directory = directory;
5905
- this.envelopes = join5(directory, "envelopes");
5906
- this.sessions = join5(directory, "sessions");
5907
- this.registrations = join5(directory, "transcript-registrations");
5908
- this.cursors = join5(directory, "transcript-cursors");
5909
- this.activeContexts = join5(directory, "active-contexts");
5910
- this.turnSelections = join5(directory, "turn-selections");
6134
+ this.envelopes = join6(directory, "envelopes");
6135
+ this.sessions = join6(directory, "sessions");
6136
+ this.registrations = join6(directory, "transcript-registrations");
6137
+ this.cursors = join6(directory, "transcript-cursors");
6138
+ this.activeContexts = join6(directory, "active-contexts");
6139
+ this.turnSelections = join6(directory, "turn-selections");
5911
6140
  }
5912
6141
  async prepare() {
5913
6142
  for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
@@ -5935,6 +6164,7 @@ var ClaudeOutboxStore = class {
5935
6164
  const path = this.activeContextPath(identity);
5936
6165
  const active = await readProjectionFile(path);
5937
6166
  if (active === null || active.prompt_ref !== promptRef || active.identity.host_turn_ref !== identity.host_turn_ref) return false;
6167
+ await this.prepare();
5938
6168
  const updated = { ...active, turn_generation_ref: turnGenerationRef };
5939
6169
  validateClaudeHostInvocationContext(updated);
5940
6170
  await durableAtomicReplace(path, JSON.stringify(updated));
@@ -5947,17 +6177,15 @@ var ClaudeOutboxStore = class {
5947
6177
  */
5948
6178
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
5949
6179
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
5950
- await this.prepare();
5951
6180
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, readProjectionFile);
5952
6181
  return context;
5953
6182
  }
5954
6183
  async listInvocationContexts(now = /* @__PURE__ */ new Date()) {
5955
- await this.prepare();
5956
6184
  const contexts = [];
5957
- for (const name of await readdir(this.activeContexts)) {
6185
+ for (const name of await listHostOutboxDirectoryNames(this.activeContexts)) {
5958
6186
  if (!name.endsWith(".json")) continue;
5959
6187
  try {
5960
- const value = JSON.parse(await readFile(join5(this.activeContexts, name), "utf8"));
6188
+ const value = JSON.parse(await readFile(join6(this.activeContexts, name), "utf8"));
5961
6189
  validateClaudeHostInvocationContext(value);
5962
6190
  if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
5963
6191
  } catch {
@@ -5971,13 +6199,12 @@ var ClaudeOutboxStore = class {
5971
6199
  await durableAtomicReplace(this.envelopePath(entry.submission_ref), JSON.stringify(entry));
5972
6200
  }
5973
6201
  async listEnvelopes() {
5974
- await this.prepare();
5975
6202
  const entries = [];
5976
6203
  let malformed = 0;
5977
- for (const name of await readdir(this.envelopes)) {
6204
+ for (const name of await listHostOutboxDirectoryNames(this.envelopes)) {
5978
6205
  if (!name.endsWith(".json")) continue;
5979
6206
  try {
5980
- const value = JSON.parse(await readFile(join5(this.envelopes, name), "utf8"));
6207
+ const value = JSON.parse(await readFile(join6(this.envelopes, name), "utf8"));
5981
6208
  validateEnvelope(value);
5982
6209
  entries.push(value);
5983
6210
  } catch {
@@ -5998,13 +6225,12 @@ var ClaudeOutboxStore = class {
5998
6225
  async saveSession(snapshot) {
5999
6226
  validateSession(snapshot);
6000
6227
  await this.prepare();
6001
- await durableAtomicReplace(join5(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
6228
+ await durableAtomicReplace(join6(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
6002
6229
  }
6003
6230
  async readSession(sourceRef, sessionRef) {
6004
6231
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
6005
- await this.prepare();
6006
6232
  try {
6007
- const value = JSON.parse(await readFile(join5(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
6233
+ const value = JSON.parse(await readFile(join6(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
6008
6234
  validateSession(value);
6009
6235
  return value;
6010
6236
  } catch (error) {
@@ -6035,18 +6261,16 @@ var ClaudeOutboxStore = class {
6035
6261
  }
6036
6262
  async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
6037
6263
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
6038
- await this.prepare();
6039
6264
  const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
6040
6265
  if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw new ClaudeHostError("storage", "Claude transcript registration identity does not match its session.");
6041
6266
  return registration;
6042
6267
  }
6043
6268
  async listTranscriptRegistrations() {
6044
- await this.prepare();
6045
6269
  const registrations = [];
6046
- for (const name of await readdir(this.registrations)) {
6270
+ for (const name of await listHostOutboxDirectoryNames(this.registrations)) {
6047
6271
  if (!name.endsWith(".json")) continue;
6048
6272
  try {
6049
- const value = JSON.parse(await readFile(join5(this.registrations, name), "utf8"));
6273
+ const value = JSON.parse(await readFile(join6(this.registrations, name), "utf8"));
6050
6274
  validateRegistration(value);
6051
6275
  registrations.push(value);
6052
6276
  } catch {
@@ -6056,7 +6280,6 @@ var ClaudeOutboxStore = class {
6056
6280
  }
6057
6281
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
6058
6282
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host turn selection identity is invalid.");
6059
- await this.prepare();
6060
6283
  try {
6061
6284
  const value = JSON.parse(await readFile(this.turnSelectionPath(hostSourceRef, hostSessionRef), "utf8"));
6062
6285
  if (!isHostInvocationTurnSelection(value) || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new ClaudeHostError("storage", "Claude Host turn selection is malformed.");
@@ -6068,7 +6291,6 @@ var ClaudeOutboxStore = class {
6068
6291
  }
6069
6292
  async readTranscriptCursor(registration) {
6070
6293
  validateRegistration(registration);
6071
- await this.prepare();
6072
6294
  try {
6073
6295
  const value = JSON.parse(await readFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "utf8"));
6074
6296
  validateCursor(value);
@@ -6084,16 +6306,16 @@ var ClaudeOutboxStore = class {
6084
6306
  await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
6085
6307
  }
6086
6308
  envelopePath(ref) {
6087
- return join5(this.envelopes, `${cealRequestSha256(ref)}.json`);
6309
+ return join6(this.envelopes, `${cealRequestSha256(ref)}.json`);
6088
6310
  }
6089
6311
  registrationPath(sourceRef, sessionRef) {
6090
- return join5(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
6312
+ return join6(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
6091
6313
  }
6092
6314
  turnSelectionPath(sourceRef, sessionRef) {
6093
- return join5(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
6315
+ return join6(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
6094
6316
  }
6095
6317
  cursorPath(sourceRef, sessionRef) {
6096
- return join5(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
6318
+ return join6(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
6097
6319
  }
6098
6320
  async readRegistrationFile(path) {
6099
6321
  try {
@@ -6113,7 +6335,7 @@ var ClaudeOutboxStore = class {
6113
6335
  }
6114
6336
  }
6115
6337
  activeContextPath(identity) {
6116
- return join5(this.activeContexts, `${invocationContextKey(identity)}.json`);
6338
+ return join6(this.activeContexts, `${invocationContextKey(identity)}.json`);
6117
6339
  }
6118
6340
  };
6119
6341
  function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
@@ -6189,7 +6411,7 @@ function validateRegistration(value) {
6189
6411
  if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
6190
6412
  }
6191
6413
  function validateRegistrationPaths(cwd, transcriptPath) {
6192
- if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute3(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
6414
+ if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute4(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
6193
6415
  throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
6194
6416
  }
6195
6417
  if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
@@ -6310,7 +6532,7 @@ var ClaudeProducer = class {
6310
6532
  // host/claude/src/claude-transcript-watcher.ts
6311
6533
  import { readdir as readdir2 } from "node:fs/promises";
6312
6534
  import { isDeepStrictEqual } from "node:util";
6313
- import { join as join6 } from "node:path";
6535
+ import { join as join7 } from "node:path";
6314
6536
 
6315
6537
  // host/claude/src/claude-subagent-overflow-checkpoint.ts
6316
6538
  var ClaudeSubagentOverflowCheckpoint = class {
@@ -6603,7 +6825,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6603
6825
  return consumed;
6604
6826
  }
6605
6827
  async consumeSubagentFile(draft, directory, name) {
6606
- const path = join6(directory, name);
6828
+ const path = join7(directory, name);
6607
6829
  let handle;
6608
6830
  try {
6609
6831
  handle = await openNoFollow(path);
@@ -6852,7 +7074,7 @@ function isAssistantUsageLine(record6) {
6852
7074
  }
6853
7075
  function subagentsDirectory(transcriptPath) {
6854
7076
  const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
6855
- return join6(stem, "subagents");
7077
+ return join7(stem, "subagents");
6856
7078
  }
6857
7079
  function observationRef(hostSourceRef, event, identity, value) {
6858
7080
  return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
@@ -6905,10 +7127,10 @@ async function drainClaudeProducerOnce(options) {
6905
7127
  }
6906
7128
 
6907
7129
  // host/claude/src/claude-usage-facts-capturer.ts
6908
- import { createHash as createHash8 } from "node:crypto";
7130
+ import { createHash as createHash9 } from "node:crypto";
6909
7131
  import { constants as constants7 } from "node:fs";
6910
7132
  import { readdir as readdir3 } from "node:fs/promises";
6911
- import { join as join7 } from "node:path";
7133
+ import { join as join8 } from "node:path";
6912
7134
  var ClaudeUsageFactsCapturer = class {
6913
7135
  sources;
6914
7136
  usage;
@@ -7021,7 +7243,7 @@ var ClaudeUsageFactsCapturer = class {
7021
7243
  async captureSubagentFile(registration, name, state) {
7022
7244
  let handle;
7023
7245
  try {
7024
- const opened = await readHostUsageTranscriptSource(() => openNoFollow(join7(subagentsDirectory(registration.transcript_path), name), constants7.O_RDONLY));
7246
+ const opened = await readHostUsageTranscriptSource(() => openNoFollow(join8(subagentsDirectory(registration.transcript_path), name), constants7.O_RDONLY));
7025
7247
  handle = opened;
7026
7248
  const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
7027
7249
  const sourceRef = sourceFileRef(registration, file.device, file.inode);
@@ -7268,7 +7490,7 @@ function errorCode5(error) {
7268
7490
  return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
7269
7491
  }
7270
7492
  function sha2563(value) {
7271
- return createHash8("sha256").update(value).digest("hex");
7493
+ return createHash9("sha256").update(value).digest("hex");
7272
7494
  }
7273
7495
 
7274
7496
  // host/claude/src/claude-producer-service.ts
@@ -7290,14 +7512,14 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
7290
7512
  // host/claude/src/claude-visible-output-budget.ts
7291
7513
  import { readFile as readFile2 } from "node:fs/promises";
7292
7514
  import { homedir } from "node:os";
7293
- import { join as join9 } from "node:path";
7515
+ import { join as join10 } from "node:path";
7294
7516
 
7295
7517
  // host/claude/src/claude-runtime-paths.ts
7296
- import { join as join8 } from "node:path";
7518
+ import { join as join9 } from "node:path";
7297
7519
  var CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT = "CLAUDE_CONFIG_DIR";
7298
7520
  var CLAUDE_HOME_DEFAULT_DIRECTORY = ".claude";
7299
7521
  function resolveClaudeConfigHome(environment, home) {
7300
- return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join8(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
7522
+ return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join9(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
7301
7523
  }
7302
7524
 
7303
7525
  // host/claude/src/claude-visible-output-budget.ts
@@ -7311,9 +7533,9 @@ async function resolveClaudeVisibleOutputMaxBytes(environment = process.env, wor
7311
7533
  }
7312
7534
  async function projectOrUserInlineLimit(environment, workingDirectory) {
7313
7535
  const configHome = resolveClaudeConfigHome(environment, homedir());
7314
- const userLimit = await settingsInlineLimit(join9(configHome, "settings.json"));
7315
- const projectLimit = await settingsInlineLimit(join9(workingDirectory, ".claude", "settings.json"));
7316
- const localLimit = await settingsInlineLimit(join9(workingDirectory, ".claude", "settings.local.json"));
7536
+ const userLimit = await settingsInlineLimit(join10(configHome, "settings.json"));
7537
+ const projectLimit = await settingsInlineLimit(join10(workingDirectory, ".claude", "settings.json"));
7538
+ const localLimit = await settingsInlineLimit(join10(workingDirectory, ".claude", "settings.local.json"));
7317
7539
  const candidate = localLimit ?? projectLimit ?? userLimit;
7318
7540
  return candidate === void 0 ? void 0 : Math.min(candidate, CLAUDE_MAX_INLINE_OUTPUT_MAX_CHARS);
7319
7541
  }
@@ -7370,10 +7592,10 @@ async function readClaudeInvocationHumanMessageWindow(input) {
7370
7592
  }
7371
7593
 
7372
7594
  // host/client-doctor.ts
7373
- import { createHash as createHash9 } from "node:crypto";
7595
+ import { createHash as createHash10 } from "node:crypto";
7374
7596
  import { execFile as execFile2 } from "node:child_process";
7375
7597
  import { access, open as open4, readFile as readFile3, realpath, stat as stat2 } from "node:fs/promises";
7376
- import { delimiter, extname, isAbsolute as isAbsolute4, join as join10 } from "node:path";
7598
+ import { delimiter, extname, isAbsolute as isAbsolute5, join as join11 } from "node:path";
7377
7599
  import { promisify } from "node:util";
7378
7600
 
7379
7601
  // host/environment.ts
@@ -7540,8 +7762,8 @@ async function resolveCealExecutable(command, environment, platform = process.pl
7540
7762
  if (!metadata.isFile()) continue;
7541
7763
  const launcherKind = await inspectLauncherKind(path);
7542
7764
  if (launcherKind !== void 0) return resolveLauncherBinary(path, launcherKind, environment, platform);
7543
- if (platform === "win32" && !isAbsolute4(command) && extname(path) === "") continue;
7544
- return { path, sha256: createHash9("sha256").update(await readFile3(path)).digest("hex") };
7765
+ if (platform === "win32" && !isAbsolute5(command) && extname(path) === "") continue;
7766
+ return { path, sha256: createHash10("sha256").update(await readFile3(path)).digest("hex") };
7545
7767
  } catch {
7546
7768
  }
7547
7769
  }
@@ -7563,7 +7785,7 @@ async function inspectLauncherKind(path) {
7563
7785
  }
7564
7786
  async function resolveLauncherBinary(launcherPath, kind, environment, platform) {
7565
7787
  const invocation = hostScriptLauncherInvocation(launcherPath, CEAL_CLIENT_DOCTOR_COMMAND, kind, platform, environment);
7566
- const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
7788
+ const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, cwd: resolveCealSpawnWorkingDirectory(), ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
7567
7789
  let parsed;
7568
7790
  try {
7569
7791
  parsed = JSON.parse(result.stdout);
@@ -7574,18 +7796,18 @@ async function resolveLauncherBinary(launcherPath, kind, environment, platform)
7574
7796
  const binaryPath = await realpath(parsed.binary_path);
7575
7797
  const metadata = await stat2(binaryPath);
7576
7798
  if (!metadata.isFile()) throw new Error("launcher doctor reported a non-file binary path");
7577
- return { path: binaryPath, sha256: createHash9("sha256").update(await readFile3(binaryPath)).digest("hex") };
7799
+ return { path: binaryPath, sha256: createHash10("sha256").update(await readFile3(binaryPath)).digest("hex") };
7578
7800
  }
7579
7801
  function executableCandidates(command, environment, platform) {
7580
- if (isAbsolute4(command)) return [command];
7802
+ if (isAbsolute5(command)) return [command];
7581
7803
  const pathValue = environmentValue(environment, "PATH", platform) ?? "";
7582
7804
  const directories = pathValue.split(delimiter).filter((entry) => entry.length > 0);
7583
- if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join10(entry, command));
7584
- return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join10(entry, `${command}${suffix}`)));
7805
+ if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join11(entry, command));
7806
+ return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join11(entry, `${command}${suffix}`)));
7585
7807
  }
7586
7808
  async function executeCealCommand(executable, args, environment) {
7587
7809
  try {
7588
- const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8" });
7810
+ const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8", cwd: resolveCealSpawnWorkingDirectory() });
7589
7811
  return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
7590
7812
  } catch (error) {
7591
7813
  if (isRecord8(error)) return { exit_code: typeof error.code === "number" ? error.code : 1, stdout: typeof error.stdout === "string" ? error.stdout : "", stderr: typeof error.stderr === "string" ? error.stderr : "" };