@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.
@@ -2207,7 +2207,7 @@ var client_wire_contract_default = {
2207
2207
  },
2208
2208
  command_request: {
2209
2209
  schema_name: "ceal.command_request",
2210
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
2210
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
2211
2211
  absolute_transport_max_bytes: 65536
2212
2212
  },
2213
2213
  command_resolution: {
@@ -2253,7 +2253,7 @@ var client_wire_contract_default = {
2253
2253
  },
2254
2254
  command_response: {
2255
2255
  schema_name: "ceal.command_response",
2256
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
2256
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
2257
2257
  descriptor_field: "verified_artifact",
2258
2258
  request_context_field: "request_context",
2259
2259
  required_fields: [
@@ -2266,7 +2266,8 @@ var client_wire_contract_default = {
2266
2266
  "visible_output_max_bytes",
2267
2267
  "local_delivery",
2268
2268
  "verified_artifact",
2269
- "request_context"
2269
+ "request_context",
2270
+ "result_file"
2270
2271
  ],
2271
2272
  bare_document_fields: [
2272
2273
  "invocation",
@@ -2395,6 +2396,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
2395
2396
  // (never connected, revoked, or expired). The caller runs that exact
2396
2397
  // Operation, completes the consent it hands back, and retries the same call.
2397
2398
  "connect_personal_account",
2399
+ // The refusal names the caller's own preferences update step: the read
2400
+ // needs a personal connection the caller holds but has not selected in
2401
+ // Ceal preferences, or has not confirmed through the initial review. The
2402
+ // caller reads personal.preferences.get, runs personal.preferences.update
2403
+ // at the current revision to select it, and retries the same call.
2404
+ "update_personal_preferences",
2398
2405
  // The provider or Gateway named a bounded wait; the caller waits that long
2399
2406
  // and submits the same read again.
2400
2407
  "retry_after",
@@ -2535,6 +2542,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
2535
2542
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
2536
2543
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
2537
2544
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
2545
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
2546
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
2547
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
2538
2548
  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"]);
2539
2549
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
2540
2550
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -2575,6 +2585,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
2575
2585
  ]);
2576
2586
 
2577
2587
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
2588
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
2589
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
2590
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
2591
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
2592
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
2593
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
2594
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
2595
+ function escapePathPattern(value) {
2596
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
2597
+ }
2598
+ function machineHomePathPatterns(flags) {
2599
+ const posix12 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
2600
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
2601
+ return [new RegExp(posix12, flags), new RegExp(windows, flags)];
2602
+ }
2578
2603
  var CealProtocolValidationError = class extends Error {
2579
2604
  name = "CealProtocolValidationError";
2580
2605
  code;
@@ -2926,10 +2951,13 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
2926
2951
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
2927
2952
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
2928
2953
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
2929
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
2954
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
2955
+ 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}\`.`;
2930
2956
  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.";
2931
- 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.";
2957
+ 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.";
2958
+ 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.";
2932
2959
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
2960
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
2933
2961
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
2934
2962
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
2935
2963
  }
@@ -2950,13 +2978,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2950
2978
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2951
2979
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2952
2980
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2953
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2954
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2955
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2956
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2957
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2958
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2959
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2981
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2982
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2983
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2984
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2985
+ 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),
2986
+ 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),
2987
+ 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),
2988
+ // A stored session that predates the authority-epoch commitment carries no
2989
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
2990
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2991
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2992
+ 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),
2993
+ 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),
2994
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
2995
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2960
2996
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2961
2997
  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),
2962
2998
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -2971,10 +3007,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2971
3007
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
2972
3008
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
2973
3009
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
2974
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
2975
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
2976
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
2977
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
3010
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
3011
+ [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),
2978
3012
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
2979
3013
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
2980
3014
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -2986,6 +3020,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2986
3020
  // The safe move varies by request. Keep the sentence conditional on the
2987
3021
  // same `retryable` and `next_action` facts the response exposes.
2988
3022
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
3023
+ // 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.
3024
+ 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),
2989
3025
  // Restored verbatim from the retired `localFailureText`
2990
3026
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
2991
3027
  // session context unavailable, so the caller repairs or adopts the
@@ -3076,7 +3112,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
3076
3112
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
3077
3113
  // The bounded Host reason does not prove ephemerality. A Host refusal never
3078
3114
  // changes mode; standalone remains the separate Client authority path.
3079
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
3115
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
3080
3116
  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),
3081
3117
  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),
3082
3118
  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),
@@ -3093,7 +3129,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
3093
3129
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
3094
3130
  // sandboxed Relay socket names the run-alone retry.
3095
3131
  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),
3096
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
3132
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
3097
3133
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
3098
3134
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
3099
3135
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -3341,7 +3377,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
3341
3377
  max_literal_nodes: 512
3342
3378
  });
3343
3379
 
3344
- // packages/ceal-client-protocol/src/operation-json-schema.ts
3380
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
3345
3381
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
3346
3382
 
3347
3383
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -3492,7 +3528,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
3492
3528
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
3493
3529
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
3494
3530
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
3495
- 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.`;
3531
+ 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.`;
3532
+ 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.`;
3496
3533
  function shellSingleQuoted(value) {
3497
3534
  return `'${value.replaceAll("'", "'\\''")}'`;
3498
3535
  }
@@ -3642,6 +3679,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3642
3679
  "review_submitted",
3643
3680
  "comment_created",
3644
3681
  "reaction_created",
3682
+ "pull_request_merged",
3683
+ "release_published",
3645
3684
  "ceal_write_completed",
3646
3685
  "event_start",
3647
3686
  "all_day_start",
@@ -3653,7 +3692,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3653
3692
  "page_last_edited",
3654
3693
  "resource_modified"
3655
3694
  ]);
3656
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
3695
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
3657
3696
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
3658
3697
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
3659
3698
  "provider_page_budget",
@@ -3674,6 +3713,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3674
3713
  "github.pull_request.opened",
3675
3714
  "github.issue.edited",
3676
3715
  "github.pull_request.edited",
3716
+ "github.pull_request.merged",
3717
+ "github.release.published",
3677
3718
  "github.review.submitted",
3678
3719
  "github.issue_comment.created",
3679
3720
  "github.review_comment.created",
@@ -3687,6 +3728,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3687
3728
  "drive.file.created",
3688
3729
  "drive.file.modified",
3689
3730
  "drive.file.viewed",
3731
+ "mail.sent",
3690
3732
  "notion.page.created",
3691
3733
  "notion.page.edited"
3692
3734
  ]);
@@ -3700,6 +3742,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3700
3742
  "github.review_comment.created": "comment_created",
3701
3743
  "github.issue.opened": "resource_created",
3702
3744
  "github.pull_request.opened": "resource_created",
3745
+ "github.pull_request.merged": "pull_request_merged",
3746
+ "github.release.published": "release_published",
3703
3747
  "github.issue.edited": "resource_modified",
3704
3748
  "github.pull_request.edited": "resource_modified",
3705
3749
  "github.reaction.created": "reaction_created",
@@ -3710,6 +3754,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3710
3754
  "drive.file.created": "file_created",
3711
3755
  "drive.file.modified": "file_modified_by_me",
3712
3756
  "drive.file.viewed": "file_viewed_by_me",
3757
+ "mail.sent": "message_created",
3713
3758
  "notion.page.created": "page_created",
3714
3759
  "notion.page.edited": "page_last_edited"
3715
3760
  });
@@ -3820,6 +3865,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
3820
3865
  "principal_inactive",
3821
3866
  "authority_replaced",
3822
3867
  "refresh_recovery_unavailable",
3868
+ "refresh_recovery_outcome_unavailable",
3869
+ "refresh_state_unavailable",
3823
3870
  "refresh_recovery_expired",
3824
3871
  // The serving gate answers this while the Gateway is still starting and the
3825
3872
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -4470,9 +4517,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
4470
4517
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
4471
4518
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
4472
4519
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
4473
- // This reason cannot distinguish a Codex side conversation from a missing
4474
- // context in a regular session, so guidance must leave that choice to the caller.
4475
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
4520
+ // A missing turn right after a Host restart clears by itself once the
4521
+ // watcher reactivates the turn, so the caller waits briefly and retries;
4522
+ // a caller that knows it is in an ephemeral side conversation keeps the
4523
+ // standalone fallback the guidance names second.
4524
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
4476
4525
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
4477
4526
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
4478
4527
  // `no_binding` now means the producer has no real current Host session. The
@@ -4489,7 +4538,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
4489
4538
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
4490
4539
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
4491
4540
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
4492
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
4541
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
4493
4542
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
4494
4543
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
4495
4544
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -4582,6 +4631,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
4582
4631
  maximum: CEAL_PROTOCOL_VERSION
4583
4632
  });
4584
4633
 
4634
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
4635
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
4636
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
4637
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
4638
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
4639
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
4640
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
4641
+ function redactOperatorDiagnosticSecrets(value) {
4642
+ 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]");
4643
+ }
4644
+ function redactOperatorDiagnosticText(value) {
4645
+ const normalized = normalizeCealSingleLineText(value);
4646
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
4647
+ }
4648
+ function renderOperatorDiagnostic(value) {
4649
+ const state = collectDiagnosticState(value);
4650
+ const fields = [
4651
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
4652
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
4653
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
4654
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
4655
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
4656
+ ].filter((field) => field !== void 0);
4657
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
4658
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
4659
+ }
4660
+ function collectDiagnosticState(value) {
4661
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
4662
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
4663
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
4664
+ const current = pending.shift();
4665
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
4666
+ }
4667
+ return state;
4668
+ }
4669
+ function visitDiagnosticNode(current, state, pending, visited) {
4670
+ if (isObject(current)) {
4671
+ if (visited.has(current)) return;
4672
+ visited.add(current);
4673
+ }
4674
+ captureProcessEvidence(current, state);
4675
+ appendCause(current, state.causes);
4676
+ enqueueCauseChildren(current, state.causes.length, pending);
4677
+ }
4678
+ function captureProcessEvidence(current, state) {
4679
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
4680
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
4681
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
4682
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
4683
+ }
4684
+ function appendCause(current, causes) {
4685
+ const errors = read(current, "errors");
4686
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
4687
+ causes.push(errorCause(current));
4688
+ return;
4689
+ }
4690
+ if (!isObject(current)) {
4691
+ const message = safeText(current);
4692
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
4693
+ }
4694
+ }
4695
+ function errorCause(error) {
4696
+ const name = safeText(read(error, "name")) ?? "Error";
4697
+ const message = safeText(read(error, "message"));
4698
+ const codeValue = read(error, "code");
4699
+ const code2 = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
4700
+ const errnoValue = read(error, "errno");
4701
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
4702
+ const syscall = safeText(read(error, "syscall"));
4703
+ const path = safePath(read(error, "path"));
4704
+ return Object.freeze({ error_class: name, ...message === void 0 ? {} : { message }, ...code2 === void 0 ? {} : { code: code2 }, ...errno === void 0 ? {} : { errno }, ...syscall === void 0 ? {} : { syscall }, ...path === void 0 ? {} : { path } });
4705
+ }
4706
+ function enqueueCauseChildren(current, causeCount, pending) {
4707
+ const cause = read(current, "cause");
4708
+ if (cause !== void 0) pending.push(cause);
4709
+ const errors = read(current, "errors");
4710
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
4711
+ }
4712
+ function isObject(value) {
4713
+ return typeof value === "object" && value !== null;
4714
+ }
4715
+ function formatCause(cause) {
4716
+ const fields = [
4717
+ cause.error_class,
4718
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
4719
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
4720
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
4721
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
4722
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
4723
+ ].filter((field) => field !== void 0);
4724
+ return fields.join(" ");
4725
+ }
4726
+ function tail(value) {
4727
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
4728
+ return safeDiagnosticText(clipped);
4729
+ }
4730
+ function safeText(value) {
4731
+ if (typeof value !== "string") return void 0;
4732
+ const safe = safeDiagnosticText(value);
4733
+ if (safe.length === 0) return void 0;
4734
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
4735
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
4736
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
4737
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4738
+ }
4739
+ function safePath(value) {
4740
+ if (typeof value !== "string") return void 0;
4741
+ const safe = safeDiagnosticText(value);
4742
+ if (safe.length === 0) return void 0;
4743
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
4744
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
4745
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
4746
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4747
+ }
4748
+ function safeDiagnosticText(value) {
4749
+ return redactOperatorDiagnosticText(String(value));
4750
+ }
4751
+ function outputText(value) {
4752
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
4753
+ if (value instanceof Uint8Array) {
4754
+ try {
4755
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
4756
+ } catch {
4757
+ return void 0;
4758
+ }
4759
+ }
4760
+ return void 0;
4761
+ }
4762
+ function safeStatus(value) {
4763
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4764
+ return typeof value === "string" ? safeText(value) : void 0;
4765
+ }
4766
+ function safeExitCode(value) {
4767
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
4768
+ }
4769
+ function read(value, key) {
4770
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
4771
+ try {
4772
+ return Reflect.get(value, key);
4773
+ } catch {
4774
+ return void 0;
4775
+ }
4776
+ }
4777
+ function redactHomePaths(value) {
4778
+ const paths = [
4779
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
4780
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
4781
+ ];
4782
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
4783
+ let output = "";
4784
+ let cursor = 0;
4785
+ for (const path of paths) {
4786
+ if (path.start < cursor) continue;
4787
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
4788
+ cursor = path.end;
4789
+ }
4790
+ return output + value.slice(cursor);
4791
+ }
4792
+ function configuredHomePathPatterns() {
4793
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
4794
+ return homes.flatMap((home) => {
4795
+ const root = home.replace(/[\\/]+$/gu, "");
4796
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
4797
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
4798
+ return [{ pattern, prefixLength: root.length }];
4799
+ });
4800
+ }
4801
+ function matchedHomePrefixLength(value) {
4802
+ let separators = 0;
4803
+ for (let index = 0; index < value.length; index += 1) {
4804
+ if (value[index] !== "/" && value[index] !== "\\") continue;
4805
+ separators += 1;
4806
+ if (separators === 3) return index;
4807
+ }
4808
+ return value.length;
4809
+ }
4810
+ function redactUrls(value) {
4811
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
4812
+ }
4813
+ function redactFilePaths(value) {
4814
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
4815
+ }
4816
+ function homePathRange(value, match, prefixLength) {
4817
+ const index = match.index;
4818
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
4819
+ const start = index;
4820
+ let end = start + match[0].length;
4821
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
4822
+ if (quote !== void 0) {
4823
+ const closing = value.indexOf(quote, end);
4824
+ if (closing >= 0) end = closing;
4825
+ }
4826
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
4827
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
4828
+ }
4829
+ function truncateUtf8(value, maxBytes) {
4830
+ if (byteLength(value) <= maxBytes) return value;
4831
+ let output = "";
4832
+ for (const character of value) {
4833
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
4834
+ output += character;
4835
+ }
4836
+ return `${output}…`;
4837
+ }
4838
+
4585
4839
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
4586
4840
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
4587
4841
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -4673,11 +4927,11 @@ function withRelayEndpointLock(endpoint, run) {
4673
4927
  const gate = new Promise((resolve) => {
4674
4928
  release = resolve;
4675
4929
  });
4676
- const tail = prior.then(() => gate);
4677
- relayEndpointLocks.set(endpoint, tail);
4930
+ const tail2 = prior.then(() => gate);
4931
+ relayEndpointLocks.set(endpoint, tail2);
4678
4932
  return prior.then(run).finally(() => {
4679
4933
  release?.();
4680
- if (relayEndpointLocks.get(endpoint) === tail) relayEndpointLocks.delete(endpoint);
4934
+ if (relayEndpointLocks.get(endpoint) === tail2) relayEndpointLocks.delete(endpoint);
4681
4935
  });
4682
4936
  }
4683
4937
  function currentUid(fallback) {
@@ -4864,8 +5118,80 @@ import { execFile } from "node:child_process";
4864
5118
  import { createHash as createHash5 } from "node:crypto";
4865
5119
  import { constants } from "node:fs";
4866
5120
  import { lstat as lstat3, open } from "node:fs/promises";
4867
- import { dirname as dirname2, join as join2, win32 as win324 } from "node:path";
5121
+ import { dirname as dirname2, join as join3, win32 as win324 } from "node:path";
4868
5122
  import { fileURLToPath } from "node:url";
5123
+
5124
+ // host/spawn-working-directory.ts
5125
+ import { mkdirSync } from "node:fs";
5126
+ import { tmpdir } from "node:os";
5127
+ import { isAbsolute, join as join2, normalize, parse, sep } from "node:path";
5128
+ function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
5129
+ const candidates = [];
5130
+ const explicit = candidateDir(stateRoot);
5131
+ if (explicit !== void 0) candidates.push(explicit);
5132
+ const fallback = defaultHostStateRoot();
5133
+ if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
5134
+ const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
5135
+ if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
5136
+ for (const dir of candidates) {
5137
+ if (!keptOutside(dir, keepOutside)) continue;
5138
+ try {
5139
+ mkdirSync(dir, { recursive: true, mode: 448 });
5140
+ return dir;
5141
+ } catch {
5142
+ continue;
5143
+ }
5144
+ }
5145
+ return tmpdir();
5146
+ }
5147
+ function candidateDir(dir) {
5148
+ if (dir === void 0 || dir === "") return void 0;
5149
+ if (!isAbsolute(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
5150
+ return normalize(dir);
5151
+ }
5152
+ function defaultHostStateRoot() {
5153
+ if (process.platform === "win32") {
5154
+ const localAppData = nonEmptyEnv("LOCALAPPDATA");
5155
+ if (localAppData === void 0) return void 0;
5156
+ return candidateDir(join2(localAppData, "Ceal", "Host"));
5157
+ }
5158
+ if (process.platform === "darwin") {
5159
+ const home2 = nonEmptyEnv("HOME");
5160
+ if (home2 === void 0) return void 0;
5161
+ return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
5162
+ }
5163
+ const xdg = nonEmptyEnv("XDG_STATE_HOME");
5164
+ if (xdg !== void 0) {
5165
+ const root = candidateDir(join2(xdg, "ceal", "host"));
5166
+ if (root !== void 0) return root;
5167
+ }
5168
+ const home = nonEmptyEnv("HOME");
5169
+ if (home === void 0) return void 0;
5170
+ return candidateDir(join2(home, ".local", "state", "ceal", "host"));
5171
+ }
5172
+ function nonEmptyEnv(name) {
5173
+ const value = process.env[name];
5174
+ return value === void 0 || value === "" ? void 0 : value;
5175
+ }
5176
+ function keptOutside(dir, keepOutside) {
5177
+ for (const tree of keepOutside) {
5178
+ const clean = candidateDir(tree);
5179
+ if (clean === void 0) continue;
5180
+ if (insideDir(dir, clean)) return false;
5181
+ }
5182
+ return true;
5183
+ }
5184
+ function insideDir(dir, tree) {
5185
+ if (sameDir(dir, tree)) return true;
5186
+ if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
5187
+ return dir.startsWith(tree + sep);
5188
+ }
5189
+ function sameDir(left, right) {
5190
+ if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
5191
+ return left === right;
5192
+ }
5193
+
5194
+ // host/secure-file.ts
4869
5195
  var SecureFileCustodyError = class extends Error {
4870
5196
  name = "SecureFileCustodyError";
4871
5197
  reason;
@@ -4996,7 +5322,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
4996
5322
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
4997
5323
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
4998
5324
  return await new Promise((resolve, reject2) => {
4999
- const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
5325
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: resolveCealSpawnWorkingDirectory() }, (error, stdout, stderr) => {
5000
5326
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
5001
5327
  if (exitCode === null) {
5002
5328
  reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -5025,7 +5351,7 @@ function securefsRefusal(stderr) {
5025
5351
  }
5026
5352
  function resolveInstalledHostExecutable(platform) {
5027
5353
  const privateRuntimeRoot = dirname2(fileURLToPath(import.meta.url));
5028
- return platform === "win32" ? win324.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
5354
+ return platform === "win32" ? win324.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
5029
5355
  }
5030
5356
  function isRecord(value) {
5031
5357
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -5358,7 +5684,7 @@ function parseCanonicalJson(text, error) {
5358
5684
  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) }])}`);
5359
5685
  return value;
5360
5686
  } catch (parseError) {
5361
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
5687
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
5362
5688
  }
5363
5689
  }
5364
5690
  function firstDifferenceIndex(left, right) {
@@ -5425,7 +5751,7 @@ import { setTimeout as delay2 } from "node:timers/promises";
5425
5751
  import { createHash as createHash6 } from "node:crypto";
5426
5752
  import { constants as constants4 } from "node:fs";
5427
5753
  import { mkdir as mkdir3, open as open3, opendir as opendir2, unlink as unlink3 } from "node:fs/promises";
5428
- import { dirname as dirname5, join as join3 } from "node:path";
5754
+ import { dirname as dirname5, join as join4 } from "node:path";
5429
5755
 
5430
5756
  // host/relay/src/durable-atomic-replacement.ts
5431
5757
  import { lstat as lstat5, mkdir as mkdir2, open as open2, rename, unlink as unlink2 } from "node:fs/promises";
@@ -5578,9 +5904,9 @@ var HostUsageFactsStore = class {
5578
5904
  afterBatchPublish;
5579
5905
  sessionDirectoryCursor;
5580
5906
  constructor(options) {
5581
- this.root = join3(options.outbox_dir, "usage-facts");
5582
- this.sessions = join3(this.root, "sessions");
5583
- this.batches = join3(this.root, "batches");
5907
+ this.root = join4(options.outbox_dir, "usage-facts");
5908
+ this.sessions = join4(this.root, "sessions");
5909
+ this.batches = join4(this.root, "batches");
5584
5910
  this.platform = options.platform ?? process.platform;
5585
5911
  this.custody = options.secure_file_custody ?? {};
5586
5912
  this.afterPendingWrite = options.afterPendingWrite;
@@ -5597,7 +5923,6 @@ var HostUsageFactsStore = class {
5597
5923
  await cursor?.close();
5598
5924
  }
5599
5925
  async readState(producer, hostSourceRef, hostSessionRef) {
5600
- await this.prepare();
5601
5926
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
5602
5927
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
5603
5928
  if (value === null) return null;
@@ -5655,11 +5980,15 @@ var HostUsageFactsStore = class {
5655
5980
  }
5656
5981
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
5657
5982
  async sweepOrphanedBatches(state) {
5658
- await this.prepare();
5659
5983
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
5660
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
5661
5984
  const expected = expectedBatchNames(state);
5662
- const directory = await opendir2(directoryPath);
5985
+ let directory;
5986
+ try {
5987
+ directory = await opendir2(directoryPath);
5988
+ } catch (error) {
5989
+ if (errorCode2(error) === "ENOENT") return 0;
5990
+ throw error;
5991
+ }
5663
5992
  let inspected = 0;
5664
5993
  let deleted = 0;
5665
5994
  try {
@@ -5668,7 +5997,7 @@ var HostUsageFactsStore = class {
5668
5997
  if (entry === null) break;
5669
5998
  inspected += 1;
5670
5999
  if (!isOrphanBatchEntry(entry, expected)) continue;
5671
- await unlink3(join3(directoryPath, entry.name));
6000
+ await unlink3(join4(directoryPath, entry.name));
5672
6001
  deleted += 1;
5673
6002
  }
5674
6003
  } finally {
@@ -5696,10 +6025,9 @@ var HostUsageFactsStore = class {
5696
6025
  });
5697
6026
  }
5698
6027
  async nextUploadCandidate(producer, hostSourceRef) {
5699
- await this.prepare();
5700
6028
  const names = await this.readNextSessionNames();
5701
6029
  for (const name of names) {
5702
- const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
6030
+ const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
5703
6031
  if (state === null) continue;
5704
6032
  validateStateOwner(state, producer, hostSourceRef);
5705
6033
  let validated = state;
@@ -5714,7 +6042,14 @@ var HostUsageFactsStore = class {
5714
6042
  return null;
5715
6043
  }
5716
6044
  async readNextSessionNames() {
5717
- this.sessionDirectoryCursor ??= await opendir2(this.sessions);
6045
+ if (this.sessionDirectoryCursor === void 0) {
6046
+ try {
6047
+ this.sessionDirectoryCursor = await opendir2(this.sessions);
6048
+ } catch (error) {
6049
+ if (errorCode2(error) === "ENOENT") return [];
6050
+ throw error;
6051
+ }
6052
+ }
5718
6053
  const names = [];
5719
6054
  let inspected = 0;
5720
6055
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -5869,25 +6204,25 @@ var HostUsageFactsStore = class {
5869
6204
  const gate = new Promise((resolve) => {
5870
6205
  release = resolve;
5871
6206
  });
5872
- const tail = previous.then(() => gate);
5873
- SESSION_TRANSITION_TAILS.set(key, tail);
6207
+ const tail2 = previous.then(() => gate);
6208
+ SESSION_TRANSITION_TAILS.set(key, tail2);
5874
6209
  await previous;
5875
6210
  try {
5876
6211
  return await run();
5877
6212
  } finally {
5878
6213
  release?.();
5879
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
6214
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
5880
6215
  }
5881
6216
  }
5882
6217
  sessionPath(producer, hostSourceRef, hostSessionRef) {
5883
- return join3(this.sessions, `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
6218
+ return join4(this.sessions, `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
5884
6219
  }
5885
6220
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
5886
6221
  const sessionName = `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
5887
- return join3(this.batches, sessionName.slice(0, -5));
6222
+ return join4(this.batches, sessionName.slice(0, -5));
5888
6223
  }
5889
6224
  batchPath(state, batchRef) {
5890
- return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
6225
+ return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
5891
6226
  }
5892
6227
  };
5893
6228
  function serializeBatch(batch) {
@@ -6129,7 +6464,7 @@ function sha2563(value) {
6129
6464
  // host/service-log.ts
6130
6465
  import { constants as constants5 } from "node:fs";
6131
6466
  import { copyFile, mkdir as mkdir4, stat, truncate, appendFile } from "node:fs/promises";
6132
- import { dirname as dirname6, isAbsolute, posix as posix5, win32 as win326 } from "node:path";
6467
+ import { dirname as dirname6, isAbsolute as isAbsolute2, posix as posix5, win32 as win326 } from "node:path";
6133
6468
 
6134
6469
  // host/service-log-delivery.ts
6135
6470
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -6302,7 +6637,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
6302
6637
  await appendHostServiceLogLine(path, line).catch(() => void 0);
6303
6638
  }
6304
6639
  async function appendHostServiceLogLine(path, line) {
6305
- if (!isAbsolute(path)) return;
6640
+ if (!isAbsolute2(path)) return;
6306
6641
  await ensureHostServiceLogDirectory(path);
6307
6642
  await appendFile(path, line);
6308
6643
  }
@@ -6365,6 +6700,10 @@ var HostUsageFactsUploader = class {
6365
6700
  async close() {
6366
6701
  await this.store.close();
6367
6702
  }
6703
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
6704
+ async prepare() {
6705
+ await this.store.prepare();
6706
+ }
6368
6707
  async uploadOne(signal) {
6369
6708
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
6370
6709
  if (candidate === null) return false;
@@ -6387,6 +6726,11 @@ var HostUsageFactsUploader = class {
6387
6726
  };
6388
6727
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
6389
6728
  const uploader = new HostUsageFactsUploader(options);
6729
+ try {
6730
+ await uploader.prepare();
6731
+ } catch {
6732
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
6733
+ }
6390
6734
  let delay3 = 500;
6391
6735
  let failures = 0;
6392
6736
  try {
@@ -6416,6 +6760,7 @@ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
6416
6760
 
6417
6761
  // host/relay/src/host-producer-core.ts
6418
6762
  import { createHash as createHash7 } from "node:crypto";
6763
+ import { readdir } from "node:fs/promises";
6419
6764
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
6420
6765
  function isHostTranscriptCursorReason(value) {
6421
6766
  return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
@@ -6460,9 +6805,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
6460
6805
  let lastNewline = -1;
6461
6806
  while (position < size) {
6462
6807
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
6463
- const read = await handle.read(buffer, 0, buffer.length, position);
6464
- if (read.bytesRead === 0) break;
6465
- const chunk = buffer.subarray(0, read.bytesRead);
6808
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
6809
+ if (read2.bytesRead === 0) break;
6810
+ const chunk = buffer.subarray(0, read2.bytesRead);
6466
6811
  chunks.push(chunk);
6467
6812
  const newline = chunk.lastIndexOf(10);
6468
6813
  if (newline >= 0) lastNewline = total + newline;
@@ -6621,6 +6966,14 @@ var HostTranscriptWatcher = class {
6621
6966
  return transcriptCursorBoundsReason(handle, cursor, size);
6622
6967
  }
6623
6968
  };
6969
+ async function listHostOutboxDirectoryNames(directory) {
6970
+ try {
6971
+ return await readdir(directory);
6972
+ } catch (error) {
6973
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
6974
+ throw error;
6975
+ }
6976
+ }
6624
6977
  var HostProducerDrainCore = class {
6625
6978
  host;
6626
6979
  now;
@@ -6635,21 +6988,21 @@ var HostProducerDrainCore = class {
6635
6988
  return run;
6636
6989
  }
6637
6990
  async drainLocked() {
6638
- const read = await this.host.listEnvelopes();
6991
+ const read2 = await this.host.listEnvelopes();
6639
6992
  let removed = 0;
6640
6993
  let expired = 0;
6641
- for (const envelope of read.entries) {
6994
+ for (const envelope of read2.entries) {
6642
6995
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
6643
6996
  else removed += 1;
6644
6997
  await this.host.removeEnvelope(envelope);
6645
6998
  }
6646
- return { removed, expired, malformed: read.malformed };
6999
+ return { removed, expired, malformed: read2.malformed };
6647
7000
  }
6648
7001
  };
6649
7002
 
6650
7003
  // host/claude/src/claude-outbox.ts
6651
- import { mkdir as mkdir5, readdir, readFile, unlink as unlink4 } from "node:fs/promises";
6652
- import { isAbsolute as isAbsolute3, join as join4 } from "node:path";
7004
+ import { mkdir as mkdir5, readFile, unlink as unlink4 } from "node:fs/promises";
7005
+ import { isAbsolute as isAbsolute4, join as join5 } from "node:path";
6653
7006
 
6654
7007
  // host/invocation-context.ts
6655
7008
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -6731,29 +7084,46 @@ var HostUsageTranscriptSourceError = class extends Error {
6731
7084
  this.name = "HostUsageTranscriptSourceError";
6732
7085
  }
6733
7086
  };
6734
- async function readHostUsageTranscriptSource(read) {
7087
+ async function readHostUsageTranscriptSource(read2) {
6735
7088
  try {
6736
- return await read();
7089
+ return await read2();
6737
7090
  } catch (error) {
6738
7091
  throw new HostUsageTranscriptSourceError({ cause: error });
6739
7092
  }
6740
7093
  }
6741
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
6742
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
6743
- let failed = false;
6744
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
6745
- const index = (startIndex + attempt) % registrations.length;
6746
- const registration = registrations[index];
6747
- if (registration === void 0) continue;
6748
- try {
6749
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
6750
- } catch (error) {
6751
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
7094
+ var HostUsageRegistrationCapture = class {
7095
+ nextIndex = 0;
7096
+ producer;
7097
+ diagnosticSink;
7098
+ constructor(producer, diagnosticSink) {
7099
+ this.producer = producer;
7100
+ this.diagnosticSink = diagnosticSink;
7101
+ }
7102
+ async captureNext(registrations, capture) {
7103
+ let failed = false;
7104
+ let captured = false;
7105
+ const onFailure = () => {
6752
7106
  failed = true;
7107
+ };
7108
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
7109
+ const index = (this.nextIndex + attempt) % registrations.length;
7110
+ const registration = registrations[index];
7111
+ if (registration === void 0) continue;
7112
+ try {
7113
+ captured = await capture(registration, onFailure);
7114
+ if (captured) {
7115
+ this.nextIndex = (index + 1) % registrations.length;
7116
+ break;
7117
+ }
7118
+ } catch (error) {
7119
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
7120
+ onFailure();
7121
+ }
6753
7122
  }
7123
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
7124
+ return captured;
6754
7125
  }
6755
- return { captured: false, nextIndex: startIndex, failed };
6756
- }
7126
+ };
6757
7127
  async function openHostUsageTranscriptCursor(input) {
6758
7128
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants6.O_RDONLY));
6759
7129
  let source;
@@ -6792,9 +7162,9 @@ async function resumeOversizedLine(handle, offset, size) {
6792
7162
  const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
6793
7163
  if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
6794
7164
  const chunk = bytes.subarray(0, bytesRead);
6795
- const delimiter = chunk.indexOf(10);
6796
- if (delimiter < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
6797
- return completeChunk(chunk.subarray(delimiter + 1), offset + delimiter + 1);
7165
+ const delimiter2 = chunk.indexOf(10);
7166
+ if (delimiter2 < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
7167
+ return completeChunk(chunk.subarray(delimiter2 + 1), offset + delimiter2 + 1);
6798
7168
  }
6799
7169
  function completeChunk(chunk, offset) {
6800
7170
  const parsed = completeLinePrefix(chunk, offset);
@@ -6868,7 +7238,7 @@ var ClaudeHostError = class extends Error {
6868
7238
  };
6869
7239
 
6870
7240
  // host/claude/src/claude-invocation-context.ts
6871
- import { isAbsolute as isAbsolute2 } from "node:path";
7241
+ import { isAbsolute as isAbsolute3 } from "node:path";
6872
7242
  function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
6873
7243
  return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
6874
7244
  }
@@ -6897,7 +7267,7 @@ function optionalSafeRef(value) {
6897
7267
  return value === void 0 || safeRef2(value);
6898
7268
  }
6899
7269
  function optionalDirectory(value) {
6900
- return value === void 0 || typeof value === "string" && isAbsolute2(value) && !value.includes("\0") && value.length <= 4096;
7270
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && !value.includes("\0") && value.length <= 4096;
6901
7271
  }
6902
7272
  function safeRef2(value) {
6903
7273
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
@@ -6922,14 +7292,14 @@ var ClaudeOutboxStore = class {
6922
7292
  activeContexts;
6923
7293
  turnSelections;
6924
7294
  constructor(directory) {
6925
- if (!isAbsolute3(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
7295
+ if (!isAbsolute4(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
6926
7296
  this.directory = directory;
6927
- this.envelopes = join4(directory, "envelopes");
6928
- this.sessions = join4(directory, "sessions");
6929
- this.registrations = join4(directory, "transcript-registrations");
6930
- this.cursors = join4(directory, "transcript-cursors");
6931
- this.activeContexts = join4(directory, "active-contexts");
6932
- this.turnSelections = join4(directory, "turn-selections");
7297
+ this.envelopes = join5(directory, "envelopes");
7298
+ this.sessions = join5(directory, "sessions");
7299
+ this.registrations = join5(directory, "transcript-registrations");
7300
+ this.cursors = join5(directory, "transcript-cursors");
7301
+ this.activeContexts = join5(directory, "active-contexts");
7302
+ this.turnSelections = join5(directory, "turn-selections");
6933
7303
  }
6934
7304
  async prepare() {
6935
7305
  for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
@@ -6957,6 +7327,7 @@ var ClaudeOutboxStore = class {
6957
7327
  const path = this.activeContextPath(identity);
6958
7328
  const active = await readProjectionFile(path);
6959
7329
  if (active === null || active.prompt_ref !== promptRef || active.identity.host_turn_ref !== identity.host_turn_ref) return false;
7330
+ await this.prepare();
6960
7331
  const updated = { ...active, turn_generation_ref: turnGenerationRef };
6961
7332
  validateClaudeHostInvocationContext(updated);
6962
7333
  await durableAtomicReplace(path, JSON.stringify(updated));
@@ -6969,17 +7340,15 @@ var ClaudeOutboxStore = class {
6969
7340
  */
6970
7341
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
6971
7342
  if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
6972
- await this.prepare();
6973
7343
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, readProjectionFile);
6974
7344
  return context;
6975
7345
  }
6976
7346
  async listInvocationContexts(now = /* @__PURE__ */ new Date()) {
6977
- await this.prepare();
6978
7347
  const contexts = [];
6979
- for (const name of await readdir(this.activeContexts)) {
7348
+ for (const name of await listHostOutboxDirectoryNames(this.activeContexts)) {
6980
7349
  if (!name.endsWith(".json")) continue;
6981
7350
  try {
6982
- const value = JSON.parse(await readFile(join4(this.activeContexts, name), "utf8"));
7351
+ const value = JSON.parse(await readFile(join5(this.activeContexts, name), "utf8"));
6983
7352
  validateClaudeHostInvocationContext(value);
6984
7353
  if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
6985
7354
  } catch {
@@ -6993,13 +7362,12 @@ var ClaudeOutboxStore = class {
6993
7362
  await durableAtomicReplace(this.envelopePath(entry.submission_ref), JSON.stringify(entry));
6994
7363
  }
6995
7364
  async listEnvelopes() {
6996
- await this.prepare();
6997
7365
  const entries = [];
6998
7366
  let malformed = 0;
6999
- for (const name of await readdir(this.envelopes)) {
7367
+ for (const name of await listHostOutboxDirectoryNames(this.envelopes)) {
7000
7368
  if (!name.endsWith(".json")) continue;
7001
7369
  try {
7002
- const value = JSON.parse(await readFile(join4(this.envelopes, name), "utf8"));
7370
+ const value = JSON.parse(await readFile(join5(this.envelopes, name), "utf8"));
7003
7371
  validateEnvelope(value);
7004
7372
  entries.push(value);
7005
7373
  } catch {
@@ -7020,13 +7388,12 @@ var ClaudeOutboxStore = class {
7020
7388
  async saveSession(snapshot) {
7021
7389
  validateSession(snapshot);
7022
7390
  await this.prepare();
7023
- await durableAtomicReplace(join4(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
7391
+ await durableAtomicReplace(join5(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
7024
7392
  }
7025
7393
  async readSession(sourceRef, sessionRef) {
7026
7394
  if (!SAFE_REF4.test(sourceRef) || !SAFE_REF4.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
7027
- await this.prepare();
7028
7395
  try {
7029
- const value = JSON.parse(await readFile(join4(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
7396
+ const value = JSON.parse(await readFile(join5(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
7030
7397
  validateSession(value);
7031
7398
  return value;
7032
7399
  } catch (error) {
@@ -7055,13 +7422,18 @@ var ClaudeOutboxStore = class {
7055
7422
  await this.removeStateFile(this.registrationPath(registration.host_source_ref, registration.host_session_ref));
7056
7423
  await this.removeStateFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref));
7057
7424
  }
7425
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
7426
+ if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
7427
+ const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
7428
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw new ClaudeHostError("storage", "Claude transcript registration identity does not match its session.");
7429
+ return registration;
7430
+ }
7058
7431
  async listTranscriptRegistrations() {
7059
- await this.prepare();
7060
7432
  const registrations = [];
7061
- for (const name of await readdir(this.registrations)) {
7433
+ for (const name of await listHostOutboxDirectoryNames(this.registrations)) {
7062
7434
  if (!name.endsWith(".json")) continue;
7063
7435
  try {
7064
- const value = JSON.parse(await readFile(join4(this.registrations, name), "utf8"));
7436
+ const value = JSON.parse(await readFile(join5(this.registrations, name), "utf8"));
7065
7437
  validateRegistration(value);
7066
7438
  registrations.push(value);
7067
7439
  } catch {
@@ -7071,7 +7443,6 @@ var ClaudeOutboxStore = class {
7071
7443
  }
7072
7444
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
7073
7445
  if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host turn selection identity is invalid.");
7074
- await this.prepare();
7075
7446
  try {
7076
7447
  const value = JSON.parse(await readFile(this.turnSelectionPath(hostSourceRef, hostSessionRef), "utf8"));
7077
7448
  if (!isHostInvocationTurnSelection(value) || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new ClaudeHostError("storage", "Claude Host turn selection is malformed.");
@@ -7083,7 +7454,6 @@ var ClaudeOutboxStore = class {
7083
7454
  }
7084
7455
  async readTranscriptCursor(registration) {
7085
7456
  validateRegistration(registration);
7086
- await this.prepare();
7087
7457
  try {
7088
7458
  const value = JSON.parse(await readFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "utf8"));
7089
7459
  validateCursor(value);
@@ -7099,16 +7469,16 @@ var ClaudeOutboxStore = class {
7099
7469
  await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
7100
7470
  }
7101
7471
  envelopePath(ref) {
7102
- return join4(this.envelopes, `${cealRequestSha256(ref)}.json`);
7472
+ return join5(this.envelopes, `${cealRequestSha256(ref)}.json`);
7103
7473
  }
7104
7474
  registrationPath(sourceRef, sessionRef) {
7105
- return join4(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
7475
+ return join5(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
7106
7476
  }
7107
7477
  turnSelectionPath(sourceRef, sessionRef) {
7108
- return join4(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
7478
+ return join5(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
7109
7479
  }
7110
7480
  cursorPath(sourceRef, sessionRef) {
7111
- return join4(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
7481
+ return join5(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
7112
7482
  }
7113
7483
  async readRegistrationFile(path) {
7114
7484
  try {
@@ -7128,7 +7498,7 @@ var ClaudeOutboxStore = class {
7128
7498
  }
7129
7499
  }
7130
7500
  activeContextPath(identity) {
7131
- return join4(this.activeContexts, `${invocationContextKey(identity)}.json`);
7501
+ return join5(this.activeContexts, `${invocationContextKey(identity)}.json`);
7132
7502
  }
7133
7503
  };
7134
7504
  function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
@@ -7204,7 +7574,7 @@ function validateRegistration(value) {
7204
7574
  if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
7205
7575
  }
7206
7576
  function validateRegistrationPaths(cwd, transcriptPath) {
7207
- if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute3(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
7577
+ if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute4(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
7208
7578
  throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
7209
7579
  }
7210
7580
  if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
@@ -7324,7 +7694,8 @@ var ClaudeProducer = class {
7324
7694
 
7325
7695
  // host/claude/src/claude-transcript-watcher.ts
7326
7696
  import { readdir as readdir2 } from "node:fs/promises";
7327
- import { join as join5 } from "node:path";
7697
+ import { isDeepStrictEqual } from "node:util";
7698
+ import { join as join6 } from "node:path";
7328
7699
 
7329
7700
  // host/claude/src/claude-decoder.ts
7330
7701
  import { createHash as createHash8 } from "node:crypto";
@@ -7409,10 +7780,39 @@ function record4(value) {
7409
7780
  return value !== null && typeof value === "object" && !Array.isArray(value);
7410
7781
  }
7411
7782
 
7783
+ // host/claude/src/claude-subagent-overflow-checkpoint.ts
7784
+ var ClaudeSubagentOverflowCheckpoint = class {
7785
+ observed = /* @__PURE__ */ new Map();
7786
+ prune(registrations) {
7787
+ const current = new Set(registrations.map(registrationKey));
7788
+ for (const key of this.observed.keys()) if (!current.has(key)) this.observed.delete(key);
7789
+ }
7790
+ clear(registration) {
7791
+ this.observed.delete(registrationKey(registration));
7792
+ }
7793
+ /** Names follow the producer's sorted inventory; only omitted names define overflow. */
7794
+ async observe(registration, names, report) {
7795
+ const key = registrationKey(registration);
7796
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
7797
+ this.clear(registration);
7798
+ return false;
7799
+ }
7800
+ const digest2 = transcriptObjectSha256(names.slice(CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES));
7801
+ if (this.observed.get(key) === digest2) return false;
7802
+ if (!await report()) return false;
7803
+ this.observed.set(key, digest2);
7804
+ return true;
7805
+ }
7806
+ };
7807
+ function registrationKey(registration) {
7808
+ return JSON.stringify([registration.host_source_ref, registration.host_session_ref, registration.transcript_path]);
7809
+ }
7810
+
7412
7811
  // host/claude/src/claude-transcript-watcher.ts
7413
7812
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
7414
7813
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7415
7814
  store;
7815
+ overflow = new ClaudeSubagentOverflowCheckpoint();
7416
7816
  diagnostic;
7417
7817
  constructor(options) {
7418
7818
  super(options, {
@@ -7427,7 +7827,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7427
7827
  return registration.transcript_path;
7428
7828
  }
7429
7829
  async listRegistrations() {
7430
- return this.store.listTranscriptRegistrations();
7830
+ const registrations = await this.store.listTranscriptRegistrations();
7831
+ this.overflow.prune(registrations);
7832
+ return registrations;
7431
7833
  }
7432
7834
  async scanOpened(handle, registration) {
7433
7835
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
@@ -7439,7 +7841,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7439
7841
  }
7440
7842
  if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
7441
7843
  const draft = mutableCursor(cursor);
7442
- await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
7844
+ await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
7443
7845
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
7444
7846
  }
7445
7847
  async scanFailed(handle, registration, error) {
@@ -7476,7 +7878,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7476
7878
  updated_at: this.stamp()
7477
7879
  };
7478
7880
  }
7479
- async scanOpenedTranscript(registration, handle, draft, size, device, inode) {
7881
+ async scanOpenedTranscript(registration, handle, previous, draft, size, device, inode) {
7480
7882
  const main = await this.readChunk(handle, draft.offset, size);
7481
7883
  if (main !== "empty" && main !== "partial") {
7482
7884
  await this.consumeMainChunk(registration, main, draft);
@@ -7484,7 +7886,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7484
7886
  }
7485
7887
  draft.consumed += await this.consumeSubagents(registration, draft);
7486
7888
  await this.emitOpenTerminal(registration, draft);
7487
- await this.commitCursor(registration, handle, draft, device, inode);
7889
+ await this.commitCursor(registration, handle, previous, draft, device, inode);
7488
7890
  }
7489
7891
  async preflight(registration, handle, size, device, inode) {
7490
7892
  const existing = await this.store.readTranscriptCursor(registration);
@@ -7644,15 +8046,24 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7644
8046
  try {
7645
8047
  names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
7646
8048
  } catch (error) {
7647
- if (isMissingTranscriptError(error) || isNotDirectory(error)) return 0;
8049
+ if (isMissingTranscriptError(error) || isNotDirectory(error)) {
8050
+ this.overflow.clear(registration);
8051
+ return 0;
8052
+ }
7648
8053
  throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
7649
8054
  }
7650
8055
  const listed = new Set(names);
7651
8056
  for (const name of Object.keys(draft.subagents)) if (!listed.has(name)) delete draft.subagents[name];
7652
- if (names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
7653
- this.log(`Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`);
7654
- names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
7655
- }
8057
+ await this.overflow.observe(registration, names, () => {
8058
+ const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
8059
+ try {
8060
+ this.log(line);
8061
+ } catch {
8062
+ return false;
8063
+ }
8064
+ return true;
8065
+ });
8066
+ names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
7656
8067
  let consumed = 0;
7657
8068
  for (const name of names) {
7658
8069
  consumed += await this.consumeSubagentFile(draft, directory, name);
@@ -7660,7 +8071,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7660
8071
  return consumed;
7661
8072
  }
7662
8073
  async consumeSubagentFile(draft, directory, name) {
7663
- const path = join5(directory, name);
8074
+ const path = join6(directory, name);
7664
8075
  let handle;
7665
8076
  try {
7666
8077
  handle = await openNoFollow(path);
@@ -7741,9 +8152,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7741
8152
  expires_at: this.expire(this.outboxRetentionMs)
7742
8153
  });
7743
8154
  }
7744
- async commitCursor(registration, handle, draft, device, inode) {
8155
+ async commitCursor(registration, handle, previous, draft, device, inode) {
7745
8156
  const anchor = await this.readAnchor(handle, draft.offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
7746
- await this.store.writeTranscriptCursor({
8157
+ const cursor = {
7747
8158
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
7748
8159
  host_source_ref: registration.host_source_ref,
7749
8160
  host_session_ref: registration.host_session_ref,
@@ -7760,7 +8171,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7760
8171
  ...draft.session_observed ? { session_observed: true } : {},
7761
8172
  status: "active",
7762
8173
  updated_at: this.stamp()
7763
- });
8174
+ };
8175
+ if (sameCursorContent(cursor, previous)) return;
8176
+ await this.store.writeTranscriptCursor(cursor);
7764
8177
  }
7765
8178
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
7766
8179
  try {
@@ -7811,6 +8224,9 @@ function mutableCursor(cursor) {
7811
8224
  enqueued: 0
7812
8225
  };
7813
8226
  }
8227
+ function sameCursorContent(left, right) {
8228
+ return isDeepStrictEqual({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
8229
+ }
7814
8230
  function zeroCounts() {
7815
8231
  return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
7816
8232
  }
@@ -7904,7 +8320,7 @@ function isAssistantUsageLine(record7) {
7904
8320
  }
7905
8321
  function subagentsDirectory(transcriptPath) {
7906
8322
  const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
7907
- return join5(stem, "subagents");
8323
+ return join6(stem, "subagents");
7908
8324
  }
7909
8325
  function observationRef(hostSourceRef, event, identity, value) {
7910
8326
  return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
@@ -7941,11 +8357,14 @@ function isSymlinkTranscript(error) {
7941
8357
  }
7942
8358
 
7943
8359
  // host/claude/src/claude-producer-runtime.ts
7944
- async function drainClaudeProducerOnce(options) {
7945
- const scan = await new ClaudeTranscriptWatcher({
7946
- outbox_dir: options.outbox_dir,
8360
+ function createClaudeProducerWatcher(outboxDir) {
8361
+ return new ClaudeTranscriptWatcher({
8362
+ outbox_dir: outboxDir,
7947
8363
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
7948
- }).scanOnce().catch((error) => {
8364
+ });
8365
+ }
8366
+ async function drainClaudeProducerOnce(options) {
8367
+ const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
7949
8368
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
7950
8369
  throw error;
7951
8370
  });
@@ -7957,30 +8376,25 @@ async function drainClaudeProducerOnce(options) {
7957
8376
  import { createHash as createHash9 } from "node:crypto";
7958
8377
  import { constants as constants7 } from "node:fs";
7959
8378
  import { readdir as readdir3 } from "node:fs/promises";
7960
- import { join as join6 } from "node:path";
8379
+ import { join as join7 } from "node:path";
7961
8380
  var ClaudeUsageFactsCapturer = class {
7962
8381
  sources;
7963
8382
  usage;
7964
8383
  now;
7965
- diagnosticSink;
7966
- nextRegistrationIndex = 0;
8384
+ registrations;
7967
8385
  nextSourceSlot = "main";
7968
8386
  nextSubagentIndex = 0;
8387
+ overflow = new ClaudeSubagentOverflowCheckpoint();
7969
8388
  constructor(options) {
7970
8389
  this.sources = new ClaudeOutboxStore(options.outbox_dir);
7971
8390
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
7972
8391
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
7973
- this.diagnosticSink = options.diagnostic_sink;
8392
+ this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
7974
8393
  }
7975
8394
  async captureNext() {
7976
8395
  const registrations = await this.sources.listTranscriptRegistrations();
7977
- let failed = false;
7978
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
7979
- failed = true;
7980
- }));
7981
- this.nextRegistrationIndex = result.nextIndex;
7982
- if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
7983
- return result.captured;
8396
+ this.overflow.prune(registrations);
8397
+ return await this.registrations.captureNext(registrations, (registration, onFailure) => this.captureRegistration(registration, onFailure));
7984
8398
  }
7985
8399
  async captureRegistration(registration, onFailure) {
7986
8400
  const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
@@ -8027,13 +8441,14 @@ var ClaudeUsageFactsCapturer = class {
8027
8441
  }
8028
8442
  async captureSubagent(registration, onFailure) {
8029
8443
  const names = await readSubagentNames(registration);
8444
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
8030
8445
  let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
8031
8446
  if (state === null) return false;
8032
8447
  state = await this.usage.recoverPending(state);
8033
8448
  if (state.quarantined_reason !== void 0) return false;
8034
8449
  if (await this.retireMissingSubagent(state, names)) return true;
8035
8450
  if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
8036
- return await this.recordExcessSubagentGap(state, names);
8451
+ return await this.recordExcessSubagentGap(registration, state, names);
8037
8452
  }
8038
8453
  async retireMissingSubagent(state, names) {
8039
8454
  const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
@@ -8044,14 +8459,14 @@ var ClaudeUsageFactsCapturer = class {
8044
8459
  }
8045
8460
  return false;
8046
8461
  }
8047
- async recordExcessSubagentGap(state, names) {
8048
- const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
8049
- if (excessCount <= 0) return false;
8462
+ async recordExcessSubagentGap(registration, state, names) {
8050
8463
  const mainCursor = state.cursors.main;
8051
8464
  if (mainCursor === void 0) return false;
8052
- const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
8053
- await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
8054
- return true;
8465
+ return await this.overflow.observe(registration, names, async () => {
8466
+ const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES };
8467
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
8468
+ return true;
8469
+ });
8055
8470
  }
8056
8471
  async captureListedSubagents(registration, names, state, onFailure) {
8057
8472
  const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
@@ -8074,7 +8489,7 @@ var ClaudeUsageFactsCapturer = class {
8074
8489
  async captureSubagentFile(registration, name, state) {
8075
8490
  let handle;
8076
8491
  try {
8077
- const opened = await readHostUsageTranscriptSource(() => openNoFollow(join6(subagentsDirectory(registration.transcript_path), name), constants7.O_RDONLY));
8492
+ const opened = await readHostUsageTranscriptSource(() => openNoFollow(join7(subagentsDirectory(registration.transcript_path), name), constants7.O_RDONLY));
8078
8493
  handle = opened;
8079
8494
  const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
8080
8495
  const sourceRef = sourceFileRef(registration, file.device, file.inode);
@@ -8332,7 +8747,7 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
8332
8747
  producer_id: "claude",
8333
8748
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
8334
8749
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
8335
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
8750
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createClaudeProducerWatcher(config.outbox_dir) }),
8336
8751
  drain: drainClaudeProducerOnce,
8337
8752
  background: (config, signal, dependencies) => {
8338
8753
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
@@ -8341,8 +8756,8 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
8341
8756
  };
8342
8757
 
8343
8758
  // host/codex/src/codex-outbox.ts
8344
- import { mkdir as mkdir6, open as open4, readdir as readdir4, rename as rename2, stat as stat2, unlink as unlink5 } from "node:fs/promises";
8345
- import { dirname as dirname7, isAbsolute as isAbsolute4, join as join7 } from "node:path";
8759
+ import { mkdir as mkdir6, open as open4, rename as rename2, stat as stat2, unlink as unlink5 } from "node:fs/promises";
8760
+ import { dirname as dirname7, isAbsolute as isAbsolute5, join as join8 } from "node:path";
8346
8761
 
8347
8762
  // host/codex/src/codex-types.ts
8348
8763
  var CODEX_CLI_VERSION = "0.152.0";
@@ -8351,6 +8766,23 @@ var CODEX_HOOKS_CONFIG_FILE = "hooks.json";
8351
8766
  var CODEX_HOOK_OWNER = "ceal-codex-host-observation-v1";
8352
8767
  var CODEX_THREAD_ID_ENVIRONMENT = "CODEX_THREAD_ID";
8353
8768
  var CODEX_SESSION_ID_ENVIRONMENT = "CODEX_SESSION_ID";
8769
+ var CODEX_TOOL_CALL_CORRELATION_MIN_VERSION = "0.163.0";
8770
+ var CODEX_VERSION_HINT_UPGRADE_FOR_TOOL_CALL_CORRELATION = "codex_upgrade_recommended_for_tool_call_correlation";
8771
+ function codexVersionHint(version) {
8772
+ const observed = parseCodexVersion(version);
8773
+ const minimum = parseCodexVersion(CODEX_TOOL_CALL_CORRELATION_MIN_VERSION);
8774
+ if (observed === null || minimum === null) return void 0;
8775
+ return compareCodexVersions(observed, minimum) < 0 ? CODEX_VERSION_HINT_UPGRADE_FOR_TOOL_CALL_CORRELATION : void 0;
8776
+ }
8777
+ function compareCodexVersions(left, right) {
8778
+ return left[0] - right[0] || left[1] - right[1] || left[2] - right[2];
8779
+ }
8780
+ function parseCodexVersion(version) {
8781
+ if (version === void 0) return null;
8782
+ const match = /^(\d{1,5})\.(\d{1,5})\.(\d{1,5})(?:[-+].*)?$/u.exec(version.trim());
8783
+ if (match?.[1] === void 0 || match[2] === void 0 || match[3] === void 0) return null;
8784
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
8785
+ }
8354
8786
  var CODEX_OUTBOX_SCHEMA_VERSION = "ceal.codex_observation_outbox.v1";
8355
8787
  var CODEX_SESSION_SCHEMA_VERSION = "ceal.codex_session.v1";
8356
8788
  var CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION = "ceal.codex_invocation_context.v1";
@@ -8421,12 +8853,12 @@ var CodexOutboxStore = class {
8421
8853
  constructor(directory) {
8422
8854
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
8423
8855
  this.directory = directory;
8424
- this.entriesDirectory = join7(directory, "entries");
8425
- this.sessionsDirectory = join7(directory, "sessions");
8426
- this.activeContextsDirectory = join7(directory, "active-contexts");
8427
- this.turnSelectionsDirectory = join7(directory, "turn-selections");
8428
- this.registrationsDirectory = join7(directory, "transcript-registrations");
8429
- this.cursorsDirectory = join7(directory, "transcript-cursors");
8856
+ this.entriesDirectory = join8(directory, "entries");
8857
+ this.sessionsDirectory = join8(directory, "sessions");
8858
+ this.activeContextsDirectory = join8(directory, "active-contexts");
8859
+ this.turnSelectionsDirectory = join8(directory, "turn-selections");
8860
+ this.registrationsDirectory = join8(directory, "transcript-registrations");
8861
+ this.cursorsDirectory = join8(directory, "transcript-cursors");
8430
8862
  }
8431
8863
  async prepare() {
8432
8864
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -8439,13 +8871,12 @@ var CodexOutboxStore = class {
8439
8871
  await writeAtomicJson(this.entryPath(entry.submission_ref), entry);
8440
8872
  }
8441
8873
  async list() {
8442
- await this.prepare();
8443
8874
  const entries = [];
8444
8875
  let malformed = 0;
8445
- for (const name of await readdir4(this.entriesDirectory)) {
8876
+ for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
8446
8877
  if (!name.endsWith(".json")) continue;
8447
8878
  try {
8448
- const value = JSON.parse(await readOwnerStateFile(join7(this.entriesDirectory, name)));
8879
+ const value = JSON.parse(await readOwnerStateFile(join8(this.entriesDirectory, name)));
8449
8880
  validateEnvelope2(value);
8450
8881
  entries.push(value);
8451
8882
  } catch {
@@ -8490,7 +8921,6 @@ var CodexOutboxStore = class {
8490
8921
  }
8491
8922
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
8492
8923
  if (!SAFE_REF5.test(hostSourceRef) || !SAFE_REF5.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
8493
- await this.prepare();
8494
8924
  return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
8495
8925
  }
8496
8926
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
@@ -8499,6 +8929,7 @@ var CodexOutboxStore = class {
8499
8929
  const path = this.activeContextPath(identity);
8500
8930
  const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
8501
8931
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
8932
+ await this.prepare();
8502
8933
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
8503
8934
  return true;
8504
8935
  }
@@ -8515,7 +8946,6 @@ var CodexOutboxStore = class {
8515
8946
  */
8516
8947
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
8517
8948
  if (!SAFE_REF5.test(hostSourceRef) || !SAFE_REF5.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
8518
- await this.prepare();
8519
8949
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
8520
8950
  return context;
8521
8951
  }
@@ -8539,7 +8969,6 @@ var CodexOutboxStore = class {
8539
8969
  async readSession(sourceRef, sessionRef) {
8540
8970
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
8541
8971
  if (!SAFE_REF5.test(sourceRef) || !SAFE_REF5.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
8542
- await this.prepare();
8543
8972
  return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession2);
8544
8973
  }
8545
8974
  async registerTranscript(registration) {
@@ -8565,13 +8994,18 @@ var CodexOutboxStore = class {
8565
8994
  await removeOwnerState(this.registrationPath(registration.host_source_ref, registration.host_session_ref), "registration");
8566
8995
  await removeOwnerState(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "cursor");
8567
8996
  }
8997
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
8998
+ const path = this.registrationPath(hostSourceRef, hostSessionRef);
8999
+ const registration = await readOptionalJson2(path, validateRegistration2);
9000
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
9001
+ return registration;
9002
+ }
8568
9003
  async listTranscriptRegistrations() {
8569
- await this.prepare();
8570
9004
  const registrations = [];
8571
- for (const name of await readdir4(this.registrationsDirectory)) {
9005
+ for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
8572
9006
  if (!name.endsWith(".json")) continue;
8573
9007
  try {
8574
- const value = JSON.parse(await readOwnerStateFile(join7(this.registrationsDirectory, name)));
9008
+ const value = JSON.parse(await readOwnerStateFile(join8(this.registrationsDirectory, name)));
8575
9009
  validateRegistration2(value);
8576
9010
  registrations.push(value);
8577
9011
  } catch {
@@ -8581,7 +9015,6 @@ var CodexOutboxStore = class {
8581
9015
  }
8582
9016
  async readTranscriptCursor(registration) {
8583
9017
  validateRegistration2(registration);
8584
- await this.prepare();
8585
9018
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor2);
8586
9019
  }
8587
9020
  async writeTranscriptCursor(cursor) {
@@ -8591,36 +9024,35 @@ var CodexOutboxStore = class {
8591
9024
  }
8592
9025
  async findByAlias(sourceRef, sessionRef, alias) {
8593
9026
  if (!SAFE_REF5.test(sourceRef) || !SAFE_REF5.test(sessionRef) || !SAFE_REF5.test(alias)) return null;
8594
- const read = await this.list();
8595
- const envelope = findEnvelopeByAlias(read.entries, sourceRef, sessionRef, alias);
9027
+ const read2 = await this.list();
9028
+ const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
8596
9029
  if (envelope !== null) return envelopeMatch(envelope);
8597
- await this.prepare();
8598
9030
  return null;
8599
9031
  }
8600
9032
  async hasPriorTurn(sourceRef, sessionRef) {
8601
9033
  if (!SAFE_REF5.test(sourceRef) || !SAFE_REF5.test(sessionRef)) return false;
8602
- const read = await this.list();
8603
- if (read.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
9034
+ const read2 = await this.list();
9035
+ if (read2.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
8604
9036
  return false;
8605
9037
  }
8606
9038
  entryPath(submissionRef2) {
8607
9039
  if (!SAFE_REF5.test(submissionRef2)) throw storageError("Codex submission identity is malformed.");
8608
- return join7(this.entriesDirectory, `${cealRequestSha256(submissionRef2)}.json`);
9040
+ return join8(this.entriesDirectory, `${cealRequestSha256(submissionRef2)}.json`);
8609
9041
  }
8610
9042
  sessionPath(sourceRef, sessionRef) {
8611
- return join7(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
9043
+ return join8(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
8612
9044
  }
8613
9045
  activeContextPath(identity) {
8614
- return join7(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
9046
+ return join8(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
8615
9047
  }
8616
9048
  turnSelectionPath(sourceRef, sessionRef) {
8617
- return join7(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
9049
+ return join8(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
8618
9050
  }
8619
9051
  registrationPath(sourceRef, sessionRef) {
8620
- return join7(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
9052
+ return join8(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
8621
9053
  }
8622
9054
  cursorPath(sourceRef, sessionRef) {
8623
- return join7(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
9055
+ return join8(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
8624
9056
  }
8625
9057
  };
8626
9058
  async function removeOwnerState(path, what) {
@@ -8656,7 +9088,7 @@ async function writeAtomicJson(path, value) {
8656
9088
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
8657
9089
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
8658
9090
  try {
8659
- const handle = await open4(temp, "wx");
9091
+ const handle = await open4(temp, "wx", 384);
8660
9092
  try {
8661
9093
  await handle.writeFile(text, "utf8");
8662
9094
  await handle.sync();
@@ -8698,13 +9130,20 @@ async function readOptionalJson2(path, validate) {
8698
9130
  }
8699
9131
  async function ensureOwnerDirectory(path) {
8700
9132
  try {
8701
- await stat2(path);
9133
+ try {
9134
+ const stats2 = await stat2(path);
9135
+ if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
9136
+ return;
9137
+ } catch (error) {
9138
+ if (!isNotFound2(error)) throw error;
9139
+ }
9140
+ await mkdir6(path, { recursive: true, mode: 448 });
9141
+ const stats = await stat2(path);
9142
+ if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8702
9143
  } catch (error) {
8703
- if (!isNotFound2(error)) throw storageError("Codex owner state directory is unavailable.");
8704
- await mkdir6(path, { recursive: true });
9144
+ if (error instanceof CodexHostAdapterError) throw error;
9145
+ throw storageError("Codex owner state directory is unavailable.");
8705
9146
  }
8706
- const stats = await stat2(path);
8707
- if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8708
9147
  }
8709
9148
  async function readOwnerStateFile(path) {
8710
9149
  let handle;
@@ -8747,7 +9186,7 @@ function validateRegistrationFields(value) {
8747
9186
  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 }])}).`);
8748
9187
  }
8749
9188
  function validRegistrationCwd(value) {
8750
- return value === void 0 || typeof value === "string" && isAbsolute4(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
9189
+ return value === void 0 || typeof value === "string" && isAbsolute5(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
8751
9190
  }
8752
9191
  function validateCursor2(value) {
8753
9192
  if (!isRecord7(value)) throw storageError("Codex transcript cursor is malformed.");
@@ -9139,11 +9578,11 @@ function timestamp5(now) {
9139
9578
  }
9140
9579
 
9141
9580
  // host/codex/src/codex-runtime-paths.ts
9142
- import { join as join8 } from "node:path";
9581
+ import { join as join9 } from "node:path";
9143
9582
  var CODEX_HOME_ENVIRONMENT = "CODEX_HOME";
9144
9583
  var CODEX_HOME_DEFAULT_DIRECTORY = ".codex";
9145
9584
  function resolveCodexHome(environment, home) {
9146
- return environment[CODEX_HOME_ENVIRONMENT] || join8(home, CODEX_HOME_DEFAULT_DIRECTORY);
9585
+ return environment[CODEX_HOME_ENVIRONMENT] || join9(home, CODEX_HOME_DEFAULT_DIRECTORY);
9147
9586
  }
9148
9587
 
9149
9588
  // host/codex/src/codex-adapter.ts
@@ -9518,20 +9957,16 @@ var CodexUsageFactsCapturer = class {
9518
9957
  sources;
9519
9958
  usage;
9520
9959
  now;
9521
- diagnosticSink;
9522
- nextRegistrationIndex = 0;
9960
+ registrations;
9523
9961
  constructor(options) {
9524
9962
  this.sources = new CodexOutboxStore(options.outbox_dir);
9525
9963
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
9526
9964
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
9527
- this.diagnosticSink = options.diagnostic_sink;
9965
+ this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
9528
9966
  }
9529
9967
  async captureNext() {
9530
9968
  const registrations = await this.sources.listTranscriptRegistrations();
9531
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
9532
- this.nextRegistrationIndex = result.nextIndex;
9533
- if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
9534
- return result.captured;
9969
+ return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
9535
9970
  }
9536
9971
  async captureRegistration(registration) {
9537
9972
  const prepared = await openHostUsageTranscriptCursor({
@@ -9760,7 +10195,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
9760
10195
 
9761
10196
  // host/relay/src/host-relay-runtime.ts
9762
10197
  import { constants as constants8 } from "node:fs";
9763
- import { dirname as dirname8, join as join9 } from "node:path";
10198
+ import { dirname as dirname8, join as join10 } from "node:path";
9764
10199
 
9765
10200
  // host/json-duplicate-guard.ts
9766
10201
  function rejectDuplicateJsonKeys(text, errors) {
@@ -10317,7 +10752,7 @@ function boundedDiagnosticLines(lines) {
10317
10752
  let totalBytes = 0;
10318
10753
  for (const line of lines.slice(0, HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_LINES)) {
10319
10754
  const safe = normalizeDiagnosticLine(line);
10320
- const value = truncateUtf8(safe, HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_LINE_BYTES);
10755
+ const value = truncateUtf82(safe, HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_LINE_BYTES);
10321
10756
  const bytes = Buffer2.byteLength(value, "utf8") + (bounded.length === 0 ? 0 : 1);
10322
10757
  if (totalBytes + bytes > HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_BYTES) break;
10323
10758
  bounded.push(value);
@@ -10327,16 +10762,13 @@ function boundedDiagnosticLines(lines) {
10327
10762
  }
10328
10763
  function normalizeDiagnosticLine(line) {
10329
10764
  let normalized = "";
10330
- for (const character of redactDiagnosticSecrets(line)) {
10765
+ for (const character of redactOperatorDiagnosticSecrets(line)) {
10331
10766
  const point = character.codePointAt(0) ?? 0;
10332
10767
  normalized += point <= 31 || point === 127 ? " " : character;
10333
10768
  }
10334
10769
  return normalized.replace(/\s+/gu, " ").trim();
10335
10770
  }
10336
- function redactDiagnosticSecrets(value) {
10337
- 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*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
10338
- }
10339
- function truncateUtf8(value, maxBytes) {
10771
+ function truncateUtf82(value, maxBytes) {
10340
10772
  if (Buffer2.byteLength(value, "utf8") <= maxBytes) return value;
10341
10773
  let output = "";
10342
10774
  let bytes = 0;
@@ -10362,7 +10794,7 @@ function rejectDuplicateJsonKeys2(text) {
10362
10794
 
10363
10795
  // host/lifecycle/src/host-runtime-hooks.ts
10364
10796
  import { lstat as lstat10 } from "node:fs/promises";
10365
- import { basename as basename3, dirname as dirname12, join as join16 } from "node:path";
10797
+ import { basename as basename3, dirname as dirname12, join as join18 } from "node:path";
10366
10798
 
10367
10799
  // host/hook-drift-policy.ts
10368
10800
  var REINSTALL_REPAIRS_PREFIX = ["owned_hook_drifted:"];
@@ -10375,7 +10807,7 @@ var OPERATOR_ONLY = /* @__PURE__ */ new Set([
10375
10807
  "settings_malformed",
10376
10808
  "local_capability_foreign"
10377
10809
  ]);
10378
- var OPERATOR_ONLY_PREFIX = ["duplicate_owned_hook:"];
10810
+ var OPERATOR_ONLY_PREFIX = ["duplicate_owned_hook:", "hook_trust_modified:"];
10379
10811
  function hookDriftRemedyFor(reason) {
10380
10812
  if (OPERATOR_ONLY.has(reason) || OPERATOR_ONLY_PREFIX.some((prefix) => reason.startsWith(prefix))) return "operator";
10381
10813
  if (REINSTALL_REPAIRS.has(reason) || REINSTALL_REPAIRS_PREFIX.some((prefix) => reason.startsWith(prefix))) return "reinstall";
@@ -10392,7 +10824,7 @@ import { constants as constants9 } from "node:fs";
10392
10824
  import { randomUUID } from "node:crypto";
10393
10825
  import { lstat as lstat6, mkdir as mkdir7, readlink, realpath, rename as rename3, stat as stat3, unlink as unlink6 } from "node:fs/promises";
10394
10826
  import { homedir } from "node:os";
10395
- import { basename, dirname as dirname9, isAbsolute as isAbsolute5, join as join10, normalize, parse } from "node:path";
10827
+ import { basename, dirname as dirname9, isAbsolute as isAbsolute6, join as join11, normalize as normalize2, parse as parse2 } from "node:path";
10396
10828
 
10397
10829
  // host/command-vector.ts
10398
10830
  import { win32 as win328 } from "node:path";
@@ -10412,19 +10844,42 @@ function validateHostCommandVector(vector, windowsConsumer = "cmd") {
10412
10844
  function formatHostCommand(vector, platform) {
10413
10845
  return formatWith(vector, platform === "windows" ? quoteWindowsArgument : quotePosixArgument);
10414
10846
  }
10847
+ function hostScriptLauncherInvocation(launcherPath2, args, kind, platform = process.platform, environment = process.env) {
10848
+ if (kind === "node") return { executable: process.execPath, args: [launcherPath2, ...args] };
10849
+ if (platform === "win32" && kind === "cmd") return windowsCmdLauncherInvocation(launcherPath2, args, environment);
10850
+ if (platform === "win32" && kind === "powershell") {
10851
+ return {
10852
+ executable: win328.join(environmentValue(environment, "SystemRoot", platform) ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
10853
+ args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", launcherPath2, ...args]
10854
+ };
10855
+ }
10856
+ return { executable: launcherPath2, args };
10857
+ }
10415
10858
  function formatWindowsPowerShellCmdScriptCommand(launcherPath2, args, environment = process.env) {
10416
10859
  validateWindowsCmdScriptVector(launcherPath2, args, "cmd");
10417
10860
  if (args.some((argument) => !WINDOWS_FIXED_CMD_ARGUMENT.test(argument))) throw new TypeError("Host script launcher argument is outside the Windows launcher alphabet.");
10418
10861
  const commandProcessor = windowsSystemCommandProcessor(environment);
10419
10862
  validateWindowsCmdScriptVector(commandProcessor, [], "cmd");
10420
10863
  const command = `${quoteWindowsArgument(launcherPath2)} ${args.map(quoteWindowsArgument).join(" ")}`.trimEnd();
10421
- const invocation = ["&", commandProcessor, "/d", "/v:off", "/s", "/c", `"${command}"`].map((value, index) => index === 0 ? value : quotePowerShellLiteral(value)).join(" ");
10864
+ const invocation = ["&", commandProcessor, "/d", "/v:off", "/s", "/c", command].map((value, index) => index === 0 ? value : quotePowerShellLiteral(value)).join(" ");
10422
10865
  return boundedHostCommand(`$LASTEXITCODE = 1; ${invocation}; exit $LASTEXITCODE`);
10423
10866
  }
10867
+ function windowsCmdLauncherInvocation(launcherPath2, args, environment) {
10868
+ validateWindowsCmdScriptVector(launcherPath2, args, "direct-exec");
10869
+ const variable = "CEAL_HOST_SCRIPT_LAUNCHER_PATH";
10870
+ const command = `"%${variable}%" ${args.map(quoteWindowsArgument).join(" ")}`.trimEnd();
10871
+ return { ...windowsCmdInvocation(environment, `"${command}"`), environment: { [variable]: launcherPath2 }, windowsVerbatimArguments: true };
10872
+ }
10424
10873
  function validateWindowsCmdScriptVector(launcherPath2, args, consumer) {
10425
10874
  if (invalidText(launcherPath2) || launcherPath2.includes('"')) throw new TypeError("Host script launcher path is invalid.");
10426
10875
  validateHostCommandVector({ executable: launcherPath2, args }, consumer);
10427
10876
  }
10877
+ function windowsCmdInvocation(environment, command) {
10878
+ return { executable: windowsAmbientCommandProcessor(environment), args: ["/d", "/v:off", "/s", "/c", command] };
10879
+ }
10880
+ function windowsAmbientCommandProcessor(environment) {
10881
+ return environmentValue(environment, "ComSpec", "win32") ?? "cmd.exe";
10882
+ }
10428
10883
  function windowsSystemCommandProcessor(environment) {
10429
10884
  const systemRoot = environmentValue(environment, "SystemRoot", "win32");
10430
10885
  if (systemRoot === void 0 || !/^[A-Za-z]:[\\/]/u.test(systemRoot) || systemRoot.split(/[\\/]/u).some((segment) => segment === "." || segment === "..")) throw new TypeError("Windows SystemRoot is unavailable or invalid.");
@@ -10477,33 +10932,38 @@ var HostEntryLinkError = class extends Error {
10477
10932
  }
10478
10933
  };
10479
10934
  function resolveHostEntryRoot(producerHome, producerDirectory) {
10480
- const home = producerHome ?? join10(homedir(), producerDirectory);
10481
- if (!isAbsolute5(home)) throw new TypeError("Host producer home must be absolute.");
10935
+ const home = producerHome ?? join11(homedir(), producerDirectory);
10936
+ if (!isAbsolute6(home)) throw new TypeError("Host producer home must be absolute.");
10482
10937
  const userRoot = basename(home) === producerDirectory ? dirname9(home) : home;
10483
- return join10(userRoot, ...HOST_ENTRY_DIRECTORY);
10938
+ return join11(userRoot, ...HOST_ENTRY_DIRECTORY);
10484
10939
  }
10485
10940
  function hostEntryCommand({ entryRoot, module: module2, configFlag, configFile, platform = process.platform }) {
10486
10941
  assertLauncherArgument(module2, "module");
10487
10942
  assertLauncherArgument(configFile, "configuration file");
10488
10943
  if (!/^--[A-Za-z0-9_-]+$/u.test(configFlag)) throw new TypeError("Host entry configuration flag must be a long option name.");
10489
10944
  return {
10490
- executable: join10(entryRoot, platform === "win32" ? HOST_ENTRY_WINDOWS_RUNTIME_LAUNCHER : HOST_ENTRY_RUNTIME_LAUNCHER),
10945
+ executable: join11(entryRoot, platform === "win32" ? HOST_ENTRY_WINDOWS_RUNTIME_LAUNCHER : HOST_ENTRY_RUNTIME_LAUNCHER),
10491
10946
  args: [module2, `${configFlag}=${configFile}`]
10492
10947
  };
10493
10948
  }
10494
10949
  async function installHostEntryLinks(entryRoot, targets, platform = process.platform, custody = {}, renameRetry = {}) {
10495
10950
  assertAbsolute(entryRoot, targets);
10496
- assertWindowsBatchTargetsAscii(targets, platform);
10951
+ assertWindowsEntryPaths(entryRoot, targets, platform);
10497
10952
  await assertEntryRootProven(entryRoot, platform, custody);
10498
10953
  await Promise.all([assertCanonicalDirectory(targets.runtime, "runtime"), assertCanonicalDirectory(targets.services, "services")]);
10499
- if (platform === "win32") await assertLegacyLinkOrAbsent(join10(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
10500
- await assertLegacyLinkOrAbsent(join10(entryRoot, HOST_ENTRY_LEGACY_SERVICES));
10954
+ if (platform === "win32") await assertLegacyLinkOrAbsent(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
10955
+ await assertLegacyLinkOrAbsent(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES));
10501
10956
  await preparePrivateEntryRoot(entryRoot);
10502
10957
  return reconcileEntryLaunchers(entryRoot, targets, platform, custody, renameRetry);
10503
10958
  }
10504
- function assertWindowsBatchTargetsAscii(targets, platform) {
10959
+ function assertWindowsEntryPaths(entryRoot, targets, platform) {
10505
10960
  if (platform !== "win32") return;
10506
10961
  if (hasNonAsciiCharacter(targets.runtime) || hasNonAsciiCharacter(targets.services)) throw new HostEntryLinkError("entry_target_invalid", "Windows Host launcher targets must use ASCII paths.", ["target_non_ascii"]);
10962
+ try {
10963
+ validateHostCommandVector({ executable: launcherPath(entryRoot, platform), args: [] });
10964
+ } catch {
10965
+ throw new HostEntryLinkError("entry_target_invalid", "Windows Host entry path cannot be serialized safely as a hook command.", ["entry_command_invalid"]);
10966
+ }
10507
10967
  }
10508
10968
  function hasNonAsciiCharacter(value) {
10509
10969
  for (const character of value) if (character.charCodeAt(0) > 127) return true;
@@ -10533,31 +10993,31 @@ async function reconcileEntryLaunchers(entryRoot, targets, platform, custody, re
10533
10993
  }
10534
10994
  async function removeLegacyEntryPaths(entryRoot, platform) {
10535
10995
  let removed = false;
10536
- if (platform === "win32") removed = await removeLegacyPath(join10(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
10537
- return await removeLegacyPath(join10(entryRoot, HOST_ENTRY_LEGACY_SERVICES)) || removed;
10996
+ if (platform === "win32") removed = await removeLegacyPath(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
10997
+ return await removeLegacyPath(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES)) || removed;
10538
10998
  }
10539
10999
  async function inspectHostEntryLinks(entryRoot, targets, platform = process.platform, custody = {}) {
10540
11000
  assertAbsolute(entryRoot, targets);
10541
11001
  await assertEntryRootProven(entryRoot, platform, custody);
10542
11002
  const installed = await readInstalledLauncher(launcherPath(entryRoot, platform), platform, custody);
10543
11003
  if (installed.status === "absent") return "missing";
10544
- if (await pathExists(join10(entryRoot, HOST_ENTRY_LEGACY_SERVICES)) || platform === "win32" && await pathExists(join10(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER))) return "drifted";
11004
+ if (await pathExists(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES)) || platform === "win32" && await pathExists(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER))) return "drifted";
10545
11005
  if (installed.status !== "ready") return "drifted";
10546
11006
  return installed.targets.runtime === targets.runtime && installed.targets.services === targets.services ? "ready" : "drifted";
10547
11007
  }
10548
11008
  async function removeHostEntryLinks(entryRoot, platform = process.platform, custody = {}) {
10549
- if (!isAbsolute5(entryRoot)) throw new TypeError("Host entry root must be absolute.");
11009
+ if (!isAbsolute6(entryRoot)) throw new TypeError("Host entry root must be absolute.");
10550
11010
  await assertEntryRootProven(entryRoot, platform, custody);
10551
- if (platform === "win32") await assertLegacyLinkOrAbsent(join10(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
10552
- await assertLegacyLinkOrAbsent(join10(entryRoot, HOST_ENTRY_LEGACY_SERVICES));
11011
+ if (platform === "win32") await assertLegacyLinkOrAbsent(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
11012
+ await assertLegacyLinkOrAbsent(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES));
10553
11013
  let changed = false;
10554
11014
  changed = await removeLauncherFile(launcherPath(entryRoot, platform), platform, custody) || changed;
10555
- if (platform === "win32") changed = await removeLegacyPath(join10(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER)) || changed;
10556
- changed = await removeLegacyPath(join10(entryRoot, HOST_ENTRY_LEGACY_SERVICES)) || changed;
11015
+ if (platform === "win32") changed = await removeLegacyPath(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER)) || changed;
11016
+ changed = await removeLegacyPath(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES)) || changed;
10557
11017
  return changed;
10558
11018
  }
10559
11019
  function launcherPath(entryRoot, platform) {
10560
- return join10(entryRoot, platform === "win32" ? HOST_ENTRY_WINDOWS_RUNTIME_LAUNCHER : HOST_ENTRY_RUNTIME_LAUNCHER);
11020
+ return join11(entryRoot, platform === "win32" ? HOST_ENTRY_WINDOWS_RUNTIME_LAUNCHER : HOST_ENTRY_RUNTIME_LAUNCHER);
10561
11021
  }
10562
11022
  async function readInstalledLauncher(path, platform, custody) {
10563
11023
  const handle = await openLauncherFile(path, platform, custody);
@@ -10806,7 +11266,7 @@ async function assertOwnedEntryRootDirectory(logical, physical, platform, custod
10806
11266
  if ((info.mode & 18) !== 0) throw new HostEntryLinkError("entry_root_unowned", `Host entry root ancestor ${logical} grants cross-user write access; remove the group/other write bits, then rerun.`);
10807
11267
  }
10808
11268
  function assertAbsolute(entryRoot, targets) {
10809
- if (![entryRoot, targets.runtime, targets.services].every((value) => typeof value === "string" && isAbsolute5(value) && !hasControlCharacters3(value))) throw new TypeError("Host entry root and launcher targets must be absolute paths without control characters.");
11269
+ if (![entryRoot, targets.runtime, targets.services].every((value) => typeof value === "string" && isAbsolute6(value) && !hasControlCharacters3(value))) throw new TypeError("Host entry root and launcher targets must be absolute paths without control characters.");
10810
11270
  }
10811
11271
  function hasControlCharacters3(value) {
10812
11272
  for (const character of value) {
@@ -10816,7 +11276,7 @@ function hasControlCharacters3(value) {
10816
11276
  return false;
10817
11277
  }
10818
11278
  async function assertCanonicalDirectory(target, role) {
10819
- if (!isAbsolute5(target) || normalize(target) !== target || parse(target).root === target) throw new HostEntryLinkError("entry_target_invalid", "Host launcher target must be a canonical absolute non-root path.", [`target_role:${role}`, "target_path_invalid"]);
11279
+ if (!isAbsolute6(target) || normalize2(target) !== target || parse2(target).root === target) throw new HostEntryLinkError("entry_target_invalid", "Host launcher target must be a canonical absolute non-root path.", [`target_role:${role}`, "target_path_invalid"]);
10820
11280
  try {
10821
11281
  if (await realpath(target) !== target) throw new HostEntryLinkError("entry_target_invalid", "Host launcher target must resolve to its canonical directory.", [`target_role:${role}`, "target_not_canonical"]);
10822
11282
  if (!(await stat3(target)).isDirectory()) throw new HostEntryLinkError("entry_target_invalid", "Host launcher target must resolve to its canonical directory.", [`target_role:${role}`, "target_not_directory"]);
@@ -10843,18 +11303,18 @@ import { constants as constants11 } from "node:fs";
10843
11303
  import { chmod, copyFile as copyFile2, lstat as lstat8, mkdir as mkdir8, open as open5, readFile as readFile2, rename as rename4, unlink as unlink7 } from "node:fs/promises";
10844
11304
  import { createHash as createHash13 } from "node:crypto";
10845
11305
  import { homedir as homedir2 } from "node:os";
10846
- import { dirname as dirname10, isAbsolute as isAbsolute7, join as join13 } from "node:path";
11306
+ import { dirname as dirname10, isAbsolute as isAbsolute8, join as join14 } from "node:path";
10847
11307
 
10848
11308
  // host/local-capability-descriptor.ts
10849
11309
  import { constants as constants10 } from "node:fs";
10850
- import { isAbsolute as isAbsolute6, join as join11 } from "node:path";
11310
+ import { isAbsolute as isAbsolute7, join as join12 } from "node:path";
10851
11311
  import { lstat as lstat7 } from "node:fs/promises";
10852
11312
  var HOST_LOCAL_CAPABILITY_AUTHENTICATION_SUFFIX = Object.freeze(["authenticate", "--client-nonce"]);
10853
11313
  var HOST_LOCAL_CAPABILITY_AUTHENTICATION_MODE = "nonce";
10854
11314
  var HOST_LOCAL_CAPABILITY_EXECUTION_MODE = "verbatim";
10855
11315
  function hostLocalCapabilityPath(userHome, producer) {
10856
- if (!isAbsolute6(userHome)) throw new TypeError("Host local capability user home must be absolute.");
10857
- return join11(userHome, ".ceal", "local-capabilities", `${producer}.json`);
11316
+ if (!isAbsolute7(userHome)) throw new TypeError("Host local capability user home must be absolute.");
11317
+ return join12(userHome, ".ceal", "local-capabilities", `${producer}.json`);
10858
11318
  }
10859
11319
  function hostLocalCapabilityDescriptor(input) {
10860
11320
  const argv = [input.authenticationCommand.executable, ...input.authenticationCommand.args];
@@ -11002,11 +11462,11 @@ function isRecord9(value) {
11002
11462
  }
11003
11463
 
11004
11464
  // host/claude/src/claude-runtime-paths.ts
11005
- import { join as join12 } from "node:path";
11465
+ import { join as join13 } from "node:path";
11006
11466
  var CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT = "CLAUDE_CONFIG_DIR";
11007
11467
  var CLAUDE_HOME_DEFAULT_DIRECTORY = ".claude";
11008
11468
  function resolveClaudeConfigHome(environment, home) {
11009
- return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join12(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
11469
+ return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join13(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
11010
11470
  }
11011
11471
 
11012
11472
  // host/claude/src/claude-installer.ts
@@ -11016,7 +11476,7 @@ var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: CLAUDE_SES
11016
11476
  var CLAUDE_CLIENT_ALLOW_RULE = `Bash(${CEAL_SESSION_ENTRY_INVOCATION}:*)`;
11017
11477
  var PERMISSION_OWNERSHIP_SCHEMA = "ceal.claude_permission_ownership.v1";
11018
11478
  function resolveClaudeSettingsPath(claudeHome, environment = process.env) {
11019
- return join13(claudeHome ?? resolveClaudeConfigHome(environment, homedir2()), "settings.json");
11479
+ return join14(claudeHome ?? resolveClaudeConfigHome(environment, homedir2()), "settings.json");
11020
11480
  }
11021
11481
  async function installClaudeHooks(options) {
11022
11482
  const normalized = validateOptions(options);
@@ -11024,15 +11484,14 @@ async function installClaudeHooks(options) {
11024
11484
  const executableSha256 = await inspectExecutable(command.executable);
11025
11485
  const current = await readSettingsForMutation(normalized.settings_path);
11026
11486
  let next = mergeOwnedHooks(current, command);
11027
- if (!allowEntries(next).includes(CLAUDE_CLIENT_ALLOW_RULE)) {
11028
- await writeAtomicJson2(normalized.permission_ownership_path, { schema_version: PERMISSION_OWNERSHIP_SCHEMA, settings_path: normalized.settings_path, allow: CLAUDE_CLIENT_ALLOW_RULE });
11029
- next = withAllowEntries(next, [...allowEntries(next), CLAUDE_CLIENT_ALLOW_RULE]);
11030
- }
11487
+ const addsAllow = !allowEntries(next).includes(CLAUDE_CLIENT_ALLOW_RULE);
11488
+ if (addsAllow) next = withAllowEntries(next, [...allowEntries(next), CLAUDE_CLIENT_ALLOW_RULE]);
11031
11489
  const changed = JSON.stringify(current) !== JSON.stringify(next);
11032
11490
  if (changed) {
11033
11491
  await backup(normalized.settings_path);
11034
11492
  await writeAtomicJson2(normalized.settings_path, next);
11035
11493
  }
11494
+ if (addsAllow) await writeAtomicJson2(normalized.permission_ownership_path, { schema_version: PERMISSION_OWNERSHIP_SCHEMA, settings_path: normalized.settings_path, allow: CLAUDE_CLIENT_ALLOW_RULE });
11036
11495
  return { settings_path: normalized.settings_path, changed, events: CLAUDE_HOOK_EVENTS, executable_sha256: executableSha256 };
11037
11496
  }
11038
11497
  async function uninstallClaudeHooks(options) {
@@ -11087,11 +11546,11 @@ function validateClaudeLocalCapabilityDescriptor(encoded) {
11087
11546
  return inspection.document;
11088
11547
  }
11089
11548
  async function installClaudeLocalCapability(path, authenticationCommand, custody = {}) {
11090
- if (!isAbsolute7(path)) throw new ClaudeHostError("configuration", "Claude local capability path must be absolute.");
11549
+ if (!isAbsolute8(path)) throw new ClaudeHostError("configuration", "Claude local capability path must be absolute.");
11091
11550
  try {
11092
11551
  validateHostCommandVector(authenticationCommand);
11093
11552
  } catch (error) {
11094
- throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11553
+ throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11095
11554
  }
11096
11555
  await inspectExecutable(authenticationCommand.executable);
11097
11556
  const next = claudeLocalCapabilityDescriptor(authenticationCommand);
@@ -11121,13 +11580,13 @@ async function inspectClaudeLocalCapability(path, authenticationCommand, custody
11121
11580
  return localCapabilityDescriptorMatches(current.encoded, claudeLocalCapabilityDescriptor(authenticationCommand)) ? [] : ["local_capability_drifted"];
11122
11581
  }
11123
11582
  async function removeClaudeLocalCapability(path, authenticationCommand, custody = {}) {
11124
- if (!isAbsolute7(path)) throw new ClaudeHostError("configuration", "Claude local capability path must be absolute.");
11583
+ if (!isAbsolute8(path)) throw new ClaudeHostError("configuration", "Claude local capability path must be absolute.");
11125
11584
  let descriptor2;
11126
11585
  try {
11127
11586
  validateHostCommandVector(authenticationCommand);
11128
11587
  descriptor2 = claudeLocalCapabilityDescriptor(authenticationCommand);
11129
11588
  } catch (error) {
11130
- throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11589
+ throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11131
11590
  }
11132
11591
  const result = await removeOwnedLocalCapability(path, descriptor2, custody);
11133
11592
  if (result === "unsafe" || result === "unavailable") throw new ClaudeHostError("storage", `Claude local capability descriptor ${result === "unsafe" ? "is unsafe" : "custody could not be proved"}.`);
@@ -11261,13 +11720,13 @@ function eventEntries(hooks, event) {
11261
11720
  }
11262
11721
  function validateOptions(options) {
11263
11722
  const settingsPath = options.settings_path ?? resolveClaudeSettingsPath(options.claude_home);
11264
- if (!isAbsolute7(settingsPath) || !isAbsolute7(options.permission_ownership_path) || !isAbsolute7(options.hook_executable) || options.hook_executable.includes("\0") || options.hook_executable.includes("\n") || options.hook_executable.includes('"')) throw new ClaudeHostError("configuration", "Claude installer paths must be absolute and shell-safe.");
11723
+ if (!isAbsolute8(settingsPath) || !isAbsolute8(options.permission_ownership_path) || !isAbsolute8(options.hook_executable) || options.hook_executable.includes("\0") || options.hook_executable.includes("\n") || options.hook_executable.includes('"')) throw new ClaudeHostError("configuration", "Claude installer paths must be absolute and shell-safe.");
11265
11724
  try {
11266
11725
  const command = resolveHookCommand(options);
11267
11726
  validateHostCommandVector(command);
11268
11727
  managedEntry(command, "SessionStart");
11269
11728
  } catch (error) {
11270
- throw new ClaudeHostError("configuration", `Claude hook command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11729
+ throw new ClaudeHostError("configuration", `Claude hook command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11271
11730
  }
11272
11731
  return { ...options, settings_path: settingsPath };
11273
11732
  }
@@ -11346,27 +11805,32 @@ var import_toml = __toESM(require_toml(), 1);
11346
11805
  import { createHash as createHash14 } from "node:crypto";
11347
11806
  import { copyFile as copyFile3, lstat as lstat9, mkdir as mkdir9, open as open6, readFile as readFile3, rename as rename5, unlink as unlink8 } from "node:fs/promises";
11348
11807
  import { homedir as homedir3 } from "node:os";
11349
- import { basename as basename2, dirname as dirname11, isAbsolute as isAbsolute8, join as join15 } from "node:path";
11808
+ import { basename as basename2, dirname as dirname11, isAbsolute as isAbsolute9, join as join17 } from "node:path";
11350
11809
  import { fileURLToPath as fileURLToPath2 } from "node:url";
11351
11810
 
11352
11811
  // host/codex/src/codex-sandbox-rule.ts
11353
- import { join as join14 } from "node:path";
11812
+ import { join as join15 } from "node:path";
11354
11813
  var CODEX_RULES_DIRECTORY = "rules";
11355
11814
  var CODEX_SANDBOX_RULE_FILE = "ceal-host.rules";
11356
11815
  var CODEX_SANDBOX_RULE_MARKER = `# ceal-owner: ${CODEX_HOOK_OWNER}`;
11357
11816
  var CODEX_SANDBOX_RULE_JUSTIFICATION = "Ceal client: needs its session store outside the workspace, network access to the Ceal Gateway, and the Ceal Host relay socket.";
11358
11817
  function codexSandboxRulePath(codexHome) {
11359
- return join14(codexHome, CODEX_RULES_DIRECTORY, CODEX_SANDBOX_RULE_FILE);
11818
+ return join15(codexHome, CODEX_RULES_DIRECTORY, CODEX_SANDBOX_RULE_FILE);
11819
+ }
11820
+ function codexClientExecutableSpellings(platform) {
11821
+ return platform === "win32" ? [CEAL_SESSION_ENTRY_INVOCATION, `${CEAL_SESSION_ENTRY_INVOCATION}.cmd`] : [CEAL_SESSION_ENTRY_INVOCATION];
11360
11822
  }
11361
- function codexSandboxRuleText() {
11823
+ function codexSandboxRuleText(platform = process.platform) {
11362
11824
  return [
11363
11825
  CODEX_SANDBOX_RULE_MARKER,
11364
11826
  "# Written by `ceal-host install` and removed by `ceal-host uninstall`; edits here are overwritten. Put your own rules in another .rules file.",
11365
- "prefix_rule(",
11366
- ` pattern = [${JSON.stringify(CEAL_SESSION_ENTRY_INVOCATION)}],`,
11367
- ' decision = "allow",',
11368
- ` justification = ${JSON.stringify(CODEX_SANDBOX_RULE_JUSTIFICATION)},`,
11369
- ")",
11827
+ ...codexClientExecutableSpellings(platform).flatMap((spelling) => [
11828
+ "prefix_rule(",
11829
+ ` pattern = [${JSON.stringify(spelling)}],`,
11830
+ ' decision = "allow",',
11831
+ ` justification = ${JSON.stringify(CODEX_SANDBOX_RULE_JUSTIFICATION)},`,
11832
+ ")"
11833
+ ]),
11370
11834
  ""
11371
11835
  ].join("\n");
11372
11836
  }
@@ -11379,6 +11843,191 @@ function codexSandboxRuleReasons(state) {
11379
11843
  return state === "installed" ? [] : [`sandbox_rule_${state}`];
11380
11844
  }
11381
11845
 
11846
+ // host/codex/src/codex-hook-trust-verdict.ts
11847
+ import { spawn } from "node:child_process";
11848
+ import { constants as constants12, access } from "node:fs/promises";
11849
+ import { delimiter, join as join16 } from "node:path";
11850
+ var PRODUCER_EVENT_BY_NAME = {
11851
+ sessionStart: "SessionStart",
11852
+ userPromptSubmit: "UserPromptSubmit"
11853
+ };
11854
+ function summarizeCodexProducerTrust(response2, ownerMarker = CODEX_HOOK_OWNER) {
11855
+ const hooks = parseHooksListResponse(response2);
11856
+ if (hooks === void 0) return { available: false };
11857
+ const reasons = [];
11858
+ for (const event of CODEX_HOOK_EVENTS) {
11859
+ const owned = hooks.filter((hook) => PRODUCER_EVENT_BY_NAME[hook.event_name] === event && hook.command !== void 0 && hook.command.includes(`--ceal-hook-owner=${ownerMarker}`));
11860
+ if (owned.length === 0) {
11861
+ reasons.push("hook_untrusted_review_required");
11862
+ continue;
11863
+ }
11864
+ for (const hook of owned) {
11865
+ if (hook.enabled === false) reasons.push("hook_disabled");
11866
+ else if (hook.trust_status === "trusted") continue;
11867
+ else if (hook.trust_status === "modified") reasons.push(`hook_trust_modified:${event}`);
11868
+ else reasons.push("hook_untrusted_review_required");
11869
+ }
11870
+ }
11871
+ return { available: true, reasons, proven_trusted: reasons.length === 0 };
11872
+ }
11873
+ function parseHooksListResponse(response2) {
11874
+ if (!isRecord10(response2) || !Array.isArray(response2.data)) return void 0;
11875
+ const verdicts = [];
11876
+ for (const entry of response2.data) {
11877
+ if (!isRecord10(entry) || !Array.isArray(entry.hooks)) return void 0;
11878
+ for (const hook of entry.hooks) {
11879
+ const parsed = parseHookMetadata(hook);
11880
+ if (parsed === void 0) return void 0;
11881
+ verdicts.push(parsed);
11882
+ }
11883
+ }
11884
+ return verdicts;
11885
+ }
11886
+ function parseHookMetadata(hook) {
11887
+ if (!isRecord10(hook)) return void 0;
11888
+ const eventName = requiredString(hook, "eventName");
11889
+ const trustStatus = requiredString(hook, "trustStatus");
11890
+ const enabled = requiredBoolean(hook, "enabled");
11891
+ const command = optionalString(hook, "command");
11892
+ const key = optionalString(hook, "key");
11893
+ const sourcePath = optionalString(hook, "sourcePath");
11894
+ if (eventName === void 0 || trustStatus === void 0 || enabled === void 0) return void 0;
11895
+ if (command === INVALID_FIELD || key === INVALID_FIELD || sourcePath === INVALID_FIELD) return void 0;
11896
+ return {
11897
+ event_name: eventName,
11898
+ ...key === void 0 ? {} : { key },
11899
+ enabled,
11900
+ trust_status: trustStatus,
11901
+ ...command === void 0 ? {} : { command },
11902
+ ...sourcePath === void 0 ? {} : { source_path: sourcePath }
11903
+ };
11904
+ }
11905
+ var INVALID_FIELD = /* @__PURE__ */ Symbol("invalid-field");
11906
+ function requiredString(record7, field) {
11907
+ const value = record7[field];
11908
+ return typeof value === "string" ? value : void 0;
11909
+ }
11910
+ function requiredBoolean(record7, field) {
11911
+ const value = record7[field];
11912
+ return typeof value === "boolean" ? value : void 0;
11913
+ }
11914
+ function optionalString(record7, field) {
11915
+ const value = record7[field];
11916
+ if (value === void 0) return void 0;
11917
+ return typeof value === "string" ? value : INVALID_FIELD;
11918
+ }
11919
+ async function readCodexHookVerdictsResponse(options = {}) {
11920
+ const executable = options.codex_executable ?? await resolveCodexExecutableOnPath();
11921
+ if (executable === void 0) return void 0;
11922
+ const spawnAppServer = options.spawn_app_server ?? defaultSpawnAppServer;
11923
+ const timeoutMs = options.timeout_ms ?? 3e4;
11924
+ try {
11925
+ return await queryHooksList(spawnAppServer, executable, options.cwd ?? process.cwd(), timeoutMs, options.codex_home);
11926
+ } catch {
11927
+ return void 0;
11928
+ }
11929
+ }
11930
+ async function queryHooksList(spawnAppServer, executable, cwd, timeoutMs, codexHome) {
11931
+ const child = spawnAppServer(executable, ["app-server"], { env: codexHome === void 0 ? { ...process.env } : { ...process.env, [CODEX_HOME_ENVIRONMENT]: codexHome } });
11932
+ const done = new Promise((resolve) => {
11933
+ let buffer = "";
11934
+ const finish = (value) => {
11935
+ removeListeners();
11936
+ resolve(value);
11937
+ };
11938
+ const timer = setTimeout(() => finish(void 0), timeoutMs);
11939
+ const removeListeners = () => {
11940
+ clearTimeout(timer);
11941
+ child.stdout.removeAllListeners("data");
11942
+ child.stderr.removeAllListeners("data");
11943
+ child.stdin.removeAllListeners("error");
11944
+ child.removeAllListeners("error");
11945
+ child.removeAllListeners("close");
11946
+ };
11947
+ const onData = (chunk) => {
11948
+ buffer += chunk.toString("utf8");
11949
+ if (buffer.length > 4 * 1024 * 1024) {
11950
+ kill(child);
11951
+ finish(void 0);
11952
+ return;
11953
+ }
11954
+ let newline;
11955
+ while ((newline = buffer.indexOf("\n")) >= 0) {
11956
+ const line = buffer.slice(0, newline).trim();
11957
+ buffer = buffer.slice(newline + 1);
11958
+ if (line.length === 0) continue;
11959
+ let message;
11960
+ try {
11961
+ message = JSON.parse(line);
11962
+ } catch {
11963
+ continue;
11964
+ }
11965
+ if (isRecord10(message) && message.id === 3) {
11966
+ kill(child);
11967
+ finish(isRecord10(message) && "result" in message ? message.result : void 0);
11968
+ return;
11969
+ }
11970
+ }
11971
+ };
11972
+ child.stdout.on("data", onData);
11973
+ child.stderr.on("data", () => {
11974
+ });
11975
+ child.stdin.on("error", () => finish(void 0));
11976
+ child.on("error", () => finish(void 0));
11977
+ child.on("close", () => finish(void 0));
11978
+ try {
11979
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { clientInfo: { name: "ceal-host", version: "0.0.0" } } })}
11980
+ `);
11981
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "initialized", params: {} })}
11982
+ `);
11983
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 3, method: "hooks/list", params: { cwds: [cwd] } })}
11984
+ `);
11985
+ } catch {
11986
+ finish(void 0);
11987
+ }
11988
+ });
11989
+ try {
11990
+ return await done;
11991
+ } finally {
11992
+ kill(child);
11993
+ }
11994
+ }
11995
+ function kill(child) {
11996
+ try {
11997
+ child.kill();
11998
+ } catch {
11999
+ }
12000
+ }
12001
+ function defaultSpawnAppServer(executable, args, options) {
12002
+ const invocation = process.platform === "win32" && executable.toLowerCase().endsWith(".cmd") ? hostScriptLauncherInvocation(executable, args, "cmd", process.platform, options.env) : { executable, args };
12003
+ const child = spawn(invocation.executable, [...invocation.args], { env: { ...options.env, ...invocation.environment }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
12004
+ if (child.stdin === null || child.stdout === null || child.stderr === null) throw new Error("Codex app-server stdio is unavailable.");
12005
+ return { stdin: child.stdin, stdout: child.stdout, stderr: child.stderr, kill: () => {
12006
+ child.stdin?.destroy();
12007
+ return child.kill();
12008
+ }, on: child.on.bind(child), removeAllListeners: child.removeAllListeners.bind(child) };
12009
+ }
12010
+ async function resolveCodexExecutableOnPath() {
12011
+ const pathValue = process.env.PATH;
12012
+ if (pathValue === void 0 || pathValue.length === 0) return void 0;
12013
+ const candidates = process.platform === "win32" ? ["codex.exe", "codex.cmd"] : ["codex"];
12014
+ for (const directory of pathValue.split(delimiter)) {
12015
+ if (directory.length === 0) continue;
12016
+ for (const candidate of candidates) {
12017
+ const full = join16(directory, candidate);
12018
+ try {
12019
+ await access(full, process.platform === "win32" ? constants12.F_OK : constants12.X_OK);
12020
+ return full;
12021
+ } catch {
12022
+ }
12023
+ }
12024
+ }
12025
+ return void 0;
12026
+ }
12027
+ function isRecord10(value) {
12028
+ return value !== null && typeof value === "object" && !Array.isArray(value);
12029
+ }
12030
+
11382
12031
  // host/codex/src/codex-installer.ts
11383
12032
  var CODEX_HOOK_COMMAND_MAX_CHARACTERS = 4096;
11384
12033
  function codexHooksInstalled(doctor) {
@@ -11390,7 +12039,7 @@ function resolveRepoCodexInvocationAuthenticationExecutable() {
11390
12039
  function resolveCodexHooksConfigPath(codexHome) {
11391
12040
  const home = codexHome ?? resolveCodexHome(process.env, homedir3());
11392
12041
  if (typeof home !== "string" || home.length === 0) throw new CodexHostAdapterError("configuration", "Codex home is unavailable.");
11393
- return join15(home, CODEX_HOOKS_CONFIG_FILE);
12042
+ return join17(home, CODEX_HOOKS_CONFIG_FILE);
11394
12043
  }
11395
12044
  async function installCodexHooks(options) {
11396
12045
  const normalized = validateInstallerOptions(options);
@@ -11430,32 +12079,34 @@ async function doctorCodexHooks(options) {
11430
12079
  const configPath = options.config_path ?? resolveCodexHooksConfigPath(options.codex_home);
11431
12080
  const trustPath = codexConfigPath(configPath);
11432
12081
  const hookCommand2 = resolveHookCommand2(options);
12082
+ const versionHint = codexVersionHint(options.codex_version);
12083
+ const withVersionHint = (result) => versionHint === void 0 ? result : { ...result, codex_version_hint: versionHint };
11433
12084
  const invalidCommand = invalidHookCommandDoctorResult(hookCommand2, configPath, trustPath);
11434
- if (invalidCommand !== null) return invalidCommand;
12085
+ if (invalidCommand !== null) return withVersionHint(invalidCommand);
11435
12086
  const { authenticationCommand, localCapabilityPath } = resolveLocalCapabilityInstallation(options);
11436
12087
  const unsupported = unsupportedDoctorResult(options, configPath, trustPath);
11437
- if (unsupported !== null) return unsupported;
12088
+ if (unsupported !== null) return withVersionHint(unsupported);
11438
12089
  const current = await readDoctorConfig(configPath, trustPath);
11439
- if (current.status !== "ready") return current.result;
12090
+ if (current.status !== "ready") return withVersionHint(current.result);
11440
12091
  const config = current.result;
11441
12092
  const configured = CODEX_HOOK_EVENTS.filter((event) => ownedEntries2(config, event).length > 0);
11442
12093
  const missing = CODEX_HOOK_EVENTS.filter((event) => ownedEntries2(config, event).length === 0);
11443
12094
  let trust;
11444
12095
  try {
11445
- trust = await inspectCodexTrust(configPath, config, hookCommand2);
12096
+ trust = await inspectCodexTrust(configPath, config, hookCommand2, options.hook_verdicts);
11446
12097
  } catch (error) {
11447
- if (error instanceof CodexHostAdapterError && error.code === "configuration") return doctorResult("malformed", configPath, trustPath, TRUST_UNAVAILABLE, configured, missing, ["malformed_config"]);
12098
+ if (error instanceof CodexHostAdapterError && error.code === "configuration") return withVersionHint(doctorResult("malformed", configPath, trustPath, TRUST_UNAVAILABLE, configured, missing, ["malformed_config"]));
11448
12099
  throw error;
11449
12100
  }
11450
12101
  const sandboxRule = codexSandboxRuleReasons(await readCodexSandboxRuleState(codexSandboxRulePath(dirname11(configPath))));
11451
12102
  const reasons = [...trust.reasons, ...await inspectCodexLocalCapability(localCapabilityPath, authenticationCommand, options.secure_file_custody), ...sandboxRule];
11452
12103
  const status = codexDoctorStatus(missing, trust, reasons);
11453
- return doctorResult(status, configPath, trustPath, trust, configured, missing, reasons);
12104
+ return withVersionHint(doctorResult(status, configPath, trustPath, trust, configured, missing, reasons));
11454
12105
  }
11455
12106
  function codexDoctorStatus(missing, trust, reasons) {
11456
12107
  if (missing.length > 0) return "drifted";
11457
12108
  if (trust.state === "trusted" && reasons.length === 0) return "ready";
11458
- return reasons.every((reason) => reason === "hook_untrusted_review_required") ? "installed" : "drifted";
12109
+ return reasons.every((reason) => reason === "hook_untrusted_review_required" || reason.startsWith("hook_trust_modified:")) ? "installed" : "drifted";
11459
12110
  }
11460
12111
  function invalidHookCommandDoctorResult(command, configPath, trustPath) {
11461
12112
  try {
@@ -11480,13 +12131,13 @@ async function readDoctorConfig(configPath, trustPath) {
11480
12131
  }
11481
12132
  function validateInstallerOptions(options) {
11482
12133
  const configPath = options.config_path ?? resolveCodexHooksConfigPath(options.codex_home);
11483
- if (!isAbsolute8(configPath) || typeof options.hook_executable !== "string" || !isAbsolute8(options.hook_executable)) throw new CodexHostAdapterError("configuration", "Codex installer paths must be absolute.");
12134
+ if (!isAbsolute9(configPath) || typeof options.hook_executable !== "string" || !isAbsolute9(options.hook_executable)) throw new CodexHostAdapterError("configuration", "Codex installer paths must be absolute.");
11484
12135
  requireLocalCapabilityPath(options.local_capability_path);
11485
12136
  validateOptionalInstallerPaths(options);
11486
12137
  try {
11487
12138
  validateHostCommandVector(resolveHookCommand2(options));
11488
12139
  } catch (error) {
11489
- throw new CodexHostAdapterError("configuration", `Codex hook command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
12140
+ throw new CodexHostAdapterError("configuration", `Codex hook command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11490
12141
  }
11491
12142
  if (options.feature_enabled === false) throw new CodexHostAdapterError("unsupported", `Codex ${CODEX_HOOK_FEATURE} feature is disabled.`);
11492
12143
  return { ...options, config_path: configPath };
@@ -11495,11 +12146,11 @@ function resolveHookCommand2(options) {
11495
12146
  return { executable: options.hook_executable, args: options.hook_arguments ?? [] };
11496
12147
  }
11497
12148
  function validateOptionalInstallerPaths(options) {
11498
- if (options.invocation_authentication_executable !== void 0 && !isAbsolute8(options.invocation_authentication_executable)) throw new CodexHostAdapterError("configuration", "Codex invocation authentication executable path must be absolute.");
12149
+ if (options.invocation_authentication_executable !== void 0 && !isAbsolute9(options.invocation_authentication_executable)) throw new CodexHostAdapterError("configuration", "Codex invocation authentication executable path must be absolute.");
11499
12150
  }
11500
12151
  var CODEX_LOCAL_CAPABILITY_OWNER = CODEX_HOOK_OWNER;
11501
12152
  function requireLocalCapabilityPath(value) {
11502
- if (typeof value !== "string" || !isAbsolute8(value)) throw new CodexHostAdapterError("configuration", "Codex local capability path must be absolute.");
12153
+ if (typeof value !== "string" || !isAbsolute9(value)) throw new CodexHostAdapterError("configuration", "Codex local capability path must be absolute.");
11503
12154
  return value;
11504
12155
  }
11505
12156
  function resolveLocalCapabilityInstallation(options) {
@@ -11509,7 +12160,7 @@ async function validateAuthenticationCommand(command) {
11509
12160
  try {
11510
12161
  validateHostCommandVector(command);
11511
12162
  } catch (error) {
11512
- throw configurationError(`Codex invocation authentication command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
12163
+ throw configurationError(`Codex invocation authentication command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11513
12164
  }
11514
12165
  try {
11515
12166
  const stats = await lstat9(command.executable);
@@ -11631,7 +12282,7 @@ async function readConfig(path) {
11631
12282
  const stats = await lstat9(path);
11632
12283
  if (!stats.isFile() || stats.isSymbolicLink()) throw configurationError("Codex hooks configuration is malformed.");
11633
12284
  const value = JSON.parse(await readFile3(path, "utf8"));
11634
- if (!isRecord10(value)) throw configurationError("Codex hooks configuration is malformed.");
12285
+ if (!isRecord11(value)) throw configurationError("Codex hooks configuration is malformed.");
11635
12286
  validateHooksConfig(value);
11636
12287
  return value;
11637
12288
  } catch (error) {
@@ -11652,7 +12303,7 @@ function validateHooksConfig(config) {
11652
12303
  if (Object.keys(config).some((key) => key !== "description" && key !== "hooks")) throw configurationError("Codex hooks configuration is malformed.");
11653
12304
  if (config.description !== void 0 && typeof config.description !== "string") throw configurationError("Codex hooks configuration is malformed.");
11654
12305
  if (config.hooks === void 0) return;
11655
- if (!isRecord10(config.hooks)) throw configurationError("Codex hooks configuration is malformed.");
12306
+ if (!isRecord11(config.hooks)) throw configurationError("Codex hooks configuration is malformed.");
11656
12307
  for (const event of CODEX_HOOK_EVENTS) {
11657
12308
  const value = config.hooks[event];
11658
12309
  if (value === void 0) continue;
@@ -11661,7 +12312,7 @@ function validateHooksConfig(config) {
11661
12312
  }
11662
12313
  }
11663
12314
  function validateHookEntry(entry) {
11664
- if (!isRecord10(entry)) throw configurationError("Codex hook entry is malformed.");
12315
+ if (!isRecord11(entry)) throw configurationError("Codex hook entry is malformed.");
11665
12316
  if (Array.isArray(entry.hooks)) {
11666
12317
  if (entry.matcher !== void 0 && typeof entry.matcher !== "string") throw configurationError("Codex hook matcher is malformed.");
11667
12318
  for (const handler of entry.hooks) validateHookHandler(handler);
@@ -11670,7 +12321,7 @@ function validateHookEntry(entry) {
11670
12321
  throw configurationError("Codex hook entry is malformed.");
11671
12322
  }
11672
12323
  function validateHookHandler(entry) {
11673
- if (!isRecord10(entry) || typeof entry.type !== "string") throw configurationError("Codex hook handler is malformed.");
12324
+ if (!isRecord11(entry) || typeof entry.type !== "string") throw configurationError("Codex hook handler is malformed.");
11674
12325
  if (entry.type === "command") return validateCommandHookHandler(entry);
11675
12326
  if (entry.type === "mcp_tool") return validateMcpHookHandler(entry);
11676
12327
  if (entry.type === "prompt" || entry.type === "agent") return;
@@ -11700,9 +12351,9 @@ function validateOptionalBoolean(value, message) {
11700
12351
  function normalizeHookGroups(entries) {
11701
12352
  const groups = [];
11702
12353
  for (const entry of entries) {
11703
- if (!isRecord10(entry)) throw configurationError("Codex hook entry is malformed.");
12354
+ if (!isRecord11(entry)) throw configurationError("Codex hook entry is malformed.");
11704
12355
  if (Array.isArray(entry.hooks)) {
11705
- groups.push({ ...entry, hooks: entry.hooks.filter(isRecord10) });
12356
+ groups.push({ ...entry, hooks: entry.hooks.filter(isRecord11) });
11706
12357
  continue;
11707
12358
  }
11708
12359
  throw configurationError("Codex hook entry is malformed.");
@@ -11713,7 +12364,7 @@ function ownedHookEntry(command, event) {
11713
12364
  return { type: "command", command: hookCommand(command, event, "posix"), commandWindows: hookCommand(command, event, "windows"), async: false };
11714
12365
  }
11715
12366
  function mergeOwnedHooks2(config, command) {
11716
- const hooks = isRecord10(config.hooks) ? { ...config.hooks } : {};
12367
+ const hooks = isRecord11(config.hooks) ? { ...config.hooks } : {};
11717
12368
  for (const event of CODEX_HOOK_EVENTS) {
11718
12369
  const groups = Array.isArray(hooks[event]) ? normalizeHookGroups(hooks[event]) : [];
11719
12370
  const retained = groups.map((group) => ({ ...group, hooks: group.hooks.filter((entry) => !ownedHookHandler(entry)) })).filter((group) => group.hooks.length > 0);
@@ -11723,7 +12374,7 @@ function mergeOwnedHooks2(config, command) {
11723
12374
  return { ...config, hooks };
11724
12375
  }
11725
12376
  function removeOwnedHooks2(config) {
11726
- if (!isRecord10(config.hooks)) return config;
12377
+ if (!isRecord11(config.hooks)) return config;
11727
12378
  const hooks = { ...config.hooks };
11728
12379
  for (const event of CODEX_HOOK_EVENTS) {
11729
12380
  removeOwnedEvent(hooks, event);
@@ -11737,7 +12388,7 @@ function removeOwnedEvent(hooks, event) {
11737
12388
  else hooks[event] = retained;
11738
12389
  }
11739
12390
  function ownedEntries2(config, event) {
11740
- if (!isRecord10(config.hooks) || !Array.isArray(config.hooks[event])) return [];
12391
+ if (!isRecord11(config.hooks) || !Array.isArray(config.hooks[event])) return [];
11741
12392
  return normalizeHookGroups(config.hooks[event]).flatMap((group) => group.hooks.filter(ownedHookHandler));
11742
12393
  }
11743
12394
  function ownedHookHandler(entry) {
@@ -11765,7 +12416,7 @@ async function writeAtomicJson3(path, value) {
11765
12416
  }
11766
12417
  async function writeAtomicText(path, text) {
11767
12418
  await mkdir9(dirname11(path), { recursive: true, mode: 448 });
11768
- const temp = join15(dirname11(path), `.${basename2(path)}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`);
12419
+ const temp = join17(dirname11(path), `.${basename2(path)}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`);
11769
12420
  let ownsTemp = false;
11770
12421
  try {
11771
12422
  const handle = await open6(temp, "wx", 384);
@@ -11803,14 +12454,19 @@ async function backupTextFile(path) {
11803
12454
  }
11804
12455
  }
11805
12456
  var TRUST_UNAVAILABLE = { state: "unavailable", codex_trust: "unavailable" };
11806
- async function inspectCodexTrust(configPath, config, command) {
12457
+ async function inspectCodexTrust(configPath, config, command, hookVerdicts) {
11807
12458
  const executable = await inspectHookExecutable(command.executable);
11808
12459
  const owned = CODEX_HOOK_EVENTS.flatMap((event) => ownedHookLocations(config, event));
11809
12460
  if (owned.length === 0) return { ...TRUST_UNAVAILABLE, reasons: executable };
12461
+ const verdict = summarizeCodexProducerTrust(hookVerdicts);
12462
+ if (verdict.available) {
12463
+ const reasons2 = [...verdict.reasons, ...inspectHookCommands(config, command), ...executable];
12464
+ return { ...trustInspection(reasons2), codex_trust: verdict.proven_trusted ? "trusted" : "awaiting_codex_approval" };
12465
+ }
11810
12466
  const codexConfig = await readTrustConfig(configPath);
11811
12467
  const states = codexConfig === null ? /* @__PURE__ */ new Map() : codexHookStates(codexConfig);
11812
12468
  const reasons = [...inspectHookStates(configPath, owned, states), ...inspectHookCommands(config, command), ...executable];
11813
- return { ...trustInspection(reasons), codex_trust: reasons.includes("hook_untrusted_review_required") ? "awaiting_codex_approval" : "trusted" };
12469
+ return { ...trustInspection(reasons), codex_trust: reasons.includes("hook_untrusted_review_required") ? "awaiting_codex_approval" : "unproven" };
11814
12470
  }
11815
12471
  function inspectHookCommands(config, command) {
11816
12472
  return CODEX_HOOK_EVENTS.flatMap((event) => {
@@ -11855,11 +12511,11 @@ async function inspectHookExecutable(path) {
11855
12511
  }
11856
12512
  }
11857
12513
  function trustInspection(reasons) {
11858
- if (reasons.some((reason) => reason === "hook_disabled" || reason === "hook_executable_unavailable" || reason === "duplicate_owned_hook")) return { state: "modified", reasons };
12514
+ if (reasons.some((reason) => reason === "hook_disabled" || reason === "hook_executable_unavailable" || reason === "duplicate_owned_hook" || reason.startsWith("hook_trust_modified:"))) return { state: "modified", reasons };
11859
12515
  return reasons.length === 0 ? { state: "trusted", reasons } : { state: "untrusted", reasons };
11860
12516
  }
11861
12517
  function ownedHookLocations(config, event) {
11862
- if (!isRecord10(config.hooks) || !Array.isArray(config.hooks[event])) return [];
12518
+ if (!isRecord11(config.hooks) || !Array.isArray(config.hooks[event])) return [];
11863
12519
  return normalizeHookGroups(config.hooks[event]).flatMap((group, groupIndex) => group.hooks.flatMap((handler, handlerIndex) => ownedHookHandler(handler) ? [{ event, group_index: groupIndex, handler_index: handlerIndex, handler }] : []));
11864
12520
  }
11865
12521
  async function readCodexConfig(path) {
@@ -11867,7 +12523,7 @@ async function readCodexConfig(path) {
11867
12523
  const stats = await lstat9(path);
11868
12524
  if (!stats.isFile() || stats.isSymbolicLink()) throw configurationError("Codex config.toml is malformed.");
11869
12525
  const value = import_toml.default.parse(await readFile3(path, "utf8"));
11870
- if (!isRecord10(value)) throw configurationError("Codex config.toml is malformed.");
12526
+ if (!isRecord11(value)) throw configurationError("Codex config.toml is malformed.");
11871
12527
  return value;
11872
12528
  } catch (error) {
11873
12529
  if (error instanceof CodexHostAdapterError) throw error;
@@ -11880,20 +12536,20 @@ function codexHookStates(config) {
11880
12536
  if (hooks === void 0) return /* @__PURE__ */ new Map();
11881
12537
  const state = hooks.state;
11882
12538
  if (state === void 0) return /* @__PURE__ */ new Map();
11883
- if (!isRecord10(state)) throw configurationError("Codex config.toml hook state is malformed.");
12539
+ if (!isRecord11(state)) throw configurationError("Codex config.toml hook state is malformed.");
11884
12540
  return new Map(Object.entries(state).map(([key, entry]) => [key, parseCodexHookState(entry)]));
11885
12541
  }
11886
12542
  function codexHooksTable(config) {
11887
12543
  if (config.hooks === void 0) return void 0;
11888
- if (!isRecord10(config.hooks)) throw configurationError("Codex config.toml hook state is malformed.");
12544
+ if (!isRecord11(config.hooks)) throw configurationError("Codex config.toml hook state is malformed.");
11889
12545
  return config.hooks;
11890
12546
  }
11891
12547
  function parseCodexHookState(entry) {
11892
- if (!isRecord10(entry) || entry.enabled !== void 0 && typeof entry.enabled !== "boolean" || entry.trusted_hash !== void 0 && typeof entry.trusted_hash !== "string") throw configurationError("Codex config.toml hook state is malformed.");
12548
+ if (!isRecord11(entry) || entry.enabled !== void 0 && typeof entry.enabled !== "boolean" || entry.trusted_hash !== void 0 && typeof entry.trusted_hash !== "string") throw configurationError("Codex config.toml hook state is malformed.");
11893
12549
  return { ...entry.enabled === void 0 ? {} : { enabled: entry.enabled }, ...entry.trusted_hash === void 0 ? {} : { trusted_hash: entry.trusted_hash } };
11894
12550
  }
11895
12551
  function codexConfigPath(configPath) {
11896
- return join15(dirname11(configPath), "config.toml");
12552
+ return join17(dirname11(configPath), "config.toml");
11897
12553
  }
11898
12554
  function codexHookStateKey(configPath, event, groupIndex, handlerIndex) {
11899
12555
  return `${configPath}:${hookEventKeyLabel(event)}:${groupIndex}:${handlerIndex}`;
@@ -11904,11 +12560,11 @@ function hookEventKeyLabel(event) {
11904
12560
  function doctorResult(status, configPath, trustPath, trust, configured, missing, reasons) {
11905
12561
  return { status, config_path: configPath, trust_path: trustPath, trust_state: trust.state, codex_trust: trust.codex_trust, feature: CODEX_HOOK_FEATURE, latest_tested_version: CODEX_CLI_VERSION, version_policy: "owned_schema_compatible", configured_events: configured, missing_events: missing, drift_reasons: reasons };
11906
12562
  }
11907
- function isRecord10(value) {
12563
+ function isRecord11(value) {
11908
12564
  return value !== null && typeof value === "object" && !Array.isArray(value);
11909
12565
  }
11910
12566
  function isNotFound4(error) {
11911
- return isRecord10(error) && error.code === "ENOENT";
12567
+ return isRecord11(error) && error.code === "ENOENT";
11912
12568
  }
11913
12569
  function storageError2(message) {
11914
12570
  return new CodexHostAdapterError("storage", message);
@@ -12026,6 +12682,7 @@ async function reconcileProducerHooks(producer, entry, homes, repaired = false)
12026
12682
  async function inspectProducerHooks(producer, entry, homes) {
12027
12683
  if (producer === "codex") {
12028
12684
  await readHostProducerConfig(CODEX_PRODUCER_DESCRIPTOR, entry.configPath, process.platform, homes.custody);
12685
+ const hook_verdicts = await readCodexHookVerdictsResponse({ ...homes.codex_home === void 0 ? {} : { codex_home: homes.codex_home } });
12029
12686
  const result2 = await doctorCodexHooks({
12030
12687
  local_capability_path: hostLocalCapabilityPath(homes.user_home, "codex"),
12031
12688
  secure_file_custody: homes.custody,
@@ -12033,7 +12690,8 @@ async function inspectProducerHooks(producer, entry, homes) {
12033
12690
  hook_executable: entry.hook.executable,
12034
12691
  hook_arguments: entry.hook.args,
12035
12692
  invocation_authentication_executable: entry.authentication.executable,
12036
- invocation_authentication_arguments: entry.authentication.args
12693
+ invocation_authentication_arguments: entry.authentication.args,
12694
+ hook_verdicts
12037
12695
  });
12038
12696
  return codexHooksInstalled(result2) ? null : { status: result2.status, reasons: result2.drift_reasons };
12039
12697
  }
@@ -12052,7 +12710,7 @@ async function validatePrivateRuntimePaths(paths, selection) {
12052
12710
  }
12053
12711
  }
12054
12712
  function claudePermissionOwnershipPath(stateRoot) {
12055
- return join16(stateRoot, "producers", "claude", "permission-ownership.json");
12713
+ return join18(stateRoot, "ownership", "claude", "permission-ownership.json");
12056
12714
  }
12057
12715
  async function assertRegularRuntimeFile(path) {
12058
12716
  let info;
@@ -12073,8 +12731,8 @@ function selectedProducers(selection) {
12073
12731
 
12074
12732
  // host/lifecycle/src/host-runtime-services-macos.ts
12075
12733
  import { execFile as execFile2 } from "node:child_process";
12076
- import { constants as constants12 } from "node:fs";
12077
- import { chmod as chmod2, lstat as lstat11, mkdir as mkdir10, open as open7, readdir as readdir5, rename as rename6, unlink as unlink9 } from "node:fs/promises";
12734
+ import { constants as constants13 } from "node:fs";
12735
+ import { chmod as chmod2, lstat as lstat11, mkdir as mkdir10, open as open7, readdir as readdir4, rename as rename6, unlink as unlink9 } from "node:fs/promises";
12078
12736
  import { homedir as homedir4 } from "node:os";
12079
12737
  import { posix as posix9 } from "node:path";
12080
12738
  import { promisify } from "node:util";
@@ -12091,7 +12749,7 @@ async function requireHostRuntimeManagerPreflight(options) {
12091
12749
  async function requireCurrentAccountHome(options) {
12092
12750
  const environment = options.environment ?? process.env;
12093
12751
  const environmentName = options.platform === "win32" ? "USERPROFILE" : "HOME";
12094
- const configuredHome = environment[environmentName];
12752
+ const configuredHome = environmentValue(environment, environmentName, options.platform);
12095
12753
  let accountHome = options.account_home;
12096
12754
  if (accountHome === void 0) {
12097
12755
  try {
@@ -12110,11 +12768,11 @@ async function requireCurrentAccountHome(options) {
12110
12768
  } catch {
12111
12769
  throw homeUnavailable();
12112
12770
  }
12113
- const normalize2 = (value) => {
12771
+ const normalize3 = (value) => {
12114
12772
  const normalized = path.normalize(value);
12115
12773
  return options.platform === "win32" ? normalized.toLocaleLowerCase("en-US") : normalized;
12116
12774
  };
12117
- if (normalize2(configuredResolved) !== normalize2(accountResolved)) {
12775
+ if (normalize3(configuredResolved) !== normalize3(accountResolved)) {
12118
12776
  throw new HostRuntimeReasonedError("host_manager_home_mismatch", ["manager_home_mismatch", "restore_account_home_environment"]);
12119
12777
  }
12120
12778
  }
@@ -12220,7 +12878,7 @@ function assertCommand(command) {
12220
12878
  try {
12221
12879
  validateHostCommandVector(command, "direct-exec");
12222
12880
  } catch (error) {
12223
- throw new HostRuntimeServiceContractError("invalid_observation", `Host service command observation is invalid (${refusalFact("error", error)}).`);
12881
+ throw new HostRuntimeServiceContractError("invalid_observation", `Host service command observation is invalid (${renderOperatorDiagnostic(error)}).`);
12224
12882
  }
12225
12883
  }
12226
12884
  function absoluteNormalizedPath(value, label, path) {
@@ -12247,7 +12905,7 @@ var MAX_PLIST_BYTES = 64 * 1024;
12247
12905
  var SERVICE_PROCESS_POLL_MS = 50;
12248
12906
  var LAUNCHCTL = "/bin/launchctl";
12249
12907
  var OWNER_MARKER = "ceal-host-runtime-service-v1";
12250
- var { basename: basename4, dirname: dirname13, join: join17 } = posix9;
12908
+ var { basename: basename4, dirname: dirname13, join: join19 } = posix9;
12251
12909
  var MacosHostRuntimeServiceError = class extends Error {
12252
12910
  code;
12253
12911
  /**
@@ -12279,7 +12937,7 @@ function createMacosHostRuntimeServiceAdapter(options) {
12279
12937
  return new MacosHostRuntimeServiceAdapter(directory, absoluteNormalized(options.log_directory), uid, options.run_launchctl ?? runMacosLaunchctl, options.run_process ?? runMacosPs, options.progress ?? (() => void 0), managerPreflight, resolveMacosHostRuntimeClock(options.clock));
12280
12938
  }
12281
12939
  function macosLaunchAgentsDirectory(environment) {
12282
- return join17(environment.HOME || homedir4(), "Library", "LaunchAgents");
12940
+ return join19(environment.HOME || homedir4(), "Library", "LaunchAgents");
12283
12941
  }
12284
12942
  function assertMacosServicePlatform(platform) {
12285
12943
  if (platform !== "darwin") throw new MacosHostRuntimeServiceError("unsupported", `The launchd Host service adapter requires macOS (${refusalFact("platform", platform, "darwin")}).`, ["fact:platform"]);
@@ -12327,7 +12985,7 @@ function loadedReferencesMatch(stdout, service) {
12327
12985
  }
12328
12986
  async function runMacosLaunchctl(args) {
12329
12987
  try {
12330
- const result = await execFileAsync(LAUNCHCTL, [...args], { encoding: "utf8", timeout: 15e3, maxBuffer: HOST_RUNTIME_SERVICE_COMMAND_MAX_OUTPUT_BYTES });
12988
+ const result = await execFileAsync(LAUNCHCTL, [...args], { encoding: "utf8", timeout: 15e3, maxBuffer: HOST_RUNTIME_SERVICE_COMMAND_MAX_OUTPUT_BYTES, cwd: resolveCealSpawnWorkingDirectory() });
12331
12989
  return boundedLaunchctlResult({ exit_code: 0, stdout: result.stdout, stderr: result.stderr });
12332
12990
  } catch (error) {
12333
12991
  const failure = executionFailure(error);
@@ -12336,7 +12994,7 @@ async function runMacosLaunchctl(args) {
12336
12994
  }
12337
12995
  async function runMacosPs(args) {
12338
12996
  try {
12339
- const result = await execFileAsync("/bin/ps", [...args], { encoding: "utf8", timeout: 5e3, maxBuffer: 16 * 1024 });
12997
+ const result = await execFileAsync("/bin/ps", [...args], { encoding: "utf8", timeout: 5e3, maxBuffer: 16 * 1024, cwd: resolveCealSpawnWorkingDirectory() });
12340
12998
  return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
12341
12999
  } catch (error) {
12342
13000
  const failure = executionFailure(error);
@@ -12470,7 +13128,7 @@ var MacosHostRuntimeServiceAdapter = class {
12470
13128
  const labels = /* @__PURE__ */ new Set();
12471
13129
  let files;
12472
13130
  try {
12473
- files = (await readdir5(this.directory)).sort();
13131
+ files = (await readdir4(this.directory)).sort();
12474
13132
  } catch {
12475
13133
  files = [];
12476
13134
  }
@@ -12500,7 +13158,7 @@ var MacosHostRuntimeServiceAdapter = class {
12500
13158
  async ownedLabelPrefix(label) {
12501
13159
  let managed;
12502
13160
  try {
12503
- managed = await readManagedPlist(join17(this.directory, `${label}.plist`), `<!-- ${OWNER_MARKER}:${label} -->`, this.uid);
13161
+ managed = await readManagedPlist(join19(this.directory, `${label}.plist`), `<!-- ${OWNER_MARKER}:${label} -->`, this.uid);
12504
13162
  } catch {
12505
13163
  return {};
12506
13164
  }
@@ -12531,7 +13189,7 @@ var MacosHostRuntimeServiceAdapter = class {
12531
13189
  }
12532
13190
  async hasOwnedDefinition(label) {
12533
13191
  try {
12534
- return await readManagedPlist(join17(this.directory, `${label}.plist`), `<!-- ${OWNER_MARKER}:${label} -->`, this.uid) !== null;
13192
+ return await readManagedPlist(join19(this.directory, `${label}.plist`), `<!-- ${OWNER_MARKER}:${label} -->`, this.uid) !== null;
12535
13193
  } catch (error) {
12536
13194
  if (error instanceof MacosHostRuntimeServiceError) return false;
12537
13195
  throw error;
@@ -12615,7 +13273,7 @@ var MacosHostRuntimeServiceAdapter = class {
12615
13273
  }
12616
13274
  owner(prefix, component) {
12617
13275
  const label = macosHostRuntimeServiceLabel(prefix, component);
12618
- return { label, marker: `<!-- ${OWNER_MARKER}:${label} -->`, path: join17(this.directory, `${label}.plist`), target: `gui/${this.uid}/${label}`, log: macosHostRuntimeServiceLogPath(this.logDirectory, component) };
13276
+ return { label, marker: `<!-- ${OWNER_MARKER}:${label} -->`, path: join19(this.directory, `${label}.plist`), target: `gui/${this.uid}/${label}`, log: macosHostRuntimeServiceLogPath(this.logDirectory, component) };
12619
13277
  }
12620
13278
  async launchctl(args) {
12621
13279
  return boundedLaunchctlResult(await this.runner(args));
@@ -12645,6 +13303,10 @@ function launchAgentPlist(owner, service) {
12645
13303
  '<plist version="1.0"><dict>',
12646
13304
  `<key>Label</key><string>${label}</string>`,
12647
13305
  `<key>ProgramArguments</key><array>${argumentsXml}</array>`,
13306
+ // The service's working directory must never sit inside the prefix
13307
+ // activation swaps; owner.log names the per-service file in the
13308
+ // per-state-root log directory, so its parent is that stable directory.
13309
+ `<key>WorkingDirectory</key><string>${xml(dirname13(owner.log))}</string>`,
12648
13310
  "<key>RunAtLoad</key><true/>",
12649
13311
  "<key>KeepAlive</key><true/>",
12650
13312
  "<key>ProcessType</key><string>Background</string>",
@@ -12702,7 +13364,7 @@ async function readManagedPlist(path, marker, uid) {
12702
13364
  async function writeManagedPlist(path, marker, text, uid, repairLooseMode = false) {
12703
13365
  const current = await readManagedPlist(path, marker, uid);
12704
13366
  if (current?.text === text && !repairLooseMode) return;
12705
- const temporary = join17(dirname13(path), `.${basename4(path)}.${process.pid}.${createHash15("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0, 12)}.tmp`);
13367
+ const temporary = join19(dirname13(path), `.${basename4(path)}.${process.pid}.${createHash15("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0, 12)}.tmp`);
12706
13368
  try {
12707
13369
  const handle = await open7(temporary, "wx", 384);
12708
13370
  try {
@@ -12713,7 +13375,7 @@ async function writeManagedPlist(path, marker, text, uid, repairLooseMode = fals
12713
13375
  }
12714
13376
  await chmod2(temporary, 384);
12715
13377
  await rename6(temporary, path);
12716
- const directory = await open7(dirname13(path), constants12.O_RDONLY);
13378
+ const directory = await open7(dirname13(path), constants13.O_RDONLY);
12717
13379
  try {
12718
13380
  await directory.sync();
12719
13381
  } finally {
@@ -12908,14 +13570,17 @@ function wireService(prefix, service, logDirectory) {
12908
13570
  executable: win3211.join(prefix, ...HOST_WINDOWS_BACKGROUND_RELATIVE_PATH.split("/")),
12909
13571
  // Task Scheduler ExecAction launches the executable directly, never
12910
13572
  // through cmd.exe, so `%` and `!` in user paths stay literal here.
12911
- arguments: [service.command.executable, ...argumentsWithLog].map(quoteWindowsExecArgument).join(" ")
13573
+ arguments: [service.command.executable, ...argumentsWithLog].map(quoteWindowsExecArgument).join(" "),
13574
+ // The task's own working directory must never sit inside the prefix
13575
+ // activation swaps; the per-state-root log directory is stable and outside it.
13576
+ ...logDirectory === void 0 ? {} : { working_directory: logDirectory }
12912
13577
  };
12913
13578
  }
12914
13579
  function validateWindowsService(prefix, service) {
12915
13580
  try {
12916
13581
  validateHostCommandVector(service.command, "direct-exec");
12917
13582
  } catch (error) {
12918
- throw invalidServiceSet(`Windows service command vectors must satisfy the Host command contract: ${refusalFact("error", error)}.`);
13583
+ throw invalidServiceSet(`Windows service command vectors must satisfy the Host command contract: ${renderOperatorDiagnostic(error)}.`);
12919
13584
  }
12920
13585
  if (!win3211.isAbsolute(service.command.executable) || win3211.normalize(service.command.executable) !== service.command.executable) throw invalidServiceSet("Windows service executables must be absolute normalized paths.");
12921
13586
  const expectedNode = win3211.join(prefix, ...HOST_BUNDLE_PRIVATE_RUNTIME_ROOT.split("/"), "node", "bin", "node.exe");
@@ -12996,15 +13661,15 @@ function parseInstallations(result) {
12996
13661
  return assembleHostRuntimeInstallations(groups);
12997
13662
  }
12998
13663
  function isWireResult(value) {
12999
- return isRecord11(value) && value.schema_version === WINDOWS_SERVICE_RESULT_SCHEMA && value.ok === true && (value.observations === void 0 || Array.isArray(value.observations)) && (value.tasks === void 0 || Array.isArray(value.tasks));
13664
+ return isRecord12(value) && value.schema_version === WINDOWS_SERVICE_RESULT_SCHEMA && value.ok === true && (value.observations === void 0 || Array.isArray(value.observations)) && (value.tasks === void 0 || Array.isArray(value.tasks));
13000
13665
  }
13001
13666
  function isWireInstallationTask(value) {
13002
- if (!isRecord11(value) || typeof value.installation_id !== "string" || !isServiceComponent2(value.component) || !isServiceState(value.state) || typeof value.name !== "string") return false;
13667
+ if (!isRecord12(value) || typeof value.installation_id !== "string" || !isServiceComponent2(value.component) || !isServiceState(value.state) || typeof value.name !== "string") return false;
13003
13668
  const match = WINDOWS_HOST_TASK_NAME_PATTERN.exec(value.name);
13004
13669
  return match?.[1] === value.installation_id && match[2] === value.component;
13005
13670
  }
13006
13671
  function isWireObservation(value) {
13007
- return isRecord11(value) && isServiceComponent2(value.component) && isServiceState(value.state) && typeof value.definition_matches === "boolean" && (value.startup_pending === void 0 || typeof value.startup_pending === "boolean") && (value.last_task_result === void 0 || Number.isSafeInteger(value.last_task_result));
13672
+ return isRecord12(value) && isServiceComponent2(value.component) && isServiceState(value.state) && typeof value.definition_matches === "boolean" && (value.startup_pending === void 0 || typeof value.startup_pending === "boolean") && (value.last_task_result === void 0 || Number.isSafeInteger(value.last_task_result));
13008
13673
  }
13009
13674
  function isServiceComponent2(value) {
13010
13675
  return HOST_RUNTIME_SERVICE_COMPONENTS.some((component) => component === value);
@@ -13020,7 +13685,7 @@ function boundedProcessFailure(result) {
13020
13685
  const detail = result.stderr.trim().slice(0, 1024);
13021
13686
  return detail.length === 0 ? `The Windows service operation exited with code ${result.exit_code}.` : `The Windows service operation failed: ${detail}`;
13022
13687
  }
13023
- function isRecord11(value) {
13688
+ function isRecord12(value) {
13024
13689
  return typeof value === "object" && value !== null && !Array.isArray(value);
13025
13690
  }
13026
13691
  function sameCommand2(left, right) {
@@ -13058,17 +13723,22 @@ function Find-WantedService([string]$component) {
13058
13723
  return $null
13059
13724
  }
13060
13725
 
13061
- function Stop-CealTaskIfRunning($task) {
13062
- if ([int]$task.State -ne 4) { return }
13726
+ function Test-CealTaskActive($task) {
13727
+ # TASK_STATE_QUEUED (2) still owns an instance that may start; READY (3) does not.
13728
+ return [int]$task.State -in 2,4
13729
+ }
13730
+
13731
+ function Stop-CealTaskIfActive($task) {
13732
+ if (-not (Test-CealTaskActive $task)) { return }
13063
13733
  try { $task.Stop(0) }
13064
- catch { if ([int]$task.State -eq 4) { throw } }
13734
+ catch { if (Test-CealTaskActive $task) { throw } }
13065
13735
  }
13066
13736
 
13067
13737
  function Stop-CealTaskAndWait($task, [string]$operation) {
13068
- Stop-CealTaskIfRunning $task
13738
+ Stop-CealTaskIfActive $task
13069
13739
  $stopDeadline = (Get-Date).AddMilliseconds(${WINDOWS_TASK_STOP_WAIT_MS})
13070
- while ([int]$task.State -eq 4 -and (Get-Date) -lt $stopDeadline) { Start-Sleep -Milliseconds ${WINDOWS_TASK_STATE_POLL_INTERVAL_MS} }
13071
- if ([int]$task.State -eq 4) { throw ('The Ceal Host task did not stop before ' + $operation + '.') }
13740
+ while ((Test-CealTaskActive $task) -and (Get-Date) -lt $stopDeadline) { Start-Sleep -Milliseconds ${WINDOWS_TASK_STATE_POLL_INTERVAL_MS} }
13741
+ if (Test-CealTaskActive $task) { throw ('The Ceal Host task did not stop before ' + $operation + '.') }
13072
13742
  }
13073
13743
 
13074
13744
  function Test-CealSid([string]$value) {
@@ -13085,6 +13755,7 @@ function Test-CealDefinition($task, $wanted) {
13085
13755
  $action = $definition.Actions.Item(1)
13086
13756
  $trigger = $definition.Triggers.Item(1)
13087
13757
  if ($action.Type -ne 0 -or [string]$action.Path -cne [string]$wanted.executable -or [string]$action.Arguments -cne [string]$wanted.arguments) { return $false }
13758
+ if ([string]$action.WorkingDirectory -cne [string]$wanted.working_directory) { return $false }
13088
13759
  if ($trigger.Type -ne 9 -or -not $trigger.Enabled -or -not (Test-CealSid ([string]$trigger.UserId))) { return $false }
13089
13760
  if (-not (Test-CealSid ([string]$definition.Principal.UserId)) -or $definition.Principal.LogonType -ne 3 -or $definition.Principal.RunLevel -ne 0) { return $false }
13090
13761
  if (-not $definition.Settings.Enabled -or -not $definition.Settings.StartWhenAvailable -or [string]$definition.Settings.ExecutionTimeLimit -cne 'PT0S' -or $definition.Settings.MultipleInstances -ne 2) { return $false }
@@ -13114,6 +13785,10 @@ function Register-CealTask($wanted) {
13114
13785
  $action = $definition.Actions.Create(0)
13115
13786
  $action.Path = [string]$wanted.executable
13116
13787
  $action.Arguments = [string]$wanted.arguments
13788
+ if ([string]$wanted.working_directory -ne '') {
13789
+ $null = New-Item -ItemType Directory -Force -Path ([string]$wanted.working_directory)
13790
+ $action.WorkingDirectory = [string]$wanted.working_directory
13791
+ }
13117
13792
  return $folder.RegisterTaskDefinition((Get-CealTaskName ([string]$wanted.component)), $definition, 6, $sid, $null, 3, $null)
13118
13793
  }
13119
13794
 
@@ -13132,7 +13807,7 @@ if ([string]$request.operation -ceq 'reconcile') {
13132
13807
  if ($null -ne $task) { Stop-CealTaskAndWait $task 'replacement' }
13133
13808
  $task = Register-CealTask $wanted
13134
13809
  }
13135
- if ($task.State -ne 4) { [void]$task.Run($null) }
13810
+ if (-not (Test-CealTaskActive $task)) { [void]$task.Run($null) }
13136
13811
  }
13137
13812
  @{ schema_version = 'ceal.host_windows_service_result.v1'; ok = $true } | ConvertTo-Json -Compress
13138
13813
  exit 0
@@ -13161,8 +13836,9 @@ if ([string]$request.operation -ceq 'inspect') {
13161
13836
  $wanted = Find-WantedService $component
13162
13837
  $task = Find-CealTask $component
13163
13838
  if ($null -eq $task) { [ordered]@{ component = $component; state = 'absent'; definition_matches = $false }; continue }
13164
- $state = switch ([int]$task.State) { 4 { 'running' } 1 { 'stopped' } 2 { 'stopped' } 3 { 'stopped' } default { 'unknown' } }
13165
- [ordered]@{ component = $component; state = $state; definition_matches = [bool](Test-CealDefinition $task $wanted); last_task_result = [long]$task.LastTaskResult; startup_pending = ([int]$task.State -eq 2) }
13839
+ $taskState = [int]$task.State
13840
+ $state = switch ($taskState) { 4 { 'running' } 1 { 'stopped' } 2 { 'stopped' } 3 { 'stopped' } default { 'unknown' } }
13841
+ [ordered]@{ component = $component; state = $state; definition_matches = [bool](Test-CealDefinition $task $wanted); last_task_result = [long]$task.LastTaskResult; startup_pending = ($taskState -eq 2) }
13166
13842
  }
13167
13843
  [ordered]@{ schema_version = 'ceal.host_windows_service_result.v1'; ok = $true; observations = @($observations) } | ConvertTo-Json -Compress -Depth 5
13168
13844
  exit 0
@@ -13197,11 +13873,11 @@ throw 'Unsupported Windows Host service operation.'
13197
13873
  var WINDOWS_TASK_SCHEDULER_PROGRAM = Buffer.from(TASK_SCHEDULER_SOURCE, "utf16le").toString("base64");
13198
13874
 
13199
13875
  // host/lifecycle/src/host-runtime-windows-process.ts
13200
- import { spawn } from "node:child_process";
13201
- var spawnWindowsHostProcess = (executable, args, options) => spawn(executable, [...args], options);
13876
+ import { spawn as spawn2 } from "node:child_process";
13877
+ var spawnWindowsHostProcess = (executable, args, options) => spawn2(executable, [...args], options);
13202
13878
  function runWindowsHostProcess(invocation, spawnProcess = spawnWindowsHostProcess) {
13203
13879
  return new Promise((resolve) => {
13204
- const child = spawnProcess(invocation.executable, [...invocation.args], { shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
13880
+ const child = spawnProcess(invocation.executable, [...invocation.args], { shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"], cwd: resolveCealSpawnWorkingDirectory() });
13205
13881
  const stdout = [];
13206
13882
  const stderr = [];
13207
13883
  let stdoutBytes = 0;
@@ -13245,7 +13921,7 @@ function runWindowsHostProcess(invocation, spawnProcess = spawnWindowsHostProces
13245
13921
 
13246
13922
  // host/lifecycle/src/host-runtime-systemd.ts
13247
13923
  import { createHash as createHash16, randomUUID as randomUUID2 } from "node:crypto";
13248
- import { lstat as lstat12, mkdir as mkdir11, open as open8, readFile as readFile4, readdir as readdir6, rename as rename7, unlink as unlink10 } from "node:fs/promises";
13924
+ import { lstat as lstat12, mkdir as mkdir11, open as open8, readFile as readFile4, readdir as readdir5, rename as rename7, unlink as unlink10 } from "node:fs/promises";
13249
13925
  import { posix as posix10 } from "node:path";
13250
13926
 
13251
13927
  // scripts/lib/systemd-unit-path.ts
@@ -13355,6 +14031,7 @@ function createLinuxUserSystemdAdapter(options) {
13355
14031
  const unitDirectory = absoluteNormalizedNonRoot(options.unit_directory, "systemd user unit directory");
13356
14032
  const systemctl = absoluteNormalizedNonRoot(options.systemctl_path ?? CEAL_SYSTEMCTL_EXECUTABLE_PATH, "systemctl executable");
13357
14033
  const journalctl = absoluteNormalizedNonRoot(options.journalctl_path ?? DEFAULT_JOURNALCTL_PATH, "journalctl executable");
14034
+ const workingDirectory = options.working_directory === void 0 ? void 0 : absoluteNormalizedNonRoot(options.working_directory, "systemd service working directory");
13358
14035
  const run = options.run;
13359
14036
  return {
13360
14037
  async reconcile({ previous, target }) {
@@ -13365,7 +14042,7 @@ function createLinuxUserSystemdAdapter(options) {
13365
14042
  await ensurePrivateUnitDirectory(unitDirectory);
13366
14043
  if (target.services.length > 0) await refuseForeignCealUnits(unitDirectory, run, systemctl, identity);
13367
14044
  const removableUnits = await ownedHostUnits(unitDirectory, identity);
13368
- for (const service of target.services) await replaceOwnedUnit(unitDirectory, identity, service);
14045
+ for (const service of target.services) await replaceOwnedUnit(unitDirectory, identity, service, workingDirectory);
13369
14046
  for (const unit of removableUnits) {
13370
14047
  if (targetByComponent.has(unit.component)) continue;
13371
14048
  await invokeSystemctl(run, systemctl, ["--user", "disable", "--now", unitName(unit.identity, unit.component)]);
@@ -13444,7 +14121,7 @@ function serviceMap(set) {
13444
14121
  }
13445
14122
  async function ownedHostUnits(directory, identity) {
13446
14123
  const owned = [];
13447
- for (const name of await readdir6(directory)) {
14124
+ for (const name of await readdir5(directory)) {
13448
14125
  const match = CEAL_HOST_UNIT_PATTERN.exec(name);
13449
14126
  if (match === null) continue;
13450
14127
  const unitIdentity = match[1];
@@ -13455,7 +14132,7 @@ async function ownedHostUnits(directory, identity) {
13455
14132
  return owned.sort((left, right) => unitName(left.identity, left.component).localeCompare(unitName(right.identity, right.component)));
13456
14133
  }
13457
14134
  async function refuseForeignCealUnits(directory, run, systemctl, identity) {
13458
- const names = (await readdir6(directory)).sort();
14135
+ const names = (await readdir5(directory)).sort();
13459
14136
  for (const name of names) {
13460
14137
  const parsed = parseCealHostUnit(name);
13461
14138
  if (parsed === void 0 || parsed.identity === identity) continue;
@@ -13499,7 +14176,7 @@ async function listSystemdInstallations(directory, run, systemctl) {
13499
14176
  async function collectCealUnitNames(directory, run, systemctl) {
13500
14177
  let files;
13501
14178
  try {
13502
- files = (await readdir6(directory)).sort();
14179
+ files = (await readdir5(directory)).sort();
13503
14180
  } catch {
13504
14181
  return [];
13505
14182
  }
@@ -13603,13 +14280,13 @@ async function ownedUnitPresent(path, identity, component) {
13603
14280
  } catch (error) {
13604
14281
  if (hasCode(error, "ENOENT")) return false;
13605
14282
  if (isAdapterError(error)) throw error;
13606
- throw projectionError(refusalFact("error", error));
14283
+ throw projectionError(renderOperatorDiagnostic(error));
13607
14284
  }
13608
14285
  }
13609
- async function replaceOwnedUnit(directory, identity, service) {
14286
+ async function replaceOwnedUnit(directory, identity, service, workingDirectory) {
13610
14287
  const destination = unitPath(directory, identity, service.component);
13611
14288
  const temporary = posix10.join(directory, `.${unitName(identity, service.component)}.${randomUUID2()}.tmp`);
13612
- const content = renderUnit(identity, service);
14289
+ const content = renderUnit(identity, service, workingDirectory);
13613
14290
  try {
13614
14291
  const handle = await open8(temporary, "wx", 384);
13615
14292
  try {
@@ -13622,7 +14299,7 @@ async function replaceOwnedUnit(directory, identity, service) {
13622
14299
  await syncDirectory3(directory);
13623
14300
  } catch (error) {
13624
14301
  await unlink10(temporary).catch(() => void 0);
13625
- throw projectionError(refusalFact("error", error));
14302
+ throw projectionError(renderOperatorDiagnostic(error));
13626
14303
  }
13627
14304
  }
13628
14305
  async function removeOwnedUnit(directory, identity, component) {
@@ -13641,7 +14318,7 @@ async function syncDirectory3(directory) {
13641
14318
  await handle.close();
13642
14319
  }
13643
14320
  }
13644
- function renderUnit(identity, service) {
14321
+ function renderUnit(identity, service, workingDirectory) {
13645
14322
  return [
13646
14323
  ownerPreamble(identity, service.component).trimEnd(),
13647
14324
  "[Unit]",
@@ -13653,6 +14330,9 @@ function renderUnit(identity, service) {
13653
14330
  "Type=simple",
13654
14331
  "UMask=0077",
13655
14332
  `ExecStart=${systemdCommandLine(service.command.executable, service.command.args, true)}`,
14333
+ // The service's working directory must never sit inside the prefix
14334
+ // activation swaps; the composed working directory is per-state-root and outside it.
14335
+ ...workingDirectory === void 0 ? [] : [`WorkingDirectory=${workingDirectory}`],
13656
14336
  "Restart=on-failure",
13657
14337
  "RestartSec=3",
13658
14338
  "",
@@ -13769,10 +14449,12 @@ function createInstalledHostRuntimeControlDependencies(options = {}) {
13769
14449
  const environment = options.environment ?? process.env;
13770
14450
  const platform = options.platform ?? process.platform;
13771
14451
  const owner = new InstalledHostRuntimeConfigurationOwner(resolveStateRoot(environment, platform), platform, options.custody ?? {});
14452
+ const codexHome = environmentValue(environment, "CODEX_HOME", platform);
14453
+ const claudeHome = environmentValue(environment, "CLAUDE_CONFIG_DIR", platform);
13772
14454
  const hooks = options.hooks ?? new InstalledHostRuntimeHookAdapter({
13773
- user_home: (platform === "win32" ? environment.USERPROFILE : environment.HOME) ?? homedir5(),
13774
- ...environment.CODEX_HOME === void 0 ? {} : { codex_home: environment.CODEX_HOME },
13775
- ...environment.CLAUDE_CONFIG_DIR === void 0 ? {} : { claude_home: environment.CLAUDE_CONFIG_DIR },
14455
+ user_home: environmentValue(environment, platform === "win32" ? "USERPROFILE" : "HOME", platform) ?? homedir5(),
14456
+ ...codexHome === void 0 ? {} : { codex_home: codexHome },
14457
+ ...claudeHome === void 0 ? {} : { claude_home: claudeHome },
13776
14458
  state_root: owner.stateRoot,
13777
14459
  custody: options.custody,
13778
14460
  config_paths: { codex: owner.configPaths.codex, claude: owner.configPaths.claude }
@@ -13989,7 +14671,7 @@ function platformServiceAdapter(platform, environment, stateRoot, progress) {
13989
14671
  if (platform === "linux") {
13990
14672
  const configRoot = environment.XDG_CONFIG_HOME ?? (environment.HOME === void 0 ? void 0 : posix11.join(environment.HOME, ".config"));
13991
14673
  if (configRoot === void 0) throw platformUnavailable();
13992
- return createLinuxUserSystemdAdapter({ unit_directory: posix11.join(configRoot, "systemd", "user"), run: runSystemctl });
14674
+ return createLinuxUserSystemdAdapter({ unit_directory: posix11.join(configRoot, "systemd", "user"), run: runSystemctl, working_directory: resolveCealSpawnWorkingDirectory(stateRoot) });
13993
14675
  }
13994
14676
  if (platform === "win32") {
13995
14677
  const systemRoot = environmentValue(environment, "SystemRoot", platform);
@@ -14000,7 +14682,7 @@ function platformServiceAdapter(platform, environment, stateRoot, progress) {
14000
14682
  }
14001
14683
  async function runSystemctl(executable, args, options) {
14002
14684
  try {
14003
- const result = await execFileAsync2(executable, [...args], { encoding: "utf8", timeout: options.timeout_ms, maxBuffer: options.max_output_bytes });
14685
+ const result = await execFileAsync2(executable, [...args], { encoding: "utf8", timeout: options.timeout_ms, maxBuffer: options.max_output_bytes, cwd: resolveCealSpawnWorkingDirectory() });
14004
14686
  return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
14005
14687
  } catch (error) {
14006
14688
  return processFailure(error);
@@ -14015,7 +14697,7 @@ function processFailure(error) {
14015
14697
  return { exit_code: code2, stdout, stderr, ...timedOut ? { timed_out: true } : {} };
14016
14698
  }
14017
14699
  function resolveStateRoot(environment, platform) {
14018
- const value = environment[STATE_ROOT_ENVIRONMENT];
14700
+ const value = environmentValue(environment, STATE_ROOT_ENVIRONMENT, platform);
14019
14701
  const path = platform === "win32" ? win3212 : posix11;
14020
14702
  if (value === void 0 || value.length === 0 || value.length > HOST_STATE_ROOT_MAX_CHARACTERS || value.includes("\0") || !path.isAbsolute(value) || path.normalize(value) !== value || path.parse(value).root === value) throw new InstalledHostRuntimeCompositionError("state_root_unavailable", `The Go-owned Host state root is unavailable (${refusalFact("state_root", value, `a normalized absolute non-root path of at most ${HOST_STATE_ROOT_MAX_CHARACTERS} characters`)}).`);
14021
14703
  return value;