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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,8 +4,9 @@ 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";
9
10
 
10
11
  // packages/ceal-client-protocol/src/canonical-json.ts
11
12
  function cealCanonicalJson(value) {
@@ -35,7 +36,7 @@ function isPlainRecord(value) {
35
36
  }
36
37
 
37
38
  // packages/ceal-client-protocol/src/client-wire-contract.ts
38
- import { createHash } from "node:crypto";
39
+ import { createHash as createHash2 } from "node:crypto";
39
40
 
40
41
  // packages/ceal-client-protocol/client-wire-contract.json
41
42
  var client_wire_contract_default = {
@@ -56,7 +57,7 @@ var client_wire_contract_default = {
56
57
  ordering: "utf16_code_unit_ascending"
57
58
  },
58
59
  artifact_descriptor: {
59
- operation_contract_bundle_schema_name: "ceal.operation_contract_bundle",
60
+ operation_contract_bundle_schema_name: "ceal.operation_contract_bundle_v2",
60
61
  operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
61
62
  schema_name: "ceal.verified_artifact_descriptor",
62
63
  fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
@@ -81,7 +82,7 @@ var client_wire_contract_default = {
81
82
  },
82
83
  command_request: {
83
84
  schema_name: "ceal.command_request",
84
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
85
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
85
86
  absolute_transport_max_bytes: 65536
86
87
  },
87
88
  command_resolution: {
@@ -127,8 +128,9 @@ var client_wire_contract_default = {
127
128
  },
128
129
  command_response: {
129
130
  schema_name: "ceal.command_response",
130
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
131
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
131
132
  descriptor_field: "verified_artifact",
133
+ request_context_field: "request_context",
132
134
  required_fields: [
133
135
  "schema_version",
134
136
  "exit_code",
@@ -138,7 +140,8 @@ var client_wire_contract_default = {
138
140
  "operation_id",
139
141
  "visible_output_max_bytes",
140
142
  "local_delivery",
141
- "verified_artifact"
143
+ "verified_artifact",
144
+ "request_context"
142
145
  ],
143
146
  bare_document_fields: [
144
147
  "invocation",
@@ -159,7 +162,7 @@ var client_wire_contract_default = {
159
162
  ],
160
163
  exit_code_max: 125,
161
164
  bare_document_max_bytes: 65536,
162
- complete_max_bytes: 66046
165
+ complete_max_bytes: 66195
163
166
  },
164
167
  host_invocation_authentication: {
165
168
  request_schema_name: "ceal.host_invocation_authentication_request",
@@ -173,6 +176,14 @@ var client_wire_contract_default = {
173
176
  "context_token",
174
177
  "expires_at"
175
178
  ],
179
+ refusal_schema_name: "ceal.host_invocation_authentication_refusal",
180
+ refusal_fields: [
181
+ "schema_version",
182
+ "ok",
183
+ "code",
184
+ "reason",
185
+ "gateway_status"
186
+ ],
176
187
  client_nonce: {
177
188
  character_class_source: "A-Za-z0-9_-",
178
189
  encoded_characters: 43
@@ -211,6 +222,8 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
211
222
  "choose_new_output_path",
212
223
  "choose_new_idempotency_key",
213
224
  "restart_search",
225
+ // The requested temporal key is absent on some observed rows; repeating the same interval without `order` can return those rows.
226
+ "search_without_order",
214
227
  "repeat_original_arguments",
215
228
  // The occurrence this call addressed is settled and cannot move again -- a
216
229
  // denied effect approval, an expired continuation -- so the caller runs the
@@ -269,6 +282,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
269
282
  // The command needs caller-owned local materialization (for example an
270
283
  // @path file) before the Gateway can receive the argument.
271
284
  "materialize_local_argument",
285
+ // A missing or stale local Host bundle is repaired through its installed lifecycle and discovery owners.
286
+ "install_ceal_host",
287
+ // An explicit Client store override points at a missing file; unsetting it selects the one canonical default store without creating a second credential store.
288
+ "unset_context_store_path",
289
+ // The producer app must reload its installed Host hook before it can start a conversation with invocation context.
290
+ "restart_producer_app",
272
291
  // A peer's derived schema identifier changed with its field set; install or
273
292
  // upgrade the CLI and Host Relay to the Gateway's release before retrying.
274
293
  "upgrade_ceal_client"
@@ -377,7 +396,6 @@ var NON_MODEL_ACTION_TO_MODEL_ACTION = Object.freeze({
377
396
  });
378
397
  var RETRY_PROMISE_NEXT_ACTIONS = ["retry", "retry_after"];
379
398
  var RETRY_PROMISE = new Set(RETRY_PROMISE_NEXT_ACTIONS);
380
- var RECOVERABLE = new Set(CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS);
381
399
  var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
382
400
  provider_permission: "ask_admin",
383
401
  access_level: "ask_admin",
@@ -399,9 +417,9 @@ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "s
399
417
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
400
418
  var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
401
419
  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"]);
420
+ var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
403
421
  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"]);
422
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
405
423
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
406
424
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
407
425
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -472,10 +490,10 @@ function assertSafeJsonArray(value, options, depth, count) {
472
490
  if (value.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
473
491
  for (const item of value) assertSafeJsonValue(item, options, depth + 1, count);
474
492
  }
475
- function assertSafeJsonRecord(record, options, depth, count) {
476
- const entries = Object.entries(record);
493
+ function assertSafeJsonRecord(record2, options, depth, count) {
494
+ const entries = Object.entries(record2);
477
495
  if (entries.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
478
- const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record.fields) : null;
496
+ const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record2.fields) : null;
479
497
  for (const [key, child] of entries) {
480
498
  if (key === "credential_material_included" && child !== false) invalidByContext(options);
481
499
  if (!isSafeNegativeMaterialAssertion(key, child)) assertSafeJsonKey(key, options);
@@ -525,16 +543,21 @@ function isSafeExternalHttpsUrl(value) {
525
543
  return false;
526
544
  }
527
545
  }
546
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE = "^https://[^\\s/@?#]+(?:[/?#][^\\s]*)?$";
547
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN = new RegExp(SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE, "u");
528
548
  function isSafeExternalHttpsUrlInput(value) {
529
549
  return typeof value === "string" && byteLength(value) <= 2048;
530
550
  }
531
- function isSafeExternalHttpsUrlShape(url) {
532
- return url.protocol === "https:" && url.username === "" && url.password === "" && url.hash === "";
551
+ function isSafeExternalHttpsUrlShape(url, allowFragment = false) {
552
+ return url.protocol === "https:" && url.hostname.length > 0 && url.username === "" && url.password === "" && (allowFragment || url.hash === "");
533
553
  }
534
554
  function isSafeResultContent(value, key) {
535
555
  const maximum = key === "text" ? 8192 : 1024;
536
556
  return typeof value === "string" && byteLength(value) <= maximum && firstDisallowedControl(value, "multi_line") === null;
537
557
  }
558
+ function requireSafeRef(value) {
559
+ if (typeof value !== "string" || !SAFE_REF.test(value)) invalidRequestOrResponse();
560
+ }
538
561
  var CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES = 512;
539
562
  function normalizeCealSingleLineText(value) {
540
563
  return value.split("").map((character) => hasControlCharacter(character) ? " " : character).join("").trim();
@@ -646,6 +669,7 @@ function cut(text) {
646
669
 
647
670
  // packages/ceal-client-protocol/src/operation-validation-primitives.ts
648
671
  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;
672
+ var EXPANDED_CANONICAL_ISO_TIMESTAMP = /^([+-])(\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/u;
649
673
  var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
650
674
  var CEAL_CALENDAR_DATE = new RegExp(CEAL_CALENDAR_DATE_PATTERN_SOURCE, "u");
651
675
  function isOperationRecord(value) {
@@ -656,13 +680,46 @@ function isOperationRecord(value) {
656
680
  function requireOperationRecord(value, message) {
657
681
  if (!isOperationRecord(value)) throw new TypeError(message);
658
682
  }
683
+ function requireExactOperationKeys(value, required, optional = [], message = "Operation contract has an invalid shape.") {
684
+ const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
685
+ if (required.some((key) => !Object.hasOwn(value, key))) throw new TypeError(message);
686
+ if (Object.keys(value).some((key) => !allowed.has(key))) throw new TypeError(message);
687
+ }
659
688
  function requireClosedValue(value, members, message) {
660
689
  if (typeof value !== "string" || !members.includes(value)) throw new TypeError(message);
661
690
  }
662
691
  function isCealIsoTimestamp(value) {
663
692
  return typeof value === "string" && parseCealIsoTimestamp(value) !== null;
664
693
  }
694
+ function canonicalCealIsoTimestamp(epochNanoseconds) {
695
+ const wholeSeconds = floorDivide(epochNanoseconds, 1000000000n);
696
+ const fractionalNanoseconds = epochNanoseconds - wholeSeconds * 1000000000n;
697
+ const utc = new Date(Number(wholeSeconds * 1000n));
698
+ const date = utc.toISOString().split(".")[0];
699
+ if (date === void 0) throw new TypeError("Ceal timestamp formatter returned an invalid ISO string");
700
+ const fraction = fractionalNanoseconds.toString().padStart(9, "0").replace(/0+$/u, "").padEnd(3, "0");
701
+ return date + "." + fraction + "Z";
702
+ }
703
+ var CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE = "0000-01-01T00:00:00.000000000+23:59";
704
+ var CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE = "9999-12-31T23:59:59.999999999-23:59";
705
+ var CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE);
706
+ var CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE);
707
+ var CEAL_INSTANT_INDEX_SPAN = CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS - CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS;
708
+ var CEAL_INSTANT_INDEX_KEY_WIDTH = CEAL_INSTANT_INDEX_SPAN.toString().length;
709
+ var CEAL_INSTANT_INDEX_KEY_PATTERN = new RegExp(`^\\d{${CEAL_INSTANT_INDEX_KEY_WIDTH}}$`, "u");
710
+ function requiredTimestampEpochNanoseconds(value) {
711
+ const parsed = parseFourDigitCealIsoTimestamp(value);
712
+ if (parsed === null) throw new Error("Ceal instant-index range basis is outside the timestamp grammar");
713
+ return parsed.epochNanoseconds;
714
+ }
665
715
  function parseCealIsoTimestamp(value) {
716
+ const ordinary = parseFourDigitCealIsoTimestamp(value);
717
+ if (ordinary !== null) return ordinary;
718
+ const expanded = parseExpandedCanonicalCealIsoTimestamp(value);
719
+ if (expanded === null || expanded.epochNanoseconds < CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS || expanded.epochNanoseconds > CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS) return null;
720
+ return canonicalCealIsoTimestamp(expanded.epochNanoseconds) === value ? expanded : null;
721
+ }
722
+ function parseFourDigitCealIsoTimestamp(value) {
666
723
  const fields = parseCealIsoTimestampFields(value);
667
724
  if (fields === null || !validCalendarDate(fields) || !validClockTime(fields) || !validUtcOffset(fields)) return null;
668
725
  const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
@@ -671,6 +728,28 @@ function parseCealIsoTimestamp(value) {
671
728
  epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
672
729
  };
673
730
  }
731
+ function parseExpandedCanonicalCealIsoTimestamp(value) {
732
+ const match = EXPANDED_CANONICAL_ISO_TIMESTAMP.exec(value);
733
+ if (match === null) return null;
734
+ const fields = {
735
+ year: (match[1] === "-" ? -1 : 1) * Number(match[2]),
736
+ month: Number(match[3]),
737
+ day: Number(match[4]),
738
+ hour: Number(match[5]),
739
+ minute: Number(match[6]),
740
+ second: Number(match[7]),
741
+ fraction: match[8] ?? "",
742
+ offsetSign: 0,
743
+ offsetHour: 0,
744
+ offsetMinute: 0
745
+ };
746
+ if (!validCalendarDate(fields) || !validClockTime(fields)) return null;
747
+ const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
748
+ if (!Number.isFinite(epochMilliseconds)) return null;
749
+ return {
750
+ epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
751
+ };
752
+ }
674
753
  function parseCealIsoTimestampFields(value) {
675
754
  const match = ISO_TIMESTAMP.exec(value);
676
755
  if (match === null) return null;
@@ -703,6 +782,10 @@ function cealFieldsEpochMilliseconds(fields) {
703
782
  const offsetMilliseconds = fields.offsetSign * (fields.offsetHour * 60 + fields.offsetMinute) * 6e4;
704
783
  return localMilliseconds - offsetMilliseconds;
705
784
  }
785
+ function floorDivide(value, divisor) {
786
+ const quotient = value / divisor;
787
+ return value % divisor < 0n ? quotient - 1n : quotient;
788
+ }
706
789
  function daysInMonth(year, month) {
707
790
  const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
708
791
  return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
@@ -720,6 +803,9 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
720
803
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
721
804
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
722
805
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
806
+ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
807
+ 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.";
808
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select or activate the current recorded turn. This does not explain why or prove ephemerality. For an independently identified ephemeral Codex side conversation, invoke the command as `ceal --standalone ...`; it uses the local Ceal session and Gateway permissions without Host session/turn audit linkage. Host refusal never switches modes. For intended Host calls, restart the producer and start a new conversation; report the error if it persists.";
723
809
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
724
810
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
725
811
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
@@ -745,6 +831,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
745
831
  refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
746
832
  refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
747
833
  refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
834
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
835
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
748
836
  refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
749
837
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
750
838
  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 +845,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
757
845
  response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
758
846
  request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
759
847
  request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
848
+ resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
760
849
  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),
850
+ contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
762
851
  // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
763
852
  // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
764
853
  // when the wait ends still unserved, moved from the `localFailureText` default branch.
@@ -770,6 +859,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
770
859
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
771
860
  // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
772
861
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
862
+ gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
773
863
  // Restored verbatim from the retired `localFailureText` `unknown_outcome`
774
864
  // case: the outcome is unknown, so a read may be retried while a write
775
865
  // must receipt-check first. Collapsing both to "do not repeat the call"
@@ -855,23 +945,24 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
855
945
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
856
946
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
857
947
  // 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
948
+ // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). Cause-specific
949
+ // sentences carry the retired policy remedies; `gateway_refused` reuses the release-upgrade guidance above.
950
+ // Statuses are the
860
951
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
861
952
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
862
953
  host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
863
954
  host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
864
955
  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),
956
+ // The bounded Host reason does not prove ephemerality. A Host refusal never
957
+ // changes mode; standalone remains the separate Client authority path.
958
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
868
959
  host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
869
960
  host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
870
961
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
871
962
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
872
963
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
873
964
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
874
- host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
965
+ host_mint_gateway_refused: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
875
966
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
876
967
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
877
968
  // producer-frame fault names the administrator repair step.
@@ -879,59 +970,16 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
879
970
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
880
971
  // sandboxed Relay socket names the run-alone retry.
881
972
  host_relay_permission_denied: guidance("An agent sandbox denied the Host Relay socket; run `ceal` as the only command, with no pipe, redirect, or `&&`, so the Host allow rule runs it outside the sandbox.", "rerun_outside_agent_sandbox", 403),
882
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
973
+ host_relay_unavailable: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 503),
883
974
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
884
975
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
885
- host_relay_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
976
+ host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
886
977
  host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
887
978
  });
888
979
  var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
889
980
 
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]);
981
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
982
+ import { createHash } from "node:crypto";
935
983
 
936
984
  // packages/ceal-client-protocol/src/operation-withheld-cause.ts
937
985
  var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
@@ -977,13 +1025,160 @@ var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
977
1025
  "interactive_unavailable"
978
1026
  ]);
979
1027
 
1028
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1029
+ var DIGEST = /^[a-f0-9]{64}$/u;
1030
+ var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1031
+ function isCealDigest(value) {
1032
+ return typeof value === "string" && DIGEST.test(value);
1033
+ }
1034
+ function cealRequestSha256(value) {
1035
+ return createHash("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1036
+ }
1037
+ function operationRecord(value, message) {
1038
+ requireOperationRecord(value, message);
1039
+ return value;
1040
+ }
1041
+ function invalid(message) {
1042
+ throw new TypeError(message);
1043
+ }
1044
+ function requirePrefixedRef(value, prefix, message) {
1045
+ if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1046
+ }
1047
+ function requireSafeRef2(value, message) {
1048
+ try {
1049
+ requireSafeRef(value);
1050
+ } catch {
1051
+ invalid(message);
1052
+ }
1053
+ }
1054
+
1055
+ // packages/ceal-client-protocol/src/request-authority.ts
1056
+ var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1057
+ var CEAL_REQUEST_REF_MAX_CHARACTERS = 128;
1058
+ var CEAL_REQUEST_REF_PATTERN_SOURCE = "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$";
1059
+ var CEAL_REQUEST_REF_PATTERN = new RegExp(CEAL_REQUEST_REF_PATTERN_SOURCE, "u");
1060
+ var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1061
+ var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1062
+ var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1063
+ var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1064
+ var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1065
+ var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1066
+ schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1067
+ ceal_request_ref: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_REF_MAX_CHARACTERS, pattern: CEAL_REQUEST_REF_PATTERN_SOURCE },
1068
+ created_at: { type: "string", minLength: 1, maxLength: 64 },
1069
+ authority: {
1070
+ type: "object",
1071
+ maxProperties: 5,
1072
+ additionalProperties: false,
1073
+ properties: {
1074
+ instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1075
+ access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1076
+ principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1077
+ execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1078
+ authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1079
+ },
1080
+ required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1081
+ }
1082
+ });
1083
+ var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1084
+ prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1085
+ host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1086
+ host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1087
+ 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." },
1088
+ host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1089
+ host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1090
+ });
1091
+ var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1092
+ 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." },
1093
+ 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." }
1094
+ });
1095
+ var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1096
+ requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1097
+ 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." }
1098
+ });
1099
+ var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1100
+ var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1101
+ var CEAL_REQUEST_JSON_SCHEMA = {
1102
+ type: "object",
1103
+ 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.",
1104
+ maxProperties: 14,
1105
+ additionalProperties: false,
1106
+ properties: {
1107
+ ...CEAL_REQUEST_COMMON_PROPERTIES,
1108
+ ...CEAL_REQUEST_HOST_PROPERTIES,
1109
+ ...CEAL_REQUEST_CALLER_PROPERTIES,
1110
+ ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1111
+ },
1112
+ required: CEAL_REQUEST_KEYS,
1113
+ anyOf: [
1114
+ {
1115
+ type: "object",
1116
+ required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1117
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1118
+ additionalProperties: false
1119
+ },
1120
+ {
1121
+ type: "object",
1122
+ required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1123
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1124
+ additionalProperties: false
1125
+ }
1126
+ ]
1127
+ };
1128
+
1129
+ // packages/ceal-client-protocol/src/client-wire-contract.ts
1130
+ var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
1131
+ var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
1132
+ var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
1133
+ var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
1134
+ var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
1135
+ var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
1136
+ function deriveCealClientWireSchemaVersion(schema) {
1137
+ 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))) {
1138
+ throw new TypeError("Client wire schema name or field set is invalid.");
1139
+ }
1140
+ const fields = schema.fields.filter((field) => field !== "schema_version").sort();
1141
+ const hash8 = createHash2("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
1142
+ return `${schema.schema_name}.v1.${hash8}`;
1143
+ }
1144
+ var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
1145
+ var commandResolutionAuthority = commandResolution.authority;
1146
+ var commandResolutionSemanticOptions = commandResolution.semantic_options;
1147
+ var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
1148
+ var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
1149
+ var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
1150
+ var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
1151
+ var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
1152
+ var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
1153
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
1154
+ var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
1155
+ var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
1156
+ var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
1157
+ var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
1158
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
1159
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
1160
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
1161
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
1162
+ var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
1163
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
1164
+ var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
1165
+ var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
1166
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
1167
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
1168
+ var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
1169
+ var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
1170
+ 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 });
1171
+ var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
1172
+
1173
+ // packages/ceal-client-protocol/src/access-level-vocabulary.ts
1174
+ var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1175
+
980
1176
  // packages/ceal-client-protocol/src/operation-access-class.ts
981
1177
  var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
982
1178
 
983
1179
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
984
1180
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
985
1181
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
986
- var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
987
1182
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
988
1183
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
989
1184
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1091,6 +1286,7 @@ var CEAL_SCHEMA_LITERALS = [
1091
1286
  "ceal.gateway_write_receipt_readback.v1",
1092
1287
  "ceal.gateway_write_request_receipt.v1",
1093
1288
  "ceal.host_observation.v1",
1289
+ "ceal.host_usage_batch.v1",
1094
1290
  "ceal.host_registration_request.v1",
1095
1291
  "ceal.host_registration_result.v1",
1096
1292
  CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
@@ -1119,7 +1315,6 @@ var CEAL_SCHEMA_LITERAL_SET = new Set(CEAL_SCHEMA_LITERALS);
1119
1315
  import { join } from "node:path";
1120
1316
  var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1121
1317
  bounded_store_sidecar: (root) => `${root}.jsonl`,
1122
- gateway_audit_archive: (root) => `${root}.jsonl`,
1123
1318
  gateway_access_group_connector_control_audit: (root) => `${root}.audit.jsonl`,
1124
1319
  gateway_access_group_connector_scope_audit: (root) => join(root, "profile-connector-scope-audit.jsonl"),
1125
1320
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
@@ -1149,6 +1344,7 @@ var CEAL_LOWERCASE_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
1149
1344
  var CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN = new RegExp(`^host-registration-attempt:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1150
1345
  var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1151
1346
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1347
+ var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1152
1348
 
1153
1349
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
1154
1350
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
@@ -1167,7 +1363,7 @@ function shellSingleQuoted(value) {
1167
1363
  return `'${value.replaceAll("'", "'\\''")}'`;
1168
1364
  }
1169
1365
  var CEAL_OPERATION_CONTRACT_REQUIRED_FIELDS = Object.freeze(["input_schema", "result_schema"]);
1170
- var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["summary", "input_resolution"]);
1366
+ var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["branches", "summary", "input_resolution"]);
1171
1367
  var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
1172
1368
  $schema: CEAL_JSON_SCHEMA_2020_12,
1173
1369
  $id: "https://ceal.dev/schemas/verified-artifact-descriptor.v1.schema.json",
@@ -1212,11 +1408,92 @@ var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_o
1212
1408
  // packages/ceal-client-protocol/src/actor-kind.ts
1213
1409
  var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
1214
1410
 
1411
+ // packages/ceal-client-protocol/src/provider-link-policy.ts
1412
+ var PROVIDER_LINK_RESULT_FIELDS = Object.freeze({
1413
+ read_row: Object.freeze({ human_link: "source_url", parent_context: Object.freeze(["thread_ref"]) }),
1414
+ write_result: Object.freeze({ human_links: Object.freeze(["user_openable_url", "url", "spreadsheet_url", "meet_url"]) })
1415
+ });
1416
+ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1417
+ { 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/" },
1418
+ { 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/" },
1419
+ { 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/" },
1420
+ { 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/" },
1421
+ { 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/" },
1422
+ { 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" },
1423
+ { 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" },
1424
+ { 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" },
1425
+ { 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" },
1426
+ { 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" },
1427
+ { 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" },
1428
+ { 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" },
1429
+ { 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" },
1430
+ { 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" },
1431
+ { 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" },
1432
+ { 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" },
1433
+ { 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" },
1434
+ { 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" },
1435
+ { 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" },
1436
+ { 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" }
1437
+ ]);
1438
+ var PROVIDER_LINK_HOSTS = Object.freeze({
1439
+ notion: Object.freeze(["notion.so", "www.notion.so", "notion.com", "www.notion.com", "app.notion.com"]),
1440
+ google_workspace: Object.freeze([
1441
+ "calendar.google.com",
1442
+ "contacts.google.com",
1443
+ "docs.google.com",
1444
+ "drive.google.com",
1445
+ "forms.google.com",
1446
+ "mail.google.com",
1447
+ "meet.google.com",
1448
+ "sites.google.com",
1449
+ "www.google.com"
1450
+ ])
1451
+ });
1452
+ var NOTION_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.notion);
1453
+ var GOOGLE_WORKSPACE_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.google_workspace);
1454
+ var PROVIDER_RESOURCE_SOURCE_URL_SCHEMA = Object.freeze({
1455
+ type: "string",
1456
+ minLength: 1,
1457
+ maxLength: 2048,
1458
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1459
+ 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."
1460
+ });
1461
+ var PROVIDER_USER_OPENABLE_URL_SCHEMA = Object.freeze({
1462
+ type: "string",
1463
+ minLength: 1,
1464
+ maxLength: 2048,
1465
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1466
+ 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."
1467
+ });
1468
+
1215
1469
  // packages/ceal-client-protocol/src/resource-row.ts
1216
1470
  var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
1217
1471
  var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
1218
1472
  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"]);
1473
+ var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
1474
+ "query",
1475
+ "modified_since",
1476
+ "since",
1477
+ "until",
1478
+ "filetype",
1479
+ "authored_by_me",
1480
+ "authored_by",
1481
+ "edited_by",
1482
+ "include_replies",
1483
+ "kinds",
1484
+ "container_ref",
1485
+ "container_refs",
1486
+ "container_names",
1487
+ "addressed_to_me",
1488
+ "unread",
1489
+ "archived",
1490
+ "state",
1491
+ "event_types",
1492
+ "starred",
1493
+ "trashed",
1494
+ "permission"
1495
+ ]);
1496
+ var CEAL_RESOURCE_SEARCH_STATES = vocabulary(["open", "closed", "draft", "prerelease", "confirmed", "tentative", "cancelled"]);
1220
1497
  var CEAL_RESOURCE_TIME_BASES = vocabulary(["created", "modified", "viewed"]);
1221
1498
  var CEAL_REPOSITORY_VISIBILITIES = vocabulary(["public", "private", "internal"]);
1222
1499
  var CEAL_ACTIVITY_V3_KINDS = vocabulary(["authored", "edited", "messaged", "responded"]);
@@ -1312,6 +1589,8 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1312
1589
  container_label: { required: true, timestamp: false },
1313
1590
  container_ref: { required: false, timestamp: false },
1314
1591
  source_url: { required: false, timestamp: false },
1592
+ thread_ref: { required: false, timestamp: false },
1593
+ reply_count: { required: false, timestamp: false },
1315
1594
  source: { required: true, timestamp: false },
1316
1595
  owner: { required: false, timestamp: false },
1317
1596
  actor_kind: { required: false, timestamp: false },
@@ -1337,6 +1616,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1337
1616
  start: { required: false, timestamp: false },
1338
1617
  end: { required: false, timestamp: false },
1339
1618
  status: { required: false, timestamp: false },
1619
+ event_type: { required: false, timestamp: false },
1340
1620
  snippet: { required: false, timestamp: false },
1341
1621
  dated_notes: { required: false, timestamp: false },
1342
1622
  state: { required: true, timestamp: false },
@@ -1400,6 +1680,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1400
1680
  "refresh_inactive",
1401
1681
  "refresh_replayed",
1402
1682
  "refresh_revoked",
1683
+ "person_inactive",
1684
+ "principal_inactive",
1403
1685
  "authority_replaced",
1404
1686
  "refresh_recovery_unavailable",
1405
1687
  "refresh_recovery_expired",
@@ -1420,116 +1702,25 @@ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
1420
1702
  var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1421
1703
  var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1422
1704
 
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
- // packages/ceal-client-protocol/src/request-operands.ts
1515
- var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1516
- var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
1517
- var CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH = 1024;
1518
- var CEAL_REQUEST_RESOLVER_SELECTION_JSON_SCHEMA = {
1519
- type: "object",
1520
- maxProperties: 2,
1521
- additionalProperties: false,
1522
- properties: {
1523
- property: { type: "string", minLength: 1, maxLength: 128 },
1524
- selectors: {
1525
- type: "object",
1526
- maxProperties: CEAL_REQUEST_MAX_SELECTOR_PROPERTIES,
1527
- properties: {},
1528
- additionalProperties: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH }
1529
- }
1530
- },
1531
- required: ["property", "selectors"]
1532
- };
1705
+ // packages/ceal-client-protocol/src/request-operands.ts
1706
+ var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1707
+ var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
1708
+ var CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH = 1024;
1709
+ var CEAL_REQUEST_RESOLVER_SELECTION_JSON_SCHEMA = {
1710
+ type: "object",
1711
+ maxProperties: 2,
1712
+ additionalProperties: false,
1713
+ properties: {
1714
+ property: { type: "string", minLength: 1, maxLength: 128 },
1715
+ selectors: {
1716
+ type: "object",
1717
+ maxProperties: CEAL_REQUEST_MAX_SELECTOR_PROPERTIES,
1718
+ properties: {},
1719
+ additionalProperties: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH }
1720
+ }
1721
+ },
1722
+ required: ["property", "selectors"]
1723
+ };
1533
1724
 
1534
1725
  // packages/ceal-client-protocol/src/request-graph.ts
1535
1726
  var CEAL_REQUEST_MAX_GRAPH_NODES = 128;
@@ -1618,6 +1809,27 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
1618
1809
  required: ["schema_version", "order", "nodes", "call_budget"]
1619
1810
  };
1620
1811
 
1812
+ // packages/ceal-client-protocol/src/host-observation-validation.ts
1813
+ var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1814
+ 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;
1815
+ function validateCealHostObservationValue(value) {
1816
+ if (value === void 0) throw new TypeError("Ceal Host observation value is invalid.");
1817
+ assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1818
+ if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) throw new TypeError("Ceal Host observation value is oversized.");
1819
+ inspectHostKeys(value);
1820
+ }
1821
+ function inspectHostKeys(value) {
1822
+ if (Array.isArray(value)) {
1823
+ for (const entry of value) inspectHostKeys(entry);
1824
+ return;
1825
+ }
1826
+ if (value === null || typeof value !== "object") return;
1827
+ for (const [key, child] of Object.entries(value)) {
1828
+ if (HOST_RESERVED_KEY.test(key)) throw new TypeError("Ceal Host observation cannot restate Gateway-owned facts.");
1829
+ inspectHostKeys(child);
1830
+ }
1831
+ }
1832
+
1621
1833
  // packages/ceal-client-protocol/src/host-observation.ts
1622
1834
  var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
1623
1835
  var HOST_OBSERVATION_PRODUCER = /^[a-z][a-z0-9]{0,31}$/u;
@@ -1664,35 +1876,238 @@ function safeCount(value) {
1664
1876
  return Number.isSafeInteger(value) && Number(value) >= 0;
1665
1877
  }
1666
1878
  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);
1879
+ const record2 = operationRecord(value, "Ceal Host observation draft is invalid.");
1880
+ requirePrefixedRef(record2.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1881
+ requireClosedValue(record2.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1882
+ requireIsoTimestamp(record2.observed_at, "Ceal Host observation time is invalid.");
1883
+ assertHostObservationValue(record2.value, record2.observation_kind);
1672
1884
  }
1673
- var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1674
1885
  var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
1675
1886
  function isCealHostPromptObservationValue(value) {
1676
1887
  return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
1677
1888
  }
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
1889
  function assertHostObservationValue(value, kind) {
1680
1890
  if (value === void 0) invalid("Ceal Host observation value is invalid.");
1681
1891
  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);
1892
+ validateCealHostObservationValue(value);
1685
1893
  }
1686
- function inspectHostKeys(value) {
1687
- if (Array.isArray(value)) {
1688
- for (const entry of value) inspectHostKeys(entry);
1894
+
1895
+ // packages/ceal-client-protocol/src/host-usage-facts.ts
1896
+ import { createHash as createHash3 } from "node:crypto";
1897
+ var CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION = "ceal.host_usage_batch.v1";
1898
+ var CEAL_HOST_USAGE_BATCH_REF_PREFIX = "host-usage-batch:";
1899
+ var CEAL_HOST_USAGE_INGRESS_PATH = "/api/ceal/v2/host-usage-batches";
1900
+ var CEAL_HOST_USAGE_BATCH_MAX_BYTES = 1024 * 1024;
1901
+ var CEAL_HOST_USAGE_FACT_MAX_BYTES = 64 * 1024;
1902
+ var CEAL_HOST_USAGE_BATCH_MAX_FACTS = 256;
1903
+ var CEAL_HOST_USAGE_BATCH_MAX_GAPS = 16;
1904
+ var CEAL_HOST_USAGE_BATCH_ACK_STATUS = 204;
1905
+ var CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES = 65;
1906
+ var CODEX_COUNTER_SEMANTICS = ["last_delta_total_cumulative", "total_cumulative_only", "unknown"];
1907
+ var CODEX_CUMULATIVE_TRANSITIONS = ["baseline", "advanced", "same", "reset_or_correction", "not_observed"];
1908
+ var HOST_USAGE_COVERAGE_GAP_REASONS = ["source_usage_unavailable", "source_file_replaced", "source_file_retired", "outbox_capacity", "unsupported_source_shape"];
1909
+ function createCealHostUsageBatch(input) {
1910
+ const body = { schema_version: CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION, ...input };
1911
+ const batch = { ...body, batch_ref: `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}` };
1912
+ validateCealHostUsageBatch(batch);
1913
+ return batch;
1914
+ }
1915
+ function validateCealHostUsageBatch(value) {
1916
+ if (!isOperationRecord(value)) invalid("Ceal Host usage batch is invalid.");
1917
+ requireExactOperationKeys(value, ["schema_version", "batch_ref", "host_source_ref", "host_session_ref", "created_at", "source_ranges", "facts", "coverage_gaps"]);
1918
+ 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.");
1919
+ const { batch_ref: _ref, ...body } = value;
1920
+ if (value.batch_ref !== `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}`) invalid("Ceal Host usage batch reference is invalid.");
1921
+ validateBatchMetadata(value);
1922
+ validateBatchContents(value);
1923
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_BATCH_MAX_BYTES) invalid("Ceal Host usage batch exceeds its byte limit.");
1924
+ }
1925
+ function validateBatchMetadata(value) {
1926
+ requireSafeRef2(value.host_source_ref, "Ceal Host usage source is invalid.");
1927
+ requireSafeRef2(value.host_session_ref, "Ceal Host usage session is invalid.");
1928
+ requireIsoTimestamp(value.created_at, "Ceal Host usage batch time is invalid.");
1929
+ 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.");
1930
+ for (const range of value.source_ranges) validateSourceRange(range);
1931
+ }
1932
+ function validateBatchContents(value) {
1933
+ const facts = validateBatchFacts(value.facts);
1934
+ const gaps = validateBatchGaps(value.coverage_gaps);
1935
+ if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
1936
+ const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
1937
+ for (const fact of facts) {
1938
+ validateFact(fact, value.host_session_ref);
1939
+ if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
1940
+ }
1941
+ for (const gap of gaps) {
1942
+ validateCoverageGap(gap);
1943
+ if (gap.source_file_ref !== null && !sourceFiles.has(gap.source_file_ref)) invalid("Ceal Host usage coverage gap is outside its source ranges.");
1944
+ }
1945
+ }
1946
+ function validateBatchFacts(value) {
1947
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_FACTS) invalid("Ceal Host usage fact count is invalid.");
1948
+ return value;
1949
+ }
1950
+ function validateBatchGaps(value) {
1951
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) invalid("Ceal Host usage coverage is invalid.");
1952
+ return value;
1953
+ }
1954
+ function sourceRangeFileRef(value) {
1955
+ return isOperationRecord(value) ? value.source_file_ref : null;
1956
+ }
1957
+ function hostUsageFactReference(sourceFileRef, sourceEventRef) {
1958
+ requireSafeRef2(sourceFileRef, "Ceal Host usage file reference is invalid.");
1959
+ requireSafeRef2(sourceEventRef, "Ceal Host usage event reference is invalid.");
1960
+ return `host-usage-fact:${sha256(JSON.stringify({ source_file_ref: sourceFileRef, source_event_ref: sourceEventRef }))}`;
1961
+ }
1962
+ function hostUsageSourceEventReference(sourceFileRef, sourceEventIdentity) {
1963
+ requireSafeRef2(sourceFileRef, "Ceal Host usage file reference is invalid.");
1964
+ if (typeof sourceEventIdentity !== "string" || sourceEventIdentity.length === 0 || sourceEventIdentity.length > 1024) invalid("Ceal Host usage event identity is invalid.");
1965
+ return `host-source-event:${sha256(JSON.stringify({ source_file_ref: sourceFileRef, source_event_identity: sourceEventIdentity }))}`;
1966
+ }
1967
+ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, device, inode) {
1968
+ 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.");
1969
+ return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
1970
+ }
1971
+ function validateFact(value, sessionRef) {
1972
+ if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
1973
+ requireFactByteLimit(value);
1974
+ if (value.producer === "codex_transcript") validateCodexFact(value);
1975
+ else if (value.producer === "claude_transcript") validateClaudeFact(value);
1976
+ else invalid("Ceal Host usage producer is invalid.");
1977
+ if (value.host_session_ref !== sessionRef) invalid("Ceal Host usage session does not match its batch.");
1978
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage file reference is invalid.");
1979
+ requireSafeRef2(value.source_event_ref, "Ceal Host usage event reference is invalid.");
1980
+ if (value.host_turn_ref !== null) requireSafeRef2(value.host_turn_ref, "Ceal Host usage turn reference is invalid.");
1981
+ if (value.requested_model !== null && !boundedText(value.requested_model, 256)) invalid("Ceal Host requested model is invalid.");
1982
+ if (value.reported_model !== null && !boundedText(value.reported_model, 256)) invalid("Ceal Host reported model is invalid.");
1983
+ if (value.fact_ref !== hostUsageFactReference(value.source_file_ref, value.source_event_ref)) invalid("Ceal Host usage identity is invalid.");
1984
+ }
1985
+ function requireFactByteLimit(value) {
1986
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_FACT_MAX_BYTES) invalid("Ceal Host usage fact exceeds its byte limit.");
1987
+ }
1988
+ function validateCodexFact(value) {
1989
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fact is invalid.");
1990
+ 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"]);
1991
+ if (value.producer !== "codex_transcript" || !safeInteger(value.source_event_ordinal)) invalid("Ceal Codex usage fact is invalid.");
1992
+ requireIsoTimestamp(value.observed_at, "Ceal Codex usage time is invalid.");
1993
+ if (!isOperationRecord(value.source_usage)) invalid("Ceal Codex source usage is invalid.");
1994
+ requireExactOperationKeys(value.source_usage, ["last_token_usage", "total_token_usage"]);
1995
+ if (value.source_usage.last_token_usage !== null) validateCodexUsageCounts(value.source_usage.last_token_usage);
1996
+ if (value.source_usage.total_token_usage !== null) validateCodexUsageCounts(value.source_usage.total_token_usage);
1997
+ 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.");
1998
+ validateNormalizedUsage(value.normalized_usage);
1999
+ }
2000
+ function validateClaudeFact(value) {
2001
+ if (!isOperationRecord(value)) invalid("Ceal Claude usage fact is invalid.");
2002
+ 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"]);
2003
+ validateClaudeIdentity(value);
2004
+ requireIsoTimestamp(value.observed_at, "Ceal Claude usage time is invalid.");
2005
+ validateClaudeSourceUsage(value.source_usage);
2006
+ validateClaudeSemantics(value);
2007
+ validateNormalizedUsage(value.normalized_usage);
2008
+ }
2009
+ function validateClaudeIdentity(value) {
2010
+ 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.");
2011
+ }
2012
+ function validateClaudeSourceUsage(value) {
2013
+ if (!isOperationRecord(value)) invalid("Ceal Claude source usage is invalid.");
2014
+ requireExactOperationKeys(value, ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"], ["cache_creation"]);
2015
+ for (const key of ["input_tokens", "output_tokens"]) if (!safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
2016
+ 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.");
2017
+ if (value.cache_creation !== void 0 && value.cache_creation !== null) validateClaudeCacheCreationUsage(value.cache_creation);
2018
+ }
2019
+ function validateClaudeCacheCreationUsage(value) {
2020
+ if (!isOperationRecord(value)) invalid("Ceal Claude cache creation usage is invalid.");
2021
+ requireExactOperationKeys(value, ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]);
2022
+ 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.");
2023
+ }
2024
+ function validateClaudeSemantics(value) {
2025
+ if (value.counter_semantics !== "assistant_message" || !validClaudeFinality(value.finality) || value.child_inclusion !== "unknown" || !validCorrectionSemantics(value.correction_semantics)) invalid("Ceal Claude usage semantics are invalid.");
2026
+ }
2027
+ function validClaudeFinality(value) {
2028
+ return value === "terminal" || value === "nonterminal" || value === "unknown";
2029
+ }
2030
+ function validCorrectionSemantics(value) {
2031
+ return value === "not_observed" || value === "unknown";
2032
+ }
2033
+ function validateCodexUsageCounts(value) {
2034
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
2035
+ requireExactOperationKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
2036
+ for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
2037
+ 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.");
2038
+ }
2039
+ function validateNormalizedUsage(value) {
2040
+ if (!isOperationRecord(value)) invalid("Ceal normalized Host usage is invalid.");
2041
+ requireExactOperationKeys(value, ["input", "output", "total", "cached_input", "cache_write_input", "reasoning_output"]);
2042
+ for (const key of Object.keys(value)) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal normalized Host usage is invalid.");
2043
+ validateNormalizedTotals(value);
2044
+ }
2045
+ function validateNormalizedTotals(value) {
2046
+ validateNormalizedCountTotal(value);
2047
+ validateNormalizedInputSubsets(value);
2048
+ validateNormalizedOutputSubset(value);
2049
+ }
2050
+ function validateNormalizedCountTotal(value) {
2051
+ 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.");
2052
+ }
2053
+ function validateNormalizedInputSubsets(value) {
2054
+ 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.");
2055
+ }
2056
+ function validateNormalizedOutputSubset(value) {
2057
+ if (value.output !== null && value.reasoning_output !== null && Number(value.reasoning_output) > Number(value.output)) invalid("Ceal normalized Host output subset is inconsistent.");
2058
+ }
2059
+ function validateSourceRange(value) {
2060
+ if (!isOperationRecord(value)) invalid("Ceal Host usage source range is invalid.");
2061
+ requireExactOperationKeys(value, ["source_file_ref", "start_offset", "end_offset"]);
2062
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage source-file reference is invalid.");
2063
+ 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.");
2064
+ }
2065
+ function validateCealHostUsageCoverageGap(value) {
2066
+ if (!isOperationRecord(value)) invalid("Ceal Host usage coverage gap is invalid.");
2067
+ requireExactOperationKeys(value, ["reason", "source_file_ref", "start_offset", "end_offset", "omitted_count"]);
2068
+ if (!isOneOf(HOST_USAGE_COVERAGE_GAP_REASONS, value.reason) || !validUsageGapCount(value.reason, value.omitted_count)) invalid("Ceal Host usage coverage gap is invalid.");
2069
+ if (value.source_file_ref === null) {
2070
+ if (value.start_offset !== null || value.end_offset !== null) invalid("Ceal Host usage coverage gap range is invalid.");
1689
2071
  return;
1690
2072
  }
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);
2073
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage coverage file reference is invalid.");
2074
+ 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.");
2075
+ }
2076
+ function validateCoverageGap(value) {
2077
+ validateCealHostUsageCoverageGap(value);
2078
+ }
2079
+ function validUsageGapCount(reason, value) {
2080
+ return value === null ? reason !== "outbox_capacity" : safeInteger(value) && Number(value) >= 1;
2081
+ }
2082
+ function isOneOf(values, value) {
2083
+ return typeof value === "string" && values.some((candidate) => candidate === value);
2084
+ }
2085
+ function isCealHostUsageBatchReference(value) {
2086
+ return typeof value === "string" && value.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX) && isCealDigest(value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length));
2087
+ }
2088
+ function cealHostUsageBatchObjectDigestFromFileName(value) {
2089
+ if (!value.endsWith(".json")) return null;
2090
+ const digest2 = value.slice(0, -5);
2091
+ return isCealDigest(digest2) ? digest2 : null;
2092
+ }
2093
+ function cealHostUsageBatchObjectDigestFromReference(value) {
2094
+ return isCealHostUsageBatchReference(value) ? value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length) : null;
2095
+ }
2096
+ function safeInteger(value) {
2097
+ return Number.isSafeInteger(value) && Number(value) >= 0;
2098
+ }
2099
+ function boundedText(value, maximum) {
2100
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters(value);
2101
+ }
2102
+ function hasControlCharacters(value) {
2103
+ for (const character of value) {
2104
+ const code = character.codePointAt(0);
2105
+ if (code !== void 0 && (code < 32 || code === 127)) return true;
1695
2106
  }
2107
+ return false;
2108
+ }
2109
+ function sha256(value) {
2110
+ return createHash3("sha256").update(value, "utf8").digest("hex");
1696
2111
  }
1697
2112
 
1698
2113
  // packages/ceal-client-protocol/src/host-prompt-ref.ts
@@ -1799,11 +2214,72 @@ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSch
1799
2214
  var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
1800
2215
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
1801
2216
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
2217
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.refusal_schema_name, fields: hostInvocationAuthenticationContract.refusal_fields });
1802
2218
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
1803
2219
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
1804
2220
  var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
1805
2221
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
2222
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
1806
2223
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
2224
+ function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
2225
+ const messages = [];
2226
+ let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
2227
+ for (const candidate of newestFirst.slice(0, CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES)) {
2228
+ 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 } : {} };
2229
+ if (encodedMessageWindowBytes([...messages, complete]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) {
2230
+ messages.push(Object.freeze(complete));
2231
+ continue;
2232
+ }
2233
+ const clipped = clipHumanMessageToWindow(messages, candidate);
2234
+ if (clipped === null) {
2235
+ truncated = true;
2236
+ break;
2237
+ }
2238
+ messages.push(Object.freeze(clipped));
2239
+ }
2240
+ return Object.freeze({ messages: Object.freeze(messages), truncated });
2241
+ }
2242
+ function encodedMessageWindowBytes(messages) {
2243
+ return new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2244
+ }
2245
+ function clipHumanMessageToWindow(prefix, candidate) {
2246
+ const clipped = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: "", text_truncated: true };
2247
+ const available = CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES - encodedMessageWindowBytes([...prefix, clipped]);
2248
+ if (available < 0) return null;
2249
+ const text = [];
2250
+ let used = 0;
2251
+ for (const point of candidate.text) {
2252
+ const encodedPoint = JSON.stringify(point);
2253
+ const cost = new TextEncoder().encode(encodedPoint).byteLength - 2;
2254
+ if (used + cost > available) break;
2255
+ text.push(point);
2256
+ used += cost;
2257
+ }
2258
+ const result = { ...clipped, text: text.join("") };
2259
+ return encodedMessageWindowBytes([...prefix, result]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES ? result : null;
2260
+ }
2261
+ function decodeCealHostInvocationHumanMessageWindow(value) {
2262
+ 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();
2263
+ const messages = value.messages.map(decodeHumanMessage);
2264
+ const bytes = new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2265
+ if (bytes > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) throw invalidInvocationContextRequest();
2266
+ return Object.freeze({ messages: Object.freeze(messages), truncated: value.truncated });
2267
+ }
2268
+ function decodeHumanMessage(candidate) {
2269
+ 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();
2270
+ if (candidate.text_truncated !== void 0 && candidate.text_truncated !== true) throw invalidInvocationContextRequest();
2271
+ 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 } : {} });
2272
+ }
2273
+ function safeReference(value) {
2274
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
2275
+ }
2276
+ function exactOptionalKeys(value, required, optional = []) {
2277
+ const keys = Object.keys(value);
2278
+ return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => required.includes(key) || optional.includes(key));
2279
+ }
2280
+ function invalidInvocationContextRequest() {
2281
+ return new TypeError("The Host invocation context request is invalid.");
2282
+ }
1807
2283
  function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1808
2284
  const clientNonce = contract.host_invocation_authentication.client_nonce;
1809
2285
  return {
@@ -1813,31 +2289,11 @@ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTR
1813
2289
  };
1814
2290
  }
1815
2291
  var hostNonceContract = deriveCealHostInvocationNonceContract();
1816
- var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
1817
2292
  var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
1818
2293
  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
2294
  var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
1833
2295
  "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"
2296
+ "request_creation_refused"
1841
2297
  ]);
1842
2298
  var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1843
2299
  "invalid_arguments",
@@ -1846,7 +2302,6 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1846
2302
  "context_unavailable",
1847
2303
  "context_replaced",
1848
2304
  "no_binding",
1849
- "context_stale",
1850
2305
  "context_expired",
1851
2306
  "host_source_refused",
1852
2307
  "host_credential_refused",
@@ -1863,31 +2318,42 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1863
2318
  "relay_failed",
1864
2319
  "host_refusal_invalid"
1865
2320
  ]);
2321
+ var CEAL_HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2322
+ "permission_denied",
2323
+ "socket_missing",
2324
+ "connection_refused",
2325
+ "closed_early",
2326
+ "response_invalid",
2327
+ "timed_out",
2328
+ "cancelled",
2329
+ "unavailable"
2330
+ ]);
1866
2331
  var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1867
2332
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
1868
2333
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
1869
2334
  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" }),
2335
+ // This reason cannot distinguish a Codex side conversation from a missing
2336
+ // context in a regular session, so guidance must leave that choice to the caller.
2337
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
1871
2338
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1872
2339
  // `no_binding` now means the producer has no real current Host session. The
1873
2340
  // Host Relay never uses it for an uncreated Gateway Request; there is no
1874
2341
  // useful retry until the consumer is running inside a Host session.
1875
2342
  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
2343
  context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
1878
2344
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
1879
2345
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
1880
2346
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
1881
2347
  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" }),
1883
- gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
2348
+ contract_mismatch: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2349
+ gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "upgrade_ceal_client" }),
1884
2350
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
1885
2351
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
1886
2352
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
1887
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2353
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
1888
2354
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
1889
2355
  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" }),
2356
+ relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
1891
2357
  host_refusal_invalid: Object.freeze({ classification: "host_refusal_invalid", next_action: "answer_with_gap" })
1892
2358
  });
1893
2359
 
@@ -1901,10 +2367,13 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
1901
2367
  "activation_recorded",
1902
2368
  "activation_failed",
1903
2369
  "watcher_scan_failed",
2370
+ "usage_capture_failed",
2371
+ "usage_upload_failed",
1904
2372
  "activation_wait_skipped",
1905
2373
  "activation_wait_engaged",
1906
2374
  "activation_wait_completed",
1907
- "activation_wait_exhausted"
2375
+ "activation_wait_exhausted",
2376
+ "invocation_authentication_failed"
1908
2377
  ]);
1909
2378
  var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1910
2379
  "malformed_line",
@@ -1914,6 +2383,17 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1914
2383
  "size_budget",
1915
2384
  "symlink"
1916
2385
  ]);
2386
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_WATCHER_OPTIONAL_FIELDS = vocabulary(["failure_kind", "cause"]);
2387
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_OPTIONAL_FIELDS = vocabulary(["cause"]);
2388
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE = "^[a-z][a-z0-9_]{0,63}(?::[A-Za-z][A-Za-z0-9_]{0,63})?$";
2389
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES = Object.freeze([
2390
+ ...CEAL_HOST_AUTHENTICATION_CAUSES,
2391
+ ...CEAL_HOST_RELAY_EXCHANGE_FAILURES.map((failure) => `relay_exchange:${failure}`)
2392
+ ]);
2393
+ var hostServiceDiagnosticCausePattern = new RegExp(CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE, "u");
2394
+ function isCealHostServiceDiagnosticCause(value, event) {
2395
+ return typeof value === "string" && hostServiceDiagnosticCausePattern.test(value) && (event !== "invocation_authentication_failed" || CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES.includes(value));
2396
+ }
1917
2397
 
1918
2398
  // packages/ceal-client-protocol/src/client-result-materialization.ts
1919
2399
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
@@ -2000,12 +2480,14 @@ var ADMIN_SOURCE_OWNERS = vocabulary([
2000
2480
  "resource",
2001
2481
  "prompt",
2002
2482
  "usage",
2483
+ "provider_request_lifecycle",
2003
2484
  "connector",
2004
2485
  "session",
2005
2486
  "knowledge",
2006
2487
  "policy"
2007
2488
  ]);
2008
2489
  var ADMIN_COMPLETENESS_STATES = vocabulary(["complete", "partial", "unknown"]);
2490
+ var ADMIN_PROVIDER_REQUEST_CAPTURE_HEALTH_STATES = vocabulary(["available", "missing", "invalid", "unreadable"]);
2009
2491
  var ADMIN_OPERATION_OUTCOMES = vocabulary(["completed", "failed", "denied", "cancelled", "unknown"]);
2010
2492
  var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
2011
2493
  var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
@@ -2027,7 +2509,7 @@ var AUDIT_IDENTITY_KEYS = Object.freeze(["event_ref", "membership_ref", "registr
2027
2509
  var FAILURE_RESPONSE_KEYS = Object.freeze(["error", "ok", "proof_ref_or_unavailable", "protocol_version", "request_id"]);
2028
2510
 
2029
2511
  // host/codex/src/codex-decoder.ts
2030
- import { createHash as createHash3 } from "node:crypto";
2512
+ import { createHash as createHash4 } from "node:crypto";
2031
2513
  import { isAbsolute, resolve } from "node:path";
2032
2514
 
2033
2515
  // host/codex/src/codex-types.ts
@@ -2073,15 +2555,15 @@ function hostInputReference(sourceRef, sessionRef, nativeTurnId, messageId, ordi
2073
2555
  if (![sourceRef, sessionRef, nativeTurnId, messageId].every((value) => SAFE_REF2.test(value)) || !Number.isSafeInteger(ordinal) || ordinal < 0) {
2074
2556
  throw new CodexHostAdapterError("invalid_input", "Codex input identity is invalid.");
2075
2557
  }
2076
- return `codex-input:${shortDigest({ source_ref: sourceRef, session_ref: sessionRef, native_turn_id: nativeTurnId, message_id: messageId, ordinal, prompt_sha256: sha256(prompt) })}`;
2558
+ return `codex-input:${shortDigest({ source_ref: sourceRef, session_ref: sessionRef, native_turn_id: nativeTurnId, message_id: messageId, ordinal, prompt_sha256: sha2562(prompt) })}`;
2077
2559
  }
2078
2560
  function promptObservationValue(prompt) {
2079
- return { body_sha256: sha256(prompt) };
2561
+ return { body_sha256: sha2562(prompt) };
2080
2562
  }
2081
2563
  function sessionObservationValue(event, environment = { operating_system: process.platform, architecture: process.arch }) {
2082
2564
  const value = {
2083
2565
  host_kind: "codex",
2084
- session_id_sha256: sha256(event.session_id),
2566
+ session_id_sha256: sha2562(event.session_id),
2085
2567
  host_version: { status: "not_recorded" },
2086
2568
  operating_system: environment.operating_system,
2087
2569
  architecture: environment.architecture,
@@ -2092,7 +2574,7 @@ function sessionObservationValue(event, environment = { operating_system: proces
2092
2574
  return value;
2093
2575
  }
2094
2576
  function turnObservationValue(sessionId, turnRef, status) {
2095
- return { status, host_session_id_sha256: sha256(sessionId), host_turn_ref: turnRef };
2577
+ return { status, host_session_id_sha256: sha2562(sessionId), host_turn_ref: turnRef };
2096
2578
  }
2097
2579
  function decodeSession(input, event) {
2098
2580
  exactKeys(input, ["cwd", "hook_event_name", "model", "permission_mode", "session_id", "source", "transcript_path"], []);
@@ -2154,8 +2636,8 @@ function validateHookEventName(input, event) {
2154
2636
  function isRecord(value) {
2155
2637
  return value !== null && typeof value === "object" && !Array.isArray(value);
2156
2638
  }
2157
- function sha256(value) {
2158
- return createHash3("sha256").update(value, "utf8").digest("hex");
2639
+ function sha2562(value) {
2640
+ return createHash4("sha256").update(value, "utf8").digest("hex");
2159
2641
  }
2160
2642
  function shortDigest(value) {
2161
2643
  return cealRequestSha256(value);
@@ -2165,8 +2647,8 @@ function reject(message) {
2165
2647
  }
2166
2648
 
2167
2649
  // 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";
2650
+ import { mkdir as mkdir4, open as open4, readdir, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
2651
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join4 } from "node:path";
2170
2652
 
2171
2653
  // host/invocation-context.ts
2172
2654
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2234,13 +2716,13 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2234
2716
  ];
2235
2717
 
2236
2718
  // host/relay/src/host-producer-core.ts
2237
- import { createHash as createHash4 } from "node:crypto";
2719
+ import { createHash as createHash5 } from "node:crypto";
2238
2720
 
2239
2721
  // host/secure-file.ts
2240
2722
  import { execFile } from "node:child_process";
2241
2723
  import { constants } from "node:fs";
2242
2724
  import { lstat, open } from "node:fs/promises";
2243
- import { dirname, win32 } from "node:path";
2725
+ import { dirname, join as join2, win32 } from "node:path";
2244
2726
  import { fileURLToPath } from "node:url";
2245
2727
  var SecureFileCustodyError = class extends Error {
2246
2728
  name = "SecureFileCustodyError";
@@ -2258,6 +2740,7 @@ var SecureFileCustodyError = class extends Error {
2258
2740
  }
2259
2741
  };
2260
2742
  var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
2743
+ var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
2261
2744
  var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
2262
2745
  var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
2263
2746
  function secureOpenFlags(flags, platform) {
@@ -2300,18 +2783,46 @@ async function assertWindowsIdentityStable(handle, first, path) {
2300
2783
  }
2301
2784
  async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
2302
2785
  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);
2786
+ const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2304
2787
  if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
2305
2788
  if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
2306
2789
  if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
2307
2790
  throw securefsRefusal(result.stderr);
2308
2791
  }
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();
2792
+ async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
2793
+ const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
2794
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2795
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
2796
+ throw securefsRefusal(result.stderr);
2797
+ }
2798
+ async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
2799
+ 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.");
2800
+ const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
2801
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2802
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
2803
+ throw securefsRefusal(result.stderr);
2804
+ }
2805
+ async function isPrivateWindowsDirectory(path, custody = {}) {
2806
+ await lstat(path);
2807
+ try {
2808
+ const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
2809
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
2810
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
2811
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
2812
+ const refusal = securefsRefusal(result.stderr);
2813
+ if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
2814
+ throw refusal;
2815
+ } catch (error) {
2816
+ if (error instanceof SecureFileCustodyError) throw error;
2817
+ throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
2818
+ }
2819
+ }
2820
+ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2821
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
2822
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2312
2823
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2313
2824
  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) => {
2825
+ const child = execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2315
2826
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2316
2827
  if (exitCode === null) {
2317
2828
  reject3(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2319,6 +2830,8 @@ async function runWindowsSecurefs(args, maxBytes, custody) {
2319
2830
  }
2320
2831
  resolve3({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
2321
2832
  });
2833
+ child.stdin?.on("error", () => void 0);
2834
+ child.stdin?.end(stdin);
2322
2835
  });
2323
2836
  }
2324
2837
  function securefsRefusal(stderr) {
@@ -2336,9 +2849,9 @@ function securefsRefusal(stderr) {
2336
2849
  if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
2337
2850
  return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
2338
2851
  }
2339
- function resolveInstalledHostExecutable() {
2852
+ function resolveInstalledHostExecutable(platform) {
2340
2853
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2341
- return win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
2854
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2342
2855
  }
2343
2856
  function isRecord3(value) {
2344
2857
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2354,6 +2867,11 @@ function isPrivateFileMode(mode, platform = process.platform, _handle) {
2354
2867
  if (platform === "win32") return false;
2355
2868
  return (mode & 63) === 0;
2356
2869
  }
2870
+ async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
2871
+ if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
2872
+ const entry = await lstat(path);
2873
+ return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
2874
+ }
2357
2875
 
2358
2876
  // host/relay/src/host-producer-core.ts
2359
2877
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
@@ -2362,7 +2880,22 @@ function isHostTranscriptCursorReason(value) {
2362
2880
  }
2363
2881
  var TRANSCRIPT_MISSING_REASON = "transcript_missing";
2364
2882
  var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
2365
- var HOST_INVOCATION_TRANSCRIPT_TAIL_MAX_BYTES = 1024 * 1024;
2883
+ var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
2884
+ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
2885
+ const seen = /* @__PURE__ */ new Set();
2886
+ const newestFirst = [];
2887
+ for (const message of [...chronological].reverse()) {
2888
+ if (seen.has(message.host_input_ref)) continue;
2889
+ seen.add(message.host_input_ref);
2890
+ newestFirst.push(message);
2891
+ }
2892
+ for (const message of existing?.messages ?? []) {
2893
+ if (seen.has(message.host_input_ref)) continue;
2894
+ seen.add(message.host_input_ref);
2895
+ newestFirst.push(message);
2896
+ }
2897
+ return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
2898
+ }
2366
2899
  function transcriptScanFailureKind(error, adapterFailureKind) {
2367
2900
  if (transcriptErrorCode(error) === "ELOOP") return "symlink";
2368
2901
  const adapter = adapterFailureKind(error);
@@ -2419,10 +2952,10 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
2419
2952
  return null;
2420
2953
  }
2421
2954
  function transcriptSha256(value) {
2422
- return createHash4("sha256").update(value).digest("hex");
2955
+ return createHash5("sha256").update(value).digest("hex");
2423
2956
  }
2424
2957
  function transcriptObjectSha256(value) {
2425
- return createHash4("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2958
+ return createHash5("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2426
2959
  }
2427
2960
  function isTranscriptRecord(value) {
2428
2961
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2540,44 +3073,1259 @@ var HostTranscriptWatcher = class {
2540
3073
  return transcriptCursorBoundsReason(handle, cursor, size);
2541
3074
  }
2542
3075
  };
2543
- var HostProducerDrainCore = class {
2544
- host;
2545
- now;
2546
- tail = Promise.resolve();
2547
- constructor(host, runtime) {
2548
- this.host = host;
2549
- this.now = runtime.now ?? (() => /* @__PURE__ */ new Date());
2550
- }
2551
- drainOutbox() {
2552
- const run = this.tail.then(() => this.drainLocked());
2553
- this.tail = run.then(() => void 0, () => void 0);
2554
- return run;
2555
- }
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);
3076
+ var HostProducerDrainCore = class {
3077
+ host;
3078
+ now;
3079
+ tail = Promise.resolve();
3080
+ constructor(host, runtime) {
3081
+ this.host = host;
3082
+ this.now = runtime.now ?? (() => /* @__PURE__ */ new Date());
3083
+ }
3084
+ drainOutbox() {
3085
+ const run = this.tail.then(() => this.drainLocked());
3086
+ this.tail = run.then(() => void 0, () => void 0);
3087
+ return run;
3088
+ }
3089
+ async drainLocked() {
3090
+ const read = await this.host.listEnvelopes();
3091
+ let removed = 0;
3092
+ let expired = 0;
3093
+ for (const envelope of read.entries) {
3094
+ if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
3095
+ else removed += 1;
3096
+ await this.host.removeEnvelope(envelope);
3097
+ }
3098
+ return { removed, expired, malformed: read.malformed };
3099
+ }
3100
+ };
3101
+
3102
+ // host/relay/src/durable-atomic-replacement.ts
3103
+ import { lstat as lstat2, mkdir, open as open2, rename, unlink } from "node:fs/promises";
3104
+ import { dirname as dirname2 } from "node:path";
3105
+
3106
+ // host/windows-rename-retry.ts
3107
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
3108
+ var RETRY_WINDOW_MS = 1e4;
3109
+ var RETRY_START_DELAY_MS = 100;
3110
+ var RETRY_MAX_DELAY_MS = 2e3;
3111
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
3112
+ var WindowsRenameRetryError = class extends Error {
3113
+ code = "rename_unavailable";
3114
+ constructor(target, attempts, options = {}) {
3115
+ 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);
3116
+ this.name = "WindowsRenameRetryError";
3117
+ }
3118
+ };
3119
+ function resolveRetrySchedule(tuning) {
3120
+ return {
3121
+ windowMs: tuning.windowMs ?? RETRY_WINDOW_MS,
3122
+ startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
3123
+ maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
3124
+ sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
3125
+ now: tuning.now ?? (() => Date.now())
3126
+ };
3127
+ }
3128
+ async function renameWithWindowsRetry(operation, tuning) {
3129
+ const schedule = resolveRetrySchedule(tuning);
3130
+ const deadline = schedule.now() + schedule.windowMs;
3131
+ let delayMs = schedule.startDelayMs;
3132
+ let attempts = 0;
3133
+ for (; ; ) {
3134
+ attempts += 1;
3135
+ try {
3136
+ await operation();
3137
+ return;
3138
+ } catch (error) {
3139
+ if (tuning.platform !== "win32" || !isRetryableRenameError(error)) throw error;
3140
+ await sleepWithinWindow(schedule, deadline, delayMs, () => new WindowsRenameRetryError(tuning.target, attempts, { cause: error }));
3141
+ delayMs = Math.min(delayMs * 2, schedule.maxDelayMs);
3142
+ }
3143
+ }
3144
+ }
3145
+ async function sleepWithinWindow(schedule, deadline, delayMs, exhausted) {
3146
+ if (schedule.now() >= deadline) throw exhausted();
3147
+ await schedule.sleep(Math.min(delayMs, deadline - schedule.now()));
3148
+ if (schedule.now() >= deadline) throw exhausted();
3149
+ }
3150
+ function isRetryableRenameError(error) {
3151
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && RETRYABLE_CODES.has(error.code);
3152
+ }
3153
+
3154
+ // host/relay/src/durable-atomic-replacement.ts
3155
+ var DEFAULT_PORT = {
3156
+ platform: process.platform,
3157
+ mkdir: (path, options) => mkdir(path, options),
3158
+ lstat: (path) => lstat2(path),
3159
+ open_file: (path) => open2(path, "wx", 384),
3160
+ rename,
3161
+ unlink,
3162
+ open_directory: (path) => open2(path),
3163
+ unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
3164
+ };
3165
+ async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
3166
+ const parent = dirname2(target);
3167
+ await port.mkdir(parent, { recursive: true, mode: 448 });
3168
+ const parentStats = await port.lstat(parent);
3169
+ const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
3170
+ const ownerPrivate = port.platform === "win32" || isOwnedBy(parentStats.uid, expectedUid) && isPrivateFileMode(parentStats.mode, port.platform);
3171
+ 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 }])}.`);
3172
+ const temporary = `${target}.${port.unique_ref()}.new`;
3173
+ let staged;
3174
+ const failures = [];
3175
+ try {
3176
+ staged = await port.open_file(temporary);
3177
+ await staged.writeFile(data, typeof data === "string" ? { encoding: "utf8" } : void 0);
3178
+ await staged.sync();
3179
+ const closing = staged;
3180
+ staged = void 0;
3181
+ await closing.close();
3182
+ await renameWithWindowsRetry(() => port.rename(temporary, target), { ...port.rename_retry, platform: port.platform, target });
3183
+ await syncParentDirectory(parent, port);
3184
+ } catch (error) {
3185
+ failures.push(error);
3186
+ }
3187
+ await closeStaged(staged, failures);
3188
+ await removeTemporary(temporary, port, failures);
3189
+ throwFailures(failures);
3190
+ }
3191
+ async function syncParentDirectory(path, port) {
3192
+ if (port.platform === "win32") return;
3193
+ const handle = await port.open_directory(path);
3194
+ let failure;
3195
+ try {
3196
+ await handle.sync();
3197
+ } catch (error) {
3198
+ if (!directorySyncUnsupported(error)) failure = error;
3199
+ }
3200
+ try {
3201
+ await handle.close();
3202
+ } catch (error) {
3203
+ if (failure === void 0) failure = error;
3204
+ else failure = new AggregateError([failure, error], "Host Relay directory sync and close failed.");
3205
+ }
3206
+ if (failure !== void 0) throw failure;
3207
+ }
3208
+ async function closeStaged(staged, failures) {
3209
+ if (staged !== void 0) try {
3210
+ await staged.close();
3211
+ } catch (error) {
3212
+ failures.push(error);
3213
+ }
3214
+ }
3215
+ async function removeTemporary(path, port, failures) {
3216
+ try {
3217
+ await port.unlink(path);
3218
+ } catch (error) {
3219
+ if (errorCode(error) !== "ENOENT") failures.push(error);
3220
+ }
3221
+ }
3222
+ function throwFailures(failures) {
3223
+ if (failures.length === 1) throw failures[0];
3224
+ if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
3225
+ }
3226
+ function directorySyncUnsupported(error) {
3227
+ return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
3228
+ }
3229
+ function errorCode(error) {
3230
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3231
+ }
3232
+
3233
+ // host/relay/src/host-usage-facts-store.ts
3234
+ import { createHash as createHash6 } from "node:crypto";
3235
+ import { constants as constants2 } from "node:fs";
3236
+ import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3237
+ import { dirname as dirname3, join as join3 } from "node:path";
3238
+ var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3239
+ var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3240
+ var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
3241
+ var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
3242
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
3243
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
3244
+ var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
3245
+ var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
3246
+ var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
3247
+ var HostUsageFactsStore = class {
3248
+ root;
3249
+ sessions;
3250
+ batches;
3251
+ platform;
3252
+ custody;
3253
+ afterPendingWrite;
3254
+ afterBatchPublish;
3255
+ sessionDirectoryCursor;
3256
+ constructor(options) {
3257
+ this.root = join3(options.outbox_dir, "usage-facts");
3258
+ this.sessions = join3(this.root, "sessions");
3259
+ this.batches = join3(this.root, "batches");
3260
+ this.platform = options.platform ?? process.platform;
3261
+ this.custody = options.secure_file_custody ?? {};
3262
+ this.afterPendingWrite = options.afterPendingWrite;
3263
+ this.afterBatchPublish = options.afterBatchPublish;
3264
+ }
3265
+ async prepare() {
3266
+ for (const directory of [this.root, this.sessions, this.batches]) {
3267
+ await preparePrivateDirectory(directory, this.platform, this.custody);
3268
+ }
3269
+ }
3270
+ async close() {
3271
+ const cursor = this.sessionDirectoryCursor;
3272
+ this.sessionDirectoryCursor = void 0;
3273
+ await cursor?.close();
3274
+ }
3275
+ async readState(producer, hostSourceRef, hostSessionRef) {
3276
+ await this.prepare();
3277
+ const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3278
+ const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3279
+ if (value === null) return null;
3280
+ validateState(value, producer, hostSourceRef, hostSessionRef);
3281
+ return value;
3282
+ }
3283
+ createState(producer, hostSourceRef, hostSessionRef) {
3284
+ return {
3285
+ schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
3286
+ producer,
3287
+ host_source_ref: hostSourceRef,
3288
+ host_session_ref: hostSessionRef,
3289
+ cursors: {},
3290
+ eligible_batches: [],
3291
+ coverage_gaps: [],
3292
+ coverage_gap_created_at: null
3293
+ };
3294
+ }
3295
+ async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
3296
+ let state = await this.readState(producer, hostSourceRef, hostSessionRef);
3297
+ if (state === null) {
3298
+ state = this.createState(producer, hostSourceRef, hostSessionRef);
3299
+ state = await this.writeCursor(state, sourceSlot, initial);
3300
+ }
3301
+ state = await this.recoverPending(state);
3302
+ if (state.quarantined_reason !== void 0) return null;
3303
+ state = await this.commitCoverageGaps(state, createdAt);
3304
+ const cursor = state.cursors[sourceSlot];
3305
+ return cursor === void 0 ? null : { state, cursor };
3306
+ }
3307
+ async writeCursor(state, sourceSlot, cursor) {
3308
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3309
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3310
+ if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
3311
+ const current = latest.cursors[sourceSlot];
3312
+ if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
3313
+ const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
3314
+ await this.writeState(updated);
3315
+ return updated;
3316
+ });
3317
+ }
3318
+ async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
3319
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3320
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3321
+ return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
3322
+ });
3323
+ }
3324
+ async recoverPending(state) {
3325
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3326
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3327
+ const recovered = await this.finishPendingTransition(latest);
3328
+ await this.sweepOrphanedBatches(recovered);
3329
+ return recovered;
3330
+ });
3331
+ }
3332
+ /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3333
+ async sweepOrphanedBatches(state) {
3334
+ await this.prepare();
3335
+ const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3336
+ await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3337
+ const expected = expectedBatchNames(state);
3338
+ const directory = await opendir(directoryPath);
3339
+ let inspected = 0;
3340
+ let deleted = 0;
3341
+ try {
3342
+ while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
3343
+ const entry = await directory.read();
3344
+ if (entry === null) break;
3345
+ inspected += 1;
3346
+ if (!isOrphanBatchEntry(entry, expected)) continue;
3347
+ await unlink2(join3(directoryPath, entry.name));
3348
+ deleted += 1;
3349
+ }
3350
+ } finally {
3351
+ await directory.close();
3352
+ }
3353
+ if (deleted > 0) await syncDirectory(directoryPath, this.platform);
3354
+ return deleted;
3355
+ }
3356
+ async commitCoverageGaps(state, createdAt) {
3357
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3358
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3359
+ if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
3360
+ const sourceRanges = coverageRanges(latest.coverage_gaps);
3361
+ const canonical = createCealHostUsageBatch({
3362
+ host_source_ref: latest.host_source_ref,
3363
+ host_session_ref: latest.host_session_ref,
3364
+ created_at: latest.coverage_gap_created_at ?? createdAt,
3365
+ source_ranges: sourceRanges,
3366
+ facts: [],
3367
+ coverage_gaps: latest.coverage_gaps
3368
+ });
3369
+ const cursor = firstCursor(latest);
3370
+ if (cursor === null) return latest;
3371
+ return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
3372
+ });
3373
+ }
3374
+ async nextUploadCandidate(producer, hostSourceRef) {
3375
+ await this.prepare();
3376
+ const names = await this.readNextSessionNames();
3377
+ for (const name of names) {
3378
+ const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3379
+ if (state === null) continue;
3380
+ validateStateOwner(state, producer, hostSourceRef);
3381
+ let validated = state;
3382
+ if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
3383
+ else validated = await this.recoverPending(validated);
3384
+ if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
3385
+ const next = validated.eligible_batches[0];
3386
+ if (next === void 0) continue;
3387
+ const batch = await this.readBatch(validated, next.batch_ref);
3388
+ return { state: validated, batch };
3389
+ }
3390
+ return null;
3391
+ }
3392
+ async readNextSessionNames() {
3393
+ this.sessionDirectoryCursor ??= await opendir(this.sessions);
3394
+ const names = [];
3395
+ let inspected = 0;
3396
+ while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
3397
+ const entry = await this.sessionDirectoryCursor.read();
3398
+ if (entry === null) {
3399
+ await this.sessionDirectoryCursor.close();
3400
+ this.sessionDirectoryCursor = void 0;
3401
+ break;
3402
+ }
3403
+ inspected += 1;
3404
+ if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
3405
+ }
3406
+ return names;
3407
+ }
3408
+ async acknowledge(state, batchRef) {
3409
+ await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3410
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3411
+ if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
3412
+ const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
3413
+ if (remaining.length === latest.eligible_batches.length) return;
3414
+ await this.writeState({ ...latest, eligible_batches: remaining });
3415
+ await removeFileIfPresent(this.batchPath(state, batchRef));
3416
+ });
3417
+ }
3418
+ async quarantine(state, reason) {
3419
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3420
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3421
+ const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
3422
+ await this.writeState(updated);
3423
+ return updated;
3424
+ });
3425
+ }
3426
+ async retireCursor(state, sourceSlot, cursor, gap) {
3427
+ return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
3428
+ }
3429
+ async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
3430
+ if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
3431
+ if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
3432
+ const queued = await this.publishTransitionBatch(state, batch);
3433
+ const pending = {
3434
+ source_slot: sourceSlot,
3435
+ before_cursor: beforeCursor,
3436
+ after_cursor: afterCursor,
3437
+ batch_ref: queued.batch_ref,
3438
+ batch_bytes: queued.batch_bytes,
3439
+ gap_delta: [...gapDelta, ...queued.overflow_gaps],
3440
+ clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
3441
+ };
3442
+ const prepared = { ...state, pending_transition: pending };
3443
+ await this.writeState(prepared);
3444
+ await this.afterPendingWrite?.();
3445
+ return await this.finishPendingTransition(prepared);
3446
+ }
3447
+ async publishTransitionBatch(state, batch) {
3448
+ if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
3449
+ const serialized = serializeBatch(batch);
3450
+ if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
3451
+ await this.writeImmutableBatch(state, batch, serialized);
3452
+ await this.afterBatchPublish?.();
3453
+ return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
3454
+ }
3455
+ async finishPendingTransition(state) {
3456
+ const pending = state.pending_transition;
3457
+ if (pending === void 0 || state.quarantined_reason !== void 0) return state;
3458
+ const current = state.cursors[pending.source_slot];
3459
+ if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
3460
+ const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
3461
+ await this.writeState(quarantined);
3462
+ return quarantined;
3463
+ }
3464
+ let cursors = state.cursors;
3465
+ if (!cursorMatches(current, pending.after_cursor)) {
3466
+ const next = { ...state.cursors };
3467
+ if (pending.after_cursor === null) delete next[pending.source_slot];
3468
+ else next[pending.source_slot] = pending.after_cursor;
3469
+ cursors = next;
3470
+ }
3471
+ const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
3472
+ const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
3473
+ const { pending_transition: _pendingTransition, ...settledState } = state;
3474
+ const updated = {
3475
+ ...settledState,
3476
+ cursors,
3477
+ eligible_batches: eligible,
3478
+ coverage_gaps: gaps,
3479
+ coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
3480
+ };
3481
+ await this.writeState(updated);
3482
+ return updated;
3483
+ }
3484
+ async writeImmutableBatch(state, batch, bytes) {
3485
+ const path = this.batchPath(state, batch.batch_ref);
3486
+ await preparePrivateDirectory(dirname3(path), this.platform, this.custody);
3487
+ const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3488
+ if (existing !== null) {
3489
+ if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3490
+ await syncExistingFile(path, this.platform);
3491
+ return;
3492
+ }
3493
+ if (this.platform === "win32") {
3494
+ await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
3495
+ return;
3496
+ }
3497
+ let handle;
3498
+ try {
3499
+ handle = await openNoFollow(path, constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY, 384, this.platform);
3500
+ await handle.writeFile(bytes);
3501
+ await handle.sync();
3502
+ await handle.close();
3503
+ handle = void 0;
3504
+ await syncDirectory(dirname3(path), this.platform);
3505
+ } catch (error) {
3506
+ await handle?.close().catch(() => void 0);
3507
+ if (errorCode2(error) === "EEXIST") {
3508
+ const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3509
+ if (winner !== null && winner.equals(bytes)) {
3510
+ await syncExistingFile(path, this.platform);
3511
+ return;
3512
+ }
3513
+ throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3514
+ }
3515
+ await removeFileIfPresent(path).catch(() => void 0);
3516
+ throw error;
3517
+ }
3518
+ }
3519
+ async readBatch(state, batchRef) {
3520
+ const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3521
+ if (bytes === null) throw new Error("Host usage facts batch object is missing.");
3522
+ let value;
3523
+ try {
3524
+ value = JSON.parse(bytes.toString("utf8"));
3525
+ } catch {
3526
+ throw new Error("Host usage facts batch object is malformed.");
3527
+ }
3528
+ validateCealHostUsageBatch(value);
3529
+ if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
3530
+ return value;
3531
+ }
3532
+ async writeState(state) {
3533
+ validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
3534
+ const bytes = Buffer.from(JSON.stringify(state), "utf8");
3535
+ if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
3536
+ await this.prepare();
3537
+ const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
3538
+ if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
3539
+ else await durableAtomicReplace(path, bytes);
3540
+ }
3541
+ async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
3542
+ const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3543
+ const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
3544
+ let release;
3545
+ const gate = new Promise((resolve3) => {
3546
+ release = resolve3;
3547
+ });
3548
+ const tail = previous.then(() => gate);
3549
+ SESSION_TRANSITION_TAILS.set(key, tail);
3550
+ await previous;
3551
+ try {
3552
+ return await run();
3553
+ } finally {
3554
+ release?.();
3555
+ if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
3556
+ }
3557
+ }
3558
+ sessionPath(producer, hostSourceRef, hostSessionRef) {
3559
+ return join3(this.sessions, `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3560
+ }
3561
+ batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3562
+ const sessionName = `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3563
+ return join3(this.batches, sessionName.slice(0, -5));
3564
+ }
3565
+ batchPath(state, batchRef) {
3566
+ return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3567
+ }
3568
+ };
3569
+ function serializeBatch(batch) {
3570
+ validateCealHostUsageBatch(batch);
3571
+ return Buffer.from(JSON.stringify(batch), "utf8");
3572
+ }
3573
+ function batchFileName(batchRef) {
3574
+ const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
3575
+ if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
3576
+ return `${digest2}.json`;
3577
+ }
3578
+ function expectedBatchNames(state) {
3579
+ const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
3580
+ const pending = state.pending_transition?.batch_ref;
3581
+ if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
3582
+ return expected;
3583
+ }
3584
+ function isOrphanBatchEntry(entry, expected) {
3585
+ return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
3586
+ }
3587
+ function hasOutboxCapacity(state, bytes) {
3588
+ const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
3589
+ return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
3590
+ }
3591
+ function overflowCoverageGaps(batch) {
3592
+ const count = batch.facts.length;
3593
+ const gaps = [...batch.coverage_gaps];
3594
+ 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 });
3595
+ return gaps;
3596
+ }
3597
+ function appendEligible(existing, next) {
3598
+ if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
3599
+ if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
3600
+ return [...existing, next];
3601
+ }
3602
+ function appendCoverageGaps(existing, added) {
3603
+ if (added.length === 0) return existing;
3604
+ const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
3605
+ for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
3606
+ const combined = [...byIdentity.values()];
3607
+ if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
3608
+ const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
3609
+ return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
3610
+ }
3611
+ function coverageRanges(gaps) {
3612
+ const ranges = /* @__PURE__ */ new Map();
3613
+ for (const gap of gaps) {
3614
+ if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
3615
+ const current = ranges.get(gap.source_file_ref);
3616
+ 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 });
3617
+ 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) });
3618
+ }
3619
+ return [...ranges.values()];
3620
+ }
3621
+ function firstCursor(state) {
3622
+ const entry = Object.entries(state.cursors)[0];
3623
+ return entry === void 0 ? null : entry;
3624
+ }
3625
+ function sameCursor(left, right) {
3626
+ return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
3627
+ }
3628
+ function cursorMatches(left, right) {
3629
+ return right === null ? left === void 0 : sameCursor(left, right);
3630
+ }
3631
+ function validateState(value, producer, hostSourceRef, hostSessionRef) {
3632
+ validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
3633
+ validateStateShape(value);
3634
+ validateStateLimits(value);
3635
+ validateStateContents(value);
3636
+ }
3637
+ function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
3638
+ 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.");
3639
+ }
3640
+ function validateStateLimits(value) {
3641
+ 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.");
3642
+ }
3643
+ function validateStateContents(value) {
3644
+ for (const [slot, cursor] of Object.entries(value.cursors)) {
3645
+ validateSourceSlot(slot);
3646
+ validateFileCursor(cursor);
3647
+ }
3648
+ for (const item of value.eligible_batches) validateEligibleBatch(item);
3649
+ if (value.pending_transition !== void 0) validatePending(value.pending_transition);
3650
+ for (const gap of value.coverage_gaps) validateGap(gap);
3651
+ validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
3652
+ }
3653
+ function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
3654
+ if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
3655
+ if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
3656
+ }
3657
+ function validateStateOwner(value, producer, hostSourceRef) {
3658
+ if (!isRecord4(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
3659
+ validateState(value, producer, hostSourceRef, String(value.host_session_ref));
3660
+ }
3661
+ function validateStateShape(value) {
3662
+ const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
3663
+ const optional = ["pending_transition", "quarantined_reason"];
3664
+ 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.");
3665
+ 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.");
3666
+ }
3667
+ function validateFileCursor(value) {
3668
+ 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.");
3669
+ validateCursorIdentity(value);
3670
+ validateCursorOffsets(value);
3671
+ validateCursorContext(value);
3672
+ if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
3673
+ if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
3674
+ }
3675
+ function validateCursorIdentity(value) {
3676
+ 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.");
3677
+ }
3678
+ function validateCursorOffsets(value) {
3679
+ 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.");
3680
+ }
3681
+ function validateCursorContext(value) {
3682
+ 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.");
3683
+ }
3684
+ function validOptionalText(value, maximum) {
3685
+ return value === null || typeof value === "string" && value.length <= maximum;
3686
+ }
3687
+ function validateCodexCounts(value) {
3688
+ 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.");
3689
+ if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
3690
+ }
3691
+ function validatePending(value) {
3692
+ 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.");
3693
+ validatePendingCursors(value);
3694
+ validatePendingBatch(value);
3695
+ validatePendingFields(value);
3696
+ for (const gap of value.gap_delta) validateGap(gap);
3697
+ }
3698
+ function validatePendingCursors(value) {
3699
+ validateSourceSlot(value.source_slot);
3700
+ validateFileCursor(value.before_cursor);
3701
+ if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
3702
+ }
3703
+ function validatePendingBatch(value) {
3704
+ if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
3705
+ }
3706
+ function validatePendingFields(value) {
3707
+ 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.");
3708
+ }
3709
+ function validateEligibleBatch(value) {
3710
+ 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.");
3711
+ }
3712
+ function validateGap(value) {
3713
+ try {
3714
+ validateCealHostUsageCoverageGap(value);
3715
+ } catch {
3716
+ throw new Error("Host usage facts coverage gap is invalid.");
3717
+ }
3718
+ }
3719
+ function validateSourceSlot(value) {
3720
+ if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
3721
+ }
3722
+ async function readOptionalJson(path, maxBytes, platform, custody) {
3723
+ const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
3724
+ if (bytes === null) return null;
3725
+ try {
3726
+ return JSON.parse(bytes.toString("utf8"));
3727
+ } catch {
3728
+ throw new Error("Host usage facts state JSON is malformed.");
3729
+ }
3730
+ }
3731
+ async function readOptionalBytes(path, maxBytes, platform, custody) {
3732
+ if (platform === "win32") {
3733
+ try {
3734
+ return await readPrivateFileWithSecurefs(path, maxBytes, custody);
3735
+ } catch (error) {
3736
+ if (errorCode2(error) === "ENOENT") return null;
3737
+ throw error;
3738
+ }
3739
+ }
3740
+ let handle;
3741
+ try {
3742
+ handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
3743
+ const stats = await handle.stat();
3744
+ 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.");
3745
+ return await handle.readFile();
3746
+ } catch (error) {
3747
+ if (errorCode2(error) === "ENOENT") return null;
3748
+ throw error;
3749
+ } finally {
3750
+ await handle?.close();
3751
+ }
3752
+ }
3753
+ async function preparePrivateDirectory(path, platform, custody) {
3754
+ if (platform === "win32") {
3755
+ await ensurePrivateDirectoryWithSecurefs(path, custody);
3756
+ return;
3757
+ }
3758
+ await mkdir2(path, { recursive: true, mode: 448 });
3759
+ if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3760
+ }
3761
+ async function syncExistingFile(path, platform) {
3762
+ const handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
3763
+ try {
3764
+ await handle.sync();
3765
+ } finally {
3766
+ await handle.close();
3767
+ }
3768
+ await syncDirectory(dirname3(path), platform);
3769
+ }
3770
+ async function syncDirectory(path, platform) {
3771
+ if (platform === "win32") return;
3772
+ const handle = await open3(path, constants2.O_RDONLY);
3773
+ try {
3774
+ await handle.sync();
3775
+ } finally {
3776
+ await handle.close();
3777
+ }
3778
+ }
3779
+ async function removeFileIfPresent(path) {
3780
+ try {
3781
+ await unlink2(path);
3782
+ } catch (error) {
3783
+ if (errorCode2(error) !== "ENOENT") throw error;
3784
+ }
3785
+ }
3786
+ function sameKeys(value, expected) {
3787
+ return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
3788
+ }
3789
+ function isRecord4(value) {
3790
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3791
+ }
3792
+ function safeInteger2(value) {
3793
+ return Number.isSafeInteger(value) && Number(value) >= 0;
3794
+ }
3795
+ function validTimestamp(value) {
3796
+ return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
3797
+ }
3798
+ function errorCode2(error) {
3799
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3800
+ }
3801
+ function sha2563(value) {
3802
+ return createHash6("sha256").update(value, "utf8").digest("hex");
3803
+ }
3804
+
3805
+ // host/relay/src/host-usage-facts-capture.ts
3806
+ import { constants as constants3 } from "node:fs";
3807
+ var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
3808
+ var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
3809
+ var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
3810
+ var HostUsageTranscriptSourceError = class extends Error {
3811
+ constructor(options) {
3812
+ super("Host usage transcript source could not be read.", options);
3813
+ this.name = "HostUsageTranscriptSourceError";
3814
+ }
3815
+ };
3816
+ async function readHostUsageTranscriptSource(read) {
3817
+ try {
3818
+ return await read();
3819
+ } catch (error) {
3820
+ throw new HostUsageTranscriptSourceError({ cause: error });
3821
+ }
3822
+ }
3823
+ async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
3824
+ if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
3825
+ let failed = false;
3826
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
3827
+ const index = (startIndex + attempt) % registrations.length;
3828
+ const registration = registrations[index];
3829
+ if (registration === void 0) continue;
3830
+ try {
3831
+ if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
3832
+ } catch (error) {
3833
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
3834
+ failed = true;
3835
+ }
3836
+ }
3837
+ return { captured: false, nextIndex: startIndex, failed };
3838
+ }
3839
+ async function openHostUsageTranscriptCursor(input) {
3840
+ const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
3841
+ let source;
3842
+ try {
3843
+ source = await readHostUsageTranscriptSource(() => input.inspect(handle));
3844
+ } catch (error) {
3845
+ await handle.close().catch(() => void 0);
3846
+ throw error;
3847
+ }
3848
+ const sourceFileRef = hostUsageSourceFileReference(input.source_kind, input.host_source_ref, input.host_session_ref, source.device, source.inode);
3849
+ let prepared;
3850
+ try {
3851
+ 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);
3852
+ } catch (error) {
3853
+ await handle.close().catch(() => void 0);
3854
+ throw error;
3855
+ }
3856
+ if (prepared === null) {
3857
+ await handle.close();
3858
+ return null;
3859
+ }
3860
+ return { handle, source, source_file_ref: sourceFileRef, ...prepared };
3861
+ }
3862
+ async function readHostUsageTranscriptChunk(handle, offset, size, skippingOversizedLine) {
3863
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(size) || size < offset) throw new TypeError("Host usage transcript range is invalid.");
3864
+ if (size === offset) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
3865
+ if (skippingOversizedLine) return await resumeOversizedLine(handle, offset, size);
3866
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
3867
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
3868
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
3869
+ const chunk = bytes.subarray(0, bytesRead);
3870
+ return completeChunk(chunk, offset);
3871
+ }
3872
+ async function resumeOversizedLine(handle, offset, size) {
3873
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
3874
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
3875
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
3876
+ const chunk = bytes.subarray(0, bytesRead);
3877
+ const delimiter = chunk.indexOf(10);
3878
+ if (delimiter < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
3879
+ return completeChunk(chunk.subarray(delimiter + 1), offset + delimiter + 1);
3880
+ }
3881
+ function completeChunk(chunk, offset) {
3882
+ const parsed = completeLinePrefix(chunk, offset);
3883
+ const oversizedRows = parsed.oversizedRows + (parsed.incompleteOversized ? 1 : 0);
3884
+ const endOffset = parsed.incompleteOversized ? offset + chunk.length : parsed.endOffset;
3885
+ return { lines: parsed.lines, end_offset: endOffset, skipping_oversized_line: parsed.incompleteOversized, oversized_rows: oversizedRows };
3886
+ }
3887
+ function completeLinePrefix(bytes, baseOffset) {
3888
+ const lines = [];
3889
+ let lineStart = 0;
3890
+ let endOffset = baseOffset;
3891
+ let oversizedRows = 0;
3892
+ let rowCount = 0;
3893
+ for (let index = 0; index < bytes.length; index += 1) {
3894
+ if (bytes[index] !== 10) continue;
3895
+ const line = bytes.subarray(lineStart, index);
3896
+ if (line.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES) oversizedRows += 1;
3897
+ else lines.push(line);
3898
+ lineStart = index + 1;
3899
+ endOffset = baseOffset + lineStart;
3900
+ rowCount += 1;
3901
+ if (rowCount >= HOST_USAGE_FACTS_SCAN_MAX_ROWS) return { lines, endOffset, oversizedRows, incompleteOversized: false };
3902
+ }
3903
+ const incomplete = bytes.subarray(lineStart);
3904
+ return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
3905
+ }
3906
+
3907
+ // host/relay/src/host-registration-state.ts
3908
+ import { constants as constants4 } from "node:fs";
3909
+ import { dirname as dirname4 } from "node:path";
3910
+
3911
+ // host/runtime-source-paths.ts
3912
+ import { createHash as createHash7 } from "node:crypto";
3913
+ import { posix as posix2, win32 as win323 } from "node:path";
3914
+
3915
+ // host/absolute-path.ts
3916
+ import { posix, win32 as win322 } from "node:path";
3917
+ function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
3918
+ const pathApi = flavor === "win32" || flavor === "windows" ? win322 : posix;
3919
+ return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
3920
+ }
3921
+
3922
+ // host/unix-socket-path.ts
3923
+ var PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES = 103;
3924
+
3925
+ // host/runtime-source-paths.ts
3926
+ var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
3927
+ function hostSourceUuid(sourceRef) {
3928
+ return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
3929
+ }
3930
+ var DARWIN_UID_MAX = 4294967295;
3931
+ var MACOS_HOST_RELAY_IPC_ROOT_PREFIX = "/private/tmp/ceal-host-";
3932
+ function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
3933
+ if (!Number.isInteger(uid) || uid < 0 || uid > DARWIN_UID_MAX) throw new TypeError("Host runtime effective user identity is invalid.");
3934
+ return `${MACOS_HOST_RELAY_IPC_ROOT_PREFIX}${uid}`;
3935
+ }
3936
+ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
3937
+ const sourceId = hostSourceUuid(sourceRef);
3938
+ if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
3939
+ const path = platform === "win32" ? win323 : posix2;
3940
+ const sourcesRoot = path.join(stateRoot, "sources");
3941
+ const sourceRoot = path.join(sourcesRoot, sourceId);
3942
+ const runtimeRoot = path.join(stateRoot, "run");
3943
+ const rootedEndpoint = path.join(runtimeRoot, `${sourceId}.sock`);
3944
+ const endpoint = projectRelayEndpoint(stateRoot, sourceRef, rootedEndpoint, platform, uid);
3945
+ 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 };
3946
+ }
3947
+ function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
3948
+ if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
3949
+ const digest2 = createHash7("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
3950
+ return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix2.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
3951
+ }
3952
+ function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
3953
+ const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
3954
+ 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.");
3955
+ return paths.endpoint;
3956
+ }
3957
+
3958
+ // host/relay/src/host-registration-state.ts
3959
+ var HOST_REGISTRATION_STATE_SCHEMA = "ceal.host_registration_state.v1";
3960
+ var HOST_REGISTRATION_STATE_KEYS = Object.freeze([
3961
+ "credential_generation",
3962
+ "gateway_request_origin",
3963
+ "host_access_token",
3964
+ "host_installation_ref",
3965
+ "host_source_ref",
3966
+ "registration_attempt_ref",
3967
+ "schema_version",
3968
+ "status"
3969
+ ]);
3970
+ var HOST_REGISTRATION_STATE_MAX_BYTES = 65536;
3971
+ var HostRegistrationStateError = class extends Error {
3972
+ name = "HostRegistrationStateError";
3973
+ code = "credential";
3974
+ };
3975
+ async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
3976
+ let raw;
3977
+ try {
3978
+ await assertPrivateRegistrationDirectory(dirname4(path), platform, custody);
3979
+ raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
3980
+ } catch (error) {
3981
+ throw registrationReadError(error);
3982
+ }
3983
+ 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}`)}.`);
3984
+ let value;
3985
+ try {
3986
+ value = JSON.parse(raw);
3987
+ } catch {
3988
+ throw new HostRegistrationStateError("Host registration state is invalid.");
3989
+ }
3990
+ return decodeHostRegistrationAuthority(value, expectedHostSourceRef);
3991
+ }
3992
+ async function readWindowsRegistration(path, custody) {
3993
+ const bytes = await readPrivateFileWithSecurefs(path, HOST_REGISTRATION_STATE_MAX_BYTES, custody);
3994
+ try {
3995
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
3996
+ } catch {
3997
+ throw new HostRegistrationStateError("Host registration state is invalid.");
3998
+ }
3999
+ }
4000
+ async function readPosixRegistration(path, platform, custody) {
4001
+ const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform, custody);
4002
+ try {
4003
+ const stats = await handle.stat();
4004
+ 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.");
4005
+ return await handle.readFile("utf8");
4006
+ } finally {
4007
+ await handle.close();
4008
+ }
4009
+ }
4010
+ function registrationReadError(error) {
4011
+ if (error instanceof HostRegistrationStateError) return error;
4012
+ if (error instanceof SecureFileCustodyError && error.reason === "not_private") return new HostRegistrationStateError("Host registration file is not private to its owner.");
4013
+ return new HostRegistrationStateError("Host registration file is unavailable.");
4014
+ }
4015
+ function decodeHostRegistrationAuthority(value, expectedHostSourceRef) {
4016
+ const keys = HOST_REGISTRATION_STATE_KEYS;
4017
+ const fieldCount = record(value) ? Object.keys(value).length : 0;
4018
+ const missing = record(value) ? keys.filter((key) => !Object.hasOwn(value, key)).length : keys.length;
4019
+ 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" }])}.`);
4020
+ 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>" }])}.`);
4021
+ 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" }])}.`);
4022
+ 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")}.`);
4023
+ return { gateway_request_origin: value.gateway_request_origin, host_access_token: value.host_access_token };
4024
+ }
4025
+ function validRegistrationIdentity(value, expectedHostSourceRef) {
4026
+ 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;
4027
+ }
4028
+ function validRegistrationCredential(value) {
4029
+ return Number.isSafeInteger(value.credential_generation) && Number(value.credential_generation) > 0 && validHostAccessToken(value.host_access_token);
4030
+ }
4031
+ function validHostAccessToken(value) {
4032
+ return typeof value === "string" && CEAL_HOST_ACCESS_TOKEN_PATTERN.test(value);
4033
+ }
4034
+ function validGatewayOrigin(value) {
4035
+ try {
4036
+ if (typeof value !== "string" || /\s|\0/u.test(value)) return false;
4037
+ const parsed = new URL(value);
4038
+ const hostname = parsed.hostname.toLowerCase().replace(/\.+$/u, "");
4039
+ return hostname !== "" && validGatewayPort(parsed.port) && (loopbackHttpOrigin(parsed, hostname) || parsed.protocol === "https:") && cleanOriginPath(parsed) && bareOriginSuffix(value);
4040
+ } catch {
4041
+ return false;
4042
+ }
4043
+ }
4044
+ function loopbackHttpOrigin(parsed, hostname) {
4045
+ return parsed.protocol === "http:" && parsed.port !== "" && (hostname === "127.0.0.1" || hostname === "[::1]");
4046
+ }
4047
+ function validGatewayPort(port) {
4048
+ if (port === "") return true;
4049
+ const numeric = Number(port);
4050
+ return Number.isInteger(numeric) && numeric >= 1 && numeric <= 65535;
4051
+ }
4052
+ function cleanOriginPath(parsed) {
4053
+ return parsed.username === "" && parsed.password === "" && parsed.pathname === "/" && parsed.search === "" && parsed.hash === "";
4054
+ }
4055
+ function bareOriginSuffix(value) {
4056
+ const schemeEnd = value.indexOf("://");
4057
+ const authority = schemeEnd < 0 ? "" : value.slice(schemeEnd + 3);
4058
+ const suffixOffset = authority.search(/[\\/?#]/u);
4059
+ const rawSuffix = suffixOffset < 0 ? "" : authority.slice(suffixOffset);
4060
+ return rawSuffix === "" || rawSuffix === "/";
4061
+ }
4062
+ async function assertPrivateRegistrationDirectory(path, platform, custody) {
4063
+ if (!await isPrivateDirectory(path, platform, custody)) throw new HostRegistrationStateError("Host registration directory is not private to its owner.");
4064
+ }
4065
+ function record(value) {
4066
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4067
+ }
4068
+
4069
+ // host/abortable-wait.ts
4070
+ function waitForAbort(signal, milliseconds) {
4071
+ if (signal.aborted) return Promise.resolve();
4072
+ return new Promise((resolve3) => {
4073
+ const timer = setTimeout(finish, milliseconds);
4074
+ function finish() {
4075
+ clearTimeout(timer);
4076
+ signal.removeEventListener("abort", finish);
4077
+ resolve3();
4078
+ }
4079
+ signal.addEventListener("abort", finish, { once: true });
4080
+ });
4081
+ }
4082
+
4083
+ // host/service-log.ts
4084
+ import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
4085
+ import { dirname as dirname5, isAbsolute as isAbsolute2, posix as posix3, win32 as win324 } from "node:path";
4086
+
4087
+ // host/service-log-delivery.ts
4088
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
4089
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
4090
+ setImmediate(flush);
4091
+ }, onDeliveryGap = () => void 0) {
4092
+ const pending = [];
4093
+ const highWaterMark = stream.writableHighWaterMark;
4094
+ const byteBudget = highWaterMark + highWaterMark;
4095
+ let pendingBytes = 0;
4096
+ let droppedLines = 0;
4097
+ let flushScheduled = false;
4098
+ let waitingForDrain = false;
4099
+ let closed = !stream.writable;
4100
+ function stop() {
4101
+ if (closed) return;
4102
+ closed = true;
4103
+ pending.length = 0;
4104
+ pendingBytes = 0;
4105
+ stream.off("drain", onDrain);
4106
+ stream.off("close", onTerminal);
4107
+ stream.off("finish", onTerminal);
4108
+ stream.off("error", onError);
4109
+ }
4110
+ function onTerminal() {
4111
+ stop();
4112
+ }
4113
+ function onError() {
4114
+ stop();
4115
+ }
4116
+ function onDrain() {
4117
+ waitingForDrain = false;
4118
+ scheduleFlush();
4119
+ }
4120
+ function scheduleFlush() {
4121
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
4122
+ flushScheduled = true;
4123
+ let scheduling = true;
4124
+ let invokedSynchronously = false;
4125
+ try {
4126
+ schedule(() => {
4127
+ if (scheduling) {
4128
+ invokedSynchronously = true;
4129
+ return;
4130
+ }
4131
+ flushScheduled = false;
4132
+ flush();
4133
+ });
4134
+ } catch {
4135
+ flushScheduled = false;
4136
+ stop();
4137
+ return;
4138
+ }
4139
+ scheduling = false;
4140
+ if (invokedSynchronously) {
4141
+ flushScheduled = false;
4142
+ stop();
4143
+ }
4144
+ }
4145
+ function flush() {
4146
+ if (closed) return;
4147
+ if (!stream.writable) {
4148
+ stop();
4149
+ return;
4150
+ }
4151
+ while (pending.length > 0) {
4152
+ if (stream.writableNeedDrain) {
4153
+ if (!waitingForDrain) {
4154
+ waitingForDrain = true;
4155
+ stream.once("drain", onDrain);
4156
+ }
4157
+ return;
4158
+ }
4159
+ const next = pending.shift();
4160
+ if (next === void 0) return;
4161
+ pendingBytes -= next.bytes;
4162
+ let accepted;
4163
+ try {
4164
+ accepted = stream.write(next.line);
4165
+ } catch {
4166
+ stop();
4167
+ return;
4168
+ }
4169
+ if (!accepted) {
4170
+ waitingForDrain = true;
4171
+ stream.once("drain", onDrain);
4172
+ return;
4173
+ }
4174
+ }
4175
+ if (droppedLines > 0) {
4176
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
4177
+ `;
4178
+ droppedLines = 0;
4179
+ try {
4180
+ onDeliveryGap(line);
4181
+ } catch {
4182
+ }
4183
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
4184
+ pendingBytes += Buffer.byteLength(line, "utf8");
4185
+ flush();
4186
+ }
4187
+ }
4188
+ stream.on("close", onTerminal);
4189
+ stream.on("finish", onTerminal);
4190
+ stream.on("error", onError);
4191
+ return (line) => {
4192
+ if (closed) return;
4193
+ const bytes = Buffer.byteLength(line, "utf8");
4194
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
4195
+ droppedLines += 1;
4196
+ scheduleFlush();
4197
+ return;
4198
+ }
4199
+ pending.push({ line, bytes });
4200
+ pendingBytes += bytes;
4201
+ scheduleFlush();
4202
+ };
4203
+ }
4204
+
4205
+ // host/invocation-authentication-client-command.ts
4206
+ var DOCTOR_FLAGS = Object.freeze({
4207
+ "--expected-sha256": "expected_sha256",
4208
+ "--expected-source-commit": "expected_source_commit",
4209
+ "--expected-instance-ref": "expected_instance_ref"
4210
+ });
4211
+
4212
+ // host/service-log.ts
4213
+ var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
4214
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
4215
+ void persistHostServiceLogLine(line);
4216
+ });
4217
+ function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
4218
+ const details = diagnosticDetails(event, failure_kind, cause);
4219
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
4220
+ `;
4221
+ try {
4222
+ (sink ?? defaultHostServiceDiagnosticSink)(line);
4223
+ } catch {
4224
+ }
4225
+ }
4226
+ function diagnosticDetails(event, failureKind, cause) {
4227
+ if (event === "watcher_scan_failed") return {
4228
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
4229
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
4230
+ };
4231
+ return validDiagnosticCause(cause, event) ? { cause } : {};
4232
+ }
4233
+ function validDiagnosticCause(cause, event) {
4234
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
4235
+ }
4236
+ function defaultHostServiceDiagnosticSink(line) {
4237
+ writeHostServiceLogLine(line);
4238
+ }
4239
+ var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
4240
+ function writeHostServiceLogLine(line, environment = process.env) {
4241
+ void persistHostServiceLogLine(line, environment);
4242
+ defaultHostServiceLogDelivery(line);
4243
+ }
4244
+ async function persistHostServiceLogLine(line, environment = process.env) {
4245
+ if (process.platform !== "win32") return;
4246
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
4247
+ if (path === void 0 || !win324.isAbsolute(path) || win324.normalize(path) !== path) return;
4248
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
4249
+ }
4250
+ async function appendHostServiceLogLine(path, line) {
4251
+ if (!isAbsolute2(path)) return;
4252
+ await ensureHostServiceLogDirectory(path);
4253
+ await appendFile(path, line);
4254
+ }
4255
+ var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
4256
+ var hostServiceLogDirectories = /* @__PURE__ */ new Map();
4257
+ function ensureHostServiceLogDirectory(path) {
4258
+ const directory = dirname5(path);
4259
+ const existing = hostServiceLogDirectories.get(directory);
4260
+ if (existing !== void 0) return existing;
4261
+ const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
4262
+ hostServiceLogDirectories.delete(directory);
4263
+ throw error;
4264
+ });
4265
+ hostServiceLogDirectories.set(directory, pending);
4266
+ return pending;
4267
+ }
4268
+
4269
+ // host/relay/src/host-usage-facts-uploader.ts
4270
+ var HostUsageFactsUploader = class {
4271
+ options;
4272
+ store;
4273
+ constructor(options) {
4274
+ if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
4275
+ this.options = options;
4276
+ this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
4277
+ }
4278
+ async close() {
4279
+ await this.store.close();
4280
+ }
4281
+ async uploadOne(signal) {
4282
+ const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4283
+ if (candidate === null) return false;
4284
+ 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);
4285
+ const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4286
+ const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4287
+ const response2 = await (this.options.fetch ?? fetch)(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4288
+ method: "POST",
4289
+ headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4290
+ body: JSON.stringify(candidate.batch),
4291
+ signal: requestSignal
4292
+ });
4293
+ if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
4294
+ await response2.body?.cancel().catch(() => void 0);
4295
+ throw new Error("Gateway did not acknowledge the Host usage facts batch.");
4296
+ }
4297
+ await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
4298
+ return true;
4299
+ }
4300
+ };
4301
+ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4302
+ const uploader = new HostUsageFactsUploader(options);
4303
+ let delay = 500;
4304
+ let failures = 0;
4305
+ try {
4306
+ while (!signal.aborted) {
4307
+ try {
4308
+ await options.capture_next?.();
4309
+ } catch {
4310
+ writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
4311
+ }
4312
+ if (signal.aborted) return;
4313
+ try {
4314
+ const uploaded = await uploader.uploadOne(signal);
4315
+ failures = 0;
4316
+ delay = uploaded ? 100 : 1e3;
4317
+ } catch {
4318
+ if (signal.aborted) return;
4319
+ failures += 1;
4320
+ delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
4321
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4322
+ }
4323
+ if (!signal.aborted) await wait(signal, delay);
2564
4324
  }
2565
- return { removed, expired, malformed: read.malformed };
4325
+ } finally {
4326
+ await uploader.close().catch(() => void 0);
2566
4327
  }
2567
- };
2568
-
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()}`
2580
- };
4328
+ }
2581
4329
 
2582
4330
  // host/relay/src/relay-quarantine-store.ts
2583
4331
  var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
@@ -2594,16 +4342,6 @@ var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2594
4342
 
2595
4343
  // host/relay/src/relay-ipc.ts
2596
4344
  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
4345
 
2608
4346
  // host/codex/src/codex-invocation-context.ts
2609
4347
  function codexInvocationContextFromTurn(identity, promptRef, expiresAt, turnGenerationRef) {
@@ -2618,12 +4356,12 @@ function validateCodexHostInvocationContext(value) {
2618
4356
  validateContextTimes(value);
2619
4357
  }
2620
4358
  function validateIdentity(value) {
2621
- if (!isRecord4(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2)) {
4359
+ if (!isRecord5(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2)) {
2622
4360
  throw new CodexHostAdapterError("storage", "Codex Host invocation identity is malformed.");
2623
4361
  }
2624
4362
  }
2625
4363
  function isContextShape(value) {
2626
- return isRecord4(value) && hasHostInvocationContextKeys(value, ["turn_generation_ref"]) && value.schema_version === CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION;
4364
+ return isRecord5(value) && hasHostInvocationContextKeys(value, ["turn_generation_ref"]) && value.schema_version === CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION;
2627
4365
  }
2628
4366
  function validateContextReferences(value) {
2629
4367
  if (!safeRef2(value.prompt_ref) || !optionalSafeRef(value.turn_generation_ref)) throw new CodexHostAdapterError("storage", "Codex Host invocation context is malformed.");
@@ -2641,7 +4379,7 @@ function safeRef2(value) {
2641
4379
  function timestamp(value) {
2642
4380
  return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
2643
4381
  }
2644
- function isRecord4(value) {
4382
+ function isRecord5(value) {
2645
4383
  return value !== null && typeof value === "object" && !Array.isArray(value);
2646
4384
  }
2647
4385
 
@@ -2659,12 +4397,12 @@ var CodexOutboxStore = class {
2659
4397
  constructor(directory) {
2660
4398
  if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
2661
4399
  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");
4400
+ this.entriesDirectory = join4(directory, "entries");
4401
+ this.sessionsDirectory = join4(directory, "sessions");
4402
+ this.activeContextsDirectory = join4(directory, "active-contexts");
4403
+ this.turnSelectionsDirectory = join4(directory, "turn-selections");
4404
+ this.registrationsDirectory = join4(directory, "transcript-registrations");
4405
+ this.cursorsDirectory = join4(directory, "transcript-cursors");
2668
4406
  }
2669
4407
  async prepare() {
2670
4408
  for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
@@ -2683,7 +4421,7 @@ var CodexOutboxStore = class {
2683
4421
  for (const name of await readdir(this.entriesDirectory)) {
2684
4422
  if (!name.endsWith(".json")) continue;
2685
4423
  try {
2686
- const value = JSON.parse(await readOwnerStateFile(join2(this.entriesDirectory, name)));
4424
+ const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
2687
4425
  validateEnvelope(value);
2688
4426
  entries.push(value);
2689
4427
  } catch {
@@ -2696,7 +4434,7 @@ var CodexOutboxStore = class {
2696
4434
  async remove(entry) {
2697
4435
  validateEnvelope(entry);
2698
4436
  try {
2699
- await unlink2(this.entryPath(entry.submission_ref));
4437
+ await unlink3(this.entryPath(entry.submission_ref));
2700
4438
  } catch (error) {
2701
4439
  if (!isNotFound(error)) throw storageError("Unable to remove the Codex outbox entry.");
2702
4440
  }
@@ -2714,7 +4452,7 @@ var CodexOutboxStore = class {
2714
4452
  await writeAtomicJson(path, context);
2715
4453
  } catch (error) {
2716
4454
  try {
2717
- await unlink2(path);
4455
+ await unlink3(path);
2718
4456
  } catch (unlinkError) {
2719
4457
  if (!isNotFound(unlinkError)) throw storageError("Unable to clear a failed Codex Host context replacement.");
2720
4458
  }
@@ -2729,13 +4467,13 @@ var CodexOutboxStore = class {
2729
4467
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
2730
4468
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
2731
4469
  await this.prepare();
2732
- return readOptionalJson(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
4470
+ return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
2733
4471
  }
2734
4472
  async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
2735
4473
  const selection = await this.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref);
2736
4474
  if (selection === null || selection.prompt_ref !== promptRef || selection.turn_generation_ref !== turnGenerationRef) return false;
2737
4475
  const path = this.activeContextPath(identity);
2738
- const active = await readOptionalJson(path, validateCodexHostInvocationContext);
4476
+ const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
2739
4477
  if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
2740
4478
  await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
2741
4479
  return true;
@@ -2754,7 +4492,7 @@ var CodexOutboxStore = class {
2754
4492
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
2755
4493
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
2756
4494
  await this.prepare();
2757
- const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson(file, validateCodexHostInvocationContext));
4495
+ const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
2758
4496
  return context;
2759
4497
  }
2760
4498
  /** Clear the projection only if the caller still owns its exact active turn. */
@@ -2763,7 +4501,7 @@ var CodexOutboxStore = class {
2763
4501
  const active = await this.readInvocationContext(identity.host_source_ref, identity.host_session_ref, now);
2764
4502
  if (active === null || !sameIdentity(active.identity, identity)) return false;
2765
4503
  try {
2766
- await unlink2(this.activeContextPath(identity));
4504
+ await unlink3(this.activeContextPath(identity));
2767
4505
  } catch (error) {
2768
4506
  if (!isNotFound(error)) throw storageError("Unable to clear the Codex Host invocation context.");
2769
4507
  }
@@ -2778,13 +4516,13 @@ var CodexOutboxStore = class {
2778
4516
  const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
2779
4517
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
2780
4518
  await this.prepare();
2781
- return readOptionalJson(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
4519
+ return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
2782
4520
  }
2783
4521
  async registerTranscript(registration) {
2784
4522
  validateRegistration(registration);
2785
4523
  await this.prepare();
2786
4524
  const path = this.registrationPath(registration.host_source_ref, registration.host_session_ref);
2787
- const existing = await readOptionalJson(path, validateRegistration);
4525
+ const existing = await readOptionalJson2(path, validateRegistration);
2788
4526
  if (existing !== null && (existing.codex_session_id !== registration.codex_session_id || existing.transcript_path !== registration.transcript_path)) {
2789
4527
  throw storageError("Codex transcript registration conflicts with the source-bound session.");
2790
4528
  }
@@ -2809,7 +4547,7 @@ var CodexOutboxStore = class {
2809
4547
  for (const name of await readdir(this.registrationsDirectory)) {
2810
4548
  if (!name.endsWith(".json")) continue;
2811
4549
  try {
2812
- const value = JSON.parse(await readOwnerStateFile(join2(this.registrationsDirectory, name)));
4550
+ const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
2813
4551
  validateRegistration(value);
2814
4552
  registrations.push(value);
2815
4553
  } catch {
@@ -2820,7 +4558,7 @@ var CodexOutboxStore = class {
2820
4558
  async readTranscriptCursor(registration) {
2821
4559
  validateRegistration(registration);
2822
4560
  await this.prepare();
2823
- return readOptionalJson(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
4561
+ return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
2824
4562
  }
2825
4563
  async writeTranscriptCursor(cursor) {
2826
4564
  validateCursor(cursor);
@@ -2843,27 +4581,27 @@ var CodexOutboxStore = class {
2843
4581
  }
2844
4582
  entryPath(submissionRef) {
2845
4583
  if (!SAFE_REF3.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
2846
- return join2(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
4584
+ return join4(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
2847
4585
  }
2848
4586
  sessionPath(sourceRef, sessionRef) {
2849
- return join2(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
4587
+ return join4(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
2850
4588
  }
2851
4589
  activeContextPath(identity) {
2852
- return join2(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
4590
+ return join4(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
2853
4591
  }
2854
4592
  turnSelectionPath(sourceRef, sessionRef) {
2855
- return join2(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
4593
+ return join4(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
2856
4594
  }
2857
4595
  registrationPath(sourceRef, sessionRef) {
2858
- return join2(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4596
+ return join4(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
2859
4597
  }
2860
4598
  cursorPath(sourceRef, sessionRef) {
2861
- return join2(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
4599
+ return join4(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
2862
4600
  }
2863
4601
  };
2864
4602
  async function removeOwnerState(path, what) {
2865
4603
  try {
2866
- await unlink2(path);
4604
+ await unlink3(path);
2867
4605
  } catch (error) {
2868
4606
  if (!isNotFound(error)) throw storageError(`Unable to retire the Codex transcript ${what}.`);
2869
4607
  }
@@ -2894,7 +4632,7 @@ async function writeAtomicJson(path, value) {
2894
4632
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
2895
4633
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
2896
4634
  try {
2897
- const handle = await open3(temp, "wx");
4635
+ const handle = await open4(temp, "wx");
2898
4636
  try {
2899
4637
  await handle.writeFile(text, "utf8");
2900
4638
  await handle.sync();
@@ -2902,19 +4640,19 @@ async function writeAtomicJson(path, value) {
2902
4640
  await handle.close();
2903
4641
  }
2904
4642
  await rename2(temp, path);
2905
- await syncDirectory(dirname2(path));
4643
+ await syncDirectory2(dirname6(path));
2906
4644
  } catch (error) {
2907
4645
  try {
2908
- await unlink2(temp);
4646
+ await unlink3(temp);
2909
4647
  } catch {
2910
4648
  }
2911
4649
  if (error instanceof CodexHostAdapterError) throw error;
2912
4650
  throw storageError("Unable to atomically replace Codex owner state.");
2913
4651
  }
2914
4652
  }
2915
- async function syncDirectory(path) {
4653
+ async function syncDirectory2(path) {
2916
4654
  try {
2917
- const handle = await open3(path, "r");
4655
+ const handle = await open4(path, "r");
2918
4656
  try {
2919
4657
  await handle.sync();
2920
4658
  } finally {
@@ -2923,7 +4661,7 @@ async function syncDirectory(path) {
2923
4661
  } catch {
2924
4662
  }
2925
4663
  }
2926
- async function readOptionalJson(path, validate) {
4664
+ async function readOptionalJson2(path, validate) {
2927
4665
  try {
2928
4666
  const value = JSON.parse(await readOwnerStateFile(path));
2929
4667
  validate(value);
@@ -2936,18 +4674,18 @@ async function readOptionalJson(path, validate) {
2936
4674
  }
2937
4675
  async function ensureOwnerDirectory(path) {
2938
4676
  try {
2939
- await stat(path);
4677
+ await stat2(path);
2940
4678
  } catch (error) {
2941
4679
  if (!isNotFound(error)) throw storageError("Codex owner state directory is unavailable.");
2942
- await mkdir2(path, { recursive: true });
4680
+ await mkdir4(path, { recursive: true });
2943
4681
  }
2944
- const stats = await stat(path);
4682
+ const stats = await stat2(path);
2945
4683
  if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
2946
4684
  }
2947
4685
  async function readOwnerStateFile(path) {
2948
4686
  let handle;
2949
4687
  try {
2950
- handle = await open3(path);
4688
+ handle = await open4(path);
2951
4689
  const stats = await handle.stat();
2952
4690
  if (!stats.isFile()) throw storageError("Codex owner state path is not a regular file.");
2953
4691
  return await handle.readFile("utf8");
@@ -2956,8 +4694,8 @@ async function readOwnerStateFile(path) {
2956
4694
  }
2957
4695
  }
2958
4696
  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")}).`);
4697
+ if (!isRecord6(value)) throw storageError("Codex outbox entry is malformed.");
4698
+ 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
4699
  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
4700
  validateIdentity2(value.identity);
2963
4701
  validateEnvelopeReferences(value);
@@ -2972,8 +4710,8 @@ function validateEnvelopeReferences(value) {
2972
4710
  if (typeof value.origin_input !== "boolean") throw storageError("Codex outbox origin disposition is malformed.");
2973
4711
  }
2974
4712
  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")}).`);
4713
+ if (!isRecord6(value)) throw storageError("Codex transcript registration is malformed.");
4714
+ 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
4715
  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
4716
  validateRegistrationFields(value);
2979
4717
  }
@@ -2985,16 +4723,31 @@ function validateRegistrationFields(value) {
2985
4723
  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
4724
  }
2987
4725
  function validRegistrationCwd(value) {
2988
- return value === void 0 || typeof value === "string" && isAbsolute2(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
4726
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
2989
4727
  }
2990
4728
  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")}).`);
4729
+ if (!isRecord6(value)) throw storageError("Codex transcript cursor is malformed.");
4730
+ 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")}).`);
4731
+ validateCursorIdentityAndPosition(value);
4732
+ validateCursorOptionalFields(value);
4733
+ }
4734
+ function validateCursorIdentityAndPosition(value) {
2993
4735
  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
4736
  if (!validCursorSource(value) || !validCursorPosition(value) || !validCursorStatus(value)) throw storageError("Codex transcript cursor fields are malformed.");
4737
+ }
4738
+ function validateCursorOptionalFields(value) {
2995
4739
  if (value.active_task !== void 0 && !validActiveTask(value.active_task)) throw storageError("Codex transcript task cursor is malformed.");
4740
+ validateHumanMessageProjection(value.human_message_window);
2996
4741
  if (value.reason !== void 0 && !isHostTranscriptCursorReason(value.reason)) throw storageError("Codex transcript cursor reason is malformed.");
2997
4742
  }
4743
+ function validateHumanMessageProjection(value) {
4744
+ if (value === void 0) return;
4745
+ try {
4746
+ decodeCealHostInvocationHumanMessageWindow(value);
4747
+ } catch {
4748
+ throw storageError("Codex transcript human-message projection is malformed.");
4749
+ }
4750
+ }
2998
4751
  function validCursorSource(value) {
2999
4752
  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
4753
  }
@@ -3005,7 +4758,7 @@ function validCursorStatus(value) {
3005
4758
  return (value.status === "active" || value.status === "quarantined") && isTimestamp(value.updated_at);
3006
4759
  }
3007
4760
  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;
4761
+ 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
4762
  return validActiveTaskIdentity(value) && validActiveTaskReferences(value) && validActiveTaskUsage(value);
3010
4763
  }
3011
4764
  function validActiveTaskIdentity(value) {
@@ -3021,7 +4774,7 @@ function validActiveTaskUsage(value) {
3021
4774
  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
4775
  }
3023
4776
  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;
4777
+ if (!isRecord6(value) || !sameKeys2(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) return false;
3025
4778
  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
4779
  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
4780
  }
@@ -3041,8 +4794,8 @@ function validateEnvelopeTimestamps(value) {
3041
4794
  if (!isTimestamp(value.expires_at)) throw storageError("Codex outbox timestamps are malformed.");
3042
4795
  }
3043
4796
  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")}).`);
4797
+ if (!isRecord6(value)) throw storageError("Codex session snapshot is malformed.");
4798
+ 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
4799
  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
4800
  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
4801
  }
@@ -3050,35 +4803,35 @@ function validateTurnSelection(value) {
3050
4803
  if (!isHostInvocationTurnSelection(value)) throw storageError("Codex Host turn selection is malformed.");
3051
4804
  }
3052
4805
  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.");
4806
+ 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
4807
  }
3055
4808
  function isJsonValue(value) {
3056
4809
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
3057
4810
  if (typeof value === "number") return Number.isFinite(value);
3058
4811
  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));
4812
+ return isRecord6(value) && Object.entries(value).every(([key, child]) => key.length > 0 && key.length <= 128 && isJsonValue(child));
3060
4813
  }
3061
4814
  function isTimestamp(value) {
3062
4815
  return typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value));
3063
4816
  }
3064
- function sameKeys(value, required, optional = []) {
4817
+ function sameKeys2(value, required, optional = []) {
3065
4818
  const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
3066
4819
  const keys = Object.keys(value);
3067
4820
  return keys.length >= required.length && keys.length <= allowed.size && required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => allowed.has(key));
3068
4821
  }
3069
- function isRecord5(value) {
4822
+ function isRecord6(value) {
3070
4823
  return value !== null && typeof value === "object" && !Array.isArray(value);
3071
4824
  }
3072
4825
  function isNotFound(error) {
3073
- return isRecord5(error) && error.code === "ENOENT";
4826
+ return isRecord6(error) && error.code === "ENOENT";
3074
4827
  }
3075
4828
  function storageError(message) {
3076
4829
  return new CodexHostAdapterError("storage", message);
3077
4830
  }
3078
4831
 
3079
4832
  // host/codex/src/codex-transcript-baseline.ts
3080
- import { createHash as createHash5 } from "node:crypto";
3081
- import { constants as constants2 } from "node:fs";
4833
+ import { createHash as createHash8 } from "node:crypto";
4834
+ import { constants as constants5 } from "node:fs";
3082
4835
 
3083
4836
  // host/codex/src/codex-transcript-decoder.ts
3084
4837
  var SAFE_REF4 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
@@ -3090,16 +4843,32 @@ function decodeCodexTranscriptLine(line) {
3090
4843
  } catch {
3091
4844
  reject2("Codex transcript record is not valid JSON.");
3092
4845
  }
3093
- if (!isRecord6(value)) reject2("Codex transcript record envelope is malformed.");
4846
+ if (!isRecord7(value)) reject2("Codex transcript record envelope is malformed.");
3094
4847
  const ordinal = safeOrdinal(value.ordinal);
3095
4848
  const timestamp4 = safeTimestamp(value.timestamp);
3096
- if (!isRecord6(value.payload) || typeof value.type !== "string") reject2("Codex transcript record payload is malformed.");
4849
+ if (!isRecord7(value.payload) || typeof value.type !== "string") reject2("Codex transcript record payload is malformed.");
3097
4850
  if (value.type === "session_meta") return decodeSessionMeta(value.payload, ordinal, timestamp4);
3098
4851
  if (value.type === "turn_context") return decodeTurnContext(value.payload, ordinal, timestamp4);
3099
4852
  if (value.type === "event_msg") return decodeEventMessage(value.payload, ordinal, timestamp4);
3100
4853
  if (value.type === "response_item") return decodeResponseItem(value.payload, ordinal, timestamp4);
3101
4854
  return { kind: "ignored", ordinal, timestamp: timestamp4 };
3102
4855
  }
4856
+ function decodeCodexUsageTranscriptLine(line) {
4857
+ let value;
4858
+ try {
4859
+ value = JSON.parse(line);
4860
+ } catch {
4861
+ reject2("Codex transcript record is not valid JSON.");
4862
+ }
4863
+ if (!isRecord7(value)) reject2("Codex transcript record envelope is malformed.");
4864
+ const ordinal = safeOrdinal(value.ordinal);
4865
+ const timestamp4 = safeTimestamp(value.timestamp);
4866
+ if (!isRecord7(value.payload) || typeof value.type !== "string") reject2("Codex transcript record payload is malformed.");
4867
+ if (value.type === "session_meta") return decodeSessionMeta(value.payload, ordinal, timestamp4);
4868
+ if (value.type === "turn_context") return decodeTurnContext(value.payload, ordinal, timestamp4);
4869
+ if (value.type === "event_msg" && ["task_started", "task_complete", "turn_aborted", "token_count"].includes(String(value.payload.type))) return decodeEventMessage(value.payload, ordinal, timestamp4);
4870
+ return { kind: "ignored", ordinal, timestamp: timestamp4 };
4871
+ }
3103
4872
  function decodeTurnContext(payload, ordinal, timestamp4) {
3104
4873
  return {
3105
4874
  kind: "turn_context",
@@ -3139,7 +4908,7 @@ function decodeEventMessage(payload, ordinal, timestamp4) {
3139
4908
  started_at: safeNumber(payload.started_at),
3140
4909
  completed_at: safeNumber(payload.completed_at),
3141
4910
  duration_ms: safeNumber(payload.duration_ms),
3142
- reason: boundedText(payload.reason, 256, "Codex task abort reason is invalid.")
4911
+ reason: boundedText2(payload.reason, 256, "Codex task abort reason is invalid.")
3143
4912
  };
3144
4913
  }
3145
4914
  if (payload.type === "token_count") return decodeTokenCount(payload, ordinal, timestamp4);
@@ -3147,7 +4916,7 @@ function decodeEventMessage(payload, ordinal, timestamp4) {
3147
4916
  }
3148
4917
  function decodeTokenCount(payload, ordinal, timestamp4) {
3149
4918
  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" };
4919
+ if (!isRecord7(payload.info)) return { kind: "token_count", ordinal, timestamp: timestamp4, usage_gap_reason: "token_count_shape_not_attributable" };
3151
4920
  const lastUsage = optionalTokenUsage(payload.info.last_token_usage);
3152
4921
  const totalUsage = optionalTokenUsage(payload.info.total_token_usage);
3153
4922
  const gap = lastUsage.status === "invalid" || totalUsage.status === "invalid";
@@ -3171,7 +4940,7 @@ function optionalTokenUsage(value) {
3171
4940
  }
3172
4941
  }
3173
4942
  function decodeTokenUsage(value) {
3174
- if (!isRecord6(value)) reject2("Codex token usage is malformed.");
4943
+ if (!isRecord7(value)) reject2("Codex token usage is malformed.");
3175
4944
  const usage = {
3176
4945
  input_tokens: safeTokenCount(value.input_tokens),
3177
4946
  cached_input_tokens: safeTokenCount(value.cached_input_tokens),
@@ -3203,14 +4972,14 @@ function userTextContentKind(kinds) {
3203
4972
  return kinds.length === 1 && (kinds[0] === "user.text" || kinds[0] === "goal.internal_context") ? kinds[0] : void 0;
3204
4973
  }
3205
4974
  function userMessageMetadata(value) {
3206
- if (!isRecord6(value) || !Array.isArray(value.content_item_kinds)) reject2("Codex user message provenance is malformed.");
4975
+ if (!isRecord7(value) || !Array.isArray(value.content_item_kinds)) reject2("Codex user message provenance is malformed.");
3207
4976
  return { ...value, content_item_kinds: value.content_item_kinds };
3208
4977
  }
3209
4978
  function userTextContent(value) {
3210
4979
  if (!Array.isArray(value)) reject2(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
3211
4980
  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.");
4981
+ 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")}).`);
4982
+ return boundedText2(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
3214
4983
  }
3215
4984
  function safeOrdinal(value) {
3216
4985
  if (!Number.isSafeInteger(value) || Number(value) < 0) reject2("Codex transcript ordinal is invalid.");
@@ -3234,18 +5003,18 @@ function safeRef3(value, message) {
3234
5003
  if (typeof value !== "string" || !SAFE_REF4.test(value)) reject2(message);
3235
5004
  return value;
3236
5005
  }
3237
- function boundedText(value, maximum, message) {
5006
+ function boundedText2(value, maximum, message) {
3238
5007
  if (typeof value !== "string") reject2(`${message} ${refusalFact("kind", typeof value, "string")}.`);
3239
5008
  const bytes = Buffer.byteLength(value, "utf8");
3240
5009
  if (bytes > maximum) reject2(`${message} ${refusalFact("bytes", bytes, `at most ${maximum} UTF-8 bytes`)}.`);
3241
5010
  return value;
3242
5011
  }
3243
5012
  function boundedNonEmptyText(value, maximum, message) {
3244
- const result = boundedText(value, maximum, message);
5013
+ const result = boundedText2(value, maximum, message);
3245
5014
  if (result.length === 0) reject2(message);
3246
5015
  return result;
3247
5016
  }
3248
- function isRecord6(value) {
5017
+ function isRecord7(value) {
3249
5018
  return value !== null && typeof value === "object" && !Array.isArray(value);
3250
5019
  }
3251
5020
  function reject2(message) {
@@ -3258,7 +5027,7 @@ var CODEX_TRANSCRIPT_ANCHOR_BYTES = 256;
3258
5027
  async function captureCodexTranscriptBaseline(registration, now = () => /* @__PURE__ */ new Date(), platform = process.platform, custody = {}) {
3259
5028
  let handle;
3260
5029
  try {
3261
- handle = await openNoFollow(registration.transcript_path, constants2.O_RDONLY, void 0, platform, custody);
5030
+ handle = await openNoFollow(registration.transcript_path, constants5.O_RDONLY, void 0, platform, custody);
3262
5031
  const { size, device, inode } = await ownedCodexTranscriptFile(handle, platform);
3263
5032
  const empty = codexTranscriptInitialCursor(registration, device, inode, now);
3264
5033
  const headerLine = await firstCompleteLine(handle, size);
@@ -3278,6 +5047,7 @@ async function captureCodexTranscriptBaseline(registration, now = () => /* @__PU
3278
5047
  anchor_start: anchorStart,
3279
5048
  anchor_sha256: digest(anchor),
3280
5049
  header_validated: true,
5050
+ human_message_window: { messages: [], truncated: offset > 0 },
3281
5051
  updated_at: timestamp2(now)
3282
5052
  };
3283
5053
  } finally {
@@ -3297,6 +5067,7 @@ function codexTranscriptInitialCursor(registration, device, inode, now) {
3297
5067
  anchor_start: 0,
3298
5068
  anchor_sha256: digest(Buffer.alloc(0)),
3299
5069
  header_validated: false,
5070
+ human_message_window: { messages: [], truncated: false },
3300
5071
  status: "active",
3301
5072
  updated_at: timestamp2(now)
3302
5073
  };
@@ -3307,10 +5078,10 @@ async function ownedCodexTranscriptFile(handle, platform = process.platform) {
3307
5078
  if (platform !== "win32" && !isSelfOwned(stats.uid, platform, handle)) throw new CodexHostAdapterError("storage", "Codex transcript source is owned by another user.");
3308
5079
  return { size: stats.size, device: String(stats.dev), inode: String(stats.ino) };
3309
5080
  }
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 }
5081
+ function assertCodexTranscriptHeader(registration, record2) {
5082
+ 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([
5083
+ { name: "kind", value: record2.kind, expected: "session_meta" },
5084
+ { name: "session_id", value: record2.kind === "session_meta" ? record2.session_id : "unavailable", expected: registration.codex_session_id }
3314
5085
  ])}).`);
3315
5086
  }
3316
5087
  async function firstCompleteLine(handle, size) {
@@ -3396,7 +5167,7 @@ async function* completeLinesBackward(handle, end) {
3396
5167
  yield { start: 0, bytes: Buffer.concat(carry) };
3397
5168
  }
3398
5169
  function digest(value) {
3399
- return createHash5("sha256").update(value).digest("hex");
5170
+ return createHash8("sha256").update(value).digest("hex");
3400
5171
  }
3401
5172
  function timestamp2(now) {
3402
5173
  const value = now();
@@ -3405,15 +5176,15 @@ function timestamp2(now) {
3405
5176
  }
3406
5177
 
3407
5178
  // host/codex/src/codex-runtime-paths.ts
3408
- import { join as join3 } from "node:path";
5179
+ import { join as join5 } from "node:path";
3409
5180
  var CODEX_HOME_ENVIRONMENT = "CODEX_HOME";
3410
5181
  var CODEX_HOME_DEFAULT_DIRECTORY = ".codex";
3411
5182
  var CODEX_SESSIONS_DIRECTORY = "sessions";
3412
5183
  function resolveCodexHome(environment, home) {
3413
- return environment[CODEX_HOME_ENVIRONMENT] || join3(home, CODEX_HOME_DEFAULT_DIRECTORY);
5184
+ return environment[CODEX_HOME_ENVIRONMENT] || join5(home, CODEX_HOME_DEFAULT_DIRECTORY);
3414
5185
  }
3415
5186
  function resolveCodexSessionsRoot(environment, home) {
3416
- return join3(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
5187
+ return join5(resolveCodexHome(environment, home), CODEX_SESSIONS_DIRECTORY);
3417
5188
  }
3418
5189
 
3419
5190
  // host/codex/src/codex-adapter.ts
@@ -3435,7 +5206,7 @@ function createCodexHostObservationAdapter(options) {
3435
5206
  }
3436
5207
  async function registerSession(event, options, store, now, retentionMs) {
3437
5208
  const defaultRoot = resolveCodexSessionsRoot(process.env, homedir());
3438
- const transcriptPath = sourceBoundTranscriptPath(event.transcript_path, options.codex_sessions_root ?? defaultRoot);
5209
+ const transcriptPath = await sourceBoundTranscriptPath(event.transcript_path, options.codex_sessions_root ?? defaultRoot);
3439
5210
  const hostSessionRef = hostSessionReference(options.host_source_ref, event.session_id);
3440
5211
  const observedAt = timestamp3(now);
3441
5212
  const expiresAt = new Date(Date.parse(observedAt) + retentionMs).toISOString();
@@ -3503,15 +5274,20 @@ async function liveSteeredTurn(options, store, hostSessionRef, hostTurnRef) {
3503
5274
  if (selection === null || selection.prompt_ref !== live.prompt_ref || selection.turn_generation_ref !== live.turn_generation_ref) return void 0;
3504
5275
  return { host_turn_ref: hostTurnRef, prompt_ref: selection.prompt_ref, turn_generation_ref: selection.turn_generation_ref };
3505
5276
  }
3506
- function sourceBoundTranscriptPath(path, sessionsRoot) {
3507
- if (!isAbsolute3(path) || !isAbsolute3(sessionsRoot)) throw new CodexHostAdapterError("configuration", "Codex transcript registration paths must be absolute.");
5277
+ async function sourceBoundTranscriptPath(path, sessionsRoot) {
5278
+ if (!isAbsolute4(path) || !isAbsolute4(sessionsRoot)) throw new CodexHostAdapterError("configuration", "Codex transcript registration paths must be absolute.");
3508
5279
  const transcript = resolve2(path);
3509
5280
  const root = resolve2(sessionsRoot);
5281
+ assertTranscriptChild(root, transcript);
5282
+ const [physicalRoot, physicalTranscript] = await Promise.all([realpath(root), realpath(transcript)]);
5283
+ assertTranscriptChild(physicalRoot, physicalTranscript);
5284
+ return transcript;
5285
+ }
5286
+ function assertTranscriptChild(root, transcript) {
3510
5287
  const child = relative(root, transcript);
3511
- if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute3(child)) {
5288
+ if (child === "" || child === ".." || child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute4(child)) {
3512
5289
  throw new CodexHostAdapterError("payload_rejected", "Codex transcript path is outside the configured sessions root.");
3513
5290
  }
3514
- return transcript;
3515
5291
  }
3516
5292
  function codexSubmissionReference(hostInputRef, event, ordinal) {
3517
5293
  if (!SAFE_REF5.test(hostInputRef) || !Number.isSafeInteger(ordinal) || ordinal < 0) throw new CodexHostAdapterError("invalid_input", "Codex submission identity is invalid.");
@@ -3523,7 +5299,7 @@ function timestamp3(now) {
3523
5299
  return value.toISOString();
3524
5300
  }
3525
5301
  function validateOptions(options) {
3526
- if (!isRecord7(options)) throw new CodexHostAdapterError("configuration", "Codex adapter options are invalid.");
5302
+ if (!isRecord8(options)) throw new CodexHostAdapterError("configuration", "Codex adapter options are invalid.");
3527
5303
  validateAdapterOwner(options);
3528
5304
  validateAdapterBehavior(options);
3529
5305
  }
@@ -3531,7 +5307,7 @@ function validateAdapterOwner(options) {
3531
5307
  if (!SAFE_REF5.test(options.host_source_ref) || options.outbox_dir.length === 0) {
3532
5308
  throw new CodexHostAdapterError("configuration", "Codex adapter options are invalid.");
3533
5309
  }
3534
- if (options.codex_sessions_root !== void 0 && !isAbsolute3(options.codex_sessions_root)) throw new CodexHostAdapterError("configuration", "Codex sessions root is invalid.");
5310
+ if (options.codex_sessions_root !== void 0 && !isAbsolute4(options.codex_sessions_root)) throw new CodexHostAdapterError("configuration", "Codex sessions root is invalid.");
3535
5311
  }
3536
5312
  function validateAdapterBehavior(options) {
3537
5313
  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 +5315,13 @@ function validateAdapterBehavior(options) {
3539
5315
  function safeReason(error) {
3540
5316
  return error instanceof CodexHostAdapterError ? error.message.slice(0, 128) : "codex_session_registration_rejected";
3541
5317
  }
3542
- function isRecord7(value) {
5318
+ function isRecord8(value) {
3543
5319
  return value !== null && typeof value === "object" && !Array.isArray(value);
3544
5320
  }
3545
5321
 
3546
5322
  // 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";
5323
+ import { posix as posix4, win32 as win325 } from "node:path";
5324
+ import { constants as constants6 } from "node:fs";
3583
5325
  import { lstat as lstat3 } from "node:fs/promises";
3584
5326
  var SAFE_REF6 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
3585
5327
  var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
@@ -3604,8 +5346,9 @@ function parseHostProducerConfigFlag(args, platform = process.platform) {
3604
5346
  }
3605
5347
  async function readHostProducerConfig(descriptor, configPath, platform = process.platform, custody = {}) {
3606
5348
  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, "../../../../..");
5349
+ const path = platform === "win32" ? win325 : posix4;
5350
+ const registrationStateFile = hostProducerRegistrationStateFile(config.outbox_dir, platform);
5351
+ const root = path.dirname(registrationStateFile);
3609
5352
  try {
3610
5353
  assertHostProducerSourcePaths(root, config, descriptor.producer_id, platform);
3611
5354
  } catch (error) {
@@ -3619,6 +5362,10 @@ function decodeHostProducerConfigText(descriptor, text, platform = process.platf
3619
5362
  const { extra_paths: extras, ...core } = decoded;
3620
5363
  return Object.freeze(descriptor.config({ schema_version: descriptor.schema, ...core }, extras));
3621
5364
  }
5365
+ function hostProducerRegistrationStateFile(outboxDirectory, platform = process.platform) {
5366
+ const path = platform === "win32" ? win325 : posix4;
5367
+ return path.join(path.resolve(outboxDirectory, "../../../../.."), "registration.json");
5368
+ }
3622
5369
  function hostProducerError(code, message = code) {
3623
5370
  return new HostProducerServiceError(code, message);
3624
5371
  }
@@ -3664,7 +5411,7 @@ async function readProducerConfigText(configPath, platform, error, custody) {
3664
5411
  function decodeProducerConfigCore(text, options) {
3665
5412
  const ownership = producerConfigKeyOwnership(options.keys, options.platform);
3666
5413
  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 })));
5414
+ 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
5415
  const hostSourceRef = typeof value.host_source_ref === "string" ? value.host_source_ref : "";
3669
5416
  const installationRef = typeof value.producer_installation_ref === "string" ? value.producer_installation_ref : "";
3670
5417
  const producerEpoch = validateIdentity3(hostSourceRef, installationRef, value.producer_epoch, options.error);
@@ -3716,7 +5463,7 @@ function validateConfigFile(value, platform, error, handle) {
3716
5463
  }
3717
5464
  async function openConfigFile(configPath, platform, error, custody) {
3718
5465
  try {
3719
- return await openNoFollow(configPath, constants3.O_RDONLY, void 0, platform, custody);
5466
+ return await openNoFollow(configPath, constants6.O_RDONLY, void 0, platform, custody);
3720
5467
  } catch (error_) {
3721
5468
  if (error_ instanceof SecureFileCustodyError) throw error(error_.reason === "not_private" ? "config_not_private" : "invalid_config");
3722
5469
  throw error("config_unavailable");
@@ -3757,7 +5504,7 @@ function firstDifferenceIndex(left, right) {
3757
5504
  return shared;
3758
5505
  }
3759
5506
  function producerShapeFacts(value, options) {
3760
- if (!isRecord8(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
5507
+ if (!isRecord9(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
3761
5508
  const tolerated = options.tolerated ?? [];
3762
5509
  const allowed = [...options.keys, ...tolerated, ...Object.keys(HOST_PRODUCER_TIMING_DEFAULTS)];
3763
5510
  const facts = [
@@ -3792,7 +5539,7 @@ function producerIntervalFacts(reconcile, retry, timeout) {
3792
5539
  function hasConfigKeys(value, required, tolerated = []) {
3793
5540
  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
5541
  }
3795
- function isRecord8(value) {
5542
+ function isRecord9(value) {
3796
5543
  return value !== null && typeof value === "object" && !Array.isArray(value);
3797
5544
  }
3798
5545
  function positive(value, maximum) {
@@ -3802,48 +5549,6 @@ function boundedMilliseconds(value) {
3802
5549
  return positive(value, 6e4) && Number(value) >= 25;
3803
5550
  }
3804
5551
 
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
5552
  // host/codex/src/codex-producer.ts
3848
5553
  var CodexProducer = class {
3849
5554
  store;
@@ -3890,7 +5595,10 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3890
5595
  const preflight = await this.preflight(registration, handle, size, device, inode);
3891
5596
  if (preflight.cursor === null) return preflight.result;
3892
5597
  const complete = await this.readChunk(handle, preflight.cursor.offset, size);
3893
- if (complete === "empty" || complete === "partial") return { records: 0, enqueued: 0, quarantined: false };
5598
+ if (complete === "empty" || complete === "partial") {
5599
+ if (preflight.projectionInitialized) await this.commitCursor(registration, handle, preflight.cursor, 0, device, inode, preflight.cursor.last_ordinal, preflight.cursor.active_task, preflight.cursor.human_message_window ?? { messages: [], truncated: false });
5600
+ return { records: 0, enqueued: 0, quarantined: false };
5601
+ }
3894
5602
  return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
3895
5603
  }
3896
5604
  async scanFailed(handle, registration, error) {
@@ -3905,40 +5613,51 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3905
5613
  const existing = await this.store.readTranscriptCursor(registration);
3906
5614
  let cursor = existing ?? codexTranscriptInitialCursor(registration, device, inode, this.now);
3907
5615
  if (cursor.status === "quarantined") {
3908
- return { cursor: null, result: { records: 0, enqueued: 0, quarantined: true } };
5616
+ return { cursor: null, projectionInitialized: false, result: { records: 0, enqueued: 0, quarantined: true } };
3909
5617
  }
3910
5618
  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 } };
5619
+ if (reason === null) {
5620
+ if (cursor.human_message_window !== void 0) return { cursor, projectionInitialized: false, result: { records: 0, enqueued: 0, quarantined: false } };
5621
+ const humanWindow = await this.readHumanMessageProjection(handle, registration, cursor);
5622
+ return { cursor: { ...cursor, human_message_window: humanWindow }, projectionInitialized: existing !== null, result: { records: 0, enqueued: 0, quarantined: false } };
5623
+ }
3912
5624
  await this.quarantine(registration, cursor, device, inode, reason);
3913
- return { cursor: null, result: { records: 0, enqueued: 0, quarantined: true } };
5625
+ this.diagnostic("watcher_scan_failed", "other", `cursor_${reason}`);
5626
+ return { cursor: null, projectionInitialized: false, result: { records: 0, enqueued: 0, quarantined: true } };
5627
+ }
5628
+ async readHumanMessageProjection(handle, registration, cursor) {
5629
+ return readCodexHumanMessageProjection(registration, cursor, (offset, size) => this.readChunk(handle, offset, size));
3914
5630
  }
3915
5631
  async consumeCompleteChunk(registration, handle, cursor, complete, device, inode) {
3916
5632
  let activeTask = cursor.active_task;
3917
5633
  let lastOrdinal = cursor.last_ordinal;
5634
+ let humanWindow = cursor.human_message_window ?? { messages: [], truncated: false };
3918
5635
  let records = 0;
3919
5636
  let enqueued = 0;
3920
5637
  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);
5638
+ const record2 = decodeCodexTranscriptLine(line);
5639
+ assertRecordSequence(registration, cursor, records, lastOrdinal, record2);
5640
+ const message = codexHumanMessage(registration, record2);
5641
+ if (message !== null) humanWindow = mergeHostInvocationHumanMessageWindow(humanWindow, [message]);
5642
+ await this.observeSessionMetadata(registration, record2);
5643
+ const outcome = await this.processRecord(registration, activeTask, record2);
3925
5644
  activeTask = outcome.activeTask;
3926
5645
  enqueued += outcome.enqueued;
3927
- lastOrdinal = record.ordinal;
5646
+ lastOrdinal = record2.ordinal;
3928
5647
  records += 1;
3929
5648
  }
3930
- await this.commitCursor(registration, handle, cursor, complete.length, device, inode, lastOrdinal, activeTask);
5649
+ await this.commitCursor(registration, handle, cursor, complete.length, device, inode, lastOrdinal, activeTask, humanWindow);
3931
5650
  return { records, enqueued, quarantined: false };
3932
5651
  }
3933
- async observeSessionMetadata(registration, record) {
3934
- if (record.kind !== "session_meta") return;
5652
+ async observeSessionMetadata(registration, record2) {
5653
+ if (record2.kind !== "session_meta") return;
3935
5654
  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 } });
5655
+ if (session !== null && this.isRecord(session.value)) await this.store.saveSession({ ...session, value: { ...session.value, host_version: record2.cli_version } });
3937
5656
  }
3938
- async commitCursor(registration, handle, cursor, consumedBytes, device, inode, lastOrdinal, activeTask) {
5657
+ async commitCursor(registration, handle, cursor, consumedBytes, device, inode, lastOrdinal, activeTask, humanWindow) {
3939
5658
  const offset = cursor.offset + consumedBytes;
3940
5659
  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() });
5660
+ 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
5661
  }
3943
5662
  async quarantineFailure(registration, handle) {
3944
5663
  if (handle === void 0) return;
@@ -3956,40 +5675,40 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3956
5675
  };
3957
5676
  await this.store.writeTranscriptCursor(quarantined);
3958
5677
  }
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);
5678
+ async processRecord(registration, activeTask, record2) {
5679
+ if (record2.kind === "task_started") return this.processTaskStarted(registration, record2);
5680
+ if (record2.kind === "turn_context") return { ...activeTask === void 0 ? {} : { activeTask: record2.turn_id === activeTask.codex_turn_id ? { ...activeTask, model: record2.model } : activeTask }, enqueued: 0 };
5681
+ if (record2.kind === "token_count") return { ...activeTask === void 0 ? {} : { activeTask: accumulateTokenCount(activeTask, record2) }, enqueued: 0 };
5682
+ if (record2.kind === "user_text") return this.processUserInput(registration, activeTask, record2);
5683
+ if (record2.kind === "task_complete" || record2.kind === "turn_aborted") return this.processTerminal(registration, activeTask, record2);
3965
5684
  return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
3966
5685
  }
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 };
5686
+ async processTaskStarted(registration, record2) {
5687
+ 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
5688
  }
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);
5689
+ async processUserInput(registration, activeTask, record2) {
5690
+ if (activeTask === void 0 || activeTask.codex_turn_id !== record2.turn_id) {
5691
+ const adopted = await this.adoptHookCorrelatedTurn(registration, record2);
3973
5692
  if (adopted === void 0) return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
3974
5693
  activeTask = adopted;
3975
5694
  }
3976
- const hostInputRef = hostInputReference(registration.host_source_ref, registration.host_session_ref, record.turn_id, record.message_id, record.ordinal, record.prompt);
5695
+ const hostInputRef = hostInputReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id, record2.message_id, record2.ordinal, record2.prompt);
3977
5696
  const origin = activeTask.origin_host_input_ref === void 0;
3978
- const promptValue = promptObservationValue(record.prompt);
5697
+ const promptValue = promptObservationValue(record2.prompt);
3979
5698
  const currentPromptRef = hostProducerPromptRef(promptValue.body_sha256);
3980
5699
  const promptRef = activeTask.prompt_ref ?? currentPromptRef;
3981
5700
  const steeredPromptRef = await this.steeredPromptRef(registration, activeTask, origin, currentPromptRef);
3982
5701
  const identity = { host_source_ref: registration.host_source_ref, host_session_ref: registration.host_session_ref, host_turn_ref: activeTask.host_turn_ref };
3983
5702
  const observations = [{
3984
- observation_ref: observationRef(registration.host_source_ref, "transcript_user_text", hostInputRef, record.prompt),
5703
+ observation_ref: observationRef(registration.host_source_ref, "transcript_user_text", hostInputRef, record2.prompt),
3985
5704
  observation_kind: "prompt",
3986
- observed_at: record.timestamp,
5705
+ observed_at: record2.timestamp,
3987
5706
  value: promptValue
3988
5707
  }];
3989
5708
  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") });
5709
+ 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
5710
  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 });
5711
+ 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
5712
  }
3994
5713
  const envelope = {
3995
5714
  schema_version: "ceal.codex_observation_outbox.v1",
@@ -3997,10 +5716,10 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
3997
5716
  host_input_ref: hostInputRef,
3998
5717
  prompt_ref: promptRef,
3999
5718
  observations,
4000
- codex_turn_id: record.turn_id,
5719
+ codex_turn_id: record2.turn_id,
4001
5720
  origin_input: origin,
4002
- submission_ref: codexSubmissionReference(hostInputRef, "input", record.ordinal),
4003
- created_at: record.timestamp,
5721
+ submission_ref: codexSubmissionReference(hostInputRef, "input", record2.ordinal),
5722
+ created_at: record2.timestamp,
4004
5723
  expires_at: this.expire(this.outboxRetentionMs)
4005
5724
  };
4006
5725
  const persisted = await this.persistUserInputTurn(activeTask, hostInputRef, origin, currentPromptRef, promptRef, identity, envelope);
@@ -4030,14 +5749,14 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
4030
5749
  * stay ignored. A stale active task for another turn releases first, the
4031
5750
  * same as a task_started supersession.
4032
5751
  */
4033
- async adoptHookCorrelatedTurn(registration, record) {
4034
- const currentPromptRef = hostProducerPromptRef(promptObservationValue(record.prompt).body_sha256);
5752
+ async adoptHookCorrelatedTurn(registration, record2) {
5753
+ const currentPromptRef = hostProducerPromptRef(promptObservationValue(record2.prompt).body_sha256);
4035
5754
  const selection = await this.store.readInvocationTurnSelection(registration.host_source_ref, registration.host_session_ref);
4036
5755
  if (selection?.prompt_ref !== currentPromptRef) return void 0;
4037
5756
  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
5757
+ codex_turn_id: record2.turn_id,
5758
+ host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id),
5759
+ started_at: record2.timestamp
4041
5760
  };
4042
5761
  }
4043
5762
  async persistUserInputTurn(activeTask, hostInputRef, origin, currentPromptRef, promptRef, identity, envelope) {
@@ -4056,21 +5775,21 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
4056
5775
  throw error;
4057
5776
  }
4058
5777
  }
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 };
5778
+ async processTerminal(registration, activeTask, record2) {
5779
+ 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
5780
  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);
5781
+ 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 };
5782
+ const observations = terminalObservations(registration, activeTask, record2, timing);
4064
5783
  await this.store.put({
4065
5784
  schema_version: "ceal.codex_observation_outbox.v1",
4066
5785
  identity,
4067
5786
  host_input_ref: activeTask.origin_host_input_ref,
4068
5787
  prompt_ref: activeTask.prompt_ref,
4069
5788
  observations,
4070
- codex_turn_id: record.turn_id,
5789
+ codex_turn_id: record2.turn_id,
4071
5790
  origin_input: false,
4072
- submission_ref: codexSubmissionReference(activeTask.origin_host_input_ref, "terminal", record.ordinal),
4073
- created_at: record.timestamp,
5791
+ submission_ref: codexSubmissionReference(activeTask.origin_host_input_ref, "terminal", record2.ordinal),
5792
+ created_at: record2.timestamp,
4074
5793
  expires_at: this.expire(this.outboxRetentionMs)
4075
5794
  });
4076
5795
  await this.store.clearInvocationContext(identity, this.now());
@@ -4081,6 +5800,29 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
4081
5800
  await this.store.writeTranscriptCursor(quarantined);
4082
5801
  }
4083
5802
  };
5803
+ async function readCodexHumanMessageProjection(registration, cursor, readChunk) {
5804
+ let offset = 0;
5805
+ const state = { records: 0, lastOrdinal: 0, window: { messages: [], truncated: false } };
5806
+ while (offset < cursor.offset) {
5807
+ const complete = await readChunk(offset, cursor.offset);
5808
+ if (complete === "empty" || complete === "partial") throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix is incomplete.");
5809
+ consumeCodexHumanMessageProjectionChunk(registration, complete, state);
5810
+ offset += complete.length;
5811
+ }
5812
+ 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.");
5813
+ return state.window;
5814
+ }
5815
+ function consumeCodexHumanMessageProjectionChunk(registration, complete, state) {
5816
+ for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
5817
+ const record2 = decodeCodexTranscriptLine(line);
5818
+ if (state.records === 0) assertCodexTranscriptHeader(registration, record2);
5819
+ else if (record2.ordinal <= state.lastOrdinal) throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix has a nonmonotonic ordinal.");
5820
+ const message = codexHumanMessage(registration, record2);
5821
+ if (message !== null) state.window = mergeHostInvocationHumanMessageWindow(state.window, [message]);
5822
+ state.lastOrdinal = record2.ordinal;
5823
+ state.records += 1;
5824
+ }
5825
+ }
4084
5826
  function codexTranscriptScanFailureKind(error) {
4085
5827
  return transcriptScanFailureKind(error, (candidate) => {
4086
5828
  if (!(candidate instanceof CodexHostAdapterError)) return void 0;
@@ -4089,10 +5831,10 @@ function codexTranscriptScanFailureKind(error) {
4089
5831
  return void 0;
4090
5832
  });
4091
5833
  }
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;
5834
+ function accumulateTokenCount(activeTask, record2) {
5835
+ if (record2.usage_gap_reason !== void 0) return { ...activeTask, token_usage_gap_reason: record2.usage_gap_reason };
5836
+ const last = record2.last_usage;
5837
+ const total = record2.total_usage;
4096
5838
  if (last === void 0 || ignoreTokenCount(activeTask.last_total_usage, total, last)) return activeTask;
4097
5839
  const tokenUsage = addUsage(activeTask.token_usage, last);
4098
5840
  return {
@@ -4106,14 +5848,14 @@ function ignoreTokenCount(previous, total, last) {
4106
5848
  if (total === void 0 || previous === void 0) return false;
4107
5849
  return sameUsage(total, previous) || regressedUsage(total, previous) && looksLikeStaleRegression(total, previous, last);
4108
5850
  }
4109
- function terminalObservations(registration, activeTask, record, timing) {
5851
+ function terminalObservations(registration, activeTask, record2, timing) {
4110
5852
  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
5853
  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 }
5854
+ { 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") },
5855
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_timing", activeTask.host_turn_ref, timing), observation_kind: "timing", observed_at: record2.timestamp, value: timing },
5856
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_token", activeTask.host_turn_ref, tokenValue), observation_kind: "token", observed_at: record2.timestamp, value: tokenValue }
4115
5857
  ];
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" } });
5858
+ 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
5859
  return observations;
4118
5860
  }
4119
5861
  function notRecorded(reason) {
@@ -4162,16 +5904,24 @@ function looksLikeStaleRegression(current, previous, last) {
4162
5904
  if (previous.total_tokens <= 0 || current.total_tokens <= 0 || last.total_tokens <= 0) return false;
4163
5905
  return current.total_tokens * 100 >= previous.total_tokens * 98 || current.total_tokens + last.total_tokens * 2 >= previous.total_tokens;
4164
5906
  }
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);
5907
+ function codexHumanMessage(registration, record2) {
5908
+ if (record2.kind !== "user_text" || record2.content_item_kind !== "user.text") return null;
5909
+ return {
5910
+ host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id),
5911
+ host_input_ref: hostInputReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id, record2.message_id, record2.ordinal, record2.prompt),
5912
+ text: record2.prompt
5913
+ };
5914
+ }
5915
+ function assertRecordSequence(registration, cursor, records, lastOrdinal, record2) {
5916
+ 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}`)}).`);
5917
+ if (!cursor.header_validated && records === 0) assertCodexTranscriptHeader(registration, record2);
4168
5918
  }
4169
5919
 
4170
5920
  // host/codex/src/codex-producer-runtime.ts
4171
5921
  async function drainCodexProducerOnce(options) {
4172
5922
  const scan = await new CodexTranscriptWatcher({
4173
5923
  outbox_dir: options.outbox_dir,
4174
- diagnostic: (event, failure_kind) => writeHostServiceDiagnostic("codex", event, failure_kind)
5924
+ diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
4175
5925
  }).scanOnce().catch((error) => {
4176
5926
  writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
4177
5927
  throw error;
@@ -4180,6 +5930,237 @@ async function drainCodexProducerOnce(options) {
4180
5930
  return { scanned: scan.enqueued, ...await producer.drainOutbox() };
4181
5931
  }
4182
5932
 
5933
+ // host/codex/src/codex-usage-facts-capturer.ts
5934
+ import { createHash as createHash9 } from "node:crypto";
5935
+ var CodexUsageFactsCapturer = class {
5936
+ sources;
5937
+ usage;
5938
+ now;
5939
+ diagnosticSink;
5940
+ nextRegistrationIndex = 0;
5941
+ constructor(options) {
5942
+ this.sources = new CodexOutboxStore(options.outbox_dir);
5943
+ this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5944
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5945
+ this.diagnosticSink = options.diagnostic_sink;
5946
+ }
5947
+ async captureNext() {
5948
+ const registrations = await this.sources.listTranscriptRegistrations();
5949
+ const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
5950
+ this.nextRegistrationIndex = result.nextIndex;
5951
+ if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5952
+ return result.captured;
5953
+ }
5954
+ async captureRegistration(registration) {
5955
+ const prepared = await openHostUsageTranscriptCursor({
5956
+ path: registration.transcript_path,
5957
+ producer: "codex",
5958
+ source_kind: "codex_transcript",
5959
+ host_source_ref: registration.host_source_ref,
5960
+ host_session_ref: registration.host_session_ref,
5961
+ source_slot: "main",
5962
+ created_at: this.stamp(),
5963
+ store: this.usage,
5964
+ inspect: ownedCodexTranscriptFile,
5965
+ initial_cursor: initialCursor
5966
+ });
5967
+ if (prepared === null) return false;
5968
+ const { handle, source, source_file_ref: sourceFileRef, state, cursor: current } = prepared;
5969
+ try {
5970
+ if (await cursorReplaced(handle, source, sourceFileRef, current)) {
5971
+ const after = replacementCursor(sourceFileRef, source.device, source.inode);
5972
+ const gap = coverageGap("source_file_replaced", null, null, null, null);
5973
+ await this.usage.commitScanTransition(state, "main", current, after, null, [gap]);
5974
+ return true;
5975
+ }
5976
+ if (source.size === current.offset && !current.skipping_oversized_line) return false;
5977
+ return await this.captureChunk(handle, registration, current, sourceFileRef, source.size, state);
5978
+ } finally {
5979
+ await handle.close();
5980
+ }
5981
+ }
5982
+ async captureChunk(handle, registration, before, sourceFileRef, size, state) {
5983
+ const chunk = await readHostUsageTranscriptChunk(handle, before.offset, size, before.skipping_oversized_line);
5984
+ if (chunk.end_offset === before.offset && chunk.lines.length === 0) return false;
5985
+ const processed = processCodexLines(chunk.lines, registration, sourceFileRef, before, chunk.oversized_rows);
5986
+ const after = await updateAnchor(handle, { ...processed.cursor, offset: chunk.end_offset, skipping_oversized_line: chunk.skipping_oversized_line });
5987
+ const gaps = buildCoverageGaps(sourceFileRef, before.offset, chunk.end_offset, processed.gapCounts);
5988
+ const batch = processed.facts.length === 0 && gaps.length === 0 ? null : createCealHostUsageBatch({
5989
+ host_source_ref: registration.host_source_ref,
5990
+ host_session_ref: registration.host_session_ref,
5991
+ created_at: processed.createdAt,
5992
+ source_ranges: [{ source_file_ref: sourceFileRef, start_offset: before.offset, end_offset: chunk.end_offset }],
5993
+ facts: processed.facts,
5994
+ coverage_gaps: gaps
5995
+ });
5996
+ await this.usage.commitScanTransition(state, "main", before, after, batch);
5997
+ return true;
5998
+ }
5999
+ stamp() {
6000
+ const value = this.now();
6001
+ if (!Number.isFinite(value.getTime())) throw new Error("Codex usage facts clock is invalid.");
6002
+ return value.toISOString();
6003
+ }
6004
+ };
6005
+ function processCodexLines(lines, registration, sourceFileRef, initial, oversizedRows) {
6006
+ let cursor = initial;
6007
+ let createdAt = registration.registered_at;
6008
+ let records = 0;
6009
+ const facts = [];
6010
+ const gapCounts = /* @__PURE__ */ new Map();
6011
+ if (oversizedRows > 0) gapCounts.set("unsupported_source_shape", oversizedRows);
6012
+ for (const bytes of lines) {
6013
+ const record2 = decodeCodexLine(bytes);
6014
+ if (record2 === null || !validInitialHeader(record2, registration, initial.offset, records) || !hasIncreasingOrdinal(cursor, record2)) {
6015
+ addCodexGap(gapCounts, "unsupported_source_shape");
6016
+ records += 1;
6017
+ continue;
6018
+ }
6019
+ createdAt = record2.timestamp;
6020
+ cursor = applyCodexRecord(cursor, record2, registration, sourceFileRef, facts, gapCounts);
6021
+ cursor = { ...cursor, last_ordinal: record2.ordinal };
6022
+ records += 1;
6023
+ }
6024
+ return { cursor, facts, gapCounts, createdAt };
6025
+ }
6026
+ function decodeCodexLine(bytes) {
6027
+ try {
6028
+ return decodeCodexUsageTranscriptLine(bytes.toString("utf8"));
6029
+ } catch {
6030
+ return null;
6031
+ }
6032
+ }
6033
+ function validInitialHeader(record2, registration, initialOffset, records) {
6034
+ if (initialOffset !== 0 || records !== 0) return true;
6035
+ try {
6036
+ assertCodexTranscriptHeader(registration, record2);
6037
+ return true;
6038
+ } catch {
6039
+ return false;
6040
+ }
6041
+ }
6042
+ function hasIncreasingOrdinal(cursor, record2) {
6043
+ return cursor.last_ordinal === null || record2.ordinal > cursor.last_ordinal;
6044
+ }
6045
+ function applyCodexRecord(cursor, record2, registration, sourceFileRef, facts, gapCounts) {
6046
+ if (record2.kind === "token_count") return applyTokenCount(cursor, registration, sourceFileRef, record2, facts, gapCounts);
6047
+ 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 };
6048
+ if (record2.kind === "turn_context" && cursor.native_turn_id === record2.turn_id) return { ...cursor, requested_model: record2.model };
6049
+ 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 };
6050
+ return cursor;
6051
+ }
6052
+ function applyTokenCount(cursor, registration, sourceFileRef, record2, facts, gapCounts) {
6053
+ if (record2.usage_gap_reason !== void 0 || record2.last_usage === void 0 && record2.total_usage === void 0) addCodexGap(gapCounts, "source_usage_unavailable");
6054
+ else facts.push(codexUsageFact(registration, sourceFileRef, cursor, record2));
6055
+ return { ...cursor, codex_total_usage: record2.total_usage ?? cursor.codex_total_usage };
6056
+ }
6057
+ function addCodexGap(gaps, reason) {
6058
+ gaps.set(reason, (gaps.get(reason) ?? 0) + 1);
6059
+ }
6060
+ function initialCursor(sourceFileRef, device, inode) {
6061
+ return {
6062
+ source_file_ref: sourceFileRef,
6063
+ device,
6064
+ inode,
6065
+ offset: 0,
6066
+ anchor_start: 0,
6067
+ anchor_sha256: sha2564(Buffer.alloc(0)),
6068
+ last_ordinal: null,
6069
+ host_turn_ref: null,
6070
+ native_turn_id: null,
6071
+ requested_model: null,
6072
+ codex_total_usage: null,
6073
+ skipping_oversized_line: false
6074
+ };
6075
+ }
6076
+ function codexUsageFact(registration, sourceFileRef, cursor, record2) {
6077
+ const sourceEventRef = hostUsageSourceEventReference(sourceFileRef, `codex:${record2.ordinal}`);
6078
+ const total = record2.total_usage;
6079
+ const cumulativeTransition = transitionKind(cursor.codex_total_usage, total);
6080
+ const selected = record2.last_usage ?? total;
6081
+ const normalized = normalizedCounts(selected);
6082
+ return {
6083
+ fact_ref: hostUsageFactReference(sourceFileRef, sourceEventRef),
6084
+ host_session_ref: registration.host_session_ref,
6085
+ host_turn_ref: cursor.host_turn_ref,
6086
+ source_file_ref: sourceFileRef,
6087
+ source_event_ref: sourceEventRef,
6088
+ source_event_ordinal: record2.ordinal,
6089
+ observed_at: record2.timestamp,
6090
+ producer: "codex_transcript",
6091
+ requested_model: cursor.requested_model,
6092
+ reported_model: null,
6093
+ source_usage: { last_token_usage: record2.last_usage ?? null, total_token_usage: total ?? null },
6094
+ normalized_usage: normalized,
6095
+ counter_semantics: record2.last_usage !== void 0 && total !== void 0 ? "last_delta_total_cumulative" : total !== void 0 ? "total_cumulative_only" : "unknown",
6096
+ cumulative_transition: cumulativeTransition,
6097
+ finality: "unknown",
6098
+ correction_semantics: "unknown"
6099
+ };
6100
+ }
6101
+ function transitionKind(baseline, total) {
6102
+ if (total === void 0) return "not_observed";
6103
+ if (baseline === null) return "baseline";
6104
+ if (sameCounts(baseline, total)) return "same";
6105
+ return isRegression(total, baseline) ? "reset_or_correction" : "advanced";
6106
+ }
6107
+ function normalizedCounts(selected) {
6108
+ return selected === void 0 ? nullCounts() : {
6109
+ input: selected.input_tokens,
6110
+ output: selected.output_tokens,
6111
+ total: selected.total_tokens,
6112
+ cached_input: selected.cached_input_tokens,
6113
+ cache_write_input: selected.cache_write_input_tokens,
6114
+ reasoning_output: selected.reasoning_output_tokens
6115
+ };
6116
+ }
6117
+ function nullCounts() {
6118
+ return { input: null, output: null, total: null, cached_input: null, cache_write_input: null, reasoning_output: null };
6119
+ }
6120
+ var USAGE_COUNT_FIELDS = ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
6121
+ function isRegression(current, previous) {
6122
+ return USAGE_COUNT_FIELDS.some((key) => current[key] < previous[key]);
6123
+ }
6124
+ function sameCounts(left, right) {
6125
+ return USAGE_COUNT_FIELDS.every((key) => left[key] === right[key]);
6126
+ }
6127
+ function buildCoverageGaps(sourceFileRef, startOffset, endOffset, counts) {
6128
+ return [...counts].map(([reason, omittedCount]) => coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount));
6129
+ }
6130
+ function coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount) {
6131
+ return { reason, source_file_ref: sourceFileRef, start_offset: startOffset, end_offset: endOffset, omitted_count: omittedCount };
6132
+ }
6133
+ function sha2564(value) {
6134
+ return createHash9("sha256").update(value).digest("hex");
6135
+ }
6136
+ async function anchorMatches(handle, cursor) {
6137
+ const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
6138
+ if (bytes.length === 0) return sha2564(bytes) === cursor.anchor_sha256;
6139
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, cursor.anchor_start));
6140
+ return bytesRead === bytes.length && sha2564(bytes) === cursor.anchor_sha256;
6141
+ }
6142
+ async function cursorReplaced(handle, source, sourceFileRef, cursor) {
6143
+ return cursor.source_file_ref !== sourceFileRef || cursor.device !== source.device || cursor.inode !== source.inode || source.size < cursor.offset || !await anchorMatches(handle, cursor);
6144
+ }
6145
+ function replacementCursor(sourceFileRef, device, inode) {
6146
+ return {
6147
+ ...initialCursor(sourceFileRef, device, inode),
6148
+ source_file_ref: sourceFileRef,
6149
+ device,
6150
+ inode,
6151
+ offset: 0
6152
+ };
6153
+ }
6154
+ async function updateAnchor(handle, cursor) {
6155
+ const anchorStart = Math.max(0, cursor.offset - CODEX_TRANSCRIPT_ANCHOR_BYTES);
6156
+ const anchor = Buffer.alloc(cursor.offset - anchorStart);
6157
+ if (anchor.length > 0) {
6158
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(anchor, 0, anchor.length, anchorStart));
6159
+ if (bytesRead !== anchor.length) throw new Error("Codex usage facts source changed during anchor read.");
6160
+ }
6161
+ return { ...cursor, anchor_start: anchorStart, anchor_sha256: sha2564(anchor) };
6162
+ }
6163
+
4183
6164
  // host/codex/src/codex-producer-service.ts
4184
6165
  var CODEX_PRODUCER_CONFIG_SCHEMA = "ceal.codex_producer_config.v1";
4185
6166
  var CODEX_SESSIONS_ROOT = "codex_sessions_root";
@@ -4188,10 +6169,12 @@ var CODEX_PRODUCER_DESCRIPTOR = {
4188
6169
  producer_id: "codex",
4189
6170
  extra_paths: [CODEX_SESSIONS_ROOT],
4190
6171
  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
6172
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6173
+ drain: drainCodexProducerOnce,
6174
+ background: (config, signal) => {
6175
+ const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });
6176
+ return runHostUsageFactsUploader({ producer: "codex", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext() }, signal);
6177
+ }
4195
6178
  };
4196
6179
 
4197
6180
  // host/codex/src/codex-hook-runner.ts
@@ -4205,23 +6188,15 @@ function codexHookEventFromArgs(args) {
4205
6188
  const event = marker?.slice("--ceal-hook-event=".length);
4206
6189
  return isCodexHookEvent(event) ? event : null;
4207
6190
  }
4208
- async function runCodexHookProcess(args, stdin, options) {
4209
- const event = codexHookEventFromArgs(args);
4210
- if (event === null) return 0;
6191
+ async function runCodexHook(event, stdin, options) {
4211
6192
  try {
4212
6193
  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" });
6194
+ if (result.disposition === "rejected") writeHostServiceDiagnostic("codex", "hook_failed", void 0, void 0, options.diagnostic_sink);
6195
+ else if (result.reason === "transcript_registered") writeHostServiceDiagnostic("codex", "registration_written", void 0, void 0, options.diagnostic_sink);
4217
6196
  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
6197
  } catch {
6198
+ writeHostServiceDiagnostic("codex", "hook_failed", void 0, void 0, options.diagnostic_sink);
6199
+ return 0;
4225
6200
  }
4226
6201
  }
4227
6202
  async function readStdin(stdin) {
@@ -4237,11 +6212,19 @@ async function readStdin(stdin) {
4237
6212
  }
4238
6213
  async function runCodexHookCli() {
4239
6214
  const args = process.argv.slice(2);
4240
- const owner = await installedCodexHookRunnerOptions(args);
4241
- return runCodexHookProcess(args, process.stdin, owner);
6215
+ const event = codexHookEventFromArgs(args);
6216
+ if (event === null) return 0;
6217
+ writeHostServiceDiagnostic("codex", "hook_invoked");
6218
+ try {
6219
+ const owner = await installedCodexHookRunnerOptions(args);
6220
+ return runCodexHook(event, process.stdin, owner);
6221
+ } catch {
6222
+ writeHostServiceDiagnostic("codex", "hook_failed");
6223
+ return 0;
6224
+ }
4242
6225
  }
4243
- async function installedCodexHookRunnerOptions(args) {
4244
- const config = await readHostProducerConfig(CODEX_PRODUCER_DESCRIPTOR, parseHostProducerConfigFlag(args));
6226
+ async function installedCodexHookRunnerOptions(args, custody = {}) {
6227
+ const config = await readHostProducerConfig(CODEX_PRODUCER_DESCRIPTOR, parseHostProducerConfigFlag(args), process.platform, custody);
4245
6228
  return { host_source_ref: config.host_source_ref, outbox_dir: config.outbox_dir, codex_sessions_root: config.codex_sessions_root };
4246
6229
  }
4247
6230