@corca-org/ceal-host-win32-x64 1.0.23 → 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) {
@@ -91,7 +91,7 @@ var client_wire_contract_default = {
91
91
  },
92
92
  command_request: {
93
93
  schema_name: "ceal.command_request",
94
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
94
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
95
95
  absolute_transport_max_bytes: 65536
96
96
  },
97
97
  command_resolution: {
@@ -137,7 +137,7 @@ var client_wire_contract_default = {
137
137
  },
138
138
  command_response: {
139
139
  schema_name: "ceal.command_response",
140
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
140
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
141
141
  descriptor_field: "verified_artifact",
142
142
  request_context_field: "request_context",
143
143
  required_fields: [
@@ -150,7 +150,8 @@ var client_wire_contract_default = {
150
150
  "visible_output_max_bytes",
151
151
  "local_delivery",
152
152
  "verified_artifact",
153
- "request_context"
153
+ "request_context",
154
+ "result_file"
154
155
  ],
155
156
  bare_document_fields: [
156
157
  "invocation",
@@ -279,6 +280,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
279
280
  // (never connected, revoked, or expired). The caller runs that exact
280
281
  // Operation, completes the consent it hands back, and retries the same call.
281
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",
282
289
  // The provider or Gateway named a bounded wait; the caller waits that long
283
290
  // and submits the same read again.
284
291
  "retry_after",
@@ -419,6 +426,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
419
426
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
420
427
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
421
428
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
429
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
430
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
431
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
422
432
  var CEAL_GATEWAY_READ_REUSE_DISPOSITIONS = vocabulary(["response_cache_hit", "corpus_hit", "corpus_hit_after_revalidation", "corpus_partial_provider_supplement", "provider_direct", "provider_continuation", "reuse_unavailable"]);
423
433
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
424
434
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -459,6 +469,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
459
469
  ]);
460
470
 
461
471
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
472
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
473
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
474
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
475
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
476
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
477
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
478
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
479
+ function escapePathPattern(value) {
480
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
481
+ }
482
+ function machineHomePathPatterns(flags) {
483
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
484
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
485
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
486
+ }
462
487
  var CealProtocolValidationError = class extends Error {
463
488
  name = "CealProtocolValidationError";
464
489
  code;
@@ -810,10 +835,13 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
810
835
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
811
836
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
812
837
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
813
- 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}\`.`;
814
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.";
815
- 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.";
816
843
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
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.";
817
845
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
818
846
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
819
847
  }
@@ -834,13 +862,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
834
862
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
835
863
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
836
864
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
837
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
838
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
839
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
840
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
841
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
842
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
843
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
865
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
866
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
867
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
868
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
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),
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),
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),
875
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
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),
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),
878
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
879
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
844
880
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
845
881
  session_store_unwritable: guidance("The Ceal client could not write its local session store; the operating system refused the write (EACCES, EPERM, or EROFS). rerun_outside_agent_sandbox reruns it with escalated execution.", "rerun_outside_agent_sandbox", 500),
846
882
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -855,10 +891,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
855
891
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
856
892
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
857
893
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
858
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
859
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
860
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
861
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
894
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
895
+ [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance("The Gateway is still starting; the refresh was not attempted and the refresh token was not consumed. Retry the same refresh attempt after the Gateway is serving.", "retry", 503, true),
862
896
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
863
897
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
864
898
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -870,6 +904,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
870
904
  // The safe move varies by request. Keep the sentence conditional on the
871
905
  // same `retryable` and `next_action` facts the response exposes.
872
906
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
907
+ // A provider write the Gateway command deadline cut after its dispatch: the write left and its receipt is still settling, so the caller reads the receipt instead of repeating the write.
908
+ write_in_progress: guidance("The provider write was dispatched but the Gateway command deadline cut the wait before its outcome settled. Do not repeat the write; read the durable receipt named by write_request_ref with write_receipt.get.", "write_receipt.get", 500),
873
909
  // Restored verbatim from the retired `localFailureText`
874
910
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
875
911
  // session context unavailable, so the caller repairs or adopts the
@@ -960,7 +996,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
960
996
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
961
997
  // The bounded Host reason does not prove ephemerality. A Host refusal never
962
998
  // changes mode; standalone remains the separate Client authority path.
963
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
999
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
964
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),
965
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),
966
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),
@@ -977,7 +1013,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
977
1013
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
978
1014
  // sandboxed Relay socket names the run-alone retry.
979
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),
980
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1016
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
981
1017
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
982
1018
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
983
1019
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1225,7 +1261,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
1225
1261
  max_literal_nodes: 512
1226
1262
  });
1227
1263
 
1228
- // packages/ceal-client-protocol/src/operation-json-schema.ts
1264
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
1229
1265
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1230
1266
 
1231
1267
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -1372,7 +1408,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
1372
1408
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
1373
1409
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
1374
1410
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
1375
- 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.`;
1376
1413
  function shellSingleQuoted(value) {
1377
1414
  return `'${value.replaceAll("'", "'\\''")}'`;
1378
1415
  }
@@ -1519,6 +1556,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1519
1556
  "review_submitted",
1520
1557
  "comment_created",
1521
1558
  "reaction_created",
1559
+ "pull_request_merged",
1560
+ "release_published",
1522
1561
  "ceal_write_completed",
1523
1562
  "event_start",
1524
1563
  "all_day_start",
@@ -1530,7 +1569,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1530
1569
  "page_last_edited",
1531
1570
  "resource_modified"
1532
1571
  ]);
1533
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
1572
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
1534
1573
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
1535
1574
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
1536
1575
  "provider_page_budget",
@@ -1551,6 +1590,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1551
1590
  "github.pull_request.opened",
1552
1591
  "github.issue.edited",
1553
1592
  "github.pull_request.edited",
1593
+ "github.pull_request.merged",
1594
+ "github.release.published",
1554
1595
  "github.review.submitted",
1555
1596
  "github.issue_comment.created",
1556
1597
  "github.review_comment.created",
@@ -1564,6 +1605,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1564
1605
  "drive.file.created",
1565
1606
  "drive.file.modified",
1566
1607
  "drive.file.viewed",
1608
+ "mail.sent",
1567
1609
  "notion.page.created",
1568
1610
  "notion.page.edited"
1569
1611
  ]);
@@ -1577,6 +1619,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1577
1619
  "github.review_comment.created": "comment_created",
1578
1620
  "github.issue.opened": "resource_created",
1579
1621
  "github.pull_request.opened": "resource_created",
1622
+ "github.pull_request.merged": "pull_request_merged",
1623
+ "github.release.published": "release_published",
1580
1624
  "github.issue.edited": "resource_modified",
1581
1625
  "github.pull_request.edited": "resource_modified",
1582
1626
  "github.reaction.created": "reaction_created",
@@ -1587,6 +1631,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1587
1631
  "drive.file.created": "file_created",
1588
1632
  "drive.file.modified": "file_modified_by_me",
1589
1633
  "drive.file.viewed": "file_viewed_by_me",
1634
+ "mail.sent": "message_created",
1590
1635
  "notion.page.created": "page_created",
1591
1636
  "notion.page.edited": "page_last_edited"
1592
1637
  });
@@ -1697,6 +1742,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1697
1742
  "principal_inactive",
1698
1743
  "authority_replaced",
1699
1744
  "refresh_recovery_unavailable",
1745
+ "refresh_recovery_outcome_unavailable",
1746
+ "refresh_state_unavailable",
1700
1747
  "refresh_recovery_expired",
1701
1748
  // The serving gate answers this while the Gateway is still starting and the
1702
1749
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -2346,9 +2393,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2346
2393
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
2347
2394
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
2348
2395
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2349
- // This reason cannot distinguish a Codex side conversation from a missing
2350
- // context in a regular session, so guidance must leave that choice to the caller.
2351
- 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" }),
2352
2401
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2353
2402
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2354
2403
  // `no_binding` now means the producer has no real current Host session. The
@@ -2365,7 +2414,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2365
2414
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2366
2415
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2367
2416
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2368
- 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" }),
2369
2418
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2370
2419
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2371
2420
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2455,6 +2504,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2455
2504
  maximum: CEAL_PROTOCOL_VERSION
2456
2505
  });
2457
2506
 
2507
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
2508
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2509
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2510
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2511
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2512
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2513
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2514
+ function redactOperatorDiagnosticSecrets(value) {
2515
+ return value.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer [redacted]").replace(/(["']?(?:authorization|[A-Za-z0-9_-]*(?:token|secret|credential|password|key))["']?\s*[:=]\s*)(?!(?:"unknown"|'unknown'|unknown\b))(?:"[^"]*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
2516
+ }
2517
+ function redactOperatorDiagnosticText(value) {
2518
+ const normalized = normalizeCealSingleLineText(value);
2519
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2520
+ }
2521
+ function renderOperatorDiagnostic(value) {
2522
+ const state = collectDiagnosticState(value);
2523
+ const fields = [
2524
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2525
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2526
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
2527
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
2528
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
2529
+ ].filter((field) => field !== void 0);
2530
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2531
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2532
+ }
2533
+ function collectDiagnosticState(value) {
2534
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2535
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
2536
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2537
+ const current = pending.shift();
2538
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2539
+ }
2540
+ return state;
2541
+ }
2542
+ function visitDiagnosticNode(current, state, pending, visited) {
2543
+ if (isObject(current)) {
2544
+ if (visited.has(current)) return;
2545
+ visited.add(current);
2546
+ }
2547
+ captureProcessEvidence(current, state);
2548
+ appendCause(current, state.causes);
2549
+ enqueueCauseChildren(current, state.causes.length, pending);
2550
+ }
2551
+ function captureProcessEvidence(current, state) {
2552
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
2553
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
2554
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2555
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2556
+ }
2557
+ function appendCause(current, causes) {
2558
+ const errors = read(current, "errors");
2559
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2560
+ causes.push(errorCause(current));
2561
+ return;
2562
+ }
2563
+ if (!isObject(current)) {
2564
+ const message = safeText(current);
2565
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2566
+ }
2567
+ }
2568
+ function errorCause(error) {
2569
+ const name = safeText(read(error, "name")) ?? "Error";
2570
+ const message = safeText(read(error, "message"));
2571
+ const codeValue = read(error, "code");
2572
+ const code = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
2573
+ const errnoValue = read(error, "errno");
2574
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2575
+ const syscall = safeText(read(error, "syscall"));
2576
+ const path = safePath(read(error, "path"));
2577
+ return Object.freeze({ error_class: name, ...message === void 0 ? {} : { message }, ...code === void 0 ? {} : { code }, ...errno === void 0 ? {} : { errno }, ...syscall === void 0 ? {} : { syscall }, ...path === void 0 ? {} : { path } });
2578
+ }
2579
+ function enqueueCauseChildren(current, causeCount, pending) {
2580
+ const cause = read(current, "cause");
2581
+ if (cause !== void 0) pending.push(cause);
2582
+ const errors = read(current, "errors");
2583
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2584
+ }
2585
+ function isObject(value) {
2586
+ return typeof value === "object" && value !== null;
2587
+ }
2588
+ function formatCause(cause) {
2589
+ const fields = [
2590
+ cause.error_class,
2591
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
2592
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
2593
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
2594
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
2595
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
2596
+ ].filter((field) => field !== void 0);
2597
+ return fields.join(" ");
2598
+ }
2599
+ function tail(value) {
2600
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
2601
+ return safeDiagnosticText(clipped);
2602
+ }
2603
+ function safeText(value) {
2604
+ if (typeof value !== "string") return void 0;
2605
+ const safe = safeDiagnosticText(value);
2606
+ if (safe.length === 0) return void 0;
2607
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
2608
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
2609
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2610
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2611
+ }
2612
+ function safePath(value) {
2613
+ if (typeof value !== "string") return void 0;
2614
+ const safe = safeDiagnosticText(value);
2615
+ if (safe.length === 0) return void 0;
2616
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2617
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2618
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
2619
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2620
+ }
2621
+ function safeDiagnosticText(value) {
2622
+ return redactOperatorDiagnosticText(String(value));
2623
+ }
2624
+ function outputText(value) {
2625
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
2626
+ if (value instanceof Uint8Array) {
2627
+ try {
2628
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
2629
+ } catch {
2630
+ return void 0;
2631
+ }
2632
+ }
2633
+ return void 0;
2634
+ }
2635
+ function safeStatus(value) {
2636
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2637
+ return typeof value === "string" ? safeText(value) : void 0;
2638
+ }
2639
+ function safeExitCode(value) {
2640
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
2641
+ }
2642
+ function read(value, key) {
2643
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
2644
+ try {
2645
+ return Reflect.get(value, key);
2646
+ } catch {
2647
+ return void 0;
2648
+ }
2649
+ }
2650
+ function redactHomePaths(value) {
2651
+ const paths = [
2652
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
2653
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
2654
+ ];
2655
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
2656
+ let output = "";
2657
+ let cursor = 0;
2658
+ for (const path of paths) {
2659
+ if (path.start < cursor) continue;
2660
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
2661
+ cursor = path.end;
2662
+ }
2663
+ return output + value.slice(cursor);
2664
+ }
2665
+ function configuredHomePathPatterns() {
2666
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
2667
+ return homes.flatMap((home) => {
2668
+ const root = home.replace(/[\\/]+$/gu, "");
2669
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
2670
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
2671
+ return [{ pattern, prefixLength: root.length }];
2672
+ });
2673
+ }
2674
+ function matchedHomePrefixLength(value) {
2675
+ let separators = 0;
2676
+ for (let index = 0; index < value.length; index += 1) {
2677
+ if (value[index] !== "/" && value[index] !== "\\") continue;
2678
+ separators += 1;
2679
+ if (separators === 3) return index;
2680
+ }
2681
+ return value.length;
2682
+ }
2683
+ function redactUrls(value) {
2684
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2685
+ }
2686
+ function redactFilePaths(value) {
2687
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2688
+ }
2689
+ function homePathRange(value, match, prefixLength) {
2690
+ const index = match.index;
2691
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
2692
+ const start = index;
2693
+ let end = start + match[0].length;
2694
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
2695
+ if (quote !== void 0) {
2696
+ const closing = value.indexOf(quote, end);
2697
+ if (closing >= 0) end = closing;
2698
+ }
2699
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
2700
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
2701
+ }
2702
+ function truncateUtf8(value, maxBytes) {
2703
+ if (byteLength(value) <= maxBytes) return value;
2704
+ let output = "";
2705
+ for (const character of value) {
2706
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
2707
+ output += character;
2708
+ }
2709
+ return `${output}…`;
2710
+ }
2711
+
2458
2712
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
2459
2713
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
2460
2714
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -2662,8 +2916,8 @@ function reject(message) {
2662
2916
  }
2663
2917
 
2664
2918
  // host/codex/src/codex-outbox.ts
2665
- import { mkdir as mkdir4, open as open4, readdir, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
2666
- 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";
2667
2921
 
2668
2922
  // host/invocation-context.ts
2669
2923
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2732,13 +2986,86 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2732
2986
 
2733
2987
  // host/relay/src/host-producer-core.ts
2734
2988
  import { createHash as createHash5 } from "node:crypto";
2989
+ import { readdir } from "node:fs/promises";
2735
2990
 
2736
2991
  // host/secure-file.ts
2737
2992
  import { execFile } from "node:child_process";
2738
2993
  import { constants } from "node:fs";
2739
2994
  import { lstat, open } from "node:fs/promises";
2740
- import { dirname, join as join2, win32 } from "node:path";
2995
+ import { dirname, join as join3, win32 } from "node:path";
2741
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
2742
3069
  var SecureFileCustodyError = class extends Error {
2743
3070
  name = "SecureFileCustodyError";
2744
3071
  reason;
@@ -2837,7 +3164,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2837
3164
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2838
3165
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2839
3166
  return await new Promise((resolve3, reject3) => {
2840
- 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) => {
2841
3168
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2842
3169
  if (exitCode === null) {
2843
3170
  reject3(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2866,7 +3193,7 @@ function securefsRefusal(stderr) {
2866
3193
  }
2867
3194
  function resolveInstalledHostExecutable(platform) {
2868
3195
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2869
- 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");
2870
3197
  }
2871
3198
  function isRecord3(value) {
2872
3199
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2890,7 +3217,7 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
2890
3217
 
2891
3218
  // host/service-log.ts
2892
3219
  import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
2893
- 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";
2894
3221
 
2895
3222
  // host/service-log-delivery.ts
2896
3223
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -3056,7 +3383,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
3056
3383
  await appendHostServiceLogLine(path, line).catch(() => void 0);
3057
3384
  }
3058
3385
  async function appendHostServiceLogLine(path, line) {
3059
- if (!isAbsolute2(path)) return;
3386
+ if (!isAbsolute3(path)) return;
3060
3387
  await ensureHostServiceLogDirectory(path);
3061
3388
  await appendFile(path, line);
3062
3389
  }
@@ -3119,9 +3446,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
3119
3446
  let lastNewline = -1;
3120
3447
  while (position < size) {
3121
3448
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
3122
- const read = await handle.read(buffer, 0, buffer.length, position);
3123
- if (read.bytesRead === 0) break;
3124
- const chunk = buffer.subarray(0, read.bytesRead);
3449
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
3450
+ if (read2.bytesRead === 0) break;
3451
+ const chunk = buffer.subarray(0, read2.bytesRead);
3125
3452
  chunks.push(chunk);
3126
3453
  const newline = chunk.lastIndexOf(10);
3127
3454
  if (newline >= 0) lastNewline = total + newline;
@@ -3280,6 +3607,14 @@ var HostTranscriptWatcher = class {
3280
3607
  return transcriptCursorBoundsReason(handle, cursor, size);
3281
3608
  }
3282
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
+ }
3283
3618
  var HostProducerDrainCore = class {
3284
3619
  host;
3285
3620
  now;
@@ -3294,15 +3629,15 @@ var HostProducerDrainCore = class {
3294
3629
  return run;
3295
3630
  }
3296
3631
  async drainLocked() {
3297
- const read = await this.host.listEnvelopes();
3632
+ const read2 = await this.host.listEnvelopes();
3298
3633
  let removed = 0;
3299
3634
  let expired = 0;
3300
- for (const envelope of read.entries) {
3635
+ for (const envelope of read2.entries) {
3301
3636
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
3302
3637
  else removed += 1;
3303
3638
  await this.host.removeEnvelope(envelope);
3304
3639
  }
3305
- return { removed, expired, malformed: read.malformed };
3640
+ return { removed, expired, malformed: read2.malformed };
3306
3641
  }
3307
3642
  };
3308
3643
 
@@ -3441,7 +3776,7 @@ function errorCode(error) {
3441
3776
  import { createHash as createHash6 } from "node:crypto";
3442
3777
  import { constants as constants2 } from "node:fs";
3443
3778
  import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3444
- import { dirname as dirname4, join as join3 } from "node:path";
3779
+ import { dirname as dirname4, join as join4 } from "node:path";
3445
3780
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3446
3781
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3447
3782
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -3461,9 +3796,9 @@ var HostUsageFactsStore = class {
3461
3796
  afterBatchPublish;
3462
3797
  sessionDirectoryCursor;
3463
3798
  constructor(options) {
3464
- this.root = join3(options.outbox_dir, "usage-facts");
3465
- this.sessions = join3(this.root, "sessions");
3466
- 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");
3467
3802
  this.platform = options.platform ?? process.platform;
3468
3803
  this.custody = options.secure_file_custody ?? {};
3469
3804
  this.afterPendingWrite = options.afterPendingWrite;
@@ -3480,7 +3815,6 @@ var HostUsageFactsStore = class {
3480
3815
  await cursor?.close();
3481
3816
  }
3482
3817
  async readState(producer, hostSourceRef, hostSessionRef) {
3483
- await this.prepare();
3484
3818
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3485
3819
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3486
3820
  if (value === null) return null;
@@ -3538,11 +3872,15 @@ var HostUsageFactsStore = class {
3538
3872
  }
3539
3873
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3540
3874
  async sweepOrphanedBatches(state) {
3541
- await this.prepare();
3542
3875
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3543
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3544
3876
  const expected = expectedBatchNames(state);
3545
- 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
+ }
3546
3884
  let inspected = 0;
3547
3885
  let deleted = 0;
3548
3886
  try {
@@ -3551,7 +3889,7 @@ var HostUsageFactsStore = class {
3551
3889
  if (entry === null) break;
3552
3890
  inspected += 1;
3553
3891
  if (!isOrphanBatchEntry(entry, expected)) continue;
3554
- await unlink2(join3(directoryPath, entry.name));
3892
+ await unlink2(join4(directoryPath, entry.name));
3555
3893
  deleted += 1;
3556
3894
  }
3557
3895
  } finally {
@@ -3579,10 +3917,9 @@ var HostUsageFactsStore = class {
3579
3917
  });
3580
3918
  }
3581
3919
  async nextUploadCandidate(producer, hostSourceRef) {
3582
- await this.prepare();
3583
3920
  const names = await this.readNextSessionNames();
3584
3921
  for (const name of names) {
3585
- 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);
3586
3923
  if (state === null) continue;
3587
3924
  validateStateOwner(state, producer, hostSourceRef);
3588
3925
  let validated = state;
@@ -3597,7 +3934,14 @@ var HostUsageFactsStore = class {
3597
3934
  return null;
3598
3935
  }
3599
3936
  async readNextSessionNames() {
3600
- 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
+ }
3601
3945
  const names = [];
3602
3946
  let inspected = 0;
3603
3947
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -3752,25 +4096,25 @@ var HostUsageFactsStore = class {
3752
4096
  const gate = new Promise((resolve3) => {
3753
4097
  release = resolve3;
3754
4098
  });
3755
- const tail = previous.then(() => gate);
3756
- SESSION_TRANSITION_TAILS.set(key, tail);
4099
+ const tail2 = previous.then(() => gate);
4100
+ SESSION_TRANSITION_TAILS.set(key, tail2);
3757
4101
  await previous;
3758
4102
  try {
3759
4103
  return await run();
3760
4104
  } finally {
3761
4105
  release?.();
3762
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
4106
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3763
4107
  }
3764
4108
  }
3765
4109
  sessionPath(producer, hostSourceRef, hostSessionRef) {
3766
- 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`);
3767
4111
  }
3768
4112
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3769
4113
  const sessionName = `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3770
- return join3(this.batches, sessionName.slice(0, -5));
4114
+ return join4(this.batches, sessionName.slice(0, -5));
3771
4115
  }
3772
4116
  batchPath(state, batchRef) {
3773
- 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));
3774
4118
  }
3775
4119
  };
3776
4120
  function serializeBatch(batch) {
@@ -4020,29 +4364,46 @@ var HostUsageTranscriptSourceError = class extends Error {
4020
4364
  this.name = "HostUsageTranscriptSourceError";
4021
4365
  }
4022
4366
  };
4023
- async function readHostUsageTranscriptSource(read) {
4367
+ async function readHostUsageTranscriptSource(read2) {
4024
4368
  try {
4025
- return await read();
4369
+ return await read2();
4026
4370
  } catch (error) {
4027
4371
  throw new HostUsageTranscriptSourceError({ cause: error });
4028
4372
  }
4029
4373
  }
4030
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4031
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4032
- let failed = false;
4033
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4034
- const index = (startIndex + attempt) % registrations.length;
4035
- const registration = registrations[index];
4036
- if (registration === void 0) continue;
4037
- try {
4038
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
4039
- } catch (error) {
4040
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4374
+ var HostUsageRegistrationCapture = class {
4375
+ nextIndex = 0;
4376
+ producer;
4377
+ diagnosticSink;
4378
+ constructor(producer, diagnosticSink) {
4379
+ this.producer = producer;
4380
+ this.diagnosticSink = diagnosticSink;
4381
+ }
4382
+ async captureNext(registrations, capture) {
4383
+ let failed = false;
4384
+ let captured = false;
4385
+ const onFailure = () => {
4041
4386
  failed = true;
4387
+ };
4388
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4389
+ const index = (this.nextIndex + attempt) % registrations.length;
4390
+ const registration = registrations[index];
4391
+ if (registration === void 0) continue;
4392
+ try {
4393
+ captured = await capture(registration, onFailure);
4394
+ if (captured) {
4395
+ this.nextIndex = (index + 1) % registrations.length;
4396
+ break;
4397
+ }
4398
+ } catch (error) {
4399
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4400
+ onFailure();
4401
+ }
4042
4402
  }
4403
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
4404
+ return captured;
4043
4405
  }
4044
- return { captured: false, nextIndex: startIndex, failed };
4045
- }
4406
+ };
4046
4407
  async function openHostUsageTranscriptCursor(input) {
4047
4408
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
4048
4409
  let source;
@@ -4299,6 +4660,10 @@ var HostUsageFactsUploader = class {
4299
4660
  async close() {
4300
4661
  await this.store.close();
4301
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
+ }
4302
4667
  async uploadOne(signal) {
4303
4668
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4304
4669
  if (candidate === null) return false;
@@ -4321,6 +4686,11 @@ var HostUsageFactsUploader = class {
4321
4686
  };
4322
4687
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4323
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
+ }
4324
4694
  let delay = 500;
4325
4695
  let failures = 0;
4326
4696
  try {
@@ -4418,12 +4788,12 @@ var CodexOutboxStore = class {
4418
4788
  constructor(directory) {
4419
4789
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
4420
4790
  this.directory = directory;
4421
- this.entriesDirectory = join4(directory, "entries");
4422
- this.sessionsDirectory = join4(directory, "sessions");
4423
- this.activeContextsDirectory = join4(directory, "active-contexts");
4424
- this.turnSelectionsDirectory = join4(directory, "turn-selections");
4425
- this.registrationsDirectory = join4(directory, "transcript-registrations");
4426
- 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");
4427
4797
  }
4428
4798
  async prepare() {
4429
4799
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -4436,13 +4806,12 @@ var CodexOutboxStore = class {
4436
4806
  await writeAtomicJson(this.entryPath(entry.submission_ref), entry);
4437
4807
  }
4438
4808
  async list() {
4439
- await this.prepare();
4440
4809
  const entries = [];
4441
4810
  let malformed = 0;
4442
- for (const name of await readdir(this.entriesDirectory)) {
4811
+ for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
4443
4812
  if (!name.endsWith(".json")) continue;
4444
4813
  try {
4445
- const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
4814
+ const value = JSON.parse(await readOwnerStateFile(join5(this.entriesDirectory, name)));
4446
4815
  validateEnvelope(value);
4447
4816
  entries.push(value);
4448
4817
  } catch {
@@ -4487,7 +4856,6 @@ var CodexOutboxStore = class {
4487
4856
  }
4488
4857
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
4489
4858
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
4490
- await this.prepare();
4491
4859
  return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
4492
4860
  }
4493
4861
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
@@ -4496,6 +4864,7 @@ var CodexOutboxStore = class {
4496
4864
  const path = this.activeContextPath(identity);
4497
4865
  const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
4498
4866
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
4867
+ await this.prepare();
4499
4868
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
4500
4869
  return true;
4501
4870
  }
@@ -4512,7 +4881,6 @@ var CodexOutboxStore = class {
4512
4881
  */
4513
4882
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
4514
4883
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
4515
- await this.prepare();
4516
4884
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
4517
4885
  return context;
4518
4886
  }
@@ -4536,7 +4904,6 @@ var CodexOutboxStore = class {
4536
4904
  async readSession(sourceRef, sessionRef) {
4537
4905
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
4538
4906
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
4539
- await this.prepare();
4540
4907
  return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
4541
4908
  }
4542
4909
  async registerTranscript(registration) {
@@ -4562,13 +4929,18 @@ var CodexOutboxStore = class {
4562
4929
  await removeOwnerState(this.registrationPath(registration.host_source_ref, registration.host_session_ref), "registration");
4563
4930
  await removeOwnerState(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "cursor");
4564
4931
  }
4932
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
4933
+ const path = this.registrationPath(hostSourceRef, hostSessionRef);
4934
+ const registration = await readOptionalJson2(path, validateRegistration);
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.");
4936
+ return registration;
4937
+ }
4565
4938
  async listTranscriptRegistrations() {
4566
- await this.prepare();
4567
4939
  const registrations = [];
4568
- for (const name of await readdir(this.registrationsDirectory)) {
4940
+ for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
4569
4941
  if (!name.endsWith(".json")) continue;
4570
4942
  try {
4571
- const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
4943
+ const value = JSON.parse(await readOwnerStateFile(join5(this.registrationsDirectory, name)));
4572
4944
  validateRegistration(value);
4573
4945
  registrations.push(value);
4574
4946
  } catch {
@@ -4578,7 +4950,6 @@ var CodexOutboxStore = class {
4578
4950
  }
4579
4951
  async readTranscriptCursor(registration) {
4580
4952
  validateRegistration(registration);
4581
- await this.prepare();
4582
4953
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
4583
4954
  }
4584
4955
  async writeTranscriptCursor(cursor) {
@@ -4588,36 +4959,35 @@ var CodexOutboxStore = class {
4588
4959
  }
4589
4960
  async findByAlias(sourceRef, sessionRef, alias) {
4590
4961
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef) || !SAFE_REF3.test(alias)) return null;
4591
- const read = await this.list();
4592
- const envelope = findEnvelopeByAlias(read.entries, sourceRef, sessionRef, alias);
4962
+ const read2 = await this.list();
4963
+ const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
4593
4964
  if (envelope !== null) return envelopeMatch(envelope);
4594
- await this.prepare();
4595
4965
  return null;
4596
4966
  }
4597
4967
  async hasPriorTurn(sourceRef, sessionRef) {
4598
4968
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) return false;
4599
- const read = await this.list();
4600
- if (read.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
4969
+ const read2 = await this.list();
4970
+ if (read2.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
4601
4971
  return false;
4602
4972
  }
4603
4973
  entryPath(submissionRef) {
4604
4974
  if (!SAFE_REF3.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
4605
- return join4(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
4975
+ return join5(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
4606
4976
  }
4607
4977
  sessionPath(sourceRef, sessionRef) {
4608
- 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`);
4609
4979
  }
4610
4980
  activeContextPath(identity) {
4611
- return join4(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
4981
+ return join5(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
4612
4982
  }
4613
4983
  turnSelectionPath(sourceRef, sessionRef) {
4614
- 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`);
4615
4985
  }
4616
4986
  registrationPath(sourceRef, sessionRef) {
4617
- return join4(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4987
+ return join5(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4618
4988
  }
4619
4989
  cursorPath(sourceRef, sessionRef) {
4620
- return join4(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4990
+ return join5(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4621
4991
  }
4622
4992
  };
4623
4993
  async function removeOwnerState(path, what) {
@@ -4653,7 +5023,7 @@ async function writeAtomicJson(path, value) {
4653
5023
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
4654
5024
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
4655
5025
  try {
4656
- const handle = await open4(temp, "wx");
5026
+ const handle = await open4(temp, "wx", 384);
4657
5027
  try {
4658
5028
  await handle.writeFile(text, "utf8");
4659
5029
  await handle.sync();
@@ -4695,13 +5065,20 @@ async function readOptionalJson2(path, validate) {
4695
5065
  }
4696
5066
  async function ensureOwnerDirectory(path) {
4697
5067
  try {
4698
- await stat2(path);
5068
+ try {
5069
+ const stats2 = await stat2(path);
5070
+ if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
5071
+ return;
5072
+ } catch (error) {
5073
+ if (!isNotFound(error)) throw error;
5074
+ }
5075
+ await mkdir4(path, { recursive: true, mode: 448 });
5076
+ const stats = await stat2(path);
5077
+ if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
4699
5078
  } catch (error) {
4700
- if (!isNotFound(error)) throw storageError("Codex owner state directory is unavailable.");
4701
- await mkdir4(path, { recursive: true });
5079
+ if (error instanceof CodexHostAdapterError) throw error;
5080
+ throw storageError("Codex owner state directory is unavailable.");
4702
5081
  }
4703
- const stats = await stat2(path);
4704
- if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
4705
5082
  }
4706
5083
  async function readOwnerStateFile(path) {
4707
5084
  let handle;
@@ -4744,7 +5121,7 @@ function validateRegistrationFields(value) {
4744
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 }])}).`);
4745
5122
  }
4746
5123
  function validRegistrationCwd(value) {
4747
- 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");
4748
5125
  }
4749
5126
  function validateCursor(value) {
4750
5127
  if (!isRecord6(value)) throw storageError("Codex transcript cursor is malformed.");
@@ -5111,9 +5488,9 @@ async function firstCompleteLine(handle, size) {
5111
5488
  let total = 0;
5112
5489
  while (position < size) {
5113
5490
  const buffer = Buffer.alloc(Math.min(BASELINE_READ_CHUNK_BYTES, size - position));
5114
- const read = await handle.read(buffer, 0, buffer.length, position);
5115
- if (read.bytesRead === 0) break;
5116
- const chunk = buffer.subarray(0, read.bytesRead);
5491
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
5492
+ if (read2.bytesRead === 0) break;
5493
+ const chunk = buffer.subarray(0, read2.bytesRead);
5117
5494
  const newline = chunk.indexOf(10);
5118
5495
  if (newline >= 0) {
5119
5496
  chunks.push(chunk.subarray(0, newline));
@@ -5130,8 +5507,8 @@ async function lastCompleteRecordOffset(handle, size) {
5130
5507
  while (end > 0) {
5131
5508
  const start = Math.max(0, end - BASELINE_READ_CHUNK_BYTES);
5132
5509
  const buffer = Buffer.alloc(end - start);
5133
- const read = await handle.read(buffer, 0, buffer.length, start);
5134
- const newline = buffer.subarray(0, read.bytesRead).lastIndexOf(10);
5510
+ const read2 = await handle.read(buffer, 0, buffer.length, start);
5511
+ const newline = buffer.subarray(0, read2.bytesRead).lastIndexOf(10);
5135
5512
  if (newline >= 0) return start + newline + 1;
5136
5513
  end = start;
5137
5514
  }
@@ -5174,8 +5551,8 @@ async function* completeLinesBackward(handle, end) {
5174
5551
  while (position > 0) {
5175
5552
  const start = Math.max(0, position - BASELINE_READ_CHUNK_BYTES);
5176
5553
  const buffer = Buffer.alloc(position - start);
5177
- const read = await handle.read(buffer, 0, buffer.length, start);
5178
- if (read.bytesRead !== buffer.length) throw new CodexHostAdapterError("storage", "Codex transcript changed size during baseline capture.");
5554
+ const read2 = await handle.read(buffer, 0, buffer.length, start);
5555
+ if (read2.bytesRead !== buffer.length) throw new CodexHostAdapterError("storage", "Codex transcript changed size during baseline capture.");
5179
5556
  let lineEnd = buffer.length;
5180
5557
  for (let newline = buffer.lastIndexOf(10, lineEnd - 1); newline >= 0; newline = lineEnd > 0 ? buffer.lastIndexOf(10, lineEnd - 1) : -1) {
5181
5558
  yield { start: start + newline + 1, bytes: Buffer.concat([buffer.subarray(newline + 1, lineEnd), ...carry]) };
@@ -5197,15 +5574,15 @@ function timestamp2(now) {
5197
5574
  }
5198
5575
 
5199
5576
  // host/codex/src/codex-runtime-paths.ts
5200
- import { join as join5 } from "node:path";
5577
+ import { join as join6 } from "node:path";
5201
5578
  var CODEX_HOME_ENVIRONMENT = "CODEX_HOME";
5202
5579
  var CODEX_HOME_DEFAULT_DIRECTORY = ".codex";
5203
5580
  var CODEX_SESSIONS_DIRECTORY = "sessions";
5204
5581
  function resolveCodexHome(environment, home) {
5205
- return environment[CODEX_HOME_ENVIRONMENT] || join5(home, CODEX_HOME_DEFAULT_DIRECTORY);
5582
+ return environment[CODEX_HOME_ENVIRONMENT] || join6(home, CODEX_HOME_DEFAULT_DIRECTORY);
5206
5583
  }
5207
5584
  function resolveCodexSessionsRoot(environment, home) {
5208
- return join5(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
5585
+ return join6(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
5209
5586
  }
5210
5587
 
5211
5588
  // host/codex/src/codex-adapter.ts
@@ -5242,12 +5619,12 @@ async function registerSession(event, options, store, now, retentionMs) {
5242
5619
  expires_at: expiresAt
5243
5620
  };
5244
5621
  const currentTurn = await selectCurrentTurn(event, options, store, hostSessionRef);
5245
- const existing = (await store.listTranscriptRegistrations()).find((candidate) => candidate.host_source_ref === registration.host_source_ref && candidate.host_session_ref === registration.host_session_ref);
5246
- if (existing === void 0) {
5622
+ const existing = await store.readTranscriptRegistration(registration.host_source_ref, registration.host_session_ref);
5623
+ if (existing === null) {
5247
5624
  await store.writeTranscriptCursor(await captureCodexTranscriptBaseline(registration, now));
5248
5625
  }
5249
5626
  await store.registerTranscript(registration);
5250
- if (existing !== void 0 && currentTurn !== void 0 && (await store.readTranscriptCursor(registration))?.status === "quarantined") {
5627
+ if (existing !== null && currentTurn !== void 0 && (await store.readTranscriptCursor(registration))?.status === "quarantined") {
5251
5628
  await store.writeTranscriptCursor(await captureCodexTranscriptBaseline(registration, now));
5252
5629
  }
5253
5630
  if (event.event === "SessionStart") {
@@ -5296,7 +5673,7 @@ async function liveSteeredTurn(options, store, hostSessionRef, hostTurnRef) {
5296
5673
  return { host_turn_ref: hostTurnRef, prompt_ref: selection.prompt_ref, turn_generation_ref: selection.turn_generation_ref };
5297
5674
  }
5298
5675
  async function sourceBoundTranscriptPath(path, sessionsRoot) {
5299
- 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.");
5300
5677
  const transcript = resolve2(path);
5301
5678
  const root = resolve2(sessionsRoot);
5302
5679
  assertTranscriptChild(root, transcript);
@@ -5306,7 +5683,7 @@ async function sourceBoundTranscriptPath(path, sessionsRoot) {
5306
5683
  }
5307
5684
  function assertTranscriptChild(root, transcript) {
5308
5685
  const child = relative(root, transcript);
5309
- if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute4(child)) {
5686
+ if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute5(child)) {
5310
5687
  throw new CodexHostAdapterError("payload_rejected", "Codex transcript path is outside the configured sessions root.");
5311
5688
  }
5312
5689
  }
@@ -5328,7 +5705,7 @@ function validateAdapterOwner(options) {
5328
5705
  if (!SAFE_REF5.test(options.host_source_ref) || options.outbox_dir.length === 0) {
5329
5706
  throw new CodexHostAdapterError("configuration", "Codex adapter options are invalid.");
5330
5707
  }
5331
- 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.");
5332
5709
  }
5333
5710
  function validateAdapterBehavior(options) {
5334
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")}).`);
@@ -5516,7 +5893,7 @@ function parseCanonicalJson(text, error) {
5516
5893
  if (canonical !== text.trim()) throw new Error(`noncanonical: ${refusalFacts([{ name: "config_bytes", value: Buffer.byteLength(text.trim(), "utf8"), expected: `the ${Buffer.byteLength(canonical, "utf8")} bytes of its canonical form` }, { name: "first_difference_index", value: firstDifferenceIndex(text.trim(), canonical) }])}`);
5517
5894
  return value;
5518
5895
  } catch (parseError) {
5519
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
5896
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
5520
5897
  }
5521
5898
  }
5522
5899
  function firstDifferenceIndex(left, right) {
@@ -5957,20 +6334,16 @@ var CodexUsageFactsCapturer = class {
5957
6334
  sources;
5958
6335
  usage;
5959
6336
  now;
5960
- diagnosticSink;
5961
- nextRegistrationIndex = 0;
6337
+ registrations;
5962
6338
  constructor(options) {
5963
6339
  this.sources = new CodexOutboxStore(options.outbox_dir);
5964
6340
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5965
6341
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5966
- this.diagnosticSink = options.diagnostic_sink;
6342
+ this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
5967
6343
  }
5968
6344
  async captureNext() {
5969
6345
  const registrations = await this.sources.listTranscriptRegistrations();
5970
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
5971
- this.nextRegistrationIndex = result.nextIndex;
5972
- if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5973
- return result.captured;
6346
+ return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
5974
6347
  }
5975
6348
  async captureRegistration(registration) {
5976
6349
  const prepared = await openHostUsageTranscriptCursor({