@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.
@@ -280,6 +280,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
280
280
  // (never connected, revoked, or expired). The caller runs that exact
281
281
  // Operation, completes the consent it hands back, and retries the same call.
282
282
  "connect_personal_account",
283
+ // The refusal names the caller's own preferences update step: the read
284
+ // needs a personal connection the caller holds but has not selected in
285
+ // Ceal preferences, or has not confirmed through the initial review. The
286
+ // caller reads personal.preferences.get, runs personal.preferences.update
287
+ // at the current revision to select it, and retries the same call.
288
+ "update_personal_preferences",
283
289
  // The provider or Gateway named a bounded wait; the caller waits that long
284
290
  // and submits the same read again.
285
291
  "retry_after",
@@ -430,7 +436,7 @@ var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
430
436
  var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
431
437
  var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
432
438
  var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
433
- var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
439
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "race_recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
434
440
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
435
441
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
436
442
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -823,15 +829,19 @@ function requireIsoTimestamp(value, message) {
823
829
  // packages/ceal-client-protocol/src/failure-guidance-table.ts
824
830
  var CEAL_FAILURE_REDACTION_CLASSES = vocabulary(["model_safe", "withheld"]);
825
831
  var CEAL_GATEWAY_STARTING_FAILURE_CODE = "gateway_starting";
832
+ var CEAL_GATEWAY_RESTARTING_FAILURE_CODE = "gateway_restarting";
826
833
  var CEAL_OWNER_BOOTSTRAP_ABSENT_FAILURE_CODE = "bootstrap_absent";
827
834
  var CEAL_OWNER_BOOTSTRAP_UNAVAILABLE_FAILURE_CODE = "bootstrap_unavailable";
828
835
  var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
829
836
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
830
837
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
831
838
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
832
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
839
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
840
+ 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}\`.`;
833
841
  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.";
834
- 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.";
842
+ 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.";
843
+ 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.";
844
+ 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.";
835
845
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
836
846
  var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
837
847
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
@@ -861,6 +871,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
861
871
  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),
862
872
  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),
863
873
  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),
874
+ // A stored session that predates the authority-epoch commitment carries no
875
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
876
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
864
877
  refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
865
878
  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),
866
879
  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),
@@ -882,6 +895,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
882
895
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
883
896
  // The serving gate answers before refresh execution, so retrying the same attempt is safe.
884
897
  [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),
898
+ // The serving gate answers before execution while the Gateway is stopping, so retrying the same request is safe.
899
+ [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),
885
900
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
886
901
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
887
902
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -985,10 +1000,11 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
985
1000
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
986
1001
  // The bounded Host reason does not prove ephemerality. A Host refusal never
987
1002
  // changes mode; standalone remains the separate Client authority path.
988
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
1003
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
989
1004
  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),
990
1005
  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),
991
1006
  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),
1007
+ host_transcript_unavailable: guidance(HOST_TRANSCRIPT_UNAVAILABLE, "retry", 401, true),
992
1008
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
993
1009
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
994
1010
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
@@ -1002,7 +1018,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1002
1018
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
1003
1019
  // sandboxed Relay socket names the run-alone retry.
1004
1020
  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),
1005
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1021
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
1006
1022
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
1007
1023
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
1008
1024
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1250,7 +1266,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
1250
1266
  max_literal_nodes: 512
1251
1267
  });
1252
1268
 
1253
- // packages/ceal-client-protocol/src/operation-json-schema.ts
1269
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
1254
1270
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1255
1271
 
1256
1272
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -1359,6 +1375,10 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1359
1375
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
1360
1376
  });
1361
1377
 
1378
+ // packages/ceal-client-protocol/src/canonical-http-boundary.ts
1379
+ var CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE = "^client-exchange:[a-f0-9]{32}$";
1380
+ 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}$";
1381
+
1362
1382
  // packages/ceal-client-protocol/src/gateway-installation-activation.ts
1363
1383
  var CEAL_GATEWAY_INSTALLATION_ACTIVATION_CODE_DATA_CHARACTERS = 32;
1364
1384
  var CEAL_GATEWAY_INSTALLATION_ACTIVATION_CODE_CHECK_CHARACTERS = 8;
@@ -1381,6 +1401,7 @@ var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUI
1381
1401
  var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1382
1402
 
1383
1403
  // packages/ceal-client-protocol/src/resource-read-result.ts
1404
+ var CEAL_RESOURCE_GET_CHILD_REF_KINDS = Object.freeze(["section", "slide", "question"]);
1384
1405
  var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
1385
1406
  var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
1386
1407
  var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
@@ -1397,7 +1418,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
1397
1418
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
1398
1419
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
1399
1420
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
1400
- 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.`;
1421
+ 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.`;
1422
+ 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.`;
1401
1423
  function shellSingleQuoted(value) {
1402
1424
  return `'${value.replaceAll("'", "'\\''")}'`;
1403
1425
  }
@@ -1583,6 +1605,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1583
1605
  "github.review.submitted",
1584
1606
  "github.issue_comment.created",
1585
1607
  "github.review_comment.created",
1608
+ "github.issue_comment.edited",
1609
+ "github.review_comment.edited",
1586
1610
  "github.reaction.created",
1587
1611
  "github.reaction.deleted",
1588
1612
  "github.pull_request.review_requested",
@@ -1611,6 +1635,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1611
1635
  "github.release.published": "release_published",
1612
1636
  "github.issue.edited": "resource_modified",
1613
1637
  "github.pull_request.edited": "resource_modified",
1638
+ "github.issue_comment.edited": "resource_modified",
1639
+ "github.review_comment.edited": "resource_modified",
1614
1640
  "github.reaction.created": "reaction_created",
1615
1641
  "github.reaction.deleted": "ceal_write_completed",
1616
1642
  "github.pull_request.review_requested": "ceal_write_completed",
@@ -2269,6 +2295,8 @@ var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
2269
2295
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
2270
2296
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
2271
2297
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
2298
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_ENTRY_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text", "text_truncated"]);
2299
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_REQUIRED_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text"]);
2272
2300
  function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
2273
2301
  const messages = [];
2274
2302
  let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
@@ -2352,6 +2380,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
2352
2380
  "context_replaced",
2353
2381
  "no_binding",
2354
2382
  "context_expired",
2383
+ "transcript_unavailable",
2355
2384
  "host_source_refused",
2356
2385
  "host_credential_refused",
2357
2386
  "gateway_unavailable",
@@ -2381,9 +2410,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2381
2410
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
2382
2411
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
2383
2412
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2384
- // This reason cannot distinguish a Codex side conversation from a missing
2385
- // context in a regular session, so guidance must leave that choice to the caller.
2386
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2413
+ // A missing turn right after a Host restart clears by itself once the
2414
+ // watcher reactivates the turn, so the caller waits briefly and retries;
2415
+ // a caller that knows it is in an ephemeral side conversation keeps the
2416
+ // standalone fallback the guidance names second.
2417
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
2387
2418
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2388
2419
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2389
2420
  // `no_binding` now means the producer has no real current Host session. The
@@ -2391,6 +2422,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2391
2422
  // useful retry until the consumer is running inside a Host session.
2392
2423
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2393
2424
  context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
2425
+ // The registered transcript is readable but names no human message for
2426
+ // this turn, so a Gateway mint could only be refused. The caller sends a
2427
+ // new message so the turn hook re-registers the transcript, then retries;
2428
+ // a retry with no new turn cannot bind anything new.
2429
+ transcript_unavailable: Object.freeze({ classification: "host_transcript_unavailable", next_action: "retry" }),
2394
2430
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
2395
2431
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
2396
2432
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
@@ -2400,7 +2436,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2400
2436
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2401
2437
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2402
2438
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2403
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2439
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
2404
2440
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2405
2441
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2406
2442
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2492,11 +2528,15 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2492
2528
 
2493
2529
  // packages/ceal-client-protocol/src/operator-diagnostic.ts
2494
2530
  var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2495
- var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2531
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES = 8;
2496
2532
  var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2497
2533
  var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2498
2534
  var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2499
2535
  var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2536
+ var LOCAL_OPERATOR_DIAGNOSTIC_PATHS = /* @__PURE__ */ Symbol.for("ceal.local-operator-diagnostic-paths");
2537
+ var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX = /(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)/u;
2538
+ var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START = new RegExp(`^${OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX.source}`, "u");
2539
+ 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");
2500
2540
  function redactOperatorDiagnosticSecrets(value) {
2501
2541
  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]");
2502
2542
  }
@@ -2505,8 +2545,9 @@ function redactOperatorDiagnosticText(value) {
2505
2545
  return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2506
2546
  }
2507
2547
  function renderOperatorDiagnostic(value) {
2508
- const state = collectDiagnosticState(value);
2548
+ const state = collectDiagnosticState(value, read(value, LOCAL_OPERATOR_DIAGNOSTIC_PATHS) === true);
2509
2549
  const fields = [
2550
+ state.truncated ? "causes_truncated=true" : void 0,
2510
2551
  state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2511
2552
  state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2512
2553
  state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
@@ -2516,23 +2557,27 @@ function renderOperatorDiagnostic(value) {
2516
2557
  const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2517
2558
  return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2518
2559
  }
2519
- function collectDiagnosticState(value) {
2520
- const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2560
+ function collectDiagnosticState(value, preserveLocalAbsolutePaths) {
2561
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0, truncated: false };
2521
2562
  const visited = /* @__PURE__ */ new Set(), pending = [value];
2522
- while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2563
+ let inspected = 0;
2564
+ while (pending.length > 0 && inspected < OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES) {
2523
2565
  const current = pending.shift();
2524
- if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2566
+ if (current === void 0 || isObject(current) && visited.has(current)) continue;
2567
+ inspected += 1;
2568
+ visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths);
2525
2569
  }
2570
+ state.truncated ||= pending.length > 0;
2526
2571
  return state;
2527
2572
  }
2528
- function visitDiagnosticNode(current, state, pending, visited) {
2573
+ function visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths) {
2529
2574
  if (isObject(current)) {
2530
2575
  if (visited.has(current)) return;
2531
2576
  visited.add(current);
2532
2577
  }
2533
2578
  captureProcessEvidence(current, state);
2534
- appendCause(current, state.causes);
2535
- enqueueCauseChildren(current, state.causes.length, pending);
2579
+ appendCause(current, state.causes, preserveLocalAbsolutePaths);
2580
+ enqueueCauseChildren(current, state, pending);
2536
2581
  }
2537
2582
  function captureProcessEvidence(current, state) {
2538
2583
  if (state.status === void 0) state.status = safeStatus(read(current, "status"));
@@ -2540,10 +2585,9 @@ function captureProcessEvidence(current, state) {
2540
2585
  if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2541
2586
  if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2542
2587
  }
2543
- function appendCause(current, causes) {
2544
- const errors = read(current, "errors");
2545
- if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2546
- causes.push(errorCause(current));
2588
+ function appendCause(current, causes, preserveLocalAbsolutePaths) {
2589
+ if (current instanceof Error) {
2590
+ causes.push(errorCause(current, preserveLocalAbsolutePaths));
2547
2591
  return;
2548
2592
  }
2549
2593
  if (!isObject(current)) {
@@ -2551,7 +2595,7 @@ function appendCause(current, causes) {
2551
2595
  if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2552
2596
  }
2553
2597
  }
2554
- function errorCause(error) {
2598
+ function errorCause(error, preserveLocalAbsolutePaths) {
2555
2599
  const name = safeText(read(error, "name")) ?? "Error";
2556
2600
  const message = safeText(read(error, "message"));
2557
2601
  const codeValue = read(error, "code");
@@ -2559,14 +2603,29 @@ function errorCause(error) {
2559
2603
  const errnoValue = read(error, "errno");
2560
2604
  const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2561
2605
  const syscall = safeText(read(error, "syscall"));
2562
- const path = safePath(read(error, "path"));
2606
+ const path = safePath(read(error, "path"), preserveLocalAbsolutePaths);
2563
2607
  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 } });
2564
2608
  }
2565
- function enqueueCauseChildren(current, causeCount, pending) {
2609
+ function enqueueCauseChildren(current, state, pending) {
2566
2610
  const cause = read(current, "cause");
2567
2611
  if (cause !== void 0) pending.push(cause);
2568
2612
  const errors = read(current, "errors");
2569
- if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2613
+ if (Array.isArray(errors)) {
2614
+ const remaining = OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES - state.causes.length;
2615
+ const length = read(errors, "length");
2616
+ if (typeof length !== "number") {
2617
+ state.truncated = true;
2618
+ return;
2619
+ }
2620
+ state.truncated ||= length > remaining;
2621
+ for (let index = 0; index < Math.min(length, remaining); index += 1) {
2622
+ try {
2623
+ pending.push(errors[index]);
2624
+ } catch {
2625
+ state.truncated = true;
2626
+ }
2627
+ }
2628
+ }
2570
2629
  }
2571
2630
  function isObject(value) {
2572
2631
  return typeof value === "object" && value !== null;
@@ -2595,10 +2654,11 @@ function safeText(value) {
2595
2654
  const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2596
2655
  return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2597
2656
  }
2598
- function safePath(value) {
2657
+ function safePath(value, preserveLocalAbsolutePaths) {
2599
2658
  if (typeof value !== "string") return void 0;
2600
2659
  const safe = safeDiagnosticText(value);
2601
2660
  if (safe.length === 0) return void 0;
2661
+ if (!preserveLocalAbsolutePaths && hasAbsolutePathPrefix(value) && !safe.startsWith("[home path redacted]")) return "[path redacted]";
2602
2662
  if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2603
2663
  const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2604
2664
  const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
@@ -2670,7 +2730,10 @@ function redactUrls(value) {
2670
2730
  return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2671
2731
  }
2672
2732
  function redactFilePaths(value) {
2673
- return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2733
+ return value.replaceAll(OPERATOR_DIAGNOSTIC_FREEFORM_PATH_PATTERN, "[path redacted]$2");
2734
+ }
2735
+ function hasAbsolutePathPrefix(value) {
2736
+ return OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START.test(value);
2674
2737
  }
2675
2738
  function homePathRange(value, match, prefixLength) {
2676
2739
  const index = match.index;
@@ -2902,8 +2965,8 @@ function reject(message) {
2902
2965
  }
2903
2966
 
2904
2967
  // host/codex/src/codex-outbox.ts
2905
- import { mkdir as mkdir4, open as open4, readdir, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
2906
- import { dirname as dirname6, isAbsolute as isAbsolute3, join as join4 } from "node:path";
2968
+ import { mkdir as mkdir4, open as open4, rename as rename2, stat as stat3, unlink as unlink3 } from "node:fs/promises";
2969
+ import { dirname as dirname7, isAbsolute as isAbsolute3, join as join4 } from "node:path";
2907
2970
 
2908
2971
  // host/invocation-context.ts
2909
2972
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2960,24 +3023,17 @@ function safeRef(value) {
2960
3023
  var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2961
3024
  var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "turn_terminal", "producer_status"];
2962
3025
  var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
2963
- var HOST_PRODUCER_FRAME_ERROR_CODES = [
2964
- "invalid_frame_encoding",
2965
- "invalid_frame_length",
2966
- "frame_truncated",
2967
- "unsupported_frame_schema",
2968
- "invalid_frame_shape",
2969
- "invalid_producer_identity",
2970
- "frame_too_large"
2971
- ];
2972
3026
 
2973
3027
  // host/relay/src/host-producer-core.ts
2974
3028
  import { createHash as createHash5 } from "node:crypto";
3029
+ import { isDeepStrictEqual } from "node:util";
3030
+ import { lstat as lstat2, readdir, stat as stat2 } from "node:fs/promises";
2975
3031
 
2976
3032
  // host/secure-file.ts
2977
3033
  import { execFile } from "node:child_process";
2978
3034
  import { constants } from "node:fs";
2979
3035
  import { lstat, open } from "node:fs/promises";
2980
- import { dirname, join as join2, win32 } from "node:path";
3036
+ import { dirname, join as join2, parse, win32 } from "node:path";
2981
3037
  import { fileURLToPath } from "node:url";
2982
3038
  var SecureFileCustodyError = class extends Error {
2983
3039
  name = "SecureFileCustodyError";
@@ -3077,7 +3133,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
3077
3133
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
3078
3134
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
3079
3135
  return await new Promise((resolve3, reject3) => {
3080
- const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
3136
+ 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) => {
3081
3137
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
3082
3138
  if (exitCode === null) {
3083
3139
  reject3(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -3335,7 +3391,9 @@ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
3335
3391
  seen.add(message.host_input_ref);
3336
3392
  newestFirst.push(message);
3337
3393
  }
3338
- return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
3394
+ const currentTurn = newestFirst[0]?.host_turn_ref;
3395
+ const currentTurnFirst = currentTurn === void 0 ? newestFirst : newestFirst.filter((message) => message.host_turn_ref === currentTurn);
3396
+ return boundCealHostInvocationHumanMessageWindow(currentTurnFirst, existing?.truncated ?? false);
3339
3397
  }
3340
3398
  function transcriptScanFailureKind(error, adapterFailureKind) {
3341
3399
  if (transcriptErrorCode(error) === "ELOOP") return "symlink";
@@ -3392,6 +3450,15 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
3392
3450
  if (cursor.offset > 0 && !await transcriptAnchorMatches(handle, cursor)) return "transcript_rewritten";
3393
3451
  return null;
3394
3452
  }
3453
+ async function statObservedPathSignature(path) {
3454
+ try {
3455
+ const info = await lstat2(path, { bigint: true });
3456
+ if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) return null;
3457
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
3458
+ } catch {
3459
+ return null;
3460
+ }
3461
+ }
3395
3462
  function transcriptSha256(value) {
3396
3463
  return createHash5("sha256").update(value).digest("hex");
3397
3464
  }
@@ -3424,27 +3491,71 @@ function createTranscriptWatcherBase(options, owner) {
3424
3491
  producerInstallationRef: options.producer_installation_ref
3425
3492
  };
3426
3493
  }
3427
- async function scanTranscriptRegistrations(registrations, scanOne) {
3494
+ async function scanTranscriptRegistrations(registrations, scanOne, totalRegistrations, signal) {
3428
3495
  let records = 0;
3429
3496
  let enqueued = 0;
3430
3497
  let quarantined = 0;
3498
+ let scanned = 0;
3431
3499
  for (const registration of registrations) {
3500
+ if (signal?.aborted) break;
3501
+ scanned += 1;
3432
3502
  const result = await scanOne(registration);
3433
3503
  records += result.records;
3434
3504
  enqueued += result.enqueued;
3435
3505
  if (result.quarantined) quarantined += 1;
3436
3506
  }
3437
- return { registrations: registrations.length, records, enqueued, quarantined };
3507
+ return { registrations: totalRegistrations ?? scanned, records, enqueued, quarantined };
3508
+ }
3509
+ var HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS = 1000000000n;
3510
+ var HostRegistrationInventory = class {
3511
+ signature;
3512
+ registrations;
3513
+ nowNs;
3514
+ observeDirectory;
3515
+ constructor(options = {}) {
3516
+ this.nowNs = options.nowNs ?? (() => BigInt(Date.now()) * 1000000n);
3517
+ this.observeDirectory = options.observeDirectory ?? hostRegistrationDirectorySignature;
3518
+ }
3519
+ async read(directory, load) {
3520
+ const observation = await this.observeDirectory(directory);
3521
+ const nowNs = this.nowNs();
3522
+ const racy = nowNs - observation.mtimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS || nowNs - observation.ctimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS;
3523
+ if (this.registrations !== void 0 && this.signature === observation.signature && !racy) return this.registrations;
3524
+ const registrations = await load();
3525
+ this.signature = observation.signature;
3526
+ this.registrations = registrations;
3527
+ return registrations;
3528
+ }
3529
+ };
3530
+ async function hostRegistrationDirectorySignature(directory) {
3531
+ try {
3532
+ const info = await stat2(directory, { bigint: true });
3533
+ return {
3534
+ signature: `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`,
3535
+ mtimeNs: info.mtimeNs,
3536
+ ctimeNs: info.ctimeNs
3537
+ };
3538
+ } catch (error) {
3539
+ if (isMissingTranscriptError(error)) return { signature: "missing", mtimeNs: 0n, ctimeNs: 0n };
3540
+ throw error;
3541
+ }
3438
3542
  }
3439
3543
  function formatRetiredTranscriptLog(producerLabel, transcriptPath) {
3440
3544
  return `${producerLabel} retired a transcript registration: transcript_path=${JSON.stringify(transcriptPath)}, reason=${TRANSCRIPT_MISSING_REASON}.`;
3441
3545
  }
3546
+ var HOST_TRANSCRIPT_RECONCILIATION_BATCH = 100;
3442
3547
  var HostTranscriptWatcher = class {
3443
3548
  outboxRetentionMs;
3444
3549
  now;
3445
3550
  log;
3446
3551
  producerInstallationRef;
3447
3552
  clockFailure;
3553
+ transcriptObservations = /* @__PURE__ */ new Map();
3554
+ registrationSnapshot;
3555
+ // Advisory scheduling only: listRegistrations remains the registration authority.
3556
+ hotRegistrations = /* @__PURE__ */ new Set();
3557
+ reconciliation;
3558
+ reconciliationRemaining = 0;
3448
3559
  constructor(options, owner) {
3449
3560
  const base = createTranscriptWatcherBase(options, owner);
3450
3561
  this.outboxRetentionMs = base.outboxRetentionMs;
@@ -3453,8 +3564,97 @@ var HostTranscriptWatcher = class {
3453
3564
  this.producerInstallationRef = base.producerInstallationRef;
3454
3565
  this.clockFailure = owner.clock_failure;
3455
3566
  }
3456
- async scanOnce() {
3457
- return scanTranscriptRegistrations(await this.listRegistrations(), (registration) => this.scanRegistration(registration));
3567
+ async scanOnce(signal) {
3568
+ if (signal?.aborted) return { registrations: this.registrationSnapshot?.length ?? 0, records: 0, enqueued: 0, quarantined: 0 };
3569
+ const registrations = await this.listRegistrations();
3570
+ this.reconcileSnapshot(registrations);
3571
+ return scanTranscriptRegistrations(this.scanCandidates(), (observation) => this.observeRegistration(observation, signal), registrations.length, signal);
3572
+ }
3573
+ async observeRegistration(observation, signal) {
3574
+ const registration = observation.registration;
3575
+ const signature = await this.scanFingerprint(registration);
3576
+ if (signal?.aborted) return { records: 0, enqueued: 0, quarantined: false };
3577
+ this.hotRegistrations.delete(observation);
3578
+ if (signature !== null && observation.signature === signature) return { records: 0, enqueued: 0, quarantined: false };
3579
+ this.hotRegistrations.add(observation);
3580
+ const result = await this.scanRegistration(registration);
3581
+ if (result.quarantined || result.retry === true) observation.signature = void 0;
3582
+ else {
3583
+ observation.signature = signature ?? void 0;
3584
+ if (result.records === 0) this.hotRegistrations.delete(observation);
3585
+ }
3586
+ return result;
3587
+ }
3588
+ *scanCandidates() {
3589
+ const hotSlice = [];
3590
+ for (const observation of this.hotRegistrations) {
3591
+ hotSlice.push(observation);
3592
+ if (hotSlice.length === HOST_TRANSCRIPT_RECONCILIATION_BATCH) break;
3593
+ }
3594
+ const observed = /* @__PURE__ */ new Set();
3595
+ for (let count = 0; count < Math.min(this.transcriptObservations.size, HOST_TRANSCRIPT_RECONCILIATION_BATCH); count += 1) {
3596
+ const observation = this.nextReconciliation();
3597
+ if (observation === void 0) break;
3598
+ observed.add(observation);
3599
+ yield observation;
3600
+ }
3601
+ for (const observation of hotSlice) if (!observed.has(observation)) yield observation;
3602
+ }
3603
+ nextReconciliation() {
3604
+ if (this.reconciliationRemaining === 0 || this.reconciliation === void 0) {
3605
+ this.reconciliation = this.transcriptObservations.values();
3606
+ this.reconciliationRemaining = this.transcriptObservations.size;
3607
+ }
3608
+ let next = this.reconciliation.next();
3609
+ if (next.done) {
3610
+ this.reconciliation = this.transcriptObservations.values();
3611
+ this.reconciliationRemaining = this.transcriptObservations.size;
3612
+ next = this.reconciliation.next();
3613
+ }
3614
+ this.reconciliationRemaining -= 1;
3615
+ return next.value;
3616
+ }
3617
+ reconcileSnapshot(registrations) {
3618
+ if (this.registrationSnapshot === registrations) return;
3619
+ const retained = /* @__PURE__ */ new Set();
3620
+ const hot = /* @__PURE__ */ new Set();
3621
+ for (const registration of registrations) {
3622
+ const key = this.registrationKey(registration);
3623
+ retained.add(key);
3624
+ let observation = this.transcriptObservations.get(key);
3625
+ if (observation === void 0) {
3626
+ observation = { registration, signature: void 0 };
3627
+ this.transcriptObservations.set(key, observation);
3628
+ hot.add(observation);
3629
+ } else {
3630
+ if (!isDeepStrictEqual(observation.registration, registration)) {
3631
+ observation.signature = void 0;
3632
+ hot.add(observation);
3633
+ }
3634
+ observation.registration = registration;
3635
+ }
3636
+ }
3637
+ for (const [key, observation] of this.transcriptObservations) {
3638
+ if (!retained.has(key)) {
3639
+ this.transcriptObservations.delete(key);
3640
+ this.hotRegistrations.delete(observation);
3641
+ }
3642
+ }
3643
+ for (const observation of this.hotRegistrations) hot.add(observation);
3644
+ this.hotRegistrations = hot;
3645
+ this.registrationSnapshot = registrations;
3646
+ }
3647
+ async scanFingerprint(registration) {
3648
+ return this.transcriptSignature(registration);
3649
+ }
3650
+ async transcriptSignature(registration) {
3651
+ try {
3652
+ const info = await lstat2(this.transcriptPathOf(registration), { bigint: true });
3653
+ if (!info.isFile() || info.isSymbolicLink()) return null;
3654
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${info.mode}:${info.uid}`;
3655
+ } catch {
3656
+ return null;
3657
+ }
3458
3658
  }
3459
3659
  async scanRegistration(registration) {
3460
3660
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
@@ -3520,6 +3720,14 @@ var HostTranscriptWatcher = class {
3520
3720
  return transcriptCursorBoundsReason(handle, cursor, size);
3521
3721
  }
3522
3722
  };
3723
+ async function listHostOutboxDirectoryNames(directory) {
3724
+ try {
3725
+ return await readdir(directory);
3726
+ } catch (error) {
3727
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
3728
+ throw error;
3729
+ }
3730
+ }
3523
3731
  var HostProducerDrainCore = class {
3524
3732
  host;
3525
3733
  now;
@@ -3547,7 +3755,7 @@ var HostProducerDrainCore = class {
3547
3755
  };
3548
3756
 
3549
3757
  // host/relay/src/durable-atomic-replacement.ts
3550
- import { lstat as lstat2, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
3758
+ import { lstat as lstat3, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
3551
3759
  import { dirname as dirname3 } from "node:path";
3552
3760
 
3553
3761
  // host/windows-rename-retry.ts
@@ -3569,7 +3777,7 @@ function resolveRetrySchedule(tuning) {
3569
3777
  startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
3570
3778
  maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
3571
3779
  sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
3572
- now: tuning.now ?? (() => Date.now())
3780
+ now: tuning.now ?? (() => performance.now())
3573
3781
  };
3574
3782
  }
3575
3783
  async function renameWithWindowsRetry(operation, tuning) {
@@ -3602,7 +3810,7 @@ function isRetryableRenameError(error) {
3602
3810
  var DEFAULT_PORT = {
3603
3811
  platform: process.platform,
3604
3812
  mkdir: (path, options) => mkdir2(path, options),
3605
- lstat: (path) => lstat2(path),
3813
+ lstat: (path) => lstat3(path),
3606
3814
  open_file: (path) => open2(path, "wx", 384),
3607
3815
  rename,
3608
3816
  unlink,
@@ -3700,6 +3908,8 @@ var HostUsageFactsStore = class {
3700
3908
  afterPendingWrite;
3701
3909
  afterBatchPublish;
3702
3910
  sessionDirectoryCursor;
3911
+ uploadScanSignature;
3912
+ uploadScanEmpty = false;
3703
3913
  constructor(options) {
3704
3914
  this.root = join3(options.outbox_dir, "usage-facts");
3705
3915
  this.sessions = join3(this.root, "sessions");
@@ -3719,8 +3929,11 @@ var HostUsageFactsStore = class {
3719
3929
  this.sessionDirectoryCursor = void 0;
3720
3930
  await cursor?.close();
3721
3931
  }
3932
+ /** The durable path behind one session's usage state, so idle fast paths can poll it without reading it. */
3933
+ statePath(producer, hostSourceRef, hostSessionRef) {
3934
+ return this.sessionPath(producer, hostSourceRef, hostSessionRef);
3935
+ }
3722
3936
  async readState(producer, hostSourceRef, hostSessionRef) {
3723
- await this.prepare();
3724
3937
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3725
3938
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3726
3939
  if (value === null) return null;
@@ -3778,11 +3991,15 @@ var HostUsageFactsStore = class {
3778
3991
  }
3779
3992
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3780
3993
  async sweepOrphanedBatches(state) {
3781
- await this.prepare();
3782
3994
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3783
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3784
3995
  const expected = expectedBatchNames(state);
3785
- const directory = await opendir(directoryPath);
3996
+ let directory;
3997
+ try {
3998
+ directory = await opendir(directoryPath);
3999
+ } catch (error) {
4000
+ if (errorCode2(error) === "ENOENT") return 0;
4001
+ throw error;
4002
+ }
3786
4003
  let inspected = 0;
3787
4004
  let deleted = 0;
3788
4005
  try {
@@ -3819,7 +4036,14 @@ var HostUsageFactsStore = class {
3819
4036
  });
3820
4037
  }
3821
4038
  async nextUploadCandidate(producer, hostSourceRef) {
3822
- await this.prepare();
4039
+ const signature = await statObservedPathSignature(this.sessions);
4040
+ if (signature !== null && signature === this.uploadScanSignature && this.uploadScanEmpty) return null;
4041
+ const candidate = await this.scanUploadCandidates(producer, hostSourceRef);
4042
+ this.uploadScanSignature = signature ?? void 0;
4043
+ this.uploadScanEmpty = candidate === null;
4044
+ return candidate;
4045
+ }
4046
+ async scanUploadCandidates(producer, hostSourceRef) {
3823
4047
  const names = await this.readNextSessionNames();
3824
4048
  for (const name of names) {
3825
4049
  const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
@@ -3837,7 +4061,14 @@ var HostUsageFactsStore = class {
3837
4061
  return null;
3838
4062
  }
3839
4063
  async readNextSessionNames() {
3840
- this.sessionDirectoryCursor ??= await opendir(this.sessions);
4064
+ if (this.sessionDirectoryCursor === void 0) {
4065
+ try {
4066
+ this.sessionDirectoryCursor = await opendir(this.sessions);
4067
+ } catch (error) {
4068
+ if (errorCode2(error) === "ENOENT") return [];
4069
+ throw error;
4070
+ }
4071
+ }
3841
4072
  const names = [];
3842
4073
  let inspected = 0;
3843
4074
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -4251,6 +4482,8 @@ function sha2563(value) {
4251
4482
 
4252
4483
  // host/relay/src/host-usage-facts-capture.ts
4253
4484
  import { constants as constants3 } from "node:fs";
4485
+ import { lstat as lstat4 } from "node:fs/promises";
4486
+ import { dirname as dirname5 } from "node:path";
4254
4487
  var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
4255
4488
  var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
4256
4489
  var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
@@ -4300,6 +4533,55 @@ var HostUsageRegistrationCapture = class {
4300
4533
  return captured;
4301
4534
  }
4302
4535
  };
4536
+ var HostUsageIdleGate = class {
4537
+ seen = /* @__PURE__ */ new Map();
4538
+ statPath;
4539
+ constructor(options = {}) {
4540
+ this.statPath = options.statPath ?? statIdleGatePath;
4541
+ }
4542
+ /**
4543
+ * Check whether the path is unchanged since the last confirmed check, without recording anything.
4544
+ * The caller confirms the returned signature only after the capture for it succeeded without a
4545
+ * source error, so a failed read leaves the source eligible on the next tick while a fully-read,
4546
+ * unchanged source keeps skipping its open plus state-read probe.
4547
+ */
4548
+ async checkUnchanged(key, path) {
4549
+ const signature = await this.statPath(path);
4550
+ if (signature === null) {
4551
+ this.seen.delete(key);
4552
+ return { unchanged: false, signature };
4553
+ }
4554
+ if (this.seen.get(key) === signature) return { unchanged: true, signature };
4555
+ return { unchanged: false, signature };
4556
+ }
4557
+ /** Remember a signature only after its capture succeeded, so failures stay eligible. */
4558
+ confirmUnchanged(key, signature) {
4559
+ if (signature === null) return;
4560
+ this.seen.set(key, signature);
4561
+ }
4562
+ };
4563
+ async function statIdleGatePath(path) {
4564
+ const direct = await statObservedPathSignature(path);
4565
+ if (direct !== null) return direct;
4566
+ try {
4567
+ await lstat4(path);
4568
+ return null;
4569
+ } catch (error) {
4570
+ const code = transcriptErrorCode(error);
4571
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
4572
+ return await missingPathAnchor(path);
4573
+ }
4574
+ }
4575
+ async function missingPathAnchor(path) {
4576
+ let ancestor = dirname5(path);
4577
+ for (let depth = 0; depth < 4; depth += 1) {
4578
+ if (ancestor === dirname5(ancestor)) return null;
4579
+ const anchor = await statObservedPathSignature(ancestor);
4580
+ if (anchor !== null) return `missing:${anchor}`;
4581
+ ancestor = dirname5(ancestor);
4582
+ }
4583
+ return null;
4584
+ }
4303
4585
  async function openHostUsageTranscriptCursor(input) {
4304
4586
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
4305
4587
  let source;
@@ -4370,7 +4652,7 @@ function completeLinePrefix(bytes, baseOffset) {
4370
4652
 
4371
4653
  // host/relay/src/host-registration-state.ts
4372
4654
  import { constants as constants4 } from "node:fs";
4373
- import { dirname as dirname5 } from "node:path";
4655
+ import { dirname as dirname6 } from "node:path";
4374
4656
 
4375
4657
  // host/runtime-source-paths.ts
4376
4658
  import { createHash as createHash7 } from "node:crypto";
@@ -4439,7 +4721,7 @@ var HostRegistrationStateError = class extends Error {
4439
4721
  async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
4440
4722
  let raw;
4441
4723
  try {
4442
- await assertPrivateRegistrationDirectory(dirname5(path), platform, custody);
4724
+ await assertPrivateRegistrationDirectory(dirname6(path), platform, custody);
4443
4725
  raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
4444
4726
  } catch (error) {
4445
4727
  throw registrationReadError(error);
@@ -4556,6 +4838,10 @@ var HostUsageFactsUploader = class {
4556
4838
  async close() {
4557
4839
  await this.store.close();
4558
4840
  }
4841
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
4842
+ async prepare() {
4843
+ await this.store.prepare();
4844
+ }
4559
4845
  async uploadOne(signal) {
4560
4846
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4561
4847
  if (candidate === null) return false;
@@ -4578,6 +4864,11 @@ var HostUsageFactsUploader = class {
4578
4864
  };
4579
4865
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4580
4866
  const uploader = new HostUsageFactsUploader(options);
4867
+ try {
4868
+ await uploader.prepare();
4869
+ } catch {
4870
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4871
+ }
4581
4872
  let delay = 500;
4582
4873
  let failures = 0;
4583
4874
  try {
@@ -4605,15 +4896,12 @@ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4605
4896
  }
4606
4897
  }
4607
4898
 
4608
- // host/relay/src/relay-quarantine-store.ts
4609
- var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
4610
- var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
4611
- var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
4612
-
4613
4899
  // host/relay/src/relay-admission-store.ts
4614
- var DEFAULT_LIMITS = { global_count: 8192, global_bytes: 64 * 1024 * 1024, producer_count: 4096, producer_bytes: 32 * 1024 * 1024 };
4615
- var RETRY_SECONDS = [1, 2, 4, 8, 16, 32, 60];
4616
- var MAX_RETRYABLE_ATTEMPTS = RETRY_SECONDS.length + 10;
4900
+ 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"]);
4901
+
4902
+ // host/relay/src/host-relay-config.ts
4903
+ var HOST_RELAY_CONFIG_MIN_BYTES = Buffer.byteLength("{}", "utf8");
4904
+ 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");
4617
4905
 
4618
4906
  // host/relay/src/relay-pipe-handshake.ts
4619
4907
  var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
@@ -4672,6 +4960,7 @@ var CodexOutboxStore = class {
4672
4960
  turnSelectionsDirectory;
4673
4961
  registrationsDirectory;
4674
4962
  cursorsDirectory;
4963
+ registrationInventory = new HostRegistrationInventory();
4675
4964
  constructor(directory) {
4676
4965
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
4677
4966
  this.directory = directory;
@@ -4693,10 +4982,9 @@ var CodexOutboxStore = class {
4693
4982
  await writeAtomicJson(this.entryPath(entry.submission_ref), entry);
4694
4983
  }
4695
4984
  async list() {
4696
- await this.prepare();
4697
4985
  const entries = [];
4698
4986
  let malformed = 0;
4699
- for (const name of await readdir(this.entriesDirectory)) {
4987
+ for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
4700
4988
  if (!name.endsWith(".json")) continue;
4701
4989
  try {
4702
4990
  const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
@@ -4744,7 +5032,6 @@ var CodexOutboxStore = class {
4744
5032
  }
4745
5033
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
4746
5034
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
4747
- await this.prepare();
4748
5035
  return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
4749
5036
  }
4750
5037
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
@@ -4753,6 +5040,7 @@ var CodexOutboxStore = class {
4753
5040
  const path = this.activeContextPath(identity);
4754
5041
  const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
4755
5042
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
5043
+ await this.prepare();
4756
5044
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
4757
5045
  return true;
4758
5046
  }
@@ -4769,7 +5057,6 @@ var CodexOutboxStore = class {
4769
5057
  */
4770
5058
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
4771
5059
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
4772
- await this.prepare();
4773
5060
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
4774
5061
  return context;
4775
5062
  }
@@ -4793,7 +5080,6 @@ var CodexOutboxStore = class {
4793
5080
  async readSession(sourceRef, sessionRef) {
4794
5081
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
4795
5082
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
4796
- await this.prepare();
4797
5083
  return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
4798
5084
  }
4799
5085
  async registerTranscript(registration) {
@@ -4821,30 +5107,38 @@ var CodexOutboxStore = class {
4821
5107
  }
4822
5108
  async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
4823
5109
  const path = this.registrationPath(hostSourceRef, hostSessionRef);
4824
- await this.prepare();
4825
5110
  const registration = await readOptionalJson2(path, validateRegistration);
4826
5111
  if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
4827
5112
  return registration;
4828
5113
  }
4829
5114
  async listTranscriptRegistrations() {
4830
- await this.prepare();
4831
- const registrations = [];
4832
- for (const name of await readdir(this.registrationsDirectory)) {
4833
- if (!name.endsWith(".json")) continue;
4834
- try {
4835
- const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
4836
- validateRegistration(value);
4837
- registrations.push(value);
4838
- } catch {
5115
+ return this.registrationInventory.read(this.registrationsDirectory, async () => {
5116
+ const registrations = [];
5117
+ for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
5118
+ if (!name.endsWith(".json")) continue;
5119
+ try {
5120
+ const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
5121
+ validateRegistration(value);
5122
+ registrations.push(value);
5123
+ } catch {
5124
+ }
4839
5125
  }
4840
- }
4841
- return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
5126
+ return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
5127
+ });
4842
5128
  }
4843
5129
  async readTranscriptCursor(registration) {
4844
5130
  validateRegistration(registration);
4845
- await this.prepare();
4846
5131
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
4847
5132
  }
5133
+ async transcriptCursorFingerprint(registration) {
5134
+ validateRegistration(registration);
5135
+ try {
5136
+ const info = await stat3(this.cursorPath(registration.host_source_ref, registration.host_session_ref), { bigint: true });
5137
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
5138
+ } catch {
5139
+ return "missing";
5140
+ }
5141
+ }
4848
5142
  async writeTranscriptCursor(cursor) {
4849
5143
  validateCursor(cursor);
4850
5144
  await this.prepare();
@@ -4855,7 +5149,6 @@ var CodexOutboxStore = class {
4855
5149
  const read2 = await this.list();
4856
5150
  const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
4857
5151
  if (envelope !== null) return envelopeMatch(envelope);
4858
- await this.prepare();
4859
5152
  return null;
4860
5153
  }
4861
5154
  async hasPriorTurn(sourceRef, sessionRef) {
@@ -4925,7 +5218,7 @@ async function writeAtomicJson(path, value) {
4925
5218
  await handle.close();
4926
5219
  }
4927
5220
  await rename2(temp, path);
4928
- await syncDirectory2(dirname6(path));
5221
+ await syncDirectory2(dirname7(path));
4929
5222
  } catch (error) {
4930
5223
  try {
4931
5224
  await unlink3(temp);
@@ -4960,14 +5253,14 @@ async function readOptionalJson2(path, validate) {
4960
5253
  async function ensureOwnerDirectory(path) {
4961
5254
  try {
4962
5255
  try {
4963
- const stats2 = await stat2(path);
5256
+ const stats2 = await stat3(path);
4964
5257
  if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
4965
5258
  return;
4966
5259
  } catch (error) {
4967
5260
  if (!isNotFound(error)) throw error;
4968
5261
  }
4969
5262
  await mkdir4(path, { recursive: true, mode: 448 });
4970
- const stats = await stat2(path);
5263
+ const stats = await stat3(path);
4971
5264
  if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
4972
5265
  } catch (error) {
4973
5266
  if (error instanceof CodexHostAdapterError) throw error;
@@ -5246,32 +5539,51 @@ function decodeTokenUsage(value) {
5246
5539
  }
5247
5540
  function decodeResponseItem(payload, ordinal, timestamp4) {
5248
5541
  if (payload.type !== "message" || payload.role !== "user") return { kind: "ignored", ordinal, timestamp: timestamp4 };
5249
- const metadata = userMessageMetadata(payload.internal_chat_message_metadata_passthrough);
5250
- const contentItemKind = userTextContentKind(metadata.content_item_kinds);
5251
- if (contentItemKind === void 0) return { kind: "ignored", ordinal, timestamp: timestamp4 };
5252
- const prompt = userTextContent(payload.content);
5542
+ const attribution = userMessageAttribution(payload.internal_chat_message_metadata_passthrough);
5543
+ if (attribution === null) return { kind: "ignored", ordinal, timestamp: timestamp4 };
5544
+ const prompt = userTextContent(payload.content, attribution.content_item_kinds);
5545
+ if (prompt === null) return { kind: "ignored", ordinal, timestamp: timestamp4 };
5253
5546
  return {
5254
5547
  kind: "user_text",
5255
5548
  ordinal,
5256
5549
  timestamp: timestamp4,
5257
- prompt,
5258
- content_item_kind: contentItemKind,
5550
+ prompt: prompt.text,
5551
+ content_item_kind: prompt.kind,
5259
5552
  message_id: safeRef3(payload.id, "Codex user message identity is invalid."),
5260
- turn_id: safeRef3(metadata.turn_id, "Codex user message task identity is invalid.")
5553
+ turn_id: safeRef3(attribution.turn_id, "Codex user message task identity is invalid.")
5261
5554
  };
5262
5555
  }
5263
- function userTextContentKind(kinds) {
5264
- return kinds.length === 1 && (kinds[0] === "user.text" || kinds[0] === "goal.internal_context") ? kinds[0] : void 0;
5556
+ function userMessageAttribution(value) {
5557
+ if (!isRecord7(value)) return null;
5558
+ if (typeof value.turn_id !== "string" || !SAFE_REF4.test(value.turn_id)) return null;
5559
+ return { turn_id: value.turn_id, content_item_kinds: Array.isArray(value.content_item_kinds) ? value.content_item_kinds : void 0 };
5265
5560
  }
5266
- function userMessageMetadata(value) {
5267
- if (!isRecord7(value) || !Array.isArray(value.content_item_kinds)) reject2("Codex user message provenance is malformed.");
5268
- return { ...value, content_item_kinds: value.content_item_kinds };
5269
- }
5270
- function userTextContent(value) {
5561
+ function userTextContent(value, kinds) {
5271
5562
  if (!Array.isArray(value)) reject2(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
5272
- if (value.length !== 1) reject2(`Codex user text content is malformed (${refusalFact("items", value.length, "exactly one")}).`);
5273
- if (!isRecord7(value[0]) || value[0].type !== "input_text") reject2(`Codex user text content is malformed (${refusalFact("item_type", isRecord7(value[0]) ? value[0].type : typeof value[0], "input_text")}).`);
5274
- return boundedText2(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
5563
+ if (kinds === void 0) {
5564
+ if (value.length !== 1) return null;
5565
+ return { text: userTextEntry(value[0]), kind: "user.text" };
5566
+ }
5567
+ if (kinds.length !== value.length) return null;
5568
+ const match = singleAlignedTextKind(kinds);
5569
+ if (match === null) return null;
5570
+ if (kinds.length === 1) return { text: userTextEntry(value[match.index]), kind: match.kind };
5571
+ if (!isRecord7(value[match.index]) || value[match.index].type !== "input_text") return null;
5572
+ return { text: boundedText2(value[match.index].text, MAX_PROMPT_BYTES, "Codex user text is invalid."), kind: match.kind };
5573
+ }
5574
+ function singleAlignedTextKind(kinds) {
5575
+ let match = null;
5576
+ for (let index = 0; index < kinds.length; index += 1) {
5577
+ const kind = kinds[index];
5578
+ if (kind !== "user.text" && kind !== "goal.internal_context") continue;
5579
+ if (match !== null) return null;
5580
+ match = { index, kind };
5581
+ }
5582
+ return match;
5583
+ }
5584
+ function userTextEntry(value) {
5585
+ if (!isRecord7(value) || value.type !== "input_text") reject2(`Codex user text content is malformed (${refusalFact("item_type", isRecord7(value) ? value.type : typeof value, "input_text")}).`);
5586
+ return boundedText2(value.text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
5275
5587
  }
5276
5588
  function safeOrdinal(value) {
5277
5589
  if (!Number.isSafeInteger(value) || Number(value) < 0) reject2("Codex transcript ordinal is invalid.");
@@ -5514,7 +5826,8 @@ async function registerSession(event, options, store, now, retentionMs) {
5514
5826
  };
5515
5827
  const currentTurn = await selectCurrentTurn(event, options, store, hostSessionRef);
5516
5828
  const existing = await store.readTranscriptRegistration(registration.host_source_ref, registration.host_session_ref);
5517
- if (existing === null) {
5829
+ const resumed = await retireResumedTranscriptRegistration(store, existing, registration);
5830
+ if (existing === null || resumed) {
5518
5831
  await store.writeTranscriptCursor(await captureCodexTranscriptBaseline(registration, now));
5519
5832
  }
5520
5833
  await store.registerTranscript(registration);
@@ -5566,6 +5879,12 @@ async function liveSteeredTurn(options, store, hostSessionRef, hostTurnRef) {
5566
5879
  if (selection === null || selection.prompt_ref !== live.prompt_ref || selection.turn_generation_ref !== live.turn_generation_ref) return void 0;
5567
5880
  return { host_turn_ref: hostTurnRef, prompt_ref: selection.prompt_ref, turn_generation_ref: selection.turn_generation_ref };
5568
5881
  }
5882
+ async function retireResumedTranscriptRegistration(store, existing, registration) {
5883
+ if (existing === null) return false;
5884
+ if (existing.codex_session_id !== registration.codex_session_id || existing.transcript_path === registration.transcript_path) return false;
5885
+ await store.retireTranscriptRegistration(existing);
5886
+ return true;
5887
+ }
5569
5888
  async function sourceBoundTranscriptPath(path, sessionsRoot) {
5570
5889
  if (!isAbsolute4(path) || !isAbsolute4(sessionsRoot)) throw new CodexHostAdapterError("configuration", "Codex transcript registration paths must be absolute.");
5571
5890
  const transcript = resolve2(path);
@@ -5614,7 +5933,7 @@ function isRecord8(value) {
5614
5933
  // host/producer-service.ts
5615
5934
  import { posix as posix4, win32 as win325 } from "node:path";
5616
5935
  import { constants as constants6 } from "node:fs";
5617
- import { lstat as lstat3 } from "node:fs/promises";
5936
+ import { lstat as lstat5 } from "node:fs/promises";
5618
5937
  var SAFE_REF6 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
5619
5938
  var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
5620
5939
  var HostProducerServiceError = class extends Error {
@@ -5743,7 +6062,7 @@ function assertProducerAbsolutePath(value, platform, kind, error) {
5743
6062
  }
5744
6063
  async function configPathStat(configPath, error) {
5745
6064
  try {
5746
- return await lstat3(configPath);
6065
+ return await lstat5(configPath);
5747
6066
  } catch {
5748
6067
  throw error("config_unavailable");
5749
6068
  }
@@ -5879,9 +6198,16 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
5879
6198
  transcriptPathOf(registration) {
5880
6199
  return registration.transcript_path;
5881
6200
  }
6201
+ registrationKey(registration) {
6202
+ return `${registration.host_source_ref}\0${registration.host_session_ref}`;
6203
+ }
5882
6204
  async listRegistrations() {
5883
6205
  return this.store.listTranscriptRegistrations();
5884
6206
  }
6207
+ async scanFingerprint(registration) {
6208
+ const transcript = await super.scanFingerprint(registration);
6209
+ return transcript === null ? null : `${transcript}|${await this.store.transcriptCursorFingerprint(registration)}`;
6210
+ }
5885
6211
  async scanOpened(handle, registration) {
5886
6212
  const { size, device, inode } = await ownedCodexTranscriptFile(handle);
5887
6213
  const preflight = await this.preflight(registration, handle, size, device, inode);
@@ -5891,7 +6217,7 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
5891
6217
  if (complete === "empty" || complete === "partial") {
5892
6218
  return { records: 0, enqueued: 0, quarantined: false };
5893
6219
  }
5894
- return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
6220
+ return { ...await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode), retry: preflight.cursor.offset + complete.length < size };
5895
6221
  }
5896
6222
  async scanFailed(handle, registration, error) {
5897
6223
  this.diagnostic("watcher_scan_failed", codexTranscriptScanFailureKind(error));
@@ -6210,11 +6536,14 @@ function assertRecordSequence(registration, cursor, records, lastOrdinal, record
6210
6536
  }
6211
6537
 
6212
6538
  // host/codex/src/codex-producer-runtime.ts
6213
- async function drainCodexProducerOnce(options) {
6214
- const scan = await new CodexTranscriptWatcher({
6215
- outbox_dir: options.outbox_dir,
6539
+ function createCodexProducerWatcher(outboxDir) {
6540
+ return new CodexTranscriptWatcher({
6541
+ outbox_dir: outboxDir,
6216
6542
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
6217
- }).scanOnce().catch((error) => {
6543
+ });
6544
+ }
6545
+ async function drainCodexProducerOnce(options, signal) {
6546
+ const scan = await (options.watcher ?? createCodexProducerWatcher(options.outbox_dir)).scanOnce(signal).catch((error) => {
6218
6547
  writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
6219
6548
  throw error;
6220
6549
  });
@@ -6229,17 +6558,34 @@ var CodexUsageFactsCapturer = class {
6229
6558
  usage;
6230
6559
  now;
6231
6560
  registrations;
6561
+ idleGate;
6232
6562
  constructor(options) {
6233
6563
  this.sources = new CodexOutboxStore(options.outbox_dir);
6234
6564
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
6235
6565
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
6236
6566
  this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
6567
+ this.idleGate = new HostUsageIdleGate();
6237
6568
  }
6238
6569
  async captureNext() {
6239
6570
  const registrations = await this.sources.listTranscriptRegistrations();
6240
6571
  return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
6241
6572
  }
6242
6573
  async captureRegistration(registration) {
6574
+ const idleKey = `${registration.host_source_ref}\0${registration.host_session_ref}`;
6575
+ const transcriptKey = `${idleKey}\0transcript`;
6576
+ const stateKey = `${idleKey}\0state`;
6577
+ const transcriptCheck = await this.idleGate.checkUnchanged(transcriptKey, registration.transcript_path);
6578
+ let stateCheck;
6579
+ if (transcriptCheck.unchanged) {
6580
+ stateCheck = await this.idleGate.checkUnchanged(stateKey, this.usage.statePath("codex", registration.host_source_ref, registration.host_session_ref));
6581
+ if (stateCheck.unchanged) return false;
6582
+ }
6583
+ const captured = await this.scanRegistration(registration);
6584
+ this.idleGate.confirmUnchanged(transcriptKey, transcriptCheck.signature);
6585
+ if (stateCheck !== void 0) this.idleGate.confirmUnchanged(stateKey, stateCheck.signature);
6586
+ return captured;
6587
+ }
6588
+ async scanRegistration(registration) {
6243
6589
  const prepared = await openHostUsageTranscriptCursor({
6244
6590
  path: registration.transcript_path,
6245
6591
  producer: "codex",
@@ -6456,7 +6802,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
6456
6802
  producer_id: "codex",
6457
6803
  extra_paths: [CODEX_SESSIONS_ROOT],
6458
6804
  config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
6459
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6805
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createCodexProducerWatcher(config.outbox_dir) }),
6460
6806
  drain: drainCodexProducerOnce,
6461
6807
  background: (config, signal, dependencies) => {
6462
6808
  const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });