@corca-org/ceal-host-win32-x64 1.0.24 → 1.0.26

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.
@@ -2307,6 +2307,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
2307
2307
  // (never connected, revoked, or expired). The caller runs that exact
2308
2308
  // Operation, completes the consent it hands back, and retries the same call.
2309
2309
  "connect_personal_account",
2310
+ // The refusal names the caller's own preferences update step: the read
2311
+ // needs a personal connection the caller holds but has not selected in
2312
+ // Ceal preferences, or has not confirmed through the initial review. The
2313
+ // caller reads personal.preferences.get, runs personal.preferences.update
2314
+ // at the current revision to select it, and retries the same call.
2315
+ "update_personal_preferences",
2310
2316
  // The provider or Gateway named a bounded wait; the caller waits that long
2311
2317
  // and submits the same read again.
2312
2318
  "retry_after",
@@ -2457,7 +2463,7 @@ var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
2457
2463
  var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
2458
2464
  var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
2459
2465
  var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
2460
- var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
2466
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "race_recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
2461
2467
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
2462
2468
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
2463
2469
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -2855,15 +2861,19 @@ function requireIsoTimestamp(value, message) {
2855
2861
  // packages/ceal-client-protocol/src/failure-guidance-table.ts
2856
2862
  var CEAL_FAILURE_REDACTION_CLASSES = vocabulary(["model_safe", "withheld"]);
2857
2863
  var CEAL_GATEWAY_STARTING_FAILURE_CODE = "gateway_starting";
2864
+ var CEAL_GATEWAY_RESTARTING_FAILURE_CODE = "gateway_restarting";
2858
2865
  var CEAL_OWNER_BOOTSTRAP_ABSENT_FAILURE_CODE = "bootstrap_absent";
2859
2866
  var CEAL_OWNER_BOOTSTRAP_UNAVAILABLE_FAILURE_CODE = "bootstrap_unavailable";
2860
2867
  var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
2861
2868
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
2862
2869
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
2863
2870
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
2864
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
2871
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
2872
+ 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}\`.`;
2865
2873
  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.";
2866
- 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.";
2874
+ 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.";
2875
+ var HOST_TRANSCRIPT_UNAVAILABLE = "The Host found no human message in the registered transcript for this turn, so this call has nothing to bind to. Send a new message in the current conversation so the Host re-registers the transcript, then retry the same command. If it still fails, start a new conversation and report intended Host calls as a gap. Host refusal never switches modes.";
2876
+ 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.";
2867
2877
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
2868
2878
  var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
2869
2879
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
@@ -2893,6 +2903,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2893
2903
  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),
2894
2904
  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),
2895
2905
  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),
2906
+ // A stored session that predates the authority-epoch commitment carries no
2907
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
2908
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2896
2909
  refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2897
2910
  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),
2898
2911
  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),
@@ -2914,6 +2927,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2914
2927
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
2915
2928
  // The serving gate answers before refresh execution, so retrying the same attempt is safe.
2916
2929
  [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),
2930
+ // The serving gate answers before execution while the Gateway is stopping, so retrying the same request is safe.
2931
+ [CEAL_GATEWAY_RESTARTING_FAILURE_CODE]: guidance("The Gateway is restarting; the request was not attempted. Retry the same request after the Gateway is serving.", "retry", 503, true),
2917
2932
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
2918
2933
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
2919
2934
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -3017,10 +3032,11 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
3017
3032
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
3018
3033
  // The bounded Host reason does not prove ephemerality. A Host refusal never
3019
3034
  // changes mode; standalone remains the separate Client authority path.
3020
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
3035
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
3021
3036
  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),
3022
3037
  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),
3023
3038
  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),
3039
+ host_transcript_unavailable: guidance(HOST_TRANSCRIPT_UNAVAILABLE, "retry", 401, true),
3024
3040
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
3025
3041
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
3026
3042
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
@@ -3034,7 +3050,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
3034
3050
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
3035
3051
  // sandboxed Relay socket names the run-alone retry.
3036
3052
  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),
3037
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
3053
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
3038
3054
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
3039
3055
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
3040
3056
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -3299,7 +3315,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
3299
3315
  max_literal_nodes: 512
3300
3316
  });
3301
3317
 
3302
- // packages/ceal-client-protocol/src/operation-json-schema.ts
3318
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
3303
3319
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
3304
3320
 
3305
3321
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -3409,6 +3425,8 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
3409
3425
  });
3410
3426
 
3411
3427
  // packages/ceal-client-protocol/src/canonical-http-boundary.ts
3428
+ var CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE = "^client-exchange:[a-f0-9]{32}$";
3429
+ var CEAL_HTTP_GATEWAY_REQUEST_REF_PATTERN_SOURCE = "^http-request:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
3412
3430
  var CEAL_CANONICAL_HTTP_MAX_RESPONSE_BYTES = CEAL_COMMAND_RESPONSE_MAX_BYTES;
3413
3431
 
3414
3432
  // packages/ceal-client-protocol/src/gateway-installation-activation.ts
@@ -3433,6 +3451,7 @@ var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUI
3433
3451
  var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
3434
3452
 
3435
3453
  // packages/ceal-client-protocol/src/resource-read-result.ts
3454
+ var CEAL_RESOURCE_GET_CHILD_REF_KINDS = Object.freeze(["section", "slide", "question"]);
3436
3455
  var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
3437
3456
  var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
3438
3457
  var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
@@ -3449,7 +3468,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
3449
3468
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
3450
3469
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
3451
3470
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
3452
- 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.`;
3471
+ 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.`;
3472
+ 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.`;
3453
3473
  function shellSingleQuoted(value) {
3454
3474
  return `'${value.replaceAll("'", "'\\''")}'`;
3455
3475
  }
@@ -3635,6 +3655,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3635
3655
  "github.review.submitted",
3636
3656
  "github.issue_comment.created",
3637
3657
  "github.review_comment.created",
3658
+ "github.issue_comment.edited",
3659
+ "github.review_comment.edited",
3638
3660
  "github.reaction.created",
3639
3661
  "github.reaction.deleted",
3640
3662
  "github.pull_request.review_requested",
@@ -3663,6 +3685,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3663
3685
  "github.release.published": "release_published",
3664
3686
  "github.issue.edited": "resource_modified",
3665
3687
  "github.pull_request.edited": "resource_modified",
3688
+ "github.issue_comment.edited": "resource_modified",
3689
+ "github.review_comment.edited": "resource_modified",
3666
3690
  "github.reaction.created": "reaction_created",
3667
3691
  "github.reaction.deleted": "ceal_write_completed",
3668
3692
  "github.pull_request.review_requested": "ceal_write_completed",
@@ -4325,6 +4349,8 @@ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
4325
4349
  var HOST_CONTEXT_EXPIRY_MAX_CHARS = 64;
4326
4350
  var CEAL_HOST_INVOCATION_CONTEXT_VISIBLE_OUTPUT_MAX_BYTES = CEAL_CANONICAL_HTTP_MAX_RESPONSE_BYTES;
4327
4351
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
4352
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_ENTRY_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text", "text_truncated"]);
4353
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_REQUIRED_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text"]);
4328
4354
  function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
4329
4355
  const messages = [];
4330
4356
  let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
@@ -4456,6 +4482,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
4456
4482
  "context_replaced",
4457
4483
  "no_binding",
4458
4484
  "context_expired",
4485
+ "transcript_unavailable",
4459
4486
  "host_source_refused",
4460
4487
  "host_credential_refused",
4461
4488
  "gateway_unavailable",
@@ -4485,9 +4512,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
4485
4512
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
4486
4513
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
4487
4514
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
4488
- // This reason cannot distinguish a Codex side conversation from a missing
4489
- // context in a regular session, so guidance must leave that choice to the caller.
4490
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
4515
+ // A missing turn right after a Host restart clears by itself once the
4516
+ // watcher reactivates the turn, so the caller waits briefly and retries;
4517
+ // a caller that knows it is in an ephemeral side conversation keeps the
4518
+ // standalone fallback the guidance names second.
4519
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
4491
4520
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
4492
4521
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
4493
4522
  // `no_binding` now means the producer has no real current Host session. The
@@ -4495,6 +4524,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
4495
4524
  // useful retry until the consumer is running inside a Host session.
4496
4525
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
4497
4526
  context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
4527
+ // The registered transcript is readable but names no human message for
4528
+ // this turn, so a Gateway mint could only be refused. The caller sends a
4529
+ // new message so the turn hook re-registers the transcript, then retries;
4530
+ // a retry with no new turn cannot bind anything new.
4531
+ transcript_unavailable: Object.freeze({ classification: "host_transcript_unavailable", next_action: "retry" }),
4498
4532
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
4499
4533
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
4500
4534
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
@@ -4504,7 +4538,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
4504
4538
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
4505
4539
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
4506
4540
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
4507
- 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" }),
4508
4542
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
4509
4543
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
4510
4544
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -4631,11 +4665,15 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
4631
4665
 
4632
4666
  // packages/ceal-client-protocol/src/operator-diagnostic.ts
4633
4667
  var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
4634
- var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
4668
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES = 8;
4635
4669
  var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
4636
4670
  var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
4637
4671
  var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
4638
4672
  var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
4673
+ var LOCAL_OPERATOR_DIAGNOSTIC_PATHS = /* @__PURE__ */ Symbol.for("ceal.local-operator-diagnostic-paths");
4674
+ var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX = /(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)/u;
4675
+ var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START = new RegExp(`^${OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX.source}`, "u");
4676
+ var OPERATOR_DIAGNOSTIC_FREEFORM_PATH_PATTERN = new RegExp(String.raw`(?<![A-Za-z0-9._-]|\[home path redacted\])${OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX.source}((?:(?!; stdout=|; stderr=)[^:\r\n"'<>])*?)( exited \d+)?(?=; stdout=|; stderr=|:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])`, "gu");
4639
4677
  function redactOperatorDiagnosticSecrets(value) {
4640
4678
  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]");
4641
4679
  }
@@ -4644,8 +4682,9 @@ function redactOperatorDiagnosticText(value) {
4644
4682
  return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
4645
4683
  }
4646
4684
  function renderOperatorDiagnostic(value) {
4647
- const state = collectDiagnosticState(value);
4685
+ const state = collectDiagnosticState(value, read(value, LOCAL_OPERATOR_DIAGNOSTIC_PATHS) === true);
4648
4686
  const fields = [
4687
+ state.truncated ? "causes_truncated=true" : void 0,
4649
4688
  state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
4650
4689
  state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
4651
4690
  state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
@@ -4655,23 +4694,27 @@ function renderOperatorDiagnostic(value) {
4655
4694
  const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
4656
4695
  return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
4657
4696
  }
4658
- function collectDiagnosticState(value) {
4659
- const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
4697
+ function collectDiagnosticState(value, preserveLocalAbsolutePaths) {
4698
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0, truncated: false };
4660
4699
  const visited = /* @__PURE__ */ new Set(), pending = [value];
4661
- while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
4700
+ let inspected = 0;
4701
+ while (pending.length > 0 && inspected < OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES) {
4662
4702
  const current = pending.shift();
4663
- if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
4703
+ if (current === void 0 || isObject(current) && visited.has(current)) continue;
4704
+ inspected += 1;
4705
+ visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths);
4664
4706
  }
4707
+ state.truncated ||= pending.length > 0;
4665
4708
  return state;
4666
4709
  }
4667
- function visitDiagnosticNode(current, state, pending, visited) {
4710
+ function visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths) {
4668
4711
  if (isObject(current)) {
4669
4712
  if (visited.has(current)) return;
4670
4713
  visited.add(current);
4671
4714
  }
4672
4715
  captureProcessEvidence(current, state);
4673
- appendCause(current, state.causes);
4674
- enqueueCauseChildren(current, state.causes.length, pending);
4716
+ appendCause(current, state.causes, preserveLocalAbsolutePaths);
4717
+ enqueueCauseChildren(current, state, pending);
4675
4718
  }
4676
4719
  function captureProcessEvidence(current, state) {
4677
4720
  if (state.status === void 0) state.status = safeStatus(read(current, "status"));
@@ -4679,10 +4722,9 @@ function captureProcessEvidence(current, state) {
4679
4722
  if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
4680
4723
  if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
4681
4724
  }
4682
- function appendCause(current, causes) {
4683
- const errors = read(current, "errors");
4684
- if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
4685
- causes.push(errorCause(current));
4725
+ function appendCause(current, causes, preserveLocalAbsolutePaths) {
4726
+ if (current instanceof Error) {
4727
+ causes.push(errorCause(current, preserveLocalAbsolutePaths));
4686
4728
  return;
4687
4729
  }
4688
4730
  if (!isObject(current)) {
@@ -4690,7 +4732,7 @@ function appendCause(current, causes) {
4690
4732
  if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
4691
4733
  }
4692
4734
  }
4693
- function errorCause(error) {
4735
+ function errorCause(error, preserveLocalAbsolutePaths) {
4694
4736
  const name = safeText(read(error, "name")) ?? "Error";
4695
4737
  const message = safeText(read(error, "message"));
4696
4738
  const codeValue = read(error, "code");
@@ -4698,14 +4740,29 @@ function errorCause(error) {
4698
4740
  const errnoValue = read(error, "errno");
4699
4741
  const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
4700
4742
  const syscall = safeText(read(error, "syscall"));
4701
- const path = safePath(read(error, "path"));
4743
+ const path = safePath(read(error, "path"), preserveLocalAbsolutePaths);
4702
4744
  return Object.freeze({ error_class: name, ...message === void 0 ? {} : { message }, ...code === void 0 ? {} : { code }, ...errno === void 0 ? {} : { errno }, ...syscall === void 0 ? {} : { syscall }, ...path === void 0 ? {} : { path } });
4703
4745
  }
4704
- function enqueueCauseChildren(current, causeCount, pending) {
4746
+ function enqueueCauseChildren(current, state, pending) {
4705
4747
  const cause = read(current, "cause");
4706
4748
  if (cause !== void 0) pending.push(cause);
4707
4749
  const errors = read(current, "errors");
4708
- if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
4750
+ if (Array.isArray(errors)) {
4751
+ const remaining = OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES - state.causes.length;
4752
+ const length = read(errors, "length");
4753
+ if (typeof length !== "number") {
4754
+ state.truncated = true;
4755
+ return;
4756
+ }
4757
+ state.truncated ||= length > remaining;
4758
+ for (let index = 0; index < Math.min(length, remaining); index += 1) {
4759
+ try {
4760
+ pending.push(errors[index]);
4761
+ } catch {
4762
+ state.truncated = true;
4763
+ }
4764
+ }
4765
+ }
4709
4766
  }
4710
4767
  function isObject(value) {
4711
4768
  return typeof value === "object" && value !== null;
@@ -4734,10 +4791,11 @@ function safeText(value) {
4734
4791
  const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
4735
4792
  return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4736
4793
  }
4737
- function safePath(value) {
4794
+ function safePath(value, preserveLocalAbsolutePaths) {
4738
4795
  if (typeof value !== "string") return void 0;
4739
4796
  const safe = safeDiagnosticText(value);
4740
4797
  if (safe.length === 0) return void 0;
4798
+ if (!preserveLocalAbsolutePaths && hasAbsolutePathPrefix(value) && !safe.startsWith("[home path redacted]")) return "[path redacted]";
4741
4799
  if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
4742
4800
  const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
4743
4801
  const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
@@ -4809,7 +4867,10 @@ function redactUrls(value) {
4809
4867
  return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
4810
4868
  }
4811
4869
  function redactFilePaths(value) {
4812
- return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
4870
+ return value.replaceAll(OPERATOR_DIAGNOSTIC_FREEFORM_PATH_PATTERN, "[path redacted]$2");
4871
+ }
4872
+ function hasAbsolutePathPrefix(value) {
4873
+ return OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START.test(value);
4813
4874
  }
4814
4875
  function homePathRange(value, match, prefixLength) {
4815
4876
  const index = match.index;
@@ -4988,10 +5049,9 @@ function hostClientProbeRefusal(probe, subject) {
4988
5049
  }
4989
5050
 
4990
5051
  // host/client-doctor.ts
4991
- import { createHash as createHash4 } from "node:crypto";
4992
- import { execFile } from "node:child_process";
4993
- import { access, open, readFile, realpath, stat } from "node:fs/promises";
4994
- import { delimiter, extname, isAbsolute, join as join2 } from "node:path";
5052
+ import { execFile as execFile2 } from "node:child_process";
5053
+ import { access, open as open2, realpath, stat } from "node:fs/promises";
5054
+ import { delimiter, extname, isAbsolute as isAbsolute2, join as join4 } from "node:path";
4995
5055
  import { promisify } from "node:util";
4996
5056
 
4997
5057
  // host/environment.ts
@@ -5010,7 +5070,7 @@ var WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET = "A-Za-z0-9._=-";
5010
5070
  var WINDOWS_FIXED_CMD_ARGUMENT_REFUSAL_PATTERN = `[^${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]`;
5011
5071
  var WINDOWS_FIXED_CMD_ARGUMENT = new RegExp(`^[${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]+$`, "u");
5012
5072
  function validateHostCommandVector(vector, windowsConsumer = "cmd") {
5013
- if (typeof vector.executable !== "string" || invalidText(vector.executable)) throw new TypeError(`Host command vector executable is invalid (${refusalFact("executable_kind", typeof vector.executable, "non-empty text without a NUL, newline or control character")}).`);
5073
+ if (typeof vector.executable !== "string" || vector.executable === "" || invalidText(vector.executable)) throw new TypeError(`Host command vector executable is invalid (${refusalFact("executable_kind", typeof vector.executable, "non-empty text without a NUL, newline or control character")}).`);
5014
5074
  if (vector.args.length > HOST_COMMAND_ARGUMENT_MAX) throw new TypeError(`Host command vector has too many arguments (${refusalFact("argument_count", vector.args.length, `at most ${HOST_COMMAND_ARGUMENT_MAX}`)}).`);
5015
5075
  const offending = vector.args.findIndex((argument) => typeof argument !== "string" || invalidText(argument));
5016
5076
  if (offending >= 0) throw new TypeError(`Host command vector argument is invalid (${refusalFact("argument_index", offending, "no argument with a NUL, newline or control character")}).`);
@@ -5073,8 +5133,329 @@ function quoteWindowsExecArgument(value) {
5073
5133
  return `"${escaped}"`;
5074
5134
  }
5075
5135
 
5136
+ // host/lifecycle/src/host-bundle-manifest.ts
5137
+ import { createHash as createHash4 } from "node:crypto";
5138
+
5139
+ // host/secure-file.ts
5140
+ import { execFile } from "node:child_process";
5141
+ import { constants } from "node:fs";
5142
+ import { lstat, open } from "node:fs/promises";
5143
+ import { dirname, join as join2, parse, win32 as win322 } from "node:path";
5144
+ import { fileURLToPath } from "node:url";
5145
+ var SecureFileCustodyError = class extends Error {
5146
+ name = "SecureFileCustodyError";
5147
+ reason;
5148
+ constructor(reason, message) {
5149
+ super(message);
5150
+ this.reason = reason;
5151
+ }
5152
+ get code() {
5153
+ if (this.reason === "reparse_point") return "ELOOP";
5154
+ if (this.reason === "not_found") return "ENOENT";
5155
+ if (this.reason === "too_large") return "secure_file_too_large";
5156
+ if (this.reason === "already_exists") return "EEXIST";
5157
+ return this.reason === "not_private" ? "secure_file_not_private" : "secure_file_unavailable";
5158
+ }
5159
+ };
5160
+ var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
5161
+ var WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES = 4096;
5162
+ var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
5163
+ var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
5164
+ var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
5165
+ function secureOpenFlags(flags, platform) {
5166
+ if (platform === "win32") return flags;
5167
+ const nofollow = constants.O_NOFOLLOW;
5168
+ if (typeof nofollow === "number" && nofollow !== 0) return flags | nofollow;
5169
+ throw new Error("Secure file reads require O_NOFOLLOW on this platform.");
5170
+ }
5171
+ async function openNoFollow(path, flags = constants.O_RDONLY, mode, platform = process.platform, _custody = {}) {
5172
+ if (platform !== "win32") return await open(path, secureOpenFlags(flags, platform), mode);
5173
+ return await openWindowsIdentityScreened(path, flags, mode);
5174
+ }
5175
+ async function openWindowsIdentityScreened(path, flags, mode) {
5176
+ const handle = await open(path, flags, mode);
5177
+ try {
5178
+ const first = await handle.stat();
5179
+ if (!first.isFile()) throw new SecureFileCustodyError("not_private", "The Windows Host file is not a regular file.");
5180
+ await assertWindowsLinkFree(path, first);
5181
+ await assertWindowsIdentityStable(handle, first, path);
5182
+ return handle;
5183
+ } catch (error) {
5184
+ await handle.close();
5185
+ throw error;
5186
+ }
5187
+ }
5188
+ async function assertWindowsLinkFree(path, first) {
5189
+ const entry = await lstat(path);
5190
+ if (entry.isSymbolicLink() || entry.dev !== first.dev || entry.ino !== first.ino) {
5191
+ throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
5192
+ }
5193
+ }
5194
+ async function assertWindowsIdentityStable(handle, first, path) {
5195
+ const second = await handle.stat();
5196
+ if (second.dev !== first.dev || second.ino !== first.ino || second.size !== first.size || second.mtimeMs !== first.mtimeMs) {
5197
+ throw new SecureFileCustodyError("unavailable", "The Windows Host file changed while its identity was checked.");
5198
+ }
5199
+ const entry = await lstat(path);
5200
+ if (entry.isSymbolicLink()) throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
5201
+ if (entry.dev !== second.dev || entry.ino !== second.ino) throw new SecureFileCustodyError("unavailable", "The Windows Host file path no longer names the opened file.");
5202
+ }
5203
+ async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
5204
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
5205
+ const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
5206
+ if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
5207
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
5208
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
5209
+ throw securefsRefusal(result.stderr);
5210
+ }
5211
+ async function createRandomPrivateFileWithSecurefs(path, byteLength2, custody = {}) {
5212
+ if (!Number.isSafeInteger(byteLength2) || byteLength2 < 1 || byteLength2 > WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES) throw new TypeError(`The securefs random-file size must be between 1 and ${WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES} bytes.`);
5213
+ const result = await runSecurefsCommand(["internal", "securefs", "create-random-private-file", path, String(byteLength2)], 0, custody);
5214
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5215
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned unexpected creation bytes.");
5216
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid creation result.");
5217
+ throw securefsRefusal(result.stderr);
5218
+ }
5219
+ async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
5220
+ const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
5221
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5222
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
5223
+ throw securefsRefusal(result.stderr);
5224
+ }
5225
+ async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
5226
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > WINDOWS_SECUREFS_MAX_WRITE_BYTES || bytes.byteLength > maxBytes) throw new TypeError("The securefs write bound or payload is invalid.");
5227
+ const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
5228
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5229
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
5230
+ throw securefsRefusal(result.stderr);
5231
+ }
5232
+ async function isPrivateWindowsDirectory(path, custody = {}) {
5233
+ await lstat(path);
5234
+ try {
5235
+ const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
5236
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
5237
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
5238
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
5239
+ const refusal = securefsRefusal(result.stderr);
5240
+ if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
5241
+ throw refusal;
5242
+ } catch (error) {
5243
+ if (error instanceof SecureFileCustodyError) throw error;
5244
+ throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
5245
+ }
5246
+ }
5247
+ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
5248
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
5249
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
5250
+ const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
5251
+ return await new Promise((resolve, reject2) => {
5252
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: parse(executable).root }, (error, stdout, stderr) => {
5253
+ const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
5254
+ if (exitCode === null) {
5255
+ reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
5256
+ return;
5257
+ }
5258
+ resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
5259
+ });
5260
+ child.stdin?.on("error", () => void 0);
5261
+ child.stdin?.end(stdin);
5262
+ });
5263
+ }
5264
+ function securefsRefusal(stderr) {
5265
+ let value;
5266
+ try {
5267
+ value = JSON.parse(stderr.toString("utf8"));
5268
+ } catch {
5269
+ return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
5270
+ }
5271
+ if (!isRecord(value) || value.schema_version !== WINDOWS_SECUREFS_REFUSAL_SCHEMA || typeof value.code !== "string") return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
5272
+ if (value.code === "reparse_point") return new SecureFileCustodyError("reparse_point", "The Windows Host securefs file is a reparse point.");
5273
+ if (value.code === "not_found") return new SecureFileCustodyError("not_found", "The Windows Host securefs file was not found.");
5274
+ if (value.code === "too_large") return new SecureFileCustodyError("too_large", "The Windows Host securefs file exceeds its read bound.");
5275
+ if (value.code === "already_exists") return new SecureFileCustodyError("already_exists", "The Windows Host securefs target already exists.");
5276
+ if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
5277
+ return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
5278
+ }
5279
+ function resolveInstalledHostExecutable(platform) {
5280
+ const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
5281
+ return platform === "win32" ? win322.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
5282
+ }
5283
+ function isRecord(value) {
5284
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5285
+ }
5286
+ function isOwnedBy(uid, expectedUid) {
5287
+ return Number.isSafeInteger(uid) && Number.isSafeInteger(expectedUid) && uid === expectedUid;
5288
+ }
5289
+ function isSelfOwned(uid, platform = process.platform, _handle) {
5290
+ if (platform === "win32" || typeof process.geteuid !== "function") return false;
5291
+ return isOwnedBy(uid, process.geteuid());
5292
+ }
5293
+ function isPrivateFileMode(mode, platform = process.platform, _handle) {
5294
+ if (platform === "win32") return false;
5295
+ return (mode & 63) === 0;
5296
+ }
5297
+ async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
5298
+ if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
5299
+ const entry = await lstat(path);
5300
+ return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
5301
+ }
5302
+
5303
+ // host/lifecycle/src/host-bundle-manifest.ts
5304
+ var HOST_BUNDLE_MAX_SELECTED_BYTES = 256 * 1024 * 1024;
5305
+ var HOST_BUNDLE_MAX_SIGSTORE_BYTES = 16 * 1024 * 1024;
5306
+ var HOST_BUNDLE_TARGETS = Object.freeze(["linux-x64", "linux-arm64", "darwin-arm64", "windows-x64"]);
5307
+ var HOST_BUNDLE_COMPONENTS = Object.freeze(["lifecycle", "relay", "codex", "claude"]);
5308
+ var HOST_BUNDLE_PRODUCERS = Object.freeze(["codex", "claude"]);
5309
+ var HOST_RUNTIME_COMPONENTS = Object.freeze(["relay", "codex", "claude"]);
5310
+ var HOST_BUNDLE_PRIVATE_RUNTIME_ROOT = "libexec/ceal-host";
5311
+ var HOST_WINDOWS_BACKGROUND_RELATIVE_PATH = `${HOST_BUNDLE_PRIVATE_RUNTIME_ROOT}/ceal-host-background.exe`;
5312
+ var HOST_BUNDLE_FILE_KEYS = Object.freeze(["executable", "owners", "path", "sha256"]);
5313
+ var HOST_BUNDLE_SUPPORTED_REQUIRED_FEATURES = Object.freeze([]);
5314
+ var HOST_BUNDLE_REFERENCE_STATUS = Object.freeze({ authority: "non_authoritative", transaction: "incomplete" });
5315
+ async function digestOpenHandleSha256(handle) {
5316
+ const hash = createHash4("sha256");
5317
+ let bytes = 0;
5318
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
5319
+ bytes += chunk.length;
5320
+ hash.update(chunk);
5321
+ }
5322
+ return { sha256: hash.digest("hex"), bytes };
5323
+ }
5324
+ async function digestFileSha256(path) {
5325
+ let handle;
5326
+ try {
5327
+ handle = await openNoFollow(path);
5328
+ return await digestOpenHandleSha256(handle);
5329
+ } finally {
5330
+ await handle?.close().catch(() => void 0);
5331
+ }
5332
+ }
5333
+
5334
+ // host/spawn-working-directory.ts
5335
+ import { lstatSync, mkdirSync, realpathSync } from "node:fs";
5336
+ import { tmpdir } from "node:os";
5337
+ import { basename, dirname as dirname2, isAbsolute, join as join3, normalize, parse as parse2, sep } from "node:path";
5338
+ function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
5339
+ const candidates = [];
5340
+ const explicit = candidateDir(stateRoot);
5341
+ if (explicit !== void 0) candidates.push(explicit);
5342
+ const fallback = defaultHostStateRoot();
5343
+ if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
5344
+ const temporary = candidateDir(join3(tmpdir(), "ceal-spawn-cwd"));
5345
+ if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
5346
+ const usable = firstKeptOutside(candidates, keepOutside);
5347
+ if (usable.directory !== void 0) return usable.directory;
5348
+ const osFallback = candidateDir(tmpdir());
5349
+ if (osFallback !== void 0 && keptOutside(osFallback, keepOutside)) return osFallback;
5350
+ throw new SpawnWorkingDirectoryRefusedError(keepOutside, usable.lastCreationError);
5351
+ }
5352
+ function firstKeptOutside(candidates, keepOutside) {
5353
+ let lastCreationError;
5354
+ for (const dir of candidates) {
5355
+ if (!keptOutside(dir, keepOutside)) continue;
5356
+ try {
5357
+ mkdirSync(dir, { recursive: true, mode: 448 });
5358
+ return { directory: dir };
5359
+ } catch (error) {
5360
+ lastCreationError = error;
5361
+ }
5362
+ }
5363
+ return { lastCreationError };
5364
+ }
5365
+ var SpawnWorkingDirectoryRefusedError = class extends Error {
5366
+ avoided;
5367
+ constructor(keepOutside, lastCreationError) {
5368
+ super(lastCreationError === void 0 ? `spawn working directory: every candidate lies inside avoided tree(s) ${JSON.stringify(keepOutside.join(", "))}; refusing a working directory that would block the activation rename` : `spawn working directory: no usable candidate; last creation error: ${lastCreationError instanceof Error ? lastCreationError.message : String(lastCreationError)}`, { cause: lastCreationError });
5369
+ this.name = "SpawnWorkingDirectoryRefusedError";
5370
+ this.avoided = [...keepOutside];
5371
+ }
5372
+ };
5373
+ function candidateDir(dir) {
5374
+ if (dir === void 0 || dir === "") return void 0;
5375
+ if (!isAbsolute(dir) || normalize(dir) !== dir || parse2(dir).root === dir) return void 0;
5376
+ return normalize(dir);
5377
+ }
5378
+ function defaultHostStateRoot() {
5379
+ if (process.platform === "win32") {
5380
+ const localAppData = nonEmptyEnv("LOCALAPPDATA");
5381
+ if (localAppData === void 0) return void 0;
5382
+ return candidateDir(join3(localAppData, "Ceal", "Host"));
5383
+ }
5384
+ if (process.platform === "darwin") {
5385
+ const home2 = nonEmptyEnv("HOME");
5386
+ if (home2 === void 0) return void 0;
5387
+ return candidateDir(join3(home2, "Library", "Application Support", "Ceal", "Host"));
5388
+ }
5389
+ const xdg = nonEmptyEnv("XDG_STATE_HOME");
5390
+ if (xdg !== void 0) {
5391
+ const root = candidateDir(join3(xdg, "ceal", "host"));
5392
+ if (root !== void 0) return root;
5393
+ }
5394
+ const home = nonEmptyEnv("HOME");
5395
+ if (home === void 0) return void 0;
5396
+ return candidateDir(join3(home, ".local", "state", "ceal", "host"));
5397
+ }
5398
+ function nonEmptyEnv(name) {
5399
+ const value = process.env[name];
5400
+ return value === void 0 || value === "" ? void 0 : value;
5401
+ }
5402
+ function keptOutside(dir, keepOutside) {
5403
+ const resolvedDir = resolveExistingPrefix(dir);
5404
+ if (resolvedDir === void 0) return false;
5405
+ for (const tree of keepOutside) {
5406
+ const clean = candidateDir(tree);
5407
+ if (clean === void 0) continue;
5408
+ const resolvedTree = resolveExistingPrefix(clean);
5409
+ if (resolvedTree === void 0) return false;
5410
+ if (insideDir(resolvedDir, resolvedTree)) return false;
5411
+ }
5412
+ return true;
5413
+ }
5414
+ function isMissingError(error) {
5415
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
5416
+ }
5417
+ function resolveExistingPrefix(path) {
5418
+ let probe = normalize(path);
5419
+ const missing = [];
5420
+ for (; ; ) {
5421
+ let exists = false;
5422
+ try {
5423
+ lstatSync(probe);
5424
+ exists = true;
5425
+ } catch (error) {
5426
+ if (!isMissingError(error)) return void 0;
5427
+ }
5428
+ if (exists) {
5429
+ let resolved;
5430
+ try {
5431
+ resolved = realpathSync.native(probe);
5432
+ } catch {
5433
+ return void 0;
5434
+ }
5435
+ for (let index = missing.length - 1; index >= 0; index -= 1) {
5436
+ const segment = missing[index];
5437
+ if (segment !== void 0) resolved = join3(resolved, segment);
5438
+ }
5439
+ return normalize(resolved);
5440
+ }
5441
+ const parent = dirname2(probe);
5442
+ if (parent === probe) return void 0;
5443
+ missing.push(basename(probe));
5444
+ probe = parent;
5445
+ }
5446
+ }
5447
+ function insideDir(dir, tree) {
5448
+ if (sameDir(dir, tree)) return true;
5449
+ if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
5450
+ return dir.startsWith(tree + sep);
5451
+ }
5452
+ function sameDir(left, right) {
5453
+ if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
5454
+ return left === right;
5455
+ }
5456
+
5076
5457
  // host/client-doctor.ts
5077
- var execFileAsync = promisify(execFile);
5458
+ var execFileAsync = promisify(execFile2);
5078
5459
  var GIT_OID = /^[a-f0-9]{40}$/u;
5079
5460
  var SHA2562 = /^[a-f0-9]{64}$/u;
5080
5461
  var SAFE_REF2 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
@@ -5158,8 +5539,8 @@ async function resolveCealExecutable(command, environment, platform = process.pl
5158
5539
  if (!metadata.isFile()) continue;
5159
5540
  const launcherKind = await inspectLauncherKind(path);
5160
5541
  if (launcherKind !== void 0) return resolveLauncherBinary(path, launcherKind, environment, platform);
5161
- if (platform === "win32" && !isAbsolute(command) && extname(path) === "") continue;
5162
- return { path, sha256: createHash4("sha256").update(await readFile(path)).digest("hex") };
5542
+ if (platform === "win32" && !isAbsolute2(command) && extname(path) === "") continue;
5543
+ return { path, sha256: (await digestFileSha256(path)).sha256 };
5163
5544
  } catch {
5164
5545
  }
5165
5546
  }
@@ -5169,7 +5550,7 @@ async function inspectLauncherKind(path) {
5169
5550
  if (/\.(?:cjs|js|mjs)$/iu.test(path)) return "node";
5170
5551
  if (/\.(?:bat|cmd)$/iu.test(path)) return "cmd";
5171
5552
  if (/\.ps1$/iu.test(path)) return "powershell";
5172
- const handle = await open(path, "r");
5553
+ const handle = await open2(path, "r");
5173
5554
  try {
5174
5555
  const buffer = Buffer.alloc(128);
5175
5556
  const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, 0);
@@ -5181,266 +5562,96 @@ async function inspectLauncherKind(path) {
5181
5562
  }
5182
5563
  async function resolveLauncherBinary(launcherPath, kind, environment, platform) {
5183
5564
  const invocation = hostScriptLauncherInvocation(launcherPath, CEAL_CLIENT_DOCTOR_COMMAND, kind, platform, environment);
5184
- const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
5565
+ const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, cwd: resolveCealSpawnWorkingDirectory(), ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
5185
5566
  let parsed;
5186
5567
  try {
5187
5568
  parsed = JSON.parse(result.stdout);
5188
5569
  } catch {
5189
5570
  throw new Error("launcher doctor returned unreadable output");
5190
5571
  }
5191
- if (!isRecord(parsed) || parsed.schema_version !== CEAL_CLIENT_DOCTOR_SCHEMA_VERSION || parsed.ok !== true || typeof parsed.binary_path !== "string" || parsed.binary_path.length === 0) throw new Error("launcher doctor did not report a binary path");
5572
+ if (!isRecord2(parsed) || parsed.schema_version !== CEAL_CLIENT_DOCTOR_SCHEMA_VERSION || parsed.ok !== true || typeof parsed.binary_path !== "string" || parsed.binary_path.length === 0) throw new Error("launcher doctor did not report a binary path");
5192
5573
  const binaryPath = await realpath(parsed.binary_path);
5193
5574
  const metadata = await stat(binaryPath);
5194
- if (!metadata.isFile()) throw new Error("launcher doctor reported a non-file binary path");
5195
- return { path: binaryPath, sha256: createHash4("sha256").update(await readFile(binaryPath)).digest("hex") };
5196
- }
5197
- function executableCandidates(command, environment, platform) {
5198
- if (isAbsolute(command)) return [command];
5199
- const pathValue = environmentValue(environment, "PATH", platform) ?? "";
5200
- const directories = pathValue.split(delimiter).filter((entry) => entry.length > 0);
5201
- if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join2(entry, command));
5202
- return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join2(entry, `${command}${suffix}`)));
5203
- }
5204
- async function executeCealCommand(executable, args, environment) {
5205
- try {
5206
- const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8" });
5207
- return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
5208
- } catch (error) {
5209
- if (isRecord(error)) return { exit_code: typeof error.code === "number" ? error.code : 1, stdout: typeof error.stdout === "string" ? error.stdout : "", stderr: typeof error.stderr === "string" ? error.stderr : "" };
5210
- throw error;
5211
- }
5212
- }
5213
- function safeRun(run, executable, args, environment) {
5214
- return run(executable, args, environment).catch(() => null);
5215
- }
5216
- function commandDocument(result) {
5217
- if (result === null) return null;
5218
- try {
5219
- const value = JSON.parse(result.stdout);
5220
- return isRecord(value) ? value : null;
5221
- } catch {
5222
- return null;
5223
- }
5224
- }
5225
- function selectedContext(value) {
5226
- if (value?.schema_version !== "ceal.access-group.v1" || value.ok !== true || !Array.isArray(value.contexts)) return null;
5227
- const selected = value.contexts.filter((item) => isRecord(item) && item.selected === true);
5228
- if (selected.length !== 1) return null;
5229
- return selectedContextRecord(selected[0]);
5230
- }
5231
- function selectedContextRecord(item) {
5232
- if (!isRecord(item) || typeof item.name !== "string" || typeof item.instance_ref !== "string") return null;
5233
- if (!SAFE_REF2.test(item.instance_ref)) return null;
5234
- return { name: item.name, instance_ref: item.instance_ref };
5235
- }
5236
- function versionIdentity(value) {
5237
- if (value?.schema_version !== CEAL_CLIENT_VERSION_SCHEMA_VERSION || value.ok !== true || typeof value.version !== "string" || typeof value.source_commit !== "string" || typeof value.source_tree !== "string") return null;
5238
- if (value.version.length === 0 || !GIT_OID.test(value.source_commit) || !GIT_OID.test(value.source_tree)) return null;
5239
- return { version: value.version, source_commit: value.source_commit, source_tree: value.source_tree };
5240
- }
5241
- function validExpectations(options) {
5242
- return (options.expected_sha256 === void 0 || SHA2562.test(options.expected_sha256)) && (options.expected_source_commit === void 0 || GIT_OID.test(options.expected_source_commit)) && (options.expected_instance_ref === void 0 || SAFE_REF2.test(options.expected_instance_ref));
5243
- }
5244
- function failure(code, message, next_action) {
5245
- return { ok: false, status: "failure", error: { code, message, next_action } };
5246
- }
5247
- function isRecord(value) {
5248
- return value !== null && typeof value === "object" && !Array.isArray(value);
5249
- }
5250
-
5251
- // host/codex/src/codex-client-doctor.ts
5252
- var CODEX_CLIENT_DOCTOR_SCHEMA_VERSION = "ceal.codex_client_doctor.v1";
5253
- async function doctorCodexClient(options = {}) {
5254
- return { schema_version: CODEX_CLIENT_DOCTOR_SCHEMA_VERSION, ...await doctorClient(options, "Codex") };
5255
- }
5256
-
5257
- // host/invocation-authentication-command.ts
5258
- import { performance } from "node:perf_hooks";
5259
-
5260
- // host/relay/src/producer-frame.ts
5261
- var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
5262
- var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "turn_terminal", "producer_status"];
5263
- var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
5264
- var HOST_PRODUCER_FRAME_ERROR_CODES = [
5265
- "invalid_frame_encoding",
5266
- "invalid_frame_length",
5267
- "frame_truncated",
5268
- "unsupported_frame_schema",
5269
- "invalid_frame_shape",
5270
- "invalid_producer_identity",
5271
- "frame_too_large"
5272
- ];
5273
-
5274
- // host/relay/src/host-producer-core.ts
5275
- import { createHash as createHash5 } from "node:crypto";
5276
-
5277
- // host/secure-file.ts
5278
- import { execFile as execFile2 } from "node:child_process";
5279
- import { constants } from "node:fs";
5280
- import { lstat, open as open2 } from "node:fs/promises";
5281
- import { dirname, join as join3, win32 as win322 } from "node:path";
5282
- import { fileURLToPath } from "node:url";
5283
- var SecureFileCustodyError = class extends Error {
5284
- name = "SecureFileCustodyError";
5285
- reason;
5286
- constructor(reason, message) {
5287
- super(message);
5288
- this.reason = reason;
5289
- }
5290
- get code() {
5291
- if (this.reason === "reparse_point") return "ELOOP";
5292
- if (this.reason === "not_found") return "ENOENT";
5293
- if (this.reason === "too_large") return "secure_file_too_large";
5294
- if (this.reason === "already_exists") return "EEXIST";
5295
- return this.reason === "not_private" ? "secure_file_not_private" : "secure_file_unavailable";
5296
- }
5297
- };
5298
- var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
5299
- var WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES = 4096;
5300
- var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
5301
- var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
5302
- var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
5303
- function secureOpenFlags(flags, platform) {
5304
- if (platform === "win32") return flags;
5305
- const nofollow = constants.O_NOFOLLOW;
5306
- if (typeof nofollow === "number" && nofollow !== 0) return flags | nofollow;
5307
- throw new Error("Secure file reads require O_NOFOLLOW on this platform.");
5308
- }
5309
- async function openNoFollow(path, flags = constants.O_RDONLY, mode, platform = process.platform, _custody = {}) {
5310
- if (platform !== "win32") return await open2(path, secureOpenFlags(flags, platform), mode);
5311
- return await openWindowsIdentityScreened(path, flags, mode);
5312
- }
5313
- async function openWindowsIdentityScreened(path, flags, mode) {
5314
- const handle = await open2(path, flags, mode);
5315
- try {
5316
- const first = await handle.stat();
5317
- if (!first.isFile()) throw new SecureFileCustodyError("not_private", "The Windows Host file is not a regular file.");
5318
- await assertWindowsLinkFree(path, first);
5319
- await assertWindowsIdentityStable(handle, first, path);
5320
- return handle;
5321
- } catch (error) {
5322
- await handle.close();
5323
- throw error;
5324
- }
5325
- }
5326
- async function assertWindowsLinkFree(path, first) {
5327
- const entry = await lstat(path);
5328
- if (entry.isSymbolicLink() || entry.dev !== first.dev || entry.ino !== first.ino) {
5329
- throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
5330
- }
5331
- }
5332
- async function assertWindowsIdentityStable(handle, first, path) {
5333
- const second = await handle.stat();
5334
- if (second.dev !== first.dev || second.ino !== first.ino || second.size !== first.size || second.mtimeMs !== first.mtimeMs) {
5335
- throw new SecureFileCustodyError("unavailable", "The Windows Host file changed while its identity was checked.");
5336
- }
5337
- const entry = await lstat(path);
5338
- if (entry.isSymbolicLink()) throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
5339
- if (entry.dev !== second.dev || entry.ino !== second.ino) throw new SecureFileCustodyError("unavailable", "The Windows Host file path no longer names the opened file.");
5340
- }
5341
- async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
5342
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
5343
- const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
5344
- if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
5345
- if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
5346
- if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
5347
- throw securefsRefusal(result.stderr);
5348
- }
5349
- async function createRandomPrivateFileWithSecurefs(path, byteLength2, custody = {}) {
5350
- if (!Number.isSafeInteger(byteLength2) || byteLength2 < 1 || byteLength2 > WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES) throw new TypeError(`The securefs random-file size must be between 1 and ${WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES} bytes.`);
5351
- const result = await runSecurefsCommand(["internal", "securefs", "create-random-private-file", path, String(byteLength2)], 0, custody);
5352
- if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5353
- if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned unexpected creation bytes.");
5354
- if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid creation result.");
5355
- throw securefsRefusal(result.stderr);
5356
- }
5357
- async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
5358
- const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
5359
- if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5360
- if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
5361
- throw securefsRefusal(result.stderr);
5362
- }
5363
- async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
5364
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > WINDOWS_SECUREFS_MAX_WRITE_BYTES || bytes.byteLength > maxBytes) throw new TypeError("The securefs write bound or payload is invalid.");
5365
- const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
5366
- if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5367
- if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
5368
- throw securefsRefusal(result.stderr);
5575
+ if (!metadata.isFile()) throw new Error("launcher doctor reported a non-file binary path");
5576
+ return { path: binaryPath, sha256: (await digestFileSha256(binaryPath)).sha256 };
5369
5577
  }
5370
- async function isPrivateWindowsDirectory(path, custody = {}) {
5371
- await lstat(path);
5578
+ function executableCandidates(command, environment, platform) {
5579
+ if (isAbsolute2(command)) return [command];
5580
+ const pathValue = environmentValue(environment, "PATH", platform) ?? "";
5581
+ const directories = pathValue.split(delimiter).filter((entry) => entry.length > 0);
5582
+ if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join4(entry, command));
5583
+ return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join4(entry, `${command}${suffix}`)));
5584
+ }
5585
+ async function executeCealCommand(executable, args, environment) {
5372
5586
  try {
5373
- const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
5374
- if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
5375
- if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
5376
- if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
5377
- const refusal = securefsRefusal(result.stderr);
5378
- if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
5379
- throw refusal;
5587
+ const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8", cwd: resolveCealSpawnWorkingDirectory() });
5588
+ return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
5380
5589
  } catch (error) {
5381
- if (error instanceof SecureFileCustodyError) throw error;
5382
- throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
5590
+ if (isRecord2(error)) return { exit_code: typeof error.code === "number" ? error.code : 1, stdout: typeof error.stdout === "string" ? error.stdout : "", stderr: typeof error.stderr === "string" ? error.stderr : "" };
5591
+ throw error;
5383
5592
  }
5384
5593
  }
5385
- async function runSecurefsCommand(args, maxBytes, custody, stdin) {
5386
- if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
5387
- const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
5388
- const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
5389
- return await new Promise((resolve, reject2) => {
5390
- const child = execFile2(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
5391
- const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
5392
- if (exitCode === null) {
5393
- reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
5394
- return;
5395
- }
5396
- resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
5397
- });
5398
- child.stdin?.on("error", () => void 0);
5399
- child.stdin?.end(stdin);
5400
- });
5594
+ function safeRun(run, executable, args, environment) {
5595
+ return run(executable, args, environment).catch(() => null);
5401
5596
  }
5402
- function securefsRefusal(stderr) {
5403
- let value;
5597
+ function commandDocument(result) {
5598
+ if (result === null) return null;
5404
5599
  try {
5405
- value = JSON.parse(stderr.toString("utf8"));
5600
+ const value = JSON.parse(result.stdout);
5601
+ return isRecord2(value) ? value : null;
5406
5602
  } catch {
5407
- return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
5603
+ return null;
5408
5604
  }
5409
- if (!isRecord2(value) || value.schema_version !== WINDOWS_SECUREFS_REFUSAL_SCHEMA || typeof value.code !== "string") return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
5410
- if (value.code === "reparse_point") return new SecureFileCustodyError("reparse_point", "The Windows Host securefs file is a reparse point.");
5411
- if (value.code === "not_found") return new SecureFileCustodyError("not_found", "The Windows Host securefs file was not found.");
5412
- if (value.code === "too_large") return new SecureFileCustodyError("too_large", "The Windows Host securefs file exceeds its read bound.");
5413
- if (value.code === "already_exists") return new SecureFileCustodyError("already_exists", "The Windows Host securefs target already exists.");
5414
- if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
5415
- return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
5416
5605
  }
5417
- function resolveInstalledHostExecutable(platform) {
5418
- const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
5419
- return platform === "win32" ? win322.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
5606
+ function selectedContext(value) {
5607
+ if (value?.schema_version !== "ceal.access-group.v1" || value.ok !== true || !Array.isArray(value.contexts)) return null;
5608
+ const selected = value.contexts.filter((item) => isRecord2(item) && item.selected === true);
5609
+ if (selected.length !== 1) return null;
5610
+ return selectedContextRecord(selected[0]);
5420
5611
  }
5421
- function isRecord2(value) {
5422
- return value !== null && typeof value === "object" && !Array.isArray(value);
5612
+ function selectedContextRecord(item) {
5613
+ if (!isRecord2(item) || typeof item.name !== "string" || typeof item.instance_ref !== "string") return null;
5614
+ if (!SAFE_REF2.test(item.instance_ref)) return null;
5615
+ return { name: item.name, instance_ref: item.instance_ref };
5423
5616
  }
5424
- function isOwnedBy(uid, expectedUid) {
5425
- return Number.isSafeInteger(uid) && Number.isSafeInteger(expectedUid) && uid === expectedUid;
5617
+ function versionIdentity(value) {
5618
+ if (value?.schema_version !== CEAL_CLIENT_VERSION_SCHEMA_VERSION || value.ok !== true || typeof value.version !== "string" || typeof value.source_commit !== "string" || typeof value.source_tree !== "string") return null;
5619
+ if (value.version.length === 0 || !GIT_OID.test(value.source_commit) || !GIT_OID.test(value.source_tree)) return null;
5620
+ return { version: value.version, source_commit: value.source_commit, source_tree: value.source_tree };
5426
5621
  }
5427
- function isSelfOwned(uid, platform = process.platform, _handle) {
5428
- if (platform === "win32" || typeof process.geteuid !== "function") return false;
5429
- return isOwnedBy(uid, process.geteuid());
5622
+ function validExpectations(options) {
5623
+ return (options.expected_sha256 === void 0 || SHA2562.test(options.expected_sha256)) && (options.expected_source_commit === void 0 || GIT_OID.test(options.expected_source_commit)) && (options.expected_instance_ref === void 0 || SAFE_REF2.test(options.expected_instance_ref));
5430
5624
  }
5431
- function isPrivateFileMode(mode, platform = process.platform, _handle) {
5432
- if (platform === "win32") return false;
5433
- return (mode & 63) === 0;
5625
+ function failure(code, message, next_action) {
5626
+ return { ok: false, status: "failure", error: { code, message, next_action } };
5434
5627
  }
5435
- async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
5436
- if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
5437
- const entry = await lstat(path);
5438
- return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
5628
+ function isRecord2(value) {
5629
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5630
+ }
5631
+
5632
+ // host/codex/src/codex-client-doctor.ts
5633
+ var CODEX_CLIENT_DOCTOR_SCHEMA_VERSION = "ceal.codex_client_doctor.v1";
5634
+ async function doctorCodexClient(options = {}) {
5635
+ return { schema_version: CODEX_CLIENT_DOCTOR_SCHEMA_VERSION, ...await doctorClient(options, "Codex") };
5439
5636
  }
5440
5637
 
5638
+ // host/invocation-authentication-command.ts
5639
+ import { createHash as createHash8 } from "node:crypto";
5640
+ import { performance as performance2 } from "node:perf_hooks";
5641
+
5642
+ // host/relay/src/producer-frame.ts
5643
+ var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
5644
+ var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "turn_terminal", "producer_status"];
5645
+ var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
5646
+
5647
+ // host/relay/src/host-producer-core.ts
5648
+ import { createHash as createHash5 } from "node:crypto";
5649
+ import { isDeepStrictEqual } from "node:util";
5650
+ import { lstat as lstat2, readdir, stat as stat3 } from "node:fs/promises";
5651
+
5441
5652
  // host/service-log.ts
5442
5653
  import { copyFile, mkdir, stat as stat2, truncate, appendFile } from "node:fs/promises";
5443
- import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win323 } from "node:path";
5654
+ import { dirname as dirname3, isAbsolute as isAbsolute3, posix, win32 as win323 } from "node:path";
5444
5655
 
5445
5656
  // host/service-log-delivery.ts
5446
5657
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -5599,14 +5810,14 @@ async function persistHostServiceLogLine(line, environment = process.env) {
5599
5810
  await appendHostServiceLogLine(path, line).catch(() => void 0);
5600
5811
  }
5601
5812
  async function appendHostServiceLogLine(path, line) {
5602
- if (!isAbsolute2(path)) return;
5813
+ if (!isAbsolute3(path)) return;
5603
5814
  await ensureHostServiceLogDirectory(path);
5604
5815
  await appendFile(path, line);
5605
5816
  }
5606
5817
  var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
5607
5818
  var hostServiceLogDirectories = /* @__PURE__ */ new Map();
5608
5819
  function ensureHostServiceLogDirectory(path) {
5609
- const directory = dirname2(path);
5820
+ const directory = dirname3(path);
5610
5821
  const existing = hostServiceLogDirectories.get(directory);
5611
5822
  if (existing !== void 0) return existing;
5612
5823
  const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
@@ -5638,7 +5849,9 @@ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
5638
5849
  seen.add(message.host_input_ref);
5639
5850
  newestFirst.push(message);
5640
5851
  }
5641
- return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
5852
+ const currentTurn = newestFirst[0]?.host_turn_ref;
5853
+ const currentTurnFirst = currentTurn === void 0 ? newestFirst : newestFirst.filter((message) => message.host_turn_ref === currentTurn);
5854
+ return boundCealHostInvocationHumanMessageWindow(currentTurnFirst, existing?.truncated ?? false);
5642
5855
  }
5643
5856
  async function readRegisteredHostInvocationHumanMessageWindow(readRegistration, readCursor, identity, decodeLine) {
5644
5857
  try {
@@ -5752,6 +5965,15 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
5752
5965
  if (cursor.offset > 0 && !await transcriptAnchorMatches(handle, cursor)) return "transcript_rewritten";
5753
5966
  return null;
5754
5967
  }
5968
+ async function statObservedPathSignature(path) {
5969
+ try {
5970
+ const info = await lstat2(path, { bigint: true });
5971
+ if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) return null;
5972
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
5973
+ } catch {
5974
+ return null;
5975
+ }
5976
+ }
5755
5977
  function transcriptSha256(value) {
5756
5978
  return createHash5("sha256").update(value).digest("hex");
5757
5979
  }
@@ -5784,27 +6006,71 @@ function createTranscriptWatcherBase(options, owner) {
5784
6006
  producerInstallationRef: options.producer_installation_ref
5785
6007
  };
5786
6008
  }
5787
- async function scanTranscriptRegistrations(registrations, scanOne) {
6009
+ async function scanTranscriptRegistrations(registrations, scanOne, totalRegistrations, signal) {
5788
6010
  let records = 0;
5789
6011
  let enqueued = 0;
5790
6012
  let quarantined = 0;
6013
+ let scanned = 0;
5791
6014
  for (const registration of registrations) {
6015
+ if (signal?.aborted) break;
6016
+ scanned += 1;
5792
6017
  const result = await scanOne(registration);
5793
6018
  records += result.records;
5794
6019
  enqueued += result.enqueued;
5795
6020
  if (result.quarantined) quarantined += 1;
5796
6021
  }
5797
- return { registrations: registrations.length, records, enqueued, quarantined };
6022
+ return { registrations: totalRegistrations ?? scanned, records, enqueued, quarantined };
6023
+ }
6024
+ var HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS = 1000000000n;
6025
+ var HostRegistrationInventory = class {
6026
+ signature;
6027
+ registrations;
6028
+ nowNs;
6029
+ observeDirectory;
6030
+ constructor(options = {}) {
6031
+ this.nowNs = options.nowNs ?? (() => BigInt(Date.now()) * 1000000n);
6032
+ this.observeDirectory = options.observeDirectory ?? hostRegistrationDirectorySignature;
6033
+ }
6034
+ async read(directory, load) {
6035
+ const observation = await this.observeDirectory(directory);
6036
+ const nowNs = this.nowNs();
6037
+ const racy = nowNs - observation.mtimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS || nowNs - observation.ctimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS;
6038
+ if (this.registrations !== void 0 && this.signature === observation.signature && !racy) return this.registrations;
6039
+ const registrations = await load();
6040
+ this.signature = observation.signature;
6041
+ this.registrations = registrations;
6042
+ return registrations;
6043
+ }
6044
+ };
6045
+ async function hostRegistrationDirectorySignature(directory) {
6046
+ try {
6047
+ const info = await stat3(directory, { bigint: true });
6048
+ return {
6049
+ signature: `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`,
6050
+ mtimeNs: info.mtimeNs,
6051
+ ctimeNs: info.ctimeNs
6052
+ };
6053
+ } catch (error) {
6054
+ if (isMissingTranscriptError(error)) return { signature: "missing", mtimeNs: 0n, ctimeNs: 0n };
6055
+ throw error;
6056
+ }
5798
6057
  }
5799
6058
  function formatRetiredTranscriptLog(producerLabel, transcriptPath) {
5800
6059
  return `${producerLabel} retired a transcript registration: transcript_path=${JSON.stringify(transcriptPath)}, reason=${TRANSCRIPT_MISSING_REASON}.`;
5801
6060
  }
6061
+ var HOST_TRANSCRIPT_RECONCILIATION_BATCH = 100;
5802
6062
  var HostTranscriptWatcher = class {
5803
6063
  outboxRetentionMs;
5804
6064
  now;
5805
6065
  log;
5806
6066
  producerInstallationRef;
5807
6067
  clockFailure;
6068
+ transcriptObservations = /* @__PURE__ */ new Map();
6069
+ registrationSnapshot;
6070
+ // Advisory scheduling only: listRegistrations remains the registration authority.
6071
+ hotRegistrations = /* @__PURE__ */ new Set();
6072
+ reconciliation;
6073
+ reconciliationRemaining = 0;
5808
6074
  constructor(options, owner) {
5809
6075
  const base = createTranscriptWatcherBase(options, owner);
5810
6076
  this.outboxRetentionMs = base.outboxRetentionMs;
@@ -5813,8 +6079,97 @@ var HostTranscriptWatcher = class {
5813
6079
  this.producerInstallationRef = base.producerInstallationRef;
5814
6080
  this.clockFailure = owner.clock_failure;
5815
6081
  }
5816
- async scanOnce() {
5817
- return scanTranscriptRegistrations(await this.listRegistrations(), (registration) => this.scanRegistration(registration));
6082
+ async scanOnce(signal) {
6083
+ if (signal?.aborted) return { registrations: this.registrationSnapshot?.length ?? 0, records: 0, enqueued: 0, quarantined: 0 };
6084
+ const registrations = await this.listRegistrations();
6085
+ this.reconcileSnapshot(registrations);
6086
+ return scanTranscriptRegistrations(this.scanCandidates(), (observation) => this.observeRegistration(observation, signal), registrations.length, signal);
6087
+ }
6088
+ async observeRegistration(observation, signal) {
6089
+ const registration = observation.registration;
6090
+ const signature = await this.scanFingerprint(registration);
6091
+ if (signal?.aborted) return { records: 0, enqueued: 0, quarantined: false };
6092
+ this.hotRegistrations.delete(observation);
6093
+ if (signature !== null && observation.signature === signature) return { records: 0, enqueued: 0, quarantined: false };
6094
+ this.hotRegistrations.add(observation);
6095
+ const result = await this.scanRegistration(registration);
6096
+ if (result.quarantined || result.retry === true) observation.signature = void 0;
6097
+ else {
6098
+ observation.signature = signature ?? void 0;
6099
+ if (result.records === 0) this.hotRegistrations.delete(observation);
6100
+ }
6101
+ return result;
6102
+ }
6103
+ *scanCandidates() {
6104
+ const hotSlice = [];
6105
+ for (const observation of this.hotRegistrations) {
6106
+ hotSlice.push(observation);
6107
+ if (hotSlice.length === HOST_TRANSCRIPT_RECONCILIATION_BATCH) break;
6108
+ }
6109
+ const observed = /* @__PURE__ */ new Set();
6110
+ for (let count = 0; count < Math.min(this.transcriptObservations.size, HOST_TRANSCRIPT_RECONCILIATION_BATCH); count += 1) {
6111
+ const observation = this.nextReconciliation();
6112
+ if (observation === void 0) break;
6113
+ observed.add(observation);
6114
+ yield observation;
6115
+ }
6116
+ for (const observation of hotSlice) if (!observed.has(observation)) yield observation;
6117
+ }
6118
+ nextReconciliation() {
6119
+ if (this.reconciliationRemaining === 0 || this.reconciliation === void 0) {
6120
+ this.reconciliation = this.transcriptObservations.values();
6121
+ this.reconciliationRemaining = this.transcriptObservations.size;
6122
+ }
6123
+ let next = this.reconciliation.next();
6124
+ if (next.done) {
6125
+ this.reconciliation = this.transcriptObservations.values();
6126
+ this.reconciliationRemaining = this.transcriptObservations.size;
6127
+ next = this.reconciliation.next();
6128
+ }
6129
+ this.reconciliationRemaining -= 1;
6130
+ return next.value;
6131
+ }
6132
+ reconcileSnapshot(registrations) {
6133
+ if (this.registrationSnapshot === registrations) return;
6134
+ const retained = /* @__PURE__ */ new Set();
6135
+ const hot = /* @__PURE__ */ new Set();
6136
+ for (const registration of registrations) {
6137
+ const key = this.registrationKey(registration);
6138
+ retained.add(key);
6139
+ let observation = this.transcriptObservations.get(key);
6140
+ if (observation === void 0) {
6141
+ observation = { registration, signature: void 0 };
6142
+ this.transcriptObservations.set(key, observation);
6143
+ hot.add(observation);
6144
+ } else {
6145
+ if (!isDeepStrictEqual(observation.registration, registration)) {
6146
+ observation.signature = void 0;
6147
+ hot.add(observation);
6148
+ }
6149
+ observation.registration = registration;
6150
+ }
6151
+ }
6152
+ for (const [key, observation] of this.transcriptObservations) {
6153
+ if (!retained.has(key)) {
6154
+ this.transcriptObservations.delete(key);
6155
+ this.hotRegistrations.delete(observation);
6156
+ }
6157
+ }
6158
+ for (const observation of this.hotRegistrations) hot.add(observation);
6159
+ this.hotRegistrations = hot;
6160
+ this.registrationSnapshot = registrations;
6161
+ }
6162
+ async scanFingerprint(registration) {
6163
+ return this.transcriptSignature(registration);
6164
+ }
6165
+ async transcriptSignature(registration) {
6166
+ try {
6167
+ const info = await lstat2(this.transcriptPathOf(registration), { bigint: true });
6168
+ if (!info.isFile() || info.isSymbolicLink()) return null;
6169
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${info.mode}:${info.uid}`;
6170
+ } catch {
6171
+ return null;
6172
+ }
5818
6173
  }
5819
6174
  async scanRegistration(registration) {
5820
6175
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
@@ -5880,6 +6235,14 @@ var HostTranscriptWatcher = class {
5880
6235
  return transcriptCursorBoundsReason(handle, cursor, size);
5881
6236
  }
5882
6237
  };
6238
+ async function listHostOutboxDirectoryNames(directory) {
6239
+ try {
6240
+ return await readdir(directory);
6241
+ } catch (error) {
6242
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
6243
+ throw error;
6244
+ }
6245
+ }
5883
6246
  var HostProducerDrainCore = class {
5884
6247
  host;
5885
6248
  now;
@@ -5907,8 +6270,8 @@ var HostProducerDrainCore = class {
5907
6270
  };
5908
6271
 
5909
6272
  // host/relay/src/durable-atomic-replacement.ts
5910
- import { lstat as lstat2, mkdir as mkdir2, open as open3, rename, unlink } from "node:fs/promises";
5911
- import { dirname as dirname3 } from "node:path";
6273
+ import { lstat as lstat3, mkdir as mkdir2, open as open3, rename, unlink } from "node:fs/promises";
6274
+ import { dirname as dirname4 } from "node:path";
5912
6275
 
5913
6276
  // host/windows-rename-retry.ts
5914
6277
  import { setTimeout as setTimeout2 } from "node:timers/promises";
@@ -5929,7 +6292,7 @@ function resolveRetrySchedule(tuning) {
5929
6292
  startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
5930
6293
  maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
5931
6294
  sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
5932
- now: tuning.now ?? (() => Date.now())
6295
+ now: tuning.now ?? (() => performance.now())
5933
6296
  };
5934
6297
  }
5935
6298
  async function renameWithWindowsRetry(operation, tuning) {
@@ -5962,7 +6325,7 @@ function isRetryableRenameError(error) {
5962
6325
  var DEFAULT_PORT = {
5963
6326
  platform: process.platform,
5964
6327
  mkdir: (path, options) => mkdir2(path, options),
5965
- lstat: (path) => lstat2(path),
6328
+ lstat: (path) => lstat3(path),
5966
6329
  open_file: (path) => open3(path, "wx", 384),
5967
6330
  rename,
5968
6331
  unlink,
@@ -5970,7 +6333,7 @@ var DEFAULT_PORT = {
5970
6333
  unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
5971
6334
  };
5972
6335
  async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
5973
- const parent = dirname3(target);
6336
+ const parent = dirname4(target);
5974
6337
  await port.mkdir(parent, { recursive: true, mode: 448 });
5975
6338
  const parentStats = await port.lstat(parent);
5976
6339
  const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
@@ -6041,7 +6404,7 @@ function errorCode2(error) {
6041
6404
  import { createHash as createHash6 } from "node:crypto";
6042
6405
  import { constants as constants2 } from "node:fs";
6043
6406
  import { mkdir as mkdir3, open as open4, opendir, unlink as unlink2 } from "node:fs/promises";
6044
- import { dirname as dirname4, join as join4 } from "node:path";
6407
+ import { dirname as dirname5, join as join5 } from "node:path";
6045
6408
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
6046
6409
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
6047
6410
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -6060,10 +6423,12 @@ var HostUsageFactsStore = class {
6060
6423
  afterPendingWrite;
6061
6424
  afterBatchPublish;
6062
6425
  sessionDirectoryCursor;
6426
+ uploadScanSignature;
6427
+ uploadScanEmpty = false;
6063
6428
  constructor(options) {
6064
- this.root = join4(options.outbox_dir, "usage-facts");
6065
- this.sessions = join4(this.root, "sessions");
6066
- this.batches = join4(this.root, "batches");
6429
+ this.root = join5(options.outbox_dir, "usage-facts");
6430
+ this.sessions = join5(this.root, "sessions");
6431
+ this.batches = join5(this.root, "batches");
6067
6432
  this.platform = options.platform ?? process.platform;
6068
6433
  this.custody = options.secure_file_custody ?? {};
6069
6434
  this.afterPendingWrite = options.afterPendingWrite;
@@ -6079,8 +6444,11 @@ var HostUsageFactsStore = class {
6079
6444
  this.sessionDirectoryCursor = void 0;
6080
6445
  await cursor?.close();
6081
6446
  }
6447
+ /** The durable path behind one session's usage state, so idle fast paths can poll it without reading it. */
6448
+ statePath(producer, hostSourceRef, hostSessionRef) {
6449
+ return this.sessionPath(producer, hostSourceRef, hostSessionRef);
6450
+ }
6082
6451
  async readState(producer, hostSourceRef, hostSessionRef) {
6083
- await this.prepare();
6084
6452
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
6085
6453
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
6086
6454
  if (value === null) return null;
@@ -6138,11 +6506,15 @@ var HostUsageFactsStore = class {
6138
6506
  }
6139
6507
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
6140
6508
  async sweepOrphanedBatches(state) {
6141
- await this.prepare();
6142
6509
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
6143
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
6144
6510
  const expected = expectedBatchNames(state);
6145
- const directory = await opendir(directoryPath);
6511
+ let directory;
6512
+ try {
6513
+ directory = await opendir(directoryPath);
6514
+ } catch (error) {
6515
+ if (errorCode3(error) === "ENOENT") return 0;
6516
+ throw error;
6517
+ }
6146
6518
  let inspected = 0;
6147
6519
  let deleted = 0;
6148
6520
  try {
@@ -6151,7 +6523,7 @@ var HostUsageFactsStore = class {
6151
6523
  if (entry === null) break;
6152
6524
  inspected += 1;
6153
6525
  if (!isOrphanBatchEntry(entry, expected)) continue;
6154
- await unlink2(join4(directoryPath, entry.name));
6526
+ await unlink2(join5(directoryPath, entry.name));
6155
6527
  deleted += 1;
6156
6528
  }
6157
6529
  } finally {
@@ -6179,10 +6551,17 @@ var HostUsageFactsStore = class {
6179
6551
  });
6180
6552
  }
6181
6553
  async nextUploadCandidate(producer, hostSourceRef) {
6182
- await this.prepare();
6554
+ const signature = await statObservedPathSignature(this.sessions);
6555
+ if (signature !== null && signature === this.uploadScanSignature && this.uploadScanEmpty) return null;
6556
+ const candidate = await this.scanUploadCandidates(producer, hostSourceRef);
6557
+ this.uploadScanSignature = signature ?? void 0;
6558
+ this.uploadScanEmpty = candidate === null;
6559
+ return candidate;
6560
+ }
6561
+ async scanUploadCandidates(producer, hostSourceRef) {
6183
6562
  const names = await this.readNextSessionNames();
6184
6563
  for (const name of names) {
6185
- const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
6564
+ const state = await readOptionalJson(join5(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
6186
6565
  if (state === null) continue;
6187
6566
  validateStateOwner(state, producer, hostSourceRef);
6188
6567
  let validated = state;
@@ -6197,7 +6576,14 @@ var HostUsageFactsStore = class {
6197
6576
  return null;
6198
6577
  }
6199
6578
  async readNextSessionNames() {
6200
- this.sessionDirectoryCursor ??= await opendir(this.sessions);
6579
+ if (this.sessionDirectoryCursor === void 0) {
6580
+ try {
6581
+ this.sessionDirectoryCursor = await opendir(this.sessions);
6582
+ } catch (error) {
6583
+ if (errorCode3(error) === "ENOENT") return [];
6584
+ throw error;
6585
+ }
6586
+ }
6201
6587
  const names = [];
6202
6588
  let inspected = 0;
6203
6589
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -6290,7 +6676,7 @@ var HostUsageFactsStore = class {
6290
6676
  }
6291
6677
  async writeImmutableBatch(state, batch, bytes) {
6292
6678
  const path = this.batchPath(state, batch.batch_ref);
6293
- await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
6679
+ await preparePrivateDirectory(dirname5(path), this.platform, this.custody);
6294
6680
  const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
6295
6681
  if (existing !== null) {
6296
6682
  if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
@@ -6308,7 +6694,7 @@ var HostUsageFactsStore = class {
6308
6694
  await handle.sync();
6309
6695
  await handle.close();
6310
6696
  handle = void 0;
6311
- await syncDirectory(dirname4(path), this.platform);
6697
+ await syncDirectory(dirname5(path), this.platform);
6312
6698
  } catch (error) {
6313
6699
  await handle?.close().catch(() => void 0);
6314
6700
  if (errorCode3(error) === "EEXIST") {
@@ -6363,14 +6749,14 @@ var HostUsageFactsStore = class {
6363
6749
  }
6364
6750
  }
6365
6751
  sessionPath(producer, hostSourceRef, hostSessionRef) {
6366
- return join4(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
6752
+ return join5(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
6367
6753
  }
6368
6754
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
6369
6755
  const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
6370
- return join4(this.batches, sessionName.slice(0, -5));
6756
+ return join5(this.batches, sessionName.slice(0, -5));
6371
6757
  }
6372
6758
  batchPath(state, batchRef) {
6373
- return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
6759
+ return join5(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
6374
6760
  }
6375
6761
  };
6376
6762
  function serializeBatch(batch) {
@@ -6572,7 +6958,7 @@ async function syncExistingFile(path, platform) {
6572
6958
  } finally {
6573
6959
  await handle.close();
6574
6960
  }
6575
- await syncDirectory(dirname4(path), platform);
6961
+ await syncDirectory(dirname5(path), platform);
6576
6962
  }
6577
6963
  async function syncDirectory(path, platform) {
6578
6964
  if (platform === "win32") return;
@@ -6611,6 +6997,8 @@ function sha2562(value) {
6611
6997
 
6612
6998
  // host/relay/src/host-usage-facts-capture.ts
6613
6999
  import { constants as constants3 } from "node:fs";
7000
+ import { lstat as lstat4 } from "node:fs/promises";
7001
+ import { dirname as dirname6 } from "node:path";
6614
7002
  var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
6615
7003
  var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
6616
7004
  var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
@@ -6660,6 +7048,55 @@ var HostUsageRegistrationCapture = class {
6660
7048
  return captured;
6661
7049
  }
6662
7050
  };
7051
+ var HostUsageIdleGate = class {
7052
+ seen = /* @__PURE__ */ new Map();
7053
+ statPath;
7054
+ constructor(options = {}) {
7055
+ this.statPath = options.statPath ?? statIdleGatePath;
7056
+ }
7057
+ /**
7058
+ * Check whether the path is unchanged since the last confirmed check, without recording anything.
7059
+ * The caller confirms the returned signature only after the capture for it succeeded without a
7060
+ * source error, so a failed read leaves the source eligible on the next tick while a fully-read,
7061
+ * unchanged source keeps skipping its open plus state-read probe.
7062
+ */
7063
+ async checkUnchanged(key, path) {
7064
+ const signature = await this.statPath(path);
7065
+ if (signature === null) {
7066
+ this.seen.delete(key);
7067
+ return { unchanged: false, signature };
7068
+ }
7069
+ if (this.seen.get(key) === signature) return { unchanged: true, signature };
7070
+ return { unchanged: false, signature };
7071
+ }
7072
+ /** Remember a signature only after its capture succeeded, so failures stay eligible. */
7073
+ confirmUnchanged(key, signature) {
7074
+ if (signature === null) return;
7075
+ this.seen.set(key, signature);
7076
+ }
7077
+ };
7078
+ async function statIdleGatePath(path) {
7079
+ const direct = await statObservedPathSignature(path);
7080
+ if (direct !== null) return direct;
7081
+ try {
7082
+ await lstat4(path);
7083
+ return null;
7084
+ } catch (error) {
7085
+ const code = transcriptErrorCode(error);
7086
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
7087
+ return await missingPathAnchor(path);
7088
+ }
7089
+ }
7090
+ async function missingPathAnchor(path) {
7091
+ let ancestor = dirname6(path);
7092
+ for (let depth = 0; depth < 4; depth += 1) {
7093
+ if (ancestor === dirname6(ancestor)) return null;
7094
+ const anchor = await statObservedPathSignature(ancestor);
7095
+ if (anchor !== null) return `missing:${anchor}`;
7096
+ ancestor = dirname6(ancestor);
7097
+ }
7098
+ return null;
7099
+ }
6663
7100
  async function openHostUsageTranscriptCursor(input) {
6664
7101
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
6665
7102
  let source;
@@ -6730,7 +7167,7 @@ function completeLinePrefix(bytes, baseOffset) {
6730
7167
 
6731
7168
  // host/relay/src/host-registration-state.ts
6732
7169
  import { constants as constants4 } from "node:fs";
6733
- import { dirname as dirname5 } from "node:path";
7170
+ import { dirname as dirname7 } from "node:path";
6734
7171
 
6735
7172
  // host/runtime-source-paths.ts
6736
7173
  import { createHash as createHash7 } from "node:crypto";
@@ -6822,7 +7259,7 @@ var HostRegistrationStateError = class extends Error {
6822
7259
  async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
6823
7260
  let raw;
6824
7261
  try {
6825
- await assertPrivateRegistrationDirectory(dirname5(path), platform, custody);
7262
+ await assertPrivateRegistrationDirectory(dirname7(path), platform, custody);
6826
7263
  raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
6827
7264
  } catch (error) {
6828
7265
  throw registrationReadError(error);
@@ -6939,6 +7376,10 @@ var HostUsageFactsUploader = class {
6939
7376
  async close() {
6940
7377
  await this.store.close();
6941
7378
  }
7379
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
7380
+ async prepare() {
7381
+ await this.store.prepare();
7382
+ }
6942
7383
  async uploadOne(signal) {
6943
7384
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
6944
7385
  if (candidate === null) return false;
@@ -6961,6 +7402,11 @@ var HostUsageFactsUploader = class {
6961
7402
  };
6962
7403
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
6963
7404
  const uploader = new HostUsageFactsUploader(options);
7405
+ try {
7406
+ await uploader.prepare();
7407
+ } catch {
7408
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
7409
+ }
6964
7410
  let delay = 500;
6965
7411
  let failures = 0;
6966
7412
  try {
@@ -6988,15 +7434,16 @@ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
6988
7434
  }
6989
7435
  }
6990
7436
 
6991
- // host/relay/src/relay-quarantine-store.ts
6992
- var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
6993
- var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
6994
- var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
6995
-
6996
7437
  // host/relay/src/relay-admission-store.ts
6997
- var DEFAULT_LIMITS = { global_count: 8192, global_bytes: 64 * 1024 * 1024, producer_count: 4096, producer_bytes: 32 * 1024 * 1024 };
6998
- var RETRY_SECONDS = [1, 2, 4, 8, 16, 32, 60];
6999
- var MAX_RETRYABLE_ATTEMPTS = RETRY_SECONDS.length + 10;
7438
+ var RELAY_ADMISSION_CODES = vocabulary(["admitted", "already_admitted", "producer_epoch_stale", "sequence_gap", "frame_identity_conflict", "producer_queue_full", "relay_queue_full", "producer_already_connected", "invalid_producer_identity"]);
7439
+
7440
+ // host/relay/src/host-relay-config.ts
7441
+ var HOST_RELAY_CONFIG_MIN_BYTES = Buffer.byteLength("{}", "utf8");
7442
+ var HOST_RELAY_INVOCATION_MINT_LOG_LINE = new RegExp(String.raw`^\[host-relay-invocation-mint\] timestamp=(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[.]\d{3}Z) outcome=(completed|failed) stage=(registration|gateway_request|gateway_response) latency_ms=(\d{1,16})(?: gateway_origin_host=([A-Za-z0-9.:[\]-]{1,255}))?(?: client_exchange_ref=(${CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE.slice(1, -1)}))?(?: gateway_http_request_ref=(${CEAL_HTTP_GATEWAY_REQUEST_REF_PATTERN_SOURCE.slice(1, -1)}))?(?: reason=([a-z][a-z0-9_]{0,63}))?(?: gateway_status=([1-5][0-9]{2}))?$`, "u");
7443
+
7444
+ // host/relay/src/relay-endpoint-ownership.ts
7445
+ import { lstat as lstat5, mkdir as mkdir4, unlink as unlink3 } from "node:fs/promises";
7446
+ import { dirname as dirname8 } from "node:path";
7000
7447
 
7001
7448
  // host/relay/src/relay-ipc-error.ts
7002
7449
  var HostRelayIpcError = class extends Error {
@@ -7017,13 +7464,11 @@ function relayIpcErrorCode(error) {
7017
7464
  }
7018
7465
 
7019
7466
  // host/relay/src/relay-endpoint-ownership.ts
7020
- import { lstat as lstat3, mkdir as mkdir4, unlink as unlink3 } from "node:fs/promises";
7021
- import { dirname as dirname6 } from "node:path";
7022
7467
  function currentUid(fallback) {
7023
7468
  return typeof process.geteuid === "function" ? process.geteuid() : fallback;
7024
7469
  }
7025
7470
  async function assertCompactRelayClientParent(endpoint) {
7026
- const parent = dirname6(endpoint);
7471
+ const parent = dirname8(endpoint);
7027
7472
  if (process.platform !== "darwin" || !isMacosHostRelayIpcDirectory(parent)) return;
7028
7473
  if (parent !== macosHostRelayIpcDirectory()) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC directory does not belong to the effective user.");
7029
7474
  await assertPrivateEndpointDirectory(parent);
@@ -7031,7 +7476,7 @@ async function assertCompactRelayClientParent(endpoint) {
7031
7476
  async function assertPrivateEndpointDirectory(parent) {
7032
7477
  let stats;
7033
7478
  try {
7034
- stats = await lstat3(parent);
7479
+ stats = await lstat5(parent);
7035
7480
  } catch (error) {
7036
7481
  throw endpointInspectionError(error, "Host Relay IPC endpoint parent is unavailable; leaving it untouched.");
7037
7482
  }
@@ -7044,13 +7489,13 @@ function endpointInspectionError(error, message) {
7044
7489
  }
7045
7490
 
7046
7491
  // host/relay/src/relay-ipc.ts
7047
- import { createConnection, createServer } from "node:net";
7492
+ import { createConnection } from "node:net";
7048
7493
 
7049
7494
  // host/relay/src/relay-pipe-handshake.ts
7050
7495
  import { createHmac, randomBytes } from "node:crypto";
7051
7496
  import { constants as constants5 } from "node:fs";
7052
7497
  import { link, unlink as unlink4 } from "node:fs/promises";
7053
- import { dirname as dirname7, join as join5 } from "node:path";
7498
+ import { dirname as dirname9, join as join6 } from "node:path";
7054
7499
  var RELAY_PIPE_HANDSHAKE_TIMEOUT_MS = 5e3;
7055
7500
  var RELAY_PIPE_KEY_BYTES = 32;
7056
7501
  var RELAY_PIPE_KEY_FILENAME = "relay-pipe.key";
@@ -7070,10 +7515,10 @@ var RelayPipeHandshakeError = class extends Error {
7070
7515
  }
7071
7516
  };
7072
7517
  function relayPipeStateRootForOutboxDir(outboxDir) {
7073
- return join5(dirname7(dirname7(dirname7(outboxDir))), "relay");
7518
+ return join6(dirname9(dirname9(dirname9(outboxDir))), "relay");
7074
7519
  }
7075
7520
  function relayPipeKeyPath(relayStateRoot) {
7076
- return join5(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
7521
+ return join6(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
7077
7522
  }
7078
7523
  async function loadRelayPipeKey(relayStateRoot, platform = process.platform, custody = {}) {
7079
7524
  const path = relayPipeKeyPath(relayStateRoot);
@@ -7084,7 +7529,7 @@ async function loadRelayPipeKey(relayStateRoot, platform = process.platform, cus
7084
7529
  }
7085
7530
  async function loadWindowsRelayPipeKey(path, custody) {
7086
7531
  try {
7087
- await ensurePrivateDirectoryWithSecurefs(dirname7(path), custody);
7532
+ await ensurePrivateDirectoryWithSecurefs(dirname9(path), custody);
7088
7533
  const existing = await readRelayPipeKey(path, "win32", custody);
7089
7534
  if (existing !== null) return existing;
7090
7535
  await createRandomPrivateFileWithSecurefs(path, RELAY_PIPE_KEY_BYTES, custody);
@@ -7513,7 +7958,7 @@ var HostInvocationAuthenticationRefusal = class extends Error {
7513
7958
  }
7514
7959
  };
7515
7960
  var INSTALLED_HOST_INVOCATION_AUTHENTICATION_DEPENDENCIES = {
7516
- process_elapsed_ms: () => performance.now(),
7961
+ process_elapsed_ms: () => performance2.now(),
7517
7962
  load_pipe_key: async (outboxDirectory) => process.platform === "win32" ? loadRelayPipeKey(relayPipeStateRootForOutboxDir(outboxDirectory)) : void 0,
7518
7963
  create_relay_port: (endpoint, pipeKey, timeoutMs) => new HostRelayInvocationContextPort(endpoint, pipeKey, timeoutMs)
7519
7964
  };
@@ -7583,24 +8028,142 @@ async function authenticateHostInvocation(descriptor2, input, options) {
7583
8028
  const request2 = decodeCealHostInvocationAuthenticationRequest({ schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA, client_nonce: input[2] });
7584
8029
  const config = validateOptions(options);
7585
8030
  const now = config.now ?? (() => /* @__PURE__ */ new Date());
7586
- const { store, current } = await currentInvocation(descriptor2, config, now);
8031
+ const store = descriptor2.create_store(config.outbox_dir);
8032
+ const resolved = resolveIdentity(descriptor2, config);
8033
+ if (resolved.status === "session_unavailable") throw new TypeError("no_binding");
8034
+ const toolCallId = resolveToolCallId(descriptor2, config);
8035
+ const selection = await readHookSelection(store, resolved.identity);
8036
+ if (selection === null) {
8037
+ const callTime = await trySelectionlessCallTimeBinding(descriptor2, store, resolved.identity, config, toolCallId);
8038
+ if (callTime !== null) return authenticateCallTimeBinding(descriptor2, store, callTime, request2.client_nonce, config, now);
8039
+ } else if (!waitPossible(config) && !await hasLiveInvocationContext(store, resolved.identity, now)) {
8040
+ const direct = await tryDirectCallTimeBinding(descriptor2, store, resolved.identity, selection, config, toolCallId);
8041
+ if (direct !== null) return authenticateCallTimeBinding(descriptor2, store, direct, request2.client_nonce, config, now);
8042
+ }
8043
+ return authenticateHookGated(descriptor2, store, request2.client_nonce, config, now, toolCallId);
8044
+ }
8045
+ function selectCallTimeBinding(window, toolCallId) {
8046
+ const newest = window.messages[0];
8047
+ if (newest === void 0) return null;
8048
+ return { message: newest, mode: toolCallId === void 0 ? "newest_message" : "tool_call" };
8049
+ }
8050
+ async function authenticateCallTimeBinding(descriptor2, store, callTime, clientNonce, config, now) {
8051
+ if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
8052
+ const query = await invocationMintQuery(descriptor2, store, { identity: callTime.binding, expires_at: callTime.expires_at }, clientNonce, config, callTime.window);
8053
+ const response2 = await mintedResult(config.mint_invocation_context, query);
8054
+ const completedAt = now();
8055
+ const newest = await rereadCallTimeNewest(descriptor2, store, callTime.binding, config);
8056
+ if (newest === null || newest.host_turn_ref !== callTime.binding.host_turn_ref || newest.host_input_ref !== callTime.window.messages[0]?.host_input_ref) throw new TypeError("context_replaced");
8057
+ return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
8058
+ }
8059
+ async function authenticateHookGated(descriptor2, store, clientNonce, config, now, toolCallId) {
8060
+ const { current } = await currentInvocation(descriptor2, config, now, store);
7587
8061
  if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
7588
- const query = await invocationMintQuery(descriptor2, store, current, request2.client_nonce, config);
8062
+ const window = await readCallTimeWindow(descriptor2, store, current.identity, config);
8063
+ const selected = selectCallTimeBinding(window, toolCallId);
8064
+ if (selected !== null && selected.message.host_turn_ref !== current.identity.host_turn_ref) {
8065
+ const selection = await readHookSelection(store, current.identity);
8066
+ if (selection === null || transcriptCatchesHookSelection(selection, selected.message)) {
8067
+ return authenticateCallTimeBinding(descriptor2, store, {
8068
+ binding: { ...current.identity, host_turn_ref: selected.message.host_turn_ref },
8069
+ expires_at: current.expires_at,
8070
+ window,
8071
+ mode: selected.mode
8072
+ }, clientNonce, config, now);
8073
+ }
8074
+ }
8075
+ const query = await invocationMintQuery(descriptor2, store, current, clientNonce, config, window);
7589
8076
  const response2 = await mintedResult(config.mint_invocation_context, query);
7590
8077
  const completedAt = now();
7591
8078
  const rechecked = await store.readInvocationContext(current.identity.host_source_ref, current.identity.host_session_ref, completedAt);
7592
8079
  if (rechecked === null || !sameTurn(current, rechecked)) throw new TypeError("context_replaced");
7593
8080
  return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
7594
8081
  }
7595
- async function invocationMintQuery(descriptor2, store, current, clientNonce, options) {
7596
- const readWindow = options.read_human_message_window?.(current.identity) ?? descriptor2.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false });
8082
+ async function trySelectionlessCallTimeBinding(descriptor2, store, identity, config, toolCallId) {
8083
+ const registration = await liveTranscriptRegistration(store, identity);
8084
+ if (registration === null) return null;
8085
+ let window;
8086
+ try {
8087
+ window = await readCallTimeWindow(descriptor2, store, identity, config);
8088
+ } catch {
8089
+ throw new TypeError("transient_retryable");
8090
+ }
8091
+ const selected = selectCallTimeBinding(window, toolCallId);
8092
+ if (selected === null) return null;
8093
+ return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
8094
+ }
8095
+ async function tryDirectCallTimeBinding(descriptor2, store, identity, selection, config, toolCallId) {
8096
+ let window;
8097
+ try {
8098
+ window = await readCallTimeWindow(descriptor2, store, identity, config);
8099
+ } catch {
8100
+ return null;
8101
+ }
8102
+ const selected = selectCallTimeBinding(window, toolCallId);
8103
+ if (selected === null || !transcriptCatchesHookSelection(selection, selected.message)) return null;
8104
+ const registration = await liveTranscriptRegistration(store, identity);
8105
+ if (registration === null) return null;
8106
+ return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
8107
+ }
8108
+ async function readCallTimeWindow(descriptor2, store, identity, config) {
8109
+ return await (config.read_human_message_window?.(identity) ?? descriptor2.read_human_message_window?.({ store, identity }) ?? Promise.resolve({ messages: [], truncated: false }));
8110
+ }
8111
+ function transcriptCatchesHookSelection(selection, newest) {
8112
+ if (newest.text_truncated === true) return false;
8113
+ return hostProducerPromptRef(createHash8("sha256").update(newest.text, "utf8").digest("hex")) === selection.prompt_ref;
8114
+ }
8115
+ async function readHookSelection(store, identity) {
8116
+ try {
8117
+ return await store.readInvocationTurnSelection?.(identity.host_source_ref, identity.host_session_ref) ?? null;
8118
+ } catch {
8119
+ return null;
8120
+ }
8121
+ }
8122
+ async function hasLiveInvocationContext(store, identity, now) {
8123
+ try {
8124
+ return await store.readInvocationContext(identity.host_source_ref, identity.host_session_ref, now()) !== null;
8125
+ } catch {
8126
+ return false;
8127
+ }
8128
+ }
8129
+ function waitPossible(config) {
8130
+ return (config.context_activation_wait_ms ?? 0) > 0;
8131
+ }
8132
+ async function liveTranscriptRegistration(store, identity) {
8133
+ try {
8134
+ const registration = await store.readTranscriptRegistration?.(identity.host_source_ref, identity.host_session_ref) ?? null;
8135
+ if (registration !== null && Date.parse(registration.expires_at) > Date.now()) return registration;
8136
+ } catch {
8137
+ }
8138
+ return null;
8139
+ }
8140
+ async function rereadCallTimeNewest(descriptor2, store, identity, config) {
8141
+ try {
8142
+ return (await readCallTimeWindow(descriptor2, store, identity, config)).messages[0] ?? null;
8143
+ } catch {
8144
+ return null;
8145
+ }
8146
+ }
8147
+ function resolveToolCallId(descriptor2, options) {
8148
+ if (options.tool_call_id !== void 0) return validToolCallId(options.tool_call_id) ? options.tool_call_id : void 0;
8149
+ if (descriptor2.tool_call_id_env === void 0) return void 0;
8150
+ const value = process.env[descriptor2.tool_call_id_env];
8151
+ return validToolCallId(value) ? value : void 0;
8152
+ }
8153
+ function validToolCallId(value) {
8154
+ return typeof value === "string" && value.length > 0 && value.length <= 256 && !value.includes("\0");
8155
+ }
8156
+ async function invocationMintQuery(descriptor2, store, current, clientNonce, options, windowOverride) {
8157
+ const readWindow = windowOverride === void 0 ? options.read_human_message_window?.(current.identity) ?? descriptor2.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false }) : Promise.resolve(windowOverride);
8158
+ const window = await readWindow;
8159
+ if (window.messages.length === 0) throw new TypeError("transcript_unavailable");
7597
8160
  return {
7598
8161
  producer_id: descriptor2.producer_id,
7599
8162
  producer_installation_ref: options.producer_installation_ref,
7600
8163
  client_nonce: clientNonce,
7601
8164
  context_expires_at: current.expires_at,
7602
8165
  host_binding: { ...current.identity },
7603
- human_message_window: await readWindow,
8166
+ human_message_window: window,
7604
8167
  ...await visibleOutputBudget(descriptor2)
7605
8168
  };
7606
8169
  }
@@ -7625,12 +8188,11 @@ async function mintedResult(mint, query) {
7625
8188
  function validGenericGatewayRefusalStatus2(value) {
7626
8189
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 400 && value < 500 && value !== 401 && value !== 429;
7627
8190
  }
7628
- async function currentInvocation(descriptor2, config, now) {
7629
- const store = descriptor2.create_store(config.outbox_dir);
8191
+ async function currentInvocation(descriptor2, config, now, store) {
7630
8192
  const identity = resolveIdentity(descriptor2, config);
7631
8193
  if (identity.status === "session_unavailable") throw new TypeError("no_binding");
7632
8194
  const waitBudgetMs = config.context_activation_wait_ms ?? 0;
7633
- const monotonicNow = config.monotonic_now ?? (() => performance.now());
8195
+ const monotonicNow = config.monotonic_now ?? (() => performance2.now());
7634
8196
  const deadline = monotonicNow() + waitBudgetMs;
7635
8197
  let firstCheck = true;
7636
8198
  let waitEngaged = false;
@@ -7643,7 +8205,7 @@ async function currentInvocation(descriptor2, config, now) {
7643
8205
  const current = await readLiveSessionContext(store, identity.identity.host_source_ref, identity.identity.host_session_ref, observedAt);
7644
8206
  if (current !== null) {
7645
8207
  recordActivationWaitCompletion(descriptor2.producer_id, waitEngaged, config.diagnostic_sink);
7646
- return { store, current };
8208
+ return { current };
7647
8209
  }
7648
8210
  await rejectWhenActivationWaitIsUnavailable(descriptor2, store, identity.identity, waitEngaged, waitBudgetMs, config.diagnostic_sink);
7649
8211
  const remainingMs = deadline - monotonicNow();
@@ -7717,7 +8279,7 @@ function waitForContextActivation(milliseconds) {
7717
8279
  });
7718
8280
  }
7719
8281
  function validateOptions(options) {
7720
- if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || !validOptionalSession(options.session_id)) {
8282
+ if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || options.tool_call_id !== void 0 && typeof options.tool_call_id !== "string" || !validOptionalSession(options.session_id)) {
7721
8283
  throw new TypeError("options_invalid");
7722
8284
  }
7723
8285
  return options;
@@ -7742,7 +8304,7 @@ function writeResult(value, sink) {
7742
8304
  // host/producer-service.ts
7743
8305
  import { posix as posix4, win32 as win326 } from "node:path";
7744
8306
  import { constants as constants6 } from "node:fs";
7745
- import { lstat as lstat4 } from "node:fs/promises";
8307
+ import { lstat as lstat6 } from "node:fs/promises";
7746
8308
  var SAFE_REF3 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
7747
8309
  var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
7748
8310
  var HostProducerServiceError = class extends Error {
@@ -7871,7 +8433,7 @@ function assertProducerAbsolutePath(value, platform, kind, error) {
7871
8433
  }
7872
8434
  async function configPathStat(configPath, error) {
7873
8435
  try {
7874
- return await lstat4(configPath);
8436
+ return await lstat6(configPath);
7875
8437
  } catch {
7876
8438
  throw error("config_unavailable");
7877
8439
  }
@@ -7970,10 +8532,11 @@ function boundedMilliseconds(value) {
7970
8532
  }
7971
8533
 
7972
8534
  // host/codex/src/codex-decoder.ts
7973
- import { createHash as createHash8 } from "node:crypto";
8535
+ import { createHash as createHash9 } from "node:crypto";
7974
8536
 
7975
8537
  // host/codex/src/codex-types.ts
7976
8538
  var CODEX_THREAD_ID_ENVIRONMENT = "CODEX_THREAD_ID";
8539
+ var CODEX_TOOL_CALL_ID_ENVIRONMENT = "CODEX_TOOL_CALL_ID";
7977
8540
  var CODEX_OUTBOX_SCHEMA_VERSION = "ceal.codex_observation_outbox.v1";
7978
8541
  var CODEX_SESSION_SCHEMA_VERSION = "ceal.codex_session.v1";
7979
8542
  var CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION = "ceal.codex_invocation_context.v1";
@@ -8015,14 +8578,14 @@ function turnObservationValue(sessionId, turnRef, status) {
8015
8578
  return { status, host_session_id_sha256: sha2563(sessionId), host_turn_ref: turnRef };
8016
8579
  }
8017
8580
  function sha2563(value) {
8018
- return createHash8("sha256").update(value, "utf8").digest("hex");
8581
+ return createHash9("sha256").update(value, "utf8").digest("hex");
8019
8582
  }
8020
8583
  function shortDigest(value) {
8021
8584
  return cealRequestSha256(value);
8022
8585
  }
8023
8586
 
8024
8587
  // host/codex/src/codex-transcript-baseline.ts
8025
- import { createHash as createHash9 } from "node:crypto";
8588
+ import { createHash as createHash10 } from "node:crypto";
8026
8589
 
8027
8590
  // host/codex/src/codex-transcript-decoder.ts
8028
8591
  var SAFE_REF5 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
@@ -8145,32 +8708,51 @@ function decodeTokenUsage(value) {
8145
8708
  }
8146
8709
  function decodeResponseItem(payload, ordinal, timestamp3) {
8147
8710
  if (payload.type !== "message" || payload.role !== "user") return { kind: "ignored", ordinal, timestamp: timestamp3 };
8148
- const metadata = userMessageMetadata(payload.internal_chat_message_metadata_passthrough);
8149
- const contentItemKind = userTextContentKind(metadata.content_item_kinds);
8150
- if (contentItemKind === void 0) return { kind: "ignored", ordinal, timestamp: timestamp3 };
8151
- const prompt = userTextContent(payload.content);
8711
+ const attribution = userMessageAttribution(payload.internal_chat_message_metadata_passthrough);
8712
+ if (attribution === null) return { kind: "ignored", ordinal, timestamp: timestamp3 };
8713
+ const prompt = userTextContent(payload.content, attribution.content_item_kinds);
8714
+ if (prompt === null) return { kind: "ignored", ordinal, timestamp: timestamp3 };
8152
8715
  return {
8153
8716
  kind: "user_text",
8154
8717
  ordinal,
8155
8718
  timestamp: timestamp3,
8156
- prompt,
8157
- content_item_kind: contentItemKind,
8719
+ prompt: prompt.text,
8720
+ content_item_kind: prompt.kind,
8158
8721
  message_id: safeRef2(payload.id, "Codex user message identity is invalid."),
8159
- turn_id: safeRef2(metadata.turn_id, "Codex user message task identity is invalid.")
8722
+ turn_id: safeRef2(attribution.turn_id, "Codex user message task identity is invalid.")
8160
8723
  };
8161
8724
  }
8162
- function userTextContentKind(kinds) {
8163
- return kinds.length === 1 && (kinds[0] === "user.text" || kinds[0] === "goal.internal_context") ? kinds[0] : void 0;
8164
- }
8165
- function userMessageMetadata(value) {
8166
- if (!isRecord6(value) || !Array.isArray(value.content_item_kinds)) reject("Codex user message provenance is malformed.");
8167
- return { ...value, content_item_kinds: value.content_item_kinds };
8725
+ function userMessageAttribution(value) {
8726
+ if (!isRecord6(value)) return null;
8727
+ if (typeof value.turn_id !== "string" || !SAFE_REF5.test(value.turn_id)) return null;
8728
+ return { turn_id: value.turn_id, content_item_kinds: Array.isArray(value.content_item_kinds) ? value.content_item_kinds : void 0 };
8168
8729
  }
8169
- function userTextContent(value) {
8730
+ function userTextContent(value, kinds) {
8170
8731
  if (!Array.isArray(value)) reject(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
8171
- if (value.length !== 1) reject(`Codex user text content is malformed (${refusalFact("items", value.length, "exactly one")}).`);
8172
- if (!isRecord6(value[0]) || value[0].type !== "input_text") reject(`Codex user text content is malformed (${refusalFact("item_type", isRecord6(value[0]) ? value[0].type : typeof value[0], "input_text")}).`);
8173
- return boundedText2(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
8732
+ if (kinds === void 0) {
8733
+ if (value.length !== 1) return null;
8734
+ return { text: userTextEntry(value[0]), kind: "user.text" };
8735
+ }
8736
+ if (kinds.length !== value.length) return null;
8737
+ const match = singleAlignedTextKind(kinds);
8738
+ if (match === null) return null;
8739
+ if (kinds.length === 1) return { text: userTextEntry(value[match.index]), kind: match.kind };
8740
+ if (!isRecord6(value[match.index]) || value[match.index].type !== "input_text") return null;
8741
+ return { text: boundedText2(value[match.index].text, MAX_PROMPT_BYTES, "Codex user text is invalid."), kind: match.kind };
8742
+ }
8743
+ function singleAlignedTextKind(kinds) {
8744
+ let match = null;
8745
+ for (let index = 0; index < kinds.length; index += 1) {
8746
+ const kind = kinds[index];
8747
+ if (kind !== "user.text" && kind !== "goal.internal_context") continue;
8748
+ if (match !== null) return null;
8749
+ match = { index, kind };
8750
+ }
8751
+ return match;
8752
+ }
8753
+ function userTextEntry(value) {
8754
+ if (!isRecord6(value) || value.type !== "input_text") reject(`Codex user text content is malformed (${refusalFact("item_type", isRecord6(value) ? value.type : typeof value, "input_text")}).`);
8755
+ return boundedText2(value.text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
8174
8756
  }
8175
8757
  function safeOrdinal(value) {
8176
8758
  if (!Number.isSafeInteger(value) || Number(value) < 0) reject("Codex transcript ordinal is invalid.");
@@ -8246,7 +8828,7 @@ function assertCodexTranscriptHeader(registration, record3) {
8246
8828
  ])}).`);
8247
8829
  }
8248
8830
  function digest(value) {
8249
- return createHash9("sha256").update(value).digest("hex");
8831
+ return createHash10("sha256").update(value).digest("hex");
8250
8832
  }
8251
8833
  function timestamp(now) {
8252
8834
  const value = now();
@@ -8255,8 +8837,8 @@ function timestamp(now) {
8255
8837
  }
8256
8838
 
8257
8839
  // host/codex/src/codex-outbox.ts
8258
- import { mkdir as mkdir5, open as open5, readdir, rename as rename2, stat as stat3, unlink as unlink5 } from "node:fs/promises";
8259
- import { dirname as dirname8, isAbsolute as isAbsolute3, join as join6 } from "node:path";
8840
+ import { mkdir as mkdir5, open as open5, rename as rename2, stat as stat4, unlink as unlink5 } from "node:fs/promises";
8841
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join7 } from "node:path";
8260
8842
 
8261
8843
  // host/invocation-context.ts
8262
8844
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -8360,15 +8942,16 @@ var CodexOutboxStore = class {
8360
8942
  turnSelectionsDirectory;
8361
8943
  registrationsDirectory;
8362
8944
  cursorsDirectory;
8945
+ registrationInventory = new HostRegistrationInventory();
8363
8946
  constructor(directory) {
8364
8947
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
8365
8948
  this.directory = directory;
8366
- this.entriesDirectory = join6(directory, "entries");
8367
- this.sessionsDirectory = join6(directory, "sessions");
8368
- this.activeContextsDirectory = join6(directory, "active-contexts");
8369
- this.turnSelectionsDirectory = join6(directory, "turn-selections");
8370
- this.registrationsDirectory = join6(directory, "transcript-registrations");
8371
- this.cursorsDirectory = join6(directory, "transcript-cursors");
8949
+ this.entriesDirectory = join7(directory, "entries");
8950
+ this.sessionsDirectory = join7(directory, "sessions");
8951
+ this.activeContextsDirectory = join7(directory, "active-contexts");
8952
+ this.turnSelectionsDirectory = join7(directory, "turn-selections");
8953
+ this.registrationsDirectory = join7(directory, "transcript-registrations");
8954
+ this.cursorsDirectory = join7(directory, "transcript-cursors");
8372
8955
  }
8373
8956
  async prepare() {
8374
8957
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -8381,13 +8964,12 @@ var CodexOutboxStore = class {
8381
8964
  await writeAtomicJson(this.entryPath(entry.submission_ref), entry);
8382
8965
  }
8383
8966
  async list() {
8384
- await this.prepare();
8385
8967
  const entries = [];
8386
8968
  let malformed = 0;
8387
- for (const name of await readdir(this.entriesDirectory)) {
8969
+ for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
8388
8970
  if (!name.endsWith(".json")) continue;
8389
8971
  try {
8390
- const value = JSON.parse(await readOwnerStateFile(join6(this.entriesDirectory, name)));
8972
+ const value = JSON.parse(await readOwnerStateFile(join7(this.entriesDirectory, name)));
8391
8973
  validateEnvelope(value);
8392
8974
  entries.push(value);
8393
8975
  } catch {
@@ -8432,7 +9014,6 @@ var CodexOutboxStore = class {
8432
9014
  }
8433
9015
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
8434
9016
  if (!SAFE_REF6.test(hostSourceRef) || !SAFE_REF6.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
8435
- await this.prepare();
8436
9017
  return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
8437
9018
  }
8438
9019
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
@@ -8441,6 +9022,7 @@ var CodexOutboxStore = class {
8441
9022
  const path = this.activeContextPath(identity);
8442
9023
  const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
8443
9024
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
9025
+ await this.prepare();
8444
9026
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
8445
9027
  return true;
8446
9028
  }
@@ -8457,7 +9039,6 @@ var CodexOutboxStore = class {
8457
9039
  */
8458
9040
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
8459
9041
  if (!SAFE_REF6.test(hostSourceRef) || !SAFE_REF6.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
8460
- await this.prepare();
8461
9042
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
8462
9043
  return context;
8463
9044
  }
@@ -8481,7 +9062,6 @@ var CodexOutboxStore = class {
8481
9062
  async readSession(sourceRef, sessionRef) {
8482
9063
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
8483
9064
  if (!SAFE_REF6.test(sourceRef) || !SAFE_REF6.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
8484
- await this.prepare();
8485
9065
  return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
8486
9066
  }
8487
9067
  async registerTranscript(registration) {
@@ -8509,30 +9089,38 @@ var CodexOutboxStore = class {
8509
9089
  }
8510
9090
  async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
8511
9091
  const path = this.registrationPath(hostSourceRef, hostSessionRef);
8512
- await this.prepare();
8513
9092
  const registration = await readOptionalJson2(path, validateRegistration);
8514
9093
  if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
8515
9094
  return registration;
8516
9095
  }
8517
9096
  async listTranscriptRegistrations() {
8518
- await this.prepare();
8519
- const registrations = [];
8520
- for (const name of await readdir(this.registrationsDirectory)) {
8521
- if (!name.endsWith(".json")) continue;
8522
- try {
8523
- const value = JSON.parse(await readOwnerStateFile(join6(this.registrationsDirectory, name)));
8524
- validateRegistration(value);
8525
- registrations.push(value);
8526
- } catch {
9097
+ return this.registrationInventory.read(this.registrationsDirectory, async () => {
9098
+ const registrations = [];
9099
+ for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
9100
+ if (!name.endsWith(".json")) continue;
9101
+ try {
9102
+ const value = JSON.parse(await readOwnerStateFile(join7(this.registrationsDirectory, name)));
9103
+ validateRegistration(value);
9104
+ registrations.push(value);
9105
+ } catch {
9106
+ }
8527
9107
  }
8528
- }
8529
- return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
9108
+ return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
9109
+ });
8530
9110
  }
8531
9111
  async readTranscriptCursor(registration) {
8532
9112
  validateRegistration(registration);
8533
- await this.prepare();
8534
9113
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
8535
9114
  }
9115
+ async transcriptCursorFingerprint(registration) {
9116
+ validateRegistration(registration);
9117
+ try {
9118
+ const info = await stat4(this.cursorPath(registration.host_source_ref, registration.host_session_ref), { bigint: true });
9119
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
9120
+ } catch {
9121
+ return "missing";
9122
+ }
9123
+ }
8536
9124
  async writeTranscriptCursor(cursor) {
8537
9125
  validateCursor(cursor);
8538
9126
  await this.prepare();
@@ -8543,7 +9131,6 @@ var CodexOutboxStore = class {
8543
9131
  const read2 = await this.list();
8544
9132
  const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
8545
9133
  if (envelope !== null) return envelopeMatch(envelope);
8546
- await this.prepare();
8547
9134
  return null;
8548
9135
  }
8549
9136
  async hasPriorTurn(sourceRef, sessionRef) {
@@ -8554,22 +9141,22 @@ var CodexOutboxStore = class {
8554
9141
  }
8555
9142
  entryPath(submissionRef) {
8556
9143
  if (!SAFE_REF6.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
8557
- return join6(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
9144
+ return join7(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
8558
9145
  }
8559
9146
  sessionPath(sourceRef, sessionRef) {
8560
- return join6(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
9147
+ return join7(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
8561
9148
  }
8562
9149
  activeContextPath(identity) {
8563
- return join6(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
9150
+ return join7(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
8564
9151
  }
8565
9152
  turnSelectionPath(sourceRef, sessionRef) {
8566
- return join6(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
9153
+ return join7(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
8567
9154
  }
8568
9155
  registrationPath(sourceRef, sessionRef) {
8569
- return join6(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
9156
+ return join7(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
8570
9157
  }
8571
9158
  cursorPath(sourceRef, sessionRef) {
8572
- return join6(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
9159
+ return join7(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
8573
9160
  }
8574
9161
  };
8575
9162
  async function removeOwnerState(path, what) {
@@ -8613,7 +9200,7 @@ async function writeAtomicJson(path, value) {
8613
9200
  await handle.close();
8614
9201
  }
8615
9202
  await rename2(temp, path);
8616
- await syncDirectory2(dirname8(path));
9203
+ await syncDirectory2(dirname10(path));
8617
9204
  } catch (error) {
8618
9205
  try {
8619
9206
  await unlink5(temp);
@@ -8648,14 +9235,14 @@ async function readOptionalJson2(path, validate) {
8648
9235
  async function ensureOwnerDirectory(path) {
8649
9236
  try {
8650
9237
  try {
8651
- const stats2 = await stat3(path);
9238
+ const stats2 = await stat4(path);
8652
9239
  if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8653
9240
  return;
8654
9241
  } catch (error) {
8655
9242
  if (!isNotFound(error)) throw error;
8656
9243
  }
8657
9244
  await mkdir5(path, { recursive: true, mode: 448 });
8658
- const stats = await stat3(path);
9245
+ const stats = await stat4(path);
8659
9246
  if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8660
9247
  } catch (error) {
8661
9248
  if (error instanceof CodexHostAdapterError) throw error;
@@ -8703,7 +9290,7 @@ function validateRegistrationFields(value) {
8703
9290
  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 }])}).`);
8704
9291
  }
8705
9292
  function validRegistrationCwd(value) {
8706
- return value === void 0 || typeof value === "string" && isAbsolute3(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
9293
+ return value === void 0 || typeof value === "string" && isAbsolute4(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
8707
9294
  }
8708
9295
  function validateCursor(value) {
8709
9296
  if (!isRecord9(value)) throw storageError("Codex transcript cursor is malformed.");
@@ -8832,11 +9419,11 @@ var CodexProducer = class {
8832
9419
  };
8833
9420
 
8834
9421
  // host/codex/src/codex-runtime-paths.ts
8835
- import { join as join7 } from "node:path";
9422
+ import { join as join8 } from "node:path";
8836
9423
  var CODEX_HOME_ENVIRONMENT = "CODEX_HOME";
8837
9424
  var CODEX_HOME_DEFAULT_DIRECTORY = ".codex";
8838
9425
  function resolveCodexHome(environment, home) {
8839
- return environment[CODEX_HOME_ENVIRONMENT] || join7(home, CODEX_HOME_DEFAULT_DIRECTORY);
9426
+ return environment[CODEX_HOME_ENVIRONMENT] || join8(home, CODEX_HOME_DEFAULT_DIRECTORY);
8840
9427
  }
8841
9428
 
8842
9429
  // host/codex/src/codex-adapter.ts
@@ -8862,9 +9449,16 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
8862
9449
  transcriptPathOf(registration) {
8863
9450
  return registration.transcript_path;
8864
9451
  }
9452
+ registrationKey(registration) {
9453
+ return `${registration.host_source_ref}\0${registration.host_session_ref}`;
9454
+ }
8865
9455
  async listRegistrations() {
8866
9456
  return this.store.listTranscriptRegistrations();
8867
9457
  }
9458
+ async scanFingerprint(registration) {
9459
+ const transcript = await super.scanFingerprint(registration);
9460
+ return transcript === null ? null : `${transcript}|${await this.store.transcriptCursorFingerprint(registration)}`;
9461
+ }
8868
9462
  async scanOpened(handle, registration) {
8869
9463
  const { size, device, inode } = await ownedCodexTranscriptFile(handle);
8870
9464
  const preflight = await this.preflight(registration, handle, size, device, inode);
@@ -8874,7 +9468,7 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
8874
9468
  if (complete === "empty" || complete === "partial") {
8875
9469
  return { records: 0, enqueued: 0, quarantined: false };
8876
9470
  }
8877
- return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
9471
+ return { ...await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode), retry: preflight.cursor.offset + complete.length < size };
8878
9472
  }
8879
9473
  async scanFailed(handle, registration, error) {
8880
9474
  this.diagnostic("watcher_scan_failed", codexTranscriptScanFailureKind(error));
@@ -9193,11 +9787,14 @@ function assertRecordSequence(registration, cursor, records, lastOrdinal, record
9193
9787
  }
9194
9788
 
9195
9789
  // host/codex/src/codex-producer-runtime.ts
9196
- async function drainCodexProducerOnce(options) {
9197
- const scan = await new CodexTranscriptWatcher({
9198
- outbox_dir: options.outbox_dir,
9790
+ function createCodexProducerWatcher(outboxDir) {
9791
+ return new CodexTranscriptWatcher({
9792
+ outbox_dir: outboxDir,
9199
9793
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
9200
- }).scanOnce().catch((error) => {
9794
+ });
9795
+ }
9796
+ async function drainCodexProducerOnce(options, signal) {
9797
+ const scan = await (options.watcher ?? createCodexProducerWatcher(options.outbox_dir)).scanOnce(signal).catch((error) => {
9201
9798
  writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
9202
9799
  throw error;
9203
9800
  });
@@ -9206,23 +9803,40 @@ async function drainCodexProducerOnce(options) {
9206
9803
  }
9207
9804
 
9208
9805
  // host/codex/src/codex-usage-facts-capturer.ts
9209
- import { createHash as createHash10 } from "node:crypto";
9806
+ import { createHash as createHash11 } from "node:crypto";
9210
9807
  var CodexUsageFactsCapturer = class {
9211
9808
  sources;
9212
9809
  usage;
9213
9810
  now;
9214
9811
  registrations;
9812
+ idleGate;
9215
9813
  constructor(options) {
9216
9814
  this.sources = new CodexOutboxStore(options.outbox_dir);
9217
9815
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
9218
9816
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
9219
9817
  this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
9818
+ this.idleGate = new HostUsageIdleGate();
9220
9819
  }
9221
9820
  async captureNext() {
9222
9821
  const registrations = await this.sources.listTranscriptRegistrations();
9223
9822
  return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
9224
9823
  }
9225
9824
  async captureRegistration(registration) {
9825
+ const idleKey = `${registration.host_source_ref}\0${registration.host_session_ref}`;
9826
+ const transcriptKey = `${idleKey}\0transcript`;
9827
+ const stateKey = `${idleKey}\0state`;
9828
+ const transcriptCheck = await this.idleGate.checkUnchanged(transcriptKey, registration.transcript_path);
9829
+ let stateCheck;
9830
+ if (transcriptCheck.unchanged) {
9831
+ stateCheck = await this.idleGate.checkUnchanged(stateKey, this.usage.statePath("codex", registration.host_source_ref, registration.host_session_ref));
9832
+ if (stateCheck.unchanged) return false;
9833
+ }
9834
+ const captured = await this.scanRegistration(registration);
9835
+ this.idleGate.confirmUnchanged(transcriptKey, transcriptCheck.signature);
9836
+ if (stateCheck !== void 0) this.idleGate.confirmUnchanged(stateKey, stateCheck.signature);
9837
+ return captured;
9838
+ }
9839
+ async scanRegistration(registration) {
9226
9840
  const prepared = await openHostUsageTranscriptCursor({
9227
9841
  path: registration.transcript_path,
9228
9842
  producer: "codex",
@@ -9401,7 +10015,7 @@ function coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount
9401
10015
  return { reason, source_file_ref: sourceFileRef, start_offset: startOffset, end_offset: endOffset, omitted_count: omittedCount };
9402
10016
  }
9403
10017
  function sha2564(value) {
9404
- return createHash10("sha256").update(value).digest("hex");
10018
+ return createHash11("sha256").update(value).digest("hex");
9405
10019
  }
9406
10020
  async function anchorMatches(handle, cursor) {
9407
10021
  const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
@@ -9439,7 +10053,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
9439
10053
  producer_id: "codex",
9440
10054
  extra_paths: [CODEX_SESSIONS_ROOT],
9441
10055
  config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
9442
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
10056
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createCodexProducerWatcher(config.outbox_dir) }),
9443
10057
  drain: drainCodexProducerOnce,
9444
10058
  background: (config, signal, dependencies) => {
9445
10059
  const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });
@@ -9448,9 +10062,9 @@ var CODEX_PRODUCER_DESCRIPTOR = {
9448
10062
  };
9449
10063
 
9450
10064
  // host/codex/src/codex-visible-output-budget.ts
9451
- import { readFile as readFile2 } from "node:fs/promises";
10065
+ import { readFile } from "node:fs/promises";
9452
10066
  import { homedir } from "node:os";
9453
- import { join as join8 } from "node:path";
10067
+ import { join as join9 } from "node:path";
9454
10068
  var import_toml = __toESM(require_toml(), 1);
9455
10069
  var CODEX_DEFAULT_TOOL_OUTPUT_TOKEN_LIMIT = 5e3;
9456
10070
  var CODEX_UTF8_BYTES_PER_OUTPUT_TOKEN = 4;
@@ -9458,7 +10072,7 @@ async function resolveCodexVisibleOutputMaxBytes(environment = process.env) {
9458
10072
  const codexHome = resolveCodexHome(environment, homedir());
9459
10073
  let source;
9460
10074
  try {
9461
- source = await readFile2(join8(codexHome, "config.toml"), "utf8");
10075
+ source = await readFile(join9(codexHome, "config.toml"), "utf8");
9462
10076
  } catch (error) {
9463
10077
  return isNotFound2(error) ? codexBytes(CODEX_DEFAULT_TOOL_OUTPUT_TOKEN_LIMIT) : void 0;
9464
10078
  }
@@ -9489,6 +10103,7 @@ var CODEX_INVOCATION_AUTHENTICATION_DESCRIPTOR = {
9489
10103
  create_store: (directory) => new CodexOutboxStore(directory),
9490
10104
  can_wait_for_context_activation: async ({ store, identity }) => await store.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref) !== null,
9491
10105
  session_id_env: CODEX_THREAD_ID_ENVIRONMENT,
10106
+ tool_call_id_env: CODEX_TOOL_CALL_ID_ENVIRONMENT,
9492
10107
  session_ref: hostSessionReference,
9493
10108
  config_flag: HOST_PRODUCER_CONFIG_FLAG,
9494
10109
  parse_config_flag: parseHostProducerConfigFlag,