@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.
@@ -2463,7 +2463,7 @@ var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
2463
2463
  var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
2464
2464
  var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
2465
2465
  var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
2466
- var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
2466
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "race_recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
2467
2467
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
2468
2468
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
2469
2469
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -2861,6 +2861,7 @@ function requireIsoTimestamp(value, message) {
2861
2861
  // packages/ceal-client-protocol/src/failure-guidance-table.ts
2862
2862
  var CEAL_FAILURE_REDACTION_CLASSES = vocabulary(["model_safe", "withheld"]);
2863
2863
  var CEAL_GATEWAY_STARTING_FAILURE_CODE = "gateway_starting";
2864
+ var CEAL_GATEWAY_RESTARTING_FAILURE_CODE = "gateway_restarting";
2864
2865
  var CEAL_OWNER_BOOTSTRAP_ABSENT_FAILURE_CODE = "bootstrap_absent";
2865
2866
  var CEAL_OWNER_BOOTSTRAP_UNAVAILABLE_FAILURE_CODE = "bootstrap_unavailable";
2866
2867
  var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
@@ -2871,6 +2872,7 @@ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
2871
2872
  var CLIENT_HOST_RELEASE_MISMATCH = `Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry. Update with \`${CEAL_CLIENT_UPGRADE_COMMAND}\`.`;
2872
2873
  var HOST_INSTALL_REPAIR = "The local Host or Relay is missing, stale, or unavailable. Run `ceal-host install`, then `ceal-host discovery sync`, and retry from a new producer conversation.";
2873
2874
  var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn right now; the Host may be restarting. Wait briefly and retry the same command. If you know you are in an ephemeral side conversation, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions without Host session/turn correlation. Otherwise return to the original regular conversation. Host refusal never switches modes. If the retry still fails, report intended Host calls as a gap.";
2875
+ var HOST_TRANSCRIPT_UNAVAILABLE = "The Host found no human message in the registered transcript for this turn, so this call has nothing to bind to. Send a new message in the current conversation so the Host re-registers the transcript, then retry the same command. If it still fails, start a new conversation and report intended Host calls as a gap. Host refusal never switches modes.";
2874
2876
  var HOST_RELAY_RESTARTING = "The Host Relay is temporarily unavailable while the Host restarts; wait briefly and retry the same command. If the retry still fails, report this as a gap.";
2875
2877
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
2876
2878
  var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
@@ -2925,6 +2927,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2925
2927
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
2926
2928
  // The serving gate answers before refresh execution, so retrying the same attempt is safe.
2927
2929
  [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance("The Gateway is still starting; the refresh was not attempted and the refresh token was not consumed. Retry the same refresh attempt after the Gateway is serving.", "retry", 503, true),
2930
+ // The serving gate answers before execution while the Gateway is stopping, so retrying the same request is safe.
2931
+ [CEAL_GATEWAY_RESTARTING_FAILURE_CODE]: guidance("The Gateway is restarting; the request was not attempted. Retry the same request after the Gateway is serving.", "retry", 503, true),
2928
2932
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
2929
2933
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
2930
2934
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -3032,6 +3036,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
3032
3036
  host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
3033
3037
  host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
3034
3038
  host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
3039
+ host_transcript_unavailable: guidance(HOST_TRANSCRIPT_UNAVAILABLE, "retry", 401, true),
3035
3040
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
3036
3041
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
3037
3042
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
@@ -3420,6 +3425,8 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
3420
3425
  });
3421
3426
 
3422
3427
  // packages/ceal-client-protocol/src/canonical-http-boundary.ts
3428
+ var CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE = "^client-exchange:[a-f0-9]{32}$";
3429
+ var CEAL_HTTP_GATEWAY_REQUEST_REF_PATTERN_SOURCE = "^http-request:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
3423
3430
  var CEAL_CANONICAL_HTTP_MAX_RESPONSE_BYTES = CEAL_COMMAND_RESPONSE_MAX_BYTES;
3424
3431
 
3425
3432
  // packages/ceal-client-protocol/src/gateway-installation-activation.ts
@@ -3444,6 +3451,7 @@ var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUI
3444
3451
  var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
3445
3452
 
3446
3453
  // packages/ceal-client-protocol/src/resource-read-result.ts
3454
+ var CEAL_RESOURCE_GET_CHILD_REF_KINDS = Object.freeze(["section", "slide", "question"]);
3447
3455
  var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
3448
3456
  var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
3449
3457
  var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
@@ -3647,6 +3655,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3647
3655
  "github.review.submitted",
3648
3656
  "github.issue_comment.created",
3649
3657
  "github.review_comment.created",
3658
+ "github.issue_comment.edited",
3659
+ "github.review_comment.edited",
3650
3660
  "github.reaction.created",
3651
3661
  "github.reaction.deleted",
3652
3662
  "github.pull_request.review_requested",
@@ -3675,6 +3685,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3675
3685
  "github.release.published": "release_published",
3676
3686
  "github.issue.edited": "resource_modified",
3677
3687
  "github.pull_request.edited": "resource_modified",
3688
+ "github.issue_comment.edited": "resource_modified",
3689
+ "github.review_comment.edited": "resource_modified",
3678
3690
  "github.reaction.created": "reaction_created",
3679
3691
  "github.reaction.deleted": "ceal_write_completed",
3680
3692
  "github.pull_request.review_requested": "ceal_write_completed",
@@ -4337,6 +4349,8 @@ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
4337
4349
  var HOST_CONTEXT_EXPIRY_MAX_CHARS = 64;
4338
4350
  var CEAL_HOST_INVOCATION_CONTEXT_VISIBLE_OUTPUT_MAX_BYTES = CEAL_CANONICAL_HTTP_MAX_RESPONSE_BYTES;
4339
4351
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
4352
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_ENTRY_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text", "text_truncated"]);
4353
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_REQUIRED_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text"]);
4340
4354
  function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
4341
4355
  const messages = [];
4342
4356
  let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
@@ -4468,6 +4482,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
4468
4482
  "context_replaced",
4469
4483
  "no_binding",
4470
4484
  "context_expired",
4485
+ "transcript_unavailable",
4471
4486
  "host_source_refused",
4472
4487
  "host_credential_refused",
4473
4488
  "gateway_unavailable",
@@ -4509,6 +4524,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
4509
4524
  // useful retry until the consumer is running inside a Host session.
4510
4525
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
4511
4526
  context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
4527
+ // The registered transcript is readable but names no human message for
4528
+ // this turn, so a Gateway mint could only be refused. The caller sends a
4529
+ // new message so the turn hook re-registers the transcript, then retries;
4530
+ // a retry with no new turn cannot bind anything new.
4531
+ transcript_unavailable: Object.freeze({ classification: "host_transcript_unavailable", next_action: "retry" }),
4512
4532
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
4513
4533
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
4514
4534
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
@@ -4645,11 +4665,15 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
4645
4665
 
4646
4666
  // packages/ceal-client-protocol/src/operator-diagnostic.ts
4647
4667
  var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
4648
- var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
4668
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES = 8;
4649
4669
  var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
4650
4670
  var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
4651
4671
  var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
4652
4672
  var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
4673
+ var LOCAL_OPERATOR_DIAGNOSTIC_PATHS = /* @__PURE__ */ Symbol.for("ceal.local-operator-diagnostic-paths");
4674
+ var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX = /(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)/u;
4675
+ var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START = new RegExp(`^${OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX.source}`, "u");
4676
+ var OPERATOR_DIAGNOSTIC_FREEFORM_PATH_PATTERN = new RegExp(String.raw`(?<![A-Za-z0-9._-]|\[home path redacted\])${OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX.source}((?:(?!; stdout=|; stderr=)[^:\r\n"'<>])*?)( exited \d+)?(?=; stdout=|; stderr=|:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])`, "gu");
4653
4677
  function redactOperatorDiagnosticSecrets(value) {
4654
4678
  return value.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer [redacted]").replace(/(["']?(?:authorization|[A-Za-z0-9_-]*(?:token|secret|credential|password|key))["']?\s*[:=]\s*)(?!(?:"unknown"|'unknown'|unknown\b))(?:"[^"]*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
4655
4679
  }
@@ -4658,8 +4682,9 @@ function redactOperatorDiagnosticText(value) {
4658
4682
  return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
4659
4683
  }
4660
4684
  function renderOperatorDiagnostic(value) {
4661
- const state = collectDiagnosticState(value);
4685
+ const state = collectDiagnosticState(value, read(value, LOCAL_OPERATOR_DIAGNOSTIC_PATHS) === true);
4662
4686
  const fields = [
4687
+ state.truncated ? "causes_truncated=true" : void 0,
4663
4688
  state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
4664
4689
  state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
4665
4690
  state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
@@ -4669,23 +4694,27 @@ function renderOperatorDiagnostic(value) {
4669
4694
  const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
4670
4695
  return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
4671
4696
  }
4672
- function collectDiagnosticState(value) {
4673
- const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
4697
+ function collectDiagnosticState(value, preserveLocalAbsolutePaths) {
4698
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0, truncated: false };
4674
4699
  const visited = /* @__PURE__ */ new Set(), pending = [value];
4675
- while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
4700
+ let inspected = 0;
4701
+ while (pending.length > 0 && inspected < OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES) {
4676
4702
  const current = pending.shift();
4677
- if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
4703
+ if (current === void 0 || isObject(current) && visited.has(current)) continue;
4704
+ inspected += 1;
4705
+ visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths);
4678
4706
  }
4707
+ state.truncated ||= pending.length > 0;
4679
4708
  return state;
4680
4709
  }
4681
- function visitDiagnosticNode(current, state, pending, visited) {
4710
+ function visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths) {
4682
4711
  if (isObject(current)) {
4683
4712
  if (visited.has(current)) return;
4684
4713
  visited.add(current);
4685
4714
  }
4686
4715
  captureProcessEvidence(current, state);
4687
- appendCause(current, state.causes);
4688
- enqueueCauseChildren(current, state.causes.length, pending);
4716
+ appendCause(current, state.causes, preserveLocalAbsolutePaths);
4717
+ enqueueCauseChildren(current, state, pending);
4689
4718
  }
4690
4719
  function captureProcessEvidence(current, state) {
4691
4720
  if (state.status === void 0) state.status = safeStatus(read(current, "status"));
@@ -4693,10 +4722,9 @@ function captureProcessEvidence(current, state) {
4693
4722
  if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
4694
4723
  if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
4695
4724
  }
4696
- function appendCause(current, causes) {
4697
- const errors = read(current, "errors");
4698
- if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
4699
- causes.push(errorCause(current));
4725
+ function appendCause(current, causes, preserveLocalAbsolutePaths) {
4726
+ if (current instanceof Error) {
4727
+ causes.push(errorCause(current, preserveLocalAbsolutePaths));
4700
4728
  return;
4701
4729
  }
4702
4730
  if (!isObject(current)) {
@@ -4704,7 +4732,7 @@ function appendCause(current, causes) {
4704
4732
  if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
4705
4733
  }
4706
4734
  }
4707
- function errorCause(error) {
4735
+ function errorCause(error, preserveLocalAbsolutePaths) {
4708
4736
  const name = safeText(read(error, "name")) ?? "Error";
4709
4737
  const message = safeText(read(error, "message"));
4710
4738
  const codeValue = read(error, "code");
@@ -4712,14 +4740,29 @@ function errorCause(error) {
4712
4740
  const errnoValue = read(error, "errno");
4713
4741
  const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
4714
4742
  const syscall = safeText(read(error, "syscall"));
4715
- const path = safePath(read(error, "path"));
4743
+ const path = safePath(read(error, "path"), preserveLocalAbsolutePaths);
4716
4744
  return Object.freeze({ error_class: name, ...message === void 0 ? {} : { message }, ...code === void 0 ? {} : { code }, ...errno === void 0 ? {} : { errno }, ...syscall === void 0 ? {} : { syscall }, ...path === void 0 ? {} : { path } });
4717
4745
  }
4718
- function enqueueCauseChildren(current, causeCount, pending) {
4746
+ function enqueueCauseChildren(current, state, pending) {
4719
4747
  const cause = read(current, "cause");
4720
4748
  if (cause !== void 0) pending.push(cause);
4721
4749
  const errors = read(current, "errors");
4722
- if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
4750
+ if (Array.isArray(errors)) {
4751
+ const remaining = OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES - state.causes.length;
4752
+ const length = read(errors, "length");
4753
+ if (typeof length !== "number") {
4754
+ state.truncated = true;
4755
+ return;
4756
+ }
4757
+ state.truncated ||= length > remaining;
4758
+ for (let index = 0; index < Math.min(length, remaining); index += 1) {
4759
+ try {
4760
+ pending.push(errors[index]);
4761
+ } catch {
4762
+ state.truncated = true;
4763
+ }
4764
+ }
4765
+ }
4723
4766
  }
4724
4767
  function isObject(value) {
4725
4768
  return typeof value === "object" && value !== null;
@@ -4748,10 +4791,11 @@ function safeText(value) {
4748
4791
  const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
4749
4792
  return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4750
4793
  }
4751
- function safePath(value) {
4794
+ function safePath(value, preserveLocalAbsolutePaths) {
4752
4795
  if (typeof value !== "string") return void 0;
4753
4796
  const safe = safeDiagnosticText(value);
4754
4797
  if (safe.length === 0) return void 0;
4798
+ if (!preserveLocalAbsolutePaths && hasAbsolutePathPrefix(value) && !safe.startsWith("[home path redacted]")) return "[path redacted]";
4755
4799
  if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
4756
4800
  const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
4757
4801
  const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
@@ -4823,7 +4867,10 @@ function redactUrls(value) {
4823
4867
  return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
4824
4868
  }
4825
4869
  function redactFilePaths(value) {
4826
- return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
4870
+ return value.replaceAll(OPERATOR_DIAGNOSTIC_FREEFORM_PATH_PATTERN, "[path redacted]$2");
4871
+ }
4872
+ function hasAbsolutePathPrefix(value) {
4873
+ return OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START.test(value);
4827
4874
  }
4828
4875
  function homePathRange(value, match, prefixLength) {
4829
4876
  const index = match.index;
@@ -5002,10 +5049,9 @@ function hostClientProbeRefusal(probe, subject) {
5002
5049
  }
5003
5050
 
5004
5051
  // host/client-doctor.ts
5005
- import { createHash as createHash4 } from "node:crypto";
5006
- import { execFile } from "node:child_process";
5007
- import { access, open, readFile, realpath, stat } from "node:fs/promises";
5008
- import { delimiter, extname, isAbsolute as isAbsolute2, join as join3 } from "node:path";
5052
+ import { execFile as execFile2 } from "node:child_process";
5053
+ import { access, open as open2, realpath, stat } from "node:fs/promises";
5054
+ import { delimiter, extname, isAbsolute as isAbsolute2, join as join4 } from "node:path";
5009
5055
  import { promisify } from "node:util";
5010
5056
 
5011
5057
  // host/environment.ts
@@ -5024,7 +5070,7 @@ var WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET = "A-Za-z0-9._=-";
5024
5070
  var WINDOWS_FIXED_CMD_ARGUMENT_REFUSAL_PATTERN = `[^${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]`;
5025
5071
  var WINDOWS_FIXED_CMD_ARGUMENT = new RegExp(`^[${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]+$`, "u");
5026
5072
  function validateHostCommandVector(vector, windowsConsumer = "cmd") {
5027
- if (typeof vector.executable !== "string" || invalidText(vector.executable)) throw new TypeError(`Host command vector executable is invalid (${refusalFact("executable_kind", typeof vector.executable, "non-empty text without a NUL, newline or control character")}).`);
5073
+ if (typeof vector.executable !== "string" || vector.executable === "" || invalidText(vector.executable)) throw new TypeError(`Host command vector executable is invalid (${refusalFact("executable_kind", typeof vector.executable, "non-empty text without a NUL, newline or control character")}).`);
5028
5074
  if (vector.args.length > HOST_COMMAND_ARGUMENT_MAX) throw new TypeError(`Host command vector has too many arguments (${refusalFact("argument_count", vector.args.length, `at most ${HOST_COMMAND_ARGUMENT_MAX}`)}).`);
5029
5075
  const offending = vector.args.findIndex((argument) => typeof argument !== "string" || invalidText(argument));
5030
5076
  if (offending >= 0) throw new TypeError(`Host command vector argument is invalid (${refusalFact("argument_index", offending, "no argument with a NUL, newline or control character")}).`);
@@ -5087,66 +5133,317 @@ function quoteWindowsExecArgument(value) {
5087
5133
  return `"${escaped}"`;
5088
5134
  }
5089
5135
 
5136
+ // host/lifecycle/src/host-bundle-manifest.ts
5137
+ import { createHash as createHash4 } from "node:crypto";
5138
+
5139
+ // host/secure-file.ts
5140
+ import { execFile } from "node:child_process";
5141
+ import { constants } from "node:fs";
5142
+ import { lstat, open } from "node:fs/promises";
5143
+ import { dirname, join as join2, parse, win32 as win322 } from "node:path";
5144
+ import { fileURLToPath } from "node:url";
5145
+ var SecureFileCustodyError = class extends Error {
5146
+ name = "SecureFileCustodyError";
5147
+ reason;
5148
+ constructor(reason, message) {
5149
+ super(message);
5150
+ this.reason = reason;
5151
+ }
5152
+ get code() {
5153
+ if (this.reason === "reparse_point") return "ELOOP";
5154
+ if (this.reason === "not_found") return "ENOENT";
5155
+ if (this.reason === "too_large") return "secure_file_too_large";
5156
+ if (this.reason === "already_exists") return "EEXIST";
5157
+ return this.reason === "not_private" ? "secure_file_not_private" : "secure_file_unavailable";
5158
+ }
5159
+ };
5160
+ var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
5161
+ var WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES = 4096;
5162
+ var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
5163
+ var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
5164
+ var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
5165
+ function secureOpenFlags(flags, platform) {
5166
+ if (platform === "win32") return flags;
5167
+ const nofollow = constants.O_NOFOLLOW;
5168
+ if (typeof nofollow === "number" && nofollow !== 0) return flags | nofollow;
5169
+ throw new Error("Secure file reads require O_NOFOLLOW on this platform.");
5170
+ }
5171
+ async function openNoFollow(path, flags = constants.O_RDONLY, mode, platform = process.platform, _custody = {}) {
5172
+ if (platform !== "win32") return await open(path, secureOpenFlags(flags, platform), mode);
5173
+ return await openWindowsIdentityScreened(path, flags, mode);
5174
+ }
5175
+ async function openWindowsIdentityScreened(path, flags, mode) {
5176
+ const handle = await open(path, flags, mode);
5177
+ try {
5178
+ const first = await handle.stat();
5179
+ if (!first.isFile()) throw new SecureFileCustodyError("not_private", "The Windows Host file is not a regular file.");
5180
+ await assertWindowsLinkFree(path, first);
5181
+ await assertWindowsIdentityStable(handle, first, path);
5182
+ return handle;
5183
+ } catch (error) {
5184
+ await handle.close();
5185
+ throw error;
5186
+ }
5187
+ }
5188
+ async function assertWindowsLinkFree(path, first) {
5189
+ const entry = await lstat(path);
5190
+ if (entry.isSymbolicLink() || entry.dev !== first.dev || entry.ino !== first.ino) {
5191
+ throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
5192
+ }
5193
+ }
5194
+ async function assertWindowsIdentityStable(handle, first, path) {
5195
+ const second = await handle.stat();
5196
+ if (second.dev !== first.dev || second.ino !== first.ino || second.size !== first.size || second.mtimeMs !== first.mtimeMs) {
5197
+ throw new SecureFileCustodyError("unavailable", "The Windows Host file changed while its identity was checked.");
5198
+ }
5199
+ const entry = await lstat(path);
5200
+ if (entry.isSymbolicLink()) throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
5201
+ if (entry.dev !== second.dev || entry.ino !== second.ino) throw new SecureFileCustodyError("unavailable", "The Windows Host file path no longer names the opened file.");
5202
+ }
5203
+ async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
5204
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
5205
+ const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
5206
+ if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
5207
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
5208
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
5209
+ throw securefsRefusal(result.stderr);
5210
+ }
5211
+ async function createRandomPrivateFileWithSecurefs(path, byteLength2, custody = {}) {
5212
+ if (!Number.isSafeInteger(byteLength2) || byteLength2 < 1 || byteLength2 > WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES) throw new TypeError(`The securefs random-file size must be between 1 and ${WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES} bytes.`);
5213
+ const result = await runSecurefsCommand(["internal", "securefs", "create-random-private-file", path, String(byteLength2)], 0, custody);
5214
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5215
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned unexpected creation bytes.");
5216
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid creation result.");
5217
+ throw securefsRefusal(result.stderr);
5218
+ }
5219
+ async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
5220
+ const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
5221
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5222
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
5223
+ throw securefsRefusal(result.stderr);
5224
+ }
5225
+ async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
5226
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > WINDOWS_SECUREFS_MAX_WRITE_BYTES || bytes.byteLength > maxBytes) throw new TypeError("The securefs write bound or payload is invalid.");
5227
+ const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
5228
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5229
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
5230
+ throw securefsRefusal(result.stderr);
5231
+ }
5232
+ async function isPrivateWindowsDirectory(path, custody = {}) {
5233
+ await lstat(path);
5234
+ try {
5235
+ const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
5236
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
5237
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
5238
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
5239
+ const refusal = securefsRefusal(result.stderr);
5240
+ if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
5241
+ throw refusal;
5242
+ } catch (error) {
5243
+ if (error instanceof SecureFileCustodyError) throw error;
5244
+ throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
5245
+ }
5246
+ }
5247
+ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
5248
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
5249
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
5250
+ const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
5251
+ return await new Promise((resolve, reject2) => {
5252
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: parse(executable).root }, (error, stdout, stderr) => {
5253
+ const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
5254
+ if (exitCode === null) {
5255
+ reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
5256
+ return;
5257
+ }
5258
+ resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
5259
+ });
5260
+ child.stdin?.on("error", () => void 0);
5261
+ child.stdin?.end(stdin);
5262
+ });
5263
+ }
5264
+ function securefsRefusal(stderr) {
5265
+ let value;
5266
+ try {
5267
+ value = JSON.parse(stderr.toString("utf8"));
5268
+ } catch {
5269
+ return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
5270
+ }
5271
+ if (!isRecord(value) || value.schema_version !== WINDOWS_SECUREFS_REFUSAL_SCHEMA || typeof value.code !== "string") return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
5272
+ if (value.code === "reparse_point") return new SecureFileCustodyError("reparse_point", "The Windows Host securefs file is a reparse point.");
5273
+ if (value.code === "not_found") return new SecureFileCustodyError("not_found", "The Windows Host securefs file was not found.");
5274
+ if (value.code === "too_large") return new SecureFileCustodyError("too_large", "The Windows Host securefs file exceeds its read bound.");
5275
+ if (value.code === "already_exists") return new SecureFileCustodyError("already_exists", "The Windows Host securefs target already exists.");
5276
+ if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
5277
+ return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
5278
+ }
5279
+ function resolveInstalledHostExecutable(platform) {
5280
+ const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
5281
+ return platform === "win32" ? win322.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
5282
+ }
5283
+ function isRecord(value) {
5284
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5285
+ }
5286
+ function isOwnedBy(uid, expectedUid) {
5287
+ return Number.isSafeInteger(uid) && Number.isSafeInteger(expectedUid) && uid === expectedUid;
5288
+ }
5289
+ function isSelfOwned(uid, platform = process.platform, _handle) {
5290
+ if (platform === "win32" || typeof process.geteuid !== "function") return false;
5291
+ return isOwnedBy(uid, process.geteuid());
5292
+ }
5293
+ function isPrivateFileMode(mode, platform = process.platform, _handle) {
5294
+ if (platform === "win32") return false;
5295
+ return (mode & 63) === 0;
5296
+ }
5297
+ async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
5298
+ if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
5299
+ const entry = await lstat(path);
5300
+ return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
5301
+ }
5302
+
5303
+ // host/lifecycle/src/host-bundle-manifest.ts
5304
+ var HOST_BUNDLE_MAX_SELECTED_BYTES = 256 * 1024 * 1024;
5305
+ var HOST_BUNDLE_MAX_SIGSTORE_BYTES = 16 * 1024 * 1024;
5306
+ var HOST_BUNDLE_TARGETS = Object.freeze(["linux-x64", "linux-arm64", "darwin-arm64", "windows-x64"]);
5307
+ var HOST_BUNDLE_COMPONENTS = Object.freeze(["lifecycle", "relay", "codex", "claude"]);
5308
+ var HOST_BUNDLE_PRODUCERS = Object.freeze(["codex", "claude"]);
5309
+ var HOST_RUNTIME_COMPONENTS = Object.freeze(["relay", "codex", "claude"]);
5310
+ var HOST_BUNDLE_PRIVATE_RUNTIME_ROOT = "libexec/ceal-host";
5311
+ var HOST_WINDOWS_BACKGROUND_RELATIVE_PATH = `${HOST_BUNDLE_PRIVATE_RUNTIME_ROOT}/ceal-host-background.exe`;
5312
+ var HOST_BUNDLE_FILE_KEYS = Object.freeze(["executable", "owners", "path", "sha256"]);
5313
+ var HOST_BUNDLE_SUPPORTED_REQUIRED_FEATURES = Object.freeze([]);
5314
+ var HOST_BUNDLE_REFERENCE_STATUS = Object.freeze({ authority: "non_authoritative", transaction: "incomplete" });
5315
+ async function digestOpenHandleSha256(handle) {
5316
+ const hash = createHash4("sha256");
5317
+ let bytes = 0;
5318
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
5319
+ bytes += chunk.length;
5320
+ hash.update(chunk);
5321
+ }
5322
+ return { sha256: hash.digest("hex"), bytes };
5323
+ }
5324
+ async function digestFileSha256(path) {
5325
+ let handle;
5326
+ try {
5327
+ handle = await openNoFollow(path);
5328
+ return await digestOpenHandleSha256(handle);
5329
+ } finally {
5330
+ await handle?.close().catch(() => void 0);
5331
+ }
5332
+ }
5333
+
5090
5334
  // host/spawn-working-directory.ts
5091
- import { mkdirSync } from "node:fs";
5335
+ import { lstatSync, mkdirSync, realpathSync } from "node:fs";
5092
5336
  import { tmpdir } from "node:os";
5093
- import { isAbsolute, join as join2, normalize, parse, sep } from "node:path";
5337
+ import { basename, dirname as dirname2, isAbsolute, join as join3, normalize, parse as parse2, sep } from "node:path";
5094
5338
  function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
5095
5339
  const candidates = [];
5096
5340
  const explicit = candidateDir(stateRoot);
5097
5341
  if (explicit !== void 0) candidates.push(explicit);
5098
5342
  const fallback = defaultHostStateRoot();
5099
5343
  if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
5100
- const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
5344
+ const temporary = candidateDir(join3(tmpdir(), "ceal-spawn-cwd"));
5101
5345
  if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
5346
+ const usable = firstKeptOutside(candidates, keepOutside);
5347
+ if (usable.directory !== void 0) return usable.directory;
5348
+ const osFallback = candidateDir(tmpdir());
5349
+ if (osFallback !== void 0 && keptOutside(osFallback, keepOutside)) return osFallback;
5350
+ throw new SpawnWorkingDirectoryRefusedError(keepOutside, usable.lastCreationError);
5351
+ }
5352
+ function firstKeptOutside(candidates, keepOutside) {
5353
+ let lastCreationError;
5102
5354
  for (const dir of candidates) {
5103
5355
  if (!keptOutside(dir, keepOutside)) continue;
5104
5356
  try {
5105
5357
  mkdirSync(dir, { recursive: true, mode: 448 });
5106
- return dir;
5107
- } catch {
5108
- continue;
5358
+ return { directory: dir };
5359
+ } catch (error) {
5360
+ lastCreationError = error;
5109
5361
  }
5110
5362
  }
5111
- return tmpdir();
5363
+ return { lastCreationError };
5112
5364
  }
5365
+ var SpawnWorkingDirectoryRefusedError = class extends Error {
5366
+ avoided;
5367
+ constructor(keepOutside, lastCreationError) {
5368
+ super(lastCreationError === void 0 ? `spawn working directory: every candidate lies inside avoided tree(s) ${JSON.stringify(keepOutside.join(", "))}; refusing a working directory that would block the activation rename` : `spawn working directory: no usable candidate; last creation error: ${lastCreationError instanceof Error ? lastCreationError.message : String(lastCreationError)}`, { cause: lastCreationError });
5369
+ this.name = "SpawnWorkingDirectoryRefusedError";
5370
+ this.avoided = [...keepOutside];
5371
+ }
5372
+ };
5113
5373
  function candidateDir(dir) {
5114
5374
  if (dir === void 0 || dir === "") return void 0;
5115
- if (!isAbsolute(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
5375
+ if (!isAbsolute(dir) || normalize(dir) !== dir || parse2(dir).root === dir) return void 0;
5116
5376
  return normalize(dir);
5117
5377
  }
5118
5378
  function defaultHostStateRoot() {
5119
5379
  if (process.platform === "win32") {
5120
5380
  const localAppData = nonEmptyEnv("LOCALAPPDATA");
5121
5381
  if (localAppData === void 0) return void 0;
5122
- return candidateDir(join2(localAppData, "Ceal", "Host"));
5382
+ return candidateDir(join3(localAppData, "Ceal", "Host"));
5123
5383
  }
5124
5384
  if (process.platform === "darwin") {
5125
5385
  const home2 = nonEmptyEnv("HOME");
5126
5386
  if (home2 === void 0) return void 0;
5127
- return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
5387
+ return candidateDir(join3(home2, "Library", "Application Support", "Ceal", "Host"));
5128
5388
  }
5129
5389
  const xdg = nonEmptyEnv("XDG_STATE_HOME");
5130
5390
  if (xdg !== void 0) {
5131
- const root = candidateDir(join2(xdg, "ceal", "host"));
5391
+ const root = candidateDir(join3(xdg, "ceal", "host"));
5132
5392
  if (root !== void 0) return root;
5133
5393
  }
5134
5394
  const home = nonEmptyEnv("HOME");
5135
5395
  if (home === void 0) return void 0;
5136
- return candidateDir(join2(home, ".local", "state", "ceal", "host"));
5396
+ return candidateDir(join3(home, ".local", "state", "ceal", "host"));
5137
5397
  }
5138
5398
  function nonEmptyEnv(name) {
5139
5399
  const value = process.env[name];
5140
5400
  return value === void 0 || value === "" ? void 0 : value;
5141
5401
  }
5142
5402
  function keptOutside(dir, keepOutside) {
5403
+ const resolvedDir = resolveExistingPrefix(dir);
5404
+ if (resolvedDir === void 0) return false;
5143
5405
  for (const tree of keepOutside) {
5144
5406
  const clean = candidateDir(tree);
5145
5407
  if (clean === void 0) continue;
5146
- if (insideDir(dir, clean)) return false;
5408
+ const resolvedTree = resolveExistingPrefix(clean);
5409
+ if (resolvedTree === void 0) return false;
5410
+ if (insideDir(resolvedDir, resolvedTree)) return false;
5147
5411
  }
5148
5412
  return true;
5149
5413
  }
5414
+ function isMissingError(error) {
5415
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
5416
+ }
5417
+ function resolveExistingPrefix(path) {
5418
+ let probe = normalize(path);
5419
+ const missing = [];
5420
+ for (; ; ) {
5421
+ let exists = false;
5422
+ try {
5423
+ lstatSync(probe);
5424
+ exists = true;
5425
+ } catch (error) {
5426
+ if (!isMissingError(error)) return void 0;
5427
+ }
5428
+ if (exists) {
5429
+ let resolved;
5430
+ try {
5431
+ resolved = realpathSync.native(probe);
5432
+ } catch {
5433
+ return void 0;
5434
+ }
5435
+ for (let index = missing.length - 1; index >= 0; index -= 1) {
5436
+ const segment = missing[index];
5437
+ if (segment !== void 0) resolved = join3(resolved, segment);
5438
+ }
5439
+ return normalize(resolved);
5440
+ }
5441
+ const parent = dirname2(probe);
5442
+ if (parent === probe) return void 0;
5443
+ missing.push(basename(probe));
5444
+ probe = parent;
5445
+ }
5446
+ }
5150
5447
  function insideDir(dir, tree) {
5151
5448
  if (sameDir(dir, tree)) return true;
5152
5449
  if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
@@ -5158,7 +5455,7 @@ function sameDir(left, right) {
5158
5455
  }
5159
5456
 
5160
5457
  // host/client-doctor.ts
5161
- var execFileAsync = promisify(execFile);
5458
+ var execFileAsync = promisify(execFile2);
5162
5459
  var GIT_OID = /^[a-f0-9]{40}$/u;
5163
5460
  var SHA2562 = /^[a-f0-9]{64}$/u;
5164
5461
  var SAFE_REF2 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
@@ -5243,7 +5540,7 @@ async function resolveCealExecutable(command, environment, platform = process.pl
5243
5540
  const launcherKind = await inspectLauncherKind(path);
5244
5541
  if (launcherKind !== void 0) return resolveLauncherBinary(path, launcherKind, environment, platform);
5245
5542
  if (platform === "win32" && !isAbsolute2(command) && extname(path) === "") continue;
5246
- return { path, sha256: createHash4("sha256").update(await readFile(path)).digest("hex") };
5543
+ return { path, sha256: (await digestFileSha256(path)).sha256 };
5247
5544
  } catch {
5248
5545
  }
5249
5546
  }
@@ -5253,7 +5550,7 @@ async function inspectLauncherKind(path) {
5253
5550
  if (/\.(?:cjs|js|mjs)$/iu.test(path)) return "node";
5254
5551
  if (/\.(?:bat|cmd)$/iu.test(path)) return "cmd";
5255
5552
  if (/\.ps1$/iu.test(path)) return "powershell";
5256
- const handle = await open(path, "r");
5553
+ const handle = await open2(path, "r");
5257
5554
  try {
5258
5555
  const buffer = Buffer.alloc(128);
5259
5556
  const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, 0);
@@ -5272,25 +5569,25 @@ async function resolveLauncherBinary(launcherPath, kind, environment, platform)
5272
5569
  } catch {
5273
5570
  throw new Error("launcher doctor returned unreadable output");
5274
5571
  }
5275
- if (!isRecord(parsed) || parsed.schema_version !== CEAL_CLIENT_DOCTOR_SCHEMA_VERSION || parsed.ok !== true || typeof parsed.binary_path !== "string" || parsed.binary_path.length === 0) throw new Error("launcher doctor did not report a binary path");
5572
+ if (!isRecord2(parsed) || parsed.schema_version !== CEAL_CLIENT_DOCTOR_SCHEMA_VERSION || parsed.ok !== true || typeof parsed.binary_path !== "string" || parsed.binary_path.length === 0) throw new Error("launcher doctor did not report a binary path");
5276
5573
  const binaryPath = await realpath(parsed.binary_path);
5277
5574
  const metadata = await stat(binaryPath);
5278
5575
  if (!metadata.isFile()) throw new Error("launcher doctor reported a non-file binary path");
5279
- return { path: binaryPath, sha256: createHash4("sha256").update(await readFile(binaryPath)).digest("hex") };
5576
+ return { path: binaryPath, sha256: (await digestFileSha256(binaryPath)).sha256 };
5280
5577
  }
5281
5578
  function executableCandidates(command, environment, platform) {
5282
5579
  if (isAbsolute2(command)) return [command];
5283
5580
  const pathValue = environmentValue(environment, "PATH", platform) ?? "";
5284
5581
  const directories = pathValue.split(delimiter).filter((entry) => entry.length > 0);
5285
- if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join3(entry, command));
5286
- return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join3(entry, `${command}${suffix}`)));
5582
+ if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join4(entry, command));
5583
+ return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join4(entry, `${command}${suffix}`)));
5287
5584
  }
5288
5585
  async function executeCealCommand(executable, args, environment) {
5289
5586
  try {
5290
5587
  const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8", cwd: resolveCealSpawnWorkingDirectory() });
5291
5588
  return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
5292
5589
  } catch (error) {
5293
- if (isRecord(error)) return { exit_code: typeof error.code === "number" ? error.code : 1, stdout: typeof error.stdout === "string" ? error.stdout : "", stderr: typeof error.stderr === "string" ? error.stderr : "" };
5590
+ if (isRecord2(error)) return { exit_code: typeof error.code === "number" ? error.code : 1, stdout: typeof error.stdout === "string" ? error.stdout : "", stderr: typeof error.stderr === "string" ? error.stderr : "" };
5294
5591
  throw error;
5295
5592
  }
5296
5593
  }
@@ -5301,19 +5598,19 @@ function commandDocument(result) {
5301
5598
  if (result === null) return null;
5302
5599
  try {
5303
5600
  const value = JSON.parse(result.stdout);
5304
- return isRecord(value) ? value : null;
5601
+ return isRecord2(value) ? value : null;
5305
5602
  } catch {
5306
5603
  return null;
5307
5604
  }
5308
5605
  }
5309
5606
  function selectedContext(value) {
5310
5607
  if (value?.schema_version !== "ceal.access-group.v1" || value.ok !== true || !Array.isArray(value.contexts)) return null;
5311
- const selected = value.contexts.filter((item) => isRecord(item) && item.selected === true);
5608
+ const selected = value.contexts.filter((item) => isRecord2(item) && item.selected === true);
5312
5609
  if (selected.length !== 1) return null;
5313
5610
  return selectedContextRecord(selected[0]);
5314
5611
  }
5315
5612
  function selectedContextRecord(item) {
5316
- if (!isRecord(item) || typeof item.name !== "string" || typeof item.instance_ref !== "string") return null;
5613
+ if (!isRecord2(item) || typeof item.name !== "string" || typeof item.instance_ref !== "string") return null;
5317
5614
  if (!SAFE_REF2.test(item.instance_ref)) return null;
5318
5615
  return { name: item.name, instance_ref: item.instance_ref };
5319
5616
  }
@@ -5328,7 +5625,7 @@ function validExpectations(options) {
5328
5625
  function failure(code, message, next_action) {
5329
5626
  return { ok: false, status: "failure", error: { code, message, next_action } };
5330
5627
  }
5331
- function isRecord(value) {
5628
+ function isRecord2(value) {
5332
5629
  return value !== null && typeof value === "object" && !Array.isArray(value);
5333
5630
  }
5334
5631
 
@@ -5340,193 +5637,21 @@ async function doctorCodexClient(options = {}) {
5340
5637
 
5341
5638
  // host/invocation-authentication-command.ts
5342
5639
  import { createHash as createHash8 } from "node:crypto";
5343
- import { performance } from "node:perf_hooks";
5640
+ import { performance as performance2 } from "node:perf_hooks";
5344
5641
 
5345
5642
  // host/relay/src/producer-frame.ts
5346
5643
  var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
5347
5644
  var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "turn_terminal", "producer_status"];
5348
5645
  var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
5349
- var HOST_PRODUCER_FRAME_ERROR_CODES = [
5350
- "invalid_frame_encoding",
5351
- "invalid_frame_length",
5352
- "frame_truncated",
5353
- "unsupported_frame_schema",
5354
- "invalid_frame_shape",
5355
- "invalid_producer_identity",
5356
- "frame_too_large"
5357
- ];
5358
5646
 
5359
5647
  // host/relay/src/host-producer-core.ts
5360
5648
  import { createHash as createHash5 } from "node:crypto";
5361
- import { readdir } from "node:fs/promises";
5362
-
5363
- // host/secure-file.ts
5364
- import { execFile as execFile2 } from "node:child_process";
5365
- import { constants } from "node:fs";
5366
- import { lstat, open as open2 } from "node:fs/promises";
5367
- import { dirname, join as join4, win32 as win322 } from "node:path";
5368
- import { fileURLToPath } from "node:url";
5369
- var SecureFileCustodyError = class extends Error {
5370
- name = "SecureFileCustodyError";
5371
- reason;
5372
- constructor(reason, message) {
5373
- super(message);
5374
- this.reason = reason;
5375
- }
5376
- get code() {
5377
- if (this.reason === "reparse_point") return "ELOOP";
5378
- if (this.reason === "not_found") return "ENOENT";
5379
- if (this.reason === "too_large") return "secure_file_too_large";
5380
- if (this.reason === "already_exists") return "EEXIST";
5381
- return this.reason === "not_private" ? "secure_file_not_private" : "secure_file_unavailable";
5382
- }
5383
- };
5384
- var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
5385
- var WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES = 4096;
5386
- var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
5387
- var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
5388
- var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
5389
- function secureOpenFlags(flags, platform) {
5390
- if (platform === "win32") return flags;
5391
- const nofollow = constants.O_NOFOLLOW;
5392
- if (typeof nofollow === "number" && nofollow !== 0) return flags | nofollow;
5393
- throw new Error("Secure file reads require O_NOFOLLOW on this platform.");
5394
- }
5395
- async function openNoFollow(path, flags = constants.O_RDONLY, mode, platform = process.platform, _custody = {}) {
5396
- if (platform !== "win32") return await open2(path, secureOpenFlags(flags, platform), mode);
5397
- return await openWindowsIdentityScreened(path, flags, mode);
5398
- }
5399
- async function openWindowsIdentityScreened(path, flags, mode) {
5400
- const handle = await open2(path, flags, mode);
5401
- try {
5402
- const first = await handle.stat();
5403
- if (!first.isFile()) throw new SecureFileCustodyError("not_private", "The Windows Host file is not a regular file.");
5404
- await assertWindowsLinkFree(path, first);
5405
- await assertWindowsIdentityStable(handle, first, path);
5406
- return handle;
5407
- } catch (error) {
5408
- await handle.close();
5409
- throw error;
5410
- }
5411
- }
5412
- async function assertWindowsLinkFree(path, first) {
5413
- const entry = await lstat(path);
5414
- if (entry.isSymbolicLink() || entry.dev !== first.dev || entry.ino !== first.ino) {
5415
- throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
5416
- }
5417
- }
5418
- async function assertWindowsIdentityStable(handle, first, path) {
5419
- const second = await handle.stat();
5420
- if (second.dev !== first.dev || second.ino !== first.ino || second.size !== first.size || second.mtimeMs !== first.mtimeMs) {
5421
- throw new SecureFileCustodyError("unavailable", "The Windows Host file changed while its identity was checked.");
5422
- }
5423
- const entry = await lstat(path);
5424
- if (entry.isSymbolicLink()) throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
5425
- if (entry.dev !== second.dev || entry.ino !== second.ino) throw new SecureFileCustodyError("unavailable", "The Windows Host file path no longer names the opened file.");
5426
- }
5427
- async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
5428
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
5429
- const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
5430
- if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
5431
- if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
5432
- if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
5433
- throw securefsRefusal(result.stderr);
5434
- }
5435
- async function createRandomPrivateFileWithSecurefs(path, byteLength2, custody = {}) {
5436
- if (!Number.isSafeInteger(byteLength2) || byteLength2 < 1 || byteLength2 > WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES) throw new TypeError(`The securefs random-file size must be between 1 and ${WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES} bytes.`);
5437
- const result = await runSecurefsCommand(["internal", "securefs", "create-random-private-file", path, String(byteLength2)], 0, custody);
5438
- if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5439
- if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned unexpected creation bytes.");
5440
- if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid creation result.");
5441
- throw securefsRefusal(result.stderr);
5442
- }
5443
- async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
5444
- const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
5445
- if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5446
- if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
5447
- throw securefsRefusal(result.stderr);
5448
- }
5449
- async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
5450
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > WINDOWS_SECUREFS_MAX_WRITE_BYTES || bytes.byteLength > maxBytes) throw new TypeError("The securefs write bound or payload is invalid.");
5451
- const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
5452
- if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
5453
- if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
5454
- throw securefsRefusal(result.stderr);
5455
- }
5456
- async function isPrivateWindowsDirectory(path, custody = {}) {
5457
- await lstat(path);
5458
- try {
5459
- const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
5460
- if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
5461
- if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
5462
- if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
5463
- const refusal = securefsRefusal(result.stderr);
5464
- if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
5465
- throw refusal;
5466
- } catch (error) {
5467
- if (error instanceof SecureFileCustodyError) throw error;
5468
- throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
5469
- }
5470
- }
5471
- async function runSecurefsCommand(args, maxBytes, custody, stdin) {
5472
- if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
5473
- const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
5474
- const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
5475
- return await new Promise((resolve, reject2) => {
5476
- const child = execFile2(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: resolveCealSpawnWorkingDirectory() }, (error, stdout, stderr) => {
5477
- const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
5478
- if (exitCode === null) {
5479
- reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
5480
- return;
5481
- }
5482
- resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
5483
- });
5484
- child.stdin?.on("error", () => void 0);
5485
- child.stdin?.end(stdin);
5486
- });
5487
- }
5488
- function securefsRefusal(stderr) {
5489
- let value;
5490
- try {
5491
- value = JSON.parse(stderr.toString("utf8"));
5492
- } catch {
5493
- return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
5494
- }
5495
- if (!isRecord2(value) || value.schema_version !== WINDOWS_SECUREFS_REFUSAL_SCHEMA || typeof value.code !== "string") return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
5496
- if (value.code === "reparse_point") return new SecureFileCustodyError("reparse_point", "The Windows Host securefs file is a reparse point.");
5497
- if (value.code === "not_found") return new SecureFileCustodyError("not_found", "The Windows Host securefs file was not found.");
5498
- if (value.code === "too_large") return new SecureFileCustodyError("too_large", "The Windows Host securefs file exceeds its read bound.");
5499
- if (value.code === "already_exists") return new SecureFileCustodyError("already_exists", "The Windows Host securefs target already exists.");
5500
- if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
5501
- return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
5502
- }
5503
- function resolveInstalledHostExecutable(platform) {
5504
- const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
5505
- return platform === "win32" ? win322.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join4(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
5506
- }
5507
- function isRecord2(value) {
5508
- return value !== null && typeof value === "object" && !Array.isArray(value);
5509
- }
5510
- function isOwnedBy(uid, expectedUid) {
5511
- return Number.isSafeInteger(uid) && Number.isSafeInteger(expectedUid) && uid === expectedUid;
5512
- }
5513
- function isSelfOwned(uid, platform = process.platform, _handle) {
5514
- if (platform === "win32" || typeof process.geteuid !== "function") return false;
5515
- return isOwnedBy(uid, process.geteuid());
5516
- }
5517
- function isPrivateFileMode(mode, platform = process.platform, _handle) {
5518
- if (platform === "win32") return false;
5519
- return (mode & 63) === 0;
5520
- }
5521
- async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
5522
- if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
5523
- const entry = await lstat(path);
5524
- return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
5525
- }
5649
+ import { isDeepStrictEqual } from "node:util";
5650
+ import { lstat as lstat2, readdir, stat as stat3 } from "node:fs/promises";
5526
5651
 
5527
5652
  // host/service-log.ts
5528
5653
  import { copyFile, mkdir, stat as stat2, truncate, appendFile } from "node:fs/promises";
5529
- import { dirname as dirname2, isAbsolute as isAbsolute3, posix, win32 as win323 } from "node:path";
5654
+ import { dirname as dirname3, isAbsolute as isAbsolute3, posix, win32 as win323 } from "node:path";
5530
5655
 
5531
5656
  // host/service-log-delivery.ts
5532
5657
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -5692,7 +5817,7 @@ async function appendHostServiceLogLine(path, line) {
5692
5817
  var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
5693
5818
  var hostServiceLogDirectories = /* @__PURE__ */ new Map();
5694
5819
  function ensureHostServiceLogDirectory(path) {
5695
- const directory = dirname2(path);
5820
+ const directory = dirname3(path);
5696
5821
  const existing = hostServiceLogDirectories.get(directory);
5697
5822
  if (existing !== void 0) return existing;
5698
5823
  const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
@@ -5724,7 +5849,9 @@ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
5724
5849
  seen.add(message.host_input_ref);
5725
5850
  newestFirst.push(message);
5726
5851
  }
5727
- return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
5852
+ const currentTurn = newestFirst[0]?.host_turn_ref;
5853
+ const currentTurnFirst = currentTurn === void 0 ? newestFirst : newestFirst.filter((message) => message.host_turn_ref === currentTurn);
5854
+ return boundCealHostInvocationHumanMessageWindow(currentTurnFirst, existing?.truncated ?? false);
5728
5855
  }
5729
5856
  async function readRegisteredHostInvocationHumanMessageWindow(readRegistration, readCursor, identity, decodeLine) {
5730
5857
  try {
@@ -5838,6 +5965,15 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
5838
5965
  if (cursor.offset > 0 && !await transcriptAnchorMatches(handle, cursor)) return "transcript_rewritten";
5839
5966
  return null;
5840
5967
  }
5968
+ async function statObservedPathSignature(path) {
5969
+ try {
5970
+ const info = await lstat2(path, { bigint: true });
5971
+ if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) return null;
5972
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
5973
+ } catch {
5974
+ return null;
5975
+ }
5976
+ }
5841
5977
  function transcriptSha256(value) {
5842
5978
  return createHash5("sha256").update(value).digest("hex");
5843
5979
  }
@@ -5870,27 +6006,71 @@ function createTranscriptWatcherBase(options, owner) {
5870
6006
  producerInstallationRef: options.producer_installation_ref
5871
6007
  };
5872
6008
  }
5873
- async function scanTranscriptRegistrations(registrations, scanOne) {
6009
+ async function scanTranscriptRegistrations(registrations, scanOne, totalRegistrations, signal) {
5874
6010
  let records = 0;
5875
6011
  let enqueued = 0;
5876
6012
  let quarantined = 0;
6013
+ let scanned = 0;
5877
6014
  for (const registration of registrations) {
6015
+ if (signal?.aborted) break;
6016
+ scanned += 1;
5878
6017
  const result = await scanOne(registration);
5879
6018
  records += result.records;
5880
6019
  enqueued += result.enqueued;
5881
6020
  if (result.quarantined) quarantined += 1;
5882
6021
  }
5883
- return { registrations: registrations.length, records, enqueued, quarantined };
6022
+ return { registrations: totalRegistrations ?? scanned, records, enqueued, quarantined };
6023
+ }
6024
+ var HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS = 1000000000n;
6025
+ var HostRegistrationInventory = class {
6026
+ signature;
6027
+ registrations;
6028
+ nowNs;
6029
+ observeDirectory;
6030
+ constructor(options = {}) {
6031
+ this.nowNs = options.nowNs ?? (() => BigInt(Date.now()) * 1000000n);
6032
+ this.observeDirectory = options.observeDirectory ?? hostRegistrationDirectorySignature;
6033
+ }
6034
+ async read(directory, load) {
6035
+ const observation = await this.observeDirectory(directory);
6036
+ const nowNs = this.nowNs();
6037
+ const racy = nowNs - observation.mtimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS || nowNs - observation.ctimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS;
6038
+ if (this.registrations !== void 0 && this.signature === observation.signature && !racy) return this.registrations;
6039
+ const registrations = await load();
6040
+ this.signature = observation.signature;
6041
+ this.registrations = registrations;
6042
+ return registrations;
6043
+ }
6044
+ };
6045
+ async function hostRegistrationDirectorySignature(directory) {
6046
+ try {
6047
+ const info = await stat3(directory, { bigint: true });
6048
+ return {
6049
+ signature: `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`,
6050
+ mtimeNs: info.mtimeNs,
6051
+ ctimeNs: info.ctimeNs
6052
+ };
6053
+ } catch (error) {
6054
+ if (isMissingTranscriptError(error)) return { signature: "missing", mtimeNs: 0n, ctimeNs: 0n };
6055
+ throw error;
6056
+ }
5884
6057
  }
5885
6058
  function formatRetiredTranscriptLog(producerLabel, transcriptPath) {
5886
6059
  return `${producerLabel} retired a transcript registration: transcript_path=${JSON.stringify(transcriptPath)}, reason=${TRANSCRIPT_MISSING_REASON}.`;
5887
6060
  }
6061
+ var HOST_TRANSCRIPT_RECONCILIATION_BATCH = 100;
5888
6062
  var HostTranscriptWatcher = class {
5889
6063
  outboxRetentionMs;
5890
6064
  now;
5891
6065
  log;
5892
6066
  producerInstallationRef;
5893
6067
  clockFailure;
6068
+ transcriptObservations = /* @__PURE__ */ new Map();
6069
+ registrationSnapshot;
6070
+ // Advisory scheduling only: listRegistrations remains the registration authority.
6071
+ hotRegistrations = /* @__PURE__ */ new Set();
6072
+ reconciliation;
6073
+ reconciliationRemaining = 0;
5894
6074
  constructor(options, owner) {
5895
6075
  const base = createTranscriptWatcherBase(options, owner);
5896
6076
  this.outboxRetentionMs = base.outboxRetentionMs;
@@ -5899,8 +6079,97 @@ var HostTranscriptWatcher = class {
5899
6079
  this.producerInstallationRef = base.producerInstallationRef;
5900
6080
  this.clockFailure = owner.clock_failure;
5901
6081
  }
5902
- async scanOnce() {
5903
- return scanTranscriptRegistrations(await this.listRegistrations(), (registration) => this.scanRegistration(registration));
6082
+ async scanOnce(signal) {
6083
+ if (signal?.aborted) return { registrations: this.registrationSnapshot?.length ?? 0, records: 0, enqueued: 0, quarantined: 0 };
6084
+ const registrations = await this.listRegistrations();
6085
+ this.reconcileSnapshot(registrations);
6086
+ return scanTranscriptRegistrations(this.scanCandidates(), (observation) => this.observeRegistration(observation, signal), registrations.length, signal);
6087
+ }
6088
+ async observeRegistration(observation, signal) {
6089
+ const registration = observation.registration;
6090
+ const signature = await this.scanFingerprint(registration);
6091
+ if (signal?.aborted) return { records: 0, enqueued: 0, quarantined: false };
6092
+ this.hotRegistrations.delete(observation);
6093
+ if (signature !== null && observation.signature === signature) return { records: 0, enqueued: 0, quarantined: false };
6094
+ this.hotRegistrations.add(observation);
6095
+ const result = await this.scanRegistration(registration);
6096
+ if (result.quarantined || result.retry === true) observation.signature = void 0;
6097
+ else {
6098
+ observation.signature = signature ?? void 0;
6099
+ if (result.records === 0) this.hotRegistrations.delete(observation);
6100
+ }
6101
+ return result;
6102
+ }
6103
+ *scanCandidates() {
6104
+ const hotSlice = [];
6105
+ for (const observation of this.hotRegistrations) {
6106
+ hotSlice.push(observation);
6107
+ if (hotSlice.length === HOST_TRANSCRIPT_RECONCILIATION_BATCH) break;
6108
+ }
6109
+ const observed = /* @__PURE__ */ new Set();
6110
+ for (let count = 0; count < Math.min(this.transcriptObservations.size, HOST_TRANSCRIPT_RECONCILIATION_BATCH); count += 1) {
6111
+ const observation = this.nextReconciliation();
6112
+ if (observation === void 0) break;
6113
+ observed.add(observation);
6114
+ yield observation;
6115
+ }
6116
+ for (const observation of hotSlice) if (!observed.has(observation)) yield observation;
6117
+ }
6118
+ nextReconciliation() {
6119
+ if (this.reconciliationRemaining === 0 || this.reconciliation === void 0) {
6120
+ this.reconciliation = this.transcriptObservations.values();
6121
+ this.reconciliationRemaining = this.transcriptObservations.size;
6122
+ }
6123
+ let next = this.reconciliation.next();
6124
+ if (next.done) {
6125
+ this.reconciliation = this.transcriptObservations.values();
6126
+ this.reconciliationRemaining = this.transcriptObservations.size;
6127
+ next = this.reconciliation.next();
6128
+ }
6129
+ this.reconciliationRemaining -= 1;
6130
+ return next.value;
6131
+ }
6132
+ reconcileSnapshot(registrations) {
6133
+ if (this.registrationSnapshot === registrations) return;
6134
+ const retained = /* @__PURE__ */ new Set();
6135
+ const hot = /* @__PURE__ */ new Set();
6136
+ for (const registration of registrations) {
6137
+ const key = this.registrationKey(registration);
6138
+ retained.add(key);
6139
+ let observation = this.transcriptObservations.get(key);
6140
+ if (observation === void 0) {
6141
+ observation = { registration, signature: void 0 };
6142
+ this.transcriptObservations.set(key, observation);
6143
+ hot.add(observation);
6144
+ } else {
6145
+ if (!isDeepStrictEqual(observation.registration, registration)) {
6146
+ observation.signature = void 0;
6147
+ hot.add(observation);
6148
+ }
6149
+ observation.registration = registration;
6150
+ }
6151
+ }
6152
+ for (const [key, observation] of this.transcriptObservations) {
6153
+ if (!retained.has(key)) {
6154
+ this.transcriptObservations.delete(key);
6155
+ this.hotRegistrations.delete(observation);
6156
+ }
6157
+ }
6158
+ for (const observation of this.hotRegistrations) hot.add(observation);
6159
+ this.hotRegistrations = hot;
6160
+ this.registrationSnapshot = registrations;
6161
+ }
6162
+ async scanFingerprint(registration) {
6163
+ return this.transcriptSignature(registration);
6164
+ }
6165
+ async transcriptSignature(registration) {
6166
+ try {
6167
+ const info = await lstat2(this.transcriptPathOf(registration), { bigint: true });
6168
+ if (!info.isFile() || info.isSymbolicLink()) return null;
6169
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${info.mode}:${info.uid}`;
6170
+ } catch {
6171
+ return null;
6172
+ }
5904
6173
  }
5905
6174
  async scanRegistration(registration) {
5906
6175
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
@@ -6001,8 +6270,8 @@ var HostProducerDrainCore = class {
6001
6270
  };
6002
6271
 
6003
6272
  // host/relay/src/durable-atomic-replacement.ts
6004
- import { lstat as lstat2, mkdir as mkdir2, open as open3, rename, unlink } from "node:fs/promises";
6005
- import { dirname as dirname3 } from "node:path";
6273
+ import { lstat as lstat3, mkdir as mkdir2, open as open3, rename, unlink } from "node:fs/promises";
6274
+ import { dirname as dirname4 } from "node:path";
6006
6275
 
6007
6276
  // host/windows-rename-retry.ts
6008
6277
  import { setTimeout as setTimeout2 } from "node:timers/promises";
@@ -6023,7 +6292,7 @@ function resolveRetrySchedule(tuning) {
6023
6292
  startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
6024
6293
  maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
6025
6294
  sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
6026
- now: tuning.now ?? (() => Date.now())
6295
+ now: tuning.now ?? (() => performance.now())
6027
6296
  };
6028
6297
  }
6029
6298
  async function renameWithWindowsRetry(operation, tuning) {
@@ -6056,7 +6325,7 @@ function isRetryableRenameError(error) {
6056
6325
  var DEFAULT_PORT = {
6057
6326
  platform: process.platform,
6058
6327
  mkdir: (path, options) => mkdir2(path, options),
6059
- lstat: (path) => lstat2(path),
6328
+ lstat: (path) => lstat3(path),
6060
6329
  open_file: (path) => open3(path, "wx", 384),
6061
6330
  rename,
6062
6331
  unlink,
@@ -6064,7 +6333,7 @@ var DEFAULT_PORT = {
6064
6333
  unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
6065
6334
  };
6066
6335
  async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
6067
- const parent = dirname3(target);
6336
+ const parent = dirname4(target);
6068
6337
  await port.mkdir(parent, { recursive: true, mode: 448 });
6069
6338
  const parentStats = await port.lstat(parent);
6070
6339
  const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
@@ -6135,7 +6404,7 @@ function errorCode2(error) {
6135
6404
  import { createHash as createHash6 } from "node:crypto";
6136
6405
  import { constants as constants2 } from "node:fs";
6137
6406
  import { mkdir as mkdir3, open as open4, opendir, unlink as unlink2 } from "node:fs/promises";
6138
- import { dirname as dirname4, join as join5 } from "node:path";
6407
+ import { dirname as dirname5, join as join5 } from "node:path";
6139
6408
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
6140
6409
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
6141
6410
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -6154,6 +6423,8 @@ var HostUsageFactsStore = class {
6154
6423
  afterPendingWrite;
6155
6424
  afterBatchPublish;
6156
6425
  sessionDirectoryCursor;
6426
+ uploadScanSignature;
6427
+ uploadScanEmpty = false;
6157
6428
  constructor(options) {
6158
6429
  this.root = join5(options.outbox_dir, "usage-facts");
6159
6430
  this.sessions = join5(this.root, "sessions");
@@ -6173,6 +6444,10 @@ var HostUsageFactsStore = class {
6173
6444
  this.sessionDirectoryCursor = void 0;
6174
6445
  await cursor?.close();
6175
6446
  }
6447
+ /** The durable path behind one session's usage state, so idle fast paths can poll it without reading it. */
6448
+ statePath(producer, hostSourceRef, hostSessionRef) {
6449
+ return this.sessionPath(producer, hostSourceRef, hostSessionRef);
6450
+ }
6176
6451
  async readState(producer, hostSourceRef, hostSessionRef) {
6177
6452
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
6178
6453
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
@@ -6276,6 +6551,14 @@ var HostUsageFactsStore = class {
6276
6551
  });
6277
6552
  }
6278
6553
  async nextUploadCandidate(producer, hostSourceRef) {
6554
+ const signature = await statObservedPathSignature(this.sessions);
6555
+ if (signature !== null && signature === this.uploadScanSignature && this.uploadScanEmpty) return null;
6556
+ const candidate = await this.scanUploadCandidates(producer, hostSourceRef);
6557
+ this.uploadScanSignature = signature ?? void 0;
6558
+ this.uploadScanEmpty = candidate === null;
6559
+ return candidate;
6560
+ }
6561
+ async scanUploadCandidates(producer, hostSourceRef) {
6279
6562
  const names = await this.readNextSessionNames();
6280
6563
  for (const name of names) {
6281
6564
  const state = await readOptionalJson(join5(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
@@ -6393,7 +6676,7 @@ var HostUsageFactsStore = class {
6393
6676
  }
6394
6677
  async writeImmutableBatch(state, batch, bytes) {
6395
6678
  const path = this.batchPath(state, batch.batch_ref);
6396
- await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
6679
+ await preparePrivateDirectory(dirname5(path), this.platform, this.custody);
6397
6680
  const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
6398
6681
  if (existing !== null) {
6399
6682
  if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
@@ -6411,7 +6694,7 @@ var HostUsageFactsStore = class {
6411
6694
  await handle.sync();
6412
6695
  await handle.close();
6413
6696
  handle = void 0;
6414
- await syncDirectory(dirname4(path), this.platform);
6697
+ await syncDirectory(dirname5(path), this.platform);
6415
6698
  } catch (error) {
6416
6699
  await handle?.close().catch(() => void 0);
6417
6700
  if (errorCode3(error) === "EEXIST") {
@@ -6675,7 +6958,7 @@ async function syncExistingFile(path, platform) {
6675
6958
  } finally {
6676
6959
  await handle.close();
6677
6960
  }
6678
- await syncDirectory(dirname4(path), platform);
6961
+ await syncDirectory(dirname5(path), platform);
6679
6962
  }
6680
6963
  async function syncDirectory(path, platform) {
6681
6964
  if (platform === "win32") return;
@@ -6714,6 +6997,8 @@ function sha2562(value) {
6714
6997
 
6715
6998
  // host/relay/src/host-usage-facts-capture.ts
6716
6999
  import { constants as constants3 } from "node:fs";
7000
+ import { lstat as lstat4 } from "node:fs/promises";
7001
+ import { dirname as dirname6 } from "node:path";
6717
7002
  var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
6718
7003
  var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
6719
7004
  var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
@@ -6763,6 +7048,55 @@ var HostUsageRegistrationCapture = class {
6763
7048
  return captured;
6764
7049
  }
6765
7050
  };
7051
+ var HostUsageIdleGate = class {
7052
+ seen = /* @__PURE__ */ new Map();
7053
+ statPath;
7054
+ constructor(options = {}) {
7055
+ this.statPath = options.statPath ?? statIdleGatePath;
7056
+ }
7057
+ /**
7058
+ * Check whether the path is unchanged since the last confirmed check, without recording anything.
7059
+ * The caller confirms the returned signature only after the capture for it succeeded without a
7060
+ * source error, so a failed read leaves the source eligible on the next tick while a fully-read,
7061
+ * unchanged source keeps skipping its open plus state-read probe.
7062
+ */
7063
+ async checkUnchanged(key, path) {
7064
+ const signature = await this.statPath(path);
7065
+ if (signature === null) {
7066
+ this.seen.delete(key);
7067
+ return { unchanged: false, signature };
7068
+ }
7069
+ if (this.seen.get(key) === signature) return { unchanged: true, signature };
7070
+ return { unchanged: false, signature };
7071
+ }
7072
+ /** Remember a signature only after its capture succeeded, so failures stay eligible. */
7073
+ confirmUnchanged(key, signature) {
7074
+ if (signature === null) return;
7075
+ this.seen.set(key, signature);
7076
+ }
7077
+ };
7078
+ async function statIdleGatePath(path) {
7079
+ const direct = await statObservedPathSignature(path);
7080
+ if (direct !== null) return direct;
7081
+ try {
7082
+ await lstat4(path);
7083
+ return null;
7084
+ } catch (error) {
7085
+ const code = transcriptErrorCode(error);
7086
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
7087
+ return await missingPathAnchor(path);
7088
+ }
7089
+ }
7090
+ async function missingPathAnchor(path) {
7091
+ let ancestor = dirname6(path);
7092
+ for (let depth = 0; depth < 4; depth += 1) {
7093
+ if (ancestor === dirname6(ancestor)) return null;
7094
+ const anchor = await statObservedPathSignature(ancestor);
7095
+ if (anchor !== null) return `missing:${anchor}`;
7096
+ ancestor = dirname6(ancestor);
7097
+ }
7098
+ return null;
7099
+ }
6766
7100
  async function openHostUsageTranscriptCursor(input) {
6767
7101
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
6768
7102
  let source;
@@ -6833,7 +7167,7 @@ function completeLinePrefix(bytes, baseOffset) {
6833
7167
 
6834
7168
  // host/relay/src/host-registration-state.ts
6835
7169
  import { constants as constants4 } from "node:fs";
6836
- import { dirname as dirname5 } from "node:path";
7170
+ import { dirname as dirname7 } from "node:path";
6837
7171
 
6838
7172
  // host/runtime-source-paths.ts
6839
7173
  import { createHash as createHash7 } from "node:crypto";
@@ -6925,7 +7259,7 @@ var HostRegistrationStateError = class extends Error {
6925
7259
  async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
6926
7260
  let raw;
6927
7261
  try {
6928
- await assertPrivateRegistrationDirectory(dirname5(path), platform, custody);
7262
+ await assertPrivateRegistrationDirectory(dirname7(path), platform, custody);
6929
7263
  raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
6930
7264
  } catch (error) {
6931
7265
  throw registrationReadError(error);
@@ -7100,15 +7434,16 @@ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
7100
7434
  }
7101
7435
  }
7102
7436
 
7103
- // host/relay/src/relay-quarantine-store.ts
7104
- var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
7105
- var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
7106
- var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
7107
-
7108
7437
  // host/relay/src/relay-admission-store.ts
7109
- var DEFAULT_LIMITS = { global_count: 8192, global_bytes: 64 * 1024 * 1024, producer_count: 4096, producer_bytes: 32 * 1024 * 1024 };
7110
- var RETRY_SECONDS = [1, 2, 4, 8, 16, 32, 60];
7111
- var MAX_RETRYABLE_ATTEMPTS = RETRY_SECONDS.length + 10;
7438
+ var RELAY_ADMISSION_CODES = vocabulary(["admitted", "already_admitted", "producer_epoch_stale", "sequence_gap", "frame_identity_conflict", "producer_queue_full", "relay_queue_full", "producer_already_connected", "invalid_producer_identity"]);
7439
+
7440
+ // host/relay/src/host-relay-config.ts
7441
+ var HOST_RELAY_CONFIG_MIN_BYTES = Buffer.byteLength("{}", "utf8");
7442
+ var HOST_RELAY_INVOCATION_MINT_LOG_LINE = new RegExp(String.raw`^\[host-relay-invocation-mint\] timestamp=(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[.]\d{3}Z) outcome=(completed|failed) stage=(registration|gateway_request|gateway_response) latency_ms=(\d{1,16})(?: gateway_origin_host=([A-Za-z0-9.:[\]-]{1,255}))?(?: client_exchange_ref=(${CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE.slice(1, -1)}))?(?: gateway_http_request_ref=(${CEAL_HTTP_GATEWAY_REQUEST_REF_PATTERN_SOURCE.slice(1, -1)}))?(?: reason=([a-z][a-z0-9_]{0,63}))?(?: gateway_status=([1-5][0-9]{2}))?$`, "u");
7443
+
7444
+ // host/relay/src/relay-endpoint-ownership.ts
7445
+ import { lstat as lstat5, mkdir as mkdir4, unlink as unlink3 } from "node:fs/promises";
7446
+ import { dirname as dirname8 } from "node:path";
7112
7447
 
7113
7448
  // host/relay/src/relay-ipc-error.ts
7114
7449
  var HostRelayIpcError = class extends Error {
@@ -7129,13 +7464,11 @@ function relayIpcErrorCode(error) {
7129
7464
  }
7130
7465
 
7131
7466
  // host/relay/src/relay-endpoint-ownership.ts
7132
- import { lstat as lstat3, mkdir as mkdir4, unlink as unlink3 } from "node:fs/promises";
7133
- import { dirname as dirname6 } from "node:path";
7134
7467
  function currentUid(fallback) {
7135
7468
  return typeof process.geteuid === "function" ? process.geteuid() : fallback;
7136
7469
  }
7137
7470
  async function assertCompactRelayClientParent(endpoint) {
7138
- const parent = dirname6(endpoint);
7471
+ const parent = dirname8(endpoint);
7139
7472
  if (process.platform !== "darwin" || !isMacosHostRelayIpcDirectory(parent)) return;
7140
7473
  if (parent !== macosHostRelayIpcDirectory()) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC directory does not belong to the effective user.");
7141
7474
  await assertPrivateEndpointDirectory(parent);
@@ -7143,7 +7476,7 @@ async function assertCompactRelayClientParent(endpoint) {
7143
7476
  async function assertPrivateEndpointDirectory(parent) {
7144
7477
  let stats;
7145
7478
  try {
7146
- stats = await lstat3(parent);
7479
+ stats = await lstat5(parent);
7147
7480
  } catch (error) {
7148
7481
  throw endpointInspectionError(error, "Host Relay IPC endpoint parent is unavailable; leaving it untouched.");
7149
7482
  }
@@ -7156,13 +7489,13 @@ function endpointInspectionError(error, message) {
7156
7489
  }
7157
7490
 
7158
7491
  // host/relay/src/relay-ipc.ts
7159
- import { createConnection, createServer } from "node:net";
7492
+ import { createConnection } from "node:net";
7160
7493
 
7161
7494
  // host/relay/src/relay-pipe-handshake.ts
7162
7495
  import { createHmac, randomBytes } from "node:crypto";
7163
7496
  import { constants as constants5 } from "node:fs";
7164
7497
  import { link, unlink as unlink4 } from "node:fs/promises";
7165
- import { dirname as dirname7, join as join6 } from "node:path";
7498
+ import { dirname as dirname9, join as join6 } from "node:path";
7166
7499
  var RELAY_PIPE_HANDSHAKE_TIMEOUT_MS = 5e3;
7167
7500
  var RELAY_PIPE_KEY_BYTES = 32;
7168
7501
  var RELAY_PIPE_KEY_FILENAME = "relay-pipe.key";
@@ -7182,7 +7515,7 @@ var RelayPipeHandshakeError = class extends Error {
7182
7515
  }
7183
7516
  };
7184
7517
  function relayPipeStateRootForOutboxDir(outboxDir) {
7185
- return join6(dirname7(dirname7(dirname7(outboxDir))), "relay");
7518
+ return join6(dirname9(dirname9(dirname9(outboxDir))), "relay");
7186
7519
  }
7187
7520
  function relayPipeKeyPath(relayStateRoot) {
7188
7521
  return join6(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
@@ -7196,7 +7529,7 @@ async function loadRelayPipeKey(relayStateRoot, platform = process.platform, cus
7196
7529
  }
7197
7530
  async function loadWindowsRelayPipeKey(path, custody) {
7198
7531
  try {
7199
- await ensurePrivateDirectoryWithSecurefs(dirname7(path), custody);
7532
+ await ensurePrivateDirectoryWithSecurefs(dirname9(path), custody);
7200
7533
  const existing = await readRelayPipeKey(path, "win32", custody);
7201
7534
  if (existing !== null) return existing;
7202
7535
  await createRandomPrivateFileWithSecurefs(path, RELAY_PIPE_KEY_BYTES, custody);
@@ -7625,7 +7958,7 @@ var HostInvocationAuthenticationRefusal = class extends Error {
7625
7958
  }
7626
7959
  };
7627
7960
  var INSTALLED_HOST_INVOCATION_AUTHENTICATION_DEPENDENCIES = {
7628
- process_elapsed_ms: () => performance.now(),
7961
+ process_elapsed_ms: () => performance2.now(),
7629
7962
  load_pipe_key: async (outboxDirectory) => process.platform === "win32" ? loadRelayPipeKey(relayPipeStateRootForOutboxDir(outboxDirectory)) : void 0,
7630
7963
  create_relay_port: (endpoint, pipeKey, timeoutMs) => new HostRelayInvocationContextPort(endpoint, pipeKey, timeoutMs)
7631
7964
  };
@@ -7822,13 +8155,15 @@ function validToolCallId(value) {
7822
8155
  }
7823
8156
  async function invocationMintQuery(descriptor2, store, current, clientNonce, options, windowOverride) {
7824
8157
  const readWindow = windowOverride === void 0 ? options.read_human_message_window?.(current.identity) ?? descriptor2.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false }) : Promise.resolve(windowOverride);
8158
+ const window = await readWindow;
8159
+ if (window.messages.length === 0) throw new TypeError("transcript_unavailable");
7825
8160
  return {
7826
8161
  producer_id: descriptor2.producer_id,
7827
8162
  producer_installation_ref: options.producer_installation_ref,
7828
8163
  client_nonce: clientNonce,
7829
8164
  context_expires_at: current.expires_at,
7830
8165
  host_binding: { ...current.identity },
7831
- human_message_window: await readWindow,
8166
+ human_message_window: window,
7832
8167
  ...await visibleOutputBudget(descriptor2)
7833
8168
  };
7834
8169
  }
@@ -7857,7 +8192,7 @@ async function currentInvocation(descriptor2, config, now, store) {
7857
8192
  const identity = resolveIdentity(descriptor2, config);
7858
8193
  if (identity.status === "session_unavailable") throw new TypeError("no_binding");
7859
8194
  const waitBudgetMs = config.context_activation_wait_ms ?? 0;
7860
- const monotonicNow = config.monotonic_now ?? (() => performance.now());
8195
+ const monotonicNow = config.monotonic_now ?? (() => performance2.now());
7861
8196
  const deadline = monotonicNow() + waitBudgetMs;
7862
8197
  let firstCheck = true;
7863
8198
  let waitEngaged = false;
@@ -7969,7 +8304,7 @@ function writeResult(value, sink) {
7969
8304
  // host/producer-service.ts
7970
8305
  import { posix as posix4, win32 as win326 } from "node:path";
7971
8306
  import { constants as constants6 } from "node:fs";
7972
- import { lstat as lstat4 } from "node:fs/promises";
8307
+ import { lstat as lstat6 } from "node:fs/promises";
7973
8308
  var SAFE_REF3 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
7974
8309
  var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
7975
8310
  var HostProducerServiceError = class extends Error {
@@ -8098,7 +8433,7 @@ function assertProducerAbsolutePath(value, platform, kind, error) {
8098
8433
  }
8099
8434
  async function configPathStat(configPath, error) {
8100
8435
  try {
8101
- return await lstat4(configPath);
8436
+ return await lstat6(configPath);
8102
8437
  } catch {
8103
8438
  throw error("config_unavailable");
8104
8439
  }
@@ -8373,32 +8708,51 @@ function decodeTokenUsage(value) {
8373
8708
  }
8374
8709
  function decodeResponseItem(payload, ordinal, timestamp3) {
8375
8710
  if (payload.type !== "message" || payload.role !== "user") return { kind: "ignored", ordinal, timestamp: timestamp3 };
8376
- const metadata = userMessageMetadata(payload.internal_chat_message_metadata_passthrough);
8377
- const contentItemKind = userTextContentKind(metadata.content_item_kinds);
8378
- if (contentItemKind === void 0) return { kind: "ignored", ordinal, timestamp: timestamp3 };
8379
- const prompt = userTextContent(payload.content);
8711
+ const attribution = userMessageAttribution(payload.internal_chat_message_metadata_passthrough);
8712
+ if (attribution === null) return { kind: "ignored", ordinal, timestamp: timestamp3 };
8713
+ const prompt = userTextContent(payload.content, attribution.content_item_kinds);
8714
+ if (prompt === null) return { kind: "ignored", ordinal, timestamp: timestamp3 };
8380
8715
  return {
8381
8716
  kind: "user_text",
8382
8717
  ordinal,
8383
8718
  timestamp: timestamp3,
8384
- prompt,
8385
- content_item_kind: contentItemKind,
8719
+ prompt: prompt.text,
8720
+ content_item_kind: prompt.kind,
8386
8721
  message_id: safeRef2(payload.id, "Codex user message identity is invalid."),
8387
- turn_id: safeRef2(metadata.turn_id, "Codex user message task identity is invalid.")
8722
+ turn_id: safeRef2(attribution.turn_id, "Codex user message task identity is invalid.")
8388
8723
  };
8389
8724
  }
8390
- function userTextContentKind(kinds) {
8391
- return kinds.length === 1 && (kinds[0] === "user.text" || kinds[0] === "goal.internal_context") ? kinds[0] : void 0;
8392
- }
8393
- function userMessageMetadata(value) {
8394
- if (!isRecord6(value) || !Array.isArray(value.content_item_kinds)) reject("Codex user message provenance is malformed.");
8395
- return { ...value, content_item_kinds: value.content_item_kinds };
8725
+ function userMessageAttribution(value) {
8726
+ if (!isRecord6(value)) return null;
8727
+ if (typeof value.turn_id !== "string" || !SAFE_REF5.test(value.turn_id)) return null;
8728
+ return { turn_id: value.turn_id, content_item_kinds: Array.isArray(value.content_item_kinds) ? value.content_item_kinds : void 0 };
8396
8729
  }
8397
- function userTextContent(value) {
8730
+ function userTextContent(value, kinds) {
8398
8731
  if (!Array.isArray(value)) reject(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
8399
- if (value.length !== 1) reject(`Codex user text content is malformed (${refusalFact("items", value.length, "exactly one")}).`);
8400
- if (!isRecord6(value[0]) || value[0].type !== "input_text") reject(`Codex user text content is malformed (${refusalFact("item_type", isRecord6(value[0]) ? value[0].type : typeof value[0], "input_text")}).`);
8401
- return boundedText2(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
8732
+ if (kinds === void 0) {
8733
+ if (value.length !== 1) return null;
8734
+ return { text: userTextEntry(value[0]), kind: "user.text" };
8735
+ }
8736
+ if (kinds.length !== value.length) return null;
8737
+ const match = singleAlignedTextKind(kinds);
8738
+ if (match === null) return null;
8739
+ if (kinds.length === 1) return { text: userTextEntry(value[match.index]), kind: match.kind };
8740
+ if (!isRecord6(value[match.index]) || value[match.index].type !== "input_text") return null;
8741
+ return { text: boundedText2(value[match.index].text, MAX_PROMPT_BYTES, "Codex user text is invalid."), kind: match.kind };
8742
+ }
8743
+ function singleAlignedTextKind(kinds) {
8744
+ let match = null;
8745
+ for (let index = 0; index < kinds.length; index += 1) {
8746
+ const kind = kinds[index];
8747
+ if (kind !== "user.text" && kind !== "goal.internal_context") continue;
8748
+ if (match !== null) return null;
8749
+ match = { index, kind };
8750
+ }
8751
+ return match;
8752
+ }
8753
+ function userTextEntry(value) {
8754
+ if (!isRecord6(value) || value.type !== "input_text") reject(`Codex user text content is malformed (${refusalFact("item_type", isRecord6(value) ? value.type : typeof value, "input_text")}).`);
8755
+ return boundedText2(value.text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
8402
8756
  }
8403
8757
  function safeOrdinal(value) {
8404
8758
  if (!Number.isSafeInteger(value) || Number(value) < 0) reject("Codex transcript ordinal is invalid.");
@@ -8483,8 +8837,8 @@ function timestamp(now) {
8483
8837
  }
8484
8838
 
8485
8839
  // host/codex/src/codex-outbox.ts
8486
- import { mkdir as mkdir5, open as open5, rename as rename2, stat as stat3, unlink as unlink5 } from "node:fs/promises";
8487
- import { dirname as dirname8, isAbsolute as isAbsolute4, join as join7 } from "node:path";
8840
+ import { mkdir as mkdir5, open as open5, rename as rename2, stat as stat4, unlink as unlink5 } from "node:fs/promises";
8841
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join7 } from "node:path";
8488
8842
 
8489
8843
  // host/invocation-context.ts
8490
8844
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -8588,6 +8942,7 @@ var CodexOutboxStore = class {
8588
8942
  turnSelectionsDirectory;
8589
8943
  registrationsDirectory;
8590
8944
  cursorsDirectory;
8945
+ registrationInventory = new HostRegistrationInventory();
8591
8946
  constructor(directory) {
8592
8947
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
8593
8948
  this.directory = directory;
@@ -8739,22 +9094,33 @@ var CodexOutboxStore = class {
8739
9094
  return registration;
8740
9095
  }
8741
9096
  async listTranscriptRegistrations() {
8742
- const registrations = [];
8743
- for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
8744
- if (!name.endsWith(".json")) continue;
8745
- try {
8746
- const value = JSON.parse(await readOwnerStateFile(join7(this.registrationsDirectory, name)));
8747
- validateRegistration(value);
8748
- registrations.push(value);
8749
- } catch {
9097
+ return this.registrationInventory.read(this.registrationsDirectory, async () => {
9098
+ const registrations = [];
9099
+ for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
9100
+ if (!name.endsWith(".json")) continue;
9101
+ try {
9102
+ const value = JSON.parse(await readOwnerStateFile(join7(this.registrationsDirectory, name)));
9103
+ validateRegistration(value);
9104
+ registrations.push(value);
9105
+ } catch {
9106
+ }
8750
9107
  }
8751
- }
8752
- return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
9108
+ return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
9109
+ });
8753
9110
  }
8754
9111
  async readTranscriptCursor(registration) {
8755
9112
  validateRegistration(registration);
8756
9113
  return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
8757
9114
  }
9115
+ async transcriptCursorFingerprint(registration) {
9116
+ validateRegistration(registration);
9117
+ try {
9118
+ const info = await stat4(this.cursorPath(registration.host_source_ref, registration.host_session_ref), { bigint: true });
9119
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
9120
+ } catch {
9121
+ return "missing";
9122
+ }
9123
+ }
8758
9124
  async writeTranscriptCursor(cursor) {
8759
9125
  validateCursor(cursor);
8760
9126
  await this.prepare();
@@ -8834,7 +9200,7 @@ async function writeAtomicJson(path, value) {
8834
9200
  await handle.close();
8835
9201
  }
8836
9202
  await rename2(temp, path);
8837
- await syncDirectory2(dirname8(path));
9203
+ await syncDirectory2(dirname10(path));
8838
9204
  } catch (error) {
8839
9205
  try {
8840
9206
  await unlink5(temp);
@@ -8869,14 +9235,14 @@ async function readOptionalJson2(path, validate) {
8869
9235
  async function ensureOwnerDirectory(path) {
8870
9236
  try {
8871
9237
  try {
8872
- const stats2 = await stat3(path);
9238
+ const stats2 = await stat4(path);
8873
9239
  if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8874
9240
  return;
8875
9241
  } catch (error) {
8876
9242
  if (!isNotFound(error)) throw error;
8877
9243
  }
8878
9244
  await mkdir5(path, { recursive: true, mode: 448 });
8879
- const stats = await stat3(path);
9245
+ const stats = await stat4(path);
8880
9246
  if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8881
9247
  } catch (error) {
8882
9248
  if (error instanceof CodexHostAdapterError) throw error;
@@ -9083,9 +9449,16 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
9083
9449
  transcriptPathOf(registration) {
9084
9450
  return registration.transcript_path;
9085
9451
  }
9452
+ registrationKey(registration) {
9453
+ return `${registration.host_source_ref}\0${registration.host_session_ref}`;
9454
+ }
9086
9455
  async listRegistrations() {
9087
9456
  return this.store.listTranscriptRegistrations();
9088
9457
  }
9458
+ async scanFingerprint(registration) {
9459
+ const transcript = await super.scanFingerprint(registration);
9460
+ return transcript === null ? null : `${transcript}|${await this.store.transcriptCursorFingerprint(registration)}`;
9461
+ }
9089
9462
  async scanOpened(handle, registration) {
9090
9463
  const { size, device, inode } = await ownedCodexTranscriptFile(handle);
9091
9464
  const preflight = await this.preflight(registration, handle, size, device, inode);
@@ -9095,7 +9468,7 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
9095
9468
  if (complete === "empty" || complete === "partial") {
9096
9469
  return { records: 0, enqueued: 0, quarantined: false };
9097
9470
  }
9098
- return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
9471
+ return { ...await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode), retry: preflight.cursor.offset + complete.length < size };
9099
9472
  }
9100
9473
  async scanFailed(handle, registration, error) {
9101
9474
  this.diagnostic("watcher_scan_failed", codexTranscriptScanFailureKind(error));
@@ -9414,11 +9787,14 @@ function assertRecordSequence(registration, cursor, records, lastOrdinal, record
9414
9787
  }
9415
9788
 
9416
9789
  // host/codex/src/codex-producer-runtime.ts
9417
- async function drainCodexProducerOnce(options) {
9418
- const scan = await new CodexTranscriptWatcher({
9419
- outbox_dir: options.outbox_dir,
9790
+ function createCodexProducerWatcher(outboxDir) {
9791
+ return new CodexTranscriptWatcher({
9792
+ outbox_dir: outboxDir,
9420
9793
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
9421
- }).scanOnce().catch((error) => {
9794
+ });
9795
+ }
9796
+ async function drainCodexProducerOnce(options, signal) {
9797
+ const scan = await (options.watcher ?? createCodexProducerWatcher(options.outbox_dir)).scanOnce(signal).catch((error) => {
9422
9798
  writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
9423
9799
  throw error;
9424
9800
  });
@@ -9433,17 +9809,34 @@ var CodexUsageFactsCapturer = class {
9433
9809
  usage;
9434
9810
  now;
9435
9811
  registrations;
9812
+ idleGate;
9436
9813
  constructor(options) {
9437
9814
  this.sources = new CodexOutboxStore(options.outbox_dir);
9438
9815
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
9439
9816
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
9440
9817
  this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
9818
+ this.idleGate = new HostUsageIdleGate();
9441
9819
  }
9442
9820
  async captureNext() {
9443
9821
  const registrations = await this.sources.listTranscriptRegistrations();
9444
9822
  return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
9445
9823
  }
9446
9824
  async captureRegistration(registration) {
9825
+ const idleKey = `${registration.host_source_ref}\0${registration.host_session_ref}`;
9826
+ const transcriptKey = `${idleKey}\0transcript`;
9827
+ const stateKey = `${idleKey}\0state`;
9828
+ const transcriptCheck = await this.idleGate.checkUnchanged(transcriptKey, registration.transcript_path);
9829
+ let stateCheck;
9830
+ if (transcriptCheck.unchanged) {
9831
+ stateCheck = await this.idleGate.checkUnchanged(stateKey, this.usage.statePath("codex", registration.host_source_ref, registration.host_session_ref));
9832
+ if (stateCheck.unchanged) return false;
9833
+ }
9834
+ const captured = await this.scanRegistration(registration);
9835
+ this.idleGate.confirmUnchanged(transcriptKey, transcriptCheck.signature);
9836
+ if (stateCheck !== void 0) this.idleGate.confirmUnchanged(stateKey, stateCheck.signature);
9837
+ return captured;
9838
+ }
9839
+ async scanRegistration(registration) {
9447
9840
  const prepared = await openHostUsageTranscriptCursor({
9448
9841
  path: registration.transcript_path,
9449
9842
  producer: "codex",
@@ -9660,7 +10053,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
9660
10053
  producer_id: "codex",
9661
10054
  extra_paths: [CODEX_SESSIONS_ROOT],
9662
10055
  config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
9663
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
10056
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createCodexProducerWatcher(config.outbox_dir) }),
9664
10057
  drain: drainCodexProducerOnce,
9665
10058
  background: (config, signal, dependencies) => {
9666
10059
  const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });
@@ -9669,7 +10062,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
9669
10062
  };
9670
10063
 
9671
10064
  // host/codex/src/codex-visible-output-budget.ts
9672
- import { readFile as readFile2 } from "node:fs/promises";
10065
+ import { readFile } from "node:fs/promises";
9673
10066
  import { homedir } from "node:os";
9674
10067
  import { join as join9 } from "node:path";
9675
10068
  var import_toml = __toESM(require_toml(), 1);
@@ -9679,7 +10072,7 @@ async function resolveCodexVisibleOutputMaxBytes(environment = process.env) {
9679
10072
  const codexHome = resolveCodexHome(environment, homedir());
9680
10073
  let source;
9681
10074
  try {
9682
- source = await readFile2(join9(codexHome, "config.toml"), "utf8");
10075
+ source = await readFile(join9(codexHome, "config.toml"), "utf8");
9683
10076
  } catch (error) {
9684
10077
  return isNotFound2(error) ? codexBytes(CODEX_DEFAULT_TOOL_OUTPUT_TOKEN_LIMIT) : void 0;
9685
10078
  }