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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,7 +33,8 @@ function isClaudeHookEvent(value) {
33
33
  }
34
34
 
35
35
  // host/claude/src/claude-decoder.ts
36
- import { createHash as createHash3 } from "node:crypto";
36
+ import { createHash as createHash4 } from "node:crypto";
37
+ import { isAbsolute } from "node:path";
37
38
 
38
39
  // packages/ceal-client-protocol/src/canonical-json.ts
39
40
  function cealCanonicalJson(value) {
@@ -63,7 +64,7 @@ function isPlainRecord(value) {
63
64
  }
64
65
 
65
66
  // packages/ceal-client-protocol/src/client-wire-contract.ts
66
- import { createHash } from "node:crypto";
67
+ import { createHash as createHash2 } from "node:crypto";
67
68
 
68
69
  // packages/ceal-client-protocol/client-wire-contract.json
69
70
  var client_wire_contract_default = {
@@ -84,7 +85,7 @@ var client_wire_contract_default = {
84
85
  ordering: "utf16_code_unit_ascending"
85
86
  },
86
87
  artifact_descriptor: {
87
- operation_contract_bundle_schema_name: "ceal.operation_contract_bundle",
88
+ operation_contract_bundle_schema_name: "ceal.operation_contract_bundle_v2",
88
89
  operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
89
90
  schema_name: "ceal.verified_artifact_descriptor",
90
91
  fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
@@ -109,7 +110,7 @@ var client_wire_contract_default = {
109
110
  },
110
111
  command_request: {
111
112
  schema_name: "ceal.command_request",
112
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
113
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
113
114
  absolute_transport_max_bytes: 65536
114
115
  },
115
116
  command_resolution: {
@@ -155,8 +156,9 @@ var client_wire_contract_default = {
155
156
  },
156
157
  command_response: {
157
158
  schema_name: "ceal.command_response",
158
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
159
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
159
160
  descriptor_field: "verified_artifact",
161
+ request_context_field: "request_context",
160
162
  required_fields: [
161
163
  "schema_version",
162
164
  "exit_code",
@@ -166,7 +168,8 @@ var client_wire_contract_default = {
166
168
  "operation_id",
167
169
  "visible_output_max_bytes",
168
170
  "local_delivery",
169
- "verified_artifact"
171
+ "verified_artifact",
172
+ "request_context"
170
173
  ],
171
174
  bare_document_fields: [
172
175
  "invocation",
@@ -187,7 +190,7 @@ var client_wire_contract_default = {
187
190
  ],
188
191
  exit_code_max: 125,
189
192
  bare_document_max_bytes: 65536,
190
- complete_max_bytes: 66046
193
+ complete_max_bytes: 66195
191
194
  },
192
195
  host_invocation_authentication: {
193
196
  request_schema_name: "ceal.host_invocation_authentication_request",
@@ -201,6 +204,14 @@ var client_wire_contract_default = {
201
204
  "context_token",
202
205
  "expires_at"
203
206
  ],
207
+ refusal_schema_name: "ceal.host_invocation_authentication_refusal",
208
+ refusal_fields: [
209
+ "schema_version",
210
+ "ok",
211
+ "code",
212
+ "reason",
213
+ "gateway_status"
214
+ ],
204
215
  client_nonce: {
205
216
  character_class_source: "A-Za-z0-9_-",
206
217
  encoded_characters: 43
@@ -239,6 +250,8 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
239
250
  "choose_new_output_path",
240
251
  "choose_new_idempotency_key",
241
252
  "restart_search",
253
+ // The requested temporal key is absent on some observed rows; repeating the same interval without `order` can return those rows.
254
+ "search_without_order",
242
255
  "repeat_original_arguments",
243
256
  // The occurrence this call addressed is settled and cannot move again -- a
244
257
  // denied effect approval, an expired continuation -- so the caller runs the
@@ -297,6 +310,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
297
310
  // The command needs caller-owned local materialization (for example an
298
311
  // @path file) before the Gateway can receive the argument.
299
312
  "materialize_local_argument",
313
+ // A missing or stale local Host bundle is repaired through its installed lifecycle and discovery owners.
314
+ "install_ceal_host",
315
+ // An explicit Client store override points at a missing file; unsetting it selects the one canonical default store without creating a second credential store.
316
+ "unset_context_store_path",
317
+ // The producer app must reload its installed Host hook before it can start a conversation with invocation context.
318
+ "restart_producer_app",
300
319
  // A peer's derived schema identifier changed with its field set; install or
301
320
  // upgrade the CLI and Host Relay to the Gateway's release before retrying.
302
321
  "upgrade_ceal_client"
@@ -405,7 +424,6 @@ var NON_MODEL_ACTION_TO_MODEL_ACTION = Object.freeze({
405
424
  });
406
425
  var RETRY_PROMISE_NEXT_ACTIONS = ["retry", "retry_after"];
407
426
  var RETRY_PROMISE = new Set(RETRY_PROMISE_NEXT_ACTIONS);
408
- var RECOVERABLE = new Set(CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS);
409
427
  var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
410
428
  provider_permission: "ask_admin",
411
429
  access_level: "ask_admin",
@@ -427,9 +445,9 @@ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "s
427
445
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
428
446
  var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
429
447
  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"]);
448
+ var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
431
449
  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"]);
450
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
433
451
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
434
452
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
435
453
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -500,10 +518,10 @@ function assertSafeJsonArray(value, options, depth, count) {
500
518
  if (value.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
501
519
  for (const item of value) assertSafeJsonValue(item, options, depth + 1, count);
502
520
  }
503
- function assertSafeJsonRecord(record4, options, depth, count) {
504
- const entries = Object.entries(record4);
521
+ function assertSafeJsonRecord(record5, options, depth, count) {
522
+ const entries = Object.entries(record5);
505
523
  if (entries.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
506
- const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record4.fields) : null;
524
+ const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record5.fields) : null;
507
525
  for (const [key, child] of entries) {
508
526
  if (key === "credential_material_included" && child !== false) invalidByContext(options);
509
527
  if (!isSafeNegativeMaterialAssertion(key, child)) assertSafeJsonKey(key, options);
@@ -553,16 +571,21 @@ function isSafeExternalHttpsUrl(value) {
553
571
  return false;
554
572
  }
555
573
  }
574
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE = "^https://[^\\s/@?#]+(?:[/?#][^\\s]*)?$";
575
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN = new RegExp(SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE, "u");
556
576
  function isSafeExternalHttpsUrlInput(value) {
557
577
  return typeof value === "string" && byteLength(value) <= 2048;
558
578
  }
559
- function isSafeExternalHttpsUrlShape(url) {
560
- return url.protocol === "https:" && url.username === "" && url.password === "" && url.hash === "";
579
+ function isSafeExternalHttpsUrlShape(url, allowFragment = false) {
580
+ return url.protocol === "https:" && url.hostname.length > 0 && url.username === "" && url.password === "" && (allowFragment || url.hash === "");
561
581
  }
562
582
  function isSafeResultContent(value, key) {
563
583
  const maximum = key === "text" ? 8192 : 1024;
564
584
  return typeof value === "string" && byteLength(value) <= maximum && firstDisallowedControl(value, "multi_line") === null;
565
585
  }
586
+ function requireSafeRef(value) {
587
+ if (typeof value !== "string" || !SAFE_REF.test(value)) invalidRequestOrResponse();
588
+ }
566
589
  var CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES = 512;
567
590
  function normalizeCealSingleLineText(value) {
568
591
  return value.split("").map((character) => hasControlCharacter(character) ? " " : character).join("").trim();
@@ -674,6 +697,7 @@ function cut(text) {
674
697
 
675
698
  // packages/ceal-client-protocol/src/operation-validation-primitives.ts
676
699
  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;
700
+ var EXPANDED_CANONICAL_ISO_TIMESTAMP = /^([+-])(\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/u;
677
701
  var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
678
702
  var CEAL_CALENDAR_DATE = new RegExp(CEAL_CALENDAR_DATE_PATTERN_SOURCE, "u");
679
703
  function isOperationRecord(value) {
@@ -684,13 +708,46 @@ function isOperationRecord(value) {
684
708
  function requireOperationRecord(value, message) {
685
709
  if (!isOperationRecord(value)) throw new TypeError(message);
686
710
  }
711
+ function requireExactOperationKeys(value, required, optional = [], message = "Operation contract has an invalid shape.") {
712
+ const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
713
+ if (required.some((key) => !Object.hasOwn(value, key))) throw new TypeError(message);
714
+ if (Object.keys(value).some((key) => !allowed.has(key))) throw new TypeError(message);
715
+ }
687
716
  function requireClosedValue(value, members, message) {
688
717
  if (typeof value !== "string" || !members.includes(value)) throw new TypeError(message);
689
718
  }
690
719
  function isCealIsoTimestamp(value) {
691
720
  return typeof value === "string" && parseCealIsoTimestamp(value) !== null;
692
721
  }
722
+ function canonicalCealIsoTimestamp(epochNanoseconds) {
723
+ const wholeSeconds = floorDivide(epochNanoseconds, 1000000000n);
724
+ const fractionalNanoseconds = epochNanoseconds - wholeSeconds * 1000000000n;
725
+ const utc = new Date(Number(wholeSeconds * 1000n));
726
+ const date = utc.toISOString().split(".")[0];
727
+ if (date === void 0) throw new TypeError("Ceal timestamp formatter returned an invalid ISO string");
728
+ const fraction = fractionalNanoseconds.toString().padStart(9, "0").replace(/0+$/u, "").padEnd(3, "0");
729
+ return date + "." + fraction + "Z";
730
+ }
731
+ var CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE = "0000-01-01T00:00:00.000000000+23:59";
732
+ var CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE = "9999-12-31T23:59:59.999999999-23:59";
733
+ var CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE);
734
+ var CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE);
735
+ var CEAL_INSTANT_INDEX_SPAN = CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS - CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS;
736
+ var CEAL_INSTANT_INDEX_KEY_WIDTH = CEAL_INSTANT_INDEX_SPAN.toString().length;
737
+ var CEAL_INSTANT_INDEX_KEY_PATTERN = new RegExp(`^\\d{${CEAL_INSTANT_INDEX_KEY_WIDTH}}$`, "u");
738
+ function requiredTimestampEpochNanoseconds(value) {
739
+ const parsed = parseFourDigitCealIsoTimestamp(value);
740
+ if (parsed === null) throw new Error("Ceal instant-index range basis is outside the timestamp grammar");
741
+ return parsed.epochNanoseconds;
742
+ }
693
743
  function parseCealIsoTimestamp(value) {
744
+ const ordinary = parseFourDigitCealIsoTimestamp(value);
745
+ if (ordinary !== null) return ordinary;
746
+ const expanded = parseExpandedCanonicalCealIsoTimestamp(value);
747
+ if (expanded === null || expanded.epochNanoseconds < CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS || expanded.epochNanoseconds > CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS) return null;
748
+ return canonicalCealIsoTimestamp(expanded.epochNanoseconds) === value ? expanded : null;
749
+ }
750
+ function parseFourDigitCealIsoTimestamp(value) {
694
751
  const fields = parseCealIsoTimestampFields(value);
695
752
  if (fields === null || !validCalendarDate(fields) || !validClockTime(fields) || !validUtcOffset(fields)) return null;
696
753
  const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
@@ -699,6 +756,28 @@ function parseCealIsoTimestamp(value) {
699
756
  epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
700
757
  };
701
758
  }
759
+ function parseExpandedCanonicalCealIsoTimestamp(value) {
760
+ const match = EXPANDED_CANONICAL_ISO_TIMESTAMP.exec(value);
761
+ if (match === null) return null;
762
+ const fields = {
763
+ year: (match[1] === "-" ? -1 : 1) * Number(match[2]),
764
+ month: Number(match[3]),
765
+ day: Number(match[4]),
766
+ hour: Number(match[5]),
767
+ minute: Number(match[6]),
768
+ second: Number(match[7]),
769
+ fraction: match[8] ?? "",
770
+ offsetSign: 0,
771
+ offsetHour: 0,
772
+ offsetMinute: 0
773
+ };
774
+ if (!validCalendarDate(fields) || !validClockTime(fields)) return null;
775
+ const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
776
+ if (!Number.isFinite(epochMilliseconds)) return null;
777
+ return {
778
+ epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
779
+ };
780
+ }
702
781
  function parseCealIsoTimestampFields(value) {
703
782
  const match = ISO_TIMESTAMP.exec(value);
704
783
  if (match === null) return null;
@@ -731,6 +810,10 @@ function cealFieldsEpochMilliseconds(fields) {
731
810
  const offsetMilliseconds = fields.offsetSign * (fields.offsetHour * 60 + fields.offsetMinute) * 6e4;
732
811
  return localMilliseconds - offsetMilliseconds;
733
812
  }
813
+ function floorDivide(value, divisor) {
814
+ const quotient = value / divisor;
815
+ return value % divisor < 0n ? quotient - 1n : quotient;
816
+ }
734
817
  function daysInMonth(year, month) {
735
818
  const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
736
819
  return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
@@ -748,6 +831,9 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
748
831
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
749
832
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
750
833
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
834
+ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
835
+ 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.";
836
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select or activate the current recorded turn. This does not explain why or prove ephemerality. For an independently identified ephemeral Codex side conversation, invoke the command as `ceal --standalone ...`; it uses the local Ceal session and Gateway permissions without Host session/turn audit linkage. Host refusal never switches modes. For intended Host calls, restart the producer and start a new conversation; report the error if it persists.";
751
837
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
752
838
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
753
839
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
@@ -773,6 +859,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
773
859
  refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
774
860
  refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
775
861
  refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
862
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
863
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
776
864
  refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
777
865
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
778
866
  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 +873,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
785
873
  response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
786
874
  request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
787
875
  request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
876
+ resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
788
877
  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),
878
+ contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
790
879
  // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
791
880
  // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
792
881
  // when the wait ends still unserved, moved from the `localFailureText` default branch.
@@ -798,6 +887,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
798
887
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
799
888
  // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
800
889
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
890
+ gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
801
891
  // Restored verbatim from the retired `localFailureText` `unknown_outcome`
802
892
  // case: the outcome is unknown, so a read may be retried while a write
803
893
  // must receipt-check first. Collapsing both to "do not repeat the call"
@@ -883,23 +973,24 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
883
973
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
884
974
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
885
975
  // 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
976
+ // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). Cause-specific
977
+ // sentences carry the retired policy remedies; `gateway_refused` reuses the release-upgrade guidance above.
978
+ // Statuses are the
888
979
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
889
980
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
890
981
  host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
891
982
  host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
892
983
  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),
984
+ // The bounded Host reason does not prove ephemerality. A Host refusal never
985
+ // changes mode; standalone remains the separate Client authority path.
986
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
896
987
  host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
897
988
  host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
898
989
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
899
990
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
900
991
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
901
992
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
902
- host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
993
+ host_mint_gateway_refused: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
903
994
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
904
995
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
905
996
  // producer-frame fault names the administrator repair step.
@@ -907,59 +998,16 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
907
998
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
908
999
  // sandboxed Relay socket names the run-alone retry.
909
1000
  host_relay_permission_denied: guidance("An agent sandbox denied the Host Relay socket; run `ceal` as the only command, with no pipe, redirect, or `&&`, so the Host allow rule runs it outside the sandbox.", "rerun_outside_agent_sandbox", 403),
910
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1001
+ host_relay_unavailable: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 503),
911
1002
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
912
1003
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
913
- host_relay_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1004
+ host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
914
1005
  host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
915
1006
  });
916
1007
  var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
917
1008
 
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]);
1009
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1010
+ import { createHash } from "node:crypto";
963
1011
 
964
1012
  // packages/ceal-client-protocol/src/operation-withheld-cause.ts
965
1013
  var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
@@ -1005,13 +1053,160 @@ var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
1005
1053
  "interactive_unavailable"
1006
1054
  ]);
1007
1055
 
1056
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1057
+ var DIGEST = /^[a-f0-9]{64}$/u;
1058
+ var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1059
+ function isCealDigest(value) {
1060
+ return typeof value === "string" && DIGEST.test(value);
1061
+ }
1062
+ function cealRequestSha256(value) {
1063
+ return createHash("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1064
+ }
1065
+ function operationRecord(value, message) {
1066
+ requireOperationRecord(value, message);
1067
+ return value;
1068
+ }
1069
+ function invalid(message) {
1070
+ throw new TypeError(message);
1071
+ }
1072
+ function requirePrefixedRef(value, prefix, message) {
1073
+ if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1074
+ }
1075
+ function requireSafeRef2(value, message) {
1076
+ try {
1077
+ requireSafeRef(value);
1078
+ } catch {
1079
+ invalid(message);
1080
+ }
1081
+ }
1082
+
1083
+ // packages/ceal-client-protocol/src/request-authority.ts
1084
+ var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1085
+ var CEAL_REQUEST_REF_MAX_CHARACTERS = 128;
1086
+ var CEAL_REQUEST_REF_PATTERN_SOURCE = "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$";
1087
+ var CEAL_REQUEST_REF_PATTERN = new RegExp(CEAL_REQUEST_REF_PATTERN_SOURCE, "u");
1088
+ var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1089
+ var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1090
+ var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1091
+ var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1092
+ var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1093
+ var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1094
+ schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1095
+ ceal_request_ref: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_REF_MAX_CHARACTERS, pattern: CEAL_REQUEST_REF_PATTERN_SOURCE },
1096
+ created_at: { type: "string", minLength: 1, maxLength: 64 },
1097
+ authority: {
1098
+ type: "object",
1099
+ maxProperties: 5,
1100
+ additionalProperties: false,
1101
+ properties: {
1102
+ instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1103
+ access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1104
+ principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1105
+ execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1106
+ authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1107
+ },
1108
+ required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1109
+ }
1110
+ });
1111
+ var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1112
+ prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1113
+ host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1114
+ host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1115
+ 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." },
1116
+ host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1117
+ host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1118
+ });
1119
+ var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1120
+ 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." },
1121
+ 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." }
1122
+ });
1123
+ var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1124
+ requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1125
+ 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." }
1126
+ });
1127
+ var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1128
+ var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1129
+ var CEAL_REQUEST_JSON_SCHEMA = {
1130
+ type: "object",
1131
+ 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.",
1132
+ maxProperties: 14,
1133
+ additionalProperties: false,
1134
+ properties: {
1135
+ ...CEAL_REQUEST_COMMON_PROPERTIES,
1136
+ ...CEAL_REQUEST_HOST_PROPERTIES,
1137
+ ...CEAL_REQUEST_CALLER_PROPERTIES,
1138
+ ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1139
+ },
1140
+ required: CEAL_REQUEST_KEYS,
1141
+ anyOf: [
1142
+ {
1143
+ type: "object",
1144
+ required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1145
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1146
+ additionalProperties: false
1147
+ },
1148
+ {
1149
+ type: "object",
1150
+ required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1151
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1152
+ additionalProperties: false
1153
+ }
1154
+ ]
1155
+ };
1156
+
1157
+ // packages/ceal-client-protocol/src/client-wire-contract.ts
1158
+ var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
1159
+ var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
1160
+ var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
1161
+ var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
1162
+ var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
1163
+ var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
1164
+ function deriveCealClientWireSchemaVersion(schema) {
1165
+ 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))) {
1166
+ throw new TypeError("Client wire schema name or field set is invalid.");
1167
+ }
1168
+ const fields = schema.fields.filter((field) => field !== "schema_version").sort();
1169
+ const hash8 = createHash2("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
1170
+ return `${schema.schema_name}.v1.${hash8}`;
1171
+ }
1172
+ var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
1173
+ var commandResolutionAuthority = commandResolution.authority;
1174
+ var commandResolutionSemanticOptions = commandResolution.semantic_options;
1175
+ var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
1176
+ var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
1177
+ var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
1178
+ var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
1179
+ var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
1180
+ var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
1181
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
1182
+ var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
1183
+ var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
1184
+ var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
1185
+ var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
1186
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
1187
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
1188
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
1189
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
1190
+ var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
1191
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
1192
+ var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
1193
+ var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
1194
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
1195
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
1196
+ var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
1197
+ var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
1198
+ 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 });
1199
+ var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
1200
+
1201
+ // packages/ceal-client-protocol/src/access-level-vocabulary.ts
1202
+ var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1203
+
1008
1204
  // packages/ceal-client-protocol/src/operation-access-class.ts
1009
1205
  var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
1010
1206
 
1011
1207
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
1012
1208
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
1013
1209
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
1014
- var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1015
1210
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
1016
1211
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
1017
1212
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1119,6 +1314,7 @@ var CEAL_SCHEMA_LITERALS = [
1119
1314
  "ceal.gateway_write_receipt_readback.v1",
1120
1315
  "ceal.gateway_write_request_receipt.v1",
1121
1316
  "ceal.host_observation.v1",
1317
+ "ceal.host_usage_batch.v1",
1122
1318
  "ceal.host_registration_request.v1",
1123
1319
  "ceal.host_registration_result.v1",
1124
1320
  CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
@@ -1147,7 +1343,6 @@ var CEAL_SCHEMA_LITERAL_SET = new Set(CEAL_SCHEMA_LITERALS);
1147
1343
  import { join } from "node:path";
1148
1344
  var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1149
1345
  bounded_store_sidecar: (root) => `${root}.jsonl`,
1150
- gateway_audit_archive: (root) => `${root}.jsonl`,
1151
1346
  gateway_access_group_connector_control_audit: (root) => `${root}.audit.jsonl`,
1152
1347
  gateway_access_group_connector_scope_audit: (root) => join(root, "profile-connector-scope-audit.jsonl"),
1153
1348
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
@@ -1177,6 +1372,7 @@ var CEAL_LOWERCASE_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
1177
1372
  var CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN = new RegExp(`^host-registration-attempt:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1178
1373
  var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1179
1374
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1375
+ var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1180
1376
 
1181
1377
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
1182
1378
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
@@ -1195,7 +1391,7 @@ function shellSingleQuoted(value) {
1195
1391
  return `'${value.replaceAll("'", "'\\''")}'`;
1196
1392
  }
1197
1393
  var CEAL_OPERATION_CONTRACT_REQUIRED_FIELDS = Object.freeze(["input_schema", "result_schema"]);
1198
- var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["summary", "input_resolution"]);
1394
+ var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["branches", "summary", "input_resolution"]);
1199
1395
  var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
1200
1396
  $schema: CEAL_JSON_SCHEMA_2020_12,
1201
1397
  $id: "https://ceal.dev/schemas/verified-artifact-descriptor.v1.schema.json",
@@ -1240,11 +1436,92 @@ var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_o
1240
1436
  // packages/ceal-client-protocol/src/actor-kind.ts
1241
1437
  var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
1242
1438
 
1439
+ // packages/ceal-client-protocol/src/provider-link-policy.ts
1440
+ var PROVIDER_LINK_RESULT_FIELDS = Object.freeze({
1441
+ read_row: Object.freeze({ human_link: "source_url", parent_context: Object.freeze(["thread_ref"]) }),
1442
+ write_result: Object.freeze({ human_links: Object.freeze(["user_openable_url", "url", "spreadsheet_url", "meet_url"]) })
1443
+ });
1444
+ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1445
+ { 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/" },
1446
+ { 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/" },
1447
+ { 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/" },
1448
+ { 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/" },
1449
+ { 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/" },
1450
+ { 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" },
1451
+ { 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" },
1452
+ { 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" },
1453
+ { 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" },
1454
+ { 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" },
1455
+ { 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" },
1456
+ { 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" },
1457
+ { 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" },
1458
+ { 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" },
1459
+ { 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" },
1460
+ { 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" },
1461
+ { 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" },
1462
+ { 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" },
1463
+ { 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" },
1464
+ { 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" }
1465
+ ]);
1466
+ var PROVIDER_LINK_HOSTS = Object.freeze({
1467
+ notion: Object.freeze(["notion.so", "www.notion.so", "notion.com", "www.notion.com", "app.notion.com"]),
1468
+ google_workspace: Object.freeze([
1469
+ "calendar.google.com",
1470
+ "contacts.google.com",
1471
+ "docs.google.com",
1472
+ "drive.google.com",
1473
+ "forms.google.com",
1474
+ "mail.google.com",
1475
+ "meet.google.com",
1476
+ "sites.google.com",
1477
+ "www.google.com"
1478
+ ])
1479
+ });
1480
+ var NOTION_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.notion);
1481
+ var GOOGLE_WORKSPACE_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.google_workspace);
1482
+ var PROVIDER_RESOURCE_SOURCE_URL_SCHEMA = Object.freeze({
1483
+ type: "string",
1484
+ minLength: 1,
1485
+ maxLength: 2048,
1486
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1487
+ 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."
1488
+ });
1489
+ var PROVIDER_USER_OPENABLE_URL_SCHEMA = Object.freeze({
1490
+ type: "string",
1491
+ minLength: 1,
1492
+ maxLength: 2048,
1493
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1494
+ 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."
1495
+ });
1496
+
1243
1497
  // packages/ceal-client-protocol/src/resource-row.ts
1244
1498
  var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
1245
1499
  var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
1246
1500
  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"]);
1501
+ var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
1502
+ "query",
1503
+ "modified_since",
1504
+ "since",
1505
+ "until",
1506
+ "filetype",
1507
+ "authored_by_me",
1508
+ "authored_by",
1509
+ "edited_by",
1510
+ "include_replies",
1511
+ "kinds",
1512
+ "container_ref",
1513
+ "container_refs",
1514
+ "container_names",
1515
+ "addressed_to_me",
1516
+ "unread",
1517
+ "archived",
1518
+ "state",
1519
+ "event_types",
1520
+ "starred",
1521
+ "trashed",
1522
+ "permission"
1523
+ ]);
1524
+ var CEAL_RESOURCE_SEARCH_STATES = vocabulary(["open", "closed", "draft", "prerelease", "confirmed", "tentative", "cancelled"]);
1248
1525
  var CEAL_RESOURCE_TIME_BASES = vocabulary(["created", "modified", "viewed"]);
1249
1526
  var CEAL_REPOSITORY_VISIBILITIES = vocabulary(["public", "private", "internal"]);
1250
1527
  var CEAL_ACTIVITY_V3_KINDS = vocabulary(["authored", "edited", "messaged", "responded"]);
@@ -1340,6 +1617,8 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1340
1617
  container_label: { required: true, timestamp: false },
1341
1618
  container_ref: { required: false, timestamp: false },
1342
1619
  source_url: { required: false, timestamp: false },
1620
+ thread_ref: { required: false, timestamp: false },
1621
+ reply_count: { required: false, timestamp: false },
1343
1622
  source: { required: true, timestamp: false },
1344
1623
  owner: { required: false, timestamp: false },
1345
1624
  actor_kind: { required: false, timestamp: false },
@@ -1365,6 +1644,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1365
1644
  start: { required: false, timestamp: false },
1366
1645
  end: { required: false, timestamp: false },
1367
1646
  status: { required: false, timestamp: false },
1647
+ event_type: { required: false, timestamp: false },
1368
1648
  snippet: { required: false, timestamp: false },
1369
1649
  dated_notes: { required: false, timestamp: false },
1370
1650
  state: { required: true, timestamp: false },
@@ -1428,6 +1708,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1428
1708
  "refresh_inactive",
1429
1709
  "refresh_replayed",
1430
1710
  "refresh_revoked",
1711
+ "person_inactive",
1712
+ "principal_inactive",
1431
1713
  "authority_replaced",
1432
1714
  "refresh_recovery_unavailable",
1433
1715
  "refresh_recovery_expired",
@@ -1448,116 +1730,25 @@ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
1448
1730
  var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1449
1731
  var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1450
1732
 
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
- // packages/ceal-client-protocol/src/request-operands.ts
1543
- var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1544
- var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
1545
- var CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH = 1024;
1546
- var CEAL_REQUEST_RESOLVER_SELECTION_JSON_SCHEMA = {
1547
- type: "object",
1548
- maxProperties: 2,
1549
- additionalProperties: false,
1550
- properties: {
1551
- property: { type: "string", minLength: 1, maxLength: 128 },
1552
- selectors: {
1553
- type: "object",
1554
- maxProperties: CEAL_REQUEST_MAX_SELECTOR_PROPERTIES,
1555
- properties: {},
1556
- additionalProperties: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH }
1557
- }
1558
- },
1559
- required: ["property", "selectors"]
1560
- };
1733
+ // packages/ceal-client-protocol/src/request-operands.ts
1734
+ var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1735
+ var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
1736
+ var CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH = 1024;
1737
+ var CEAL_REQUEST_RESOLVER_SELECTION_JSON_SCHEMA = {
1738
+ type: "object",
1739
+ maxProperties: 2,
1740
+ additionalProperties: false,
1741
+ properties: {
1742
+ property: { type: "string", minLength: 1, maxLength: 128 },
1743
+ selectors: {
1744
+ type: "object",
1745
+ maxProperties: CEAL_REQUEST_MAX_SELECTOR_PROPERTIES,
1746
+ properties: {},
1747
+ additionalProperties: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH }
1748
+ }
1749
+ },
1750
+ required: ["property", "selectors"]
1751
+ };
1561
1752
 
1562
1753
  // packages/ceal-client-protocol/src/request-graph.ts
1563
1754
  var CEAL_REQUEST_MAX_GRAPH_NODES = 128;
@@ -1646,6 +1837,27 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
1646
1837
  required: ["schema_version", "order", "nodes", "call_budget"]
1647
1838
  };
1648
1839
 
1840
+ // packages/ceal-client-protocol/src/host-observation-validation.ts
1841
+ var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1842
+ 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;
1843
+ function validateCealHostObservationValue(value) {
1844
+ if (value === void 0) throw new TypeError("Ceal Host observation value is invalid.");
1845
+ assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1846
+ if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) throw new TypeError("Ceal Host observation value is oversized.");
1847
+ inspectHostKeys(value);
1848
+ }
1849
+ function inspectHostKeys(value) {
1850
+ if (Array.isArray(value)) {
1851
+ for (const entry of value) inspectHostKeys(entry);
1852
+ return;
1853
+ }
1854
+ if (value === null || typeof value !== "object") return;
1855
+ for (const [key, child] of Object.entries(value)) {
1856
+ if (HOST_RESERVED_KEY.test(key)) throw new TypeError("Ceal Host observation cannot restate Gateway-owned facts.");
1857
+ inspectHostKeys(child);
1858
+ }
1859
+ }
1860
+
1649
1861
  // packages/ceal-client-protocol/src/host-observation.ts
1650
1862
  var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
1651
1863
  var HOST_OBSERVATION_PRODUCER = /^[a-z][a-z0-9]{0,31}$/u;
@@ -1692,35 +1904,238 @@ function safeCount(value) {
1692
1904
  return Number.isSafeInteger(value) && Number(value) >= 0;
1693
1905
  }
1694
1906
  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);
1907
+ const record5 = operationRecord(value, "Ceal Host observation draft is invalid.");
1908
+ requirePrefixedRef(record5.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1909
+ requireClosedValue(record5.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1910
+ requireIsoTimestamp(record5.observed_at, "Ceal Host observation time is invalid.");
1911
+ assertHostObservationValue(record5.value, record5.observation_kind);
1700
1912
  }
1701
- var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1702
1913
  var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
1703
1914
  function isCealHostPromptObservationValue(value) {
1704
1915
  return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
1705
1916
  }
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
1917
  function assertHostObservationValue(value, kind) {
1708
1918
  if (value === void 0) invalid("Ceal Host observation value is invalid.");
1709
1919
  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);
1920
+ validateCealHostObservationValue(value);
1713
1921
  }
1714
- function inspectHostKeys(value) {
1715
- if (Array.isArray(value)) {
1716
- for (const entry of value) inspectHostKeys(entry);
1922
+
1923
+ // packages/ceal-client-protocol/src/host-usage-facts.ts
1924
+ import { createHash as createHash3 } from "node:crypto";
1925
+ var CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION = "ceal.host_usage_batch.v1";
1926
+ var CEAL_HOST_USAGE_BATCH_REF_PREFIX = "host-usage-batch:";
1927
+ var CEAL_HOST_USAGE_INGRESS_PATH = "/api/ceal/v2/host-usage-batches";
1928
+ var CEAL_HOST_USAGE_BATCH_MAX_BYTES = 1024 * 1024;
1929
+ var CEAL_HOST_USAGE_FACT_MAX_BYTES = 64 * 1024;
1930
+ var CEAL_HOST_USAGE_BATCH_MAX_FACTS = 256;
1931
+ var CEAL_HOST_USAGE_BATCH_MAX_GAPS = 16;
1932
+ var CEAL_HOST_USAGE_BATCH_ACK_STATUS = 204;
1933
+ var CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES = 65;
1934
+ var CODEX_COUNTER_SEMANTICS = ["last_delta_total_cumulative", "total_cumulative_only", "unknown"];
1935
+ var CODEX_CUMULATIVE_TRANSITIONS = ["baseline", "advanced", "same", "reset_or_correction", "not_observed"];
1936
+ var HOST_USAGE_COVERAGE_GAP_REASONS = ["source_usage_unavailable", "source_file_replaced", "source_file_retired", "outbox_capacity", "unsupported_source_shape"];
1937
+ function createCealHostUsageBatch(input) {
1938
+ const body = { schema_version: CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION, ...input };
1939
+ const batch = { ...body, batch_ref: `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}` };
1940
+ validateCealHostUsageBatch(batch);
1941
+ return batch;
1942
+ }
1943
+ function validateCealHostUsageBatch(value) {
1944
+ if (!isOperationRecord(value)) invalid("Ceal Host usage batch is invalid.");
1945
+ requireExactOperationKeys(value, ["schema_version", "batch_ref", "host_source_ref", "host_session_ref", "created_at", "source_ranges", "facts", "coverage_gaps"]);
1946
+ 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.");
1947
+ const { batch_ref: _ref, ...body } = value;
1948
+ if (value.batch_ref !== `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}`) invalid("Ceal Host usage batch reference is invalid.");
1949
+ validateBatchMetadata(value);
1950
+ validateBatchContents(value);
1951
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_BATCH_MAX_BYTES) invalid("Ceal Host usage batch exceeds its byte limit.");
1952
+ }
1953
+ function validateBatchMetadata(value) {
1954
+ requireSafeRef2(value.host_source_ref, "Ceal Host usage source is invalid.");
1955
+ requireSafeRef2(value.host_session_ref, "Ceal Host usage session is invalid.");
1956
+ requireIsoTimestamp(value.created_at, "Ceal Host usage batch time is invalid.");
1957
+ 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.");
1958
+ for (const range of value.source_ranges) validateSourceRange(range);
1959
+ }
1960
+ function validateBatchContents(value) {
1961
+ const facts = validateBatchFacts(value.facts);
1962
+ const gaps = validateBatchGaps(value.coverage_gaps);
1963
+ if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
1964
+ const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
1965
+ for (const fact of facts) {
1966
+ validateFact(fact, value.host_session_ref);
1967
+ if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
1968
+ }
1969
+ for (const gap of gaps) {
1970
+ validateCoverageGap(gap);
1971
+ if (gap.source_file_ref !== null && !sourceFiles.has(gap.source_file_ref)) invalid("Ceal Host usage coverage gap is outside its source ranges.");
1972
+ }
1973
+ }
1974
+ function validateBatchFacts(value) {
1975
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_FACTS) invalid("Ceal Host usage fact count is invalid.");
1976
+ return value;
1977
+ }
1978
+ function validateBatchGaps(value) {
1979
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) invalid("Ceal Host usage coverage is invalid.");
1980
+ return value;
1981
+ }
1982
+ function sourceRangeFileRef(value) {
1983
+ return isOperationRecord(value) ? value.source_file_ref : null;
1984
+ }
1985
+ function hostUsageFactReference(sourceFileRef2, sourceEventRef) {
1986
+ requireSafeRef2(sourceFileRef2, "Ceal Host usage file reference is invalid.");
1987
+ requireSafeRef2(sourceEventRef, "Ceal Host usage event reference is invalid.");
1988
+ return `host-usage-fact:${sha256(JSON.stringify({ source_file_ref: sourceFileRef2, source_event_ref: sourceEventRef }))}`;
1989
+ }
1990
+ function hostUsageSourceEventReference(sourceFileRef2, sourceEventIdentity) {
1991
+ requireSafeRef2(sourceFileRef2, "Ceal Host usage file reference is invalid.");
1992
+ if (typeof sourceEventIdentity !== "string" || sourceEventIdentity.length === 0 || sourceEventIdentity.length > 1024) invalid("Ceal Host usage event identity is invalid.");
1993
+ return `host-source-event:${sha256(JSON.stringify({ source_file_ref: sourceFileRef2, source_event_identity: sourceEventIdentity }))}`;
1994
+ }
1995
+ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, device, inode) {
1996
+ 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.");
1997
+ return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
1998
+ }
1999
+ function validateFact(value, sessionRef) {
2000
+ if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
2001
+ requireFactByteLimit(value);
2002
+ if (value.producer === "codex_transcript") validateCodexFact(value);
2003
+ else if (value.producer === "claude_transcript") validateClaudeFact(value);
2004
+ else invalid("Ceal Host usage producer is invalid.");
2005
+ if (value.host_session_ref !== sessionRef) invalid("Ceal Host usage session does not match its batch.");
2006
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage file reference is invalid.");
2007
+ requireSafeRef2(value.source_event_ref, "Ceal Host usage event reference is invalid.");
2008
+ if (value.host_turn_ref !== null) requireSafeRef2(value.host_turn_ref, "Ceal Host usage turn reference is invalid.");
2009
+ if (value.requested_model !== null && !boundedText(value.requested_model, 256)) invalid("Ceal Host requested model is invalid.");
2010
+ if (value.reported_model !== null && !boundedText(value.reported_model, 256)) invalid("Ceal Host reported model is invalid.");
2011
+ if (value.fact_ref !== hostUsageFactReference(value.source_file_ref, value.source_event_ref)) invalid("Ceal Host usage identity is invalid.");
2012
+ }
2013
+ function requireFactByteLimit(value) {
2014
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_FACT_MAX_BYTES) invalid("Ceal Host usage fact exceeds its byte limit.");
2015
+ }
2016
+ function validateCodexFact(value) {
2017
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fact is invalid.");
2018
+ 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"]);
2019
+ if (value.producer !== "codex_transcript" || !safeInteger(value.source_event_ordinal)) invalid("Ceal Codex usage fact is invalid.");
2020
+ requireIsoTimestamp(value.observed_at, "Ceal Codex usage time is invalid.");
2021
+ if (!isOperationRecord(value.source_usage)) invalid("Ceal Codex source usage is invalid.");
2022
+ requireExactOperationKeys(value.source_usage, ["last_token_usage", "total_token_usage"]);
2023
+ if (value.source_usage.last_token_usage !== null) validateCodexUsageCounts(value.source_usage.last_token_usage);
2024
+ if (value.source_usage.total_token_usage !== null) validateCodexUsageCounts(value.source_usage.total_token_usage);
2025
+ 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.");
2026
+ validateNormalizedUsage(value.normalized_usage);
2027
+ }
2028
+ function validateClaudeFact(value) {
2029
+ if (!isOperationRecord(value)) invalid("Ceal Claude usage fact is invalid.");
2030
+ 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"]);
2031
+ validateClaudeIdentity(value);
2032
+ requireIsoTimestamp(value.observed_at, "Ceal Claude usage time is invalid.");
2033
+ validateClaudeSourceUsage(value.source_usage);
2034
+ validateClaudeSemantics(value);
2035
+ validateNormalizedUsage(value.normalized_usage);
2036
+ }
2037
+ function validateClaudeIdentity(value) {
2038
+ 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.");
2039
+ }
2040
+ function validateClaudeSourceUsage(value) {
2041
+ if (!isOperationRecord(value)) invalid("Ceal Claude source usage is invalid.");
2042
+ requireExactOperationKeys(value, ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"], ["cache_creation"]);
2043
+ for (const key of ["input_tokens", "output_tokens"]) if (!safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
2044
+ 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.");
2045
+ if (value.cache_creation !== void 0 && value.cache_creation !== null) validateClaudeCacheCreationUsage(value.cache_creation);
2046
+ }
2047
+ function validateClaudeCacheCreationUsage(value) {
2048
+ if (!isOperationRecord(value)) invalid("Ceal Claude cache creation usage is invalid.");
2049
+ requireExactOperationKeys(value, ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]);
2050
+ 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.");
2051
+ }
2052
+ function validateClaudeSemantics(value) {
2053
+ if (value.counter_semantics !== "assistant_message" || !validClaudeFinality(value.finality) || value.child_inclusion !== "unknown" || !validCorrectionSemantics(value.correction_semantics)) invalid("Ceal Claude usage semantics are invalid.");
2054
+ }
2055
+ function validClaudeFinality(value) {
2056
+ return value === "terminal" || value === "nonterminal" || value === "unknown";
2057
+ }
2058
+ function validCorrectionSemantics(value) {
2059
+ return value === "not_observed" || value === "unknown";
2060
+ }
2061
+ function validateCodexUsageCounts(value) {
2062
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
2063
+ requireExactOperationKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
2064
+ for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
2065
+ 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.");
2066
+ }
2067
+ function validateNormalizedUsage(value) {
2068
+ if (!isOperationRecord(value)) invalid("Ceal normalized Host usage is invalid.");
2069
+ requireExactOperationKeys(value, ["input", "output", "total", "cached_input", "cache_write_input", "reasoning_output"]);
2070
+ for (const key of Object.keys(value)) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal normalized Host usage is invalid.");
2071
+ validateNormalizedTotals(value);
2072
+ }
2073
+ function validateNormalizedTotals(value) {
2074
+ validateNormalizedCountTotal(value);
2075
+ validateNormalizedInputSubsets(value);
2076
+ validateNormalizedOutputSubset(value);
2077
+ }
2078
+ function validateNormalizedCountTotal(value) {
2079
+ 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.");
2080
+ }
2081
+ function validateNormalizedInputSubsets(value) {
2082
+ 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.");
2083
+ }
2084
+ function validateNormalizedOutputSubset(value) {
2085
+ if (value.output !== null && value.reasoning_output !== null && Number(value.reasoning_output) > Number(value.output)) invalid("Ceal normalized Host output subset is inconsistent.");
2086
+ }
2087
+ function validateSourceRange(value) {
2088
+ if (!isOperationRecord(value)) invalid("Ceal Host usage source range is invalid.");
2089
+ requireExactOperationKeys(value, ["source_file_ref", "start_offset", "end_offset"]);
2090
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage source-file reference is invalid.");
2091
+ 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.");
2092
+ }
2093
+ function validateCealHostUsageCoverageGap(value) {
2094
+ if (!isOperationRecord(value)) invalid("Ceal Host usage coverage gap is invalid.");
2095
+ requireExactOperationKeys(value, ["reason", "source_file_ref", "start_offset", "end_offset", "omitted_count"]);
2096
+ if (!isOneOf(HOST_USAGE_COVERAGE_GAP_REASONS, value.reason) || !validUsageGapCount(value.reason, value.omitted_count)) invalid("Ceal Host usage coverage gap is invalid.");
2097
+ if (value.source_file_ref === null) {
2098
+ if (value.start_offset !== null || value.end_offset !== null) invalid("Ceal Host usage coverage gap range is invalid.");
1717
2099
  return;
1718
2100
  }
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);
2101
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage coverage file reference is invalid.");
2102
+ 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.");
2103
+ }
2104
+ function validateCoverageGap(value) {
2105
+ validateCealHostUsageCoverageGap(value);
2106
+ }
2107
+ function validUsageGapCount(reason, value) {
2108
+ return value === null ? reason !== "outbox_capacity" : safeInteger(value) && Number(value) >= 1;
2109
+ }
2110
+ function isOneOf(values, value) {
2111
+ return typeof value === "string" && values.some((candidate) => candidate === value);
2112
+ }
2113
+ function isCealHostUsageBatchReference(value) {
2114
+ return typeof value === "string" && value.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX) && isCealDigest(value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length));
2115
+ }
2116
+ function cealHostUsageBatchObjectDigestFromFileName(value) {
2117
+ if (!value.endsWith(".json")) return null;
2118
+ const digest2 = value.slice(0, -5);
2119
+ return isCealDigest(digest2) ? digest2 : null;
2120
+ }
2121
+ function cealHostUsageBatchObjectDigestFromReference(value) {
2122
+ return isCealHostUsageBatchReference(value) ? value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length) : null;
2123
+ }
2124
+ function safeInteger(value) {
2125
+ return Number.isSafeInteger(value) && Number(value) >= 0;
2126
+ }
2127
+ function boundedText(value, maximum) {
2128
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters(value);
2129
+ }
2130
+ function hasControlCharacters(value) {
2131
+ for (const character of value) {
2132
+ const code2 = character.codePointAt(0);
2133
+ if (code2 !== void 0 && (code2 < 32 || code2 === 127)) return true;
1723
2134
  }
2135
+ return false;
2136
+ }
2137
+ function sha256(value) {
2138
+ return createHash3("sha256").update(value, "utf8").digest("hex");
1724
2139
  }
1725
2140
 
1726
2141
  // packages/ceal-client-protocol/src/host-prompt-ref.ts
@@ -1827,11 +2242,72 @@ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSch
1827
2242
  var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
1828
2243
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
1829
2244
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
2245
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.refusal_schema_name, fields: hostInvocationAuthenticationContract.refusal_fields });
1830
2246
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
1831
2247
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
1832
2248
  var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
1833
2249
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
2250
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
1834
2251
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
2252
+ function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
2253
+ const messages = [];
2254
+ let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
2255
+ for (const candidate of newestFirst.slice(0, CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES)) {
2256
+ 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 } : {} };
2257
+ if (encodedMessageWindowBytes([...messages, complete]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) {
2258
+ messages.push(Object.freeze(complete));
2259
+ continue;
2260
+ }
2261
+ const clipped = clipHumanMessageToWindow(messages, candidate);
2262
+ if (clipped === null) {
2263
+ truncated = true;
2264
+ break;
2265
+ }
2266
+ messages.push(Object.freeze(clipped));
2267
+ }
2268
+ return Object.freeze({ messages: Object.freeze(messages), truncated });
2269
+ }
2270
+ function encodedMessageWindowBytes(messages) {
2271
+ return new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2272
+ }
2273
+ function clipHumanMessageToWindow(prefix, candidate) {
2274
+ const clipped = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: "", text_truncated: true };
2275
+ const available = CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES - encodedMessageWindowBytes([...prefix, clipped]);
2276
+ if (available < 0) return null;
2277
+ const text = [];
2278
+ let used = 0;
2279
+ for (const point of candidate.text) {
2280
+ const encodedPoint = JSON.stringify(point);
2281
+ const cost = new TextEncoder().encode(encodedPoint).byteLength - 2;
2282
+ if (used + cost > available) break;
2283
+ text.push(point);
2284
+ used += cost;
2285
+ }
2286
+ const result = { ...clipped, text: text.join("") };
2287
+ return encodedMessageWindowBytes([...prefix, result]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES ? result : null;
2288
+ }
2289
+ function decodeCealHostInvocationHumanMessageWindow(value) {
2290
+ 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();
2291
+ const messages = value.messages.map(decodeHumanMessage);
2292
+ const bytes = new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2293
+ if (bytes > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) throw invalidInvocationContextRequest();
2294
+ return Object.freeze({ messages: Object.freeze(messages), truncated: value.truncated });
2295
+ }
2296
+ function decodeHumanMessage(candidate) {
2297
+ 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();
2298
+ if (candidate.text_truncated !== void 0 && candidate.text_truncated !== true) throw invalidInvocationContextRequest();
2299
+ 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 } : {} });
2300
+ }
2301
+ function safeReference(value) {
2302
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
2303
+ }
2304
+ function exactOptionalKeys(value, required, optional = []) {
2305
+ const keys = Object.keys(value);
2306
+ return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => required.includes(key) || optional.includes(key));
2307
+ }
2308
+ function invalidInvocationContextRequest() {
2309
+ return new TypeError("The Host invocation context request is invalid.");
2310
+ }
1835
2311
  function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1836
2312
  const clientNonce = contract.host_invocation_authentication.client_nonce;
1837
2313
  return {
@@ -1841,31 +2317,11 @@ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTR
1841
2317
  };
1842
2318
  }
1843
2319
  var hostNonceContract = deriveCealHostInvocationNonceContract();
1844
- var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
1845
2320
  var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
1846
2321
  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
2322
  var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
1861
2323
  "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"
2324
+ "request_creation_refused"
1869
2325
  ]);
1870
2326
  var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1871
2327
  "invalid_arguments",
@@ -1874,7 +2330,6 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1874
2330
  "context_unavailable",
1875
2331
  "context_replaced",
1876
2332
  "no_binding",
1877
- "context_stale",
1878
2333
  "context_expired",
1879
2334
  "host_source_refused",
1880
2335
  "host_credential_refused",
@@ -1891,31 +2346,42 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1891
2346
  "relay_failed",
1892
2347
  "host_refusal_invalid"
1893
2348
  ]);
2349
+ var CEAL_HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2350
+ "permission_denied",
2351
+ "socket_missing",
2352
+ "connection_refused",
2353
+ "closed_early",
2354
+ "response_invalid",
2355
+ "timed_out",
2356
+ "cancelled",
2357
+ "unavailable"
2358
+ ]);
1894
2359
  var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1895
2360
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
1896
2361
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
1897
2362
  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" }),
2363
+ // This reason cannot distinguish a Codex side conversation from a missing
2364
+ // context in a regular session, so guidance must leave that choice to the caller.
2365
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
1899
2366
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1900
2367
  // `no_binding` now means the producer has no real current Host session. The
1901
2368
  // Host Relay never uses it for an uncreated Gateway Request; there is no
1902
2369
  // useful retry until the consumer is running inside a Host session.
1903
2370
  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
2371
  context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
1906
2372
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
1907
2373
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
1908
2374
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
1909
2375
  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" }),
1911
- gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
2376
+ contract_mismatch: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2377
+ gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "upgrade_ceal_client" }),
1912
2378
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
1913
2379
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
1914
2380
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
1915
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2381
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
1916
2382
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
1917
2383
  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" }),
2384
+ relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
1919
2385
  host_refusal_invalid: Object.freeze({ classification: "host_refusal_invalid", next_action: "answer_with_gap" })
1920
2386
  });
1921
2387
 
@@ -1929,10 +2395,13 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
1929
2395
  "activation_recorded",
1930
2396
  "activation_failed",
1931
2397
  "watcher_scan_failed",
2398
+ "usage_capture_failed",
2399
+ "usage_upload_failed",
1932
2400
  "activation_wait_skipped",
1933
2401
  "activation_wait_engaged",
1934
2402
  "activation_wait_completed",
1935
- "activation_wait_exhausted"
2403
+ "activation_wait_exhausted",
2404
+ "invocation_authentication_failed"
1936
2405
  ]);
1937
2406
  var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1938
2407
  "malformed_line",
@@ -1942,6 +2411,17 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1942
2411
  "size_budget",
1943
2412
  "symlink"
1944
2413
  ]);
2414
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_WATCHER_OPTIONAL_FIELDS = vocabulary(["failure_kind", "cause"]);
2415
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_OPTIONAL_FIELDS = vocabulary(["cause"]);
2416
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE = "^[a-z][a-z0-9_]{0,63}(?::[A-Za-z][A-Za-z0-9_]{0,63})?$";
2417
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES = Object.freeze([
2418
+ ...CEAL_HOST_AUTHENTICATION_CAUSES,
2419
+ ...CEAL_HOST_RELAY_EXCHANGE_FAILURES.map((failure) => `relay_exchange:${failure}`)
2420
+ ]);
2421
+ var hostServiceDiagnosticCausePattern = new RegExp(CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE, "u");
2422
+ function isCealHostServiceDiagnosticCause(value, event) {
2423
+ return typeof value === "string" && hostServiceDiagnosticCausePattern.test(value) && (event !== "invocation_authentication_failed" || CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES.includes(value));
2424
+ }
1945
2425
 
1946
2426
  // packages/ceal-client-protocol/src/client-result-materialization.ts
1947
2427
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
@@ -2031,12 +2511,14 @@ var ADMIN_SOURCE_OWNERS = vocabulary([
2031
2511
  "resource",
2032
2512
  "prompt",
2033
2513
  "usage",
2514
+ "provider_request_lifecycle",
2034
2515
  "connector",
2035
2516
  "session",
2036
2517
  "knowledge",
2037
2518
  "policy"
2038
2519
  ]);
2039
2520
  var ADMIN_COMPLETENESS_STATES = vocabulary(["complete", "partial", "unknown"]);
2521
+ var ADMIN_PROVIDER_REQUEST_CAPTURE_HEALTH_STATES = vocabulary(["available", "missing", "invalid", "unreadable"]);
2040
2522
  var ADMIN_OPERATION_OUTCOMES = vocabulary(["completed", "failed", "denied", "cancelled", "unknown"]);
2041
2523
  var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
2042
2524
  var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
@@ -2089,6 +2571,22 @@ function decodeClaudeQueuedPromptRow(row, sessionId) {
2089
2571
  if (row.type === "queue-operation") return decodeQueueEnqueuePrompt(row, sessionId);
2090
2572
  return null;
2091
2573
  }
2574
+ function decodeClaudeHumanMessageRow(row, sessionId) {
2575
+ if (!isClaudeNativeHumanMessageRow(row)) return decodeClaudeQueuedPromptRow(row, sessionId);
2576
+ return decodeClaudeNativeHumanMessage(row, sessionId);
2577
+ }
2578
+ function isClaudeNativeHumanMessageRow(row) {
2579
+ return record(row) && row.type === "user" && record(row.message) && typeof row.message.content === "string";
2580
+ }
2581
+ function decodeClaudeNativeHumanMessage(row, sessionId) {
2582
+ if (!sessionMatches(row, sessionId)) return null;
2583
+ if (row.isMeta === true && (!record(row.origin) || typeof row.origin.kind !== "string")) return null;
2584
+ const identity = queuedRowIdentity(row);
2585
+ if (identity === null) throw new ClaudeHostError("payload_rejected", "Claude transcript human message identity is malformed.");
2586
+ const message = row.message;
2587
+ if (!record(message) || typeof message.content !== "string") return null;
2588
+ return { turnId: identity.uuid, timestamp: identity.timestamp, content: message.content };
2589
+ }
2092
2590
  function decodeArrayTextPrompt(row, sessionId) {
2093
2591
  if (!record(row.message) || !Array.isArray(row.message.content)) return null;
2094
2592
  if (!sessionMatches(row, sessionId)) return null;
@@ -2131,9 +2629,9 @@ function queuedRowIdentity(row) {
2131
2629
  if (typeof row.timestamp !== "string" || !Number.isFinite(Date.parse(row.timestamp))) return null;
2132
2630
  return { uuid: row.uuid, timestamp: row.timestamp };
2133
2631
  }
2134
- function queueEnqueueTurnId(sessionId, timestamp4, content) {
2135
- return `queue-enqueue:${createHash3("sha256").update(`${sessionId}
2136
- ${timestamp4}
2632
+ function queueEnqueueTurnId(sessionId, timestamp5, content) {
2633
+ return `queue-enqueue:${createHash4("sha256").update(`${sessionId}
2634
+ ${timestamp5}
2137
2635
  ${content}`, "utf8").digest("hex").slice(0, 32)}`;
2138
2636
  }
2139
2637
  function claudeLocalSessionRef(sessionId) {
@@ -2150,7 +2648,7 @@ function isSessionSource(value) {
2150
2648
  }
2151
2649
  function requiredAbsolutePath(value, message) {
2152
2650
  const text = requiredText(value, 4096, message);
2153
- if (!text.startsWith("/") || text.includes("\0")) throw invalid2(message);
2651
+ if (!isAbsolute(text) || text.includes("\0")) throw invalid2(message);
2154
2652
  return text;
2155
2653
  }
2156
2654
  function requiredText(value, max, message) {
@@ -2165,7 +2663,7 @@ function optionalText(value, max) {
2165
2663
  return requiredText(value, max, "Claude optional hook field is invalid.");
2166
2664
  }
2167
2665
  function digest(value) {
2168
- return createHash3("sha256").update(value, "utf8").digest("hex");
2666
+ return createHash4("sha256").update(value, "utf8").digest("hex");
2169
2667
  }
2170
2668
  function record(value) {
2171
2669
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2175,8 +2673,8 @@ function invalid2(message) {
2175
2673
  }
2176
2674
 
2177
2675
  // 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";
2676
+ import { mkdir as mkdir4, readdir, readFile, unlink as unlink3 } from "node:fs/promises";
2677
+ import { isAbsolute as isAbsolute4, join as join4 } from "node:path";
2180
2678
 
2181
2679
  // host/invocation-context.ts
2182
2680
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2244,13 +2742,13 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2244
2742
  ];
2245
2743
 
2246
2744
  // host/relay/src/host-producer-core.ts
2247
- import { createHash as createHash4 } from "node:crypto";
2745
+ import { createHash as createHash5 } from "node:crypto";
2248
2746
 
2249
2747
  // host/secure-file.ts
2250
2748
  import { execFile } from "node:child_process";
2251
2749
  import { constants } from "node:fs";
2252
2750
  import { lstat, open } from "node:fs/promises";
2253
- import { dirname, win32 } from "node:path";
2751
+ import { dirname, join as join2, win32 } from "node:path";
2254
2752
  import { fileURLToPath } from "node:url";
2255
2753
  var SecureFileCustodyError = class extends Error {
2256
2754
  name = "SecureFileCustodyError";
@@ -2268,6 +2766,7 @@ var SecureFileCustodyError = class extends Error {
2268
2766
  }
2269
2767
  };
2270
2768
  var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
2769
+ var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
2271
2770
  var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
2272
2771
  var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
2273
2772
  function secureOpenFlags(flags, platform) {
@@ -2310,18 +2809,46 @@ async function assertWindowsIdentityStable(handle, first, path) {
2310
2809
  }
2311
2810
  async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
2312
2811
  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);
2812
+ const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2314
2813
  if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
2315
2814
  if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
2316
2815
  if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
2317
2816
  throw securefsRefusal(result.stderr);
2318
2817
  }
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();
2818
+ async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
2819
+ const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
2820
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2821
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
2822
+ throw securefsRefusal(result.stderr);
2823
+ }
2824
+ async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
2825
+ 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.");
2826
+ const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
2827
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2828
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
2829
+ throw securefsRefusal(result.stderr);
2830
+ }
2831
+ async function isPrivateWindowsDirectory(path, custody = {}) {
2832
+ await lstat(path);
2833
+ try {
2834
+ const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
2835
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
2836
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
2837
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
2838
+ const refusal = securefsRefusal(result.stderr);
2839
+ if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
2840
+ throw refusal;
2841
+ } catch (error) {
2842
+ if (error instanceof SecureFileCustodyError) throw error;
2843
+ throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
2844
+ }
2845
+ }
2846
+ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2847
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
2848
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2322
2849
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2323
2850
  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) => {
2851
+ const child = execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2325
2852
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2326
2853
  if (exitCode === null) {
2327
2854
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2329,6 +2856,8 @@ async function runWindowsSecurefs(args, maxBytes, custody) {
2329
2856
  }
2330
2857
  resolve2({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
2331
2858
  });
2859
+ child.stdin?.on("error", () => void 0);
2860
+ child.stdin?.end(stdin);
2332
2861
  });
2333
2862
  }
2334
2863
  function securefsRefusal(stderr) {
@@ -2346,9 +2875,9 @@ function securefsRefusal(stderr) {
2346
2875
  if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
2347
2876
  return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
2348
2877
  }
2349
- function resolveInstalledHostExecutable() {
2878
+ function resolveInstalledHostExecutable(platform) {
2350
2879
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2351
- return win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
2880
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2352
2881
  }
2353
2882
  function isRecord2(value) {
2354
2883
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2364,6 +2893,11 @@ function isPrivateFileMode(mode, platform = process.platform, _handle) {
2364
2893
  if (platform === "win32") return false;
2365
2894
  return (mode & 63) === 0;
2366
2895
  }
2896
+ async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
2897
+ if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
2898
+ const entry = await lstat(path);
2899
+ return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
2900
+ }
2367
2901
 
2368
2902
  // host/relay/src/host-producer-core.ts
2369
2903
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
@@ -2372,7 +2906,22 @@ function isHostTranscriptCursorReason(value) {
2372
2906
  }
2373
2907
  var TRANSCRIPT_MISSING_REASON = "transcript_missing";
2374
2908
  var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
2375
- var HOST_INVOCATION_TRANSCRIPT_TAIL_MAX_BYTES = 1024 * 1024;
2909
+ var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
2910
+ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
2911
+ const seen = /* @__PURE__ */ new Set();
2912
+ const newestFirst = [];
2913
+ for (const message of [...chronological].reverse()) {
2914
+ if (seen.has(message.host_input_ref)) continue;
2915
+ seen.add(message.host_input_ref);
2916
+ newestFirst.push(message);
2917
+ }
2918
+ for (const message of existing?.messages ?? []) {
2919
+ if (seen.has(message.host_input_ref)) continue;
2920
+ seen.add(message.host_input_ref);
2921
+ newestFirst.push(message);
2922
+ }
2923
+ return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
2924
+ }
2376
2925
  function transcriptScanFailureKind(error, adapterFailureKind) {
2377
2926
  if (transcriptErrorCode(error) === "ELOOP") return "symlink";
2378
2927
  const adapter = adapterFailureKind(error);
@@ -2429,10 +2978,10 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
2429
2978
  return null;
2430
2979
  }
2431
2980
  function transcriptSha256(value) {
2432
- return createHash4("sha256").update(value).digest("hex");
2981
+ return createHash5("sha256").update(value).digest("hex");
2433
2982
  }
2434
2983
  function transcriptObjectSha256(value) {
2435
- return createHash4("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2984
+ return createHash5("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2436
2985
  }
2437
2986
  function isTranscriptRecord(value) {
2438
2987
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2696,15 +3245,1112 @@ async function removeTemporary(path, port, failures) {
2696
3245
  if (errorCode(error) !== "ENOENT") failures.push(error);
2697
3246
  }
2698
3247
  }
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.");
3248
+ function throwFailures(failures) {
3249
+ if (failures.length === 1) throw failures[0];
3250
+ if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
3251
+ }
3252
+ function directorySyncUnsupported(error) {
3253
+ return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
3254
+ }
3255
+ function errorCode(error) {
3256
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3257
+ }
3258
+
3259
+ // host/relay/src/host-usage-facts-store.ts
3260
+ import { createHash as createHash6 } from "node:crypto";
3261
+ import { constants as constants2 } from "node:fs";
3262
+ import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3263
+ import { dirname as dirname3, join as join3 } from "node:path";
3264
+ var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3265
+ var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3266
+ var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
3267
+ var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
3268
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
3269
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
3270
+ var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
3271
+ var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
3272
+ var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
3273
+ var HostUsageFactsStore = class {
3274
+ root;
3275
+ sessions;
3276
+ batches;
3277
+ platform;
3278
+ custody;
3279
+ afterPendingWrite;
3280
+ afterBatchPublish;
3281
+ sessionDirectoryCursor;
3282
+ constructor(options) {
3283
+ this.root = join3(options.outbox_dir, "usage-facts");
3284
+ this.sessions = join3(this.root, "sessions");
3285
+ this.batches = join3(this.root, "batches");
3286
+ this.platform = options.platform ?? process.platform;
3287
+ this.custody = options.secure_file_custody ?? {};
3288
+ this.afterPendingWrite = options.afterPendingWrite;
3289
+ this.afterBatchPublish = options.afterBatchPublish;
3290
+ }
3291
+ async prepare() {
3292
+ for (const directory of [this.root, this.sessions, this.batches]) {
3293
+ await preparePrivateDirectory(directory, this.platform, this.custody);
3294
+ }
3295
+ }
3296
+ async close() {
3297
+ const cursor = this.sessionDirectoryCursor;
3298
+ this.sessionDirectoryCursor = void 0;
3299
+ await cursor?.close();
3300
+ }
3301
+ async readState(producer, hostSourceRef, hostSessionRef) {
3302
+ await this.prepare();
3303
+ const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3304
+ const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3305
+ if (value === null) return null;
3306
+ validateState(value, producer, hostSourceRef, hostSessionRef);
3307
+ return value;
3308
+ }
3309
+ createState(producer, hostSourceRef, hostSessionRef) {
3310
+ return {
3311
+ schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
3312
+ producer,
3313
+ host_source_ref: hostSourceRef,
3314
+ host_session_ref: hostSessionRef,
3315
+ cursors: {},
3316
+ eligible_batches: [],
3317
+ coverage_gaps: [],
3318
+ coverage_gap_created_at: null
3319
+ };
3320
+ }
3321
+ async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
3322
+ let state = await this.readState(producer, hostSourceRef, hostSessionRef);
3323
+ if (state === null) {
3324
+ state = this.createState(producer, hostSourceRef, hostSessionRef);
3325
+ state = await this.writeCursor(state, sourceSlot, initial);
3326
+ }
3327
+ state = await this.recoverPending(state);
3328
+ if (state.quarantined_reason !== void 0) return null;
3329
+ state = await this.commitCoverageGaps(state, createdAt);
3330
+ const cursor = state.cursors[sourceSlot];
3331
+ return cursor === void 0 ? null : { state, cursor };
3332
+ }
3333
+ async writeCursor(state, sourceSlot, cursor) {
3334
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3335
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3336
+ if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
3337
+ const current = latest.cursors[sourceSlot];
3338
+ if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
3339
+ const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
3340
+ await this.writeState(updated);
3341
+ return updated;
3342
+ });
3343
+ }
3344
+ async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
3345
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3346
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3347
+ return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
3348
+ });
3349
+ }
3350
+ async recoverPending(state) {
3351
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3352
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3353
+ const recovered = await this.finishPendingTransition(latest);
3354
+ await this.sweepOrphanedBatches(recovered);
3355
+ return recovered;
3356
+ });
3357
+ }
3358
+ /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3359
+ async sweepOrphanedBatches(state) {
3360
+ await this.prepare();
3361
+ const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3362
+ await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3363
+ const expected = expectedBatchNames(state);
3364
+ const directory = await opendir(directoryPath);
3365
+ let inspected = 0;
3366
+ let deleted = 0;
3367
+ try {
3368
+ while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
3369
+ const entry = await directory.read();
3370
+ if (entry === null) break;
3371
+ inspected += 1;
3372
+ if (!isOrphanBatchEntry(entry, expected)) continue;
3373
+ await unlink2(join3(directoryPath, entry.name));
3374
+ deleted += 1;
3375
+ }
3376
+ } finally {
3377
+ await directory.close();
3378
+ }
3379
+ if (deleted > 0) await syncDirectory(directoryPath, this.platform);
3380
+ return deleted;
3381
+ }
3382
+ async commitCoverageGaps(state, createdAt) {
3383
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3384
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3385
+ if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
3386
+ const sourceRanges = coverageRanges(latest.coverage_gaps);
3387
+ const canonical = createCealHostUsageBatch({
3388
+ host_source_ref: latest.host_source_ref,
3389
+ host_session_ref: latest.host_session_ref,
3390
+ created_at: latest.coverage_gap_created_at ?? createdAt,
3391
+ source_ranges: sourceRanges,
3392
+ facts: [],
3393
+ coverage_gaps: latest.coverage_gaps
3394
+ });
3395
+ const cursor = firstCursor(latest);
3396
+ if (cursor === null) return latest;
3397
+ return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
3398
+ });
3399
+ }
3400
+ async nextUploadCandidate(producer, hostSourceRef) {
3401
+ await this.prepare();
3402
+ const names = await this.readNextSessionNames();
3403
+ for (const name of names) {
3404
+ const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3405
+ if (state === null) continue;
3406
+ validateStateOwner(state, producer, hostSourceRef);
3407
+ let validated = state;
3408
+ if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
3409
+ else validated = await this.recoverPending(validated);
3410
+ if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
3411
+ const next = validated.eligible_batches[0];
3412
+ if (next === void 0) continue;
3413
+ const batch = await this.readBatch(validated, next.batch_ref);
3414
+ return { state: validated, batch };
3415
+ }
3416
+ return null;
3417
+ }
3418
+ async readNextSessionNames() {
3419
+ this.sessionDirectoryCursor ??= await opendir(this.sessions);
3420
+ const names = [];
3421
+ let inspected = 0;
3422
+ while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
3423
+ const entry = await this.sessionDirectoryCursor.read();
3424
+ if (entry === null) {
3425
+ await this.sessionDirectoryCursor.close();
3426
+ this.sessionDirectoryCursor = void 0;
3427
+ break;
3428
+ }
3429
+ inspected += 1;
3430
+ if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
3431
+ }
3432
+ return names;
3433
+ }
3434
+ async acknowledge(state, batchRef) {
3435
+ await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3436
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3437
+ if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
3438
+ const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
3439
+ if (remaining.length === latest.eligible_batches.length) return;
3440
+ await this.writeState({ ...latest, eligible_batches: remaining });
3441
+ await removeFileIfPresent(this.batchPath(state, batchRef));
3442
+ });
3443
+ }
3444
+ async quarantine(state, reason) {
3445
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3446
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3447
+ const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
3448
+ await this.writeState(updated);
3449
+ return updated;
3450
+ });
3451
+ }
3452
+ async retireCursor(state, sourceSlot, cursor, gap) {
3453
+ return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
3454
+ }
3455
+ async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
3456
+ if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
3457
+ if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
3458
+ const queued = await this.publishTransitionBatch(state, batch);
3459
+ const pending = {
3460
+ source_slot: sourceSlot,
3461
+ before_cursor: beforeCursor,
3462
+ after_cursor: afterCursor,
3463
+ batch_ref: queued.batch_ref,
3464
+ batch_bytes: queued.batch_bytes,
3465
+ gap_delta: [...gapDelta, ...queued.overflow_gaps],
3466
+ clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
3467
+ };
3468
+ const prepared = { ...state, pending_transition: pending };
3469
+ await this.writeState(prepared);
3470
+ await this.afterPendingWrite?.();
3471
+ return await this.finishPendingTransition(prepared);
3472
+ }
3473
+ async publishTransitionBatch(state, batch) {
3474
+ if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
3475
+ const serialized = serializeBatch(batch);
3476
+ if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
3477
+ await this.writeImmutableBatch(state, batch, serialized);
3478
+ await this.afterBatchPublish?.();
3479
+ return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
3480
+ }
3481
+ async finishPendingTransition(state) {
3482
+ const pending = state.pending_transition;
3483
+ if (pending === void 0 || state.quarantined_reason !== void 0) return state;
3484
+ const current = state.cursors[pending.source_slot];
3485
+ if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
3486
+ const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
3487
+ await this.writeState(quarantined);
3488
+ return quarantined;
3489
+ }
3490
+ let cursors = state.cursors;
3491
+ if (!cursorMatches(current, pending.after_cursor)) {
3492
+ const next = { ...state.cursors };
3493
+ if (pending.after_cursor === null) delete next[pending.source_slot];
3494
+ else next[pending.source_slot] = pending.after_cursor;
3495
+ cursors = next;
3496
+ }
3497
+ const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
3498
+ const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
3499
+ const { pending_transition: _pendingTransition, ...settledState } = state;
3500
+ const updated = {
3501
+ ...settledState,
3502
+ cursors,
3503
+ eligible_batches: eligible,
3504
+ coverage_gaps: gaps,
3505
+ coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
3506
+ };
3507
+ await this.writeState(updated);
3508
+ return updated;
3509
+ }
3510
+ async writeImmutableBatch(state, batch, bytes) {
3511
+ const path = this.batchPath(state, batch.batch_ref);
3512
+ await preparePrivateDirectory(dirname3(path), this.platform, this.custody);
3513
+ const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3514
+ if (existing !== null) {
3515
+ if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3516
+ await syncExistingFile(path, this.platform);
3517
+ return;
3518
+ }
3519
+ if (this.platform === "win32") {
3520
+ await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
3521
+ return;
3522
+ }
3523
+ let handle;
3524
+ try {
3525
+ handle = await openNoFollow(path, constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY, 384, this.platform);
3526
+ await handle.writeFile(bytes);
3527
+ await handle.sync();
3528
+ await handle.close();
3529
+ handle = void 0;
3530
+ await syncDirectory(dirname3(path), this.platform);
3531
+ } catch (error) {
3532
+ await handle?.close().catch(() => void 0);
3533
+ if (errorCode2(error) === "EEXIST") {
3534
+ const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3535
+ if (winner !== null && winner.equals(bytes)) {
3536
+ await syncExistingFile(path, this.platform);
3537
+ return;
3538
+ }
3539
+ throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3540
+ }
3541
+ await removeFileIfPresent(path).catch(() => void 0);
3542
+ throw error;
3543
+ }
3544
+ }
3545
+ async readBatch(state, batchRef) {
3546
+ const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3547
+ if (bytes === null) throw new Error("Host usage facts batch object is missing.");
3548
+ let value;
3549
+ try {
3550
+ value = JSON.parse(bytes.toString("utf8"));
3551
+ } catch {
3552
+ throw new Error("Host usage facts batch object is malformed.");
3553
+ }
3554
+ validateCealHostUsageBatch(value);
3555
+ if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
3556
+ return value;
3557
+ }
3558
+ async writeState(state) {
3559
+ validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
3560
+ const bytes = Buffer.from(JSON.stringify(state), "utf8");
3561
+ if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
3562
+ await this.prepare();
3563
+ const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
3564
+ if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
3565
+ else await durableAtomicReplace(path, bytes);
3566
+ }
3567
+ async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
3568
+ const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3569
+ const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
3570
+ let release;
3571
+ const gate = new Promise((resolve2) => {
3572
+ release = resolve2;
3573
+ });
3574
+ const tail = previous.then(() => gate);
3575
+ SESSION_TRANSITION_TAILS.set(key, tail);
3576
+ await previous;
3577
+ try {
3578
+ return await run();
3579
+ } finally {
3580
+ release?.();
3581
+ if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
3582
+ }
3583
+ }
3584
+ sessionPath(producer, hostSourceRef, hostSessionRef) {
3585
+ return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3586
+ }
3587
+ batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3588
+ const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3589
+ return join3(this.batches, sessionName.slice(0, -5));
3590
+ }
3591
+ batchPath(state, batchRef) {
3592
+ return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3593
+ }
3594
+ };
3595
+ function serializeBatch(batch) {
3596
+ validateCealHostUsageBatch(batch);
3597
+ return Buffer.from(JSON.stringify(batch), "utf8");
3598
+ }
3599
+ function batchFileName(batchRef) {
3600
+ const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
3601
+ if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
3602
+ return `${digest2}.json`;
3603
+ }
3604
+ function expectedBatchNames(state) {
3605
+ const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
3606
+ const pending = state.pending_transition?.batch_ref;
3607
+ if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
3608
+ return expected;
3609
+ }
3610
+ function isOrphanBatchEntry(entry, expected) {
3611
+ return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
3612
+ }
3613
+ function hasOutboxCapacity(state, bytes) {
3614
+ const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
3615
+ return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
3616
+ }
3617
+ function overflowCoverageGaps(batch) {
3618
+ const count = batch.facts.length;
3619
+ const gaps = [...batch.coverage_gaps];
3620
+ 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 });
3621
+ return gaps;
3622
+ }
3623
+ function appendEligible(existing, next) {
3624
+ if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
3625
+ if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
3626
+ return [...existing, next];
3627
+ }
3628
+ function appendCoverageGaps(existing, added) {
3629
+ if (added.length === 0) return existing;
3630
+ const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
3631
+ for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
3632
+ const combined = [...byIdentity.values()];
3633
+ if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
3634
+ const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
3635
+ return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
3636
+ }
3637
+ function coverageRanges(gaps) {
3638
+ const ranges = /* @__PURE__ */ new Map();
3639
+ for (const gap of gaps) {
3640
+ if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
3641
+ const current = ranges.get(gap.source_file_ref);
3642
+ 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 });
3643
+ 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) });
3644
+ }
3645
+ return [...ranges.values()];
3646
+ }
3647
+ function firstCursor(state) {
3648
+ const entry = Object.entries(state.cursors)[0];
3649
+ return entry === void 0 ? null : entry;
3650
+ }
3651
+ function sameCursor(left, right) {
3652
+ return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
3653
+ }
3654
+ function cursorMatches(left, right) {
3655
+ return right === null ? left === void 0 : sameCursor(left, right);
3656
+ }
3657
+ function validateState(value, producer, hostSourceRef, hostSessionRef) {
3658
+ validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
3659
+ validateStateShape(value);
3660
+ validateStateLimits(value);
3661
+ validateStateContents(value);
3662
+ }
3663
+ function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
3664
+ 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.");
3665
+ }
3666
+ function validateStateLimits(value) {
3667
+ 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.");
3668
+ }
3669
+ function validateStateContents(value) {
3670
+ for (const [slot, cursor] of Object.entries(value.cursors)) {
3671
+ validateSourceSlot(slot);
3672
+ validateFileCursor(cursor);
3673
+ }
3674
+ for (const item of value.eligible_batches) validateEligibleBatch(item);
3675
+ if (value.pending_transition !== void 0) validatePending(value.pending_transition);
3676
+ for (const gap of value.coverage_gaps) validateGap(gap);
3677
+ validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
3678
+ }
3679
+ function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
3680
+ if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
3681
+ if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
3682
+ }
3683
+ function validateStateOwner(value, producer, hostSourceRef) {
3684
+ if (!isRecord3(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
3685
+ validateState(value, producer, hostSourceRef, String(value.host_session_ref));
3686
+ }
3687
+ function validateStateShape(value) {
3688
+ const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
3689
+ const optional = ["pending_transition", "quarantined_reason"];
3690
+ 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.");
3691
+ 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.");
3692
+ }
3693
+ function validateFileCursor(value) {
3694
+ 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.");
3695
+ validateCursorIdentity(value);
3696
+ validateCursorOffsets(value);
3697
+ validateCursorContext(value);
3698
+ if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
3699
+ if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
3700
+ }
3701
+ function validateCursorIdentity(value) {
3702
+ 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.");
3703
+ }
3704
+ function validateCursorOffsets(value) {
3705
+ 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.");
3706
+ }
3707
+ function validateCursorContext(value) {
3708
+ 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.");
3709
+ }
3710
+ function validOptionalText(value, maximum) {
3711
+ return value === null || typeof value === "string" && value.length <= maximum;
3712
+ }
3713
+ function validateCodexCounts(value) {
3714
+ 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.");
3715
+ if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
3716
+ }
3717
+ function validatePending(value) {
3718
+ 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.");
3719
+ validatePendingCursors(value);
3720
+ validatePendingBatch(value);
3721
+ validatePendingFields(value);
3722
+ for (const gap of value.gap_delta) validateGap(gap);
3723
+ }
3724
+ function validatePendingCursors(value) {
3725
+ validateSourceSlot(value.source_slot);
3726
+ validateFileCursor(value.before_cursor);
3727
+ if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
3728
+ }
3729
+ function validatePendingBatch(value) {
3730
+ if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
3731
+ }
3732
+ function validatePendingFields(value) {
3733
+ 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.");
3734
+ }
3735
+ function validateEligibleBatch(value) {
3736
+ 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.");
3737
+ }
3738
+ function validateGap(value) {
3739
+ try {
3740
+ validateCealHostUsageCoverageGap(value);
3741
+ } catch {
3742
+ throw new Error("Host usage facts coverage gap is invalid.");
3743
+ }
3744
+ }
3745
+ function validateSourceSlot(value) {
3746
+ if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
3747
+ }
3748
+ async function readOptionalJson(path, maxBytes, platform, custody) {
3749
+ const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
3750
+ if (bytes === null) return null;
3751
+ try {
3752
+ return JSON.parse(bytes.toString("utf8"));
3753
+ } catch {
3754
+ throw new Error("Host usage facts state JSON is malformed.");
3755
+ }
3756
+ }
3757
+ async function readOptionalBytes(path, maxBytes, platform, custody) {
3758
+ if (platform === "win32") {
3759
+ try {
3760
+ return await readPrivateFileWithSecurefs(path, maxBytes, custody);
3761
+ } catch (error) {
3762
+ if (errorCode2(error) === "ENOENT") return null;
3763
+ throw error;
3764
+ }
3765
+ }
3766
+ let handle;
3767
+ try {
3768
+ handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
3769
+ const stats = await handle.stat();
3770
+ 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.");
3771
+ return await handle.readFile();
3772
+ } catch (error) {
3773
+ if (errorCode2(error) === "ENOENT") return null;
3774
+ throw error;
3775
+ } finally {
3776
+ await handle?.close();
3777
+ }
3778
+ }
3779
+ async function preparePrivateDirectory(path, platform, custody) {
3780
+ if (platform === "win32") {
3781
+ await ensurePrivateDirectoryWithSecurefs(path, custody);
3782
+ return;
3783
+ }
3784
+ await mkdir2(path, { recursive: true, mode: 448 });
3785
+ if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3786
+ }
3787
+ async function syncExistingFile(path, platform) {
3788
+ const handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
3789
+ try {
3790
+ await handle.sync();
3791
+ } finally {
3792
+ await handle.close();
3793
+ }
3794
+ await syncDirectory(dirname3(path), platform);
3795
+ }
3796
+ async function syncDirectory(path, platform) {
3797
+ if (platform === "win32") return;
3798
+ const handle = await open3(path, constants2.O_RDONLY);
3799
+ try {
3800
+ await handle.sync();
3801
+ } finally {
3802
+ await handle.close();
3803
+ }
3804
+ }
3805
+ async function removeFileIfPresent(path) {
3806
+ try {
3807
+ await unlink2(path);
3808
+ } catch (error) {
3809
+ if (errorCode2(error) !== "ENOENT") throw error;
3810
+ }
3811
+ }
3812
+ function sameKeys(value, expected) {
3813
+ return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
3814
+ }
3815
+ function isRecord3(value) {
3816
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3817
+ }
3818
+ function safeInteger2(value) {
3819
+ return Number.isSafeInteger(value) && Number(value) >= 0;
3820
+ }
3821
+ function validTimestamp(value) {
3822
+ return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
3823
+ }
3824
+ function errorCode2(error) {
3825
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3826
+ }
3827
+ function sha2562(value) {
3828
+ return createHash6("sha256").update(value, "utf8").digest("hex");
3829
+ }
3830
+
3831
+ // host/relay/src/host-usage-facts-capture.ts
3832
+ import { constants as constants3 } from "node:fs";
3833
+ var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
3834
+ var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
3835
+ var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
3836
+ var HostUsageTranscriptSourceError = class extends Error {
3837
+ constructor(options) {
3838
+ super("Host usage transcript source could not be read.", options);
3839
+ this.name = "HostUsageTranscriptSourceError";
3840
+ }
3841
+ };
3842
+ async function readHostUsageTranscriptSource(read) {
3843
+ try {
3844
+ return await read();
3845
+ } catch (error) {
3846
+ throw new HostUsageTranscriptSourceError({ cause: error });
3847
+ }
3848
+ }
3849
+ async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
3850
+ if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
3851
+ let failed = false;
3852
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
3853
+ const index = (startIndex + attempt) % registrations.length;
3854
+ const registration = registrations[index];
3855
+ if (registration === void 0) continue;
3856
+ try {
3857
+ if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
3858
+ } catch (error) {
3859
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
3860
+ failed = true;
3861
+ }
3862
+ }
3863
+ return { captured: false, nextIndex: startIndex, failed };
3864
+ }
3865
+ async function openHostUsageTranscriptCursor(input) {
3866
+ const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
3867
+ let source;
3868
+ try {
3869
+ source = await readHostUsageTranscriptSource(() => input.inspect(handle));
3870
+ } catch (error) {
3871
+ await handle.close().catch(() => void 0);
3872
+ throw error;
3873
+ }
3874
+ const sourceFileRef2 = hostUsageSourceFileReference(input.source_kind, input.host_source_ref, input.host_session_ref, source.device, source.inode);
3875
+ let prepared;
3876
+ try {
3877
+ 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);
3878
+ } catch (error) {
3879
+ await handle.close().catch(() => void 0);
3880
+ throw error;
3881
+ }
3882
+ if (prepared === null) {
3883
+ await handle.close();
3884
+ return null;
3885
+ }
3886
+ return { handle, source, source_file_ref: sourceFileRef2, ...prepared };
3887
+ }
3888
+ async function readHostUsageTranscriptChunk(handle, offset, size, skippingOversizedLine) {
3889
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(size) || size < offset) throw new TypeError("Host usage transcript range is invalid.");
3890
+ if (size === offset) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
3891
+ if (skippingOversizedLine) return await resumeOversizedLine(handle, offset, size);
3892
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
3893
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
3894
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
3895
+ const chunk = bytes.subarray(0, bytesRead);
3896
+ return completeChunk(chunk, offset);
3897
+ }
3898
+ async function resumeOversizedLine(handle, offset, size) {
3899
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
3900
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
3901
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
3902
+ const chunk = bytes.subarray(0, bytesRead);
3903
+ const delimiter = chunk.indexOf(10);
3904
+ if (delimiter < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
3905
+ return completeChunk(chunk.subarray(delimiter + 1), offset + delimiter + 1);
3906
+ }
3907
+ function completeChunk(chunk, offset) {
3908
+ const parsed = completeLinePrefix(chunk, offset);
3909
+ const oversizedRows = parsed.oversizedRows + (parsed.incompleteOversized ? 1 : 0);
3910
+ const endOffset = parsed.incompleteOversized ? offset + chunk.length : parsed.endOffset;
3911
+ return { lines: parsed.lines, end_offset: endOffset, skipping_oversized_line: parsed.incompleteOversized, oversized_rows: oversizedRows };
3912
+ }
3913
+ function completeLinePrefix(bytes, baseOffset) {
3914
+ const lines = [];
3915
+ let lineStart = 0;
3916
+ let endOffset = baseOffset;
3917
+ let oversizedRows = 0;
3918
+ let rowCount = 0;
3919
+ for (let index = 0; index < bytes.length; index += 1) {
3920
+ if (bytes[index] !== 10) continue;
3921
+ const line = bytes.subarray(lineStart, index);
3922
+ if (line.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES) oversizedRows += 1;
3923
+ else lines.push(line);
3924
+ lineStart = index + 1;
3925
+ endOffset = baseOffset + lineStart;
3926
+ rowCount += 1;
3927
+ if (rowCount >= HOST_USAGE_FACTS_SCAN_MAX_ROWS) return { lines, endOffset, oversizedRows, incompleteOversized: false };
3928
+ }
3929
+ const incomplete = bytes.subarray(lineStart);
3930
+ return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
3931
+ }
3932
+
3933
+ // host/relay/src/host-registration-state.ts
3934
+ import { constants as constants4 } from "node:fs";
3935
+ import { dirname as dirname4 } from "node:path";
3936
+
3937
+ // host/runtime-source-paths.ts
3938
+ import { createHash as createHash7 } from "node:crypto";
3939
+ import { posix as posix2, win32 as win323 } from "node:path";
3940
+
3941
+ // host/absolute-path.ts
3942
+ import { posix, win32 as win322 } from "node:path";
3943
+ function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
3944
+ const pathApi = flavor === "win32" || flavor === "windows" ? win322 : posix;
3945
+ return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
3946
+ }
3947
+
3948
+ // host/unix-socket-path.ts
3949
+ var PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES = 103;
3950
+
3951
+ // host/runtime-source-paths.ts
3952
+ var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
3953
+ function hostSourceUuid(sourceRef) {
3954
+ return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
3955
+ }
3956
+ var DARWIN_UID_MAX = 4294967295;
3957
+ var MACOS_HOST_RELAY_IPC_ROOT_PREFIX = "/private/tmp/ceal-host-";
3958
+ function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
3959
+ if (!Number.isInteger(uid) || uid < 0 || uid > DARWIN_UID_MAX) throw new TypeError("Host runtime effective user identity is invalid.");
3960
+ return `${MACOS_HOST_RELAY_IPC_ROOT_PREFIX}${uid}`;
3961
+ }
3962
+ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
3963
+ const sourceId = hostSourceUuid(sourceRef);
3964
+ if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
3965
+ const path = platform === "win32" ? win323 : posix2;
3966
+ const sourcesRoot = path.join(stateRoot, "sources");
3967
+ const sourceRoot = path.join(sourcesRoot, sourceId);
3968
+ const runtimeRoot = path.join(stateRoot, "run");
3969
+ const rootedEndpoint = path.join(runtimeRoot, `${sourceId}.sock`);
3970
+ const endpoint = projectRelayEndpoint(stateRoot, sourceRef, rootedEndpoint, platform, uid);
3971
+ 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 };
3972
+ }
3973
+ function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
3974
+ if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
3975
+ const digest2 = createHash7("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
3976
+ return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix2.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
3977
+ }
3978
+ function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
3979
+ const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
3980
+ 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.");
3981
+ return paths.endpoint;
3982
+ }
3983
+
3984
+ // host/relay/src/host-registration-state.ts
3985
+ var HOST_REGISTRATION_STATE_SCHEMA = "ceal.host_registration_state.v1";
3986
+ var HOST_REGISTRATION_STATE_KEYS = Object.freeze([
3987
+ "credential_generation",
3988
+ "gateway_request_origin",
3989
+ "host_access_token",
3990
+ "host_installation_ref",
3991
+ "host_source_ref",
3992
+ "registration_attempt_ref",
3993
+ "schema_version",
3994
+ "status"
3995
+ ]);
3996
+ var HOST_REGISTRATION_STATE_MAX_BYTES = 65536;
3997
+ var HostRegistrationStateError = class extends Error {
3998
+ name = "HostRegistrationStateError";
3999
+ code = "credential";
4000
+ };
4001
+ async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
4002
+ let raw;
4003
+ try {
4004
+ await assertPrivateRegistrationDirectory(dirname4(path), platform, custody);
4005
+ raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
4006
+ } catch (error) {
4007
+ throw registrationReadError(error);
4008
+ }
4009
+ 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}`)}.`);
4010
+ let value;
4011
+ try {
4012
+ value = JSON.parse(raw);
4013
+ } catch {
4014
+ throw new HostRegistrationStateError("Host registration state is invalid.");
4015
+ }
4016
+ return decodeHostRegistrationAuthority(value, expectedHostSourceRef);
4017
+ }
4018
+ async function readWindowsRegistration(path, custody) {
4019
+ const bytes = await readPrivateFileWithSecurefs(path, HOST_REGISTRATION_STATE_MAX_BYTES, custody);
4020
+ try {
4021
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
4022
+ } catch {
4023
+ throw new HostRegistrationStateError("Host registration state is invalid.");
4024
+ }
4025
+ }
4026
+ async function readPosixRegistration(path, platform, custody) {
4027
+ const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform, custody);
4028
+ try {
4029
+ const stats = await handle.stat();
4030
+ 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.");
4031
+ return await handle.readFile("utf8");
4032
+ } finally {
4033
+ await handle.close();
4034
+ }
4035
+ }
4036
+ function registrationReadError(error) {
4037
+ if (error instanceof HostRegistrationStateError) return error;
4038
+ if (error instanceof SecureFileCustodyError && error.reason === "not_private") return new HostRegistrationStateError("Host registration file is not private to its owner.");
4039
+ return new HostRegistrationStateError("Host registration file is unavailable.");
4040
+ }
4041
+ function decodeHostRegistrationAuthority(value, expectedHostSourceRef) {
4042
+ const keys = HOST_REGISTRATION_STATE_KEYS;
4043
+ const fieldCount = record2(value) ? Object.keys(value).length : 0;
4044
+ const missing = record2(value) ? keys.filter((key) => !Object.hasOwn(value, key)).length : keys.length;
4045
+ 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" }])}.`);
4046
+ 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>" }])}.`);
4047
+ 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" }])}.`);
4048
+ 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")}.`);
4049
+ return { gateway_request_origin: value.gateway_request_origin, host_access_token: value.host_access_token };
4050
+ }
4051
+ function validRegistrationIdentity(value, expectedHostSourceRef) {
4052
+ 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;
4053
+ }
4054
+ function validRegistrationCredential(value) {
4055
+ return Number.isSafeInteger(value.credential_generation) && Number(value.credential_generation) > 0 && validHostAccessToken(value.host_access_token);
4056
+ }
4057
+ function validHostAccessToken(value) {
4058
+ return typeof value === "string" && CEAL_HOST_ACCESS_TOKEN_PATTERN.test(value);
4059
+ }
4060
+ function validGatewayOrigin(value) {
4061
+ try {
4062
+ if (typeof value !== "string" || /\s|\0/u.test(value)) return false;
4063
+ const parsed = new URL(value);
4064
+ const hostname = parsed.hostname.toLowerCase().replace(/\.+$/u, "");
4065
+ return hostname !== "" && validGatewayPort(parsed.port) && (loopbackHttpOrigin(parsed, hostname) || parsed.protocol === "https:") && cleanOriginPath(parsed) && bareOriginSuffix(value);
4066
+ } catch {
4067
+ return false;
4068
+ }
4069
+ }
4070
+ function loopbackHttpOrigin(parsed, hostname) {
4071
+ return parsed.protocol === "http:" && parsed.port !== "" && (hostname === "127.0.0.1" || hostname === "[::1]");
4072
+ }
4073
+ function validGatewayPort(port) {
4074
+ if (port === "") return true;
4075
+ const numeric = Number(port);
4076
+ return Number.isInteger(numeric) && numeric >= 1 && numeric <= 65535;
4077
+ }
4078
+ function cleanOriginPath(parsed) {
4079
+ return parsed.username === "" && parsed.password === "" && parsed.pathname === "/" && parsed.search === "" && parsed.hash === "";
4080
+ }
4081
+ function bareOriginSuffix(value) {
4082
+ const schemeEnd = value.indexOf("://");
4083
+ const authority = schemeEnd < 0 ? "" : value.slice(schemeEnd + 3);
4084
+ const suffixOffset = authority.search(/[\\/?#]/u);
4085
+ const rawSuffix = suffixOffset < 0 ? "" : authority.slice(suffixOffset);
4086
+ return rawSuffix === "" || rawSuffix === "/";
4087
+ }
4088
+ async function assertPrivateRegistrationDirectory(path, platform, custody) {
4089
+ if (!await isPrivateDirectory(path, platform, custody)) throw new HostRegistrationStateError("Host registration directory is not private to its owner.");
4090
+ }
4091
+ function record2(value) {
4092
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4093
+ }
4094
+
4095
+ // host/abortable-wait.ts
4096
+ function waitForAbort(signal, milliseconds) {
4097
+ if (signal.aborted) return Promise.resolve();
4098
+ return new Promise((resolve2) => {
4099
+ const timer = setTimeout(finish, milliseconds);
4100
+ function finish() {
4101
+ clearTimeout(timer);
4102
+ signal.removeEventListener("abort", finish);
4103
+ resolve2();
4104
+ }
4105
+ signal.addEventListener("abort", finish, { once: true });
4106
+ });
4107
+ }
4108
+
4109
+ // host/service-log.ts
4110
+ import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
4111
+ import { dirname as dirname5, isAbsolute as isAbsolute2, posix as posix3, win32 as win324 } from "node:path";
4112
+
4113
+ // host/service-log-delivery.ts
4114
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
4115
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
4116
+ setImmediate(flush);
4117
+ }, onDeliveryGap = () => void 0) {
4118
+ const pending = [];
4119
+ const highWaterMark = stream.writableHighWaterMark;
4120
+ const byteBudget = highWaterMark + highWaterMark;
4121
+ let pendingBytes = 0;
4122
+ let droppedLines = 0;
4123
+ let flushScheduled = false;
4124
+ let waitingForDrain = false;
4125
+ let closed = !stream.writable;
4126
+ function stop() {
4127
+ if (closed) return;
4128
+ closed = true;
4129
+ pending.length = 0;
4130
+ pendingBytes = 0;
4131
+ stream.off("drain", onDrain);
4132
+ stream.off("close", onTerminal);
4133
+ stream.off("finish", onTerminal);
4134
+ stream.off("error", onError);
4135
+ }
4136
+ function onTerminal() {
4137
+ stop();
4138
+ }
4139
+ function onError() {
4140
+ stop();
4141
+ }
4142
+ function onDrain() {
4143
+ waitingForDrain = false;
4144
+ scheduleFlush();
4145
+ }
4146
+ function scheduleFlush() {
4147
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
4148
+ flushScheduled = true;
4149
+ let scheduling = true;
4150
+ let invokedSynchronously = false;
4151
+ try {
4152
+ schedule(() => {
4153
+ if (scheduling) {
4154
+ invokedSynchronously = true;
4155
+ return;
4156
+ }
4157
+ flushScheduled = false;
4158
+ flush();
4159
+ });
4160
+ } catch {
4161
+ flushScheduled = false;
4162
+ stop();
4163
+ return;
4164
+ }
4165
+ scheduling = false;
4166
+ if (invokedSynchronously) {
4167
+ flushScheduled = false;
4168
+ stop();
4169
+ }
4170
+ }
4171
+ function flush() {
4172
+ if (closed) return;
4173
+ if (!stream.writable) {
4174
+ stop();
4175
+ return;
4176
+ }
4177
+ while (pending.length > 0) {
4178
+ if (stream.writableNeedDrain) {
4179
+ if (!waitingForDrain) {
4180
+ waitingForDrain = true;
4181
+ stream.once("drain", onDrain);
4182
+ }
4183
+ return;
4184
+ }
4185
+ const next = pending.shift();
4186
+ if (next === void 0) return;
4187
+ pendingBytes -= next.bytes;
4188
+ let accepted;
4189
+ try {
4190
+ accepted = stream.write(next.line);
4191
+ } catch {
4192
+ stop();
4193
+ return;
4194
+ }
4195
+ if (!accepted) {
4196
+ waitingForDrain = true;
4197
+ stream.once("drain", onDrain);
4198
+ return;
4199
+ }
4200
+ }
4201
+ if (droppedLines > 0) {
4202
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
4203
+ `;
4204
+ droppedLines = 0;
4205
+ try {
4206
+ onDeliveryGap(line);
4207
+ } catch {
4208
+ }
4209
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
4210
+ pendingBytes += Buffer.byteLength(line, "utf8");
4211
+ flush();
4212
+ }
4213
+ }
4214
+ stream.on("close", onTerminal);
4215
+ stream.on("finish", onTerminal);
4216
+ stream.on("error", onError);
4217
+ return (line) => {
4218
+ if (closed) return;
4219
+ const bytes = Buffer.byteLength(line, "utf8");
4220
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
4221
+ droppedLines += 1;
4222
+ scheduleFlush();
4223
+ return;
4224
+ }
4225
+ pending.push({ line, bytes });
4226
+ pendingBytes += bytes;
4227
+ scheduleFlush();
4228
+ };
4229
+ }
4230
+
4231
+ // host/invocation-authentication-client-command.ts
4232
+ var DOCTOR_FLAGS = Object.freeze({
4233
+ "--expected-sha256": "expected_sha256",
4234
+ "--expected-source-commit": "expected_source_commit",
4235
+ "--expected-instance-ref": "expected_instance_ref"
4236
+ });
4237
+
4238
+ // host/service-log.ts
4239
+ var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
4240
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
4241
+ void persistHostServiceLogLine(line);
4242
+ });
4243
+ function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
4244
+ const details = diagnosticDetails(event, failure_kind, cause);
4245
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
4246
+ `;
4247
+ try {
4248
+ (sink ?? defaultHostServiceDiagnosticSink)(line);
4249
+ } catch {
4250
+ }
4251
+ }
4252
+ function diagnosticDetails(event, failureKind, cause) {
4253
+ if (event === "watcher_scan_failed") return {
4254
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
4255
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
4256
+ };
4257
+ return validDiagnosticCause(cause, event) ? { cause } : {};
2702
4258
  }
2703
- function directorySyncUnsupported(error) {
2704
- return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
4259
+ function validDiagnosticCause(cause, event) {
4260
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
2705
4261
  }
2706
- function errorCode(error) {
2707
- return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
4262
+ function defaultHostServiceDiagnosticSink(line) {
4263
+ writeHostServiceLogLine(line);
4264
+ }
4265
+ var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
4266
+ function writeHostServiceLogLine(line, environment = process.env) {
4267
+ void persistHostServiceLogLine(line, environment);
4268
+ defaultHostServiceLogDelivery(line);
4269
+ }
4270
+ async function persistHostServiceLogLine(line, environment = process.env) {
4271
+ if (process.platform !== "win32") return;
4272
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
4273
+ if (path === void 0 || !win324.isAbsolute(path) || win324.normalize(path) !== path) return;
4274
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
4275
+ }
4276
+ async function appendHostServiceLogLine(path, line) {
4277
+ if (!isAbsolute2(path)) return;
4278
+ await ensureHostServiceLogDirectory(path);
4279
+ await appendFile(path, line);
4280
+ }
4281
+ var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
4282
+ var hostServiceLogDirectories = /* @__PURE__ */ new Map();
4283
+ function ensureHostServiceLogDirectory(path) {
4284
+ const directory = dirname5(path);
4285
+ const existing = hostServiceLogDirectories.get(directory);
4286
+ if (existing !== void 0) return existing;
4287
+ const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
4288
+ hostServiceLogDirectories.delete(directory);
4289
+ throw error;
4290
+ });
4291
+ hostServiceLogDirectories.set(directory, pending);
4292
+ return pending;
4293
+ }
4294
+
4295
+ // host/relay/src/host-usage-facts-uploader.ts
4296
+ var HostUsageFactsUploader = class {
4297
+ options;
4298
+ store;
4299
+ constructor(options) {
4300
+ if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
4301
+ this.options = options;
4302
+ this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
4303
+ }
4304
+ async close() {
4305
+ await this.store.close();
4306
+ }
4307
+ async uploadOne(signal) {
4308
+ const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4309
+ if (candidate === null) return false;
4310
+ 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);
4311
+ const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4312
+ const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4313
+ const response2 = await (this.options.fetch ?? fetch)(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4314
+ method: "POST",
4315
+ headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4316
+ body: JSON.stringify(candidate.batch),
4317
+ signal: requestSignal
4318
+ });
4319
+ if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
4320
+ await response2.body?.cancel().catch(() => void 0);
4321
+ throw new Error("Gateway did not acknowledge the Host usage facts batch.");
4322
+ }
4323
+ await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
4324
+ return true;
4325
+ }
4326
+ };
4327
+ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4328
+ const uploader = new HostUsageFactsUploader(options);
4329
+ let delay = 500;
4330
+ let failures = 0;
4331
+ try {
4332
+ while (!signal.aborted) {
4333
+ try {
4334
+ await options.capture_next?.();
4335
+ } catch {
4336
+ writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
4337
+ }
4338
+ if (signal.aborted) return;
4339
+ try {
4340
+ const uploaded = await uploader.uploadOne(signal);
4341
+ failures = 0;
4342
+ delay = uploaded ? 100 : 1e3;
4343
+ } catch {
4344
+ if (signal.aborted) return;
4345
+ failures += 1;
4346
+ delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
4347
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4348
+ }
4349
+ if (!signal.aborted) await wait(signal, delay);
4350
+ }
4351
+ } finally {
4352
+ await uploader.close().catch(() => void 0);
4353
+ }
2708
4354
  }
2709
4355
 
2710
4356
  // host/relay/src/relay-quarantine-store.ts
@@ -2722,18 +4368,9 @@ var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2722
4368
 
2723
4369
  // host/relay/src/relay-ipc.ts
2724
4370
  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
4371
 
2736
4372
  // host/claude/src/claude-invocation-context.ts
4373
+ import { isAbsolute as isAbsolute3 } from "node:path";
2737
4374
  function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
2738
4375
  return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
2739
4376
  }
@@ -2744,7 +4381,7 @@ function validateClaudeHostInvocationContext(value) {
2744
4381
  validateContextTimes(value);
2745
4382
  }
2746
4383
  function contextShape(value) {
2747
- return record2(value) && value.schema_version === CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION && hasHostInvocationContextKeys(value, ["working_directory", "turn_generation_ref"]);
4384
+ return record3(value) && value.schema_version === CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION && hasHostInvocationContextKeys(value, ["working_directory", "turn_generation_ref"]);
2748
4385
  }
2749
4386
  function validateIdentity(value) {
2750
4387
  if (!validIdentity(value)) throw new ClaudeHostError("storage", "Claude Host invocation identity is malformed.");
@@ -2756,13 +4393,13 @@ function validateContextTimes(value) {
2756
4393
  if (!timestamp(value.expires_at) || !optionalDirectory(value.working_directory)) throw new ClaudeHostError("storage", "Claude Host invocation context is malformed.");
2757
4394
  }
2758
4395
  function validIdentity(value) {
2759
- return record2(value) && hasHostInvocationIdentityKeys(value) && [value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2);
4396
+ return record3(value) && hasHostInvocationIdentityKeys(value) && [value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2);
2760
4397
  }
2761
4398
  function optionalSafeRef(value) {
2762
4399
  return value === void 0 || safeRef2(value);
2763
4400
  }
2764
4401
  function optionalDirectory(value) {
2765
- return value === void 0 || typeof value === "string" && value.startsWith("/") && !value.includes("\0") && value.length <= 4096;
4402
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && !value.includes("\0") && value.length <= 4096;
2766
4403
  }
2767
4404
  function safeRef2(value) {
2768
4405
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
@@ -2770,7 +4407,7 @@ function safeRef2(value) {
2770
4407
  function timestamp(value) {
2771
4408
  return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
2772
4409
  }
2773
- function record2(value) {
4410
+ function record3(value) {
2774
4411
  return value !== null && typeof value === "object" && !Array.isArray(value);
2775
4412
  }
2776
4413
 
@@ -2787,18 +4424,18 @@ var ClaudeOutboxStore = class {
2787
4424
  activeContexts;
2788
4425
  turnSelections;
2789
4426
  constructor(directory) {
2790
- if (!directory.startsWith("/")) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
4427
+ if (!isAbsolute4(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
2791
4428
  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");
4429
+ this.envelopes = join4(directory, "envelopes");
4430
+ this.sessions = join4(directory, "sessions");
4431
+ this.registrations = join4(directory, "transcript-registrations");
4432
+ this.cursors = join4(directory, "transcript-cursors");
4433
+ this.activeContexts = join4(directory, "active-contexts");
4434
+ this.turnSelections = join4(directory, "turn-selections");
2798
4435
  }
2799
4436
  async prepare() {
2800
4437
  for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
2801
- await mkdir2(path, { recursive: true, mode: 448 });
4438
+ await mkdir4(path, { recursive: true, mode: 448 });
2802
4439
  }
2803
4440
  }
2804
4441
  async activateInvocationContext(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
@@ -2844,7 +4481,7 @@ var ClaudeOutboxStore = class {
2844
4481
  for (const name of await readdir(this.activeContexts)) {
2845
4482
  if (!name.endsWith(".json")) continue;
2846
4483
  try {
2847
- const value = JSON.parse(await readFile(join2(this.activeContexts, name), "utf8"));
4484
+ const value = JSON.parse(await readFile(join4(this.activeContexts, name), "utf8"));
2848
4485
  validateClaudeHostInvocationContext(value);
2849
4486
  if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
2850
4487
  } catch {
@@ -2864,7 +4501,7 @@ var ClaudeOutboxStore = class {
2864
4501
  for (const name of await readdir(this.envelopes)) {
2865
4502
  if (!name.endsWith(".json")) continue;
2866
4503
  try {
2867
- const value = JSON.parse(await readFile(join2(this.envelopes, name), "utf8"));
4504
+ const value = JSON.parse(await readFile(join4(this.envelopes, name), "utf8"));
2868
4505
  validateEnvelope(value);
2869
4506
  entries.push(value);
2870
4507
  } catch {
@@ -2877,7 +4514,7 @@ var ClaudeOutboxStore = class {
2877
4514
  async removeEnvelope(entry) {
2878
4515
  validateEnvelope(entry);
2879
4516
  try {
2880
- await unlink2(this.envelopePath(entry.submission_ref));
4517
+ await unlink3(this.envelopePath(entry.submission_ref));
2881
4518
  } catch (error) {
2882
4519
  if (code(error) !== "ENOENT") throw error;
2883
4520
  }
@@ -2885,13 +4522,13 @@ var ClaudeOutboxStore = class {
2885
4522
  async saveSession(snapshot) {
2886
4523
  validateSession(snapshot);
2887
4524
  await this.prepare();
2888
- await durableAtomicReplace(join2(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
4525
+ await durableAtomicReplace(join4(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
2889
4526
  }
2890
4527
  async readSession(sourceRef, sessionRef) {
2891
4528
  if (!SAFE_REF2.test(sourceRef) || !SAFE_REF2.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
2892
4529
  await this.prepare();
2893
4530
  try {
2894
- const value = JSON.parse(await readFile(join2(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
4531
+ const value = JSON.parse(await readFile(join4(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
2895
4532
  validateSession(value);
2896
4533
  return value;
2897
4534
  } catch (error) {
@@ -2926,7 +4563,7 @@ var ClaudeOutboxStore = class {
2926
4563
  for (const name of await readdir(this.registrations)) {
2927
4564
  if (!name.endsWith(".json")) continue;
2928
4565
  try {
2929
- const value = JSON.parse(await readFile(join2(this.registrations, name), "utf8"));
4566
+ const value = JSON.parse(await readFile(join4(this.registrations, name), "utf8"));
2930
4567
  validateRegistration(value);
2931
4568
  registrations.push(value);
2932
4569
  } catch {
@@ -2964,16 +4601,16 @@ var ClaudeOutboxStore = class {
2964
4601
  await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
2965
4602
  }
2966
4603
  envelopePath(ref) {
2967
- return join2(this.envelopes, `${cealRequestSha256(ref)}.json`);
4604
+ return join4(this.envelopes, `${cealRequestSha256(ref)}.json`);
2968
4605
  }
2969
4606
  registrationPath(sourceRef, sessionRef) {
2970
- return join2(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4607
+ return join4(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
2971
4608
  }
2972
4609
  turnSelectionPath(sourceRef, sessionRef) {
2973
- return join2(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4610
+ return join4(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
2974
4611
  }
2975
4612
  cursorPath(sourceRef, sessionRef) {
2976
- return join2(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4613
+ return join4(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
2977
4614
  }
2978
4615
  async readRegistrationFile(path) {
2979
4616
  try {
@@ -2987,13 +4624,13 @@ var ClaudeOutboxStore = class {
2987
4624
  }
2988
4625
  async removeStateFile(path) {
2989
4626
  try {
2990
- await unlink2(path);
4627
+ await unlink3(path);
2991
4628
  } catch (error) {
2992
4629
  if (code(error) !== "ENOENT") throw error;
2993
4630
  }
2994
4631
  }
2995
4632
  activeContextPath(identity) {
2996
- return join2(this.activeContexts, `${invocationContextKey(identity)}.json`);
4633
+ return join4(this.activeContexts, `${invocationContextKey(identity)}.json`);
2997
4634
  }
2998
4635
  };
2999
4636
  function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
@@ -3016,15 +4653,15 @@ function safeRef3(value) {
3016
4653
  function timestamp2(value) {
3017
4654
  return typeof value === "string" && Number.isFinite(Date.parse(value));
3018
4655
  }
3019
- function record3(value) {
4656
+ function record4(value) {
3020
4657
  return value !== null && typeof value === "object" && !Array.isArray(value);
3021
4658
  }
3022
4659
  function code(error) {
3023
- return record3(error) && typeof error.code === "string" ? error.code : null;
4660
+ return record4(error) && typeof error.code === "string" ? error.code : null;
3024
4661
  }
3025
4662
  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"])) {
4663
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude outbox entry is malformed.");
4664
+ if (!sameKeys2(value, ["schema_version", "identity", "host_input_ref", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"])) {
3028
4665
  throw new ClaudeHostError("storage", `Claude outbox entry key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the outbox entry key set")}).`);
3029
4666
  }
3030
4667
  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 +4684,8 @@ function validateEnvelopeObservations(value) {
3047
4684
  }
3048
4685
  }
3049
4686
  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"])) {
4687
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude session snapshot is malformed.");
4688
+ if (!sameKeys2(value, ["schema_version", "host_session_ref", "host_source_ref", "observed_at", "value", "expires_at"])) {
3052
4689
  throw new ClaudeHostError("storage", `Claude session snapshot key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the session snapshot key set")}).`);
3053
4690
  }
3054
4691
  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 +4694,8 @@ function validateSession(value) {
3057
4694
  }
3058
4695
  }
3059
4696
  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"])) {
4697
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
4698
+ if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "claude_session_id", "transcript_path", "registered_at", "expires_at"], ["cwd"])) {
3062
4699
  throw new ClaudeHostError("storage", `Claude transcript registration key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the registration key set")}).`);
3063
4700
  }
3064
4701
  if (value.schema_version !== CLAUDE_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
@@ -3069,7 +4706,7 @@ function validateRegistration(value) {
3069
4706
  if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
3070
4707
  }
3071
4708
  function validateRegistrationPaths(cwd, transcriptPath) {
3072
- if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
4709
+ if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute4(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
3073
4710
  throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
3074
4711
  }
3075
4712
  if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
@@ -3077,14 +4714,21 @@ function validateRegistrationPaths(cwd, transcriptPath) {
3077
4714
  }
3078
4715
  }
3079
4716
  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"])) {
4717
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
4718
+ 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
4719
  throw new ClaudeHostError("storage", "Claude transcript cursor key set is malformed.");
3083
4720
  }
3084
4721
  if (value.schema_version !== CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
3085
4722
  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
4723
  if (typeof value.transcript_path !== "string" || value.transcript_path.length === 0) throw new ClaudeHostError("storage", "Claude transcript cursor path is malformed.");
3087
4724
  validateCursorPosition(value);
4725
+ if (value.human_message_window !== void 0) {
4726
+ try {
4727
+ decodeCealHostInvocationHumanMessageWindow(value.human_message_window);
4728
+ } catch {
4729
+ throw new ClaudeHostError("storage", "Claude transcript human-message projection is malformed.");
4730
+ }
4731
+ }
3088
4732
  validateCursorTurn(value.open_turn, value.unattributed, value.session_observed);
3089
4733
  validateSubagentCursors(value.subagents);
3090
4734
  if (value.reason !== void 0 && !isHostTranscriptCursorReason(value.reason)) throw new ClaudeHostError("storage", "Claude transcript cursor reason is malformed.");
@@ -3102,13 +4746,13 @@ function validateCursorTurn(openTurn, unattributed, sessionObserved) {
3102
4746
  if (sessionObserved !== void 0 && typeof sessionObserved !== "boolean") throw new ClaudeHostError("storage", "Claude transcript cursor session marker is malformed.");
3103
4747
  }
3104
4748
  function validateSubagentCursors(value) {
3105
- if (!record3(value)) throw new ClaudeHostError("storage", "Claude transcript subagent cursors are malformed.");
4749
+ if (!record4(value)) throw new ClaudeHostError("storage", "Claude transcript subagent cursors are malformed.");
3106
4750
  for (const [name, entry] of Object.entries(value)) validateSubagentEntry(name, entry);
3107
4751
  }
3108
4752
  function validateSubagentEntry(name, entry) {
3109
4753
  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
4754
  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.");
4755
+ 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
4756
  validateSubagentIdentity(entry);
3113
4757
  }
3114
4758
  function validateSubagentIdentity(entry) {
@@ -3124,7 +4768,7 @@ function validCursorPosition(value) {
3124
4768
  return nonNegativeInteger(value.offset) && nonNegativeInteger(value.anchor_start) && typeof value.anchor_sha256 === "string" && /^[a-f0-9]{64}$/u.test(value.anchor_sha256);
3125
4769
  }
3126
4770
  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;
4771
+ 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
4772
  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
4773
  if (!timestamp2(value.started_at) || !timestamp2(value.last_observed_at)) return false;
3130
4774
  if (!validMessageIds(value.message_ids)) return false;
@@ -3137,30 +4781,30 @@ function validMessageIds(value) {
3137
4781
  return new Set(value).size === value.length;
3138
4782
  }
3139
4783
  function validUnattributed(value) {
3140
- if (!record3(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output", "message_ids", "last_observed_at"])) return false;
4784
+ if (!record4(value) || !sameKeys2(value, ["input", "cached_input", "cache_write_input", "output", "message_ids", "last_observed_at"])) return false;
3141
4785
  if (!validMessageIds(value.message_ids) || value.message_ids.length === 0) return false;
3142
4786
  if (!timestamp2(value.last_observed_at)) return false;
3143
4787
  return validTurnCounts(value);
3144
4788
  }
3145
4789
  function validTurnCounts(value) {
3146
- if (!record3(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output"])) return false;
4790
+ if (!record4(value) || !sameKeys2(value, ["input", "cached_input", "cache_write_input", "output"])) return false;
3147
4791
  return [value.input, value.cached_input, value.cache_write_input, value.output].every(nonNegativeInteger);
3148
4792
  }
3149
4793
  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))) {
4794
+ 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
4795
  throw new ClaudeHostError("storage", "Claude Host identity is malformed.");
3152
4796
  }
3153
4797
  }
3154
4798
  function nonNegativeInteger(value) {
3155
4799
  return Number.isSafeInteger(value) && Number(value) >= 0;
3156
4800
  }
3157
- function sameKeys(value, required, optional = []) {
4801
+ function sameKeys2(value, required, optional = []) {
3158
4802
  return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
3159
4803
  }
3160
4804
 
3161
4805
  // host/claude/src/claude-transcript-watcher.ts
3162
4806
  import { readdir as readdir2 } from "node:fs/promises";
3163
- import { join as join3 } from "node:path";
4807
+ import { join as join5 } from "node:path";
3164
4808
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
3165
4809
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3166
4810
  store;
@@ -3210,6 +4854,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3210
4854
  offset: 0,
3211
4855
  anchor_start: 0,
3212
4856
  anchor_sha256: this.sha(Buffer.alloc(0)),
4857
+ human_message_window: { messages: [], truncated: false },
3213
4858
  subagents: {},
3214
4859
  status: "active",
3215
4860
  updated_at: this.stamp()
@@ -3231,33 +4876,64 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3231
4876
  const cursor = existing ?? this.initialCursor(registration);
3232
4877
  if (cursor.device === void 0) {
3233
4878
  if (cursor.offset !== 0) return await this.quarantineStored(cursor, device, inode, "transcript_replaced");
3234
- return { ...cursor, device, inode };
4879
+ return { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
3235
4880
  }
3236
4881
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
3237
4882
  if (reason !== null) return await this.quarantineStored(cursor, device, inode, reason);
3238
- return cursor;
4883
+ if (cursor.human_message_window !== void 0) return cursor;
4884
+ return { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) };
4885
+ }
4886
+ async readHumanMessageProjection(registration, handle, watermark) {
4887
+ let offset = 0;
4888
+ let window = { messages: [], truncated: false };
4889
+ while (offset < watermark) {
4890
+ const complete = await this.readChunk(handle, offset, watermark);
4891
+ if (complete === "empty" || complete === "partial") throw new ClaudeHostError("payload_rejected", "Claude transcript projection prefix is incomplete.", "malformed_line");
4892
+ for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
4893
+ let row;
4894
+ try {
4895
+ row = JSON.parse(line);
4896
+ } catch {
4897
+ throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
4898
+ }
4899
+ const prompt = decodeClaudeHumanMessageRow(row, registration.claude_session_id);
4900
+ if (prompt !== null) window = mergeHostInvocationHumanMessageWindow(window, [{
4901
+ host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, prompt.turnId),
4902
+ host_input_ref: claudeLocalInputRef(registration.claude_session_id, prompt.turnId),
4903
+ text: prompt.content
4904
+ }]);
4905
+ }
4906
+ offset += complete.length;
4907
+ }
4908
+ if (offset !== watermark) throw new ClaudeHostError("payload_rejected", "Claude transcript projection prefix does not match its cursor boundary.", "malformed_line");
4909
+ return window;
3239
4910
  }
3240
4911
  async consumeMainChunk(registration, complete, draft) {
3241
4912
  for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3242
4913
  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.");
4914
+ const record5 = parseTranscriptLine(line);
4915
+ if (record5 === null) throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
4916
+ if (isUserTurnLine(record5)) await this.openTurn(registration, draft, record5);
4917
+ else if (isAssistantUsageLine(record5)) this.accumulateUsage(draft, toUsage(record5.uuid, record5.timestamp, record5.message.usage));
4918
+ else if (isAssistantLine(record5) && record5.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude transcript usage is malformed.");
3248
4919
  else {
3249
- const queued = decodeClaudeQueuedPromptRow(record4, registration.claude_session_id);
4920
+ const queued = decodeClaudeQueuedPromptRow(record5, registration.claude_session_id);
3250
4921
  if (queued !== null) await this.openQueuedTurn(registration, draft, queued);
3251
4922
  }
3252
4923
  }
3253
4924
  }
3254
- async openTurn(registration, draft, record4) {
3255
- await this.openPromptTurn(registration, draft, { uuid: record4.uuid, timestamp: record4.timestamp, content: record4.message.content });
4925
+ async openTurn(registration, draft, record5) {
4926
+ await this.openPromptTurn(registration, draft, { uuid: record5.uuid, timestamp: record5.timestamp, content: record5.message.content });
3256
4927
  }
3257
4928
  async openQueuedTurn(registration, draft, queued) {
3258
4929
  await this.openPromptTurn(registration, draft, { uuid: queued.turnId, timestamp: queued.timestamp, content: queued.content });
3259
4930
  }
3260
4931
  async openPromptTurn(registration, draft, prompt) {
4932
+ draft.human_message_window = mergeHostInvocationHumanMessageWindow(draft.human_message_window, [{
4933
+ host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, prompt.uuid),
4934
+ host_input_ref: claudeLocalInputRef(registration.claude_session_id, prompt.uuid),
4935
+ text: prompt.content
4936
+ }]);
3261
4937
  await this.closeTurn(registration, draft, prompt.timestamp);
3262
4938
  const sessionRef = registration.host_session_ref;
3263
4939
  const turnRef = claudeLocalTurnRef(registration.claude_session_id, prompt.uuid);
@@ -3275,7 +4951,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3275
4951
  }
3276
4952
  await this.persistOpenedTurnContext(draft, { uuid: prompt.uuid, timestamp: prompt.timestamp, message: { content: prompt.content } }, inputRef, turnRef, promptRef, identity, observations);
3277
4953
  }
3278
- async persistOpenedTurnContext(draft, record4, inputRef, turnRef, promptRef, identity, observations) {
4954
+ async persistOpenedTurnContext(draft, record5, inputRef, turnRef, promptRef, identity, observations) {
3279
4955
  const expiresAt = this.expire(this.outboxRetentionMs);
3280
4956
  await this.store.putEnvelope({
3281
4957
  schema_version: "ceal.claude_observation_outbox.v1",
@@ -3285,27 +4961,27 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3285
4961
  observations,
3286
4962
  origin_input: true,
3287
4963
  submission_ref: submissionRef("input", turnRef, inputRef, promptRef),
3288
- created_at: record4.timestamp,
4964
+ created_at: record5.timestamp,
3289
4965
  expires_at: expiresAt
3290
4966
  });
3291
4967
  draft.enqueued += 1;
3292
4968
  await this.activateOpenedTurnContext(identity, promptRef, expiresAt);
3293
- this.setOpenedTurn(draft, record4, inputRef, turnRef, promptRef);
4969
+ this.setOpenedTurn(draft, record5, inputRef, turnRef, promptRef);
3294
4970
  }
3295
4971
  async activateOpenedTurnContext(identity, promptRef, expiresAt) {
3296
4972
  const selection = await this.store.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref);
3297
4973
  const turnGenerationRef = selection?.prompt_ref === promptRef ? selection.turn_generation_ref : void 0;
3298
4974
  await this.activateContext(identity, promptRef, turnGenerationRef, expiresAt);
3299
4975
  }
3300
- setOpenedTurn(draft, record4, inputRef, turnRef, promptRef) {
4976
+ setOpenedTurn(draft, record5, inputRef, turnRef, promptRef) {
3301
4977
  const folded = foldUnattributed(draft.unattributed);
3302
4978
  draft.open_turn = {
3303
4979
  turn_key: turnRef,
3304
- user_uuid: record4.uuid,
4980
+ user_uuid: record5.uuid,
3305
4981
  prompt_ref: promptRef,
3306
4982
  host_input_ref: inputRef,
3307
- started_at: record4.timestamp,
3308
- last_observed_at: folded?.last_observed_at ?? record4.timestamp,
4983
+ started_at: record5.timestamp,
4984
+ last_observed_at: folded?.last_observed_at ?? record5.timestamp,
3309
4985
  message_ids: folded?.message_ids ?? [],
3310
4986
  counts: folded?.counts ?? zeroCounts()
3311
4987
  };
@@ -3366,7 +5042,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3366
5042
  return consumed;
3367
5043
  }
3368
5044
  async consumeSubagentFile(draft, directory, name) {
3369
- const path = join3(directory, name);
5045
+ const path = join5(directory, name);
3370
5046
  let handle;
3371
5047
  try {
3372
5048
  handle = await openNoFollow(path);
@@ -3397,10 +5073,10 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3397
5073
  let consumed = 0;
3398
5074
  for (const line of chunk.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3399
5075
  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.");
5076
+ const record5 = parseTranscriptLine(line);
5077
+ if (record5 === null) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript line is not valid JSON.", "malformed_line");
5078
+ if (isAssistantUsageLine(record5)) this.accumulateUsage(draft, toUsage(record5.uuid, record5.timestamp, record5.message.usage));
5079
+ else if (isAssistantLine(record5) && record5.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript usage is malformed.");
3404
5080
  }
3405
5081
  return consumed;
3406
5082
  }
@@ -3459,6 +5135,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3459
5135
  offset: draft.offset,
3460
5136
  anchor_start: anchor.start,
3461
5137
  anchor_sha256: anchor.sha256,
5138
+ human_message_window: draft.human_message_window,
3462
5139
  subagents: draft.subagents,
3463
5140
  ...draft.open_turn === void 0 ? {} : { open_turn: draft.open_turn },
3464
5141
  ...draft.unattributed === void 0 ? {} : { unattributed: draft.unattributed },
@@ -3504,6 +5181,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3504
5181
  function mutableCursor(cursor) {
3505
5182
  return {
3506
5183
  offset: cursor.offset,
5184
+ human_message_window: cursor.human_message_window ?? { messages: [], truncated: false },
3507
5185
  ...cursor.open_turn === void 0 ? {} : { open_turn: cursor.open_turn },
3508
5186
  ...cursor.unattributed === void 0 ? {} : { unattributed: cursor.unattributed },
3509
5187
  subagents: Object.fromEntries(Object.entries(cursor.subagents).map(([name, entry]) => [name, { ...entry }])),
@@ -3580,32 +5258,32 @@ function parseTranscriptLine(line) {
3580
5258
  return null;
3581
5259
  }
3582
5260
  }
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 };
5261
+ function lineIdentity(record5) {
5262
+ if (typeof record5.uuid !== "string" || record5.uuid.length === 0 || record5.uuid.length > 256) return null;
5263
+ if (typeof record5.timestamp !== "string" || !Number.isFinite(Date.parse(record5.timestamp))) return null;
5264
+ return { uuid: record5.uuid, timestamp: record5.timestamp };
3587
5265
  }
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);
5266
+ function isUserTurnLine(record5) {
5267
+ if (!isTranscriptRecord(record5) || record5.type !== "user") return false;
5268
+ if (!isTranscriptRecord(record5.message) || typeof record5.message.content !== "string") return false;
5269
+ if (record5.isMeta === true && (!isTranscriptRecord(record5.origin) || typeof record5.origin.kind !== "string")) return false;
5270
+ const identity = lineIdentity(record5);
3593
5271
  if (identity === null) throw new ClaudeHostError("payload_rejected", "Claude transcript user line is malformed.");
3594
5272
  return true;
3595
5273
  }
3596
- function isAssistantLine(record4) {
3597
- return isTranscriptRecord(record4) && record4.type === "assistant" && isTranscriptRecord(record4.message);
5274
+ function isAssistantLine(record5) {
5275
+ return isTranscriptRecord(record5) && record5.type === "assistant" && isTranscriptRecord(record5.message);
3598
5276
  }
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.");
5277
+ function isAssistantUsageLine(record5) {
5278
+ if (!isTranscriptRecord(record5)) return false;
5279
+ if (!isAssistantLine(record5) || record5.message.usage === void 0) return false;
5280
+ const identity = lineIdentity(record5);
5281
+ if (identity === null || !isTranscriptRecord(record5.message.usage)) throw new ClaudeHostError("payload_rejected", "Claude transcript usage line is malformed.");
3604
5282
  return true;
3605
5283
  }
3606
5284
  function subagentsDirectory(transcriptPath) {
3607
5285
  const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
3608
- return join3(stem, "subagents");
5286
+ return join5(stem, "subagents");
3609
5287
  }
3610
5288
  function observationRef(hostSourceRef, event, identity, value) {
3611
5289
  return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
@@ -3641,23 +5319,394 @@ function isSymlinkTranscript(error) {
3641
5319
  return typeof error === "object" && error !== null && "code" in error && error.code === "ELOOP";
3642
5320
  }
3643
5321
 
3644
- // host/claude/src/claude-adapter.ts
3645
- import { createHash as createHash5, randomUUID } from "node:crypto";
5322
+ // host/claude/src/claude-usage-facts-capturer.ts
5323
+ import { createHash as createHash8 } from "node:crypto";
5324
+ import { constants as constants5 } from "node:fs";
3646
5325
  import { readdir as readdir3 } from "node:fs/promises";
3647
- import { constants as constants2 } from "node:fs";
5326
+ import { join as join6 } from "node:path";
5327
+ var ClaudeUsageFactsCapturer = class {
5328
+ sources;
5329
+ usage;
5330
+ now;
5331
+ diagnosticSink;
5332
+ nextRegistrationIndex = 0;
5333
+ nextSourceSlot = "main";
5334
+ nextSubagentIndex = 0;
5335
+ constructor(options) {
5336
+ this.sources = new ClaudeOutboxStore(options.outbox_dir);
5337
+ this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5338
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5339
+ this.diagnosticSink = options.diagnostic_sink;
5340
+ }
5341
+ async captureNext() {
5342
+ const registrations = await this.sources.listTranscriptRegistrations();
5343
+ let failed = false;
5344
+ const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
5345
+ failed = true;
5346
+ }));
5347
+ this.nextRegistrationIndex = result.nextIndex;
5348
+ if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5349
+ return result.captured;
5350
+ }
5351
+ async captureRegistration(registration, onFailure) {
5352
+ const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
5353
+ for (const source of sources) {
5354
+ let captured = false;
5355
+ try {
5356
+ captured = source === "main" ? await this.captureMain(registration) : await this.captureSubagent(registration, onFailure);
5357
+ } catch (error) {
5358
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
5359
+ onFailure();
5360
+ }
5361
+ if (captured) {
5362
+ this.nextSourceSlot = source === "main" ? "subagent" : "main";
5363
+ return true;
5364
+ }
5365
+ }
5366
+ return false;
5367
+ }
5368
+ async captureMain(registration) {
5369
+ const prepared = await openHostUsageTranscriptCursor({
5370
+ path: registration.transcript_path,
5371
+ producer: "claude",
5372
+ source_kind: "claude_transcript",
5373
+ host_source_ref: registration.host_source_ref,
5374
+ host_session_ref: registration.host_session_ref,
5375
+ source_slot: "main",
5376
+ created_at: this.stamp(),
5377
+ store: this.usage,
5378
+ inspect: ownedClaudeTranscriptFile,
5379
+ initial_cursor: initialCursor
5380
+ });
5381
+ if (prepared === null) return false;
5382
+ const { handle: main2, source: mainFile, source_file_ref: mainRef, state, cursor } = prepared;
5383
+ try {
5384
+ if (cursor.source_file_ref !== mainRef || cursor.device !== mainFile.device || cursor.inode !== mainFile.inode || mainFile.size < cursor.offset || !await anchorMatches(main2, cursor)) {
5385
+ await this.usage.commitScanTransition(state, "main", cursor, initialCursor(mainRef, mainFile.device, mainFile.inode), null, [unscopedGap("source_file_replaced")]);
5386
+ return true;
5387
+ }
5388
+ if (mainFile.size > cursor.offset) return await this.captureFile(main2, registration, "main", mainRef, cursor, mainFile.size, state);
5389
+ } finally {
5390
+ await main2.close();
5391
+ }
5392
+ return false;
5393
+ }
5394
+ async captureSubagent(registration, onFailure) {
5395
+ const names = await readSubagentNames(registration);
5396
+ let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
5397
+ if (state === null) return false;
5398
+ state = await this.usage.recoverPending(state);
5399
+ if (state.quarantined_reason !== void 0) return false;
5400
+ if (await this.retireMissingSubagent(state, names)) return true;
5401
+ if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
5402
+ return await this.recordExcessSubagentGap(state, names);
5403
+ }
5404
+ async retireMissingSubagent(state, names) {
5405
+ const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
5406
+ for (const [slot, cursor] of Object.entries(state.cursors)) {
5407
+ if (!slot.startsWith("subagent:") || liveSlots.has(slot)) continue;
5408
+ await this.usage.retireCursor(state, slot, cursor, unscopedGap("source_file_retired"));
5409
+ return true;
5410
+ }
5411
+ return false;
5412
+ }
5413
+ async recordExcessSubagentGap(state, names) {
5414
+ const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
5415
+ if (excessCount <= 0) return false;
5416
+ const mainCursor = state.cursors.main;
5417
+ if (mainCursor === void 0) return false;
5418
+ const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
5419
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
5420
+ return true;
5421
+ }
5422
+ async captureListedSubagents(registration, names, state, onFailure) {
5423
+ const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5424
+ for (let attempt = 0; attempt < candidates.length; attempt += 1) {
5425
+ const index = (this.nextSubagentIndex + attempt) % candidates.length;
5426
+ const name = candidates[index];
5427
+ if (name === void 0) continue;
5428
+ try {
5429
+ if (await this.captureSubagentFile(registration, name, state)) {
5430
+ this.nextSubagentIndex = (index + 1) % candidates.length;
5431
+ return true;
5432
+ }
5433
+ } catch (error) {
5434
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
5435
+ onFailure();
5436
+ }
5437
+ }
5438
+ return false;
5439
+ }
5440
+ async captureSubagentFile(registration, name, state) {
5441
+ let handle;
5442
+ try {
5443
+ const opened = await readHostUsageTranscriptSource(() => openNoFollow(join6(subagentsDirectory(registration.transcript_path), name), constants5.O_RDONLY));
5444
+ handle = opened;
5445
+ const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
5446
+ const sourceRef = sourceFileRef(registration, file.device, file.inode);
5447
+ const slot = subagentSlot(name);
5448
+ let current = state.cursors[slot];
5449
+ if (current === void 0) {
5450
+ current = initialCursor(sourceRef, file.device, file.inode);
5451
+ state = await this.usage.writeCursor(state, slot, current);
5452
+ }
5453
+ if (await cursorReplaced(handle, file, sourceRef, current)) {
5454
+ await this.usage.commitScanTransition(state, slot, current, initialCursor(sourceRef, file.device, file.inode), null, [unscopedGap("source_file_replaced")]);
5455
+ return true;
5456
+ }
5457
+ if (file.size > current.offset) return await this.captureFile(handle, registration, slot, sourceRef, current, file.size, state, "subagent");
5458
+ return false;
5459
+ } finally {
5460
+ await handle?.close();
5461
+ }
5462
+ }
5463
+ async captureFile(handle, registration, slot, sourceRef, before, size, state, kind = "main") {
5464
+ const chunk = await readHostUsageTranscriptChunk(handle, before.offset, size, before.skipping_oversized_line);
5465
+ if (chunk.end_offset === before.offset && chunk.lines.length === 0) return false;
5466
+ const processed = processClaudeChunk(chunk.lines, registration, sourceRef, kind, before, chunk.oversized_rows);
5467
+ const after = await updateAnchor(handle, { ...processed.cursor, offset: chunk.end_offset, skipping_oversized_line: chunk.skipping_oversized_line });
5468
+ const gaps = [...processed.gapCounts].map(([reason, omitted_count]) => ({ reason, source_file_ref: sourceRef, start_offset: before.offset, end_offset: chunk.end_offset, omitted_count }));
5469
+ const batch = processed.facts.length === 0 && gaps.length === 0 ? null : createCealHostUsageBatch({
5470
+ host_source_ref: registration.host_source_ref,
5471
+ host_session_ref: registration.host_session_ref,
5472
+ created_at: processed.createdAt,
5473
+ source_ranges: [{ source_file_ref: sourceRef, start_offset: before.offset, end_offset: chunk.end_offset }],
5474
+ facts: processed.facts,
5475
+ coverage_gaps: gaps
5476
+ });
5477
+ await this.usage.commitScanTransition(state, slot, before, after, batch);
5478
+ return true;
5479
+ }
5480
+ stamp() {
5481
+ const value = this.now();
5482
+ if (!Number.isFinite(value.getTime())) throw new Error("Claude usage facts clock is invalid.");
5483
+ return value.toISOString();
5484
+ }
5485
+ };
5486
+ function parseClaudeRow(line, registration, sourceRef, kind, hostTurnRef) {
5487
+ const value = parseRowRecord(line);
5488
+ const userTurn = kind === "main" ? mainUserTurn(value, registration.claude_session_id) : null;
5489
+ if (userTurn !== null) return { timestamp: timestamp3(userTurn.timestamp), turn_id: userTurn.turnId };
5490
+ if (!assistantRow(value)) return { timestamp: rowTimestamp(value) };
5491
+ return parseAssistantRow(value, registration, sourceRef, kind, hostTurnRef);
5492
+ }
5493
+ function mainUserTurn(value, sessionId) {
5494
+ return decodeClaudeHumanMessageRow(value, sessionId);
5495
+ }
5496
+ function parseRowRecord(line) {
5497
+ let value;
5498
+ try {
5499
+ value = JSON.parse(line);
5500
+ } catch {
5501
+ throw new Error("Claude transcript row is malformed.");
5502
+ }
5503
+ if (!isRecord4(value)) throw new Error("Claude transcript row is malformed.");
5504
+ return value;
5505
+ }
5506
+ function assistantRow(value) {
5507
+ return value.type === "assistant" && isRecord4(value.message);
5508
+ }
5509
+ function parseAssistantRow(value, registration, sourceRef, kind, hostTurnRef) {
5510
+ const message = value.message;
5511
+ const terminal = message.stop_reason === "end_turn";
5512
+ if (message.usage === void 0) return { timestamp: rowTimestamp(value), terminal };
5513
+ if (!isRecord4(message.usage)) return { timestamp: rowTimestamp(value), unsupported: true, terminal };
5514
+ const parsed = parseAssistantUsage(value, message, message.usage, registration, sourceRef, kind, hostTurnRef, terminal);
5515
+ return parsed;
5516
+ }
5517
+ function parseAssistantUsage(value, message, usage, registration, sourceRef, kind, hostTurnRef, terminal) {
5518
+ const observedAt = rowTimestamp(value);
5519
+ const values = assistantUsageValues(value, message, usage);
5520
+ if (values === null) return { timestamp: observedAt, unsupported: true, terminal };
5521
+ const { uuid, input, output, cached, cacheWrite, cacheCreation, reportedModel } = values;
5522
+ const normalizedInput = safeSum(input, cached, cacheWrite);
5523
+ if (normalizedInput === void 0) return { timestamp: observedAt, unsupported: true, terminal };
5524
+ const fact = createClaudeFact({ uuid, input, output, cached, cacheWrite, cacheCreation, normalizedInput, reportedModel, observedAt, registration, sourceRef, kind, hostTurnRef, terminal, stopReason: message.stop_reason });
5525
+ return { timestamp: observedAt, fact, terminal };
5526
+ }
5527
+ function assistantUsageValues(value, message, usage) {
5528
+ const uuid = boundedText2(value.uuid, 256);
5529
+ const input = safeCounter(usage.input_tokens);
5530
+ const output = safeCounter(usage.output_tokens);
5531
+ const cached = optionalCounter(usage, "cache_read_input_tokens");
5532
+ const cacheWrite = optionalCounter(usage, "cache_creation_input_tokens");
5533
+ const cacheCreation = cacheCreationUsage(usage.cache_creation);
5534
+ const reportedModel = message.model === void 0 || message.model === null ? null : boundedText2(message.model, 256);
5535
+ if (uuid === null || input === null || output === null || cached.invalid || cacheWrite.invalid || cacheCreation.invalid || invalidReportedModel(message.model, reportedModel)) return null;
5536
+ return { uuid, input, output, cached: cached.value, cacheWrite: cacheWrite.value, cacheCreation: cacheCreation.value, reportedModel };
5537
+ }
5538
+ function cacheCreationUsage(value) {
5539
+ if (value === void 0 || value === null) return { value: null, invalid: false };
5540
+ if (!isRecord4(value)) return { value: null, invalid: true };
5541
+ const oneHour = optionalCounter(value, "ephemeral_1h_input_tokens");
5542
+ const fiveMinutes = optionalCounter(value, "ephemeral_5m_input_tokens");
5543
+ return {
5544
+ value: { ephemeral_1h_input_tokens: oneHour.value, ephemeral_5m_input_tokens: fiveMinutes.value },
5545
+ invalid: oneHour.invalid || fiveMinutes.invalid
5546
+ };
5547
+ }
5548
+ function invalidReportedModel(model, reportedModel) {
5549
+ return model !== void 0 && model !== null && reportedModel === null;
5550
+ }
5551
+ function safeSum(input, cached, cacheWrite) {
5552
+ if (cached === null || cacheWrite === null) return null;
5553
+ const total = input + cached + cacheWrite;
5554
+ return Number.isSafeInteger(total) ? total : void 0;
5555
+ }
5556
+ function createClaudeFact({ uuid, input, output, cached, cacheWrite, cacheCreation, normalizedInput, reportedModel, observedAt, registration, sourceRef, kind, hostTurnRef, terminal, stopReason }) {
5557
+ const sourceUsage = { input_tokens: input, cache_read_input_tokens: cached, cache_creation_input_tokens: cacheWrite, cache_creation: cacheCreation, output_tokens: output };
5558
+ const sourceEventRef = hostUsageSourceEventReference(sourceRef, `claude:${uuid}:${sha2563(JSON.stringify(sourceUsage))}`);
5559
+ const normalizedTotal = normalizedInput === null ? null : safeOutputTotal(normalizedInput, output);
5560
+ return {
5561
+ fact_ref: hostUsageFactReference(sourceRef, sourceEventRef),
5562
+ host_session_ref: registration.host_session_ref,
5563
+ host_turn_ref: kind === "main" ? hostTurnRef : null,
5564
+ source_file_ref: sourceRef,
5565
+ source_event_ref: sourceEventRef,
5566
+ source_event_uuid: uuid,
5567
+ source_file_kind: kind,
5568
+ observed_at: observedAt,
5569
+ producer: "claude_transcript",
5570
+ requested_model: null,
5571
+ reported_model: reportedModel,
5572
+ source_usage: sourceUsage,
5573
+ normalized_usage: { input: normalizedInput, output, total: normalizedTotal, cached_input: cached, cache_write_input: cacheWrite, reasoning_output: null },
5574
+ counter_semantics: "assistant_message",
5575
+ finality: finality(terminal, stopReason),
5576
+ child_inclusion: "unknown",
5577
+ correction_semantics: "unknown"
5578
+ };
5579
+ }
5580
+ function safeOutputTotal(input, output) {
5581
+ const total = input + output;
5582
+ return Number.isSafeInteger(total) ? total : null;
5583
+ }
5584
+ function finality(terminal, stopReason) {
5585
+ return terminal ? "terminal" : stopReason === null || stopReason === void 0 ? "nonterminal" : "unknown";
5586
+ }
5587
+ function processClaudeChunk(lines, registration, sourceRef, kind, initial, oversizedRows) {
5588
+ let cursor = initial;
5589
+ let createdAt = registration.registered_at;
5590
+ const facts = [];
5591
+ const gapCounts = /* @__PURE__ */ new Map();
5592
+ if (oversizedRows > 0) gapCounts.set("unsupported_source_shape", oversizedRows);
5593
+ for (const line of lines) {
5594
+ let parsed;
5595
+ try {
5596
+ parsed = parseClaudeRow(line.toString("utf8"), registration, sourceRef, kind, cursor.host_turn_ref);
5597
+ } catch {
5598
+ addUnsupportedGap(gapCounts);
5599
+ continue;
5600
+ }
5601
+ createdAt = parsed.timestamp;
5602
+ if (parsed.unsupported === true) addUnsupportedGap(gapCounts);
5603
+ if (parsed.fact !== void 0) facts.push(parsed.fact);
5604
+ cursor = updateClaudeTurnCursor(cursor, parsed, registration, kind);
5605
+ }
5606
+ return { cursor, facts, gapCounts, createdAt };
5607
+ }
5608
+ function addUnsupportedGap(gapCounts) {
5609
+ gapCounts.set("unsupported_source_shape", (gapCounts.get("unsupported_source_shape") ?? 0) + 1);
5610
+ }
5611
+ function updateClaudeTurnCursor(cursor, row, registration, kind) {
5612
+ if (kind !== "main") return cursor;
5613
+ 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) };
5614
+ return row.terminal === true ? { ...cursor, native_turn_id: null, host_turn_ref: null } : cursor;
5615
+ }
5616
+ async function readSubagentNames(registration) {
5617
+ try {
5618
+ return (await readHostUsageTranscriptSource(() => readdir3(subagentsDirectory(registration.transcript_path)))).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
5619
+ } catch (error) {
5620
+ const cause = error instanceof HostUsageTranscriptSourceError ? error.cause : error;
5621
+ if (errorCode3(cause) === "ENOENT" || errorCode3(cause) === "ENOTDIR") return [];
5622
+ throw error;
5623
+ }
5624
+ }
5625
+ function initialCursor(sourceFileRef2, device, inode) {
5626
+ 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 };
5627
+ }
5628
+ function sourceFileRef(registration, device, inode) {
5629
+ return hostUsageSourceFileReference("claude_transcript", registration.host_source_ref, registration.host_session_ref, device, inode);
5630
+ }
5631
+ function subagentSlot(name) {
5632
+ return `subagent:${sha2563(name)}`;
5633
+ }
5634
+ function unscopedGap(reason) {
5635
+ return { reason, source_file_ref: null, start_offset: null, end_offset: null, omitted_count: null };
5636
+ }
5637
+ async function anchorMatches(handle, cursor) {
5638
+ const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
5639
+ if (bytes.length === 0) return sha2563("") === cursor.anchor_sha256;
5640
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, cursor.anchor_start));
5641
+ return bytesRead === bytes.length && sha2563(bytes) === cursor.anchor_sha256;
5642
+ }
5643
+ async function cursorReplaced(handle, file, sourceRef, cursor) {
5644
+ return cursor.source_file_ref !== sourceRef || cursor.device !== file.device || cursor.inode !== file.inode || file.size < cursor.offset || !await anchorMatches(handle, cursor);
5645
+ }
5646
+ async function updateAnchor(handle, cursor) {
5647
+ const anchor_start = Math.max(0, cursor.offset - CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
5648
+ const anchor = Buffer.alloc(cursor.offset - anchor_start);
5649
+ if (anchor.length > 0) {
5650
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(anchor, 0, anchor.length, anchor_start));
5651
+ if (bytesRead !== anchor.length) throw new Error("Claude usage facts source changed during anchor read.");
5652
+ }
5653
+ return { ...cursor, anchor_start, anchor_sha256: sha2563(anchor) };
5654
+ }
5655
+ function rowTimestamp(value) {
5656
+ return timestamp3(value.timestamp);
5657
+ }
5658
+ function timestamp3(value) {
5659
+ if (!safeTimestamp(value)) throw new Error("Claude transcript timestamp is malformed.");
5660
+ return value;
5661
+ }
5662
+ function safeTimestamp(value) {
5663
+ return typeof value === "string" && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
5664
+ }
5665
+ function boundedText2(value, maximum) {
5666
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters2(value) ? value : null;
5667
+ }
5668
+ function hasControlCharacters2(value) {
5669
+ for (const character of value) {
5670
+ const code2 = character.codePointAt(0);
5671
+ if (code2 !== void 0 && (code2 < 32 || code2 === 127)) return true;
5672
+ }
5673
+ return false;
5674
+ }
5675
+ function safeCounter(value) {
5676
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
5677
+ }
5678
+ function optionalCounter(value, key) {
5679
+ if (!Object.hasOwn(value, key) || value[key] === null) return { value: null, invalid: false };
5680
+ const count = safeCounter(value[key]);
5681
+ return { value: count, invalid: count === null };
5682
+ }
5683
+ function isRecord4(value) {
5684
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5685
+ }
5686
+ function errorCode3(error) {
5687
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
5688
+ }
5689
+ function sha2563(value) {
5690
+ return createHash8("sha256").update(value).digest("hex");
5691
+ }
5692
+
5693
+ // host/claude/src/claude-adapter.ts
5694
+ import { createHash as createHash9, randomUUID } from "node:crypto";
5695
+ import { readdir as readdir4 } from "node:fs/promises";
5696
+ import { constants as constants6 } from "node:fs";
3648
5697
  import { homedir } from "node:os";
3649
- import { isAbsolute as isAbsolute2, join as join5, relative, resolve } from "node:path";
5698
+ import { isAbsolute as isAbsolute5, join as join8, relative, resolve } from "node:path";
3650
5699
 
3651
5700
  // host/claude/src/claude-runtime-paths.ts
3652
- import { join as join4 } from "node:path";
5701
+ import { join as join7 } from "node:path";
3653
5702
  var CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT = "CLAUDE_CONFIG_DIR";
3654
5703
  var CLAUDE_HOME_DEFAULT_DIRECTORY = ".claude";
3655
5704
  var CLAUDE_PROJECTS_DIRECTORY = "projects";
3656
5705
  function resolveClaudeConfigHome(environment, home) {
3657
- return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join4(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
5706
+ return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join7(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
3658
5707
  }
3659
5708
  function resolveClaudeProjectsRoot(environment, home) {
3660
- return join4(resolveClaudeConfigHome(environment, home), CLAUDE_PROJECTS_DIRECTORY);
5709
+ return join7(resolveClaudeConfigHome(environment, home), CLAUDE_PROJECTS_DIRECTORY);
3661
5710
  }
3662
5711
 
3663
5712
  // host/claude/src/claude-adapter.ts
@@ -3695,7 +5744,7 @@ var ClaudeHookAdapter = class {
3695
5744
  const defaultRoot = resolveClaudeProjectsRoot(process.env, homedir());
3696
5745
  const transcriptPath = sourceBoundTranscriptPath(input.transcript_path, this.transcriptsRoot ?? defaultRoot, this.platform);
3697
5746
  const hostSessionRef = claudeLocalSessionRef(input.session_id);
3698
- const observedAt = timestamp3(this.now);
5747
+ const observedAt = timestamp4(this.now);
3699
5748
  const expiresAt = new Date(Date.parse(observedAt) + CLAUDE_DEFAULT_RETENTION_MS).toISOString();
3700
5749
  const registration = {
3701
5750
  schema_version: "ceal.claude_transcript_registration.v1",
@@ -3726,7 +5775,7 @@ var ClaudeHookAdapter = class {
3726
5775
  async registerCurrentTurn(input) {
3727
5776
  const transcriptPath = sourceBoundTranscriptPath(input.transcript_path, this.transcriptsRoot ?? resolveClaudeProjectsRoot(process.env, homedir()), this.platform);
3728
5777
  const hostSessionRef = claudeLocalSessionRef(input.session_id);
3729
- const observedAt = timestamp3(this.now);
5778
+ const observedAt = timestamp4(this.now);
3730
5779
  const expiresAt = new Date(Date.parse(observedAt) + CLAUDE_DEFAULT_RETENTION_MS).toISOString();
3731
5780
  const registration = {
3732
5781
  schema_version: "ceal.claude_transcript_registration.v1",
@@ -3738,7 +5787,7 @@ var ClaudeHookAdapter = class {
3738
5787
  registered_at: observedAt,
3739
5788
  expires_at: expiresAt
3740
5789
  };
3741
- const promptRef = hostProducerPromptRef(createHash5("sha256").update(input.prompt, "utf8").digest("hex"));
5790
+ const promptRef = hostProducerPromptRef(createHash9("sha256").update(input.prompt, "utf8").digest("hex"));
3742
5791
  const turnGenerationRef = this.randomUuid();
3743
5792
  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
5793
  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 +5804,11 @@ function sessionObservationValue(input) {
3755
5804
  return { status: "started", host_kind: "claude", source: input.source, model: input.model ?? "unavailable", decoder_evidence_version: "claude-code-2.1.258" };
3756
5805
  }
3757
5806
  function sourceBoundTranscriptPath(path, transcriptsRoot, platform = process.platform) {
3758
- if (!isAbsolute2(path) || !isAbsolute2(transcriptsRoot)) throw new ClaudeHostError("configuration", "Claude transcript registration paths must be absolute.");
5807
+ if (!isAbsolute5(path) || !isAbsolute5(transcriptsRoot)) throw new ClaudeHostError("configuration", "Claude transcript registration paths must be absolute.");
3759
5808
  const transcript = resolve(path);
3760
5809
  const root = resolve(transcriptsRoot);
3761
5810
  const child = relative(root, transcript);
3762
- if (child === "" || child === ".." || child.startsWith(`..${platform === "win32" ? "\\" : "/"}`) || isAbsolute2(child)) {
5811
+ if (child === "" || child === ".." || child.startsWith(`..${platform === "win32" ? "\\" : "/"}`) || isAbsolute5(child)) {
3763
5812
  throw new ClaudeHostError("invalid_input", "Claude transcript path is outside the configured transcripts root.");
3764
5813
  }
3765
5814
  return transcript;
@@ -3780,9 +5829,9 @@ async function refreshCurrentTurnCursor(store, registration, baseline, promptRef
3780
5829
  async function captureClaudeTranscriptBaseline(registration, now, currentPrompt, platform = process.platform, custody = {}) {
3781
5830
  let handle;
3782
5831
  try {
3783
- handle = await openNoFollow(registration.transcript_path, constants2.O_RDONLY, void 0, platform, custody);
5832
+ handle = await openNoFollow(registration.transcript_path, constants6.O_RDONLY, void 0, platform, custody);
3784
5833
  } catch (error) {
3785
- if (isNotFound(error)) return { cursor: initialCursor(registration, now) };
5834
+ if (isNotFound(error)) return { cursor: initialCursor2(registration, now) };
3786
5835
  throw error;
3787
5836
  }
3788
5837
  try {
@@ -3863,17 +5912,18 @@ async function makeClaudeBaselineCursor(handle, registration, now, file, offset,
3863
5912
  inode: file.inode,
3864
5913
  offset,
3865
5914
  anchor_start: anchorStart,
3866
- anchor_sha256: createHash5("sha256").update(anchor).digest("hex"),
5915
+ anchor_sha256: createHash9("sha256").update(anchor).digest("hex"),
5916
+ human_message_window: { messages: [], truncated: offset > 0 },
3867
5917
  subagents: await readClaudeSubagentBaseline(registration.transcript_path, platform, custody),
3868
5918
  status: "active",
3869
- updated_at: timestamp3(now)
5919
+ updated_at: timestamp4(now)
3870
5920
  };
3871
5921
  }
3872
5922
  async function readClaudeSubagentBaseline(transcriptPath, platform, custody) {
3873
5923
  const directory = subagentsDirectory(transcriptPath);
3874
5924
  let names;
3875
5925
  try {
3876
- names = (await readdir3(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
5926
+ names = (await readdir4(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
3877
5927
  } catch (error) {
3878
5928
  if (isNotFound(error)) return {};
3879
5929
  throw new ClaudeHostError("storage", "subagent_baseline_unavailable");
@@ -3891,7 +5941,7 @@ async function readClaudeSubagentBaseline(transcriptPath, platform, custody) {
3891
5941
  async function readClaudeSubagentSeed(directory, name, platform, custody) {
3892
5942
  let handle;
3893
5943
  try {
3894
- handle = await openNoFollow(join5(directory, name), constants2.O_RDONLY, void 0, platform, custody);
5944
+ handle = await openNoFollow(join8(directory, name), constants6.O_RDONLY, void 0, platform, custody);
3895
5945
  const stats = await handle.stat();
3896
5946
  if (!stats.isFile()) throw new ClaudeHostError("storage", "Claude subagent baseline source is not a regular file.");
3897
5947
  if (platform !== "win32" && !isSelfOwned(stats.uid, platform, handle)) throw new ClaudeHostError("storage", "Claude subagent baseline source is owned by another user.");
@@ -3900,7 +5950,7 @@ async function readClaudeSubagentSeed(directory, name, platform, custody) {
3900
5950
  inode: String(stats.ino),
3901
5951
  offset: stats.size,
3902
5952
  anchor_start: 0,
3903
- anchor_sha256: createHash5("sha256").update(Buffer.alloc(0)).digest("hex")
5953
+ anchor_sha256: createHash9("sha256").update(Buffer.alloc(0)).digest("hex")
3904
5954
  };
3905
5955
  } finally {
3906
5956
  await handle?.close();
@@ -3908,24 +5958,24 @@ async function readClaudeSubagentSeed(directory, name, platform, custody) {
3908
5958
  }
3909
5959
  function parseClaudeUserLine(line, sessionId) {
3910
5960
  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;
5961
+ if (row === null || row.type !== "user" || row.sessionId !== sessionId || typeof row.uuid !== "string" || row.uuid.length === 0 || !isRecord5(row.message)) return null;
3912
5962
  return typeof row.message.content === "string" ? { uuid: row.uuid, content: row.message.content } : null;
3913
5963
  }
3914
5964
  function parseClaudeJsonObject(line) {
3915
5965
  try {
3916
5966
  const value = JSON.parse(line);
3917
- return isRecord3(value) ? value : null;
5967
+ return isRecord5(value) ? value : null;
3918
5968
  } catch {
3919
5969
  return null;
3920
5970
  }
3921
5971
  }
3922
- function isRecord3(value) {
5972
+ function isRecord5(value) {
3923
5973
  return value !== null && typeof value === "object" && !Array.isArray(value);
3924
5974
  }
3925
5975
  function isNotFound(error) {
3926
- return isRecord3(error) && error.code === "ENOENT";
5976
+ return isRecord5(error) && error.code === "ENOENT";
3927
5977
  }
3928
- function initialCursor(registration, now) {
5978
+ function initialCursor2(registration, now) {
3929
5979
  return {
3930
5980
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
3931
5981
  host_source_ref: registration.host_source_ref,
@@ -3933,13 +5983,13 @@ function initialCursor(registration, now) {
3933
5983
  transcript_path: registration.transcript_path,
3934
5984
  offset: 0,
3935
5985
  anchor_start: 0,
3936
- anchor_sha256: createHash5("sha256").update(Buffer.alloc(0)).digest("hex"),
5986
+ anchor_sha256: createHash9("sha256").update(Buffer.alloc(0)).digest("hex"),
3937
5987
  subagents: {},
3938
5988
  status: "active",
3939
- updated_at: timestamp3(now)
5989
+ updated_at: timestamp4(now)
3940
5990
  };
3941
5991
  }
3942
- function timestamp3(now) {
5992
+ function timestamp4(now) {
3943
5993
  const value = now();
3944
5994
  if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError("Claude Host clock is invalid.");
3945
5995
  return value.toISOString();
@@ -3967,48 +6017,6 @@ var ClaudeProducer = class {
3967
6017
  }
3968
6018
  };
3969
6019
 
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
6020
  // host/claude/src/claude-producer-runtime.ts
4013
6021
  async function drainClaudeProducerOnce(options) {
4014
6022
  const scan = await new ClaudeTranscriptWatcher({
@@ -4024,45 +6032,11 @@ async function drainClaudeProducerOnce(options) {
4024
6032
 
4025
6033
  // host/claude/src/claude-hook-runner.ts
4026
6034
  import { homedir as homedir2 } from "node:os";
4027
- import { join as join6 } from "node:path";
6035
+ import { join as join9 } from "node:path";
4028
6036
 
4029
6037
  // host/producer-service.ts
4030
6038
  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";
6039
+ import { constants as constants7 } from "node:fs";
4066
6040
  import { lstat as lstat3 } from "node:fs/promises";
4067
6041
  var SAFE_REF3 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
4068
6042
  var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
@@ -4088,7 +6062,8 @@ function parseHostProducerConfigFlag(args, platform = process.platform) {
4088
6062
  async function readHostProducerConfig(descriptor, configPath, platform = process.platform, custody = {}) {
4089
6063
  const config = decodeHostProducerConfigText(descriptor, await readProducerConfigText(configPath, platform, hostProducerError, custody), platform);
4090
6064
  const path = platform === "win32" ? win325 : posix4;
4091
- const root = path.resolve(config.outbox_dir, "../../../../..");
6065
+ const registrationStateFile = hostProducerRegistrationStateFile(config.outbox_dir, platform);
6066
+ const root = path.dirname(registrationStateFile);
4092
6067
  try {
4093
6068
  assertHostProducerSourcePaths(root, config, descriptor.producer_id, platform);
4094
6069
  } catch (error) {
@@ -4102,6 +6077,10 @@ function decodeHostProducerConfigText(descriptor, text, platform = process.platf
4102
6077
  const { extra_paths: extras, ...core } = decoded;
4103
6078
  return Object.freeze(descriptor.config({ schema_version: descriptor.schema, ...core }, extras));
4104
6079
  }
6080
+ function hostProducerRegistrationStateFile(outboxDirectory, platform = process.platform) {
6081
+ const path = platform === "win32" ? win325 : posix4;
6082
+ return path.join(path.resolve(outboxDirectory, "../../../../.."), "registration.json");
6083
+ }
4105
6084
  function hostProducerError(code2, message = code2) {
4106
6085
  return new HostProducerServiceError(code2, message);
4107
6086
  }
@@ -4147,7 +6126,7 @@ async function readProducerConfigText(configPath, platform, error, custody) {
4147
6126
  function decodeProducerConfigCore(text, options) {
4148
6127
  const ownership = producerConfigKeyOwnership(options.keys, options.platform);
4149
6128
  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 })));
6129
+ 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
6130
  const hostSourceRef = typeof value.host_source_ref === "string" ? value.host_source_ref : "";
4152
6131
  const installationRef = typeof value.producer_installation_ref === "string" ? value.producer_installation_ref : "";
4153
6132
  const producerEpoch = validateIdentity3(hostSourceRef, installationRef, value.producer_epoch, options.error);
@@ -4199,7 +6178,7 @@ function validateConfigFile(value, platform, error, handle) {
4199
6178
  }
4200
6179
  async function openConfigFile(configPath, platform, error, custody) {
4201
6180
  try {
4202
- return await openNoFollow(configPath, constants3.O_RDONLY, void 0, platform, custody);
6181
+ return await openNoFollow(configPath, constants7.O_RDONLY, void 0, platform, custody);
4203
6182
  } catch (error_) {
4204
6183
  if (error_ instanceof SecureFileCustodyError) throw error(error_.reason === "not_private" ? "config_not_private" : "invalid_config");
4205
6184
  throw error("config_unavailable");
@@ -4240,7 +6219,7 @@ function firstDifferenceIndex(left, right) {
4240
6219
  return shared;
4241
6220
  }
4242
6221
  function producerShapeFacts(value, options) {
4243
- if (!isRecord4(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
6222
+ if (!isRecord6(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
4244
6223
  const tolerated = options.tolerated ?? [];
4245
6224
  const allowed = [...options.keys, ...tolerated, ...Object.keys(HOST_PRODUCER_TIMING_DEFAULTS)];
4246
6225
  const facts = [
@@ -4275,7 +6254,7 @@ function producerIntervalFacts(reconcile, retry, timeout) {
4275
6254
  function hasConfigKeys(value, required, tolerated = []) {
4276
6255
  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
6256
  }
4278
- function isRecord4(value) {
6257
+ function isRecord6(value) {
4279
6258
  return value !== null && typeof value === "object" && !Array.isArray(value);
4280
6259
  }
4281
6260
  function positive(value, maximum) {
@@ -4293,10 +6272,12 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
4293
6272
  producer_id: "claude",
4294
6273
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
4295
6274
  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
6275
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6276
+ drain: drainClaudeProducerOnce,
6277
+ background: (config, signal) => {
6278
+ const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
6279
+ 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() }, signal);
6280
+ }
4300
6281
  };
4301
6282
 
4302
6283
  // host/claude/src/claude-hook-runner.ts
@@ -4332,15 +6313,15 @@ async function runClaudeHookCli() {
4332
6313
  return 0;
4333
6314
  }
4334
6315
  }
4335
- async function installedClaudeHookRunnerOptions(args) {
4336
- const config = await readHostProducerConfig(CLAUDE_PRODUCER_DESCRIPTOR, parseHostProducerConfigFlag(args));
6316
+ async function installedClaudeHookRunnerOptions(args, custody = {}) {
6317
+ const config = await readHostProducerConfig(CLAUDE_PRODUCER_DESCRIPTOR, parseHostProducerConfigFlag(args), process.platform, custody);
4337
6318
  const options = { outbox_dir: config.outbox_dir, claude_transcripts_root: config.claude_transcripts_root };
4338
6319
  Object.defineProperty(options, "host_source_ref", { value: config.host_source_ref, enumerable: false });
4339
6320
  return options;
4340
6321
  }
4341
6322
  function standaloneClaudeHookRunnerOptions(overrides) {
4342
6323
  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()) };
6324
+ return { outbox_dir: overrides?.outbox_dir ?? join9(claudeHome, ".ceal", "claude-observation-outbox"), claude_transcripts_root: resolveClaudeProjectsRoot(process.env, homedir2()) };
4344
6325
  }
4345
6326
  function hasHostConfigArgument(args) {
4346
6327
  return args.some((argument) => argument === HOST_PRODUCER_CONFIG_FLAG || argument.startsWith(`${HOST_PRODUCER_CONFIG_FLAG}=`));
@@ -4359,17 +6340,23 @@ async function readStdin(stdin) {
4359
6340
 
4360
6341
  // host/local-capability-descriptor.ts
4361
6342
  var HOST_LOCAL_CAPABILITY_AUTHENTICATION_SUFFIX = Object.freeze(["authenticate", "--client-nonce"]);
6343
+ var LOCAL_CAPABILITY_CUSTODY_REFUSALS = Object.freeze({
6344
+ not_private: "is not private to the current user.",
6345
+ reparse_point: "must not be a reparse point.",
6346
+ not_found: "custody could not be proved.",
6347
+ too_large: "custody could not be proved.",
6348
+ already_exists: "custody could not be proved.",
6349
+ unavailable: "custody could not be proved."
6350
+ });
4362
6351
 
4363
6352
  // host/client-doctor.ts
4364
6353
  import { execFile as execFile2 } from "node:child_process";
4365
6354
  import { promisify } from "node:util";
4366
6355
 
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
- });
6356
+ // host/command-vector.ts
6357
+ var WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET = "A-Za-z0-9._=-";
6358
+ var WINDOWS_FIXED_CMD_ARGUMENT_REFUSAL_PATTERN = `[^${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]`;
6359
+ var WINDOWS_FIXED_CMD_ARGUMENT = new RegExp(`^[${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]+$`, "u");
4373
6360
 
4374
6361
  // host/client-doctor.ts
4375
6362
  var execFileAsync = promisify(execFile2);