@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.
@@ -6,7 +6,7 @@ const require = __cealCreateRequire(import.meta.url);
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { realpath } from "node:fs/promises";
8
8
  import { homedir } from "node:os";
9
- import { isAbsolute as isAbsolute4, relative, resolve as resolve2 } from "node:path";
9
+ import { isAbsolute as isAbsolute5, relative, resolve as resolve2 } from "node:path";
10
10
 
11
11
  // packages/ceal-client-protocol/src/vocabulary.ts
12
12
  function vocabulary(words) {
@@ -280,6 +280,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
280
280
  // (never connected, revoked, or expired). The caller runs that exact
281
281
  // Operation, completes the consent it hands back, and retries the same call.
282
282
  "connect_personal_account",
283
+ // The refusal names the caller's own preferences update step: the read
284
+ // needs a personal connection the caller holds but has not selected in
285
+ // Ceal preferences, or has not confirmed through the initial review. The
286
+ // caller reads personal.preferences.get, runs personal.preferences.update
287
+ // at the current revision to select it, and retries the same call.
288
+ "update_personal_preferences",
283
289
  // The provider or Gateway named a bounded wait; the caller waits that long
284
290
  // and submits the same read again.
285
291
  "retry_after",
@@ -829,9 +835,11 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
829
835
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
830
836
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
831
837
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
832
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
838
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
839
+ 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}\`.`;
833
840
  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.";
834
- 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.";
841
+ 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.";
842
+ 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.";
835
843
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
836
844
  var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
837
845
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
@@ -861,6 +869,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
861
869
  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),
862
870
  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),
863
871
  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),
872
+ // A stored session that predates the authority-epoch commitment carries no
873
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
874
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
864
875
  refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
865
876
  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),
866
877
  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),
@@ -985,7 +996,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
985
996
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
986
997
  // The bounded Host reason does not prove ephemerality. A Host refusal never
987
998
  // changes mode; standalone remains the separate Client authority path.
988
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
999
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
989
1000
  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),
990
1001
  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),
991
1002
  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),
@@ -1002,7 +1013,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1002
1013
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
1003
1014
  // sandboxed Relay socket names the run-alone retry.
1004
1015
  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),
1005
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1016
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
1006
1017
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
1007
1018
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
1008
1019
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1250,7 +1261,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
1250
1261
  max_literal_nodes: 512
1251
1262
  });
1252
1263
 
1253
- // packages/ceal-client-protocol/src/operation-json-schema.ts
1264
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
1254
1265
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1255
1266
 
1256
1267
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -1397,7 +1408,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
1397
1408
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
1398
1409
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
1399
1410
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
1400
- 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.`;
1411
+ 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.`;
1412
+ 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.`;
1401
1413
  function shellSingleQuoted(value) {
1402
1414
  return `'${value.replaceAll("'", "'\\''")}'`;
1403
1415
  }
@@ -2381,9 +2393,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2381
2393
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
2382
2394
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
2383
2395
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2384
- // This reason cannot distinguish a Codex side conversation from a missing
2385
- // context in a regular session, so guidance must leave that choice to the caller.
2386
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2396
+ // A missing turn right after a Host restart clears by itself once the
2397
+ // watcher reactivates the turn, so the caller waits briefly and retries;
2398
+ // a caller that knows it is in an ephemeral side conversation keeps the
2399
+ // standalone fallback the guidance names second.
2400
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
2387
2401
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2388
2402
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2389
2403
  // `no_binding` now means the producer has no real current Host session. The
@@ -2400,7 +2414,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2400
2414
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2401
2415
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2402
2416
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2403
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2417
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
2404
2418
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2405
2419
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2406
2420
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2902,8 +2916,8 @@ function reject(message) {
2902
2916
  }
2903
2917
 
2904
2918
  // host/codex/src/codex-outbox.ts
2905
- import { mkdir as mkdir4, open as open4, readdir, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
2906
- import { dirname as dirname6, isAbsolute as isAbsolute3, join as join4 } from "node:path";
2919
+ import { mkdir as mkdir4, open as open4, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
2920
+ import { dirname as dirname6, isAbsolute as isAbsolute4, join as join5 } from "node:path";
2907
2921
 
2908
2922
  // host/invocation-context.ts
2909
2923
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2972,13 +2986,86 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2972
2986
 
2973
2987
  // host/relay/src/host-producer-core.ts
2974
2988
  import { createHash as createHash5 } from "node:crypto";
2989
+ import { readdir } from "node:fs/promises";
2975
2990
 
2976
2991
  // host/secure-file.ts
2977
2992
  import { execFile } from "node:child_process";
2978
2993
  import { constants } from "node:fs";
2979
2994
  import { lstat, open } from "node:fs/promises";
2980
- import { dirname, join as join2, win32 } from "node:path";
2995
+ import { dirname, join as join3, win32 } from "node:path";
2981
2996
  import { fileURLToPath } from "node:url";
2997
+
2998
+ // host/spawn-working-directory.ts
2999
+ import { mkdirSync } from "node:fs";
3000
+ import { tmpdir } from "node:os";
3001
+ import { isAbsolute as isAbsolute2, join as join2, normalize, parse, sep } from "node:path";
3002
+ function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
3003
+ const candidates = [];
3004
+ const explicit = candidateDir(stateRoot);
3005
+ if (explicit !== void 0) candidates.push(explicit);
3006
+ const fallback = defaultHostStateRoot();
3007
+ if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
3008
+ const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
3009
+ if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
3010
+ for (const dir of candidates) {
3011
+ if (!keptOutside(dir, keepOutside)) continue;
3012
+ try {
3013
+ mkdirSync(dir, { recursive: true, mode: 448 });
3014
+ return dir;
3015
+ } catch {
3016
+ continue;
3017
+ }
3018
+ }
3019
+ return tmpdir();
3020
+ }
3021
+ function candidateDir(dir) {
3022
+ if (dir === void 0 || dir === "") return void 0;
3023
+ if (!isAbsolute2(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
3024
+ return normalize(dir);
3025
+ }
3026
+ function defaultHostStateRoot() {
3027
+ if (process.platform === "win32") {
3028
+ const localAppData = nonEmptyEnv("LOCALAPPDATA");
3029
+ if (localAppData === void 0) return void 0;
3030
+ return candidateDir(join2(localAppData, "Ceal", "Host"));
3031
+ }
3032
+ if (process.platform === "darwin") {
3033
+ const home2 = nonEmptyEnv("HOME");
3034
+ if (home2 === void 0) return void 0;
3035
+ return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
3036
+ }
3037
+ const xdg = nonEmptyEnv("XDG_STATE_HOME");
3038
+ if (xdg !== void 0) {
3039
+ const root = candidateDir(join2(xdg, "ceal", "host"));
3040
+ if (root !== void 0) return root;
3041
+ }
3042
+ const home = nonEmptyEnv("HOME");
3043
+ if (home === void 0) return void 0;
3044
+ return candidateDir(join2(home, ".local", "state", "ceal", "host"));
3045
+ }
3046
+ function nonEmptyEnv(name) {
3047
+ const value = process.env[name];
3048
+ return value === void 0 || value === "" ? void 0 : value;
3049
+ }
3050
+ function keptOutside(dir, keepOutside) {
3051
+ for (const tree of keepOutside) {
3052
+ const clean = candidateDir(tree);
3053
+ if (clean === void 0) continue;
3054
+ if (insideDir(dir, clean)) return false;
3055
+ }
3056
+ return true;
3057
+ }
3058
+ function insideDir(dir, tree) {
3059
+ if (sameDir(dir, tree)) return true;
3060
+ if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
3061
+ return dir.startsWith(tree + sep);
3062
+ }
3063
+ function sameDir(left, right) {
3064
+ if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
3065
+ return left === right;
3066
+ }
3067
+
3068
+ // host/secure-file.ts
2982
3069
  var SecureFileCustodyError = class extends Error {
2983
3070
  name = "SecureFileCustodyError";
2984
3071
  reason;
@@ -3077,7 +3164,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
3077
3164
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
3078
3165
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
3079
3166
  return await new Promise((resolve3, reject3) => {
3080
- const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
3167
+ 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) => {
3081
3168
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
3082
3169
  if (exitCode === null) {
3083
3170
  reject3(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -3106,7 +3193,7 @@ function securefsRefusal(stderr) {
3106
3193
  }
3107
3194
  function resolveInstalledHostExecutable(platform) {
3108
3195
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
3109
- return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3196
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3110
3197
  }
3111
3198
  function isRecord3(value) {
3112
3199
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -3130,7 +3217,7 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
3130
3217
 
3131
3218
  // host/service-log.ts
3132
3219
  import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
3133
- import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win322 } from "node:path";
3220
+ import { dirname as dirname2, isAbsolute as isAbsolute3, posix, win32 as win322 } from "node:path";
3134
3221
 
3135
3222
  // host/service-log-delivery.ts
3136
3223
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -3296,7 +3383,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
3296
3383
  await appendHostServiceLogLine(path, line).catch(() => void 0);
3297
3384
  }
3298
3385
  async function appendHostServiceLogLine(path, line) {
3299
- if (!isAbsolute2(path)) return;
3386
+ if (!isAbsolute3(path)) return;
3300
3387
  await ensureHostServiceLogDirectory(path);
3301
3388
  await appendFile(path, line);
3302
3389
  }
@@ -3520,6 +3607,14 @@ var HostTranscriptWatcher = class {
3520
3607
  return transcriptCursorBoundsReason(handle, cursor, size);
3521
3608
  }
3522
3609
  };
3610
+ async function listHostOutboxDirectoryNames(directory) {
3611
+ try {
3612
+ return await readdir(directory);
3613
+ } catch (error) {
3614
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
3615
+ throw error;
3616
+ }
3617
+ }
3523
3618
  var HostProducerDrainCore = class {
3524
3619
  host;
3525
3620
  now;
@@ -3681,7 +3776,7 @@ function errorCode(error) {
3681
3776
  import { createHash as createHash6 } from "node:crypto";
3682
3777
  import { constants as constants2 } from "node:fs";
3683
3778
  import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3684
- import { dirname as dirname4, join as join3 } from "node:path";
3779
+ import { dirname as dirname4, join as join4 } from "node:path";
3685
3780
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3686
3781
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3687
3782
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -3701,9 +3796,9 @@ var HostUsageFactsStore = class {
3701
3796
  afterBatchPublish;
3702
3797
  sessionDirectoryCursor;
3703
3798
  constructor(options) {
3704
- this.root = join3(options.outbox_dir, "usage-facts");
3705
- this.sessions = join3(this.root, "sessions");
3706
- this.batches = join3(this.root, "batches");
3799
+ this.root = join4(options.outbox_dir, "usage-facts");
3800
+ this.sessions = join4(this.root, "sessions");
3801
+ this.batches = join4(this.root, "batches");
3707
3802
  this.platform = options.platform ?? process.platform;
3708
3803
  this.custody = options.secure_file_custody ?? {};
3709
3804
  this.afterPendingWrite = options.afterPendingWrite;
@@ -3720,7 +3815,6 @@ var HostUsageFactsStore = class {
3720
3815
  await cursor?.close();
3721
3816
  }
3722
3817
  async readState(producer, hostSourceRef, hostSessionRef) {
3723
- await this.prepare();
3724
3818
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3725
3819
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3726
3820
  if (value === null) return null;
@@ -3778,11 +3872,15 @@ var HostUsageFactsStore = class {
3778
3872
  }
3779
3873
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3780
3874
  async sweepOrphanedBatches(state) {
3781
- await this.prepare();
3782
3875
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3783
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3784
3876
  const expected = expectedBatchNames(state);
3785
- const directory = await opendir(directoryPath);
3877
+ let directory;
3878
+ try {
3879
+ directory = await opendir(directoryPath);
3880
+ } catch (error) {
3881
+ if (errorCode2(error) === "ENOENT") return 0;
3882
+ throw error;
3883
+ }
3786
3884
  let inspected = 0;
3787
3885
  let deleted = 0;
3788
3886
  try {
@@ -3791,7 +3889,7 @@ var HostUsageFactsStore = class {
3791
3889
  if (entry === null) break;
3792
3890
  inspected += 1;
3793
3891
  if (!isOrphanBatchEntry(entry, expected)) continue;
3794
- await unlink2(join3(directoryPath, entry.name));
3892
+ await unlink2(join4(directoryPath, entry.name));
3795
3893
  deleted += 1;
3796
3894
  }
3797
3895
  } finally {
@@ -3819,10 +3917,9 @@ var HostUsageFactsStore = class {
3819
3917
  });
3820
3918
  }
3821
3919
  async nextUploadCandidate(producer, hostSourceRef) {
3822
- await this.prepare();
3823
3920
  const names = await this.readNextSessionNames();
3824
3921
  for (const name of names) {
3825
- const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3922
+ const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3826
3923
  if (state === null) continue;
3827
3924
  validateStateOwner(state, producer, hostSourceRef);
3828
3925
  let validated = state;
@@ -3837,7 +3934,14 @@ var HostUsageFactsStore = class {
3837
3934
  return null;
3838
3935
  }
3839
3936
  async readNextSessionNames() {
3840
- this.sessionDirectoryCursor ??= await opendir(this.sessions);
3937
+ if (this.sessionDirectoryCursor === void 0) {
3938
+ try {
3939
+ this.sessionDirectoryCursor = await opendir(this.sessions);
3940
+ } catch (error) {
3941
+ if (errorCode2(error) === "ENOENT") return [];
3942
+ throw error;
3943
+ }
3944
+ }
3841
3945
  const names = [];
3842
3946
  let inspected = 0;
3843
3947
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -4003,14 +4107,14 @@ var HostUsageFactsStore = class {
4003
4107
  }
4004
4108
  }
4005
4109
  sessionPath(producer, hostSourceRef, hostSessionRef) {
4006
- return join3(this.sessions, `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
4110
+ return join4(this.sessions, `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
4007
4111
  }
4008
4112
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
4009
4113
  const sessionName = `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
4010
- return join3(this.batches, sessionName.slice(0, -5));
4114
+ return join4(this.batches, sessionName.slice(0, -5));
4011
4115
  }
4012
4116
  batchPath(state, batchRef) {
4013
- return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
4117
+ return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
4014
4118
  }
4015
4119
  };
4016
4120
  function serializeBatch(batch) {
@@ -4556,6 +4660,10 @@ var HostUsageFactsUploader = class {
4556
4660
  async close() {
4557
4661
  await this.store.close();
4558
4662
  }
4663
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
4664
+ async prepare() {
4665
+ await this.store.prepare();
4666
+ }
4559
4667
  async uploadOne(signal) {
4560
4668
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4561
4669
  if (candidate === null) return false;
@@ -4578,6 +4686,11 @@ var HostUsageFactsUploader = class {
4578
4686
  };
4579
4687
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4580
4688
  const uploader = new HostUsageFactsUploader(options);
4689
+ try {
4690
+ await uploader.prepare();
4691
+ } catch {
4692
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4693
+ }
4581
4694
  let delay = 500;
4582
4695
  let failures = 0;
4583
4696
  try {
@@ -4675,12 +4788,12 @@ var CodexOutboxStore = class {
4675
4788
  constructor(directory) {
4676
4789
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
4677
4790
  this.directory = directory;
4678
- this.entriesDirectory = join4(directory, "entries");
4679
- this.sessionsDirectory = join4(directory, "sessions");
4680
- this.activeContextsDirectory = join4(directory, "active-contexts");
4681
- this.turnSelectionsDirectory = join4(directory, "turn-selections");
4682
- this.registrationsDirectory = join4(directory, "transcript-registrations");
4683
- this.cursorsDirectory = join4(directory, "transcript-cursors");
4791
+ this.entriesDirectory = join5(directory, "entries");
4792
+ this.sessionsDirectory = join5(directory, "sessions");
4793
+ this.activeContextsDirectory = join5(directory, "active-contexts");
4794
+ this.turnSelectionsDirectory = join5(directory, "turn-selections");
4795
+ this.registrationsDirectory = join5(directory, "transcript-registrations");
4796
+ this.cursorsDirectory = join5(directory, "transcript-cursors");
4684
4797
  }
4685
4798
  async prepare() {
4686
4799
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -4693,13 +4806,12 @@ var CodexOutboxStore = class {
4693
4806
  await writeAtomicJson(this.entryPath(entry.submission_ref), entry);
4694
4807
  }
4695
4808
  async list() {
4696
- await this.prepare();
4697
4809
  const entries = [];
4698
4810
  let malformed = 0;
4699
- for (const name of await readdir(this.entriesDirectory)) {
4811
+ for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
4700
4812
  if (!name.endsWith(".json")) continue;
4701
4813
  try {
4702
- const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
4814
+ const value = JSON.parse(await readOwnerStateFile(join5(this.entriesDirectory, name)));
4703
4815
  validateEnvelope(value);
4704
4816
  entries.push(value);
4705
4817
  } catch {
@@ -4744,7 +4856,6 @@ var CodexOutboxStore = class {
4744
4856
  }
4745
4857
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
4746
4858
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
4747
- await this.prepare();
4748
4859
  return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
4749
4860
  }
4750
4861
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
@@ -4753,6 +4864,7 @@ var CodexOutboxStore = class {
4753
4864
  const path = this.activeContextPath(identity);
4754
4865
  const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
4755
4866
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
4867
+ await this.prepare();
4756
4868
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
4757
4869
  return true;
4758
4870
  }
@@ -4769,7 +4881,6 @@ var CodexOutboxStore = class {
4769
4881
  */
4770
4882
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
4771
4883
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
4772
- await this.prepare();
4773
4884
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
4774
4885
  return context;
4775
4886
  }
@@ -4793,7 +4904,6 @@ var CodexOutboxStore = class {
4793
4904
  async readSession(sourceRef, sessionRef) {
4794
4905
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
4795
4906
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
4796
- await this.prepare();
4797
4907
  return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
4798
4908
  }
4799
4909
  async registerTranscript(registration) {
@@ -4821,18 +4931,16 @@ var CodexOutboxStore = class {
4821
4931
  }
4822
4932
  async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
4823
4933
  const path = this.registrationPath(hostSourceRef, hostSessionRef);
4824
- await this.prepare();
4825
4934
  const registration = await readOptionalJson2(path, validateRegistration);
4826
4935
  if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
4827
4936
  return registration;
4828
4937
  }
4829
4938
  async listTranscriptRegistrations() {
4830
- await this.prepare();
4831
4939
  const registrations = [];
4832
- for (const name of await readdir(this.registrationsDirectory)) {
4940
+ for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
4833
4941
  if (!name.endsWith(".json")) continue;
4834
4942
  try {
4835
- const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
4943
+ const value = JSON.parse(await readOwnerStateFile(join5(this.registrationsDirectory, name)));
4836
4944
  validateRegistration(value);
4837
4945
  registrations.push(value);
4838
4946
  } catch {
@@ -4842,7 +4950,6 @@ var CodexOutboxStore = class {
4842
4950
  }
4843
4951
  async readTranscriptCursor(registration) {
4844
4952
  validateRegistration(registration);
4845
- await this.prepare();
4846
4953
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
4847
4954
  }
4848
4955
  async writeTranscriptCursor(cursor) {
@@ -4855,7 +4962,6 @@ var CodexOutboxStore = class {
4855
4962
  const read2 = await this.list();
4856
4963
  const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
4857
4964
  if (envelope !== null) return envelopeMatch(envelope);
4858
- await this.prepare();
4859
4965
  return null;
4860
4966
  }
4861
4967
  async hasPriorTurn(sourceRef, sessionRef) {
@@ -4866,22 +4972,22 @@ var CodexOutboxStore = class {
4866
4972
  }
4867
4973
  entryPath(submissionRef) {
4868
4974
  if (!SAFE_REF3.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
4869
- return join4(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
4975
+ return join5(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
4870
4976
  }
4871
4977
  sessionPath(sourceRef, sessionRef) {
4872
- return join4(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
4978
+ return join5(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
4873
4979
  }
4874
4980
  activeContextPath(identity) {
4875
- return join4(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
4981
+ return join5(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
4876
4982
  }
4877
4983
  turnSelectionPath(sourceRef, sessionRef) {
4878
- return join4(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
4984
+ return join5(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
4879
4985
  }
4880
4986
  registrationPath(sourceRef, sessionRef) {
4881
- return join4(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4987
+ return join5(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4882
4988
  }
4883
4989
  cursorPath(sourceRef, sessionRef) {
4884
- return join4(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4990
+ return join5(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4885
4991
  }
4886
4992
  };
4887
4993
  async function removeOwnerState(path, what) {
@@ -5015,7 +5121,7 @@ function validateRegistrationFields(value) {
5015
5121
  if (!isTimestamp(value.registered_at) || !isTimestamp(value.expires_at)) throw storageError(`Codex transcript registration timestamps are malformed (${refusalFacts([{ name: "registered_at", value: value.registered_at }, { name: "expires_at", value: value.expires_at }])}).`);
5016
5122
  }
5017
5123
  function validRegistrationCwd(value) {
5018
- return value === void 0 || typeof value === "string" && isAbsolute3(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
5124
+ return value === void 0 || typeof value === "string" && isAbsolute4(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
5019
5125
  }
5020
5126
  function validateCursor(value) {
5021
5127
  if (!isRecord6(value)) throw storageError("Codex transcript cursor is malformed.");
@@ -5468,15 +5574,15 @@ function timestamp2(now) {
5468
5574
  }
5469
5575
 
5470
5576
  // host/codex/src/codex-runtime-paths.ts
5471
- import { join as join5 } from "node:path";
5577
+ import { join as join6 } from "node:path";
5472
5578
  var CODEX_HOME_ENVIRONMENT = "CODEX_HOME";
5473
5579
  var CODEX_HOME_DEFAULT_DIRECTORY = ".codex";
5474
5580
  var CODEX_SESSIONS_DIRECTORY = "sessions";
5475
5581
  function resolveCodexHome(environment, home) {
5476
- return environment[CODEX_HOME_ENVIRONMENT] || join5(home, CODEX_HOME_DEFAULT_DIRECTORY);
5582
+ return environment[CODEX_HOME_ENVIRONMENT] || join6(home, CODEX_HOME_DEFAULT_DIRECTORY);
5477
5583
  }
5478
5584
  function resolveCodexSessionsRoot(environment, home) {
5479
- return join5(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
5585
+ return join6(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
5480
5586
  }
5481
5587
 
5482
5588
  // host/codex/src/codex-adapter.ts
@@ -5567,7 +5673,7 @@ async function liveSteeredTurn(options, store, hostSessionRef, hostTurnRef) {
5567
5673
  return { host_turn_ref: hostTurnRef, prompt_ref: selection.prompt_ref, turn_generation_ref: selection.turn_generation_ref };
5568
5674
  }
5569
5675
  async function sourceBoundTranscriptPath(path, sessionsRoot) {
5570
- if (!isAbsolute4(path) || !isAbsolute4(sessionsRoot)) throw new CodexHostAdapterError("configuration", "Codex transcript registration paths must be absolute.");
5676
+ if (!isAbsolute5(path) || !isAbsolute5(sessionsRoot)) throw new CodexHostAdapterError("configuration", "Codex transcript registration paths must be absolute.");
5571
5677
  const transcript = resolve2(path);
5572
5678
  const root = resolve2(sessionsRoot);
5573
5679
  assertTranscriptChild(root, transcript);
@@ -5577,7 +5683,7 @@ async function sourceBoundTranscriptPath(path, sessionsRoot) {
5577
5683
  }
5578
5684
  function assertTranscriptChild(root, transcript) {
5579
5685
  const child = relative(root, transcript);
5580
- if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute4(child)) {
5686
+ if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute5(child)) {
5581
5687
  throw new CodexHostAdapterError("payload_rejected", "Codex transcript path is outside the configured sessions root.");
5582
5688
  }
5583
5689
  }
@@ -5599,7 +5705,7 @@ function validateAdapterOwner(options) {
5599
5705
  if (!SAFE_REF5.test(options.host_source_ref) || options.outbox_dir.length === 0) {
5600
5706
  throw new CodexHostAdapterError("configuration", "Codex adapter options are invalid.");
5601
5707
  }
5602
- if (options.codex_sessions_root !== void 0 && !isAbsolute4(options.codex_sessions_root)) throw new CodexHostAdapterError("configuration", "Codex sessions root is invalid.");
5708
+ if (options.codex_sessions_root !== void 0 && !isAbsolute5(options.codex_sessions_root)) throw new CodexHostAdapterError("configuration", "Codex sessions root is invalid.");
5603
5709
  }
5604
5710
  function validateAdapterBehavior(options) {
5605
5711
  if (options.retention_ms !== void 0 && (!Number.isSafeInteger(options.retention_ms) || options.retention_ms < 1)) throw new CodexHostAdapterError("configuration", `Codex retention is invalid (${refusalFact("retention_ms", options.retention_ms, "a positive integer")}).`);