@corca-org/ceal-host-win32-x64 1.0.25 → 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.
@@ -6,7 +6,7 @@ const require = __cealCreateRequire(import.meta.url);
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { realpath } from "node:fs/promises";
8
8
  import { homedir } from "node:os";
9
- import { isAbsolute as isAbsolute5, relative, resolve as resolve2 } from "node:path";
9
+ import { isAbsolute as isAbsolute4, relative, resolve as resolve2 } from "node:path";
10
10
 
11
11
  // packages/ceal-client-protocol/src/vocabulary.ts
12
12
  function vocabulary(words) {
@@ -436,7 +436,7 @@ var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
436
436
  var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
437
437
  var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
438
438
  var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
439
- 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"]);
440
440
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
441
441
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
442
442
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -829,6 +829,7 @@ function requireIsoTimestamp(value, message) {
829
829
  // packages/ceal-client-protocol/src/failure-guidance-table.ts
830
830
  var CEAL_FAILURE_REDACTION_CLASSES = vocabulary(["model_safe", "withheld"]);
831
831
  var CEAL_GATEWAY_STARTING_FAILURE_CODE = "gateway_starting";
832
+ var CEAL_GATEWAY_RESTARTING_FAILURE_CODE = "gateway_restarting";
832
833
  var CEAL_OWNER_BOOTSTRAP_ABSENT_FAILURE_CODE = "bootstrap_absent";
833
834
  var CEAL_OWNER_BOOTSTRAP_UNAVAILABLE_FAILURE_CODE = "bootstrap_unavailable";
834
835
  var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
@@ -839,6 +840,7 @@ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
839
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}\`.`;
840
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.";
841
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.";
842
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.";
843
845
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
844
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.";
@@ -893,6 +895,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
893
895
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
894
896
  // The serving gate answers before refresh execution, so retrying the same attempt is safe.
895
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),
896
900
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
897
901
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
898
902
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -1000,6 +1004,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1000
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),
1001
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),
1002
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),
1003
1008
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
1004
1009
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
1005
1010
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
@@ -1370,6 +1375,10 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1370
1375
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
1371
1376
  });
1372
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
+
1373
1382
  // packages/ceal-client-protocol/src/gateway-installation-activation.ts
1374
1383
  var CEAL_GATEWAY_INSTALLATION_ACTIVATION_CODE_DATA_CHARACTERS = 32;
1375
1384
  var CEAL_GATEWAY_INSTALLATION_ACTIVATION_CODE_CHECK_CHARACTERS = 8;
@@ -1392,6 +1401,7 @@ var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUI
1392
1401
  var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1393
1402
 
1394
1403
  // packages/ceal-client-protocol/src/resource-read-result.ts
1404
+ var CEAL_RESOURCE_GET_CHILD_REF_KINDS = Object.freeze(["section", "slide", "question"]);
1395
1405
  var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
1396
1406
  var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
1397
1407
  var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
@@ -1595,6 +1605,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1595
1605
  "github.review.submitted",
1596
1606
  "github.issue_comment.created",
1597
1607
  "github.review_comment.created",
1608
+ "github.issue_comment.edited",
1609
+ "github.review_comment.edited",
1598
1610
  "github.reaction.created",
1599
1611
  "github.reaction.deleted",
1600
1612
  "github.pull_request.review_requested",
@@ -1623,6 +1635,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1623
1635
  "github.release.published": "release_published",
1624
1636
  "github.issue.edited": "resource_modified",
1625
1637
  "github.pull_request.edited": "resource_modified",
1638
+ "github.issue_comment.edited": "resource_modified",
1639
+ "github.review_comment.edited": "resource_modified",
1626
1640
  "github.reaction.created": "reaction_created",
1627
1641
  "github.reaction.deleted": "ceal_write_completed",
1628
1642
  "github.pull_request.review_requested": "ceal_write_completed",
@@ -2281,6 +2295,8 @@ var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
2281
2295
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
2282
2296
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
2283
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"]);
2284
2300
  function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
2285
2301
  const messages = [];
2286
2302
  let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
@@ -2364,6 +2380,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
2364
2380
  "context_replaced",
2365
2381
  "no_binding",
2366
2382
  "context_expired",
2383
+ "transcript_unavailable",
2367
2384
  "host_source_refused",
2368
2385
  "host_credential_refused",
2369
2386
  "gateway_unavailable",
@@ -2405,6 +2422,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2405
2422
  // useful retry until the consumer is running inside a Host session.
2406
2423
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2407
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" }),
2408
2430
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
2409
2431
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
2410
2432
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
@@ -2506,11 +2528,15 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2506
2528
 
2507
2529
  // packages/ceal-client-protocol/src/operator-diagnostic.ts
2508
2530
  var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2509
- var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2531
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES = 8;
2510
2532
  var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2511
2533
  var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2512
2534
  var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2513
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");
2514
2540
  function redactOperatorDiagnosticSecrets(value) {
2515
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]");
2516
2542
  }
@@ -2519,8 +2545,9 @@ function redactOperatorDiagnosticText(value) {
2519
2545
  return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2520
2546
  }
2521
2547
  function renderOperatorDiagnostic(value) {
2522
- const state = collectDiagnosticState(value);
2548
+ const state = collectDiagnosticState(value, read(value, LOCAL_OPERATOR_DIAGNOSTIC_PATHS) === true);
2523
2549
  const fields = [
2550
+ state.truncated ? "causes_truncated=true" : void 0,
2524
2551
  state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2525
2552
  state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2526
2553
  state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
@@ -2530,23 +2557,27 @@ function renderOperatorDiagnostic(value) {
2530
2557
  const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2531
2558
  return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2532
2559
  }
2533
- function collectDiagnosticState(value) {
2534
- 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 };
2535
2562
  const visited = /* @__PURE__ */ new Set(), pending = [value];
2536
- 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) {
2537
2565
  const current = pending.shift();
2538
- 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);
2539
2569
  }
2570
+ state.truncated ||= pending.length > 0;
2540
2571
  return state;
2541
2572
  }
2542
- function visitDiagnosticNode(current, state, pending, visited) {
2573
+ function visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths) {
2543
2574
  if (isObject(current)) {
2544
2575
  if (visited.has(current)) return;
2545
2576
  visited.add(current);
2546
2577
  }
2547
2578
  captureProcessEvidence(current, state);
2548
- appendCause(current, state.causes);
2549
- enqueueCauseChildren(current, state.causes.length, pending);
2579
+ appendCause(current, state.causes, preserveLocalAbsolutePaths);
2580
+ enqueueCauseChildren(current, state, pending);
2550
2581
  }
2551
2582
  function captureProcessEvidence(current, state) {
2552
2583
  if (state.status === void 0) state.status = safeStatus(read(current, "status"));
@@ -2554,10 +2585,9 @@ function captureProcessEvidence(current, state) {
2554
2585
  if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2555
2586
  if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2556
2587
  }
2557
- function appendCause(current, causes) {
2558
- const errors = read(current, "errors");
2559
- if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2560
- causes.push(errorCause(current));
2588
+ function appendCause(current, causes, preserveLocalAbsolutePaths) {
2589
+ if (current instanceof Error) {
2590
+ causes.push(errorCause(current, preserveLocalAbsolutePaths));
2561
2591
  return;
2562
2592
  }
2563
2593
  if (!isObject(current)) {
@@ -2565,7 +2595,7 @@ function appendCause(current, causes) {
2565
2595
  if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2566
2596
  }
2567
2597
  }
2568
- function errorCause(error) {
2598
+ function errorCause(error, preserveLocalAbsolutePaths) {
2569
2599
  const name = safeText(read(error, "name")) ?? "Error";
2570
2600
  const message = safeText(read(error, "message"));
2571
2601
  const codeValue = read(error, "code");
@@ -2573,14 +2603,29 @@ function errorCause(error) {
2573
2603
  const errnoValue = read(error, "errno");
2574
2604
  const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2575
2605
  const syscall = safeText(read(error, "syscall"));
2576
- const path = safePath(read(error, "path"));
2606
+ const path = safePath(read(error, "path"), preserveLocalAbsolutePaths);
2577
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 } });
2578
2608
  }
2579
- function enqueueCauseChildren(current, causeCount, pending) {
2609
+ function enqueueCauseChildren(current, state, pending) {
2580
2610
  const cause = read(current, "cause");
2581
2611
  if (cause !== void 0) pending.push(cause);
2582
2612
  const errors = read(current, "errors");
2583
- 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
+ }
2584
2629
  }
2585
2630
  function isObject(value) {
2586
2631
  return typeof value === "object" && value !== null;
@@ -2609,10 +2654,11 @@ function safeText(value) {
2609
2654
  const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2610
2655
  return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2611
2656
  }
2612
- function safePath(value) {
2657
+ function safePath(value, preserveLocalAbsolutePaths) {
2613
2658
  if (typeof value !== "string") return void 0;
2614
2659
  const safe = safeDiagnosticText(value);
2615
2660
  if (safe.length === 0) return void 0;
2661
+ if (!preserveLocalAbsolutePaths && hasAbsolutePathPrefix(value) && !safe.startsWith("[home path redacted]")) return "[path redacted]";
2616
2662
  if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2617
2663
  const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2618
2664
  const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
@@ -2684,7 +2730,10 @@ function redactUrls(value) {
2684
2730
  return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2685
2731
  }
2686
2732
  function redactFilePaths(value) {
2687
- 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);
2688
2737
  }
2689
2738
  function homePathRange(value, match, prefixLength) {
2690
2739
  const index = match.index;
@@ -2916,8 +2965,8 @@ function reject(message) {
2916
2965
  }
2917
2966
 
2918
2967
  // host/codex/src/codex-outbox.ts
2919
- import { mkdir as mkdir4, open as open4, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
2920
- import { dirname as dirname6, isAbsolute as isAbsolute4, join as join5 } 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";
2921
2970
 
2922
2971
  // host/invocation-context.ts
2923
2972
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2974,98 +3023,18 @@ function safeRef(value) {
2974
3023
  var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2975
3024
  var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "turn_terminal", "producer_status"];
2976
3025
  var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
2977
- var HOST_PRODUCER_FRAME_ERROR_CODES = [
2978
- "invalid_frame_encoding",
2979
- "invalid_frame_length",
2980
- "frame_truncated",
2981
- "unsupported_frame_schema",
2982
- "invalid_frame_shape",
2983
- "invalid_producer_identity",
2984
- "frame_too_large"
2985
- ];
2986
3026
 
2987
3027
  // host/relay/src/host-producer-core.ts
2988
3028
  import { createHash as createHash5 } from "node:crypto";
2989
- import { readdir } from "node:fs/promises";
3029
+ import { isDeepStrictEqual } from "node:util";
3030
+ import { lstat as lstat2, readdir, stat as stat2 } from "node:fs/promises";
2990
3031
 
2991
3032
  // host/secure-file.ts
2992
3033
  import { execFile } from "node:child_process";
2993
3034
  import { constants } from "node:fs";
2994
3035
  import { lstat, open } from "node:fs/promises";
2995
- import { dirname, join as join3, win32 } from "node:path";
3036
+ import { dirname, join as join2, parse, win32 } from "node:path";
2996
3037
  import { fileURLToPath } from "node:url";
2997
-
2998
- // host/spawn-working-directory.ts
2999
- import { mkdirSync } from "node:fs";
3000
- import { tmpdir } from "node:os";
3001
- import { isAbsolute as isAbsolute2, join as join2, normalize, parse, sep } from "node:path";
3002
- function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
3003
- const candidates = [];
3004
- const explicit = candidateDir(stateRoot);
3005
- if (explicit !== void 0) candidates.push(explicit);
3006
- const fallback = defaultHostStateRoot();
3007
- if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
3008
- const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
3009
- if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
3010
- for (const dir of candidates) {
3011
- if (!keptOutside(dir, keepOutside)) continue;
3012
- try {
3013
- mkdirSync(dir, { recursive: true, mode: 448 });
3014
- return dir;
3015
- } catch {
3016
- continue;
3017
- }
3018
- }
3019
- return tmpdir();
3020
- }
3021
- function candidateDir(dir) {
3022
- if (dir === void 0 || dir === "") return void 0;
3023
- if (!isAbsolute2(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
3024
- return normalize(dir);
3025
- }
3026
- function defaultHostStateRoot() {
3027
- if (process.platform === "win32") {
3028
- const localAppData = nonEmptyEnv("LOCALAPPDATA");
3029
- if (localAppData === void 0) return void 0;
3030
- return candidateDir(join2(localAppData, "Ceal", "Host"));
3031
- }
3032
- if (process.platform === "darwin") {
3033
- const home2 = nonEmptyEnv("HOME");
3034
- if (home2 === void 0) return void 0;
3035
- return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
3036
- }
3037
- const xdg = nonEmptyEnv("XDG_STATE_HOME");
3038
- if (xdg !== void 0) {
3039
- const root = candidateDir(join2(xdg, "ceal", "host"));
3040
- if (root !== void 0) return root;
3041
- }
3042
- const home = nonEmptyEnv("HOME");
3043
- if (home === void 0) return void 0;
3044
- return candidateDir(join2(home, ".local", "state", "ceal", "host"));
3045
- }
3046
- function nonEmptyEnv(name) {
3047
- const value = process.env[name];
3048
- return value === void 0 || value === "" ? void 0 : value;
3049
- }
3050
- function keptOutside(dir, keepOutside) {
3051
- for (const tree of keepOutside) {
3052
- const clean = candidateDir(tree);
3053
- if (clean === void 0) continue;
3054
- if (insideDir(dir, clean)) return false;
3055
- }
3056
- return true;
3057
- }
3058
- function insideDir(dir, tree) {
3059
- if (sameDir(dir, tree)) return true;
3060
- if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
3061
- return dir.startsWith(tree + sep);
3062
- }
3063
- function sameDir(left, right) {
3064
- if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
3065
- return left === right;
3066
- }
3067
-
3068
- // host/secure-file.ts
3069
3038
  var SecureFileCustodyError = class extends Error {
3070
3039
  name = "SecureFileCustodyError";
3071
3040
  reason;
@@ -3164,7 +3133,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
3164
3133
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
3165
3134
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
3166
3135
  return await new Promise((resolve3, reject3) => {
3167
- const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: resolveCealSpawnWorkingDirectory() }, (error, stdout, stderr) => {
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) => {
3168
3137
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
3169
3138
  if (exitCode === null) {
3170
3139
  reject3(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -3193,7 +3162,7 @@ function securefsRefusal(stderr) {
3193
3162
  }
3194
3163
  function resolveInstalledHostExecutable(platform) {
3195
3164
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
3196
- return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3165
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3197
3166
  }
3198
3167
  function isRecord3(value) {
3199
3168
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -3217,7 +3186,7 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
3217
3186
 
3218
3187
  // host/service-log.ts
3219
3188
  import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
3220
- import { dirname as dirname2, isAbsolute as isAbsolute3, posix, win32 as win322 } from "node:path";
3189
+ import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win322 } from "node:path";
3221
3190
 
3222
3191
  // host/service-log-delivery.ts
3223
3192
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -3383,7 +3352,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
3383
3352
  await appendHostServiceLogLine(path, line).catch(() => void 0);
3384
3353
  }
3385
3354
  async function appendHostServiceLogLine(path, line) {
3386
- if (!isAbsolute3(path)) return;
3355
+ if (!isAbsolute2(path)) return;
3387
3356
  await ensureHostServiceLogDirectory(path);
3388
3357
  await appendFile(path, line);
3389
3358
  }
@@ -3422,7 +3391,9 @@ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
3422
3391
  seen.add(message.host_input_ref);
3423
3392
  newestFirst.push(message);
3424
3393
  }
3425
- 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);
3426
3397
  }
3427
3398
  function transcriptScanFailureKind(error, adapterFailureKind) {
3428
3399
  if (transcriptErrorCode(error) === "ELOOP") return "symlink";
@@ -3479,6 +3450,15 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
3479
3450
  if (cursor.offset > 0 && !await transcriptAnchorMatches(handle, cursor)) return "transcript_rewritten";
3480
3451
  return null;
3481
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
+ }
3482
3462
  function transcriptSha256(value) {
3483
3463
  return createHash5("sha256").update(value).digest("hex");
3484
3464
  }
@@ -3511,27 +3491,71 @@ function createTranscriptWatcherBase(options, owner) {
3511
3491
  producerInstallationRef: options.producer_installation_ref
3512
3492
  };
3513
3493
  }
3514
- async function scanTranscriptRegistrations(registrations, scanOne) {
3494
+ async function scanTranscriptRegistrations(registrations, scanOne, totalRegistrations, signal) {
3515
3495
  let records = 0;
3516
3496
  let enqueued = 0;
3517
3497
  let quarantined = 0;
3498
+ let scanned = 0;
3518
3499
  for (const registration of registrations) {
3500
+ if (signal?.aborted) break;
3501
+ scanned += 1;
3519
3502
  const result = await scanOne(registration);
3520
3503
  records += result.records;
3521
3504
  enqueued += result.enqueued;
3522
3505
  if (result.quarantined) quarantined += 1;
3523
3506
  }
3524
- 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
+ }
3525
3542
  }
3526
3543
  function formatRetiredTranscriptLog(producerLabel, transcriptPath) {
3527
3544
  return `${producerLabel} retired a transcript registration: transcript_path=${JSON.stringify(transcriptPath)}, reason=${TRANSCRIPT_MISSING_REASON}.`;
3528
3545
  }
3546
+ var HOST_TRANSCRIPT_RECONCILIATION_BATCH = 100;
3529
3547
  var HostTranscriptWatcher = class {
3530
3548
  outboxRetentionMs;
3531
3549
  now;
3532
3550
  log;
3533
3551
  producerInstallationRef;
3534
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;
3535
3559
  constructor(options, owner) {
3536
3560
  const base = createTranscriptWatcherBase(options, owner);
3537
3561
  this.outboxRetentionMs = base.outboxRetentionMs;
@@ -3540,8 +3564,97 @@ var HostTranscriptWatcher = class {
3540
3564
  this.producerInstallationRef = base.producerInstallationRef;
3541
3565
  this.clockFailure = owner.clock_failure;
3542
3566
  }
3543
- async scanOnce() {
3544
- 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
+ }
3545
3658
  }
3546
3659
  async scanRegistration(registration) {
3547
3660
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
@@ -3642,7 +3755,7 @@ var HostProducerDrainCore = class {
3642
3755
  };
3643
3756
 
3644
3757
  // host/relay/src/durable-atomic-replacement.ts
3645
- 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";
3646
3759
  import { dirname as dirname3 } from "node:path";
3647
3760
 
3648
3761
  // host/windows-rename-retry.ts
@@ -3664,7 +3777,7 @@ function resolveRetrySchedule(tuning) {
3664
3777
  startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
3665
3778
  maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
3666
3779
  sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
3667
- now: tuning.now ?? (() => Date.now())
3780
+ now: tuning.now ?? (() => performance.now())
3668
3781
  };
3669
3782
  }
3670
3783
  async function renameWithWindowsRetry(operation, tuning) {
@@ -3697,7 +3810,7 @@ function isRetryableRenameError(error) {
3697
3810
  var DEFAULT_PORT = {
3698
3811
  platform: process.platform,
3699
3812
  mkdir: (path, options) => mkdir2(path, options),
3700
- lstat: (path) => lstat2(path),
3813
+ lstat: (path) => lstat3(path),
3701
3814
  open_file: (path) => open2(path, "wx", 384),
3702
3815
  rename,
3703
3816
  unlink,
@@ -3776,7 +3889,7 @@ function errorCode(error) {
3776
3889
  import { createHash as createHash6 } from "node:crypto";
3777
3890
  import { constants as constants2 } from "node:fs";
3778
3891
  import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3779
- import { dirname as dirname4, join as join4 } from "node:path";
3892
+ import { dirname as dirname4, join as join3 } from "node:path";
3780
3893
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3781
3894
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3782
3895
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -3795,10 +3908,12 @@ var HostUsageFactsStore = class {
3795
3908
  afterPendingWrite;
3796
3909
  afterBatchPublish;
3797
3910
  sessionDirectoryCursor;
3911
+ uploadScanSignature;
3912
+ uploadScanEmpty = false;
3798
3913
  constructor(options) {
3799
- this.root = join4(options.outbox_dir, "usage-facts");
3800
- this.sessions = join4(this.root, "sessions");
3801
- this.batches = join4(this.root, "batches");
3914
+ this.root = join3(options.outbox_dir, "usage-facts");
3915
+ this.sessions = join3(this.root, "sessions");
3916
+ this.batches = join3(this.root, "batches");
3802
3917
  this.platform = options.platform ?? process.platform;
3803
3918
  this.custody = options.secure_file_custody ?? {};
3804
3919
  this.afterPendingWrite = options.afterPendingWrite;
@@ -3814,6 +3929,10 @@ var HostUsageFactsStore = class {
3814
3929
  this.sessionDirectoryCursor = void 0;
3815
3930
  await cursor?.close();
3816
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
+ }
3817
3936
  async readState(producer, hostSourceRef, hostSessionRef) {
3818
3937
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3819
3938
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
@@ -3889,7 +4008,7 @@ var HostUsageFactsStore = class {
3889
4008
  if (entry === null) break;
3890
4009
  inspected += 1;
3891
4010
  if (!isOrphanBatchEntry(entry, expected)) continue;
3892
- await unlink2(join4(directoryPath, entry.name));
4011
+ await unlink2(join3(directoryPath, entry.name));
3893
4012
  deleted += 1;
3894
4013
  }
3895
4014
  } finally {
@@ -3917,9 +4036,17 @@ var HostUsageFactsStore = class {
3917
4036
  });
3918
4037
  }
3919
4038
  async nextUploadCandidate(producer, hostSourceRef) {
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) {
3920
4047
  const names = await this.readNextSessionNames();
3921
4048
  for (const name of names) {
3922
- const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
4049
+ const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3923
4050
  if (state === null) continue;
3924
4051
  validateStateOwner(state, producer, hostSourceRef);
3925
4052
  let validated = state;
@@ -4107,14 +4234,14 @@ var HostUsageFactsStore = class {
4107
4234
  }
4108
4235
  }
4109
4236
  sessionPath(producer, hostSourceRef, hostSessionRef) {
4110
- return join4(this.sessions, `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
4237
+ return join3(this.sessions, `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
4111
4238
  }
4112
4239
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
4113
4240
  const sessionName = `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
4114
- return join4(this.batches, sessionName.slice(0, -5));
4241
+ return join3(this.batches, sessionName.slice(0, -5));
4115
4242
  }
4116
4243
  batchPath(state, batchRef) {
4117
- return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
4244
+ return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
4118
4245
  }
4119
4246
  };
4120
4247
  function serializeBatch(batch) {
@@ -4355,6 +4482,8 @@ function sha2563(value) {
4355
4482
 
4356
4483
  // host/relay/src/host-usage-facts-capture.ts
4357
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";
4358
4487
  var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
4359
4488
  var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
4360
4489
  var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
@@ -4404,6 +4533,55 @@ var HostUsageRegistrationCapture = class {
4404
4533
  return captured;
4405
4534
  }
4406
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
+ }
4407
4585
  async function openHostUsageTranscriptCursor(input) {
4408
4586
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
4409
4587
  let source;
@@ -4474,7 +4652,7 @@ function completeLinePrefix(bytes, baseOffset) {
4474
4652
 
4475
4653
  // host/relay/src/host-registration-state.ts
4476
4654
  import { constants as constants4 } from "node:fs";
4477
- import { dirname as dirname5 } from "node:path";
4655
+ import { dirname as dirname6 } from "node:path";
4478
4656
 
4479
4657
  // host/runtime-source-paths.ts
4480
4658
  import { createHash as createHash7 } from "node:crypto";
@@ -4543,7 +4721,7 @@ var HostRegistrationStateError = class extends Error {
4543
4721
  async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
4544
4722
  let raw;
4545
4723
  try {
4546
- await assertPrivateRegistrationDirectory(dirname5(path), platform, custody);
4724
+ await assertPrivateRegistrationDirectory(dirname6(path), platform, custody);
4547
4725
  raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
4548
4726
  } catch (error) {
4549
4727
  throw registrationReadError(error);
@@ -4718,15 +4896,12 @@ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4718
4896
  }
4719
4897
  }
4720
4898
 
4721
- // host/relay/src/relay-quarantine-store.ts
4722
- var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
4723
- var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
4724
- var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
4725
-
4726
4899
  // host/relay/src/relay-admission-store.ts
4727
- var DEFAULT_LIMITS = { global_count: 8192, global_bytes: 64 * 1024 * 1024, producer_count: 4096, producer_bytes: 32 * 1024 * 1024 };
4728
- var RETRY_SECONDS = [1, 2, 4, 8, 16, 32, 60];
4729
- 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");
4730
4905
 
4731
4906
  // host/relay/src/relay-pipe-handshake.ts
4732
4907
  var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
@@ -4785,15 +4960,16 @@ var CodexOutboxStore = class {
4785
4960
  turnSelectionsDirectory;
4786
4961
  registrationsDirectory;
4787
4962
  cursorsDirectory;
4963
+ registrationInventory = new HostRegistrationInventory();
4788
4964
  constructor(directory) {
4789
4965
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
4790
4966
  this.directory = directory;
4791
- this.entriesDirectory = join5(directory, "entries");
4792
- this.sessionsDirectory = join5(directory, "sessions");
4793
- this.activeContextsDirectory = join5(directory, "active-contexts");
4794
- this.turnSelectionsDirectory = join5(directory, "turn-selections");
4795
- this.registrationsDirectory = join5(directory, "transcript-registrations");
4796
- this.cursorsDirectory = join5(directory, "transcript-cursors");
4967
+ this.entriesDirectory = join4(directory, "entries");
4968
+ this.sessionsDirectory = join4(directory, "sessions");
4969
+ this.activeContextsDirectory = join4(directory, "active-contexts");
4970
+ this.turnSelectionsDirectory = join4(directory, "turn-selections");
4971
+ this.registrationsDirectory = join4(directory, "transcript-registrations");
4972
+ this.cursorsDirectory = join4(directory, "transcript-cursors");
4797
4973
  }
4798
4974
  async prepare() {
4799
4975
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -4811,7 +4987,7 @@ var CodexOutboxStore = class {
4811
4987
  for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
4812
4988
  if (!name.endsWith(".json")) continue;
4813
4989
  try {
4814
- const value = JSON.parse(await readOwnerStateFile(join5(this.entriesDirectory, name)));
4990
+ const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
4815
4991
  validateEnvelope(value);
4816
4992
  entries.push(value);
4817
4993
  } catch {
@@ -4936,22 +5112,33 @@ var CodexOutboxStore = class {
4936
5112
  return registration;
4937
5113
  }
4938
5114
  async listTranscriptRegistrations() {
4939
- const registrations = [];
4940
- for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
4941
- if (!name.endsWith(".json")) continue;
4942
- try {
4943
- const value = JSON.parse(await readOwnerStateFile(join5(this.registrationsDirectory, name)));
4944
- validateRegistration(value);
4945
- registrations.push(value);
4946
- } 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
+ }
4947
5125
  }
4948
- }
4949
- 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
+ });
4950
5128
  }
4951
5129
  async readTranscriptCursor(registration) {
4952
5130
  validateRegistration(registration);
4953
5131
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
4954
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
+ }
4955
5142
  async writeTranscriptCursor(cursor) {
4956
5143
  validateCursor(cursor);
4957
5144
  await this.prepare();
@@ -4972,22 +5159,22 @@ var CodexOutboxStore = class {
4972
5159
  }
4973
5160
  entryPath(submissionRef) {
4974
5161
  if (!SAFE_REF3.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
4975
- return join5(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
5162
+ return join4(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
4976
5163
  }
4977
5164
  sessionPath(sourceRef, sessionRef) {
4978
- return join5(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
5165
+ return join4(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
4979
5166
  }
4980
5167
  activeContextPath(identity) {
4981
- return join5(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
5168
+ return join4(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
4982
5169
  }
4983
5170
  turnSelectionPath(sourceRef, sessionRef) {
4984
- return join5(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
5171
+ return join4(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
4985
5172
  }
4986
5173
  registrationPath(sourceRef, sessionRef) {
4987
- return join5(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
5174
+ return join4(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4988
5175
  }
4989
5176
  cursorPath(sourceRef, sessionRef) {
4990
- return join5(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
5177
+ return join4(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4991
5178
  }
4992
5179
  };
4993
5180
  async function removeOwnerState(path, what) {
@@ -5031,7 +5218,7 @@ async function writeAtomicJson(path, value) {
5031
5218
  await handle.close();
5032
5219
  }
5033
5220
  await rename2(temp, path);
5034
- await syncDirectory2(dirname6(path));
5221
+ await syncDirectory2(dirname7(path));
5035
5222
  } catch (error) {
5036
5223
  try {
5037
5224
  await unlink3(temp);
@@ -5066,14 +5253,14 @@ async function readOptionalJson2(path, validate) {
5066
5253
  async function ensureOwnerDirectory(path) {
5067
5254
  try {
5068
5255
  try {
5069
- const stats2 = await stat2(path);
5256
+ const stats2 = await stat3(path);
5070
5257
  if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
5071
5258
  return;
5072
5259
  } catch (error) {
5073
5260
  if (!isNotFound(error)) throw error;
5074
5261
  }
5075
5262
  await mkdir4(path, { recursive: true, mode: 448 });
5076
- const stats = await stat2(path);
5263
+ const stats = await stat3(path);
5077
5264
  if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
5078
5265
  } catch (error) {
5079
5266
  if (error instanceof CodexHostAdapterError) throw error;
@@ -5121,7 +5308,7 @@ function validateRegistrationFields(value) {
5121
5308
  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 }])}).`);
5122
5309
  }
5123
5310
  function validRegistrationCwd(value) {
5124
- return value === void 0 || typeof value === "string" && isAbsolute4(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
5311
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
5125
5312
  }
5126
5313
  function validateCursor(value) {
5127
5314
  if (!isRecord6(value)) throw storageError("Codex transcript cursor is malformed.");
@@ -5352,32 +5539,51 @@ function decodeTokenUsage(value) {
5352
5539
  }
5353
5540
  function decodeResponseItem(payload, ordinal, timestamp4) {
5354
5541
  if (payload.type !== "message" || payload.role !== "user") return { kind: "ignored", ordinal, timestamp: timestamp4 };
5355
- const metadata = userMessageMetadata(payload.internal_chat_message_metadata_passthrough);
5356
- const contentItemKind = userTextContentKind(metadata.content_item_kinds);
5357
- if (contentItemKind === void 0) return { kind: "ignored", ordinal, timestamp: timestamp4 };
5358
- 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 };
5359
5546
  return {
5360
5547
  kind: "user_text",
5361
5548
  ordinal,
5362
5549
  timestamp: timestamp4,
5363
- prompt,
5364
- content_item_kind: contentItemKind,
5550
+ prompt: prompt.text,
5551
+ content_item_kind: prompt.kind,
5365
5552
  message_id: safeRef3(payload.id, "Codex user message identity is invalid."),
5366
- 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.")
5367
5554
  };
5368
5555
  }
5369
- function userTextContentKind(kinds) {
5370
- 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 };
5371
5560
  }
5372
- function userMessageMetadata(value) {
5373
- if (!isRecord7(value) || !Array.isArray(value.content_item_kinds)) reject2("Codex user message provenance is malformed.");
5374
- return { ...value, content_item_kinds: value.content_item_kinds };
5375
- }
5376
- function userTextContent(value) {
5561
+ function userTextContent(value, kinds) {
5377
5562
  if (!Array.isArray(value)) reject2(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
5378
- if (value.length !== 1) reject2(`Codex user text content is malformed (${refusalFact("items", value.length, "exactly one")}).`);
5379
- 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")}).`);
5380
- 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.");
5381
5587
  }
5382
5588
  function safeOrdinal(value) {
5383
5589
  if (!Number.isSafeInteger(value) || Number(value) < 0) reject2("Codex transcript ordinal is invalid.");
@@ -5574,15 +5780,15 @@ function timestamp2(now) {
5574
5780
  }
5575
5781
 
5576
5782
  // host/codex/src/codex-runtime-paths.ts
5577
- import { join as join6 } from "node:path";
5783
+ import { join as join5 } from "node:path";
5578
5784
  var CODEX_HOME_ENVIRONMENT = "CODEX_HOME";
5579
5785
  var CODEX_HOME_DEFAULT_DIRECTORY = ".codex";
5580
5786
  var CODEX_SESSIONS_DIRECTORY = "sessions";
5581
5787
  function resolveCodexHome(environment, home) {
5582
- return environment[CODEX_HOME_ENVIRONMENT] || join6(home, CODEX_HOME_DEFAULT_DIRECTORY);
5788
+ return environment[CODEX_HOME_ENVIRONMENT] || join5(home, CODEX_HOME_DEFAULT_DIRECTORY);
5583
5789
  }
5584
5790
  function resolveCodexSessionsRoot(environment, home) {
5585
- return join6(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
5791
+ return join5(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
5586
5792
  }
5587
5793
 
5588
5794
  // host/codex/src/codex-adapter.ts
@@ -5620,7 +5826,8 @@ async function registerSession(event, options, store, now, retentionMs) {
5620
5826
  };
5621
5827
  const currentTurn = await selectCurrentTurn(event, options, store, hostSessionRef);
5622
5828
  const existing = await store.readTranscriptRegistration(registration.host_source_ref, registration.host_session_ref);
5623
- if (existing === null) {
5829
+ const resumed = await retireResumedTranscriptRegistration(store, existing, registration);
5830
+ if (existing === null || resumed) {
5624
5831
  await store.writeTranscriptCursor(await captureCodexTranscriptBaseline(registration, now));
5625
5832
  }
5626
5833
  await store.registerTranscript(registration);
@@ -5672,8 +5879,14 @@ async function liveSteeredTurn(options, store, hostSessionRef, hostTurnRef) {
5672
5879
  if (selection === null || selection.prompt_ref !== live.prompt_ref || selection.turn_generation_ref !== live.turn_generation_ref) return void 0;
5673
5880
  return { host_turn_ref: hostTurnRef, prompt_ref: selection.prompt_ref, turn_generation_ref: selection.turn_generation_ref };
5674
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
+ }
5675
5888
  async function sourceBoundTranscriptPath(path, sessionsRoot) {
5676
- if (!isAbsolute5(path) || !isAbsolute5(sessionsRoot)) throw new CodexHostAdapterError("configuration", "Codex transcript registration paths must be absolute.");
5889
+ if (!isAbsolute4(path) || !isAbsolute4(sessionsRoot)) throw new CodexHostAdapterError("configuration", "Codex transcript registration paths must be absolute.");
5677
5890
  const transcript = resolve2(path);
5678
5891
  const root = resolve2(sessionsRoot);
5679
5892
  assertTranscriptChild(root, transcript);
@@ -5683,7 +5896,7 @@ async function sourceBoundTranscriptPath(path, sessionsRoot) {
5683
5896
  }
5684
5897
  function assertTranscriptChild(root, transcript) {
5685
5898
  const child = relative(root, transcript);
5686
- if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute5(child)) {
5899
+ if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute4(child)) {
5687
5900
  throw new CodexHostAdapterError("payload_rejected", "Codex transcript path is outside the configured sessions root.");
5688
5901
  }
5689
5902
  }
@@ -5705,7 +5918,7 @@ function validateAdapterOwner(options) {
5705
5918
  if (!SAFE_REF5.test(options.host_source_ref) || options.outbox_dir.length === 0) {
5706
5919
  throw new CodexHostAdapterError("configuration", "Codex adapter options are invalid.");
5707
5920
  }
5708
- if (options.codex_sessions_root !== void 0 && !isAbsolute5(options.codex_sessions_root)) throw new CodexHostAdapterError("configuration", "Codex sessions root is invalid.");
5921
+ if (options.codex_sessions_root !== void 0 && !isAbsolute4(options.codex_sessions_root)) throw new CodexHostAdapterError("configuration", "Codex sessions root is invalid.");
5709
5922
  }
5710
5923
  function validateAdapterBehavior(options) {
5711
5924
  if (options.retention_ms !== void 0 && (!Number.isSafeInteger(options.retention_ms) || options.retention_ms < 1)) throw new CodexHostAdapterError("configuration", `Codex retention is invalid (${refusalFact("retention_ms", options.retention_ms, "a positive integer")}).`);
@@ -5720,7 +5933,7 @@ function isRecord8(value) {
5720
5933
  // host/producer-service.ts
5721
5934
  import { posix as posix4, win32 as win325 } from "node:path";
5722
5935
  import { constants as constants6 } from "node:fs";
5723
- import { lstat as lstat3 } from "node:fs/promises";
5936
+ import { lstat as lstat5 } from "node:fs/promises";
5724
5937
  var SAFE_REF6 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
5725
5938
  var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
5726
5939
  var HostProducerServiceError = class extends Error {
@@ -5849,7 +6062,7 @@ function assertProducerAbsolutePath(value, platform, kind, error) {
5849
6062
  }
5850
6063
  async function configPathStat(configPath, error) {
5851
6064
  try {
5852
- return await lstat3(configPath);
6065
+ return await lstat5(configPath);
5853
6066
  } catch {
5854
6067
  throw error("config_unavailable");
5855
6068
  }
@@ -5985,9 +6198,16 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
5985
6198
  transcriptPathOf(registration) {
5986
6199
  return registration.transcript_path;
5987
6200
  }
6201
+ registrationKey(registration) {
6202
+ return `${registration.host_source_ref}\0${registration.host_session_ref}`;
6203
+ }
5988
6204
  async listRegistrations() {
5989
6205
  return this.store.listTranscriptRegistrations();
5990
6206
  }
6207
+ async scanFingerprint(registration) {
6208
+ const transcript = await super.scanFingerprint(registration);
6209
+ return transcript === null ? null : `${transcript}|${await this.store.transcriptCursorFingerprint(registration)}`;
6210
+ }
5991
6211
  async scanOpened(handle, registration) {
5992
6212
  const { size, device, inode } = await ownedCodexTranscriptFile(handle);
5993
6213
  const preflight = await this.preflight(registration, handle, size, device, inode);
@@ -5997,7 +6217,7 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
5997
6217
  if (complete === "empty" || complete === "partial") {
5998
6218
  return { records: 0, enqueued: 0, quarantined: false };
5999
6219
  }
6000
- 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 };
6001
6221
  }
6002
6222
  async scanFailed(handle, registration, error) {
6003
6223
  this.diagnostic("watcher_scan_failed", codexTranscriptScanFailureKind(error));
@@ -6316,11 +6536,14 @@ function assertRecordSequence(registration, cursor, records, lastOrdinal, record
6316
6536
  }
6317
6537
 
6318
6538
  // host/codex/src/codex-producer-runtime.ts
6319
- async function drainCodexProducerOnce(options) {
6320
- const scan = await new CodexTranscriptWatcher({
6321
- outbox_dir: options.outbox_dir,
6539
+ function createCodexProducerWatcher(outboxDir) {
6540
+ return new CodexTranscriptWatcher({
6541
+ outbox_dir: outboxDir,
6322
6542
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
6323
- }).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) => {
6324
6547
  writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
6325
6548
  throw error;
6326
6549
  });
@@ -6335,17 +6558,34 @@ var CodexUsageFactsCapturer = class {
6335
6558
  usage;
6336
6559
  now;
6337
6560
  registrations;
6561
+ idleGate;
6338
6562
  constructor(options) {
6339
6563
  this.sources = new CodexOutboxStore(options.outbox_dir);
6340
6564
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
6341
6565
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
6342
6566
  this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
6567
+ this.idleGate = new HostUsageIdleGate();
6343
6568
  }
6344
6569
  async captureNext() {
6345
6570
  const registrations = await this.sources.listTranscriptRegistrations();
6346
6571
  return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
6347
6572
  }
6348
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) {
6349
6589
  const prepared = await openHostUsageTranscriptCursor({
6350
6590
  path: registration.transcript_path,
6351
6591
  producer: "codex",
@@ -6562,7 +6802,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
6562
6802
  producer_id: "codex",
6563
6803
  extra_paths: [CODEX_SESSIONS_ROOT],
6564
6804
  config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
6565
- 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) }),
6566
6806
  drain: drainCodexProducerOnce,
6567
6807
  background: (config, signal, dependencies) => {
6568
6808
  const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });