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

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