@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.
@@ -2118,7 +2118,7 @@ var client_wire_contract_default = {
2118
2118
  },
2119
2119
  command_request: {
2120
2120
  schema_name: "ceal.command_request",
2121
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
2121
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
2122
2122
  absolute_transport_max_bytes: 65536
2123
2123
  },
2124
2124
  command_resolution: {
@@ -2164,7 +2164,7 @@ var client_wire_contract_default = {
2164
2164
  },
2165
2165
  command_response: {
2166
2166
  schema_name: "ceal.command_response",
2167
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
2167
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
2168
2168
  descriptor_field: "verified_artifact",
2169
2169
  request_context_field: "request_context",
2170
2170
  required_fields: [
@@ -2177,7 +2177,8 @@ var client_wire_contract_default = {
2177
2177
  "visible_output_max_bytes",
2178
2178
  "local_delivery",
2179
2179
  "verified_artifact",
2180
- "request_context"
2180
+ "request_context",
2181
+ "result_file"
2181
2182
  ],
2182
2183
  bare_document_fields: [
2183
2184
  "invocation",
@@ -2306,6 +2307,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
2306
2307
  // (never connected, revoked, or expired). The caller runs that exact
2307
2308
  // Operation, completes the consent it hands back, and retries the same call.
2308
2309
  "connect_personal_account",
2310
+ // The refusal names the caller's own preferences update step: the read
2311
+ // needs a personal connection the caller holds but has not selected in
2312
+ // Ceal preferences, or has not confirmed through the initial review. The
2313
+ // caller reads personal.preferences.get, runs personal.preferences.update
2314
+ // at the current revision to select it, and retries the same call.
2315
+ "update_personal_preferences",
2309
2316
  // The provider or Gateway named a bounded wait; the caller waits that long
2310
2317
  // and submits the same read again.
2311
2318
  "retry_after",
@@ -2446,6 +2453,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
2446
2453
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
2447
2454
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
2448
2455
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
2456
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
2457
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
2458
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
2449
2459
  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"]);
2450
2460
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
2451
2461
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -2486,6 +2496,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
2486
2496
  ]);
2487
2497
 
2488
2498
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
2499
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
2500
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
2501
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
2502
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
2503
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
2504
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
2505
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
2506
+ function escapePathPattern(value) {
2507
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
2508
+ }
2509
+ function machineHomePathPatterns(flags) {
2510
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
2511
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
2512
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
2513
+ }
2489
2514
  var CealProtocolValidationError = class extends Error {
2490
2515
  name = "CealProtocolValidationError";
2491
2516
  code;
@@ -2842,10 +2867,13 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
2842
2867
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
2843
2868
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
2844
2869
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
2845
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
2870
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
2871
+ 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}\`.`;
2846
2872
  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.";
2847
- 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.";
2873
+ 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.";
2874
+ 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.";
2848
2875
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
2876
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
2849
2877
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
2850
2878
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
2851
2879
  }
@@ -2866,13 +2894,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2866
2894
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2867
2895
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2868
2896
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2869
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2870
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2871
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2872
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2873
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2874
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2875
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2897
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2898
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2899
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2900
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2901
+ 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),
2902
+ 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),
2903
+ 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),
2904
+ // A stored session that predates the authority-epoch commitment carries no
2905
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
2906
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2907
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2908
+ 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),
2909
+ 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),
2910
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
2911
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2876
2912
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2877
2913
  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),
2878
2914
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -2887,10 +2923,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2887
2923
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
2888
2924
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
2889
2925
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
2890
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
2891
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
2892
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
2893
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
2926
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
2927
+ [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),
2894
2928
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
2895
2929
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
2896
2930
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -2902,6 +2936,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2902
2936
  // The safe move varies by request. Keep the sentence conditional on the
2903
2937
  // same `retryable` and `next_action` facts the response exposes.
2904
2938
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
2939
+ // 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.
2940
+ 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),
2905
2941
  // Restored verbatim from the retired `localFailureText`
2906
2942
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
2907
2943
  // session context unavailable, so the caller repairs or adopts the
@@ -2992,7 +3028,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2992
3028
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
2993
3029
  // The bounded Host reason does not prove ephemerality. A Host refusal never
2994
3030
  // changes mode; standalone remains the separate Client authority path.
2995
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
3031
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
2996
3032
  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),
2997
3033
  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),
2998
3034
  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),
@@ -3009,7 +3045,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
3009
3045
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
3010
3046
  // sandboxed Relay socket names the run-alone retry.
3011
3047
  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),
3012
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
3048
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
3013
3049
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
3014
3050
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
3015
3051
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -3274,7 +3310,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
3274
3310
  max_literal_nodes: 512
3275
3311
  });
3276
3312
 
3277
- // packages/ceal-client-protocol/src/operation-json-schema.ts
3313
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
3278
3314
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
3279
3315
 
3280
3316
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -3424,7 +3460,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
3424
3460
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
3425
3461
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
3426
3462
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
3427
- 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.`;
3463
+ 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.`;
3464
+ 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.`;
3428
3465
  function shellSingleQuoted(value) {
3429
3466
  return `'${value.replaceAll("'", "'\\''")}'`;
3430
3467
  }
@@ -3571,6 +3608,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3571
3608
  "review_submitted",
3572
3609
  "comment_created",
3573
3610
  "reaction_created",
3611
+ "pull_request_merged",
3612
+ "release_published",
3574
3613
  "ceal_write_completed",
3575
3614
  "event_start",
3576
3615
  "all_day_start",
@@ -3582,7 +3621,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3582
3621
  "page_last_edited",
3583
3622
  "resource_modified"
3584
3623
  ]);
3585
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
3624
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
3586
3625
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
3587
3626
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
3588
3627
  "provider_page_budget",
@@ -3603,6 +3642,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3603
3642
  "github.pull_request.opened",
3604
3643
  "github.issue.edited",
3605
3644
  "github.pull_request.edited",
3645
+ "github.pull_request.merged",
3646
+ "github.release.published",
3606
3647
  "github.review.submitted",
3607
3648
  "github.issue_comment.created",
3608
3649
  "github.review_comment.created",
@@ -3616,6 +3657,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3616
3657
  "drive.file.created",
3617
3658
  "drive.file.modified",
3618
3659
  "drive.file.viewed",
3660
+ "mail.sent",
3619
3661
  "notion.page.created",
3620
3662
  "notion.page.edited"
3621
3663
  ]);
@@ -3629,6 +3671,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3629
3671
  "github.review_comment.created": "comment_created",
3630
3672
  "github.issue.opened": "resource_created",
3631
3673
  "github.pull_request.opened": "resource_created",
3674
+ "github.pull_request.merged": "pull_request_merged",
3675
+ "github.release.published": "release_published",
3632
3676
  "github.issue.edited": "resource_modified",
3633
3677
  "github.pull_request.edited": "resource_modified",
3634
3678
  "github.reaction.created": "reaction_created",
@@ -3639,6 +3683,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3639
3683
  "drive.file.created": "file_created",
3640
3684
  "drive.file.modified": "file_modified_by_me",
3641
3685
  "drive.file.viewed": "file_viewed_by_me",
3686
+ "mail.sent": "message_created",
3642
3687
  "notion.page.created": "page_created",
3643
3688
  "notion.page.edited": "page_last_edited"
3644
3689
  });
@@ -3749,6 +3794,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
3749
3794
  "principal_inactive",
3750
3795
  "authority_replaced",
3751
3796
  "refresh_recovery_unavailable",
3797
+ "refresh_recovery_outcome_unavailable",
3798
+ "refresh_state_unavailable",
3752
3799
  "refresh_recovery_expired",
3753
3800
  // The serving gate answers this while the Gateway is still starting and the
3754
3801
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -4450,9 +4497,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
4450
4497
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
4451
4498
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
4452
4499
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
4453
- // This reason cannot distinguish a Codex side conversation from a missing
4454
- // context in a regular session, so guidance must leave that choice to the caller.
4455
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
4500
+ // A missing turn right after a Host restart clears by itself once the
4501
+ // watcher reactivates the turn, so the caller waits briefly and retries;
4502
+ // a caller that knows it is in an ephemeral side conversation keeps the
4503
+ // standalone fallback the guidance names second.
4504
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
4456
4505
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
4457
4506
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
4458
4507
  // `no_binding` now means the producer has no real current Host session. The
@@ -4469,7 +4518,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
4469
4518
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
4470
4519
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
4471
4520
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
4472
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
4521
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
4473
4522
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
4474
4523
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
4475
4524
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -4594,6 +4643,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
4594
4643
  maximum: CEAL_PROTOCOL_VERSION
4595
4644
  });
4596
4645
 
4646
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
4647
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
4648
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
4649
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
4650
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
4651
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
4652
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
4653
+ function redactOperatorDiagnosticSecrets(value) {
4654
+ 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]");
4655
+ }
4656
+ function redactOperatorDiagnosticText(value) {
4657
+ const normalized = normalizeCealSingleLineText(value);
4658
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
4659
+ }
4660
+ function renderOperatorDiagnostic(value) {
4661
+ const state = collectDiagnosticState(value);
4662
+ const fields = [
4663
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
4664
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
4665
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
4666
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
4667
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
4668
+ ].filter((field) => field !== void 0);
4669
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
4670
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
4671
+ }
4672
+ function collectDiagnosticState(value) {
4673
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
4674
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
4675
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
4676
+ const current = pending.shift();
4677
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
4678
+ }
4679
+ return state;
4680
+ }
4681
+ function visitDiagnosticNode(current, state, pending, visited) {
4682
+ if (isObject(current)) {
4683
+ if (visited.has(current)) return;
4684
+ visited.add(current);
4685
+ }
4686
+ captureProcessEvidence(current, state);
4687
+ appendCause(current, state.causes);
4688
+ enqueueCauseChildren(current, state.causes.length, pending);
4689
+ }
4690
+ function captureProcessEvidence(current, state) {
4691
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
4692
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
4693
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
4694
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
4695
+ }
4696
+ function appendCause(current, causes) {
4697
+ const errors = read(current, "errors");
4698
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
4699
+ causes.push(errorCause(current));
4700
+ return;
4701
+ }
4702
+ if (!isObject(current)) {
4703
+ const message = safeText(current);
4704
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
4705
+ }
4706
+ }
4707
+ function errorCause(error) {
4708
+ const name = safeText(read(error, "name")) ?? "Error";
4709
+ const message = safeText(read(error, "message"));
4710
+ const codeValue = read(error, "code");
4711
+ const code = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
4712
+ const errnoValue = read(error, "errno");
4713
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
4714
+ const syscall = safeText(read(error, "syscall"));
4715
+ const path = safePath(read(error, "path"));
4716
+ 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 } });
4717
+ }
4718
+ function enqueueCauseChildren(current, causeCount, pending) {
4719
+ const cause = read(current, "cause");
4720
+ if (cause !== void 0) pending.push(cause);
4721
+ const errors = read(current, "errors");
4722
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
4723
+ }
4724
+ function isObject(value) {
4725
+ return typeof value === "object" && value !== null;
4726
+ }
4727
+ function formatCause(cause) {
4728
+ const fields = [
4729
+ cause.error_class,
4730
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
4731
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
4732
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
4733
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
4734
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
4735
+ ].filter((field) => field !== void 0);
4736
+ return fields.join(" ");
4737
+ }
4738
+ function tail(value) {
4739
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
4740
+ return safeDiagnosticText(clipped);
4741
+ }
4742
+ function safeText(value) {
4743
+ if (typeof value !== "string") return void 0;
4744
+ const safe = safeDiagnosticText(value);
4745
+ if (safe.length === 0) return void 0;
4746
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
4747
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
4748
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
4749
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4750
+ }
4751
+ function safePath(value) {
4752
+ if (typeof value !== "string") return void 0;
4753
+ const safe = safeDiagnosticText(value);
4754
+ if (safe.length === 0) return void 0;
4755
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
4756
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
4757
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
4758
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4759
+ }
4760
+ function safeDiagnosticText(value) {
4761
+ return redactOperatorDiagnosticText(String(value));
4762
+ }
4763
+ function outputText(value) {
4764
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
4765
+ if (value instanceof Uint8Array) {
4766
+ try {
4767
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
4768
+ } catch {
4769
+ return void 0;
4770
+ }
4771
+ }
4772
+ return void 0;
4773
+ }
4774
+ function safeStatus(value) {
4775
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4776
+ return typeof value === "string" ? safeText(value) : void 0;
4777
+ }
4778
+ function safeExitCode(value) {
4779
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
4780
+ }
4781
+ function read(value, key) {
4782
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
4783
+ try {
4784
+ return Reflect.get(value, key);
4785
+ } catch {
4786
+ return void 0;
4787
+ }
4788
+ }
4789
+ function redactHomePaths(value) {
4790
+ const paths = [
4791
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
4792
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
4793
+ ];
4794
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
4795
+ let output = "";
4796
+ let cursor = 0;
4797
+ for (const path of paths) {
4798
+ if (path.start < cursor) continue;
4799
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
4800
+ cursor = path.end;
4801
+ }
4802
+ return output + value.slice(cursor);
4803
+ }
4804
+ function configuredHomePathPatterns() {
4805
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
4806
+ return homes.flatMap((home) => {
4807
+ const root = home.replace(/[\\/]+$/gu, "");
4808
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
4809
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
4810
+ return [{ pattern, prefixLength: root.length }];
4811
+ });
4812
+ }
4813
+ function matchedHomePrefixLength(value) {
4814
+ let separators = 0;
4815
+ for (let index = 0; index < value.length; index += 1) {
4816
+ if (value[index] !== "/" && value[index] !== "\\") continue;
4817
+ separators += 1;
4818
+ if (separators === 3) return index;
4819
+ }
4820
+ return value.length;
4821
+ }
4822
+ function redactUrls(value) {
4823
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
4824
+ }
4825
+ function redactFilePaths(value) {
4826
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
4827
+ }
4828
+ function homePathRange(value, match, prefixLength) {
4829
+ const index = match.index;
4830
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
4831
+ const start = index;
4832
+ let end = start + match[0].length;
4833
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
4834
+ if (quote !== void 0) {
4835
+ const closing = value.indexOf(quote, end);
4836
+ if (closing >= 0) end = closing;
4837
+ }
4838
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
4839
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
4840
+ }
4841
+ function truncateUtf8(value, maxBytes) {
4842
+ if (byteLength(value) <= maxBytes) return value;
4843
+ let output = "";
4844
+ for (const character of value) {
4845
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
4846
+ output += character;
4847
+ }
4848
+ return `${output}…`;
4849
+ }
4850
+
4597
4851
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
4598
4852
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
4599
4853
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -4734,10 +4988,10 @@ function failureDetail(error) {
4734
4988
  function errorCode(error) {
4735
4989
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
4736
4990
  }
4737
- function hostClientProbe(result, read) {
4991
+ function hostClientProbe(result, read2) {
4738
4992
  if (result === null) return { kind: "unreachable" };
4739
4993
  if (result.exit_code !== 0) return { kind: "refused", exit_code: result.exit_code };
4740
- const value = read(result);
4994
+ const value = read2(result);
4741
4995
  return value === null ? { kind: "unreadable" } : { kind: "value", value };
4742
4996
  }
4743
4997
  function hostClientProbeRefusal(probe, subject) {
@@ -4751,7 +5005,7 @@ function hostClientProbeRefusal(probe, subject) {
4751
5005
  import { createHash as createHash4 } from "node:crypto";
4752
5006
  import { execFile } from "node:child_process";
4753
5007
  import { access, open, readFile, realpath, stat } from "node:fs/promises";
4754
- import { delimiter, extname, isAbsolute, join as join2 } from "node:path";
5008
+ import { delimiter, extname, isAbsolute as isAbsolute2, join as join3 } from "node:path";
4755
5009
  import { promisify } from "node:util";
4756
5010
 
4757
5011
  // host/environment.ts
@@ -4833,6 +5087,76 @@ function quoteWindowsExecArgument(value) {
4833
5087
  return `"${escaped}"`;
4834
5088
  }
4835
5089
 
5090
+ // host/spawn-working-directory.ts
5091
+ import { mkdirSync } from "node:fs";
5092
+ import { tmpdir } from "node:os";
5093
+ import { isAbsolute, join as join2, normalize, parse, sep } from "node:path";
5094
+ function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
5095
+ const candidates = [];
5096
+ const explicit = candidateDir(stateRoot);
5097
+ if (explicit !== void 0) candidates.push(explicit);
5098
+ const fallback = defaultHostStateRoot();
5099
+ if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
5100
+ const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
5101
+ if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
5102
+ for (const dir of candidates) {
5103
+ if (!keptOutside(dir, keepOutside)) continue;
5104
+ try {
5105
+ mkdirSync(dir, { recursive: true, mode: 448 });
5106
+ return dir;
5107
+ } catch {
5108
+ continue;
5109
+ }
5110
+ }
5111
+ return tmpdir();
5112
+ }
5113
+ function candidateDir(dir) {
5114
+ if (dir === void 0 || dir === "") return void 0;
5115
+ if (!isAbsolute(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
5116
+ return normalize(dir);
5117
+ }
5118
+ function defaultHostStateRoot() {
5119
+ if (process.platform === "win32") {
5120
+ const localAppData = nonEmptyEnv("LOCALAPPDATA");
5121
+ if (localAppData === void 0) return void 0;
5122
+ return candidateDir(join2(localAppData, "Ceal", "Host"));
5123
+ }
5124
+ if (process.platform === "darwin") {
5125
+ const home2 = nonEmptyEnv("HOME");
5126
+ if (home2 === void 0) return void 0;
5127
+ return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
5128
+ }
5129
+ const xdg = nonEmptyEnv("XDG_STATE_HOME");
5130
+ if (xdg !== void 0) {
5131
+ const root = candidateDir(join2(xdg, "ceal", "host"));
5132
+ if (root !== void 0) return root;
5133
+ }
5134
+ const home = nonEmptyEnv("HOME");
5135
+ if (home === void 0) return void 0;
5136
+ return candidateDir(join2(home, ".local", "state", "ceal", "host"));
5137
+ }
5138
+ function nonEmptyEnv(name) {
5139
+ const value = process.env[name];
5140
+ return value === void 0 || value === "" ? void 0 : value;
5141
+ }
5142
+ function keptOutside(dir, keepOutside) {
5143
+ for (const tree of keepOutside) {
5144
+ const clean = candidateDir(tree);
5145
+ if (clean === void 0) continue;
5146
+ if (insideDir(dir, clean)) return false;
5147
+ }
5148
+ return true;
5149
+ }
5150
+ function insideDir(dir, tree) {
5151
+ if (sameDir(dir, tree)) return true;
5152
+ if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
5153
+ return dir.startsWith(tree + sep);
5154
+ }
5155
+ function sameDir(left, right) {
5156
+ if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
5157
+ return left === right;
5158
+ }
5159
+
4836
5160
  // host/client-doctor.ts
4837
5161
  var execFileAsync = promisify(execFile);
4838
5162
  var GIT_OID = /^[a-f0-9]{40}$/u;
@@ -4869,7 +5193,7 @@ async function inspectExecutable(options, environment, component) {
4869
5193
  try {
4870
5194
  executable = await (options.resolve_executable ?? resolveCealExecutable)(options.executable ?? "ceal", environment);
4871
5195
  } catch (error) {
4872
- return inspectedFailure("ceal_unavailable", `The ${component} Host cannot resolve an executable Ceal client from its current environment (${refusalFact("error", error)}).`, `Install the intended Ceal client in the Host PATH, restart ${component}, and run this doctor again.`);
5196
+ return inspectedFailure("ceal_unavailable", `The ${component} Host cannot resolve an executable Ceal client from its current environment (${renderOperatorDiagnostic(error)}).`, `Install the intended Ceal client in the Host PATH, restart ${component}, and run this doctor again.`);
4873
5197
  }
4874
5198
  if (!validExpectations(options) || options.expected_sha256 !== void 0 && executable.sha256 !== options.expected_sha256) return inspectedFailure("ceal_identity_mismatch", `The Ceal executable visible to the ${component} Host does not match the intended candidate.`, `Install the exact candidate bytes, restart ${component}, and run this doctor with the expected identity.`);
4875
5199
  return { ok: true, value: executable };
@@ -4918,7 +5242,7 @@ async function resolveCealExecutable(command, environment, platform = process.pl
4918
5242
  if (!metadata.isFile()) continue;
4919
5243
  const launcherKind = await inspectLauncherKind(path);
4920
5244
  if (launcherKind !== void 0) return resolveLauncherBinary(path, launcherKind, environment, platform);
4921
- if (platform === "win32" && !isAbsolute(command) && extname(path) === "") continue;
5245
+ if (platform === "win32" && !isAbsolute2(command) && extname(path) === "") continue;
4922
5246
  return { path, sha256: createHash4("sha256").update(await readFile(path)).digest("hex") };
4923
5247
  } catch {
4924
5248
  }
@@ -4941,7 +5265,7 @@ async function inspectLauncherKind(path) {
4941
5265
  }
4942
5266
  async function resolveLauncherBinary(launcherPath, kind, environment, platform) {
4943
5267
  const invocation = hostScriptLauncherInvocation(launcherPath, CEAL_CLIENT_DOCTOR_COMMAND, kind, platform, environment);
4944
- const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
5268
+ const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, cwd: resolveCealSpawnWorkingDirectory(), ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
4945
5269
  let parsed;
4946
5270
  try {
4947
5271
  parsed = JSON.parse(result.stdout);
@@ -4955,15 +5279,15 @@ async function resolveLauncherBinary(launcherPath, kind, environment, platform)
4955
5279
  return { path: binaryPath, sha256: createHash4("sha256").update(await readFile(binaryPath)).digest("hex") };
4956
5280
  }
4957
5281
  function executableCandidates(command, environment, platform) {
4958
- if (isAbsolute(command)) return [command];
5282
+ if (isAbsolute2(command)) return [command];
4959
5283
  const pathValue = environmentValue(environment, "PATH", platform) ?? "";
4960
5284
  const directories = pathValue.split(delimiter).filter((entry) => entry.length > 0);
4961
- if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join2(entry, command));
4962
- return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join2(entry, `${command}${suffix}`)));
5285
+ if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join3(entry, command));
5286
+ return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join3(entry, `${command}${suffix}`)));
4963
5287
  }
4964
5288
  async function executeCealCommand(executable, args, environment) {
4965
5289
  try {
4966
- const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8" });
5290
+ const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8", cwd: resolveCealSpawnWorkingDirectory() });
4967
5291
  return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
4968
5292
  } catch (error) {
4969
5293
  if (isRecord(error)) return { exit_code: typeof error.code === "number" ? error.code : 1, stdout: typeof error.stdout === "string" ? error.stdout : "", stderr: typeof error.stderr === "string" ? error.stderr : "" };
@@ -5015,6 +5339,7 @@ async function doctorCodexClient(options = {}) {
5015
5339
  }
5016
5340
 
5017
5341
  // host/invocation-authentication-command.ts
5342
+ import { createHash as createHash8 } from "node:crypto";
5018
5343
  import { performance } from "node:perf_hooks";
5019
5344
 
5020
5345
  // host/relay/src/producer-frame.ts
@@ -5033,12 +5358,13 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
5033
5358
 
5034
5359
  // host/relay/src/host-producer-core.ts
5035
5360
  import { createHash as createHash5 } from "node:crypto";
5361
+ import { readdir } from "node:fs/promises";
5036
5362
 
5037
5363
  // host/secure-file.ts
5038
5364
  import { execFile as execFile2 } from "node:child_process";
5039
5365
  import { constants } from "node:fs";
5040
5366
  import { lstat, open as open2 } from "node:fs/promises";
5041
- import { dirname, join as join3, win32 as win322 } from "node:path";
5367
+ import { dirname, join as join4, win32 as win322 } from "node:path";
5042
5368
  import { fileURLToPath } from "node:url";
5043
5369
  var SecureFileCustodyError = class extends Error {
5044
5370
  name = "SecureFileCustodyError";
@@ -5147,7 +5473,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
5147
5473
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
5148
5474
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
5149
5475
  return await new Promise((resolve, reject2) => {
5150
- const child = execFile2(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
5476
+ const child = execFile2(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: resolveCealSpawnWorkingDirectory() }, (error, stdout, stderr) => {
5151
5477
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
5152
5478
  if (exitCode === null) {
5153
5479
  reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -5176,7 +5502,7 @@ function securefsRefusal(stderr) {
5176
5502
  }
5177
5503
  function resolveInstalledHostExecutable(platform) {
5178
5504
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
5179
- return platform === "win32" ? win322.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
5505
+ return platform === "win32" ? win322.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join4(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
5180
5506
  }
5181
5507
  function isRecord2(value) {
5182
5508
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -5200,7 +5526,7 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
5200
5526
 
5201
5527
  // host/service-log.ts
5202
5528
  import { copyFile, mkdir, stat as stat2, truncate, appendFile } from "node:fs/promises";
5203
- import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win323 } from "node:path";
5529
+ import { dirname as dirname2, isAbsolute as isAbsolute3, posix, win32 as win323 } from "node:path";
5204
5530
 
5205
5531
  // host/service-log-delivery.ts
5206
5532
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -5359,7 +5685,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
5359
5685
  await appendHostServiceLogLine(path, line).catch(() => void 0);
5360
5686
  }
5361
5687
  async function appendHostServiceLogLine(path, line) {
5362
- if (!isAbsolute2(path)) return;
5688
+ if (!isAbsolute3(path)) return;
5363
5689
  await ensureHostServiceLogDirectory(path);
5364
5690
  await appendFile(path, line);
5365
5691
  }
@@ -5400,9 +5726,9 @@ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
5400
5726
  }
5401
5727
  return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
5402
5728
  }
5403
- async function readRegisteredHostInvocationHumanMessageWindow(listRegistrations, readCursor, identity, decodeLine) {
5729
+ async function readRegisteredHostInvocationHumanMessageWindow(readRegistration, readCursor, identity, decodeLine) {
5404
5730
  try {
5405
- const registration = await findLiveHostInvocationRegistration(listRegistrations, identity);
5731
+ const registration = await findLiveHostInvocationRegistration(readRegistration, identity);
5406
5732
  const cursor = await readCursor(registration);
5407
5733
  assertUsableHostInvocationHumanMessageCursor(cursor, registration);
5408
5734
  return await readHostInvocationHumanMessageWindow(registration, cursor, (line) => decodeLine(line, registration, cursor));
@@ -5410,9 +5736,9 @@ async function readRegisteredHostInvocationHumanMessageWindow(listRegistrations,
5410
5736
  throw new TypeError("context_unavailable");
5411
5737
  }
5412
5738
  }
5413
- async function findLiveHostInvocationRegistration(listRegistrations, identity) {
5414
- const registration = (await listRegistrations()).find((candidate) => candidate.host_source_ref === identity.host_source_ref && candidate.host_session_ref === identity.host_session_ref && Date.parse(candidate.expires_at) > Date.now());
5415
- if (registration === void 0) throw new TypeError("context_unavailable");
5739
+ async function findLiveHostInvocationRegistration(readRegistration, identity) {
5740
+ const registration = await readRegistration(identity);
5741
+ if (registration === null || registration.host_source_ref !== identity.host_source_ref || registration.host_session_ref !== identity.host_session_ref || !(Date.parse(registration.expires_at) > Date.now())) throw new TypeError("context_unavailable");
5416
5742
  return registration;
5417
5743
  }
5418
5744
  function assertUsableHostInvocationHumanMessageCursor(cursor, registration) {
@@ -5479,9 +5805,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
5479
5805
  let lastNewline = -1;
5480
5806
  while (position < size) {
5481
5807
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
5482
- const read = await handle.read(buffer, 0, buffer.length, position);
5483
- if (read.bytesRead === 0) break;
5484
- const chunk = buffer.subarray(0, read.bytesRead);
5808
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
5809
+ if (read2.bytesRead === 0) break;
5810
+ const chunk = buffer.subarray(0, read2.bytesRead);
5485
5811
  chunks.push(chunk);
5486
5812
  const newline = chunk.lastIndexOf(10);
5487
5813
  if (newline >= 0) lastNewline = total + newline;
@@ -5640,6 +5966,14 @@ var HostTranscriptWatcher = class {
5640
5966
  return transcriptCursorBoundsReason(handle, cursor, size);
5641
5967
  }
5642
5968
  };
5969
+ async function listHostOutboxDirectoryNames(directory) {
5970
+ try {
5971
+ return await readdir(directory);
5972
+ } catch (error) {
5973
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
5974
+ throw error;
5975
+ }
5976
+ }
5643
5977
  var HostProducerDrainCore = class {
5644
5978
  host;
5645
5979
  now;
@@ -5654,15 +5988,15 @@ var HostProducerDrainCore = class {
5654
5988
  return run;
5655
5989
  }
5656
5990
  async drainLocked() {
5657
- const read = await this.host.listEnvelopes();
5991
+ const read2 = await this.host.listEnvelopes();
5658
5992
  let removed = 0;
5659
5993
  let expired = 0;
5660
- for (const envelope of read.entries) {
5994
+ for (const envelope of read2.entries) {
5661
5995
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
5662
5996
  else removed += 1;
5663
5997
  await this.host.removeEnvelope(envelope);
5664
5998
  }
5665
- return { removed, expired, malformed: read.malformed };
5999
+ return { removed, expired, malformed: read2.malformed };
5666
6000
  }
5667
6001
  };
5668
6002
 
@@ -5801,7 +6135,7 @@ function errorCode2(error) {
5801
6135
  import { createHash as createHash6 } from "node:crypto";
5802
6136
  import { constants as constants2 } from "node:fs";
5803
6137
  import { mkdir as mkdir3, open as open4, opendir, unlink as unlink2 } from "node:fs/promises";
5804
- import { dirname as dirname4, join as join4 } from "node:path";
6138
+ import { dirname as dirname4, join as join5 } from "node:path";
5805
6139
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
5806
6140
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
5807
6141
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -5821,9 +6155,9 @@ var HostUsageFactsStore = class {
5821
6155
  afterBatchPublish;
5822
6156
  sessionDirectoryCursor;
5823
6157
  constructor(options) {
5824
- this.root = join4(options.outbox_dir, "usage-facts");
5825
- this.sessions = join4(this.root, "sessions");
5826
- this.batches = join4(this.root, "batches");
6158
+ this.root = join5(options.outbox_dir, "usage-facts");
6159
+ this.sessions = join5(this.root, "sessions");
6160
+ this.batches = join5(this.root, "batches");
5827
6161
  this.platform = options.platform ?? process.platform;
5828
6162
  this.custody = options.secure_file_custody ?? {};
5829
6163
  this.afterPendingWrite = options.afterPendingWrite;
@@ -5840,7 +6174,6 @@ var HostUsageFactsStore = class {
5840
6174
  await cursor?.close();
5841
6175
  }
5842
6176
  async readState(producer, hostSourceRef, hostSessionRef) {
5843
- await this.prepare();
5844
6177
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
5845
6178
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
5846
6179
  if (value === null) return null;
@@ -5898,11 +6231,15 @@ var HostUsageFactsStore = class {
5898
6231
  }
5899
6232
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
5900
6233
  async sweepOrphanedBatches(state) {
5901
- await this.prepare();
5902
6234
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
5903
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
5904
6235
  const expected = expectedBatchNames(state);
5905
- const directory = await opendir(directoryPath);
6236
+ let directory;
6237
+ try {
6238
+ directory = await opendir(directoryPath);
6239
+ } catch (error) {
6240
+ if (errorCode3(error) === "ENOENT") return 0;
6241
+ throw error;
6242
+ }
5906
6243
  let inspected = 0;
5907
6244
  let deleted = 0;
5908
6245
  try {
@@ -5911,7 +6248,7 @@ var HostUsageFactsStore = class {
5911
6248
  if (entry === null) break;
5912
6249
  inspected += 1;
5913
6250
  if (!isOrphanBatchEntry(entry, expected)) continue;
5914
- await unlink2(join4(directoryPath, entry.name));
6251
+ await unlink2(join5(directoryPath, entry.name));
5915
6252
  deleted += 1;
5916
6253
  }
5917
6254
  } finally {
@@ -5939,10 +6276,9 @@ var HostUsageFactsStore = class {
5939
6276
  });
5940
6277
  }
5941
6278
  async nextUploadCandidate(producer, hostSourceRef) {
5942
- await this.prepare();
5943
6279
  const names = await this.readNextSessionNames();
5944
6280
  for (const name of names) {
5945
- const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
6281
+ const state = await readOptionalJson(join5(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
5946
6282
  if (state === null) continue;
5947
6283
  validateStateOwner(state, producer, hostSourceRef);
5948
6284
  let validated = state;
@@ -5957,7 +6293,14 @@ var HostUsageFactsStore = class {
5957
6293
  return null;
5958
6294
  }
5959
6295
  async readNextSessionNames() {
5960
- this.sessionDirectoryCursor ??= await opendir(this.sessions);
6296
+ if (this.sessionDirectoryCursor === void 0) {
6297
+ try {
6298
+ this.sessionDirectoryCursor = await opendir(this.sessions);
6299
+ } catch (error) {
6300
+ if (errorCode3(error) === "ENOENT") return [];
6301
+ throw error;
6302
+ }
6303
+ }
5961
6304
  const names = [];
5962
6305
  let inspected = 0;
5963
6306
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -6112,25 +6455,25 @@ var HostUsageFactsStore = class {
6112
6455
  const gate = new Promise((resolve) => {
6113
6456
  release = resolve;
6114
6457
  });
6115
- const tail = previous.then(() => gate);
6116
- SESSION_TRANSITION_TAILS.set(key, tail);
6458
+ const tail2 = previous.then(() => gate);
6459
+ SESSION_TRANSITION_TAILS.set(key, tail2);
6117
6460
  await previous;
6118
6461
  try {
6119
6462
  return await run();
6120
6463
  } finally {
6121
6464
  release?.();
6122
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
6465
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
6123
6466
  }
6124
6467
  }
6125
6468
  sessionPath(producer, hostSourceRef, hostSessionRef) {
6126
- return join4(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
6469
+ return join5(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
6127
6470
  }
6128
6471
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
6129
6472
  const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
6130
- return join4(this.batches, sessionName.slice(0, -5));
6473
+ return join5(this.batches, sessionName.slice(0, -5));
6131
6474
  }
6132
6475
  batchPath(state, batchRef) {
6133
- return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
6476
+ return join5(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
6134
6477
  }
6135
6478
  };
6136
6479
  function serializeBatch(batch) {
@@ -6380,29 +6723,46 @@ var HostUsageTranscriptSourceError = class extends Error {
6380
6723
  this.name = "HostUsageTranscriptSourceError";
6381
6724
  }
6382
6725
  };
6383
- async function readHostUsageTranscriptSource(read) {
6726
+ async function readHostUsageTranscriptSource(read2) {
6384
6727
  try {
6385
- return await read();
6728
+ return await read2();
6386
6729
  } catch (error) {
6387
6730
  throw new HostUsageTranscriptSourceError({ cause: error });
6388
6731
  }
6389
6732
  }
6390
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
6391
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
6392
- let failed = false;
6393
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
6394
- const index = (startIndex + attempt) % registrations.length;
6395
- const registration = registrations[index];
6396
- if (registration === void 0) continue;
6397
- try {
6398
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
6399
- } catch (error) {
6400
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
6733
+ var HostUsageRegistrationCapture = class {
6734
+ nextIndex = 0;
6735
+ producer;
6736
+ diagnosticSink;
6737
+ constructor(producer, diagnosticSink) {
6738
+ this.producer = producer;
6739
+ this.diagnosticSink = diagnosticSink;
6740
+ }
6741
+ async captureNext(registrations, capture) {
6742
+ let failed = false;
6743
+ let captured = false;
6744
+ const onFailure = () => {
6401
6745
  failed = true;
6746
+ };
6747
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
6748
+ const index = (this.nextIndex + attempt) % registrations.length;
6749
+ const registration = registrations[index];
6750
+ if (registration === void 0) continue;
6751
+ try {
6752
+ captured = await capture(registration, onFailure);
6753
+ if (captured) {
6754
+ this.nextIndex = (index + 1) % registrations.length;
6755
+ break;
6756
+ }
6757
+ } catch (error) {
6758
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
6759
+ onFailure();
6760
+ }
6402
6761
  }
6762
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
6763
+ return captured;
6403
6764
  }
6404
- return { captured: false, nextIndex: startIndex, failed };
6405
- }
6765
+ };
6406
6766
  async function openHostUsageTranscriptCursor(input) {
6407
6767
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
6408
6768
  let source;
@@ -6682,6 +7042,10 @@ var HostUsageFactsUploader = class {
6682
7042
  async close() {
6683
7043
  await this.store.close();
6684
7044
  }
7045
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
7046
+ async prepare() {
7047
+ await this.store.prepare();
7048
+ }
6685
7049
  async uploadOne(signal) {
6686
7050
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
6687
7051
  if (candidate === null) return false;
@@ -6704,6 +7068,11 @@ var HostUsageFactsUploader = class {
6704
7068
  };
6705
7069
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
6706
7070
  const uploader = new HostUsageFactsUploader(options);
7071
+ try {
7072
+ await uploader.prepare();
7073
+ } catch {
7074
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
7075
+ }
6707
7076
  let delay = 500;
6708
7077
  let failures = 0;
6709
7078
  try {
@@ -6793,7 +7162,7 @@ import { createConnection, createServer } from "node:net";
6793
7162
  import { createHmac, randomBytes } from "node:crypto";
6794
7163
  import { constants as constants5 } from "node:fs";
6795
7164
  import { link, unlink as unlink4 } from "node:fs/promises";
6796
- import { dirname as dirname7, join as join5 } from "node:path";
7165
+ import { dirname as dirname7, join as join6 } from "node:path";
6797
7166
  var RELAY_PIPE_HANDSHAKE_TIMEOUT_MS = 5e3;
6798
7167
  var RELAY_PIPE_KEY_BYTES = 32;
6799
7168
  var RELAY_PIPE_KEY_FILENAME = "relay-pipe.key";
@@ -6813,10 +7182,10 @@ var RelayPipeHandshakeError = class extends Error {
6813
7182
  }
6814
7183
  };
6815
7184
  function relayPipeStateRootForOutboxDir(outboxDir) {
6816
- return join5(dirname7(dirname7(dirname7(outboxDir))), "relay");
7185
+ return join6(dirname7(dirname7(dirname7(outboxDir))), "relay");
6817
7186
  }
6818
7187
  function relayPipeKeyPath(relayStateRoot) {
6819
- return join5(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
7188
+ return join6(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
6820
7189
  }
6821
7190
  async function loadRelayPipeKey(relayStateRoot, platform = process.platform, custody = {}) {
6822
7191
  const path = relayPipeKeyPath(relayStateRoot);
@@ -7326,17 +7695,133 @@ async function authenticateHostInvocation(descriptor2, input, options) {
7326
7695
  const request2 = decodeCealHostInvocationAuthenticationRequest({ schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA, client_nonce: input[2] });
7327
7696
  const config = validateOptions(options);
7328
7697
  const now = config.now ?? (() => /* @__PURE__ */ new Date());
7329
- const { store, current } = await currentInvocation(descriptor2, config, now);
7698
+ const store = descriptor2.create_store(config.outbox_dir);
7699
+ const resolved = resolveIdentity(descriptor2, config);
7700
+ if (resolved.status === "session_unavailable") throw new TypeError("no_binding");
7701
+ const toolCallId = resolveToolCallId(descriptor2, config);
7702
+ const selection = await readHookSelection(store, resolved.identity);
7703
+ if (selection === null) {
7704
+ const callTime = await trySelectionlessCallTimeBinding(descriptor2, store, resolved.identity, config, toolCallId);
7705
+ if (callTime !== null) return authenticateCallTimeBinding(descriptor2, store, callTime, request2.client_nonce, config, now);
7706
+ } else if (!waitPossible(config) && !await hasLiveInvocationContext(store, resolved.identity, now)) {
7707
+ const direct = await tryDirectCallTimeBinding(descriptor2, store, resolved.identity, selection, config, toolCallId);
7708
+ if (direct !== null) return authenticateCallTimeBinding(descriptor2, store, direct, request2.client_nonce, config, now);
7709
+ }
7710
+ return authenticateHookGated(descriptor2, store, request2.client_nonce, config, now, toolCallId);
7711
+ }
7712
+ function selectCallTimeBinding(window, toolCallId) {
7713
+ const newest = window.messages[0];
7714
+ if (newest === void 0) return null;
7715
+ return { message: newest, mode: toolCallId === void 0 ? "newest_message" : "tool_call" };
7716
+ }
7717
+ async function authenticateCallTimeBinding(descriptor2, store, callTime, clientNonce, config, now) {
7330
7718
  if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
7331
- const query = await invocationMintQuery(descriptor2, store, current, request2.client_nonce, config);
7719
+ const query = await invocationMintQuery(descriptor2, store, { identity: callTime.binding, expires_at: callTime.expires_at }, clientNonce, config, callTime.window);
7720
+ const response2 = await mintedResult(config.mint_invocation_context, query);
7721
+ const completedAt = now();
7722
+ const newest = await rereadCallTimeNewest(descriptor2, store, callTime.binding, config);
7723
+ if (newest === null || newest.host_turn_ref !== callTime.binding.host_turn_ref || newest.host_input_ref !== callTime.window.messages[0]?.host_input_ref) throw new TypeError("context_replaced");
7724
+ return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
7725
+ }
7726
+ async function authenticateHookGated(descriptor2, store, clientNonce, config, now, toolCallId) {
7727
+ const { current } = await currentInvocation(descriptor2, config, now, store);
7728
+ if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
7729
+ const window = await readCallTimeWindow(descriptor2, store, current.identity, config);
7730
+ const selected = selectCallTimeBinding(window, toolCallId);
7731
+ if (selected !== null && selected.message.host_turn_ref !== current.identity.host_turn_ref) {
7732
+ const selection = await readHookSelection(store, current.identity);
7733
+ if (selection === null || transcriptCatchesHookSelection(selection, selected.message)) {
7734
+ return authenticateCallTimeBinding(descriptor2, store, {
7735
+ binding: { ...current.identity, host_turn_ref: selected.message.host_turn_ref },
7736
+ expires_at: current.expires_at,
7737
+ window,
7738
+ mode: selected.mode
7739
+ }, clientNonce, config, now);
7740
+ }
7741
+ }
7742
+ const query = await invocationMintQuery(descriptor2, store, current, clientNonce, config, window);
7332
7743
  const response2 = await mintedResult(config.mint_invocation_context, query);
7333
7744
  const completedAt = now();
7334
7745
  const rechecked = await store.readInvocationContext(current.identity.host_source_ref, current.identity.host_session_ref, completedAt);
7335
7746
  if (rechecked === null || !sameTurn(current, rechecked)) throw new TypeError("context_replaced");
7336
7747
  return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
7337
7748
  }
7338
- async function invocationMintQuery(descriptor2, store, current, clientNonce, options) {
7339
- const readWindow = options.read_human_message_window?.(current.identity) ?? descriptor2.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false });
7749
+ async function trySelectionlessCallTimeBinding(descriptor2, store, identity, config, toolCallId) {
7750
+ const registration = await liveTranscriptRegistration(store, identity);
7751
+ if (registration === null) return null;
7752
+ let window;
7753
+ try {
7754
+ window = await readCallTimeWindow(descriptor2, store, identity, config);
7755
+ } catch {
7756
+ throw new TypeError("transient_retryable");
7757
+ }
7758
+ const selected = selectCallTimeBinding(window, toolCallId);
7759
+ if (selected === null) return null;
7760
+ return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
7761
+ }
7762
+ async function tryDirectCallTimeBinding(descriptor2, store, identity, selection, config, toolCallId) {
7763
+ let window;
7764
+ try {
7765
+ window = await readCallTimeWindow(descriptor2, store, identity, config);
7766
+ } catch {
7767
+ return null;
7768
+ }
7769
+ const selected = selectCallTimeBinding(window, toolCallId);
7770
+ if (selected === null || !transcriptCatchesHookSelection(selection, selected.message)) return null;
7771
+ const registration = await liveTranscriptRegistration(store, identity);
7772
+ if (registration === null) return null;
7773
+ return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
7774
+ }
7775
+ async function readCallTimeWindow(descriptor2, store, identity, config) {
7776
+ return await (config.read_human_message_window?.(identity) ?? descriptor2.read_human_message_window?.({ store, identity }) ?? Promise.resolve({ messages: [], truncated: false }));
7777
+ }
7778
+ function transcriptCatchesHookSelection(selection, newest) {
7779
+ if (newest.text_truncated === true) return false;
7780
+ return hostProducerPromptRef(createHash8("sha256").update(newest.text, "utf8").digest("hex")) === selection.prompt_ref;
7781
+ }
7782
+ async function readHookSelection(store, identity) {
7783
+ try {
7784
+ return await store.readInvocationTurnSelection?.(identity.host_source_ref, identity.host_session_ref) ?? null;
7785
+ } catch {
7786
+ return null;
7787
+ }
7788
+ }
7789
+ async function hasLiveInvocationContext(store, identity, now) {
7790
+ try {
7791
+ return await store.readInvocationContext(identity.host_source_ref, identity.host_session_ref, now()) !== null;
7792
+ } catch {
7793
+ return false;
7794
+ }
7795
+ }
7796
+ function waitPossible(config) {
7797
+ return (config.context_activation_wait_ms ?? 0) > 0;
7798
+ }
7799
+ async function liveTranscriptRegistration(store, identity) {
7800
+ try {
7801
+ const registration = await store.readTranscriptRegistration?.(identity.host_source_ref, identity.host_session_ref) ?? null;
7802
+ if (registration !== null && Date.parse(registration.expires_at) > Date.now()) return registration;
7803
+ } catch {
7804
+ }
7805
+ return null;
7806
+ }
7807
+ async function rereadCallTimeNewest(descriptor2, store, identity, config) {
7808
+ try {
7809
+ return (await readCallTimeWindow(descriptor2, store, identity, config)).messages[0] ?? null;
7810
+ } catch {
7811
+ return null;
7812
+ }
7813
+ }
7814
+ function resolveToolCallId(descriptor2, options) {
7815
+ if (options.tool_call_id !== void 0) return validToolCallId(options.tool_call_id) ? options.tool_call_id : void 0;
7816
+ if (descriptor2.tool_call_id_env === void 0) return void 0;
7817
+ const value = process.env[descriptor2.tool_call_id_env];
7818
+ return validToolCallId(value) ? value : void 0;
7819
+ }
7820
+ function validToolCallId(value) {
7821
+ return typeof value === "string" && value.length > 0 && value.length <= 256 && !value.includes("\0");
7822
+ }
7823
+ async function invocationMintQuery(descriptor2, store, current, clientNonce, options, windowOverride) {
7824
+ const readWindow = windowOverride === void 0 ? options.read_human_message_window?.(current.identity) ?? descriptor2.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false }) : Promise.resolve(windowOverride);
7340
7825
  return {
7341
7826
  producer_id: descriptor2.producer_id,
7342
7827
  producer_installation_ref: options.producer_installation_ref,
@@ -7368,8 +7853,7 @@ async function mintedResult(mint, query) {
7368
7853
  function validGenericGatewayRefusalStatus2(value) {
7369
7854
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 400 && value < 500 && value !== 401 && value !== 429;
7370
7855
  }
7371
- async function currentInvocation(descriptor2, config, now) {
7372
- const store = descriptor2.create_store(config.outbox_dir);
7856
+ async function currentInvocation(descriptor2, config, now, store) {
7373
7857
  const identity = resolveIdentity(descriptor2, config);
7374
7858
  if (identity.status === "session_unavailable") throw new TypeError("no_binding");
7375
7859
  const waitBudgetMs = config.context_activation_wait_ms ?? 0;
@@ -7386,7 +7870,7 @@ async function currentInvocation(descriptor2, config, now) {
7386
7870
  const current = await readLiveSessionContext(store, identity.identity.host_source_ref, identity.identity.host_session_ref, observedAt);
7387
7871
  if (current !== null) {
7388
7872
  recordActivationWaitCompletion(descriptor2.producer_id, waitEngaged, config.diagnostic_sink);
7389
- return { store, current };
7873
+ return { current };
7390
7874
  }
7391
7875
  await rejectWhenActivationWaitIsUnavailable(descriptor2, store, identity.identity, waitEngaged, waitBudgetMs, config.diagnostic_sink);
7392
7876
  const remainingMs = deadline - monotonicNow();
@@ -7460,7 +7944,7 @@ function waitForContextActivation(milliseconds) {
7460
7944
  });
7461
7945
  }
7462
7946
  function validateOptions(options) {
7463
- if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || !validOptionalSession(options.session_id)) {
7947
+ if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || options.tool_call_id !== void 0 && typeof options.tool_call_id !== "string" || !validOptionalSession(options.session_id)) {
7464
7948
  throw new TypeError("options_invalid");
7465
7949
  }
7466
7950
  return options;
@@ -7658,7 +8142,7 @@ function parseCanonicalJson(text, error) {
7658
8142
  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) }])}`);
7659
8143
  return value;
7660
8144
  } catch (parseError) {
7661
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
8145
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
7662
8146
  }
7663
8147
  }
7664
8148
  function firstDifferenceIndex(left, right) {
@@ -7713,10 +8197,11 @@ function boundedMilliseconds(value) {
7713
8197
  }
7714
8198
 
7715
8199
  // host/codex/src/codex-decoder.ts
7716
- import { createHash as createHash8 } from "node:crypto";
8200
+ import { createHash as createHash9 } from "node:crypto";
7717
8201
 
7718
8202
  // host/codex/src/codex-types.ts
7719
8203
  var CODEX_THREAD_ID_ENVIRONMENT = "CODEX_THREAD_ID";
8204
+ var CODEX_TOOL_CALL_ID_ENVIRONMENT = "CODEX_TOOL_CALL_ID";
7720
8205
  var CODEX_OUTBOX_SCHEMA_VERSION = "ceal.codex_observation_outbox.v1";
7721
8206
  var CODEX_SESSION_SCHEMA_VERSION = "ceal.codex_session.v1";
7722
8207
  var CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION = "ceal.codex_invocation_context.v1";
@@ -7758,14 +8243,14 @@ function turnObservationValue(sessionId, turnRef, status) {
7758
8243
  return { status, host_session_id_sha256: sha2563(sessionId), host_turn_ref: turnRef };
7759
8244
  }
7760
8245
  function sha2563(value) {
7761
- return createHash8("sha256").update(value, "utf8").digest("hex");
8246
+ return createHash9("sha256").update(value, "utf8").digest("hex");
7762
8247
  }
7763
8248
  function shortDigest(value) {
7764
8249
  return cealRequestSha256(value);
7765
8250
  }
7766
8251
 
7767
8252
  // host/codex/src/codex-transcript-baseline.ts
7768
- import { createHash as createHash9 } from "node:crypto";
8253
+ import { createHash as createHash10 } from "node:crypto";
7769
8254
 
7770
8255
  // host/codex/src/codex-transcript-decoder.ts
7771
8256
  var SAFE_REF5 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
@@ -7989,7 +8474,7 @@ function assertCodexTranscriptHeader(registration, record3) {
7989
8474
  ])}).`);
7990
8475
  }
7991
8476
  function digest(value) {
7992
- return createHash9("sha256").update(value).digest("hex");
8477
+ return createHash10("sha256").update(value).digest("hex");
7993
8478
  }
7994
8479
  function timestamp(now) {
7995
8480
  const value = now();
@@ -7998,8 +8483,8 @@ function timestamp(now) {
7998
8483
  }
7999
8484
 
8000
8485
  // host/codex/src/codex-outbox.ts
8001
- import { mkdir as mkdir5, open as open5, readdir, rename as rename2, stat as stat3, unlink as unlink5 } from "node:fs/promises";
8002
- import { dirname as dirname8, isAbsolute as isAbsolute3, join as join6 } from "node:path";
8486
+ import { mkdir as mkdir5, open as open5, rename as rename2, stat as stat3, unlink as unlink5 } from "node:fs/promises";
8487
+ import { dirname as dirname8, isAbsolute as isAbsolute4, join as join7 } from "node:path";
8003
8488
 
8004
8489
  // host/invocation-context.ts
8005
8490
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -8106,12 +8591,12 @@ var CodexOutboxStore = class {
8106
8591
  constructor(directory) {
8107
8592
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
8108
8593
  this.directory = directory;
8109
- this.entriesDirectory = join6(directory, "entries");
8110
- this.sessionsDirectory = join6(directory, "sessions");
8111
- this.activeContextsDirectory = join6(directory, "active-contexts");
8112
- this.turnSelectionsDirectory = join6(directory, "turn-selections");
8113
- this.registrationsDirectory = join6(directory, "transcript-registrations");
8114
- this.cursorsDirectory = join6(directory, "transcript-cursors");
8594
+ this.entriesDirectory = join7(directory, "entries");
8595
+ this.sessionsDirectory = join7(directory, "sessions");
8596
+ this.activeContextsDirectory = join7(directory, "active-contexts");
8597
+ this.turnSelectionsDirectory = join7(directory, "turn-selections");
8598
+ this.registrationsDirectory = join7(directory, "transcript-registrations");
8599
+ this.cursorsDirectory = join7(directory, "transcript-cursors");
8115
8600
  }
8116
8601
  async prepare() {
8117
8602
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -8124,13 +8609,12 @@ var CodexOutboxStore = class {
8124
8609
  await writeAtomicJson(this.entryPath(entry.submission_ref), entry);
8125
8610
  }
8126
8611
  async list() {
8127
- await this.prepare();
8128
8612
  const entries = [];
8129
8613
  let malformed = 0;
8130
- for (const name of await readdir(this.entriesDirectory)) {
8614
+ for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
8131
8615
  if (!name.endsWith(".json")) continue;
8132
8616
  try {
8133
- const value = JSON.parse(await readOwnerStateFile(join6(this.entriesDirectory, name)));
8617
+ const value = JSON.parse(await readOwnerStateFile(join7(this.entriesDirectory, name)));
8134
8618
  validateEnvelope(value);
8135
8619
  entries.push(value);
8136
8620
  } catch {
@@ -8175,7 +8659,6 @@ var CodexOutboxStore = class {
8175
8659
  }
8176
8660
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
8177
8661
  if (!SAFE_REF6.test(hostSourceRef) || !SAFE_REF6.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
8178
- await this.prepare();
8179
8662
  return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
8180
8663
  }
8181
8664
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
@@ -8184,6 +8667,7 @@ var CodexOutboxStore = class {
8184
8667
  const path = this.activeContextPath(identity);
8185
8668
  const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
8186
8669
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
8670
+ await this.prepare();
8187
8671
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
8188
8672
  return true;
8189
8673
  }
@@ -8200,7 +8684,6 @@ var CodexOutboxStore = class {
8200
8684
  */
8201
8685
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
8202
8686
  if (!SAFE_REF6.test(hostSourceRef) || !SAFE_REF6.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
8203
- await this.prepare();
8204
8687
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
8205
8688
  return context;
8206
8689
  }
@@ -8224,7 +8707,6 @@ var CodexOutboxStore = class {
8224
8707
  async readSession(sourceRef, sessionRef) {
8225
8708
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
8226
8709
  if (!SAFE_REF6.test(sourceRef) || !SAFE_REF6.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
8227
- await this.prepare();
8228
8710
  return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
8229
8711
  }
8230
8712
  async registerTranscript(registration) {
@@ -8250,13 +8732,18 @@ var CodexOutboxStore = class {
8250
8732
  await removeOwnerState(this.registrationPath(registration.host_source_ref, registration.host_session_ref), "registration");
8251
8733
  await removeOwnerState(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "cursor");
8252
8734
  }
8735
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
8736
+ const path = this.registrationPath(hostSourceRef, hostSessionRef);
8737
+ const registration = await readOptionalJson2(path, validateRegistration);
8738
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
8739
+ return registration;
8740
+ }
8253
8741
  async listTranscriptRegistrations() {
8254
- await this.prepare();
8255
8742
  const registrations = [];
8256
- for (const name of await readdir(this.registrationsDirectory)) {
8743
+ for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
8257
8744
  if (!name.endsWith(".json")) continue;
8258
8745
  try {
8259
- const value = JSON.parse(await readOwnerStateFile(join6(this.registrationsDirectory, name)));
8746
+ const value = JSON.parse(await readOwnerStateFile(join7(this.registrationsDirectory, name)));
8260
8747
  validateRegistration(value);
8261
8748
  registrations.push(value);
8262
8749
  } catch {
@@ -8266,7 +8753,6 @@ var CodexOutboxStore = class {
8266
8753
  }
8267
8754
  async readTranscriptCursor(registration) {
8268
8755
  validateRegistration(registration);
8269
- await this.prepare();
8270
8756
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
8271
8757
  }
8272
8758
  async writeTranscriptCursor(cursor) {
@@ -8276,36 +8762,35 @@ var CodexOutboxStore = class {
8276
8762
  }
8277
8763
  async findByAlias(sourceRef, sessionRef, alias) {
8278
8764
  if (!SAFE_REF6.test(sourceRef) || !SAFE_REF6.test(sessionRef) || !SAFE_REF6.test(alias)) return null;
8279
- const read = await this.list();
8280
- const envelope = findEnvelopeByAlias(read.entries, sourceRef, sessionRef, alias);
8765
+ const read2 = await this.list();
8766
+ const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
8281
8767
  if (envelope !== null) return envelopeMatch(envelope);
8282
- await this.prepare();
8283
8768
  return null;
8284
8769
  }
8285
8770
  async hasPriorTurn(sourceRef, sessionRef) {
8286
8771
  if (!SAFE_REF6.test(sourceRef) || !SAFE_REF6.test(sessionRef)) return false;
8287
- const read = await this.list();
8288
- if (read.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
8772
+ const read2 = await this.list();
8773
+ if (read2.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
8289
8774
  return false;
8290
8775
  }
8291
8776
  entryPath(submissionRef) {
8292
8777
  if (!SAFE_REF6.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
8293
- return join6(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
8778
+ return join7(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
8294
8779
  }
8295
8780
  sessionPath(sourceRef, sessionRef) {
8296
- return join6(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
8781
+ return join7(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
8297
8782
  }
8298
8783
  activeContextPath(identity) {
8299
- return join6(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
8784
+ return join7(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
8300
8785
  }
8301
8786
  turnSelectionPath(sourceRef, sessionRef) {
8302
- return join6(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
8787
+ return join7(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
8303
8788
  }
8304
8789
  registrationPath(sourceRef, sessionRef) {
8305
- return join6(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
8790
+ return join7(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
8306
8791
  }
8307
8792
  cursorPath(sourceRef, sessionRef) {
8308
- return join6(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
8793
+ return join7(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
8309
8794
  }
8310
8795
  };
8311
8796
  async function removeOwnerState(path, what) {
@@ -8341,7 +8826,7 @@ async function writeAtomicJson(path, value) {
8341
8826
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
8342
8827
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
8343
8828
  try {
8344
- const handle = await open5(temp, "wx");
8829
+ const handle = await open5(temp, "wx", 384);
8345
8830
  try {
8346
8831
  await handle.writeFile(text, "utf8");
8347
8832
  await handle.sync();
@@ -8383,13 +8868,20 @@ async function readOptionalJson2(path, validate) {
8383
8868
  }
8384
8869
  async function ensureOwnerDirectory(path) {
8385
8870
  try {
8386
- await stat3(path);
8871
+ try {
8872
+ const stats2 = await stat3(path);
8873
+ if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8874
+ return;
8875
+ } catch (error) {
8876
+ if (!isNotFound(error)) throw error;
8877
+ }
8878
+ await mkdir5(path, { recursive: true, mode: 448 });
8879
+ const stats = await stat3(path);
8880
+ if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8387
8881
  } catch (error) {
8388
- if (!isNotFound(error)) throw storageError("Codex owner state directory is unavailable.");
8389
- await mkdir5(path, { recursive: true });
8882
+ if (error instanceof CodexHostAdapterError) throw error;
8883
+ throw storageError("Codex owner state directory is unavailable.");
8390
8884
  }
8391
- const stats = await stat3(path);
8392
- if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8393
8885
  }
8394
8886
  async function readOwnerStateFile(path) {
8395
8887
  let handle;
@@ -8432,7 +8924,7 @@ function validateRegistrationFields(value) {
8432
8924
  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 }])}).`);
8433
8925
  }
8434
8926
  function validRegistrationCwd(value) {
8435
- return value === void 0 || typeof value === "string" && isAbsolute3(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
8927
+ return value === void 0 || typeof value === "string" && isAbsolute4(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
8436
8928
  }
8437
8929
  function validateCursor(value) {
8438
8930
  if (!isRecord9(value)) throw storageError("Codex transcript cursor is malformed.");
@@ -8561,11 +9053,11 @@ var CodexProducer = class {
8561
9053
  };
8562
9054
 
8563
9055
  // host/codex/src/codex-runtime-paths.ts
8564
- import { join as join7 } from "node:path";
9056
+ import { join as join8 } from "node:path";
8565
9057
  var CODEX_HOME_ENVIRONMENT = "CODEX_HOME";
8566
9058
  var CODEX_HOME_DEFAULT_DIRECTORY = ".codex";
8567
9059
  function resolveCodexHome(environment, home) {
8568
- return environment[CODEX_HOME_ENVIRONMENT] || join7(home, CODEX_HOME_DEFAULT_DIRECTORY);
9060
+ return environment[CODEX_HOME_ENVIRONMENT] || join8(home, CODEX_HOME_DEFAULT_DIRECTORY);
8569
9061
  }
8570
9062
 
8571
9063
  // host/codex/src/codex-adapter.ts
@@ -8935,25 +9427,21 @@ async function drainCodexProducerOnce(options) {
8935
9427
  }
8936
9428
 
8937
9429
  // host/codex/src/codex-usage-facts-capturer.ts
8938
- import { createHash as createHash10 } from "node:crypto";
9430
+ import { createHash as createHash11 } from "node:crypto";
8939
9431
  var CodexUsageFactsCapturer = class {
8940
9432
  sources;
8941
9433
  usage;
8942
9434
  now;
8943
- diagnosticSink;
8944
- nextRegistrationIndex = 0;
9435
+ registrations;
8945
9436
  constructor(options) {
8946
9437
  this.sources = new CodexOutboxStore(options.outbox_dir);
8947
9438
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
8948
9439
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
8949
- this.diagnosticSink = options.diagnostic_sink;
9440
+ this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
8950
9441
  }
8951
9442
  async captureNext() {
8952
9443
  const registrations = await this.sources.listTranscriptRegistrations();
8953
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
8954
- this.nextRegistrationIndex = result.nextIndex;
8955
- if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
8956
- return result.captured;
9444
+ return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
8957
9445
  }
8958
9446
  async captureRegistration(registration) {
8959
9447
  const prepared = await openHostUsageTranscriptCursor({
@@ -9134,7 +9622,7 @@ function coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount
9134
9622
  return { reason, source_file_ref: sourceFileRef, start_offset: startOffset, end_offset: endOffset, omitted_count: omittedCount };
9135
9623
  }
9136
9624
  function sha2564(value) {
9137
- return createHash10("sha256").update(value).digest("hex");
9625
+ return createHash11("sha256").update(value).digest("hex");
9138
9626
  }
9139
9627
  async function anchorMatches(handle, cursor) {
9140
9628
  const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
@@ -9183,7 +9671,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
9183
9671
  // host/codex/src/codex-visible-output-budget.ts
9184
9672
  import { readFile as readFile2 } from "node:fs/promises";
9185
9673
  import { homedir } from "node:os";
9186
- import { join as join8 } from "node:path";
9674
+ import { join as join9 } from "node:path";
9187
9675
  var import_toml = __toESM(require_toml(), 1);
9188
9676
  var CODEX_DEFAULT_TOOL_OUTPUT_TOKEN_LIMIT = 5e3;
9189
9677
  var CODEX_UTF8_BYTES_PER_OUTPUT_TOKEN = 4;
@@ -9191,7 +9679,7 @@ async function resolveCodexVisibleOutputMaxBytes(environment = process.env) {
9191
9679
  const codexHome = resolveCodexHome(environment, homedir());
9192
9680
  let source;
9193
9681
  try {
9194
- source = await readFile2(join8(codexHome, "config.toml"), "utf8");
9682
+ source = await readFile2(join9(codexHome, "config.toml"), "utf8");
9195
9683
  } catch (error) {
9196
9684
  return isNotFound2(error) ? codexBytes(CODEX_DEFAULT_TOOL_OUTPUT_TOKEN_LIMIT) : void 0;
9197
9685
  }
@@ -9222,6 +9710,7 @@ var CODEX_INVOCATION_AUTHENTICATION_DESCRIPTOR = {
9222
9710
  create_store: (directory) => new CodexOutboxStore(directory),
9223
9711
  can_wait_for_context_activation: async ({ store, identity }) => await store.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref) !== null,
9224
9712
  session_id_env: CODEX_THREAD_ID_ENVIRONMENT,
9713
+ tool_call_id_env: CODEX_TOOL_CALL_ID_ENVIRONMENT,
9225
9714
  session_ref: hostSessionReference,
9226
9715
  config_flag: HOST_PRODUCER_CONFIG_FLAG,
9227
9716
  parse_config_flag: parseHostProducerConfigFlag,
@@ -9234,7 +9723,7 @@ function runCodexInvocationAuthenticationCommand(args, options) {
9234
9723
  }
9235
9724
  async function readCodexInvocationHumanMessageWindow(input) {
9236
9725
  let lastOrdinal;
9237
- return readRegisteredHostInvocationHumanMessageWindow(() => input.store.listTranscriptRegistrations(), (registration) => input.store.readTranscriptCursor(registration), input.identity, (line, registration, cursor) => {
9726
+ return readRegisteredHostInvocationHumanMessageWindow((identity) => input.store.readTranscriptRegistration(identity.host_source_ref, identity.host_session_ref), (registration) => input.store.readTranscriptCursor(registration), input.identity, (line, registration, cursor) => {
9238
9727
  let record3;
9239
9728
  try {
9240
9729
  record3 = decodeCodexTranscriptLine(line);