@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.
@@ -484,7 +484,7 @@ var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
484
484
  var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
485
485
  var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
486
486
  var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
487
- var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
487
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "race_recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
488
488
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
489
489
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
490
490
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -877,6 +877,7 @@ function requireIsoTimestamp(value, message) {
877
877
  // packages/ceal-client-protocol/src/failure-guidance-table.ts
878
878
  var CEAL_FAILURE_REDACTION_CLASSES = vocabulary(["model_safe", "withheld"]);
879
879
  var CEAL_GATEWAY_STARTING_FAILURE_CODE = "gateway_starting";
880
+ var CEAL_GATEWAY_RESTARTING_FAILURE_CODE = "gateway_restarting";
880
881
  var CEAL_OWNER_BOOTSTRAP_ABSENT_FAILURE_CODE = "bootstrap_absent";
881
882
  var CEAL_OWNER_BOOTSTRAP_UNAVAILABLE_FAILURE_CODE = "bootstrap_unavailable";
882
883
  var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
@@ -887,6 +888,7 @@ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
887
888
  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}\`.`;
888
889
  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.";
889
890
  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.";
891
+ 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.";
890
892
  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.";
891
893
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
892
894
  var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
@@ -941,6 +943,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
941
943
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
942
944
  // The serving gate answers before refresh execution, so retrying the same attempt is safe.
943
945
  [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),
946
+ // The serving gate answers before execution while the Gateway is stopping, so retrying the same request is safe.
947
+ [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),
944
948
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
945
949
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
946
950
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -1048,6 +1052,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1048
1052
  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),
1049
1053
  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),
1050
1054
  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),
1055
+ host_transcript_unavailable: guidance(HOST_TRANSCRIPT_UNAVAILABLE, "retry", 401, true),
1051
1056
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
1052
1057
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
1053
1058
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
@@ -1418,6 +1423,10 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1418
1423
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
1419
1424
  });
1420
1425
 
1426
+ // packages/ceal-client-protocol/src/canonical-http-boundary.ts
1427
+ var CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE = "^client-exchange:[a-f0-9]{32}$";
1428
+ 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}$";
1429
+
1421
1430
  // packages/ceal-client-protocol/src/gateway-installation-activation.ts
1422
1431
  var CEAL_GATEWAY_INSTALLATION_ACTIVATION_CODE_DATA_CHARACTERS = 32;
1423
1432
  var CEAL_GATEWAY_INSTALLATION_ACTIVATION_CODE_CHECK_CHARACTERS = 8;
@@ -1440,6 +1449,7 @@ var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUI
1440
1449
  var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1441
1450
 
1442
1451
  // packages/ceal-client-protocol/src/resource-read-result.ts
1452
+ var CEAL_RESOURCE_GET_CHILD_REF_KINDS = Object.freeze(["section", "slide", "question"]);
1443
1453
  var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
1444
1454
  var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
1445
1455
  var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
@@ -1643,6 +1653,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1643
1653
  "github.review.submitted",
1644
1654
  "github.issue_comment.created",
1645
1655
  "github.review_comment.created",
1656
+ "github.issue_comment.edited",
1657
+ "github.review_comment.edited",
1646
1658
  "github.reaction.created",
1647
1659
  "github.reaction.deleted",
1648
1660
  "github.pull_request.review_requested",
@@ -1671,6 +1683,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1671
1683
  "github.release.published": "release_published",
1672
1684
  "github.issue.edited": "resource_modified",
1673
1685
  "github.pull_request.edited": "resource_modified",
1686
+ "github.issue_comment.edited": "resource_modified",
1687
+ "github.review_comment.edited": "resource_modified",
1674
1688
  "github.reaction.created": "reaction_created",
1675
1689
  "github.reaction.deleted": "ceal_write_completed",
1676
1690
  "github.pull_request.review_requested": "ceal_write_completed",
@@ -2329,6 +2343,8 @@ var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
2329
2343
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
2330
2344
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
2331
2345
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
2346
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_ENTRY_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text", "text_truncated"]);
2347
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_REQUIRED_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text"]);
2332
2348
  function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
2333
2349
  const messages = [];
2334
2350
  let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
@@ -2412,6 +2428,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
2412
2428
  "context_replaced",
2413
2429
  "no_binding",
2414
2430
  "context_expired",
2431
+ "transcript_unavailable",
2415
2432
  "host_source_refused",
2416
2433
  "host_credential_refused",
2417
2434
  "gateway_unavailable",
@@ -2453,6 +2470,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2453
2470
  // useful retry until the consumer is running inside a Host session.
2454
2471
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2455
2472
  context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
2473
+ // The registered transcript is readable but names no human message for
2474
+ // this turn, so a Gateway mint could only be refused. The caller sends a
2475
+ // new message so the turn hook re-registers the transcript, then retries;
2476
+ // a retry with no new turn cannot bind anything new.
2477
+ transcript_unavailable: Object.freeze({ classification: "host_transcript_unavailable", next_action: "retry" }),
2456
2478
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
2457
2479
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
2458
2480
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
@@ -2554,11 +2576,15 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2554
2576
 
2555
2577
  // packages/ceal-client-protocol/src/operator-diagnostic.ts
2556
2578
  var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2557
- var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2579
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES = 8;
2558
2580
  var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2559
2581
  var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2560
2582
  var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2561
2583
  var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2584
+ var LOCAL_OPERATOR_DIAGNOSTIC_PATHS = /* @__PURE__ */ Symbol.for("ceal.local-operator-diagnostic-paths");
2585
+ var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX = /(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)/u;
2586
+ var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START = new RegExp(`^${OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX.source}`, "u");
2587
+ 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");
2562
2588
  function redactOperatorDiagnosticSecrets(value) {
2563
2589
  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]");
2564
2590
  }
@@ -2567,8 +2593,9 @@ function redactOperatorDiagnosticText(value) {
2567
2593
  return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2568
2594
  }
2569
2595
  function renderOperatorDiagnostic(value) {
2570
- const state = collectDiagnosticState(value);
2596
+ const state = collectDiagnosticState(value, read(value, LOCAL_OPERATOR_DIAGNOSTIC_PATHS) === true);
2571
2597
  const fields = [
2598
+ state.truncated ? "causes_truncated=true" : void 0,
2572
2599
  state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2573
2600
  state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2574
2601
  state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
@@ -2578,23 +2605,27 @@ function renderOperatorDiagnostic(value) {
2578
2605
  const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2579
2606
  return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2580
2607
  }
2581
- function collectDiagnosticState(value) {
2582
- const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2608
+ function collectDiagnosticState(value, preserveLocalAbsolutePaths) {
2609
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0, truncated: false };
2583
2610
  const visited = /* @__PURE__ */ new Set(), pending = [value];
2584
- while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2611
+ let inspected = 0;
2612
+ while (pending.length > 0 && inspected < OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES) {
2585
2613
  const current = pending.shift();
2586
- if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2614
+ if (current === void 0 || isObject(current) && visited.has(current)) continue;
2615
+ inspected += 1;
2616
+ visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths);
2587
2617
  }
2618
+ state.truncated ||= pending.length > 0;
2588
2619
  return state;
2589
2620
  }
2590
- function visitDiagnosticNode(current, state, pending, visited) {
2621
+ function visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths) {
2591
2622
  if (isObject(current)) {
2592
2623
  if (visited.has(current)) return;
2593
2624
  visited.add(current);
2594
2625
  }
2595
2626
  captureProcessEvidence(current, state);
2596
- appendCause(current, state.causes);
2597
- enqueueCauseChildren(current, state.causes.length, pending);
2627
+ appendCause(current, state.causes, preserveLocalAbsolutePaths);
2628
+ enqueueCauseChildren(current, state, pending);
2598
2629
  }
2599
2630
  function captureProcessEvidence(current, state) {
2600
2631
  if (state.status === void 0) state.status = safeStatus(read(current, "status"));
@@ -2602,10 +2633,9 @@ function captureProcessEvidence(current, state) {
2602
2633
  if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2603
2634
  if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2604
2635
  }
2605
- function appendCause(current, causes) {
2606
- const errors = read(current, "errors");
2607
- if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2608
- causes.push(errorCause(current));
2636
+ function appendCause(current, causes, preserveLocalAbsolutePaths) {
2637
+ if (current instanceof Error) {
2638
+ causes.push(errorCause(current, preserveLocalAbsolutePaths));
2609
2639
  return;
2610
2640
  }
2611
2641
  if (!isObject(current)) {
@@ -2613,7 +2643,7 @@ function appendCause(current, causes) {
2613
2643
  if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2614
2644
  }
2615
2645
  }
2616
- function errorCause(error) {
2646
+ function errorCause(error, preserveLocalAbsolutePaths) {
2617
2647
  const name = safeText(read(error, "name")) ?? "Error";
2618
2648
  const message = safeText(read(error, "message"));
2619
2649
  const codeValue = read(error, "code");
@@ -2621,14 +2651,29 @@ function errorCause(error) {
2621
2651
  const errnoValue = read(error, "errno");
2622
2652
  const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2623
2653
  const syscall = safeText(read(error, "syscall"));
2624
- const path = safePath(read(error, "path"));
2654
+ const path = safePath(read(error, "path"), preserveLocalAbsolutePaths);
2625
2655
  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 } });
2626
2656
  }
2627
- function enqueueCauseChildren(current, causeCount, pending) {
2657
+ function enqueueCauseChildren(current, state, pending) {
2628
2658
  const cause = read(current, "cause");
2629
2659
  if (cause !== void 0) pending.push(cause);
2630
2660
  const errors = read(current, "errors");
2631
- if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2661
+ if (Array.isArray(errors)) {
2662
+ const remaining = OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES - state.causes.length;
2663
+ const length = read(errors, "length");
2664
+ if (typeof length !== "number") {
2665
+ state.truncated = true;
2666
+ return;
2667
+ }
2668
+ state.truncated ||= length > remaining;
2669
+ for (let index = 0; index < Math.min(length, remaining); index += 1) {
2670
+ try {
2671
+ pending.push(errors[index]);
2672
+ } catch {
2673
+ state.truncated = true;
2674
+ }
2675
+ }
2676
+ }
2632
2677
  }
2633
2678
  function isObject(value) {
2634
2679
  return typeof value === "object" && value !== null;
@@ -2657,10 +2702,11 @@ function safeText(value) {
2657
2702
  const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2658
2703
  return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2659
2704
  }
2660
- function safePath(value) {
2705
+ function safePath(value, preserveLocalAbsolutePaths) {
2661
2706
  if (typeof value !== "string") return void 0;
2662
2707
  const safe = safeDiagnosticText(value);
2663
2708
  if (safe.length === 0) return void 0;
2709
+ if (!preserveLocalAbsolutePaths && hasAbsolutePathPrefix(value) && !safe.startsWith("[home path redacted]")) return "[path redacted]";
2664
2710
  if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2665
2711
  const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2666
2712
  const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
@@ -2732,7 +2778,10 @@ function redactUrls(value) {
2732
2778
  return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2733
2779
  }
2734
2780
  function redactFilePaths(value) {
2735
- return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2781
+ return value.replaceAll(OPERATOR_DIAGNOSTIC_FREEFORM_PATH_PATTERN, "[path redacted]$2");
2782
+ }
2783
+ function hasAbsolutePathPrefix(value) {
2784
+ return OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START.test(value);
2736
2785
  }
2737
2786
  function homePathRange(value, match, prefixLength) {
2738
2787
  const index = match.index;
@@ -2843,80 +2892,8 @@ function waitForAbort(signal, milliseconds) {
2843
2892
  import { execFile } from "node:child_process";
2844
2893
  import { constants } from "node:fs";
2845
2894
  import { lstat, open } from "node:fs/promises";
2846
- import { dirname, join as join3, win32 as win323 } from "node:path";
2895
+ import { dirname, join as join2, parse, win32 as win323 } from "node:path";
2847
2896
  import { fileURLToPath } from "node:url";
2848
-
2849
- // host/spawn-working-directory.ts
2850
- import { mkdirSync } from "node:fs";
2851
- import { tmpdir } from "node:os";
2852
- import { isAbsolute, join as join2, normalize, parse, sep } from "node:path";
2853
- function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
2854
- const candidates = [];
2855
- const explicit = candidateDir(stateRoot);
2856
- if (explicit !== void 0) candidates.push(explicit);
2857
- const fallback = defaultHostStateRoot();
2858
- if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
2859
- const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
2860
- if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
2861
- for (const dir of candidates) {
2862
- if (!keptOutside(dir, keepOutside)) continue;
2863
- try {
2864
- mkdirSync(dir, { recursive: true, mode: 448 });
2865
- return dir;
2866
- } catch {
2867
- continue;
2868
- }
2869
- }
2870
- return tmpdir();
2871
- }
2872
- function candidateDir(dir) {
2873
- if (dir === void 0 || dir === "") return void 0;
2874
- if (!isAbsolute(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
2875
- return normalize(dir);
2876
- }
2877
- function defaultHostStateRoot() {
2878
- if (process.platform === "win32") {
2879
- const localAppData = nonEmptyEnv("LOCALAPPDATA");
2880
- if (localAppData === void 0) return void 0;
2881
- return candidateDir(join2(localAppData, "Ceal", "Host"));
2882
- }
2883
- if (process.platform === "darwin") {
2884
- const home2 = nonEmptyEnv("HOME");
2885
- if (home2 === void 0) return void 0;
2886
- return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
2887
- }
2888
- const xdg = nonEmptyEnv("XDG_STATE_HOME");
2889
- if (xdg !== void 0) {
2890
- const root = candidateDir(join2(xdg, "ceal", "host"));
2891
- if (root !== void 0) return root;
2892
- }
2893
- const home = nonEmptyEnv("HOME");
2894
- if (home === void 0) return void 0;
2895
- return candidateDir(join2(home, ".local", "state", "ceal", "host"));
2896
- }
2897
- function nonEmptyEnv(name) {
2898
- const value = process.env[name];
2899
- return value === void 0 || value === "" ? void 0 : value;
2900
- }
2901
- function keptOutside(dir, keepOutside) {
2902
- for (const tree of keepOutside) {
2903
- const clean = candidateDir(tree);
2904
- if (clean === void 0) continue;
2905
- if (insideDir(dir, clean)) return false;
2906
- }
2907
- return true;
2908
- }
2909
- function insideDir(dir, tree) {
2910
- if (sameDir(dir, tree)) return true;
2911
- if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
2912
- return dir.startsWith(tree + sep);
2913
- }
2914
- function sameDir(left, right) {
2915
- if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
2916
- return left === right;
2917
- }
2918
-
2919
- // host/secure-file.ts
2920
2897
  var SecureFileCustodyError = class extends Error {
2921
2898
  name = "SecureFileCustodyError";
2922
2899
  reason;
@@ -3015,7 +2992,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
3015
2992
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
3016
2993
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
3017
2994
  return await new Promise((resolve, reject2) => {
3018
- 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) => {
2995
+ 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) => {
3019
2996
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
3020
2997
  if (exitCode === null) {
3021
2998
  reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -3044,7 +3021,7 @@ function securefsRefusal(stderr) {
3044
3021
  }
3045
3022
  function resolveInstalledHostExecutable(platform) {
3046
3023
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
3047
- return platform === "win32" ? win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3024
+ return platform === "win32" ? win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3048
3025
  }
3049
3026
  function isRecord(value) {
3050
3027
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -3193,7 +3170,7 @@ async function serveProducer(runtimeOptions, timing, signal, drain, wait = (mill
3193
3170
  while (!signal.aborted) {
3194
3171
  let delay = timing.reconcile_interval_ms;
3195
3172
  try {
3196
- await drain(runtimeOptions);
3173
+ await drain(runtimeOptions, signal);
3197
3174
  } catch {
3198
3175
  delay = timing.retry_backoff_ms;
3199
3176
  }
@@ -3428,10 +3405,10 @@ function record(value) {
3428
3405
  }
3429
3406
 
3430
3407
  // host/relay/src/host-usage-facts-store.ts
3431
- import { createHash as createHash5 } from "node:crypto";
3408
+ import { createHash as createHash6 } from "node:crypto";
3432
3409
  import { constants as constants4 } from "node:fs";
3433
- import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3434
- import { dirname as dirname4, join as join4 } from "node:path";
3410
+ import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3411
+ import { dirname as dirname5, join as join3 } from "node:path";
3435
3412
 
3436
3413
  // host/relay/src/durable-atomic-replacement.ts
3437
3414
  import { lstat as lstat3, mkdir, open as open2, rename, unlink } from "node:fs/promises";
@@ -3456,7 +3433,7 @@ function resolveRetrySchedule(tuning) {
3456
3433
  startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
3457
3434
  maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
3458
3435
  sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
3459
- now: tuning.now ?? (() => Date.now())
3436
+ now: tuning.now ?? (() => performance.now())
3460
3437
  };
3461
3438
  }
3462
3439
  async function renameWithWindowsRetry(operation, tuning) {
@@ -3564,1154 +3541,1315 @@ function errorCode(error) {
3564
3541
  return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3565
3542
  }
3566
3543
 
3567
- // host/relay/src/host-usage-facts-store.ts
3568
- var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3569
- var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3570
- var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
3571
- var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
3572
- var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
3573
- var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
3574
- var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
3575
- var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
3576
- var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
3577
- var HostUsageFactsStore = class {
3578
- root;
3579
- sessions;
3580
- batches;
3581
- platform;
3582
- custody;
3583
- afterPendingWrite;
3584
- afterBatchPublish;
3585
- sessionDirectoryCursor;
3586
- constructor(options) {
3587
- this.root = join4(options.outbox_dir, "usage-facts");
3588
- this.sessions = join4(this.root, "sessions");
3589
- this.batches = join4(this.root, "batches");
3590
- this.platform = options.platform ?? process.platform;
3591
- this.custody = options.secure_file_custody ?? {};
3592
- this.afterPendingWrite = options.afterPendingWrite;
3593
- this.afterBatchPublish = options.afterBatchPublish;
3594
- }
3595
- async prepare() {
3596
- for (const directory of [this.root, this.sessions, this.batches]) {
3597
- await preparePrivateDirectory(directory, this.platform, this.custody);
3598
- }
3599
- }
3600
- async close() {
3601
- const cursor = this.sessionDirectoryCursor;
3602
- this.sessionDirectoryCursor = void 0;
3603
- await cursor?.close();
3604
- }
3605
- async readState(producer, hostSourceRef, hostSessionRef) {
3606
- const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3607
- const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3608
- if (value === null) return null;
3609
- validateState(value, producer, hostSourceRef, hostSessionRef);
3610
- return value;
3611
- }
3612
- createState(producer, hostSourceRef, hostSessionRef) {
3613
- return {
3614
- schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
3615
- producer,
3616
- host_source_ref: hostSourceRef,
3617
- host_session_ref: hostSessionRef,
3618
- cursors: {},
3619
- eligible_batches: [],
3620
- coverage_gaps: [],
3621
- coverage_gap_created_at: null
3622
- };
3623
- }
3624
- async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
3625
- let state = await this.readState(producer, hostSourceRef, hostSessionRef);
3626
- if (state === null) {
3627
- state = this.createState(producer, hostSourceRef, hostSessionRef);
3628
- state = await this.writeCursor(state, sourceSlot, initial);
3629
- }
3630
- state = await this.recoverPending(state);
3631
- if (state.quarantined_reason !== void 0) return null;
3632
- state = await this.commitCoverageGaps(state, createdAt);
3633
- const cursor = state.cursors[sourceSlot];
3634
- return cursor === void 0 ? null : { state, cursor };
3544
+ // host/relay/src/host-producer-core.ts
3545
+ import { createHash as createHash5 } from "node:crypto";
3546
+ import { isDeepStrictEqual } from "node:util";
3547
+ import { lstat as lstat4, readdir, stat as stat2 } from "node:fs/promises";
3548
+
3549
+ // host/service-log.ts
3550
+ import { copyFile, mkdir as mkdir2, stat, truncate, appendFile } from "node:fs/promises";
3551
+ import { dirname as dirname4, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
3552
+
3553
+ // host/service-log-delivery.ts
3554
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
3555
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
3556
+ setImmediate(flush);
3557
+ }, onDeliveryGap = () => void 0) {
3558
+ const pending = [];
3559
+ const highWaterMark = stream.writableHighWaterMark;
3560
+ const byteBudget = highWaterMark + highWaterMark;
3561
+ let pendingBytes = 0;
3562
+ let droppedLines = 0;
3563
+ let flushScheduled = false;
3564
+ let waitingForDrain = false;
3565
+ let closed = !stream.writable;
3566
+ function stop() {
3567
+ if (closed) return;
3568
+ closed = true;
3569
+ pending.length = 0;
3570
+ pendingBytes = 0;
3571
+ stream.off("drain", onDrain);
3572
+ stream.off("close", onTerminal);
3573
+ stream.off("finish", onTerminal);
3574
+ stream.off("error", onError);
3635
3575
  }
3636
- async writeCursor(state, sourceSlot, cursor) {
3637
- return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3638
- const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3639
- if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
3640
- const current = latest.cursors[sourceSlot];
3641
- if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
3642
- const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
3643
- await this.writeState(updated);
3644
- return updated;
3645
- });
3576
+ function onTerminal() {
3577
+ stop();
3646
3578
  }
3647
- async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
3648
- return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3649
- const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3650
- return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
3651
- });
3579
+ function onError() {
3580
+ stop();
3652
3581
  }
3653
- async recoverPending(state) {
3654
- return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3655
- const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3656
- const recovered = await this.finishPendingTransition(latest);
3657
- await this.sweepOrphanedBatches(recovered);
3658
- return recovered;
3659
- });
3582
+ function onDrain() {
3583
+ waitingForDrain = false;
3584
+ scheduleFlush();
3660
3585
  }
3661
- /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3662
- async sweepOrphanedBatches(state) {
3663
- const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3664
- const expected = expectedBatchNames(state);
3665
- let directory;
3586
+ function scheduleFlush() {
3587
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
3588
+ flushScheduled = true;
3589
+ let scheduling = true;
3590
+ let invokedSynchronously = false;
3666
3591
  try {
3667
- directory = await opendir(directoryPath);
3668
- } catch (error) {
3669
- if (errorCode2(error) === "ENOENT") return 0;
3670
- throw error;
3592
+ schedule(() => {
3593
+ if (scheduling) {
3594
+ invokedSynchronously = true;
3595
+ return;
3596
+ }
3597
+ flushScheduled = false;
3598
+ flush();
3599
+ });
3600
+ } catch {
3601
+ flushScheduled = false;
3602
+ stop();
3603
+ return;
3671
3604
  }
3672
- let inspected = 0;
3673
- let deleted = 0;
3674
- try {
3675
- while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
3676
- const entry = await directory.read();
3677
- if (entry === null) break;
3678
- inspected += 1;
3679
- if (!isOrphanBatchEntry(entry, expected)) continue;
3680
- await unlink2(join4(directoryPath, entry.name));
3681
- deleted += 1;
3682
- }
3683
- } finally {
3684
- await directory.close();
3605
+ scheduling = false;
3606
+ if (invokedSynchronously) {
3607
+ flushScheduled = false;
3608
+ stop();
3685
3609
  }
3686
- if (deleted > 0) await syncDirectory(directoryPath, this.platform);
3687
- return deleted;
3688
- }
3689
- async commitCoverageGaps(state, createdAt) {
3690
- return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3691
- const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3692
- if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
3693
- const sourceRanges = coverageRanges(latest.coverage_gaps);
3694
- const canonical = createCealHostUsageBatch({
3695
- host_source_ref: latest.host_source_ref,
3696
- host_session_ref: latest.host_session_ref,
3697
- created_at: latest.coverage_gap_created_at ?? createdAt,
3698
- source_ranges: sourceRanges,
3699
- facts: [],
3700
- coverage_gaps: latest.coverage_gaps
3701
- });
3702
- const cursor = firstCursor(latest);
3703
- if (cursor === null) return latest;
3704
- return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
3705
- });
3706
3610
  }
3707
- async nextUploadCandidate(producer, hostSourceRef) {
3708
- const names = await this.readNextSessionNames();
3709
- for (const name of names) {
3710
- const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3711
- if (state === null) continue;
3712
- validateStateOwner(state, producer, hostSourceRef);
3713
- let validated = state;
3714
- if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
3715
- else validated = await this.recoverPending(validated);
3716
- if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
3717
- const next = validated.eligible_batches[0];
3718
- if (next === void 0) continue;
3719
- const batch = await this.readBatch(validated, next.batch_ref);
3720
- return { state: validated, batch };
3611
+ function flush() {
3612
+ if (closed) return;
3613
+ if (!stream.writable) {
3614
+ stop();
3615
+ return;
3721
3616
  }
3722
- return null;
3723
- }
3724
- async readNextSessionNames() {
3725
- if (this.sessionDirectoryCursor === void 0) {
3617
+ while (pending.length > 0) {
3618
+ if (stream.writableNeedDrain) {
3619
+ if (!waitingForDrain) {
3620
+ waitingForDrain = true;
3621
+ stream.once("drain", onDrain);
3622
+ }
3623
+ return;
3624
+ }
3625
+ const next = pending.shift();
3626
+ if (next === void 0) return;
3627
+ pendingBytes -= next.bytes;
3628
+ let accepted;
3726
3629
  try {
3727
- this.sessionDirectoryCursor = await opendir(this.sessions);
3728
- } catch (error) {
3729
- if (errorCode2(error) === "ENOENT") return [];
3730
- throw error;
3630
+ accepted = stream.write(next.line);
3631
+ } catch {
3632
+ stop();
3633
+ return;
3731
3634
  }
3732
- }
3733
- const names = [];
3734
- let inspected = 0;
3735
- while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
3736
- const entry = await this.sessionDirectoryCursor.read();
3737
- if (entry === null) {
3738
- await this.sessionDirectoryCursor.close();
3739
- this.sessionDirectoryCursor = void 0;
3740
- break;
3635
+ if (!accepted) {
3636
+ waitingForDrain = true;
3637
+ stream.once("drain", onDrain);
3638
+ return;
3741
3639
  }
3742
- inspected += 1;
3743
- if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
3744
- }
3745
- return names;
3746
- }
3747
- async acknowledge(state, batchRef) {
3748
- await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3749
- const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3750
- if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
3751
- const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
3752
- if (remaining.length === latest.eligible_batches.length) return;
3753
- await this.writeState({ ...latest, eligible_batches: remaining });
3754
- await removeFileIfPresent(this.batchPath(state, batchRef));
3755
- });
3756
- }
3757
- async quarantine(state, reason) {
3758
- return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3759
- const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3760
- const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
3761
- await this.writeState(updated);
3762
- return updated;
3763
- });
3764
- }
3765
- async retireCursor(state, sourceSlot, cursor, gap) {
3766
- return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
3767
- }
3768
- async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
3769
- if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
3770
- if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
3771
- const queued = await this.publishTransitionBatch(state, batch);
3772
- const pending = {
3773
- source_slot: sourceSlot,
3774
- before_cursor: beforeCursor,
3775
- after_cursor: afterCursor,
3776
- batch_ref: queued.batch_ref,
3777
- batch_bytes: queued.batch_bytes,
3778
- gap_delta: [...gapDelta, ...queued.overflow_gaps],
3779
- clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
3780
- };
3781
- const prepared = { ...state, pending_transition: pending };
3782
- await this.writeState(prepared);
3783
- await this.afterPendingWrite?.();
3784
- return await this.finishPendingTransition(prepared);
3785
- }
3786
- async publishTransitionBatch(state, batch) {
3787
- if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
3788
- const serialized = serializeBatch(batch);
3789
- if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
3790
- await this.writeImmutableBatch(state, batch, serialized);
3791
- await this.afterBatchPublish?.();
3792
- return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
3793
- }
3794
- async finishPendingTransition(state) {
3795
- const pending = state.pending_transition;
3796
- if (pending === void 0 || state.quarantined_reason !== void 0) return state;
3797
- const current = state.cursors[pending.source_slot];
3798
- if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
3799
- const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
3800
- await this.writeState(quarantined);
3801
- return quarantined;
3802
- }
3803
- let cursors = state.cursors;
3804
- if (!cursorMatches(current, pending.after_cursor)) {
3805
- const next = { ...state.cursors };
3806
- if (pending.after_cursor === null) delete next[pending.source_slot];
3807
- else next[pending.source_slot] = pending.after_cursor;
3808
- cursors = next;
3809
- }
3810
- const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
3811
- const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
3812
- const { pending_transition: _pendingTransition, ...settledState } = state;
3813
- const updated = {
3814
- ...settledState,
3815
- cursors,
3816
- eligible_batches: eligible,
3817
- coverage_gaps: gaps,
3818
- coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
3819
- };
3820
- await this.writeState(updated);
3821
- return updated;
3822
- }
3823
- async writeImmutableBatch(state, batch, bytes) {
3824
- const path = this.batchPath(state, batch.batch_ref);
3825
- await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
3826
- const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3827
- if (existing !== null) {
3828
- if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3829
- await syncExistingFile(path, this.platform);
3830
- return;
3831
- }
3832
- if (this.platform === "win32") {
3833
- await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
3834
- return;
3835
3640
  }
3836
- let handle;
3837
- try {
3838
- handle = await openNoFollow(path, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384, this.platform);
3839
- await handle.writeFile(bytes);
3840
- await handle.sync();
3841
- await handle.close();
3842
- handle = void 0;
3843
- await syncDirectory(dirname4(path), this.platform);
3844
- } catch (error) {
3845
- await handle?.close().catch(() => void 0);
3846
- if (errorCode2(error) === "EEXIST") {
3847
- const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3848
- if (winner !== null && winner.equals(bytes)) {
3849
- await syncExistingFile(path, this.platform);
3850
- return;
3851
- }
3852
- throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3641
+ if (droppedLines > 0) {
3642
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
3643
+ `;
3644
+ droppedLines = 0;
3645
+ try {
3646
+ onDeliveryGap(line);
3647
+ } catch {
3853
3648
  }
3854
- await removeFileIfPresent(path).catch(() => void 0);
3855
- throw error;
3856
- }
3857
- }
3858
- async readBatch(state, batchRef) {
3859
- const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3860
- if (bytes === null) throw new Error("Host usage facts batch object is missing.");
3861
- let value;
3862
- try {
3863
- value = JSON.parse(bytes.toString("utf8"));
3864
- } catch {
3865
- throw new Error("Host usage facts batch object is malformed.");
3649
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
3650
+ pendingBytes += Buffer.byteLength(line, "utf8");
3651
+ flush();
3866
3652
  }
3867
- validateCealHostUsageBatch(value);
3868
- if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
3869
- return value;
3870
3653
  }
3871
- async writeState(state) {
3872
- validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
3873
- const bytes = Buffer.from(JSON.stringify(state), "utf8");
3874
- if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
3875
- await this.prepare();
3876
- const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
3877
- if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
3878
- else await durableAtomicReplace(path, bytes);
3879
- }
3880
- async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
3881
- const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3882
- const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
3883
- let release;
3884
- const gate = new Promise((resolve) => {
3885
- release = resolve;
3886
- });
3887
- const tail2 = previous.then(() => gate);
3888
- SESSION_TRANSITION_TAILS.set(key, tail2);
3889
- await previous;
3890
- try {
3891
- return await run();
3892
- } finally {
3893
- release?.();
3894
- if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3654
+ stream.on("close", onTerminal);
3655
+ stream.on("finish", onTerminal);
3656
+ stream.on("error", onError);
3657
+ return (line) => {
3658
+ if (closed) return;
3659
+ const bytes = Buffer.byteLength(line, "utf8");
3660
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
3661
+ droppedLines += 1;
3662
+ scheduleFlush();
3663
+ return;
3895
3664
  }
3896
- }
3897
- sessionPath(producer, hostSourceRef, hostSessionRef) {
3898
- return join4(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3899
- }
3900
- batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3901
- const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3902
- return join4(this.batches, sessionName.slice(0, -5));
3903
- }
3904
- batchPath(state, batchRef) {
3905
- return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3665
+ pending.push({ line, bytes });
3666
+ pendingBytes += bytes;
3667
+ scheduleFlush();
3668
+ };
3669
+ }
3670
+
3671
+ // host/invocation-authentication-client-command.ts
3672
+ var HOST_OWNED_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){0,7}$/u;
3673
+ function isHostOwnedFailureCode(value) {
3674
+ return typeof value === "string" && HOST_OWNED_CODE.test(value);
3675
+ }
3676
+ var DOCTOR_FLAGS = Object.freeze({
3677
+ "--expected-sha256": "expected_sha256",
3678
+ "--expected-source-commit": "expected_source_commit",
3679
+ "--expected-instance-ref": "expected_instance_ref"
3680
+ });
3681
+
3682
+ // host/service-log.ts
3683
+ var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
3684
+ var HOST_SERVICE_LOG_ARGUMENT = "--ceal-host-service-log";
3685
+ var HostServiceLogArgumentError = class extends Error {
3686
+ constructor() {
3687
+ super("The Host service log argument must occur once with an absolute normalized path.");
3688
+ this.name = "HostServiceLogArgumentError";
3906
3689
  }
3907
3690
  };
3908
- function serializeBatch(batch) {
3909
- validateCealHostUsageBatch(batch);
3910
- return Buffer.from(JSON.stringify(batch), "utf8");
3691
+ function consumeHostServiceLogArgument(args, platform = process.platform) {
3692
+ const indexes = args.flatMap((value, index2) => value === HOST_SERVICE_LOG_ARGUMENT ? [index2] : []);
3693
+ if (indexes.length === 0) return { args: [...args] };
3694
+ const index = indexes[0];
3695
+ if (index === void 0) throw new HostServiceLogArgumentError();
3696
+ const path = args[index + 1];
3697
+ const pathApi = platform === "win32" ? win325 : posix4;
3698
+ if (indexes.length !== 1 || path === void 0 || !pathApi.isAbsolute(path) || pathApi.normalize(path) !== path) throw new HostServiceLogArgumentError();
3699
+ return { args: [...args.slice(0, index), ...args.slice(index + 2)], path };
3911
3700
  }
3912
- function batchFileName(batchRef) {
3913
- const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
3914
- if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
3915
- return `${digest2}.json`;
3701
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
3702
+ void persistHostServiceLogLine(line);
3703
+ });
3704
+ function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
3705
+ const details = diagnosticDetails(event, failure_kind, cause);
3706
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
3707
+ `;
3708
+ try {
3709
+ (sink ?? defaultHostServiceDiagnosticSink)(line);
3710
+ } catch {
3711
+ }
3916
3712
  }
3917
- function expectedBatchNames(state) {
3918
- const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
3919
- const pending = state.pending_transition?.batch_ref;
3920
- if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
3921
- return expected;
3713
+ function diagnosticDetails(event, failureKind, cause) {
3714
+ if (event === "watcher_scan_failed") return {
3715
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3716
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
3717
+ };
3718
+ return validDiagnosticCause(cause, event) ? { cause } : {};
3922
3719
  }
3923
- function isOrphanBatchEntry(entry, expected) {
3924
- return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
3720
+ function validDiagnosticCause(cause, event) {
3721
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
3925
3722
  }
3926
- function hasOutboxCapacity(state, bytes) {
3927
- const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
3928
- return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
3723
+ function defaultHostServiceDiagnosticSink(line) {
3724
+ writeHostServiceLogLine(line);
3929
3725
  }
3930
- function overflowCoverageGaps(batch) {
3931
- const count = batch.facts.length;
3932
- const gaps = [...batch.coverage_gaps];
3933
- if (count > 0) gaps.push({ reason: "outbox_capacity", source_file_ref: batch.source_ranges[0]?.source_file_ref ?? null, start_offset: batch.source_ranges[0]?.start_offset ?? null, end_offset: batch.source_ranges[0]?.end_offset ?? null, omitted_count: count });
3934
- return gaps;
3935
- }
3936
- function appendEligible(existing, next) {
3937
- if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
3938
- if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
3939
- return [...existing, next];
3940
- }
3941
- function appendCoverageGaps(existing, added) {
3942
- if (added.length === 0) return existing;
3943
- const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
3944
- for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
3945
- const combined = [...byIdentity.values()];
3946
- if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
3947
- const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
3948
- return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
3726
+ var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
3727
+ var HOST_SERVICE_LOG_CHECK_INTERVAL_MS = 6e4;
3728
+ function hostServiceLogPreviousPath(path) {
3729
+ return `${path}.1`;
3949
3730
  }
3950
- function coverageRanges(gaps) {
3951
- const ranges = /* @__PURE__ */ new Map();
3952
- for (const gap of gaps) {
3953
- if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
3954
- const current = ranges.get(gap.source_file_ref);
3955
- if (current === void 0) ranges.set(gap.source_file_ref, { source_file_ref: gap.source_file_ref, start_offset: gap.start_offset, end_offset: gap.end_offset });
3956
- else ranges.set(gap.source_file_ref, { ...current, start_offset: Math.min(current.start_offset, gap.start_offset), end_offset: Math.max(current.end_offset, gap.end_offset) });
3731
+ async function rotateHostServiceLog(path, maxBytes = HOST_SERVICE_LOG_MAX_BYTES) {
3732
+ let size;
3733
+ try {
3734
+ size = (await stat(path)).size;
3735
+ } catch (error) {
3736
+ if (isNotFound(error)) return false;
3737
+ throw error;
3957
3738
  }
3958
- return [...ranges.values()];
3959
- }
3960
- function firstCursor(state) {
3961
- const entry = Object.entries(state.cursors)[0];
3962
- return entry === void 0 ? null : entry;
3963
- }
3964
- function sameCursor(left, right) {
3965
- return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
3966
- }
3967
- function cursorMatches(left, right) {
3968
- return right === null ? left === void 0 : sameCursor(left, right);
3969
- }
3970
- function validateState(value, producer, hostSourceRef, hostSessionRef) {
3971
- validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
3972
- validateStateShape(value);
3973
- validateStateLimits(value);
3974
- validateStateContents(value);
3739
+ if (size <= maxBytes) return false;
3740
+ await copyFile(path, hostServiceLogPreviousPath(path));
3741
+ await truncate(path, 0);
3742
+ return true;
3975
3743
  }
3976
- function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
3977
- if (!isRecord3(value) || value.schema_version !== HOST_USAGE_FACTS_STATE_SCHEMA || value.producer !== producer || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new Error("Host usage facts state identity is invalid.");
3744
+ function boundHostServiceLog(environment = process.env) {
3745
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
3746
+ if (path === void 0 || !isAbsolute(path)) return () => void 0;
3747
+ let reported = false;
3748
+ const ready = ensureHostServiceLogDirectory(path);
3749
+ const check = () => {
3750
+ ready.then(() => rotateHostServiceLog(path)).catch((error) => {
3751
+ if (reported) return;
3752
+ reported = true;
3753
+ writeHostServiceLogLine(`[host-service-log] rotation_failed code=${errorCode2(error)}
3754
+ `);
3755
+ });
3756
+ };
3757
+ check();
3758
+ const timer = setInterval(check, HOST_SERVICE_LOG_CHECK_INTERVAL_MS);
3759
+ timer.unref();
3760
+ return () => clearInterval(timer);
3978
3761
  }
3979
- function validateStateLimits(value) {
3980
- if (Object.keys(value.cursors).length > HOST_USAGE_FACTS_MAX_SOURCE_CURSORS || value.eligible_batches.length > HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES || value.coverage_gaps.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) throw new Error("Host usage facts state exceeds its bounds.");
3762
+ function writeHostServiceLogLine(line, environment = process.env) {
3763
+ void persistHostServiceLogLine(line, environment);
3764
+ defaultHostServiceLogDelivery(line);
3981
3765
  }
3982
- function validateStateContents(value) {
3983
- for (const [slot, cursor] of Object.entries(value.cursors)) {
3984
- validateSourceSlot(slot);
3985
- validateFileCursor(cursor);
3986
- }
3987
- for (const item of value.eligible_batches) validateEligibleBatch(item);
3988
- if (value.pending_transition !== void 0) validatePending(value.pending_transition);
3989
- for (const gap of value.coverage_gaps) validateGap(gap);
3990
- validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
3766
+ async function writeHostServiceCommandResult(schemaVersion, result, sink) {
3767
+ const line = `${JSON.stringify({ schema_version: schemaVersion, ...result })}
3768
+ `;
3769
+ const serviceLine = `${JSON.stringify({ schema_version: schemaVersion, ok: result.ok, ...!result.ok ? { code: isHostOwnedFailureCode(result.code) ? result.code : "host_failure_unclassified" } : {} })}
3770
+ `;
3771
+ await persistHostServiceLogLine(serviceLine);
3772
+ sink(line);
3991
3773
  }
3992
- function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
3993
- if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
3994
- if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
3774
+ async function persistHostServiceLogLine(line, environment = process.env) {
3775
+ if (process.platform !== "win32") return;
3776
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
3777
+ if (path === void 0 || !win325.isAbsolute(path) || win325.normalize(path) !== path) return;
3778
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
3995
3779
  }
3996
- function validateStateOwner(value, producer, hostSourceRef) {
3997
- if (!isRecord3(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
3998
- validateState(value, producer, hostSourceRef, String(value.host_session_ref));
3780
+ async function appendHostServiceLogLine(path, line) {
3781
+ if (!isAbsolute(path)) return;
3782
+ await ensureHostServiceLogDirectory(path);
3783
+ await appendFile(path, line);
3999
3784
  }
4000
- function validateStateShape(value) {
4001
- const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
4002
- const optional = ["pending_transition", "quarantined_reason"];
4003
- if (required.some((key) => !Object.hasOwn(value, key)) || Object.keys(value).some((key) => !required.includes(key) && !optional.includes(key))) throw new Error("Host usage facts state keys are invalid.");
4004
- if (!isRecord3(value.cursors) || !Array.isArray(value.eligible_batches) || !Array.isArray(value.coverage_gaps) || value.coverage_gap_created_at !== null && typeof value.coverage_gap_created_at !== "string") throw new Error("Host usage facts state collections are invalid.");
3785
+ var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
3786
+ var hostServiceLogDirectories = /* @__PURE__ */ new Map();
3787
+ function ensureHostServiceLogDirectory(path) {
3788
+ const directory = dirname4(path);
3789
+ const existing = hostServiceLogDirectories.get(directory);
3790
+ if (existing !== void 0) return existing;
3791
+ const pending = mkdir2(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
3792
+ hostServiceLogDirectories.delete(directory);
3793
+ throw error;
3794
+ });
3795
+ hostServiceLogDirectories.set(directory, pending);
3796
+ return pending;
4005
3797
  }
4006
- function validateFileCursor(value) {
4007
- if (!isRecord3(value) || !sameKeys(value, ["source_file_ref", "device", "inode", "offset", "anchor_start", "anchor_sha256", "last_ordinal", "host_turn_ref", "native_turn_id", "requested_model", "codex_total_usage", "skipping_oversized_line"])) throw new Error("Host usage facts source cursor is invalid.");
4008
- validateCursorIdentity(value);
4009
- validateCursorOffsets(value);
4010
- validateCursorContext(value);
4011
- if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
4012
- if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
3798
+ function isNotFound(error) {
3799
+ return errorCode2(error) === "ENOENT";
4013
3800
  }
4014
- function validateCursorIdentity(value) {
4015
- if (![value.source_file_ref, value.device, value.inode].every((part) => typeof part === "string" && part.length > 0 && part.length <= HOST_USAGE_FACTS_REF_MAX_LENGTH)) throw new Error("Host usage facts source cursor identity is invalid.");
3801
+ function errorCode2(error) {
3802
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unknown";
4016
3803
  }
4017
- function validateCursorOffsets(value) {
4018
- if (!/^host-source-file:[a-f0-9]{64}$/u.test(String(value.source_file_ref)) || !safeInteger2(value.offset) || !safeInteger2(value.anchor_start) || Number(value.anchor_start) > Number(value.offset) || !/^[a-f0-9]{64}$/u.test(String(value.anchor_sha256)) || value.last_ordinal !== null && !safeInteger2(value.last_ordinal)) throw new Error("Host usage facts source cursor fields are invalid.");
3804
+
3805
+ // host/relay/src/host-producer-core.ts
3806
+ var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
3807
+ function isHostTranscriptCursorReason(value) {
3808
+ return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
4019
3809
  }
4020
- function validateCursorContext(value) {
4021
- if (!validOptionalText(value.host_turn_ref, HOST_USAGE_FACTS_REF_MAX_LENGTH) || !validOptionalText(value.native_turn_id, HOST_USAGE_FACTS_REF_MAX_LENGTH) || !validOptionalText(value.requested_model, 256)) throw new Error("Host usage facts source context is invalid.");
3810
+ var TRANSCRIPT_MISSING_REASON = "transcript_missing";
3811
+ var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
3812
+ var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
3813
+ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
3814
+ const seen = /* @__PURE__ */ new Set();
3815
+ const newestFirst = [];
3816
+ for (const message of [...chronological].reverse()) {
3817
+ if (seen.has(message.host_input_ref)) continue;
3818
+ seen.add(message.host_input_ref);
3819
+ newestFirst.push(message);
3820
+ }
3821
+ for (const message of existing?.messages ?? []) {
3822
+ if (seen.has(message.host_input_ref)) continue;
3823
+ seen.add(message.host_input_ref);
3824
+ newestFirst.push(message);
3825
+ }
3826
+ const currentTurn = newestFirst[0]?.host_turn_ref;
3827
+ const currentTurnFirst = currentTurn === void 0 ? newestFirst : newestFirst.filter((message) => message.host_turn_ref === currentTurn);
3828
+ return boundCealHostInvocationHumanMessageWindow(currentTurnFirst, existing?.truncated ?? false);
4022
3829
  }
4023
- function validOptionalText(value, maximum) {
4024
- return value === null || typeof value === "string" && value.length <= maximum;
3830
+ function transcriptScanFailureKind(error, adapterFailureKind) {
3831
+ if (transcriptErrorCode(error) === "ELOOP") return "symlink";
3832
+ const adapter = adapterFailureKind(error);
3833
+ if (adapter !== void 0) return adapter;
3834
+ const code = transcriptErrorCode(error);
3835
+ if (code === "EFBIG") return "size_budget";
3836
+ if (code !== null && TRANSCRIPT_SCAN_READ_ERROR_ERRNOS.includes(code)) return "read_error";
3837
+ return "other";
4025
3838
  }
4026
- function validateCodexCounts(value) {
4027
- if (!isRecord3(value) || !sameKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) throw new Error("Host usage facts cumulative usage is invalid.");
4028
- if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
3839
+ function transcriptErrorCode(error) {
3840
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
4029
3841
  }
4030
- function validatePending(value) {
4031
- if (!isRecord3(value) || !sameKeys(value, ["source_slot", "before_cursor", "after_cursor", "batch_ref", "batch_bytes", "gap_delta", "clear_coverage_gaps"])) throw new Error("Host usage facts pending transition is invalid.");
4032
- validatePendingCursors(value);
4033
- validatePendingBatch(value);
4034
- validatePendingFields(value);
4035
- for (const gap of value.gap_delta) validateGap(gap);
3842
+ var HOST_TRANSCRIPT_READ_CHUNK_BYTES = 256 * 1024;
3843
+ async function readTranscriptCompleteChunk(handle, offset, size) {
3844
+ const available = Math.max(0, size - offset);
3845
+ if (available === 0) return "empty";
3846
+ const chunks = [];
3847
+ let position = offset;
3848
+ let total = 0;
3849
+ let lastNewline = -1;
3850
+ while (position < size) {
3851
+ const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
3852
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
3853
+ if (read2.bytesRead === 0) break;
3854
+ const chunk = buffer.subarray(0, read2.bytesRead);
3855
+ chunks.push(chunk);
3856
+ const newline = chunk.lastIndexOf(10);
3857
+ if (newline >= 0) lastNewline = total + newline;
3858
+ total += chunk.length;
3859
+ position += chunk.length;
3860
+ if (lastNewline >= 0) break;
3861
+ }
3862
+ if (lastNewline < 0) return "partial";
3863
+ return Buffer.concat(chunks, total).subarray(0, lastNewline + 1);
4036
3864
  }
4037
- function validatePendingCursors(value) {
4038
- validateSourceSlot(value.source_slot);
4039
- validateFileCursor(value.before_cursor);
4040
- if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
3865
+ async function readTranscriptAnchor(handle, offset, anchorBytes) {
3866
+ const start = Math.max(0, offset - anchorBytes);
3867
+ const anchor = Buffer.alloc(offset - start);
3868
+ if (anchor.length > 0) await handle.read(anchor, 0, anchor.length, start);
3869
+ return { start, sha256: transcriptSha256(anchor) };
4041
3870
  }
4042
- function validatePendingBatch(value) {
4043
- if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
3871
+ async function transcriptAnchorMatches(handle, cursor) {
3872
+ const buffer = Buffer.alloc(cursor.offset - cursor.anchor_start);
3873
+ if (buffer.length > 0) await handle.read(buffer, 0, buffer.length, cursor.anchor_start);
3874
+ return transcriptSha256(buffer) === cursor.anchor_sha256;
4044
3875
  }
4045
- function validatePendingFields(value) {
4046
- if (!safeInteger2(value.batch_bytes) || !Array.isArray(value.gap_delta) || value.gap_delta.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS || typeof value.clear_coverage_gaps !== "boolean") throw new Error("Host usage facts pending transition fields are invalid.");
3876
+ function transcriptCursorIdentityReason(cursor, transcriptPath, device, inode) {
3877
+ if (cursor.device !== device || cursor.inode !== inode || cursor.transcript_path !== transcriptPath) return "transcript_replaced";
3878
+ return null;
4047
3879
  }
4048
- function validateEligibleBatch(value) {
4049
- if (!isRecord3(value) || !sameKeys(value, ["batch_ref", "bytes"]) || !isCealHostUsageBatchReference(value.batch_ref) || !safeInteger2(value.bytes) || Number(value.bytes) < 1 || Number(value.bytes) > CEAL_HOST_USAGE_BATCH_MAX_BYTES) throw new Error("Host usage facts eligible batch is invalid.");
3880
+ async function transcriptCursorBoundsReason(handle, cursor, size) {
3881
+ if (size < cursor.offset) return "transcript_truncated";
3882
+ if (cursor.offset > 0 && !await transcriptAnchorMatches(handle, cursor)) return "transcript_rewritten";
3883
+ return null;
4050
3884
  }
4051
- function validateGap(value) {
3885
+ async function statObservedPathSignature(path) {
4052
3886
  try {
4053
- validateCealHostUsageCoverageGap(value);
3887
+ const info = await lstat4(path, { bigint: true });
3888
+ if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) return null;
3889
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
4054
3890
  } catch {
4055
- throw new Error("Host usage facts coverage gap is invalid.");
3891
+ return null;
4056
3892
  }
4057
3893
  }
4058
- function validateSourceSlot(value) {
4059
- if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
3894
+ function transcriptSha256(value) {
3895
+ return createHash5("sha256").update(value).digest("hex");
4060
3896
  }
4061
- async function readOptionalJson(path, maxBytes, platform, custody) {
4062
- const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
4063
- if (bytes === null) return null;
4064
- try {
4065
- return JSON.parse(bytes.toString("utf8"));
4066
- } catch {
4067
- throw new Error("Host usage facts state JSON is malformed.");
4068
- }
3897
+ function transcriptObjectSha256(value) {
3898
+ return createHash5("sha256").update(JSON.stringify(value), "utf8").digest("hex");
4069
3899
  }
4070
- async function readOptionalBytes(path, maxBytes, platform, custody) {
4071
- if (platform === "win32") {
4072
- try {
4073
- return await readPrivateFileWithSecurefs(path, maxBytes, custody);
4074
- } catch (error) {
4075
- if (errorCode2(error) === "ENOENT") return null;
4076
- throw error;
4077
- }
4078
- }
4079
- let handle;
4080
- try {
4081
- handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
4082
- const stats = await handle.stat();
4083
- if (!stats.isFile() || !isSelfOwned(stats.uid, platform, handle) || !isPrivateFileMode(stats.mode, platform, handle) || stats.size > maxBytes) throw new Error("Host usage facts file custody or size is invalid.");
4084
- return await handle.readFile();
4085
- } catch (error) {
4086
- if (errorCode2(error) === "ENOENT") return null;
4087
- throw error;
4088
- } finally {
4089
- await handle?.close();
4090
- }
3900
+ function isTranscriptRecord(value) {
3901
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4091
3902
  }
4092
- async function preparePrivateDirectory(path, platform, custody) {
4093
- if (platform === "win32") {
4094
- await ensurePrivateDirectoryWithSecurefs(path, custody);
4095
- return;
4096
- }
4097
- await mkdir2(path, { recursive: true, mode: 448 });
4098
- if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3903
+ function isMissingTranscriptError(error) {
3904
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
4099
3905
  }
4100
- async function syncExistingFile(path, platform) {
4101
- const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
4102
- try {
4103
- await handle.sync();
4104
- } finally {
4105
- await handle.close();
4106
- }
4107
- await syncDirectory(dirname4(path), platform);
3906
+ function transcriptTimestamp(now, fail) {
3907
+ const value = now();
3908
+ if (!Number.isFinite(value.getTime())) throw fail();
3909
+ return value.toISOString();
4108
3910
  }
4109
- async function syncDirectory(path, platform) {
4110
- if (platform === "win32") return;
4111
- const handle = await open3(path, constants4.O_RDONLY);
4112
- try {
4113
- await handle.sync();
4114
- } finally {
4115
- await handle.close();
3911
+ function transcriptExpiration(now, retentionMs, fail) {
3912
+ return new Date(Date.parse(transcriptTimestamp(now, fail)) + retentionMs).toISOString();
3913
+ }
3914
+ function createTranscriptWatcherBase(options, owner) {
3915
+ if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0) throw owner.invalid_outbox();
3916
+ return {
3917
+ outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
3918
+ now: options.now ?? (() => /* @__PURE__ */ new Date()),
3919
+ log: options.log ?? ((line) => {
3920
+ writeHostServiceLogLine(`${line}
3921
+ `);
3922
+ }),
3923
+ producerInstallationRef: options.producer_installation_ref
3924
+ };
3925
+ }
3926
+ async function scanTranscriptRegistrations(registrations, scanOne, totalRegistrations, signal) {
3927
+ let records = 0;
3928
+ let enqueued = 0;
3929
+ let quarantined = 0;
3930
+ let scanned = 0;
3931
+ for (const registration of registrations) {
3932
+ if (signal?.aborted) break;
3933
+ scanned += 1;
3934
+ const result = await scanOne(registration);
3935
+ records += result.records;
3936
+ enqueued += result.enqueued;
3937
+ if (result.quarantined) quarantined += 1;
4116
3938
  }
3939
+ return { registrations: totalRegistrations ?? scanned, records, enqueued, quarantined };
4117
3940
  }
4118
- async function removeFileIfPresent(path) {
3941
+ var HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS = 1000000000n;
3942
+ var HostRegistrationInventory = class {
3943
+ signature;
3944
+ registrations;
3945
+ nowNs;
3946
+ observeDirectory;
3947
+ constructor(options = {}) {
3948
+ this.nowNs = options.nowNs ?? (() => BigInt(Date.now()) * 1000000n);
3949
+ this.observeDirectory = options.observeDirectory ?? hostRegistrationDirectorySignature;
3950
+ }
3951
+ async read(directory, load) {
3952
+ const observation = await this.observeDirectory(directory);
3953
+ const nowNs = this.nowNs();
3954
+ const racy = nowNs - observation.mtimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS || nowNs - observation.ctimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS;
3955
+ if (this.registrations !== void 0 && this.signature === observation.signature && !racy) return this.registrations;
3956
+ const registrations = await load();
3957
+ this.signature = observation.signature;
3958
+ this.registrations = registrations;
3959
+ return registrations;
3960
+ }
3961
+ };
3962
+ async function hostRegistrationDirectorySignature(directory) {
4119
3963
  try {
4120
- await unlink2(path);
3964
+ const info = await stat2(directory, { bigint: true });
3965
+ return {
3966
+ signature: `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`,
3967
+ mtimeNs: info.mtimeNs,
3968
+ ctimeNs: info.ctimeNs
3969
+ };
4121
3970
  } catch (error) {
4122
- if (errorCode2(error) !== "ENOENT") throw error;
3971
+ if (isMissingTranscriptError(error)) return { signature: "missing", mtimeNs: 0n, ctimeNs: 0n };
3972
+ throw error;
4123
3973
  }
4124
3974
  }
4125
- function sameKeys(value, expected) {
4126
- return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
4127
- }
4128
- function isRecord3(value) {
4129
- return value !== null && typeof value === "object" && !Array.isArray(value);
4130
- }
4131
- function safeInteger2(value) {
4132
- return Number.isSafeInteger(value) && Number(value) >= 0;
4133
- }
4134
- function validTimestamp(value) {
4135
- return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
4136
- }
4137
- function errorCode2(error) {
4138
- return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
4139
- }
4140
- function sha2562(value) {
4141
- return createHash5("sha256").update(value, "utf8").digest("hex");
3975
+ function formatRetiredTranscriptLog(producerLabel, transcriptPath) {
3976
+ return `${producerLabel} retired a transcript registration: transcript_path=${JSON.stringify(transcriptPath)}, reason=${TRANSCRIPT_MISSING_REASON}.`;
4142
3977
  }
4143
-
4144
- // host/service-log.ts
4145
- import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
4146
- import { dirname as dirname5, isAbsolute as isAbsolute2, posix as posix4, win32 as win325 } from "node:path";
4147
-
4148
- // host/service-log-delivery.ts
4149
- var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
4150
- function createHostServiceLogDelivery(stream, schedule = (flush) => {
4151
- setImmediate(flush);
4152
- }, onDeliveryGap = () => void 0) {
4153
- const pending = [];
4154
- const highWaterMark = stream.writableHighWaterMark;
4155
- const byteBudget = highWaterMark + highWaterMark;
4156
- let pendingBytes = 0;
4157
- let droppedLines = 0;
4158
- let flushScheduled = false;
4159
- let waitingForDrain = false;
4160
- let closed = !stream.writable;
4161
- function stop() {
4162
- if (closed) return;
4163
- closed = true;
4164
- pending.length = 0;
4165
- pendingBytes = 0;
4166
- stream.off("drain", onDrain);
4167
- stream.off("close", onTerminal);
4168
- stream.off("finish", onTerminal);
4169
- stream.off("error", onError);
4170
- }
4171
- function onTerminal() {
4172
- stop();
4173
- }
4174
- function onError() {
4175
- stop();
3978
+ var HOST_TRANSCRIPT_RECONCILIATION_BATCH = 100;
3979
+ var HostTranscriptWatcher = class {
3980
+ outboxRetentionMs;
3981
+ now;
3982
+ log;
3983
+ producerInstallationRef;
3984
+ clockFailure;
3985
+ transcriptObservations = /* @__PURE__ */ new Map();
3986
+ registrationSnapshot;
3987
+ // Advisory scheduling only: listRegistrations remains the registration authority.
3988
+ hotRegistrations = /* @__PURE__ */ new Set();
3989
+ reconciliation;
3990
+ reconciliationRemaining = 0;
3991
+ constructor(options, owner) {
3992
+ const base = createTranscriptWatcherBase(options, owner);
3993
+ this.outboxRetentionMs = base.outboxRetentionMs;
3994
+ this.now = base.now;
3995
+ this.log = base.log;
3996
+ this.producerInstallationRef = base.producerInstallationRef;
3997
+ this.clockFailure = owner.clock_failure;
4176
3998
  }
4177
- function onDrain() {
4178
- waitingForDrain = false;
4179
- scheduleFlush();
3999
+ async scanOnce(signal) {
4000
+ if (signal?.aborted) return { registrations: this.registrationSnapshot?.length ?? 0, records: 0, enqueued: 0, quarantined: 0 };
4001
+ const registrations = await this.listRegistrations();
4002
+ this.reconcileSnapshot(registrations);
4003
+ return scanTranscriptRegistrations(this.scanCandidates(), (observation) => this.observeRegistration(observation, signal), registrations.length, signal);
4004
+ }
4005
+ async observeRegistration(observation, signal) {
4006
+ const registration = observation.registration;
4007
+ const signature = await this.scanFingerprint(registration);
4008
+ if (signal?.aborted) return { records: 0, enqueued: 0, quarantined: false };
4009
+ this.hotRegistrations.delete(observation);
4010
+ if (signature !== null && observation.signature === signature) return { records: 0, enqueued: 0, quarantined: false };
4011
+ this.hotRegistrations.add(observation);
4012
+ const result = await this.scanRegistration(registration);
4013
+ if (result.quarantined || result.retry === true) observation.signature = void 0;
4014
+ else {
4015
+ observation.signature = signature ?? void 0;
4016
+ if (result.records === 0) this.hotRegistrations.delete(observation);
4017
+ }
4018
+ return result;
4180
4019
  }
4181
- function scheduleFlush() {
4182
- if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
4183
- flushScheduled = true;
4184
- let scheduling = true;
4185
- let invokedSynchronously = false;
4186
- try {
4187
- schedule(() => {
4188
- if (scheduling) {
4189
- invokedSynchronously = true;
4190
- return;
4191
- }
4192
- flushScheduled = false;
4193
- flush();
4194
- });
4195
- } catch {
4196
- flushScheduled = false;
4197
- stop();
4198
- return;
4020
+ *scanCandidates() {
4021
+ const hotSlice = [];
4022
+ for (const observation of this.hotRegistrations) {
4023
+ hotSlice.push(observation);
4024
+ if (hotSlice.length === HOST_TRANSCRIPT_RECONCILIATION_BATCH) break;
4199
4025
  }
4200
- scheduling = false;
4201
- if (invokedSynchronously) {
4202
- flushScheduled = false;
4203
- stop();
4026
+ const observed = /* @__PURE__ */ new Set();
4027
+ for (let count = 0; count < Math.min(this.transcriptObservations.size, HOST_TRANSCRIPT_RECONCILIATION_BATCH); count += 1) {
4028
+ const observation = this.nextReconciliation();
4029
+ if (observation === void 0) break;
4030
+ observed.add(observation);
4031
+ yield observation;
4204
4032
  }
4033
+ for (const observation of hotSlice) if (!observed.has(observation)) yield observation;
4205
4034
  }
4206
- function flush() {
4207
- if (closed) return;
4208
- if (!stream.writable) {
4209
- stop();
4210
- return;
4035
+ nextReconciliation() {
4036
+ if (this.reconciliationRemaining === 0 || this.reconciliation === void 0) {
4037
+ this.reconciliation = this.transcriptObservations.values();
4038
+ this.reconciliationRemaining = this.transcriptObservations.size;
4211
4039
  }
4212
- while (pending.length > 0) {
4213
- if (stream.writableNeedDrain) {
4214
- if (!waitingForDrain) {
4215
- waitingForDrain = true;
4216
- stream.once("drain", onDrain);
4040
+ let next = this.reconciliation.next();
4041
+ if (next.done) {
4042
+ this.reconciliation = this.transcriptObservations.values();
4043
+ this.reconciliationRemaining = this.transcriptObservations.size;
4044
+ next = this.reconciliation.next();
4045
+ }
4046
+ this.reconciliationRemaining -= 1;
4047
+ return next.value;
4048
+ }
4049
+ reconcileSnapshot(registrations) {
4050
+ if (this.registrationSnapshot === registrations) return;
4051
+ const retained = /* @__PURE__ */ new Set();
4052
+ const hot = /* @__PURE__ */ new Set();
4053
+ for (const registration of registrations) {
4054
+ const key = this.registrationKey(registration);
4055
+ retained.add(key);
4056
+ let observation = this.transcriptObservations.get(key);
4057
+ if (observation === void 0) {
4058
+ observation = { registration, signature: void 0 };
4059
+ this.transcriptObservations.set(key, observation);
4060
+ hot.add(observation);
4061
+ } else {
4062
+ if (!isDeepStrictEqual(observation.registration, registration)) {
4063
+ observation.signature = void 0;
4064
+ hot.add(observation);
4217
4065
  }
4218
- return;
4219
- }
4220
- const next = pending.shift();
4221
- if (next === void 0) return;
4222
- pendingBytes -= next.bytes;
4223
- let accepted;
4224
- try {
4225
- accepted = stream.write(next.line);
4226
- } catch {
4227
- stop();
4228
- return;
4229
- }
4230
- if (!accepted) {
4231
- waitingForDrain = true;
4232
- stream.once("drain", onDrain);
4233
- return;
4066
+ observation.registration = registration;
4234
4067
  }
4235
4068
  }
4236
- if (droppedLines > 0) {
4237
- const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
4238
- `;
4239
- droppedLines = 0;
4240
- try {
4241
- onDeliveryGap(line);
4242
- } catch {
4069
+ for (const [key, observation] of this.transcriptObservations) {
4070
+ if (!retained.has(key)) {
4071
+ this.transcriptObservations.delete(key);
4072
+ this.hotRegistrations.delete(observation);
4243
4073
  }
4244
- pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
4245
- pendingBytes += Buffer.byteLength(line, "utf8");
4246
- flush();
4247
4074
  }
4075
+ for (const observation of this.hotRegistrations) hot.add(observation);
4076
+ this.hotRegistrations = hot;
4077
+ this.registrationSnapshot = registrations;
4248
4078
  }
4249
- stream.on("close", onTerminal);
4250
- stream.on("finish", onTerminal);
4251
- stream.on("error", onError);
4252
- return (line) => {
4253
- if (closed) return;
4254
- const bytes = Buffer.byteLength(line, "utf8");
4255
- if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
4256
- droppedLines += 1;
4257
- scheduleFlush();
4258
- return;
4259
- }
4260
- pending.push({ line, bytes });
4261
- pendingBytes += bytes;
4262
- scheduleFlush();
4263
- };
4264
- }
4265
-
4266
- // host/invocation-authentication-client-command.ts
4267
- var HOST_OWNED_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){0,7}$/u;
4268
- function isHostOwnedFailureCode(value) {
4269
- return typeof value === "string" && HOST_OWNED_CODE.test(value);
4270
- }
4271
- var DOCTOR_FLAGS = Object.freeze({
4272
- "--expected-sha256": "expected_sha256",
4273
- "--expected-source-commit": "expected_source_commit",
4274
- "--expected-instance-ref": "expected_instance_ref"
4275
- });
4276
-
4277
- // host/service-log.ts
4278
- var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
4279
- var HOST_SERVICE_LOG_ARGUMENT = "--ceal-host-service-log";
4280
- var HostServiceLogArgumentError = class extends Error {
4281
- constructor() {
4282
- super("The Host service log argument must occur once with an absolute normalized path.");
4283
- this.name = "HostServiceLogArgumentError";
4079
+ async scanFingerprint(registration) {
4080
+ return this.transcriptSignature(registration);
4284
4081
  }
4285
- };
4286
- function consumeHostServiceLogArgument(args, platform = process.platform) {
4287
- const indexes = args.flatMap((value, index2) => value === HOST_SERVICE_LOG_ARGUMENT ? [index2] : []);
4288
- if (indexes.length === 0) return { args: [...args] };
4289
- const index = indexes[0];
4290
- if (index === void 0) throw new HostServiceLogArgumentError();
4291
- const path = args[index + 1];
4292
- const pathApi = platform === "win32" ? win325 : posix4;
4293
- if (indexes.length !== 1 || path === void 0 || !pathApi.isAbsolute(path) || pathApi.normalize(path) !== path) throw new HostServiceLogArgumentError();
4294
- return { args: [...args.slice(0, index), ...args.slice(index + 2)], path };
4295
- }
4296
- var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
4297
- void persistHostServiceLogLine(line);
4298
- });
4299
- function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
4300
- const details = diagnosticDetails(event, failure_kind, cause);
4301
- const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
4302
- `;
4303
- try {
4304
- (sink ?? defaultHostServiceDiagnosticSink)(line);
4305
- } catch {
4082
+ async transcriptSignature(registration) {
4083
+ try {
4084
+ const info = await lstat4(this.transcriptPathOf(registration), { bigint: true });
4085
+ if (!info.isFile() || info.isSymbolicLink()) return null;
4086
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${info.mode}:${info.uid}`;
4087
+ } catch {
4088
+ return null;
4089
+ }
4306
4090
  }
4307
- }
4308
- function diagnosticDetails(event, failureKind, cause) {
4309
- if (event === "watcher_scan_failed") return {
4310
- ...failureKind === void 0 ? {} : { failure_kind: failureKind },
4311
- ...validDiagnosticCause(cause, event) ? { cause } : {}
4312
- };
4313
- return validDiagnosticCause(cause, event) ? { cause } : {};
4314
- }
4315
- function validDiagnosticCause(cause, event) {
4316
- return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
4317
- }
4318
- function defaultHostServiceDiagnosticSink(line) {
4319
- writeHostServiceLogLine(line);
4320
- }
4321
- var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
4322
- var HOST_SERVICE_LOG_CHECK_INTERVAL_MS = 6e4;
4323
- function hostServiceLogPreviousPath(path) {
4324
- return `${path}.1`;
4325
- }
4326
- async function rotateHostServiceLog(path, maxBytes = HOST_SERVICE_LOG_MAX_BYTES) {
4327
- let size;
4091
+ async scanRegistration(registration) {
4092
+ return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
4093
+ missing: async () => {
4094
+ try {
4095
+ return await this.retireMissing(registration);
4096
+ } catch (error) {
4097
+ return this.scanFailed(void 0, registration, error);
4098
+ }
4099
+ },
4100
+ failed: (handle, error) => this.scanFailed(handle, registration, error)
4101
+ });
4102
+ }
4103
+ async openTranscript(registration, scan, handlers) {
4104
+ let handle;
4105
+ try {
4106
+ handle = await openNoFollow(this.transcriptPathOf(registration));
4107
+ return await scan(handle);
4108
+ } catch (error) {
4109
+ if (handle === void 0 && isMissingTranscriptError(error)) return handlers.missing();
4110
+ return handlers.failed(handle, error);
4111
+ } finally {
4112
+ await handle?.close();
4113
+ }
4114
+ }
4115
+ /**
4116
+ * A transcript the Host deleted never comes back, so retrying its
4117
+ * registration once per reconcile interval is a failure with no end.
4118
+ * Retire it at the scan that finds it missing and say so once. Only
4119
+ * ENOENT means gone; a permission or busy failure is about this moment,
4120
+ * not about the file, and keeps the registration for the next scan.
4121
+ */
4122
+ async retireMissingTranscript(transcriptPath, producerLabel, retire) {
4123
+ await retire();
4124
+ this.log(formatRetiredTranscriptLog(producerLabel, transcriptPath));
4125
+ return { records: 0, enqueued: 0, quarantined: false };
4126
+ }
4127
+ stamp() {
4128
+ return transcriptTimestamp(this.now, this.clockFailure);
4129
+ }
4130
+ expire(retentionMs) {
4131
+ return transcriptExpiration(this.now, retentionMs, this.clockFailure);
4132
+ }
4133
+ sha(value) {
4134
+ return transcriptSha256(value);
4135
+ }
4136
+ objectSha(value) {
4137
+ return transcriptObjectSha256(value);
4138
+ }
4139
+ isRecord(value) {
4140
+ return isTranscriptRecord(value);
4141
+ }
4142
+ readChunk(handle, offset, size) {
4143
+ return readTranscriptCompleteChunk(handle, offset, size);
4144
+ }
4145
+ readAnchor(handle, offset, anchorBytes) {
4146
+ return readTranscriptAnchor(handle, offset, anchorBytes);
4147
+ }
4148
+ cursorIdentityReason(cursor, transcriptPath, device, inode) {
4149
+ return transcriptCursorIdentityReason(cursor, transcriptPath, device, inode);
4150
+ }
4151
+ cursorBoundsReason(handle, cursor, size) {
4152
+ return transcriptCursorBoundsReason(handle, cursor, size);
4153
+ }
4154
+ };
4155
+ async function listHostOutboxDirectoryNames(directory) {
4328
4156
  try {
4329
- size = (await stat(path)).size;
4157
+ return await readdir(directory);
4330
4158
  } catch (error) {
4331
- if (isNotFound(error)) return false;
4159
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
4332
4160
  throw error;
4333
4161
  }
4334
- if (size <= maxBytes) return false;
4335
- await copyFile(path, hostServiceLogPreviousPath(path));
4336
- await truncate(path, 0);
4337
- return true;
4338
- }
4339
- function boundHostServiceLog(environment = process.env) {
4340
- const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
4341
- if (path === void 0 || !isAbsolute2(path)) return () => void 0;
4342
- let reported = false;
4343
- const ready = ensureHostServiceLogDirectory(path);
4344
- const check = () => {
4345
- ready.then(() => rotateHostServiceLog(path)).catch((error) => {
4346
- if (reported) return;
4347
- reported = true;
4348
- writeHostServiceLogLine(`[host-service-log] rotation_failed code=${errorCode3(error)}
4349
- `);
4350
- });
4351
- };
4352
- check();
4353
- const timer = setInterval(check, HOST_SERVICE_LOG_CHECK_INTERVAL_MS);
4354
- timer.unref();
4355
- return () => clearInterval(timer);
4356
- }
4357
- function writeHostServiceLogLine(line, environment = process.env) {
4358
- void persistHostServiceLogLine(line, environment);
4359
- defaultHostServiceLogDelivery(line);
4360
- }
4361
- async function writeHostServiceCommandResult(schemaVersion, result, sink) {
4362
- const line = `${JSON.stringify({ schema_version: schemaVersion, ...result })}
4363
- `;
4364
- const serviceLine = `${JSON.stringify({ schema_version: schemaVersion, ok: result.ok, ...!result.ok ? { code: isHostOwnedFailureCode(result.code) ? result.code : "host_failure_unclassified" } : {} })}
4365
- `;
4366
- await persistHostServiceLogLine(serviceLine);
4367
- sink(line);
4368
- }
4369
- async function persistHostServiceLogLine(line, environment = process.env) {
4370
- if (process.platform !== "win32") return;
4371
- const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
4372
- if (path === void 0 || !win325.isAbsolute(path) || win325.normalize(path) !== path) return;
4373
- await appendHostServiceLogLine(path, line).catch(() => void 0);
4374
- }
4375
- async function appendHostServiceLogLine(path, line) {
4376
- if (!isAbsolute2(path)) return;
4377
- await ensureHostServiceLogDirectory(path);
4378
- await appendFile(path, line);
4379
- }
4380
- var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
4381
- var hostServiceLogDirectories = /* @__PURE__ */ new Map();
4382
- function ensureHostServiceLogDirectory(path) {
4383
- const directory = dirname5(path);
4384
- const existing = hostServiceLogDirectories.get(directory);
4385
- if (existing !== void 0) return existing;
4386
- const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
4387
- hostServiceLogDirectories.delete(directory);
4388
- throw error;
4389
- });
4390
- hostServiceLogDirectories.set(directory, pending);
4391
- return pending;
4392
- }
4393
- function isNotFound(error) {
4394
- return errorCode3(error) === "ENOENT";
4395
- }
4396
- function errorCode3(error) {
4397
- return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unknown";
4398
4162
  }
4163
+ var HostProducerDrainCore = class {
4164
+ host;
4165
+ now;
4166
+ tail = Promise.resolve();
4167
+ constructor(host, runtime) {
4168
+ this.host = host;
4169
+ this.now = runtime.now ?? (() => /* @__PURE__ */ new Date());
4170
+ }
4171
+ drainOutbox() {
4172
+ const run = this.tail.then(() => this.drainLocked());
4173
+ this.tail = run.then(() => void 0, () => void 0);
4174
+ return run;
4175
+ }
4176
+ async drainLocked() {
4177
+ const read2 = await this.host.listEnvelopes();
4178
+ let removed = 0;
4179
+ let expired = 0;
4180
+ for (const envelope of read2.entries) {
4181
+ if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
4182
+ else removed += 1;
4183
+ await this.host.removeEnvelope(envelope);
4184
+ }
4185
+ return { removed, expired, malformed: read2.malformed };
4186
+ }
4187
+ };
4399
4188
 
4400
- // host/relay/src/host-usage-facts-uploader.ts
4401
- var HostUsageFactsUploader = class {
4402
- options;
4403
- store;
4189
+ // host/relay/src/host-usage-facts-store.ts
4190
+ var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
4191
+ var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
4192
+ var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
4193
+ var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
4194
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
4195
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
4196
+ var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
4197
+ var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
4198
+ var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
4199
+ var HostUsageFactsStore = class {
4200
+ root;
4201
+ sessions;
4202
+ batches;
4203
+ platform;
4204
+ custody;
4205
+ afterPendingWrite;
4206
+ afterBatchPublish;
4207
+ sessionDirectoryCursor;
4208
+ uploadScanSignature;
4209
+ uploadScanEmpty = false;
4404
4210
  constructor(options) {
4405
- if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
4406
- this.options = options;
4407
- this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
4211
+ this.root = join3(options.outbox_dir, "usage-facts");
4212
+ this.sessions = join3(this.root, "sessions");
4213
+ this.batches = join3(this.root, "batches");
4214
+ this.platform = options.platform ?? process.platform;
4215
+ this.custody = options.secure_file_custody ?? {};
4216
+ this.afterPendingWrite = options.afterPendingWrite;
4217
+ this.afterBatchPublish = options.afterBatchPublish;
4218
+ }
4219
+ async prepare() {
4220
+ for (const directory of [this.root, this.sessions, this.batches]) {
4221
+ await preparePrivateDirectory(directory, this.platform, this.custody);
4222
+ }
4408
4223
  }
4409
4224
  async close() {
4410
- await this.store.close();
4225
+ const cursor = this.sessionDirectoryCursor;
4226
+ this.sessionDirectoryCursor = void 0;
4227
+ await cursor?.close();
4411
4228
  }
4412
- /** The start owner prepares the store once, so idle ticks below never re-prepare. */
4413
- async prepare() {
4414
- await this.store.prepare();
4229
+ /** The durable path behind one session's usage state, so idle fast paths can poll it without reading it. */
4230
+ statePath(producer, hostSourceRef, hostSessionRef) {
4231
+ return this.sessionPath(producer, hostSourceRef, hostSessionRef);
4415
4232
  }
4416
- async uploadOne(signal) {
4417
- const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4418
- if (candidate === null) return false;
4419
- const registration = await readHostRegistrationAuthority(this.options.registration_state_file, this.options.host_source_ref, this.options.store_options?.platform, this.options.store_options?.secure_file_custody);
4420
- const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4421
- const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4422
- const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4423
- method: "POST",
4424
- headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4425
- body: JSON.stringify(candidate.batch),
4426
- signal: requestSignal
4427
- });
4428
- if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
4429
- await response2.body?.cancel().catch(() => void 0);
4430
- throw new Error("Gateway did not acknowledge the Host usage facts batch.");
4431
- }
4432
- await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
4433
- return true;
4233
+ async readState(producer, hostSourceRef, hostSessionRef) {
4234
+ const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
4235
+ const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
4236
+ if (value === null) return null;
4237
+ validateState(value, producer, hostSourceRef, hostSessionRef);
4238
+ return value;
4434
4239
  }
4435
- };
4436
- async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4437
- const uploader = new HostUsageFactsUploader(options);
4438
- try {
4439
- await uploader.prepare();
4440
- } catch {
4441
- writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4240
+ createState(producer, hostSourceRef, hostSessionRef) {
4241
+ return {
4242
+ schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
4243
+ producer,
4244
+ host_source_ref: hostSourceRef,
4245
+ host_session_ref: hostSessionRef,
4246
+ cursors: {},
4247
+ eligible_batches: [],
4248
+ coverage_gaps: [],
4249
+ coverage_gap_created_at: null
4250
+ };
4442
4251
  }
4443
- let delay = 500;
4444
- let failures = 0;
4445
- try {
4446
- while (!signal.aborted) {
4447
- try {
4448
- await options.capture_next?.();
4449
- } catch {
4450
- writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
4252
+ async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
4253
+ let state = await this.readState(producer, hostSourceRef, hostSessionRef);
4254
+ if (state === null) {
4255
+ state = this.createState(producer, hostSourceRef, hostSessionRef);
4256
+ state = await this.writeCursor(state, sourceSlot, initial);
4257
+ }
4258
+ state = await this.recoverPending(state);
4259
+ if (state.quarantined_reason !== void 0) return null;
4260
+ state = await this.commitCoverageGaps(state, createdAt);
4261
+ const cursor = state.cursors[sourceSlot];
4262
+ return cursor === void 0 ? null : { state, cursor };
4263
+ }
4264
+ async writeCursor(state, sourceSlot, cursor) {
4265
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
4266
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
4267
+ if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
4268
+ const current = latest.cursors[sourceSlot];
4269
+ if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
4270
+ const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
4271
+ await this.writeState(updated);
4272
+ return updated;
4273
+ });
4274
+ }
4275
+ async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
4276
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
4277
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
4278
+ return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
4279
+ });
4280
+ }
4281
+ async recoverPending(state) {
4282
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
4283
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
4284
+ const recovered = await this.finishPendingTransition(latest);
4285
+ await this.sweepOrphanedBatches(recovered);
4286
+ return recovered;
4287
+ });
4288
+ }
4289
+ /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
4290
+ async sweepOrphanedBatches(state) {
4291
+ const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
4292
+ const expected = expectedBatchNames(state);
4293
+ let directory;
4294
+ try {
4295
+ directory = await opendir(directoryPath);
4296
+ } catch (error) {
4297
+ if (errorCode3(error) === "ENOENT") return 0;
4298
+ throw error;
4299
+ }
4300
+ let inspected = 0;
4301
+ let deleted = 0;
4302
+ try {
4303
+ while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
4304
+ const entry = await directory.read();
4305
+ if (entry === null) break;
4306
+ inspected += 1;
4307
+ if (!isOrphanBatchEntry(entry, expected)) continue;
4308
+ await unlink2(join3(directoryPath, entry.name));
4309
+ deleted += 1;
4451
4310
  }
4452
- if (signal.aborted) return;
4311
+ } finally {
4312
+ await directory.close();
4313
+ }
4314
+ if (deleted > 0) await syncDirectory(directoryPath, this.platform);
4315
+ return deleted;
4316
+ }
4317
+ async commitCoverageGaps(state, createdAt) {
4318
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
4319
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
4320
+ if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
4321
+ const sourceRanges = coverageRanges(latest.coverage_gaps);
4322
+ const canonical = createCealHostUsageBatch({
4323
+ host_source_ref: latest.host_source_ref,
4324
+ host_session_ref: latest.host_session_ref,
4325
+ created_at: latest.coverage_gap_created_at ?? createdAt,
4326
+ source_ranges: sourceRanges,
4327
+ facts: [],
4328
+ coverage_gaps: latest.coverage_gaps
4329
+ });
4330
+ const cursor = firstCursor(latest);
4331
+ if (cursor === null) return latest;
4332
+ return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
4333
+ });
4334
+ }
4335
+ async nextUploadCandidate(producer, hostSourceRef) {
4336
+ const signature = await statObservedPathSignature(this.sessions);
4337
+ if (signature !== null && signature === this.uploadScanSignature && this.uploadScanEmpty) return null;
4338
+ const candidate = await this.scanUploadCandidates(producer, hostSourceRef);
4339
+ this.uploadScanSignature = signature ?? void 0;
4340
+ this.uploadScanEmpty = candidate === null;
4341
+ return candidate;
4342
+ }
4343
+ async scanUploadCandidates(producer, hostSourceRef) {
4344
+ const names = await this.readNextSessionNames();
4345
+ for (const name of names) {
4346
+ const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
4347
+ if (state === null) continue;
4348
+ validateStateOwner(state, producer, hostSourceRef);
4349
+ let validated = state;
4350
+ if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
4351
+ else validated = await this.recoverPending(validated);
4352
+ if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
4353
+ const next = validated.eligible_batches[0];
4354
+ if (next === void 0) continue;
4355
+ const batch = await this.readBatch(validated, next.batch_ref);
4356
+ return { state: validated, batch };
4357
+ }
4358
+ return null;
4359
+ }
4360
+ async readNextSessionNames() {
4361
+ if (this.sessionDirectoryCursor === void 0) {
4453
4362
  try {
4454
- const uploaded = await uploader.uploadOne(signal);
4455
- failures = 0;
4456
- delay = uploaded ? 100 : 1e3;
4457
- } catch {
4458
- if (signal.aborted) return;
4459
- failures += 1;
4460
- delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
4461
- writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4363
+ this.sessionDirectoryCursor = await opendir(this.sessions);
4364
+ } catch (error) {
4365
+ if (errorCode3(error) === "ENOENT") return [];
4366
+ throw error;
4462
4367
  }
4463
- if (!signal.aborted) await wait(signal, delay);
4464
4368
  }
4465
- } finally {
4466
- await uploader.close().catch(() => void 0);
4369
+ const names = [];
4370
+ let inspected = 0;
4371
+ while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
4372
+ const entry = await this.sessionDirectoryCursor.read();
4373
+ if (entry === null) {
4374
+ await this.sessionDirectoryCursor.close();
4375
+ this.sessionDirectoryCursor = void 0;
4376
+ break;
4377
+ }
4378
+ inspected += 1;
4379
+ if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
4380
+ }
4381
+ return names;
4382
+ }
4383
+ async acknowledge(state, batchRef) {
4384
+ await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
4385
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
4386
+ if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
4387
+ const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
4388
+ if (remaining.length === latest.eligible_batches.length) return;
4389
+ await this.writeState({ ...latest, eligible_batches: remaining });
4390
+ await removeFileIfPresent(this.batchPath(state, batchRef));
4391
+ });
4392
+ }
4393
+ async quarantine(state, reason) {
4394
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
4395
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
4396
+ const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
4397
+ await this.writeState(updated);
4398
+ return updated;
4399
+ });
4400
+ }
4401
+ async retireCursor(state, sourceSlot, cursor, gap) {
4402
+ return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
4403
+ }
4404
+ async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
4405
+ if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
4406
+ if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
4407
+ const queued = await this.publishTransitionBatch(state, batch);
4408
+ const pending = {
4409
+ source_slot: sourceSlot,
4410
+ before_cursor: beforeCursor,
4411
+ after_cursor: afterCursor,
4412
+ batch_ref: queued.batch_ref,
4413
+ batch_bytes: queued.batch_bytes,
4414
+ gap_delta: [...gapDelta, ...queued.overflow_gaps],
4415
+ clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
4416
+ };
4417
+ const prepared = { ...state, pending_transition: pending };
4418
+ await this.writeState(prepared);
4419
+ await this.afterPendingWrite?.();
4420
+ return await this.finishPendingTransition(prepared);
4421
+ }
4422
+ async publishTransitionBatch(state, batch) {
4423
+ if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
4424
+ const serialized = serializeBatch(batch);
4425
+ if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
4426
+ await this.writeImmutableBatch(state, batch, serialized);
4427
+ await this.afterBatchPublish?.();
4428
+ return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
4429
+ }
4430
+ async finishPendingTransition(state) {
4431
+ const pending = state.pending_transition;
4432
+ if (pending === void 0 || state.quarantined_reason !== void 0) return state;
4433
+ const current = state.cursors[pending.source_slot];
4434
+ if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
4435
+ const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
4436
+ await this.writeState(quarantined);
4437
+ return quarantined;
4438
+ }
4439
+ let cursors = state.cursors;
4440
+ if (!cursorMatches(current, pending.after_cursor)) {
4441
+ const next = { ...state.cursors };
4442
+ if (pending.after_cursor === null) delete next[pending.source_slot];
4443
+ else next[pending.source_slot] = pending.after_cursor;
4444
+ cursors = next;
4445
+ }
4446
+ const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
4447
+ const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
4448
+ const { pending_transition: _pendingTransition, ...settledState } = state;
4449
+ const updated = {
4450
+ ...settledState,
4451
+ cursors,
4452
+ eligible_batches: eligible,
4453
+ coverage_gaps: gaps,
4454
+ coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
4455
+ };
4456
+ await this.writeState(updated);
4457
+ return updated;
4458
+ }
4459
+ async writeImmutableBatch(state, batch, bytes) {
4460
+ const path = this.batchPath(state, batch.batch_ref);
4461
+ await preparePrivateDirectory(dirname5(path), this.platform, this.custody);
4462
+ const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
4463
+ if (existing !== null) {
4464
+ if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
4465
+ await syncExistingFile(path, this.platform);
4466
+ return;
4467
+ }
4468
+ if (this.platform === "win32") {
4469
+ await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
4470
+ return;
4471
+ }
4472
+ let handle;
4473
+ try {
4474
+ handle = await openNoFollow(path, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384, this.platform);
4475
+ await handle.writeFile(bytes);
4476
+ await handle.sync();
4477
+ await handle.close();
4478
+ handle = void 0;
4479
+ await syncDirectory(dirname5(path), this.platform);
4480
+ } catch (error) {
4481
+ await handle?.close().catch(() => void 0);
4482
+ if (errorCode3(error) === "EEXIST") {
4483
+ const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
4484
+ if (winner !== null && winner.equals(bytes)) {
4485
+ await syncExistingFile(path, this.platform);
4486
+ return;
4487
+ }
4488
+ throw new Error("Host usage facts batch reference conflicts with existing bytes.");
4489
+ }
4490
+ await removeFileIfPresent(path).catch(() => void 0);
4491
+ throw error;
4492
+ }
4493
+ }
4494
+ async readBatch(state, batchRef) {
4495
+ const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
4496
+ if (bytes === null) throw new Error("Host usage facts batch object is missing.");
4497
+ let value;
4498
+ try {
4499
+ value = JSON.parse(bytes.toString("utf8"));
4500
+ } catch {
4501
+ throw new Error("Host usage facts batch object is malformed.");
4502
+ }
4503
+ validateCealHostUsageBatch(value);
4504
+ if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
4505
+ return value;
4506
+ }
4507
+ async writeState(state) {
4508
+ validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
4509
+ const bytes = Buffer.from(JSON.stringify(state), "utf8");
4510
+ if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
4511
+ await this.prepare();
4512
+ const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
4513
+ if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
4514
+ else await durableAtomicReplace(path, bytes);
4515
+ }
4516
+ async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
4517
+ const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
4518
+ const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
4519
+ let release;
4520
+ const gate = new Promise((resolve) => {
4521
+ release = resolve;
4522
+ });
4523
+ const tail2 = previous.then(() => gate);
4524
+ SESSION_TRANSITION_TAILS.set(key, tail2);
4525
+ await previous;
4526
+ try {
4527
+ return await run();
4528
+ } finally {
4529
+ release?.();
4530
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
4531
+ }
4467
4532
  }
4533
+ sessionPath(producer, hostSourceRef, hostSessionRef) {
4534
+ return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
4535
+ }
4536
+ batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
4537
+ const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
4538
+ return join3(this.batches, sessionName.slice(0, -5));
4539
+ }
4540
+ batchPath(state, batchRef) {
4541
+ return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
4542
+ }
4543
+ };
4544
+ function serializeBatch(batch) {
4545
+ validateCealHostUsageBatch(batch);
4546
+ return Buffer.from(JSON.stringify(batch), "utf8");
4468
4547
  }
4469
-
4470
- // host/relay/src/host-producer-core.ts
4471
- import { createHash as createHash6 } from "node:crypto";
4472
- import { readdir } from "node:fs/promises";
4473
- var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
4474
- function isHostTranscriptCursorReason(value) {
4475
- return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
4548
+ function batchFileName(batchRef) {
4549
+ const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
4550
+ if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
4551
+ return `${digest2}.json`;
4476
4552
  }
4477
- var TRANSCRIPT_MISSING_REASON = "transcript_missing";
4478
- var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
4479
- var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
4480
- function mergeHostInvocationHumanMessageWindow(existing, chronological) {
4481
- const seen = /* @__PURE__ */ new Set();
4482
- const newestFirst = [];
4483
- for (const message of [...chronological].reverse()) {
4484
- if (seen.has(message.host_input_ref)) continue;
4485
- seen.add(message.host_input_ref);
4486
- newestFirst.push(message);
4487
- }
4488
- for (const message of existing?.messages ?? []) {
4489
- if (seen.has(message.host_input_ref)) continue;
4490
- seen.add(message.host_input_ref);
4491
- newestFirst.push(message);
4553
+ function expectedBatchNames(state) {
4554
+ const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
4555
+ const pending = state.pending_transition?.batch_ref;
4556
+ if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
4557
+ return expected;
4558
+ }
4559
+ function isOrphanBatchEntry(entry, expected) {
4560
+ return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
4561
+ }
4562
+ function hasOutboxCapacity(state, bytes) {
4563
+ const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
4564
+ return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
4565
+ }
4566
+ function overflowCoverageGaps(batch) {
4567
+ const count = batch.facts.length;
4568
+ const gaps = [...batch.coverage_gaps];
4569
+ if (count > 0) gaps.push({ reason: "outbox_capacity", source_file_ref: batch.source_ranges[0]?.source_file_ref ?? null, start_offset: batch.source_ranges[0]?.start_offset ?? null, end_offset: batch.source_ranges[0]?.end_offset ?? null, omitted_count: count });
4570
+ return gaps;
4571
+ }
4572
+ function appendEligible(existing, next) {
4573
+ if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
4574
+ if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
4575
+ return [...existing, next];
4576
+ }
4577
+ function appendCoverageGaps(existing, added) {
4578
+ if (added.length === 0) return existing;
4579
+ const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
4580
+ for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
4581
+ const combined = [...byIdentity.values()];
4582
+ if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
4583
+ const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
4584
+ return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
4585
+ }
4586
+ function coverageRanges(gaps) {
4587
+ const ranges = /* @__PURE__ */ new Map();
4588
+ for (const gap of gaps) {
4589
+ if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
4590
+ const current = ranges.get(gap.source_file_ref);
4591
+ if (current === void 0) ranges.set(gap.source_file_ref, { source_file_ref: gap.source_file_ref, start_offset: gap.start_offset, end_offset: gap.end_offset });
4592
+ else ranges.set(gap.source_file_ref, { ...current, start_offset: Math.min(current.start_offset, gap.start_offset), end_offset: Math.max(current.end_offset, gap.end_offset) });
4492
4593
  }
4493
- return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
4594
+ return [...ranges.values()];
4494
4595
  }
4495
- function transcriptScanFailureKind(error, adapterFailureKind) {
4496
- if (transcriptErrorCode(error) === "ELOOP") return "symlink";
4497
- const adapter = adapterFailureKind(error);
4498
- if (adapter !== void 0) return adapter;
4499
- const code = transcriptErrorCode(error);
4500
- if (code === "EFBIG") return "size_budget";
4501
- if (code !== null && TRANSCRIPT_SCAN_READ_ERROR_ERRNOS.includes(code)) return "read_error";
4502
- return "other";
4596
+ function firstCursor(state) {
4597
+ const entry = Object.entries(state.cursors)[0];
4598
+ return entry === void 0 ? null : entry;
4503
4599
  }
4504
- function transcriptErrorCode(error) {
4505
- return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
4600
+ function sameCursor(left, right) {
4601
+ return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
4506
4602
  }
4507
- var HOST_TRANSCRIPT_READ_CHUNK_BYTES = 256 * 1024;
4508
- async function readTranscriptCompleteChunk(handle, offset, size) {
4509
- const available = Math.max(0, size - offset);
4510
- if (available === 0) return "empty";
4511
- const chunks = [];
4512
- let position = offset;
4513
- let total = 0;
4514
- let lastNewline = -1;
4515
- while (position < size) {
4516
- const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
4517
- const read2 = await handle.read(buffer, 0, buffer.length, position);
4518
- if (read2.bytesRead === 0) break;
4519
- const chunk = buffer.subarray(0, read2.bytesRead);
4520
- chunks.push(chunk);
4521
- const newline = chunk.lastIndexOf(10);
4522
- if (newline >= 0) lastNewline = total + newline;
4523
- total += chunk.length;
4524
- position += chunk.length;
4525
- if (lastNewline >= 0) break;
4603
+ function cursorMatches(left, right) {
4604
+ return right === null ? left === void 0 : sameCursor(left, right);
4605
+ }
4606
+ function validateState(value, producer, hostSourceRef, hostSessionRef) {
4607
+ validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
4608
+ validateStateShape(value);
4609
+ validateStateLimits(value);
4610
+ validateStateContents(value);
4611
+ }
4612
+ function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
4613
+ if (!isRecord3(value) || value.schema_version !== HOST_USAGE_FACTS_STATE_SCHEMA || value.producer !== producer || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new Error("Host usage facts state identity is invalid.");
4614
+ }
4615
+ function validateStateLimits(value) {
4616
+ if (Object.keys(value.cursors).length > HOST_USAGE_FACTS_MAX_SOURCE_CURSORS || value.eligible_batches.length > HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES || value.coverage_gaps.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) throw new Error("Host usage facts state exceeds its bounds.");
4617
+ }
4618
+ function validateStateContents(value) {
4619
+ for (const [slot, cursor] of Object.entries(value.cursors)) {
4620
+ validateSourceSlot(slot);
4621
+ validateFileCursor(cursor);
4526
4622
  }
4527
- if (lastNewline < 0) return "partial";
4528
- return Buffer.concat(chunks, total).subarray(0, lastNewline + 1);
4623
+ for (const item of value.eligible_batches) validateEligibleBatch(item);
4624
+ if (value.pending_transition !== void 0) validatePending(value.pending_transition);
4625
+ for (const gap of value.coverage_gaps) validateGap(gap);
4626
+ validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
4529
4627
  }
4530
- async function readTranscriptAnchor(handle, offset, anchorBytes) {
4531
- const start = Math.max(0, offset - anchorBytes);
4532
- const anchor = Buffer.alloc(offset - start);
4533
- if (anchor.length > 0) await handle.read(anchor, 0, anchor.length, start);
4534
- return { start, sha256: transcriptSha256(anchor) };
4628
+ function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
4629
+ if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
4630
+ if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
4535
4631
  }
4536
- async function transcriptAnchorMatches(handle, cursor) {
4537
- const buffer = Buffer.alloc(cursor.offset - cursor.anchor_start);
4538
- if (buffer.length > 0) await handle.read(buffer, 0, buffer.length, cursor.anchor_start);
4539
- return transcriptSha256(buffer) === cursor.anchor_sha256;
4632
+ function validateStateOwner(value, producer, hostSourceRef) {
4633
+ if (!isRecord3(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
4634
+ validateState(value, producer, hostSourceRef, String(value.host_session_ref));
4540
4635
  }
4541
- function transcriptCursorIdentityReason(cursor, transcriptPath, device, inode) {
4542
- if (cursor.device !== device || cursor.inode !== inode || cursor.transcript_path !== transcriptPath) return "transcript_replaced";
4543
- return null;
4636
+ function validateStateShape(value) {
4637
+ const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
4638
+ const optional = ["pending_transition", "quarantined_reason"];
4639
+ if (required.some((key) => !Object.hasOwn(value, key)) || Object.keys(value).some((key) => !required.includes(key) && !optional.includes(key))) throw new Error("Host usage facts state keys are invalid.");
4640
+ if (!isRecord3(value.cursors) || !Array.isArray(value.eligible_batches) || !Array.isArray(value.coverage_gaps) || value.coverage_gap_created_at !== null && typeof value.coverage_gap_created_at !== "string") throw new Error("Host usage facts state collections are invalid.");
4544
4641
  }
4545
- async function transcriptCursorBoundsReason(handle, cursor, size) {
4546
- if (size < cursor.offset) return "transcript_truncated";
4547
- if (cursor.offset > 0 && !await transcriptAnchorMatches(handle, cursor)) return "transcript_rewritten";
4548
- return null;
4642
+ function validateFileCursor(value) {
4643
+ if (!isRecord3(value) || !sameKeys(value, ["source_file_ref", "device", "inode", "offset", "anchor_start", "anchor_sha256", "last_ordinal", "host_turn_ref", "native_turn_id", "requested_model", "codex_total_usage", "skipping_oversized_line"])) throw new Error("Host usage facts source cursor is invalid.");
4644
+ validateCursorIdentity(value);
4645
+ validateCursorOffsets(value);
4646
+ validateCursorContext(value);
4647
+ if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
4648
+ if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
4549
4649
  }
4550
- function transcriptSha256(value) {
4551
- return createHash6("sha256").update(value).digest("hex");
4650
+ function validateCursorIdentity(value) {
4651
+ if (![value.source_file_ref, value.device, value.inode].every((part) => typeof part === "string" && part.length > 0 && part.length <= HOST_USAGE_FACTS_REF_MAX_LENGTH)) throw new Error("Host usage facts source cursor identity is invalid.");
4552
4652
  }
4553
- function transcriptObjectSha256(value) {
4554
- return createHash6("sha256").update(JSON.stringify(value), "utf8").digest("hex");
4653
+ function validateCursorOffsets(value) {
4654
+ if (!/^host-source-file:[a-f0-9]{64}$/u.test(String(value.source_file_ref)) || !safeInteger2(value.offset) || !safeInteger2(value.anchor_start) || Number(value.anchor_start) > Number(value.offset) || !/^[a-f0-9]{64}$/u.test(String(value.anchor_sha256)) || value.last_ordinal !== null && !safeInteger2(value.last_ordinal)) throw new Error("Host usage facts source cursor fields are invalid.");
4555
4655
  }
4556
- function isTranscriptRecord(value) {
4557
- return value !== null && typeof value === "object" && !Array.isArray(value);
4656
+ function validateCursorContext(value) {
4657
+ if (!validOptionalText(value.host_turn_ref, HOST_USAGE_FACTS_REF_MAX_LENGTH) || !validOptionalText(value.native_turn_id, HOST_USAGE_FACTS_REF_MAX_LENGTH) || !validOptionalText(value.requested_model, 256)) throw new Error("Host usage facts source context is invalid.");
4558
4658
  }
4559
- function isMissingTranscriptError(error) {
4560
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
4659
+ function validOptionalText(value, maximum) {
4660
+ return value === null || typeof value === "string" && value.length <= maximum;
4561
4661
  }
4562
- function transcriptTimestamp(now, fail) {
4563
- const value = now();
4564
- if (!Number.isFinite(value.getTime())) throw fail();
4565
- return value.toISOString();
4662
+ function validateCodexCounts(value) {
4663
+ if (!isRecord3(value) || !sameKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) throw new Error("Host usage facts cumulative usage is invalid.");
4664
+ if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
4566
4665
  }
4567
- function transcriptExpiration(now, retentionMs, fail) {
4568
- return new Date(Date.parse(transcriptTimestamp(now, fail)) + retentionMs).toISOString();
4666
+ function validatePending(value) {
4667
+ if (!isRecord3(value) || !sameKeys(value, ["source_slot", "before_cursor", "after_cursor", "batch_ref", "batch_bytes", "gap_delta", "clear_coverage_gaps"])) throw new Error("Host usage facts pending transition is invalid.");
4668
+ validatePendingCursors(value);
4669
+ validatePendingBatch(value);
4670
+ validatePendingFields(value);
4671
+ for (const gap of value.gap_delta) validateGap(gap);
4569
4672
  }
4570
- function createTranscriptWatcherBase(options, owner) {
4571
- if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0) throw owner.invalid_outbox();
4572
- return {
4573
- outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
4574
- now: options.now ?? (() => /* @__PURE__ */ new Date()),
4575
- log: options.log ?? ((line) => {
4576
- writeHostServiceLogLine(`${line}
4577
- `);
4578
- }),
4579
- producerInstallationRef: options.producer_installation_ref
4580
- };
4673
+ function validatePendingCursors(value) {
4674
+ validateSourceSlot(value.source_slot);
4675
+ validateFileCursor(value.before_cursor);
4676
+ if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
4581
4677
  }
4582
- async function scanTranscriptRegistrations(registrations, scanOne) {
4583
- let records = 0;
4584
- let enqueued = 0;
4585
- let quarantined = 0;
4586
- for (const registration of registrations) {
4587
- const result = await scanOne(registration);
4588
- records += result.records;
4589
- enqueued += result.enqueued;
4590
- if (result.quarantined) quarantined += 1;
4591
- }
4592
- return { registrations: registrations.length, records, enqueued, quarantined };
4678
+ function validatePendingBatch(value) {
4679
+ if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
4593
4680
  }
4594
- function formatRetiredTranscriptLog(producerLabel, transcriptPath) {
4595
- return `${producerLabel} retired a transcript registration: transcript_path=${JSON.stringify(transcriptPath)}, reason=${TRANSCRIPT_MISSING_REASON}.`;
4681
+ function validatePendingFields(value) {
4682
+ if (!safeInteger2(value.batch_bytes) || !Array.isArray(value.gap_delta) || value.gap_delta.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS || typeof value.clear_coverage_gaps !== "boolean") throw new Error("Host usage facts pending transition fields are invalid.");
4596
4683
  }
4597
- var HostTranscriptWatcher = class {
4598
- outboxRetentionMs;
4599
- now;
4600
- log;
4601
- producerInstallationRef;
4602
- clockFailure;
4603
- constructor(options, owner) {
4604
- const base = createTranscriptWatcherBase(options, owner);
4605
- this.outboxRetentionMs = base.outboxRetentionMs;
4606
- this.now = base.now;
4607
- this.log = base.log;
4608
- this.producerInstallationRef = base.producerInstallationRef;
4609
- this.clockFailure = owner.clock_failure;
4610
- }
4611
- async scanOnce() {
4612
- return scanTranscriptRegistrations(await this.listRegistrations(), (registration) => this.scanRegistration(registration));
4684
+ function validateEligibleBatch(value) {
4685
+ if (!isRecord3(value) || !sameKeys(value, ["batch_ref", "bytes"]) || !isCealHostUsageBatchReference(value.batch_ref) || !safeInteger2(value.bytes) || Number(value.bytes) < 1 || Number(value.bytes) > CEAL_HOST_USAGE_BATCH_MAX_BYTES) throw new Error("Host usage facts eligible batch is invalid.");
4686
+ }
4687
+ function validateGap(value) {
4688
+ try {
4689
+ validateCealHostUsageCoverageGap(value);
4690
+ } catch {
4691
+ throw new Error("Host usage facts coverage gap is invalid.");
4613
4692
  }
4614
- async scanRegistration(registration) {
4615
- return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
4616
- missing: async () => {
4617
- try {
4618
- return await this.retireMissing(registration);
4619
- } catch (error) {
4620
- return this.scanFailed(void 0, registration, error);
4621
- }
4622
- },
4623
- failed: (handle, error) => this.scanFailed(handle, registration, error)
4624
- });
4693
+ }
4694
+ function validateSourceSlot(value) {
4695
+ if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
4696
+ }
4697
+ async function readOptionalJson(path, maxBytes, platform, custody) {
4698
+ const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
4699
+ if (bytes === null) return null;
4700
+ try {
4701
+ return JSON.parse(bytes.toString("utf8"));
4702
+ } catch {
4703
+ throw new Error("Host usage facts state JSON is malformed.");
4625
4704
  }
4626
- async openTranscript(registration, scan, handlers) {
4627
- let handle;
4705
+ }
4706
+ async function readOptionalBytes(path, maxBytes, platform, custody) {
4707
+ if (platform === "win32") {
4628
4708
  try {
4629
- handle = await openNoFollow(this.transcriptPathOf(registration));
4630
- return await scan(handle);
4709
+ return await readPrivateFileWithSecurefs(path, maxBytes, custody);
4631
4710
  } catch (error) {
4632
- if (handle === void 0 && isMissingTranscriptError(error)) return handlers.missing();
4633
- return handlers.failed(handle, error);
4634
- } finally {
4635
- await handle?.close();
4711
+ if (errorCode3(error) === "ENOENT") return null;
4712
+ throw error;
4636
4713
  }
4637
4714
  }
4638
- /**
4639
- * A transcript the Host deleted never comes back, so retrying its
4640
- * registration once per reconcile interval is a failure with no end.
4641
- * Retire it at the scan that finds it missing and say so once. Only
4642
- * ENOENT means gone; a permission or busy failure is about this moment,
4643
- * not about the file, and keeps the registration for the next scan.
4644
- */
4645
- async retireMissingTranscript(transcriptPath, producerLabel, retire) {
4646
- await retire();
4647
- this.log(formatRetiredTranscriptLog(producerLabel, transcriptPath));
4648
- return { records: 0, enqueued: 0, quarantined: false };
4649
- }
4650
- stamp() {
4651
- return transcriptTimestamp(this.now, this.clockFailure);
4715
+ let handle;
4716
+ try {
4717
+ handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
4718
+ const stats = await handle.stat();
4719
+ if (!stats.isFile() || !isSelfOwned(stats.uid, platform, handle) || !isPrivateFileMode(stats.mode, platform, handle) || stats.size > maxBytes) throw new Error("Host usage facts file custody or size is invalid.");
4720
+ return await handle.readFile();
4721
+ } catch (error) {
4722
+ if (errorCode3(error) === "ENOENT") return null;
4723
+ throw error;
4724
+ } finally {
4725
+ await handle?.close();
4652
4726
  }
4653
- expire(retentionMs) {
4654
- return transcriptExpiration(this.now, retentionMs, this.clockFailure);
4727
+ }
4728
+ async function preparePrivateDirectory(path, platform, custody) {
4729
+ if (platform === "win32") {
4730
+ await ensurePrivateDirectoryWithSecurefs(path, custody);
4731
+ return;
4655
4732
  }
4656
- sha(value) {
4657
- return transcriptSha256(value);
4733
+ await mkdir3(path, { recursive: true, mode: 448 });
4734
+ if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
4735
+ }
4736
+ async function syncExistingFile(path, platform) {
4737
+ const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
4738
+ try {
4739
+ await handle.sync();
4740
+ } finally {
4741
+ await handle.close();
4658
4742
  }
4659
- objectSha(value) {
4660
- return transcriptObjectSha256(value);
4743
+ await syncDirectory(dirname5(path), platform);
4744
+ }
4745
+ async function syncDirectory(path, platform) {
4746
+ if (platform === "win32") return;
4747
+ const handle = await open3(path, constants4.O_RDONLY);
4748
+ try {
4749
+ await handle.sync();
4750
+ } finally {
4751
+ await handle.close();
4661
4752
  }
4662
- isRecord(value) {
4663
- return isTranscriptRecord(value);
4753
+ }
4754
+ async function removeFileIfPresent(path) {
4755
+ try {
4756
+ await unlink2(path);
4757
+ } catch (error) {
4758
+ if (errorCode3(error) !== "ENOENT") throw error;
4664
4759
  }
4665
- readChunk(handle, offset, size) {
4666
- return readTranscriptCompleteChunk(handle, offset, size);
4760
+ }
4761
+ function sameKeys(value, expected) {
4762
+ return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
4763
+ }
4764
+ function isRecord3(value) {
4765
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4766
+ }
4767
+ function safeInteger2(value) {
4768
+ return Number.isSafeInteger(value) && Number(value) >= 0;
4769
+ }
4770
+ function validTimestamp(value) {
4771
+ return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
4772
+ }
4773
+ function errorCode3(error) {
4774
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
4775
+ }
4776
+ function sha2562(value) {
4777
+ return createHash6("sha256").update(value, "utf8").digest("hex");
4778
+ }
4779
+
4780
+ // host/relay/src/host-usage-facts-uploader.ts
4781
+ var HostUsageFactsUploader = class {
4782
+ options;
4783
+ store;
4784
+ constructor(options) {
4785
+ if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
4786
+ this.options = options;
4787
+ this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
4667
4788
  }
4668
- readAnchor(handle, offset, anchorBytes) {
4669
- return readTranscriptAnchor(handle, offset, anchorBytes);
4789
+ async close() {
4790
+ await this.store.close();
4670
4791
  }
4671
- cursorIdentityReason(cursor, transcriptPath, device, inode) {
4672
- return transcriptCursorIdentityReason(cursor, transcriptPath, device, inode);
4792
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
4793
+ async prepare() {
4794
+ await this.store.prepare();
4673
4795
  }
4674
- cursorBoundsReason(handle, cursor, size) {
4675
- return transcriptCursorBoundsReason(handle, cursor, size);
4796
+ async uploadOne(signal) {
4797
+ const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4798
+ if (candidate === null) return false;
4799
+ const registration = await readHostRegistrationAuthority(this.options.registration_state_file, this.options.host_source_ref, this.options.store_options?.platform, this.options.store_options?.secure_file_custody);
4800
+ const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4801
+ const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4802
+ const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4803
+ method: "POST",
4804
+ headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4805
+ body: JSON.stringify(candidate.batch),
4806
+ signal: requestSignal
4807
+ });
4808
+ if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
4809
+ await response2.body?.cancel().catch(() => void 0);
4810
+ throw new Error("Gateway did not acknowledge the Host usage facts batch.");
4811
+ }
4812
+ await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
4813
+ return true;
4676
4814
  }
4677
4815
  };
4678
- async function listHostOutboxDirectoryNames(directory) {
4816
+ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4817
+ const uploader = new HostUsageFactsUploader(options);
4679
4818
  try {
4680
- return await readdir(directory);
4681
- } catch (error) {
4682
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
4683
- throw error;
4684
- }
4685
- }
4686
- var HostProducerDrainCore = class {
4687
- host;
4688
- now;
4689
- tail = Promise.resolve();
4690
- constructor(host, runtime) {
4691
- this.host = host;
4692
- this.now = runtime.now ?? (() => /* @__PURE__ */ new Date());
4693
- }
4694
- drainOutbox() {
4695
- const run = this.tail.then(() => this.drainLocked());
4696
- this.tail = run.then(() => void 0, () => void 0);
4697
- return run;
4819
+ await uploader.prepare();
4820
+ } catch {
4821
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4698
4822
  }
4699
- async drainLocked() {
4700
- const read2 = await this.host.listEnvelopes();
4701
- let removed = 0;
4702
- let expired = 0;
4703
- for (const envelope of read2.entries) {
4704
- if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
4705
- else removed += 1;
4706
- await this.host.removeEnvelope(envelope);
4823
+ let delay = 500;
4824
+ let failures = 0;
4825
+ try {
4826
+ while (!signal.aborted) {
4827
+ try {
4828
+ await options.capture_next?.();
4829
+ } catch {
4830
+ writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
4831
+ }
4832
+ if (signal.aborted) return;
4833
+ try {
4834
+ const uploaded = await uploader.uploadOne(signal);
4835
+ failures = 0;
4836
+ delay = uploaded ? 100 : 1e3;
4837
+ } catch {
4838
+ if (signal.aborted) return;
4839
+ failures += 1;
4840
+ delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
4841
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4842
+ }
4843
+ if (!signal.aborted) await wait(signal, delay);
4707
4844
  }
4708
- return { removed, expired, malformed: read2.malformed };
4845
+ } finally {
4846
+ await uploader.close().catch(() => void 0);
4709
4847
  }
4710
- };
4848
+ }
4711
4849
 
4712
4850
  // host/codex/src/codex-outbox.ts
4713
- import { mkdir as mkdir4, open as open4, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
4714
- import { dirname as dirname6, isAbsolute as isAbsolute3, join as join5 } from "node:path";
4851
+ import { mkdir as mkdir4, open as open4, rename as rename2, stat as stat3, unlink as unlink3 } from "node:fs/promises";
4852
+ import { dirname as dirname7, isAbsolute as isAbsolute2, join as join4 } from "node:path";
4715
4853
 
4716
4854
  // host/invocation-context.ts
4717
4855
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -4768,18 +4906,11 @@ function safeRef(value) {
4768
4906
  var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
4769
4907
  var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "turn_terminal", "producer_status"];
4770
4908
  var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
4771
- var HOST_PRODUCER_FRAME_ERROR_CODES = [
4772
- "invalid_frame_encoding",
4773
- "invalid_frame_length",
4774
- "frame_truncated",
4775
- "unsupported_frame_schema",
4776
- "invalid_frame_shape",
4777
- "invalid_producer_identity",
4778
- "frame_too_large"
4779
- ];
4780
4909
 
4781
4910
  // host/relay/src/host-usage-facts-capture.ts
4782
4911
  import { constants as constants5 } from "node:fs";
4912
+ import { lstat as lstat5 } from "node:fs/promises";
4913
+ import { dirname as dirname6 } from "node:path";
4783
4914
  var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
4784
4915
  var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
4785
4916
  var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
@@ -4829,6 +4960,55 @@ var HostUsageRegistrationCapture = class {
4829
4960
  return captured;
4830
4961
  }
4831
4962
  };
4963
+ var HostUsageIdleGate = class {
4964
+ seen = /* @__PURE__ */ new Map();
4965
+ statPath;
4966
+ constructor(options = {}) {
4967
+ this.statPath = options.statPath ?? statIdleGatePath;
4968
+ }
4969
+ /**
4970
+ * Check whether the path is unchanged since the last confirmed check, without recording anything.
4971
+ * The caller confirms the returned signature only after the capture for it succeeded without a
4972
+ * source error, so a failed read leaves the source eligible on the next tick while a fully-read,
4973
+ * unchanged source keeps skipping its open plus state-read probe.
4974
+ */
4975
+ async checkUnchanged(key, path) {
4976
+ const signature = await this.statPath(path);
4977
+ if (signature === null) {
4978
+ this.seen.delete(key);
4979
+ return { unchanged: false, signature };
4980
+ }
4981
+ if (this.seen.get(key) === signature) return { unchanged: true, signature };
4982
+ return { unchanged: false, signature };
4983
+ }
4984
+ /** Remember a signature only after its capture succeeded, so failures stay eligible. */
4985
+ confirmUnchanged(key, signature) {
4986
+ if (signature === null) return;
4987
+ this.seen.set(key, signature);
4988
+ }
4989
+ };
4990
+ async function statIdleGatePath(path) {
4991
+ const direct = await statObservedPathSignature(path);
4992
+ if (direct !== null) return direct;
4993
+ try {
4994
+ await lstat5(path);
4995
+ return null;
4996
+ } catch (error) {
4997
+ const code = transcriptErrorCode(error);
4998
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
4999
+ return await missingPathAnchor(path);
5000
+ }
5001
+ }
5002
+ async function missingPathAnchor(path) {
5003
+ let ancestor = dirname6(path);
5004
+ for (let depth = 0; depth < 4; depth += 1) {
5005
+ if (ancestor === dirname6(ancestor)) return null;
5006
+ const anchor = await statObservedPathSignature(ancestor);
5007
+ if (anchor !== null) return `missing:${anchor}`;
5008
+ ancestor = dirname6(ancestor);
5009
+ }
5010
+ return null;
5011
+ }
4832
5012
  async function openHostUsageTranscriptCursor(input) {
4833
5013
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants5.O_RDONLY));
4834
5014
  let source;
@@ -4897,15 +5077,12 @@ function completeLinePrefix(bytes, baseOffset) {
4897
5077
  return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
4898
5078
  }
4899
5079
 
4900
- // host/relay/src/relay-quarantine-store.ts
4901
- var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
4902
- var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
4903
- var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
4904
-
4905
5080
  // host/relay/src/relay-admission-store.ts
4906
- var DEFAULT_LIMITS = { global_count: 8192, global_bytes: 64 * 1024 * 1024, producer_count: 4096, producer_bytes: 32 * 1024 * 1024 };
4907
- var RETRY_SECONDS = [1, 2, 4, 8, 16, 32, 60];
4908
- var MAX_RETRYABLE_ATTEMPTS = RETRY_SECONDS.length + 10;
5081
+ 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"]);
5082
+
5083
+ // host/relay/src/host-relay-config.ts
5084
+ var HOST_RELAY_CONFIG_MIN_BYTES = Buffer.byteLength("{}", "utf8");
5085
+ 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");
4909
5086
 
4910
5087
  // host/relay/src/relay-pipe-handshake.ts
4911
5088
  var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
@@ -4980,15 +5157,16 @@ var CodexOutboxStore = class {
4980
5157
  turnSelectionsDirectory;
4981
5158
  registrationsDirectory;
4982
5159
  cursorsDirectory;
5160
+ registrationInventory = new HostRegistrationInventory();
4983
5161
  constructor(directory) {
4984
5162
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
4985
5163
  this.directory = directory;
4986
- this.entriesDirectory = join5(directory, "entries");
4987
- this.sessionsDirectory = join5(directory, "sessions");
4988
- this.activeContextsDirectory = join5(directory, "active-contexts");
4989
- this.turnSelectionsDirectory = join5(directory, "turn-selections");
4990
- this.registrationsDirectory = join5(directory, "transcript-registrations");
4991
- this.cursorsDirectory = join5(directory, "transcript-cursors");
5164
+ this.entriesDirectory = join4(directory, "entries");
5165
+ this.sessionsDirectory = join4(directory, "sessions");
5166
+ this.activeContextsDirectory = join4(directory, "active-contexts");
5167
+ this.turnSelectionsDirectory = join4(directory, "turn-selections");
5168
+ this.registrationsDirectory = join4(directory, "transcript-registrations");
5169
+ this.cursorsDirectory = join4(directory, "transcript-cursors");
4992
5170
  }
4993
5171
  async prepare() {
4994
5172
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -5006,7 +5184,7 @@ var CodexOutboxStore = class {
5006
5184
  for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
5007
5185
  if (!name.endsWith(".json")) continue;
5008
5186
  try {
5009
- const value = JSON.parse(await readOwnerStateFile(join5(this.entriesDirectory, name)));
5187
+ const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
5010
5188
  validateEnvelope(value);
5011
5189
  entries.push(value);
5012
5190
  } catch {
@@ -5131,22 +5309,33 @@ var CodexOutboxStore = class {
5131
5309
  return registration;
5132
5310
  }
5133
5311
  async listTranscriptRegistrations() {
5134
- const registrations = [];
5135
- for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
5136
- if (!name.endsWith(".json")) continue;
5137
- try {
5138
- const value = JSON.parse(await readOwnerStateFile(join5(this.registrationsDirectory, name)));
5139
- validateRegistration(value);
5140
- registrations.push(value);
5141
- } catch {
5312
+ return this.registrationInventory.read(this.registrationsDirectory, async () => {
5313
+ const registrations = [];
5314
+ for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
5315
+ if (!name.endsWith(".json")) continue;
5316
+ try {
5317
+ const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
5318
+ validateRegistration(value);
5319
+ registrations.push(value);
5320
+ } catch {
5321
+ }
5142
5322
  }
5143
- }
5144
- return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
5323
+ return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
5324
+ });
5145
5325
  }
5146
5326
  async readTranscriptCursor(registration) {
5147
5327
  validateRegistration(registration);
5148
5328
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
5149
5329
  }
5330
+ async transcriptCursorFingerprint(registration) {
5331
+ validateRegistration(registration);
5332
+ try {
5333
+ const info = await stat3(this.cursorPath(registration.host_source_ref, registration.host_session_ref), { bigint: true });
5334
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
5335
+ } catch {
5336
+ return "missing";
5337
+ }
5338
+ }
5150
5339
  async writeTranscriptCursor(cursor) {
5151
5340
  validateCursor(cursor);
5152
5341
  await this.prepare();
@@ -5167,22 +5356,22 @@ var CodexOutboxStore = class {
5167
5356
  }
5168
5357
  entryPath(submissionRef) {
5169
5358
  if (!SAFE_REF3.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
5170
- return join5(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
5359
+ return join4(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
5171
5360
  }
5172
5361
  sessionPath(sourceRef, sessionRef) {
5173
- return join5(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
5362
+ return join4(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
5174
5363
  }
5175
5364
  activeContextPath(identity) {
5176
- return join5(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
5365
+ return join4(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
5177
5366
  }
5178
5367
  turnSelectionPath(sourceRef, sessionRef) {
5179
- return join5(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
5368
+ return join4(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
5180
5369
  }
5181
5370
  registrationPath(sourceRef, sessionRef) {
5182
- return join5(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
5371
+ return join4(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
5183
5372
  }
5184
5373
  cursorPath(sourceRef, sessionRef) {
5185
- return join5(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
5374
+ return join4(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
5186
5375
  }
5187
5376
  };
5188
5377
  async function removeOwnerState(path, what) {
@@ -5226,7 +5415,7 @@ async function writeAtomicJson(path, value) {
5226
5415
  await handle.close();
5227
5416
  }
5228
5417
  await rename2(temp, path);
5229
- await syncDirectory2(dirname6(path));
5418
+ await syncDirectory2(dirname7(path));
5230
5419
  } catch (error) {
5231
5420
  try {
5232
5421
  await unlink3(temp);
@@ -5261,14 +5450,14 @@ async function readOptionalJson2(path, validate) {
5261
5450
  async function ensureOwnerDirectory(path) {
5262
5451
  try {
5263
5452
  try {
5264
- const stats2 = await stat2(path);
5453
+ const stats2 = await stat3(path);
5265
5454
  if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
5266
5455
  return;
5267
5456
  } catch (error) {
5268
5457
  if (!isNotFound2(error)) throw error;
5269
5458
  }
5270
5459
  await mkdir4(path, { recursive: true, mode: 448 });
5271
- const stats = await stat2(path);
5460
+ const stats = await stat3(path);
5272
5461
  if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
5273
5462
  } catch (error) {
5274
5463
  if (error instanceof CodexHostAdapterError) throw error;
@@ -5316,7 +5505,7 @@ function validateRegistrationFields(value) {
5316
5505
  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 }])}).`);
5317
5506
  }
5318
5507
  function validRegistrationCwd(value) {
5319
- return value === void 0 || typeof value === "string" && isAbsolute3(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
5508
+ return value === void 0 || typeof value === "string" && isAbsolute2(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
5320
5509
  }
5321
5510
  function validateCursor(value) {
5322
5511
  if (!isRecord6(value)) throw storageError("Codex transcript cursor is malformed.");
@@ -5598,32 +5787,51 @@ function decodeTokenUsage(value) {
5598
5787
  }
5599
5788
  function decodeResponseItem(payload, ordinal, timestamp3) {
5600
5789
  if (payload.type !== "message" || payload.role !== "user") return { kind: "ignored", ordinal, timestamp: timestamp3 };
5601
- const metadata = userMessageMetadata(payload.internal_chat_message_metadata_passthrough);
5602
- const contentItemKind = userTextContentKind(metadata.content_item_kinds);
5603
- if (contentItemKind === void 0) return { kind: "ignored", ordinal, timestamp: timestamp3 };
5604
- const prompt = userTextContent(payload.content);
5790
+ const attribution = userMessageAttribution(payload.internal_chat_message_metadata_passthrough);
5791
+ if (attribution === null) return { kind: "ignored", ordinal, timestamp: timestamp3 };
5792
+ const prompt = userTextContent(payload.content, attribution.content_item_kinds);
5793
+ if (prompt === null) return { kind: "ignored", ordinal, timestamp: timestamp3 };
5605
5794
  return {
5606
5795
  kind: "user_text",
5607
5796
  ordinal,
5608
5797
  timestamp: timestamp3,
5609
- prompt,
5610
- content_item_kind: contentItemKind,
5798
+ prompt: prompt.text,
5799
+ content_item_kind: prompt.kind,
5611
5800
  message_id: safeRef3(payload.id, "Codex user message identity is invalid."),
5612
- turn_id: safeRef3(metadata.turn_id, "Codex user message task identity is invalid.")
5801
+ turn_id: safeRef3(attribution.turn_id, "Codex user message task identity is invalid.")
5613
5802
  };
5614
5803
  }
5615
- function userTextContentKind(kinds) {
5616
- return kinds.length === 1 && (kinds[0] === "user.text" || kinds[0] === "goal.internal_context") ? kinds[0] : void 0;
5804
+ function userMessageAttribution(value) {
5805
+ if (!isRecord7(value)) return null;
5806
+ if (typeof value.turn_id !== "string" || !SAFE_REF5.test(value.turn_id)) return null;
5807
+ return { turn_id: value.turn_id, content_item_kinds: Array.isArray(value.content_item_kinds) ? value.content_item_kinds : void 0 };
5617
5808
  }
5618
- function userMessageMetadata(value) {
5619
- if (!isRecord7(value) || !Array.isArray(value.content_item_kinds)) reject("Codex user message provenance is malformed.");
5620
- return { ...value, content_item_kinds: value.content_item_kinds };
5621
- }
5622
- function userTextContent(value) {
5809
+ function userTextContent(value, kinds) {
5623
5810
  if (!Array.isArray(value)) reject(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
5624
- if (value.length !== 1) reject(`Codex user text content is malformed (${refusalFact("items", value.length, "exactly one")}).`);
5625
- if (!isRecord7(value[0]) || value[0].type !== "input_text") reject(`Codex user text content is malformed (${refusalFact("item_type", isRecord7(value[0]) ? value[0].type : typeof value[0], "input_text")}).`);
5626
- return boundedText2(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
5811
+ if (kinds === void 0) {
5812
+ if (value.length !== 1) return null;
5813
+ return { text: userTextEntry(value[0]), kind: "user.text" };
5814
+ }
5815
+ if (kinds.length !== value.length) return null;
5816
+ const match = singleAlignedTextKind(kinds);
5817
+ if (match === null) return null;
5818
+ if (kinds.length === 1) return { text: userTextEntry(value[match.index]), kind: match.kind };
5819
+ if (!isRecord7(value[match.index]) || value[match.index].type !== "input_text") return null;
5820
+ return { text: boundedText2(value[match.index].text, MAX_PROMPT_BYTES, "Codex user text is invalid."), kind: match.kind };
5821
+ }
5822
+ function singleAlignedTextKind(kinds) {
5823
+ let match = null;
5824
+ for (let index = 0; index < kinds.length; index += 1) {
5825
+ const kind = kinds[index];
5826
+ if (kind !== "user.text" && kind !== "goal.internal_context") continue;
5827
+ if (match !== null) return null;
5828
+ match = { index, kind };
5829
+ }
5830
+ return match;
5831
+ }
5832
+ function userTextEntry(value) {
5833
+ if (!isRecord7(value) || value.type !== "input_text") reject(`Codex user text content is malformed (${refusalFact("item_type", isRecord7(value) ? value.type : typeof value, "input_text")}).`);
5834
+ return boundedText2(value.text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
5627
5835
  }
5628
5836
  function safeOrdinal(value) {
5629
5837
  if (!Number.isSafeInteger(value) || Number(value) < 0) reject("Codex transcript ordinal is invalid.");
@@ -5730,9 +5938,16 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
5730
5938
  transcriptPathOf(registration) {
5731
5939
  return registration.transcript_path;
5732
5940
  }
5941
+ registrationKey(registration) {
5942
+ return `${registration.host_source_ref}\0${registration.host_session_ref}`;
5943
+ }
5733
5944
  async listRegistrations() {
5734
5945
  return this.store.listTranscriptRegistrations();
5735
5946
  }
5947
+ async scanFingerprint(registration) {
5948
+ const transcript = await super.scanFingerprint(registration);
5949
+ return transcript === null ? null : `${transcript}|${await this.store.transcriptCursorFingerprint(registration)}`;
5950
+ }
5736
5951
  async scanOpened(handle, registration) {
5737
5952
  const { size, device, inode } = await ownedCodexTranscriptFile(handle);
5738
5953
  const preflight = await this.preflight(registration, handle, size, device, inode);
@@ -5742,7 +5957,7 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
5742
5957
  if (complete === "empty" || complete === "partial") {
5743
5958
  return { records: 0, enqueued: 0, quarantined: false };
5744
5959
  }
5745
- return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
5960
+ return { ...await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode), retry: preflight.cursor.offset + complete.length < size };
5746
5961
  }
5747
5962
  async scanFailed(handle, registration, error) {
5748
5963
  this.diagnostic("watcher_scan_failed", codexTranscriptScanFailureKind(error));
@@ -6061,11 +6276,14 @@ function assertRecordSequence(registration, cursor, records, lastOrdinal, record
6061
6276
  }
6062
6277
 
6063
6278
  // host/codex/src/codex-producer-runtime.ts
6064
- async function drainCodexProducerOnce(options) {
6065
- const scan = await new CodexTranscriptWatcher({
6066
- outbox_dir: options.outbox_dir,
6279
+ function createCodexProducerWatcher(outboxDir) {
6280
+ return new CodexTranscriptWatcher({
6281
+ outbox_dir: outboxDir,
6067
6282
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
6068
- }).scanOnce().catch((error) => {
6283
+ });
6284
+ }
6285
+ async function drainCodexProducerOnce(options, signal) {
6286
+ const scan = await (options.watcher ?? createCodexProducerWatcher(options.outbox_dir)).scanOnce(signal).catch((error) => {
6069
6287
  writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
6070
6288
  throw error;
6071
6289
  });
@@ -6080,17 +6298,34 @@ var CodexUsageFactsCapturer = class {
6080
6298
  usage;
6081
6299
  now;
6082
6300
  registrations;
6301
+ idleGate;
6083
6302
  constructor(options) {
6084
6303
  this.sources = new CodexOutboxStore(options.outbox_dir);
6085
6304
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
6086
6305
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
6087
6306
  this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
6307
+ this.idleGate = new HostUsageIdleGate();
6088
6308
  }
6089
6309
  async captureNext() {
6090
6310
  const registrations = await this.sources.listTranscriptRegistrations();
6091
6311
  return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
6092
6312
  }
6093
6313
  async captureRegistration(registration) {
6314
+ const idleKey = `${registration.host_source_ref}\0${registration.host_session_ref}`;
6315
+ const transcriptKey = `${idleKey}\0transcript`;
6316
+ const stateKey = `${idleKey}\0state`;
6317
+ const transcriptCheck = await this.idleGate.checkUnchanged(transcriptKey, registration.transcript_path);
6318
+ let stateCheck;
6319
+ if (transcriptCheck.unchanged) {
6320
+ stateCheck = await this.idleGate.checkUnchanged(stateKey, this.usage.statePath("codex", registration.host_source_ref, registration.host_session_ref));
6321
+ if (stateCheck.unchanged) return false;
6322
+ }
6323
+ const captured = await this.scanRegistration(registration);
6324
+ this.idleGate.confirmUnchanged(transcriptKey, transcriptCheck.signature);
6325
+ if (stateCheck !== void 0) this.idleGate.confirmUnchanged(stateKey, stateCheck.signature);
6326
+ return captured;
6327
+ }
6328
+ async scanRegistration(registration) {
6094
6329
  const prepared = await openHostUsageTranscriptCursor({
6095
6330
  path: registration.transcript_path,
6096
6331
  producer: "codex",
@@ -6307,7 +6542,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
6307
6542
  producer_id: "codex",
6308
6543
  extra_paths: [CODEX_SESSIONS_ROOT],
6309
6544
  config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
6310
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6545
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createCodexProducerWatcher(config.outbox_dir) }),
6311
6546
  drain: drainCodexProducerOnce,
6312
6547
  background: (config, signal, dependencies) => {
6313
6548
  const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });