@corca-org/ceal-host-win32-x64 1.0.21 → 1.0.22

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.
@@ -16,21 +16,36 @@ function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allow
16
16
  return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
17
17
  }
18
18
 
19
+ // host/unix-socket-path.ts
20
+ var PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES = 103;
21
+
19
22
  // host/runtime-source-paths.ts
20
23
  var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
21
24
  function hostSourceUuid(sourceRef) {
22
25
  return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
23
26
  }
24
- function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform) {
27
+ var DARWIN_UID_MAX = 4294967295;
28
+ var MACOS_HOST_RELAY_IPC_ROOT_PREFIX = "/private/tmp/ceal-host-";
29
+ function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
30
+ if (!Number.isInteger(uid) || uid < 0 || uid > DARWIN_UID_MAX) throw new TypeError("Host runtime effective user identity is invalid.");
31
+ return `${MACOS_HOST_RELAY_IPC_ROOT_PREFIX}${uid}`;
32
+ }
33
+ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
25
34
  const sourceId = hostSourceUuid(sourceRef);
26
35
  if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
27
36
  const path = platform === "win32" ? win322 : posix2;
28
37
  const sourcesRoot = path.join(stateRoot, "sources");
29
38
  const sourceRoot = path.join(sourcesRoot, sourceId);
30
39
  const runtimeRoot = path.join(stateRoot, "run");
31
- const endpoint = platform === "win32" ? `\\\\.\\pipe\\ceal-host-${createHash("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex").slice(0, 24)}` : path.join(runtimeRoot, `${sourceId}.sock`);
40
+ const rootedEndpoint = path.join(runtimeRoot, `${sourceId}.sock`);
41
+ const endpoint = projectRelayEndpoint(stateRoot, sourceRef, rootedEndpoint, platform, uid);
32
42
  return { sourceId, sourcesRoot, sourceRoot, relayRoot: path.join(sourceRoot, "relay"), codexOutbox: path.join(sourceRoot, "producers", "codex", "outbox"), claudeOutbox: path.join(sourceRoot, "producers", "claude", "outbox"), endpoint, runtimeRoot };
33
43
  }
44
+ function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
45
+ if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
46
+ const digest2 = createHash("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
47
+ return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix2.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
48
+ }
34
49
  function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
35
50
  const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
36
51
  if (config.outbox_dir !== (producer === "codex" ? paths.codexOutbox : paths.claudeOutbox) || platform !== "win32" && config.relay_endpoint !== paths.endpoint) throw new TypeError("Host producer outbox and IPC must belong to its configured source.");
@@ -69,7 +84,7 @@ function isPlainRecord(value) {
69
84
  }
70
85
 
71
86
  // packages/ceal-client-protocol/src/client-wire-contract.ts
72
- import { createHash as createHash2 } from "node:crypto";
87
+ import { createHash as createHash3 } from "node:crypto";
73
88
 
74
89
  // packages/ceal-client-protocol/client-wire-contract.json
75
90
  var client_wire_contract_default = {
@@ -90,7 +105,7 @@ var client_wire_contract_default = {
90
105
  ordering: "utf16_code_unit_ascending"
91
106
  },
92
107
  artifact_descriptor: {
93
- operation_contract_bundle_schema_name: "ceal.operation_contract_bundle",
108
+ operation_contract_bundle_schema_name: "ceal.operation_contract_bundle_v2",
94
109
  operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
95
110
  schema_name: "ceal.verified_artifact_descriptor",
96
111
  fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
@@ -115,7 +130,7 @@ var client_wire_contract_default = {
115
130
  },
116
131
  command_request: {
117
132
  schema_name: "ceal.command_request",
118
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
133
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
119
134
  absolute_transport_max_bytes: 65536
120
135
  },
121
136
  command_resolution: {
@@ -161,8 +176,9 @@ var client_wire_contract_default = {
161
176
  },
162
177
  command_response: {
163
178
  schema_name: "ceal.command_response",
164
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
179
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
165
180
  descriptor_field: "verified_artifact",
181
+ request_context_field: "request_context",
166
182
  required_fields: [
167
183
  "schema_version",
168
184
  "exit_code",
@@ -172,7 +188,8 @@ var client_wire_contract_default = {
172
188
  "operation_id",
173
189
  "visible_output_max_bytes",
174
190
  "local_delivery",
175
- "verified_artifact"
191
+ "verified_artifact",
192
+ "request_context"
176
193
  ],
177
194
  bare_document_fields: [
178
195
  "invocation",
@@ -193,7 +210,7 @@ var client_wire_contract_default = {
193
210
  ],
194
211
  exit_code_max: 125,
195
212
  bare_document_max_bytes: 65536,
196
- complete_max_bytes: 66046
213
+ complete_max_bytes: 66195
197
214
  },
198
215
  host_invocation_authentication: {
199
216
  request_schema_name: "ceal.host_invocation_authentication_request",
@@ -207,6 +224,14 @@ var client_wire_contract_default = {
207
224
  "context_token",
208
225
  "expires_at"
209
226
  ],
227
+ refusal_schema_name: "ceal.host_invocation_authentication_refusal",
228
+ refusal_fields: [
229
+ "schema_version",
230
+ "ok",
231
+ "code",
232
+ "reason",
233
+ "gateway_status"
234
+ ],
210
235
  client_nonce: {
211
236
  character_class_source: "A-Za-z0-9_-",
212
237
  encoded_characters: 43
@@ -245,6 +270,8 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
245
270
  "choose_new_output_path",
246
271
  "choose_new_idempotency_key",
247
272
  "restart_search",
273
+ // The requested temporal key is absent on some observed rows; repeating the same interval without `order` can return those rows.
274
+ "search_without_order",
248
275
  "repeat_original_arguments",
249
276
  // The occurrence this call addressed is settled and cannot move again -- a
250
277
  // denied effect approval, an expired continuation -- so the caller runs the
@@ -303,6 +330,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
303
330
  // The command needs caller-owned local materialization (for example an
304
331
  // @path file) before the Gateway can receive the argument.
305
332
  "materialize_local_argument",
333
+ // A missing or stale local Host bundle is repaired through its installed lifecycle and discovery owners.
334
+ "install_ceal_host",
335
+ // An explicit Client store override points at a missing file; unsetting it selects the one canonical default store without creating a second credential store.
336
+ "unset_context_store_path",
337
+ // The producer app must reload its installed Host hook before it can start a conversation with invocation context.
338
+ "restart_producer_app",
306
339
  // A peer's derived schema identifier changed with its field set; install or
307
340
  // upgrade the CLI and Host Relay to the Gateway's release before retrying.
308
341
  "upgrade_ceal_client"
@@ -411,7 +444,6 @@ var NON_MODEL_ACTION_TO_MODEL_ACTION = Object.freeze({
411
444
  });
412
445
  var RETRY_PROMISE_NEXT_ACTIONS = ["retry", "retry_after"];
413
446
  var RETRY_PROMISE = new Set(RETRY_PROMISE_NEXT_ACTIONS);
414
- var RECOVERABLE = new Set(CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS);
415
447
  var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
416
448
  provider_permission: "ask_admin",
417
449
  access_level: "ask_admin",
@@ -433,9 +465,9 @@ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "s
433
465
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
434
466
  var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
435
467
  var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
436
- var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "scope_limit_exceeded"]);
468
+ var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
437
469
  var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
438
- var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable"]);
470
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
439
471
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
440
472
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
441
473
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -506,10 +538,10 @@ function assertSafeJsonArray(value, options, depth, count) {
506
538
  if (value.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
507
539
  for (const item of value) assertSafeJsonValue(item, options, depth + 1, count);
508
540
  }
509
- function assertSafeJsonRecord(record, options, depth, count) {
510
- const entries = Object.entries(record);
541
+ function assertSafeJsonRecord(record2, options, depth, count) {
542
+ const entries = Object.entries(record2);
511
543
  if (entries.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
512
- const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record.fields) : null;
544
+ const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record2.fields) : null;
513
545
  for (const [key, child] of entries) {
514
546
  if (key === "credential_material_included" && child !== false) invalidByContext(options);
515
547
  if (!isSafeNegativeMaterialAssertion(key, child)) assertSafeJsonKey(key, options);
@@ -559,16 +591,21 @@ function isSafeExternalHttpsUrl(value) {
559
591
  return false;
560
592
  }
561
593
  }
594
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE = "^https://[^\\s/@?#]+(?:[/?#][^\\s]*)?$";
595
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN = new RegExp(SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE, "u");
562
596
  function isSafeExternalHttpsUrlInput(value) {
563
597
  return typeof value === "string" && byteLength(value) <= 2048;
564
598
  }
565
- function isSafeExternalHttpsUrlShape(url) {
566
- return url.protocol === "https:" && url.username === "" && url.password === "" && url.hash === "";
599
+ function isSafeExternalHttpsUrlShape(url, allowFragment = false) {
600
+ return url.protocol === "https:" && url.hostname.length > 0 && url.username === "" && url.password === "" && (allowFragment || url.hash === "");
567
601
  }
568
602
  function isSafeResultContent(value, key) {
569
603
  const maximum = key === "text" ? 8192 : 1024;
570
604
  return typeof value === "string" && byteLength(value) <= maximum && firstDisallowedControl(value, "multi_line") === null;
571
605
  }
606
+ function requireSafeRef(value) {
607
+ if (typeof value !== "string" || !SAFE_REF.test(value)) invalidRequestOrResponse();
608
+ }
572
609
  var CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES = 512;
573
610
  function normalizeCealSingleLineText(value) {
574
611
  return value.split("").map((character) => hasControlCharacter(character) ? " " : character).join("").trim();
@@ -680,6 +717,7 @@ function cut(text) {
680
717
 
681
718
  // packages/ceal-client-protocol/src/operation-validation-primitives.ts
682
719
  var ISO_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?([Zz]|([+-])(\d{2}):(\d{2}))$/u;
720
+ var EXPANDED_CANONICAL_ISO_TIMESTAMP = /^([+-])(\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/u;
683
721
  var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
684
722
  var CEAL_CALENDAR_DATE = new RegExp(CEAL_CALENDAR_DATE_PATTERN_SOURCE, "u");
685
723
  function isOperationRecord(value) {
@@ -690,13 +728,46 @@ function isOperationRecord(value) {
690
728
  function requireOperationRecord(value, message) {
691
729
  if (!isOperationRecord(value)) throw new TypeError(message);
692
730
  }
731
+ function requireExactOperationKeys(value, required, optional = [], message = "Operation contract has an invalid shape.") {
732
+ const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
733
+ if (required.some((key) => !Object.hasOwn(value, key))) throw new TypeError(message);
734
+ if (Object.keys(value).some((key) => !allowed.has(key))) throw new TypeError(message);
735
+ }
693
736
  function requireClosedValue(value, members, message) {
694
737
  if (typeof value !== "string" || !members.includes(value)) throw new TypeError(message);
695
738
  }
696
739
  function isCealIsoTimestamp(value) {
697
740
  return typeof value === "string" && parseCealIsoTimestamp(value) !== null;
698
741
  }
742
+ function canonicalCealIsoTimestamp(epochNanoseconds) {
743
+ const wholeSeconds = floorDivide(epochNanoseconds, 1000000000n);
744
+ const fractionalNanoseconds = epochNanoseconds - wholeSeconds * 1000000000n;
745
+ const utc = new Date(Number(wholeSeconds * 1000n));
746
+ const date = utc.toISOString().split(".")[0];
747
+ if (date === void 0) throw new TypeError("Ceal timestamp formatter returned an invalid ISO string");
748
+ const fraction = fractionalNanoseconds.toString().padStart(9, "0").replace(/0+$/u, "").padEnd(3, "0");
749
+ return date + "." + fraction + "Z";
750
+ }
751
+ var CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE = "0000-01-01T00:00:00.000000000+23:59";
752
+ var CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE = "9999-12-31T23:59:59.999999999-23:59";
753
+ var CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE);
754
+ var CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE);
755
+ var CEAL_INSTANT_INDEX_SPAN = CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS - CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS;
756
+ var CEAL_INSTANT_INDEX_KEY_WIDTH = CEAL_INSTANT_INDEX_SPAN.toString().length;
757
+ var CEAL_INSTANT_INDEX_KEY_PATTERN = new RegExp(`^\\d{${CEAL_INSTANT_INDEX_KEY_WIDTH}}$`, "u");
758
+ function requiredTimestampEpochNanoseconds(value) {
759
+ const parsed = parseFourDigitCealIsoTimestamp(value);
760
+ if (parsed === null) throw new Error("Ceal instant-index range basis is outside the timestamp grammar");
761
+ return parsed.epochNanoseconds;
762
+ }
699
763
  function parseCealIsoTimestamp(value) {
764
+ const ordinary = parseFourDigitCealIsoTimestamp(value);
765
+ if (ordinary !== null) return ordinary;
766
+ const expanded = parseExpandedCanonicalCealIsoTimestamp(value);
767
+ if (expanded === null || expanded.epochNanoseconds < CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS || expanded.epochNanoseconds > CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS) return null;
768
+ return canonicalCealIsoTimestamp(expanded.epochNanoseconds) === value ? expanded : null;
769
+ }
770
+ function parseFourDigitCealIsoTimestamp(value) {
700
771
  const fields = parseCealIsoTimestampFields(value);
701
772
  if (fields === null || !validCalendarDate(fields) || !validClockTime(fields) || !validUtcOffset(fields)) return null;
702
773
  const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
@@ -705,6 +776,28 @@ function parseCealIsoTimestamp(value) {
705
776
  epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
706
777
  };
707
778
  }
779
+ function parseExpandedCanonicalCealIsoTimestamp(value) {
780
+ const match = EXPANDED_CANONICAL_ISO_TIMESTAMP.exec(value);
781
+ if (match === null) return null;
782
+ const fields = {
783
+ year: (match[1] === "-" ? -1 : 1) * Number(match[2]),
784
+ month: Number(match[3]),
785
+ day: Number(match[4]),
786
+ hour: Number(match[5]),
787
+ minute: Number(match[6]),
788
+ second: Number(match[7]),
789
+ fraction: match[8] ?? "",
790
+ offsetSign: 0,
791
+ offsetHour: 0,
792
+ offsetMinute: 0
793
+ };
794
+ if (!validCalendarDate(fields) || !validClockTime(fields)) return null;
795
+ const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
796
+ if (!Number.isFinite(epochMilliseconds)) return null;
797
+ return {
798
+ epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
799
+ };
800
+ }
708
801
  function parseCealIsoTimestampFields(value) {
709
802
  const match = ISO_TIMESTAMP.exec(value);
710
803
  if (match === null) return null;
@@ -737,6 +830,10 @@ function cealFieldsEpochMilliseconds(fields) {
737
830
  const offsetMilliseconds = fields.offsetSign * (fields.offsetHour * 60 + fields.offsetMinute) * 6e4;
738
831
  return localMilliseconds - offsetMilliseconds;
739
832
  }
833
+ function floorDivide(value, divisor) {
834
+ const quotient = value / divisor;
835
+ return value % divisor < 0n ? quotient - 1n : quotient;
836
+ }
740
837
  function daysInMonth(year, month) {
741
838
  const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
742
839
  return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
@@ -754,6 +851,9 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
754
851
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
755
852
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
756
853
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
854
+ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
855
+ 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.";
856
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select or activate the current recorded turn. This does not explain why or prove ephemerality. For an independently identified ephemeral Codex side conversation, invoke the command as `ceal --standalone ...`; it uses the local Ceal session and Gateway permissions without Host session/turn audit linkage. Host refusal never switches modes. For intended Host calls, restart the producer and start a new conversation; report the error if it persists.";
757
857
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
758
858
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
759
859
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
@@ -779,6 +879,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
779
879
  refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
780
880
  refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
781
881
  refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
882
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
883
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
782
884
  refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
783
885
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
784
886
  session_store_unwritable: guidance("The Ceal client could not write its local session store; the operating system refused the write (EACCES, EPERM, or EROFS). rerun_outside_agent_sandbox reruns it with escalated execution.", "rerun_outside_agent_sandbox", 500),
@@ -791,8 +893,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
791
893
  response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
792
894
  request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
793
895
  request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
896
+ resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
794
897
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
795
- contract_mismatch: guidance("Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.", "upgrade_ceal_client", 409),
898
+ contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
796
899
  // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
797
900
  // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
798
901
  // when the wait ends still unserved, moved from the `localFailureText` default branch.
@@ -804,6 +907,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
804
907
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
805
908
  // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
806
909
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
910
+ gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
807
911
  // Restored verbatim from the retired `localFailureText` `unknown_outcome`
808
912
  // case: the outcome is unknown, so a read may be retried while a write
809
913
  // must receipt-check first. Collapsing both to "do not repeat the call"
@@ -889,23 +993,24 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
889
993
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
890
994
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
891
995
  // is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
892
- // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). The three rows
893
- // with their own sentences carry the retired policy remedies as Gateway-owned guidance. Statuses are the
996
+ // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). Cause-specific
997
+ // sentences carry the retired policy remedies; `gateway_refused` reuses the release-upgrade guidance above.
998
+ // Statuses are the
894
999
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
895
1000
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
896
1001
  host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
897
1002
  host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
898
1003
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
899
- // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
900
- // missing exact-turn fact names the fresh Host turn, not a reinstall.
901
- host_context_unavailable: guidance("The Host has not activated an invocation context for this session yet. Wait for the Host turn hook to register the session, then retry this command.", "retry", 401, true),
1004
+ // The bounded Host reason does not prove ephemerality. A Host refusal never
1005
+ // changes mode; standalone remains the separate Client authority path.
1006
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
902
1007
  host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
903
1008
  host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
904
1009
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
905
1010
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
906
1011
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
907
1012
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
908
- host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1013
+ host_mint_gateway_refused: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
909
1014
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
910
1015
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
911
1016
  // producer-frame fault names the administrator repair step.
@@ -913,59 +1018,16 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
913
1018
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
914
1019
  // sandboxed Relay socket names the run-alone retry.
915
1020
  host_relay_permission_denied: guidance("An agent sandbox denied the Host Relay socket; run `ceal` as the only command, with no pipe, redirect, or `&&`, so the Host allow rule runs it outside the sandbox.", "rerun_outside_agent_sandbox", 403),
916
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1021
+ host_relay_unavailable: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 503),
917
1022
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
918
1023
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
919
- host_relay_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1024
+ host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
920
1025
  host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
921
1026
  });
922
1027
  var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
923
1028
 
924
- // packages/ceal-client-protocol/src/client-wire-contract.ts
925
- var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
926
- var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
927
- var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
928
- var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
929
- var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
930
- var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
931
- function deriveCealClientWireSchemaVersion(schema) {
932
- if (!/^ceal\.[a-z][a-z0-9_]*$/u.test(schema.schema_name) || !schema.fields.includes("schema_version") || new Set(schema.fields).size !== schema.fields.length || schema.fields.some((field) => typeof field !== "string" || !/^[a-z][a-z0-9_]*$/u.test(field))) {
933
- throw new TypeError("Client wire schema name or field set is invalid.");
934
- }
935
- const fields = schema.fields.filter((field) => field !== "schema_version").sort();
936
- const hash8 = createHash2("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
937
- return `${schema.schema_name}.v1.${hash8}`;
938
- }
939
- var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
940
- var commandResolutionAuthority = commandResolution.authority;
941
- var commandResolutionSemanticOptions = commandResolution.semantic_options;
942
- var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
943
- var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
944
- var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
945
- var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
946
- var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
947
- var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
948
- var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
949
- var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
950
- var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
951
- var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
952
- var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
953
- var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
954
- var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
955
- var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
956
- var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
957
- var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
958
- var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
959
- var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
960
- var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
961
- var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
962
- var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
963
- var CEAL_COMMAND_RESPONSE_DISCOVERY_COMMAND = response.discovery_command;
964
- var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
965
- var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
966
- var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_DOCUMENT_FIELDS = Object.freeze([...response.discovery_manifest_document_fields]);
967
- var CEAL_RESOURCE_STREAM_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_schema_name, fields: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields });
968
- var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
1029
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1030
+ import { createHash as createHash2 } from "node:crypto";
969
1031
 
970
1032
  // packages/ceal-client-protocol/src/operation-withheld-cause.ts
971
1033
  var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
@@ -1011,13 +1073,160 @@ var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
1011
1073
  "interactive_unavailable"
1012
1074
  ]);
1013
1075
 
1076
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1077
+ var DIGEST = /^[a-f0-9]{64}$/u;
1078
+ var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1079
+ function isCealDigest(value) {
1080
+ return typeof value === "string" && DIGEST.test(value);
1081
+ }
1082
+ function cealRequestSha256(value) {
1083
+ return createHash2("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1084
+ }
1085
+ function operationRecord(value, message) {
1086
+ requireOperationRecord(value, message);
1087
+ return value;
1088
+ }
1089
+ function invalid(message) {
1090
+ throw new TypeError(message);
1091
+ }
1092
+ function requirePrefixedRef(value, prefix, message) {
1093
+ if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1094
+ }
1095
+ function requireSafeRef2(value, message) {
1096
+ try {
1097
+ requireSafeRef(value);
1098
+ } catch {
1099
+ invalid(message);
1100
+ }
1101
+ }
1102
+
1103
+ // packages/ceal-client-protocol/src/request-authority.ts
1104
+ var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1105
+ var CEAL_REQUEST_REF_MAX_CHARACTERS = 128;
1106
+ var CEAL_REQUEST_REF_PATTERN_SOURCE = "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$";
1107
+ var CEAL_REQUEST_REF_PATTERN = new RegExp(CEAL_REQUEST_REF_PATTERN_SOURCE, "u");
1108
+ var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1109
+ var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1110
+ var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1111
+ var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1112
+ var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1113
+ var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1114
+ schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1115
+ ceal_request_ref: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_REF_MAX_CHARACTERS, pattern: CEAL_REQUEST_REF_PATTERN_SOURCE },
1116
+ created_at: { type: "string", minLength: 1, maxLength: 64 },
1117
+ authority: {
1118
+ type: "object",
1119
+ maxProperties: 5,
1120
+ additionalProperties: false,
1121
+ properties: {
1122
+ instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1123
+ access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1124
+ principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1125
+ execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1126
+ authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1127
+ },
1128
+ required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1129
+ }
1130
+ });
1131
+ var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1132
+ prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1133
+ host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1134
+ host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1135
+ host_source_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Original authenticated Host turn reference before Gateway Request call-group identity is derived; absent for older Requests." },
1136
+ host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1137
+ host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1138
+ });
1139
+ var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1140
+ caller_call_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Gateway-minted call-group identity for a non-Host caller." },
1141
+ caller_call_input_sha256: { type: "string", minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$", description: "Commitment to the exact input for active non-Host identity-reuse checks; a migrated legacy call group commits to its legacy group key because the original input may no longer exist." }
1142
+ });
1143
+ var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1144
+ requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1145
+ device_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Device that submitted this Request through its client session, including Host turns when the authenticated Host registration carries the device; absent for older records." }
1146
+ });
1147
+ var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1148
+ var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1149
+ var CEAL_REQUEST_JSON_SCHEMA = {
1150
+ type: "object",
1151
+ description: "A Request has exactly one creation identity: the complete Host tuple and prompt reference, or a caller call-group identity. Caller Requests retain no prompt reference or prompt body.",
1152
+ maxProperties: 14,
1153
+ additionalProperties: false,
1154
+ properties: {
1155
+ ...CEAL_REQUEST_COMMON_PROPERTIES,
1156
+ ...CEAL_REQUEST_HOST_PROPERTIES,
1157
+ ...CEAL_REQUEST_CALLER_PROPERTIES,
1158
+ ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1159
+ },
1160
+ required: CEAL_REQUEST_KEYS,
1161
+ anyOf: [
1162
+ {
1163
+ type: "object",
1164
+ required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1165
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1166
+ additionalProperties: false
1167
+ },
1168
+ {
1169
+ type: "object",
1170
+ required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1171
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1172
+ additionalProperties: false
1173
+ }
1174
+ ]
1175
+ };
1176
+
1177
+ // packages/ceal-client-protocol/src/client-wire-contract.ts
1178
+ var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
1179
+ var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
1180
+ var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
1181
+ var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
1182
+ var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
1183
+ var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
1184
+ function deriveCealClientWireSchemaVersion(schema) {
1185
+ if (!/^ceal\.[a-z][a-z0-9_]*$/u.test(schema.schema_name) || !schema.fields.includes("schema_version") || new Set(schema.fields).size !== schema.fields.length || schema.fields.some((field) => typeof field !== "string" || !/^[a-z][a-z0-9_]*$/u.test(field))) {
1186
+ throw new TypeError("Client wire schema name or field set is invalid.");
1187
+ }
1188
+ const fields = schema.fields.filter((field) => field !== "schema_version").sort();
1189
+ const hash8 = createHash3("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
1190
+ return `${schema.schema_name}.v1.${hash8}`;
1191
+ }
1192
+ var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
1193
+ var commandResolutionAuthority = commandResolution.authority;
1194
+ var commandResolutionSemanticOptions = commandResolution.semantic_options;
1195
+ var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
1196
+ var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
1197
+ var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
1198
+ var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
1199
+ var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
1200
+ var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
1201
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
1202
+ var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
1203
+ var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
1204
+ var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
1205
+ var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
1206
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
1207
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
1208
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
1209
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
1210
+ var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
1211
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
1212
+ var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
1213
+ var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
1214
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
1215
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
1216
+ var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
1217
+ var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
1218
+ var CEAL_RESOURCE_STREAM_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_schema_name, fields: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields });
1219
+ var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
1220
+
1221
+ // packages/ceal-client-protocol/src/access-level-vocabulary.ts
1222
+ var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1223
+
1014
1224
  // packages/ceal-client-protocol/src/operation-access-class.ts
1015
1225
  var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
1016
1226
 
1017
1227
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
1018
1228
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
1019
1229
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
1020
- var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1021
1230
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
1022
1231
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
1023
1232
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1125,6 +1334,7 @@ var CEAL_SCHEMA_LITERALS = [
1125
1334
  "ceal.gateway_write_receipt_readback.v1",
1126
1335
  "ceal.gateway_write_request_receipt.v1",
1127
1336
  "ceal.host_observation.v1",
1337
+ "ceal.host_usage_batch.v1",
1128
1338
  "ceal.host_registration_request.v1",
1129
1339
  "ceal.host_registration_result.v1",
1130
1340
  CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
@@ -1153,7 +1363,6 @@ var CEAL_SCHEMA_LITERAL_SET = new Set(CEAL_SCHEMA_LITERALS);
1153
1363
  import { join } from "node:path";
1154
1364
  var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1155
1365
  bounded_store_sidecar: (root) => `${root}.jsonl`,
1156
- gateway_audit_archive: (root) => `${root}.jsonl`,
1157
1366
  gateway_access_group_connector_control_audit: (root) => `${root}.audit.jsonl`,
1158
1367
  gateway_access_group_connector_scope_audit: (root) => join(root, "profile-connector-scope-audit.jsonl"),
1159
1368
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
@@ -1183,6 +1392,7 @@ var CEAL_LOWERCASE_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
1183
1392
  var CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN = new RegExp(`^host-registration-attempt:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1184
1393
  var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1185
1394
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1395
+ var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1186
1396
 
1187
1397
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
1188
1398
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
@@ -1201,7 +1411,7 @@ function shellSingleQuoted(value) {
1201
1411
  return `'${value.replaceAll("'", "'\\''")}'`;
1202
1412
  }
1203
1413
  var CEAL_OPERATION_CONTRACT_REQUIRED_FIELDS = Object.freeze(["input_schema", "result_schema"]);
1204
- var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["summary", "input_resolution"]);
1414
+ var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["branches", "summary", "input_resolution"]);
1205
1415
  var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
1206
1416
  $schema: CEAL_JSON_SCHEMA_2020_12,
1207
1417
  $id: "https://ceal.dev/schemas/verified-artifact-descriptor.v1.schema.json",
@@ -1246,11 +1456,92 @@ var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_o
1246
1456
  // packages/ceal-client-protocol/src/actor-kind.ts
1247
1457
  var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
1248
1458
 
1459
+ // packages/ceal-client-protocol/src/provider-link-policy.ts
1460
+ var PROVIDER_LINK_RESULT_FIELDS = Object.freeze({
1461
+ read_row: Object.freeze({ human_link: "source_url", parent_context: Object.freeze(["thread_ref"]) }),
1462
+ write_result: Object.freeze({ human_links: Object.freeze(["user_openable_url", "url", "spreadsheet_url", "meet_url"]) })
1463
+ });
1464
+ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1465
+ { provider: "slack", result_kind: "message_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "message permalink or the existing canonical workspace/channel/timestamp permalink", source: "https://docs.slack.dev/reference/methods/chat.getPermalink/" },
1466
+ { provider: "slack", result_kind: "message_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "chat.getPermalink result permalink", source: "https://docs.slack.dev/reference/methods/chat.getPermalink/" },
1467
+ { provider: "slack", result_kind: "message_update_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "chat.getPermalink result permalink after verified readback", source: "https://docs.slack.dev/reference/methods/chat.getPermalink/" },
1468
+ { provider: "slack", result_kind: "file_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "file permalink; url_private and url_private_download are excluded", source: "https://docs.slack.dev/reference/objects/file-object/" },
1469
+ { provider: "slack", result_kind: "file_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "file permalink; url_private and url_private_download are excluded", source: "https://docs.slack.dev/reference/objects/file-object/" },
1470
+ { provider: "notion", result_kind: "page_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "page url matching the returned page id", source: "https://developers.notion.com/reference/page" },
1471
+ { provider: "notion", result_kind: "page_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "page url matching the verified page id", source: "https://developers.notion.com/reference/page" },
1472
+ { provider: "github", result_kind: "issue_pull_request_code_release_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "html_url", source: "https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28" },
1473
+ { provider: "github", result_kind: "issue_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback html_url", source: "https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28" },
1474
+ { provider: "github", result_kind: "issue_update_write_result", field: "url", status: "required_when_provider_supplies", provider_shape: "verified readback html_url; replay receipts omit links without provider readback", source: "https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28" },
1475
+ { provider: "github", result_kind: "pull_request_review_write_result", field: "url", status: "required_when_provider_supplies", provider_shape: "submitted review html_url", source: "https://docs.github.com/en/rest/pulls/reviews" },
1476
+ { provider: "github", result_kind: "comment_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "issue comment html_url from provider readback", source: "https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28" },
1477
+ { provider: "google-workspace", result_kind: "drive_file_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
1478
+ { provider: "google-workspace", result_kind: "calendar_event_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "htmlLink", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
1479
+ { provider: "google-workspace", result_kind: "drive_document_calendar_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink or htmlLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
1480
+ { provider: "google-workspace", result_kind: "drive_file_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
1481
+ { provider: "google-workspace", result_kind: "spreadsheet_write_result", field: "spreadsheet_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
1482
+ { provider: "google-workspace", result_kind: "calendar_meet_link_write_result", field: "meet_url", status: "required_when_provider_supplies", provider_shape: "verified conferenceData entryPoint uri", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
1483
+ { provider: "google-workspace", result_kind: "gmail_message_read_row", field: "source_url", status: "not_available", reason: "The Gmail API Message representation exposes id and threadId but no human UI URL; cite by title and date.", source: "https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.messages#Message" },
1484
+ { provider: "google-workspace", result_kind: "gmail_message_write_result", field: "user_openable_url", status: "not_available", reason: "The Gmail API Message representation exposes id and threadId but no human UI URL; no URL is reconstructed.", source: "https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.messages#Message" }
1485
+ ]);
1486
+ var PROVIDER_LINK_HOSTS = Object.freeze({
1487
+ notion: Object.freeze(["notion.so", "www.notion.so", "notion.com", "www.notion.com", "app.notion.com"]),
1488
+ google_workspace: Object.freeze([
1489
+ "calendar.google.com",
1490
+ "contacts.google.com",
1491
+ "docs.google.com",
1492
+ "drive.google.com",
1493
+ "forms.google.com",
1494
+ "mail.google.com",
1495
+ "meet.google.com",
1496
+ "sites.google.com",
1497
+ "www.google.com"
1498
+ ])
1499
+ });
1500
+ var NOTION_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.notion);
1501
+ var GOOGLE_WORKSPACE_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.google_workspace);
1502
+ var PROVIDER_RESOURCE_SOURCE_URL_SCHEMA = Object.freeze({
1503
+ type: "string",
1504
+ minLength: 1,
1505
+ maxLength: 2048,
1506
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1507
+ description: "A provider-owned human link for this exact resource; include it when available. Rows without a provider UI link, such as Gmail messages, are cited by title and date."
1508
+ });
1509
+ var PROVIDER_USER_OPENABLE_URL_SCHEMA = Object.freeze({
1510
+ type: "string",
1511
+ minLength: 1,
1512
+ maxLength: 2048,
1513
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1514
+ description: "The provider-owned human URL for the written resource, when the provider response or verified readback supplies one. Ceal does not construct a fallback URL."
1515
+ });
1516
+
1249
1517
  // packages/ceal-client-protocol/src/resource-row.ts
1250
1518
  var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
1251
1519
  var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
1252
1520
  var CEAL_RESOURCE_SEARCH_DIRECTIONS = vocabulary(["ascending", "descending"]);
1253
- var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary(["query", "modified_since", "since", "until", "authored_by_me", "authored_by", "include_replies", "kinds", "container_ref", "container_refs", "container_names", "addressed_to_me", "unread"]);
1521
+ var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
1522
+ "query",
1523
+ "modified_since",
1524
+ "since",
1525
+ "until",
1526
+ "filetype",
1527
+ "authored_by_me",
1528
+ "authored_by",
1529
+ "edited_by",
1530
+ "include_replies",
1531
+ "kinds",
1532
+ "container_ref",
1533
+ "container_refs",
1534
+ "container_names",
1535
+ "addressed_to_me",
1536
+ "unread",
1537
+ "archived",
1538
+ "state",
1539
+ "event_types",
1540
+ "starred",
1541
+ "trashed",
1542
+ "permission"
1543
+ ]);
1544
+ var CEAL_RESOURCE_SEARCH_STATES = vocabulary(["open", "closed", "draft", "prerelease", "confirmed", "tentative", "cancelled"]);
1254
1545
  var CEAL_RESOURCE_TIME_BASES = vocabulary(["created", "modified", "viewed"]);
1255
1546
  var CEAL_REPOSITORY_VISIBILITIES = vocabulary(["public", "private", "internal"]);
1256
1547
  var CEAL_ACTIVITY_V3_KINDS = vocabulary(["authored", "edited", "messaged", "responded"]);
@@ -1346,6 +1637,8 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1346
1637
  container_label: { required: true, timestamp: false },
1347
1638
  container_ref: { required: false, timestamp: false },
1348
1639
  source_url: { required: false, timestamp: false },
1640
+ thread_ref: { required: false, timestamp: false },
1641
+ reply_count: { required: false, timestamp: false },
1349
1642
  source: { required: true, timestamp: false },
1350
1643
  owner: { required: false, timestamp: false },
1351
1644
  actor_kind: { required: false, timestamp: false },
@@ -1371,6 +1664,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1371
1664
  start: { required: false, timestamp: false },
1372
1665
  end: { required: false, timestamp: false },
1373
1666
  status: { required: false, timestamp: false },
1667
+ event_type: { required: false, timestamp: false },
1374
1668
  snippet: { required: false, timestamp: false },
1375
1669
  dated_notes: { required: false, timestamp: false },
1376
1670
  state: { required: true, timestamp: false },
@@ -1434,6 +1728,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1434
1728
  "refresh_inactive",
1435
1729
  "refresh_replayed",
1436
1730
  "refresh_revoked",
1731
+ "person_inactive",
1732
+ "principal_inactive",
1437
1733
  "authority_replaced",
1438
1734
  "refresh_recovery_unavailable",
1439
1735
  "refresh_recovery_expired",
@@ -1454,116 +1750,25 @@ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
1454
1750
  var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1455
1751
  var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1456
1752
 
1457
- // packages/ceal-client-protocol/src/request-validation-primitives.ts
1458
- import { createHash as createHash3 } from "node:crypto";
1459
- var DIGEST = /^[a-f0-9]{64}$/u;
1460
- var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1461
- function isCealDigest(value) {
1462
- return typeof value === "string" && DIGEST.test(value);
1463
- }
1464
- function cealRequestSha256(value) {
1465
- return createHash3("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1466
- }
1467
- function operationRecord(value, message) {
1468
- requireOperationRecord(value, message);
1469
- return value;
1470
- }
1471
- function invalid(message) {
1472
- throw new TypeError(message);
1473
- }
1474
- function requirePrefixedRef(value, prefix, message) {
1475
- if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1476
- }
1477
-
1478
- // packages/ceal-client-protocol/src/request-authority.ts
1479
- var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1480
- var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1481
- var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1482
- var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1483
- var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1484
- var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1485
- var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1486
- schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1487
- ceal_request_ref: { type: "string", minLength: 1, maxLength: 128, pattern: "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$" },
1488
- created_at: { type: "string", minLength: 1, maxLength: 64 },
1489
- authority: {
1490
- type: "object",
1491
- maxProperties: 5,
1492
- additionalProperties: false,
1493
- properties: {
1494
- instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1495
- access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1496
- principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1497
- execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1498
- authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1499
- },
1500
- required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1501
- }
1502
- });
1503
- var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1504
- prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1505
- host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1506
- host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1507
- host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1508
- host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1509
- });
1510
- var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1511
- caller_call_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Gateway-minted call-group identity for a non-Host caller." },
1512
- caller_call_input_sha256: { type: "string", minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$", description: "Commitment to the exact input for active non-Host identity-reuse checks; a migrated legacy call group commits to its legacy group key because the original input may no longer exist." }
1513
- });
1514
- var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1515
- requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1516
- device_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Device that submitted this Request through its client session, including Host turns when the authenticated Host registration carries the device; absent for older records." }
1517
- });
1518
- var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1519
- var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1520
- var CEAL_REQUEST_JSON_SCHEMA = {
1521
- type: "object",
1522
- description: "A Request has exactly one creation identity: the complete Host tuple and prompt reference, or a caller call-group identity. Caller Requests retain no prompt reference or prompt body.",
1523
- maxProperties: 13,
1524
- additionalProperties: false,
1525
- properties: {
1526
- ...CEAL_REQUEST_COMMON_PROPERTIES,
1527
- ...CEAL_REQUEST_HOST_PROPERTIES,
1528
- ...CEAL_REQUEST_CALLER_PROPERTIES,
1529
- ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1530
- },
1531
- required: CEAL_REQUEST_KEYS,
1532
- anyOf: [
1533
- {
1534
- type: "object",
1535
- required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1536
- properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1537
- additionalProperties: false
1538
- },
1539
- {
1540
- type: "object",
1541
- required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1542
- properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1543
- additionalProperties: false
1544
- }
1545
- ]
1546
- };
1547
-
1548
- // packages/ceal-client-protocol/src/request-operands.ts
1549
- var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1550
- var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
1551
- var CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH = 1024;
1552
- var CEAL_REQUEST_RESOLVER_SELECTION_JSON_SCHEMA = {
1553
- type: "object",
1554
- maxProperties: 2,
1555
- additionalProperties: false,
1556
- properties: {
1557
- property: { type: "string", minLength: 1, maxLength: 128 },
1558
- selectors: {
1559
- type: "object",
1560
- maxProperties: CEAL_REQUEST_MAX_SELECTOR_PROPERTIES,
1561
- properties: {},
1562
- additionalProperties: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH }
1563
- }
1564
- },
1565
- required: ["property", "selectors"]
1566
- };
1753
+ // packages/ceal-client-protocol/src/request-operands.ts
1754
+ var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1755
+ var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
1756
+ var CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH = 1024;
1757
+ var CEAL_REQUEST_RESOLVER_SELECTION_JSON_SCHEMA = {
1758
+ type: "object",
1759
+ maxProperties: 2,
1760
+ additionalProperties: false,
1761
+ properties: {
1762
+ property: { type: "string", minLength: 1, maxLength: 128 },
1763
+ selectors: {
1764
+ type: "object",
1765
+ maxProperties: CEAL_REQUEST_MAX_SELECTOR_PROPERTIES,
1766
+ properties: {},
1767
+ additionalProperties: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH }
1768
+ }
1769
+ },
1770
+ required: ["property", "selectors"]
1771
+ };
1567
1772
 
1568
1773
  // packages/ceal-client-protocol/src/request-graph.ts
1569
1774
  var CEAL_REQUEST_MAX_GRAPH_NODES = 128;
@@ -1652,6 +1857,27 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
1652
1857
  required: ["schema_version", "order", "nodes", "call_budget"]
1653
1858
  };
1654
1859
 
1860
+ // packages/ceal-client-protocol/src/host-observation-validation.ts
1861
+ var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1862
+ var HOST_RESERVED_KEY = /^(?:access_group|admission|approval|audit|authorization|cancellation|capability|effect|grant|occurrence|operation|policy|profile|provider_readback|receipt|reconciliation|replay|target|write_request)(?:_|$)/iu;
1863
+ function validateCealHostObservationValue(value) {
1864
+ if (value === void 0) throw new TypeError("Ceal Host observation value is invalid.");
1865
+ assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1866
+ if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) throw new TypeError("Ceal Host observation value is oversized.");
1867
+ inspectHostKeys(value);
1868
+ }
1869
+ function inspectHostKeys(value) {
1870
+ if (Array.isArray(value)) {
1871
+ for (const entry of value) inspectHostKeys(entry);
1872
+ return;
1873
+ }
1874
+ if (value === null || typeof value !== "object") return;
1875
+ for (const [key, child] of Object.entries(value)) {
1876
+ if (HOST_RESERVED_KEY.test(key)) throw new TypeError("Ceal Host observation cannot restate Gateway-owned facts.");
1877
+ inspectHostKeys(child);
1878
+ }
1879
+ }
1880
+
1655
1881
  // packages/ceal-client-protocol/src/host-observation.ts
1656
1882
  var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
1657
1883
  var HOST_OBSERVATION_PRODUCER = /^[a-z][a-z0-9]{0,31}$/u;
@@ -1698,35 +1924,238 @@ function safeCount(value) {
1698
1924
  return Number.isSafeInteger(value) && Number(value) >= 0;
1699
1925
  }
1700
1926
  function validateCealHostObservationDraft(value) {
1701
- const record = operationRecord(value, "Ceal Host observation draft is invalid.");
1702
- requirePrefixedRef(record.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1703
- requireClosedValue(record.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1704
- requireIsoTimestamp(record.observed_at, "Ceal Host observation time is invalid.");
1705
- assertHostObservationValue(record.value, record.observation_kind);
1927
+ const record2 = operationRecord(value, "Ceal Host observation draft is invalid.");
1928
+ requirePrefixedRef(record2.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1929
+ requireClosedValue(record2.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1930
+ requireIsoTimestamp(record2.observed_at, "Ceal Host observation time is invalid.");
1931
+ assertHostObservationValue(record2.value, record2.observation_kind);
1706
1932
  }
1707
- var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1708
1933
  var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
1709
1934
  function isCealHostPromptObservationValue(value) {
1710
1935
  return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
1711
1936
  }
1712
- var HOST_RESERVED_KEY = /^(?:access_group|admission|approval|audit|authorization|cancellation|capability|effect|grant|occurrence|operation|policy|profile|provider_readback|receipt|reconciliation|replay|target|write_request)(?:_|$)/iu;
1713
1937
  function assertHostObservationValue(value, kind) {
1714
1938
  if (value === void 0) invalid("Ceal Host observation value is invalid.");
1715
1939
  if (kind === "prompt" && !isCealHostPromptObservationValue(value)) invalid("Ceal Host prompt observation must contain only its body digest.");
1716
- assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1717
- if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) invalid("Ceal Host observation value is oversized.");
1718
- inspectHostKeys(value);
1940
+ validateCealHostObservationValue(value);
1719
1941
  }
1720
- function inspectHostKeys(value) {
1721
- if (Array.isArray(value)) {
1722
- for (const entry of value) inspectHostKeys(entry);
1942
+
1943
+ // packages/ceal-client-protocol/src/host-usage-facts.ts
1944
+ import { createHash as createHash4 } from "node:crypto";
1945
+ var CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION = "ceal.host_usage_batch.v1";
1946
+ var CEAL_HOST_USAGE_BATCH_REF_PREFIX = "host-usage-batch:";
1947
+ var CEAL_HOST_USAGE_INGRESS_PATH = "/api/ceal/v2/host-usage-batches";
1948
+ var CEAL_HOST_USAGE_BATCH_MAX_BYTES = 1024 * 1024;
1949
+ var CEAL_HOST_USAGE_FACT_MAX_BYTES = 64 * 1024;
1950
+ var CEAL_HOST_USAGE_BATCH_MAX_FACTS = 256;
1951
+ var CEAL_HOST_USAGE_BATCH_MAX_GAPS = 16;
1952
+ var CEAL_HOST_USAGE_BATCH_ACK_STATUS = 204;
1953
+ var CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES = 65;
1954
+ var CODEX_COUNTER_SEMANTICS = ["last_delta_total_cumulative", "total_cumulative_only", "unknown"];
1955
+ var CODEX_CUMULATIVE_TRANSITIONS = ["baseline", "advanced", "same", "reset_or_correction", "not_observed"];
1956
+ var HOST_USAGE_COVERAGE_GAP_REASONS = ["source_usage_unavailable", "source_file_replaced", "source_file_retired", "outbox_capacity", "unsupported_source_shape"];
1957
+ function createCealHostUsageBatch(input) {
1958
+ const body = { schema_version: CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION, ...input };
1959
+ const batch = { ...body, batch_ref: `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}` };
1960
+ validateCealHostUsageBatch(batch);
1961
+ return batch;
1962
+ }
1963
+ function validateCealHostUsageBatch(value) {
1964
+ if (!isOperationRecord(value)) invalid("Ceal Host usage batch is invalid.");
1965
+ requireExactOperationKeys(value, ["schema_version", "batch_ref", "host_source_ref", "host_session_ref", "created_at", "source_ranges", "facts", "coverage_gaps"]);
1966
+ if (value.schema_version !== CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION || typeof value.batch_ref !== "string" || !value.batch_ref.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX)) invalid("Ceal Host usage batch is invalid.");
1967
+ const { batch_ref: _ref, ...body } = value;
1968
+ if (value.batch_ref !== `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}`) invalid("Ceal Host usage batch reference is invalid.");
1969
+ validateBatchMetadata(value);
1970
+ validateBatchContents(value);
1971
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_BATCH_MAX_BYTES) invalid("Ceal Host usage batch exceeds its byte limit.");
1972
+ }
1973
+ function validateBatchMetadata(value) {
1974
+ requireSafeRef2(value.host_source_ref, "Ceal Host usage source is invalid.");
1975
+ requireSafeRef2(value.host_session_ref, "Ceal Host usage session is invalid.");
1976
+ requireIsoTimestamp(value.created_at, "Ceal Host usage batch time is invalid.");
1977
+ if (!Array.isArray(value.source_ranges) || value.source_ranges.length > CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES) invalid("Ceal Host usage source ranges are invalid.");
1978
+ for (const range of value.source_ranges) validateSourceRange(range);
1979
+ }
1980
+ function validateBatchContents(value) {
1981
+ const facts = validateBatchFacts(value.facts);
1982
+ const gaps = validateBatchGaps(value.coverage_gaps);
1983
+ if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
1984
+ const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
1985
+ for (const fact of facts) {
1986
+ validateFact(fact, value.host_session_ref);
1987
+ if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
1988
+ }
1989
+ for (const gap of gaps) {
1990
+ validateCoverageGap(gap);
1991
+ if (gap.source_file_ref !== null && !sourceFiles.has(gap.source_file_ref)) invalid("Ceal Host usage coverage gap is outside its source ranges.");
1992
+ }
1993
+ }
1994
+ function validateBatchFacts(value) {
1995
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_FACTS) invalid("Ceal Host usage fact count is invalid.");
1996
+ return value;
1997
+ }
1998
+ function validateBatchGaps(value) {
1999
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) invalid("Ceal Host usage coverage is invalid.");
2000
+ return value;
2001
+ }
2002
+ function sourceRangeFileRef(value) {
2003
+ return isOperationRecord(value) ? value.source_file_ref : null;
2004
+ }
2005
+ function hostUsageFactReference(sourceFileRef, sourceEventRef) {
2006
+ requireSafeRef2(sourceFileRef, "Ceal Host usage file reference is invalid.");
2007
+ requireSafeRef2(sourceEventRef, "Ceal Host usage event reference is invalid.");
2008
+ return `host-usage-fact:${sha256(JSON.stringify({ source_file_ref: sourceFileRef, source_event_ref: sourceEventRef }))}`;
2009
+ }
2010
+ function hostUsageSourceEventReference(sourceFileRef, sourceEventIdentity) {
2011
+ requireSafeRef2(sourceFileRef, "Ceal Host usage file reference is invalid.");
2012
+ if (typeof sourceEventIdentity !== "string" || sourceEventIdentity.length === 0 || sourceEventIdentity.length > 1024) invalid("Ceal Host usage event identity is invalid.");
2013
+ return `host-source-event:${sha256(JSON.stringify({ source_file_ref: sourceFileRef, source_event_identity: sourceEventIdentity }))}`;
2014
+ }
2015
+ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, device, inode) {
2016
+ for (const part of [producer, hostSourceRef, hostSessionRef, device, inode]) if (typeof part !== "string" || part.length === 0 || part.length > 512) invalid("Ceal Host usage file identity is invalid.");
2017
+ return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
2018
+ }
2019
+ function validateFact(value, sessionRef) {
2020
+ if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
2021
+ requireFactByteLimit(value);
2022
+ if (value.producer === "codex_transcript") validateCodexFact(value);
2023
+ else if (value.producer === "claude_transcript") validateClaudeFact(value);
2024
+ else invalid("Ceal Host usage producer is invalid.");
2025
+ if (value.host_session_ref !== sessionRef) invalid("Ceal Host usage session does not match its batch.");
2026
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage file reference is invalid.");
2027
+ requireSafeRef2(value.source_event_ref, "Ceal Host usage event reference is invalid.");
2028
+ if (value.host_turn_ref !== null) requireSafeRef2(value.host_turn_ref, "Ceal Host usage turn reference is invalid.");
2029
+ if (value.requested_model !== null && !boundedText(value.requested_model, 256)) invalid("Ceal Host requested model is invalid.");
2030
+ if (value.reported_model !== null && !boundedText(value.reported_model, 256)) invalid("Ceal Host reported model is invalid.");
2031
+ if (value.fact_ref !== hostUsageFactReference(value.source_file_ref, value.source_event_ref)) invalid("Ceal Host usage identity is invalid.");
2032
+ }
2033
+ function requireFactByteLimit(value) {
2034
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_FACT_MAX_BYTES) invalid("Ceal Host usage fact exceeds its byte limit.");
2035
+ }
2036
+ function validateCodexFact(value) {
2037
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fact is invalid.");
2038
+ requireExactOperationKeys(value, ["fact_ref", "host_session_ref", "host_turn_ref", "source_file_ref", "source_event_ref", "source_event_ordinal", "observed_at", "producer", "requested_model", "reported_model", "source_usage", "normalized_usage", "counter_semantics", "cumulative_transition", "finality", "correction_semantics"]);
2039
+ if (value.producer !== "codex_transcript" || !safeInteger(value.source_event_ordinal)) invalid("Ceal Codex usage fact is invalid.");
2040
+ requireIsoTimestamp(value.observed_at, "Ceal Codex usage time is invalid.");
2041
+ if (!isOperationRecord(value.source_usage)) invalid("Ceal Codex source usage is invalid.");
2042
+ requireExactOperationKeys(value.source_usage, ["last_token_usage", "total_token_usage"]);
2043
+ if (value.source_usage.last_token_usage !== null) validateCodexUsageCounts(value.source_usage.last_token_usage);
2044
+ if (value.source_usage.total_token_usage !== null) validateCodexUsageCounts(value.source_usage.total_token_usage);
2045
+ if (!isOneOf(CODEX_COUNTER_SEMANTICS, value.counter_semantics) || !isOneOf(CODEX_CUMULATIVE_TRANSITIONS, value.cumulative_transition) || value.finality !== "unknown" || !["not_observed", "unknown"].includes(String(value.correction_semantics))) invalid("Ceal Codex usage semantics are invalid.");
2046
+ validateNormalizedUsage(value.normalized_usage);
2047
+ }
2048
+ function validateClaudeFact(value) {
2049
+ if (!isOperationRecord(value)) invalid("Ceal Claude usage fact is invalid.");
2050
+ requireExactOperationKeys(value, ["fact_ref", "host_session_ref", "host_turn_ref", "source_file_ref", "source_event_ref", "source_event_uuid", "source_file_kind", "observed_at", "producer", "requested_model", "reported_model", "source_usage", "normalized_usage", "counter_semantics", "finality", "child_inclusion", "correction_semantics"]);
2051
+ validateClaudeIdentity(value);
2052
+ requireIsoTimestamp(value.observed_at, "Ceal Claude usage time is invalid.");
2053
+ validateClaudeSourceUsage(value.source_usage);
2054
+ validateClaudeSemantics(value);
2055
+ validateNormalizedUsage(value.normalized_usage);
2056
+ }
2057
+ function validateClaudeIdentity(value) {
2058
+ if (value.producer !== "claude_transcript" || !boundedText(value.source_event_uuid, 256) || !["main", "subagent"].includes(String(value.source_file_kind))) invalid("Ceal Claude usage fact is invalid.");
2059
+ }
2060
+ function validateClaudeSourceUsage(value) {
2061
+ if (!isOperationRecord(value)) invalid("Ceal Claude source usage is invalid.");
2062
+ requireExactOperationKeys(value, ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"], ["cache_creation"]);
2063
+ for (const key of ["input_tokens", "output_tokens"]) if (!safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
2064
+ for (const key of ["cache_read_input_tokens", "cache_creation_input_tokens"]) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
2065
+ if (value.cache_creation !== void 0 && value.cache_creation !== null) validateClaudeCacheCreationUsage(value.cache_creation);
2066
+ }
2067
+ function validateClaudeCacheCreationUsage(value) {
2068
+ if (!isOperationRecord(value)) invalid("Ceal Claude cache creation usage is invalid.");
2069
+ requireExactOperationKeys(value, ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]);
2070
+ for (const key of ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal Claude cache creation usage is invalid.");
2071
+ }
2072
+ function validateClaudeSemantics(value) {
2073
+ if (value.counter_semantics !== "assistant_message" || !validClaudeFinality(value.finality) || value.child_inclusion !== "unknown" || !validCorrectionSemantics(value.correction_semantics)) invalid("Ceal Claude usage semantics are invalid.");
2074
+ }
2075
+ function validClaudeFinality(value) {
2076
+ return value === "terminal" || value === "nonterminal" || value === "unknown";
2077
+ }
2078
+ function validCorrectionSemantics(value) {
2079
+ return value === "not_observed" || value === "unknown";
2080
+ }
2081
+ function validateCodexUsageCounts(value) {
2082
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
2083
+ requireExactOperationKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
2084
+ for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
2085
+ if (Number(value.total_tokens) !== Number(value.input_tokens) + Number(value.output_tokens) || Number(value.cached_input_tokens) + Number(value.cache_write_input_tokens) > Number(value.input_tokens) || Number(value.reasoning_output_tokens) > Number(value.output_tokens)) invalid("Ceal Codex usage fields are inconsistent.");
2086
+ }
2087
+ function validateNormalizedUsage(value) {
2088
+ if (!isOperationRecord(value)) invalid("Ceal normalized Host usage is invalid.");
2089
+ requireExactOperationKeys(value, ["input", "output", "total", "cached_input", "cache_write_input", "reasoning_output"]);
2090
+ for (const key of Object.keys(value)) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal normalized Host usage is invalid.");
2091
+ validateNormalizedTotals(value);
2092
+ }
2093
+ function validateNormalizedTotals(value) {
2094
+ validateNormalizedCountTotal(value);
2095
+ validateNormalizedInputSubsets(value);
2096
+ validateNormalizedOutputSubset(value);
2097
+ }
2098
+ function validateNormalizedCountTotal(value) {
2099
+ if (value.input !== null && value.output !== null && value.total !== null && Number(value.total) !== Number(value.input) + Number(value.output)) invalid("Ceal normalized Host usage total is inconsistent.");
2100
+ }
2101
+ function validateNormalizedInputSubsets(value) {
2102
+ if (value.input !== null && value.cached_input !== null && value.cache_write_input !== null && Number(value.cached_input) + Number(value.cache_write_input) > Number(value.input)) invalid("Ceal normalized Host input subsets are inconsistent.");
2103
+ }
2104
+ function validateNormalizedOutputSubset(value) {
2105
+ if (value.output !== null && value.reasoning_output !== null && Number(value.reasoning_output) > Number(value.output)) invalid("Ceal normalized Host output subset is inconsistent.");
2106
+ }
2107
+ function validateSourceRange(value) {
2108
+ if (!isOperationRecord(value)) invalid("Ceal Host usage source range is invalid.");
2109
+ requireExactOperationKeys(value, ["source_file_ref", "start_offset", "end_offset"]);
2110
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage source-file reference is invalid.");
2111
+ if (!safeInteger(value.start_offset) || !safeInteger(value.end_offset) || Number(value.end_offset) <= Number(value.start_offset)) invalid("Ceal Host usage source range is invalid.");
2112
+ }
2113
+ function validateCealHostUsageCoverageGap(value) {
2114
+ if (!isOperationRecord(value)) invalid("Ceal Host usage coverage gap is invalid.");
2115
+ requireExactOperationKeys(value, ["reason", "source_file_ref", "start_offset", "end_offset", "omitted_count"]);
2116
+ if (!isOneOf(HOST_USAGE_COVERAGE_GAP_REASONS, value.reason) || !validUsageGapCount(value.reason, value.omitted_count)) invalid("Ceal Host usage coverage gap is invalid.");
2117
+ if (value.source_file_ref === null) {
2118
+ if (value.start_offset !== null || value.end_offset !== null) invalid("Ceal Host usage coverage gap range is invalid.");
1723
2119
  return;
1724
2120
  }
1725
- if (value === null || typeof value !== "object") return;
1726
- for (const [key, child] of Object.entries(value)) {
1727
- if (HOST_RESERVED_KEY.test(key)) invalid("Ceal Host observation cannot restate Gateway-owned facts.");
1728
- inspectHostKeys(child);
2121
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage coverage file reference is invalid.");
2122
+ if (!safeInteger(value.start_offset) || !safeInteger(value.end_offset) || Number(value.end_offset) <= Number(value.start_offset)) invalid("Ceal Host usage coverage gap range is invalid.");
2123
+ }
2124
+ function validateCoverageGap(value) {
2125
+ validateCealHostUsageCoverageGap(value);
2126
+ }
2127
+ function validUsageGapCount(reason, value) {
2128
+ return value === null ? reason !== "outbox_capacity" : safeInteger(value) && Number(value) >= 1;
2129
+ }
2130
+ function isOneOf(values, value) {
2131
+ return typeof value === "string" && values.some((candidate) => candidate === value);
2132
+ }
2133
+ function isCealHostUsageBatchReference(value) {
2134
+ return typeof value === "string" && value.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX) && isCealDigest(value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length));
2135
+ }
2136
+ function cealHostUsageBatchObjectDigestFromFileName(value) {
2137
+ if (!value.endsWith(".json")) return null;
2138
+ const digest2 = value.slice(0, -5);
2139
+ return isCealDigest(digest2) ? digest2 : null;
2140
+ }
2141
+ function cealHostUsageBatchObjectDigestFromReference(value) {
2142
+ return isCealHostUsageBatchReference(value) ? value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length) : null;
2143
+ }
2144
+ function safeInteger(value) {
2145
+ return Number.isSafeInteger(value) && Number(value) >= 0;
2146
+ }
2147
+ function boundedText(value, maximum) {
2148
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters(value);
2149
+ }
2150
+ function hasControlCharacters(value) {
2151
+ for (const character of value) {
2152
+ const code = character.codePointAt(0);
2153
+ if (code !== void 0 && (code < 32 || code === 127)) return true;
1729
2154
  }
2155
+ return false;
2156
+ }
2157
+ function sha256(value) {
2158
+ return createHash4("sha256").update(value, "utf8").digest("hex");
1730
2159
  }
1731
2160
 
1732
2161
  // packages/ceal-client-protocol/src/host-prompt-ref.ts
@@ -1833,11 +2262,72 @@ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSch
1833
2262
  var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
1834
2263
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
1835
2264
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
2265
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.refusal_schema_name, fields: hostInvocationAuthenticationContract.refusal_fields });
1836
2266
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
1837
2267
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
1838
2268
  var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
1839
2269
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
2270
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
1840
2271
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
2272
+ function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
2273
+ const messages = [];
2274
+ let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
2275
+ for (const candidate of newestFirst.slice(0, CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES)) {
2276
+ const complete = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: candidate.text, ...candidate.text_truncated === true ? { text_truncated: candidate.text_truncated } : {} };
2277
+ if (encodedMessageWindowBytes([...messages, complete]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) {
2278
+ messages.push(Object.freeze(complete));
2279
+ continue;
2280
+ }
2281
+ const clipped = clipHumanMessageToWindow(messages, candidate);
2282
+ if (clipped === null) {
2283
+ truncated = true;
2284
+ break;
2285
+ }
2286
+ messages.push(Object.freeze(clipped));
2287
+ }
2288
+ return Object.freeze({ messages: Object.freeze(messages), truncated });
2289
+ }
2290
+ function encodedMessageWindowBytes(messages) {
2291
+ return new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2292
+ }
2293
+ function clipHumanMessageToWindow(prefix, candidate) {
2294
+ const clipped = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: "", text_truncated: true };
2295
+ const available = CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES - encodedMessageWindowBytes([...prefix, clipped]);
2296
+ if (available < 0) return null;
2297
+ const text = [];
2298
+ let used = 0;
2299
+ for (const point of candidate.text) {
2300
+ const encodedPoint = JSON.stringify(point);
2301
+ const cost = new TextEncoder().encode(encodedPoint).byteLength - 2;
2302
+ if (used + cost > available) break;
2303
+ text.push(point);
2304
+ used += cost;
2305
+ }
2306
+ const result = { ...clipped, text: text.join("") };
2307
+ return encodedMessageWindowBytes([...prefix, result]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES ? result : null;
2308
+ }
2309
+ function decodeCealHostInvocationHumanMessageWindow(value) {
2310
+ if (!isCealJsonRecord(value) || !exactOptionalKeys(value, ["messages", "truncated"], []) || !Array.isArray(value.messages) || value.messages.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES || typeof value.truncated !== "boolean") throw invalidInvocationContextRequest();
2311
+ const messages = value.messages.map(decodeHumanMessage);
2312
+ const bytes = new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2313
+ if (bytes > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) throw invalidInvocationContextRequest();
2314
+ return Object.freeze({ messages: Object.freeze(messages), truncated: value.truncated });
2315
+ }
2316
+ function decodeHumanMessage(candidate) {
2317
+ if (!isCealJsonRecord(candidate) || !exactOptionalKeys(candidate, ["host_turn_ref", "host_input_ref", "text"], ["text_truncated"]) || !safeReference(candidate.host_turn_ref) || !safeReference(candidate.host_input_ref) || typeof candidate.text !== "string") throw invalidInvocationContextRequest();
2318
+ if (candidate.text_truncated !== void 0 && candidate.text_truncated !== true) throw invalidInvocationContextRequest();
2319
+ return Object.freeze({ host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: candidate.text, ...candidate.text_truncated === true ? { text_truncated: candidate.text_truncated } : {} });
2320
+ }
2321
+ function safeReference(value) {
2322
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
2323
+ }
2324
+ function exactOptionalKeys(value, required, optional = []) {
2325
+ const keys = Object.keys(value);
2326
+ return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => required.includes(key) || optional.includes(key));
2327
+ }
2328
+ function invalidInvocationContextRequest() {
2329
+ return new TypeError("The Host invocation context request is invalid.");
2330
+ }
1841
2331
  function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1842
2332
  const clientNonce = contract.host_invocation_authentication.client_nonce;
1843
2333
  return {
@@ -1847,31 +2337,11 @@ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTR
1847
2337
  };
1848
2338
  }
1849
2339
  var hostNonceContract = deriveCealHostInvocationNonceContract();
1850
- var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
1851
2340
  var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
1852
2341
  var CEAL_HOST_CONTEXT_TOKEN_PATTERN = new RegExp(hostNonceContract.context_token_pattern_source, "u");
1853
- var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_MAX_BYTES = deriveCealHostInvocationAuthenticationResultMaxBytes();
1854
- function deriveCealHostInvocationAuthenticationResultMaxBytes(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1855
- const hostAuthentication = contract.host_invocation_authentication;
1856
- const values = {
1857
- schema_version: deriveCealClientWireSchemaVersion({ schema_name: hostAuthentication.result_schema_name, fields: hostAuthentication.result_fields }),
1858
- context_token: `${CEAL_HOST_CONTEXT_TOKEN_PREFIX}${"A".repeat(hostAuthentication.client_nonce.encoded_characters)}`,
1859
- expires_at: (/* @__PURE__ */ new Date("+010000-01-01T00:00:00.000Z")).toISOString()
1860
- };
1861
- const fields = hostAuthentication.result_fields;
1862
- if (fields.some((field) => !Object.hasOwn(values, field))) throw new TypeError("Host invocation result fields have no bounded sample value.");
1863
- return new TextEncoder().encode(`${JSON.stringify(Object.fromEntries(fields.map((field) => [field, values[field]])))}
1864
- `).byteLength;
1865
- }
1866
2342
  var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
1867
2343
  "request_authority_unavailable",
1868
- "request_missing",
1869
- "authority_mismatch",
1870
- "host_source_mismatch",
1871
- "host_session_mismatch",
1872
- "host_turn_mismatch",
1873
- "host_input_mismatch",
1874
- "host_prompt_mismatch"
2344
+ "request_creation_refused"
1875
2345
  ]);
1876
2346
  var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1877
2347
  "invalid_arguments",
@@ -1880,7 +2350,6 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1880
2350
  "context_unavailable",
1881
2351
  "context_replaced",
1882
2352
  "no_binding",
1883
- "context_stale",
1884
2353
  "context_expired",
1885
2354
  "host_source_refused",
1886
2355
  "host_credential_refused",
@@ -1897,31 +2366,42 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1897
2366
  "relay_failed",
1898
2367
  "host_refusal_invalid"
1899
2368
  ]);
2369
+ var CEAL_HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2370
+ "permission_denied",
2371
+ "socket_missing",
2372
+ "connection_refused",
2373
+ "closed_early",
2374
+ "response_invalid",
2375
+ "timed_out",
2376
+ "cancelled",
2377
+ "unavailable"
2378
+ ]);
1900
2379
  var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1901
2380
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
1902
2381
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
1903
2382
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1904
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
2383
+ // This reason cannot distinguish a Codex side conversation from a missing
2384
+ // context in a regular session, so guidance must leave that choice to the caller.
2385
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
1905
2386
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1906
2387
  // `no_binding` now means the producer has no real current Host session. The
1907
2388
  // Host Relay never uses it for an uncreated Gateway Request; there is no
1908
2389
  // useful retry until the consumer is running inside a Host session.
1909
2390
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1910
- context_stale: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1911
2391
  context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
1912
2392
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
1913
2393
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
1914
2394
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
1915
2395
  gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
1916
- contract_mismatch: Object.freeze({ classification: "contract_mismatch", next_action: "upgrade_ceal_client" }),
1917
- gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
2396
+ contract_mismatch: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2397
+ gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "upgrade_ceal_client" }),
1918
2398
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
1919
2399
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
1920
2400
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
1921
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2401
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
1922
2402
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
1923
2403
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
1924
- relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "answer_with_gap" }),
2404
+ relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
1925
2405
  host_refusal_invalid: Object.freeze({ classification: "host_refusal_invalid", next_action: "answer_with_gap" })
1926
2406
  });
1927
2407
 
@@ -1935,10 +2415,13 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
1935
2415
  "activation_recorded",
1936
2416
  "activation_failed",
1937
2417
  "watcher_scan_failed",
2418
+ "usage_capture_failed",
2419
+ "usage_upload_failed",
1938
2420
  "activation_wait_skipped",
1939
2421
  "activation_wait_engaged",
1940
2422
  "activation_wait_completed",
1941
- "activation_wait_exhausted"
2423
+ "activation_wait_exhausted",
2424
+ "invocation_authentication_failed"
1942
2425
  ]);
1943
2426
  var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1944
2427
  "malformed_line",
@@ -1948,6 +2431,17 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1948
2431
  "size_budget",
1949
2432
  "symlink"
1950
2433
  ]);
2434
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_WATCHER_OPTIONAL_FIELDS = vocabulary(["failure_kind", "cause"]);
2435
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_OPTIONAL_FIELDS = vocabulary(["cause"]);
2436
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE = "^[a-z][a-z0-9_]{0,63}(?::[A-Za-z][A-Za-z0-9_]{0,63})?$";
2437
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES = Object.freeze([
2438
+ ...CEAL_HOST_AUTHENTICATION_CAUSES,
2439
+ ...CEAL_HOST_RELAY_EXCHANGE_FAILURES.map((failure) => `relay_exchange:${failure}`)
2440
+ ]);
2441
+ var hostServiceDiagnosticCausePattern = new RegExp(CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE, "u");
2442
+ function isCealHostServiceDiagnosticCause(value, event) {
2443
+ return typeof value === "string" && hostServiceDiagnosticCausePattern.test(value) && (event !== "invocation_authentication_failed" || CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES.includes(value));
2444
+ }
1951
2445
 
1952
2446
  // packages/ceal-client-protocol/src/client-result-materialization.ts
1953
2447
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
@@ -2034,12 +2528,14 @@ var ADMIN_SOURCE_OWNERS = vocabulary([
2034
2528
  "resource",
2035
2529
  "prompt",
2036
2530
  "usage",
2531
+ "provider_request_lifecycle",
2037
2532
  "connector",
2038
2533
  "session",
2039
2534
  "knowledge",
2040
2535
  "policy"
2041
2536
  ]);
2042
2537
  var ADMIN_COMPLETENESS_STATES = vocabulary(["complete", "partial", "unknown"]);
2538
+ var ADMIN_PROVIDER_REQUEST_CAPTURE_HEALTH_STATES = vocabulary(["available", "missing", "invalid", "unreadable"]);
2043
2539
  var ADMIN_OPERATION_OUTCOMES = vocabulary(["completed", "failed", "denied", "cancelled", "unknown"]);
2044
2540
  var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
2045
2541
  var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
@@ -2078,7 +2574,7 @@ function waitForAbort(signal, milliseconds) {
2078
2574
  import { execFile } from "node:child_process";
2079
2575
  import { constants } from "node:fs";
2080
2576
  import { lstat, open } from "node:fs/promises";
2081
- import { dirname, win32 as win323 } from "node:path";
2577
+ import { dirname, join as join2, win32 as win323 } from "node:path";
2082
2578
  import { fileURLToPath } from "node:url";
2083
2579
  var SecureFileCustodyError = class extends Error {
2084
2580
  name = "SecureFileCustodyError";
@@ -2096,6 +2592,7 @@ var SecureFileCustodyError = class extends Error {
2096
2592
  }
2097
2593
  };
2098
2594
  var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
2595
+ var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
2099
2596
  var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
2100
2597
  var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
2101
2598
  function secureOpenFlags(flags, platform) {
@@ -2138,18 +2635,46 @@ async function assertWindowsIdentityStable(handle, first, path) {
2138
2635
  }
2139
2636
  async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
2140
2637
  if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
2141
- const result = await runWindowsSecurefs(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2638
+ const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2142
2639
  if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
2143
2640
  if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
2144
2641
  if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
2145
2642
  throw securefsRefusal(result.stderr);
2146
2643
  }
2147
- async function runWindowsSecurefs(args, maxBytes, custody) {
2148
- if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args);
2149
- const executable = custody.securefs_executable ?? resolveInstalledHostExecutable();
2644
+ async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
2645
+ const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
2646
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2647
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
2648
+ throw securefsRefusal(result.stderr);
2649
+ }
2650
+ async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
2651
+ 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.");
2652
+ const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
2653
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2654
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
2655
+ throw securefsRefusal(result.stderr);
2656
+ }
2657
+ async function isPrivateWindowsDirectory(path, custody = {}) {
2658
+ await lstat(path);
2659
+ try {
2660
+ const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
2661
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
2662
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
2663
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
2664
+ const refusal = securefsRefusal(result.stderr);
2665
+ if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
2666
+ throw refusal;
2667
+ } catch (error) {
2668
+ if (error instanceof SecureFileCustodyError) throw error;
2669
+ throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
2670
+ }
2671
+ }
2672
+ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2673
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
2674
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2150
2675
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2151
2676
  return await new Promise((resolve, reject2) => {
2152
- execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2677
+ const child = execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2153
2678
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2154
2679
  if (exitCode === null) {
2155
2680
  reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2157,6 +2682,8 @@ async function runWindowsSecurefs(args, maxBytes, custody) {
2157
2682
  }
2158
2683
  resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
2159
2684
  });
2685
+ child.stdin?.on("error", () => void 0);
2686
+ child.stdin?.end(stdin);
2160
2687
  });
2161
2688
  }
2162
2689
  function securefsRefusal(stderr) {
@@ -2174,9 +2701,9 @@ function securefsRefusal(stderr) {
2174
2701
  if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
2175
2702
  return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
2176
2703
  }
2177
- function resolveInstalledHostExecutable() {
2704
+ function resolveInstalledHostExecutable(platform) {
2178
2705
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2179
- return win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
2706
+ return platform === "win32" ? win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2180
2707
  }
2181
2708
  function isRecord(value) {
2182
2709
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2192,6 +2719,11 @@ function isPrivateFileMode(mode, platform = process.platform, _handle) {
2192
2719
  if (platform === "win32") return false;
2193
2720
  return (mode & 63) === 0;
2194
2721
  }
2722
+ async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
2723
+ if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
2724
+ const entry = await lstat(path);
2725
+ return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
2726
+ }
2195
2727
 
2196
2728
  // host/producer-service.ts
2197
2729
  var SAFE_REF2 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
@@ -2218,7 +2750,8 @@ function parseHostProducerServeArgs(args, platform = process.platform) {
2218
2750
  async function readHostProducerConfig(descriptor, configPath, platform = process.platform, custody = {}) {
2219
2751
  const config = decodeHostProducerConfigText(descriptor, await readProducerConfigText(configPath, platform, hostProducerError, custody), platform);
2220
2752
  const path = platform === "win32" ? win324 : posix3;
2221
- const root = path.resolve(config.outbox_dir, "../../../../..");
2753
+ const registrationStateFile = hostProducerRegistrationStateFile(config.outbox_dir, platform);
2754
+ const root = path.dirname(registrationStateFile);
2222
2755
  try {
2223
2756
  assertHostProducerSourcePaths(root, config, descriptor.producer_id, platform);
2224
2757
  } catch (error) {
@@ -2233,7 +2766,18 @@ function decodeHostProducerConfigText(descriptor, text, platform = process.platf
2233
2766
  return Object.freeze(descriptor.config({ schema_version: descriptor.schema, ...core }, extras));
2234
2767
  }
2235
2768
  async function serveHostProducer(descriptor, config, signal, dependencies = {}) {
2236
- await serveProducer(descriptor.runtime_options(config), config, signal, dependencies.drain ?? descriptor.drain, dependencies.wait);
2769
+ const runtimeOptions = descriptor.runtime_options(config);
2770
+ const serving = serveProducer(runtimeOptions, config, signal, dependencies.drain ?? descriptor.drain, dependencies.wait);
2771
+ if (descriptor.background === void 0 || dependencies.drain !== void 0) {
2772
+ await serving;
2773
+ return;
2774
+ }
2775
+ const background = descriptor.background(config, signal);
2776
+ await Promise.all([serving, background]);
2777
+ }
2778
+ function hostProducerRegistrationStateFile(outboxDirectory, platform = process.platform) {
2779
+ const path = platform === "win32" ? win324 : posix3;
2780
+ return path.join(path.resolve(outboxDirectory, "../../../../.."), "registration.json");
2237
2781
  }
2238
2782
  async function runHostProducerCli(descriptor, args, signal, dependencies = {}) {
2239
2783
  await serveHostProducer(descriptor, await readHostProducerConfig(descriptor, parseHostProducerServeArgs(args)), signal, dependencies);
@@ -2394,44 +2938,993 @@ function producerShapeFacts(value, options) {
2394
2938
  if (Object.hasOwn(value, "schema_version") && value.schema_version !== options.schema) facts.push({ name: "schema_version", value: "wrong_type", expected: options.schema });
2395
2939
  return facts;
2396
2940
  }
2397
- function validateIdentity(sourceRef, installationRef, epoch, error) {
2398
- if (!SAFE_REF2.test(sourceRef) || !SAFE_REF2.test(installationRef) || !positive(epoch, 2147483647)) throw error("invalid_config", refusalFacts(producerIdentityFacts(sourceRef, installationRef, epoch)));
2399
- return epoch;
2941
+ function validateIdentity(sourceRef, installationRef, epoch, error) {
2942
+ if (!SAFE_REF2.test(sourceRef) || !SAFE_REF2.test(installationRef) || !positive(epoch, 2147483647)) throw error("invalid_config", refusalFacts(producerIdentityFacts(sourceRef, installationRef, epoch)));
2943
+ return epoch;
2944
+ }
2945
+ function producerIdentityFacts(sourceRef, installationRef, epoch) {
2946
+ const facts = [];
2947
+ if (!SAFE_REF2.test(sourceRef)) facts.push({ name: "host_source_ref", value: "wrong_type", expected: "a safe reference" });
2948
+ if (!SAFE_REF2.test(installationRef)) facts.push({ name: "producer_installation_ref", value: "wrong_type", expected: "a safe reference" });
2949
+ if (!positive(epoch, 2147483647)) facts.push({ name: "producer_epoch", value: "wrong_type", expected: "a positive integer" });
2950
+ return facts;
2951
+ }
2952
+ function validateIntervals(reconcile, retry, timeout, error) {
2953
+ if (!boundedMilliseconds(reconcile) || !boundedMilliseconds(retry) || !boundedMilliseconds(timeout)) throw error("invalid_config", refusalFacts(producerIntervalFacts(reconcile, retry, timeout)));
2954
+ return [reconcile, retry, timeout];
2955
+ }
2956
+ function producerIntervalFacts(reconcile, retry, timeout) {
2957
+ const facts = [];
2958
+ if (!boundedMilliseconds(reconcile)) facts.push({ name: "reconcile_interval_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
2959
+ if (!boundedMilliseconds(retry)) facts.push({ name: "retry_backoff_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
2960
+ if (!boundedMilliseconds(timeout)) facts.push({ name: "ipc_timeout_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
2961
+ return facts;
2962
+ }
2963
+ function hasConfigKeys(value, required, tolerated = []) {
2964
+ return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || tolerated.includes(key) || Object.hasOwn(HOST_PRODUCER_TIMING_DEFAULTS, key));
2965
+ }
2966
+ function isRecord2(value) {
2967
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2968
+ }
2969
+ function positive(value, maximum) {
2970
+ return Number.isSafeInteger(value) && Number(value) > 0 && Number(value) <= maximum;
2971
+ }
2972
+ function boundedMilliseconds(value) {
2973
+ return positive(value, 6e4) && Number(value) >= 25;
2974
+ }
2975
+
2976
+ // host/relay/src/host-registration-state.ts
2977
+ import { constants as constants3 } from "node:fs";
2978
+ import { dirname as dirname2 } from "node:path";
2979
+ var HOST_REGISTRATION_STATE_SCHEMA = "ceal.host_registration_state.v1";
2980
+ var HOST_REGISTRATION_STATE_KEYS = Object.freeze([
2981
+ "credential_generation",
2982
+ "gateway_request_origin",
2983
+ "host_access_token",
2984
+ "host_installation_ref",
2985
+ "host_source_ref",
2986
+ "registration_attempt_ref",
2987
+ "schema_version",
2988
+ "status"
2989
+ ]);
2990
+ var HOST_REGISTRATION_STATE_MAX_BYTES = 65536;
2991
+ var HostRegistrationStateError = class extends Error {
2992
+ name = "HostRegistrationStateError";
2993
+ code = "credential";
2994
+ };
2995
+ async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
2996
+ let raw;
2997
+ try {
2998
+ await assertPrivateRegistrationDirectory(dirname2(path), platform, custody);
2999
+ raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
3000
+ } catch (error) {
3001
+ throw registrationReadError(error);
3002
+ }
3003
+ if (Buffer.byteLength(raw, "utf8") > HOST_REGISTRATION_STATE_MAX_BYTES) throw new HostRegistrationStateError(`Host registration state is invalid: ${refusalFact("registration_state_bytes", Buffer.byteLength(raw, "utf8"), `at most ${HOST_REGISTRATION_STATE_MAX_BYTES}`)}.`);
3004
+ let value;
3005
+ try {
3006
+ value = JSON.parse(raw);
3007
+ } catch {
3008
+ throw new HostRegistrationStateError("Host registration state is invalid.");
3009
+ }
3010
+ return decodeHostRegistrationAuthority(value, expectedHostSourceRef);
3011
+ }
3012
+ async function readWindowsRegistration(path, custody) {
3013
+ const bytes = await readPrivateFileWithSecurefs(path, HOST_REGISTRATION_STATE_MAX_BYTES, custody);
3014
+ try {
3015
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
3016
+ } catch {
3017
+ throw new HostRegistrationStateError("Host registration state is invalid.");
3018
+ }
3019
+ }
3020
+ async function readPosixRegistration(path, platform, custody) {
3021
+ const handle = await openNoFollow(path, constants3.O_RDONLY, void 0, platform, custody);
3022
+ try {
3023
+ const stats = await handle.stat();
3024
+ if (!stats.isFile() || !isSelfOwned(stats.uid, platform, handle) || !isPrivateFileMode(stats.mode, platform, handle)) throw new HostRegistrationStateError("Host registration file is not private to its owner.");
3025
+ return await handle.readFile("utf8");
3026
+ } finally {
3027
+ await handle.close();
3028
+ }
3029
+ }
3030
+ function registrationReadError(error) {
3031
+ if (error instanceof HostRegistrationStateError) return error;
3032
+ if (error instanceof SecureFileCustodyError && error.reason === "not_private") return new HostRegistrationStateError("Host registration file is not private to its owner.");
3033
+ return new HostRegistrationStateError("Host registration file is unavailable.");
3034
+ }
3035
+ function decodeHostRegistrationAuthority(value, expectedHostSourceRef) {
3036
+ const keys = HOST_REGISTRATION_STATE_KEYS;
3037
+ const fieldCount = record(value) ? Object.keys(value).length : 0;
3038
+ const missing = record(value) ? keys.filter((key) => !Object.hasOwn(value, key)).length : keys.length;
3039
+ if (!record(value) || fieldCount !== keys.length || missing !== 0) throw new HostRegistrationStateError(`Host registration state is invalid or does not match this Relay: ${refusalFacts([{ name: "registration_field_count", value: fieldCount, expected: `exactly ${keys.length}` }, { name: "missing_registration_field_count", value: missing, expected: "0" }])}.`);
3040
+ if (!validRegistrationIdentity(value, expectedHostSourceRef)) throw new HostRegistrationStateError(`Host registration state is invalid or does not match this Relay: ${refusalFacts([{ name: "schema_version", value: value.schema_version, expected: HOST_REGISTRATION_STATE_SCHEMA }, { name: "status", value: value.status, expected: "active" }, { name: "host_source_ref", value: value.host_source_ref, expected: expectedHostSourceRef }, { name: "registration_attempt_ref", value: value.registration_attempt_ref, expected: "host-registration-attempt:<uuid>" }, { name: "host_installation_ref", value: value.host_installation_ref, expected: "host-installation:<uuid>" }])}.`);
3041
+ if (!validRegistrationCredential(value)) throw new HostRegistrationStateError(`Host registration state is invalid or does not match this Relay: ${refusalFacts([{ name: "credential_generation", value: value.credential_generation, expected: "a positive safe integer" }, { name: "host_access_token_matches_registered_shape", value: validHostAccessToken(value.host_access_token), expected: "true" }])}.`);
3042
+ if (!validGatewayOrigin(value.gateway_request_origin)) throw new HostRegistrationStateError(`Host registration state is invalid or does not match this Relay: ${refusalFact("gateway_request_origin", value.gateway_request_origin, "an HTTPS origin or explicit-port loopback HTTP origin")}.`);
3043
+ return { gateway_request_origin: value.gateway_request_origin, host_access_token: value.host_access_token };
3044
+ }
3045
+ function validRegistrationIdentity(value, expectedHostSourceRef) {
3046
+ return value.schema_version === HOST_REGISTRATION_STATE_SCHEMA && value.status === "active" && value.host_source_ref === expectedHostSourceRef && typeof value.registration_attempt_ref === "string" && CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN.test(value.registration_attempt_ref) && typeof value.host_installation_ref === "string" && CEAL_HOST_INSTALLATION_REF_PATTERN.test(value.host_installation_ref) && typeof value.host_source_ref === "string" && hostSourceUuid(value.host_source_ref) !== null;
3047
+ }
3048
+ function validRegistrationCredential(value) {
3049
+ return Number.isSafeInteger(value.credential_generation) && Number(value.credential_generation) > 0 && validHostAccessToken(value.host_access_token);
3050
+ }
3051
+ function validHostAccessToken(value) {
3052
+ return typeof value === "string" && CEAL_HOST_ACCESS_TOKEN_PATTERN.test(value);
3053
+ }
3054
+ function validGatewayOrigin(value) {
3055
+ try {
3056
+ if (typeof value !== "string" || /\s|\0/u.test(value)) return false;
3057
+ const parsed = new URL(value);
3058
+ const hostname = parsed.hostname.toLowerCase().replace(/\.+$/u, "");
3059
+ return hostname !== "" && validGatewayPort(parsed.port) && (loopbackHttpOrigin(parsed, hostname) || parsed.protocol === "https:") && cleanOriginPath(parsed) && bareOriginSuffix(value);
3060
+ } catch {
3061
+ return false;
3062
+ }
3063
+ }
3064
+ function loopbackHttpOrigin(parsed, hostname) {
3065
+ return parsed.protocol === "http:" && parsed.port !== "" && (hostname === "127.0.0.1" || hostname === "[::1]");
3066
+ }
3067
+ function validGatewayPort(port) {
3068
+ if (port === "") return true;
3069
+ const numeric = Number(port);
3070
+ return Number.isInteger(numeric) && numeric >= 1 && numeric <= 65535;
3071
+ }
3072
+ function cleanOriginPath(parsed) {
3073
+ return parsed.username === "" && parsed.password === "" && parsed.pathname === "/" && parsed.search === "" && parsed.hash === "";
3074
+ }
3075
+ function bareOriginSuffix(value) {
3076
+ const schemeEnd = value.indexOf("://");
3077
+ const authority = schemeEnd < 0 ? "" : value.slice(schemeEnd + 3);
3078
+ const suffixOffset = authority.search(/[\\/?#]/u);
3079
+ const rawSuffix = suffixOffset < 0 ? "" : authority.slice(suffixOffset);
3080
+ return rawSuffix === "" || rawSuffix === "/";
3081
+ }
3082
+ async function assertPrivateRegistrationDirectory(path, platform, custody) {
3083
+ if (!await isPrivateDirectory(path, platform, custody)) throw new HostRegistrationStateError("Host registration directory is not private to its owner.");
3084
+ }
3085
+ function record(value) {
3086
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3087
+ }
3088
+
3089
+ // host/relay/src/host-usage-facts-store.ts
3090
+ import { createHash as createHash5 } from "node:crypto";
3091
+ import { constants as constants4 } from "node:fs";
3092
+ import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3093
+ import { dirname as dirname4, join as join3 } from "node:path";
3094
+
3095
+ // host/relay/src/durable-atomic-replacement.ts
3096
+ import { lstat as lstat3, mkdir, open as open2, rename, unlink } from "node:fs/promises";
3097
+ import { dirname as dirname3 } from "node:path";
3098
+
3099
+ // host/windows-rename-retry.ts
3100
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
3101
+ var RETRY_WINDOW_MS = 1e4;
3102
+ var RETRY_START_DELAY_MS = 100;
3103
+ var RETRY_MAX_DELAY_MS = 2e3;
3104
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
3105
+ var WindowsRenameRetryError = class extends Error {
3106
+ code = "rename_unavailable";
3107
+ constructor(target, attempts, options = {}) {
3108
+ super(`Windows did not permit renaming into place within the bounded retry window: ${target} (after ${attempts} attempts). Wait for the process holding the path to release it, then rerun the same install or update command.`, options);
3109
+ this.name = "WindowsRenameRetryError";
3110
+ }
3111
+ };
3112
+ function resolveRetrySchedule(tuning) {
3113
+ return {
3114
+ windowMs: tuning.windowMs ?? RETRY_WINDOW_MS,
3115
+ startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
3116
+ maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
3117
+ sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
3118
+ now: tuning.now ?? (() => Date.now())
3119
+ };
3120
+ }
3121
+ async function renameWithWindowsRetry(operation, tuning) {
3122
+ const schedule = resolveRetrySchedule(tuning);
3123
+ const deadline = schedule.now() + schedule.windowMs;
3124
+ let delayMs = schedule.startDelayMs;
3125
+ let attempts = 0;
3126
+ for (; ; ) {
3127
+ attempts += 1;
3128
+ try {
3129
+ await operation();
3130
+ return;
3131
+ } catch (error) {
3132
+ if (tuning.platform !== "win32" || !isRetryableRenameError(error)) throw error;
3133
+ await sleepWithinWindow(schedule, deadline, delayMs, () => new WindowsRenameRetryError(tuning.target, attempts, { cause: error }));
3134
+ delayMs = Math.min(delayMs * 2, schedule.maxDelayMs);
3135
+ }
3136
+ }
3137
+ }
3138
+ async function sleepWithinWindow(schedule, deadline, delayMs, exhausted) {
3139
+ if (schedule.now() >= deadline) throw exhausted();
3140
+ await schedule.sleep(Math.min(delayMs, deadline - schedule.now()));
3141
+ if (schedule.now() >= deadline) throw exhausted();
3142
+ }
3143
+ function isRetryableRenameError(error) {
3144
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && RETRYABLE_CODES.has(error.code);
3145
+ }
3146
+
3147
+ // host/relay/src/durable-atomic-replacement.ts
3148
+ var DEFAULT_PORT = {
3149
+ platform: process.platform,
3150
+ mkdir: (path, options) => mkdir(path, options),
3151
+ lstat: (path) => lstat3(path),
3152
+ open_file: (path) => open2(path, "wx", 384),
3153
+ rename,
3154
+ unlink,
3155
+ open_directory: (path) => open2(path),
3156
+ unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
3157
+ };
3158
+ async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
3159
+ const parent = dirname3(target);
3160
+ await port.mkdir(parent, { recursive: true, mode: 448 });
3161
+ const parentStats = await port.lstat(parent);
3162
+ const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
3163
+ const ownerPrivate = port.platform === "win32" || isOwnedBy(parentStats.uid, expectedUid) && isPrivateFileMode(parentStats.mode, port.platform);
3164
+ if (!parentStats.isDirectory() || parentStats.isSymbolicLink() || !ownerPrivate) throw new TypeError(`Host Relay durable-state directory is unsafe: ${refusalFacts([{ name: "parent_stats", value: parentStats, expected: "an owner-private directory" }, { name: "platform", value: port.platform }])}.`);
3165
+ const temporary = `${target}.${port.unique_ref()}.new`;
3166
+ let staged;
3167
+ const failures = [];
3168
+ try {
3169
+ staged = await port.open_file(temporary);
3170
+ await staged.writeFile(data, typeof data === "string" ? { encoding: "utf8" } : void 0);
3171
+ await staged.sync();
3172
+ const closing = staged;
3173
+ staged = void 0;
3174
+ await closing.close();
3175
+ await renameWithWindowsRetry(() => port.rename(temporary, target), { ...port.rename_retry, platform: port.platform, target });
3176
+ await syncParentDirectory(parent, port);
3177
+ } catch (error) {
3178
+ failures.push(error);
3179
+ }
3180
+ await closeStaged(staged, failures);
3181
+ await removeTemporary(temporary, port, failures);
3182
+ throwFailures(failures);
3183
+ }
3184
+ async function syncParentDirectory(path, port) {
3185
+ if (port.platform === "win32") return;
3186
+ const handle = await port.open_directory(path);
3187
+ let failure;
3188
+ try {
3189
+ await handle.sync();
3190
+ } catch (error) {
3191
+ if (!directorySyncUnsupported(error)) failure = error;
3192
+ }
3193
+ try {
3194
+ await handle.close();
3195
+ } catch (error) {
3196
+ if (failure === void 0) failure = error;
3197
+ else failure = new AggregateError([failure, error], "Host Relay directory sync and close failed.");
3198
+ }
3199
+ if (failure !== void 0) throw failure;
3200
+ }
3201
+ async function closeStaged(staged, failures) {
3202
+ if (staged !== void 0) try {
3203
+ await staged.close();
3204
+ } catch (error) {
3205
+ failures.push(error);
3206
+ }
3207
+ }
3208
+ async function removeTemporary(path, port, failures) {
3209
+ try {
3210
+ await port.unlink(path);
3211
+ } catch (error) {
3212
+ if (errorCode(error) !== "ENOENT") failures.push(error);
3213
+ }
3214
+ }
3215
+ function throwFailures(failures) {
3216
+ if (failures.length === 1) throw failures[0];
3217
+ if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
3218
+ }
3219
+ function directorySyncUnsupported(error) {
3220
+ return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
3221
+ }
3222
+ function errorCode(error) {
3223
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3224
+ }
3225
+
3226
+ // host/relay/src/host-usage-facts-store.ts
3227
+ var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3228
+ var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3229
+ var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
3230
+ var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
3231
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
3232
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
3233
+ var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
3234
+ var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
3235
+ var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
3236
+ var HostUsageFactsStore = class {
3237
+ root;
3238
+ sessions;
3239
+ batches;
3240
+ platform;
3241
+ custody;
3242
+ afterPendingWrite;
3243
+ afterBatchPublish;
3244
+ sessionDirectoryCursor;
3245
+ constructor(options) {
3246
+ this.root = join3(options.outbox_dir, "usage-facts");
3247
+ this.sessions = join3(this.root, "sessions");
3248
+ this.batches = join3(this.root, "batches");
3249
+ this.platform = options.platform ?? process.platform;
3250
+ this.custody = options.secure_file_custody ?? {};
3251
+ this.afterPendingWrite = options.afterPendingWrite;
3252
+ this.afterBatchPublish = options.afterBatchPublish;
3253
+ }
3254
+ async prepare() {
3255
+ for (const directory of [this.root, this.sessions, this.batches]) {
3256
+ await preparePrivateDirectory(directory, this.platform, this.custody);
3257
+ }
3258
+ }
3259
+ async close() {
3260
+ const cursor = this.sessionDirectoryCursor;
3261
+ this.sessionDirectoryCursor = void 0;
3262
+ await cursor?.close();
3263
+ }
3264
+ async readState(producer, hostSourceRef, hostSessionRef) {
3265
+ await this.prepare();
3266
+ const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3267
+ const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3268
+ if (value === null) return null;
3269
+ validateState(value, producer, hostSourceRef, hostSessionRef);
3270
+ return value;
3271
+ }
3272
+ createState(producer, hostSourceRef, hostSessionRef) {
3273
+ return {
3274
+ schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
3275
+ producer,
3276
+ host_source_ref: hostSourceRef,
3277
+ host_session_ref: hostSessionRef,
3278
+ cursors: {},
3279
+ eligible_batches: [],
3280
+ coverage_gaps: [],
3281
+ coverage_gap_created_at: null
3282
+ };
3283
+ }
3284
+ async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
3285
+ let state = await this.readState(producer, hostSourceRef, hostSessionRef);
3286
+ if (state === null) {
3287
+ state = this.createState(producer, hostSourceRef, hostSessionRef);
3288
+ state = await this.writeCursor(state, sourceSlot, initial);
3289
+ }
3290
+ state = await this.recoverPending(state);
3291
+ if (state.quarantined_reason !== void 0) return null;
3292
+ state = await this.commitCoverageGaps(state, createdAt);
3293
+ const cursor = state.cursors[sourceSlot];
3294
+ return cursor === void 0 ? null : { state, cursor };
3295
+ }
3296
+ async writeCursor(state, sourceSlot, cursor) {
3297
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3298
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3299
+ if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
3300
+ const current = latest.cursors[sourceSlot];
3301
+ if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
3302
+ const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
3303
+ await this.writeState(updated);
3304
+ return updated;
3305
+ });
3306
+ }
3307
+ async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
3308
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3309
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3310
+ return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
3311
+ });
3312
+ }
3313
+ async recoverPending(state) {
3314
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3315
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3316
+ const recovered = await this.finishPendingTransition(latest);
3317
+ await this.sweepOrphanedBatches(recovered);
3318
+ return recovered;
3319
+ });
3320
+ }
3321
+ /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3322
+ async sweepOrphanedBatches(state) {
3323
+ await this.prepare();
3324
+ const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3325
+ await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3326
+ const expected = expectedBatchNames(state);
3327
+ const directory = await opendir(directoryPath);
3328
+ let inspected = 0;
3329
+ let deleted = 0;
3330
+ try {
3331
+ while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
3332
+ const entry = await directory.read();
3333
+ if (entry === null) break;
3334
+ inspected += 1;
3335
+ if (!isOrphanBatchEntry(entry, expected)) continue;
3336
+ await unlink2(join3(directoryPath, entry.name));
3337
+ deleted += 1;
3338
+ }
3339
+ } finally {
3340
+ await directory.close();
3341
+ }
3342
+ if (deleted > 0) await syncDirectory(directoryPath, this.platform);
3343
+ return deleted;
3344
+ }
3345
+ async commitCoverageGaps(state, createdAt) {
3346
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3347
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3348
+ if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
3349
+ const sourceRanges = coverageRanges(latest.coverage_gaps);
3350
+ const canonical = createCealHostUsageBatch({
3351
+ host_source_ref: latest.host_source_ref,
3352
+ host_session_ref: latest.host_session_ref,
3353
+ created_at: latest.coverage_gap_created_at ?? createdAt,
3354
+ source_ranges: sourceRanges,
3355
+ facts: [],
3356
+ coverage_gaps: latest.coverage_gaps
3357
+ });
3358
+ const cursor = firstCursor(latest);
3359
+ if (cursor === null) return latest;
3360
+ return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
3361
+ });
3362
+ }
3363
+ async nextUploadCandidate(producer, hostSourceRef) {
3364
+ await this.prepare();
3365
+ const names = await this.readNextSessionNames();
3366
+ for (const name of names) {
3367
+ const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3368
+ if (state === null) continue;
3369
+ validateStateOwner(state, producer, hostSourceRef);
3370
+ let validated = state;
3371
+ if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
3372
+ else validated = await this.recoverPending(validated);
3373
+ if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
3374
+ const next = validated.eligible_batches[0];
3375
+ if (next === void 0) continue;
3376
+ const batch = await this.readBatch(validated, next.batch_ref);
3377
+ return { state: validated, batch };
3378
+ }
3379
+ return null;
3380
+ }
3381
+ async readNextSessionNames() {
3382
+ this.sessionDirectoryCursor ??= await opendir(this.sessions);
3383
+ const names = [];
3384
+ let inspected = 0;
3385
+ while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
3386
+ const entry = await this.sessionDirectoryCursor.read();
3387
+ if (entry === null) {
3388
+ await this.sessionDirectoryCursor.close();
3389
+ this.sessionDirectoryCursor = void 0;
3390
+ break;
3391
+ }
3392
+ inspected += 1;
3393
+ if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
3394
+ }
3395
+ return names;
3396
+ }
3397
+ async acknowledge(state, batchRef) {
3398
+ await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3399
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3400
+ if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
3401
+ const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
3402
+ if (remaining.length === latest.eligible_batches.length) return;
3403
+ await this.writeState({ ...latest, eligible_batches: remaining });
3404
+ await removeFileIfPresent(this.batchPath(state, batchRef));
3405
+ });
3406
+ }
3407
+ async quarantine(state, reason) {
3408
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3409
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3410
+ const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
3411
+ await this.writeState(updated);
3412
+ return updated;
3413
+ });
3414
+ }
3415
+ async retireCursor(state, sourceSlot, cursor, gap) {
3416
+ return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
3417
+ }
3418
+ async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
3419
+ if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
3420
+ if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
3421
+ const queued = await this.publishTransitionBatch(state, batch);
3422
+ const pending = {
3423
+ source_slot: sourceSlot,
3424
+ before_cursor: beforeCursor,
3425
+ after_cursor: afterCursor,
3426
+ batch_ref: queued.batch_ref,
3427
+ batch_bytes: queued.batch_bytes,
3428
+ gap_delta: [...gapDelta, ...queued.overflow_gaps],
3429
+ clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
3430
+ };
3431
+ const prepared = { ...state, pending_transition: pending };
3432
+ await this.writeState(prepared);
3433
+ await this.afterPendingWrite?.();
3434
+ return await this.finishPendingTransition(prepared);
3435
+ }
3436
+ async publishTransitionBatch(state, batch) {
3437
+ if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
3438
+ const serialized = serializeBatch(batch);
3439
+ if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
3440
+ await this.writeImmutableBatch(state, batch, serialized);
3441
+ await this.afterBatchPublish?.();
3442
+ return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
3443
+ }
3444
+ async finishPendingTransition(state) {
3445
+ const pending = state.pending_transition;
3446
+ if (pending === void 0 || state.quarantined_reason !== void 0) return state;
3447
+ const current = state.cursors[pending.source_slot];
3448
+ if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
3449
+ const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
3450
+ await this.writeState(quarantined);
3451
+ return quarantined;
3452
+ }
3453
+ let cursors = state.cursors;
3454
+ if (!cursorMatches(current, pending.after_cursor)) {
3455
+ const next = { ...state.cursors };
3456
+ if (pending.after_cursor === null) delete next[pending.source_slot];
3457
+ else next[pending.source_slot] = pending.after_cursor;
3458
+ cursors = next;
3459
+ }
3460
+ const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
3461
+ const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
3462
+ const { pending_transition: _pendingTransition, ...settledState } = state;
3463
+ const updated = {
3464
+ ...settledState,
3465
+ cursors,
3466
+ eligible_batches: eligible,
3467
+ coverage_gaps: gaps,
3468
+ coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
3469
+ };
3470
+ await this.writeState(updated);
3471
+ return updated;
3472
+ }
3473
+ async writeImmutableBatch(state, batch, bytes) {
3474
+ const path = this.batchPath(state, batch.batch_ref);
3475
+ await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
3476
+ const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3477
+ if (existing !== null) {
3478
+ if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3479
+ await syncExistingFile(path, this.platform);
3480
+ return;
3481
+ }
3482
+ if (this.platform === "win32") {
3483
+ await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
3484
+ return;
3485
+ }
3486
+ let handle;
3487
+ try {
3488
+ handle = await openNoFollow(path, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384, this.platform);
3489
+ await handle.writeFile(bytes);
3490
+ await handle.sync();
3491
+ await handle.close();
3492
+ handle = void 0;
3493
+ await syncDirectory(dirname4(path), this.platform);
3494
+ } catch (error) {
3495
+ await handle?.close().catch(() => void 0);
3496
+ if (errorCode2(error) === "EEXIST") {
3497
+ const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3498
+ if (winner !== null && winner.equals(bytes)) {
3499
+ await syncExistingFile(path, this.platform);
3500
+ return;
3501
+ }
3502
+ throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3503
+ }
3504
+ await removeFileIfPresent(path).catch(() => void 0);
3505
+ throw error;
3506
+ }
3507
+ }
3508
+ async readBatch(state, batchRef) {
3509
+ const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3510
+ if (bytes === null) throw new Error("Host usage facts batch object is missing.");
3511
+ let value;
3512
+ try {
3513
+ value = JSON.parse(bytes.toString("utf8"));
3514
+ } catch {
3515
+ throw new Error("Host usage facts batch object is malformed.");
3516
+ }
3517
+ validateCealHostUsageBatch(value);
3518
+ if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
3519
+ return value;
3520
+ }
3521
+ async writeState(state) {
3522
+ validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
3523
+ const bytes = Buffer.from(JSON.stringify(state), "utf8");
3524
+ if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
3525
+ await this.prepare();
3526
+ const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
3527
+ if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
3528
+ else await durableAtomicReplace(path, bytes);
3529
+ }
3530
+ async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
3531
+ const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3532
+ const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
3533
+ let release;
3534
+ const gate = new Promise((resolve) => {
3535
+ release = resolve;
3536
+ });
3537
+ const tail = previous.then(() => gate);
3538
+ SESSION_TRANSITION_TAILS.set(key, tail);
3539
+ await previous;
3540
+ try {
3541
+ return await run();
3542
+ } finally {
3543
+ release?.();
3544
+ if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
3545
+ }
3546
+ }
3547
+ sessionPath(producer, hostSourceRef, hostSessionRef) {
3548
+ return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3549
+ }
3550
+ batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3551
+ const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3552
+ return join3(this.batches, sessionName.slice(0, -5));
3553
+ }
3554
+ batchPath(state, batchRef) {
3555
+ return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3556
+ }
3557
+ };
3558
+ function serializeBatch(batch) {
3559
+ validateCealHostUsageBatch(batch);
3560
+ return Buffer.from(JSON.stringify(batch), "utf8");
3561
+ }
3562
+ function batchFileName(batchRef) {
3563
+ const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
3564
+ if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
3565
+ return `${digest2}.json`;
3566
+ }
3567
+ function expectedBatchNames(state) {
3568
+ const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
3569
+ const pending = state.pending_transition?.batch_ref;
3570
+ if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
3571
+ return expected;
3572
+ }
3573
+ function isOrphanBatchEntry(entry, expected) {
3574
+ return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
3575
+ }
3576
+ function hasOutboxCapacity(state, bytes) {
3577
+ const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
3578
+ return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
3579
+ }
3580
+ function overflowCoverageGaps(batch) {
3581
+ const count = batch.facts.length;
3582
+ const gaps = [...batch.coverage_gaps];
3583
+ if (count > 0) gaps.push({ reason: "outbox_capacity", source_file_ref: batch.source_ranges[0]?.source_file_ref ?? null, start_offset: batch.source_ranges[0]?.start_offset ?? null, end_offset: batch.source_ranges[0]?.end_offset ?? null, omitted_count: count });
3584
+ return gaps;
3585
+ }
3586
+ function appendEligible(existing, next) {
3587
+ if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
3588
+ if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
3589
+ return [...existing, next];
3590
+ }
3591
+ function appendCoverageGaps(existing, added) {
3592
+ if (added.length === 0) return existing;
3593
+ const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
3594
+ for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
3595
+ const combined = [...byIdentity.values()];
3596
+ if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
3597
+ const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
3598
+ return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
3599
+ }
3600
+ function coverageRanges(gaps) {
3601
+ const ranges = /* @__PURE__ */ new Map();
3602
+ for (const gap of gaps) {
3603
+ if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
3604
+ const current = ranges.get(gap.source_file_ref);
3605
+ if (current === void 0) ranges.set(gap.source_file_ref, { source_file_ref: gap.source_file_ref, start_offset: gap.start_offset, end_offset: gap.end_offset });
3606
+ else ranges.set(gap.source_file_ref, { ...current, start_offset: Math.min(current.start_offset, gap.start_offset), end_offset: Math.max(current.end_offset, gap.end_offset) });
3607
+ }
3608
+ return [...ranges.values()];
3609
+ }
3610
+ function firstCursor(state) {
3611
+ const entry = Object.entries(state.cursors)[0];
3612
+ return entry === void 0 ? null : entry;
3613
+ }
3614
+ function sameCursor(left, right) {
3615
+ return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
3616
+ }
3617
+ function cursorMatches(left, right) {
3618
+ return right === null ? left === void 0 : sameCursor(left, right);
3619
+ }
3620
+ function validateState(value, producer, hostSourceRef, hostSessionRef) {
3621
+ validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
3622
+ validateStateShape(value);
3623
+ validateStateLimits(value);
3624
+ validateStateContents(value);
3625
+ }
3626
+ function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
3627
+ if (!isRecord3(value) || value.schema_version !== HOST_USAGE_FACTS_STATE_SCHEMA || value.producer !== producer || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new Error("Host usage facts state identity is invalid.");
3628
+ }
3629
+ function validateStateLimits(value) {
3630
+ if (Object.keys(value.cursors).length > HOST_USAGE_FACTS_MAX_SOURCE_CURSORS || value.eligible_batches.length > HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES || value.coverage_gaps.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) throw new Error("Host usage facts state exceeds its bounds.");
3631
+ }
3632
+ function validateStateContents(value) {
3633
+ for (const [slot, cursor] of Object.entries(value.cursors)) {
3634
+ validateSourceSlot(slot);
3635
+ validateFileCursor(cursor);
3636
+ }
3637
+ for (const item of value.eligible_batches) validateEligibleBatch(item);
3638
+ if (value.pending_transition !== void 0) validatePending(value.pending_transition);
3639
+ for (const gap of value.coverage_gaps) validateGap(gap);
3640
+ validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
3641
+ }
3642
+ function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
3643
+ if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
3644
+ if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
3645
+ }
3646
+ function validateStateOwner(value, producer, hostSourceRef) {
3647
+ if (!isRecord3(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
3648
+ validateState(value, producer, hostSourceRef, String(value.host_session_ref));
3649
+ }
3650
+ function validateStateShape(value) {
3651
+ const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
3652
+ const optional = ["pending_transition", "quarantined_reason"];
3653
+ if (required.some((key) => !Object.hasOwn(value, key)) || Object.keys(value).some((key) => !required.includes(key) && !optional.includes(key))) throw new Error("Host usage facts state keys are invalid.");
3654
+ if (!isRecord3(value.cursors) || !Array.isArray(value.eligible_batches) || !Array.isArray(value.coverage_gaps) || value.coverage_gap_created_at !== null && typeof value.coverage_gap_created_at !== "string") throw new Error("Host usage facts state collections are invalid.");
3655
+ }
3656
+ function validateFileCursor(value) {
3657
+ if (!isRecord3(value) || !sameKeys(value, ["source_file_ref", "device", "inode", "offset", "anchor_start", "anchor_sha256", "last_ordinal", "host_turn_ref", "native_turn_id", "requested_model", "codex_total_usage", "skipping_oversized_line"])) throw new Error("Host usage facts source cursor is invalid.");
3658
+ validateCursorIdentity(value);
3659
+ validateCursorOffsets(value);
3660
+ validateCursorContext(value);
3661
+ if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
3662
+ if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
3663
+ }
3664
+ function validateCursorIdentity(value) {
3665
+ if (![value.source_file_ref, value.device, value.inode].every((part) => typeof part === "string" && part.length > 0 && part.length <= HOST_USAGE_FACTS_REF_MAX_LENGTH)) throw new Error("Host usage facts source cursor identity is invalid.");
3666
+ }
3667
+ function validateCursorOffsets(value) {
3668
+ if (!/^host-source-file:[a-f0-9]{64}$/u.test(String(value.source_file_ref)) || !safeInteger2(value.offset) || !safeInteger2(value.anchor_start) || Number(value.anchor_start) > Number(value.offset) || !/^[a-f0-9]{64}$/u.test(String(value.anchor_sha256)) || value.last_ordinal !== null && !safeInteger2(value.last_ordinal)) throw new Error("Host usage facts source cursor fields are invalid.");
3669
+ }
3670
+ function validateCursorContext(value) {
3671
+ if (!validOptionalText(value.host_turn_ref, HOST_USAGE_FACTS_REF_MAX_LENGTH) || !validOptionalText(value.native_turn_id, HOST_USAGE_FACTS_REF_MAX_LENGTH) || !validOptionalText(value.requested_model, 256)) throw new Error("Host usage facts source context is invalid.");
3672
+ }
3673
+ function validOptionalText(value, maximum) {
3674
+ return value === null || typeof value === "string" && value.length <= maximum;
3675
+ }
3676
+ function validateCodexCounts(value) {
3677
+ if (!isRecord3(value) || !sameKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) throw new Error("Host usage facts cumulative usage is invalid.");
3678
+ if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
3679
+ }
3680
+ function validatePending(value) {
3681
+ if (!isRecord3(value) || !sameKeys(value, ["source_slot", "before_cursor", "after_cursor", "batch_ref", "batch_bytes", "gap_delta", "clear_coverage_gaps"])) throw new Error("Host usage facts pending transition is invalid.");
3682
+ validatePendingCursors(value);
3683
+ validatePendingBatch(value);
3684
+ validatePendingFields(value);
3685
+ for (const gap of value.gap_delta) validateGap(gap);
3686
+ }
3687
+ function validatePendingCursors(value) {
3688
+ validateSourceSlot(value.source_slot);
3689
+ validateFileCursor(value.before_cursor);
3690
+ if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
3691
+ }
3692
+ function validatePendingBatch(value) {
3693
+ if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
3694
+ }
3695
+ function validatePendingFields(value) {
3696
+ if (!safeInteger2(value.batch_bytes) || !Array.isArray(value.gap_delta) || value.gap_delta.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS || typeof value.clear_coverage_gaps !== "boolean") throw new Error("Host usage facts pending transition fields are invalid.");
3697
+ }
3698
+ function validateEligibleBatch(value) {
3699
+ if (!isRecord3(value) || !sameKeys(value, ["batch_ref", "bytes"]) || !isCealHostUsageBatchReference(value.batch_ref) || !safeInteger2(value.bytes) || Number(value.bytes) < 1 || Number(value.bytes) > CEAL_HOST_USAGE_BATCH_MAX_BYTES) throw new Error("Host usage facts eligible batch is invalid.");
3700
+ }
3701
+ function validateGap(value) {
3702
+ try {
3703
+ validateCealHostUsageCoverageGap(value);
3704
+ } catch {
3705
+ throw new Error("Host usage facts coverage gap is invalid.");
3706
+ }
3707
+ }
3708
+ function validateSourceSlot(value) {
3709
+ if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
3710
+ }
3711
+ async function readOptionalJson(path, maxBytes, platform, custody) {
3712
+ const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
3713
+ if (bytes === null) return null;
3714
+ try {
3715
+ return JSON.parse(bytes.toString("utf8"));
3716
+ } catch {
3717
+ throw new Error("Host usage facts state JSON is malformed.");
3718
+ }
3719
+ }
3720
+ async function readOptionalBytes(path, maxBytes, platform, custody) {
3721
+ if (platform === "win32") {
3722
+ try {
3723
+ return await readPrivateFileWithSecurefs(path, maxBytes, custody);
3724
+ } catch (error) {
3725
+ if (errorCode2(error) === "ENOENT") return null;
3726
+ throw error;
3727
+ }
3728
+ }
3729
+ let handle;
3730
+ try {
3731
+ handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
3732
+ const stats = await handle.stat();
3733
+ if (!stats.isFile() || !isSelfOwned(stats.uid, platform, handle) || !isPrivateFileMode(stats.mode, platform, handle) || stats.size > maxBytes) throw new Error("Host usage facts file custody or size is invalid.");
3734
+ return await handle.readFile();
3735
+ } catch (error) {
3736
+ if (errorCode2(error) === "ENOENT") return null;
3737
+ throw error;
3738
+ } finally {
3739
+ await handle?.close();
3740
+ }
3741
+ }
3742
+ async function preparePrivateDirectory(path, platform, custody) {
3743
+ if (platform === "win32") {
3744
+ await ensurePrivateDirectoryWithSecurefs(path, custody);
3745
+ return;
3746
+ }
3747
+ await mkdir2(path, { recursive: true, mode: 448 });
3748
+ if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3749
+ }
3750
+ async function syncExistingFile(path, platform) {
3751
+ const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
3752
+ try {
3753
+ await handle.sync();
3754
+ } finally {
3755
+ await handle.close();
3756
+ }
3757
+ await syncDirectory(dirname4(path), platform);
3758
+ }
3759
+ async function syncDirectory(path, platform) {
3760
+ if (platform === "win32") return;
3761
+ const handle = await open3(path, constants4.O_RDONLY);
3762
+ try {
3763
+ await handle.sync();
3764
+ } finally {
3765
+ await handle.close();
3766
+ }
3767
+ }
3768
+ async function removeFileIfPresent(path) {
3769
+ try {
3770
+ await unlink2(path);
3771
+ } catch (error) {
3772
+ if (errorCode2(error) !== "ENOENT") throw error;
3773
+ }
2400
3774
  }
2401
- function producerIdentityFacts(sourceRef, installationRef, epoch) {
2402
- const facts = [];
2403
- if (!SAFE_REF2.test(sourceRef)) facts.push({ name: "host_source_ref", value: "wrong_type", expected: "a safe reference" });
2404
- if (!SAFE_REF2.test(installationRef)) facts.push({ name: "producer_installation_ref", value: "wrong_type", expected: "a safe reference" });
2405
- if (!positive(epoch, 2147483647)) facts.push({ name: "producer_epoch", value: "wrong_type", expected: "a positive integer" });
2406
- return facts;
3775
+ function sameKeys(value, expected) {
3776
+ return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
2407
3777
  }
2408
- function validateIntervals(reconcile, retry, timeout, error) {
2409
- if (!boundedMilliseconds(reconcile) || !boundedMilliseconds(retry) || !boundedMilliseconds(timeout)) throw error("invalid_config", refusalFacts(producerIntervalFacts(reconcile, retry, timeout)));
2410
- return [reconcile, retry, timeout];
3778
+ function isRecord3(value) {
3779
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2411
3780
  }
2412
- function producerIntervalFacts(reconcile, retry, timeout) {
2413
- const facts = [];
2414
- if (!boundedMilliseconds(reconcile)) facts.push({ name: "reconcile_interval_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
2415
- if (!boundedMilliseconds(retry)) facts.push({ name: "retry_backoff_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
2416
- if (!boundedMilliseconds(timeout)) facts.push({ name: "ipc_timeout_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
2417
- return facts;
3781
+ function safeInteger2(value) {
3782
+ return Number.isSafeInteger(value) && Number(value) >= 0;
2418
3783
  }
2419
- function hasConfigKeys(value, required, tolerated = []) {
2420
- return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || tolerated.includes(key) || Object.hasOwn(HOST_PRODUCER_TIMING_DEFAULTS, key));
3784
+ function validTimestamp(value) {
3785
+ return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
2421
3786
  }
2422
- function isRecord2(value) {
2423
- return value !== null && typeof value === "object" && !Array.isArray(value);
3787
+ function errorCode2(error) {
3788
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
2424
3789
  }
2425
- function positive(value, maximum) {
2426
- return Number.isSafeInteger(value) && Number(value) > 0 && Number(value) <= maximum;
3790
+ function sha2562(value) {
3791
+ return createHash5("sha256").update(value, "utf8").digest("hex");
2427
3792
  }
2428
- function boundedMilliseconds(value) {
2429
- return positive(value, 6e4) && Number(value) >= 25;
3793
+
3794
+ // host/service-log.ts
3795
+ import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
3796
+ import { dirname as dirname5, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
3797
+
3798
+ // host/service-log-delivery.ts
3799
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
3800
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
3801
+ setImmediate(flush);
3802
+ }, onDeliveryGap = () => void 0) {
3803
+ const pending = [];
3804
+ const highWaterMark = stream.writableHighWaterMark;
3805
+ const byteBudget = highWaterMark + highWaterMark;
3806
+ let pendingBytes = 0;
3807
+ let droppedLines = 0;
3808
+ let flushScheduled = false;
3809
+ let waitingForDrain = false;
3810
+ let closed = !stream.writable;
3811
+ function stop() {
3812
+ if (closed) return;
3813
+ closed = true;
3814
+ pending.length = 0;
3815
+ pendingBytes = 0;
3816
+ stream.off("drain", onDrain);
3817
+ stream.off("close", onTerminal);
3818
+ stream.off("finish", onTerminal);
3819
+ stream.off("error", onError);
3820
+ }
3821
+ function onTerminal() {
3822
+ stop();
3823
+ }
3824
+ function onError() {
3825
+ stop();
3826
+ }
3827
+ function onDrain() {
3828
+ waitingForDrain = false;
3829
+ scheduleFlush();
3830
+ }
3831
+ function scheduleFlush() {
3832
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
3833
+ flushScheduled = true;
3834
+ let scheduling = true;
3835
+ let invokedSynchronously = false;
3836
+ try {
3837
+ schedule(() => {
3838
+ if (scheduling) {
3839
+ invokedSynchronously = true;
3840
+ return;
3841
+ }
3842
+ flushScheduled = false;
3843
+ flush();
3844
+ });
3845
+ } catch {
3846
+ flushScheduled = false;
3847
+ stop();
3848
+ return;
3849
+ }
3850
+ scheduling = false;
3851
+ if (invokedSynchronously) {
3852
+ flushScheduled = false;
3853
+ stop();
3854
+ }
3855
+ }
3856
+ function flush() {
3857
+ if (closed) return;
3858
+ if (!stream.writable) {
3859
+ stop();
3860
+ return;
3861
+ }
3862
+ while (pending.length > 0) {
3863
+ if (stream.writableNeedDrain) {
3864
+ if (!waitingForDrain) {
3865
+ waitingForDrain = true;
3866
+ stream.once("drain", onDrain);
3867
+ }
3868
+ return;
3869
+ }
3870
+ const next = pending.shift();
3871
+ if (next === void 0) return;
3872
+ pendingBytes -= next.bytes;
3873
+ let accepted;
3874
+ try {
3875
+ accepted = stream.write(next.line);
3876
+ } catch {
3877
+ stop();
3878
+ return;
3879
+ }
3880
+ if (!accepted) {
3881
+ waitingForDrain = true;
3882
+ stream.once("drain", onDrain);
3883
+ return;
3884
+ }
3885
+ }
3886
+ if (droppedLines > 0) {
3887
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
3888
+ `;
3889
+ droppedLines = 0;
3890
+ try {
3891
+ onDeliveryGap(line);
3892
+ } catch {
3893
+ }
3894
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
3895
+ pendingBytes += Buffer.byteLength(line, "utf8");
3896
+ flush();
3897
+ }
3898
+ }
3899
+ stream.on("close", onTerminal);
3900
+ stream.on("finish", onTerminal);
3901
+ stream.on("error", onError);
3902
+ return (line) => {
3903
+ if (closed) return;
3904
+ const bytes = Buffer.byteLength(line, "utf8");
3905
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
3906
+ droppedLines += 1;
3907
+ scheduleFlush();
3908
+ return;
3909
+ }
3910
+ pending.push({ line, bytes });
3911
+ pendingBytes += bytes;
3912
+ scheduleFlush();
3913
+ };
2430
3914
  }
2431
3915
 
3916
+ // host/invocation-authentication-client-command.ts
3917
+ var HOST_OWNED_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){0,7}$/u;
3918
+ function isHostOwnedFailureCode(value) {
3919
+ return typeof value === "string" && HOST_OWNED_CODE.test(value);
3920
+ }
3921
+ var DOCTOR_FLAGS = Object.freeze({
3922
+ "--expected-sha256": "expected_sha256",
3923
+ "--expected-source-commit": "expected_source_commit",
3924
+ "--expected-instance-ref": "expected_instance_ref"
3925
+ });
3926
+
2432
3927
  // host/service-log.ts
2433
- import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
2434
- import { dirname as dirname2, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
2435
3928
  var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
2436
3929
  var HOST_SERVICE_LOG_ARGUMENT = "--ceal-host-service-log";
2437
3930
  var HostServiceLogArgumentError = class extends Error {
@@ -2450,17 +3943,30 @@ function consumeHostServiceLogArgument(args, platform = process.platform) {
2450
3943
  if (indexes.length !== 1 || path === void 0 || !pathApi.isAbsolute(path) || pathApi.normalize(path) !== path) throw new HostServiceLogArgumentError();
2451
3944
  return { args: [...args.slice(0, index), ...args.slice(index + 2)], path };
2452
3945
  }
3946
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
3947
+ void persistHostServiceLogLine(line);
3948
+ });
2453
3949
  function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
2454
- const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...event === "watcher_scan_failed" && failure_kind !== void 0 ? { failure_kind } : {}, ...event === "watcher_scan_failed" && cause !== void 0 ? { cause } : {} })}
3950
+ const details = diagnosticDetails(event, failure_kind, cause);
3951
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
2455
3952
  `;
2456
3953
  try {
2457
3954
  (sink ?? defaultHostServiceDiagnosticSink)(line);
2458
3955
  } catch {
2459
3956
  }
2460
3957
  }
3958
+ function diagnosticDetails(event, failureKind, cause) {
3959
+ if (event === "watcher_scan_failed") return {
3960
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3961
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
3962
+ };
3963
+ return validDiagnosticCause(cause, event) ? { cause } : {};
3964
+ }
3965
+ function validDiagnosticCause(cause, event) {
3966
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
3967
+ }
2461
3968
  function defaultHostServiceDiagnosticSink(line) {
2462
3969
  writeHostServiceLogLine(line);
2463
- process.stderr.write(line);
2464
3970
  }
2465
3971
  var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
2466
3972
  var HOST_SERVICE_LOG_CHECK_INTERVAL_MS = 6e4;
@@ -2489,7 +3995,7 @@ function boundHostServiceLog(environment = process.env) {
2489
3995
  ready.then(() => rotateHostServiceLog(path)).catch((error) => {
2490
3996
  if (reported) return;
2491
3997
  reported = true;
2492
- process.stderr.write(`[host-service-log] rotation_failed code=${errorCode(error)}
3998
+ writeHostServiceLogLine(`[host-service-log] rotation_failed code=${errorCode3(error)}
2493
3999
  `);
2494
4000
  });
2495
4001
  };
@@ -2499,10 +4005,22 @@ function boundHostServiceLog(environment = process.env) {
2499
4005
  return () => clearInterval(timer);
2500
4006
  }
2501
4007
  function writeHostServiceLogLine(line, environment = process.env) {
4008
+ void persistHostServiceLogLine(line, environment);
4009
+ defaultHostServiceLogDelivery(line);
4010
+ }
4011
+ async function writeHostServiceCommandResult(schemaVersion, result, sink) {
4012
+ const line = `${JSON.stringify({ schema_version: schemaVersion, ...result })}
4013
+ `;
4014
+ const serviceLine = `${JSON.stringify({ schema_version: schemaVersion, ok: result.ok, ...!result.ok ? { code: isHostOwnedFailureCode(result.code) ? result.code : "host_failure_unclassified" } : {} })}
4015
+ `;
4016
+ await persistHostServiceLogLine(serviceLine);
4017
+ sink(line);
4018
+ }
4019
+ async function persistHostServiceLogLine(line, environment = process.env) {
2502
4020
  if (process.platform !== "win32") return;
2503
4021
  const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
2504
4022
  if (path === void 0 || !win325.isAbsolute(path) || win325.normalize(path) !== path) return;
2505
- void appendHostServiceLogLine(path, line).catch(() => void 0);
4023
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
2506
4024
  }
2507
4025
  async function appendHostServiceLogLine(path, line) {
2508
4026
  if (!isAbsolute(path)) return;
@@ -2512,10 +4030,10 @@ async function appendHostServiceLogLine(path, line) {
2512
4030
  var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
2513
4031
  var hostServiceLogDirectories = /* @__PURE__ */ new Map();
2514
4032
  function ensureHostServiceLogDirectory(path) {
2515
- const directory = dirname2(path);
4033
+ const directory = dirname5(path);
2516
4034
  const existing = hostServiceLogDirectories.get(directory);
2517
4035
  if (existing !== void 0) return existing;
2518
- const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
4036
+ const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
2519
4037
  hostServiceLogDirectories.delete(directory);
2520
4038
  throw error;
2521
4039
  });
@@ -2523,21 +4041,97 @@ function ensureHostServiceLogDirectory(path) {
2523
4041
  return pending;
2524
4042
  }
2525
4043
  function isNotFound(error) {
2526
- return errorCode(error) === "ENOENT";
4044
+ return errorCode3(error) === "ENOENT";
2527
4045
  }
2528
- function errorCode(error) {
4046
+ function errorCode3(error) {
2529
4047
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unknown";
2530
4048
  }
2531
4049
 
4050
+ // host/relay/src/host-usage-facts-uploader.ts
4051
+ var HostUsageFactsUploader = class {
4052
+ options;
4053
+ store;
4054
+ constructor(options) {
4055
+ if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
4056
+ this.options = options;
4057
+ this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
4058
+ }
4059
+ async close() {
4060
+ await this.store.close();
4061
+ }
4062
+ async uploadOne(signal) {
4063
+ const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4064
+ if (candidate === null) return false;
4065
+ const registration = await readHostRegistrationAuthority(this.options.registration_state_file, this.options.host_source_ref, this.options.store_options?.platform, this.options.store_options?.secure_file_custody);
4066
+ const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4067
+ const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4068
+ const response2 = await (this.options.fetch ?? fetch)(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4069
+ method: "POST",
4070
+ headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4071
+ body: JSON.stringify(candidate.batch),
4072
+ signal: requestSignal
4073
+ });
4074
+ if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
4075
+ await response2.body?.cancel().catch(() => void 0);
4076
+ throw new Error("Gateway did not acknowledge the Host usage facts batch.");
4077
+ }
4078
+ await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
4079
+ return true;
4080
+ }
4081
+ };
4082
+ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4083
+ const uploader = new HostUsageFactsUploader(options);
4084
+ let delay = 500;
4085
+ let failures = 0;
4086
+ try {
4087
+ while (!signal.aborted) {
4088
+ try {
4089
+ await options.capture_next?.();
4090
+ } catch {
4091
+ writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
4092
+ }
4093
+ if (signal.aborted) return;
4094
+ try {
4095
+ const uploaded = await uploader.uploadOne(signal);
4096
+ failures = 0;
4097
+ delay = uploaded ? 100 : 1e3;
4098
+ } catch {
4099
+ if (signal.aborted) return;
4100
+ failures += 1;
4101
+ delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
4102
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4103
+ }
4104
+ if (!signal.aborted) await wait(signal, delay);
4105
+ }
4106
+ } finally {
4107
+ await uploader.close().catch(() => void 0);
4108
+ }
4109
+ }
4110
+
2532
4111
  // host/relay/src/host-producer-core.ts
2533
- import { createHash as createHash4 } from "node:crypto";
4112
+ import { createHash as createHash6 } from "node:crypto";
2534
4113
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
2535
4114
  function isHostTranscriptCursorReason(value) {
2536
4115
  return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
2537
4116
  }
2538
4117
  var TRANSCRIPT_MISSING_REASON = "transcript_missing";
2539
4118
  var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
2540
- var HOST_INVOCATION_TRANSCRIPT_TAIL_MAX_BYTES = 1024 * 1024;
4119
+ var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
4120
+ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
4121
+ const seen = /* @__PURE__ */ new Set();
4122
+ const newestFirst = [];
4123
+ for (const message of [...chronological].reverse()) {
4124
+ if (seen.has(message.host_input_ref)) continue;
4125
+ seen.add(message.host_input_ref);
4126
+ newestFirst.push(message);
4127
+ }
4128
+ for (const message of existing?.messages ?? []) {
4129
+ if (seen.has(message.host_input_ref)) continue;
4130
+ seen.add(message.host_input_ref);
4131
+ newestFirst.push(message);
4132
+ }
4133
+ return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
4134
+ }
2541
4135
  function transcriptScanFailureKind(error, adapterFailureKind) {
2542
4136
  if (transcriptErrorCode(error) === "ELOOP") return "symlink";
2543
4137
  const adapter = adapterFailureKind(error);
@@ -2594,10 +4188,10 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
2594
4188
  return null;
2595
4189
  }
2596
4190
  function transcriptSha256(value) {
2597
- return createHash4("sha256").update(value).digest("hex");
4191
+ return createHash6("sha256").update(value).digest("hex");
2598
4192
  }
2599
4193
  function transcriptObjectSha256(value) {
2600
- return createHash4("sha256").update(JSON.stringify(value), "utf8").digest("hex");
4194
+ return createHash6("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2601
4195
  }
2602
4196
  function isTranscriptRecord(value) {
2603
4197
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2742,8 +4336,8 @@ var HostProducerDrainCore = class {
2742
4336
  };
2743
4337
 
2744
4338
  // host/codex/src/codex-outbox.ts
2745
- import { mkdir as mkdir3, open as open3, readdir, rename as rename2, stat as stat2, unlink as unlink2 } from "node:fs/promises";
2746
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join2 } from "node:path";
4339
+ import { mkdir as mkdir4, open as open4, readdir, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
4340
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join4 } from "node:path";
2747
4341
 
2748
4342
  // host/invocation-context.ts
2749
4343
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2778,7 +4372,7 @@ function invocationContextFromTurn(identity, promptRef, expiresAt, descriptor) {
2778
4372
  return Object.freeze(context);
2779
4373
  }
2780
4374
  function isHostInvocationTurnSelection(value) {
2781
- return isRecord3(value) && Object.keys(value).length === 5 && value.schema_version === HOST_INVOCATION_TURN_SELECTION_SCHEMA && ["host_source_ref", "host_session_ref", "prompt_ref", "turn_generation_ref"].every((key) => safeRef(value[key]));
4375
+ return isRecord4(value) && Object.keys(value).length === 5 && value.schema_version === HOST_INVOCATION_TURN_SELECTION_SCHEMA && ["host_source_ref", "host_session_ref", "prompt_ref", "turn_generation_ref"].every((key) => safeRef(value[key]));
2782
4376
  }
2783
4377
  function exactKeys(value, keys) {
2784
4378
  const actual = Object.keys(value);
@@ -2789,7 +4383,7 @@ function requiredKeys(value, required, optional) {
2789
4383
  const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
2790
4384
  return actual.length >= required.length && actual.length <= allowed.size && required.every((key) => Object.hasOwn(value, key)) && actual.every((key) => allowed.has(key));
2791
4385
  }
2792
- function isRecord3(value) {
4386
+ function isRecord4(value) {
2793
4387
  return value !== null && typeof value === "object" && !Array.isArray(value);
2794
4388
  }
2795
4389
  function safeRef(value) {
@@ -2810,18 +4404,107 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2810
4404
  "frame_too_large"
2811
4405
  ];
2812
4406
 
2813
- // host/relay/src/durable-atomic-replacement.ts
2814
- import { lstat as lstat3, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
2815
- var DEFAULT_PORT = {
2816
- platform: process.platform,
2817
- mkdir: (path, options) => mkdir2(path, options),
2818
- lstat: (path) => lstat3(path),
2819
- open_file: (path) => open2(path, "wx", 384),
2820
- rename,
2821
- unlink,
2822
- open_directory: (path) => open2(path),
2823
- unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
4407
+ // host/relay/src/host-usage-facts-capture.ts
4408
+ import { constants as constants5 } from "node:fs";
4409
+ var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
4410
+ var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
4411
+ var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
4412
+ var HostUsageTranscriptSourceError = class extends Error {
4413
+ constructor(options) {
4414
+ super("Host usage transcript source could not be read.", options);
4415
+ this.name = "HostUsageTranscriptSourceError";
4416
+ }
2824
4417
  };
4418
+ async function readHostUsageTranscriptSource(read) {
4419
+ try {
4420
+ return await read();
4421
+ } catch (error) {
4422
+ throw new HostUsageTranscriptSourceError({ cause: error });
4423
+ }
4424
+ }
4425
+ async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4426
+ if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4427
+ let failed = false;
4428
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4429
+ const index = (startIndex + attempt) % registrations.length;
4430
+ const registration = registrations[index];
4431
+ if (registration === void 0) continue;
4432
+ try {
4433
+ if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
4434
+ } catch (error) {
4435
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4436
+ failed = true;
4437
+ }
4438
+ }
4439
+ return { captured: false, nextIndex: startIndex, failed };
4440
+ }
4441
+ async function openHostUsageTranscriptCursor(input) {
4442
+ const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants5.O_RDONLY));
4443
+ let source;
4444
+ try {
4445
+ source = await readHostUsageTranscriptSource(() => input.inspect(handle));
4446
+ } catch (error) {
4447
+ await handle.close().catch(() => void 0);
4448
+ throw error;
4449
+ }
4450
+ const sourceFileRef = hostUsageSourceFileReference(input.source_kind, input.host_source_ref, input.host_session_ref, source.device, source.inode);
4451
+ let prepared;
4452
+ try {
4453
+ prepared = await input.store.prepareSourceCursor(input.producer, input.host_source_ref, input.host_session_ref, input.source_slot, input.initial_cursor(sourceFileRef, source.device, source.inode), input.created_at);
4454
+ } catch (error) {
4455
+ await handle.close().catch(() => void 0);
4456
+ throw error;
4457
+ }
4458
+ if (prepared === null) {
4459
+ await handle.close();
4460
+ return null;
4461
+ }
4462
+ return { handle, source, source_file_ref: sourceFileRef, ...prepared };
4463
+ }
4464
+ async function readHostUsageTranscriptChunk(handle, offset, size, skippingOversizedLine) {
4465
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(size) || size < offset) throw new TypeError("Host usage transcript range is invalid.");
4466
+ if (size === offset) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
4467
+ if (skippingOversizedLine) return await resumeOversizedLine(handle, offset, size);
4468
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
4469
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
4470
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
4471
+ const chunk = bytes.subarray(0, bytesRead);
4472
+ return completeChunk(chunk, offset);
4473
+ }
4474
+ async function resumeOversizedLine(handle, offset, size) {
4475
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
4476
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
4477
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
4478
+ const chunk = bytes.subarray(0, bytesRead);
4479
+ const delimiter = chunk.indexOf(10);
4480
+ if (delimiter < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
4481
+ return completeChunk(chunk.subarray(delimiter + 1), offset + delimiter + 1);
4482
+ }
4483
+ function completeChunk(chunk, offset) {
4484
+ const parsed = completeLinePrefix(chunk, offset);
4485
+ const oversizedRows = parsed.oversizedRows + (parsed.incompleteOversized ? 1 : 0);
4486
+ const endOffset = parsed.incompleteOversized ? offset + chunk.length : parsed.endOffset;
4487
+ return { lines: parsed.lines, end_offset: endOffset, skipping_oversized_line: parsed.incompleteOversized, oversized_rows: oversizedRows };
4488
+ }
4489
+ function completeLinePrefix(bytes, baseOffset) {
4490
+ const lines = [];
4491
+ let lineStart = 0;
4492
+ let endOffset = baseOffset;
4493
+ let oversizedRows = 0;
4494
+ let rowCount = 0;
4495
+ for (let index = 0; index < bytes.length; index += 1) {
4496
+ if (bytes[index] !== 10) continue;
4497
+ const line = bytes.subarray(lineStart, index);
4498
+ if (line.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES) oversizedRows += 1;
4499
+ else lines.push(line);
4500
+ lineStart = index + 1;
4501
+ endOffset = baseOffset + lineStart;
4502
+ rowCount += 1;
4503
+ if (rowCount >= HOST_USAGE_FACTS_SCAN_MAX_ROWS) return { lines, endOffset, oversizedRows, incompleteOversized: false };
4504
+ }
4505
+ const incomplete = bytes.subarray(lineStart);
4506
+ return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
4507
+ }
2825
4508
 
2826
4509
  // host/relay/src/relay-quarantine-store.ts
2827
4510
  var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
@@ -2838,16 +4521,6 @@ var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2838
4521
 
2839
4522
  // host/relay/src/relay-ipc.ts
2840
4523
  var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2841
- var HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2842
- "permission_denied",
2843
- "socket_missing",
2844
- "connection_refused",
2845
- "closed_early",
2846
- "response_invalid",
2847
- "timed_out",
2848
- "cancelled",
2849
- "unavailable"
2850
- ]);
2851
4524
 
2852
4525
  // host/codex/src/codex-types.ts
2853
4526
  var CODEX_OUTBOX_SCHEMA_VERSION = "ceal.codex_observation_outbox.v1";
@@ -2878,12 +4551,12 @@ function validateCodexHostInvocationContext(value) {
2878
4551
  validateContextTimes(value);
2879
4552
  }
2880
4553
  function validateIdentity2(value) {
2881
- if (!isRecord4(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2)) {
4554
+ if (!isRecord5(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2)) {
2882
4555
  throw new CodexHostAdapterError("storage", "Codex Host invocation identity is malformed.");
2883
4556
  }
2884
4557
  }
2885
4558
  function isContextShape(value) {
2886
- return isRecord4(value) && hasHostInvocationContextKeys(value, ["turn_generation_ref"]) && value.schema_version === CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION;
4559
+ return isRecord5(value) && hasHostInvocationContextKeys(value, ["turn_generation_ref"]) && value.schema_version === CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION;
2887
4560
  }
2888
4561
  function validateContextReferences(value) {
2889
4562
  if (!safeRef2(value.prompt_ref) || !optionalSafeRef(value.turn_generation_ref)) throw new CodexHostAdapterError("storage", "Codex Host invocation context is malformed.");
@@ -2901,7 +4574,7 @@ function safeRef2(value) {
2901
4574
  function timestamp(value) {
2902
4575
  return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
2903
4576
  }
2904
- function isRecord4(value) {
4577
+ function isRecord5(value) {
2905
4578
  return value !== null && typeof value === "object" && !Array.isArray(value);
2906
4579
  }
2907
4580
 
@@ -2919,12 +4592,12 @@ var CodexOutboxStore = class {
2919
4592
  constructor(directory) {
2920
4593
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
2921
4594
  this.directory = directory;
2922
- this.entriesDirectory = join2(directory, "entries");
2923
- this.sessionsDirectory = join2(directory, "sessions");
2924
- this.activeContextsDirectory = join2(directory, "active-contexts");
2925
- this.turnSelectionsDirectory = join2(directory, "turn-selections");
2926
- this.registrationsDirectory = join2(directory, "transcript-registrations");
2927
- this.cursorsDirectory = join2(directory, "transcript-cursors");
4595
+ this.entriesDirectory = join4(directory, "entries");
4596
+ this.sessionsDirectory = join4(directory, "sessions");
4597
+ this.activeContextsDirectory = join4(directory, "active-contexts");
4598
+ this.turnSelectionsDirectory = join4(directory, "turn-selections");
4599
+ this.registrationsDirectory = join4(directory, "transcript-registrations");
4600
+ this.cursorsDirectory = join4(directory, "transcript-cursors");
2928
4601
  }
2929
4602
  async prepare() {
2930
4603
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -2943,7 +4616,7 @@ var CodexOutboxStore = class {
2943
4616
  for (const name of await readdir(this.entriesDirectory)) {
2944
4617
  if (!name.endsWith(".json")) continue;
2945
4618
  try {
2946
- const value = JSON.parse(await readOwnerStateFile(join2(this.entriesDirectory, name)));
4619
+ const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
2947
4620
  validateEnvelope(value);
2948
4621
  entries.push(value);
2949
4622
  } catch {
@@ -2956,7 +4629,7 @@ var CodexOutboxStore = class {
2956
4629
  async remove(entry) {
2957
4630
  validateEnvelope(entry);
2958
4631
  try {
2959
- await unlink2(this.entryPath(entry.submission_ref));
4632
+ await unlink3(this.entryPath(entry.submission_ref));
2960
4633
  } catch (error) {
2961
4634
  if (!isNotFound2(error)) throw storageError("Unable to remove the Codex outbox entry.");
2962
4635
  }
@@ -2974,7 +4647,7 @@ var CodexOutboxStore = class {
2974
4647
  await writeAtomicJson(path, context);
2975
4648
  } catch (error) {
2976
4649
  try {
2977
- await unlink2(path);
4650
+ await unlink3(path);
2978
4651
  } catch (unlinkError) {
2979
4652
  if (!isNotFound2(unlinkError)) throw storageError("Unable to clear a failed Codex Host context replacement.");
2980
4653
  }
@@ -2989,13 +4662,13 @@ var CodexOutboxStore = class {
2989
4662
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
2990
4663
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
2991
4664
  await this.prepare();
2992
- return readOptionalJson(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
4665
+ return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
2993
4666
  }
2994
4667
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
2995
4668
  const selection = await this.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref);
2996
4669
  if (selection === null || selection.prompt_ref !== promptRef || selection.turn_generation_ref !== turnGenerationRef) return false;
2997
4670
  const path = this.activeContextPath(identity);
2998
- const active = await readOptionalJson(path, validateCodexHostInvocationContext);
4671
+ const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
2999
4672
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
3000
4673
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
3001
4674
  return true;
@@ -3014,7 +4687,7 @@ var CodexOutboxStore = class {
3014
4687
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
3015
4688
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
3016
4689
  await this.prepare();
3017
- const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson(file, validateCodexHostInvocationContext));
4690
+ const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
3018
4691
  return context;
3019
4692
  }
3020
4693
  /** Clear the projection only if the caller still owns its exact active turn. */
@@ -3023,7 +4696,7 @@ var CodexOutboxStore = class {
3023
4696
  const active = await this.readInvocationContext(identity.host_source_ref, identity.host_session_ref, now);
3024
4697
  if (active === null || !sameIdentity(active.identity, identity)) return false;
3025
4698
  try {
3026
- await unlink2(this.activeContextPath(identity));
4699
+ await unlink3(this.activeContextPath(identity));
3027
4700
  } catch (error) {
3028
4701
  if (!isNotFound2(error)) throw storageError("Unable to clear the Codex Host invocation context.");
3029
4702
  }
@@ -3038,13 +4711,13 @@ var CodexOutboxStore = class {
3038
4711
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
3039
4712
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
3040
4713
  await this.prepare();
3041
- return readOptionalJson(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
4714
+ return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
3042
4715
  }
3043
4716
  async registerTranscript(registration) {
3044
4717
  validateRegistration(registration);
3045
4718
  await this.prepare();
3046
4719
  const path = this.registrationPath(registration.host_source_ref, registration.host_session_ref);
3047
- const existing = await readOptionalJson(path, validateRegistration);
4720
+ const existing = await readOptionalJson2(path, validateRegistration);
3048
4721
  if (existing !== null && (existing.codex_session_id !== registration.codex_session_id || existing.transcript_path !== registration.transcript_path)) {
3049
4722
  throw storageError("Codex transcript registration conflicts with the source-bound session.");
3050
4723
  }
@@ -3069,7 +4742,7 @@ var CodexOutboxStore = class {
3069
4742
  for (const name of await readdir(this.registrationsDirectory)) {
3070
4743
  if (!name.endsWith(".json")) continue;
3071
4744
  try {
3072
- const value = JSON.parse(await readOwnerStateFile(join2(this.registrationsDirectory, name)));
4745
+ const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
3073
4746
  validateRegistration(value);
3074
4747
  registrations.push(value);
3075
4748
  } catch {
@@ -3080,7 +4753,7 @@ var CodexOutboxStore = class {
3080
4753
  async readTranscriptCursor(registration) {
3081
4754
  validateRegistration(registration);
3082
4755
  await this.prepare();
3083
- return readOptionalJson(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
4756
+ return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
3084
4757
  }
3085
4758
  async writeTranscriptCursor(cursor) {
3086
4759
  validateCursor(cursor);
@@ -3103,27 +4776,27 @@ var CodexOutboxStore = class {
3103
4776
  }
3104
4777
  entryPath(submissionRef) {
3105
4778
  if (!SAFE_REF3.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
3106
- return join2(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
4779
+ return join4(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
3107
4780
  }
3108
4781
  sessionPath(sourceRef, sessionRef) {
3109
- return join2(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
4782
+ return join4(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
3110
4783
  }
3111
4784
  activeContextPath(identity) {
3112
- return join2(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
4785
+ return join4(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
3113
4786
  }
3114
4787
  turnSelectionPath(sourceRef, sessionRef) {
3115
- return join2(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
4788
+ return join4(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
3116
4789
  }
3117
4790
  registrationPath(sourceRef, sessionRef) {
3118
- return join2(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4791
+ return join4(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
3119
4792
  }
3120
4793
  cursorPath(sourceRef, sessionRef) {
3121
- return join2(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4794
+ return join4(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
3122
4795
  }
3123
4796
  };
3124
4797
  async function removeOwnerState(path, what) {
3125
4798
  try {
3126
- await unlink2(path);
4799
+ await unlink3(path);
3127
4800
  } catch (error) {
3128
4801
  if (!isNotFound2(error)) throw storageError(`Unable to retire the Codex transcript ${what}.`);
3129
4802
  }
@@ -3154,7 +4827,7 @@ async function writeAtomicJson(path, value) {
3154
4827
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
3155
4828
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
3156
4829
  try {
3157
- const handle = await open3(temp, "wx");
4830
+ const handle = await open4(temp, "wx");
3158
4831
  try {
3159
4832
  await handle.writeFile(text, "utf8");
3160
4833
  await handle.sync();
@@ -3162,19 +4835,19 @@ async function writeAtomicJson(path, value) {
3162
4835
  await handle.close();
3163
4836
  }
3164
4837
  await rename2(temp, path);
3165
- await syncDirectory(dirname3(path));
4838
+ await syncDirectory2(dirname6(path));
3166
4839
  } catch (error) {
3167
4840
  try {
3168
- await unlink2(temp);
4841
+ await unlink3(temp);
3169
4842
  } catch {
3170
4843
  }
3171
4844
  if (error instanceof CodexHostAdapterError) throw error;
3172
4845
  throw storageError("Unable to atomically replace Codex owner state.");
3173
4846
  }
3174
4847
  }
3175
- async function syncDirectory(path) {
4848
+ async function syncDirectory2(path) {
3176
4849
  try {
3177
- const handle = await open3(path, "r");
4850
+ const handle = await open4(path, "r");
3178
4851
  try {
3179
4852
  await handle.sync();
3180
4853
  } finally {
@@ -3183,7 +4856,7 @@ async function syncDirectory(path) {
3183
4856
  } catch {
3184
4857
  }
3185
4858
  }
3186
- async function readOptionalJson(path, validate) {
4859
+ async function readOptionalJson2(path, validate) {
3187
4860
  try {
3188
4861
  const value = JSON.parse(await readOwnerStateFile(path));
3189
4862
  validate(value);
@@ -3199,7 +4872,7 @@ async function ensureOwnerDirectory(path) {
3199
4872
  await stat2(path);
3200
4873
  } catch (error) {
3201
4874
  if (!isNotFound2(error)) throw storageError("Codex owner state directory is unavailable.");
3202
- await mkdir3(path, { recursive: true });
4875
+ await mkdir4(path, { recursive: true });
3203
4876
  }
3204
4877
  const stats = await stat2(path);
3205
4878
  if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
@@ -3207,7 +4880,7 @@ async function ensureOwnerDirectory(path) {
3207
4880
  async function readOwnerStateFile(path) {
3208
4881
  let handle;
3209
4882
  try {
3210
- handle = await open3(path);
4883
+ handle = await open4(path);
3211
4884
  const stats = await handle.stat();
3212
4885
  if (!stats.isFile()) throw storageError("Codex owner state path is not a regular file.");
3213
4886
  return await handle.readFile("utf8");
@@ -3216,8 +4889,8 @@ async function readOwnerStateFile(path) {
3216
4889
  }
3217
4890
  }
3218
4891
  function validateEnvelope(value) {
3219
- if (!isRecord5(value)) throw storageError("Codex outbox entry is malformed.");
3220
- if (!sameKeys(value, ["schema_version", "identity", "host_input_ref", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"], ["codex_turn_id"])) throw storageError(`Codex outbox entry key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the outbox entry key set")}).`);
4892
+ if (!isRecord6(value)) throw storageError("Codex outbox entry is malformed.");
4893
+ if (!sameKeys2(value, ["schema_version", "identity", "host_input_ref", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"], ["codex_turn_id"])) throw storageError(`Codex outbox entry key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the outbox entry key set")}).`);
3221
4894
  if (value.schema_version !== CODEX_OUTBOX_SCHEMA_VERSION) throw storageError(`Codex outbox entry is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CODEX_OUTBOX_SCHEMA_VERSION}`)}).`);
3222
4895
  validateIdentity3(value.identity);
3223
4896
  validateEnvelopeReferences(value);
@@ -3232,8 +4905,8 @@ function validateEnvelopeReferences(value) {
3232
4905
  if (typeof value.origin_input !== "boolean") throw storageError("Codex outbox origin disposition is malformed.");
3233
4906
  }
3234
4907
  function validateRegistration(value) {
3235
- if (!isRecord5(value)) throw storageError("Codex transcript registration is malformed.");
3236
- if (!sameKeys(value, ["schema_version", "host_source_ref", "host_session_ref", "codex_session_id", "transcript_path", "registered_at", "expires_at"], ["cwd"])) throw storageError(`Codex transcript registration key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the registration key set")}).`);
4908
+ if (!isRecord6(value)) throw storageError("Codex transcript registration is malformed.");
4909
+ if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "codex_session_id", "transcript_path", "registered_at", "expires_at"], ["cwd"])) throw storageError(`Codex transcript registration key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the registration key set")}).`);
3237
4910
  if (value.schema_version !== CODEX_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION) throw storageError(`Codex transcript registration is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CODEX_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION}`)}).`);
3238
4911
  validateRegistrationFields(value);
3239
4912
  }
@@ -3248,13 +4921,28 @@ function validRegistrationCwd(value) {
3248
4921
  return value === void 0 || typeof value === "string" && isAbsolute2(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
3249
4922
  }
3250
4923
  function validateCursor(value) {
3251
- if (!isRecord5(value)) throw storageError("Codex transcript cursor is malformed.");
3252
- if (!sameKeys(value, ["schema_version", "host_source_ref", "host_session_ref", "transcript_path", "device", "inode", "offset", "last_ordinal", "anchor_start", "anchor_sha256", "header_validated", "status", "updated_at"], ["active_task", "reason"])) throw storageError(`Codex transcript cursor key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the cursor key set")}).`);
4924
+ if (!isRecord6(value)) throw storageError("Codex transcript cursor is malformed.");
4925
+ if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "transcript_path", "device", "inode", "offset", "last_ordinal", "anchor_start", "anchor_sha256", "header_validated", "status", "updated_at"], ["active_task", "human_message_window", "reason"])) throw storageError(`Codex transcript cursor key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the cursor key set")}).`);
4926
+ validateCursorIdentityAndPosition(value);
4927
+ validateCursorOptionalFields(value);
4928
+ }
4929
+ function validateCursorIdentityAndPosition(value) {
3253
4930
  if (value.schema_version !== CODEX_TRANSCRIPT_CURSOR_SCHEMA_VERSION) throw storageError(`Codex transcript cursor is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CODEX_TRANSCRIPT_CURSOR_SCHEMA_VERSION}`)}).`);
3254
4931
  if (!validCursorSource(value) || !validCursorPosition(value) || !validCursorStatus(value)) throw storageError("Codex transcript cursor fields are malformed.");
4932
+ }
4933
+ function validateCursorOptionalFields(value) {
3255
4934
  if (value.active_task !== void 0 && !validActiveTask(value.active_task)) throw storageError("Codex transcript task cursor is malformed.");
4935
+ validateHumanMessageProjection(value.human_message_window);
3256
4936
  if (value.reason !== void 0 && !isHostTranscriptCursorReason(value.reason)) throw storageError("Codex transcript cursor reason is malformed.");
3257
4937
  }
4938
+ function validateHumanMessageProjection(value) {
4939
+ if (value === void 0) return;
4940
+ try {
4941
+ decodeCealHostInvocationHumanMessageWindow(value);
4942
+ } catch {
4943
+ throw storageError("Codex transcript human-message projection is malformed.");
4944
+ }
4945
+ }
3258
4946
  function validCursorSource(value) {
3259
4947
  return [value.host_source_ref, value.host_session_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate)) && typeof value.transcript_path === "string" && value.transcript_path.length > 0 && typeof value.device === "string" && typeof value.inode === "string";
3260
4948
  }
@@ -3265,7 +4953,7 @@ function validCursorStatus(value) {
3265
4953
  return (value.status === "active" || value.status === "quarantined") && isTimestamp(value.updated_at);
3266
4954
  }
3267
4955
  function validActiveTask(value) {
3268
- if (!isRecord5(value) || !sameKeys(value, ["codex_turn_id", "host_turn_ref", "started_at"], ["origin_host_input_ref", "prompt_ref", "model", "token_usage", "last_total_usage", "token_usage_gap_reason"])) return false;
4956
+ if (!isRecord6(value) || !sameKeys2(value, ["codex_turn_id", "host_turn_ref", "started_at"], ["origin_host_input_ref", "prompt_ref", "model", "token_usage", "last_total_usage", "token_usage_gap_reason"])) return false;
3269
4957
  return validActiveTaskIdentity(value) && validActiveTaskReferences(value) && validActiveTaskUsage(value);
3270
4958
  }
3271
4959
  function validActiveTaskIdentity(value) {
@@ -3281,7 +4969,7 @@ function validActiveTaskUsage(value) {
3281
4969
  return (value.token_usage === void 0 || validTokenUsage(value.token_usage)) && (value.last_total_usage === void 0 || validTokenUsage(value.last_total_usage)) && (value.token_usage_gap_reason === void 0 || value.token_usage_gap_reason === "token_count_shape_not_attributable");
3282
4970
  }
3283
4971
  function validTokenUsage(value) {
3284
- if (!isRecord5(value) || !sameKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) return false;
4972
+ if (!isRecord6(value) || !sameKeys2(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) return false;
3285
4973
  if (![value.input_tokens, value.cached_input_tokens, value.cache_write_input_tokens, value.output_tokens, value.reasoning_output_tokens, value.total_tokens].every(nonNegativeInteger)) return false;
3286
4974
  return value.total_tokens === Number(value.input_tokens) + Number(value.output_tokens) && Number(value.cached_input_tokens) + Number(value.cache_write_input_tokens) <= Number(value.input_tokens) && Number(value.reasoning_output_tokens) <= Number(value.output_tokens);
3287
4975
  }
@@ -3301,8 +4989,8 @@ function validateEnvelopeTimestamps(value) {
3301
4989
  if (!isTimestamp(value.expires_at)) throw storageError("Codex outbox timestamps are malformed.");
3302
4990
  }
3303
4991
  function validateSession(value) {
3304
- if (!isRecord5(value)) throw storageError("Codex session snapshot is malformed.");
3305
- if (!sameKeys(value, ["schema_version", "host_session_ref", "host_source_ref", "observed_at", "value", "expires_at"])) throw storageError(`Codex session snapshot key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the session snapshot key set")}).`);
4992
+ if (!isRecord6(value)) throw storageError("Codex session snapshot is malformed.");
4993
+ if (!sameKeys2(value, ["schema_version", "host_session_ref", "host_source_ref", "observed_at", "value", "expires_at"])) throw storageError(`Codex session snapshot key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the session snapshot key set")}).`);
3306
4994
  if (value.schema_version !== CODEX_SESSION_SCHEMA_VERSION) throw storageError(`Codex session snapshot is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CODEX_SESSION_SCHEMA_VERSION}`)}).`);
3307
4995
  if (!SAFE_REF3.test(String(value.host_session_ref)) || !SAFE_REF3.test(String(value.host_source_ref)) || !isTimestamp(value.observed_at) || !isTimestamp(value.expires_at) || !isJsonValue(value.value)) throw storageError("Codex session snapshot fields are malformed.");
3308
4996
  }
@@ -3310,27 +4998,27 @@ function validateTurnSelection(value) {
3310
4998
  if (!isHostInvocationTurnSelection(value)) throw storageError("Codex Host turn selection is malformed.");
3311
4999
  }
3312
5000
  function validateIdentity3(value) {
3313
- if (!isRecord5(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) throw storageError("Codex Host identity is malformed.");
5001
+ if (!isRecord6(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) throw storageError("Codex Host identity is malformed.");
3314
5002
  }
3315
5003
  function isJsonValue(value) {
3316
5004
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
3317
5005
  if (typeof value === "number") return Number.isFinite(value);
3318
5006
  if (Array.isArray(value)) return value.every(isJsonValue);
3319
- return isRecord5(value) && Object.entries(value).every(([key, child]) => key.length > 0 && key.length <= 128 && isJsonValue(child));
5007
+ return isRecord6(value) && Object.entries(value).every(([key, child]) => key.length > 0 && key.length <= 128 && isJsonValue(child));
3320
5008
  }
3321
5009
  function isTimestamp(value) {
3322
5010
  return typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value));
3323
5011
  }
3324
- function sameKeys(value, required, optional = []) {
5012
+ function sameKeys2(value, required, optional = []) {
3325
5013
  const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
3326
5014
  const keys = Object.keys(value);
3327
5015
  return keys.length >= required.length && keys.length <= allowed.size && required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => allowed.has(key));
3328
5016
  }
3329
- function isRecord5(value) {
5017
+ function isRecord6(value) {
3330
5018
  return value !== null && typeof value === "object" && !Array.isArray(value);
3331
5019
  }
3332
5020
  function isNotFound2(error) {
3333
- return isRecord5(error) && error.code === "ENOENT";
5021
+ return isRecord6(error) && error.code === "ENOENT";
3334
5022
  }
3335
5023
  function storageError(message) {
3336
5024
  return new CodexHostAdapterError("storage", message);
@@ -3359,7 +5047,7 @@ var CodexProducer = class {
3359
5047
  };
3360
5048
 
3361
5049
  // host/codex/src/codex-decoder.ts
3362
- import { createHash as createHash5 } from "node:crypto";
5050
+ import { createHash as createHash7 } from "node:crypto";
3363
5051
  var SAFE_REF4 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
3364
5052
  var MAX_PAYLOAD_BYTES = 512 * 1024;
3365
5053
  function observationRef(hostSourceRef, event, identity, value) {
@@ -3373,23 +5061,23 @@ function hostInputReference(sourceRef, sessionRef, nativeTurnId, messageId, ordi
3373
5061
  if (![sourceRef, sessionRef, nativeTurnId, messageId].every((value) => SAFE_REF4.test(value)) || !Number.isSafeInteger(ordinal) || ordinal < 0) {
3374
5062
  throw new CodexHostAdapterError("invalid_input", "Codex input identity is invalid.");
3375
5063
  }
3376
- return `codex-input:${shortDigest({ source_ref: sourceRef, session_ref: sessionRef, native_turn_id: nativeTurnId, message_id: messageId, ordinal, prompt_sha256: sha256(prompt) })}`;
5064
+ return `codex-input:${shortDigest({ source_ref: sourceRef, session_ref: sessionRef, native_turn_id: nativeTurnId, message_id: messageId, ordinal, prompt_sha256: sha2563(prompt) })}`;
3377
5065
  }
3378
5066
  function promptObservationValue(prompt) {
3379
- return { body_sha256: sha256(prompt) };
5067
+ return { body_sha256: sha2563(prompt) };
3380
5068
  }
3381
5069
  function turnObservationValue(sessionId, turnRef, status) {
3382
- return { status, host_session_id_sha256: sha256(sessionId), host_turn_ref: turnRef };
5070
+ return { status, host_session_id_sha256: sha2563(sessionId), host_turn_ref: turnRef };
3383
5071
  }
3384
- function sha256(value) {
3385
- return createHash5("sha256").update(value, "utf8").digest("hex");
5072
+ function sha2563(value) {
5073
+ return createHash7("sha256").update(value, "utf8").digest("hex");
3386
5074
  }
3387
5075
  function shortDigest(value) {
3388
5076
  return cealRequestSha256(value);
3389
5077
  }
3390
5078
 
3391
5079
  // host/codex/src/codex-transcript-baseline.ts
3392
- import { createHash as createHash6 } from "node:crypto";
5080
+ import { createHash as createHash8 } from "node:crypto";
3393
5081
 
3394
5082
  // host/codex/src/codex-transcript-decoder.ts
3395
5083
  var SAFE_REF5 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
@@ -3401,16 +5089,32 @@ function decodeCodexTranscriptLine(line) {
3401
5089
  } catch {
3402
5090
  reject("Codex transcript record is not valid JSON.");
3403
5091
  }
3404
- if (!isRecord6(value)) reject("Codex transcript record envelope is malformed.");
5092
+ if (!isRecord7(value)) reject("Codex transcript record envelope is malformed.");
3405
5093
  const ordinal = safeOrdinal(value.ordinal);
3406
5094
  const timestamp3 = safeTimestamp(value.timestamp);
3407
- if (!isRecord6(value.payload) || typeof value.type !== "string") reject("Codex transcript record payload is malformed.");
5095
+ if (!isRecord7(value.payload) || typeof value.type !== "string") reject("Codex transcript record payload is malformed.");
3408
5096
  if (value.type === "session_meta") return decodeSessionMeta(value.payload, ordinal, timestamp3);
3409
5097
  if (value.type === "turn_context") return decodeTurnContext(value.payload, ordinal, timestamp3);
3410
5098
  if (value.type === "event_msg") return decodeEventMessage(value.payload, ordinal, timestamp3);
3411
5099
  if (value.type === "response_item") return decodeResponseItem(value.payload, ordinal, timestamp3);
3412
5100
  return { kind: "ignored", ordinal, timestamp: timestamp3 };
3413
5101
  }
5102
+ function decodeCodexUsageTranscriptLine(line) {
5103
+ let value;
5104
+ try {
5105
+ value = JSON.parse(line);
5106
+ } catch {
5107
+ reject("Codex transcript record is not valid JSON.");
5108
+ }
5109
+ if (!isRecord7(value)) reject("Codex transcript record envelope is malformed.");
5110
+ const ordinal = safeOrdinal(value.ordinal);
5111
+ const timestamp3 = safeTimestamp(value.timestamp);
5112
+ if (!isRecord7(value.payload) || typeof value.type !== "string") reject("Codex transcript record payload is malformed.");
5113
+ if (value.type === "session_meta") return decodeSessionMeta(value.payload, ordinal, timestamp3);
5114
+ if (value.type === "turn_context") return decodeTurnContext(value.payload, ordinal, timestamp3);
5115
+ if (value.type === "event_msg" && ["task_started", "task_complete", "turn_aborted", "token_count"].includes(String(value.payload.type))) return decodeEventMessage(value.payload, ordinal, timestamp3);
5116
+ return { kind: "ignored", ordinal, timestamp: timestamp3 };
5117
+ }
3414
5118
  function decodeTurnContext(payload, ordinal, timestamp3) {
3415
5119
  return {
3416
5120
  kind: "turn_context",
@@ -3450,7 +5154,7 @@ function decodeEventMessage(payload, ordinal, timestamp3) {
3450
5154
  started_at: safeNumber(payload.started_at),
3451
5155
  completed_at: safeNumber(payload.completed_at),
3452
5156
  duration_ms: safeNumber(payload.duration_ms),
3453
- reason: boundedText(payload.reason, 256, "Codex task abort reason is invalid.")
5157
+ reason: boundedText2(payload.reason, 256, "Codex task abort reason is invalid.")
3454
5158
  };
3455
5159
  }
3456
5160
  if (payload.type === "token_count") return decodeTokenCount(payload, ordinal, timestamp3);
@@ -3458,7 +5162,7 @@ function decodeEventMessage(payload, ordinal, timestamp3) {
3458
5162
  }
3459
5163
  function decodeTokenCount(payload, ordinal, timestamp3) {
3460
5164
  if (payload.info === null) return { kind: "token_count", ordinal, timestamp: timestamp3 };
3461
- if (!isRecord6(payload.info)) return { kind: "token_count", ordinal, timestamp: timestamp3, usage_gap_reason: "token_count_shape_not_attributable" };
5165
+ if (!isRecord7(payload.info)) return { kind: "token_count", ordinal, timestamp: timestamp3, usage_gap_reason: "token_count_shape_not_attributable" };
3462
5166
  const lastUsage = optionalTokenUsage(payload.info.last_token_usage);
3463
5167
  const totalUsage = optionalTokenUsage(payload.info.total_token_usage);
3464
5168
  const gap = lastUsage.status === "invalid" || totalUsage.status === "invalid";
@@ -3482,7 +5186,7 @@ function optionalTokenUsage(value) {
3482
5186
  }
3483
5187
  }
3484
5188
  function decodeTokenUsage(value) {
3485
- if (!isRecord6(value)) reject("Codex token usage is malformed.");
5189
+ if (!isRecord7(value)) reject("Codex token usage is malformed.");
3486
5190
  const usage = {
3487
5191
  input_tokens: safeTokenCount(value.input_tokens),
3488
5192
  cached_input_tokens: safeTokenCount(value.cached_input_tokens),
@@ -3514,14 +5218,14 @@ function userTextContentKind(kinds) {
3514
5218
  return kinds.length === 1 && (kinds[0] === "user.text" || kinds[0] === "goal.internal_context") ? kinds[0] : void 0;
3515
5219
  }
3516
5220
  function userMessageMetadata(value) {
3517
- if (!isRecord6(value) || !Array.isArray(value.content_item_kinds)) reject("Codex user message provenance is malformed.");
5221
+ if (!isRecord7(value) || !Array.isArray(value.content_item_kinds)) reject("Codex user message provenance is malformed.");
3518
5222
  return { ...value, content_item_kinds: value.content_item_kinds };
3519
5223
  }
3520
5224
  function userTextContent(value) {
3521
5225
  if (!Array.isArray(value)) reject(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
3522
5226
  if (value.length !== 1) reject(`Codex user text content is malformed (${refusalFact("items", value.length, "exactly one")}).`);
3523
- 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")}).`);
3524
- return boundedText(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
5227
+ if (!isRecord7(value[0]) || value[0].type !== "input_text") reject(`Codex user text content is malformed (${refusalFact("item_type", isRecord7(value[0]) ? value[0].type : typeof value[0], "input_text")}).`);
5228
+ return boundedText2(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
3525
5229
  }
3526
5230
  function safeOrdinal(value) {
3527
5231
  if (!Number.isSafeInteger(value) || Number(value) < 0) reject("Codex transcript ordinal is invalid.");
@@ -3545,18 +5249,18 @@ function safeRef3(value, message) {
3545
5249
  if (typeof value !== "string" || !SAFE_REF5.test(value)) reject(message);
3546
5250
  return value;
3547
5251
  }
3548
- function boundedText(value, maximum, message) {
5252
+ function boundedText2(value, maximum, message) {
3549
5253
  if (typeof value !== "string") reject(`${message} ${refusalFact("kind", typeof value, "string")}.`);
3550
5254
  const bytes = Buffer.byteLength(value, "utf8");
3551
5255
  if (bytes > maximum) reject(`${message} ${refusalFact("bytes", bytes, `at most ${maximum} UTF-8 bytes`)}.`);
3552
5256
  return value;
3553
5257
  }
3554
5258
  function boundedNonEmptyText(value, maximum, message) {
3555
- const result = boundedText(value, maximum, message);
5259
+ const result = boundedText2(value, maximum, message);
3556
5260
  if (result.length === 0) reject(message);
3557
5261
  return result;
3558
5262
  }
3559
- function isRecord6(value) {
5263
+ function isRecord7(value) {
3560
5264
  return value !== null && typeof value === "object" && !Array.isArray(value);
3561
5265
  }
3562
5266
  function reject(message) {
@@ -3579,6 +5283,7 @@ function codexTranscriptInitialCursor(registration, device, inode, now) {
3579
5283
  anchor_start: 0,
3580
5284
  anchor_sha256: digest(Buffer.alloc(0)),
3581
5285
  header_validated: false,
5286
+ human_message_window: { messages: [], truncated: false },
3582
5287
  status: "active",
3583
5288
  updated_at: timestamp2(now)
3584
5289
  };
@@ -3589,14 +5294,14 @@ async function ownedCodexTranscriptFile(handle, platform = process.platform) {
3589
5294
  if (platform !== "win32" && !isSelfOwned(stats.uid, platform, handle)) throw new CodexHostAdapterError("storage", "Codex transcript source is owned by another user.");
3590
5295
  return { size: stats.size, device: String(stats.dev), inode: String(stats.ino) };
3591
5296
  }
3592
- function assertCodexTranscriptHeader(registration, record) {
3593
- if (record.kind !== "session_meta" || record.session_id !== registration.codex_session_id) throw new CodexHostAdapterError("payload_rejected", `Codex transcript header does not match its SessionStart registration (${refusalFacts([
3594
- { name: "kind", value: record.kind, expected: "session_meta" },
3595
- { name: "session_id", value: record.kind === "session_meta" ? record.session_id : "unavailable", expected: registration.codex_session_id }
5297
+ function assertCodexTranscriptHeader(registration, record2) {
5298
+ if (record2.kind !== "session_meta" || record2.session_id !== registration.codex_session_id) throw new CodexHostAdapterError("payload_rejected", `Codex transcript header does not match its SessionStart registration (${refusalFacts([
5299
+ { name: "kind", value: record2.kind, expected: "session_meta" },
5300
+ { name: "session_id", value: record2.kind === "session_meta" ? record2.session_id : "unavailable", expected: registration.codex_session_id }
3596
5301
  ])}).`);
3597
5302
  }
3598
5303
  function digest(value) {
3599
- return createHash6("sha256").update(value).digest("hex");
5304
+ return createHash8("sha256").update(value).digest("hex");
3600
5305
  }
3601
5306
  function timestamp2(now) {
3602
5307
  const value = now();
@@ -3635,7 +5340,10 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3635
5340
  const preflight = await this.preflight(registration, handle, size, device, inode);
3636
5341
  if (preflight.cursor === null) return preflight.result;
3637
5342
  const complete = await this.readChunk(handle, preflight.cursor.offset, size);
3638
- if (complete === "empty" || complete === "partial") return { records: 0, enqueued: 0, quarantined: false };
5343
+ if (complete === "empty" || complete === "partial") {
5344
+ if (preflight.projectionInitialized) await this.commitCursor(registration, handle, preflight.cursor, 0, device, inode, preflight.cursor.last_ordinal, preflight.cursor.active_task, preflight.cursor.human_message_window ?? { messages: [], truncated: false });
5345
+ return { records: 0, enqueued: 0, quarantined: false };
5346
+ }
3639
5347
  return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
3640
5348
  }
3641
5349
  async scanFailed(handle, registration, error) {
@@ -3650,40 +5358,51 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3650
5358
  const existing = await this.store.readTranscriptCursor(registration);
3651
5359
  let cursor = existing ?? codexTranscriptInitialCursor(registration, device, inode, this.now);
3652
5360
  if (cursor.status === "quarantined") {
3653
- return { cursor: null, result: { records: 0, enqueued: 0, quarantined: true } };
5361
+ return { cursor: null, projectionInitialized: false, result: { records: 0, enqueued: 0, quarantined: true } };
3654
5362
  }
3655
5363
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
3656
- if (reason === null) return { cursor, result: { records: 0, enqueued: 0, quarantined: false } };
5364
+ if (reason === null) {
5365
+ if (cursor.human_message_window !== void 0) return { cursor, projectionInitialized: false, result: { records: 0, enqueued: 0, quarantined: false } };
5366
+ const humanWindow = await this.readHumanMessageProjection(handle, registration, cursor);
5367
+ return { cursor: { ...cursor, human_message_window: humanWindow }, projectionInitialized: existing !== null, result: { records: 0, enqueued: 0, quarantined: false } };
5368
+ }
3657
5369
  await this.quarantine(registration, cursor, device, inode, reason);
3658
- return { cursor: null, result: { records: 0, enqueued: 0, quarantined: true } };
5370
+ this.diagnostic("watcher_scan_failed", "other", `cursor_${reason}`);
5371
+ return { cursor: null, projectionInitialized: false, result: { records: 0, enqueued: 0, quarantined: true } };
5372
+ }
5373
+ async readHumanMessageProjection(handle, registration, cursor) {
5374
+ return readCodexHumanMessageProjection(registration, cursor, (offset, size) => this.readChunk(handle, offset, size));
3659
5375
  }
3660
5376
  async consumeCompleteChunk(registration, handle, cursor, complete, device, inode) {
3661
5377
  let activeTask = cursor.active_task;
3662
5378
  let lastOrdinal = cursor.last_ordinal;
5379
+ let humanWindow = cursor.human_message_window ?? { messages: [], truncated: false };
3663
5380
  let records = 0;
3664
5381
  let enqueued = 0;
3665
5382
  for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3666
- const record = decodeCodexTranscriptLine(line);
3667
- assertRecordSequence(registration, cursor, records, lastOrdinal, record);
3668
- await this.observeSessionMetadata(registration, record);
3669
- const outcome = await this.processRecord(registration, activeTask, record);
5383
+ const record2 = decodeCodexTranscriptLine(line);
5384
+ assertRecordSequence(registration, cursor, records, lastOrdinal, record2);
5385
+ const message = codexHumanMessage(registration, record2);
5386
+ if (message !== null) humanWindow = mergeHostInvocationHumanMessageWindow(humanWindow, [message]);
5387
+ await this.observeSessionMetadata(registration, record2);
5388
+ const outcome = await this.processRecord(registration, activeTask, record2);
3670
5389
  activeTask = outcome.activeTask;
3671
5390
  enqueued += outcome.enqueued;
3672
- lastOrdinal = record.ordinal;
5391
+ lastOrdinal = record2.ordinal;
3673
5392
  records += 1;
3674
5393
  }
3675
- await this.commitCursor(registration, handle, cursor, complete.length, device, inode, lastOrdinal, activeTask);
5394
+ await this.commitCursor(registration, handle, cursor, complete.length, device, inode, lastOrdinal, activeTask, humanWindow);
3676
5395
  return { records, enqueued, quarantined: false };
3677
5396
  }
3678
- async observeSessionMetadata(registration, record) {
3679
- if (record.kind !== "session_meta") return;
5397
+ async observeSessionMetadata(registration, record2) {
5398
+ if (record2.kind !== "session_meta") return;
3680
5399
  const session = await this.store.readSession(registration.host_source_ref, registration.host_session_ref);
3681
- if (session !== null && this.isRecord(session.value)) await this.store.saveSession({ ...session, value: { ...session.value, host_version: record.cli_version } });
5400
+ if (session !== null && this.isRecord(session.value)) await this.store.saveSession({ ...session, value: { ...session.value, host_version: record2.cli_version } });
3682
5401
  }
3683
- async commitCursor(registration, handle, cursor, consumedBytes, device, inode, lastOrdinal, activeTask) {
5402
+ async commitCursor(registration, handle, cursor, consumedBytes, device, inode, lastOrdinal, activeTask, humanWindow) {
3684
5403
  const offset = cursor.offset + consumedBytes;
3685
5404
  const anchor = await this.readAnchor(handle, offset, CODEX_TRANSCRIPT_ANCHOR_BYTES);
3686
- await this.store.writeTranscriptCursor({ schema_version: "ceal.codex_transcript_cursor.v1", host_source_ref: registration.host_source_ref, host_session_ref: registration.host_session_ref, transcript_path: registration.transcript_path, device, inode, offset, last_ordinal: lastOrdinal, anchor_start: anchor.start, anchor_sha256: anchor.sha256, header_validated: true, ...activeTask === void 0 ? {} : { active_task: activeTask }, status: "active", updated_at: this.stamp() });
5405
+ await this.store.writeTranscriptCursor({ ...cursor, transcript_path: registration.transcript_path, device, inode, offset, last_ordinal: lastOrdinal, anchor_start: anchor.start, anchor_sha256: anchor.sha256, header_validated: cursor.header_validated || consumedBytes > 0, human_message_window: humanWindow, ...activeTask === void 0 ? { active_task: void 0 } : { active_task: activeTask }, status: "active", updated_at: this.stamp() });
3687
5406
  }
3688
5407
  async quarantineFailure(registration, handle) {
3689
5408
  if (handle === void 0) return;
@@ -3701,40 +5420,40 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3701
5420
  };
3702
5421
  await this.store.writeTranscriptCursor(quarantined);
3703
5422
  }
3704
- async processRecord(registration, activeTask, record) {
3705
- if (record.kind === "task_started") return this.processTaskStarted(registration, record);
3706
- if (record.kind === "turn_context") return { ...activeTask === void 0 ? {} : { activeTask: record.turn_id === activeTask.codex_turn_id ? { ...activeTask, model: record.model } : activeTask }, enqueued: 0 };
3707
- if (record.kind === "token_count") return { ...activeTask === void 0 ? {} : { activeTask: accumulateTokenCount(activeTask, record) }, enqueued: 0 };
3708
- if (record.kind === "user_text") return this.processUserInput(registration, activeTask, record);
3709
- if (record.kind === "task_complete" || record.kind === "turn_aborted") return this.processTerminal(registration, activeTask, record);
5423
+ async processRecord(registration, activeTask, record2) {
5424
+ if (record2.kind === "task_started") return this.processTaskStarted(registration, record2);
5425
+ if (record2.kind === "turn_context") return { ...activeTask === void 0 ? {} : { activeTask: record2.turn_id === activeTask.codex_turn_id ? { ...activeTask, model: record2.model } : activeTask }, enqueued: 0 };
5426
+ if (record2.kind === "token_count") return { ...activeTask === void 0 ? {} : { activeTask: accumulateTokenCount(activeTask, record2) }, enqueued: 0 };
5427
+ if (record2.kind === "user_text") return this.processUserInput(registration, activeTask, record2);
5428
+ if (record2.kind === "task_complete" || record2.kind === "turn_aborted") return this.processTerminal(registration, activeTask, record2);
3710
5429
  return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
3711
5430
  }
3712
- async processTaskStarted(registration, record) {
3713
- return { activeTask: { codex_turn_id: record.turn_id, host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record.turn_id), started_at: record.timestamp }, enqueued: 0 };
5431
+ async processTaskStarted(registration, record2) {
5432
+ return { activeTask: { codex_turn_id: record2.turn_id, host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id), started_at: record2.timestamp }, enqueued: 0 };
3714
5433
  }
3715
- async processUserInput(registration, activeTask, record) {
3716
- if (activeTask === void 0 || activeTask.codex_turn_id !== record.turn_id) {
3717
- const adopted = await this.adoptHookCorrelatedTurn(registration, record);
5434
+ async processUserInput(registration, activeTask, record2) {
5435
+ if (activeTask === void 0 || activeTask.codex_turn_id !== record2.turn_id) {
5436
+ const adopted = await this.adoptHookCorrelatedTurn(registration, record2);
3718
5437
  if (adopted === void 0) return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
3719
5438
  activeTask = adopted;
3720
5439
  }
3721
- const hostInputRef = hostInputReference(registration.host_source_ref, registration.host_session_ref, record.turn_id, record.message_id, record.ordinal, record.prompt);
5440
+ const hostInputRef = hostInputReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id, record2.message_id, record2.ordinal, record2.prompt);
3722
5441
  const origin = activeTask.origin_host_input_ref === void 0;
3723
- const promptValue = promptObservationValue(record.prompt);
5442
+ const promptValue = promptObservationValue(record2.prompt);
3724
5443
  const currentPromptRef = hostProducerPromptRef(promptValue.body_sha256);
3725
5444
  const promptRef = activeTask.prompt_ref ?? currentPromptRef;
3726
5445
  const steeredPromptRef = await this.steeredPromptRef(registration, activeTask, origin, currentPromptRef);
3727
5446
  const identity = { host_source_ref: registration.host_source_ref, host_session_ref: registration.host_session_ref, host_turn_ref: activeTask.host_turn_ref };
3728
5447
  const observations = [{
3729
- observation_ref: observationRef(registration.host_source_ref, "transcript_user_text", hostInputRef, record.prompt),
5448
+ observation_ref: observationRef(registration.host_source_ref, "transcript_user_text", hostInputRef, record2.prompt),
3730
5449
  observation_kind: "prompt",
3731
- observed_at: record.timestamp,
5450
+ observed_at: record2.timestamp,
3732
5451
  value: promptValue
3733
5452
  }];
3734
5453
  if (origin) {
3735
- observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_task_started", activeTask.host_turn_ref, record.turn_id), observation_kind: "turn", observed_at: record.timestamp, value: turnObservationValue(registration.codex_session_id, activeTask.host_turn_ref, "started") });
5454
+ observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_task_started", activeTask.host_turn_ref, record2.turn_id), observation_kind: "turn", observed_at: record2.timestamp, value: turnObservationValue(registration.codex_session_id, activeTask.host_turn_ref, "started") });
3736
5455
  const session = await this.store.readSession(registration.host_source_ref, registration.host_session_ref);
3737
- if (session !== null) observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_session", registration.host_session_ref, session.value), observation_kind: "session", observed_at: record.timestamp, value: session.value });
5456
+ if (session !== null) observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_session", registration.host_session_ref, session.value), observation_kind: "session", observed_at: record2.timestamp, value: session.value });
3738
5457
  }
3739
5458
  const envelope = {
3740
5459
  schema_version: "ceal.codex_observation_outbox.v1",
@@ -3742,10 +5461,10 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3742
5461
  host_input_ref: hostInputRef,
3743
5462
  prompt_ref: promptRef,
3744
5463
  observations,
3745
- codex_turn_id: record.turn_id,
5464
+ codex_turn_id: record2.turn_id,
3746
5465
  origin_input: origin,
3747
- submission_ref: codexSubmissionReference(hostInputRef, "input", record.ordinal),
3748
- created_at: record.timestamp,
5466
+ submission_ref: codexSubmissionReference(hostInputRef, "input", record2.ordinal),
5467
+ created_at: record2.timestamp,
3749
5468
  expires_at: this.expire(this.outboxRetentionMs)
3750
5469
  };
3751
5470
  const persisted = await this.persistUserInputTurn(activeTask, hostInputRef, origin, currentPromptRef, promptRef, identity, envelope);
@@ -3775,14 +5494,14 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3775
5494
  * stay ignored. A stale active task for another turn releases first, the
3776
5495
  * same as a task_started supersession.
3777
5496
  */
3778
- async adoptHookCorrelatedTurn(registration, record) {
3779
- const currentPromptRef = hostProducerPromptRef(promptObservationValue(record.prompt).body_sha256);
5497
+ async adoptHookCorrelatedTurn(registration, record2) {
5498
+ const currentPromptRef = hostProducerPromptRef(promptObservationValue(record2.prompt).body_sha256);
3780
5499
  const selection = await this.store.readInvocationTurnSelection(registration.host_source_ref, registration.host_session_ref);
3781
5500
  if (selection?.prompt_ref !== currentPromptRef) return void 0;
3782
5501
  return {
3783
- codex_turn_id: record.turn_id,
3784
- host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record.turn_id),
3785
- started_at: record.timestamp
5502
+ codex_turn_id: record2.turn_id,
5503
+ host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id),
5504
+ started_at: record2.timestamp
3786
5505
  };
3787
5506
  }
3788
5507
  async persistUserInputTurn(activeTask, hostInputRef, origin, currentPromptRef, promptRef, identity, envelope) {
@@ -3801,21 +5520,21 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3801
5520
  throw error;
3802
5521
  }
3803
5522
  }
3804
- async processTerminal(registration, activeTask, record) {
3805
- if (activeTask === void 0 || activeTask.codex_turn_id !== record.turn_id || activeTask.origin_host_input_ref === void 0 || activeTask.prompt_ref === void 0) return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
5523
+ async processTerminal(registration, activeTask, record2) {
5524
+ if (activeTask === void 0 || activeTask.codex_turn_id !== record2.turn_id || activeTask.origin_host_input_ref === void 0 || activeTask.prompt_ref === void 0) return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
3806
5525
  const identity = { host_source_ref: registration.host_source_ref, host_session_ref: registration.host_session_ref, host_turn_ref: activeTask.host_turn_ref };
3807
- const timing = record.kind === "task_complete" ? { status: "available", unit: "milliseconds", started_at: record.started_at, completed_at: record.completed_at, duration_ms: record.duration_ms, time_to_first_token_ms: record.time_to_first_token_ms } : { status: "available", unit: "milliseconds", started_at: record.started_at, completed_at: record.completed_at, duration_ms: record.duration_ms, terminal: "aborted", reason: record.reason };
3808
- const observations = terminalObservations(registration, activeTask, record, timing);
5526
+ const timing = record2.kind === "task_complete" ? { status: "available", unit: "milliseconds", started_at: record2.started_at, completed_at: record2.completed_at, duration_ms: record2.duration_ms, time_to_first_token_ms: record2.time_to_first_token_ms } : { status: "available", unit: "milliseconds", started_at: record2.started_at, completed_at: record2.completed_at, duration_ms: record2.duration_ms, terminal: "aborted", reason: record2.reason };
5527
+ const observations = terminalObservations(registration, activeTask, record2, timing);
3809
5528
  await this.store.put({
3810
5529
  schema_version: "ceal.codex_observation_outbox.v1",
3811
5530
  identity,
3812
5531
  host_input_ref: activeTask.origin_host_input_ref,
3813
5532
  prompt_ref: activeTask.prompt_ref,
3814
5533
  observations,
3815
- codex_turn_id: record.turn_id,
5534
+ codex_turn_id: record2.turn_id,
3816
5535
  origin_input: false,
3817
- submission_ref: codexSubmissionReference(activeTask.origin_host_input_ref, "terminal", record.ordinal),
3818
- created_at: record.timestamp,
5536
+ submission_ref: codexSubmissionReference(activeTask.origin_host_input_ref, "terminal", record2.ordinal),
5537
+ created_at: record2.timestamp,
3819
5538
  expires_at: this.expire(this.outboxRetentionMs)
3820
5539
  });
3821
5540
  await this.store.clearInvocationContext(identity, this.now());
@@ -3826,6 +5545,29 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3826
5545
  await this.store.writeTranscriptCursor(quarantined);
3827
5546
  }
3828
5547
  };
5548
+ async function readCodexHumanMessageProjection(registration, cursor, readChunk) {
5549
+ let offset = 0;
5550
+ const state = { records: 0, lastOrdinal: 0, window: { messages: [], truncated: false } };
5551
+ while (offset < cursor.offset) {
5552
+ const complete = await readChunk(offset, cursor.offset);
5553
+ if (complete === "empty" || complete === "partial") throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix is incomplete.");
5554
+ consumeCodexHumanMessageProjectionChunk(registration, complete, state);
5555
+ offset += complete.length;
5556
+ }
5557
+ if (offset !== cursor.offset || cursor.offset > 0 && (state.records === 0 || state.lastOrdinal !== cursor.last_ordinal)) throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix does not match its cursor boundary.");
5558
+ return state.window;
5559
+ }
5560
+ function consumeCodexHumanMessageProjectionChunk(registration, complete, state) {
5561
+ for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
5562
+ const record2 = decodeCodexTranscriptLine(line);
5563
+ if (state.records === 0) assertCodexTranscriptHeader(registration, record2);
5564
+ else if (record2.ordinal <= state.lastOrdinal) throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix has a nonmonotonic ordinal.");
5565
+ const message = codexHumanMessage(registration, record2);
5566
+ if (message !== null) state.window = mergeHostInvocationHumanMessageWindow(state.window, [message]);
5567
+ state.lastOrdinal = record2.ordinal;
5568
+ state.records += 1;
5569
+ }
5570
+ }
3829
5571
  function codexTranscriptScanFailureKind(error) {
3830
5572
  return transcriptScanFailureKind(error, (candidate) => {
3831
5573
  if (!(candidate instanceof CodexHostAdapterError)) return void 0;
@@ -3834,10 +5576,10 @@ function codexTranscriptScanFailureKind(error) {
3834
5576
  return void 0;
3835
5577
  });
3836
5578
  }
3837
- function accumulateTokenCount(activeTask, record) {
3838
- if (record.usage_gap_reason !== void 0) return { ...activeTask, token_usage_gap_reason: record.usage_gap_reason };
3839
- const last = record.last_usage;
3840
- const total = record.total_usage;
5579
+ function accumulateTokenCount(activeTask, record2) {
5580
+ if (record2.usage_gap_reason !== void 0) return { ...activeTask, token_usage_gap_reason: record2.usage_gap_reason };
5581
+ const last = record2.last_usage;
5582
+ const total = record2.total_usage;
3841
5583
  if (last === void 0 || ignoreTokenCount(activeTask.last_total_usage, total, last)) return activeTask;
3842
5584
  const tokenUsage = addUsage(activeTask.token_usage, last);
3843
5585
  return {
@@ -3851,14 +5593,14 @@ function ignoreTokenCount(previous, total, last) {
3851
5593
  if (total === void 0 || previous === void 0) return false;
3852
5594
  return sameUsage(total, previous) || regressedUsage(total, previous) && looksLikeStaleRegression(total, previous, last);
3853
5595
  }
3854
- function terminalObservations(registration, activeTask, record, timing) {
5596
+ function terminalObservations(registration, activeTask, record2, timing) {
3855
5597
  const tokenValue = activeTask.token_usage_gap_reason !== void 0 ? notRecorded(activeTask.token_usage_gap_reason) : activeTask.token_usage === void 0 ? notRecorded("token_count_not_observed_for_active_turn") : tokenObservationValue(activeTask.token_usage);
3856
5598
  const observations = [
3857
- { observation_ref: observationRef(registration.host_source_ref, "transcript_terminal", activeTask.host_turn_ref, record), observation_kind: "turn", observed_at: record.timestamp, value: turnObservationValue(registration.codex_session_id, activeTask.host_turn_ref, "stopped") },
3858
- { observation_ref: observationRef(registration.host_source_ref, "transcript_timing", activeTask.host_turn_ref, timing), observation_kind: "timing", observed_at: record.timestamp, value: timing },
3859
- { observation_ref: observationRef(registration.host_source_ref, "transcript_token", activeTask.host_turn_ref, tokenValue), observation_kind: "token", observed_at: record.timestamp, value: tokenValue }
5599
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_terminal", activeTask.host_turn_ref, record2), observation_kind: "turn", observed_at: record2.timestamp, value: turnObservationValue(registration.codex_session_id, activeTask.host_turn_ref, "stopped") },
5600
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_timing", activeTask.host_turn_ref, timing), observation_kind: "timing", observed_at: record2.timestamp, value: timing },
5601
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_token", activeTask.host_turn_ref, tokenValue), observation_kind: "token", observed_at: record2.timestamp, value: tokenValue }
3860
5602
  ];
3861
- if (activeTask.model !== void 0) observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_model", activeTask.host_turn_ref, activeTask.model), observation_kind: "model", observed_at: record.timestamp, value: { status: "available", value: activeTask.model, source: "turn_context.model" } });
5603
+ if (activeTask.model !== void 0) observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_model", activeTask.host_turn_ref, activeTask.model), observation_kind: "model", observed_at: record2.timestamp, value: { status: "available", value: activeTask.model, source: "turn_context.model" } });
3862
5604
  return observations;
3863
5605
  }
3864
5606
  function notRecorded(reason) {
@@ -3907,16 +5649,24 @@ function looksLikeStaleRegression(current, previous, last) {
3907
5649
  if (previous.total_tokens <= 0 || current.total_tokens <= 0 || last.total_tokens <= 0) return false;
3908
5650
  return current.total_tokens * 100 >= previous.total_tokens * 98 || current.total_tokens + last.total_tokens * 2 >= previous.total_tokens;
3909
5651
  }
3910
- function assertRecordSequence(registration, cursor, records, lastOrdinal, record) {
3911
- if ((cursor.header_validated || records > 0) && record.ordinal <= lastOrdinal) throw new CodexHostAdapterError("payload_rejected", `Codex transcript ordinal is not monotonic (${refusalFact("ordinal", record.ordinal, `greater than ${lastOrdinal}`)}).`);
3912
- if (!cursor.header_validated && records === 0) assertCodexTranscriptHeader(registration, record);
5652
+ function codexHumanMessage(registration, record2) {
5653
+ if (record2.kind !== "user_text" || record2.content_item_kind !== "user.text") return null;
5654
+ return {
5655
+ host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id),
5656
+ host_input_ref: hostInputReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id, record2.message_id, record2.ordinal, record2.prompt),
5657
+ text: record2.prompt
5658
+ };
5659
+ }
5660
+ function assertRecordSequence(registration, cursor, records, lastOrdinal, record2) {
5661
+ if ((cursor.header_validated || records > 0) && record2.ordinal <= lastOrdinal) throw new CodexHostAdapterError("payload_rejected", `Codex transcript ordinal is not monotonic (${refusalFact("ordinal", record2.ordinal, `greater than ${lastOrdinal}`)}).`);
5662
+ if (!cursor.header_validated && records === 0) assertCodexTranscriptHeader(registration, record2);
3913
5663
  }
3914
5664
 
3915
5665
  // host/codex/src/codex-producer-runtime.ts
3916
5666
  async function drainCodexProducerOnce(options) {
3917
5667
  const scan = await new CodexTranscriptWatcher({
3918
5668
  outbox_dir: options.outbox_dir,
3919
- diagnostic: (event, failure_kind) => writeHostServiceDiagnostic("codex", event, failure_kind)
5669
+ diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
3920
5670
  }).scanOnce().catch((error) => {
3921
5671
  writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
3922
5672
  throw error;
@@ -3925,6 +5675,237 @@ async function drainCodexProducerOnce(options) {
3925
5675
  return { scanned: scan.enqueued, ...await producer.drainOutbox() };
3926
5676
  }
3927
5677
 
5678
+ // host/codex/src/codex-usage-facts-capturer.ts
5679
+ import { createHash as createHash9 } from "node:crypto";
5680
+ var CodexUsageFactsCapturer = class {
5681
+ sources;
5682
+ usage;
5683
+ now;
5684
+ diagnosticSink;
5685
+ nextRegistrationIndex = 0;
5686
+ constructor(options) {
5687
+ this.sources = new CodexOutboxStore(options.outbox_dir);
5688
+ this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5689
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5690
+ this.diagnosticSink = options.diagnostic_sink;
5691
+ }
5692
+ async captureNext() {
5693
+ const registrations = await this.sources.listTranscriptRegistrations();
5694
+ const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
5695
+ this.nextRegistrationIndex = result.nextIndex;
5696
+ if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5697
+ return result.captured;
5698
+ }
5699
+ async captureRegistration(registration) {
5700
+ const prepared = await openHostUsageTranscriptCursor({
5701
+ path: registration.transcript_path,
5702
+ producer: "codex",
5703
+ source_kind: "codex_transcript",
5704
+ host_source_ref: registration.host_source_ref,
5705
+ host_session_ref: registration.host_session_ref,
5706
+ source_slot: "main",
5707
+ created_at: this.stamp(),
5708
+ store: this.usage,
5709
+ inspect: ownedCodexTranscriptFile,
5710
+ initial_cursor: initialCursor
5711
+ });
5712
+ if (prepared === null) return false;
5713
+ const { handle, source, source_file_ref: sourceFileRef, state, cursor: current } = prepared;
5714
+ try {
5715
+ if (await cursorReplaced(handle, source, sourceFileRef, current)) {
5716
+ const after = replacementCursor(sourceFileRef, source.device, source.inode);
5717
+ const gap = coverageGap("source_file_replaced", null, null, null, null);
5718
+ await this.usage.commitScanTransition(state, "main", current, after, null, [gap]);
5719
+ return true;
5720
+ }
5721
+ if (source.size === current.offset && !current.skipping_oversized_line) return false;
5722
+ return await this.captureChunk(handle, registration, current, sourceFileRef, source.size, state);
5723
+ } finally {
5724
+ await handle.close();
5725
+ }
5726
+ }
5727
+ async captureChunk(handle, registration, before, sourceFileRef, size, state) {
5728
+ const chunk = await readHostUsageTranscriptChunk(handle, before.offset, size, before.skipping_oversized_line);
5729
+ if (chunk.end_offset === before.offset && chunk.lines.length === 0) return false;
5730
+ const processed = processCodexLines(chunk.lines, registration, sourceFileRef, before, chunk.oversized_rows);
5731
+ const after = await updateAnchor(handle, { ...processed.cursor, offset: chunk.end_offset, skipping_oversized_line: chunk.skipping_oversized_line });
5732
+ const gaps = buildCoverageGaps(sourceFileRef, before.offset, chunk.end_offset, processed.gapCounts);
5733
+ const batch = processed.facts.length === 0 && gaps.length === 0 ? null : createCealHostUsageBatch({
5734
+ host_source_ref: registration.host_source_ref,
5735
+ host_session_ref: registration.host_session_ref,
5736
+ created_at: processed.createdAt,
5737
+ source_ranges: [{ source_file_ref: sourceFileRef, start_offset: before.offset, end_offset: chunk.end_offset }],
5738
+ facts: processed.facts,
5739
+ coverage_gaps: gaps
5740
+ });
5741
+ await this.usage.commitScanTransition(state, "main", before, after, batch);
5742
+ return true;
5743
+ }
5744
+ stamp() {
5745
+ const value = this.now();
5746
+ if (!Number.isFinite(value.getTime())) throw new Error("Codex usage facts clock is invalid.");
5747
+ return value.toISOString();
5748
+ }
5749
+ };
5750
+ function processCodexLines(lines, registration, sourceFileRef, initial, oversizedRows) {
5751
+ let cursor = initial;
5752
+ let createdAt = registration.registered_at;
5753
+ let records = 0;
5754
+ const facts = [];
5755
+ const gapCounts = /* @__PURE__ */ new Map();
5756
+ if (oversizedRows > 0) gapCounts.set("unsupported_source_shape", oversizedRows);
5757
+ for (const bytes of lines) {
5758
+ const record2 = decodeCodexLine(bytes);
5759
+ if (record2 === null || !validInitialHeader(record2, registration, initial.offset, records) || !hasIncreasingOrdinal(cursor, record2)) {
5760
+ addCodexGap(gapCounts, "unsupported_source_shape");
5761
+ records += 1;
5762
+ continue;
5763
+ }
5764
+ createdAt = record2.timestamp;
5765
+ cursor = applyCodexRecord(cursor, record2, registration, sourceFileRef, facts, gapCounts);
5766
+ cursor = { ...cursor, last_ordinal: record2.ordinal };
5767
+ records += 1;
5768
+ }
5769
+ return { cursor, facts, gapCounts, createdAt };
5770
+ }
5771
+ function decodeCodexLine(bytes) {
5772
+ try {
5773
+ return decodeCodexUsageTranscriptLine(bytes.toString("utf8"));
5774
+ } catch {
5775
+ return null;
5776
+ }
5777
+ }
5778
+ function validInitialHeader(record2, registration, initialOffset, records) {
5779
+ if (initialOffset !== 0 || records !== 0) return true;
5780
+ try {
5781
+ assertCodexTranscriptHeader(registration, record2);
5782
+ return true;
5783
+ } catch {
5784
+ return false;
5785
+ }
5786
+ }
5787
+ function hasIncreasingOrdinal(cursor, record2) {
5788
+ return cursor.last_ordinal === null || record2.ordinal > cursor.last_ordinal;
5789
+ }
5790
+ function applyCodexRecord(cursor, record2, registration, sourceFileRef, facts, gapCounts) {
5791
+ if (record2.kind === "token_count") return applyTokenCount(cursor, registration, sourceFileRef, record2, facts, gapCounts);
5792
+ if (record2.kind === "task_started") return { ...cursor, host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id), native_turn_id: record2.turn_id, requested_model: null, codex_total_usage: null };
5793
+ if (record2.kind === "turn_context" && cursor.native_turn_id === record2.turn_id) return { ...cursor, requested_model: record2.model };
5794
+ if ((record2.kind === "task_complete" || record2.kind === "turn_aborted") && cursor.native_turn_id === record2.turn_id) return { ...cursor, host_turn_ref: null, native_turn_id: null, requested_model: null, codex_total_usage: null };
5795
+ return cursor;
5796
+ }
5797
+ function applyTokenCount(cursor, registration, sourceFileRef, record2, facts, gapCounts) {
5798
+ if (record2.usage_gap_reason !== void 0 || record2.last_usage === void 0 && record2.total_usage === void 0) addCodexGap(gapCounts, "source_usage_unavailable");
5799
+ else facts.push(codexUsageFact(registration, sourceFileRef, cursor, record2));
5800
+ return { ...cursor, codex_total_usage: record2.total_usage ?? cursor.codex_total_usage };
5801
+ }
5802
+ function addCodexGap(gaps, reason) {
5803
+ gaps.set(reason, (gaps.get(reason) ?? 0) + 1);
5804
+ }
5805
+ function initialCursor(sourceFileRef, device, inode) {
5806
+ return {
5807
+ source_file_ref: sourceFileRef,
5808
+ device,
5809
+ inode,
5810
+ offset: 0,
5811
+ anchor_start: 0,
5812
+ anchor_sha256: sha2564(Buffer.alloc(0)),
5813
+ last_ordinal: null,
5814
+ host_turn_ref: null,
5815
+ native_turn_id: null,
5816
+ requested_model: null,
5817
+ codex_total_usage: null,
5818
+ skipping_oversized_line: false
5819
+ };
5820
+ }
5821
+ function codexUsageFact(registration, sourceFileRef, cursor, record2) {
5822
+ const sourceEventRef = hostUsageSourceEventReference(sourceFileRef, `codex:${record2.ordinal}`);
5823
+ const total = record2.total_usage;
5824
+ const cumulativeTransition = transitionKind(cursor.codex_total_usage, total);
5825
+ const selected = record2.last_usage ?? total;
5826
+ const normalized = normalizedCounts(selected);
5827
+ return {
5828
+ fact_ref: hostUsageFactReference(sourceFileRef, sourceEventRef),
5829
+ host_session_ref: registration.host_session_ref,
5830
+ host_turn_ref: cursor.host_turn_ref,
5831
+ source_file_ref: sourceFileRef,
5832
+ source_event_ref: sourceEventRef,
5833
+ source_event_ordinal: record2.ordinal,
5834
+ observed_at: record2.timestamp,
5835
+ producer: "codex_transcript",
5836
+ requested_model: cursor.requested_model,
5837
+ reported_model: null,
5838
+ source_usage: { last_token_usage: record2.last_usage ?? null, total_token_usage: total ?? null },
5839
+ normalized_usage: normalized,
5840
+ counter_semantics: record2.last_usage !== void 0 && total !== void 0 ? "last_delta_total_cumulative" : total !== void 0 ? "total_cumulative_only" : "unknown",
5841
+ cumulative_transition: cumulativeTransition,
5842
+ finality: "unknown",
5843
+ correction_semantics: "unknown"
5844
+ };
5845
+ }
5846
+ function transitionKind(baseline, total) {
5847
+ if (total === void 0) return "not_observed";
5848
+ if (baseline === null) return "baseline";
5849
+ if (sameCounts(baseline, total)) return "same";
5850
+ return isRegression(total, baseline) ? "reset_or_correction" : "advanced";
5851
+ }
5852
+ function normalizedCounts(selected) {
5853
+ return selected === void 0 ? nullCounts() : {
5854
+ input: selected.input_tokens,
5855
+ output: selected.output_tokens,
5856
+ total: selected.total_tokens,
5857
+ cached_input: selected.cached_input_tokens,
5858
+ cache_write_input: selected.cache_write_input_tokens,
5859
+ reasoning_output: selected.reasoning_output_tokens
5860
+ };
5861
+ }
5862
+ function nullCounts() {
5863
+ return { input: null, output: null, total: null, cached_input: null, cache_write_input: null, reasoning_output: null };
5864
+ }
5865
+ var USAGE_COUNT_FIELDS = ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
5866
+ function isRegression(current, previous) {
5867
+ return USAGE_COUNT_FIELDS.some((key) => current[key] < previous[key]);
5868
+ }
5869
+ function sameCounts(left, right) {
5870
+ return USAGE_COUNT_FIELDS.every((key) => left[key] === right[key]);
5871
+ }
5872
+ function buildCoverageGaps(sourceFileRef, startOffset, endOffset, counts) {
5873
+ return [...counts].map(([reason, omittedCount]) => coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount));
5874
+ }
5875
+ function coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount) {
5876
+ return { reason, source_file_ref: sourceFileRef, start_offset: startOffset, end_offset: endOffset, omitted_count: omittedCount };
5877
+ }
5878
+ function sha2564(value) {
5879
+ return createHash9("sha256").update(value).digest("hex");
5880
+ }
5881
+ async function anchorMatches(handle, cursor) {
5882
+ const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
5883
+ if (bytes.length === 0) return sha2564(bytes) === cursor.anchor_sha256;
5884
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, cursor.anchor_start));
5885
+ return bytesRead === bytes.length && sha2564(bytes) === cursor.anchor_sha256;
5886
+ }
5887
+ async function cursorReplaced(handle, source, sourceFileRef, cursor) {
5888
+ return cursor.source_file_ref !== sourceFileRef || cursor.device !== source.device || cursor.inode !== source.inode || source.size < cursor.offset || !await anchorMatches(handle, cursor);
5889
+ }
5890
+ function replacementCursor(sourceFileRef, device, inode) {
5891
+ return {
5892
+ ...initialCursor(sourceFileRef, device, inode),
5893
+ source_file_ref: sourceFileRef,
5894
+ device,
5895
+ inode,
5896
+ offset: 0
5897
+ };
5898
+ }
5899
+ async function updateAnchor(handle, cursor) {
5900
+ const anchorStart = Math.max(0, cursor.offset - CODEX_TRANSCRIPT_ANCHOR_BYTES);
5901
+ const anchor = Buffer.alloc(cursor.offset - anchorStart);
5902
+ if (anchor.length > 0) {
5903
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(anchor, 0, anchor.length, anchorStart));
5904
+ if (bytesRead !== anchor.length) throw new Error("Codex usage facts source changed during anchor read.");
5905
+ }
5906
+ return { ...cursor, anchor_start: anchorStart, anchor_sha256: sha2564(anchor) };
5907
+ }
5908
+
3928
5909
  // host/codex/src/codex-producer-service.ts
3929
5910
  var CODEX_PRODUCER_CONFIG_SCHEMA = "ceal.codex_producer_config.v1";
3930
5911
  var CODEX_SESSIONS_ROOT = "codex_sessions_root";
@@ -3933,10 +5914,12 @@ var CODEX_PRODUCER_DESCRIPTOR = {
3933
5914
  producer_id: "codex",
3934
5915
  extra_paths: [CODEX_SESSIONS_ROOT],
3935
5916
  config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
3936
- runtime_options: (config) => Object.freeze({
3937
- outbox_dir: config.outbox_dir
3938
- }),
3939
- drain: drainCodexProducerOnce
5917
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
5918
+ drain: drainCodexProducerOnce,
5919
+ background: (config, signal) => {
5920
+ const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });
5921
+ return runHostUsageFactsUploader({ producer: "codex", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext() }, signal);
5922
+ }
3940
5923
  };
3941
5924
  function runCodexProducerCli(args, signal, dependencies = {}) {
3942
5925
  return runHostProducerCli(CODEX_PRODUCER_DESCRIPTOR, args, signal, dependencies);
@@ -3955,8 +5938,7 @@ async function runProducerCommand(schemaVersion, run) {
3955
5938
  await run(serviceArguments.args, controller.signal);
3956
5939
  } catch (error) {
3957
5940
  const code = typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "producer_failed";
3958
- process.stderr.write(`${JSON.stringify({ schema_version: schemaVersion, ok: false, code })}
3959
- `);
5941
+ await writeHostServiceCommandResult(schemaVersion, { ok: false, code }, (line) => process.stderr.write(line));
3960
5942
  process.exitCode = 1;
3961
5943
  } finally {
3962
5944
  stopLogBound();