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

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.
@@ -4,8 +4,18 @@ const require = __cealCreateRequire(import.meta.url);
4
4
 
5
5
  // host/codex/src/codex-adapter.ts
6
6
  import { randomUUID } from "node:crypto";
7
+ import { realpath } from "node:fs/promises";
7
8
  import { homedir } from "node:os";
8
- import { isAbsolute as isAbsolute3, relative, resolve as resolve2 } from "node:path";
9
+ import { isAbsolute as isAbsolute4, relative, resolve as resolve2 } from "node:path";
10
+
11
+ // packages/ceal-client-protocol/src/vocabulary.ts
12
+ function vocabulary(words) {
13
+ return Object.freeze(words);
14
+ }
15
+
16
+ // packages/ceal-client-protocol/src/host-usage-fields.ts
17
+ var CEAL_CODEX_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
18
+ var CEAL_CLAUDE_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"]);
9
19
 
10
20
  // packages/ceal-client-protocol/src/canonical-json.ts
11
21
  function cealCanonicalJson(value) {
@@ -35,7 +45,7 @@ function isPlainRecord(value) {
35
45
  }
36
46
 
37
47
  // packages/ceal-client-protocol/src/client-wire-contract.ts
38
- import { createHash } from "node:crypto";
48
+ import { createHash as createHash2 } from "node:crypto";
39
49
 
40
50
  // packages/ceal-client-protocol/client-wire-contract.json
41
51
  var client_wire_contract_default = {
@@ -56,7 +66,7 @@ var client_wire_contract_default = {
56
66
  ordering: "utf16_code_unit_ascending"
57
67
  },
58
68
  artifact_descriptor: {
59
- operation_contract_bundle_schema_name: "ceal.operation_contract_bundle",
69
+ operation_contract_bundle_schema_name: "ceal.operation_contract_bundle_v2",
60
70
  operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
61
71
  schema_name: "ceal.verified_artifact_descriptor",
62
72
  fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
@@ -81,7 +91,7 @@ var client_wire_contract_default = {
81
91
  },
82
92
  command_request: {
83
93
  schema_name: "ceal.command_request",
84
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
94
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
85
95
  absolute_transport_max_bytes: 65536
86
96
  },
87
97
  command_resolution: {
@@ -127,8 +137,9 @@ var client_wire_contract_default = {
127
137
  },
128
138
  command_response: {
129
139
  schema_name: "ceal.command_response",
130
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
140
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
131
141
  descriptor_field: "verified_artifact",
142
+ request_context_field: "request_context",
132
143
  required_fields: [
133
144
  "schema_version",
134
145
  "exit_code",
@@ -138,7 +149,8 @@ var client_wire_contract_default = {
138
149
  "operation_id",
139
150
  "visible_output_max_bytes",
140
151
  "local_delivery",
141
- "verified_artifact"
152
+ "verified_artifact",
153
+ "request_context"
142
154
  ],
143
155
  bare_document_fields: [
144
156
  "invocation",
@@ -159,7 +171,7 @@ var client_wire_contract_default = {
159
171
  ],
160
172
  exit_code_max: 125,
161
173
  bare_document_max_bytes: 65536,
162
- complete_max_bytes: 66046
174
+ complete_max_bytes: 66195
163
175
  },
164
176
  host_invocation_authentication: {
165
177
  request_schema_name: "ceal.host_invocation_authentication_request",
@@ -173,6 +185,17 @@ var client_wire_contract_default = {
173
185
  "context_token",
174
186
  "expires_at"
175
187
  ],
188
+ refusal_schema_name: "ceal.host_invocation_authentication_refusal",
189
+ refusal_fields: [
190
+ "schema_version",
191
+ "ok",
192
+ "code",
193
+ "reason",
194
+ "gateway_status",
195
+ "retry_after_ms"
196
+ ],
197
+ refusal_required_fields: ["schema_version", "ok", "code", "reason"],
198
+ refusal_optional_fields: ["gateway_status", "retry_after_ms"],
176
199
  client_nonce: {
177
200
  character_class_source: "A-Za-z0-9_-",
178
201
  encoded_characters: 43
@@ -211,6 +234,8 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
211
234
  "choose_new_output_path",
212
235
  "choose_new_idempotency_key",
213
236
  "restart_search",
237
+ // The requested temporal key is absent on some observed rows; repeating the same interval without `order` can return those rows.
238
+ "search_without_order",
214
239
  "repeat_original_arguments",
215
240
  // The occurrence this call addressed is settled and cannot move again -- a
216
241
  // denied effect approval, an expired continuation -- so the caller runs the
@@ -269,6 +294,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
269
294
  // The command needs caller-owned local materialization (for example an
270
295
  // @path file) before the Gateway can receive the argument.
271
296
  "materialize_local_argument",
297
+ // A missing or stale local Host bundle is repaired through its installed lifecycle and discovery owners.
298
+ "install_ceal_host",
299
+ // An explicit Client store override points at a missing file; unsetting it selects the one canonical default store without creating a second credential store.
300
+ "unset_context_store_path",
301
+ // The producer app must reload its installed Host hook before it can start a conversation with invocation context.
302
+ "restart_producer_app",
272
303
  // A peer's derived schema identifier changed with its field set; install or
273
304
  // upgrade the CLI and Host Relay to the Gateway's release before retrying.
274
305
  "upgrade_ceal_client"
@@ -377,18 +408,12 @@ var NON_MODEL_ACTION_TO_MODEL_ACTION = Object.freeze({
377
408
  });
378
409
  var RETRY_PROMISE_NEXT_ACTIONS = ["retry", "retry_after"];
379
410
  var RETRY_PROMISE = new Set(RETRY_PROMISE_NEXT_ACTIONS);
380
- var RECOVERABLE = new Set(CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS);
381
411
  var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
382
412
  provider_permission: "ask_admin",
383
413
  access_level: "ask_admin",
384
414
  personal_authorization_required: "connect_personal_account"
385
415
  });
386
416
 
387
- // packages/ceal-client-protocol/src/vocabulary.ts
388
- function vocabulary(words) {
389
- return Object.freeze(words);
390
- }
391
-
392
417
  // packages/ceal-client-protocol/src/gateway-response-types.ts
393
418
  var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
394
419
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
@@ -399,9 +424,9 @@ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "s
399
424
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
400
425
  var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
401
426
  var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
402
- var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "scope_limit_exceeded"]);
427
+ var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
403
428
  var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
404
- var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable"]);
429
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
405
430
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
406
431
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
407
432
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -472,10 +497,10 @@ function assertSafeJsonArray(value, options, depth, count) {
472
497
  if (value.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
473
498
  for (const item of value) assertSafeJsonValue(item, options, depth + 1, count);
474
499
  }
475
- function assertSafeJsonRecord(record, options, depth, count) {
476
- const entries = Object.entries(record);
500
+ function assertSafeJsonRecord(record2, options, depth, count) {
501
+ const entries = Object.entries(record2);
477
502
  if (entries.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
478
- const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record.fields) : null;
503
+ const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record2.fields) : null;
479
504
  for (const [key, child] of entries) {
480
505
  if (key === "credential_material_included" && child !== false) invalidByContext(options);
481
506
  if (!isSafeNegativeMaterialAssertion(key, child)) assertSafeJsonKey(key, options);
@@ -525,16 +550,21 @@ function isSafeExternalHttpsUrl(value) {
525
550
  return false;
526
551
  }
527
552
  }
553
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE = "^https://[^\\s/@?#]+(?:[/?#][^\\s]*)?$";
554
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN = new RegExp(SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE, "u");
528
555
  function isSafeExternalHttpsUrlInput(value) {
529
556
  return typeof value === "string" && byteLength(value) <= 2048;
530
557
  }
531
- function isSafeExternalHttpsUrlShape(url) {
532
- return url.protocol === "https:" && url.username === "" && url.password === "" && url.hash === "";
558
+ function isSafeExternalHttpsUrlShape(url, allowFragment = false) {
559
+ return url.protocol === "https:" && url.hostname.length > 0 && url.username === "" && url.password === "" && (allowFragment || url.hash === "");
533
560
  }
534
561
  function isSafeResultContent(value, key) {
535
562
  const maximum = key === "text" ? 8192 : 1024;
536
563
  return typeof value === "string" && byteLength(value) <= maximum && firstDisallowedControl(value, "multi_line") === null;
537
564
  }
565
+ function requireSafeRef(value) {
566
+ if (typeof value !== "string" || !SAFE_REF.test(value)) invalidRequestOrResponse();
567
+ }
538
568
  var CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES = 512;
539
569
  function normalizeCealSingleLineText(value) {
540
570
  return value.split("").map((character) => hasControlCharacter(character) ? " " : character).join("").trim();
@@ -646,6 +676,7 @@ function cut(text) {
646
676
 
647
677
  // packages/ceal-client-protocol/src/operation-validation-primitives.ts
648
678
  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;
679
+ var EXPANDED_CANONICAL_ISO_TIMESTAMP = /^([+-])(\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/u;
649
680
  var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
650
681
  var CEAL_CALENDAR_DATE = new RegExp(CEAL_CALENDAR_DATE_PATTERN_SOURCE, "u");
651
682
  function isOperationRecord(value) {
@@ -656,13 +687,46 @@ function isOperationRecord(value) {
656
687
  function requireOperationRecord(value, message) {
657
688
  if (!isOperationRecord(value)) throw new TypeError(message);
658
689
  }
690
+ function requireExactOperationKeys(value, required, optional = [], message = "Operation contract has an invalid shape.") {
691
+ const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
692
+ if (required.some((key) => !Object.hasOwn(value, key))) throw new TypeError(message);
693
+ if (Object.keys(value).some((key) => !allowed.has(key))) throw new TypeError(message);
694
+ }
659
695
  function requireClosedValue(value, members, message) {
660
696
  if (typeof value !== "string" || !members.includes(value)) throw new TypeError(message);
661
697
  }
662
698
  function isCealIsoTimestamp(value) {
663
699
  return typeof value === "string" && parseCealIsoTimestamp(value) !== null;
664
700
  }
701
+ function canonicalCealIsoTimestamp(epochNanoseconds) {
702
+ const wholeSeconds = floorDivide(epochNanoseconds, 1000000000n);
703
+ const fractionalNanoseconds = epochNanoseconds - wholeSeconds * 1000000000n;
704
+ const utc = new Date(Number(wholeSeconds * 1000n));
705
+ const date = utc.toISOString().split(".")[0];
706
+ if (date === void 0) throw new TypeError("Ceal timestamp formatter returned an invalid ISO string");
707
+ const fraction = fractionalNanoseconds.toString().padStart(9, "0").replace(/0+$/u, "").padEnd(3, "0");
708
+ return date + "." + fraction + "Z";
709
+ }
710
+ var CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE = "0000-01-01T00:00:00.000000000+23:59";
711
+ var CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE = "9999-12-31T23:59:59.999999999-23:59";
712
+ var CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE);
713
+ var CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE);
714
+ var CEAL_INSTANT_INDEX_SPAN = CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS - CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS;
715
+ var CEAL_INSTANT_INDEX_KEY_WIDTH = CEAL_INSTANT_INDEX_SPAN.toString().length;
716
+ var CEAL_INSTANT_INDEX_KEY_PATTERN = new RegExp(`^\\d{${CEAL_INSTANT_INDEX_KEY_WIDTH}}$`, "u");
717
+ function requiredTimestampEpochNanoseconds(value) {
718
+ const parsed = parseFourDigitCealIsoTimestamp(value);
719
+ if (parsed === null) throw new Error("Ceal instant-index range basis is outside the timestamp grammar");
720
+ return parsed.epochNanoseconds;
721
+ }
665
722
  function parseCealIsoTimestamp(value) {
723
+ const ordinary = parseFourDigitCealIsoTimestamp(value);
724
+ if (ordinary !== null) return ordinary;
725
+ const expanded = parseExpandedCanonicalCealIsoTimestamp(value);
726
+ if (expanded === null || expanded.epochNanoseconds < CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS || expanded.epochNanoseconds > CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS) return null;
727
+ return canonicalCealIsoTimestamp(expanded.epochNanoseconds) === value ? expanded : null;
728
+ }
729
+ function parseFourDigitCealIsoTimestamp(value) {
666
730
  const fields = parseCealIsoTimestampFields(value);
667
731
  if (fields === null || !validCalendarDate(fields) || !validClockTime(fields) || !validUtcOffset(fields)) return null;
668
732
  const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
@@ -671,6 +735,28 @@ function parseCealIsoTimestamp(value) {
671
735
  epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
672
736
  };
673
737
  }
738
+ function parseExpandedCanonicalCealIsoTimestamp(value) {
739
+ const match = EXPANDED_CANONICAL_ISO_TIMESTAMP.exec(value);
740
+ if (match === null) return null;
741
+ const fields = {
742
+ year: (match[1] === "-" ? -1 : 1) * Number(match[2]),
743
+ month: Number(match[3]),
744
+ day: Number(match[4]),
745
+ hour: Number(match[5]),
746
+ minute: Number(match[6]),
747
+ second: Number(match[7]),
748
+ fraction: match[8] ?? "",
749
+ offsetSign: 0,
750
+ offsetHour: 0,
751
+ offsetMinute: 0
752
+ };
753
+ if (!validCalendarDate(fields) || !validClockTime(fields)) return null;
754
+ const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
755
+ if (!Number.isFinite(epochMilliseconds)) return null;
756
+ return {
757
+ epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
758
+ };
759
+ }
674
760
  function parseCealIsoTimestampFields(value) {
675
761
  const match = ISO_TIMESTAMP.exec(value);
676
762
  if (match === null) return null;
@@ -703,6 +789,10 @@ function cealFieldsEpochMilliseconds(fields) {
703
789
  const offsetMilliseconds = fields.offsetSign * (fields.offsetHour * 60 + fields.offsetMinute) * 6e4;
704
790
  return localMilliseconds - offsetMilliseconds;
705
791
  }
792
+ function floorDivide(value, divisor) {
793
+ const quotient = value / divisor;
794
+ return value % divisor < 0n ? quotient - 1n : quotient;
795
+ }
706
796
  function daysInMonth(year, month) {
707
797
  const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
708
798
  return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
@@ -720,6 +810,9 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
720
810
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
721
811
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
722
812
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
813
+ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
814
+ 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.";
815
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
723
816
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
724
817
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
725
818
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
@@ -745,6 +838,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
745
838
  refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
746
839
  refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
747
840
  refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
841
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
842
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
748
843
  refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
749
844
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
750
845
  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),
@@ -757,8 +852,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
757
852
  response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
758
853
  request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
759
854
  request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
855
+ resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
760
856
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
761
- 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),
857
+ contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
762
858
  // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
763
859
  // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
764
860
  // when the wait ends still unserved, moved from the `localFailureText` default branch.
@@ -768,13 +864,12 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
768
864
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
769
865
  internal_error: guidance("The Gateway failed without exposing internal state.", "answer_with_gap", 500),
770
866
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
771
- // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
867
+ // the static client variant was retired when the client started reading this table.
772
868
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
773
- // Restored verbatim from the retired `localFailureText` `unknown_outcome`
774
- // case: the outcome is unknown, so a read may be retried while a write
775
- // must receipt-check first. Collapsing both to "do not repeat the call"
776
- // forbids the safe read retry the sentence exists to allow.
777
- unknown_outcome: guidance("The transport outcome is unknown: a read may be retried; for a write, check write_receipt.get before repeating.", "answer_with_gap", 500),
869
+ gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
870
+ // The safe move varies by request. Keep the sentence conditional on the
871
+ // same `retryable` and `next_action` facts the response exposes.
872
+ unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
778
873
  // Restored verbatim from the retired `localFailureText`
779
874
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
780
875
  // session context unavailable, so the caller repairs or adopts the
@@ -855,24 +950,27 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
855
950
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
856
951
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
857
952
  // is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
858
- // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). The three rows
859
- // with their own sentences carry the retired policy remedies as Gateway-owned guidance. Statuses are the
953
+ // and `retryable` from `hostAuthenticationFailureForCause` (the table's explicit retry verdict). Cause-specific
954
+ // sentences carry only remedies proved by the Host or Relay cause; generic Gateway refusals do not prove a release mismatch.
955
+ // Statuses are the
860
956
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
861
957
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
862
958
  host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
863
959
  host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
864
960
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
865
- // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
866
- // missing exact-turn fact names the fresh Host turn, not a reinstall.
867
- 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),
868
- host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
869
- host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
961
+ // The bounded Host reason does not prove ephemerality. A Host refusal never
962
+ // changes mode; standalone remains the separate Client authority path.
963
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
964
+ host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
965
+ host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
966
+ host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
870
967
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
871
968
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
872
969
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
873
970
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
874
971
  host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
875
972
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
973
+ host_contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
876
974
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
877
975
  // producer-frame fault names the administrator repair step.
878
976
  host_producer_frame_invalid: guidance("Ask an administrator to inspect and repair the producer frame, then start a fresh Host turn.", "ask_admin", 400),
@@ -882,56 +980,13 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
882
980
  host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
883
981
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
884
982
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
885
- host_relay_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
983
+ host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
886
984
  host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
887
985
  });
888
986
  var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
889
987
 
890
- // packages/ceal-client-protocol/src/client-wire-contract.ts
891
- var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
892
- var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
893
- var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
894
- var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
895
- var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
896
- var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
897
- function deriveCealClientWireSchemaVersion(schema) {
898
- 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))) {
899
- throw new TypeError("Client wire schema name or field set is invalid.");
900
- }
901
- const fields = schema.fields.filter((field) => field !== "schema_version").sort();
902
- const hash8 = createHash("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
903
- return `${schema.schema_name}.v1.${hash8}`;
904
- }
905
- var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
906
- var commandResolutionAuthority = commandResolution.authority;
907
- var commandResolutionSemanticOptions = commandResolution.semantic_options;
908
- var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
909
- var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
910
- var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
911
- var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
912
- var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
913
- var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
914
- var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
915
- var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
916
- var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
917
- var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
918
- var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
919
- var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
920
- var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
921
- var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
922
- var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
923
- var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
924
- var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
925
- var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
926
- var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
927
- var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
928
- var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
929
- var CEAL_COMMAND_RESPONSE_DISCOVERY_COMMAND = response.discovery_command;
930
- var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
931
- var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
932
- var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_DOCUMENT_FIELDS = Object.freeze([...response.discovery_manifest_document_fields]);
933
- 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 });
934
- var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
988
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
989
+ import { createHash } from "node:crypto";
935
990
 
936
991
  // packages/ceal-client-protocol/src/operation-withheld-cause.ts
937
992
  var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
@@ -960,7 +1015,7 @@ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
960
1015
  var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
961
1016
  var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
962
1017
  var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
963
- var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
1018
+ var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_applicable", "not_offered", "offered", "accepted", "rejected", "unknown"]);
964
1019
  var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
965
1020
  var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
966
1021
  var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
@@ -977,13 +1032,161 @@ var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
977
1032
  "interactive_unavailable"
978
1033
  ]);
979
1034
 
1035
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1036
+ var DIGEST = /^[a-f0-9]{64}$/u;
1037
+ var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1038
+ function isCealDigest(value) {
1039
+ return typeof value === "string" && DIGEST.test(value);
1040
+ }
1041
+ function cealRequestSha256(value) {
1042
+ return createHash("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1043
+ }
1044
+ function operationRecord(value, message) {
1045
+ requireOperationRecord(value, message);
1046
+ return value;
1047
+ }
1048
+ function invalid(message) {
1049
+ throw new TypeError(message);
1050
+ }
1051
+ function requirePrefixedRef(value, prefix, message) {
1052
+ if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1053
+ }
1054
+ function requireSafeRef2(value, message) {
1055
+ try {
1056
+ requireSafeRef(value);
1057
+ } catch {
1058
+ invalid(message);
1059
+ }
1060
+ }
1061
+
1062
+ // packages/ceal-client-protocol/src/request-authority.ts
1063
+ var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1064
+ var CEAL_REQUEST_REF_MAX_CHARACTERS = 128;
1065
+ var CEAL_REQUEST_REF_PATTERN_SOURCE = "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$";
1066
+ var CEAL_REQUEST_REF_PATTERN = new RegExp(CEAL_REQUEST_REF_PATTERN_SOURCE, "u");
1067
+ var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1068
+ var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1069
+ var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1070
+ var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1071
+ var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1072
+ var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1073
+ schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1074
+ ceal_request_ref: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_REF_MAX_CHARACTERS, pattern: CEAL_REQUEST_REF_PATTERN_SOURCE },
1075
+ created_at: { type: "string", minLength: 1, maxLength: 64 },
1076
+ authority: {
1077
+ type: "object",
1078
+ maxProperties: 5,
1079
+ additionalProperties: false,
1080
+ properties: {
1081
+ instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1082
+ access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1083
+ principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1084
+ execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1085
+ authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1086
+ },
1087
+ required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1088
+ }
1089
+ });
1090
+ var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1091
+ prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1092
+ host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1093
+ host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1094
+ 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." },
1095
+ host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1096
+ host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1097
+ });
1098
+ var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1099
+ 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." },
1100
+ 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." }
1101
+ });
1102
+ var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1103
+ requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1104
+ 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." }
1105
+ });
1106
+ var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1107
+ var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1108
+ var CEAL_REQUEST_JSON_SCHEMA = {
1109
+ type: "object",
1110
+ 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.",
1111
+ maxProperties: 14,
1112
+ additionalProperties: false,
1113
+ properties: {
1114
+ ...CEAL_REQUEST_COMMON_PROPERTIES,
1115
+ ...CEAL_REQUEST_HOST_PROPERTIES,
1116
+ ...CEAL_REQUEST_CALLER_PROPERTIES,
1117
+ ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1118
+ },
1119
+ required: CEAL_REQUEST_KEYS,
1120
+ anyOf: [
1121
+ {
1122
+ type: "object",
1123
+ required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1124
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1125
+ additionalProperties: false
1126
+ },
1127
+ {
1128
+ type: "object",
1129
+ required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1130
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1131
+ additionalProperties: false
1132
+ }
1133
+ ]
1134
+ };
1135
+
1136
+ // packages/ceal-client-protocol/src/client-wire-contract.ts
1137
+ var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
1138
+ var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
1139
+ var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
1140
+ var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
1141
+ var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
1142
+ var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
1143
+ function deriveCealClientWireSchemaVersion(schema) {
1144
+ 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))) {
1145
+ throw new TypeError("Client wire schema name or field set is invalid.");
1146
+ }
1147
+ const fields = schema.fields.filter((field) => field !== "schema_version").sort();
1148
+ const hash8 = createHash2("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
1149
+ return `${schema.schema_name}.v1.${hash8}`;
1150
+ }
1151
+ var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
1152
+ var commandResolutionAuthority = commandResolution.authority;
1153
+ var commandResolutionSemanticOptions = commandResolution.semantic_options;
1154
+ var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
1155
+ var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
1156
+ var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
1157
+ var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
1158
+ var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
1159
+ var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
1160
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
1161
+ var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
1162
+ var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
1163
+ var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
1164
+ var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
1165
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
1166
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
1167
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
1168
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
1169
+ var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
1170
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
1171
+ var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
1172
+ var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
1173
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
1174
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
1175
+ var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
1176
+ var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
1177
+ 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 });
1178
+ var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
1179
+
1180
+ // packages/ceal-client-protocol/src/access-level-vocabulary.ts
1181
+ var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1182
+
980
1183
  // packages/ceal-client-protocol/src/operation-access-class.ts
981
1184
  var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
982
1185
 
983
1186
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
984
1187
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
985
1188
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
986
- var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1189
+ var CEAL_PROVIDER_BOUNDARY_FIELDS = vocabulary(["provider_boundary_ref", "provider_boundary_kind", "provider_boundary_label", "provider_native_id", "provider_boundary_evidence"]);
987
1190
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
988
1191
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
989
1192
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1029,7 +1232,7 @@ var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1029
1232
  var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
1030
1233
  var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
1031
1234
  var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
1032
- var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
1235
+ var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary", "standard_names"]);
1033
1236
 
1034
1237
  // packages/ceal-client-protocol/src/operation-catalog.ts
1035
1238
  var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
@@ -1091,6 +1294,7 @@ var CEAL_SCHEMA_LITERALS = [
1091
1294
  "ceal.gateway_write_receipt_readback.v1",
1092
1295
  "ceal.gateway_write_request_receipt.v1",
1093
1296
  "ceal.host_observation.v1",
1297
+ "ceal.host_usage_batch.v1",
1094
1298
  "ceal.host_registration_request.v1",
1095
1299
  "ceal.host_registration_result.v1",
1096
1300
  CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
@@ -1119,12 +1323,12 @@ var CEAL_SCHEMA_LITERAL_SET = new Set(CEAL_SCHEMA_LITERALS);
1119
1323
  import { join } from "node:path";
1120
1324
  var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1121
1325
  bounded_store_sidecar: (root) => `${root}.jsonl`,
1122
- gateway_audit_archive: (root) => `${root}.jsonl`,
1123
1326
  gateway_access_group_connector_control_audit: (root) => `${root}.audit.jsonl`,
1124
1327
  gateway_access_group_connector_scope_audit: (root) => join(root, "profile-connector-scope-audit.jsonl"),
1125
1328
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
1126
1329
  gateway_access_group_connector_calendar_scope_audit: (root) => join(root, "profile-connector-calendar-scope-audit.jsonl"),
1127
1330
  gateway_access_group_connector_readiness_audit: (root) => join(root, "profile-connector-readiness.audit.jsonl"),
1331
+ gateway_deployment_events: (root) => join(root, "gateway-deployments.jsonl"),
1128
1332
  gateway_organization_audit_ledger: (root) => join(root, "organization-ledger.jsonl"),
1129
1333
  gateway_personal_client_audit: (root) => join(root, "audit.jsonl"),
1130
1334
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
@@ -1149,6 +1353,12 @@ var CEAL_LOWERCASE_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
1149
1353
  var CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN = new RegExp(`^host-registration-attempt:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1150
1354
  var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1151
1355
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1356
+ var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1357
+
1358
+ // packages/ceal-client-protocol/src/resource-read-result.ts
1359
+ var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
1360
+ var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
1361
+ var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1152
1362
 
1153
1363
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
1154
1364
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
@@ -1167,7 +1377,7 @@ function shellSingleQuoted(value) {
1167
1377
  return `'${value.replaceAll("'", "'\\''")}'`;
1168
1378
  }
1169
1379
  var CEAL_OPERATION_CONTRACT_REQUIRED_FIELDS = Object.freeze(["input_schema", "result_schema"]);
1170
- var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["summary", "input_resolution"]);
1380
+ var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["branches", "summary", "input_resolution"]);
1171
1381
  var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
1172
1382
  $schema: CEAL_JSON_SCHEMA_2020_12,
1173
1383
  $id: "https://ceal.dev/schemas/verified-artifact-descriptor.v1.schema.json",
@@ -1212,11 +1422,93 @@ var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_o
1212
1422
  // packages/ceal-client-protocol/src/actor-kind.ts
1213
1423
  var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
1214
1424
 
1425
+ // packages/ceal-client-protocol/src/provider-link-policy.ts
1426
+ var PROVIDER_LINK_RESULT_FIELDS = Object.freeze({
1427
+ read_row: Object.freeze({ human_link: "source_url", parent_context: Object.freeze(["thread_ref"]) }),
1428
+ write_result: Object.freeze({ human_links: Object.freeze(["user_openable_url", "url", "spreadsheet_url", "meet_url"]) })
1429
+ });
1430
+ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1431
+ { 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/" },
1432
+ { 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/" },
1433
+ { 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/" },
1434
+ { 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/" },
1435
+ { 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/" },
1436
+ { 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" },
1437
+ { 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" },
1438
+ { 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" },
1439
+ { 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" },
1440
+ { 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" },
1441
+ { 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" },
1442
+ { 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" },
1443
+ { 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" },
1444
+ { 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" },
1445
+ { 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" },
1446
+ { 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" },
1447
+ { provider: "google-workspace", result_kind: "form_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified Forms responderUri", source: "https://developers.google.com/workspace/forms/api/reference/rest/v1/forms" },
1448
+ { 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" },
1449
+ { 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" },
1450
+ { 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" },
1451
+ { 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" }
1452
+ ]);
1453
+ var PROVIDER_LINK_HOSTS = Object.freeze({
1454
+ notion: Object.freeze(["notion.so", "www.notion.so", "notion.com", "www.notion.com", "app.notion.com"]),
1455
+ google_workspace: Object.freeze([
1456
+ "calendar.google.com",
1457
+ "contacts.google.com",
1458
+ "docs.google.com",
1459
+ "drive.google.com",
1460
+ "forms.google.com",
1461
+ "mail.google.com",
1462
+ "meet.google.com",
1463
+ "sites.google.com",
1464
+ "www.google.com"
1465
+ ])
1466
+ });
1467
+ var NOTION_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.notion);
1468
+ var GOOGLE_WORKSPACE_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.google_workspace);
1469
+ var PROVIDER_RESOURCE_SOURCE_URL_SCHEMA = Object.freeze({
1470
+ type: "string",
1471
+ minLength: 1,
1472
+ maxLength: 2048,
1473
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1474
+ 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."
1475
+ });
1476
+ var PROVIDER_USER_OPENABLE_URL_SCHEMA = Object.freeze({
1477
+ type: "string",
1478
+ minLength: 1,
1479
+ maxLength: 2048,
1480
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1481
+ 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."
1482
+ });
1483
+
1215
1484
  // packages/ceal-client-protocol/src/resource-row.ts
1216
1485
  var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
1217
1486
  var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
1218
1487
  var CEAL_RESOURCE_SEARCH_DIRECTIONS = vocabulary(["ascending", "descending"]);
1219
- 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"]);
1488
+ var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
1489
+ "query",
1490
+ "modified_since",
1491
+ "since",
1492
+ "until",
1493
+ "filetype",
1494
+ "authored_by_me",
1495
+ "authored_by",
1496
+ "edited_by",
1497
+ "include_replies",
1498
+ "kinds",
1499
+ "container_ref",
1500
+ "container_refs",
1501
+ "container_names",
1502
+ "addressed_to_me",
1503
+ "unread",
1504
+ "archived",
1505
+ "state",
1506
+ "event_types",
1507
+ "starred",
1508
+ "trashed",
1509
+ "permission"
1510
+ ]);
1511
+ var CEAL_RESOURCE_SEARCH_STATES = vocabulary(["open", "closed", "draft", "prerelease", "confirmed", "tentative", "cancelled"]);
1220
1512
  var CEAL_RESOURCE_TIME_BASES = vocabulary(["created", "modified", "viewed"]);
1221
1513
  var CEAL_REPOSITORY_VISIBILITIES = vocabulary(["public", "private", "internal"]);
1222
1514
  var CEAL_ACTIVITY_V3_KINDS = vocabulary(["authored", "edited", "messaged", "responded"]);
@@ -1312,6 +1604,8 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1312
1604
  container_label: { required: true, timestamp: false },
1313
1605
  container_ref: { required: false, timestamp: false },
1314
1606
  source_url: { required: false, timestamp: false },
1607
+ thread_ref: { required: false, timestamp: false },
1608
+ reply_count: { required: false, timestamp: false },
1315
1609
  source: { required: true, timestamp: false },
1316
1610
  owner: { required: false, timestamp: false },
1317
1611
  actor_kind: { required: false, timestamp: false },
@@ -1320,6 +1614,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1320
1614
  created_at: { required: false, timestamp: true },
1321
1615
  created_at_local: { required: false, timestamp: true },
1322
1616
  modified_at: { required: false, timestamp: true },
1617
+ observed_at: { required: false, timestamp: true },
1323
1618
  modified_at_local: { required: false, timestamp: true },
1324
1619
  viewed_by_me_at: { required: false, timestamp: true },
1325
1620
  modified_by_me_at: { required: false, timestamp: true },
@@ -1337,6 +1632,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1337
1632
  start: { required: false, timestamp: false },
1338
1633
  end: { required: false, timestamp: false },
1339
1634
  status: { required: false, timestamp: false },
1635
+ event_type: { required: false, timestamp: false },
1340
1636
  snippet: { required: false, timestamp: false },
1341
1637
  dated_notes: { required: false, timestamp: false },
1342
1638
  state: { required: true, timestamp: false },
@@ -1346,9 +1642,6 @@ var RESOURCE_ROW_REQUIRED_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(
1346
1642
  var RESOURCE_ROW_KEYS = new Set(Object.keys(RESOURCE_ROW_KEY_RULES));
1347
1643
  var RESOURCE_ROW_TIMESTAMP_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(([key, rule]) => rule.timestamp ? [key] : []);
1348
1644
 
1349
- // packages/ceal-client-protocol/src/resource-read-result.ts
1350
- var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1351
-
1352
1645
  // packages/ceal-client-protocol/src/excluded-target-coverage.ts
1353
1646
  var CEAL_EXCLUDED_TARGET_COVERAGE_MAX_ENTRIES = 64;
1354
1647
  function cealExcludedTargetCoverageJsonSchema() {
@@ -1400,6 +1693,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1400
1693
  "refresh_inactive",
1401
1694
  "refresh_replayed",
1402
1695
  "refresh_revoked",
1696
+ "person_inactive",
1697
+ "principal_inactive",
1403
1698
  "authority_replaced",
1404
1699
  "refresh_recovery_unavailable",
1405
1700
  "refresh_recovery_expired",
@@ -1420,97 +1715,6 @@ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
1420
1715
  var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1421
1716
  var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1422
1717
 
1423
- // packages/ceal-client-protocol/src/request-validation-primitives.ts
1424
- import { createHash as createHash2 } from "node:crypto";
1425
- var DIGEST = /^[a-f0-9]{64}$/u;
1426
- var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1427
- function isCealDigest(value) {
1428
- return typeof value === "string" && DIGEST.test(value);
1429
- }
1430
- function cealRequestSha256(value) {
1431
- return createHash2("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1432
- }
1433
- function operationRecord(value, message) {
1434
- requireOperationRecord(value, message);
1435
- return value;
1436
- }
1437
- function invalid(message) {
1438
- throw new TypeError(message);
1439
- }
1440
- function requirePrefixedRef(value, prefix, message) {
1441
- if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1442
- }
1443
-
1444
- // packages/ceal-client-protocol/src/request-authority.ts
1445
- var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1446
- var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1447
- var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1448
- var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1449
- var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1450
- var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1451
- var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1452
- schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1453
- ceal_request_ref: { type: "string", minLength: 1, maxLength: 128, pattern: "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$" },
1454
- created_at: { type: "string", minLength: 1, maxLength: 64 },
1455
- authority: {
1456
- type: "object",
1457
- maxProperties: 5,
1458
- additionalProperties: false,
1459
- properties: {
1460
- instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1461
- access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1462
- principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1463
- execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1464
- authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1465
- },
1466
- required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1467
- }
1468
- });
1469
- var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1470
- prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1471
- host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1472
- host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1473
- host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1474
- host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1475
- });
1476
- var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1477
- 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." },
1478
- 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." }
1479
- });
1480
- var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1481
- requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1482
- 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." }
1483
- });
1484
- var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1485
- var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1486
- var CEAL_REQUEST_JSON_SCHEMA = {
1487
- type: "object",
1488
- 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.",
1489
- maxProperties: 13,
1490
- additionalProperties: false,
1491
- properties: {
1492
- ...CEAL_REQUEST_COMMON_PROPERTIES,
1493
- ...CEAL_REQUEST_HOST_PROPERTIES,
1494
- ...CEAL_REQUEST_CALLER_PROPERTIES,
1495
- ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1496
- },
1497
- required: CEAL_REQUEST_KEYS,
1498
- anyOf: [
1499
- {
1500
- type: "object",
1501
- required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1502
- properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1503
- additionalProperties: false
1504
- },
1505
- {
1506
- type: "object",
1507
- required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1508
- properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1509
- additionalProperties: false
1510
- }
1511
- ]
1512
- };
1513
-
1514
1718
  // packages/ceal-client-protocol/src/request-operands.ts
1515
1719
  var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1516
1720
  var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
@@ -1618,6 +1822,27 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
1618
1822
  required: ["schema_version", "order", "nodes", "call_budget"]
1619
1823
  };
1620
1824
 
1825
+ // packages/ceal-client-protocol/src/host-observation-validation.ts
1826
+ var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1827
+ 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;
1828
+ function validateCealHostObservationValue(value) {
1829
+ if (value === void 0) throw new TypeError("Ceal Host observation value is invalid.");
1830
+ assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1831
+ if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) throw new TypeError("Ceal Host observation value is oversized.");
1832
+ inspectHostKeys(value);
1833
+ }
1834
+ function inspectHostKeys(value) {
1835
+ if (Array.isArray(value)) {
1836
+ for (const entry of value) inspectHostKeys(entry);
1837
+ return;
1838
+ }
1839
+ if (value === null || typeof value !== "object") return;
1840
+ for (const [key, child] of Object.entries(value)) {
1841
+ if (HOST_RESERVED_KEY.test(key)) throw new TypeError("Ceal Host observation cannot restate Gateway-owned facts.");
1842
+ inspectHostKeys(child);
1843
+ }
1844
+ }
1845
+
1621
1846
  // packages/ceal-client-protocol/src/host-observation.ts
1622
1847
  var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
1623
1848
  var HOST_OBSERVATION_PRODUCER = /^[a-z][a-z0-9]{0,31}$/u;
@@ -1664,35 +1889,238 @@ function safeCount(value) {
1664
1889
  return Number.isSafeInteger(value) && Number(value) >= 0;
1665
1890
  }
1666
1891
  function validateCealHostObservationDraft(value) {
1667
- const record = operationRecord(value, "Ceal Host observation draft is invalid.");
1668
- requirePrefixedRef(record.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1669
- requireClosedValue(record.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1670
- requireIsoTimestamp(record.observed_at, "Ceal Host observation time is invalid.");
1671
- assertHostObservationValue(record.value, record.observation_kind);
1892
+ const record2 = operationRecord(value, "Ceal Host observation draft is invalid.");
1893
+ requirePrefixedRef(record2.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1894
+ requireClosedValue(record2.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1895
+ requireIsoTimestamp(record2.observed_at, "Ceal Host observation time is invalid.");
1896
+ assertHostObservationValue(record2.value, record2.observation_kind);
1672
1897
  }
1673
- var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1674
1898
  var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
1675
1899
  function isCealHostPromptObservationValue(value) {
1676
1900
  return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
1677
1901
  }
1678
- 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;
1679
1902
  function assertHostObservationValue(value, kind) {
1680
1903
  if (value === void 0) invalid("Ceal Host observation value is invalid.");
1681
1904
  if (kind === "prompt" && !isCealHostPromptObservationValue(value)) invalid("Ceal Host prompt observation must contain only its body digest.");
1682
- assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1683
- if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) invalid("Ceal Host observation value is oversized.");
1684
- inspectHostKeys(value);
1905
+ validateCealHostObservationValue(value);
1685
1906
  }
1686
- function inspectHostKeys(value) {
1687
- if (Array.isArray(value)) {
1688
- for (const entry of value) inspectHostKeys(entry);
1907
+
1908
+ // packages/ceal-client-protocol/src/host-usage-facts.ts
1909
+ import { createHash as createHash3 } from "node:crypto";
1910
+ var CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION = "ceal.host_usage_batch.v1";
1911
+ var CEAL_HOST_USAGE_BATCH_REF_PREFIX = "host-usage-batch:";
1912
+ var CEAL_HOST_USAGE_INGRESS_PATH = "/api/ceal/v2/host-usage-batches";
1913
+ var CEAL_HOST_USAGE_BATCH_MAX_BYTES = 1024 * 1024;
1914
+ var CEAL_HOST_USAGE_FACT_MAX_BYTES = 64 * 1024;
1915
+ var CEAL_HOST_USAGE_BATCH_MAX_FACTS = 256;
1916
+ var CEAL_HOST_USAGE_BATCH_MAX_GAPS = 16;
1917
+ var CEAL_HOST_USAGE_BATCH_ACK_STATUS = 204;
1918
+ var CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES = 65;
1919
+ var CODEX_COUNTER_SEMANTICS = ["last_delta_total_cumulative", "total_cumulative_only", "unknown"];
1920
+ var CODEX_CUMULATIVE_TRANSITIONS = ["baseline", "advanced", "same", "reset_or_correction", "not_observed"];
1921
+ var HOST_USAGE_COVERAGE_GAP_REASONS = ["source_usage_unavailable", "source_file_replaced", "source_file_retired", "outbox_capacity", "unsupported_source_shape"];
1922
+ function createCealHostUsageBatch(input) {
1923
+ const body = { schema_version: CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION, ...input };
1924
+ const batch = { ...body, batch_ref: `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}` };
1925
+ validateCealHostUsageBatch(batch);
1926
+ return batch;
1927
+ }
1928
+ function validateCealHostUsageBatch(value) {
1929
+ if (!isOperationRecord(value)) invalid("Ceal Host usage batch is invalid.");
1930
+ requireExactOperationKeys(value, ["schema_version", "batch_ref", "host_source_ref", "host_session_ref", "created_at", "source_ranges", "facts", "coverage_gaps"]);
1931
+ 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.");
1932
+ const { batch_ref: _ref, ...body } = value;
1933
+ if (value.batch_ref !== `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}`) invalid("Ceal Host usage batch reference is invalid.");
1934
+ validateBatchMetadata(value);
1935
+ validateBatchContents(value);
1936
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_BATCH_MAX_BYTES) invalid("Ceal Host usage batch exceeds its byte limit.");
1937
+ }
1938
+ function validateBatchMetadata(value) {
1939
+ requireSafeRef2(value.host_source_ref, "Ceal Host usage source is invalid.");
1940
+ requireSafeRef2(value.host_session_ref, "Ceal Host usage session is invalid.");
1941
+ requireIsoTimestamp(value.created_at, "Ceal Host usage batch time is invalid.");
1942
+ 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.");
1943
+ for (const range of value.source_ranges) validateSourceRange(range);
1944
+ }
1945
+ function validateBatchContents(value) {
1946
+ const facts = validateBatchFacts(value.facts);
1947
+ const gaps = validateBatchGaps(value.coverage_gaps);
1948
+ if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
1949
+ const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
1950
+ for (const fact of facts) {
1951
+ validateCealHostUsageFact(fact, value.host_session_ref);
1952
+ if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
1953
+ }
1954
+ for (const gap of gaps) {
1955
+ validateCoverageGap(gap);
1956
+ if (gap.source_file_ref !== null && !sourceFiles.has(gap.source_file_ref)) invalid("Ceal Host usage coverage gap is outside its source ranges.");
1957
+ }
1958
+ }
1959
+ function validateBatchFacts(value) {
1960
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_FACTS) invalid("Ceal Host usage fact count is invalid.");
1961
+ return value;
1962
+ }
1963
+ function validateBatchGaps(value) {
1964
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) invalid("Ceal Host usage coverage is invalid.");
1965
+ return value;
1966
+ }
1967
+ function sourceRangeFileRef(value) {
1968
+ return isOperationRecord(value) ? value.source_file_ref : null;
1969
+ }
1970
+ function hostUsageFactReference(sourceFileRef, sourceEventRef) {
1971
+ requireSafeRef2(sourceFileRef, "Ceal Host usage file reference is invalid.");
1972
+ requireSafeRef2(sourceEventRef, "Ceal Host usage event reference is invalid.");
1973
+ return `host-usage-fact:${sha256(JSON.stringify({ source_file_ref: sourceFileRef, source_event_ref: sourceEventRef }))}`;
1974
+ }
1975
+ function hostUsageSourceEventReference(sourceFileRef, sourceEventIdentity) {
1976
+ requireSafeRef2(sourceFileRef, "Ceal Host usage file reference is invalid.");
1977
+ if (typeof sourceEventIdentity !== "string" || sourceEventIdentity.length === 0 || sourceEventIdentity.length > 1024) invalid("Ceal Host usage event identity is invalid.");
1978
+ return `host-source-event:${sha256(JSON.stringify({ source_file_ref: sourceFileRef, source_event_identity: sourceEventIdentity }))}`;
1979
+ }
1980
+ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, device, inode) {
1981
+ 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.");
1982
+ return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
1983
+ }
1984
+ function validateCealHostUsageFact(value, sessionRef) {
1985
+ if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
1986
+ requireFactByteLimit(value);
1987
+ if (value.producer === "codex_transcript") validateCodexFact(value);
1988
+ else if (value.producer === "claude_transcript") validateClaudeFact(value);
1989
+ else invalid("Ceal Host usage producer is invalid.");
1990
+ if (value.host_session_ref !== sessionRef) invalid("Ceal Host usage session does not match its batch.");
1991
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage file reference is invalid.");
1992
+ requireSafeRef2(value.source_event_ref, "Ceal Host usage event reference is invalid.");
1993
+ if (value.host_turn_ref !== null) requireSafeRef2(value.host_turn_ref, "Ceal Host usage turn reference is invalid.");
1994
+ if (value.requested_model !== null && !boundedText(value.requested_model, 256)) invalid("Ceal Host requested model is invalid.");
1995
+ if (value.reported_model !== null && !boundedText(value.reported_model, 256)) invalid("Ceal Host reported model is invalid.");
1996
+ if (value.fact_ref !== hostUsageFactReference(value.source_file_ref, value.source_event_ref)) invalid("Ceal Host usage identity is invalid.");
1997
+ }
1998
+ function requireFactByteLimit(value) {
1999
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_FACT_MAX_BYTES) invalid("Ceal Host usage fact exceeds its byte limit.");
2000
+ }
2001
+ function validateCodexFact(value) {
2002
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fact is invalid.");
2003
+ 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"]);
2004
+ if (value.producer !== "codex_transcript" || !safeInteger(value.source_event_ordinal)) invalid("Ceal Codex usage fact is invalid.");
2005
+ requireIsoTimestamp(value.observed_at, "Ceal Codex usage time is invalid.");
2006
+ if (!isOperationRecord(value.source_usage)) invalid("Ceal Codex source usage is invalid.");
2007
+ requireExactOperationKeys(value.source_usage, ["last_token_usage", "total_token_usage"]);
2008
+ if (value.source_usage.last_token_usage !== null) validateCodexUsageCounts(value.source_usage.last_token_usage);
2009
+ if (value.source_usage.total_token_usage !== null) validateCodexUsageCounts(value.source_usage.total_token_usage);
2010
+ 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.");
2011
+ validateNormalizedUsage(value.normalized_usage);
2012
+ }
2013
+ function validateClaudeFact(value) {
2014
+ if (!isOperationRecord(value)) invalid("Ceal Claude usage fact is invalid.");
2015
+ 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"]);
2016
+ validateClaudeIdentity(value);
2017
+ requireIsoTimestamp(value.observed_at, "Ceal Claude usage time is invalid.");
2018
+ validateClaudeSourceUsage(value.source_usage);
2019
+ validateClaudeSemantics(value);
2020
+ validateNormalizedUsage(value.normalized_usage);
2021
+ }
2022
+ function validateClaudeIdentity(value) {
2023
+ 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.");
2024
+ }
2025
+ function validateClaudeSourceUsage(value) {
2026
+ if (!isOperationRecord(value)) invalid("Ceal Claude source usage is invalid.");
2027
+ requireExactOperationKeys(value, ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"], ["cache_creation"]);
2028
+ for (const key of ["input_tokens", "output_tokens"]) if (!safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
2029
+ 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.");
2030
+ if (value.cache_creation !== void 0 && value.cache_creation !== null) validateClaudeCacheCreationUsage(value.cache_creation);
2031
+ }
2032
+ function validateClaudeCacheCreationUsage(value) {
2033
+ if (!isOperationRecord(value)) invalid("Ceal Claude cache creation usage is invalid.");
2034
+ requireExactOperationKeys(value, ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]);
2035
+ 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.");
2036
+ }
2037
+ function validateClaudeSemantics(value) {
2038
+ if (value.counter_semantics !== "assistant_message" || !validClaudeFinality(value.finality) || value.child_inclusion !== "unknown" || !validCorrectionSemantics(value.correction_semantics)) invalid("Ceal Claude usage semantics are invalid.");
2039
+ }
2040
+ function validClaudeFinality(value) {
2041
+ return value === "terminal" || value === "nonterminal" || value === "unknown";
2042
+ }
2043
+ function validCorrectionSemantics(value) {
2044
+ return value === "not_observed" || value === "unknown";
2045
+ }
2046
+ function validateCodexUsageCounts(value) {
2047
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
2048
+ requireExactOperationKeys(value, CEAL_CODEX_USAGE_COUNT_FIELDS);
2049
+ for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
2050
+ 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.");
2051
+ }
2052
+ function validateNormalizedUsage(value) {
2053
+ if (!isOperationRecord(value)) invalid("Ceal normalized Host usage is invalid.");
2054
+ requireExactOperationKeys(value, ["input", "output", "total", "cached_input", "cache_write_input", "reasoning_output"]);
2055
+ for (const key of Object.keys(value)) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal normalized Host usage is invalid.");
2056
+ validateNormalizedTotals(value);
2057
+ }
2058
+ function validateNormalizedTotals(value) {
2059
+ validateNormalizedCountTotal(value);
2060
+ validateNormalizedInputSubsets(value);
2061
+ validateNormalizedOutputSubset(value);
2062
+ }
2063
+ function validateNormalizedCountTotal(value) {
2064
+ 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.");
2065
+ }
2066
+ function validateNormalizedInputSubsets(value) {
2067
+ 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.");
2068
+ }
2069
+ function validateNormalizedOutputSubset(value) {
2070
+ if (value.output !== null && value.reasoning_output !== null && Number(value.reasoning_output) > Number(value.output)) invalid("Ceal normalized Host output subset is inconsistent.");
2071
+ }
2072
+ function validateSourceRange(value) {
2073
+ if (!isOperationRecord(value)) invalid("Ceal Host usage source range is invalid.");
2074
+ requireExactOperationKeys(value, ["source_file_ref", "start_offset", "end_offset"]);
2075
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage source-file reference is invalid.");
2076
+ 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.");
2077
+ }
2078
+ function validateCealHostUsageCoverageGap(value) {
2079
+ if (!isOperationRecord(value)) invalid("Ceal Host usage coverage gap is invalid.");
2080
+ requireExactOperationKeys(value, ["reason", "source_file_ref", "start_offset", "end_offset", "omitted_count"]);
2081
+ if (!isOneOf(HOST_USAGE_COVERAGE_GAP_REASONS, value.reason) || !validUsageGapCount(value.reason, value.omitted_count)) invalid("Ceal Host usage coverage gap is invalid.");
2082
+ if (value.source_file_ref === null) {
2083
+ if (value.start_offset !== null || value.end_offset !== null) invalid("Ceal Host usage coverage gap range is invalid.");
1689
2084
  return;
1690
2085
  }
1691
- if (value === null || typeof value !== "object") return;
1692
- for (const [key, child] of Object.entries(value)) {
1693
- if (HOST_RESERVED_KEY.test(key)) invalid("Ceal Host observation cannot restate Gateway-owned facts.");
1694
- inspectHostKeys(child);
2086
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage coverage file reference is invalid.");
2087
+ 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.");
2088
+ }
2089
+ function validateCoverageGap(value) {
2090
+ validateCealHostUsageCoverageGap(value);
2091
+ }
2092
+ function validUsageGapCount(reason, value) {
2093
+ return value === null ? reason !== "outbox_capacity" : safeInteger(value) && Number(value) >= 1;
2094
+ }
2095
+ function isOneOf(values, value) {
2096
+ return typeof value === "string" && values.some((candidate) => candidate === value);
2097
+ }
2098
+ function isCealHostUsageBatchReference(value) {
2099
+ return typeof value === "string" && value.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX) && isCealDigest(value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length));
2100
+ }
2101
+ function cealHostUsageBatchObjectDigestFromFileName(value) {
2102
+ if (!value.endsWith(".json")) return null;
2103
+ const digest2 = value.slice(0, -5);
2104
+ return isCealDigest(digest2) ? digest2 : null;
2105
+ }
2106
+ function cealHostUsageBatchObjectDigestFromReference(value) {
2107
+ return isCealHostUsageBatchReference(value) ? value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length) : null;
2108
+ }
2109
+ function safeInteger(value) {
2110
+ return Number.isSafeInteger(value) && Number(value) >= 0;
2111
+ }
2112
+ function boundedText(value, maximum) {
2113
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters(value);
2114
+ }
2115
+ function hasControlCharacters(value) {
2116
+ for (const character of value) {
2117
+ const code = character.codePointAt(0);
2118
+ if (code !== void 0 && (code < 32 || code === 127)) return true;
1695
2119
  }
2120
+ return false;
2121
+ }
2122
+ function sha256(value) {
2123
+ return createHash3("sha256").update(value, "utf8").digest("hex");
1696
2124
  }
1697
2125
 
1698
2126
  // packages/ceal-client-protocol/src/host-prompt-ref.ts
@@ -1799,11 +2227,72 @@ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSch
1799
2227
  var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
1800
2228
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
1801
2229
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
2230
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.refusal_schema_name, fields: hostInvocationAuthenticationContract.refusal_fields });
1802
2231
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
1803
2232
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
1804
2233
  var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
1805
2234
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
2235
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
1806
2236
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
2237
+ function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
2238
+ const messages = [];
2239
+ let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
2240
+ for (const candidate of newestFirst.slice(0, CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES)) {
2241
+ 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 } : {} };
2242
+ if (encodedMessageWindowBytes([...messages, complete]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) {
2243
+ messages.push(Object.freeze(complete));
2244
+ continue;
2245
+ }
2246
+ const clipped = clipHumanMessageToWindow(messages, candidate);
2247
+ if (clipped === null) {
2248
+ truncated = true;
2249
+ break;
2250
+ }
2251
+ messages.push(Object.freeze(clipped));
2252
+ }
2253
+ return Object.freeze({ messages: Object.freeze(messages), truncated });
2254
+ }
2255
+ function encodedMessageWindowBytes(messages) {
2256
+ return new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2257
+ }
2258
+ function clipHumanMessageToWindow(prefix, candidate) {
2259
+ const clipped = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: "", text_truncated: true };
2260
+ const available = CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES - encodedMessageWindowBytes([...prefix, clipped]);
2261
+ if (available < 0) return null;
2262
+ const text = [];
2263
+ let used = 0;
2264
+ for (const point of candidate.text) {
2265
+ const encodedPoint = JSON.stringify(point);
2266
+ const cost = new TextEncoder().encode(encodedPoint).byteLength - 2;
2267
+ if (used + cost > available) break;
2268
+ text.push(point);
2269
+ used += cost;
2270
+ }
2271
+ const result = { ...clipped, text: text.join("") };
2272
+ return encodedMessageWindowBytes([...prefix, result]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES ? result : null;
2273
+ }
2274
+ function decodeCealHostInvocationHumanMessageWindow(value) {
2275
+ 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();
2276
+ const messages = value.messages.map(decodeHumanMessage);
2277
+ const bytes = new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2278
+ if (bytes > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) throw invalidInvocationContextRequest();
2279
+ return Object.freeze({ messages: Object.freeze(messages), truncated: value.truncated });
2280
+ }
2281
+ function decodeHumanMessage(candidate) {
2282
+ 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();
2283
+ if (candidate.text_truncated !== void 0 && candidate.text_truncated !== true) throw invalidInvocationContextRequest();
2284
+ 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 } : {} });
2285
+ }
2286
+ function safeReference(value) {
2287
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
2288
+ }
2289
+ function exactOptionalKeys(value, required, optional = []) {
2290
+ const keys = Object.keys(value);
2291
+ return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => required.includes(key) || optional.includes(key));
2292
+ }
2293
+ function invalidInvocationContextRequest() {
2294
+ return new TypeError("The Host invocation context request is invalid.");
2295
+ }
1807
2296
  function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1808
2297
  const clientNonce = contract.host_invocation_authentication.client_nonce;
1809
2298
  return {
@@ -1813,40 +2302,20 @@ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTR
1813
2302
  };
1814
2303
  }
1815
2304
  var hostNonceContract = deriveCealHostInvocationNonceContract();
1816
- var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
1817
2305
  var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
1818
2306
  var CEAL_HOST_CONTEXT_TOKEN_PATTERN = new RegExp(hostNonceContract.context_token_pattern_source, "u");
1819
- var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_MAX_BYTES = deriveCealHostInvocationAuthenticationResultMaxBytes();
1820
- function deriveCealHostInvocationAuthenticationResultMaxBytes(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1821
- const hostAuthentication = contract.host_invocation_authentication;
1822
- const values = {
1823
- schema_version: deriveCealClientWireSchemaVersion({ schema_name: hostAuthentication.result_schema_name, fields: hostAuthentication.result_fields }),
1824
- context_token: `${CEAL_HOST_CONTEXT_TOKEN_PREFIX}${"A".repeat(hostAuthentication.client_nonce.encoded_characters)}`,
1825
- expires_at: (/* @__PURE__ */ new Date("+010000-01-01T00:00:00.000Z")).toISOString()
1826
- };
1827
- const fields = hostAuthentication.result_fields;
1828
- if (fields.some((field) => !Object.hasOwn(values, field))) throw new TypeError("Host invocation result fields have no bounded sample value.");
1829
- return new TextEncoder().encode(`${JSON.stringify(Object.fromEntries(fields.map((field) => [field, values[field]])))}
1830
- `).byteLength;
1831
- }
1832
2307
  var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
1833
2308
  "request_authority_unavailable",
1834
- "request_missing",
1835
- "authority_mismatch",
1836
- "host_source_mismatch",
1837
- "host_session_mismatch",
1838
- "host_turn_mismatch",
1839
- "host_input_mismatch",
1840
- "host_prompt_mismatch"
2309
+ "request_creation_refused"
1841
2310
  ]);
1842
2311
  var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1843
2312
  "invalid_arguments",
1844
2313
  "options_invalid",
1845
2314
  "session_unavailable",
1846
2315
  "context_unavailable",
2316
+ "activation_wait_exhausted",
1847
2317
  "context_replaced",
1848
2318
  "no_binding",
1849
- "context_stale",
1850
2319
  "context_expired",
1851
2320
  "host_source_refused",
1852
2321
  "host_credential_refused",
@@ -1863,23 +2332,35 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1863
2332
  "relay_failed",
1864
2333
  "host_refusal_invalid"
1865
2334
  ]);
2335
+ var CEAL_HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2336
+ "permission_denied",
2337
+ "socket_missing",
2338
+ "connection_refused",
2339
+ "closed_early",
2340
+ "response_invalid",
2341
+ "timed_out",
2342
+ "cancelled",
2343
+ "unavailable"
2344
+ ]);
1866
2345
  var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1867
2346
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
1868
2347
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
1869
2348
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1870
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
1871
- context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
2349
+ // This reason cannot distinguish a Codex side conversation from a missing
2350
+ // context in a regular session, so guidance must leave that choice to the caller.
2351
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2352
+ activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2353
+ context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
1872
2354
  // `no_binding` now means the producer has no real current Host session. The
1873
2355
  // Host Relay never uses it for an uncreated Gateway Request; there is no
1874
2356
  // useful retry until the consumer is running inside a Host session.
1875
2357
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1876
- context_stale: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1877
- context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
2358
+ context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
1878
2359
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
1879
2360
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
1880
2361
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
1881
2362
  gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
1882
- contract_mismatch: Object.freeze({ classification: "contract_mismatch", next_action: "upgrade_ceal_client" }),
2363
+ contract_mismatch: Object.freeze({ classification: "host_contract_mismatch", next_action: "upgrade_ceal_client" }),
1883
2364
  gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
1884
2365
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
1885
2366
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
@@ -1887,7 +2368,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1887
2368
  relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
1888
2369
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
1889
2370
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
1890
- relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "answer_with_gap" }),
2371
+ relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
1891
2372
  host_refusal_invalid: Object.freeze({ classification: "host_refusal_invalid", next_action: "answer_with_gap" })
1892
2373
  });
1893
2374
 
@@ -1901,10 +2382,13 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
1901
2382
  "activation_recorded",
1902
2383
  "activation_failed",
1903
2384
  "watcher_scan_failed",
2385
+ "usage_capture_failed",
2386
+ "usage_upload_failed",
1904
2387
  "activation_wait_skipped",
1905
2388
  "activation_wait_engaged",
1906
2389
  "activation_wait_completed",
1907
- "activation_wait_exhausted"
2390
+ "activation_wait_exhausted",
2391
+ "invocation_authentication_failed"
1908
2392
  ]);
1909
2393
  var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1910
2394
  "malformed_line",
@@ -1914,11 +2398,22 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1914
2398
  "size_budget",
1915
2399
  "symlink"
1916
2400
  ]);
2401
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_WATCHER_OPTIONAL_FIELDS = vocabulary(["failure_kind", "cause"]);
2402
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_OPTIONAL_FIELDS = vocabulary(["cause"]);
2403
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE = "^[a-z][a-z0-9_]{0,63}(?::[A-Za-z][A-Za-z0-9_]{0,63})?$";
2404
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES = Object.freeze([
2405
+ ...CEAL_HOST_AUTHENTICATION_CAUSES,
2406
+ ...CEAL_HOST_RELAY_EXCHANGE_FAILURES.map((failure) => `relay_exchange:${failure}`)
2407
+ ]);
2408
+ var hostServiceDiagnosticCausePattern = new RegExp(CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE, "u");
2409
+ function isCealHostServiceDiagnosticCause(value, event) {
2410
+ return typeof value === "string" && hostServiceDiagnosticCausePattern.test(value) && (event !== "invocation_authentication_failed" || CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES.includes(value));
2411
+ }
1917
2412
 
1918
2413
  // packages/ceal-client-protocol/src/client-result-materialization.ts
1919
2414
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
1920
2415
  var REQUIRED_FIELDS2 = Object.freeze(["schema_version", "operation_id", "path", "sha256"]);
1921
- var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "items_path", "row_count", "result_complete", "coverage", "local_result_root", "model_disclosure", "continue_argv", "how_to_read"]);
2416
+ var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "local_result_root", "request_context_argv", "how_to_read"]);
1922
2417
 
1923
2418
  // packages/ceal-client-protocol/src/discovery-manifest.ts
1924
2419
  var DISCOVERY_MANIFEST_KEYS = CEAL_CLIENT_WIRE_CONTRACT.command_response.discovery_manifest_fields;
@@ -2000,12 +2495,14 @@ var ADMIN_SOURCE_OWNERS = vocabulary([
2000
2495
  "resource",
2001
2496
  "prompt",
2002
2497
  "usage",
2498
+ "provider_request_lifecycle",
2003
2499
  "connector",
2004
2500
  "session",
2005
2501
  "knowledge",
2006
2502
  "policy"
2007
2503
  ]);
2008
2504
  var ADMIN_COMPLETENESS_STATES = vocabulary(["complete", "partial", "unknown"]);
2505
+ var ADMIN_PROVIDER_REQUEST_CAPTURE_HEALTH_STATES = vocabulary(["available", "missing", "invalid", "unreadable"]);
2009
2506
  var ADMIN_OPERATION_OUTCOMES = vocabulary(["completed", "failed", "denied", "cancelled", "unknown"]);
2010
2507
  var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
2011
2508
  var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
@@ -2027,7 +2524,7 @@ var AUDIT_IDENTITY_KEYS = Object.freeze(["event_ref", "membership_ref", "registr
2027
2524
  var FAILURE_RESPONSE_KEYS = Object.freeze(["error", "ok", "proof_ref_or_unavailable", "protocol_version", "request_id"]);
2028
2525
 
2029
2526
  // host/codex/src/codex-decoder.ts
2030
- import { createHash as createHash3 } from "node:crypto";
2527
+ import { createHash as createHash4 } from "node:crypto";
2031
2528
  import { isAbsolute, resolve } from "node:path";
2032
2529
 
2033
2530
  // host/codex/src/codex-types.ts
@@ -2073,15 +2570,15 @@ function hostInputReference(sourceRef, sessionRef, nativeTurnId, messageId, ordi
2073
2570
  if (![sourceRef, sessionRef, nativeTurnId, messageId].every((value) => SAFE_REF2.test(value)) || !Number.isSafeInteger(ordinal) || ordinal < 0) {
2074
2571
  throw new CodexHostAdapterError("invalid_input", "Codex input identity is invalid.");
2075
2572
  }
2076
- return `codex-input:${shortDigest({ source_ref: sourceRef, session_ref: sessionRef, native_turn_id: nativeTurnId, message_id: messageId, ordinal, prompt_sha256: sha256(prompt) })}`;
2573
+ return `codex-input:${shortDigest({ source_ref: sourceRef, session_ref: sessionRef, native_turn_id: nativeTurnId, message_id: messageId, ordinal, prompt_sha256: sha2562(prompt) })}`;
2077
2574
  }
2078
2575
  function promptObservationValue(prompt) {
2079
- return { body_sha256: sha256(prompt) };
2576
+ return { body_sha256: sha2562(prompt) };
2080
2577
  }
2081
2578
  function sessionObservationValue(event, environment = { operating_system: process.platform, architecture: process.arch }) {
2082
2579
  const value = {
2083
2580
  host_kind: "codex",
2084
- session_id_sha256: sha256(event.session_id),
2581
+ session_id_sha256: sha2562(event.session_id),
2085
2582
  host_version: { status: "not_recorded" },
2086
2583
  operating_system: environment.operating_system,
2087
2584
  architecture: environment.architecture,
@@ -2092,7 +2589,7 @@ function sessionObservationValue(event, environment = { operating_system: proces
2092
2589
  return value;
2093
2590
  }
2094
2591
  function turnObservationValue(sessionId, turnRef, status) {
2095
- return { status, host_session_id_sha256: sha256(sessionId), host_turn_ref: turnRef };
2592
+ return { status, host_session_id_sha256: sha2562(sessionId), host_turn_ref: turnRef };
2096
2593
  }
2097
2594
  function decodeSession(input, event) {
2098
2595
  exactKeys(input, ["cwd", "hook_event_name", "model", "permission_mode", "session_id", "source", "transcript_path"], []);
@@ -2154,8 +2651,8 @@ function validateHookEventName(input, event) {
2154
2651
  function isRecord(value) {
2155
2652
  return value !== null && typeof value === "object" && !Array.isArray(value);
2156
2653
  }
2157
- function sha256(value) {
2158
- return createHash3("sha256").update(value, "utf8").digest("hex");
2654
+ function sha2562(value) {
2655
+ return createHash4("sha256").update(value, "utf8").digest("hex");
2159
2656
  }
2160
2657
  function shortDigest(value) {
2161
2658
  return cealRequestSha256(value);
@@ -2165,8 +2662,8 @@ function reject(message) {
2165
2662
  }
2166
2663
 
2167
2664
  // host/codex/src/codex-outbox.ts
2168
- import { mkdir as mkdir2, open as open3, readdir, rename as rename2, stat, unlink as unlink2 } from "node:fs/promises";
2169
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2 } from "node:path";
2665
+ import { mkdir as mkdir4, open as open4, readdir, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
2666
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join4 } from "node:path";
2170
2667
 
2171
2668
  // host/invocation-context.ts
2172
2669
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2234,13 +2731,13 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2234
2731
  ];
2235
2732
 
2236
2733
  // host/relay/src/host-producer-core.ts
2237
- import { createHash as createHash4 } from "node:crypto";
2734
+ import { createHash as createHash5 } from "node:crypto";
2238
2735
 
2239
2736
  // host/secure-file.ts
2240
2737
  import { execFile } from "node:child_process";
2241
2738
  import { constants } from "node:fs";
2242
2739
  import { lstat, open } from "node:fs/promises";
2243
- import { dirname, win32 } from "node:path";
2740
+ import { dirname, join as join2, win32 } from "node:path";
2244
2741
  import { fileURLToPath } from "node:url";
2245
2742
  var SecureFileCustodyError = class extends Error {
2246
2743
  name = "SecureFileCustodyError";
@@ -2258,6 +2755,7 @@ var SecureFileCustodyError = class extends Error {
2258
2755
  }
2259
2756
  };
2260
2757
  var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
2758
+ var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
2261
2759
  var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
2262
2760
  var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
2263
2761
  function secureOpenFlags(flags, platform) {
@@ -2300,18 +2798,46 @@ async function assertWindowsIdentityStable(handle, first, path) {
2300
2798
  }
2301
2799
  async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
2302
2800
  if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
2303
- const result = await runWindowsSecurefs(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2801
+ const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2304
2802
  if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
2305
2803
  if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
2306
2804
  if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
2307
2805
  throw securefsRefusal(result.stderr);
2308
2806
  }
2309
- async function runWindowsSecurefs(args, maxBytes, custody) {
2310
- if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args);
2311
- const executable = custody.securefs_executable ?? resolveInstalledHostExecutable();
2807
+ async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
2808
+ const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
2809
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2810
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
2811
+ throw securefsRefusal(result.stderr);
2812
+ }
2813
+ async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
2814
+ 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.");
2815
+ const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
2816
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2817
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
2818
+ throw securefsRefusal(result.stderr);
2819
+ }
2820
+ async function isPrivateWindowsDirectory(path, custody = {}) {
2821
+ await lstat(path);
2822
+ try {
2823
+ const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
2824
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
2825
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
2826
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
2827
+ const refusal = securefsRefusal(result.stderr);
2828
+ if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
2829
+ throw refusal;
2830
+ } catch (error) {
2831
+ if (error instanceof SecureFileCustodyError) throw error;
2832
+ throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
2833
+ }
2834
+ }
2835
+ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2836
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
2837
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2312
2838
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2313
2839
  return await new Promise((resolve3, reject3) => {
2314
- execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2840
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2315
2841
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2316
2842
  if (exitCode === null) {
2317
2843
  reject3(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2319,6 +2845,8 @@ async function runWindowsSecurefs(args, maxBytes, custody) {
2319
2845
  }
2320
2846
  resolve3({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
2321
2847
  });
2848
+ child.stdin?.on("error", () => void 0);
2849
+ child.stdin?.end(stdin);
2322
2850
  });
2323
2851
  }
2324
2852
  function securefsRefusal(stderr) {
@@ -2336,9 +2864,9 @@ function securefsRefusal(stderr) {
2336
2864
  if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
2337
2865
  return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
2338
2866
  }
2339
- function resolveInstalledHostExecutable() {
2867
+ function resolveInstalledHostExecutable(platform) {
2340
2868
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2341
- return win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
2869
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2342
2870
  }
2343
2871
  function isRecord3(value) {
2344
2872
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2354,6 +2882,197 @@ function isPrivateFileMode(mode, platform = process.platform, _handle) {
2354
2882
  if (platform === "win32") return false;
2355
2883
  return (mode & 63) === 0;
2356
2884
  }
2885
+ async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
2886
+ if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
2887
+ const entry = await lstat(path);
2888
+ return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
2889
+ }
2890
+
2891
+ // host/service-log.ts
2892
+ import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
2893
+ import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win322 } from "node:path";
2894
+
2895
+ // host/service-log-delivery.ts
2896
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
2897
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
2898
+ setImmediate(flush);
2899
+ }, onDeliveryGap = () => void 0) {
2900
+ const pending = [];
2901
+ const highWaterMark = stream.writableHighWaterMark;
2902
+ const byteBudget = highWaterMark + highWaterMark;
2903
+ let pendingBytes = 0;
2904
+ let droppedLines = 0;
2905
+ let flushScheduled = false;
2906
+ let waitingForDrain = false;
2907
+ let closed = !stream.writable;
2908
+ function stop() {
2909
+ if (closed) return;
2910
+ closed = true;
2911
+ pending.length = 0;
2912
+ pendingBytes = 0;
2913
+ stream.off("drain", onDrain);
2914
+ stream.off("close", onTerminal);
2915
+ stream.off("finish", onTerminal);
2916
+ stream.off("error", onError);
2917
+ }
2918
+ function onTerminal() {
2919
+ stop();
2920
+ }
2921
+ function onError() {
2922
+ stop();
2923
+ }
2924
+ function onDrain() {
2925
+ waitingForDrain = false;
2926
+ scheduleFlush();
2927
+ }
2928
+ function scheduleFlush() {
2929
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
2930
+ flushScheduled = true;
2931
+ let scheduling = true;
2932
+ let invokedSynchronously = false;
2933
+ try {
2934
+ schedule(() => {
2935
+ if (scheduling) {
2936
+ invokedSynchronously = true;
2937
+ return;
2938
+ }
2939
+ flushScheduled = false;
2940
+ flush();
2941
+ });
2942
+ } catch {
2943
+ flushScheduled = false;
2944
+ stop();
2945
+ return;
2946
+ }
2947
+ scheduling = false;
2948
+ if (invokedSynchronously) {
2949
+ flushScheduled = false;
2950
+ stop();
2951
+ }
2952
+ }
2953
+ function flush() {
2954
+ if (closed) return;
2955
+ if (!stream.writable) {
2956
+ stop();
2957
+ return;
2958
+ }
2959
+ while (pending.length > 0) {
2960
+ if (stream.writableNeedDrain) {
2961
+ if (!waitingForDrain) {
2962
+ waitingForDrain = true;
2963
+ stream.once("drain", onDrain);
2964
+ }
2965
+ return;
2966
+ }
2967
+ const next = pending.shift();
2968
+ if (next === void 0) return;
2969
+ pendingBytes -= next.bytes;
2970
+ let accepted;
2971
+ try {
2972
+ accepted = stream.write(next.line);
2973
+ } catch {
2974
+ stop();
2975
+ return;
2976
+ }
2977
+ if (!accepted) {
2978
+ waitingForDrain = true;
2979
+ stream.once("drain", onDrain);
2980
+ return;
2981
+ }
2982
+ }
2983
+ if (droppedLines > 0) {
2984
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
2985
+ `;
2986
+ droppedLines = 0;
2987
+ try {
2988
+ onDeliveryGap(line);
2989
+ } catch {
2990
+ }
2991
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
2992
+ pendingBytes += Buffer.byteLength(line, "utf8");
2993
+ flush();
2994
+ }
2995
+ }
2996
+ stream.on("close", onTerminal);
2997
+ stream.on("finish", onTerminal);
2998
+ stream.on("error", onError);
2999
+ return (line) => {
3000
+ if (closed) return;
3001
+ const bytes = Buffer.byteLength(line, "utf8");
3002
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
3003
+ droppedLines += 1;
3004
+ scheduleFlush();
3005
+ return;
3006
+ }
3007
+ pending.push({ line, bytes });
3008
+ pendingBytes += bytes;
3009
+ scheduleFlush();
3010
+ };
3011
+ }
3012
+
3013
+ // host/invocation-authentication-client-command.ts
3014
+ var DOCTOR_FLAGS = Object.freeze({
3015
+ "--expected-sha256": "expected_sha256",
3016
+ "--expected-source-commit": "expected_source_commit",
3017
+ "--expected-instance-ref": "expected_instance_ref"
3018
+ });
3019
+
3020
+ // host/service-log.ts
3021
+ var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
3022
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
3023
+ void persistHostServiceLogLine(line);
3024
+ });
3025
+ function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
3026
+ const details = diagnosticDetails(event, failure_kind, cause);
3027
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
3028
+ `;
3029
+ try {
3030
+ (sink ?? defaultHostServiceDiagnosticSink)(line);
3031
+ } catch {
3032
+ }
3033
+ }
3034
+ function diagnosticDetails(event, failureKind, cause) {
3035
+ if (event === "watcher_scan_failed") return {
3036
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3037
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
3038
+ };
3039
+ return validDiagnosticCause(cause, event) ? { cause } : {};
3040
+ }
3041
+ function validDiagnosticCause(cause, event) {
3042
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
3043
+ }
3044
+ function defaultHostServiceDiagnosticSink(line) {
3045
+ writeHostServiceLogLine(line);
3046
+ }
3047
+ var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
3048
+ function writeHostServiceLogLine(line, environment = process.env) {
3049
+ void persistHostServiceLogLine(line, environment);
3050
+ defaultHostServiceLogDelivery(line);
3051
+ }
3052
+ async function persistHostServiceLogLine(line, environment = process.env) {
3053
+ if (process.platform !== "win32") return;
3054
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
3055
+ if (path === void 0 || !win322.isAbsolute(path) || win322.normalize(path) !== path) return;
3056
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
3057
+ }
3058
+ async function appendHostServiceLogLine(path, line) {
3059
+ if (!isAbsolute2(path)) return;
3060
+ await ensureHostServiceLogDirectory(path);
3061
+ await appendFile(path, line);
3062
+ }
3063
+ var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
3064
+ var hostServiceLogDirectories = /* @__PURE__ */ new Map();
3065
+ function ensureHostServiceLogDirectory(path) {
3066
+ const directory = dirname2(path);
3067
+ const existing = hostServiceLogDirectories.get(directory);
3068
+ if (existing !== void 0) return existing;
3069
+ const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
3070
+ hostServiceLogDirectories.delete(directory);
3071
+ throw error;
3072
+ });
3073
+ hostServiceLogDirectories.set(directory, pending);
3074
+ return pending;
3075
+ }
2357
3076
 
2358
3077
  // host/relay/src/host-producer-core.ts
2359
3078
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
@@ -2362,7 +3081,22 @@ function isHostTranscriptCursorReason(value) {
2362
3081
  }
2363
3082
  var TRANSCRIPT_MISSING_REASON = "transcript_missing";
2364
3083
  var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
2365
- var HOST_INVOCATION_TRANSCRIPT_TAIL_MAX_BYTES = 1024 * 1024;
3084
+ var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
3085
+ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
3086
+ const seen = /* @__PURE__ */ new Set();
3087
+ const newestFirst = [];
3088
+ for (const message of [...chronological].reverse()) {
3089
+ if (seen.has(message.host_input_ref)) continue;
3090
+ seen.add(message.host_input_ref);
3091
+ newestFirst.push(message);
3092
+ }
3093
+ for (const message of existing?.messages ?? []) {
3094
+ if (seen.has(message.host_input_ref)) continue;
3095
+ seen.add(message.host_input_ref);
3096
+ newestFirst.push(message);
3097
+ }
3098
+ return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
3099
+ }
2366
3100
  function transcriptScanFailureKind(error, adapterFailureKind) {
2367
3101
  if (transcriptErrorCode(error) === "ELOOP") return "symlink";
2368
3102
  const adapter = adapterFailureKind(error);
@@ -2419,10 +3153,10 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
2419
3153
  return null;
2420
3154
  }
2421
3155
  function transcriptSha256(value) {
2422
- return createHash4("sha256").update(value).digest("hex");
3156
+ return createHash5("sha256").update(value).digest("hex");
2423
3157
  }
2424
3158
  function transcriptObjectSha256(value) {
2425
- return createHash4("sha256").update(JSON.stringify(value), "utf8").digest("hex");
3159
+ return createHash5("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2426
3160
  }
2427
3161
  function isTranscriptRecord(value) {
2428
3162
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2444,7 +3178,7 @@ function createTranscriptWatcherBase(options, owner) {
2444
3178
  outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
2445
3179
  now: options.now ?? (() => /* @__PURE__ */ new Date()),
2446
3180
  log: options.log ?? ((line) => {
2447
- process.stderr.write(`${line}
3181
+ writeHostServiceLogLine(`${line}
2448
3182
  `);
2449
3183
  }),
2450
3184
  producerInstallationRef: options.producer_installation_ref
@@ -2484,7 +3218,13 @@ var HostTranscriptWatcher = class {
2484
3218
  }
2485
3219
  async scanRegistration(registration) {
2486
3220
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
2487
- missing: () => this.retireMissing(registration),
3221
+ missing: async () => {
3222
+ try {
3223
+ return await this.retireMissing(registration);
3224
+ } catch (error) {
3225
+ return this.scanFailed(void 0, registration, error);
3226
+ }
3227
+ },
2488
3228
  failed: (handle, error) => this.scanFailed(handle, registration, error)
2489
3229
  });
2490
3230
  }
@@ -2553,31 +3293,1060 @@ var HostProducerDrainCore = class {
2553
3293
  this.tail = run.then(() => void 0, () => void 0);
2554
3294
  return run;
2555
3295
  }
2556
- async drainLocked() {
2557
- const read = await this.host.listEnvelopes();
2558
- let removed = 0;
2559
- let expired = 0;
2560
- for (const envelope of read.entries) {
2561
- if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
2562
- else removed += 1;
2563
- await this.host.removeEnvelope(envelope);
3296
+ async drainLocked() {
3297
+ const read = await this.host.listEnvelopes();
3298
+ let removed = 0;
3299
+ let expired = 0;
3300
+ for (const envelope of read.entries) {
3301
+ if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
3302
+ else removed += 1;
3303
+ await this.host.removeEnvelope(envelope);
3304
+ }
3305
+ return { removed, expired, malformed: read.malformed };
3306
+ }
3307
+ };
3308
+
3309
+ // host/relay/src/durable-atomic-replacement.ts
3310
+ import { lstat as lstat2, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
3311
+ import { dirname as dirname3 } from "node:path";
3312
+
3313
+ // host/windows-rename-retry.ts
3314
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
3315
+ var RETRY_WINDOW_MS = 1e4;
3316
+ var RETRY_START_DELAY_MS = 100;
3317
+ var RETRY_MAX_DELAY_MS = 2e3;
3318
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
3319
+ var WindowsRenameRetryError = class extends Error {
3320
+ code = "rename_unavailable";
3321
+ constructor(target, attempts, options = {}) {
3322
+ 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);
3323
+ this.name = "WindowsRenameRetryError";
3324
+ }
3325
+ };
3326
+ function resolveRetrySchedule(tuning) {
3327
+ return {
3328
+ windowMs: tuning.windowMs ?? RETRY_WINDOW_MS,
3329
+ startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
3330
+ maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
3331
+ sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
3332
+ now: tuning.now ?? (() => Date.now())
3333
+ };
3334
+ }
3335
+ async function renameWithWindowsRetry(operation, tuning) {
3336
+ const schedule = resolveRetrySchedule(tuning);
3337
+ const deadline = schedule.now() + schedule.windowMs;
3338
+ let delayMs = schedule.startDelayMs;
3339
+ let attempts = 0;
3340
+ for (; ; ) {
3341
+ attempts += 1;
3342
+ try {
3343
+ await operation();
3344
+ return;
3345
+ } catch (error) {
3346
+ if (tuning.platform !== "win32" || !isRetryableRenameError(error)) throw error;
3347
+ await sleepWithinWindow(schedule, deadline, delayMs, () => new WindowsRenameRetryError(tuning.target, attempts, { cause: error }));
3348
+ delayMs = Math.min(delayMs * 2, schedule.maxDelayMs);
3349
+ }
3350
+ }
3351
+ }
3352
+ async function sleepWithinWindow(schedule, deadline, delayMs, exhausted) {
3353
+ if (schedule.now() >= deadline) throw exhausted();
3354
+ await schedule.sleep(Math.min(delayMs, deadline - schedule.now()));
3355
+ if (schedule.now() >= deadline) throw exhausted();
3356
+ }
3357
+ function isRetryableRenameError(error) {
3358
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && RETRYABLE_CODES.has(error.code);
3359
+ }
3360
+
3361
+ // host/relay/src/durable-atomic-replacement.ts
3362
+ var DEFAULT_PORT = {
3363
+ platform: process.platform,
3364
+ mkdir: (path, options) => mkdir2(path, options),
3365
+ lstat: (path) => lstat2(path),
3366
+ open_file: (path) => open2(path, "wx", 384),
3367
+ rename,
3368
+ unlink,
3369
+ open_directory: (path) => open2(path),
3370
+ unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
3371
+ };
3372
+ async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
3373
+ const parent = dirname3(target);
3374
+ await port.mkdir(parent, { recursive: true, mode: 448 });
3375
+ const parentStats = await port.lstat(parent);
3376
+ const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
3377
+ const ownerPrivate = port.platform === "win32" || isOwnedBy(parentStats.uid, expectedUid) && isPrivateFileMode(parentStats.mode, port.platform);
3378
+ 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 }])}.`);
3379
+ const temporary = `${target}.${port.unique_ref()}.new`;
3380
+ let staged;
3381
+ const failures = [];
3382
+ try {
3383
+ staged = await port.open_file(temporary);
3384
+ await staged.writeFile(data, typeof data === "string" ? { encoding: "utf8" } : void 0);
3385
+ await staged.sync();
3386
+ const closing = staged;
3387
+ staged = void 0;
3388
+ await closing.close();
3389
+ await renameWithWindowsRetry(() => port.rename(temporary, target), { ...port.rename_retry, platform: port.platform, target });
3390
+ await syncParentDirectory(parent, port);
3391
+ } catch (error) {
3392
+ failures.push(error);
3393
+ }
3394
+ await closeStaged(staged, failures);
3395
+ await removeTemporary(temporary, port, failures);
3396
+ throwFailures(failures);
3397
+ }
3398
+ async function syncParentDirectory(path, port) {
3399
+ if (port.platform === "win32") return;
3400
+ const handle = await port.open_directory(path);
3401
+ let failure;
3402
+ try {
3403
+ await handle.sync();
3404
+ } catch (error) {
3405
+ if (!directorySyncUnsupported(error)) failure = error;
3406
+ }
3407
+ try {
3408
+ await handle.close();
3409
+ } catch (error) {
3410
+ if (failure === void 0) failure = error;
3411
+ else failure = new AggregateError([failure, error], "Host Relay directory sync and close failed.");
3412
+ }
3413
+ if (failure !== void 0) throw failure;
3414
+ }
3415
+ async function closeStaged(staged, failures) {
3416
+ if (staged !== void 0) try {
3417
+ await staged.close();
3418
+ } catch (error) {
3419
+ failures.push(error);
3420
+ }
3421
+ }
3422
+ async function removeTemporary(path, port, failures) {
3423
+ try {
3424
+ await port.unlink(path);
3425
+ } catch (error) {
3426
+ if (errorCode(error) !== "ENOENT") failures.push(error);
3427
+ }
3428
+ }
3429
+ function throwFailures(failures) {
3430
+ if (failures.length === 1) throw failures[0];
3431
+ if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
3432
+ }
3433
+ function directorySyncUnsupported(error) {
3434
+ return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
3435
+ }
3436
+ function errorCode(error) {
3437
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3438
+ }
3439
+
3440
+ // host/relay/src/host-usage-facts-store.ts
3441
+ import { createHash as createHash6 } from "node:crypto";
3442
+ import { constants as constants2 } from "node:fs";
3443
+ import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3444
+ import { dirname as dirname4, join as join3 } from "node:path";
3445
+ var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3446
+ var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3447
+ var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
3448
+ var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
3449
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
3450
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
3451
+ var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
3452
+ var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
3453
+ var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
3454
+ var HostUsageFactsStore = class {
3455
+ root;
3456
+ sessions;
3457
+ batches;
3458
+ platform;
3459
+ custody;
3460
+ afterPendingWrite;
3461
+ afterBatchPublish;
3462
+ sessionDirectoryCursor;
3463
+ constructor(options) {
3464
+ this.root = join3(options.outbox_dir, "usage-facts");
3465
+ this.sessions = join3(this.root, "sessions");
3466
+ this.batches = join3(this.root, "batches");
3467
+ this.platform = options.platform ?? process.platform;
3468
+ this.custody = options.secure_file_custody ?? {};
3469
+ this.afterPendingWrite = options.afterPendingWrite;
3470
+ this.afterBatchPublish = options.afterBatchPublish;
3471
+ }
3472
+ async prepare() {
3473
+ for (const directory of [this.root, this.sessions, this.batches]) {
3474
+ await preparePrivateDirectory(directory, this.platform, this.custody);
3475
+ }
3476
+ }
3477
+ async close() {
3478
+ const cursor = this.sessionDirectoryCursor;
3479
+ this.sessionDirectoryCursor = void 0;
3480
+ await cursor?.close();
3481
+ }
3482
+ async readState(producer, hostSourceRef, hostSessionRef) {
3483
+ await this.prepare();
3484
+ const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3485
+ const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3486
+ if (value === null) return null;
3487
+ validateState(value, producer, hostSourceRef, hostSessionRef);
3488
+ return value;
3489
+ }
3490
+ createState(producer, hostSourceRef, hostSessionRef) {
3491
+ return {
3492
+ schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
3493
+ producer,
3494
+ host_source_ref: hostSourceRef,
3495
+ host_session_ref: hostSessionRef,
3496
+ cursors: {},
3497
+ eligible_batches: [],
3498
+ coverage_gaps: [],
3499
+ coverage_gap_created_at: null
3500
+ };
3501
+ }
3502
+ async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
3503
+ let state = await this.readState(producer, hostSourceRef, hostSessionRef);
3504
+ if (state === null) {
3505
+ state = this.createState(producer, hostSourceRef, hostSessionRef);
3506
+ state = await this.writeCursor(state, sourceSlot, initial);
3507
+ }
3508
+ state = await this.recoverPending(state);
3509
+ if (state.quarantined_reason !== void 0) return null;
3510
+ state = await this.commitCoverageGaps(state, createdAt);
3511
+ const cursor = state.cursors[sourceSlot];
3512
+ return cursor === void 0 ? null : { state, cursor };
3513
+ }
3514
+ async writeCursor(state, sourceSlot, cursor) {
3515
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3516
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3517
+ if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
3518
+ const current = latest.cursors[sourceSlot];
3519
+ if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
3520
+ const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
3521
+ await this.writeState(updated);
3522
+ return updated;
3523
+ });
3524
+ }
3525
+ async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
3526
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3527
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3528
+ return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
3529
+ });
3530
+ }
3531
+ async recoverPending(state) {
3532
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3533
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3534
+ const recovered = await this.finishPendingTransition(latest);
3535
+ await this.sweepOrphanedBatches(recovered);
3536
+ return recovered;
3537
+ });
3538
+ }
3539
+ /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3540
+ async sweepOrphanedBatches(state) {
3541
+ await this.prepare();
3542
+ const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3543
+ await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3544
+ const expected = expectedBatchNames(state);
3545
+ const directory = await opendir(directoryPath);
3546
+ let inspected = 0;
3547
+ let deleted = 0;
3548
+ try {
3549
+ while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
3550
+ const entry = await directory.read();
3551
+ if (entry === null) break;
3552
+ inspected += 1;
3553
+ if (!isOrphanBatchEntry(entry, expected)) continue;
3554
+ await unlink2(join3(directoryPath, entry.name));
3555
+ deleted += 1;
3556
+ }
3557
+ } finally {
3558
+ await directory.close();
3559
+ }
3560
+ if (deleted > 0) await syncDirectory(directoryPath, this.platform);
3561
+ return deleted;
3562
+ }
3563
+ async commitCoverageGaps(state, createdAt) {
3564
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3565
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3566
+ if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
3567
+ const sourceRanges = coverageRanges(latest.coverage_gaps);
3568
+ const canonical = createCealHostUsageBatch({
3569
+ host_source_ref: latest.host_source_ref,
3570
+ host_session_ref: latest.host_session_ref,
3571
+ created_at: latest.coverage_gap_created_at ?? createdAt,
3572
+ source_ranges: sourceRanges,
3573
+ facts: [],
3574
+ coverage_gaps: latest.coverage_gaps
3575
+ });
3576
+ const cursor = firstCursor(latest);
3577
+ if (cursor === null) return latest;
3578
+ return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
3579
+ });
3580
+ }
3581
+ async nextUploadCandidate(producer, hostSourceRef) {
3582
+ await this.prepare();
3583
+ const names = await this.readNextSessionNames();
3584
+ for (const name of names) {
3585
+ const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3586
+ if (state === null) continue;
3587
+ validateStateOwner(state, producer, hostSourceRef);
3588
+ let validated = state;
3589
+ if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
3590
+ else validated = await this.recoverPending(validated);
3591
+ if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
3592
+ const next = validated.eligible_batches[0];
3593
+ if (next === void 0) continue;
3594
+ const batch = await this.readBatch(validated, next.batch_ref);
3595
+ return { state: validated, batch };
3596
+ }
3597
+ return null;
3598
+ }
3599
+ async readNextSessionNames() {
3600
+ this.sessionDirectoryCursor ??= await opendir(this.sessions);
3601
+ const names = [];
3602
+ let inspected = 0;
3603
+ while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
3604
+ const entry = await this.sessionDirectoryCursor.read();
3605
+ if (entry === null) {
3606
+ await this.sessionDirectoryCursor.close();
3607
+ this.sessionDirectoryCursor = void 0;
3608
+ break;
3609
+ }
3610
+ inspected += 1;
3611
+ if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
3612
+ }
3613
+ return names;
3614
+ }
3615
+ async acknowledge(state, batchRef) {
3616
+ await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3617
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3618
+ if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
3619
+ const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
3620
+ if (remaining.length === latest.eligible_batches.length) return;
3621
+ await this.writeState({ ...latest, eligible_batches: remaining });
3622
+ await removeFileIfPresent(this.batchPath(state, batchRef));
3623
+ });
3624
+ }
3625
+ async quarantine(state, reason) {
3626
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3627
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3628
+ const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
3629
+ await this.writeState(updated);
3630
+ return updated;
3631
+ });
3632
+ }
3633
+ async retireCursor(state, sourceSlot, cursor, gap) {
3634
+ return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
3635
+ }
3636
+ async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
3637
+ if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
3638
+ if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
3639
+ const queued = await this.publishTransitionBatch(state, batch);
3640
+ const pending = {
3641
+ source_slot: sourceSlot,
3642
+ before_cursor: beforeCursor,
3643
+ after_cursor: afterCursor,
3644
+ batch_ref: queued.batch_ref,
3645
+ batch_bytes: queued.batch_bytes,
3646
+ gap_delta: [...gapDelta, ...queued.overflow_gaps],
3647
+ clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
3648
+ };
3649
+ const prepared = { ...state, pending_transition: pending };
3650
+ await this.writeState(prepared);
3651
+ await this.afterPendingWrite?.();
3652
+ return await this.finishPendingTransition(prepared);
3653
+ }
3654
+ async publishTransitionBatch(state, batch) {
3655
+ if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
3656
+ const serialized = serializeBatch(batch);
3657
+ if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
3658
+ await this.writeImmutableBatch(state, batch, serialized);
3659
+ await this.afterBatchPublish?.();
3660
+ return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
3661
+ }
3662
+ async finishPendingTransition(state) {
3663
+ const pending = state.pending_transition;
3664
+ if (pending === void 0 || state.quarantined_reason !== void 0) return state;
3665
+ const current = state.cursors[pending.source_slot];
3666
+ if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
3667
+ const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
3668
+ await this.writeState(quarantined);
3669
+ return quarantined;
3670
+ }
3671
+ let cursors = state.cursors;
3672
+ if (!cursorMatches(current, pending.after_cursor)) {
3673
+ const next = { ...state.cursors };
3674
+ if (pending.after_cursor === null) delete next[pending.source_slot];
3675
+ else next[pending.source_slot] = pending.after_cursor;
3676
+ cursors = next;
3677
+ }
3678
+ const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
3679
+ const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
3680
+ const { pending_transition: _pendingTransition, ...settledState } = state;
3681
+ const updated = {
3682
+ ...settledState,
3683
+ cursors,
3684
+ eligible_batches: eligible,
3685
+ coverage_gaps: gaps,
3686
+ coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
3687
+ };
3688
+ await this.writeState(updated);
3689
+ return updated;
3690
+ }
3691
+ async writeImmutableBatch(state, batch, bytes) {
3692
+ const path = this.batchPath(state, batch.batch_ref);
3693
+ await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
3694
+ const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3695
+ if (existing !== null) {
3696
+ if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3697
+ await syncExistingFile(path, this.platform);
3698
+ return;
3699
+ }
3700
+ if (this.platform === "win32") {
3701
+ await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
3702
+ return;
3703
+ }
3704
+ let handle;
3705
+ try {
3706
+ handle = await openNoFollow(path, constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY, 384, this.platform);
3707
+ await handle.writeFile(bytes);
3708
+ await handle.sync();
3709
+ await handle.close();
3710
+ handle = void 0;
3711
+ await syncDirectory(dirname4(path), this.platform);
3712
+ } catch (error) {
3713
+ await handle?.close().catch(() => void 0);
3714
+ if (errorCode2(error) === "EEXIST") {
3715
+ const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3716
+ if (winner !== null && winner.equals(bytes)) {
3717
+ await syncExistingFile(path, this.platform);
3718
+ return;
3719
+ }
3720
+ throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3721
+ }
3722
+ await removeFileIfPresent(path).catch(() => void 0);
3723
+ throw error;
3724
+ }
3725
+ }
3726
+ async readBatch(state, batchRef) {
3727
+ const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3728
+ if (bytes === null) throw new Error("Host usage facts batch object is missing.");
3729
+ let value;
3730
+ try {
3731
+ value = JSON.parse(bytes.toString("utf8"));
3732
+ } catch {
3733
+ throw new Error("Host usage facts batch object is malformed.");
3734
+ }
3735
+ validateCealHostUsageBatch(value);
3736
+ if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
3737
+ return value;
3738
+ }
3739
+ async writeState(state) {
3740
+ validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
3741
+ const bytes = Buffer.from(JSON.stringify(state), "utf8");
3742
+ if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
3743
+ await this.prepare();
3744
+ const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
3745
+ if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
3746
+ else await durableAtomicReplace(path, bytes);
3747
+ }
3748
+ async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
3749
+ const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3750
+ const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
3751
+ let release;
3752
+ const gate = new Promise((resolve3) => {
3753
+ release = resolve3;
3754
+ });
3755
+ const tail = previous.then(() => gate);
3756
+ SESSION_TRANSITION_TAILS.set(key, tail);
3757
+ await previous;
3758
+ try {
3759
+ return await run();
3760
+ } finally {
3761
+ release?.();
3762
+ if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
3763
+ }
3764
+ }
3765
+ sessionPath(producer, hostSourceRef, hostSessionRef) {
3766
+ return join3(this.sessions, `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3767
+ }
3768
+ batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3769
+ const sessionName = `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3770
+ return join3(this.batches, sessionName.slice(0, -5));
3771
+ }
3772
+ batchPath(state, batchRef) {
3773
+ return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3774
+ }
3775
+ };
3776
+ function serializeBatch(batch) {
3777
+ validateCealHostUsageBatch(batch);
3778
+ return Buffer.from(JSON.stringify(batch), "utf8");
3779
+ }
3780
+ function batchFileName(batchRef) {
3781
+ const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
3782
+ if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
3783
+ return `${digest2}.json`;
3784
+ }
3785
+ function expectedBatchNames(state) {
3786
+ const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
3787
+ const pending = state.pending_transition?.batch_ref;
3788
+ if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
3789
+ return expected;
3790
+ }
3791
+ function isOrphanBatchEntry(entry, expected) {
3792
+ return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
3793
+ }
3794
+ function hasOutboxCapacity(state, bytes) {
3795
+ const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
3796
+ return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
3797
+ }
3798
+ function overflowCoverageGaps(batch) {
3799
+ const count = batch.facts.length;
3800
+ const gaps = [...batch.coverage_gaps];
3801
+ 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 });
3802
+ return gaps;
3803
+ }
3804
+ function appendEligible(existing, next) {
3805
+ if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
3806
+ if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
3807
+ return [...existing, next];
3808
+ }
3809
+ function appendCoverageGaps(existing, added) {
3810
+ if (added.length === 0) return existing;
3811
+ const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
3812
+ for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
3813
+ const combined = [...byIdentity.values()];
3814
+ if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
3815
+ const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
3816
+ return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
3817
+ }
3818
+ function coverageRanges(gaps) {
3819
+ const ranges = /* @__PURE__ */ new Map();
3820
+ for (const gap of gaps) {
3821
+ if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
3822
+ const current = ranges.get(gap.source_file_ref);
3823
+ 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 });
3824
+ 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) });
3825
+ }
3826
+ return [...ranges.values()];
3827
+ }
3828
+ function firstCursor(state) {
3829
+ const entry = Object.entries(state.cursors)[0];
3830
+ return entry === void 0 ? null : entry;
3831
+ }
3832
+ function sameCursor(left, right) {
3833
+ return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
3834
+ }
3835
+ function cursorMatches(left, right) {
3836
+ return right === null ? left === void 0 : sameCursor(left, right);
3837
+ }
3838
+ function validateState(value, producer, hostSourceRef, hostSessionRef) {
3839
+ validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
3840
+ validateStateShape(value);
3841
+ validateStateLimits(value);
3842
+ validateStateContents(value);
3843
+ }
3844
+ function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
3845
+ if (!isRecord4(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.");
3846
+ }
3847
+ function validateStateLimits(value) {
3848
+ 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.");
3849
+ }
3850
+ function validateStateContents(value) {
3851
+ for (const [slot, cursor] of Object.entries(value.cursors)) {
3852
+ validateSourceSlot(slot);
3853
+ validateFileCursor(cursor);
3854
+ }
3855
+ for (const item of value.eligible_batches) validateEligibleBatch(item);
3856
+ if (value.pending_transition !== void 0) validatePending(value.pending_transition);
3857
+ for (const gap of value.coverage_gaps) validateGap(gap);
3858
+ validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
3859
+ }
3860
+ function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
3861
+ if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
3862
+ if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
3863
+ }
3864
+ function validateStateOwner(value, producer, hostSourceRef) {
3865
+ if (!isRecord4(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
3866
+ validateState(value, producer, hostSourceRef, String(value.host_session_ref));
3867
+ }
3868
+ function validateStateShape(value) {
3869
+ const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
3870
+ const optional = ["pending_transition", "quarantined_reason"];
3871
+ 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.");
3872
+ if (!isRecord4(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.");
3873
+ }
3874
+ function validateFileCursor(value) {
3875
+ if (!isRecord4(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.");
3876
+ validateCursorIdentity(value);
3877
+ validateCursorOffsets(value);
3878
+ validateCursorContext(value);
3879
+ if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
3880
+ if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
3881
+ }
3882
+ function validateCursorIdentity(value) {
3883
+ 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.");
3884
+ }
3885
+ function validateCursorOffsets(value) {
3886
+ 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.");
3887
+ }
3888
+ function validateCursorContext(value) {
3889
+ 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.");
3890
+ }
3891
+ function validOptionalText(value, maximum) {
3892
+ return value === null || typeof value === "string" && value.length <= maximum;
3893
+ }
3894
+ function validateCodexCounts(value) {
3895
+ if (!isRecord4(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.");
3896
+ if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
3897
+ }
3898
+ function validatePending(value) {
3899
+ if (!isRecord4(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.");
3900
+ validatePendingCursors(value);
3901
+ validatePendingBatch(value);
3902
+ validatePendingFields(value);
3903
+ for (const gap of value.gap_delta) validateGap(gap);
3904
+ }
3905
+ function validatePendingCursors(value) {
3906
+ validateSourceSlot(value.source_slot);
3907
+ validateFileCursor(value.before_cursor);
3908
+ if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
3909
+ }
3910
+ function validatePendingBatch(value) {
3911
+ if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
3912
+ }
3913
+ function validatePendingFields(value) {
3914
+ 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.");
3915
+ }
3916
+ function validateEligibleBatch(value) {
3917
+ if (!isRecord4(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.");
3918
+ }
3919
+ function validateGap(value) {
3920
+ try {
3921
+ validateCealHostUsageCoverageGap(value);
3922
+ } catch {
3923
+ throw new Error("Host usage facts coverage gap is invalid.");
3924
+ }
3925
+ }
3926
+ function validateSourceSlot(value) {
3927
+ if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
3928
+ }
3929
+ async function readOptionalJson(path, maxBytes, platform, custody) {
3930
+ const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
3931
+ if (bytes === null) return null;
3932
+ try {
3933
+ return JSON.parse(bytes.toString("utf8"));
3934
+ } catch {
3935
+ throw new Error("Host usage facts state JSON is malformed.");
3936
+ }
3937
+ }
3938
+ async function readOptionalBytes(path, maxBytes, platform, custody) {
3939
+ if (platform === "win32") {
3940
+ try {
3941
+ return await readPrivateFileWithSecurefs(path, maxBytes, custody);
3942
+ } catch (error) {
3943
+ if (errorCode2(error) === "ENOENT") return null;
3944
+ throw error;
3945
+ }
3946
+ }
3947
+ let handle;
3948
+ try {
3949
+ handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
3950
+ const stats = await handle.stat();
3951
+ 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.");
3952
+ return await handle.readFile();
3953
+ } catch (error) {
3954
+ if (errorCode2(error) === "ENOENT") return null;
3955
+ throw error;
3956
+ } finally {
3957
+ await handle?.close();
3958
+ }
3959
+ }
3960
+ async function preparePrivateDirectory(path, platform, custody) {
3961
+ if (platform === "win32") {
3962
+ await ensurePrivateDirectoryWithSecurefs(path, custody);
3963
+ return;
3964
+ }
3965
+ await mkdir3(path, { recursive: true, mode: 448 });
3966
+ if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3967
+ }
3968
+ async function syncExistingFile(path, platform) {
3969
+ const handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
3970
+ try {
3971
+ await handle.sync();
3972
+ } finally {
3973
+ await handle.close();
3974
+ }
3975
+ await syncDirectory(dirname4(path), platform);
3976
+ }
3977
+ async function syncDirectory(path, platform) {
3978
+ if (platform === "win32") return;
3979
+ const handle = await open3(path, constants2.O_RDONLY);
3980
+ try {
3981
+ await handle.sync();
3982
+ } finally {
3983
+ await handle.close();
3984
+ }
3985
+ }
3986
+ async function removeFileIfPresent(path) {
3987
+ try {
3988
+ await unlink2(path);
3989
+ } catch (error) {
3990
+ if (errorCode2(error) !== "ENOENT") throw error;
3991
+ }
3992
+ }
3993
+ function sameKeys(value, expected) {
3994
+ return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
3995
+ }
3996
+ function isRecord4(value) {
3997
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3998
+ }
3999
+ function safeInteger2(value) {
4000
+ return Number.isSafeInteger(value) && Number(value) >= 0;
4001
+ }
4002
+ function validTimestamp(value) {
4003
+ return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
4004
+ }
4005
+ function errorCode2(error) {
4006
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
4007
+ }
4008
+ function sha2563(value) {
4009
+ return createHash6("sha256").update(value, "utf8").digest("hex");
4010
+ }
4011
+
4012
+ // host/relay/src/host-usage-facts-capture.ts
4013
+ import { constants as constants3 } from "node:fs";
4014
+ var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
4015
+ var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
4016
+ var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
4017
+ var HostUsageTranscriptSourceError = class extends Error {
4018
+ constructor(options) {
4019
+ super("Host usage transcript source could not be read.", options);
4020
+ this.name = "HostUsageTranscriptSourceError";
4021
+ }
4022
+ };
4023
+ async function readHostUsageTranscriptSource(read) {
4024
+ try {
4025
+ return await read();
4026
+ } catch (error) {
4027
+ throw new HostUsageTranscriptSourceError({ cause: error });
4028
+ }
4029
+ }
4030
+ async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4031
+ if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4032
+ let failed = false;
4033
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4034
+ const index = (startIndex + attempt) % registrations.length;
4035
+ const registration = registrations[index];
4036
+ if (registration === void 0) continue;
4037
+ try {
4038
+ if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
4039
+ } catch (error) {
4040
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4041
+ failed = true;
4042
+ }
4043
+ }
4044
+ return { captured: false, nextIndex: startIndex, failed };
4045
+ }
4046
+ async function openHostUsageTranscriptCursor(input) {
4047
+ const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
4048
+ let source;
4049
+ try {
4050
+ source = await readHostUsageTranscriptSource(() => input.inspect(handle));
4051
+ } catch (error) {
4052
+ await handle.close().catch(() => void 0);
4053
+ throw error;
4054
+ }
4055
+ const sourceFileRef = hostUsageSourceFileReference(input.source_kind, input.host_source_ref, input.host_session_ref, source.device, source.inode);
4056
+ let prepared;
4057
+ try {
4058
+ 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);
4059
+ } catch (error) {
4060
+ await handle.close().catch(() => void 0);
4061
+ throw error;
4062
+ }
4063
+ if (prepared === null) {
4064
+ await handle.close();
4065
+ return null;
4066
+ }
4067
+ return { handle, source, source_file_ref: sourceFileRef, ...prepared };
4068
+ }
4069
+ async function readHostUsageTranscriptChunk(handle, offset, size, skippingOversizedLine) {
4070
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(size) || size < offset) throw new TypeError("Host usage transcript range is invalid.");
4071
+ if (size === offset) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
4072
+ if (skippingOversizedLine) return await resumeOversizedLine(handle, offset, size);
4073
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
4074
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
4075
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
4076
+ const chunk = bytes.subarray(0, bytesRead);
4077
+ return completeChunk(chunk, offset);
4078
+ }
4079
+ async function resumeOversizedLine(handle, offset, size) {
4080
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
4081
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
4082
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
4083
+ const chunk = bytes.subarray(0, bytesRead);
4084
+ const delimiter = chunk.indexOf(10);
4085
+ if (delimiter < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
4086
+ return completeChunk(chunk.subarray(delimiter + 1), offset + delimiter + 1);
4087
+ }
4088
+ function completeChunk(chunk, offset) {
4089
+ const parsed = completeLinePrefix(chunk, offset);
4090
+ const oversizedRows = parsed.oversizedRows + (parsed.incompleteOversized ? 1 : 0);
4091
+ const endOffset = parsed.incompleteOversized ? offset + chunk.length : parsed.endOffset;
4092
+ return { lines: parsed.lines, end_offset: endOffset, skipping_oversized_line: parsed.incompleteOversized, oversized_rows: oversizedRows };
4093
+ }
4094
+ function completeLinePrefix(bytes, baseOffset) {
4095
+ const lines = [];
4096
+ let lineStart = 0;
4097
+ let endOffset = baseOffset;
4098
+ let oversizedRows = 0;
4099
+ let rowCount = 0;
4100
+ for (let index = 0; index < bytes.length; index += 1) {
4101
+ if (bytes[index] !== 10) continue;
4102
+ const line = bytes.subarray(lineStart, index);
4103
+ if (line.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES) oversizedRows += 1;
4104
+ else lines.push(line);
4105
+ lineStart = index + 1;
4106
+ endOffset = baseOffset + lineStart;
4107
+ rowCount += 1;
4108
+ if (rowCount >= HOST_USAGE_FACTS_SCAN_MAX_ROWS) return { lines, endOffset, oversizedRows, incompleteOversized: false };
4109
+ }
4110
+ const incomplete = bytes.subarray(lineStart);
4111
+ return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
4112
+ }
4113
+
4114
+ // host/relay/src/host-registration-state.ts
4115
+ import { constants as constants4 } from "node:fs";
4116
+ import { dirname as dirname5 } from "node:path";
4117
+
4118
+ // host/runtime-source-paths.ts
4119
+ import { createHash as createHash7 } from "node:crypto";
4120
+ import { posix as posix3, win32 as win324 } from "node:path";
4121
+
4122
+ // host/absolute-path.ts
4123
+ import { posix as posix2, win32 as win323 } from "node:path";
4124
+ function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
4125
+ const pathApi = flavor === "win32" || flavor === "windows" ? win323 : posix2;
4126
+ return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
4127
+ }
4128
+
4129
+ // host/unix-socket-path.ts
4130
+ var PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES = 103;
4131
+
4132
+ // host/runtime-source-paths.ts
4133
+ var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
4134
+ function hostSourceUuid(sourceRef) {
4135
+ return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
4136
+ }
4137
+ var DARWIN_UID_MAX = 4294967295;
4138
+ var MACOS_HOST_RELAY_IPC_ROOT_PREFIX = "/private/tmp/ceal-host-";
4139
+ function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
4140
+ if (!Number.isInteger(uid) || uid < 0 || uid > DARWIN_UID_MAX) throw new TypeError("Host runtime effective user identity is invalid.");
4141
+ return `${MACOS_HOST_RELAY_IPC_ROOT_PREFIX}${uid}`;
4142
+ }
4143
+ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
4144
+ const sourceId = hostSourceUuid(sourceRef);
4145
+ if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
4146
+ const path = platform === "win32" ? win324 : posix3;
4147
+ const sourcesRoot = path.join(stateRoot, "sources");
4148
+ const sourceRoot = path.join(sourcesRoot, sourceId);
4149
+ const runtimeRoot = path.join(stateRoot, "run");
4150
+ const rootedEndpoint = path.join(runtimeRoot, `${sourceId}.sock`);
4151
+ const endpoint = projectRelayEndpoint(stateRoot, sourceRef, rootedEndpoint, platform, uid);
4152
+ 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 };
4153
+ }
4154
+ function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
4155
+ if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
4156
+ const digest2 = createHash7("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
4157
+ return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix3.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
4158
+ }
4159
+ function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
4160
+ const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
4161
+ 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.");
4162
+ return paths.endpoint;
4163
+ }
4164
+
4165
+ // host/relay/src/host-registration-state.ts
4166
+ var HOST_REGISTRATION_STATE_SCHEMA = "ceal.host_registration_state.v1";
4167
+ var HOST_REGISTRATION_STATE_KEYS = Object.freeze([
4168
+ "credential_generation",
4169
+ "gateway_request_origin",
4170
+ "host_access_token",
4171
+ "host_installation_ref",
4172
+ "host_source_ref",
4173
+ "registration_attempt_ref",
4174
+ "schema_version",
4175
+ "status"
4176
+ ]);
4177
+ var HOST_REGISTRATION_STATE_MAX_BYTES = 65536;
4178
+ var HostRegistrationStateError = class extends Error {
4179
+ name = "HostRegistrationStateError";
4180
+ code = "credential";
4181
+ };
4182
+ async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
4183
+ let raw;
4184
+ try {
4185
+ await assertPrivateRegistrationDirectory(dirname5(path), platform, custody);
4186
+ raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
4187
+ } catch (error) {
4188
+ throw registrationReadError(error);
4189
+ }
4190
+ 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}`)}.`);
4191
+ let value;
4192
+ try {
4193
+ value = JSON.parse(raw);
4194
+ } catch {
4195
+ throw new HostRegistrationStateError("Host registration state is invalid.");
4196
+ }
4197
+ return decodeHostRegistrationAuthority(value, expectedHostSourceRef);
4198
+ }
4199
+ async function readWindowsRegistration(path, custody) {
4200
+ const bytes = await readPrivateFileWithSecurefs(path, HOST_REGISTRATION_STATE_MAX_BYTES, custody);
4201
+ try {
4202
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
4203
+ } catch {
4204
+ throw new HostRegistrationStateError("Host registration state is invalid.");
4205
+ }
4206
+ }
4207
+ async function readPosixRegistration(path, platform, custody) {
4208
+ const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform, custody);
4209
+ try {
4210
+ const stats = await handle.stat();
4211
+ 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.");
4212
+ return await handle.readFile("utf8");
4213
+ } finally {
4214
+ await handle.close();
4215
+ }
4216
+ }
4217
+ function registrationReadError(error) {
4218
+ if (error instanceof HostRegistrationStateError) return error;
4219
+ if (error instanceof SecureFileCustodyError && error.reason === "not_private") return new HostRegistrationStateError("Host registration file is not private to its owner.");
4220
+ return new HostRegistrationStateError("Host registration file is unavailable.");
4221
+ }
4222
+ function decodeHostRegistrationAuthority(value, expectedHostSourceRef) {
4223
+ const keys = HOST_REGISTRATION_STATE_KEYS;
4224
+ const fieldCount = record(value) ? Object.keys(value).length : 0;
4225
+ const missing = record(value) ? keys.filter((key) => !Object.hasOwn(value, key)).length : keys.length;
4226
+ 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" }])}.`);
4227
+ 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>" }])}.`);
4228
+ 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" }])}.`);
4229
+ 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")}.`);
4230
+ return { gateway_request_origin: value.gateway_request_origin, host_access_token: value.host_access_token };
4231
+ }
4232
+ function validRegistrationIdentity(value, expectedHostSourceRef) {
4233
+ 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;
4234
+ }
4235
+ function validRegistrationCredential(value) {
4236
+ return Number.isSafeInteger(value.credential_generation) && Number(value.credential_generation) > 0 && validHostAccessToken(value.host_access_token);
4237
+ }
4238
+ function validHostAccessToken(value) {
4239
+ return typeof value === "string" && CEAL_HOST_ACCESS_TOKEN_PATTERN.test(value);
4240
+ }
4241
+ function validGatewayOrigin(value) {
4242
+ try {
4243
+ if (typeof value !== "string" || /\s|\0/u.test(value)) return false;
4244
+ const parsed = new URL(value);
4245
+ const hostname = parsed.hostname.toLowerCase().replace(/\.+$/u, "");
4246
+ return hostname !== "" && validGatewayPort(parsed.port) && (loopbackHttpOrigin(parsed, hostname) || parsed.protocol === "https:") && cleanOriginPath(parsed) && bareOriginSuffix(value);
4247
+ } catch {
4248
+ return false;
4249
+ }
4250
+ }
4251
+ function loopbackHttpOrigin(parsed, hostname) {
4252
+ return parsed.protocol === "http:" && parsed.port !== "" && (hostname === "127.0.0.1" || hostname === "[::1]");
4253
+ }
4254
+ function validGatewayPort(port) {
4255
+ if (port === "") return true;
4256
+ const numeric = Number(port);
4257
+ return Number.isInteger(numeric) && numeric >= 1 && numeric <= 65535;
4258
+ }
4259
+ function cleanOriginPath(parsed) {
4260
+ return parsed.username === "" && parsed.password === "" && parsed.pathname === "/" && parsed.search === "" && parsed.hash === "";
4261
+ }
4262
+ function bareOriginSuffix(value) {
4263
+ const schemeEnd = value.indexOf("://");
4264
+ const authority = schemeEnd < 0 ? "" : value.slice(schemeEnd + 3);
4265
+ const suffixOffset = authority.search(/[\\/?#]/u);
4266
+ const rawSuffix = suffixOffset < 0 ? "" : authority.slice(suffixOffset);
4267
+ return rawSuffix === "" || rawSuffix === "/";
4268
+ }
4269
+ async function assertPrivateRegistrationDirectory(path, platform, custody) {
4270
+ if (!await isPrivateDirectory(path, platform, custody)) throw new HostRegistrationStateError("Host registration directory is not private to its owner.");
4271
+ }
4272
+ function record(value) {
4273
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4274
+ }
4275
+
4276
+ // host/abortable-wait.ts
4277
+ function waitForAbort(signal, milliseconds) {
4278
+ if (signal.aborted) return Promise.resolve();
4279
+ return new Promise((resolve3) => {
4280
+ const timer = setTimeout(finish, milliseconds);
4281
+ function finish() {
4282
+ clearTimeout(timer);
4283
+ signal.removeEventListener("abort", finish);
4284
+ resolve3();
2564
4285
  }
2565
- return { removed, expired, malformed: read.malformed };
2566
- }
2567
- };
4286
+ signal.addEventListener("abort", finish, { once: true });
4287
+ });
4288
+ }
2568
4289
 
2569
- // host/relay/src/durable-atomic-replacement.ts
2570
- import { lstat as lstat2, mkdir, open as open2, rename, unlink } from "node:fs/promises";
2571
- var DEFAULT_PORT = {
2572
- platform: process.platform,
2573
- mkdir: (path, options) => mkdir(path, options),
2574
- lstat: (path) => lstat2(path),
2575
- open_file: (path) => open2(path, "wx", 384),
2576
- rename,
2577
- unlink,
2578
- open_directory: (path) => open2(path),
2579
- unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
4290
+ // host/relay/src/host-usage-facts-uploader.ts
4291
+ var HostUsageFactsUploader = class {
4292
+ options;
4293
+ store;
4294
+ constructor(options) {
4295
+ if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
4296
+ this.options = options;
4297
+ this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
4298
+ }
4299
+ async close() {
4300
+ await this.store.close();
4301
+ }
4302
+ async uploadOne(signal) {
4303
+ const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4304
+ if (candidate === null) return false;
4305
+ 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);
4306
+ const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4307
+ const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4308
+ const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4309
+ method: "POST",
4310
+ headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4311
+ body: JSON.stringify(candidate.batch),
4312
+ signal: requestSignal
4313
+ });
4314
+ if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
4315
+ await response2.body?.cancel().catch(() => void 0);
4316
+ throw new Error("Gateway did not acknowledge the Host usage facts batch.");
4317
+ }
4318
+ await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
4319
+ return true;
4320
+ }
2580
4321
  };
4322
+ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4323
+ const uploader = new HostUsageFactsUploader(options);
4324
+ let delay = 500;
4325
+ let failures = 0;
4326
+ try {
4327
+ while (!signal.aborted) {
4328
+ try {
4329
+ await options.capture_next?.();
4330
+ } catch {
4331
+ writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
4332
+ }
4333
+ if (signal.aborted) return;
4334
+ try {
4335
+ const uploaded = await uploader.uploadOne(signal);
4336
+ failures = 0;
4337
+ delay = uploaded ? 100 : 1e3;
4338
+ } catch {
4339
+ if (signal.aborted) return;
4340
+ failures += 1;
4341
+ delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
4342
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4343
+ }
4344
+ if (!signal.aborted) await wait(signal, delay);
4345
+ }
4346
+ } finally {
4347
+ await uploader.close().catch(() => void 0);
4348
+ }
4349
+ }
2581
4350
 
2582
4351
  // host/relay/src/relay-quarantine-store.ts
2583
4352
  var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
@@ -2594,16 +4363,6 @@ var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2594
4363
 
2595
4364
  // host/relay/src/relay-ipc.ts
2596
4365
  var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2597
- var HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2598
- "permission_denied",
2599
- "socket_missing",
2600
- "connection_refused",
2601
- "closed_early",
2602
- "response_invalid",
2603
- "timed_out",
2604
- "cancelled",
2605
- "unavailable"
2606
- ]);
2607
4366
 
2608
4367
  // host/codex/src/codex-invocation-context.ts
2609
4368
  function codexInvocationContextFromTurn(identity, promptRef, expiresAt, turnGenerationRef) {
@@ -2618,12 +4377,12 @@ function validateCodexHostInvocationContext(value) {
2618
4377
  validateContextTimes(value);
2619
4378
  }
2620
4379
  function validateIdentity(value) {
2621
- if (!isRecord4(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2)) {
4380
+ if (!isRecord5(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2)) {
2622
4381
  throw new CodexHostAdapterError("storage", "Codex Host invocation identity is malformed.");
2623
4382
  }
2624
4383
  }
2625
4384
  function isContextShape(value) {
2626
- return isRecord4(value) && hasHostInvocationContextKeys(value, ["turn_generation_ref"]) && value.schema_version === CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION;
4385
+ return isRecord5(value) && hasHostInvocationContextKeys(value, ["turn_generation_ref"]) && value.schema_version === CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION;
2627
4386
  }
2628
4387
  function validateContextReferences(value) {
2629
4388
  if (!safeRef2(value.prompt_ref) || !optionalSafeRef(value.turn_generation_ref)) throw new CodexHostAdapterError("storage", "Codex Host invocation context is malformed.");
@@ -2641,7 +4400,7 @@ function safeRef2(value) {
2641
4400
  function timestamp(value) {
2642
4401
  return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
2643
4402
  }
2644
- function isRecord4(value) {
4403
+ function isRecord5(value) {
2645
4404
  return value !== null && typeof value === "object" && !Array.isArray(value);
2646
4405
  }
2647
4406
 
@@ -2659,12 +4418,12 @@ var CodexOutboxStore = class {
2659
4418
  constructor(directory) {
2660
4419
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
2661
4420
  this.directory = directory;
2662
- this.entriesDirectory = join2(directory, "entries");
2663
- this.sessionsDirectory = join2(directory, "sessions");
2664
- this.activeContextsDirectory = join2(directory, "active-contexts");
2665
- this.turnSelectionsDirectory = join2(directory, "turn-selections");
2666
- this.registrationsDirectory = join2(directory, "transcript-registrations");
2667
- this.cursorsDirectory = join2(directory, "transcript-cursors");
4421
+ this.entriesDirectory = join4(directory, "entries");
4422
+ this.sessionsDirectory = join4(directory, "sessions");
4423
+ this.activeContextsDirectory = join4(directory, "active-contexts");
4424
+ this.turnSelectionsDirectory = join4(directory, "turn-selections");
4425
+ this.registrationsDirectory = join4(directory, "transcript-registrations");
4426
+ this.cursorsDirectory = join4(directory, "transcript-cursors");
2668
4427
  }
2669
4428
  async prepare() {
2670
4429
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -2683,7 +4442,7 @@ var CodexOutboxStore = class {
2683
4442
  for (const name of await readdir(this.entriesDirectory)) {
2684
4443
  if (!name.endsWith(".json")) continue;
2685
4444
  try {
2686
- const value = JSON.parse(await readOwnerStateFile(join2(this.entriesDirectory, name)));
4445
+ const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
2687
4446
  validateEnvelope(value);
2688
4447
  entries.push(value);
2689
4448
  } catch {
@@ -2696,7 +4455,7 @@ var CodexOutboxStore = class {
2696
4455
  async remove(entry) {
2697
4456
  validateEnvelope(entry);
2698
4457
  try {
2699
- await unlink2(this.entryPath(entry.submission_ref));
4458
+ await unlink3(this.entryPath(entry.submission_ref));
2700
4459
  } catch (error) {
2701
4460
  if (!isNotFound(error)) throw storageError("Unable to remove the Codex outbox entry.");
2702
4461
  }
@@ -2714,7 +4473,7 @@ var CodexOutboxStore = class {
2714
4473
  await writeAtomicJson(path, context);
2715
4474
  } catch (error) {
2716
4475
  try {
2717
- await unlink2(path);
4476
+ await unlink3(path);
2718
4477
  } catch (unlinkError) {
2719
4478
  if (!isNotFound(unlinkError)) throw storageError("Unable to clear a failed Codex Host context replacement.");
2720
4479
  }
@@ -2729,13 +4488,13 @@ var CodexOutboxStore = class {
2729
4488
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
2730
4489
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
2731
4490
  await this.prepare();
2732
- return readOptionalJson(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
4491
+ return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
2733
4492
  }
2734
4493
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
2735
4494
  const selection = await this.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref);
2736
4495
  if (selection === null || selection.prompt_ref !== promptRef || selection.turn_generation_ref !== turnGenerationRef) return false;
2737
4496
  const path = this.activeContextPath(identity);
2738
- const active = await readOptionalJson(path, validateCodexHostInvocationContext);
4497
+ const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
2739
4498
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
2740
4499
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
2741
4500
  return true;
@@ -2754,7 +4513,7 @@ var CodexOutboxStore = class {
2754
4513
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
2755
4514
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
2756
4515
  await this.prepare();
2757
- const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson(file, validateCodexHostInvocationContext));
4516
+ const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
2758
4517
  return context;
2759
4518
  }
2760
4519
  /** Clear the projection only if the caller still owns its exact active turn. */
@@ -2763,7 +4522,7 @@ var CodexOutboxStore = class {
2763
4522
  const active = await this.readInvocationContext(identity.host_source_ref, identity.host_session_ref, now);
2764
4523
  if (active === null || !sameIdentity(active.identity, identity)) return false;
2765
4524
  try {
2766
- await unlink2(this.activeContextPath(identity));
4525
+ await unlink3(this.activeContextPath(identity));
2767
4526
  } catch (error) {
2768
4527
  if (!isNotFound(error)) throw storageError("Unable to clear the Codex Host invocation context.");
2769
4528
  }
@@ -2778,13 +4537,13 @@ var CodexOutboxStore = class {
2778
4537
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
2779
4538
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
2780
4539
  await this.prepare();
2781
- return readOptionalJson(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
4540
+ return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
2782
4541
  }
2783
4542
  async registerTranscript(registration) {
2784
4543
  validateRegistration(registration);
2785
4544
  await this.prepare();
2786
4545
  const path = this.registrationPath(registration.host_source_ref, registration.host_session_ref);
2787
- const existing = await readOptionalJson(path, validateRegistration);
4546
+ const existing = await readOptionalJson2(path, validateRegistration);
2788
4547
  if (existing !== null && (existing.codex_session_id !== registration.codex_session_id || existing.transcript_path !== registration.transcript_path)) {
2789
4548
  throw storageError("Codex transcript registration conflicts with the source-bound session.");
2790
4549
  }
@@ -2809,7 +4568,7 @@ var CodexOutboxStore = class {
2809
4568
  for (const name of await readdir(this.registrationsDirectory)) {
2810
4569
  if (!name.endsWith(".json")) continue;
2811
4570
  try {
2812
- const value = JSON.parse(await readOwnerStateFile(join2(this.registrationsDirectory, name)));
4571
+ const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
2813
4572
  validateRegistration(value);
2814
4573
  registrations.push(value);
2815
4574
  } catch {
@@ -2820,7 +4579,7 @@ var CodexOutboxStore = class {
2820
4579
  async readTranscriptCursor(registration) {
2821
4580
  validateRegistration(registration);
2822
4581
  await this.prepare();
2823
- return readOptionalJson(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
4582
+ return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
2824
4583
  }
2825
4584
  async writeTranscriptCursor(cursor) {
2826
4585
  validateCursor(cursor);
@@ -2843,27 +4602,27 @@ var CodexOutboxStore = class {
2843
4602
  }
2844
4603
  entryPath(submissionRef) {
2845
4604
  if (!SAFE_REF3.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
2846
- return join2(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
4605
+ return join4(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
2847
4606
  }
2848
4607
  sessionPath(sourceRef, sessionRef) {
2849
- return join2(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
4608
+ return join4(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
2850
4609
  }
2851
4610
  activeContextPath(identity) {
2852
- return join2(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
4611
+ return join4(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
2853
4612
  }
2854
4613
  turnSelectionPath(sourceRef, sessionRef) {
2855
- return join2(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
4614
+ return join4(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
2856
4615
  }
2857
4616
  registrationPath(sourceRef, sessionRef) {
2858
- return join2(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4617
+ return join4(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
2859
4618
  }
2860
4619
  cursorPath(sourceRef, sessionRef) {
2861
- return join2(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4620
+ return join4(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
2862
4621
  }
2863
4622
  };
2864
4623
  async function removeOwnerState(path, what) {
2865
4624
  try {
2866
- await unlink2(path);
4625
+ await unlink3(path);
2867
4626
  } catch (error) {
2868
4627
  if (!isNotFound(error)) throw storageError(`Unable to retire the Codex transcript ${what}.`);
2869
4628
  }
@@ -2894,7 +4653,7 @@ async function writeAtomicJson(path, value) {
2894
4653
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
2895
4654
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
2896
4655
  try {
2897
- const handle = await open3(temp, "wx");
4656
+ const handle = await open4(temp, "wx");
2898
4657
  try {
2899
4658
  await handle.writeFile(text, "utf8");
2900
4659
  await handle.sync();
@@ -2902,19 +4661,19 @@ async function writeAtomicJson(path, value) {
2902
4661
  await handle.close();
2903
4662
  }
2904
4663
  await rename2(temp, path);
2905
- await syncDirectory(dirname2(path));
4664
+ await syncDirectory2(dirname6(path));
2906
4665
  } catch (error) {
2907
4666
  try {
2908
- await unlink2(temp);
4667
+ await unlink3(temp);
2909
4668
  } catch {
2910
4669
  }
2911
4670
  if (error instanceof CodexHostAdapterError) throw error;
2912
4671
  throw storageError("Unable to atomically replace Codex owner state.");
2913
4672
  }
2914
4673
  }
2915
- async function syncDirectory(path) {
4674
+ async function syncDirectory2(path) {
2916
4675
  try {
2917
- const handle = await open3(path, "r");
4676
+ const handle = await open4(path, "r");
2918
4677
  try {
2919
4678
  await handle.sync();
2920
4679
  } finally {
@@ -2923,7 +4682,7 @@ async function syncDirectory(path) {
2923
4682
  } catch {
2924
4683
  }
2925
4684
  }
2926
- async function readOptionalJson(path, validate) {
4685
+ async function readOptionalJson2(path, validate) {
2927
4686
  try {
2928
4687
  const value = JSON.parse(await readOwnerStateFile(path));
2929
4688
  validate(value);
@@ -2936,18 +4695,18 @@ async function readOptionalJson(path, validate) {
2936
4695
  }
2937
4696
  async function ensureOwnerDirectory(path) {
2938
4697
  try {
2939
- await stat(path);
4698
+ await stat2(path);
2940
4699
  } catch (error) {
2941
4700
  if (!isNotFound(error)) throw storageError("Codex owner state directory is unavailable.");
2942
- await mkdir2(path, { recursive: true });
4701
+ await mkdir4(path, { recursive: true });
2943
4702
  }
2944
- const stats = await stat(path);
4703
+ const stats = await stat2(path);
2945
4704
  if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
2946
4705
  }
2947
4706
  async function readOwnerStateFile(path) {
2948
4707
  let handle;
2949
4708
  try {
2950
- handle = await open3(path);
4709
+ handle = await open4(path);
2951
4710
  const stats = await handle.stat();
2952
4711
  if (!stats.isFile()) throw storageError("Codex owner state path is not a regular file.");
2953
4712
  return await handle.readFile("utf8");
@@ -2956,8 +4715,8 @@ async function readOwnerStateFile(path) {
2956
4715
  }
2957
4716
  }
2958
4717
  function validateEnvelope(value) {
2959
- if (!isRecord5(value)) throw storageError("Codex outbox entry is malformed.");
2960
- 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")}).`);
4718
+ if (!isRecord6(value)) throw storageError("Codex outbox entry is malformed.");
4719
+ 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")}).`);
2961
4720
  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}`)}).`);
2962
4721
  validateIdentity2(value.identity);
2963
4722
  validateEnvelopeReferences(value);
@@ -2972,8 +4731,8 @@ function validateEnvelopeReferences(value) {
2972
4731
  if (typeof value.origin_input !== "boolean") throw storageError("Codex outbox origin disposition is malformed.");
2973
4732
  }
2974
4733
  function validateRegistration(value) {
2975
- if (!isRecord5(value)) throw storageError("Codex transcript registration is malformed.");
2976
- 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")}).`);
4734
+ if (!isRecord6(value)) throw storageError("Codex transcript registration is malformed.");
4735
+ 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")}).`);
2977
4736
  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}`)}).`);
2978
4737
  validateRegistrationFields(value);
2979
4738
  }
@@ -2985,16 +4744,31 @@ function validateRegistrationFields(value) {
2985
4744
  if (!isTimestamp(value.registered_at) || !isTimestamp(value.expires_at)) throw storageError(`Codex transcript registration timestamps are malformed (${refusalFacts([{ name: "registered_at", value: value.registered_at }, { name: "expires_at", value: value.expires_at }])}).`);
2986
4745
  }
2987
4746
  function validRegistrationCwd(value) {
2988
- return value === void 0 || typeof value === "string" && isAbsolute2(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
4747
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
2989
4748
  }
2990
4749
  function validateCursor(value) {
2991
- if (!isRecord5(value)) throw storageError("Codex transcript cursor is malformed.");
2992
- 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")}).`);
4750
+ if (!isRecord6(value)) throw storageError("Codex transcript cursor is malformed.");
4751
+ 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")}).`);
4752
+ validateCursorIdentityAndPosition(value);
4753
+ validateCursorOptionalFields(value);
4754
+ }
4755
+ function validateCursorIdentityAndPosition(value) {
2993
4756
  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}`)}).`);
2994
4757
  if (!validCursorSource(value) || !validCursorPosition(value) || !validCursorStatus(value)) throw storageError("Codex transcript cursor fields are malformed.");
4758
+ }
4759
+ function validateCursorOptionalFields(value) {
2995
4760
  if (value.active_task !== void 0 && !validActiveTask(value.active_task)) throw storageError("Codex transcript task cursor is malformed.");
4761
+ validateHumanMessageProjection(value.human_message_window);
2996
4762
  if (value.reason !== void 0 && !isHostTranscriptCursorReason(value.reason)) throw storageError("Codex transcript cursor reason is malformed.");
2997
4763
  }
4764
+ function validateHumanMessageProjection(value) {
4765
+ if (value === void 0) return;
4766
+ try {
4767
+ decodeCealHostInvocationHumanMessageWindow(value);
4768
+ } catch {
4769
+ throw storageError("Codex transcript human-message projection is malformed.");
4770
+ }
4771
+ }
2998
4772
  function validCursorSource(value) {
2999
4773
  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";
3000
4774
  }
@@ -3005,7 +4779,7 @@ function validCursorStatus(value) {
3005
4779
  return (value.status === "active" || value.status === "quarantined") && isTimestamp(value.updated_at);
3006
4780
  }
3007
4781
  function validActiveTask(value) {
3008
- 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;
4782
+ 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;
3009
4783
  return validActiveTaskIdentity(value) && validActiveTaskReferences(value) && validActiveTaskUsage(value);
3010
4784
  }
3011
4785
  function validActiveTaskIdentity(value) {
@@ -3021,7 +4795,7 @@ function validActiveTaskUsage(value) {
3021
4795
  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");
3022
4796
  }
3023
4797
  function validTokenUsage(value) {
3024
- if (!isRecord5(value) || !sameKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) return false;
4798
+ if (!isRecord6(value) || !sameKeys2(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) return false;
3025
4799
  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;
3026
4800
  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);
3027
4801
  }
@@ -3041,8 +4815,8 @@ function validateEnvelopeTimestamps(value) {
3041
4815
  if (!isTimestamp(value.expires_at)) throw storageError("Codex outbox timestamps are malformed.");
3042
4816
  }
3043
4817
  function validateSession(value) {
3044
- if (!isRecord5(value)) throw storageError("Codex session snapshot is malformed.");
3045
- 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")}).`);
4818
+ if (!isRecord6(value)) throw storageError("Codex session snapshot is malformed.");
4819
+ 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")}).`);
3046
4820
  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}`)}).`);
3047
4821
  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.");
3048
4822
  }
@@ -3050,35 +4824,35 @@ function validateTurnSelection(value) {
3050
4824
  if (!isHostInvocationTurnSelection(value)) throw storageError("Codex Host turn selection is malformed.");
3051
4825
  }
3052
4826
  function validateIdentity2(value) {
3053
- 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.");
4827
+ 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.");
3054
4828
  }
3055
4829
  function isJsonValue(value) {
3056
4830
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
3057
4831
  if (typeof value === "number") return Number.isFinite(value);
3058
4832
  if (Array.isArray(value)) return value.every(isJsonValue);
3059
- return isRecord5(value) && Object.entries(value).every(([key, child]) => key.length > 0 && key.length <= 128 && isJsonValue(child));
4833
+ return isRecord6(value) && Object.entries(value).every(([key, child]) => key.length > 0 && key.length <= 128 && isJsonValue(child));
3060
4834
  }
3061
4835
  function isTimestamp(value) {
3062
4836
  return typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value));
3063
4837
  }
3064
- function sameKeys(value, required, optional = []) {
4838
+ function sameKeys2(value, required, optional = []) {
3065
4839
  const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
3066
4840
  const keys = Object.keys(value);
3067
4841
  return keys.length >= required.length && keys.length <= allowed.size && required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => allowed.has(key));
3068
4842
  }
3069
- function isRecord5(value) {
4843
+ function isRecord6(value) {
3070
4844
  return value !== null && typeof value === "object" && !Array.isArray(value);
3071
4845
  }
3072
4846
  function isNotFound(error) {
3073
- return isRecord5(error) && error.code === "ENOENT";
4847
+ return isRecord6(error) && error.code === "ENOENT";
3074
4848
  }
3075
4849
  function storageError(message) {
3076
4850
  return new CodexHostAdapterError("storage", message);
3077
4851
  }
3078
4852
 
3079
4853
  // host/codex/src/codex-transcript-baseline.ts
3080
- import { createHash as createHash5 } from "node:crypto";
3081
- import { constants as constants2 } from "node:fs";
4854
+ import { createHash as createHash8 } from "node:crypto";
4855
+ import { constants as constants5 } from "node:fs";
3082
4856
 
3083
4857
  // host/codex/src/codex-transcript-decoder.ts
3084
4858
  var SAFE_REF4 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
@@ -3090,16 +4864,32 @@ function decodeCodexTranscriptLine(line) {
3090
4864
  } catch {
3091
4865
  reject2("Codex transcript record is not valid JSON.");
3092
4866
  }
3093
- if (!isRecord6(value)) reject2("Codex transcript record envelope is malformed.");
4867
+ if (!isRecord7(value)) reject2("Codex transcript record envelope is malformed.");
3094
4868
  const ordinal = safeOrdinal(value.ordinal);
3095
4869
  const timestamp4 = safeTimestamp(value.timestamp);
3096
- if (!isRecord6(value.payload) || typeof value.type !== "string") reject2("Codex transcript record payload is malformed.");
4870
+ if (!isRecord7(value.payload) || typeof value.type !== "string") reject2("Codex transcript record payload is malformed.");
3097
4871
  if (value.type === "session_meta") return decodeSessionMeta(value.payload, ordinal, timestamp4);
3098
4872
  if (value.type === "turn_context") return decodeTurnContext(value.payload, ordinal, timestamp4);
3099
4873
  if (value.type === "event_msg") return decodeEventMessage(value.payload, ordinal, timestamp4);
3100
4874
  if (value.type === "response_item") return decodeResponseItem(value.payload, ordinal, timestamp4);
3101
4875
  return { kind: "ignored", ordinal, timestamp: timestamp4 };
3102
4876
  }
4877
+ function decodeCodexUsageTranscriptLine(line) {
4878
+ let value;
4879
+ try {
4880
+ value = JSON.parse(line);
4881
+ } catch {
4882
+ reject2("Codex transcript record is not valid JSON.");
4883
+ }
4884
+ if (!isRecord7(value)) reject2("Codex transcript record envelope is malformed.");
4885
+ const ordinal = safeOrdinal(value.ordinal);
4886
+ const timestamp4 = safeTimestamp(value.timestamp);
4887
+ if (!isRecord7(value.payload) || typeof value.type !== "string") reject2("Codex transcript record payload is malformed.");
4888
+ if (value.type === "session_meta") return decodeSessionMeta(value.payload, ordinal, timestamp4);
4889
+ if (value.type === "turn_context") return decodeTurnContext(value.payload, ordinal, timestamp4);
4890
+ if (value.type === "event_msg" && ["task_started", "task_complete", "turn_aborted", "token_count"].includes(String(value.payload.type))) return decodeEventMessage(value.payload, ordinal, timestamp4);
4891
+ return { kind: "ignored", ordinal, timestamp: timestamp4 };
4892
+ }
3103
4893
  function decodeTurnContext(payload, ordinal, timestamp4) {
3104
4894
  return {
3105
4895
  kind: "turn_context",
@@ -3139,7 +4929,7 @@ function decodeEventMessage(payload, ordinal, timestamp4) {
3139
4929
  started_at: safeNumber(payload.started_at),
3140
4930
  completed_at: safeNumber(payload.completed_at),
3141
4931
  duration_ms: safeNumber(payload.duration_ms),
3142
- reason: boundedText(payload.reason, 256, "Codex task abort reason is invalid.")
4932
+ reason: boundedText2(payload.reason, 256, "Codex task abort reason is invalid.")
3143
4933
  };
3144
4934
  }
3145
4935
  if (payload.type === "token_count") return decodeTokenCount(payload, ordinal, timestamp4);
@@ -3147,7 +4937,7 @@ function decodeEventMessage(payload, ordinal, timestamp4) {
3147
4937
  }
3148
4938
  function decodeTokenCount(payload, ordinal, timestamp4) {
3149
4939
  if (payload.info === null) return { kind: "token_count", ordinal, timestamp: timestamp4 };
3150
- if (!isRecord6(payload.info)) return { kind: "token_count", ordinal, timestamp: timestamp4, usage_gap_reason: "token_count_shape_not_attributable" };
4940
+ if (!isRecord7(payload.info)) return { kind: "token_count", ordinal, timestamp: timestamp4, usage_gap_reason: "token_count_shape_not_attributable" };
3151
4941
  const lastUsage = optionalTokenUsage(payload.info.last_token_usage);
3152
4942
  const totalUsage = optionalTokenUsage(payload.info.total_token_usage);
3153
4943
  const gap = lastUsage.status === "invalid" || totalUsage.status === "invalid";
@@ -3171,7 +4961,7 @@ function optionalTokenUsage(value) {
3171
4961
  }
3172
4962
  }
3173
4963
  function decodeTokenUsage(value) {
3174
- if (!isRecord6(value)) reject2("Codex token usage is malformed.");
4964
+ if (!isRecord7(value)) reject2("Codex token usage is malformed.");
3175
4965
  const usage = {
3176
4966
  input_tokens: safeTokenCount(value.input_tokens),
3177
4967
  cached_input_tokens: safeTokenCount(value.cached_input_tokens),
@@ -3203,14 +4993,14 @@ function userTextContentKind(kinds) {
3203
4993
  return kinds.length === 1 && (kinds[0] === "user.text" || kinds[0] === "goal.internal_context") ? kinds[0] : void 0;
3204
4994
  }
3205
4995
  function userMessageMetadata(value) {
3206
- if (!isRecord6(value) || !Array.isArray(value.content_item_kinds)) reject2("Codex user message provenance is malformed.");
4996
+ if (!isRecord7(value) || !Array.isArray(value.content_item_kinds)) reject2("Codex user message provenance is malformed.");
3207
4997
  return { ...value, content_item_kinds: value.content_item_kinds };
3208
4998
  }
3209
4999
  function userTextContent(value) {
3210
5000
  if (!Array.isArray(value)) reject2(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
3211
5001
  if (value.length !== 1) reject2(`Codex user text content is malformed (${refusalFact("items", value.length, "exactly one")}).`);
3212
- if (!isRecord6(value[0]) || value[0].type !== "input_text") reject2(`Codex user text content is malformed (${refusalFact("item_type", isRecord6(value[0]) ? value[0].type : typeof value[0], "input_text")}).`);
3213
- return boundedText(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
5002
+ if (!isRecord7(value[0]) || value[0].type !== "input_text") reject2(`Codex user text content is malformed (${refusalFact("item_type", isRecord7(value[0]) ? value[0].type : typeof value[0], "input_text")}).`);
5003
+ return boundedText2(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
3214
5004
  }
3215
5005
  function safeOrdinal(value) {
3216
5006
  if (!Number.isSafeInteger(value) || Number(value) < 0) reject2("Codex transcript ordinal is invalid.");
@@ -3234,18 +5024,18 @@ function safeRef3(value, message) {
3234
5024
  if (typeof value !== "string" || !SAFE_REF4.test(value)) reject2(message);
3235
5025
  return value;
3236
5026
  }
3237
- function boundedText(value, maximum, message) {
5027
+ function boundedText2(value, maximum, message) {
3238
5028
  if (typeof value !== "string") reject2(`${message} ${refusalFact("kind", typeof value, "string")}.`);
3239
5029
  const bytes = Buffer.byteLength(value, "utf8");
3240
5030
  if (bytes > maximum) reject2(`${message} ${refusalFact("bytes", bytes, `at most ${maximum} UTF-8 bytes`)}.`);
3241
5031
  return value;
3242
5032
  }
3243
5033
  function boundedNonEmptyText(value, maximum, message) {
3244
- const result = boundedText(value, maximum, message);
5034
+ const result = boundedText2(value, maximum, message);
3245
5035
  if (result.length === 0) reject2(message);
3246
5036
  return result;
3247
5037
  }
3248
- function isRecord6(value) {
5038
+ function isRecord7(value) {
3249
5039
  return value !== null && typeof value === "object" && !Array.isArray(value);
3250
5040
  }
3251
5041
  function reject2(message) {
@@ -3258,7 +5048,7 @@ var CODEX_TRANSCRIPT_ANCHOR_BYTES = 256;
3258
5048
  async function captureCodexTranscriptBaseline(registration, now = () => /* @__PURE__ */ new Date(), platform = process.platform, custody = {}) {
3259
5049
  let handle;
3260
5050
  try {
3261
- handle = await openNoFollow(registration.transcript_path, constants2.O_RDONLY, void 0, platform, custody);
5051
+ handle = await openNoFollow(registration.transcript_path, constants5.O_RDONLY, void 0, platform, custody);
3262
5052
  const { size, device, inode } = await ownedCodexTranscriptFile(handle, platform);
3263
5053
  const empty = codexTranscriptInitialCursor(registration, device, inode, now);
3264
5054
  const headerLine = await firstCompleteLine(handle, size);
@@ -3278,6 +5068,7 @@ async function captureCodexTranscriptBaseline(registration, now = () => /* @__PU
3278
5068
  anchor_start: anchorStart,
3279
5069
  anchor_sha256: digest(anchor),
3280
5070
  header_validated: true,
5071
+ human_message_window: { messages: [], truncated: offset > 0 },
3281
5072
  updated_at: timestamp2(now)
3282
5073
  };
3283
5074
  } finally {
@@ -3297,6 +5088,7 @@ function codexTranscriptInitialCursor(registration, device, inode, now) {
3297
5088
  anchor_start: 0,
3298
5089
  anchor_sha256: digest(Buffer.alloc(0)),
3299
5090
  header_validated: false,
5091
+ human_message_window: { messages: [], truncated: false },
3300
5092
  status: "active",
3301
5093
  updated_at: timestamp2(now)
3302
5094
  };
@@ -3307,10 +5099,10 @@ async function ownedCodexTranscriptFile(handle, platform = process.platform) {
3307
5099
  if (platform !== "win32" && !isSelfOwned(stats.uid, platform, handle)) throw new CodexHostAdapterError("storage", "Codex transcript source is owned by another user.");
3308
5100
  return { size: stats.size, device: String(stats.dev), inode: String(stats.ino) };
3309
5101
  }
3310
- function assertCodexTranscriptHeader(registration, record) {
3311
- 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([
3312
- { name: "kind", value: record.kind, expected: "session_meta" },
3313
- { name: "session_id", value: record.kind === "session_meta" ? record.session_id : "unavailable", expected: registration.codex_session_id }
5102
+ function assertCodexTranscriptHeader(registration, record2) {
5103
+ 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([
5104
+ { name: "kind", value: record2.kind, expected: "session_meta" },
5105
+ { name: "session_id", value: record2.kind === "session_meta" ? record2.session_id : "unavailable", expected: registration.codex_session_id }
3314
5106
  ])}).`);
3315
5107
  }
3316
5108
  async function firstCompleteLine(handle, size) {
@@ -3396,7 +5188,7 @@ async function* completeLinesBackward(handle, end) {
3396
5188
  yield { start: 0, bytes: Buffer.concat(carry) };
3397
5189
  }
3398
5190
  function digest(value) {
3399
- return createHash5("sha256").update(value).digest("hex");
5191
+ return createHash8("sha256").update(value).digest("hex");
3400
5192
  }
3401
5193
  function timestamp2(now) {
3402
5194
  const value = now();
@@ -3405,15 +5197,15 @@ function timestamp2(now) {
3405
5197
  }
3406
5198
 
3407
5199
  // host/codex/src/codex-runtime-paths.ts
3408
- import { join as join3 } from "node:path";
5200
+ import { join as join5 } from "node:path";
3409
5201
  var CODEX_HOME_ENVIRONMENT = "CODEX_HOME";
3410
5202
  var CODEX_HOME_DEFAULT_DIRECTORY = ".codex";
3411
5203
  var CODEX_SESSIONS_DIRECTORY = "sessions";
3412
5204
  function resolveCodexHome(environment, home) {
3413
- return environment[CODEX_HOME_ENVIRONMENT] || join3(home, CODEX_HOME_DEFAULT_DIRECTORY);
5205
+ return environment[CODEX_HOME_ENVIRONMENT] || join5(home, CODEX_HOME_DEFAULT_DIRECTORY);
3414
5206
  }
3415
5207
  function resolveCodexSessionsRoot(environment, home) {
3416
- return join3(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
5208
+ return join5(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
3417
5209
  }
3418
5210
 
3419
5211
  // host/codex/src/codex-adapter.ts
@@ -3435,7 +5227,7 @@ function createCodexHostObservationAdapter(options) {
3435
5227
  }
3436
5228
  async function registerSession(event, options, store, now, retentionMs) {
3437
5229
  const defaultRoot = resolveCodexSessionsRoot(process.env, homedir());
3438
- const transcriptPath = sourceBoundTranscriptPath(event.transcript_path, options.codex_sessions_root ?? defaultRoot);
5230
+ const transcriptPath = await sourceBoundTranscriptPath(event.transcript_path, options.codex_sessions_root ?? defaultRoot);
3439
5231
  const hostSessionRef = hostSessionReference(options.host_source_ref, event.session_id);
3440
5232
  const observedAt = timestamp3(now);
3441
5233
  const expiresAt = new Date(Date.parse(observedAt) + retentionMs).toISOString();
@@ -3503,15 +5295,20 @@ async function liveSteeredTurn(options, store, hostSessionRef, hostTurnRef) {
3503
5295
  if (selection === null || selection.prompt_ref !== live.prompt_ref || selection.turn_generation_ref !== live.turn_generation_ref) return void 0;
3504
5296
  return { host_turn_ref: hostTurnRef, prompt_ref: selection.prompt_ref, turn_generation_ref: selection.turn_generation_ref };
3505
5297
  }
3506
- function sourceBoundTranscriptPath(path, sessionsRoot) {
3507
- if (!isAbsolute3(path) || !isAbsolute3(sessionsRoot)) throw new CodexHostAdapterError("configuration", "Codex transcript registration paths must be absolute.");
5298
+ async function sourceBoundTranscriptPath(path, sessionsRoot) {
5299
+ if (!isAbsolute4(path) || !isAbsolute4(sessionsRoot)) throw new CodexHostAdapterError("configuration", "Codex transcript registration paths must be absolute.");
3508
5300
  const transcript = resolve2(path);
3509
5301
  const root = resolve2(sessionsRoot);
5302
+ assertTranscriptChild(root, transcript);
5303
+ const [physicalRoot, physicalTranscript] = await Promise.all([realpath(root), realpath(transcript)]);
5304
+ assertTranscriptChild(physicalRoot, physicalTranscript);
5305
+ return transcript;
5306
+ }
5307
+ function assertTranscriptChild(root, transcript) {
3510
5308
  const child = relative(root, transcript);
3511
- if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute3(child)) {
5309
+ if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute4(child)) {
3512
5310
  throw new CodexHostAdapterError("payload_rejected", "Codex transcript path is outside the configured sessions root.");
3513
5311
  }
3514
- return transcript;
3515
5312
  }
3516
5313
  function codexSubmissionReference(hostInputRef, event, ordinal) {
3517
5314
  if (!SAFE_REF5.test(hostInputRef) || !Number.isSafeInteger(ordinal) || ordinal < 0) throw new CodexHostAdapterError("invalid_input", "Codex submission identity is invalid.");
@@ -3523,7 +5320,7 @@ function timestamp3(now) {
3523
5320
  return value.toISOString();
3524
5321
  }
3525
5322
  function validateOptions(options) {
3526
- if (!isRecord7(options)) throw new CodexHostAdapterError("configuration", "Codex adapter options are invalid.");
5323
+ if (!isRecord8(options)) throw new CodexHostAdapterError("configuration", "Codex adapter options are invalid.");
3527
5324
  validateAdapterOwner(options);
3528
5325
  validateAdapterBehavior(options);
3529
5326
  }
@@ -3531,7 +5328,7 @@ function validateAdapterOwner(options) {
3531
5328
  if (!SAFE_REF5.test(options.host_source_ref) || options.outbox_dir.length === 0) {
3532
5329
  throw new CodexHostAdapterError("configuration", "Codex adapter options are invalid.");
3533
5330
  }
3534
- if (options.codex_sessions_root !== void 0 && !isAbsolute3(options.codex_sessions_root)) throw new CodexHostAdapterError("configuration", "Codex sessions root is invalid.");
5331
+ if (options.codex_sessions_root !== void 0 && !isAbsolute4(options.codex_sessions_root)) throw new CodexHostAdapterError("configuration", "Codex sessions root is invalid.");
3535
5332
  }
3536
5333
  function validateAdapterBehavior(options) {
3537
5334
  if (options.retention_ms !== void 0 && (!Number.isSafeInteger(options.retention_ms) || options.retention_ms < 1)) throw new CodexHostAdapterError("configuration", `Codex retention is invalid (${refusalFact("retention_ms", options.retention_ms, "a positive integer")}).`);
@@ -3539,47 +5336,13 @@ function validateAdapterBehavior(options) {
3539
5336
  function safeReason(error) {
3540
5337
  return error instanceof CodexHostAdapterError ? error.message.slice(0, 128) : "codex_session_registration_rejected";
3541
5338
  }
3542
- function isRecord7(value) {
5339
+ function isRecord8(value) {
3543
5340
  return value !== null && typeof value === "object" && !Array.isArray(value);
3544
5341
  }
3545
5342
 
3546
5343
  // host/producer-service.ts
3547
- import { posix as posix3, win32 as win324 } from "node:path";
3548
-
3549
- // host/runtime-source-paths.ts
3550
- import { createHash as createHash6 } from "node:crypto";
3551
- import { posix as posix2, win32 as win323 } from "node:path";
3552
-
3553
- // host/absolute-path.ts
3554
- import { posix, win32 as win322 } from "node:path";
3555
- function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
3556
- const pathApi = flavor === "win32" || flavor === "windows" ? win322 : posix;
3557
- return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
3558
- }
3559
-
3560
- // host/runtime-source-paths.ts
3561
- var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
3562
- function hostSourceUuid(sourceRef) {
3563
- return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
3564
- }
3565
- function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform) {
3566
- const sourceId = hostSourceUuid(sourceRef);
3567
- if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
3568
- const path = platform === "win32" ? win323 : posix2;
3569
- const sourcesRoot = path.join(stateRoot, "sources");
3570
- const sourceRoot = path.join(sourcesRoot, sourceId);
3571
- const runtimeRoot = path.join(stateRoot, "run");
3572
- const endpoint = platform === "win32" ? `\\\\.\\pipe\\ceal-host-${createHash6("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex").slice(0, 24)}` : path.join(runtimeRoot, `${sourceId}.sock`);
3573
- 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 };
3574
- }
3575
- function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
3576
- const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
3577
- 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.");
3578
- return paths.endpoint;
3579
- }
3580
-
3581
- // host/producer-service.ts
3582
- import { constants as constants3 } from "node:fs";
5344
+ import { posix as posix4, win32 as win325 } from "node:path";
5345
+ import { constants as constants6 } from "node:fs";
3583
5346
  import { lstat as lstat3 } from "node:fs/promises";
3584
5347
  var SAFE_REF6 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
3585
5348
  var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
@@ -3604,8 +5367,9 @@ function parseHostProducerConfigFlag(args, platform = process.platform) {
3604
5367
  }
3605
5368
  async function readHostProducerConfig(descriptor, configPath, platform = process.platform, custody = {}) {
3606
5369
  const config = decodeHostProducerConfigText(descriptor, await readProducerConfigText(configPath, platform, hostProducerError, custody), platform);
3607
- const path = platform === "win32" ? win324 : posix3;
3608
- const root = path.resolve(config.outbox_dir, "../../../../..");
5370
+ const path = platform === "win32" ? win325 : posix4;
5371
+ const registrationStateFile = hostProducerRegistrationStateFile(config.outbox_dir, platform);
5372
+ const root = path.dirname(registrationStateFile);
3609
5373
  try {
3610
5374
  assertHostProducerSourcePaths(root, config, descriptor.producer_id, platform);
3611
5375
  } catch (error) {
@@ -3619,6 +5383,10 @@ function decodeHostProducerConfigText(descriptor, text, platform = process.platf
3619
5383
  const { extra_paths: extras, ...core } = decoded;
3620
5384
  return Object.freeze(descriptor.config({ schema_version: descriptor.schema, ...core }, extras));
3621
5385
  }
5386
+ function hostProducerRegistrationStateFile(outboxDirectory, platform = process.platform) {
5387
+ const path = platform === "win32" ? win325 : posix4;
5388
+ return path.join(path.resolve(outboxDirectory, "../../../../.."), "registration.json");
5389
+ }
3622
5390
  function hostProducerError(code, message = code) {
3623
5391
  return new HostProducerServiceError(code, message);
3624
5392
  }
@@ -3664,7 +5432,7 @@ async function readProducerConfigText(configPath, platform, error, custody) {
3664
5432
  function decodeProducerConfigCore(text, options) {
3665
5433
  const ownership = producerConfigKeyOwnership(options.keys, options.platform);
3666
5434
  const value = parseCanonicalJson(text, options.error);
3667
- if (!isRecord8(value) || !hasConfigKeys(value, ownership.required, ownership.tolerated) || value.schema_version !== options.schema) throw options.error("invalid_config", refusalFacts(producerShapeFacts(value, { schema: options.schema, keys: ownership.required, tolerated: ownership.tolerated })));
5435
+ if (!isRecord9(value) || !hasConfigKeys(value, ownership.required, ownership.tolerated) || value.schema_version !== options.schema) throw options.error("invalid_config", refusalFacts(producerShapeFacts(value, { schema: options.schema, keys: ownership.required, tolerated: ownership.tolerated })));
3668
5436
  const hostSourceRef = typeof value.host_source_ref === "string" ? value.host_source_ref : "";
3669
5437
  const installationRef = typeof value.producer_installation_ref === "string" ? value.producer_installation_ref : "";
3670
5438
  const producerEpoch = validateIdentity3(hostSourceRef, installationRef, value.producer_epoch, options.error);
@@ -3716,7 +5484,7 @@ function validateConfigFile(value, platform, error, handle) {
3716
5484
  }
3717
5485
  async function openConfigFile(configPath, platform, error, custody) {
3718
5486
  try {
3719
- return await openNoFollow(configPath, constants3.O_RDONLY, void 0, platform, custody);
5487
+ return await openNoFollow(configPath, constants6.O_RDONLY, void 0, platform, custody);
3720
5488
  } catch (error_) {
3721
5489
  if (error_ instanceof SecureFileCustodyError) throw error(error_.reason === "not_private" ? "config_not_private" : "invalid_config");
3722
5490
  throw error("config_unavailable");
@@ -3757,7 +5525,7 @@ function firstDifferenceIndex(left, right) {
3757
5525
  return shared;
3758
5526
  }
3759
5527
  function producerShapeFacts(value, options) {
3760
- if (!isRecord8(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
5528
+ if (!isRecord9(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
3761
5529
  const tolerated = options.tolerated ?? [];
3762
5530
  const allowed = [...options.keys, ...tolerated, ...Object.keys(HOST_PRODUCER_TIMING_DEFAULTS)];
3763
5531
  const facts = [
@@ -3792,7 +5560,7 @@ function producerIntervalFacts(reconcile, retry, timeout) {
3792
5560
  function hasConfigKeys(value, required, tolerated = []) {
3793
5561
  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));
3794
5562
  }
3795
- function isRecord8(value) {
5563
+ function isRecord9(value) {
3796
5564
  return value !== null && typeof value === "object" && !Array.isArray(value);
3797
5565
  }
3798
5566
  function positive(value, maximum) {
@@ -3802,48 +5570,6 @@ function boundedMilliseconds(value) {
3802
5570
  return positive(value, 6e4) && Number(value) >= 25;
3803
5571
  }
3804
5572
 
3805
- // host/service-log.ts
3806
- import { copyFile, mkdir as mkdir3, stat as stat2, truncate, appendFile } from "node:fs/promises";
3807
- import { dirname as dirname3, isAbsolute as isAbsolute4, posix as posix4, win32 as win325 } from "node:path";
3808
- var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
3809
- function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
3810
- 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 } : {} })}
3811
- `;
3812
- try {
3813
- (sink ?? defaultHostServiceDiagnosticSink)(line);
3814
- } catch {
3815
- }
3816
- }
3817
- function defaultHostServiceDiagnosticSink(line) {
3818
- writeHostServiceLogLine(line);
3819
- process.stderr.write(line);
3820
- }
3821
- var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
3822
- function writeHostServiceLogLine(line, environment = process.env) {
3823
- if (process.platform !== "win32") return;
3824
- const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
3825
- if (path === void 0 || !win325.isAbsolute(path) || win325.normalize(path) !== path) return;
3826
- void appendHostServiceLogLine(path, line).catch(() => void 0);
3827
- }
3828
- async function appendHostServiceLogLine(path, line) {
3829
- if (!isAbsolute4(path)) return;
3830
- await ensureHostServiceLogDirectory(path);
3831
- await appendFile(path, line);
3832
- }
3833
- var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
3834
- var hostServiceLogDirectories = /* @__PURE__ */ new Map();
3835
- function ensureHostServiceLogDirectory(path) {
3836
- const directory = dirname3(path);
3837
- const existing = hostServiceLogDirectories.get(directory);
3838
- if (existing !== void 0) return existing;
3839
- const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
3840
- hostServiceLogDirectories.delete(directory);
3841
- throw error;
3842
- });
3843
- hostServiceLogDirectories.set(directory, pending);
3844
- return pending;
3845
- }
3846
-
3847
5573
  // host/codex/src/codex-producer.ts
3848
5574
  var CodexProducer = class {
3849
5575
  store;
@@ -3889,8 +5615,11 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3889
5615
  const { size, device, inode } = await ownedCodexTranscriptFile(handle);
3890
5616
  const preflight = await this.preflight(registration, handle, size, device, inode);
3891
5617
  if (preflight.cursor === null) return preflight.result;
5618
+ if (preflight.checkpointPending) 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 });
3892
5619
  const complete = await this.readChunk(handle, preflight.cursor.offset, size);
3893
- if (complete === "empty" || complete === "partial") return { records: 0, enqueued: 0, quarantined: false };
5620
+ if (complete === "empty" || complete === "partial") {
5621
+ return { records: 0, enqueued: 0, quarantined: false };
5622
+ }
3894
5623
  return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
3895
5624
  }
3896
5625
  async scanFailed(handle, registration, error) {
@@ -3905,40 +5634,51 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3905
5634
  const existing = await this.store.readTranscriptCursor(registration);
3906
5635
  let cursor = existing ?? codexTranscriptInitialCursor(registration, device, inode, this.now);
3907
5636
  if (cursor.status === "quarantined") {
3908
- return { cursor: null, result: { records: 0, enqueued: 0, quarantined: true } };
5637
+ return { cursor: null, checkpointPending: false, result: { records: 0, enqueued: 0, quarantined: true } };
3909
5638
  }
3910
5639
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
3911
- if (reason === null) return { cursor, result: { records: 0, enqueued: 0, quarantined: false } };
5640
+ if (reason === null) {
5641
+ if (cursor.human_message_window !== void 0) return { cursor, checkpointPending: existing === null, result: { records: 0, enqueued: 0, quarantined: false } };
5642
+ const humanWindow = await this.readHumanMessageProjection(handle, registration, cursor);
5643
+ return { cursor: { ...cursor, human_message_window: humanWindow }, checkpointPending: true, result: { records: 0, enqueued: 0, quarantined: false } };
5644
+ }
3912
5645
  await this.quarantine(registration, cursor, device, inode, reason);
3913
- return { cursor: null, result: { records: 0, enqueued: 0, quarantined: true } };
5646
+ this.diagnostic("watcher_scan_failed", "other", `cursor_${reason}`);
5647
+ return { cursor: null, checkpointPending: false, result: { records: 0, enqueued: 0, quarantined: true } };
5648
+ }
5649
+ async readHumanMessageProjection(handle, registration, cursor) {
5650
+ return readCodexHumanMessageProjection(registration, cursor, (offset, size) => this.readChunk(handle, offset, size));
3914
5651
  }
3915
5652
  async consumeCompleteChunk(registration, handle, cursor, complete, device, inode) {
3916
5653
  let activeTask = cursor.active_task;
3917
5654
  let lastOrdinal = cursor.last_ordinal;
5655
+ let humanWindow = cursor.human_message_window ?? { messages: [], truncated: false };
3918
5656
  let records = 0;
3919
5657
  let enqueued = 0;
3920
5658
  for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3921
- const record = decodeCodexTranscriptLine(line);
3922
- assertRecordSequence(registration, cursor, records, lastOrdinal, record);
3923
- await this.observeSessionMetadata(registration, record);
3924
- const outcome = await this.processRecord(registration, activeTask, record);
5659
+ const record2 = decodeCodexTranscriptLine(line);
5660
+ assertRecordSequence(registration, cursor, records, lastOrdinal, record2);
5661
+ const message = codexHumanMessage(registration, record2);
5662
+ if (message !== null) humanWindow = mergeHostInvocationHumanMessageWindow(humanWindow, [message]);
5663
+ await this.observeSessionMetadata(registration, record2);
5664
+ const outcome = await this.processRecord(registration, activeTask, record2);
3925
5665
  activeTask = outcome.activeTask;
3926
5666
  enqueued += outcome.enqueued;
3927
- lastOrdinal = record.ordinal;
5667
+ lastOrdinal = record2.ordinal;
3928
5668
  records += 1;
3929
5669
  }
3930
- await this.commitCursor(registration, handle, cursor, complete.length, device, inode, lastOrdinal, activeTask);
5670
+ await this.commitCursor(registration, handle, cursor, complete.length, device, inode, lastOrdinal, activeTask, humanWindow);
3931
5671
  return { records, enqueued, quarantined: false };
3932
5672
  }
3933
- async observeSessionMetadata(registration, record) {
3934
- if (record.kind !== "session_meta") return;
5673
+ async observeSessionMetadata(registration, record2) {
5674
+ if (record2.kind !== "session_meta") return;
3935
5675
  const session = await this.store.readSession(registration.host_source_ref, registration.host_session_ref);
3936
- if (session !== null && this.isRecord(session.value)) await this.store.saveSession({ ...session, value: { ...session.value, host_version: record.cli_version } });
5676
+ if (session !== null && this.isRecord(session.value)) await this.store.saveSession({ ...session, value: { ...session.value, host_version: record2.cli_version } });
3937
5677
  }
3938
- async commitCursor(registration, handle, cursor, consumedBytes, device, inode, lastOrdinal, activeTask) {
5678
+ async commitCursor(registration, handle, cursor, consumedBytes, device, inode, lastOrdinal, activeTask, humanWindow) {
3939
5679
  const offset = cursor.offset + consumedBytes;
3940
5680
  const anchor = await this.readAnchor(handle, offset, CODEX_TRANSCRIPT_ANCHOR_BYTES);
3941
- 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() });
5681
+ 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() });
3942
5682
  }
3943
5683
  async quarantineFailure(registration, handle) {
3944
5684
  if (handle === void 0) return;
@@ -3956,40 +5696,40 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3956
5696
  };
3957
5697
  await this.store.writeTranscriptCursor(quarantined);
3958
5698
  }
3959
- async processRecord(registration, activeTask, record) {
3960
- if (record.kind === "task_started") return this.processTaskStarted(registration, record);
3961
- if (record.kind === "turn_context") return { ...activeTask === void 0 ? {} : { activeTask: record.turn_id === activeTask.codex_turn_id ? { ...activeTask, model: record.model } : activeTask }, enqueued: 0 };
3962
- if (record.kind === "token_count") return { ...activeTask === void 0 ? {} : { activeTask: accumulateTokenCount(activeTask, record) }, enqueued: 0 };
3963
- if (record.kind === "user_text") return this.processUserInput(registration, activeTask, record);
3964
- if (record.kind === "task_complete" || record.kind === "turn_aborted") return this.processTerminal(registration, activeTask, record);
5699
+ async processRecord(registration, activeTask, record2) {
5700
+ if (record2.kind === "task_started") return this.processTaskStarted(registration, record2);
5701
+ if (record2.kind === "turn_context") return { ...activeTask === void 0 ? {} : { activeTask: record2.turn_id === activeTask.codex_turn_id ? { ...activeTask, model: record2.model } : activeTask }, enqueued: 0 };
5702
+ if (record2.kind === "token_count") return { ...activeTask === void 0 ? {} : { activeTask: accumulateTokenCount(activeTask, record2) }, enqueued: 0 };
5703
+ if (record2.kind === "user_text") return this.processUserInput(registration, activeTask, record2);
5704
+ if (record2.kind === "task_complete" || record2.kind === "turn_aborted") return this.processTerminal(registration, activeTask, record2);
3965
5705
  return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
3966
5706
  }
3967
- async processTaskStarted(registration, record) {
3968
- 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 };
5707
+ async processTaskStarted(registration, record2) {
5708
+ 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 };
3969
5709
  }
3970
- async processUserInput(registration, activeTask, record) {
3971
- if (activeTask === void 0 || activeTask.codex_turn_id !== record.turn_id) {
3972
- const adopted = await this.adoptHookCorrelatedTurn(registration, record);
5710
+ async processUserInput(registration, activeTask, record2) {
5711
+ if (activeTask === void 0 || activeTask.codex_turn_id !== record2.turn_id) {
5712
+ const adopted = await this.adoptHookCorrelatedTurn(registration, record2);
3973
5713
  if (adopted === void 0) return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
3974
5714
  activeTask = adopted;
3975
5715
  }
3976
- const hostInputRef = hostInputReference(registration.host_source_ref, registration.host_session_ref, record.turn_id, record.message_id, record.ordinal, record.prompt);
5716
+ const hostInputRef = hostInputReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id, record2.message_id, record2.ordinal, record2.prompt);
3977
5717
  const origin = activeTask.origin_host_input_ref === void 0;
3978
- const promptValue = promptObservationValue(record.prompt);
5718
+ const promptValue = promptObservationValue(record2.prompt);
3979
5719
  const currentPromptRef = hostProducerPromptRef(promptValue.body_sha256);
3980
5720
  const promptRef = activeTask.prompt_ref ?? currentPromptRef;
3981
5721
  const steeredPromptRef = await this.steeredPromptRef(registration, activeTask, origin, currentPromptRef);
3982
5722
  const identity = { host_source_ref: registration.host_source_ref, host_session_ref: registration.host_session_ref, host_turn_ref: activeTask.host_turn_ref };
3983
5723
  const observations = [{
3984
- observation_ref: observationRef(registration.host_source_ref, "transcript_user_text", hostInputRef, record.prompt),
5724
+ observation_ref: observationRef(registration.host_source_ref, "transcript_user_text", hostInputRef, record2.prompt),
3985
5725
  observation_kind: "prompt",
3986
- observed_at: record.timestamp,
5726
+ observed_at: record2.timestamp,
3987
5727
  value: promptValue
3988
5728
  }];
3989
5729
  if (origin) {
3990
- 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") });
5730
+ 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") });
3991
5731
  const session = await this.store.readSession(registration.host_source_ref, registration.host_session_ref);
3992
- 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 });
5732
+ 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 });
3993
5733
  }
3994
5734
  const envelope = {
3995
5735
  schema_version: "ceal.codex_observation_outbox.v1",
@@ -3997,10 +5737,10 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3997
5737
  host_input_ref: hostInputRef,
3998
5738
  prompt_ref: promptRef,
3999
5739
  observations,
4000
- codex_turn_id: record.turn_id,
5740
+ codex_turn_id: record2.turn_id,
4001
5741
  origin_input: origin,
4002
- submission_ref: codexSubmissionReference(hostInputRef, "input", record.ordinal),
4003
- created_at: record.timestamp,
5742
+ submission_ref: codexSubmissionReference(hostInputRef, "input", record2.ordinal),
5743
+ created_at: record2.timestamp,
4004
5744
  expires_at: this.expire(this.outboxRetentionMs)
4005
5745
  };
4006
5746
  const persisted = await this.persistUserInputTurn(activeTask, hostInputRef, origin, currentPromptRef, promptRef, identity, envelope);
@@ -4030,14 +5770,14 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
4030
5770
  * stay ignored. A stale active task for another turn releases first, the
4031
5771
  * same as a task_started supersession.
4032
5772
  */
4033
- async adoptHookCorrelatedTurn(registration, record) {
4034
- const currentPromptRef = hostProducerPromptRef(promptObservationValue(record.prompt).body_sha256);
5773
+ async adoptHookCorrelatedTurn(registration, record2) {
5774
+ const currentPromptRef = hostProducerPromptRef(promptObservationValue(record2.prompt).body_sha256);
4035
5775
  const selection = await this.store.readInvocationTurnSelection(registration.host_source_ref, registration.host_session_ref);
4036
5776
  if (selection?.prompt_ref !== currentPromptRef) return void 0;
4037
5777
  return {
4038
- codex_turn_id: record.turn_id,
4039
- host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record.turn_id),
4040
- started_at: record.timestamp
5778
+ codex_turn_id: record2.turn_id,
5779
+ host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id),
5780
+ started_at: record2.timestamp
4041
5781
  };
4042
5782
  }
4043
5783
  async persistUserInputTurn(activeTask, hostInputRef, origin, currentPromptRef, promptRef, identity, envelope) {
@@ -4056,21 +5796,21 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
4056
5796
  throw error;
4057
5797
  }
4058
5798
  }
4059
- async processTerminal(registration, activeTask, record) {
4060
- 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 };
5799
+ async processTerminal(registration, activeTask, record2) {
5800
+ 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 };
4061
5801
  const identity = { host_source_ref: registration.host_source_ref, host_session_ref: registration.host_session_ref, host_turn_ref: activeTask.host_turn_ref };
4062
- 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 };
4063
- const observations = terminalObservations(registration, activeTask, record, timing);
5802
+ 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 };
5803
+ const observations = terminalObservations(registration, activeTask, record2, timing);
4064
5804
  await this.store.put({
4065
5805
  schema_version: "ceal.codex_observation_outbox.v1",
4066
5806
  identity,
4067
5807
  host_input_ref: activeTask.origin_host_input_ref,
4068
5808
  prompt_ref: activeTask.prompt_ref,
4069
5809
  observations,
4070
- codex_turn_id: record.turn_id,
5810
+ codex_turn_id: record2.turn_id,
4071
5811
  origin_input: false,
4072
- submission_ref: codexSubmissionReference(activeTask.origin_host_input_ref, "terminal", record.ordinal),
4073
- created_at: record.timestamp,
5812
+ submission_ref: codexSubmissionReference(activeTask.origin_host_input_ref, "terminal", record2.ordinal),
5813
+ created_at: record2.timestamp,
4074
5814
  expires_at: this.expire(this.outboxRetentionMs)
4075
5815
  });
4076
5816
  await this.store.clearInvocationContext(identity, this.now());
@@ -4081,6 +5821,29 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
4081
5821
  await this.store.writeTranscriptCursor(quarantined);
4082
5822
  }
4083
5823
  };
5824
+ async function readCodexHumanMessageProjection(registration, cursor, readChunk) {
5825
+ let offset = 0;
5826
+ const state = { records: 0, lastOrdinal: 0, window: { messages: [], truncated: false } };
5827
+ while (offset < cursor.offset) {
5828
+ const complete = await readChunk(offset, cursor.offset);
5829
+ if (complete === "empty" || complete === "partial") throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix is incomplete.");
5830
+ consumeCodexHumanMessageProjectionChunk(registration, complete, state);
5831
+ offset += complete.length;
5832
+ }
5833
+ 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.");
5834
+ return state.window;
5835
+ }
5836
+ function consumeCodexHumanMessageProjectionChunk(registration, complete, state) {
5837
+ for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
5838
+ const record2 = decodeCodexTranscriptLine(line);
5839
+ if (state.records === 0) assertCodexTranscriptHeader(registration, record2);
5840
+ else if (record2.ordinal <= state.lastOrdinal) throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix has a nonmonotonic ordinal.");
5841
+ const message = codexHumanMessage(registration, record2);
5842
+ if (message !== null) state.window = mergeHostInvocationHumanMessageWindow(state.window, [message]);
5843
+ state.lastOrdinal = record2.ordinal;
5844
+ state.records += 1;
5845
+ }
5846
+ }
4084
5847
  function codexTranscriptScanFailureKind(error) {
4085
5848
  return transcriptScanFailureKind(error, (candidate) => {
4086
5849
  if (!(candidate instanceof CodexHostAdapterError)) return void 0;
@@ -4089,10 +5852,10 @@ function codexTranscriptScanFailureKind(error) {
4089
5852
  return void 0;
4090
5853
  });
4091
5854
  }
4092
- function accumulateTokenCount(activeTask, record) {
4093
- if (record.usage_gap_reason !== void 0) return { ...activeTask, token_usage_gap_reason: record.usage_gap_reason };
4094
- const last = record.last_usage;
4095
- const total = record.total_usage;
5855
+ function accumulateTokenCount(activeTask, record2) {
5856
+ if (record2.usage_gap_reason !== void 0) return { ...activeTask, token_usage_gap_reason: record2.usage_gap_reason };
5857
+ const last = record2.last_usage;
5858
+ const total = record2.total_usage;
4096
5859
  if (last === void 0 || ignoreTokenCount(activeTask.last_total_usage, total, last)) return activeTask;
4097
5860
  const tokenUsage = addUsage(activeTask.token_usage, last);
4098
5861
  return {
@@ -4106,14 +5869,14 @@ function ignoreTokenCount(previous, total, last) {
4106
5869
  if (total === void 0 || previous === void 0) return false;
4107
5870
  return sameUsage(total, previous) || regressedUsage(total, previous) && looksLikeStaleRegression(total, previous, last);
4108
5871
  }
4109
- function terminalObservations(registration, activeTask, record, timing) {
5872
+ function terminalObservations(registration, activeTask, record2, timing) {
4110
5873
  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);
4111
5874
  const observations = [
4112
- { 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") },
4113
- { observation_ref: observationRef(registration.host_source_ref, "transcript_timing", activeTask.host_turn_ref, timing), observation_kind: "timing", observed_at: record.timestamp, value: timing },
4114
- { observation_ref: observationRef(registration.host_source_ref, "transcript_token", activeTask.host_turn_ref, tokenValue), observation_kind: "token", observed_at: record.timestamp, value: tokenValue }
5875
+ { 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") },
5876
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_timing", activeTask.host_turn_ref, timing), observation_kind: "timing", observed_at: record2.timestamp, value: timing },
5877
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_token", activeTask.host_turn_ref, tokenValue), observation_kind: "token", observed_at: record2.timestamp, value: tokenValue }
4115
5878
  ];
4116
- 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" } });
5879
+ 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" } });
4117
5880
  return observations;
4118
5881
  }
4119
5882
  function notRecorded(reason) {
@@ -4162,16 +5925,24 @@ function looksLikeStaleRegression(current, previous, last) {
4162
5925
  if (previous.total_tokens <= 0 || current.total_tokens <= 0 || last.total_tokens <= 0) return false;
4163
5926
  return current.total_tokens * 100 >= previous.total_tokens * 98 || current.total_tokens + last.total_tokens * 2 >= previous.total_tokens;
4164
5927
  }
4165
- function assertRecordSequence(registration, cursor, records, lastOrdinal, record) {
4166
- 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}`)}).`);
4167
- if (!cursor.header_validated && records === 0) assertCodexTranscriptHeader(registration, record);
5928
+ function codexHumanMessage(registration, record2) {
5929
+ if (record2.kind !== "user_text" || record2.content_item_kind !== "user.text") return null;
5930
+ return {
5931
+ host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id),
5932
+ host_input_ref: hostInputReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id, record2.message_id, record2.ordinal, record2.prompt),
5933
+ text: record2.prompt
5934
+ };
5935
+ }
5936
+ function assertRecordSequence(registration, cursor, records, lastOrdinal, record2) {
5937
+ 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}`)}).`);
5938
+ if (!cursor.header_validated && records === 0) assertCodexTranscriptHeader(registration, record2);
4168
5939
  }
4169
5940
 
4170
5941
  // host/codex/src/codex-producer-runtime.ts
4171
5942
  async function drainCodexProducerOnce(options) {
4172
5943
  const scan = await new CodexTranscriptWatcher({
4173
5944
  outbox_dir: options.outbox_dir,
4174
- diagnostic: (event, failure_kind) => writeHostServiceDiagnostic("codex", event, failure_kind)
5945
+ diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
4175
5946
  }).scanOnce().catch((error) => {
4176
5947
  writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
4177
5948
  throw error;
@@ -4180,6 +5951,236 @@ async function drainCodexProducerOnce(options) {
4180
5951
  return { scanned: scan.enqueued, ...await producer.drainOutbox() };
4181
5952
  }
4182
5953
 
5954
+ // host/codex/src/codex-usage-facts-capturer.ts
5955
+ import { createHash as createHash9 } from "node:crypto";
5956
+ var CodexUsageFactsCapturer = class {
5957
+ sources;
5958
+ usage;
5959
+ now;
5960
+ diagnosticSink;
5961
+ nextRegistrationIndex = 0;
5962
+ constructor(options) {
5963
+ this.sources = new CodexOutboxStore(options.outbox_dir);
5964
+ this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5965
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5966
+ this.diagnosticSink = options.diagnostic_sink;
5967
+ }
5968
+ async captureNext() {
5969
+ const registrations = await this.sources.listTranscriptRegistrations();
5970
+ const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
5971
+ this.nextRegistrationIndex = result.nextIndex;
5972
+ if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5973
+ return result.captured;
5974
+ }
5975
+ async captureRegistration(registration) {
5976
+ const prepared = await openHostUsageTranscriptCursor({
5977
+ path: registration.transcript_path,
5978
+ producer: "codex",
5979
+ source_kind: "codex_transcript",
5980
+ host_source_ref: registration.host_source_ref,
5981
+ host_session_ref: registration.host_session_ref,
5982
+ source_slot: "main",
5983
+ created_at: this.stamp(),
5984
+ store: this.usage,
5985
+ inspect: ownedCodexTranscriptFile,
5986
+ initial_cursor: initialCursor
5987
+ });
5988
+ if (prepared === null) return false;
5989
+ const { handle, source, source_file_ref: sourceFileRef, state, cursor: current } = prepared;
5990
+ try {
5991
+ if (await cursorReplaced(handle, source, sourceFileRef, current)) {
5992
+ const after = replacementCursor(sourceFileRef, source.device, source.inode);
5993
+ const gap = coverageGap("source_file_replaced", null, null, null, null);
5994
+ await this.usage.commitScanTransition(state, "main", current, after, null, [gap]);
5995
+ return true;
5996
+ }
5997
+ if (source.size === current.offset && !current.skipping_oversized_line) return false;
5998
+ return await this.captureChunk(handle, registration, current, sourceFileRef, source.size, state);
5999
+ } finally {
6000
+ await handle.close();
6001
+ }
6002
+ }
6003
+ async captureChunk(handle, registration, before, sourceFileRef, size, state) {
6004
+ const chunk = await readHostUsageTranscriptChunk(handle, before.offset, size, before.skipping_oversized_line);
6005
+ if (chunk.end_offset === before.offset && chunk.lines.length === 0) return false;
6006
+ const processed = processCodexLines(chunk.lines, registration, sourceFileRef, before, chunk.oversized_rows);
6007
+ const after = await updateAnchor(handle, { ...processed.cursor, offset: chunk.end_offset, skipping_oversized_line: chunk.skipping_oversized_line });
6008
+ const gaps = buildCoverageGaps(sourceFileRef, before.offset, chunk.end_offset, processed.gapCounts);
6009
+ const batch = processed.facts.length === 0 && gaps.length === 0 ? null : createCealHostUsageBatch({
6010
+ host_source_ref: registration.host_source_ref,
6011
+ host_session_ref: registration.host_session_ref,
6012
+ created_at: processed.createdAt,
6013
+ source_ranges: [{ source_file_ref: sourceFileRef, start_offset: before.offset, end_offset: chunk.end_offset }],
6014
+ facts: processed.facts,
6015
+ coverage_gaps: gaps
6016
+ });
6017
+ await this.usage.commitScanTransition(state, "main", before, after, batch);
6018
+ return true;
6019
+ }
6020
+ stamp() {
6021
+ const value = this.now();
6022
+ if (!Number.isFinite(value.getTime())) throw new Error("Codex usage facts clock is invalid.");
6023
+ return value.toISOString();
6024
+ }
6025
+ };
6026
+ function processCodexLines(lines, registration, sourceFileRef, initial, oversizedRows) {
6027
+ let cursor = initial;
6028
+ let createdAt = registration.registered_at;
6029
+ let records = 0;
6030
+ const facts = [];
6031
+ const gapCounts = /* @__PURE__ */ new Map();
6032
+ if (oversizedRows > 0) gapCounts.set("unsupported_source_shape", oversizedRows);
6033
+ for (const bytes of lines) {
6034
+ const record2 = decodeCodexLine(bytes);
6035
+ if (record2 === null || !validInitialHeader(record2, registration, initial.offset, records) || !hasIncreasingOrdinal(cursor, record2)) {
6036
+ addCodexGap(gapCounts, "unsupported_source_shape");
6037
+ records += 1;
6038
+ continue;
6039
+ }
6040
+ createdAt = record2.timestamp;
6041
+ cursor = applyCodexRecord(cursor, record2, registration, sourceFileRef, facts, gapCounts);
6042
+ cursor = { ...cursor, last_ordinal: record2.ordinal };
6043
+ records += 1;
6044
+ }
6045
+ return { cursor, facts, gapCounts, createdAt };
6046
+ }
6047
+ function decodeCodexLine(bytes) {
6048
+ try {
6049
+ return decodeCodexUsageTranscriptLine(bytes.toString("utf8"));
6050
+ } catch {
6051
+ return null;
6052
+ }
6053
+ }
6054
+ function validInitialHeader(record2, registration, initialOffset, records) {
6055
+ if (initialOffset !== 0 || records !== 0) return true;
6056
+ try {
6057
+ assertCodexTranscriptHeader(registration, record2);
6058
+ return true;
6059
+ } catch {
6060
+ return false;
6061
+ }
6062
+ }
6063
+ function hasIncreasingOrdinal(cursor, record2) {
6064
+ return cursor.last_ordinal === null || record2.ordinal > cursor.last_ordinal;
6065
+ }
6066
+ function applyCodexRecord(cursor, record2, registration, sourceFileRef, facts, gapCounts) {
6067
+ if (record2.kind === "token_count") return applyTokenCount(cursor, registration, sourceFileRef, record2, facts, gapCounts);
6068
+ 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 };
6069
+ if (record2.kind === "turn_context" && cursor.native_turn_id === record2.turn_id) return { ...cursor, requested_model: record2.model };
6070
+ 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 };
6071
+ return cursor;
6072
+ }
6073
+ function applyTokenCount(cursor, registration, sourceFileRef, record2, facts, gapCounts) {
6074
+ if (record2.usage_gap_reason !== void 0 || record2.last_usage === void 0 && record2.total_usage === void 0) addCodexGap(gapCounts, "source_usage_unavailable");
6075
+ else facts.push(codexUsageFact(registration, sourceFileRef, cursor, record2));
6076
+ return { ...cursor, codex_total_usage: record2.total_usage ?? cursor.codex_total_usage };
6077
+ }
6078
+ function addCodexGap(gaps, reason) {
6079
+ gaps.set(reason, (gaps.get(reason) ?? 0) + 1);
6080
+ }
6081
+ function initialCursor(sourceFileRef, device, inode) {
6082
+ return {
6083
+ source_file_ref: sourceFileRef,
6084
+ device,
6085
+ inode,
6086
+ offset: 0,
6087
+ anchor_start: 0,
6088
+ anchor_sha256: sha2564(Buffer.alloc(0)),
6089
+ last_ordinal: null,
6090
+ host_turn_ref: null,
6091
+ native_turn_id: null,
6092
+ requested_model: null,
6093
+ codex_total_usage: null,
6094
+ skipping_oversized_line: false
6095
+ };
6096
+ }
6097
+ function codexUsageFact(registration, sourceFileRef, cursor, record2) {
6098
+ const sourceEventRef = hostUsageSourceEventReference(sourceFileRef, `codex:${record2.ordinal}`);
6099
+ const total = record2.total_usage;
6100
+ const cumulativeTransition = transitionKind(cursor.codex_total_usage, total);
6101
+ const selected = record2.last_usage ?? total;
6102
+ const normalized = normalizedCounts(selected);
6103
+ return {
6104
+ fact_ref: hostUsageFactReference(sourceFileRef, sourceEventRef),
6105
+ host_session_ref: registration.host_session_ref,
6106
+ host_turn_ref: cursor.host_turn_ref,
6107
+ source_file_ref: sourceFileRef,
6108
+ source_event_ref: sourceEventRef,
6109
+ source_event_ordinal: record2.ordinal,
6110
+ observed_at: record2.timestamp,
6111
+ producer: "codex_transcript",
6112
+ requested_model: cursor.requested_model,
6113
+ reported_model: null,
6114
+ source_usage: { last_token_usage: record2.last_usage ?? null, total_token_usage: total ?? null },
6115
+ normalized_usage: normalized,
6116
+ counter_semantics: record2.last_usage !== void 0 && total !== void 0 ? "last_delta_total_cumulative" : total !== void 0 ? "total_cumulative_only" : "unknown",
6117
+ cumulative_transition: cumulativeTransition,
6118
+ finality: "unknown",
6119
+ correction_semantics: "unknown"
6120
+ };
6121
+ }
6122
+ function transitionKind(baseline, total) {
6123
+ if (total === void 0) return "not_observed";
6124
+ if (baseline === null) return "baseline";
6125
+ if (sameCounts(baseline, total)) return "same";
6126
+ return isRegression(total, baseline) ? "reset_or_correction" : "advanced";
6127
+ }
6128
+ function normalizedCounts(selected) {
6129
+ return selected === void 0 ? nullCounts() : {
6130
+ input: selected.input_tokens,
6131
+ output: selected.output_tokens,
6132
+ total: selected.total_tokens,
6133
+ cached_input: selected.cached_input_tokens,
6134
+ cache_write_input: selected.cache_write_input_tokens,
6135
+ reasoning_output: selected.reasoning_output_tokens
6136
+ };
6137
+ }
6138
+ function nullCounts() {
6139
+ return { input: null, output: null, total: null, cached_input: null, cache_write_input: null, reasoning_output: null };
6140
+ }
6141
+ function isRegression(current, previous) {
6142
+ return CEAL_CODEX_USAGE_COUNT_FIELDS.some((key) => current[key] < previous[key]);
6143
+ }
6144
+ function sameCounts(left, right) {
6145
+ return CEAL_CODEX_USAGE_COUNT_FIELDS.every((key) => left[key] === right[key]);
6146
+ }
6147
+ function buildCoverageGaps(sourceFileRef, startOffset, endOffset, counts) {
6148
+ return [...counts].map(([reason, omittedCount]) => coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount));
6149
+ }
6150
+ function coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount) {
6151
+ return { reason, source_file_ref: sourceFileRef, start_offset: startOffset, end_offset: endOffset, omitted_count: omittedCount };
6152
+ }
6153
+ function sha2564(value) {
6154
+ return createHash9("sha256").update(value).digest("hex");
6155
+ }
6156
+ async function anchorMatches(handle, cursor) {
6157
+ const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
6158
+ if (bytes.length === 0) return sha2564(bytes) === cursor.anchor_sha256;
6159
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, cursor.anchor_start));
6160
+ return bytesRead === bytes.length && sha2564(bytes) === cursor.anchor_sha256;
6161
+ }
6162
+ async function cursorReplaced(handle, source, sourceFileRef, cursor) {
6163
+ return cursor.source_file_ref !== sourceFileRef || cursor.device !== source.device || cursor.inode !== source.inode || source.size < cursor.offset || !await anchorMatches(handle, cursor);
6164
+ }
6165
+ function replacementCursor(sourceFileRef, device, inode) {
6166
+ return {
6167
+ ...initialCursor(sourceFileRef, device, inode),
6168
+ source_file_ref: sourceFileRef,
6169
+ device,
6170
+ inode,
6171
+ offset: 0
6172
+ };
6173
+ }
6174
+ async function updateAnchor(handle, cursor) {
6175
+ const anchorStart = Math.max(0, cursor.offset - CODEX_TRANSCRIPT_ANCHOR_BYTES);
6176
+ const anchor = Buffer.alloc(cursor.offset - anchorStart);
6177
+ if (anchor.length > 0) {
6178
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(anchor, 0, anchor.length, anchorStart));
6179
+ if (bytesRead !== anchor.length) throw new Error("Codex usage facts source changed during anchor read.");
6180
+ }
6181
+ return { ...cursor, anchor_start: anchorStart, anchor_sha256: sha2564(anchor) };
6182
+ }
6183
+
4183
6184
  // host/codex/src/codex-producer-service.ts
4184
6185
  var CODEX_PRODUCER_CONFIG_SCHEMA = "ceal.codex_producer_config.v1";
4185
6186
  var CODEX_SESSIONS_ROOT = "codex_sessions_root";
@@ -4188,10 +6189,12 @@ var CODEX_PRODUCER_DESCRIPTOR = {
4188
6189
  producer_id: "codex",
4189
6190
  extra_paths: [CODEX_SESSIONS_ROOT],
4190
6191
  config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
4191
- runtime_options: (config) => Object.freeze({
4192
- outbox_dir: config.outbox_dir
4193
- }),
4194
- drain: drainCodexProducerOnce
6192
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6193
+ drain: drainCodexProducerOnce,
6194
+ background: (config, signal, dependencies) => {
6195
+ const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });
6196
+ 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(), fetch: dependencies.fetch }, signal);
6197
+ }
4195
6198
  };
4196
6199
 
4197
6200
  // host/codex/src/codex-hook-runner.ts
@@ -4205,23 +6208,15 @@ function codexHookEventFromArgs(args) {
4205
6208
  const event = marker?.slice("--ceal-hook-event=".length);
4206
6209
  return isCodexHookEvent(event) ? event : null;
4207
6210
  }
4208
- async function runCodexHookProcess(args, stdin, options) {
4209
- const event = codexHookEventFromArgs(args);
4210
- if (event === null) return 0;
6211
+ async function runCodexHook(event, stdin, options) {
4211
6212
  try {
4212
6213
  const result = await runCodexHookFromStdin(event, stdin, options);
4213
- if (result.disposition === "rejected") writeCodexHookDiagnostic(result);
4214
- return 0;
4215
- } catch (error) {
4216
- writeCodexHookDiagnostic({ event, disposition: "rejected", reason: error instanceof Error ? error.message.slice(0, 128) : "codex_hook_failed" });
6214
+ if (result.disposition === "rejected") writeHostServiceDiagnostic("codex", "hook_failed", void 0, void 0, options.diagnostic_sink);
6215
+ else if (result.reason === "transcript_registered") writeHostServiceDiagnostic("codex", "registration_written", void 0, void 0, options.diagnostic_sink);
4217
6216
  return 0;
4218
- }
4219
- }
4220
- function writeCodexHookDiagnostic(result) {
4221
- try {
4222
- process.stderr.write(`${JSON.stringify({ schema_version: "ceal.codex_sessionstart_diagnostic.v1", event: result.event, disposition: result.disposition, ...result.reason === void 0 ? {} : { reason: result.reason } })}
4223
- `);
4224
6217
  } catch {
6218
+ writeHostServiceDiagnostic("codex", "hook_failed", void 0, void 0, options.diagnostic_sink);
6219
+ return 0;
4225
6220
  }
4226
6221
  }
4227
6222
  async function readStdin(stdin) {
@@ -4237,11 +6232,19 @@ async function readStdin(stdin) {
4237
6232
  }
4238
6233
  async function runCodexHookCli() {
4239
6234
  const args = process.argv.slice(2);
4240
- const owner = await installedCodexHookRunnerOptions(args);
4241
- return runCodexHookProcess(args, process.stdin, owner);
6235
+ const event = codexHookEventFromArgs(args);
6236
+ if (event === null) return 0;
6237
+ writeHostServiceDiagnostic("codex", "hook_invoked");
6238
+ try {
6239
+ const owner = await installedCodexHookRunnerOptions(args);
6240
+ return runCodexHook(event, process.stdin, owner);
6241
+ } catch {
6242
+ writeHostServiceDiagnostic("codex", "hook_failed");
6243
+ return 0;
6244
+ }
4242
6245
  }
4243
- async function installedCodexHookRunnerOptions(args) {
4244
- const config = await readHostProducerConfig(CODEX_PRODUCER_DESCRIPTOR, parseHostProducerConfigFlag(args));
6246
+ async function installedCodexHookRunnerOptions(args, custody = {}) {
6247
+ const config = await readHostProducerConfig(CODEX_PRODUCER_DESCRIPTOR, parseHostProducerConfigFlag(args), process.platform, custody);
4245
6248
  return { host_source_ref: config.host_source_ref, outbox_dir: config.outbox_dir, codex_sessions_root: config.codex_sessions_root };
4246
6249
  }
4247
6250