@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.
@@ -139,7 +139,7 @@ var client_wire_contract_default = {
139
139
  },
140
140
  command_request: {
141
141
  schema_name: "ceal.command_request",
142
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
142
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
143
143
  absolute_transport_max_bytes: 65536
144
144
  },
145
145
  command_resolution: {
@@ -185,7 +185,7 @@ var client_wire_contract_default = {
185
185
  },
186
186
  command_response: {
187
187
  schema_name: "ceal.command_response",
188
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
188
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
189
189
  descriptor_field: "verified_artifact",
190
190
  request_context_field: "request_context",
191
191
  required_fields: [
@@ -198,7 +198,8 @@ var client_wire_contract_default = {
198
198
  "visible_output_max_bytes",
199
199
  "local_delivery",
200
200
  "verified_artifact",
201
- "request_context"
201
+ "request_context",
202
+ "result_file"
202
203
  ],
203
204
  bare_document_fields: [
204
205
  "invocation",
@@ -327,6 +328,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
327
328
  // (never connected, revoked, or expired). The caller runs that exact
328
329
  // Operation, completes the consent it hands back, and retries the same call.
329
330
  "connect_personal_account",
331
+ // The refusal names the caller's own preferences update step: the read
332
+ // needs a personal connection the caller holds but has not selected in
333
+ // Ceal preferences, or has not confirmed through the initial review. The
334
+ // caller reads personal.preferences.get, runs personal.preferences.update
335
+ // at the current revision to select it, and retries the same call.
336
+ "update_personal_preferences",
330
337
  // The provider or Gateway named a bounded wait; the caller waits that long
331
338
  // and submits the same read again.
332
339
  "retry_after",
@@ -467,6 +474,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
467
474
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
468
475
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
469
476
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
477
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
478
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
479
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
470
480
  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"]);
471
481
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
472
482
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -507,6 +517,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
507
517
  ]);
508
518
 
509
519
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
520
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
521
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
522
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
523
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
524
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
525
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
526
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
527
+ function escapePathPattern(value) {
528
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
529
+ }
530
+ function machineHomePathPatterns(flags) {
531
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
532
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
533
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
534
+ }
510
535
  var CealProtocolValidationError = class extends Error {
511
536
  name = "CealProtocolValidationError";
512
537
  code;
@@ -858,10 +883,13 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
858
883
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
859
884
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
860
885
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
861
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
886
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
887
+ 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}\`.`;
862
888
  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.";
863
- 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.";
889
+ 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.";
890
+ 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.";
864
891
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
892
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
865
893
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
866
894
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
867
895
  }
@@ -882,13 +910,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
882
910
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
883
911
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
884
912
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
885
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
886
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
887
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
888
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
889
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
890
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
891
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
913
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
914
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
915
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
916
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
917
+ 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),
918
+ 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),
919
+ 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),
920
+ // A stored session that predates the authority-epoch commitment carries no
921
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
922
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
923
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
924
+ 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),
925
+ 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),
926
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
927
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
892
928
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
893
929
  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),
894
930
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -903,10 +939,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
903
939
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
904
940
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
905
941
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
906
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
907
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
908
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
909
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
942
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
943
+ [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),
910
944
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
911
945
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
912
946
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -918,6 +952,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
918
952
  // The safe move varies by request. Keep the sentence conditional on the
919
953
  // same `retryable` and `next_action` facts the response exposes.
920
954
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
955
+ // 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.
956
+ 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),
921
957
  // Restored verbatim from the retired `localFailureText`
922
958
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
923
959
  // session context unavailable, so the caller repairs or adopts the
@@ -1008,7 +1044,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1008
1044
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
1009
1045
  // The bounded Host reason does not prove ephemerality. A Host refusal never
1010
1046
  // changes mode; standalone remains the separate Client authority path.
1011
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
1047
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
1012
1048
  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),
1013
1049
  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),
1014
1050
  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),
@@ -1025,7 +1061,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1025
1061
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
1026
1062
  // sandboxed Relay socket names the run-alone retry.
1027
1063
  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),
1028
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1064
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
1029
1065
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
1030
1066
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
1031
1067
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1273,7 +1309,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
1273
1309
  max_literal_nodes: 512
1274
1310
  });
1275
1311
 
1276
- // packages/ceal-client-protocol/src/operation-json-schema.ts
1312
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
1277
1313
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1278
1314
 
1279
1315
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -1420,7 +1456,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
1420
1456
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
1421
1457
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
1422
1458
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
1423
- 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.`;
1459
+ 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.`;
1460
+ 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.`;
1424
1461
  function shellSingleQuoted(value) {
1425
1462
  return `'${value.replaceAll("'", "'\\''")}'`;
1426
1463
  }
@@ -1567,6 +1604,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1567
1604
  "review_submitted",
1568
1605
  "comment_created",
1569
1606
  "reaction_created",
1607
+ "pull_request_merged",
1608
+ "release_published",
1570
1609
  "ceal_write_completed",
1571
1610
  "event_start",
1572
1611
  "all_day_start",
@@ -1578,7 +1617,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1578
1617
  "page_last_edited",
1579
1618
  "resource_modified"
1580
1619
  ]);
1581
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
1620
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
1582
1621
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
1583
1622
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
1584
1623
  "provider_page_budget",
@@ -1599,6 +1638,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1599
1638
  "github.pull_request.opened",
1600
1639
  "github.issue.edited",
1601
1640
  "github.pull_request.edited",
1641
+ "github.pull_request.merged",
1642
+ "github.release.published",
1602
1643
  "github.review.submitted",
1603
1644
  "github.issue_comment.created",
1604
1645
  "github.review_comment.created",
@@ -1612,6 +1653,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1612
1653
  "drive.file.created",
1613
1654
  "drive.file.modified",
1614
1655
  "drive.file.viewed",
1656
+ "mail.sent",
1615
1657
  "notion.page.created",
1616
1658
  "notion.page.edited"
1617
1659
  ]);
@@ -1625,6 +1667,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1625
1667
  "github.review_comment.created": "comment_created",
1626
1668
  "github.issue.opened": "resource_created",
1627
1669
  "github.pull_request.opened": "resource_created",
1670
+ "github.pull_request.merged": "pull_request_merged",
1671
+ "github.release.published": "release_published",
1628
1672
  "github.issue.edited": "resource_modified",
1629
1673
  "github.pull_request.edited": "resource_modified",
1630
1674
  "github.reaction.created": "reaction_created",
@@ -1635,6 +1679,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1635
1679
  "drive.file.created": "file_created",
1636
1680
  "drive.file.modified": "file_modified_by_me",
1637
1681
  "drive.file.viewed": "file_viewed_by_me",
1682
+ "mail.sent": "message_created",
1638
1683
  "notion.page.created": "page_created",
1639
1684
  "notion.page.edited": "page_last_edited"
1640
1685
  });
@@ -1745,6 +1790,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1745
1790
  "principal_inactive",
1746
1791
  "authority_replaced",
1747
1792
  "refresh_recovery_unavailable",
1793
+ "refresh_recovery_outcome_unavailable",
1794
+ "refresh_state_unavailable",
1748
1795
  "refresh_recovery_expired",
1749
1796
  // The serving gate answers this while the Gateway is still starting and the
1750
1797
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -2394,9 +2441,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2394
2441
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
2395
2442
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
2396
2443
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2397
- // This reason cannot distinguish a Codex side conversation from a missing
2398
- // context in a regular session, so guidance must leave that choice to the caller.
2399
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2444
+ // A missing turn right after a Host restart clears by itself once the
2445
+ // watcher reactivates the turn, so the caller waits briefly and retries;
2446
+ // a caller that knows it is in an ephemeral side conversation keeps the
2447
+ // standalone fallback the guidance names second.
2448
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
2400
2449
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2401
2450
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2402
2451
  // `no_binding` now means the producer has no real current Host session. The
@@ -2413,7 +2462,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2413
2462
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2414
2463
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2415
2464
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2416
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2465
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
2417
2466
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2418
2467
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2419
2468
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2503,6 +2552,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2503
2552
  maximum: CEAL_PROTOCOL_VERSION
2504
2553
  });
2505
2554
 
2555
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
2556
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2557
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2558
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2559
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2560
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2561
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2562
+ function redactOperatorDiagnosticSecrets(value) {
2563
+ 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]");
2564
+ }
2565
+ function redactOperatorDiagnosticText(value) {
2566
+ const normalized = normalizeCealSingleLineText(value);
2567
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2568
+ }
2569
+ function renderOperatorDiagnostic(value) {
2570
+ const state = collectDiagnosticState(value);
2571
+ const fields = [
2572
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2573
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2574
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
2575
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
2576
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
2577
+ ].filter((field) => field !== void 0);
2578
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2579
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2580
+ }
2581
+ function collectDiagnosticState(value) {
2582
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2583
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
2584
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2585
+ const current = pending.shift();
2586
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2587
+ }
2588
+ return state;
2589
+ }
2590
+ function visitDiagnosticNode(current, state, pending, visited) {
2591
+ if (isObject(current)) {
2592
+ if (visited.has(current)) return;
2593
+ visited.add(current);
2594
+ }
2595
+ captureProcessEvidence(current, state);
2596
+ appendCause(current, state.causes);
2597
+ enqueueCauseChildren(current, state.causes.length, pending);
2598
+ }
2599
+ function captureProcessEvidence(current, state) {
2600
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
2601
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
2602
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2603
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2604
+ }
2605
+ function appendCause(current, causes) {
2606
+ const errors = read(current, "errors");
2607
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2608
+ causes.push(errorCause(current));
2609
+ return;
2610
+ }
2611
+ if (!isObject(current)) {
2612
+ const message = safeText(current);
2613
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2614
+ }
2615
+ }
2616
+ function errorCause(error) {
2617
+ const name = safeText(read(error, "name")) ?? "Error";
2618
+ const message = safeText(read(error, "message"));
2619
+ const codeValue = read(error, "code");
2620
+ const code = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
2621
+ const errnoValue = read(error, "errno");
2622
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2623
+ const syscall = safeText(read(error, "syscall"));
2624
+ const path = safePath(read(error, "path"));
2625
+ 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 } });
2626
+ }
2627
+ function enqueueCauseChildren(current, causeCount, pending) {
2628
+ const cause = read(current, "cause");
2629
+ if (cause !== void 0) pending.push(cause);
2630
+ const errors = read(current, "errors");
2631
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2632
+ }
2633
+ function isObject(value) {
2634
+ return typeof value === "object" && value !== null;
2635
+ }
2636
+ function formatCause(cause) {
2637
+ const fields = [
2638
+ cause.error_class,
2639
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
2640
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
2641
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
2642
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
2643
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
2644
+ ].filter((field) => field !== void 0);
2645
+ return fields.join(" ");
2646
+ }
2647
+ function tail(value) {
2648
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
2649
+ return safeDiagnosticText(clipped);
2650
+ }
2651
+ function safeText(value) {
2652
+ if (typeof value !== "string") return void 0;
2653
+ const safe = safeDiagnosticText(value);
2654
+ if (safe.length === 0) return void 0;
2655
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
2656
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
2657
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2658
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2659
+ }
2660
+ function safePath(value) {
2661
+ if (typeof value !== "string") return void 0;
2662
+ const safe = safeDiagnosticText(value);
2663
+ if (safe.length === 0) return void 0;
2664
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2665
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2666
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
2667
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2668
+ }
2669
+ function safeDiagnosticText(value) {
2670
+ return redactOperatorDiagnosticText(String(value));
2671
+ }
2672
+ function outputText(value) {
2673
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
2674
+ if (value instanceof Uint8Array) {
2675
+ try {
2676
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
2677
+ } catch {
2678
+ return void 0;
2679
+ }
2680
+ }
2681
+ return void 0;
2682
+ }
2683
+ function safeStatus(value) {
2684
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2685
+ return typeof value === "string" ? safeText(value) : void 0;
2686
+ }
2687
+ function safeExitCode(value) {
2688
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
2689
+ }
2690
+ function read(value, key) {
2691
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
2692
+ try {
2693
+ return Reflect.get(value, key);
2694
+ } catch {
2695
+ return void 0;
2696
+ }
2697
+ }
2698
+ function redactHomePaths(value) {
2699
+ const paths = [
2700
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
2701
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
2702
+ ];
2703
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
2704
+ let output = "";
2705
+ let cursor = 0;
2706
+ for (const path of paths) {
2707
+ if (path.start < cursor) continue;
2708
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
2709
+ cursor = path.end;
2710
+ }
2711
+ return output + value.slice(cursor);
2712
+ }
2713
+ function configuredHomePathPatterns() {
2714
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
2715
+ return homes.flatMap((home) => {
2716
+ const root = home.replace(/[\\/]+$/gu, "");
2717
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
2718
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
2719
+ return [{ pattern, prefixLength: root.length }];
2720
+ });
2721
+ }
2722
+ function matchedHomePrefixLength(value) {
2723
+ let separators = 0;
2724
+ for (let index = 0; index < value.length; index += 1) {
2725
+ if (value[index] !== "/" && value[index] !== "\\") continue;
2726
+ separators += 1;
2727
+ if (separators === 3) return index;
2728
+ }
2729
+ return value.length;
2730
+ }
2731
+ function redactUrls(value) {
2732
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2733
+ }
2734
+ function redactFilePaths(value) {
2735
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2736
+ }
2737
+ function homePathRange(value, match, prefixLength) {
2738
+ const index = match.index;
2739
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
2740
+ const start = index;
2741
+ let end = start + match[0].length;
2742
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
2743
+ if (quote !== void 0) {
2744
+ const closing = value.indexOf(quote, end);
2745
+ if (closing >= 0) end = closing;
2746
+ }
2747
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
2748
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
2749
+ }
2750
+ function truncateUtf8(value, maxBytes) {
2751
+ if (byteLength(value) <= maxBytes) return value;
2752
+ let output = "";
2753
+ for (const character of value) {
2754
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
2755
+ output += character;
2756
+ }
2757
+ return `${output}…`;
2758
+ }
2759
+
2506
2760
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
2507
2761
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
2508
2762
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -2589,8 +2843,80 @@ function waitForAbort(signal, milliseconds) {
2589
2843
  import { execFile } from "node:child_process";
2590
2844
  import { constants } from "node:fs";
2591
2845
  import { lstat, open } from "node:fs/promises";
2592
- import { dirname, join as join2, win32 as win323 } from "node:path";
2846
+ import { dirname, join as join3, win32 as win323 } from "node:path";
2593
2847
  import { fileURLToPath } from "node:url";
2848
+
2849
+ // host/spawn-working-directory.ts
2850
+ import { mkdirSync } from "node:fs";
2851
+ import { tmpdir } from "node:os";
2852
+ import { isAbsolute, join as join2, normalize, parse, sep } from "node:path";
2853
+ function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
2854
+ const candidates = [];
2855
+ const explicit = candidateDir(stateRoot);
2856
+ if (explicit !== void 0) candidates.push(explicit);
2857
+ const fallback = defaultHostStateRoot();
2858
+ if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
2859
+ const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
2860
+ if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
2861
+ for (const dir of candidates) {
2862
+ if (!keptOutside(dir, keepOutside)) continue;
2863
+ try {
2864
+ mkdirSync(dir, { recursive: true, mode: 448 });
2865
+ return dir;
2866
+ } catch {
2867
+ continue;
2868
+ }
2869
+ }
2870
+ return tmpdir();
2871
+ }
2872
+ function candidateDir(dir) {
2873
+ if (dir === void 0 || dir === "") return void 0;
2874
+ if (!isAbsolute(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
2875
+ return normalize(dir);
2876
+ }
2877
+ function defaultHostStateRoot() {
2878
+ if (process.platform === "win32") {
2879
+ const localAppData = nonEmptyEnv("LOCALAPPDATA");
2880
+ if (localAppData === void 0) return void 0;
2881
+ return candidateDir(join2(localAppData, "Ceal", "Host"));
2882
+ }
2883
+ if (process.platform === "darwin") {
2884
+ const home2 = nonEmptyEnv("HOME");
2885
+ if (home2 === void 0) return void 0;
2886
+ return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
2887
+ }
2888
+ const xdg = nonEmptyEnv("XDG_STATE_HOME");
2889
+ if (xdg !== void 0) {
2890
+ const root = candidateDir(join2(xdg, "ceal", "host"));
2891
+ if (root !== void 0) return root;
2892
+ }
2893
+ const home = nonEmptyEnv("HOME");
2894
+ if (home === void 0) return void 0;
2895
+ return candidateDir(join2(home, ".local", "state", "ceal", "host"));
2896
+ }
2897
+ function nonEmptyEnv(name) {
2898
+ const value = process.env[name];
2899
+ return value === void 0 || value === "" ? void 0 : value;
2900
+ }
2901
+ function keptOutside(dir, keepOutside) {
2902
+ for (const tree of keepOutside) {
2903
+ const clean = candidateDir(tree);
2904
+ if (clean === void 0) continue;
2905
+ if (insideDir(dir, clean)) return false;
2906
+ }
2907
+ return true;
2908
+ }
2909
+ function insideDir(dir, tree) {
2910
+ if (sameDir(dir, tree)) return true;
2911
+ if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
2912
+ return dir.startsWith(tree + sep);
2913
+ }
2914
+ function sameDir(left, right) {
2915
+ if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
2916
+ return left === right;
2917
+ }
2918
+
2919
+ // host/secure-file.ts
2594
2920
  var SecureFileCustodyError = class extends Error {
2595
2921
  name = "SecureFileCustodyError";
2596
2922
  reason;
@@ -2689,7 +3015,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2689
3015
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2690
3016
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2691
3017
  return await new Promise((resolve, reject2) => {
2692
- const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
3018
+ 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) => {
2693
3019
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2694
3020
  if (exitCode === null) {
2695
3021
  reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2718,7 +3044,7 @@ function securefsRefusal(stderr) {
2718
3044
  }
2719
3045
  function resolveInstalledHostExecutable(platform) {
2720
3046
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2721
- return platform === "win32" ? win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3047
+ return platform === "win32" ? win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2722
3048
  }
2723
3049
  function isRecord(value) {
2724
3050
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2934,7 +3260,7 @@ function parseCanonicalJson(text, error) {
2934
3260
  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) }])}`);
2935
3261
  return value;
2936
3262
  } catch (parseError) {
2937
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
3263
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
2938
3264
  }
2939
3265
  }
2940
3266
  function firstDifferenceIndex(left, right) {
@@ -3105,7 +3431,7 @@ function record(value) {
3105
3431
  import { createHash as createHash5 } from "node:crypto";
3106
3432
  import { constants as constants4 } from "node:fs";
3107
3433
  import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3108
- import { dirname as dirname4, join as join3 } from "node:path";
3434
+ import { dirname as dirname4, join as join4 } from "node:path";
3109
3435
 
3110
3436
  // host/relay/src/durable-atomic-replacement.ts
3111
3437
  import { lstat as lstat3, mkdir, open as open2, rename, unlink } from "node:fs/promises";
@@ -3258,9 +3584,9 @@ var HostUsageFactsStore = class {
3258
3584
  afterBatchPublish;
3259
3585
  sessionDirectoryCursor;
3260
3586
  constructor(options) {
3261
- this.root = join3(options.outbox_dir, "usage-facts");
3262
- this.sessions = join3(this.root, "sessions");
3263
- this.batches = join3(this.root, "batches");
3587
+ this.root = join4(options.outbox_dir, "usage-facts");
3588
+ this.sessions = join4(this.root, "sessions");
3589
+ this.batches = join4(this.root, "batches");
3264
3590
  this.platform = options.platform ?? process.platform;
3265
3591
  this.custody = options.secure_file_custody ?? {};
3266
3592
  this.afterPendingWrite = options.afterPendingWrite;
@@ -3277,7 +3603,6 @@ var HostUsageFactsStore = class {
3277
3603
  await cursor?.close();
3278
3604
  }
3279
3605
  async readState(producer, hostSourceRef, hostSessionRef) {
3280
- await this.prepare();
3281
3606
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3282
3607
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3283
3608
  if (value === null) return null;
@@ -3335,11 +3660,15 @@ var HostUsageFactsStore = class {
3335
3660
  }
3336
3661
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3337
3662
  async sweepOrphanedBatches(state) {
3338
- await this.prepare();
3339
3663
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3340
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3341
3664
  const expected = expectedBatchNames(state);
3342
- const directory = await opendir(directoryPath);
3665
+ let directory;
3666
+ try {
3667
+ directory = await opendir(directoryPath);
3668
+ } catch (error) {
3669
+ if (errorCode2(error) === "ENOENT") return 0;
3670
+ throw error;
3671
+ }
3343
3672
  let inspected = 0;
3344
3673
  let deleted = 0;
3345
3674
  try {
@@ -3348,7 +3677,7 @@ var HostUsageFactsStore = class {
3348
3677
  if (entry === null) break;
3349
3678
  inspected += 1;
3350
3679
  if (!isOrphanBatchEntry(entry, expected)) continue;
3351
- await unlink2(join3(directoryPath, entry.name));
3680
+ await unlink2(join4(directoryPath, entry.name));
3352
3681
  deleted += 1;
3353
3682
  }
3354
3683
  } finally {
@@ -3376,10 +3705,9 @@ var HostUsageFactsStore = class {
3376
3705
  });
3377
3706
  }
3378
3707
  async nextUploadCandidate(producer, hostSourceRef) {
3379
- await this.prepare();
3380
3708
  const names = await this.readNextSessionNames();
3381
3709
  for (const name of names) {
3382
- const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3710
+ const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3383
3711
  if (state === null) continue;
3384
3712
  validateStateOwner(state, producer, hostSourceRef);
3385
3713
  let validated = state;
@@ -3394,7 +3722,14 @@ var HostUsageFactsStore = class {
3394
3722
  return null;
3395
3723
  }
3396
3724
  async readNextSessionNames() {
3397
- this.sessionDirectoryCursor ??= await opendir(this.sessions);
3725
+ if (this.sessionDirectoryCursor === void 0) {
3726
+ try {
3727
+ this.sessionDirectoryCursor = await opendir(this.sessions);
3728
+ } catch (error) {
3729
+ if (errorCode2(error) === "ENOENT") return [];
3730
+ throw error;
3731
+ }
3732
+ }
3398
3733
  const names = [];
3399
3734
  let inspected = 0;
3400
3735
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -3549,25 +3884,25 @@ var HostUsageFactsStore = class {
3549
3884
  const gate = new Promise((resolve) => {
3550
3885
  release = resolve;
3551
3886
  });
3552
- const tail = previous.then(() => gate);
3553
- SESSION_TRANSITION_TAILS.set(key, tail);
3887
+ const tail2 = previous.then(() => gate);
3888
+ SESSION_TRANSITION_TAILS.set(key, tail2);
3554
3889
  await previous;
3555
3890
  try {
3556
3891
  return await run();
3557
3892
  } finally {
3558
3893
  release?.();
3559
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
3894
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3560
3895
  }
3561
3896
  }
3562
3897
  sessionPath(producer, hostSourceRef, hostSessionRef) {
3563
- return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3898
+ return join4(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3564
3899
  }
3565
3900
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3566
3901
  const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3567
- return join3(this.batches, sessionName.slice(0, -5));
3902
+ return join4(this.batches, sessionName.slice(0, -5));
3568
3903
  }
3569
3904
  batchPath(state, batchRef) {
3570
- return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3905
+ return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3571
3906
  }
3572
3907
  };
3573
3908
  function serializeBatch(batch) {
@@ -3808,7 +4143,7 @@ function sha2562(value) {
3808
4143
 
3809
4144
  // host/service-log.ts
3810
4145
  import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
3811
- import { dirname as dirname5, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
4146
+ import { dirname as dirname5, isAbsolute as isAbsolute2, posix as posix4, win32 as win325 } from "node:path";
3812
4147
 
3813
4148
  // host/service-log-delivery.ts
3814
4149
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -4003,7 +4338,7 @@ async function rotateHostServiceLog(path, maxBytes = HOST_SERVICE_LOG_MAX_BYTES)
4003
4338
  }
4004
4339
  function boundHostServiceLog(environment = process.env) {
4005
4340
  const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
4006
- if (path === void 0 || !isAbsolute(path)) return () => void 0;
4341
+ if (path === void 0 || !isAbsolute2(path)) return () => void 0;
4007
4342
  let reported = false;
4008
4343
  const ready = ensureHostServiceLogDirectory(path);
4009
4344
  const check = () => {
@@ -4038,7 +4373,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
4038
4373
  await appendHostServiceLogLine(path, line).catch(() => void 0);
4039
4374
  }
4040
4375
  async function appendHostServiceLogLine(path, line) {
4041
- if (!isAbsolute(path)) return;
4376
+ if (!isAbsolute2(path)) return;
4042
4377
  await ensureHostServiceLogDirectory(path);
4043
4378
  await appendFile(path, line);
4044
4379
  }
@@ -4074,6 +4409,10 @@ var HostUsageFactsUploader = class {
4074
4409
  async close() {
4075
4410
  await this.store.close();
4076
4411
  }
4412
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
4413
+ async prepare() {
4414
+ await this.store.prepare();
4415
+ }
4077
4416
  async uploadOne(signal) {
4078
4417
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4079
4418
  if (candidate === null) return false;
@@ -4096,6 +4435,11 @@ var HostUsageFactsUploader = class {
4096
4435
  };
4097
4436
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4098
4437
  const uploader = new HostUsageFactsUploader(options);
4438
+ try {
4439
+ await uploader.prepare();
4440
+ } catch {
4441
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4442
+ }
4099
4443
  let delay = 500;
4100
4444
  let failures = 0;
4101
4445
  try {
@@ -4125,6 +4469,7 @@ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4125
4469
 
4126
4470
  // host/relay/src/host-producer-core.ts
4127
4471
  import { createHash as createHash6 } from "node:crypto";
4472
+ import { readdir } from "node:fs/promises";
4128
4473
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
4129
4474
  function isHostTranscriptCursorReason(value) {
4130
4475
  return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
@@ -4169,9 +4514,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
4169
4514
  let lastNewline = -1;
4170
4515
  while (position < size) {
4171
4516
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
4172
- const read = await handle.read(buffer, 0, buffer.length, position);
4173
- if (read.bytesRead === 0) break;
4174
- const chunk = buffer.subarray(0, read.bytesRead);
4517
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
4518
+ if (read2.bytesRead === 0) break;
4519
+ const chunk = buffer.subarray(0, read2.bytesRead);
4175
4520
  chunks.push(chunk);
4176
4521
  const newline = chunk.lastIndexOf(10);
4177
4522
  if (newline >= 0) lastNewline = total + newline;
@@ -4330,6 +4675,14 @@ var HostTranscriptWatcher = class {
4330
4675
  return transcriptCursorBoundsReason(handle, cursor, size);
4331
4676
  }
4332
4677
  };
4678
+ async function listHostOutboxDirectoryNames(directory) {
4679
+ try {
4680
+ return await readdir(directory);
4681
+ } catch (error) {
4682
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
4683
+ throw error;
4684
+ }
4685
+ }
4333
4686
  var HostProducerDrainCore = class {
4334
4687
  host;
4335
4688
  now;
@@ -4344,21 +4697,21 @@ var HostProducerDrainCore = class {
4344
4697
  return run;
4345
4698
  }
4346
4699
  async drainLocked() {
4347
- const read = await this.host.listEnvelopes();
4700
+ const read2 = await this.host.listEnvelopes();
4348
4701
  let removed = 0;
4349
4702
  let expired = 0;
4350
- for (const envelope of read.entries) {
4703
+ for (const envelope of read2.entries) {
4351
4704
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
4352
4705
  else removed += 1;
4353
4706
  await this.host.removeEnvelope(envelope);
4354
4707
  }
4355
- return { removed, expired, malformed: read.malformed };
4708
+ return { removed, expired, malformed: read2.malformed };
4356
4709
  }
4357
4710
  };
4358
4711
 
4359
4712
  // host/codex/src/codex-outbox.ts
4360
- import { mkdir as mkdir4, open as open4, readdir, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
4361
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join4 } from "node:path";
4713
+ import { mkdir as mkdir4, open as open4, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
4714
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join5 } from "node:path";
4362
4715
 
4363
4716
  // host/invocation-context.ts
4364
4717
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -4436,29 +4789,46 @@ var HostUsageTranscriptSourceError = class extends Error {
4436
4789
  this.name = "HostUsageTranscriptSourceError";
4437
4790
  }
4438
4791
  };
4439
- async function readHostUsageTranscriptSource(read) {
4792
+ async function readHostUsageTranscriptSource(read2) {
4440
4793
  try {
4441
- return await read();
4794
+ return await read2();
4442
4795
  } catch (error) {
4443
4796
  throw new HostUsageTranscriptSourceError({ cause: error });
4444
4797
  }
4445
4798
  }
4446
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4447
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4448
- let failed = false;
4449
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4450
- const index = (startIndex + attempt) % registrations.length;
4451
- const registration = registrations[index];
4452
- if (registration === void 0) continue;
4453
- try {
4454
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
4455
- } catch (error) {
4456
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4799
+ var HostUsageRegistrationCapture = class {
4800
+ nextIndex = 0;
4801
+ producer;
4802
+ diagnosticSink;
4803
+ constructor(producer, diagnosticSink) {
4804
+ this.producer = producer;
4805
+ this.diagnosticSink = diagnosticSink;
4806
+ }
4807
+ async captureNext(registrations, capture) {
4808
+ let failed = false;
4809
+ let captured = false;
4810
+ const onFailure = () => {
4457
4811
  failed = true;
4812
+ };
4813
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4814
+ const index = (this.nextIndex + attempt) % registrations.length;
4815
+ const registration = registrations[index];
4816
+ if (registration === void 0) continue;
4817
+ try {
4818
+ captured = await capture(registration, onFailure);
4819
+ if (captured) {
4820
+ this.nextIndex = (index + 1) % registrations.length;
4821
+ break;
4822
+ }
4823
+ } catch (error) {
4824
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4825
+ onFailure();
4826
+ }
4458
4827
  }
4828
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
4829
+ return captured;
4459
4830
  }
4460
- return { captured: false, nextIndex: startIndex, failed };
4461
- }
4831
+ };
4462
4832
  async function openHostUsageTranscriptCursor(input) {
4463
4833
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants5.O_RDONLY));
4464
4834
  let source;
@@ -4613,12 +4983,12 @@ var CodexOutboxStore = class {
4613
4983
  constructor(directory) {
4614
4984
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
4615
4985
  this.directory = directory;
4616
- this.entriesDirectory = join4(directory, "entries");
4617
- this.sessionsDirectory = join4(directory, "sessions");
4618
- this.activeContextsDirectory = join4(directory, "active-contexts");
4619
- this.turnSelectionsDirectory = join4(directory, "turn-selections");
4620
- this.registrationsDirectory = join4(directory, "transcript-registrations");
4621
- this.cursorsDirectory = join4(directory, "transcript-cursors");
4986
+ this.entriesDirectory = join5(directory, "entries");
4987
+ this.sessionsDirectory = join5(directory, "sessions");
4988
+ this.activeContextsDirectory = join5(directory, "active-contexts");
4989
+ this.turnSelectionsDirectory = join5(directory, "turn-selections");
4990
+ this.registrationsDirectory = join5(directory, "transcript-registrations");
4991
+ this.cursorsDirectory = join5(directory, "transcript-cursors");
4622
4992
  }
4623
4993
  async prepare() {
4624
4994
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -4631,13 +5001,12 @@ var CodexOutboxStore = class {
4631
5001
  await writeAtomicJson(this.entryPath(entry.submission_ref), entry);
4632
5002
  }
4633
5003
  async list() {
4634
- await this.prepare();
4635
5004
  const entries = [];
4636
5005
  let malformed = 0;
4637
- for (const name of await readdir(this.entriesDirectory)) {
5006
+ for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
4638
5007
  if (!name.endsWith(".json")) continue;
4639
5008
  try {
4640
- const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
5009
+ const value = JSON.parse(await readOwnerStateFile(join5(this.entriesDirectory, name)));
4641
5010
  validateEnvelope(value);
4642
5011
  entries.push(value);
4643
5012
  } catch {
@@ -4682,7 +5051,6 @@ var CodexOutboxStore = class {
4682
5051
  }
4683
5052
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
4684
5053
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
4685
- await this.prepare();
4686
5054
  return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
4687
5055
  }
4688
5056
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
@@ -4691,6 +5059,7 @@ var CodexOutboxStore = class {
4691
5059
  const path = this.activeContextPath(identity);
4692
5060
  const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
4693
5061
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
5062
+ await this.prepare();
4694
5063
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
4695
5064
  return true;
4696
5065
  }
@@ -4707,7 +5076,6 @@ var CodexOutboxStore = class {
4707
5076
  */
4708
5077
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
4709
5078
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
4710
- await this.prepare();
4711
5079
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
4712
5080
  return context;
4713
5081
  }
@@ -4731,7 +5099,6 @@ var CodexOutboxStore = class {
4731
5099
  async readSession(sourceRef, sessionRef) {
4732
5100
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
4733
5101
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
4734
- await this.prepare();
4735
5102
  return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
4736
5103
  }
4737
5104
  async registerTranscript(registration) {
@@ -4757,13 +5124,18 @@ var CodexOutboxStore = class {
4757
5124
  await removeOwnerState(this.registrationPath(registration.host_source_ref, registration.host_session_ref), "registration");
4758
5125
  await removeOwnerState(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "cursor");
4759
5126
  }
5127
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
5128
+ const path = this.registrationPath(hostSourceRef, hostSessionRef);
5129
+ const registration = await readOptionalJson2(path, validateRegistration);
5130
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
5131
+ return registration;
5132
+ }
4760
5133
  async listTranscriptRegistrations() {
4761
- await this.prepare();
4762
5134
  const registrations = [];
4763
- for (const name of await readdir(this.registrationsDirectory)) {
5135
+ for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
4764
5136
  if (!name.endsWith(".json")) continue;
4765
5137
  try {
4766
- const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
5138
+ const value = JSON.parse(await readOwnerStateFile(join5(this.registrationsDirectory, name)));
4767
5139
  validateRegistration(value);
4768
5140
  registrations.push(value);
4769
5141
  } catch {
@@ -4773,7 +5145,6 @@ var CodexOutboxStore = class {
4773
5145
  }
4774
5146
  async readTranscriptCursor(registration) {
4775
5147
  validateRegistration(registration);
4776
- await this.prepare();
4777
5148
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
4778
5149
  }
4779
5150
  async writeTranscriptCursor(cursor) {
@@ -4783,36 +5154,35 @@ var CodexOutboxStore = class {
4783
5154
  }
4784
5155
  async findByAlias(sourceRef, sessionRef, alias) {
4785
5156
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef) || !SAFE_REF3.test(alias)) return null;
4786
- const read = await this.list();
4787
- const envelope = findEnvelopeByAlias(read.entries, sourceRef, sessionRef, alias);
5157
+ const read2 = await this.list();
5158
+ const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
4788
5159
  if (envelope !== null) return envelopeMatch(envelope);
4789
- await this.prepare();
4790
5160
  return null;
4791
5161
  }
4792
5162
  async hasPriorTurn(sourceRef, sessionRef) {
4793
5163
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) return false;
4794
- const read = await this.list();
4795
- if (read.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
5164
+ const read2 = await this.list();
5165
+ if (read2.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
4796
5166
  return false;
4797
5167
  }
4798
5168
  entryPath(submissionRef) {
4799
5169
  if (!SAFE_REF3.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
4800
- return join4(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
5170
+ return join5(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
4801
5171
  }
4802
5172
  sessionPath(sourceRef, sessionRef) {
4803
- return join4(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
5173
+ return join5(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
4804
5174
  }
4805
5175
  activeContextPath(identity) {
4806
- return join4(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
5176
+ return join5(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
4807
5177
  }
4808
5178
  turnSelectionPath(sourceRef, sessionRef) {
4809
- return join4(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
5179
+ return join5(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
4810
5180
  }
4811
5181
  registrationPath(sourceRef, sessionRef) {
4812
- return join4(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
5182
+ return join5(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4813
5183
  }
4814
5184
  cursorPath(sourceRef, sessionRef) {
4815
- return join4(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
5185
+ return join5(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4816
5186
  }
4817
5187
  };
4818
5188
  async function removeOwnerState(path, what) {
@@ -4848,7 +5218,7 @@ async function writeAtomicJson(path, value) {
4848
5218
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
4849
5219
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
4850
5220
  try {
4851
- const handle = await open4(temp, "wx");
5221
+ const handle = await open4(temp, "wx", 384);
4852
5222
  try {
4853
5223
  await handle.writeFile(text, "utf8");
4854
5224
  await handle.sync();
@@ -4890,13 +5260,20 @@ async function readOptionalJson2(path, validate) {
4890
5260
  }
4891
5261
  async function ensureOwnerDirectory(path) {
4892
5262
  try {
4893
- await stat2(path);
5263
+ try {
5264
+ const stats2 = await stat2(path);
5265
+ if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
5266
+ return;
5267
+ } catch (error) {
5268
+ if (!isNotFound2(error)) throw error;
5269
+ }
5270
+ await mkdir4(path, { recursive: true, mode: 448 });
5271
+ const stats = await stat2(path);
5272
+ if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
4894
5273
  } catch (error) {
4895
- if (!isNotFound2(error)) throw storageError("Codex owner state directory is unavailable.");
4896
- await mkdir4(path, { recursive: true });
5274
+ if (error instanceof CodexHostAdapterError) throw error;
5275
+ throw storageError("Codex owner state directory is unavailable.");
4897
5276
  }
4898
- const stats = await stat2(path);
4899
- if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
4900
5277
  }
4901
5278
  async function readOwnerStateFile(path) {
4902
5279
  let handle;
@@ -4939,7 +5316,7 @@ function validateRegistrationFields(value) {
4939
5316
  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 }])}).`);
4940
5317
  }
4941
5318
  function validRegistrationCwd(value) {
4942
- return value === void 0 || typeof value === "string" && isAbsolute2(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
5319
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
4943
5320
  }
4944
5321
  function validateCursor(value) {
4945
5322
  if (!isRecord6(value)) throw storageError("Codex transcript cursor is malformed.");
@@ -5702,20 +6079,16 @@ var CodexUsageFactsCapturer = class {
5702
6079
  sources;
5703
6080
  usage;
5704
6081
  now;
5705
- diagnosticSink;
5706
- nextRegistrationIndex = 0;
6082
+ registrations;
5707
6083
  constructor(options) {
5708
6084
  this.sources = new CodexOutboxStore(options.outbox_dir);
5709
6085
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5710
6086
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5711
- this.diagnosticSink = options.diagnostic_sink;
6087
+ this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
5712
6088
  }
5713
6089
  async captureNext() {
5714
6090
  const registrations = await this.sources.listTranscriptRegistrations();
5715
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
5716
- this.nextRegistrationIndex = result.nextIndex;
5717
- if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5718
- return result.captured;
6091
+ return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
5719
6092
  }
5720
6093
  async captureRegistration(registration) {
5721
6094
  const prepared = await openHostUsageTranscriptCursor({