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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,7 @@ const require = __cealCreateRequire(import.meta.url);
4
4
 
5
5
  // host/claude/src/claude-types.ts
6
6
  var CLAUDE_HOOK_EVENTS = ["SessionStart", "UserPromptSubmit"];
7
+ var CLAUDE_SESSION_ID_ENVIRONMENT = "CLAUDE_CODE_SESSION_ID";
7
8
  var CLAUDE_HOST_ERROR_CODES = ["invalid_input", "payload_rejected", "storage", "configuration"];
8
9
  function isClaudeHostErrorCode(value) {
9
10
  return typeof value === "string" && CLAUDE_HOST_ERROR_CODES.some((code2) => code2 === value);
@@ -33,7 +34,17 @@ function isClaudeHookEvent(value) {
33
34
  }
34
35
 
35
36
  // host/claude/src/claude-decoder.ts
36
- import { createHash as createHash3 } from "node:crypto";
37
+ import { createHash as createHash4 } from "node:crypto";
38
+ import { isAbsolute } from "node:path";
39
+
40
+ // packages/ceal-client-protocol/src/vocabulary.ts
41
+ function vocabulary(words) {
42
+ return Object.freeze(words);
43
+ }
44
+
45
+ // packages/ceal-client-protocol/src/host-usage-fields.ts
46
+ var CEAL_CODEX_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
47
+ var CEAL_CLAUDE_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"]);
37
48
 
38
49
  // packages/ceal-client-protocol/src/canonical-json.ts
39
50
  function cealCanonicalJson(value) {
@@ -63,7 +74,7 @@ function isPlainRecord(value) {
63
74
  }
64
75
 
65
76
  // packages/ceal-client-protocol/src/client-wire-contract.ts
66
- import { createHash } from "node:crypto";
77
+ import { createHash as createHash2 } from "node:crypto";
67
78
 
68
79
  // packages/ceal-client-protocol/client-wire-contract.json
69
80
  var client_wire_contract_default = {
@@ -84,7 +95,7 @@ var client_wire_contract_default = {
84
95
  ordering: "utf16_code_unit_ascending"
85
96
  },
86
97
  artifact_descriptor: {
87
- operation_contract_bundle_schema_name: "ceal.operation_contract_bundle",
98
+ operation_contract_bundle_schema_name: "ceal.operation_contract_bundle_v2",
88
99
  operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
89
100
  schema_name: "ceal.verified_artifact_descriptor",
90
101
  fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
@@ -109,7 +120,7 @@ var client_wire_contract_default = {
109
120
  },
110
121
  command_request: {
111
122
  schema_name: "ceal.command_request",
112
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
123
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
113
124
  absolute_transport_max_bytes: 65536
114
125
  },
115
126
  command_resolution: {
@@ -155,8 +166,9 @@ var client_wire_contract_default = {
155
166
  },
156
167
  command_response: {
157
168
  schema_name: "ceal.command_response",
158
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
169
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
159
170
  descriptor_field: "verified_artifact",
171
+ request_context_field: "request_context",
160
172
  required_fields: [
161
173
  "schema_version",
162
174
  "exit_code",
@@ -166,7 +178,8 @@ var client_wire_contract_default = {
166
178
  "operation_id",
167
179
  "visible_output_max_bytes",
168
180
  "local_delivery",
169
- "verified_artifact"
181
+ "verified_artifact",
182
+ "request_context"
170
183
  ],
171
184
  bare_document_fields: [
172
185
  "invocation",
@@ -187,7 +200,7 @@ var client_wire_contract_default = {
187
200
  ],
188
201
  exit_code_max: 125,
189
202
  bare_document_max_bytes: 65536,
190
- complete_max_bytes: 66046
203
+ complete_max_bytes: 66195
191
204
  },
192
205
  host_invocation_authentication: {
193
206
  request_schema_name: "ceal.host_invocation_authentication_request",
@@ -201,6 +214,17 @@ var client_wire_contract_default = {
201
214
  "context_token",
202
215
  "expires_at"
203
216
  ],
217
+ refusal_schema_name: "ceal.host_invocation_authentication_refusal",
218
+ refusal_fields: [
219
+ "schema_version",
220
+ "ok",
221
+ "code",
222
+ "reason",
223
+ "gateway_status",
224
+ "retry_after_ms"
225
+ ],
226
+ refusal_required_fields: ["schema_version", "ok", "code", "reason"],
227
+ refusal_optional_fields: ["gateway_status", "retry_after_ms"],
204
228
  client_nonce: {
205
229
  character_class_source: "A-Za-z0-9_-",
206
230
  encoded_characters: 43
@@ -239,6 +263,8 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
239
263
  "choose_new_output_path",
240
264
  "choose_new_idempotency_key",
241
265
  "restart_search",
266
+ // The requested temporal key is absent on some observed rows; repeating the same interval without `order` can return those rows.
267
+ "search_without_order",
242
268
  "repeat_original_arguments",
243
269
  // The occurrence this call addressed is settled and cannot move again -- a
244
270
  // denied effect approval, an expired continuation -- so the caller runs the
@@ -297,6 +323,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
297
323
  // The command needs caller-owned local materialization (for example an
298
324
  // @path file) before the Gateway can receive the argument.
299
325
  "materialize_local_argument",
326
+ // A missing or stale local Host bundle is repaired through its installed lifecycle and discovery owners.
327
+ "install_ceal_host",
328
+ // An explicit Client store override points at a missing file; unsetting it selects the one canonical default store without creating a second credential store.
329
+ "unset_context_store_path",
330
+ // The producer app must reload its installed Host hook before it can start a conversation with invocation context.
331
+ "restart_producer_app",
300
332
  // A peer's derived schema identifier changed with its field set; install or
301
333
  // upgrade the CLI and Host Relay to the Gateway's release before retrying.
302
334
  "upgrade_ceal_client"
@@ -405,18 +437,12 @@ var NON_MODEL_ACTION_TO_MODEL_ACTION = Object.freeze({
405
437
  });
406
438
  var RETRY_PROMISE_NEXT_ACTIONS = ["retry", "retry_after"];
407
439
  var RETRY_PROMISE = new Set(RETRY_PROMISE_NEXT_ACTIONS);
408
- var RECOVERABLE = new Set(CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS);
409
440
  var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
410
441
  provider_permission: "ask_admin",
411
442
  access_level: "ask_admin",
412
443
  personal_authorization_required: "connect_personal_account"
413
444
  });
414
445
 
415
- // packages/ceal-client-protocol/src/vocabulary.ts
416
- function vocabulary(words) {
417
- return Object.freeze(words);
418
- }
419
-
420
446
  // packages/ceal-client-protocol/src/gateway-response-types.ts
421
447
  var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
422
448
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
@@ -427,9 +453,9 @@ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "s
427
453
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
428
454
  var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
429
455
  var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
430
- var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "scope_limit_exceeded"]);
456
+ var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
431
457
  var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
432
- var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable"]);
458
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
433
459
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
434
460
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
435
461
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -500,10 +526,10 @@ function assertSafeJsonArray(value, options, depth, count) {
500
526
  if (value.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
501
527
  for (const item of value) assertSafeJsonValue(item, options, depth + 1, count);
502
528
  }
503
- function assertSafeJsonRecord(record4, options, depth, count) {
504
- const entries = Object.entries(record4);
529
+ function assertSafeJsonRecord(record5, options, depth, count) {
530
+ const entries = Object.entries(record5);
505
531
  if (entries.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
506
- const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record4.fields) : null;
532
+ const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record5.fields) : null;
507
533
  for (const [key, child] of entries) {
508
534
  if (key === "credential_material_included" && child !== false) invalidByContext(options);
509
535
  if (!isSafeNegativeMaterialAssertion(key, child)) assertSafeJsonKey(key, options);
@@ -553,16 +579,21 @@ function isSafeExternalHttpsUrl(value) {
553
579
  return false;
554
580
  }
555
581
  }
582
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE = "^https://[^\\s/@?#]+(?:[/?#][^\\s]*)?$";
583
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN = new RegExp(SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE, "u");
556
584
  function isSafeExternalHttpsUrlInput(value) {
557
585
  return typeof value === "string" && byteLength(value) <= 2048;
558
586
  }
559
- function isSafeExternalHttpsUrlShape(url) {
560
- return url.protocol === "https:" && url.username === "" && url.password === "" && url.hash === "";
587
+ function isSafeExternalHttpsUrlShape(url, allowFragment = false) {
588
+ return url.protocol === "https:" && url.hostname.length > 0 && url.username === "" && url.password === "" && (allowFragment || url.hash === "");
561
589
  }
562
590
  function isSafeResultContent(value, key) {
563
591
  const maximum = key === "text" ? 8192 : 1024;
564
592
  return typeof value === "string" && byteLength(value) <= maximum && firstDisallowedControl(value, "multi_line") === null;
565
593
  }
594
+ function requireSafeRef(value) {
595
+ if (typeof value !== "string" || !SAFE_REF.test(value)) invalidRequestOrResponse();
596
+ }
566
597
  var CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES = 512;
567
598
  function normalizeCealSingleLineText(value) {
568
599
  return value.split("").map((character) => hasControlCharacter(character) ? " " : character).join("").trim();
@@ -674,6 +705,7 @@ function cut(text) {
674
705
 
675
706
  // packages/ceal-client-protocol/src/operation-validation-primitives.ts
676
707
  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;
708
+ var EXPANDED_CANONICAL_ISO_TIMESTAMP = /^([+-])(\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/u;
677
709
  var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
678
710
  var CEAL_CALENDAR_DATE = new RegExp(CEAL_CALENDAR_DATE_PATTERN_SOURCE, "u");
679
711
  function isOperationRecord(value) {
@@ -684,13 +716,46 @@ function isOperationRecord(value) {
684
716
  function requireOperationRecord(value, message) {
685
717
  if (!isOperationRecord(value)) throw new TypeError(message);
686
718
  }
719
+ function requireExactOperationKeys(value, required, optional = [], message = "Operation contract has an invalid shape.") {
720
+ const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
721
+ if (required.some((key) => !Object.hasOwn(value, key))) throw new TypeError(message);
722
+ if (Object.keys(value).some((key) => !allowed.has(key))) throw new TypeError(message);
723
+ }
687
724
  function requireClosedValue(value, members, message) {
688
725
  if (typeof value !== "string" || !members.includes(value)) throw new TypeError(message);
689
726
  }
690
727
  function isCealIsoTimestamp(value) {
691
728
  return typeof value === "string" && parseCealIsoTimestamp(value) !== null;
692
729
  }
730
+ function canonicalCealIsoTimestamp(epochNanoseconds) {
731
+ const wholeSeconds = floorDivide(epochNanoseconds, 1000000000n);
732
+ const fractionalNanoseconds = epochNanoseconds - wholeSeconds * 1000000000n;
733
+ const utc = new Date(Number(wholeSeconds * 1000n));
734
+ const date = utc.toISOString().split(".")[0];
735
+ if (date === void 0) throw new TypeError("Ceal timestamp formatter returned an invalid ISO string");
736
+ const fraction = fractionalNanoseconds.toString().padStart(9, "0").replace(/0+$/u, "").padEnd(3, "0");
737
+ return date + "." + fraction + "Z";
738
+ }
739
+ var CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE = "0000-01-01T00:00:00.000000000+23:59";
740
+ var CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE = "9999-12-31T23:59:59.999999999-23:59";
741
+ var CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE);
742
+ var CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE);
743
+ var CEAL_INSTANT_INDEX_SPAN = CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS - CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS;
744
+ var CEAL_INSTANT_INDEX_KEY_WIDTH = CEAL_INSTANT_INDEX_SPAN.toString().length;
745
+ var CEAL_INSTANT_INDEX_KEY_PATTERN = new RegExp(`^\\d{${CEAL_INSTANT_INDEX_KEY_WIDTH}}$`, "u");
746
+ function requiredTimestampEpochNanoseconds(value) {
747
+ const parsed = parseFourDigitCealIsoTimestamp(value);
748
+ if (parsed === null) throw new Error("Ceal instant-index range basis is outside the timestamp grammar");
749
+ return parsed.epochNanoseconds;
750
+ }
693
751
  function parseCealIsoTimestamp(value) {
752
+ const ordinary = parseFourDigitCealIsoTimestamp(value);
753
+ if (ordinary !== null) return ordinary;
754
+ const expanded = parseExpandedCanonicalCealIsoTimestamp(value);
755
+ if (expanded === null || expanded.epochNanoseconds < CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS || expanded.epochNanoseconds > CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS) return null;
756
+ return canonicalCealIsoTimestamp(expanded.epochNanoseconds) === value ? expanded : null;
757
+ }
758
+ function parseFourDigitCealIsoTimestamp(value) {
694
759
  const fields = parseCealIsoTimestampFields(value);
695
760
  if (fields === null || !validCalendarDate(fields) || !validClockTime(fields) || !validUtcOffset(fields)) return null;
696
761
  const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
@@ -699,6 +764,28 @@ function parseCealIsoTimestamp(value) {
699
764
  epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
700
765
  };
701
766
  }
767
+ function parseExpandedCanonicalCealIsoTimestamp(value) {
768
+ const match = EXPANDED_CANONICAL_ISO_TIMESTAMP.exec(value);
769
+ if (match === null) return null;
770
+ const fields = {
771
+ year: (match[1] === "-" ? -1 : 1) * Number(match[2]),
772
+ month: Number(match[3]),
773
+ day: Number(match[4]),
774
+ hour: Number(match[5]),
775
+ minute: Number(match[6]),
776
+ second: Number(match[7]),
777
+ fraction: match[8] ?? "",
778
+ offsetSign: 0,
779
+ offsetHour: 0,
780
+ offsetMinute: 0
781
+ };
782
+ if (!validCalendarDate(fields) || !validClockTime(fields)) return null;
783
+ const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
784
+ if (!Number.isFinite(epochMilliseconds)) return null;
785
+ return {
786
+ epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
787
+ };
788
+ }
702
789
  function parseCealIsoTimestampFields(value) {
703
790
  const match = ISO_TIMESTAMP.exec(value);
704
791
  if (match === null) return null;
@@ -731,6 +818,10 @@ function cealFieldsEpochMilliseconds(fields) {
731
818
  const offsetMilliseconds = fields.offsetSign * (fields.offsetHour * 60 + fields.offsetMinute) * 6e4;
732
819
  return localMilliseconds - offsetMilliseconds;
733
820
  }
821
+ function floorDivide(value, divisor) {
822
+ const quotient = value / divisor;
823
+ return value % divisor < 0n ? quotient - 1n : quotient;
824
+ }
734
825
  function daysInMonth(year, month) {
735
826
  const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
736
827
  return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
@@ -748,6 +839,9 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
748
839
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
749
840
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
750
841
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
842
+ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
843
+ 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.";
844
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
751
845
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
752
846
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
753
847
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
@@ -773,6 +867,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
773
867
  refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
774
868
  refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
775
869
  refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
870
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
871
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
776
872
  refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
777
873
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
778
874
  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),
@@ -785,8 +881,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
785
881
  response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
786
882
  request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
787
883
  request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
884
+ resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
788
885
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
789
- 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),
886
+ contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
790
887
  // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
791
888
  // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
792
889
  // when the wait ends still unserved, moved from the `localFailureText` default branch.
@@ -796,13 +893,12 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
796
893
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
797
894
  internal_error: guidance("The Gateway failed without exposing internal state.", "answer_with_gap", 500),
798
895
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
799
- // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
896
+ // the static client variant was retired when the client started reading this table.
800
897
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
801
- // Restored verbatim from the retired `localFailureText` `unknown_outcome`
802
- // case: the outcome is unknown, so a read may be retried while a write
803
- // must receipt-check first. Collapsing both to "do not repeat the call"
804
- // forbids the safe read retry the sentence exists to allow.
805
- unknown_outcome: guidance("The transport outcome is unknown: a read may be retried; for a write, check write_receipt.get before repeating.", "answer_with_gap", 500),
898
+ gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
899
+ // The safe move varies by request. Keep the sentence conditional on the
900
+ // same `retryable` and `next_action` facts the response exposes.
901
+ unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
806
902
  // Restored verbatim from the retired `localFailureText`
807
903
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
808
904
  // session context unavailable, so the caller repairs or adopts the
@@ -883,24 +979,27 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
883
979
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
884
980
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
885
981
  // is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
886
- // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). The three rows
887
- // with their own sentences carry the retired policy remedies as Gateway-owned guidance. Statuses are the
982
+ // and `retryable` from `hostAuthenticationFailureForCause` (the table's explicit retry verdict). Cause-specific
983
+ // sentences carry only remedies proved by the Host or Relay cause; generic Gateway refusals do not prove a release mismatch.
984
+ // Statuses are the
888
985
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
889
986
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
890
987
  host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
891
988
  host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
892
989
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
893
- // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
894
- // missing exact-turn fact names the fresh Host turn, not a reinstall.
895
- 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),
896
- host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
897
- host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
990
+ // The bounded Host reason does not prove ephemerality. A Host refusal never
991
+ // changes mode; standalone remains the separate Client authority path.
992
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
993
+ host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
994
+ host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
995
+ host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
898
996
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
899
997
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
900
998
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
901
999
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
902
1000
  host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
903
1001
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1002
+ host_contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
904
1003
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
905
1004
  // producer-frame fault names the administrator repair step.
906
1005
  host_producer_frame_invalid: guidance("Ask an administrator to inspect and repair the producer frame, then start a fresh Host turn.", "ask_admin", 400),
@@ -910,56 +1009,13 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
910
1009
  host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
911
1010
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
912
1011
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
913
- host_relay_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1012
+ host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
914
1013
  host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
915
1014
  });
916
1015
  var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
917
1016
 
918
- // packages/ceal-client-protocol/src/client-wire-contract.ts
919
- var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
920
- var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
921
- var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
922
- var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
923
- var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
924
- var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
925
- function deriveCealClientWireSchemaVersion(schema) {
926
- 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))) {
927
- throw new TypeError("Client wire schema name or field set is invalid.");
928
- }
929
- const fields = schema.fields.filter((field) => field !== "schema_version").sort();
930
- const hash8 = createHash("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
931
- return `${schema.schema_name}.v1.${hash8}`;
932
- }
933
- var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
934
- var commandResolutionAuthority = commandResolution.authority;
935
- var commandResolutionSemanticOptions = commandResolution.semantic_options;
936
- var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
937
- var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
938
- var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
939
- var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
940
- var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
941
- var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
942
- var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
943
- var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
944
- var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
945
- var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
946
- var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
947
- var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
948
- var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
949
- var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
950
- var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
951
- var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
952
- var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
953
- var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
954
- var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
955
- var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
956
- var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
957
- var CEAL_COMMAND_RESPONSE_DISCOVERY_COMMAND = response.discovery_command;
958
- var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
959
- var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
960
- var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_DOCUMENT_FIELDS = Object.freeze([...response.discovery_manifest_document_fields]);
961
- 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 });
962
- var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
1017
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1018
+ import { createHash } from "node:crypto";
963
1019
 
964
1020
  // packages/ceal-client-protocol/src/operation-withheld-cause.ts
965
1021
  var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
@@ -988,7 +1044,7 @@ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
988
1044
  var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
989
1045
  var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
990
1046
  var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
991
- var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
1047
+ var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_applicable", "not_offered", "offered", "accepted", "rejected", "unknown"]);
992
1048
  var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
993
1049
  var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
994
1050
  var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
@@ -1005,13 +1061,161 @@ var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
1005
1061
  "interactive_unavailable"
1006
1062
  ]);
1007
1063
 
1064
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1065
+ var DIGEST = /^[a-f0-9]{64}$/u;
1066
+ var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1067
+ function isCealDigest(value) {
1068
+ return typeof value === "string" && DIGEST.test(value);
1069
+ }
1070
+ function cealRequestSha256(value) {
1071
+ return createHash("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1072
+ }
1073
+ function operationRecord(value, message) {
1074
+ requireOperationRecord(value, message);
1075
+ return value;
1076
+ }
1077
+ function invalid(message) {
1078
+ throw new TypeError(message);
1079
+ }
1080
+ function requirePrefixedRef(value, prefix, message) {
1081
+ if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1082
+ }
1083
+ function requireSafeRef2(value, message) {
1084
+ try {
1085
+ requireSafeRef(value);
1086
+ } catch {
1087
+ invalid(message);
1088
+ }
1089
+ }
1090
+
1091
+ // packages/ceal-client-protocol/src/request-authority.ts
1092
+ var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1093
+ var CEAL_REQUEST_REF_MAX_CHARACTERS = 128;
1094
+ var CEAL_REQUEST_REF_PATTERN_SOURCE = "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$";
1095
+ var CEAL_REQUEST_REF_PATTERN = new RegExp(CEAL_REQUEST_REF_PATTERN_SOURCE, "u");
1096
+ var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1097
+ var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1098
+ var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1099
+ var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1100
+ var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1101
+ var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1102
+ schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1103
+ ceal_request_ref: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_REF_MAX_CHARACTERS, pattern: CEAL_REQUEST_REF_PATTERN_SOURCE },
1104
+ created_at: { type: "string", minLength: 1, maxLength: 64 },
1105
+ authority: {
1106
+ type: "object",
1107
+ maxProperties: 5,
1108
+ additionalProperties: false,
1109
+ properties: {
1110
+ instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1111
+ access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1112
+ principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1113
+ execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1114
+ authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1115
+ },
1116
+ required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1117
+ }
1118
+ });
1119
+ var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1120
+ prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1121
+ host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1122
+ host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1123
+ 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." },
1124
+ host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1125
+ host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1126
+ });
1127
+ var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1128
+ 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." },
1129
+ 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." }
1130
+ });
1131
+ var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1132
+ requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1133
+ 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." }
1134
+ });
1135
+ var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1136
+ var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1137
+ var CEAL_REQUEST_JSON_SCHEMA = {
1138
+ type: "object",
1139
+ 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.",
1140
+ maxProperties: 14,
1141
+ additionalProperties: false,
1142
+ properties: {
1143
+ ...CEAL_REQUEST_COMMON_PROPERTIES,
1144
+ ...CEAL_REQUEST_HOST_PROPERTIES,
1145
+ ...CEAL_REQUEST_CALLER_PROPERTIES,
1146
+ ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1147
+ },
1148
+ required: CEAL_REQUEST_KEYS,
1149
+ anyOf: [
1150
+ {
1151
+ type: "object",
1152
+ required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1153
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1154
+ additionalProperties: false
1155
+ },
1156
+ {
1157
+ type: "object",
1158
+ required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1159
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1160
+ additionalProperties: false
1161
+ }
1162
+ ]
1163
+ };
1164
+
1165
+ // packages/ceal-client-protocol/src/client-wire-contract.ts
1166
+ var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
1167
+ var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
1168
+ var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
1169
+ var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
1170
+ var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
1171
+ var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
1172
+ function deriveCealClientWireSchemaVersion(schema) {
1173
+ 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))) {
1174
+ throw new TypeError("Client wire schema name or field set is invalid.");
1175
+ }
1176
+ const fields = schema.fields.filter((field) => field !== "schema_version").sort();
1177
+ const hash8 = createHash2("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
1178
+ return `${schema.schema_name}.v1.${hash8}`;
1179
+ }
1180
+ var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
1181
+ var commandResolutionAuthority = commandResolution.authority;
1182
+ var commandResolutionSemanticOptions = commandResolution.semantic_options;
1183
+ var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
1184
+ var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
1185
+ var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
1186
+ var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
1187
+ var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
1188
+ var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
1189
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
1190
+ var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
1191
+ var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
1192
+ var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
1193
+ var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
1194
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
1195
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
1196
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
1197
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
1198
+ var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
1199
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
1200
+ var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
1201
+ var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
1202
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
1203
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
1204
+ var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
1205
+ var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
1206
+ 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 });
1207
+ var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
1208
+
1209
+ // packages/ceal-client-protocol/src/access-level-vocabulary.ts
1210
+ var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1211
+
1008
1212
  // packages/ceal-client-protocol/src/operation-access-class.ts
1009
1213
  var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
1010
1214
 
1011
1215
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
1012
1216
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
1013
1217
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
1014
- var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1218
+ var CEAL_PROVIDER_BOUNDARY_FIELDS = vocabulary(["provider_boundary_ref", "provider_boundary_kind", "provider_boundary_label", "provider_native_id", "provider_boundary_evidence"]);
1015
1219
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
1016
1220
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
1017
1221
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1057,7 +1261,7 @@ var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1057
1261
  var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
1058
1262
  var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
1059
1263
  var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
1060
- var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
1264
+ var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary", "standard_names"]);
1061
1265
 
1062
1266
  // packages/ceal-client-protocol/src/operation-catalog.ts
1063
1267
  var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
@@ -1119,6 +1323,7 @@ var CEAL_SCHEMA_LITERALS = [
1119
1323
  "ceal.gateway_write_receipt_readback.v1",
1120
1324
  "ceal.gateway_write_request_receipt.v1",
1121
1325
  "ceal.host_observation.v1",
1326
+ "ceal.host_usage_batch.v1",
1122
1327
  "ceal.host_registration_request.v1",
1123
1328
  "ceal.host_registration_result.v1",
1124
1329
  CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
@@ -1147,12 +1352,12 @@ var CEAL_SCHEMA_LITERAL_SET = new Set(CEAL_SCHEMA_LITERALS);
1147
1352
  import { join } from "node:path";
1148
1353
  var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1149
1354
  bounded_store_sidecar: (root) => `${root}.jsonl`,
1150
- gateway_audit_archive: (root) => `${root}.jsonl`,
1151
1355
  gateway_access_group_connector_control_audit: (root) => `${root}.audit.jsonl`,
1152
1356
  gateway_access_group_connector_scope_audit: (root) => join(root, "profile-connector-scope-audit.jsonl"),
1153
1357
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
1154
1358
  gateway_access_group_connector_calendar_scope_audit: (root) => join(root, "profile-connector-calendar-scope-audit.jsonl"),
1155
1359
  gateway_access_group_connector_readiness_audit: (root) => join(root, "profile-connector-readiness.audit.jsonl"),
1360
+ gateway_deployment_events: (root) => join(root, "gateway-deployments.jsonl"),
1156
1361
  gateway_organization_audit_ledger: (root) => join(root, "organization-ledger.jsonl"),
1157
1362
  gateway_personal_client_audit: (root) => join(root, "audit.jsonl"),
1158
1363
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
@@ -1177,6 +1382,12 @@ var CEAL_LOWERCASE_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
1177
1382
  var CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN = new RegExp(`^host-registration-attempt:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1178
1383
  var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1179
1384
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1385
+ var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1386
+
1387
+ // packages/ceal-client-protocol/src/resource-read-result.ts
1388
+ var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
1389
+ var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
1390
+ var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1180
1391
 
1181
1392
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
1182
1393
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
@@ -1195,7 +1406,7 @@ function shellSingleQuoted(value) {
1195
1406
  return `'${value.replaceAll("'", "'\\''")}'`;
1196
1407
  }
1197
1408
  var CEAL_OPERATION_CONTRACT_REQUIRED_FIELDS = Object.freeze(["input_schema", "result_schema"]);
1198
- var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["summary", "input_resolution"]);
1409
+ var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["branches", "summary", "input_resolution"]);
1199
1410
  var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
1200
1411
  $schema: CEAL_JSON_SCHEMA_2020_12,
1201
1412
  $id: "https://ceal.dev/schemas/verified-artifact-descriptor.v1.schema.json",
@@ -1240,11 +1451,93 @@ var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_o
1240
1451
  // packages/ceal-client-protocol/src/actor-kind.ts
1241
1452
  var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
1242
1453
 
1454
+ // packages/ceal-client-protocol/src/provider-link-policy.ts
1455
+ var PROVIDER_LINK_RESULT_FIELDS = Object.freeze({
1456
+ read_row: Object.freeze({ human_link: "source_url", parent_context: Object.freeze(["thread_ref"]) }),
1457
+ write_result: Object.freeze({ human_links: Object.freeze(["user_openable_url", "url", "spreadsheet_url", "meet_url"]) })
1458
+ });
1459
+ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1460
+ { 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/" },
1461
+ { 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/" },
1462
+ { 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/" },
1463
+ { 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/" },
1464
+ { 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/" },
1465
+ { 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" },
1466
+ { 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" },
1467
+ { 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" },
1468
+ { 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" },
1469
+ { 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" },
1470
+ { 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" },
1471
+ { 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" },
1472
+ { 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" },
1473
+ { 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" },
1474
+ { 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" },
1475
+ { 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" },
1476
+ { provider: "google-workspace", result_kind: "form_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified Forms responderUri", source: "https://developers.google.com/workspace/forms/api/reference/rest/v1/forms" },
1477
+ { 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" },
1478
+ { 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" },
1479
+ { 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" },
1480
+ { 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" }
1481
+ ]);
1482
+ var PROVIDER_LINK_HOSTS = Object.freeze({
1483
+ notion: Object.freeze(["notion.so", "www.notion.so", "notion.com", "www.notion.com", "app.notion.com"]),
1484
+ google_workspace: Object.freeze([
1485
+ "calendar.google.com",
1486
+ "contacts.google.com",
1487
+ "docs.google.com",
1488
+ "drive.google.com",
1489
+ "forms.google.com",
1490
+ "mail.google.com",
1491
+ "meet.google.com",
1492
+ "sites.google.com",
1493
+ "www.google.com"
1494
+ ])
1495
+ });
1496
+ var NOTION_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.notion);
1497
+ var GOOGLE_WORKSPACE_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.google_workspace);
1498
+ var PROVIDER_RESOURCE_SOURCE_URL_SCHEMA = Object.freeze({
1499
+ type: "string",
1500
+ minLength: 1,
1501
+ maxLength: 2048,
1502
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1503
+ 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."
1504
+ });
1505
+ var PROVIDER_USER_OPENABLE_URL_SCHEMA = Object.freeze({
1506
+ type: "string",
1507
+ minLength: 1,
1508
+ maxLength: 2048,
1509
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1510
+ 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."
1511
+ });
1512
+
1243
1513
  // packages/ceal-client-protocol/src/resource-row.ts
1244
1514
  var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
1245
1515
  var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
1246
1516
  var CEAL_RESOURCE_SEARCH_DIRECTIONS = vocabulary(["ascending", "descending"]);
1247
- 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"]);
1517
+ var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
1518
+ "query",
1519
+ "modified_since",
1520
+ "since",
1521
+ "until",
1522
+ "filetype",
1523
+ "authored_by_me",
1524
+ "authored_by",
1525
+ "edited_by",
1526
+ "include_replies",
1527
+ "kinds",
1528
+ "container_ref",
1529
+ "container_refs",
1530
+ "container_names",
1531
+ "addressed_to_me",
1532
+ "unread",
1533
+ "archived",
1534
+ "state",
1535
+ "event_types",
1536
+ "starred",
1537
+ "trashed",
1538
+ "permission"
1539
+ ]);
1540
+ var CEAL_RESOURCE_SEARCH_STATES = vocabulary(["open", "closed", "draft", "prerelease", "confirmed", "tentative", "cancelled"]);
1248
1541
  var CEAL_RESOURCE_TIME_BASES = vocabulary(["created", "modified", "viewed"]);
1249
1542
  var CEAL_REPOSITORY_VISIBILITIES = vocabulary(["public", "private", "internal"]);
1250
1543
  var CEAL_ACTIVITY_V3_KINDS = vocabulary(["authored", "edited", "messaged", "responded"]);
@@ -1340,6 +1633,8 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1340
1633
  container_label: { required: true, timestamp: false },
1341
1634
  container_ref: { required: false, timestamp: false },
1342
1635
  source_url: { required: false, timestamp: false },
1636
+ thread_ref: { required: false, timestamp: false },
1637
+ reply_count: { required: false, timestamp: false },
1343
1638
  source: { required: true, timestamp: false },
1344
1639
  owner: { required: false, timestamp: false },
1345
1640
  actor_kind: { required: false, timestamp: false },
@@ -1348,6 +1643,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1348
1643
  created_at: { required: false, timestamp: true },
1349
1644
  created_at_local: { required: false, timestamp: true },
1350
1645
  modified_at: { required: false, timestamp: true },
1646
+ observed_at: { required: false, timestamp: true },
1351
1647
  modified_at_local: { required: false, timestamp: true },
1352
1648
  viewed_by_me_at: { required: false, timestamp: true },
1353
1649
  modified_by_me_at: { required: false, timestamp: true },
@@ -1365,6 +1661,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1365
1661
  start: { required: false, timestamp: false },
1366
1662
  end: { required: false, timestamp: false },
1367
1663
  status: { required: false, timestamp: false },
1664
+ event_type: { required: false, timestamp: false },
1368
1665
  snippet: { required: false, timestamp: false },
1369
1666
  dated_notes: { required: false, timestamp: false },
1370
1667
  state: { required: true, timestamp: false },
@@ -1374,9 +1671,6 @@ var RESOURCE_ROW_REQUIRED_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(
1374
1671
  var RESOURCE_ROW_KEYS = new Set(Object.keys(RESOURCE_ROW_KEY_RULES));
1375
1672
  var RESOURCE_ROW_TIMESTAMP_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(([key, rule]) => rule.timestamp ? [key] : []);
1376
1673
 
1377
- // packages/ceal-client-protocol/src/resource-read-result.ts
1378
- var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1379
-
1380
1674
  // packages/ceal-client-protocol/src/excluded-target-coverage.ts
1381
1675
  var CEAL_EXCLUDED_TARGET_COVERAGE_MAX_ENTRIES = 64;
1382
1676
  function cealExcludedTargetCoverageJsonSchema() {
@@ -1428,6 +1722,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1428
1722
  "refresh_inactive",
1429
1723
  "refresh_replayed",
1430
1724
  "refresh_revoked",
1725
+ "person_inactive",
1726
+ "principal_inactive",
1431
1727
  "authority_replaced",
1432
1728
  "refresh_recovery_unavailable",
1433
1729
  "refresh_recovery_expired",
@@ -1448,97 +1744,6 @@ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
1448
1744
  var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1449
1745
  var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1450
1746
 
1451
- // packages/ceal-client-protocol/src/request-validation-primitives.ts
1452
- import { createHash as createHash2 } from "node:crypto";
1453
- var DIGEST = /^[a-f0-9]{64}$/u;
1454
- var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1455
- function isCealDigest(value) {
1456
- return typeof value === "string" && DIGEST.test(value);
1457
- }
1458
- function cealRequestSha256(value) {
1459
- return createHash2("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1460
- }
1461
- function operationRecord(value, message) {
1462
- requireOperationRecord(value, message);
1463
- return value;
1464
- }
1465
- function invalid(message) {
1466
- throw new TypeError(message);
1467
- }
1468
- function requirePrefixedRef(value, prefix, message) {
1469
- if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1470
- }
1471
-
1472
- // packages/ceal-client-protocol/src/request-authority.ts
1473
- var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1474
- var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1475
- var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1476
- var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1477
- var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1478
- var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1479
- var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1480
- schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1481
- ceal_request_ref: { type: "string", minLength: 1, maxLength: 128, pattern: "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$" },
1482
- created_at: { type: "string", minLength: 1, maxLength: 64 },
1483
- authority: {
1484
- type: "object",
1485
- maxProperties: 5,
1486
- additionalProperties: false,
1487
- properties: {
1488
- instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1489
- access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1490
- principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1491
- execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1492
- authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1493
- },
1494
- required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1495
- }
1496
- });
1497
- var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1498
- prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1499
- host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1500
- host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1501
- host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1502
- host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1503
- });
1504
- var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1505
- 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." },
1506
- 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." }
1507
- });
1508
- var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1509
- requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1510
- 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." }
1511
- });
1512
- var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1513
- var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1514
- var CEAL_REQUEST_JSON_SCHEMA = {
1515
- type: "object",
1516
- 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.",
1517
- maxProperties: 13,
1518
- additionalProperties: false,
1519
- properties: {
1520
- ...CEAL_REQUEST_COMMON_PROPERTIES,
1521
- ...CEAL_REQUEST_HOST_PROPERTIES,
1522
- ...CEAL_REQUEST_CALLER_PROPERTIES,
1523
- ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1524
- },
1525
- required: CEAL_REQUEST_KEYS,
1526
- anyOf: [
1527
- {
1528
- type: "object",
1529
- required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1530
- properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1531
- additionalProperties: false
1532
- },
1533
- {
1534
- type: "object",
1535
- required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1536
- properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1537
- additionalProperties: false
1538
- }
1539
- ]
1540
- };
1541
-
1542
1747
  // packages/ceal-client-protocol/src/request-operands.ts
1543
1748
  var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1544
1749
  var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
@@ -1646,6 +1851,27 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
1646
1851
  required: ["schema_version", "order", "nodes", "call_budget"]
1647
1852
  };
1648
1853
 
1854
+ // packages/ceal-client-protocol/src/host-observation-validation.ts
1855
+ var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1856
+ 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;
1857
+ function validateCealHostObservationValue(value) {
1858
+ if (value === void 0) throw new TypeError("Ceal Host observation value is invalid.");
1859
+ assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1860
+ if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) throw new TypeError("Ceal Host observation value is oversized.");
1861
+ inspectHostKeys(value);
1862
+ }
1863
+ function inspectHostKeys(value) {
1864
+ if (Array.isArray(value)) {
1865
+ for (const entry of value) inspectHostKeys(entry);
1866
+ return;
1867
+ }
1868
+ if (value === null || typeof value !== "object") return;
1869
+ for (const [key, child] of Object.entries(value)) {
1870
+ if (HOST_RESERVED_KEY.test(key)) throw new TypeError("Ceal Host observation cannot restate Gateway-owned facts.");
1871
+ inspectHostKeys(child);
1872
+ }
1873
+ }
1874
+
1649
1875
  // packages/ceal-client-protocol/src/host-observation.ts
1650
1876
  var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
1651
1877
  var HOST_OBSERVATION_PRODUCER = /^[a-z][a-z0-9]{0,31}$/u;
@@ -1692,35 +1918,238 @@ function safeCount(value) {
1692
1918
  return Number.isSafeInteger(value) && Number(value) >= 0;
1693
1919
  }
1694
1920
  function validateCealHostObservationDraft(value) {
1695
- const record4 = operationRecord(value, "Ceal Host observation draft is invalid.");
1696
- requirePrefixedRef(record4.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1697
- requireClosedValue(record4.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1698
- requireIsoTimestamp(record4.observed_at, "Ceal Host observation time is invalid.");
1699
- assertHostObservationValue(record4.value, record4.observation_kind);
1921
+ const record5 = operationRecord(value, "Ceal Host observation draft is invalid.");
1922
+ requirePrefixedRef(record5.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1923
+ requireClosedValue(record5.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1924
+ requireIsoTimestamp(record5.observed_at, "Ceal Host observation time is invalid.");
1925
+ assertHostObservationValue(record5.value, record5.observation_kind);
1700
1926
  }
1701
- var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1702
1927
  var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
1703
1928
  function isCealHostPromptObservationValue(value) {
1704
1929
  return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
1705
1930
  }
1706
- 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;
1707
1931
  function assertHostObservationValue(value, kind) {
1708
1932
  if (value === void 0) invalid("Ceal Host observation value is invalid.");
1709
1933
  if (kind === "prompt" && !isCealHostPromptObservationValue(value)) invalid("Ceal Host prompt observation must contain only its body digest.");
1710
- assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1711
- if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) invalid("Ceal Host observation value is oversized.");
1712
- inspectHostKeys(value);
1934
+ validateCealHostObservationValue(value);
1713
1935
  }
1714
- function inspectHostKeys(value) {
1715
- if (Array.isArray(value)) {
1716
- for (const entry of value) inspectHostKeys(entry);
1936
+
1937
+ // packages/ceal-client-protocol/src/host-usage-facts.ts
1938
+ import { createHash as createHash3 } from "node:crypto";
1939
+ var CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION = "ceal.host_usage_batch.v1";
1940
+ var CEAL_HOST_USAGE_BATCH_REF_PREFIX = "host-usage-batch:";
1941
+ var CEAL_HOST_USAGE_INGRESS_PATH = "/api/ceal/v2/host-usage-batches";
1942
+ var CEAL_HOST_USAGE_BATCH_MAX_BYTES = 1024 * 1024;
1943
+ var CEAL_HOST_USAGE_FACT_MAX_BYTES = 64 * 1024;
1944
+ var CEAL_HOST_USAGE_BATCH_MAX_FACTS = 256;
1945
+ var CEAL_HOST_USAGE_BATCH_MAX_GAPS = 16;
1946
+ var CEAL_HOST_USAGE_BATCH_ACK_STATUS = 204;
1947
+ var CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES = 65;
1948
+ var CODEX_COUNTER_SEMANTICS = ["last_delta_total_cumulative", "total_cumulative_only", "unknown"];
1949
+ var CODEX_CUMULATIVE_TRANSITIONS = ["baseline", "advanced", "same", "reset_or_correction", "not_observed"];
1950
+ var HOST_USAGE_COVERAGE_GAP_REASONS = ["source_usage_unavailable", "source_file_replaced", "source_file_retired", "outbox_capacity", "unsupported_source_shape"];
1951
+ function createCealHostUsageBatch(input) {
1952
+ const body = { schema_version: CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION, ...input };
1953
+ const batch = { ...body, batch_ref: `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}` };
1954
+ validateCealHostUsageBatch(batch);
1955
+ return batch;
1956
+ }
1957
+ function validateCealHostUsageBatch(value) {
1958
+ if (!isOperationRecord(value)) invalid("Ceal Host usage batch is invalid.");
1959
+ requireExactOperationKeys(value, ["schema_version", "batch_ref", "host_source_ref", "host_session_ref", "created_at", "source_ranges", "facts", "coverage_gaps"]);
1960
+ 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.");
1961
+ const { batch_ref: _ref, ...body } = value;
1962
+ if (value.batch_ref !== `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}`) invalid("Ceal Host usage batch reference is invalid.");
1963
+ validateBatchMetadata(value);
1964
+ validateBatchContents(value);
1965
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_BATCH_MAX_BYTES) invalid("Ceal Host usage batch exceeds its byte limit.");
1966
+ }
1967
+ function validateBatchMetadata(value) {
1968
+ requireSafeRef2(value.host_source_ref, "Ceal Host usage source is invalid.");
1969
+ requireSafeRef2(value.host_session_ref, "Ceal Host usage session is invalid.");
1970
+ requireIsoTimestamp(value.created_at, "Ceal Host usage batch time is invalid.");
1971
+ 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.");
1972
+ for (const range of value.source_ranges) validateSourceRange(range);
1973
+ }
1974
+ function validateBatchContents(value) {
1975
+ const facts = validateBatchFacts(value.facts);
1976
+ const gaps = validateBatchGaps(value.coverage_gaps);
1977
+ if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
1978
+ const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
1979
+ for (const fact of facts) {
1980
+ validateCealHostUsageFact(fact, value.host_session_ref);
1981
+ if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
1982
+ }
1983
+ for (const gap of gaps) {
1984
+ validateCoverageGap(gap);
1985
+ if (gap.source_file_ref !== null && !sourceFiles.has(gap.source_file_ref)) invalid("Ceal Host usage coverage gap is outside its source ranges.");
1986
+ }
1987
+ }
1988
+ function validateBatchFacts(value) {
1989
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_FACTS) invalid("Ceal Host usage fact count is invalid.");
1990
+ return value;
1991
+ }
1992
+ function validateBatchGaps(value) {
1993
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) invalid("Ceal Host usage coverage is invalid.");
1994
+ return value;
1995
+ }
1996
+ function sourceRangeFileRef(value) {
1997
+ return isOperationRecord(value) ? value.source_file_ref : null;
1998
+ }
1999
+ function hostUsageFactReference(sourceFileRef2, sourceEventRef) {
2000
+ requireSafeRef2(sourceFileRef2, "Ceal Host usage file reference is invalid.");
2001
+ requireSafeRef2(sourceEventRef, "Ceal Host usage event reference is invalid.");
2002
+ return `host-usage-fact:${sha256(JSON.stringify({ source_file_ref: sourceFileRef2, source_event_ref: sourceEventRef }))}`;
2003
+ }
2004
+ function hostUsageSourceEventReference(sourceFileRef2, sourceEventIdentity) {
2005
+ requireSafeRef2(sourceFileRef2, "Ceal Host usage file reference is invalid.");
2006
+ if (typeof sourceEventIdentity !== "string" || sourceEventIdentity.length === 0 || sourceEventIdentity.length > 1024) invalid("Ceal Host usage event identity is invalid.");
2007
+ return `host-source-event:${sha256(JSON.stringify({ source_file_ref: sourceFileRef2, source_event_identity: sourceEventIdentity }))}`;
2008
+ }
2009
+ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, device, inode) {
2010
+ 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.");
2011
+ return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
2012
+ }
2013
+ function validateCealHostUsageFact(value, sessionRef) {
2014
+ if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
2015
+ requireFactByteLimit(value);
2016
+ if (value.producer === "codex_transcript") validateCodexFact(value);
2017
+ else if (value.producer === "claude_transcript") validateClaudeFact(value);
2018
+ else invalid("Ceal Host usage producer is invalid.");
2019
+ if (value.host_session_ref !== sessionRef) invalid("Ceal Host usage session does not match its batch.");
2020
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage file reference is invalid.");
2021
+ requireSafeRef2(value.source_event_ref, "Ceal Host usage event reference is invalid.");
2022
+ if (value.host_turn_ref !== null) requireSafeRef2(value.host_turn_ref, "Ceal Host usage turn reference is invalid.");
2023
+ if (value.requested_model !== null && !boundedText(value.requested_model, 256)) invalid("Ceal Host requested model is invalid.");
2024
+ if (value.reported_model !== null && !boundedText(value.reported_model, 256)) invalid("Ceal Host reported model is invalid.");
2025
+ if (value.fact_ref !== hostUsageFactReference(value.source_file_ref, value.source_event_ref)) invalid("Ceal Host usage identity is invalid.");
2026
+ }
2027
+ function requireFactByteLimit(value) {
2028
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_FACT_MAX_BYTES) invalid("Ceal Host usage fact exceeds its byte limit.");
2029
+ }
2030
+ function validateCodexFact(value) {
2031
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fact is invalid.");
2032
+ 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"]);
2033
+ if (value.producer !== "codex_transcript" || !safeInteger(value.source_event_ordinal)) invalid("Ceal Codex usage fact is invalid.");
2034
+ requireIsoTimestamp(value.observed_at, "Ceal Codex usage time is invalid.");
2035
+ if (!isOperationRecord(value.source_usage)) invalid("Ceal Codex source usage is invalid.");
2036
+ requireExactOperationKeys(value.source_usage, ["last_token_usage", "total_token_usage"]);
2037
+ if (value.source_usage.last_token_usage !== null) validateCodexUsageCounts(value.source_usage.last_token_usage);
2038
+ if (value.source_usage.total_token_usage !== null) validateCodexUsageCounts(value.source_usage.total_token_usage);
2039
+ 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.");
2040
+ validateNormalizedUsage(value.normalized_usage);
2041
+ }
2042
+ function validateClaudeFact(value) {
2043
+ if (!isOperationRecord(value)) invalid("Ceal Claude usage fact is invalid.");
2044
+ 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"]);
2045
+ validateClaudeIdentity(value);
2046
+ requireIsoTimestamp(value.observed_at, "Ceal Claude usage time is invalid.");
2047
+ validateClaudeSourceUsage(value.source_usage);
2048
+ validateClaudeSemantics(value);
2049
+ validateNormalizedUsage(value.normalized_usage);
2050
+ }
2051
+ function validateClaudeIdentity(value) {
2052
+ 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.");
2053
+ }
2054
+ function validateClaudeSourceUsage(value) {
2055
+ if (!isOperationRecord(value)) invalid("Ceal Claude source usage is invalid.");
2056
+ requireExactOperationKeys(value, ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"], ["cache_creation"]);
2057
+ for (const key of ["input_tokens", "output_tokens"]) if (!safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
2058
+ 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.");
2059
+ if (value.cache_creation !== void 0 && value.cache_creation !== null) validateClaudeCacheCreationUsage(value.cache_creation);
2060
+ }
2061
+ function validateClaudeCacheCreationUsage(value) {
2062
+ if (!isOperationRecord(value)) invalid("Ceal Claude cache creation usage is invalid.");
2063
+ requireExactOperationKeys(value, ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]);
2064
+ 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.");
2065
+ }
2066
+ function validateClaudeSemantics(value) {
2067
+ if (value.counter_semantics !== "assistant_message" || !validClaudeFinality(value.finality) || value.child_inclusion !== "unknown" || !validCorrectionSemantics(value.correction_semantics)) invalid("Ceal Claude usage semantics are invalid.");
2068
+ }
2069
+ function validClaudeFinality(value) {
2070
+ return value === "terminal" || value === "nonterminal" || value === "unknown";
2071
+ }
2072
+ function validCorrectionSemantics(value) {
2073
+ return value === "not_observed" || value === "unknown";
2074
+ }
2075
+ function validateCodexUsageCounts(value) {
2076
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
2077
+ requireExactOperationKeys(value, CEAL_CODEX_USAGE_COUNT_FIELDS);
2078
+ for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
2079
+ 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.");
2080
+ }
2081
+ function validateNormalizedUsage(value) {
2082
+ if (!isOperationRecord(value)) invalid("Ceal normalized Host usage is invalid.");
2083
+ requireExactOperationKeys(value, ["input", "output", "total", "cached_input", "cache_write_input", "reasoning_output"]);
2084
+ for (const key of Object.keys(value)) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal normalized Host usage is invalid.");
2085
+ validateNormalizedTotals(value);
2086
+ }
2087
+ function validateNormalizedTotals(value) {
2088
+ validateNormalizedCountTotal(value);
2089
+ validateNormalizedInputSubsets(value);
2090
+ validateNormalizedOutputSubset(value);
2091
+ }
2092
+ function validateNormalizedCountTotal(value) {
2093
+ 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.");
2094
+ }
2095
+ function validateNormalizedInputSubsets(value) {
2096
+ 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.");
2097
+ }
2098
+ function validateNormalizedOutputSubset(value) {
2099
+ if (value.output !== null && value.reasoning_output !== null && Number(value.reasoning_output) > Number(value.output)) invalid("Ceal normalized Host output subset is inconsistent.");
2100
+ }
2101
+ function validateSourceRange(value) {
2102
+ if (!isOperationRecord(value)) invalid("Ceal Host usage source range is invalid.");
2103
+ requireExactOperationKeys(value, ["source_file_ref", "start_offset", "end_offset"]);
2104
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage source-file reference is invalid.");
2105
+ 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.");
2106
+ }
2107
+ function validateCealHostUsageCoverageGap(value) {
2108
+ if (!isOperationRecord(value)) invalid("Ceal Host usage coverage gap is invalid.");
2109
+ requireExactOperationKeys(value, ["reason", "source_file_ref", "start_offset", "end_offset", "omitted_count"]);
2110
+ if (!isOneOf(HOST_USAGE_COVERAGE_GAP_REASONS, value.reason) || !validUsageGapCount(value.reason, value.omitted_count)) invalid("Ceal Host usage coverage gap is invalid.");
2111
+ if (value.source_file_ref === null) {
2112
+ if (value.start_offset !== null || value.end_offset !== null) invalid("Ceal Host usage coverage gap range is invalid.");
1717
2113
  return;
1718
2114
  }
1719
- if (value === null || typeof value !== "object") return;
1720
- for (const [key, child] of Object.entries(value)) {
1721
- if (HOST_RESERVED_KEY.test(key)) invalid("Ceal Host observation cannot restate Gateway-owned facts.");
1722
- inspectHostKeys(child);
2115
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage coverage file reference is invalid.");
2116
+ 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.");
2117
+ }
2118
+ function validateCoverageGap(value) {
2119
+ validateCealHostUsageCoverageGap(value);
2120
+ }
2121
+ function validUsageGapCount(reason, value) {
2122
+ return value === null ? reason !== "outbox_capacity" : safeInteger(value) && Number(value) >= 1;
2123
+ }
2124
+ function isOneOf(values, value) {
2125
+ return typeof value === "string" && values.some((candidate) => candidate === value);
2126
+ }
2127
+ function isCealHostUsageBatchReference(value) {
2128
+ return typeof value === "string" && value.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX) && isCealDigest(value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length));
2129
+ }
2130
+ function cealHostUsageBatchObjectDigestFromFileName(value) {
2131
+ if (!value.endsWith(".json")) return null;
2132
+ const digest2 = value.slice(0, -5);
2133
+ return isCealDigest(digest2) ? digest2 : null;
2134
+ }
2135
+ function cealHostUsageBatchObjectDigestFromReference(value) {
2136
+ return isCealHostUsageBatchReference(value) ? value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length) : null;
2137
+ }
2138
+ function safeInteger(value) {
2139
+ return Number.isSafeInteger(value) && Number(value) >= 0;
2140
+ }
2141
+ function boundedText(value, maximum) {
2142
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters(value);
2143
+ }
2144
+ function hasControlCharacters(value) {
2145
+ for (const character of value) {
2146
+ const code2 = character.codePointAt(0);
2147
+ if (code2 !== void 0 && (code2 < 32 || code2 === 127)) return true;
1723
2148
  }
2149
+ return false;
2150
+ }
2151
+ function sha256(value) {
2152
+ return createHash3("sha256").update(value, "utf8").digest("hex");
1724
2153
  }
1725
2154
 
1726
2155
  // packages/ceal-client-protocol/src/host-prompt-ref.ts
@@ -1827,11 +2256,72 @@ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSch
1827
2256
  var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
1828
2257
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
1829
2258
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
2259
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.refusal_schema_name, fields: hostInvocationAuthenticationContract.refusal_fields });
1830
2260
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
1831
2261
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
1832
2262
  var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
1833
2263
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
2264
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
1834
2265
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
2266
+ function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
2267
+ const messages = [];
2268
+ let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
2269
+ for (const candidate of newestFirst.slice(0, CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES)) {
2270
+ 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 } : {} };
2271
+ if (encodedMessageWindowBytes([...messages, complete]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) {
2272
+ messages.push(Object.freeze(complete));
2273
+ continue;
2274
+ }
2275
+ const clipped = clipHumanMessageToWindow(messages, candidate);
2276
+ if (clipped === null) {
2277
+ truncated = true;
2278
+ break;
2279
+ }
2280
+ messages.push(Object.freeze(clipped));
2281
+ }
2282
+ return Object.freeze({ messages: Object.freeze(messages), truncated });
2283
+ }
2284
+ function encodedMessageWindowBytes(messages) {
2285
+ return new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2286
+ }
2287
+ function clipHumanMessageToWindow(prefix, candidate) {
2288
+ const clipped = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: "", text_truncated: true };
2289
+ const available = CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES - encodedMessageWindowBytes([...prefix, clipped]);
2290
+ if (available < 0) return null;
2291
+ const text = [];
2292
+ let used = 0;
2293
+ for (const point of candidate.text) {
2294
+ const encodedPoint = JSON.stringify(point);
2295
+ const cost = new TextEncoder().encode(encodedPoint).byteLength - 2;
2296
+ if (used + cost > available) break;
2297
+ text.push(point);
2298
+ used += cost;
2299
+ }
2300
+ const result = { ...clipped, text: text.join("") };
2301
+ return encodedMessageWindowBytes([...prefix, result]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES ? result : null;
2302
+ }
2303
+ function decodeCealHostInvocationHumanMessageWindow(value) {
2304
+ 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();
2305
+ const messages = value.messages.map(decodeHumanMessage);
2306
+ const bytes = new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2307
+ if (bytes > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) throw invalidInvocationContextRequest();
2308
+ return Object.freeze({ messages: Object.freeze(messages), truncated: value.truncated });
2309
+ }
2310
+ function decodeHumanMessage(candidate) {
2311
+ 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();
2312
+ if (candidate.text_truncated !== void 0 && candidate.text_truncated !== true) throw invalidInvocationContextRequest();
2313
+ 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 } : {} });
2314
+ }
2315
+ function safeReference(value) {
2316
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
2317
+ }
2318
+ function exactOptionalKeys(value, required, optional = []) {
2319
+ const keys = Object.keys(value);
2320
+ return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => required.includes(key) || optional.includes(key));
2321
+ }
2322
+ function invalidInvocationContextRequest() {
2323
+ return new TypeError("The Host invocation context request is invalid.");
2324
+ }
1835
2325
  function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1836
2326
  const clientNonce = contract.host_invocation_authentication.client_nonce;
1837
2327
  return {
@@ -1841,40 +2331,20 @@ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTR
1841
2331
  };
1842
2332
  }
1843
2333
  var hostNonceContract = deriveCealHostInvocationNonceContract();
1844
- var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
1845
2334
  var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
1846
2335
  var CEAL_HOST_CONTEXT_TOKEN_PATTERN = new RegExp(hostNonceContract.context_token_pattern_source, "u");
1847
- var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_MAX_BYTES = deriveCealHostInvocationAuthenticationResultMaxBytes();
1848
- function deriveCealHostInvocationAuthenticationResultMaxBytes(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1849
- const hostAuthentication = contract.host_invocation_authentication;
1850
- const values = {
1851
- schema_version: deriveCealClientWireSchemaVersion({ schema_name: hostAuthentication.result_schema_name, fields: hostAuthentication.result_fields }),
1852
- context_token: `${CEAL_HOST_CONTEXT_TOKEN_PREFIX}${"A".repeat(hostAuthentication.client_nonce.encoded_characters)}`,
1853
- expires_at: (/* @__PURE__ */ new Date("+010000-01-01T00:00:00.000Z")).toISOString()
1854
- };
1855
- const fields = hostAuthentication.result_fields;
1856
- if (fields.some((field) => !Object.hasOwn(values, field))) throw new TypeError("Host invocation result fields have no bounded sample value.");
1857
- return new TextEncoder().encode(`${JSON.stringify(Object.fromEntries(fields.map((field) => [field, values[field]])))}
1858
- `).byteLength;
1859
- }
1860
2336
  var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
1861
2337
  "request_authority_unavailable",
1862
- "request_missing",
1863
- "authority_mismatch",
1864
- "host_source_mismatch",
1865
- "host_session_mismatch",
1866
- "host_turn_mismatch",
1867
- "host_input_mismatch",
1868
- "host_prompt_mismatch"
2338
+ "request_creation_refused"
1869
2339
  ]);
1870
2340
  var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1871
2341
  "invalid_arguments",
1872
2342
  "options_invalid",
1873
2343
  "session_unavailable",
1874
2344
  "context_unavailable",
2345
+ "activation_wait_exhausted",
1875
2346
  "context_replaced",
1876
2347
  "no_binding",
1877
- "context_stale",
1878
2348
  "context_expired",
1879
2349
  "host_source_refused",
1880
2350
  "host_credential_refused",
@@ -1891,23 +2361,35 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1891
2361
  "relay_failed",
1892
2362
  "host_refusal_invalid"
1893
2363
  ]);
2364
+ var CEAL_HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2365
+ "permission_denied",
2366
+ "socket_missing",
2367
+ "connection_refused",
2368
+ "closed_early",
2369
+ "response_invalid",
2370
+ "timed_out",
2371
+ "cancelled",
2372
+ "unavailable"
2373
+ ]);
1894
2374
  var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1895
2375
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
1896
2376
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
1897
2377
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1898
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
1899
- context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
2378
+ // This reason cannot distinguish a Codex side conversation from a missing
2379
+ // context in a regular session, so guidance must leave that choice to the caller.
2380
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2381
+ activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2382
+ context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
1900
2383
  // `no_binding` now means the producer has no real current Host session. The
1901
2384
  // Host Relay never uses it for an uncreated Gateway Request; there is no
1902
2385
  // useful retry until the consumer is running inside a Host session.
1903
2386
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1904
- context_stale: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1905
- context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
2387
+ context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
1906
2388
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
1907
2389
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
1908
2390
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
1909
2391
  gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
1910
- contract_mismatch: Object.freeze({ classification: "contract_mismatch", next_action: "upgrade_ceal_client" }),
2392
+ contract_mismatch: Object.freeze({ classification: "host_contract_mismatch", next_action: "upgrade_ceal_client" }),
1911
2393
  gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
1912
2394
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
1913
2395
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
@@ -1915,7 +2397,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1915
2397
  relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
1916
2398
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
1917
2399
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
1918
- relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "answer_with_gap" }),
2400
+ relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
1919
2401
  host_refusal_invalid: Object.freeze({ classification: "host_refusal_invalid", next_action: "answer_with_gap" })
1920
2402
  });
1921
2403
 
@@ -1929,10 +2411,13 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
1929
2411
  "activation_recorded",
1930
2412
  "activation_failed",
1931
2413
  "watcher_scan_failed",
2414
+ "usage_capture_failed",
2415
+ "usage_upload_failed",
1932
2416
  "activation_wait_skipped",
1933
2417
  "activation_wait_engaged",
1934
2418
  "activation_wait_completed",
1935
- "activation_wait_exhausted"
2419
+ "activation_wait_exhausted",
2420
+ "invocation_authentication_failed"
1936
2421
  ]);
1937
2422
  var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1938
2423
  "malformed_line",
@@ -1942,11 +2427,22 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1942
2427
  "size_budget",
1943
2428
  "symlink"
1944
2429
  ]);
2430
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_WATCHER_OPTIONAL_FIELDS = vocabulary(["failure_kind", "cause"]);
2431
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_OPTIONAL_FIELDS = vocabulary(["cause"]);
2432
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE = "^[a-z][a-z0-9_]{0,63}(?::[A-Za-z][A-Za-z0-9_]{0,63})?$";
2433
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES = Object.freeze([
2434
+ ...CEAL_HOST_AUTHENTICATION_CAUSES,
2435
+ ...CEAL_HOST_RELAY_EXCHANGE_FAILURES.map((failure) => `relay_exchange:${failure}`)
2436
+ ]);
2437
+ var hostServiceDiagnosticCausePattern = new RegExp(CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE, "u");
2438
+ function isCealHostServiceDiagnosticCause(value, event) {
2439
+ return typeof value === "string" && hostServiceDiagnosticCausePattern.test(value) && (event !== "invocation_authentication_failed" || CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES.includes(value));
2440
+ }
1945
2441
 
1946
2442
  // packages/ceal-client-protocol/src/client-result-materialization.ts
1947
2443
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
1948
2444
  var REQUIRED_FIELDS2 = Object.freeze(["schema_version", "operation_id", "path", "sha256"]);
1949
- var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "items_path", "row_count", "result_complete", "coverage", "local_result_root", "model_disclosure", "continue_argv", "how_to_read"]);
2445
+ var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "local_result_root", "request_context_argv", "how_to_read"]);
1950
2446
 
1951
2447
  // packages/ceal-client-protocol/src/session-start-affordance.ts
1952
2448
  var CEAL_SESSION_ENTRY_INVOCATION = "ceal";
@@ -2031,12 +2527,14 @@ var ADMIN_SOURCE_OWNERS = vocabulary([
2031
2527
  "resource",
2032
2528
  "prompt",
2033
2529
  "usage",
2530
+ "provider_request_lifecycle",
2034
2531
  "connector",
2035
2532
  "session",
2036
2533
  "knowledge",
2037
2534
  "policy"
2038
2535
  ]);
2039
2536
  var ADMIN_COMPLETENESS_STATES = vocabulary(["complete", "partial", "unknown"]);
2537
+ var ADMIN_PROVIDER_REQUEST_CAPTURE_HEALTH_STATES = vocabulary(["available", "missing", "invalid", "unreadable"]);
2040
2538
  var ADMIN_OPERATION_OUTCOMES = vocabulary(["completed", "failed", "denied", "cancelled", "unknown"]);
2041
2539
  var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
2042
2540
  var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
@@ -2089,6 +2587,22 @@ function decodeClaudeQueuedPromptRow(row, sessionId) {
2089
2587
  if (row.type === "queue-operation") return decodeQueueEnqueuePrompt(row, sessionId);
2090
2588
  return null;
2091
2589
  }
2590
+ function decodeClaudeHumanMessageRow(row, sessionId) {
2591
+ if (!isClaudeNativeHumanMessageRow(row)) return decodeClaudeQueuedPromptRow(row, sessionId);
2592
+ return decodeClaudeNativeHumanMessage(row, sessionId);
2593
+ }
2594
+ function isClaudeNativeHumanMessageRow(row) {
2595
+ return record(row) && row.type === "user" && record(row.message) && typeof row.message.content === "string";
2596
+ }
2597
+ function decodeClaudeNativeHumanMessage(row, sessionId) {
2598
+ if (!sessionMatches(row, sessionId)) return null;
2599
+ if (row.isMeta === true && (!record(row.origin) || typeof row.origin.kind !== "string")) return null;
2600
+ const identity = queuedRowIdentity(row);
2601
+ if (identity === null) throw new ClaudeHostError("payload_rejected", "Claude transcript human message identity is malformed.");
2602
+ const message = row.message;
2603
+ if (!record(message) || typeof message.content !== "string") return null;
2604
+ return { turnId: identity.uuid, timestamp: identity.timestamp, content: message.content };
2605
+ }
2092
2606
  function decodeArrayTextPrompt(row, sessionId) {
2093
2607
  if (!record(row.message) || !Array.isArray(row.message.content)) return null;
2094
2608
  if (!sessionMatches(row, sessionId)) return null;
@@ -2131,9 +2645,9 @@ function queuedRowIdentity(row) {
2131
2645
  if (typeof row.timestamp !== "string" || !Number.isFinite(Date.parse(row.timestamp))) return null;
2132
2646
  return { uuid: row.uuid, timestamp: row.timestamp };
2133
2647
  }
2134
- function queueEnqueueTurnId(sessionId, timestamp4, content) {
2135
- return `queue-enqueue:${createHash3("sha256").update(`${sessionId}
2136
- ${timestamp4}
2648
+ function queueEnqueueTurnId(sessionId, timestamp5, content) {
2649
+ return `queue-enqueue:${createHash4("sha256").update(`${sessionId}
2650
+ ${timestamp5}
2137
2651
  ${content}`, "utf8").digest("hex").slice(0, 32)}`;
2138
2652
  }
2139
2653
  function claudeLocalSessionRef(sessionId) {
@@ -2150,7 +2664,7 @@ function isSessionSource(value) {
2150
2664
  }
2151
2665
  function requiredAbsolutePath(value, message) {
2152
2666
  const text = requiredText(value, 4096, message);
2153
- if (!text.startsWith("/") || text.includes("\0")) throw invalid2(message);
2667
+ if (!isAbsolute(text) || text.includes("\0")) throw invalid2(message);
2154
2668
  return text;
2155
2669
  }
2156
2670
  function requiredText(value, max, message) {
@@ -2165,7 +2679,7 @@ function optionalText(value, max) {
2165
2679
  return requiredText(value, max, "Claude optional hook field is invalid.");
2166
2680
  }
2167
2681
  function digest(value) {
2168
- return createHash3("sha256").update(value, "utf8").digest("hex");
2682
+ return createHash4("sha256").update(value, "utf8").digest("hex");
2169
2683
  }
2170
2684
  function record(value) {
2171
2685
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2175,8 +2689,8 @@ function invalid2(message) {
2175
2689
  }
2176
2690
 
2177
2691
  // host/claude/src/claude-outbox.ts
2178
- import { mkdir as mkdir2, readdir, readFile, unlink as unlink2 } from "node:fs/promises";
2179
- import { isAbsolute, join as join2 } from "node:path";
2692
+ import { mkdir as mkdir4, readdir, readFile, unlink as unlink3 } from "node:fs/promises";
2693
+ import { isAbsolute as isAbsolute4, join as join4 } from "node:path";
2180
2694
 
2181
2695
  // host/invocation-context.ts
2182
2696
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2244,13 +2758,13 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2244
2758
  ];
2245
2759
 
2246
2760
  // host/relay/src/host-producer-core.ts
2247
- import { createHash as createHash4 } from "node:crypto";
2761
+ import { createHash as createHash5 } from "node:crypto";
2248
2762
 
2249
2763
  // host/secure-file.ts
2250
2764
  import { execFile } from "node:child_process";
2251
2765
  import { constants } from "node:fs";
2252
2766
  import { lstat, open } from "node:fs/promises";
2253
- import { dirname, win32 } from "node:path";
2767
+ import { dirname, join as join2, win32 } from "node:path";
2254
2768
  import { fileURLToPath } from "node:url";
2255
2769
  var SecureFileCustodyError = class extends Error {
2256
2770
  name = "SecureFileCustodyError";
@@ -2268,6 +2782,7 @@ var SecureFileCustodyError = class extends Error {
2268
2782
  }
2269
2783
  };
2270
2784
  var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
2785
+ var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
2271
2786
  var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
2272
2787
  var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
2273
2788
  function secureOpenFlags(flags, platform) {
@@ -2310,18 +2825,46 @@ async function assertWindowsIdentityStable(handle, first, path) {
2310
2825
  }
2311
2826
  async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
2312
2827
  if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
2313
- const result = await runWindowsSecurefs(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2828
+ const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2314
2829
  if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
2315
2830
  if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
2316
2831
  if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
2317
2832
  throw securefsRefusal(result.stderr);
2318
2833
  }
2319
- async function runWindowsSecurefs(args, maxBytes, custody) {
2320
- if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args);
2321
- const executable = custody.securefs_executable ?? resolveInstalledHostExecutable();
2834
+ async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
2835
+ const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
2836
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2837
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
2838
+ throw securefsRefusal(result.stderr);
2839
+ }
2840
+ async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
2841
+ 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.");
2842
+ const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
2843
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2844
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
2845
+ throw securefsRefusal(result.stderr);
2846
+ }
2847
+ async function isPrivateWindowsDirectory(path, custody = {}) {
2848
+ await lstat(path);
2849
+ try {
2850
+ const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
2851
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
2852
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
2853
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
2854
+ const refusal = securefsRefusal(result.stderr);
2855
+ if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
2856
+ throw refusal;
2857
+ } catch (error) {
2858
+ if (error instanceof SecureFileCustodyError) throw error;
2859
+ throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
2860
+ }
2861
+ }
2862
+ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2863
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
2864
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2322
2865
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2323
2866
  return await new Promise((resolve2, reject) => {
2324
- execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2867
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2325
2868
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2326
2869
  if (exitCode === null) {
2327
2870
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2329,6 +2872,8 @@ async function runWindowsSecurefs(args, maxBytes, custody) {
2329
2872
  }
2330
2873
  resolve2({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
2331
2874
  });
2875
+ child.stdin?.on("error", () => void 0);
2876
+ child.stdin?.end(stdin);
2332
2877
  });
2333
2878
  }
2334
2879
  function securefsRefusal(stderr) {
@@ -2346,9 +2891,9 @@ function securefsRefusal(stderr) {
2346
2891
  if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
2347
2892
  return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
2348
2893
  }
2349
- function resolveInstalledHostExecutable() {
2894
+ function resolveInstalledHostExecutable(platform) {
2350
2895
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2351
- return win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
2896
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2352
2897
  }
2353
2898
  function isRecord2(value) {
2354
2899
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2364,6 +2909,197 @@ function isPrivateFileMode(mode, platform = process.platform, _handle) {
2364
2909
  if (platform === "win32") return false;
2365
2910
  return (mode & 63) === 0;
2366
2911
  }
2912
+ async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
2913
+ if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
2914
+ const entry = await lstat(path);
2915
+ return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
2916
+ }
2917
+
2918
+ // host/service-log.ts
2919
+ import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
2920
+ import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win322 } from "node:path";
2921
+
2922
+ // host/service-log-delivery.ts
2923
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
2924
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
2925
+ setImmediate(flush);
2926
+ }, onDeliveryGap = () => void 0) {
2927
+ const pending = [];
2928
+ const highWaterMark = stream.writableHighWaterMark;
2929
+ const byteBudget = highWaterMark + highWaterMark;
2930
+ let pendingBytes = 0;
2931
+ let droppedLines = 0;
2932
+ let flushScheduled = false;
2933
+ let waitingForDrain = false;
2934
+ let closed = !stream.writable;
2935
+ function stop() {
2936
+ if (closed) return;
2937
+ closed = true;
2938
+ pending.length = 0;
2939
+ pendingBytes = 0;
2940
+ stream.off("drain", onDrain);
2941
+ stream.off("close", onTerminal);
2942
+ stream.off("finish", onTerminal);
2943
+ stream.off("error", onError);
2944
+ }
2945
+ function onTerminal() {
2946
+ stop();
2947
+ }
2948
+ function onError() {
2949
+ stop();
2950
+ }
2951
+ function onDrain() {
2952
+ waitingForDrain = false;
2953
+ scheduleFlush();
2954
+ }
2955
+ function scheduleFlush() {
2956
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
2957
+ flushScheduled = true;
2958
+ let scheduling = true;
2959
+ let invokedSynchronously = false;
2960
+ try {
2961
+ schedule(() => {
2962
+ if (scheduling) {
2963
+ invokedSynchronously = true;
2964
+ return;
2965
+ }
2966
+ flushScheduled = false;
2967
+ flush();
2968
+ });
2969
+ } catch {
2970
+ flushScheduled = false;
2971
+ stop();
2972
+ return;
2973
+ }
2974
+ scheduling = false;
2975
+ if (invokedSynchronously) {
2976
+ flushScheduled = false;
2977
+ stop();
2978
+ }
2979
+ }
2980
+ function flush() {
2981
+ if (closed) return;
2982
+ if (!stream.writable) {
2983
+ stop();
2984
+ return;
2985
+ }
2986
+ while (pending.length > 0) {
2987
+ if (stream.writableNeedDrain) {
2988
+ if (!waitingForDrain) {
2989
+ waitingForDrain = true;
2990
+ stream.once("drain", onDrain);
2991
+ }
2992
+ return;
2993
+ }
2994
+ const next = pending.shift();
2995
+ if (next === void 0) return;
2996
+ pendingBytes -= next.bytes;
2997
+ let accepted;
2998
+ try {
2999
+ accepted = stream.write(next.line);
3000
+ } catch {
3001
+ stop();
3002
+ return;
3003
+ }
3004
+ if (!accepted) {
3005
+ waitingForDrain = true;
3006
+ stream.once("drain", onDrain);
3007
+ return;
3008
+ }
3009
+ }
3010
+ if (droppedLines > 0) {
3011
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
3012
+ `;
3013
+ droppedLines = 0;
3014
+ try {
3015
+ onDeliveryGap(line);
3016
+ } catch {
3017
+ }
3018
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
3019
+ pendingBytes += Buffer.byteLength(line, "utf8");
3020
+ flush();
3021
+ }
3022
+ }
3023
+ stream.on("close", onTerminal);
3024
+ stream.on("finish", onTerminal);
3025
+ stream.on("error", onError);
3026
+ return (line) => {
3027
+ if (closed) return;
3028
+ const bytes = Buffer.byteLength(line, "utf8");
3029
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
3030
+ droppedLines += 1;
3031
+ scheduleFlush();
3032
+ return;
3033
+ }
3034
+ pending.push({ line, bytes });
3035
+ pendingBytes += bytes;
3036
+ scheduleFlush();
3037
+ };
3038
+ }
3039
+
3040
+ // host/invocation-authentication-client-command.ts
3041
+ var DOCTOR_FLAGS = Object.freeze({
3042
+ "--expected-sha256": "expected_sha256",
3043
+ "--expected-source-commit": "expected_source_commit",
3044
+ "--expected-instance-ref": "expected_instance_ref"
3045
+ });
3046
+
3047
+ // host/service-log.ts
3048
+ var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
3049
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
3050
+ void persistHostServiceLogLine(line);
3051
+ });
3052
+ function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
3053
+ const details = diagnosticDetails(event, failure_kind, cause);
3054
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
3055
+ `;
3056
+ try {
3057
+ (sink ?? defaultHostServiceDiagnosticSink)(line);
3058
+ } catch {
3059
+ }
3060
+ }
3061
+ function diagnosticDetails(event, failureKind, cause) {
3062
+ if (event === "watcher_scan_failed") return {
3063
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3064
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
3065
+ };
3066
+ return validDiagnosticCause(cause, event) ? { cause } : {};
3067
+ }
3068
+ function validDiagnosticCause(cause, event) {
3069
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
3070
+ }
3071
+ function defaultHostServiceDiagnosticSink(line) {
3072
+ writeHostServiceLogLine(line);
3073
+ }
3074
+ var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
3075
+ function writeHostServiceLogLine(line, environment = process.env) {
3076
+ void persistHostServiceLogLine(line, environment);
3077
+ defaultHostServiceLogDelivery(line);
3078
+ }
3079
+ async function persistHostServiceLogLine(line, environment = process.env) {
3080
+ if (process.platform !== "win32") return;
3081
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
3082
+ if (path === void 0 || !win322.isAbsolute(path) || win322.normalize(path) !== path) return;
3083
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
3084
+ }
3085
+ async function appendHostServiceLogLine(path, line) {
3086
+ if (!isAbsolute2(path)) return;
3087
+ await ensureHostServiceLogDirectory(path);
3088
+ await appendFile(path, line);
3089
+ }
3090
+ var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
3091
+ var hostServiceLogDirectories = /* @__PURE__ */ new Map();
3092
+ function ensureHostServiceLogDirectory(path) {
3093
+ const directory = dirname2(path);
3094
+ const existing = hostServiceLogDirectories.get(directory);
3095
+ if (existing !== void 0) return existing;
3096
+ const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
3097
+ hostServiceLogDirectories.delete(directory);
3098
+ throw error;
3099
+ });
3100
+ hostServiceLogDirectories.set(directory, pending);
3101
+ return pending;
3102
+ }
2367
3103
 
2368
3104
  // host/relay/src/host-producer-core.ts
2369
3105
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
@@ -2372,7 +3108,22 @@ function isHostTranscriptCursorReason(value) {
2372
3108
  }
2373
3109
  var TRANSCRIPT_MISSING_REASON = "transcript_missing";
2374
3110
  var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
2375
- var HOST_INVOCATION_TRANSCRIPT_TAIL_MAX_BYTES = 1024 * 1024;
3111
+ var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
3112
+ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
3113
+ const seen = /* @__PURE__ */ new Set();
3114
+ const newestFirst = [];
3115
+ for (const message of [...chronological].reverse()) {
3116
+ if (seen.has(message.host_input_ref)) continue;
3117
+ seen.add(message.host_input_ref);
3118
+ newestFirst.push(message);
3119
+ }
3120
+ for (const message of existing?.messages ?? []) {
3121
+ if (seen.has(message.host_input_ref)) continue;
3122
+ seen.add(message.host_input_ref);
3123
+ newestFirst.push(message);
3124
+ }
3125
+ return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
3126
+ }
2376
3127
  function transcriptScanFailureKind(error, adapterFailureKind) {
2377
3128
  if (transcriptErrorCode(error) === "ELOOP") return "symlink";
2378
3129
  const adapter = adapterFailureKind(error);
@@ -2429,10 +3180,10 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
2429
3180
  return null;
2430
3181
  }
2431
3182
  function transcriptSha256(value) {
2432
- return createHash4("sha256").update(value).digest("hex");
3183
+ return createHash5("sha256").update(value).digest("hex");
2433
3184
  }
2434
3185
  function transcriptObjectSha256(value) {
2435
- return createHash4("sha256").update(JSON.stringify(value), "utf8").digest("hex");
3186
+ return createHash5("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2436
3187
  }
2437
3188
  function isTranscriptRecord(value) {
2438
3189
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2454,7 +3205,7 @@ function createTranscriptWatcherBase(options, owner) {
2454
3205
  outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
2455
3206
  now: options.now ?? (() => /* @__PURE__ */ new Date()),
2456
3207
  log: options.log ?? ((line) => {
2457
- process.stderr.write(`${line}
3208
+ writeHostServiceLogLine(`${line}
2458
3209
  `);
2459
3210
  }),
2460
3211
  producerInstallationRef: options.producer_installation_ref
@@ -2494,7 +3245,13 @@ var HostTranscriptWatcher = class {
2494
3245
  }
2495
3246
  async scanRegistration(registration) {
2496
3247
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
2497
- missing: () => this.retireMissing(registration),
3248
+ missing: async () => {
3249
+ try {
3250
+ return await this.retireMissing(registration);
3251
+ } catch (error) {
3252
+ return this.scanFailed(void 0, registration, error);
3253
+ }
3254
+ },
2498
3255
  failed: (handle, error) => this.scanFailed(handle, registration, error)
2499
3256
  });
2500
3257
  }
@@ -2577,8 +3334,8 @@ var HostProducerDrainCore = class {
2577
3334
  };
2578
3335
 
2579
3336
  // host/relay/src/durable-atomic-replacement.ts
2580
- import { lstat as lstat2, mkdir, open as open2, rename, unlink } from "node:fs/promises";
2581
- import { dirname as dirname2 } from "node:path";
3337
+ import { lstat as lstat2, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
3338
+ import { dirname as dirname3 } from "node:path";
2582
3339
 
2583
3340
  // host/windows-rename-retry.ts
2584
3341
  import { setTimeout as setTimeout2 } from "node:timers/promises";
@@ -2631,7 +3388,7 @@ function isRetryableRenameError(error) {
2631
3388
  // host/relay/src/durable-atomic-replacement.ts
2632
3389
  var DEFAULT_PORT = {
2633
3390
  platform: process.platform,
2634
- mkdir: (path, options) => mkdir(path, options),
3391
+ mkdir: (path, options) => mkdir2(path, options),
2635
3392
  lstat: (path) => lstat2(path),
2636
3393
  open_file: (path) => open2(path, "wx", 384),
2637
3394
  rename,
@@ -2640,7 +3397,7 @@ var DEFAULT_PORT = {
2640
3397
  unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
2641
3398
  };
2642
3399
  async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
2643
- const parent = dirname2(target);
3400
+ const parent = dirname3(target);
2644
3401
  await port.mkdir(parent, { recursive: true, mode: 448 });
2645
3402
  const parentStats = await port.lstat(parent);
2646
3403
  const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
@@ -2689,22 +3446,933 @@ async function closeStaged(staged, failures) {
2689
3446
  failures.push(error);
2690
3447
  }
2691
3448
  }
2692
- async function removeTemporary(path, port, failures) {
3449
+ async function removeTemporary(path, port, failures) {
3450
+ try {
3451
+ await port.unlink(path);
3452
+ } catch (error) {
3453
+ if (errorCode(error) !== "ENOENT") failures.push(error);
3454
+ }
3455
+ }
3456
+ function throwFailures(failures) {
3457
+ if (failures.length === 1) throw failures[0];
3458
+ if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
3459
+ }
3460
+ function directorySyncUnsupported(error) {
3461
+ return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
3462
+ }
3463
+ function errorCode(error) {
3464
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3465
+ }
3466
+
3467
+ // host/relay/src/host-usage-facts-store.ts
3468
+ import { createHash as createHash6 } from "node:crypto";
3469
+ import { constants as constants2 } from "node:fs";
3470
+ import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3471
+ import { dirname as dirname4, join as join3 } from "node:path";
3472
+ var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3473
+ var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3474
+ var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
3475
+ var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
3476
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
3477
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
3478
+ var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
3479
+ var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
3480
+ var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
3481
+ var HostUsageFactsStore = class {
3482
+ root;
3483
+ sessions;
3484
+ batches;
3485
+ platform;
3486
+ custody;
3487
+ afterPendingWrite;
3488
+ afterBatchPublish;
3489
+ sessionDirectoryCursor;
3490
+ constructor(options) {
3491
+ this.root = join3(options.outbox_dir, "usage-facts");
3492
+ this.sessions = join3(this.root, "sessions");
3493
+ this.batches = join3(this.root, "batches");
3494
+ this.platform = options.platform ?? process.platform;
3495
+ this.custody = options.secure_file_custody ?? {};
3496
+ this.afterPendingWrite = options.afterPendingWrite;
3497
+ this.afterBatchPublish = options.afterBatchPublish;
3498
+ }
3499
+ async prepare() {
3500
+ for (const directory of [this.root, this.sessions, this.batches]) {
3501
+ await preparePrivateDirectory(directory, this.platform, this.custody);
3502
+ }
3503
+ }
3504
+ async close() {
3505
+ const cursor = this.sessionDirectoryCursor;
3506
+ this.sessionDirectoryCursor = void 0;
3507
+ await cursor?.close();
3508
+ }
3509
+ async readState(producer, hostSourceRef, hostSessionRef) {
3510
+ await this.prepare();
3511
+ const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3512
+ const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3513
+ if (value === null) return null;
3514
+ validateState(value, producer, hostSourceRef, hostSessionRef);
3515
+ return value;
3516
+ }
3517
+ createState(producer, hostSourceRef, hostSessionRef) {
3518
+ return {
3519
+ schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
3520
+ producer,
3521
+ host_source_ref: hostSourceRef,
3522
+ host_session_ref: hostSessionRef,
3523
+ cursors: {},
3524
+ eligible_batches: [],
3525
+ coverage_gaps: [],
3526
+ coverage_gap_created_at: null
3527
+ };
3528
+ }
3529
+ async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
3530
+ let state = await this.readState(producer, hostSourceRef, hostSessionRef);
3531
+ if (state === null) {
3532
+ state = this.createState(producer, hostSourceRef, hostSessionRef);
3533
+ state = await this.writeCursor(state, sourceSlot, initial);
3534
+ }
3535
+ state = await this.recoverPending(state);
3536
+ if (state.quarantined_reason !== void 0) return null;
3537
+ state = await this.commitCoverageGaps(state, createdAt);
3538
+ const cursor = state.cursors[sourceSlot];
3539
+ return cursor === void 0 ? null : { state, cursor };
3540
+ }
3541
+ async writeCursor(state, sourceSlot, cursor) {
3542
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3543
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3544
+ if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
3545
+ const current = latest.cursors[sourceSlot];
3546
+ if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
3547
+ const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
3548
+ await this.writeState(updated);
3549
+ return updated;
3550
+ });
3551
+ }
3552
+ async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
3553
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3554
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3555
+ return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
3556
+ });
3557
+ }
3558
+ async recoverPending(state) {
3559
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3560
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3561
+ const recovered = await this.finishPendingTransition(latest);
3562
+ await this.sweepOrphanedBatches(recovered);
3563
+ return recovered;
3564
+ });
3565
+ }
3566
+ /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3567
+ async sweepOrphanedBatches(state) {
3568
+ await this.prepare();
3569
+ const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3570
+ await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3571
+ const expected = expectedBatchNames(state);
3572
+ const directory = await opendir(directoryPath);
3573
+ let inspected = 0;
3574
+ let deleted = 0;
3575
+ try {
3576
+ while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
3577
+ const entry = await directory.read();
3578
+ if (entry === null) break;
3579
+ inspected += 1;
3580
+ if (!isOrphanBatchEntry(entry, expected)) continue;
3581
+ await unlink2(join3(directoryPath, entry.name));
3582
+ deleted += 1;
3583
+ }
3584
+ } finally {
3585
+ await directory.close();
3586
+ }
3587
+ if (deleted > 0) await syncDirectory(directoryPath, this.platform);
3588
+ return deleted;
3589
+ }
3590
+ async commitCoverageGaps(state, createdAt) {
3591
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3592
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3593
+ if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
3594
+ const sourceRanges = coverageRanges(latest.coverage_gaps);
3595
+ const canonical = createCealHostUsageBatch({
3596
+ host_source_ref: latest.host_source_ref,
3597
+ host_session_ref: latest.host_session_ref,
3598
+ created_at: latest.coverage_gap_created_at ?? createdAt,
3599
+ source_ranges: sourceRanges,
3600
+ facts: [],
3601
+ coverage_gaps: latest.coverage_gaps
3602
+ });
3603
+ const cursor = firstCursor(latest);
3604
+ if (cursor === null) return latest;
3605
+ return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
3606
+ });
3607
+ }
3608
+ async nextUploadCandidate(producer, hostSourceRef) {
3609
+ await this.prepare();
3610
+ const names = await this.readNextSessionNames();
3611
+ for (const name of names) {
3612
+ const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3613
+ if (state === null) continue;
3614
+ validateStateOwner(state, producer, hostSourceRef);
3615
+ let validated = state;
3616
+ if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
3617
+ else validated = await this.recoverPending(validated);
3618
+ if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
3619
+ const next = validated.eligible_batches[0];
3620
+ if (next === void 0) continue;
3621
+ const batch = await this.readBatch(validated, next.batch_ref);
3622
+ return { state: validated, batch };
3623
+ }
3624
+ return null;
3625
+ }
3626
+ async readNextSessionNames() {
3627
+ this.sessionDirectoryCursor ??= await opendir(this.sessions);
3628
+ const names = [];
3629
+ let inspected = 0;
3630
+ while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
3631
+ const entry = await this.sessionDirectoryCursor.read();
3632
+ if (entry === null) {
3633
+ await this.sessionDirectoryCursor.close();
3634
+ this.sessionDirectoryCursor = void 0;
3635
+ break;
3636
+ }
3637
+ inspected += 1;
3638
+ if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
3639
+ }
3640
+ return names;
3641
+ }
3642
+ async acknowledge(state, batchRef) {
3643
+ await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3644
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3645
+ if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
3646
+ const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
3647
+ if (remaining.length === latest.eligible_batches.length) return;
3648
+ await this.writeState({ ...latest, eligible_batches: remaining });
3649
+ await removeFileIfPresent(this.batchPath(state, batchRef));
3650
+ });
3651
+ }
3652
+ async quarantine(state, reason) {
3653
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3654
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3655
+ const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
3656
+ await this.writeState(updated);
3657
+ return updated;
3658
+ });
3659
+ }
3660
+ async retireCursor(state, sourceSlot, cursor, gap) {
3661
+ return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
3662
+ }
3663
+ async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
3664
+ if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
3665
+ if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
3666
+ const queued = await this.publishTransitionBatch(state, batch);
3667
+ const pending = {
3668
+ source_slot: sourceSlot,
3669
+ before_cursor: beforeCursor,
3670
+ after_cursor: afterCursor,
3671
+ batch_ref: queued.batch_ref,
3672
+ batch_bytes: queued.batch_bytes,
3673
+ gap_delta: [...gapDelta, ...queued.overflow_gaps],
3674
+ clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
3675
+ };
3676
+ const prepared = { ...state, pending_transition: pending };
3677
+ await this.writeState(prepared);
3678
+ await this.afterPendingWrite?.();
3679
+ return await this.finishPendingTransition(prepared);
3680
+ }
3681
+ async publishTransitionBatch(state, batch) {
3682
+ if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
3683
+ const serialized = serializeBatch(batch);
3684
+ if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
3685
+ await this.writeImmutableBatch(state, batch, serialized);
3686
+ await this.afterBatchPublish?.();
3687
+ return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
3688
+ }
3689
+ async finishPendingTransition(state) {
3690
+ const pending = state.pending_transition;
3691
+ if (pending === void 0 || state.quarantined_reason !== void 0) return state;
3692
+ const current = state.cursors[pending.source_slot];
3693
+ if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
3694
+ const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
3695
+ await this.writeState(quarantined);
3696
+ return quarantined;
3697
+ }
3698
+ let cursors = state.cursors;
3699
+ if (!cursorMatches(current, pending.after_cursor)) {
3700
+ const next = { ...state.cursors };
3701
+ if (pending.after_cursor === null) delete next[pending.source_slot];
3702
+ else next[pending.source_slot] = pending.after_cursor;
3703
+ cursors = next;
3704
+ }
3705
+ const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
3706
+ const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
3707
+ const { pending_transition: _pendingTransition, ...settledState } = state;
3708
+ const updated = {
3709
+ ...settledState,
3710
+ cursors,
3711
+ eligible_batches: eligible,
3712
+ coverage_gaps: gaps,
3713
+ coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
3714
+ };
3715
+ await this.writeState(updated);
3716
+ return updated;
3717
+ }
3718
+ async writeImmutableBatch(state, batch, bytes) {
3719
+ const path = this.batchPath(state, batch.batch_ref);
3720
+ await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
3721
+ const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3722
+ if (existing !== null) {
3723
+ if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3724
+ await syncExistingFile(path, this.platform);
3725
+ return;
3726
+ }
3727
+ if (this.platform === "win32") {
3728
+ await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
3729
+ return;
3730
+ }
3731
+ let handle;
3732
+ try {
3733
+ handle = await openNoFollow(path, constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY, 384, this.platform);
3734
+ await handle.writeFile(bytes);
3735
+ await handle.sync();
3736
+ await handle.close();
3737
+ handle = void 0;
3738
+ await syncDirectory(dirname4(path), this.platform);
3739
+ } catch (error) {
3740
+ await handle?.close().catch(() => void 0);
3741
+ if (errorCode2(error) === "EEXIST") {
3742
+ const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3743
+ if (winner !== null && winner.equals(bytes)) {
3744
+ await syncExistingFile(path, this.platform);
3745
+ return;
3746
+ }
3747
+ throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3748
+ }
3749
+ await removeFileIfPresent(path).catch(() => void 0);
3750
+ throw error;
3751
+ }
3752
+ }
3753
+ async readBatch(state, batchRef) {
3754
+ const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3755
+ if (bytes === null) throw new Error("Host usage facts batch object is missing.");
3756
+ let value;
3757
+ try {
3758
+ value = JSON.parse(bytes.toString("utf8"));
3759
+ } catch {
3760
+ throw new Error("Host usage facts batch object is malformed.");
3761
+ }
3762
+ validateCealHostUsageBatch(value);
3763
+ if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
3764
+ return value;
3765
+ }
3766
+ async writeState(state) {
3767
+ validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
3768
+ const bytes = Buffer.from(JSON.stringify(state), "utf8");
3769
+ if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
3770
+ await this.prepare();
3771
+ const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
3772
+ if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
3773
+ else await durableAtomicReplace(path, bytes);
3774
+ }
3775
+ async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
3776
+ const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3777
+ const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
3778
+ let release;
3779
+ const gate = new Promise((resolve2) => {
3780
+ release = resolve2;
3781
+ });
3782
+ const tail = previous.then(() => gate);
3783
+ SESSION_TRANSITION_TAILS.set(key, tail);
3784
+ await previous;
3785
+ try {
3786
+ return await run();
3787
+ } finally {
3788
+ release?.();
3789
+ if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
3790
+ }
3791
+ }
3792
+ sessionPath(producer, hostSourceRef, hostSessionRef) {
3793
+ return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3794
+ }
3795
+ batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3796
+ const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3797
+ return join3(this.batches, sessionName.slice(0, -5));
3798
+ }
3799
+ batchPath(state, batchRef) {
3800
+ return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3801
+ }
3802
+ };
3803
+ function serializeBatch(batch) {
3804
+ validateCealHostUsageBatch(batch);
3805
+ return Buffer.from(JSON.stringify(batch), "utf8");
3806
+ }
3807
+ function batchFileName(batchRef) {
3808
+ const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
3809
+ if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
3810
+ return `${digest2}.json`;
3811
+ }
3812
+ function expectedBatchNames(state) {
3813
+ const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
3814
+ const pending = state.pending_transition?.batch_ref;
3815
+ if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
3816
+ return expected;
3817
+ }
3818
+ function isOrphanBatchEntry(entry, expected) {
3819
+ return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
3820
+ }
3821
+ function hasOutboxCapacity(state, bytes) {
3822
+ const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
3823
+ return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
3824
+ }
3825
+ function overflowCoverageGaps(batch) {
3826
+ const count = batch.facts.length;
3827
+ const gaps = [...batch.coverage_gaps];
3828
+ 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 });
3829
+ return gaps;
3830
+ }
3831
+ function appendEligible(existing, next) {
3832
+ if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
3833
+ if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
3834
+ return [...existing, next];
3835
+ }
3836
+ function appendCoverageGaps(existing, added) {
3837
+ if (added.length === 0) return existing;
3838
+ const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
3839
+ for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
3840
+ const combined = [...byIdentity.values()];
3841
+ if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
3842
+ const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
3843
+ return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
3844
+ }
3845
+ function coverageRanges(gaps) {
3846
+ const ranges = /* @__PURE__ */ new Map();
3847
+ for (const gap of gaps) {
3848
+ if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
3849
+ const current = ranges.get(gap.source_file_ref);
3850
+ 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 });
3851
+ 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) });
3852
+ }
3853
+ return [...ranges.values()];
3854
+ }
3855
+ function firstCursor(state) {
3856
+ const entry = Object.entries(state.cursors)[0];
3857
+ return entry === void 0 ? null : entry;
3858
+ }
3859
+ function sameCursor(left, right) {
3860
+ return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
3861
+ }
3862
+ function cursorMatches(left, right) {
3863
+ return right === null ? left === void 0 : sameCursor(left, right);
3864
+ }
3865
+ function validateState(value, producer, hostSourceRef, hostSessionRef) {
3866
+ validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
3867
+ validateStateShape(value);
3868
+ validateStateLimits(value);
3869
+ validateStateContents(value);
3870
+ }
3871
+ function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
3872
+ if (!isRecord3(value) || value.schema_version !== HOST_USAGE_FACTS_STATE_SCHEMA || value.producer !== producer || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new Error("Host usage facts state identity is invalid.");
3873
+ }
3874
+ function validateStateLimits(value) {
3875
+ 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.");
3876
+ }
3877
+ function validateStateContents(value) {
3878
+ for (const [slot, cursor] of Object.entries(value.cursors)) {
3879
+ validateSourceSlot(slot);
3880
+ validateFileCursor(cursor);
3881
+ }
3882
+ for (const item of value.eligible_batches) validateEligibleBatch(item);
3883
+ if (value.pending_transition !== void 0) validatePending(value.pending_transition);
3884
+ for (const gap of value.coverage_gaps) validateGap(gap);
3885
+ validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
3886
+ }
3887
+ function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
3888
+ if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
3889
+ if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
3890
+ }
3891
+ function validateStateOwner(value, producer, hostSourceRef) {
3892
+ if (!isRecord3(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
3893
+ validateState(value, producer, hostSourceRef, String(value.host_session_ref));
3894
+ }
3895
+ function validateStateShape(value) {
3896
+ const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
3897
+ const optional = ["pending_transition", "quarantined_reason"];
3898
+ 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.");
3899
+ if (!isRecord3(value.cursors) || !Array.isArray(value.eligible_batches) || !Array.isArray(value.coverage_gaps) || value.coverage_gap_created_at !== null && typeof value.coverage_gap_created_at !== "string") throw new Error("Host usage facts state collections are invalid.");
3900
+ }
3901
+ function validateFileCursor(value) {
3902
+ if (!isRecord3(value) || !sameKeys(value, ["source_file_ref", "device", "inode", "offset", "anchor_start", "anchor_sha256", "last_ordinal", "host_turn_ref", "native_turn_id", "requested_model", "codex_total_usage", "skipping_oversized_line"])) throw new Error("Host usage facts source cursor is invalid.");
3903
+ validateCursorIdentity(value);
3904
+ validateCursorOffsets(value);
3905
+ validateCursorContext(value);
3906
+ if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
3907
+ if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
3908
+ }
3909
+ function validateCursorIdentity(value) {
3910
+ 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.");
3911
+ }
3912
+ function validateCursorOffsets(value) {
3913
+ 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.");
3914
+ }
3915
+ function validateCursorContext(value) {
3916
+ 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.");
3917
+ }
3918
+ function validOptionalText(value, maximum) {
3919
+ return value === null || typeof value === "string" && value.length <= maximum;
3920
+ }
3921
+ function validateCodexCounts(value) {
3922
+ if (!isRecord3(value) || !sameKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) throw new Error("Host usage facts cumulative usage is invalid.");
3923
+ if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
3924
+ }
3925
+ function validatePending(value) {
3926
+ if (!isRecord3(value) || !sameKeys(value, ["source_slot", "before_cursor", "after_cursor", "batch_ref", "batch_bytes", "gap_delta", "clear_coverage_gaps"])) throw new Error("Host usage facts pending transition is invalid.");
3927
+ validatePendingCursors(value);
3928
+ validatePendingBatch(value);
3929
+ validatePendingFields(value);
3930
+ for (const gap of value.gap_delta) validateGap(gap);
3931
+ }
3932
+ function validatePendingCursors(value) {
3933
+ validateSourceSlot(value.source_slot);
3934
+ validateFileCursor(value.before_cursor);
3935
+ if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
3936
+ }
3937
+ function validatePendingBatch(value) {
3938
+ if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
3939
+ }
3940
+ function validatePendingFields(value) {
3941
+ 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.");
3942
+ }
3943
+ function validateEligibleBatch(value) {
3944
+ if (!isRecord3(value) || !sameKeys(value, ["batch_ref", "bytes"]) || !isCealHostUsageBatchReference(value.batch_ref) || !safeInteger2(value.bytes) || Number(value.bytes) < 1 || Number(value.bytes) > CEAL_HOST_USAGE_BATCH_MAX_BYTES) throw new Error("Host usage facts eligible batch is invalid.");
3945
+ }
3946
+ function validateGap(value) {
3947
+ try {
3948
+ validateCealHostUsageCoverageGap(value);
3949
+ } catch {
3950
+ throw new Error("Host usage facts coverage gap is invalid.");
3951
+ }
3952
+ }
3953
+ function validateSourceSlot(value) {
3954
+ if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
3955
+ }
3956
+ async function readOptionalJson(path, maxBytes, platform, custody) {
3957
+ const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
3958
+ if (bytes === null) return null;
3959
+ try {
3960
+ return JSON.parse(bytes.toString("utf8"));
3961
+ } catch {
3962
+ throw new Error("Host usage facts state JSON is malformed.");
3963
+ }
3964
+ }
3965
+ async function readOptionalBytes(path, maxBytes, platform, custody) {
3966
+ if (platform === "win32") {
3967
+ try {
3968
+ return await readPrivateFileWithSecurefs(path, maxBytes, custody);
3969
+ } catch (error) {
3970
+ if (errorCode2(error) === "ENOENT") return null;
3971
+ throw error;
3972
+ }
3973
+ }
3974
+ let handle;
3975
+ try {
3976
+ handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
3977
+ const stats = await handle.stat();
3978
+ 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.");
3979
+ return await handle.readFile();
3980
+ } catch (error) {
3981
+ if (errorCode2(error) === "ENOENT") return null;
3982
+ throw error;
3983
+ } finally {
3984
+ await handle?.close();
3985
+ }
3986
+ }
3987
+ async function preparePrivateDirectory(path, platform, custody) {
3988
+ if (platform === "win32") {
3989
+ await ensurePrivateDirectoryWithSecurefs(path, custody);
3990
+ return;
3991
+ }
3992
+ await mkdir3(path, { recursive: true, mode: 448 });
3993
+ if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3994
+ }
3995
+ async function syncExistingFile(path, platform) {
3996
+ const handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
3997
+ try {
3998
+ await handle.sync();
3999
+ } finally {
4000
+ await handle.close();
4001
+ }
4002
+ await syncDirectory(dirname4(path), platform);
4003
+ }
4004
+ async function syncDirectory(path, platform) {
4005
+ if (platform === "win32") return;
4006
+ const handle = await open3(path, constants2.O_RDONLY);
4007
+ try {
4008
+ await handle.sync();
4009
+ } finally {
4010
+ await handle.close();
4011
+ }
4012
+ }
4013
+ async function removeFileIfPresent(path) {
4014
+ try {
4015
+ await unlink2(path);
4016
+ } catch (error) {
4017
+ if (errorCode2(error) !== "ENOENT") throw error;
4018
+ }
4019
+ }
4020
+ function sameKeys(value, expected) {
4021
+ return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
4022
+ }
4023
+ function isRecord3(value) {
4024
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4025
+ }
4026
+ function safeInteger2(value) {
4027
+ return Number.isSafeInteger(value) && Number(value) >= 0;
4028
+ }
4029
+ function validTimestamp(value) {
4030
+ return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
4031
+ }
4032
+ function errorCode2(error) {
4033
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
4034
+ }
4035
+ function sha2562(value) {
4036
+ return createHash6("sha256").update(value, "utf8").digest("hex");
4037
+ }
4038
+
4039
+ // host/relay/src/host-usage-facts-capture.ts
4040
+ import { constants as constants3 } from "node:fs";
4041
+ var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
4042
+ var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
4043
+ var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
4044
+ var HostUsageTranscriptSourceError = class extends Error {
4045
+ constructor(options) {
4046
+ super("Host usage transcript source could not be read.", options);
4047
+ this.name = "HostUsageTranscriptSourceError";
4048
+ }
4049
+ };
4050
+ async function readHostUsageTranscriptSource(read) {
4051
+ try {
4052
+ return await read();
4053
+ } catch (error) {
4054
+ throw new HostUsageTranscriptSourceError({ cause: error });
4055
+ }
4056
+ }
4057
+ async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4058
+ if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4059
+ let failed = false;
4060
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4061
+ const index = (startIndex + attempt) % registrations.length;
4062
+ const registration = registrations[index];
4063
+ if (registration === void 0) continue;
4064
+ try {
4065
+ if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
4066
+ } catch (error) {
4067
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4068
+ failed = true;
4069
+ }
4070
+ }
4071
+ return { captured: false, nextIndex: startIndex, failed };
4072
+ }
4073
+ async function openHostUsageTranscriptCursor(input) {
4074
+ const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
4075
+ let source;
4076
+ try {
4077
+ source = await readHostUsageTranscriptSource(() => input.inspect(handle));
4078
+ } catch (error) {
4079
+ await handle.close().catch(() => void 0);
4080
+ throw error;
4081
+ }
4082
+ const sourceFileRef2 = hostUsageSourceFileReference(input.source_kind, input.host_source_ref, input.host_session_ref, source.device, source.inode);
4083
+ let prepared;
4084
+ try {
4085
+ prepared = await input.store.prepareSourceCursor(input.producer, input.host_source_ref, input.host_session_ref, input.source_slot, input.initial_cursor(sourceFileRef2, source.device, source.inode), input.created_at);
4086
+ } catch (error) {
4087
+ await handle.close().catch(() => void 0);
4088
+ throw error;
4089
+ }
4090
+ if (prepared === null) {
4091
+ await handle.close();
4092
+ return null;
4093
+ }
4094
+ return { handle, source, source_file_ref: sourceFileRef2, ...prepared };
4095
+ }
4096
+ async function readHostUsageTranscriptChunk(handle, offset, size, skippingOversizedLine) {
4097
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(size) || size < offset) throw new TypeError("Host usage transcript range is invalid.");
4098
+ if (size === offset) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
4099
+ if (skippingOversizedLine) return await resumeOversizedLine(handle, offset, size);
4100
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
4101
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
4102
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
4103
+ const chunk = bytes.subarray(0, bytesRead);
4104
+ return completeChunk(chunk, offset);
4105
+ }
4106
+ async function resumeOversizedLine(handle, offset, size) {
4107
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
4108
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
4109
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
4110
+ const chunk = bytes.subarray(0, bytesRead);
4111
+ const delimiter = chunk.indexOf(10);
4112
+ if (delimiter < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
4113
+ return completeChunk(chunk.subarray(delimiter + 1), offset + delimiter + 1);
4114
+ }
4115
+ function completeChunk(chunk, offset) {
4116
+ const parsed = completeLinePrefix(chunk, offset);
4117
+ const oversizedRows = parsed.oversizedRows + (parsed.incompleteOversized ? 1 : 0);
4118
+ const endOffset = parsed.incompleteOversized ? offset + chunk.length : parsed.endOffset;
4119
+ return { lines: parsed.lines, end_offset: endOffset, skipping_oversized_line: parsed.incompleteOversized, oversized_rows: oversizedRows };
4120
+ }
4121
+ function completeLinePrefix(bytes, baseOffset) {
4122
+ const lines = [];
4123
+ let lineStart = 0;
4124
+ let endOffset = baseOffset;
4125
+ let oversizedRows = 0;
4126
+ let rowCount = 0;
4127
+ for (let index = 0; index < bytes.length; index += 1) {
4128
+ if (bytes[index] !== 10) continue;
4129
+ const line = bytes.subarray(lineStart, index);
4130
+ if (line.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES) oversizedRows += 1;
4131
+ else lines.push(line);
4132
+ lineStart = index + 1;
4133
+ endOffset = baseOffset + lineStart;
4134
+ rowCount += 1;
4135
+ if (rowCount >= HOST_USAGE_FACTS_SCAN_MAX_ROWS) return { lines, endOffset, oversizedRows, incompleteOversized: false };
4136
+ }
4137
+ const incomplete = bytes.subarray(lineStart);
4138
+ return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
4139
+ }
4140
+
4141
+ // host/relay/src/host-registration-state.ts
4142
+ import { constants as constants4 } from "node:fs";
4143
+ import { dirname as dirname5 } from "node:path";
4144
+
4145
+ // host/runtime-source-paths.ts
4146
+ import { createHash as createHash7 } from "node:crypto";
4147
+ import { posix as posix3, win32 as win324 } from "node:path";
4148
+
4149
+ // host/absolute-path.ts
4150
+ import { posix as posix2, win32 as win323 } from "node:path";
4151
+ function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
4152
+ const pathApi = flavor === "win32" || flavor === "windows" ? win323 : posix2;
4153
+ return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
4154
+ }
4155
+
4156
+ // host/unix-socket-path.ts
4157
+ var PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES = 103;
4158
+
4159
+ // host/runtime-source-paths.ts
4160
+ var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
4161
+ function hostSourceUuid(sourceRef) {
4162
+ return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
4163
+ }
4164
+ var DARWIN_UID_MAX = 4294967295;
4165
+ var MACOS_HOST_RELAY_IPC_ROOT_PREFIX = "/private/tmp/ceal-host-";
4166
+ function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
4167
+ if (!Number.isInteger(uid) || uid < 0 || uid > DARWIN_UID_MAX) throw new TypeError("Host runtime effective user identity is invalid.");
4168
+ return `${MACOS_HOST_RELAY_IPC_ROOT_PREFIX}${uid}`;
4169
+ }
4170
+ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
4171
+ const sourceId = hostSourceUuid(sourceRef);
4172
+ if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
4173
+ const path = platform === "win32" ? win324 : posix3;
4174
+ const sourcesRoot = path.join(stateRoot, "sources");
4175
+ const sourceRoot = path.join(sourcesRoot, sourceId);
4176
+ const runtimeRoot = path.join(stateRoot, "run");
4177
+ const rootedEndpoint = path.join(runtimeRoot, `${sourceId}.sock`);
4178
+ const endpoint = projectRelayEndpoint(stateRoot, sourceRef, rootedEndpoint, platform, uid);
4179
+ 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 };
4180
+ }
4181
+ function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
4182
+ if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
4183
+ const digest2 = createHash7("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
4184
+ return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix3.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
4185
+ }
4186
+ function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
4187
+ const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
4188
+ 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.");
4189
+ return paths.endpoint;
4190
+ }
4191
+
4192
+ // host/relay/src/host-registration-state.ts
4193
+ var HOST_REGISTRATION_STATE_SCHEMA = "ceal.host_registration_state.v1";
4194
+ var HOST_REGISTRATION_STATE_KEYS = Object.freeze([
4195
+ "credential_generation",
4196
+ "gateway_request_origin",
4197
+ "host_access_token",
4198
+ "host_installation_ref",
4199
+ "host_source_ref",
4200
+ "registration_attempt_ref",
4201
+ "schema_version",
4202
+ "status"
4203
+ ]);
4204
+ var HOST_REGISTRATION_STATE_MAX_BYTES = 65536;
4205
+ var HostRegistrationStateError = class extends Error {
4206
+ name = "HostRegistrationStateError";
4207
+ code = "credential";
4208
+ };
4209
+ async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
4210
+ let raw;
4211
+ try {
4212
+ await assertPrivateRegistrationDirectory(dirname5(path), platform, custody);
4213
+ raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
4214
+ } catch (error) {
4215
+ throw registrationReadError(error);
4216
+ }
4217
+ 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}`)}.`);
4218
+ let value;
4219
+ try {
4220
+ value = JSON.parse(raw);
4221
+ } catch {
4222
+ throw new HostRegistrationStateError("Host registration state is invalid.");
4223
+ }
4224
+ return decodeHostRegistrationAuthority(value, expectedHostSourceRef);
4225
+ }
4226
+ async function readWindowsRegistration(path, custody) {
4227
+ const bytes = await readPrivateFileWithSecurefs(path, HOST_REGISTRATION_STATE_MAX_BYTES, custody);
4228
+ try {
4229
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
4230
+ } catch {
4231
+ throw new HostRegistrationStateError("Host registration state is invalid.");
4232
+ }
4233
+ }
4234
+ async function readPosixRegistration(path, platform, custody) {
4235
+ const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform, custody);
4236
+ try {
4237
+ const stats = await handle.stat();
4238
+ 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.");
4239
+ return await handle.readFile("utf8");
4240
+ } finally {
4241
+ await handle.close();
4242
+ }
4243
+ }
4244
+ function registrationReadError(error) {
4245
+ if (error instanceof HostRegistrationStateError) return error;
4246
+ if (error instanceof SecureFileCustodyError && error.reason === "not_private") return new HostRegistrationStateError("Host registration file is not private to its owner.");
4247
+ return new HostRegistrationStateError("Host registration file is unavailable.");
4248
+ }
4249
+ function decodeHostRegistrationAuthority(value, expectedHostSourceRef) {
4250
+ const keys = HOST_REGISTRATION_STATE_KEYS;
4251
+ const fieldCount = record2(value) ? Object.keys(value).length : 0;
4252
+ const missing = record2(value) ? keys.filter((key) => !Object.hasOwn(value, key)).length : keys.length;
4253
+ if (!record2(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" }])}.`);
4254
+ 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>" }])}.`);
4255
+ 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" }])}.`);
4256
+ 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")}.`);
4257
+ return { gateway_request_origin: value.gateway_request_origin, host_access_token: value.host_access_token };
4258
+ }
4259
+ function validRegistrationIdentity(value, expectedHostSourceRef) {
4260
+ 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;
4261
+ }
4262
+ function validRegistrationCredential(value) {
4263
+ return Number.isSafeInteger(value.credential_generation) && Number(value.credential_generation) > 0 && validHostAccessToken(value.host_access_token);
4264
+ }
4265
+ function validHostAccessToken(value) {
4266
+ return typeof value === "string" && CEAL_HOST_ACCESS_TOKEN_PATTERN.test(value);
4267
+ }
4268
+ function validGatewayOrigin(value) {
2693
4269
  try {
2694
- await port.unlink(path);
2695
- } catch (error) {
2696
- if (errorCode(error) !== "ENOENT") failures.push(error);
4270
+ if (typeof value !== "string" || /\s|\0/u.test(value)) return false;
4271
+ const parsed = new URL(value);
4272
+ const hostname = parsed.hostname.toLowerCase().replace(/\.+$/u, "");
4273
+ return hostname !== "" && validGatewayPort(parsed.port) && (loopbackHttpOrigin(parsed, hostname) || parsed.protocol === "https:") && cleanOriginPath(parsed) && bareOriginSuffix(value);
4274
+ } catch {
4275
+ return false;
2697
4276
  }
2698
4277
  }
2699
- function throwFailures(failures) {
2700
- if (failures.length === 1) throw failures[0];
2701
- if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
4278
+ function loopbackHttpOrigin(parsed, hostname) {
4279
+ return parsed.protocol === "http:" && parsed.port !== "" && (hostname === "127.0.0.1" || hostname === "[::1]");
2702
4280
  }
2703
- function directorySyncUnsupported(error) {
2704
- return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
4281
+ function validGatewayPort(port) {
4282
+ if (port === "") return true;
4283
+ const numeric = Number(port);
4284
+ return Number.isInteger(numeric) && numeric >= 1 && numeric <= 65535;
2705
4285
  }
2706
- function errorCode(error) {
2707
- return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
4286
+ function cleanOriginPath(parsed) {
4287
+ return parsed.username === "" && parsed.password === "" && parsed.pathname === "/" && parsed.search === "" && parsed.hash === "";
4288
+ }
4289
+ function bareOriginSuffix(value) {
4290
+ const schemeEnd = value.indexOf("://");
4291
+ const authority = schemeEnd < 0 ? "" : value.slice(schemeEnd + 3);
4292
+ const suffixOffset = authority.search(/[\\/?#]/u);
4293
+ const rawSuffix = suffixOffset < 0 ? "" : authority.slice(suffixOffset);
4294
+ return rawSuffix === "" || rawSuffix === "/";
4295
+ }
4296
+ async function assertPrivateRegistrationDirectory(path, platform, custody) {
4297
+ if (!await isPrivateDirectory(path, platform, custody)) throw new HostRegistrationStateError("Host registration directory is not private to its owner.");
4298
+ }
4299
+ function record2(value) {
4300
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4301
+ }
4302
+
4303
+ // host/abortable-wait.ts
4304
+ function waitForAbort(signal, milliseconds) {
4305
+ if (signal.aborted) return Promise.resolve();
4306
+ return new Promise((resolve2) => {
4307
+ const timer = setTimeout(finish, milliseconds);
4308
+ function finish() {
4309
+ clearTimeout(timer);
4310
+ signal.removeEventListener("abort", finish);
4311
+ resolve2();
4312
+ }
4313
+ signal.addEventListener("abort", finish, { once: true });
4314
+ });
4315
+ }
4316
+
4317
+ // host/relay/src/host-usage-facts-uploader.ts
4318
+ var HostUsageFactsUploader = class {
4319
+ options;
4320
+ store;
4321
+ constructor(options) {
4322
+ if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
4323
+ this.options = options;
4324
+ this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
4325
+ }
4326
+ async close() {
4327
+ await this.store.close();
4328
+ }
4329
+ async uploadOne(signal) {
4330
+ const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4331
+ if (candidate === null) return false;
4332
+ 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);
4333
+ const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4334
+ const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4335
+ const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4336
+ method: "POST",
4337
+ headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4338
+ body: JSON.stringify(candidate.batch),
4339
+ signal: requestSignal
4340
+ });
4341
+ if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
4342
+ await response2.body?.cancel().catch(() => void 0);
4343
+ throw new Error("Gateway did not acknowledge the Host usage facts batch.");
4344
+ }
4345
+ await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
4346
+ return true;
4347
+ }
4348
+ };
4349
+ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4350
+ const uploader = new HostUsageFactsUploader(options);
4351
+ let delay = 500;
4352
+ let failures = 0;
4353
+ try {
4354
+ while (!signal.aborted) {
4355
+ try {
4356
+ await options.capture_next?.();
4357
+ } catch {
4358
+ writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
4359
+ }
4360
+ if (signal.aborted) return;
4361
+ try {
4362
+ const uploaded = await uploader.uploadOne(signal);
4363
+ failures = 0;
4364
+ delay = uploaded ? 100 : 1e3;
4365
+ } catch {
4366
+ if (signal.aborted) return;
4367
+ failures += 1;
4368
+ delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
4369
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4370
+ }
4371
+ if (!signal.aborted) await wait(signal, delay);
4372
+ }
4373
+ } finally {
4374
+ await uploader.close().catch(() => void 0);
4375
+ }
2708
4376
  }
2709
4377
 
2710
4378
  // host/relay/src/relay-quarantine-store.ts
@@ -2722,18 +4390,9 @@ var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2722
4390
 
2723
4391
  // host/relay/src/relay-ipc.ts
2724
4392
  var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2725
- var HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2726
- "permission_denied",
2727
- "socket_missing",
2728
- "connection_refused",
2729
- "closed_early",
2730
- "response_invalid",
2731
- "timed_out",
2732
- "cancelled",
2733
- "unavailable"
2734
- ]);
2735
4393
 
2736
4394
  // host/claude/src/claude-invocation-context.ts
4395
+ import { isAbsolute as isAbsolute3 } from "node:path";
2737
4396
  function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
2738
4397
  return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
2739
4398
  }
@@ -2744,7 +4403,7 @@ function validateClaudeHostInvocationContext(value) {
2744
4403
  validateContextTimes(value);
2745
4404
  }
2746
4405
  function contextShape(value) {
2747
- return record2(value) && value.schema_version === CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION && hasHostInvocationContextKeys(value, ["working_directory", "turn_generation_ref"]);
4406
+ return record3(value) && value.schema_version === CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION && hasHostInvocationContextKeys(value, ["working_directory", "turn_generation_ref"]);
2748
4407
  }
2749
4408
  function validateIdentity(value) {
2750
4409
  if (!validIdentity(value)) throw new ClaudeHostError("storage", "Claude Host invocation identity is malformed.");
@@ -2756,13 +4415,13 @@ function validateContextTimes(value) {
2756
4415
  if (!timestamp(value.expires_at) || !optionalDirectory(value.working_directory)) throw new ClaudeHostError("storage", "Claude Host invocation context is malformed.");
2757
4416
  }
2758
4417
  function validIdentity(value) {
2759
- return record2(value) && hasHostInvocationIdentityKeys(value) && [value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2);
4418
+ return record3(value) && hasHostInvocationIdentityKeys(value) && [value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2);
2760
4419
  }
2761
4420
  function optionalSafeRef(value) {
2762
4421
  return value === void 0 || safeRef2(value);
2763
4422
  }
2764
4423
  function optionalDirectory(value) {
2765
- return value === void 0 || typeof value === "string" && value.startsWith("/") && !value.includes("\0") && value.length <= 4096;
4424
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && !value.includes("\0") && value.length <= 4096;
2766
4425
  }
2767
4426
  function safeRef2(value) {
2768
4427
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
@@ -2770,7 +4429,7 @@ function safeRef2(value) {
2770
4429
  function timestamp(value) {
2771
4430
  return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
2772
4431
  }
2773
- function record2(value) {
4432
+ function record3(value) {
2774
4433
  return value !== null && typeof value === "object" && !Array.isArray(value);
2775
4434
  }
2776
4435
 
@@ -2787,18 +4446,18 @@ var ClaudeOutboxStore = class {
2787
4446
  activeContexts;
2788
4447
  turnSelections;
2789
4448
  constructor(directory) {
2790
- if (!directory.startsWith("/")) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
4449
+ if (!isAbsolute4(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
2791
4450
  this.directory = directory;
2792
- this.envelopes = join2(directory, "envelopes");
2793
- this.sessions = join2(directory, "sessions");
2794
- this.registrations = join2(directory, "transcript-registrations");
2795
- this.cursors = join2(directory, "transcript-cursors");
2796
- this.activeContexts = join2(directory, "active-contexts");
2797
- this.turnSelections = join2(directory, "turn-selections");
4451
+ this.envelopes = join4(directory, "envelopes");
4452
+ this.sessions = join4(directory, "sessions");
4453
+ this.registrations = join4(directory, "transcript-registrations");
4454
+ this.cursors = join4(directory, "transcript-cursors");
4455
+ this.activeContexts = join4(directory, "active-contexts");
4456
+ this.turnSelections = join4(directory, "turn-selections");
2798
4457
  }
2799
4458
  async prepare() {
2800
4459
  for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
2801
- await mkdir2(path, { recursive: true, mode: 448 });
4460
+ await mkdir4(path, { recursive: true, mode: 448 });
2802
4461
  }
2803
4462
  }
2804
4463
  async activateInvocationContext(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
@@ -2844,7 +4503,7 @@ var ClaudeOutboxStore = class {
2844
4503
  for (const name of await readdir(this.activeContexts)) {
2845
4504
  if (!name.endsWith(".json")) continue;
2846
4505
  try {
2847
- const value = JSON.parse(await readFile(join2(this.activeContexts, name), "utf8"));
4506
+ const value = JSON.parse(await readFile(join4(this.activeContexts, name), "utf8"));
2848
4507
  validateClaudeHostInvocationContext(value);
2849
4508
  if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
2850
4509
  } catch {
@@ -2864,7 +4523,7 @@ var ClaudeOutboxStore = class {
2864
4523
  for (const name of await readdir(this.envelopes)) {
2865
4524
  if (!name.endsWith(".json")) continue;
2866
4525
  try {
2867
- const value = JSON.parse(await readFile(join2(this.envelopes, name), "utf8"));
4526
+ const value = JSON.parse(await readFile(join4(this.envelopes, name), "utf8"));
2868
4527
  validateEnvelope(value);
2869
4528
  entries.push(value);
2870
4529
  } catch {
@@ -2877,7 +4536,7 @@ var ClaudeOutboxStore = class {
2877
4536
  async removeEnvelope(entry) {
2878
4537
  validateEnvelope(entry);
2879
4538
  try {
2880
- await unlink2(this.envelopePath(entry.submission_ref));
4539
+ await unlink3(this.envelopePath(entry.submission_ref));
2881
4540
  } catch (error) {
2882
4541
  if (code(error) !== "ENOENT") throw error;
2883
4542
  }
@@ -2885,13 +4544,13 @@ var ClaudeOutboxStore = class {
2885
4544
  async saveSession(snapshot) {
2886
4545
  validateSession(snapshot);
2887
4546
  await this.prepare();
2888
- await durableAtomicReplace(join2(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
4547
+ await durableAtomicReplace(join4(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
2889
4548
  }
2890
4549
  async readSession(sourceRef, sessionRef) {
2891
4550
  if (!SAFE_REF2.test(sourceRef) || !SAFE_REF2.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
2892
4551
  await this.prepare();
2893
4552
  try {
2894
- const value = JSON.parse(await readFile(join2(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
4553
+ const value = JSON.parse(await readFile(join4(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
2895
4554
  validateSession(value);
2896
4555
  return value;
2897
4556
  } catch (error) {
@@ -2926,7 +4585,7 @@ var ClaudeOutboxStore = class {
2926
4585
  for (const name of await readdir(this.registrations)) {
2927
4586
  if (!name.endsWith(".json")) continue;
2928
4587
  try {
2929
- const value = JSON.parse(await readFile(join2(this.registrations, name), "utf8"));
4588
+ const value = JSON.parse(await readFile(join4(this.registrations, name), "utf8"));
2930
4589
  validateRegistration(value);
2931
4590
  registrations.push(value);
2932
4591
  } catch {
@@ -2964,16 +4623,16 @@ var ClaudeOutboxStore = class {
2964
4623
  await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
2965
4624
  }
2966
4625
  envelopePath(ref) {
2967
- return join2(this.envelopes, `${cealRequestSha256(ref)}.json`);
4626
+ return join4(this.envelopes, `${cealRequestSha256(ref)}.json`);
2968
4627
  }
2969
4628
  registrationPath(sourceRef, sessionRef) {
2970
- return join2(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4629
+ return join4(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
2971
4630
  }
2972
4631
  turnSelectionPath(sourceRef, sessionRef) {
2973
- return join2(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4632
+ return join4(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
2974
4633
  }
2975
4634
  cursorPath(sourceRef, sessionRef) {
2976
- return join2(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4635
+ return join4(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
2977
4636
  }
2978
4637
  async readRegistrationFile(path) {
2979
4638
  try {
@@ -2987,13 +4646,13 @@ var ClaudeOutboxStore = class {
2987
4646
  }
2988
4647
  async removeStateFile(path) {
2989
4648
  try {
2990
- await unlink2(path);
4649
+ await unlink3(path);
2991
4650
  } catch (error) {
2992
4651
  if (code(error) !== "ENOENT") throw error;
2993
4652
  }
2994
4653
  }
2995
4654
  activeContextPath(identity) {
2996
- return join2(this.activeContexts, `${invocationContextKey(identity)}.json`);
4655
+ return join4(this.activeContexts, `${invocationContextKey(identity)}.json`);
2997
4656
  }
2998
4657
  };
2999
4658
  function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
@@ -3016,15 +4675,15 @@ function safeRef3(value) {
3016
4675
  function timestamp2(value) {
3017
4676
  return typeof value === "string" && Number.isFinite(Date.parse(value));
3018
4677
  }
3019
- function record3(value) {
4678
+ function record4(value) {
3020
4679
  return value !== null && typeof value === "object" && !Array.isArray(value);
3021
4680
  }
3022
4681
  function code(error) {
3023
- return record3(error) && typeof error.code === "string" ? error.code : null;
4682
+ return record4(error) && typeof error.code === "string" ? error.code : null;
3024
4683
  }
3025
4684
  function validateEnvelope(value) {
3026
- if (!record3(value)) throw new ClaudeHostError("storage", "Claude outbox entry is malformed.");
3027
- if (!sameKeys(value, ["schema_version", "identity", "host_input_ref", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"])) {
4685
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude outbox entry is malformed.");
4686
+ if (!sameKeys2(value, ["schema_version", "identity", "host_input_ref", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"])) {
3028
4687
  throw new ClaudeHostError("storage", `Claude outbox entry key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the outbox entry key set")}).`);
3029
4688
  }
3030
4689
  if (value.schema_version !== CLAUDE_OUTBOX_SCHEMA_VERSION) throw new ClaudeHostError("storage", `Claude outbox entry is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CLAUDE_OUTBOX_SCHEMA_VERSION}`)}).`);
@@ -3047,8 +4706,8 @@ function validateEnvelopeObservations(value) {
3047
4706
  }
3048
4707
  }
3049
4708
  function validateSession(value) {
3050
- if (!record3(value)) throw new ClaudeHostError("storage", "Claude session snapshot is malformed.");
3051
- if (!sameKeys(value, ["schema_version", "host_session_ref", "host_source_ref", "observed_at", "value", "expires_at"])) {
4709
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude session snapshot is malformed.");
4710
+ if (!sameKeys2(value, ["schema_version", "host_session_ref", "host_source_ref", "observed_at", "value", "expires_at"])) {
3052
4711
  throw new ClaudeHostError("storage", `Claude session snapshot key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the session snapshot key set")}).`);
3053
4712
  }
3054
4713
  if (value.schema_version !== CLAUDE_SESSION_SCHEMA_VERSION) throw new ClaudeHostError("storage", `Claude session snapshot is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CLAUDE_SESSION_SCHEMA_VERSION}`)}).`);
@@ -3057,8 +4716,8 @@ function validateSession(value) {
3057
4716
  }
3058
4717
  }
3059
4718
  function validateRegistration(value) {
3060
- if (!record3(value)) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
3061
- if (!sameKeys(value, ["schema_version", "host_source_ref", "host_session_ref", "claude_session_id", "transcript_path", "registered_at", "expires_at"], ["cwd"])) {
4719
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
4720
+ if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "claude_session_id", "transcript_path", "registered_at", "expires_at"], ["cwd"])) {
3062
4721
  throw new ClaudeHostError("storage", `Claude transcript registration key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the registration key set")}).`);
3063
4722
  }
3064
4723
  if (value.schema_version !== CLAUDE_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
@@ -3069,7 +4728,7 @@ function validateRegistration(value) {
3069
4728
  if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
3070
4729
  }
3071
4730
  function validateRegistrationPaths(cwd, transcriptPath) {
3072
- if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
4731
+ if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute4(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
3073
4732
  throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
3074
4733
  }
3075
4734
  if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
@@ -3077,14 +4736,21 @@ function validateRegistrationPaths(cwd, transcriptPath) {
3077
4736
  }
3078
4737
  }
3079
4738
  function validateCursor(value) {
3080
- if (!record3(value)) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
3081
- if (!sameKeys(value, ["schema_version", "host_source_ref", "host_session_ref", "transcript_path", "offset", "anchor_start", "anchor_sha256", "subagents", "status", "updated_at"], ["device", "inode", "open_turn", "unattributed", "session_observed", "reason"])) {
4739
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
4740
+ if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "transcript_path", "offset", "anchor_start", "anchor_sha256", "subagents", "status", "updated_at"], ["device", "human_message_window", "inode", "open_turn", "unattributed", "session_observed", "reason"])) {
3082
4741
  throw new ClaudeHostError("storage", "Claude transcript cursor key set is malformed.");
3083
4742
  }
3084
4743
  if (value.schema_version !== CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
3085
4744
  if (![value.host_source_ref, value.host_session_ref].every((candidate) => typeof candidate === "string" && SAFE_REF2.test(candidate))) throw new ClaudeHostError("storage", "Claude transcript cursor references are malformed.");
3086
4745
  if (typeof value.transcript_path !== "string" || value.transcript_path.length === 0) throw new ClaudeHostError("storage", "Claude transcript cursor path is malformed.");
3087
4746
  validateCursorPosition(value);
4747
+ if (value.human_message_window !== void 0) {
4748
+ try {
4749
+ decodeCealHostInvocationHumanMessageWindow(value.human_message_window);
4750
+ } catch {
4751
+ throw new ClaudeHostError("storage", "Claude transcript human-message projection is malformed.");
4752
+ }
4753
+ }
3088
4754
  validateCursorTurn(value.open_turn, value.unattributed, value.session_observed);
3089
4755
  validateSubagentCursors(value.subagents);
3090
4756
  if (value.reason !== void 0 && !isHostTranscriptCursorReason(value.reason)) throw new ClaudeHostError("storage", "Claude transcript cursor reason is malformed.");
@@ -3102,13 +4768,13 @@ function validateCursorTurn(openTurn, unattributed, sessionObserved) {
3102
4768
  if (sessionObserved !== void 0 && typeof sessionObserved !== "boolean") throw new ClaudeHostError("storage", "Claude transcript cursor session marker is malformed.");
3103
4769
  }
3104
4770
  function validateSubagentCursors(value) {
3105
- if (!record3(value)) throw new ClaudeHostError("storage", "Claude transcript subagent cursors are malformed.");
4771
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude transcript subagent cursors are malformed.");
3106
4772
  for (const [name, entry] of Object.entries(value)) validateSubagentEntry(name, entry);
3107
4773
  }
3108
4774
  function validateSubagentEntry(name, entry) {
3109
4775
  if (name.length === 0 || name.length > CLAUDE_TRANSCRIPT_SUBAGENT_NAME_MAX_CHARACTERS || name.includes("/")) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
3110
4776
  if (name.includes("\0")) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
3111
- if (!record3(entry) || !sameKeys(entry, ["offset", "anchor_start", "anchor_sha256"], ["device", "inode"]) || !nonNegativeInteger(entry.offset)) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
4777
+ if (!record4(entry) || !sameKeys2(entry, ["offset", "anchor_start", "anchor_sha256"], ["device", "inode"]) || !nonNegativeInteger(entry.offset)) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
3112
4778
  validateSubagentIdentity(entry);
3113
4779
  }
3114
4780
  function validateSubagentIdentity(entry) {
@@ -3124,7 +4790,7 @@ function validCursorPosition(value) {
3124
4790
  return nonNegativeInteger(value.offset) && nonNegativeInteger(value.anchor_start) && typeof value.anchor_sha256 === "string" && /^[a-f0-9]{64}$/u.test(value.anchor_sha256);
3125
4791
  }
3126
4792
  function validOpenTurn(value) {
3127
- if (!record3(value) || !sameKeys(value, ["turn_key", "user_uuid", "prompt_ref", "host_input_ref", "started_at", "last_observed_at", "message_ids", "counts"], ["last_terminal_digest"])) return false;
4793
+ if (!record4(value) || !sameKeys2(value, ["turn_key", "user_uuid", "prompt_ref", "host_input_ref", "started_at", "last_observed_at", "message_ids", "counts"], ["last_terminal_digest"])) return false;
3128
4794
  if (![value.turn_key, value.user_uuid, value.prompt_ref, value.host_input_ref].every((candidate) => typeof candidate === "string" && SAFE_REF2.test(candidate))) return false;
3129
4795
  if (!timestamp2(value.started_at) || !timestamp2(value.last_observed_at)) return false;
3130
4796
  if (!validMessageIds(value.message_ids)) return false;
@@ -3137,30 +4803,30 @@ function validMessageIds(value) {
3137
4803
  return new Set(value).size === value.length;
3138
4804
  }
3139
4805
  function validUnattributed(value) {
3140
- if (!record3(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output", "message_ids", "last_observed_at"])) return false;
4806
+ if (!record4(value) || !sameKeys2(value, ["input", "cached_input", "cache_write_input", "output", "message_ids", "last_observed_at"])) return false;
3141
4807
  if (!validMessageIds(value.message_ids) || value.message_ids.length === 0) return false;
3142
4808
  if (!timestamp2(value.last_observed_at)) return false;
3143
4809
  return validTurnCounts(value);
3144
4810
  }
3145
4811
  function validTurnCounts(value) {
3146
- if (!record3(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output"])) return false;
4812
+ if (!record4(value) || !sameKeys2(value, ["input", "cached_input", "cache_write_input", "output"])) return false;
3147
4813
  return [value.input, value.cached_input, value.cache_write_input, value.output].every(nonNegativeInteger);
3148
4814
  }
3149
4815
  function validateIdentity2(value) {
3150
- if (!record3(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every((candidate) => typeof candidate === "string" && SAFE_REF2.test(candidate))) {
4816
+ if (!record4(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every((candidate) => typeof candidate === "string" && SAFE_REF2.test(candidate))) {
3151
4817
  throw new ClaudeHostError("storage", "Claude Host identity is malformed.");
3152
4818
  }
3153
4819
  }
3154
4820
  function nonNegativeInteger(value) {
3155
4821
  return Number.isSafeInteger(value) && Number(value) >= 0;
3156
4822
  }
3157
- function sameKeys(value, required, optional = []) {
4823
+ function sameKeys2(value, required, optional = []) {
3158
4824
  return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
3159
4825
  }
3160
4826
 
3161
4827
  // host/claude/src/claude-transcript-watcher.ts
3162
4828
  import { readdir as readdir2 } from "node:fs/promises";
3163
- import { join as join3 } from "node:path";
4829
+ import { join as join5 } from "node:path";
3164
4830
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
3165
4831
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3166
4832
  store;
@@ -3182,11 +4848,13 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3182
4848
  }
3183
4849
  async scanOpened(handle, registration) {
3184
4850
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
3185
- const cursor = await this.preflight(registration, handle, size, device, inode);
4851
+ const preflight = await this.preflight(registration, handle, size, device, inode);
4852
+ const cursor = preflight.cursor;
3186
4853
  if (cursor === null) return { records: 0, enqueued: 0, quarantined: true };
3187
4854
  if (cursor.status === "quarantined") {
3188
4855
  return { records: 0, enqueued: 0, quarantined: true };
3189
4856
  }
4857
+ if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
3190
4858
  const draft = mutableCursor(cursor);
3191
4859
  await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
3192
4860
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
@@ -3199,6 +4867,15 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3199
4867
  return { records: 0, enqueued: 0, quarantined: true };
3200
4868
  }
3201
4869
  async retireMissing(registration) {
4870
+ const observedAt = this.stamp();
4871
+ if (Date.parse(registration.expires_at) <= Date.parse(observedAt)) return this.retireTranscript(registration);
4872
+ const cursor = await this.store.readTranscriptCursor(registration);
4873
+ if (cursor !== null && isUnmaterializedCursor(cursor, this.sha(Buffer.alloc(0)))) {
4874
+ return { records: 0, enqueued: 0, quarantined: false };
4875
+ }
4876
+ return this.retireTranscript(registration);
4877
+ }
4878
+ retireTranscript(registration) {
3202
4879
  return this.retireMissingTranscript(registration.transcript_path, "Claude", () => this.store.retireTranscriptRegistration(registration));
3203
4880
  }
3204
4881
  initialCursor(registration) {
@@ -3210,6 +4887,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3210
4887
  offset: 0,
3211
4888
  anchor_start: 0,
3212
4889
  anchor_sha256: this.sha(Buffer.alloc(0)),
4890
+ human_message_window: { messages: [], truncated: false },
3213
4891
  subagents: {},
3214
4892
  status: "active",
3215
4893
  updated_at: this.stamp()
@@ -3227,37 +4905,70 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3227
4905
  }
3228
4906
  async preflight(registration, handle, size, device, inode) {
3229
4907
  const existing = await this.store.readTranscriptCursor(registration);
3230
- if (existing?.status === "quarantined") return existing;
4908
+ if (existing?.status === "quarantined") return { cursor: existing, checkpointPending: false };
3231
4909
  const cursor = existing ?? this.initialCursor(registration);
3232
4910
  if (cursor.device === void 0) {
3233
- if (cursor.offset !== 0) return await this.quarantineStored(cursor, device, inode, "transcript_replaced");
3234
- return { ...cursor, device, inode };
4911
+ const pinned = { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
4912
+ const reason2 = this.cursorIdentityReason(pinned, registration.transcript_path, device, inode);
4913
+ if (cursor.offset !== 0 || reason2 !== null) return { cursor: await this.quarantineStored(cursor, device, inode, "transcript_replaced"), checkpointPending: false };
4914
+ return { cursor: pinned, checkpointPending: true };
3235
4915
  }
3236
4916
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
3237
- if (reason !== null) return await this.quarantineStored(cursor, device, inode, reason);
3238
- return cursor;
4917
+ if (reason !== null) return { cursor: await this.quarantineStored(cursor, device, inode, reason), checkpointPending: false };
4918
+ if (cursor.human_message_window !== void 0) return { cursor, checkpointPending: false };
4919
+ return { cursor: { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) }, checkpointPending: true };
4920
+ }
4921
+ async readHumanMessageProjection(registration, handle, watermark) {
4922
+ let offset = 0;
4923
+ let window = { messages: [], truncated: false };
4924
+ while (offset < watermark) {
4925
+ const complete = await this.readChunk(handle, offset, watermark);
4926
+ if (complete === "empty" || complete === "partial") throw new ClaudeHostError("payload_rejected", "Claude transcript projection prefix is incomplete.", "malformed_line");
4927
+ for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
4928
+ let row;
4929
+ try {
4930
+ row = JSON.parse(line);
4931
+ } catch {
4932
+ throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
4933
+ }
4934
+ const prompt = decodeClaudeHumanMessageRow(row, registration.claude_session_id);
4935
+ if (prompt !== null) window = mergeHostInvocationHumanMessageWindow(window, [{
4936
+ host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, prompt.turnId),
4937
+ host_input_ref: claudeLocalInputRef(registration.claude_session_id, prompt.turnId),
4938
+ text: prompt.content
4939
+ }]);
4940
+ }
4941
+ offset += complete.length;
4942
+ }
4943
+ if (offset !== watermark) throw new ClaudeHostError("payload_rejected", "Claude transcript projection prefix does not match its cursor boundary.", "malformed_line");
4944
+ return window;
3239
4945
  }
3240
4946
  async consumeMainChunk(registration, complete, draft) {
3241
4947
  for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3242
4948
  draft.consumed += 1;
3243
- const record4 = parseTranscriptLine(line);
3244
- if (record4 === null) throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
3245
- if (isUserTurnLine(record4)) await this.openTurn(registration, draft, record4);
3246
- else if (isAssistantUsageLine(record4)) this.accumulateUsage(draft, toUsage(record4.uuid, record4.timestamp, record4.message.usage));
3247
- else if (isAssistantLine(record4) && record4.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude transcript usage is malformed.");
4949
+ const record5 = parseTranscriptLine(line);
4950
+ if (record5 === null) throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
4951
+ if (isUserTurnLine(record5)) await this.openTurn(registration, draft, record5);
4952
+ else if (isAssistantUsageLine(record5)) this.accumulateUsage(draft, toUsage(record5.uuid, record5.timestamp, record5.message.usage));
4953
+ else if (isAssistantLine(record5) && record5.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude transcript usage is malformed.");
3248
4954
  else {
3249
- const queued = decodeClaudeQueuedPromptRow(record4, registration.claude_session_id);
4955
+ const queued = decodeClaudeQueuedPromptRow(record5, registration.claude_session_id);
3250
4956
  if (queued !== null) await this.openQueuedTurn(registration, draft, queued);
3251
4957
  }
3252
4958
  }
3253
4959
  }
3254
- async openTurn(registration, draft, record4) {
3255
- await this.openPromptTurn(registration, draft, { uuid: record4.uuid, timestamp: record4.timestamp, content: record4.message.content });
4960
+ async openTurn(registration, draft, record5) {
4961
+ await this.openPromptTurn(registration, draft, { uuid: record5.uuid, timestamp: record5.timestamp, content: record5.message.content });
3256
4962
  }
3257
4963
  async openQueuedTurn(registration, draft, queued) {
3258
4964
  await this.openPromptTurn(registration, draft, { uuid: queued.turnId, timestamp: queued.timestamp, content: queued.content });
3259
4965
  }
3260
4966
  async openPromptTurn(registration, draft, prompt) {
4967
+ draft.human_message_window = mergeHostInvocationHumanMessageWindow(draft.human_message_window, [{
4968
+ host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, prompt.uuid),
4969
+ host_input_ref: claudeLocalInputRef(registration.claude_session_id, prompt.uuid),
4970
+ text: prompt.content
4971
+ }]);
3261
4972
  await this.closeTurn(registration, draft, prompt.timestamp);
3262
4973
  const sessionRef = registration.host_session_ref;
3263
4974
  const turnRef = claudeLocalTurnRef(registration.claude_session_id, prompt.uuid);
@@ -3275,7 +4986,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3275
4986
  }
3276
4987
  await this.persistOpenedTurnContext(draft, { uuid: prompt.uuid, timestamp: prompt.timestamp, message: { content: prompt.content } }, inputRef, turnRef, promptRef, identity, observations);
3277
4988
  }
3278
- async persistOpenedTurnContext(draft, record4, inputRef, turnRef, promptRef, identity, observations) {
4989
+ async persistOpenedTurnContext(draft, record5, inputRef, turnRef, promptRef, identity, observations) {
3279
4990
  const expiresAt = this.expire(this.outboxRetentionMs);
3280
4991
  await this.store.putEnvelope({
3281
4992
  schema_version: "ceal.claude_observation_outbox.v1",
@@ -3285,27 +4996,27 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3285
4996
  observations,
3286
4997
  origin_input: true,
3287
4998
  submission_ref: submissionRef("input", turnRef, inputRef, promptRef),
3288
- created_at: record4.timestamp,
4999
+ created_at: record5.timestamp,
3289
5000
  expires_at: expiresAt
3290
5001
  });
3291
5002
  draft.enqueued += 1;
3292
5003
  await this.activateOpenedTurnContext(identity, promptRef, expiresAt);
3293
- this.setOpenedTurn(draft, record4, inputRef, turnRef, promptRef);
5004
+ this.setOpenedTurn(draft, record5, inputRef, turnRef, promptRef);
3294
5005
  }
3295
5006
  async activateOpenedTurnContext(identity, promptRef, expiresAt) {
3296
5007
  const selection = await this.store.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref);
3297
5008
  const turnGenerationRef = selection?.prompt_ref === promptRef ? selection.turn_generation_ref : void 0;
3298
5009
  await this.activateContext(identity, promptRef, turnGenerationRef, expiresAt);
3299
5010
  }
3300
- setOpenedTurn(draft, record4, inputRef, turnRef, promptRef) {
5011
+ setOpenedTurn(draft, record5, inputRef, turnRef, promptRef) {
3301
5012
  const folded = foldUnattributed(draft.unattributed);
3302
5013
  draft.open_turn = {
3303
5014
  turn_key: turnRef,
3304
- user_uuid: record4.uuid,
5015
+ user_uuid: record5.uuid,
3305
5016
  prompt_ref: promptRef,
3306
5017
  host_input_ref: inputRef,
3307
- started_at: record4.timestamp,
3308
- last_observed_at: folded?.last_observed_at ?? record4.timestamp,
5018
+ started_at: record5.timestamp,
5019
+ last_observed_at: folded?.last_observed_at ?? record5.timestamp,
3309
5020
  message_ids: folded?.message_ids ?? [],
3310
5021
  counts: folded?.counts ?? zeroCounts()
3311
5022
  };
@@ -3366,7 +5077,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3366
5077
  return consumed;
3367
5078
  }
3368
5079
  async consumeSubagentFile(draft, directory, name) {
3369
- const path = join3(directory, name);
5080
+ const path = join5(directory, name);
3370
5081
  let handle;
3371
5082
  try {
3372
5083
  handle = await openNoFollow(path);
@@ -3397,10 +5108,10 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3397
5108
  let consumed = 0;
3398
5109
  for (const line of chunk.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3399
5110
  consumed += 1;
3400
- const record4 = parseTranscriptLine(line);
3401
- if (record4 === null) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript line is not valid JSON.", "malformed_line");
3402
- if (isAssistantUsageLine(record4)) this.accumulateUsage(draft, toUsage(record4.uuid, record4.timestamp, record4.message.usage));
3403
- else if (isAssistantLine(record4) && record4.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript usage is malformed.");
5111
+ const record5 = parseTranscriptLine(line);
5112
+ if (record5 === null) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript line is not valid JSON.", "malformed_line");
5113
+ if (isAssistantUsageLine(record5)) this.accumulateUsage(draft, toUsage(record5.uuid, record5.timestamp, record5.message.usage));
5114
+ else if (isAssistantLine(record5) && record5.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript usage is malformed.");
3404
5115
  }
3405
5116
  return consumed;
3406
5117
  }
@@ -3459,6 +5170,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3459
5170
  offset: draft.offset,
3460
5171
  anchor_start: anchor.start,
3461
5172
  anchor_sha256: anchor.sha256,
5173
+ human_message_window: draft.human_message_window,
3462
5174
  subagents: draft.subagents,
3463
5175
  ...draft.open_turn === void 0 ? {} : { open_turn: draft.open_turn },
3464
5176
  ...draft.unattributed === void 0 ? {} : { unattributed: draft.unattributed },
@@ -3501,9 +5213,13 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3501
5213
  return await this.store.readTranscriptCursor(registration).catch(() => null) ?? this.initialCursor(registration);
3502
5214
  }
3503
5215
  };
5216
+ function isUnmaterializedCursor(cursor, emptyAnchorSha256) {
5217
+ return cursor.status === "active" && cursor.device === void 0 && cursor.inode === void 0 && cursor.offset === 0 && cursor.anchor_start === 0 && cursor.anchor_sha256 === emptyAnchorSha256;
5218
+ }
3504
5219
  function mutableCursor(cursor) {
3505
5220
  return {
3506
5221
  offset: cursor.offset,
5222
+ human_message_window: cursor.human_message_window ?? { messages: [], truncated: false },
3507
5223
  ...cursor.open_turn === void 0 ? {} : { open_turn: cursor.open_turn },
3508
5224
  ...cursor.unattributed === void 0 ? {} : { unattributed: cursor.unattributed },
3509
5225
  subagents: Object.fromEntries(Object.entries(cursor.subagents).map(([name, entry]) => [name, { ...entry }])),
@@ -3580,32 +5296,32 @@ function parseTranscriptLine(line) {
3580
5296
  return null;
3581
5297
  }
3582
5298
  }
3583
- function lineIdentity(record4) {
3584
- if (typeof record4.uuid !== "string" || record4.uuid.length === 0 || record4.uuid.length > 256) return null;
3585
- if (typeof record4.timestamp !== "string" || !Number.isFinite(Date.parse(record4.timestamp))) return null;
3586
- return { uuid: record4.uuid, timestamp: record4.timestamp };
5299
+ function lineIdentity(record5) {
5300
+ if (typeof record5.uuid !== "string" || record5.uuid.length === 0 || record5.uuid.length > 256) return null;
5301
+ if (typeof record5.timestamp !== "string" || !Number.isFinite(Date.parse(record5.timestamp))) return null;
5302
+ return { uuid: record5.uuid, timestamp: record5.timestamp };
3587
5303
  }
3588
- function isUserTurnLine(record4) {
3589
- if (!isTranscriptRecord(record4) || record4.type !== "user") return false;
3590
- if (!isTranscriptRecord(record4.message) || typeof record4.message.content !== "string") return false;
3591
- if (record4.isMeta === true && (!isTranscriptRecord(record4.origin) || typeof record4.origin.kind !== "string")) return false;
3592
- const identity = lineIdentity(record4);
5304
+ function isUserTurnLine(record5) {
5305
+ if (!isTranscriptRecord(record5) || record5.type !== "user") return false;
5306
+ if (!isTranscriptRecord(record5.message) || typeof record5.message.content !== "string") return false;
5307
+ if (record5.isMeta === true && (!isTranscriptRecord(record5.origin) || typeof record5.origin.kind !== "string")) return false;
5308
+ const identity = lineIdentity(record5);
3593
5309
  if (identity === null) throw new ClaudeHostError("payload_rejected", "Claude transcript user line is malformed.");
3594
5310
  return true;
3595
5311
  }
3596
- function isAssistantLine(record4) {
3597
- return isTranscriptRecord(record4) && record4.type === "assistant" && isTranscriptRecord(record4.message);
5312
+ function isAssistantLine(record5) {
5313
+ return isTranscriptRecord(record5) && record5.type === "assistant" && isTranscriptRecord(record5.message);
3598
5314
  }
3599
- function isAssistantUsageLine(record4) {
3600
- if (!isTranscriptRecord(record4)) return false;
3601
- if (!isAssistantLine(record4) || record4.message.usage === void 0) return false;
3602
- const identity = lineIdentity(record4);
3603
- if (identity === null || !isTranscriptRecord(record4.message.usage)) throw new ClaudeHostError("payload_rejected", "Claude transcript usage line is malformed.");
5315
+ function isAssistantUsageLine(record5) {
5316
+ if (!isTranscriptRecord(record5)) return false;
5317
+ if (!isAssistantLine(record5) || record5.message.usage === void 0) return false;
5318
+ const identity = lineIdentity(record5);
5319
+ if (identity === null || !isTranscriptRecord(record5.message.usage)) throw new ClaudeHostError("payload_rejected", "Claude transcript usage line is malformed.");
3604
5320
  return true;
3605
5321
  }
3606
5322
  function subagentsDirectory(transcriptPath) {
3607
5323
  const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
3608
- return join3(stem, "subagents");
5324
+ return join5(stem, "subagents");
3609
5325
  }
3610
5326
  function observationRef(hostSourceRef, event, identity, value) {
3611
5327
  return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
@@ -3641,23 +5357,394 @@ function isSymlinkTranscript(error) {
3641
5357
  return typeof error === "object" && error !== null && "code" in error && error.code === "ELOOP";
3642
5358
  }
3643
5359
 
3644
- // host/claude/src/claude-adapter.ts
3645
- import { createHash as createHash5, randomUUID } from "node:crypto";
5360
+ // host/claude/src/claude-usage-facts-capturer.ts
5361
+ import { createHash as createHash8 } from "node:crypto";
5362
+ import { constants as constants5 } from "node:fs";
3646
5363
  import { readdir as readdir3 } from "node:fs/promises";
3647
- import { constants as constants2 } from "node:fs";
5364
+ import { join as join6 } from "node:path";
5365
+ var ClaudeUsageFactsCapturer = class {
5366
+ sources;
5367
+ usage;
5368
+ now;
5369
+ diagnosticSink;
5370
+ nextRegistrationIndex = 0;
5371
+ nextSourceSlot = "main";
5372
+ nextSubagentIndex = 0;
5373
+ constructor(options) {
5374
+ this.sources = new ClaudeOutboxStore(options.outbox_dir);
5375
+ this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5376
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5377
+ this.diagnosticSink = options.diagnostic_sink;
5378
+ }
5379
+ async captureNext() {
5380
+ const registrations = await this.sources.listTranscriptRegistrations();
5381
+ let failed = false;
5382
+ const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
5383
+ failed = true;
5384
+ }));
5385
+ this.nextRegistrationIndex = result.nextIndex;
5386
+ if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5387
+ return result.captured;
5388
+ }
5389
+ async captureRegistration(registration, onFailure) {
5390
+ const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
5391
+ for (const source of sources) {
5392
+ let captured = false;
5393
+ try {
5394
+ captured = source === "main" ? await this.captureMain(registration) : await this.captureSubagent(registration, onFailure);
5395
+ } catch (error) {
5396
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
5397
+ onFailure();
5398
+ }
5399
+ if (captured) {
5400
+ this.nextSourceSlot = source === "main" ? "subagent" : "main";
5401
+ return true;
5402
+ }
5403
+ }
5404
+ return false;
5405
+ }
5406
+ async captureMain(registration) {
5407
+ const prepared = await openHostUsageTranscriptCursor({
5408
+ path: registration.transcript_path,
5409
+ producer: "claude",
5410
+ source_kind: "claude_transcript",
5411
+ host_source_ref: registration.host_source_ref,
5412
+ host_session_ref: registration.host_session_ref,
5413
+ source_slot: "main",
5414
+ created_at: this.stamp(),
5415
+ store: this.usage,
5416
+ inspect: ownedClaudeTranscriptFile,
5417
+ initial_cursor: initialCursor
5418
+ });
5419
+ if (prepared === null) return false;
5420
+ const { handle: main2, source: mainFile, source_file_ref: mainRef, state, cursor } = prepared;
5421
+ try {
5422
+ if (cursor.source_file_ref !== mainRef || cursor.device !== mainFile.device || cursor.inode !== mainFile.inode || mainFile.size < cursor.offset || !await anchorMatches(main2, cursor)) {
5423
+ await this.usage.commitScanTransition(state, "main", cursor, initialCursor(mainRef, mainFile.device, mainFile.inode), null, [unscopedGap("source_file_replaced")]);
5424
+ return true;
5425
+ }
5426
+ if (mainFile.size > cursor.offset) return await this.captureFile(main2, registration, "main", mainRef, cursor, mainFile.size, state);
5427
+ } finally {
5428
+ await main2.close();
5429
+ }
5430
+ return false;
5431
+ }
5432
+ async captureSubagent(registration, onFailure) {
5433
+ const names = await readSubagentNames(registration);
5434
+ let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
5435
+ if (state === null) return false;
5436
+ state = await this.usage.recoverPending(state);
5437
+ if (state.quarantined_reason !== void 0) return false;
5438
+ if (await this.retireMissingSubagent(state, names)) return true;
5439
+ if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
5440
+ return await this.recordExcessSubagentGap(state, names);
5441
+ }
5442
+ async retireMissingSubagent(state, names) {
5443
+ const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
5444
+ for (const [slot, cursor] of Object.entries(state.cursors)) {
5445
+ if (!slot.startsWith("subagent:") || liveSlots.has(slot)) continue;
5446
+ await this.usage.retireCursor(state, slot, cursor, unscopedGap("source_file_retired"));
5447
+ return true;
5448
+ }
5449
+ return false;
5450
+ }
5451
+ async recordExcessSubagentGap(state, names) {
5452
+ const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
5453
+ if (excessCount <= 0) return false;
5454
+ const mainCursor = state.cursors.main;
5455
+ if (mainCursor === void 0) return false;
5456
+ const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
5457
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
5458
+ return true;
5459
+ }
5460
+ async captureListedSubagents(registration, names, state, onFailure) {
5461
+ const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5462
+ for (let attempt = 0; attempt < candidates.length; attempt += 1) {
5463
+ const index = (this.nextSubagentIndex + attempt) % candidates.length;
5464
+ const name = candidates[index];
5465
+ if (name === void 0) continue;
5466
+ try {
5467
+ if (await this.captureSubagentFile(registration, name, state)) {
5468
+ this.nextSubagentIndex = (index + 1) % candidates.length;
5469
+ return true;
5470
+ }
5471
+ } catch (error) {
5472
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
5473
+ onFailure();
5474
+ }
5475
+ }
5476
+ return false;
5477
+ }
5478
+ async captureSubagentFile(registration, name, state) {
5479
+ let handle;
5480
+ try {
5481
+ const opened = await readHostUsageTranscriptSource(() => openNoFollow(join6(subagentsDirectory(registration.transcript_path), name), constants5.O_RDONLY));
5482
+ handle = opened;
5483
+ const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
5484
+ const sourceRef = sourceFileRef(registration, file.device, file.inode);
5485
+ const slot = subagentSlot(name);
5486
+ let current = state.cursors[slot];
5487
+ if (current === void 0) {
5488
+ current = initialCursor(sourceRef, file.device, file.inode);
5489
+ state = await this.usage.writeCursor(state, slot, current);
5490
+ }
5491
+ if (await cursorReplaced(handle, file, sourceRef, current)) {
5492
+ await this.usage.commitScanTransition(state, slot, current, initialCursor(sourceRef, file.device, file.inode), null, [unscopedGap("source_file_replaced")]);
5493
+ return true;
5494
+ }
5495
+ if (file.size > current.offset) return await this.captureFile(handle, registration, slot, sourceRef, current, file.size, state, "subagent");
5496
+ return false;
5497
+ } finally {
5498
+ await handle?.close();
5499
+ }
5500
+ }
5501
+ async captureFile(handle, registration, slot, sourceRef, before, size, state, kind = "main") {
5502
+ const chunk = await readHostUsageTranscriptChunk(handle, before.offset, size, before.skipping_oversized_line);
5503
+ if (chunk.end_offset === before.offset && chunk.lines.length === 0) return false;
5504
+ const processed = processClaudeChunk(chunk.lines, registration, sourceRef, kind, before, chunk.oversized_rows);
5505
+ const after = await updateAnchor(handle, { ...processed.cursor, offset: chunk.end_offset, skipping_oversized_line: chunk.skipping_oversized_line });
5506
+ const gaps = [...processed.gapCounts].map(([reason, omitted_count]) => ({ reason, source_file_ref: sourceRef, start_offset: before.offset, end_offset: chunk.end_offset, omitted_count }));
5507
+ const batch = processed.facts.length === 0 && gaps.length === 0 ? null : createCealHostUsageBatch({
5508
+ host_source_ref: registration.host_source_ref,
5509
+ host_session_ref: registration.host_session_ref,
5510
+ created_at: processed.createdAt,
5511
+ source_ranges: [{ source_file_ref: sourceRef, start_offset: before.offset, end_offset: chunk.end_offset }],
5512
+ facts: processed.facts,
5513
+ coverage_gaps: gaps
5514
+ });
5515
+ await this.usage.commitScanTransition(state, slot, before, after, batch);
5516
+ return true;
5517
+ }
5518
+ stamp() {
5519
+ const value = this.now();
5520
+ if (!Number.isFinite(value.getTime())) throw new Error("Claude usage facts clock is invalid.");
5521
+ return value.toISOString();
5522
+ }
5523
+ };
5524
+ function parseClaudeRow(line, registration, sourceRef, kind, hostTurnRef) {
5525
+ const value = parseRowRecord(line);
5526
+ const userTurn = kind === "main" ? mainUserTurn(value, registration.claude_session_id) : null;
5527
+ if (userTurn !== null) return { timestamp: timestamp3(userTurn.timestamp), turn_id: userTurn.turnId };
5528
+ if (!assistantRow(value)) return { timestamp: rowTimestamp(value) };
5529
+ return parseAssistantRow(value, registration, sourceRef, kind, hostTurnRef);
5530
+ }
5531
+ function mainUserTurn(value, sessionId) {
5532
+ return decodeClaudeHumanMessageRow(value, sessionId);
5533
+ }
5534
+ function parseRowRecord(line) {
5535
+ let value;
5536
+ try {
5537
+ value = JSON.parse(line);
5538
+ } catch {
5539
+ throw new Error("Claude transcript row is malformed.");
5540
+ }
5541
+ if (!isRecord4(value)) throw new Error("Claude transcript row is malformed.");
5542
+ return value;
5543
+ }
5544
+ function assistantRow(value) {
5545
+ return value.type === "assistant" && isRecord4(value.message);
5546
+ }
5547
+ function parseAssistantRow(value, registration, sourceRef, kind, hostTurnRef) {
5548
+ const message = value.message;
5549
+ const terminal = message.stop_reason === "end_turn";
5550
+ if (message.usage === void 0) return { timestamp: rowTimestamp(value), terminal };
5551
+ if (!isRecord4(message.usage)) return { timestamp: rowTimestamp(value), unsupported: true, terminal };
5552
+ const parsed = parseAssistantUsage(value, message, message.usage, registration, sourceRef, kind, hostTurnRef, terminal);
5553
+ return parsed;
5554
+ }
5555
+ function parseAssistantUsage(value, message, usage, registration, sourceRef, kind, hostTurnRef, terminal) {
5556
+ const observedAt = rowTimestamp(value);
5557
+ const values = assistantUsageValues(value, message, usage);
5558
+ if (values === null) return { timestamp: observedAt, unsupported: true, terminal };
5559
+ const { uuid, input, output, cached, cacheWrite, cacheCreation, reportedModel } = values;
5560
+ const normalizedInput = safeSum(input, cached, cacheWrite);
5561
+ if (normalizedInput === void 0) return { timestamp: observedAt, unsupported: true, terminal };
5562
+ const fact = createClaudeFact({ uuid, input, output, cached, cacheWrite, cacheCreation, normalizedInput, reportedModel, observedAt, registration, sourceRef, kind, hostTurnRef, terminal, stopReason: message.stop_reason });
5563
+ return { timestamp: observedAt, fact, terminal };
5564
+ }
5565
+ function assistantUsageValues(value, message, usage) {
5566
+ const uuid = boundedText2(value.uuid, 256);
5567
+ const input = safeCounter(usage.input_tokens);
5568
+ const output = safeCounter(usage.output_tokens);
5569
+ const cached = optionalCounter(usage, "cache_read_input_tokens");
5570
+ const cacheWrite = optionalCounter(usage, "cache_creation_input_tokens");
5571
+ const cacheCreation = cacheCreationUsage(usage.cache_creation);
5572
+ const reportedModel = message.model === void 0 || message.model === null ? null : boundedText2(message.model, 256);
5573
+ if (uuid === null || input === null || output === null || cached.invalid || cacheWrite.invalid || cacheCreation.invalid || invalidReportedModel(message.model, reportedModel)) return null;
5574
+ return { uuid, input, output, cached: cached.value, cacheWrite: cacheWrite.value, cacheCreation: cacheCreation.value, reportedModel };
5575
+ }
5576
+ function cacheCreationUsage(value) {
5577
+ if (value === void 0 || value === null) return { value: null, invalid: false };
5578
+ if (!isRecord4(value)) return { value: null, invalid: true };
5579
+ const oneHour = optionalCounter(value, "ephemeral_1h_input_tokens");
5580
+ const fiveMinutes = optionalCounter(value, "ephemeral_5m_input_tokens");
5581
+ return {
5582
+ value: { ephemeral_1h_input_tokens: oneHour.value, ephemeral_5m_input_tokens: fiveMinutes.value },
5583
+ invalid: oneHour.invalid || fiveMinutes.invalid
5584
+ };
5585
+ }
5586
+ function invalidReportedModel(model, reportedModel) {
5587
+ return model !== void 0 && model !== null && reportedModel === null;
5588
+ }
5589
+ function safeSum(input, cached, cacheWrite) {
5590
+ if (cached === null || cacheWrite === null) return null;
5591
+ const total = input + cached + cacheWrite;
5592
+ return Number.isSafeInteger(total) ? total : void 0;
5593
+ }
5594
+ function createClaudeFact({ uuid, input, output, cached, cacheWrite, cacheCreation, normalizedInput, reportedModel, observedAt, registration, sourceRef, kind, hostTurnRef, terminal, stopReason }) {
5595
+ const sourceUsage = { input_tokens: input, cache_read_input_tokens: cached, cache_creation_input_tokens: cacheWrite, cache_creation: cacheCreation, output_tokens: output };
5596
+ const sourceEventRef = hostUsageSourceEventReference(sourceRef, `claude:${uuid}:${sha2563(JSON.stringify(sourceUsage))}`);
5597
+ const normalizedTotal = normalizedInput === null ? null : safeOutputTotal(normalizedInput, output);
5598
+ return {
5599
+ fact_ref: hostUsageFactReference(sourceRef, sourceEventRef),
5600
+ host_session_ref: registration.host_session_ref,
5601
+ host_turn_ref: kind === "main" ? hostTurnRef : null,
5602
+ source_file_ref: sourceRef,
5603
+ source_event_ref: sourceEventRef,
5604
+ source_event_uuid: uuid,
5605
+ source_file_kind: kind,
5606
+ observed_at: observedAt,
5607
+ producer: "claude_transcript",
5608
+ requested_model: null,
5609
+ reported_model: reportedModel,
5610
+ source_usage: sourceUsage,
5611
+ normalized_usage: { input: normalizedInput, output, total: normalizedTotal, cached_input: cached, cache_write_input: cacheWrite, reasoning_output: null },
5612
+ counter_semantics: "assistant_message",
5613
+ finality: finality(terminal, stopReason),
5614
+ child_inclusion: "unknown",
5615
+ correction_semantics: "unknown"
5616
+ };
5617
+ }
5618
+ function safeOutputTotal(input, output) {
5619
+ const total = input + output;
5620
+ return Number.isSafeInteger(total) ? total : null;
5621
+ }
5622
+ function finality(terminal, stopReason) {
5623
+ return terminal ? "terminal" : stopReason === null || stopReason === void 0 ? "nonterminal" : "unknown";
5624
+ }
5625
+ function processClaudeChunk(lines, registration, sourceRef, kind, initial, oversizedRows) {
5626
+ let cursor = initial;
5627
+ let createdAt = registration.registered_at;
5628
+ const facts = [];
5629
+ const gapCounts = /* @__PURE__ */ new Map();
5630
+ if (oversizedRows > 0) gapCounts.set("unsupported_source_shape", oversizedRows);
5631
+ for (const line of lines) {
5632
+ let parsed;
5633
+ try {
5634
+ parsed = parseClaudeRow(line.toString("utf8"), registration, sourceRef, kind, cursor.host_turn_ref);
5635
+ } catch {
5636
+ addUnsupportedGap(gapCounts);
5637
+ continue;
5638
+ }
5639
+ createdAt = parsed.timestamp;
5640
+ if (parsed.unsupported === true) addUnsupportedGap(gapCounts);
5641
+ if (parsed.fact !== void 0) facts.push(parsed.fact);
5642
+ cursor = updateClaudeTurnCursor(cursor, parsed, registration, kind);
5643
+ }
5644
+ return { cursor, facts, gapCounts, createdAt };
5645
+ }
5646
+ function addUnsupportedGap(gapCounts) {
5647
+ gapCounts.set("unsupported_source_shape", (gapCounts.get("unsupported_source_shape") ?? 0) + 1);
5648
+ }
5649
+ function updateClaudeTurnCursor(cursor, row, registration, kind) {
5650
+ if (kind !== "main") return cursor;
5651
+ if (row.turn_id !== void 0) return { ...cursor, native_turn_id: row.turn_id, host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, row.turn_id) };
5652
+ return row.terminal === true ? { ...cursor, native_turn_id: null, host_turn_ref: null } : cursor;
5653
+ }
5654
+ async function readSubagentNames(registration) {
5655
+ try {
5656
+ return (await readHostUsageTranscriptSource(() => readdir3(subagentsDirectory(registration.transcript_path)))).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
5657
+ } catch (error) {
5658
+ const cause = error instanceof HostUsageTranscriptSourceError ? error.cause : error;
5659
+ if (errorCode3(cause) === "ENOENT" || errorCode3(cause) === "ENOTDIR") return [];
5660
+ throw error;
5661
+ }
5662
+ }
5663
+ function initialCursor(sourceFileRef2, device, inode) {
5664
+ return { source_file_ref: sourceFileRef2, device, inode, offset: 0, anchor_start: 0, anchor_sha256: sha2563(""), last_ordinal: null, host_turn_ref: null, native_turn_id: null, requested_model: null, codex_total_usage: null, skipping_oversized_line: false };
5665
+ }
5666
+ function sourceFileRef(registration, device, inode) {
5667
+ return hostUsageSourceFileReference("claude_transcript", registration.host_source_ref, registration.host_session_ref, device, inode);
5668
+ }
5669
+ function subagentSlot(name) {
5670
+ return `subagent:${sha2563(name)}`;
5671
+ }
5672
+ function unscopedGap(reason) {
5673
+ return { reason, source_file_ref: null, start_offset: null, end_offset: null, omitted_count: null };
5674
+ }
5675
+ async function anchorMatches(handle, cursor) {
5676
+ const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
5677
+ if (bytes.length === 0) return sha2563("") === cursor.anchor_sha256;
5678
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, cursor.anchor_start));
5679
+ return bytesRead === bytes.length && sha2563(bytes) === cursor.anchor_sha256;
5680
+ }
5681
+ async function cursorReplaced(handle, file, sourceRef, cursor) {
5682
+ return cursor.source_file_ref !== sourceRef || cursor.device !== file.device || cursor.inode !== file.inode || file.size < cursor.offset || !await anchorMatches(handle, cursor);
5683
+ }
5684
+ async function updateAnchor(handle, cursor) {
5685
+ const anchor_start = Math.max(0, cursor.offset - CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
5686
+ const anchor = Buffer.alloc(cursor.offset - anchor_start);
5687
+ if (anchor.length > 0) {
5688
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(anchor, 0, anchor.length, anchor_start));
5689
+ if (bytesRead !== anchor.length) throw new Error("Claude usage facts source changed during anchor read.");
5690
+ }
5691
+ return { ...cursor, anchor_start, anchor_sha256: sha2563(anchor) };
5692
+ }
5693
+ function rowTimestamp(value) {
5694
+ return timestamp3(value.timestamp);
5695
+ }
5696
+ function timestamp3(value) {
5697
+ if (!safeTimestamp(value)) throw new Error("Claude transcript timestamp is malformed.");
5698
+ return value;
5699
+ }
5700
+ function safeTimestamp(value) {
5701
+ return typeof value === "string" && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
5702
+ }
5703
+ function boundedText2(value, maximum) {
5704
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters2(value) ? value : null;
5705
+ }
5706
+ function hasControlCharacters2(value) {
5707
+ for (const character of value) {
5708
+ const code2 = character.codePointAt(0);
5709
+ if (code2 !== void 0 && (code2 < 32 || code2 === 127)) return true;
5710
+ }
5711
+ return false;
5712
+ }
5713
+ function safeCounter(value) {
5714
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
5715
+ }
5716
+ function optionalCounter(value, key) {
5717
+ if (!Object.hasOwn(value, key) || value[key] === null) return { value: null, invalid: false };
5718
+ const count = safeCounter(value[key]);
5719
+ return { value: count, invalid: count === null };
5720
+ }
5721
+ function isRecord4(value) {
5722
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5723
+ }
5724
+ function errorCode3(error) {
5725
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
5726
+ }
5727
+ function sha2563(value) {
5728
+ return createHash8("sha256").update(value).digest("hex");
5729
+ }
5730
+
5731
+ // host/claude/src/claude-adapter.ts
5732
+ import { createHash as createHash9, randomUUID } from "node:crypto";
5733
+ import { readdir as readdir4 } from "node:fs/promises";
5734
+ import { constants as constants6 } from "node:fs";
3648
5735
  import { homedir } from "node:os";
3649
- import { isAbsolute as isAbsolute2, join as join5, relative, resolve } from "node:path";
5736
+ import { isAbsolute as isAbsolute5, join as join8, relative, resolve } from "node:path";
3650
5737
 
3651
5738
  // host/claude/src/claude-runtime-paths.ts
3652
- import { join as join4 } from "node:path";
5739
+ import { join as join7 } from "node:path";
3653
5740
  var CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT = "CLAUDE_CONFIG_DIR";
3654
5741
  var CLAUDE_HOME_DEFAULT_DIRECTORY = ".claude";
3655
5742
  var CLAUDE_PROJECTS_DIRECTORY = "projects";
3656
5743
  function resolveClaudeConfigHome(environment, home) {
3657
- return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join4(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
5744
+ return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join7(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
3658
5745
  }
3659
5746
  function resolveClaudeProjectsRoot(environment, home) {
3660
- return join4(resolveClaudeConfigHome(environment, home), CLAUDE_PROJECTS_DIRECTORY);
5747
+ return join7(resolveClaudeConfigHome(environment, home), CLAUDE_PROJECTS_DIRECTORY);
3661
5748
  }
3662
5749
 
3663
5750
  // host/claude/src/claude-adapter.ts
@@ -3695,7 +5782,7 @@ var ClaudeHookAdapter = class {
3695
5782
  const defaultRoot = resolveClaudeProjectsRoot(process.env, homedir());
3696
5783
  const transcriptPath = sourceBoundTranscriptPath(input.transcript_path, this.transcriptsRoot ?? defaultRoot, this.platform);
3697
5784
  const hostSessionRef = claudeLocalSessionRef(input.session_id);
3698
- const observedAt = timestamp3(this.now);
5785
+ const observedAt = timestamp4(this.now);
3699
5786
  const expiresAt = new Date(Date.parse(observedAt) + CLAUDE_DEFAULT_RETENTION_MS).toISOString();
3700
5787
  const registration = {
3701
5788
  schema_version: "ceal.claude_transcript_registration.v1",
@@ -3726,7 +5813,7 @@ var ClaudeHookAdapter = class {
3726
5813
  async registerCurrentTurn(input) {
3727
5814
  const transcriptPath = sourceBoundTranscriptPath(input.transcript_path, this.transcriptsRoot ?? resolveClaudeProjectsRoot(process.env, homedir()), this.platform);
3728
5815
  const hostSessionRef = claudeLocalSessionRef(input.session_id);
3729
- const observedAt = timestamp3(this.now);
5816
+ const observedAt = timestamp4(this.now);
3730
5817
  const expiresAt = new Date(Date.parse(observedAt) + CLAUDE_DEFAULT_RETENTION_MS).toISOString();
3731
5818
  const registration = {
3732
5819
  schema_version: "ceal.claude_transcript_registration.v1",
@@ -3738,7 +5825,7 @@ var ClaudeHookAdapter = class {
3738
5825
  registered_at: observedAt,
3739
5826
  expires_at: expiresAt
3740
5827
  };
3741
- const promptRef = hostProducerPromptRef(createHash5("sha256").update(input.prompt, "utf8").digest("hex"));
5828
+ const promptRef = hostProducerPromptRef(createHash9("sha256").update(input.prompt, "utf8").digest("hex"));
3742
5829
  const turnGenerationRef = this.randomUuid();
3743
5830
  const selection = { schema_version: HOST_INVOCATION_TURN_SELECTION_SCHEMA, host_source_ref: this.optionsSourceRef, host_session_ref: hostSessionRef, prompt_ref: promptRef, turn_generation_ref: turnGenerationRef };
3744
5831
  const existing = (await this.store.listTranscriptRegistrations()).find((candidate) => candidate.host_source_ref === registration.host_source_ref && candidate.host_session_ref === registration.host_session_ref);
@@ -3755,11 +5842,11 @@ function sessionObservationValue(input) {
3755
5842
  return { status: "started", host_kind: "claude", source: input.source, model: input.model ?? "unavailable", decoder_evidence_version: "claude-code-2.1.258" };
3756
5843
  }
3757
5844
  function sourceBoundTranscriptPath(path, transcriptsRoot, platform = process.platform) {
3758
- if (!isAbsolute2(path) || !isAbsolute2(transcriptsRoot)) throw new ClaudeHostError("configuration", "Claude transcript registration paths must be absolute.");
5845
+ if (!isAbsolute5(path) || !isAbsolute5(transcriptsRoot)) throw new ClaudeHostError("configuration", "Claude transcript registration paths must be absolute.");
3759
5846
  const transcript = resolve(path);
3760
5847
  const root = resolve(transcriptsRoot);
3761
5848
  const child = relative(root, transcript);
3762
- if (child === "" || child === ".." || child.startsWith(`..${platform === "win32" ? "\\" : "/"}`) || isAbsolute2(child)) {
5849
+ if (child === "" || child === ".." || child.startsWith(`..${platform === "win32" ? "\\" : "/"}`) || isAbsolute5(child)) {
3763
5850
  throw new ClaudeHostError("invalid_input", "Claude transcript path is outside the configured transcripts root.");
3764
5851
  }
3765
5852
  return transcript;
@@ -3780,9 +5867,9 @@ async function refreshCurrentTurnCursor(store, registration, baseline, promptRef
3780
5867
  async function captureClaudeTranscriptBaseline(registration, now, currentPrompt, platform = process.platform, custody = {}) {
3781
5868
  let handle;
3782
5869
  try {
3783
- handle = await openNoFollow(registration.transcript_path, constants2.O_RDONLY, void 0, platform, custody);
5870
+ handle = await openNoFollow(registration.transcript_path, constants6.O_RDONLY, void 0, platform, custody);
3784
5871
  } catch (error) {
3785
- if (isNotFound(error)) return { cursor: initialCursor(registration, now) };
5872
+ if (isNotFound(error)) return { cursor: initialCursor2(registration, now) };
3786
5873
  throw error;
3787
5874
  }
3788
5875
  try {
@@ -3863,17 +5950,18 @@ async function makeClaudeBaselineCursor(handle, registration, now, file, offset,
3863
5950
  inode: file.inode,
3864
5951
  offset,
3865
5952
  anchor_start: anchorStart,
3866
- anchor_sha256: createHash5("sha256").update(anchor).digest("hex"),
5953
+ anchor_sha256: createHash9("sha256").update(anchor).digest("hex"),
5954
+ human_message_window: { messages: [], truncated: offset > 0 },
3867
5955
  subagents: await readClaudeSubagentBaseline(registration.transcript_path, platform, custody),
3868
5956
  status: "active",
3869
- updated_at: timestamp3(now)
5957
+ updated_at: timestamp4(now)
3870
5958
  };
3871
5959
  }
3872
5960
  async function readClaudeSubagentBaseline(transcriptPath, platform, custody) {
3873
5961
  const directory = subagentsDirectory(transcriptPath);
3874
5962
  let names;
3875
5963
  try {
3876
- names = (await readdir3(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
5964
+ names = (await readdir4(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
3877
5965
  } catch (error) {
3878
5966
  if (isNotFound(error)) return {};
3879
5967
  throw new ClaudeHostError("storage", "subagent_baseline_unavailable");
@@ -3891,7 +5979,7 @@ async function readClaudeSubagentBaseline(transcriptPath, platform, custody) {
3891
5979
  async function readClaudeSubagentSeed(directory, name, platform, custody) {
3892
5980
  let handle;
3893
5981
  try {
3894
- handle = await openNoFollow(join5(directory, name), constants2.O_RDONLY, void 0, platform, custody);
5982
+ handle = await openNoFollow(join8(directory, name), constants6.O_RDONLY, void 0, platform, custody);
3895
5983
  const stats = await handle.stat();
3896
5984
  if (!stats.isFile()) throw new ClaudeHostError("storage", "Claude subagent baseline source is not a regular file.");
3897
5985
  if (platform !== "win32" && !isSelfOwned(stats.uid, platform, handle)) throw new ClaudeHostError("storage", "Claude subagent baseline source is owned by another user.");
@@ -3900,7 +5988,7 @@ async function readClaudeSubagentSeed(directory, name, platform, custody) {
3900
5988
  inode: String(stats.ino),
3901
5989
  offset: stats.size,
3902
5990
  anchor_start: 0,
3903
- anchor_sha256: createHash5("sha256").update(Buffer.alloc(0)).digest("hex")
5991
+ anchor_sha256: createHash9("sha256").update(Buffer.alloc(0)).digest("hex")
3904
5992
  };
3905
5993
  } finally {
3906
5994
  await handle?.close();
@@ -3908,24 +5996,24 @@ async function readClaudeSubagentSeed(directory, name, platform, custody) {
3908
5996
  }
3909
5997
  function parseClaudeUserLine(line, sessionId) {
3910
5998
  const row = parseClaudeJsonObject(line);
3911
- if (row === null || row.type !== "user" || row.sessionId !== sessionId || typeof row.uuid !== "string" || row.uuid.length === 0 || !isRecord3(row.message)) return null;
5999
+ if (row === null || row.type !== "user" || row.sessionId !== sessionId || typeof row.uuid !== "string" || row.uuid.length === 0 || !isRecord5(row.message)) return null;
3912
6000
  return typeof row.message.content === "string" ? { uuid: row.uuid, content: row.message.content } : null;
3913
6001
  }
3914
6002
  function parseClaudeJsonObject(line) {
3915
6003
  try {
3916
6004
  const value = JSON.parse(line);
3917
- return isRecord3(value) ? value : null;
6005
+ return isRecord5(value) ? value : null;
3918
6006
  } catch {
3919
6007
  return null;
3920
6008
  }
3921
6009
  }
3922
- function isRecord3(value) {
6010
+ function isRecord5(value) {
3923
6011
  return value !== null && typeof value === "object" && !Array.isArray(value);
3924
6012
  }
3925
6013
  function isNotFound(error) {
3926
- return isRecord3(error) && error.code === "ENOENT";
6014
+ return isRecord5(error) && error.code === "ENOENT";
3927
6015
  }
3928
- function initialCursor(registration, now) {
6016
+ function initialCursor2(registration, now) {
3929
6017
  return {
3930
6018
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
3931
6019
  host_source_ref: registration.host_source_ref,
@@ -3933,13 +6021,13 @@ function initialCursor(registration, now) {
3933
6021
  transcript_path: registration.transcript_path,
3934
6022
  offset: 0,
3935
6023
  anchor_start: 0,
3936
- anchor_sha256: createHash5("sha256").update(Buffer.alloc(0)).digest("hex"),
6024
+ anchor_sha256: createHash9("sha256").update(Buffer.alloc(0)).digest("hex"),
3937
6025
  subagents: {},
3938
6026
  status: "active",
3939
- updated_at: timestamp3(now)
6027
+ updated_at: timestamp4(now)
3940
6028
  };
3941
6029
  }
3942
- function timestamp3(now) {
6030
+ function timestamp4(now) {
3943
6031
  const value = now();
3944
6032
  if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError("Claude Host clock is invalid.");
3945
6033
  return value.toISOString();
@@ -3967,48 +6055,6 @@ var ClaudeProducer = class {
3967
6055
  }
3968
6056
  };
3969
6057
 
3970
- // host/service-log.ts
3971
- import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
3972
- import { dirname as dirname3, isAbsolute as isAbsolute3, posix, win32 as win322 } from "node:path";
3973
- var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
3974
- function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
3975
- 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 } : {} })}
3976
- `;
3977
- try {
3978
- (sink ?? defaultHostServiceDiagnosticSink)(line);
3979
- } catch {
3980
- }
3981
- }
3982
- function defaultHostServiceDiagnosticSink(line) {
3983
- writeHostServiceLogLine(line);
3984
- process.stderr.write(line);
3985
- }
3986
- var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
3987
- function writeHostServiceLogLine(line, environment = process.env) {
3988
- if (process.platform !== "win32") return;
3989
- const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
3990
- if (path === void 0 || !win322.isAbsolute(path) || win322.normalize(path) !== path) return;
3991
- void appendHostServiceLogLine(path, line).catch(() => void 0);
3992
- }
3993
- async function appendHostServiceLogLine(path, line) {
3994
- if (!isAbsolute3(path)) return;
3995
- await ensureHostServiceLogDirectory(path);
3996
- await appendFile(path, line);
3997
- }
3998
- var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
3999
- var hostServiceLogDirectories = /* @__PURE__ */ new Map();
4000
- function ensureHostServiceLogDirectory(path) {
4001
- const directory = dirname3(path);
4002
- const existing = hostServiceLogDirectories.get(directory);
4003
- if (existing !== void 0) return existing;
4004
- const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
4005
- hostServiceLogDirectories.delete(directory);
4006
- throw error;
4007
- });
4008
- hostServiceLogDirectories.set(directory, pending);
4009
- return pending;
4010
- }
4011
-
4012
6058
  // host/claude/src/claude-producer-runtime.ts
4013
6059
  async function drainClaudeProducerOnce(options) {
4014
6060
  const scan = await new ClaudeTranscriptWatcher({
@@ -4024,45 +6070,11 @@ async function drainClaudeProducerOnce(options) {
4024
6070
 
4025
6071
  // host/claude/src/claude-hook-runner.ts
4026
6072
  import { homedir as homedir2 } from "node:os";
4027
- import { join as join6 } from "node:path";
6073
+ import { join as join9 } from "node:path";
4028
6074
 
4029
6075
  // host/producer-service.ts
4030
6076
  import { posix as posix4, win32 as win325 } from "node:path";
4031
-
4032
- // host/runtime-source-paths.ts
4033
- import { createHash as createHash6 } from "node:crypto";
4034
- import { posix as posix3, win32 as win324 } from "node:path";
4035
-
4036
- // host/absolute-path.ts
4037
- import { posix as posix2, win32 as win323 } from "node:path";
4038
- function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
4039
- const pathApi = flavor === "win32" || flavor === "windows" ? win323 : posix2;
4040
- return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
4041
- }
4042
-
4043
- // host/runtime-source-paths.ts
4044
- var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
4045
- function hostSourceUuid(sourceRef) {
4046
- return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
4047
- }
4048
- function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform) {
4049
- const sourceId = hostSourceUuid(sourceRef);
4050
- if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
4051
- const path = platform === "win32" ? win324 : posix3;
4052
- const sourcesRoot = path.join(stateRoot, "sources");
4053
- const sourceRoot = path.join(sourcesRoot, sourceId);
4054
- const runtimeRoot = path.join(stateRoot, "run");
4055
- const endpoint = platform === "win32" ? `\\\\.\\pipe\\ceal-host-${createHash6("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex").slice(0, 24)}` : path.join(runtimeRoot, `${sourceId}.sock`);
4056
- 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 };
4057
- }
4058
- function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
4059
- const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
4060
- 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.");
4061
- return paths.endpoint;
4062
- }
4063
-
4064
- // host/producer-service.ts
4065
- import { constants as constants3 } from "node:fs";
6077
+ import { constants as constants7 } from "node:fs";
4066
6078
  import { lstat as lstat3 } from "node:fs/promises";
4067
6079
  var SAFE_REF3 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
4068
6080
  var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
@@ -4088,7 +6100,8 @@ function parseHostProducerConfigFlag(args, platform = process.platform) {
4088
6100
  async function readHostProducerConfig(descriptor, configPath, platform = process.platform, custody = {}) {
4089
6101
  const config = decodeHostProducerConfigText(descriptor, await readProducerConfigText(configPath, platform, hostProducerError, custody), platform);
4090
6102
  const path = platform === "win32" ? win325 : posix4;
4091
- const root = path.resolve(config.outbox_dir, "../../../../..");
6103
+ const registrationStateFile = hostProducerRegistrationStateFile(config.outbox_dir, platform);
6104
+ const root = path.dirname(registrationStateFile);
4092
6105
  try {
4093
6106
  assertHostProducerSourcePaths(root, config, descriptor.producer_id, platform);
4094
6107
  } catch (error) {
@@ -4102,6 +6115,10 @@ function decodeHostProducerConfigText(descriptor, text, platform = process.platf
4102
6115
  const { extra_paths: extras, ...core } = decoded;
4103
6116
  return Object.freeze(descriptor.config({ schema_version: descriptor.schema, ...core }, extras));
4104
6117
  }
6118
+ function hostProducerRegistrationStateFile(outboxDirectory, platform = process.platform) {
6119
+ const path = platform === "win32" ? win325 : posix4;
6120
+ return path.join(path.resolve(outboxDirectory, "../../../../.."), "registration.json");
6121
+ }
4105
6122
  function hostProducerError(code2, message = code2) {
4106
6123
  return new HostProducerServiceError(code2, message);
4107
6124
  }
@@ -4147,7 +6164,7 @@ async function readProducerConfigText(configPath, platform, error, custody) {
4147
6164
  function decodeProducerConfigCore(text, options) {
4148
6165
  const ownership = producerConfigKeyOwnership(options.keys, options.platform);
4149
6166
  const value = parseCanonicalJson(text, options.error);
4150
- if (!isRecord4(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 })));
6167
+ if (!isRecord6(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 })));
4151
6168
  const hostSourceRef = typeof value.host_source_ref === "string" ? value.host_source_ref : "";
4152
6169
  const installationRef = typeof value.producer_installation_ref === "string" ? value.producer_installation_ref : "";
4153
6170
  const producerEpoch = validateIdentity3(hostSourceRef, installationRef, value.producer_epoch, options.error);
@@ -4199,7 +6216,7 @@ function validateConfigFile(value, platform, error, handle) {
4199
6216
  }
4200
6217
  async function openConfigFile(configPath, platform, error, custody) {
4201
6218
  try {
4202
- return await openNoFollow(configPath, constants3.O_RDONLY, void 0, platform, custody);
6219
+ return await openNoFollow(configPath, constants7.O_RDONLY, void 0, platform, custody);
4203
6220
  } catch (error_) {
4204
6221
  if (error_ instanceof SecureFileCustodyError) throw error(error_.reason === "not_private" ? "config_not_private" : "invalid_config");
4205
6222
  throw error("config_unavailable");
@@ -4240,7 +6257,7 @@ function firstDifferenceIndex(left, right) {
4240
6257
  return shared;
4241
6258
  }
4242
6259
  function producerShapeFacts(value, options) {
4243
- if (!isRecord4(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
6260
+ if (!isRecord6(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
4244
6261
  const tolerated = options.tolerated ?? [];
4245
6262
  const allowed = [...options.keys, ...tolerated, ...Object.keys(HOST_PRODUCER_TIMING_DEFAULTS)];
4246
6263
  const facts = [
@@ -4275,7 +6292,7 @@ function producerIntervalFacts(reconcile, retry, timeout) {
4275
6292
  function hasConfigKeys(value, required, tolerated = []) {
4276
6293
  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));
4277
6294
  }
4278
- function isRecord4(value) {
6295
+ function isRecord6(value) {
4279
6296
  return value !== null && typeof value === "object" && !Array.isArray(value);
4280
6297
  }
4281
6298
  function positive(value, maximum) {
@@ -4293,10 +6310,12 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
4293
6310
  producer_id: "claude",
4294
6311
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
4295
6312
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
4296
- runtime_options: (config) => Object.freeze({
4297
- outbox_dir: config.outbox_dir
4298
- }),
4299
- drain: drainClaudeProducerOnce
6313
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6314
+ drain: drainClaudeProducerOnce,
6315
+ background: (config, signal, dependencies) => {
6316
+ const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
6317
+ return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext(), fetch: dependencies.fetch }, signal);
6318
+ }
4300
6319
  };
4301
6320
 
4302
6321
  // host/claude/src/claude-hook-runner.ts
@@ -4332,15 +6351,15 @@ async function runClaudeHookCli() {
4332
6351
  return 0;
4333
6352
  }
4334
6353
  }
4335
- async function installedClaudeHookRunnerOptions(args) {
4336
- const config = await readHostProducerConfig(CLAUDE_PRODUCER_DESCRIPTOR, parseHostProducerConfigFlag(args));
6354
+ async function installedClaudeHookRunnerOptions(args, custody = {}) {
6355
+ const config = await readHostProducerConfig(CLAUDE_PRODUCER_DESCRIPTOR, parseHostProducerConfigFlag(args), process.platform, custody);
4337
6356
  const options = { outbox_dir: config.outbox_dir, claude_transcripts_root: config.claude_transcripts_root };
4338
6357
  Object.defineProperty(options, "host_source_ref", { value: config.host_source_ref, enumerable: false });
4339
6358
  return options;
4340
6359
  }
4341
6360
  function standaloneClaudeHookRunnerOptions(overrides) {
4342
6361
  const claudeHome = resolveClaudeConfigHome(process.env, homedir2());
4343
- return { outbox_dir: overrides?.outbox_dir ?? join6(claudeHome, ".ceal", "claude-observation-outbox"), claude_transcripts_root: resolveClaudeProjectsRoot(process.env, homedir2()) };
6362
+ return { outbox_dir: overrides?.outbox_dir ?? join9(claudeHome, ".ceal", "claude-observation-outbox"), claude_transcripts_root: resolveClaudeProjectsRoot(process.env, homedir2()) };
4344
6363
  }
4345
6364
  function hasHostConfigArgument(args) {
4346
6365
  return args.some((argument) => argument === HOST_PRODUCER_CONFIG_FLAG || argument.startsWith(`${HOST_PRODUCER_CONFIG_FLAG}=`));
@@ -4359,24 +6378,30 @@ async function readStdin(stdin) {
4359
6378
 
4360
6379
  // host/local-capability-descriptor.ts
4361
6380
  var HOST_LOCAL_CAPABILITY_AUTHENTICATION_SUFFIX = Object.freeze(["authenticate", "--client-nonce"]);
6381
+ var LOCAL_CAPABILITY_CUSTODY_REFUSALS = Object.freeze({
6382
+ not_private: "is not private to the current user.",
6383
+ reparse_point: "must not be a reparse point.",
6384
+ not_found: "custody could not be proved.",
6385
+ too_large: "custody could not be proved.",
6386
+ already_exists: "custody could not be proved.",
6387
+ unavailable: "custody could not be proved."
6388
+ });
4362
6389
 
4363
6390
  // host/client-doctor.ts
4364
6391
  import { execFile as execFile2 } from "node:child_process";
4365
6392
  import { promisify } from "node:util";
4366
6393
 
4367
- // host/invocation-authentication-client-command.ts
4368
- var DOCTOR_FLAGS = Object.freeze({
4369
- "--expected-sha256": "expected_sha256",
4370
- "--expected-source-commit": "expected_source_commit",
4371
- "--expected-instance-ref": "expected_instance_ref"
4372
- });
6394
+ // host/command-vector.ts
6395
+ var WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET = "A-Za-z0-9._=-";
6396
+ var WINDOWS_FIXED_CMD_ARGUMENT_REFUSAL_PATTERN = `[^${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]`;
6397
+ var WINDOWS_FIXED_CMD_ARGUMENT = new RegExp(`^[${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]+$`, "u");
4373
6398
 
4374
6399
  // host/client-doctor.ts
4375
6400
  var execFileAsync = promisify(execFile2);
4376
6401
 
4377
6402
  // host/claude/src/claude-installer.ts
4378
6403
  var ACTIVE_CLAUDE_HOOK_EVENTS = new Set(CLAUDE_HOOK_EVENTS);
4379
- var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: "CLAUDE_CODE_ENTRYPOINT", value: "cli" });
6404
+ var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: CLAUDE_SESSION_ID_ENVIRONMENT, value: Object.freeze({ environment: CLAUDE_SESSION_ID_ENVIRONMENT }) });
4380
6405
  var CLAUDE_CLIENT_ALLOW_RULE = `Bash(${CEAL_SESSION_ENTRY_INVOCATION}:*)`;
4381
6406
 
4382
6407
  // host/claude/bin/ceal-claude-hook.ts