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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.");
@@ -41,6 +56,15 @@ function assertHostProducerSourcePaths(stateRoot, config, producer, platform = p
41
56
  import { constants as constants2 } from "node:fs";
42
57
  import { lstat as lstat2 } from "node:fs/promises";
43
58
 
59
+ // packages/ceal-client-protocol/src/vocabulary.ts
60
+ function vocabulary(words) {
61
+ return Object.freeze(words);
62
+ }
63
+
64
+ // packages/ceal-client-protocol/src/host-usage-fields.ts
65
+ var CEAL_CODEX_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
66
+ var CEAL_CLAUDE_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"]);
67
+
44
68
  // packages/ceal-client-protocol/src/canonical-json.ts
45
69
  function cealCanonicalJson(value) {
46
70
  if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
@@ -69,7 +93,7 @@ function isPlainRecord(value) {
69
93
  }
70
94
 
71
95
  // packages/ceal-client-protocol/src/client-wire-contract.ts
72
- import { createHash as createHash2 } from "node:crypto";
96
+ import { createHash as createHash3 } from "node:crypto";
73
97
 
74
98
  // packages/ceal-client-protocol/client-wire-contract.json
75
99
  var client_wire_contract_default = {
@@ -90,7 +114,7 @@ var client_wire_contract_default = {
90
114
  ordering: "utf16_code_unit_ascending"
91
115
  },
92
116
  artifact_descriptor: {
93
- operation_contract_bundle_schema_name: "ceal.operation_contract_bundle",
117
+ operation_contract_bundle_schema_name: "ceal.operation_contract_bundle_v2",
94
118
  operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
95
119
  schema_name: "ceal.verified_artifact_descriptor",
96
120
  fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
@@ -115,7 +139,7 @@ var client_wire_contract_default = {
115
139
  },
116
140
  command_request: {
117
141
  schema_name: "ceal.command_request",
118
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
142
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
119
143
  absolute_transport_max_bytes: 65536
120
144
  },
121
145
  command_resolution: {
@@ -161,8 +185,9 @@ var client_wire_contract_default = {
161
185
  },
162
186
  command_response: {
163
187
  schema_name: "ceal.command_response",
164
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
188
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
165
189
  descriptor_field: "verified_artifact",
190
+ request_context_field: "request_context",
166
191
  required_fields: [
167
192
  "schema_version",
168
193
  "exit_code",
@@ -172,7 +197,8 @@ var client_wire_contract_default = {
172
197
  "operation_id",
173
198
  "visible_output_max_bytes",
174
199
  "local_delivery",
175
- "verified_artifact"
200
+ "verified_artifact",
201
+ "request_context"
176
202
  ],
177
203
  bare_document_fields: [
178
204
  "invocation",
@@ -193,7 +219,7 @@ var client_wire_contract_default = {
193
219
  ],
194
220
  exit_code_max: 125,
195
221
  bare_document_max_bytes: 65536,
196
- complete_max_bytes: 66046
222
+ complete_max_bytes: 66195
197
223
  },
198
224
  host_invocation_authentication: {
199
225
  request_schema_name: "ceal.host_invocation_authentication_request",
@@ -207,6 +233,17 @@ var client_wire_contract_default = {
207
233
  "context_token",
208
234
  "expires_at"
209
235
  ],
236
+ refusal_schema_name: "ceal.host_invocation_authentication_refusal",
237
+ refusal_fields: [
238
+ "schema_version",
239
+ "ok",
240
+ "code",
241
+ "reason",
242
+ "gateway_status",
243
+ "retry_after_ms"
244
+ ],
245
+ refusal_required_fields: ["schema_version", "ok", "code", "reason"],
246
+ refusal_optional_fields: ["gateway_status", "retry_after_ms"],
210
247
  client_nonce: {
211
248
  character_class_source: "A-Za-z0-9_-",
212
249
  encoded_characters: 43
@@ -245,6 +282,8 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
245
282
  "choose_new_output_path",
246
283
  "choose_new_idempotency_key",
247
284
  "restart_search",
285
+ // The requested temporal key is absent on some observed rows; repeating the same interval without `order` can return those rows.
286
+ "search_without_order",
248
287
  "repeat_original_arguments",
249
288
  // The occurrence this call addressed is settled and cannot move again -- a
250
289
  // denied effect approval, an expired continuation -- so the caller runs the
@@ -303,6 +342,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
303
342
  // The command needs caller-owned local materialization (for example an
304
343
  // @path file) before the Gateway can receive the argument.
305
344
  "materialize_local_argument",
345
+ // A missing or stale local Host bundle is repaired through its installed lifecycle and discovery owners.
346
+ "install_ceal_host",
347
+ // An explicit Client store override points at a missing file; unsetting it selects the one canonical default store without creating a second credential store.
348
+ "unset_context_store_path",
349
+ // The producer app must reload its installed Host hook before it can start a conversation with invocation context.
350
+ "restart_producer_app",
306
351
  // A peer's derived schema identifier changed with its field set; install or
307
352
  // upgrade the CLI and Host Relay to the Gateway's release before retrying.
308
353
  "upgrade_ceal_client"
@@ -411,18 +456,12 @@ var NON_MODEL_ACTION_TO_MODEL_ACTION = Object.freeze({
411
456
  });
412
457
  var RETRY_PROMISE_NEXT_ACTIONS = ["retry", "retry_after"];
413
458
  var RETRY_PROMISE = new Set(RETRY_PROMISE_NEXT_ACTIONS);
414
- var RECOVERABLE = new Set(CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS);
415
459
  var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
416
460
  provider_permission: "ask_admin",
417
461
  access_level: "ask_admin",
418
462
  personal_authorization_required: "connect_personal_account"
419
463
  });
420
464
 
421
- // packages/ceal-client-protocol/src/vocabulary.ts
422
- function vocabulary(words) {
423
- return Object.freeze(words);
424
- }
425
-
426
465
  // packages/ceal-client-protocol/src/gateway-response-types.ts
427
466
  var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
428
467
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
@@ -433,9 +472,9 @@ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "s
433
472
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
434
473
  var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
435
474
  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"]);
475
+ var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
437
476
  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"]);
477
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
439
478
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
440
479
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
441
480
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -506,10 +545,10 @@ function assertSafeJsonArray(value, options, depth, count) {
506
545
  if (value.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
507
546
  for (const item of value) assertSafeJsonValue(item, options, depth + 1, count);
508
547
  }
509
- function assertSafeJsonRecord(record4, options, depth, count) {
510
- const entries = Object.entries(record4);
548
+ function assertSafeJsonRecord(record5, options, depth, count) {
549
+ const entries = Object.entries(record5);
511
550
  if (entries.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
512
- const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record4.fields) : null;
551
+ const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record5.fields) : null;
513
552
  for (const [key, child] of entries) {
514
553
  if (key === "credential_material_included" && child !== false) invalidByContext(options);
515
554
  if (!isSafeNegativeMaterialAssertion(key, child)) assertSafeJsonKey(key, options);
@@ -559,16 +598,21 @@ function isSafeExternalHttpsUrl(value) {
559
598
  return false;
560
599
  }
561
600
  }
601
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE = "^https://[^\\s/@?#]+(?:[/?#][^\\s]*)?$";
602
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN = new RegExp(SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE, "u");
562
603
  function isSafeExternalHttpsUrlInput(value) {
563
604
  return typeof value === "string" && byteLength(value) <= 2048;
564
605
  }
565
- function isSafeExternalHttpsUrlShape(url) {
566
- return url.protocol === "https:" && url.username === "" && url.password === "" && url.hash === "";
606
+ function isSafeExternalHttpsUrlShape(url, allowFragment = false) {
607
+ return url.protocol === "https:" && url.hostname.length > 0 && url.username === "" && url.password === "" && (allowFragment || url.hash === "");
567
608
  }
568
609
  function isSafeResultContent(value, key) {
569
610
  const maximum = key === "text" ? 8192 : 1024;
570
611
  return typeof value === "string" && byteLength(value) <= maximum && firstDisallowedControl(value, "multi_line") === null;
571
612
  }
613
+ function requireSafeRef(value) {
614
+ if (typeof value !== "string" || !SAFE_REF.test(value)) invalidRequestOrResponse();
615
+ }
572
616
  var CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES = 512;
573
617
  function normalizeCealSingleLineText(value) {
574
618
  return value.split("").map((character) => hasControlCharacter(character) ? " " : character).join("").trim();
@@ -680,6 +724,7 @@ function cut(text) {
680
724
 
681
725
  // packages/ceal-client-protocol/src/operation-validation-primitives.ts
682
726
  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;
727
+ var EXPANDED_CANONICAL_ISO_TIMESTAMP = /^([+-])(\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/u;
683
728
  var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
684
729
  var CEAL_CALENDAR_DATE = new RegExp(CEAL_CALENDAR_DATE_PATTERN_SOURCE, "u");
685
730
  function isOperationRecord(value) {
@@ -690,13 +735,46 @@ function isOperationRecord(value) {
690
735
  function requireOperationRecord(value, message) {
691
736
  if (!isOperationRecord(value)) throw new TypeError(message);
692
737
  }
738
+ function requireExactOperationKeys(value, required, optional = [], message = "Operation contract has an invalid shape.") {
739
+ const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
740
+ if (required.some((key) => !Object.hasOwn(value, key))) throw new TypeError(message);
741
+ if (Object.keys(value).some((key) => !allowed.has(key))) throw new TypeError(message);
742
+ }
693
743
  function requireClosedValue(value, members, message) {
694
744
  if (typeof value !== "string" || !members.includes(value)) throw new TypeError(message);
695
745
  }
696
746
  function isCealIsoTimestamp(value) {
697
747
  return typeof value === "string" && parseCealIsoTimestamp(value) !== null;
698
748
  }
749
+ function canonicalCealIsoTimestamp(epochNanoseconds) {
750
+ const wholeSeconds = floorDivide(epochNanoseconds, 1000000000n);
751
+ const fractionalNanoseconds = epochNanoseconds - wholeSeconds * 1000000000n;
752
+ const utc = new Date(Number(wholeSeconds * 1000n));
753
+ const date = utc.toISOString().split(".")[0];
754
+ if (date === void 0) throw new TypeError("Ceal timestamp formatter returned an invalid ISO string");
755
+ const fraction = fractionalNanoseconds.toString().padStart(9, "0").replace(/0+$/u, "").padEnd(3, "0");
756
+ return date + "." + fraction + "Z";
757
+ }
758
+ var CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE = "0000-01-01T00:00:00.000000000+23:59";
759
+ var CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE = "9999-12-31T23:59:59.999999999-23:59";
760
+ var CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE);
761
+ var CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE);
762
+ var CEAL_INSTANT_INDEX_SPAN = CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS - CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS;
763
+ var CEAL_INSTANT_INDEX_KEY_WIDTH = CEAL_INSTANT_INDEX_SPAN.toString().length;
764
+ var CEAL_INSTANT_INDEX_KEY_PATTERN = new RegExp(`^\\d{${CEAL_INSTANT_INDEX_KEY_WIDTH}}$`, "u");
765
+ function requiredTimestampEpochNanoseconds(value) {
766
+ const parsed = parseFourDigitCealIsoTimestamp(value);
767
+ if (parsed === null) throw new Error("Ceal instant-index range basis is outside the timestamp grammar");
768
+ return parsed.epochNanoseconds;
769
+ }
699
770
  function parseCealIsoTimestamp(value) {
771
+ const ordinary = parseFourDigitCealIsoTimestamp(value);
772
+ if (ordinary !== null) return ordinary;
773
+ const expanded = parseExpandedCanonicalCealIsoTimestamp(value);
774
+ if (expanded === null || expanded.epochNanoseconds < CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS || expanded.epochNanoseconds > CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS) return null;
775
+ return canonicalCealIsoTimestamp(expanded.epochNanoseconds) === value ? expanded : null;
776
+ }
777
+ function parseFourDigitCealIsoTimestamp(value) {
700
778
  const fields = parseCealIsoTimestampFields(value);
701
779
  if (fields === null || !validCalendarDate(fields) || !validClockTime(fields) || !validUtcOffset(fields)) return null;
702
780
  const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
@@ -705,6 +783,28 @@ function parseCealIsoTimestamp(value) {
705
783
  epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
706
784
  };
707
785
  }
786
+ function parseExpandedCanonicalCealIsoTimestamp(value) {
787
+ const match = EXPANDED_CANONICAL_ISO_TIMESTAMP.exec(value);
788
+ if (match === null) return null;
789
+ const fields = {
790
+ year: (match[1] === "-" ? -1 : 1) * Number(match[2]),
791
+ month: Number(match[3]),
792
+ day: Number(match[4]),
793
+ hour: Number(match[5]),
794
+ minute: Number(match[6]),
795
+ second: Number(match[7]),
796
+ fraction: match[8] ?? "",
797
+ offsetSign: 0,
798
+ offsetHour: 0,
799
+ offsetMinute: 0
800
+ };
801
+ if (!validCalendarDate(fields) || !validClockTime(fields)) return null;
802
+ const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
803
+ if (!Number.isFinite(epochMilliseconds)) return null;
804
+ return {
805
+ epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
806
+ };
807
+ }
708
808
  function parseCealIsoTimestampFields(value) {
709
809
  const match = ISO_TIMESTAMP.exec(value);
710
810
  if (match === null) return null;
@@ -737,6 +837,10 @@ function cealFieldsEpochMilliseconds(fields) {
737
837
  const offsetMilliseconds = fields.offsetSign * (fields.offsetHour * 60 + fields.offsetMinute) * 6e4;
738
838
  return localMilliseconds - offsetMilliseconds;
739
839
  }
840
+ function floorDivide(value, divisor) {
841
+ const quotient = value / divisor;
842
+ return value % divisor < 0n ? quotient - 1n : quotient;
843
+ }
740
844
  function daysInMonth(year, month) {
741
845
  const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
742
846
  return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
@@ -754,6 +858,9 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
754
858
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
755
859
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
756
860
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
861
+ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
862
+ 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.";
863
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
757
864
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
758
865
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
759
866
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
@@ -779,6 +886,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
779
886
  refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
780
887
  refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
781
888
  refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
889
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
890
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
782
891
  refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
783
892
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
784
893
  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 +900,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
791
900
  response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
792
901
  request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
793
902
  request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
903
+ resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
794
904
  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),
905
+ contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
796
906
  // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
797
907
  // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
798
908
  // when the wait ends still unserved, moved from the `localFailureText` default branch.
@@ -802,13 +912,12 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
802
912
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
803
913
  internal_error: guidance("The Gateway failed without exposing internal state.", "answer_with_gap", 500),
804
914
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
805
- // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
915
+ // the static client variant was retired when the client started reading this table.
806
916
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
807
- // Restored verbatim from the retired `localFailureText` `unknown_outcome`
808
- // case: the outcome is unknown, so a read may be retried while a write
809
- // must receipt-check first. Collapsing both to "do not repeat the call"
810
- // forbids the safe read retry the sentence exists to allow.
811
- unknown_outcome: guidance("The transport outcome is unknown: a read may be retried; for a write, check write_receipt.get before repeating.", "answer_with_gap", 500),
917
+ gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
918
+ // The safe move varies by request. Keep the sentence conditional on the
919
+ // same `retryable` and `next_action` facts the response exposes.
920
+ unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
812
921
  // Restored verbatim from the retired `localFailureText`
813
922
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
814
923
  // session context unavailable, so the caller repairs or adopts the
@@ -889,24 +998,27 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
889
998
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
890
999
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
891
1000
  // 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
1001
+ // and `retryable` from `hostAuthenticationFailureForCause` (the table's explicit retry verdict). Cause-specific
1002
+ // sentences carry only remedies proved by the Host or Relay cause; generic Gateway refusals do not prove a release mismatch.
1003
+ // Statuses are the
894
1004
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
895
1005
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
896
1006
  host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
897
1007
  host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
898
1008
  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),
902
- host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
903
- host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
1009
+ // The bounded Host reason does not prove ephemerality. A Host refusal never
1010
+ // changes mode; standalone remains the separate Client authority path.
1011
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
1012
+ host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
1013
+ host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
1014
+ host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
904
1015
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
905
1016
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
906
1017
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
907
1018
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
908
1019
  host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
909
1020
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1021
+ host_contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
910
1022
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
911
1023
  // producer-frame fault names the administrator repair step.
912
1024
  host_producer_frame_invalid: guidance("Ask an administrator to inspect and repair the producer frame, then start a fresh Host turn.", "ask_admin", 400),
@@ -916,56 +1028,13 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
916
1028
  host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
917
1029
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
918
1030
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
919
- host_relay_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1031
+ host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
920
1032
  host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
921
1033
  });
922
1034
  var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
923
1035
 
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]);
1036
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1037
+ import { createHash as createHash2 } from "node:crypto";
969
1038
 
970
1039
  // packages/ceal-client-protocol/src/operation-withheld-cause.ts
971
1040
  var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
@@ -994,7 +1063,7 @@ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
994
1063
  var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
995
1064
  var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
996
1065
  var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
997
- var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
1066
+ var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_applicable", "not_offered", "offered", "accepted", "rejected", "unknown"]);
998
1067
  var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
999
1068
  var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
1000
1069
  var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
@@ -1011,13 +1080,161 @@ var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
1011
1080
  "interactive_unavailable"
1012
1081
  ]);
1013
1082
 
1083
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1084
+ var DIGEST = /^[a-f0-9]{64}$/u;
1085
+ var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1086
+ function isCealDigest(value) {
1087
+ return typeof value === "string" && DIGEST.test(value);
1088
+ }
1089
+ function cealRequestSha256(value) {
1090
+ return createHash2("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1091
+ }
1092
+ function operationRecord(value, message) {
1093
+ requireOperationRecord(value, message);
1094
+ return value;
1095
+ }
1096
+ function invalid(message) {
1097
+ throw new TypeError(message);
1098
+ }
1099
+ function requirePrefixedRef(value, prefix, message) {
1100
+ if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1101
+ }
1102
+ function requireSafeRef2(value, message) {
1103
+ try {
1104
+ requireSafeRef(value);
1105
+ } catch {
1106
+ invalid(message);
1107
+ }
1108
+ }
1109
+
1110
+ // packages/ceal-client-protocol/src/request-authority.ts
1111
+ var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1112
+ var CEAL_REQUEST_REF_MAX_CHARACTERS = 128;
1113
+ var CEAL_REQUEST_REF_PATTERN_SOURCE = "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$";
1114
+ var CEAL_REQUEST_REF_PATTERN = new RegExp(CEAL_REQUEST_REF_PATTERN_SOURCE, "u");
1115
+ var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1116
+ var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1117
+ var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1118
+ var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1119
+ var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1120
+ var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1121
+ schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1122
+ ceal_request_ref: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_REF_MAX_CHARACTERS, pattern: CEAL_REQUEST_REF_PATTERN_SOURCE },
1123
+ created_at: { type: "string", minLength: 1, maxLength: 64 },
1124
+ authority: {
1125
+ type: "object",
1126
+ maxProperties: 5,
1127
+ additionalProperties: false,
1128
+ properties: {
1129
+ instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1130
+ access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1131
+ principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1132
+ execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1133
+ authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1134
+ },
1135
+ required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1136
+ }
1137
+ });
1138
+ var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1139
+ prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1140
+ host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1141
+ host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1142
+ 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." },
1143
+ host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1144
+ host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1145
+ });
1146
+ var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1147
+ 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." },
1148
+ 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." }
1149
+ });
1150
+ var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1151
+ requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1152
+ 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." }
1153
+ });
1154
+ var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1155
+ var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1156
+ var CEAL_REQUEST_JSON_SCHEMA = {
1157
+ type: "object",
1158
+ 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.",
1159
+ maxProperties: 14,
1160
+ additionalProperties: false,
1161
+ properties: {
1162
+ ...CEAL_REQUEST_COMMON_PROPERTIES,
1163
+ ...CEAL_REQUEST_HOST_PROPERTIES,
1164
+ ...CEAL_REQUEST_CALLER_PROPERTIES,
1165
+ ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1166
+ },
1167
+ required: CEAL_REQUEST_KEYS,
1168
+ anyOf: [
1169
+ {
1170
+ type: "object",
1171
+ required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1172
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1173
+ additionalProperties: false
1174
+ },
1175
+ {
1176
+ type: "object",
1177
+ required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1178
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1179
+ additionalProperties: false
1180
+ }
1181
+ ]
1182
+ };
1183
+
1184
+ // packages/ceal-client-protocol/src/client-wire-contract.ts
1185
+ var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
1186
+ var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
1187
+ var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
1188
+ var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
1189
+ var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
1190
+ var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
1191
+ function deriveCealClientWireSchemaVersion(schema) {
1192
+ 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))) {
1193
+ throw new TypeError("Client wire schema name or field set is invalid.");
1194
+ }
1195
+ const fields = schema.fields.filter((field) => field !== "schema_version").sort();
1196
+ const hash8 = createHash3("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
1197
+ return `${schema.schema_name}.v1.${hash8}`;
1198
+ }
1199
+ var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
1200
+ var commandResolutionAuthority = commandResolution.authority;
1201
+ var commandResolutionSemanticOptions = commandResolution.semantic_options;
1202
+ var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
1203
+ var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
1204
+ var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
1205
+ var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
1206
+ var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
1207
+ var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
1208
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
1209
+ var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
1210
+ var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
1211
+ var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
1212
+ var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
1213
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
1214
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
1215
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
1216
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
1217
+ var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
1218
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
1219
+ var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
1220
+ var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
1221
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
1222
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
1223
+ var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
1224
+ var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
1225
+ 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 });
1226
+ var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
1227
+
1228
+ // packages/ceal-client-protocol/src/access-level-vocabulary.ts
1229
+ var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1230
+
1014
1231
  // packages/ceal-client-protocol/src/operation-access-class.ts
1015
1232
  var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
1016
1233
 
1017
1234
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
1018
1235
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
1019
1236
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
1020
- var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1237
+ var CEAL_PROVIDER_BOUNDARY_FIELDS = vocabulary(["provider_boundary_ref", "provider_boundary_kind", "provider_boundary_label", "provider_native_id", "provider_boundary_evidence"]);
1021
1238
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
1022
1239
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
1023
1240
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1063,7 +1280,7 @@ var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1063
1280
  var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
1064
1281
  var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
1065
1282
  var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
1066
- var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
1283
+ var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary", "standard_names"]);
1067
1284
 
1068
1285
  // packages/ceal-client-protocol/src/operation-catalog.ts
1069
1286
  var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
@@ -1125,6 +1342,7 @@ var CEAL_SCHEMA_LITERALS = [
1125
1342
  "ceal.gateway_write_receipt_readback.v1",
1126
1343
  "ceal.gateway_write_request_receipt.v1",
1127
1344
  "ceal.host_observation.v1",
1345
+ "ceal.host_usage_batch.v1",
1128
1346
  "ceal.host_registration_request.v1",
1129
1347
  "ceal.host_registration_result.v1",
1130
1348
  CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
@@ -1153,12 +1371,12 @@ var CEAL_SCHEMA_LITERAL_SET = new Set(CEAL_SCHEMA_LITERALS);
1153
1371
  import { join } from "node:path";
1154
1372
  var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1155
1373
  bounded_store_sidecar: (root) => `${root}.jsonl`,
1156
- gateway_audit_archive: (root) => `${root}.jsonl`,
1157
1374
  gateway_access_group_connector_control_audit: (root) => `${root}.audit.jsonl`,
1158
1375
  gateway_access_group_connector_scope_audit: (root) => join(root, "profile-connector-scope-audit.jsonl"),
1159
1376
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
1160
1377
  gateway_access_group_connector_calendar_scope_audit: (root) => join(root, "profile-connector-calendar-scope-audit.jsonl"),
1161
1378
  gateway_access_group_connector_readiness_audit: (root) => join(root, "profile-connector-readiness.audit.jsonl"),
1379
+ gateway_deployment_events: (root) => join(root, "gateway-deployments.jsonl"),
1162
1380
  gateway_organization_audit_ledger: (root) => join(root, "organization-ledger.jsonl"),
1163
1381
  gateway_personal_client_audit: (root) => join(root, "audit.jsonl"),
1164
1382
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
@@ -1183,6 +1401,12 @@ var CEAL_LOWERCASE_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
1183
1401
  var CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN = new RegExp(`^host-registration-attempt:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1184
1402
  var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1185
1403
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1404
+ var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1405
+
1406
+ // packages/ceal-client-protocol/src/resource-read-result.ts
1407
+ var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
1408
+ var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
1409
+ var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1186
1410
 
1187
1411
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
1188
1412
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
@@ -1201,7 +1425,7 @@ function shellSingleQuoted(value) {
1201
1425
  return `'${value.replaceAll("'", "'\\''")}'`;
1202
1426
  }
1203
1427
  var CEAL_OPERATION_CONTRACT_REQUIRED_FIELDS = Object.freeze(["input_schema", "result_schema"]);
1204
- var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["summary", "input_resolution"]);
1428
+ var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["branches", "summary", "input_resolution"]);
1205
1429
  var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
1206
1430
  $schema: CEAL_JSON_SCHEMA_2020_12,
1207
1431
  $id: "https://ceal.dev/schemas/verified-artifact-descriptor.v1.schema.json",
@@ -1246,11 +1470,93 @@ var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_o
1246
1470
  // packages/ceal-client-protocol/src/actor-kind.ts
1247
1471
  var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
1248
1472
 
1473
+ // packages/ceal-client-protocol/src/provider-link-policy.ts
1474
+ var PROVIDER_LINK_RESULT_FIELDS = Object.freeze({
1475
+ read_row: Object.freeze({ human_link: "source_url", parent_context: Object.freeze(["thread_ref"]) }),
1476
+ write_result: Object.freeze({ human_links: Object.freeze(["user_openable_url", "url", "spreadsheet_url", "meet_url"]) })
1477
+ });
1478
+ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1479
+ { 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/" },
1480
+ { 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/" },
1481
+ { 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/" },
1482
+ { 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/" },
1483
+ { 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/" },
1484
+ { 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" },
1485
+ { 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" },
1486
+ { 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" },
1487
+ { 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" },
1488
+ { 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" },
1489
+ { 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" },
1490
+ { 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" },
1491
+ { 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" },
1492
+ { 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" },
1493
+ { 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" },
1494
+ { 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" },
1495
+ { provider: "google-workspace", result_kind: "form_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified Forms responderUri", source: "https://developers.google.com/workspace/forms/api/reference/rest/v1/forms" },
1496
+ { 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" },
1497
+ { 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" },
1498
+ { 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" },
1499
+ { 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" }
1500
+ ]);
1501
+ var PROVIDER_LINK_HOSTS = Object.freeze({
1502
+ notion: Object.freeze(["notion.so", "www.notion.so", "notion.com", "www.notion.com", "app.notion.com"]),
1503
+ google_workspace: Object.freeze([
1504
+ "calendar.google.com",
1505
+ "contacts.google.com",
1506
+ "docs.google.com",
1507
+ "drive.google.com",
1508
+ "forms.google.com",
1509
+ "mail.google.com",
1510
+ "meet.google.com",
1511
+ "sites.google.com",
1512
+ "www.google.com"
1513
+ ])
1514
+ });
1515
+ var NOTION_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.notion);
1516
+ var GOOGLE_WORKSPACE_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.google_workspace);
1517
+ var PROVIDER_RESOURCE_SOURCE_URL_SCHEMA = Object.freeze({
1518
+ type: "string",
1519
+ minLength: 1,
1520
+ maxLength: 2048,
1521
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1522
+ 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."
1523
+ });
1524
+ var PROVIDER_USER_OPENABLE_URL_SCHEMA = Object.freeze({
1525
+ type: "string",
1526
+ minLength: 1,
1527
+ maxLength: 2048,
1528
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1529
+ 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."
1530
+ });
1531
+
1249
1532
  // packages/ceal-client-protocol/src/resource-row.ts
1250
1533
  var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
1251
1534
  var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
1252
1535
  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"]);
1536
+ var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
1537
+ "query",
1538
+ "modified_since",
1539
+ "since",
1540
+ "until",
1541
+ "filetype",
1542
+ "authored_by_me",
1543
+ "authored_by",
1544
+ "edited_by",
1545
+ "include_replies",
1546
+ "kinds",
1547
+ "container_ref",
1548
+ "container_refs",
1549
+ "container_names",
1550
+ "addressed_to_me",
1551
+ "unread",
1552
+ "archived",
1553
+ "state",
1554
+ "event_types",
1555
+ "starred",
1556
+ "trashed",
1557
+ "permission"
1558
+ ]);
1559
+ var CEAL_RESOURCE_SEARCH_STATES = vocabulary(["open", "closed", "draft", "prerelease", "confirmed", "tentative", "cancelled"]);
1254
1560
  var CEAL_RESOURCE_TIME_BASES = vocabulary(["created", "modified", "viewed"]);
1255
1561
  var CEAL_REPOSITORY_VISIBILITIES = vocabulary(["public", "private", "internal"]);
1256
1562
  var CEAL_ACTIVITY_V3_KINDS = vocabulary(["authored", "edited", "messaged", "responded"]);
@@ -1346,6 +1652,8 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1346
1652
  container_label: { required: true, timestamp: false },
1347
1653
  container_ref: { required: false, timestamp: false },
1348
1654
  source_url: { required: false, timestamp: false },
1655
+ thread_ref: { required: false, timestamp: false },
1656
+ reply_count: { required: false, timestamp: false },
1349
1657
  source: { required: true, timestamp: false },
1350
1658
  owner: { required: false, timestamp: false },
1351
1659
  actor_kind: { required: false, timestamp: false },
@@ -1354,6 +1662,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1354
1662
  created_at: { required: false, timestamp: true },
1355
1663
  created_at_local: { required: false, timestamp: true },
1356
1664
  modified_at: { required: false, timestamp: true },
1665
+ observed_at: { required: false, timestamp: true },
1357
1666
  modified_at_local: { required: false, timestamp: true },
1358
1667
  viewed_by_me_at: { required: false, timestamp: true },
1359
1668
  modified_by_me_at: { required: false, timestamp: true },
@@ -1371,6 +1680,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1371
1680
  start: { required: false, timestamp: false },
1372
1681
  end: { required: false, timestamp: false },
1373
1682
  status: { required: false, timestamp: false },
1683
+ event_type: { required: false, timestamp: false },
1374
1684
  snippet: { required: false, timestamp: false },
1375
1685
  dated_notes: { required: false, timestamp: false },
1376
1686
  state: { required: true, timestamp: false },
@@ -1380,9 +1690,6 @@ var RESOURCE_ROW_REQUIRED_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(
1380
1690
  var RESOURCE_ROW_KEYS = new Set(Object.keys(RESOURCE_ROW_KEY_RULES));
1381
1691
  var RESOURCE_ROW_TIMESTAMP_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(([key, rule]) => rule.timestamp ? [key] : []);
1382
1692
 
1383
- // packages/ceal-client-protocol/src/resource-read-result.ts
1384
- var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1385
-
1386
1693
  // packages/ceal-client-protocol/src/excluded-target-coverage.ts
1387
1694
  var CEAL_EXCLUDED_TARGET_COVERAGE_MAX_ENTRIES = 64;
1388
1695
  function cealExcludedTargetCoverageJsonSchema() {
@@ -1434,6 +1741,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1434
1741
  "refresh_inactive",
1435
1742
  "refresh_replayed",
1436
1743
  "refresh_revoked",
1744
+ "person_inactive",
1745
+ "principal_inactive",
1437
1746
  "authority_replaced",
1438
1747
  "refresh_recovery_unavailable",
1439
1748
  "refresh_recovery_expired",
@@ -1454,97 +1763,6 @@ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
1454
1763
  var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1455
1764
  var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1456
1765
 
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
1766
  // packages/ceal-client-protocol/src/request-operands.ts
1549
1767
  var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1550
1768
  var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
@@ -1652,6 +1870,27 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
1652
1870
  required: ["schema_version", "order", "nodes", "call_budget"]
1653
1871
  };
1654
1872
 
1873
+ // packages/ceal-client-protocol/src/host-observation-validation.ts
1874
+ var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1875
+ 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;
1876
+ function validateCealHostObservationValue(value) {
1877
+ if (value === void 0) throw new TypeError("Ceal Host observation value is invalid.");
1878
+ assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1879
+ if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) throw new TypeError("Ceal Host observation value is oversized.");
1880
+ inspectHostKeys(value);
1881
+ }
1882
+ function inspectHostKeys(value) {
1883
+ if (Array.isArray(value)) {
1884
+ for (const entry of value) inspectHostKeys(entry);
1885
+ return;
1886
+ }
1887
+ if (value === null || typeof value !== "object") return;
1888
+ for (const [key, child] of Object.entries(value)) {
1889
+ if (HOST_RESERVED_KEY.test(key)) throw new TypeError("Ceal Host observation cannot restate Gateway-owned facts.");
1890
+ inspectHostKeys(child);
1891
+ }
1892
+ }
1893
+
1655
1894
  // packages/ceal-client-protocol/src/host-observation.ts
1656
1895
  var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
1657
1896
  var HOST_OBSERVATION_PRODUCER = /^[a-z][a-z0-9]{0,31}$/u;
@@ -1698,35 +1937,238 @@ function safeCount(value) {
1698
1937
  return Number.isSafeInteger(value) && Number(value) >= 0;
1699
1938
  }
1700
1939
  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);
1940
+ const record5 = operationRecord(value, "Ceal Host observation draft is invalid.");
1941
+ requirePrefixedRef(record5.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1942
+ requireClosedValue(record5.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1943
+ requireIsoTimestamp(record5.observed_at, "Ceal Host observation time is invalid.");
1944
+ assertHostObservationValue(record5.value, record5.observation_kind);
1706
1945
  }
1707
- var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1708
1946
  var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
1709
1947
  function isCealHostPromptObservationValue(value) {
1710
1948
  return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
1711
1949
  }
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
1950
  function assertHostObservationValue(value, kind) {
1714
1951
  if (value === void 0) invalid("Ceal Host observation value is invalid.");
1715
1952
  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);
1953
+ validateCealHostObservationValue(value);
1719
1954
  }
1720
- function inspectHostKeys(value) {
1721
- if (Array.isArray(value)) {
1722
- for (const entry of value) inspectHostKeys(entry);
1955
+
1956
+ // packages/ceal-client-protocol/src/host-usage-facts.ts
1957
+ import { createHash as createHash4 } from "node:crypto";
1958
+ var CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION = "ceal.host_usage_batch.v1";
1959
+ var CEAL_HOST_USAGE_BATCH_REF_PREFIX = "host-usage-batch:";
1960
+ var CEAL_HOST_USAGE_INGRESS_PATH = "/api/ceal/v2/host-usage-batches";
1961
+ var CEAL_HOST_USAGE_BATCH_MAX_BYTES = 1024 * 1024;
1962
+ var CEAL_HOST_USAGE_FACT_MAX_BYTES = 64 * 1024;
1963
+ var CEAL_HOST_USAGE_BATCH_MAX_FACTS = 256;
1964
+ var CEAL_HOST_USAGE_BATCH_MAX_GAPS = 16;
1965
+ var CEAL_HOST_USAGE_BATCH_ACK_STATUS = 204;
1966
+ var CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES = 65;
1967
+ var CODEX_COUNTER_SEMANTICS = ["last_delta_total_cumulative", "total_cumulative_only", "unknown"];
1968
+ var CODEX_CUMULATIVE_TRANSITIONS = ["baseline", "advanced", "same", "reset_or_correction", "not_observed"];
1969
+ var HOST_USAGE_COVERAGE_GAP_REASONS = ["source_usage_unavailable", "source_file_replaced", "source_file_retired", "outbox_capacity", "unsupported_source_shape"];
1970
+ function createCealHostUsageBatch(input) {
1971
+ const body = { schema_version: CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION, ...input };
1972
+ const batch = { ...body, batch_ref: `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}` };
1973
+ validateCealHostUsageBatch(batch);
1974
+ return batch;
1975
+ }
1976
+ function validateCealHostUsageBatch(value) {
1977
+ if (!isOperationRecord(value)) invalid("Ceal Host usage batch is invalid.");
1978
+ requireExactOperationKeys(value, ["schema_version", "batch_ref", "host_source_ref", "host_session_ref", "created_at", "source_ranges", "facts", "coverage_gaps"]);
1979
+ 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.");
1980
+ const { batch_ref: _ref, ...body } = value;
1981
+ if (value.batch_ref !== `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}`) invalid("Ceal Host usage batch reference is invalid.");
1982
+ validateBatchMetadata(value);
1983
+ validateBatchContents(value);
1984
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_BATCH_MAX_BYTES) invalid("Ceal Host usage batch exceeds its byte limit.");
1985
+ }
1986
+ function validateBatchMetadata(value) {
1987
+ requireSafeRef2(value.host_source_ref, "Ceal Host usage source is invalid.");
1988
+ requireSafeRef2(value.host_session_ref, "Ceal Host usage session is invalid.");
1989
+ requireIsoTimestamp(value.created_at, "Ceal Host usage batch time is invalid.");
1990
+ 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.");
1991
+ for (const range of value.source_ranges) validateSourceRange(range);
1992
+ }
1993
+ function validateBatchContents(value) {
1994
+ const facts = validateBatchFacts(value.facts);
1995
+ const gaps = validateBatchGaps(value.coverage_gaps);
1996
+ if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
1997
+ const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
1998
+ for (const fact of facts) {
1999
+ validateCealHostUsageFact(fact, value.host_session_ref);
2000
+ if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
2001
+ }
2002
+ for (const gap of gaps) {
2003
+ validateCoverageGap(gap);
2004
+ if (gap.source_file_ref !== null && !sourceFiles.has(gap.source_file_ref)) invalid("Ceal Host usage coverage gap is outside its source ranges.");
2005
+ }
2006
+ }
2007
+ function validateBatchFacts(value) {
2008
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_FACTS) invalid("Ceal Host usage fact count is invalid.");
2009
+ return value;
2010
+ }
2011
+ function validateBatchGaps(value) {
2012
+ if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) invalid("Ceal Host usage coverage is invalid.");
2013
+ return value;
2014
+ }
2015
+ function sourceRangeFileRef(value) {
2016
+ return isOperationRecord(value) ? value.source_file_ref : null;
2017
+ }
2018
+ function hostUsageFactReference(sourceFileRef2, sourceEventRef) {
2019
+ requireSafeRef2(sourceFileRef2, "Ceal Host usage file reference is invalid.");
2020
+ requireSafeRef2(sourceEventRef, "Ceal Host usage event reference is invalid.");
2021
+ return `host-usage-fact:${sha256(JSON.stringify({ source_file_ref: sourceFileRef2, source_event_ref: sourceEventRef }))}`;
2022
+ }
2023
+ function hostUsageSourceEventReference(sourceFileRef2, sourceEventIdentity) {
2024
+ requireSafeRef2(sourceFileRef2, "Ceal Host usage file reference is invalid.");
2025
+ if (typeof sourceEventIdentity !== "string" || sourceEventIdentity.length === 0 || sourceEventIdentity.length > 1024) invalid("Ceal Host usage event identity is invalid.");
2026
+ return `host-source-event:${sha256(JSON.stringify({ source_file_ref: sourceFileRef2, source_event_identity: sourceEventIdentity }))}`;
2027
+ }
2028
+ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, device, inode) {
2029
+ 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.");
2030
+ return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
2031
+ }
2032
+ function validateCealHostUsageFact(value, sessionRef) {
2033
+ if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
2034
+ requireFactByteLimit(value);
2035
+ if (value.producer === "codex_transcript") validateCodexFact(value);
2036
+ else if (value.producer === "claude_transcript") validateClaudeFact(value);
2037
+ else invalid("Ceal Host usage producer is invalid.");
2038
+ if (value.host_session_ref !== sessionRef) invalid("Ceal Host usage session does not match its batch.");
2039
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage file reference is invalid.");
2040
+ requireSafeRef2(value.source_event_ref, "Ceal Host usage event reference is invalid.");
2041
+ if (value.host_turn_ref !== null) requireSafeRef2(value.host_turn_ref, "Ceal Host usage turn reference is invalid.");
2042
+ if (value.requested_model !== null && !boundedText(value.requested_model, 256)) invalid("Ceal Host requested model is invalid.");
2043
+ if (value.reported_model !== null && !boundedText(value.reported_model, 256)) invalid("Ceal Host reported model is invalid.");
2044
+ if (value.fact_ref !== hostUsageFactReference(value.source_file_ref, value.source_event_ref)) invalid("Ceal Host usage identity is invalid.");
2045
+ }
2046
+ function requireFactByteLimit(value) {
2047
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_FACT_MAX_BYTES) invalid("Ceal Host usage fact exceeds its byte limit.");
2048
+ }
2049
+ function validateCodexFact(value) {
2050
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fact is invalid.");
2051
+ 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"]);
2052
+ if (value.producer !== "codex_transcript" || !safeInteger(value.source_event_ordinal)) invalid("Ceal Codex usage fact is invalid.");
2053
+ requireIsoTimestamp(value.observed_at, "Ceal Codex usage time is invalid.");
2054
+ if (!isOperationRecord(value.source_usage)) invalid("Ceal Codex source usage is invalid.");
2055
+ requireExactOperationKeys(value.source_usage, ["last_token_usage", "total_token_usage"]);
2056
+ if (value.source_usage.last_token_usage !== null) validateCodexUsageCounts(value.source_usage.last_token_usage);
2057
+ if (value.source_usage.total_token_usage !== null) validateCodexUsageCounts(value.source_usage.total_token_usage);
2058
+ 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.");
2059
+ validateNormalizedUsage(value.normalized_usage);
2060
+ }
2061
+ function validateClaudeFact(value) {
2062
+ if (!isOperationRecord(value)) invalid("Ceal Claude usage fact is invalid.");
2063
+ 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"]);
2064
+ validateClaudeIdentity(value);
2065
+ requireIsoTimestamp(value.observed_at, "Ceal Claude usage time is invalid.");
2066
+ validateClaudeSourceUsage(value.source_usage);
2067
+ validateClaudeSemantics(value);
2068
+ validateNormalizedUsage(value.normalized_usage);
2069
+ }
2070
+ function validateClaudeIdentity(value) {
2071
+ 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.");
2072
+ }
2073
+ function validateClaudeSourceUsage(value) {
2074
+ if (!isOperationRecord(value)) invalid("Ceal Claude source usage is invalid.");
2075
+ requireExactOperationKeys(value, ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"], ["cache_creation"]);
2076
+ for (const key of ["input_tokens", "output_tokens"]) if (!safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
2077
+ 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.");
2078
+ if (value.cache_creation !== void 0 && value.cache_creation !== null) validateClaudeCacheCreationUsage(value.cache_creation);
2079
+ }
2080
+ function validateClaudeCacheCreationUsage(value) {
2081
+ if (!isOperationRecord(value)) invalid("Ceal Claude cache creation usage is invalid.");
2082
+ requireExactOperationKeys(value, ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]);
2083
+ 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.");
2084
+ }
2085
+ function validateClaudeSemantics(value) {
2086
+ if (value.counter_semantics !== "assistant_message" || !validClaudeFinality(value.finality) || value.child_inclusion !== "unknown" || !validCorrectionSemantics(value.correction_semantics)) invalid("Ceal Claude usage semantics are invalid.");
2087
+ }
2088
+ function validClaudeFinality(value) {
2089
+ return value === "terminal" || value === "nonterminal" || value === "unknown";
2090
+ }
2091
+ function validCorrectionSemantics(value) {
2092
+ return value === "not_observed" || value === "unknown";
2093
+ }
2094
+ function validateCodexUsageCounts(value) {
2095
+ if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
2096
+ requireExactOperationKeys(value, CEAL_CODEX_USAGE_COUNT_FIELDS);
2097
+ for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
2098
+ 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.");
2099
+ }
2100
+ function validateNormalizedUsage(value) {
2101
+ if (!isOperationRecord(value)) invalid("Ceal normalized Host usage is invalid.");
2102
+ requireExactOperationKeys(value, ["input", "output", "total", "cached_input", "cache_write_input", "reasoning_output"]);
2103
+ for (const key of Object.keys(value)) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal normalized Host usage is invalid.");
2104
+ validateNormalizedTotals(value);
2105
+ }
2106
+ function validateNormalizedTotals(value) {
2107
+ validateNormalizedCountTotal(value);
2108
+ validateNormalizedInputSubsets(value);
2109
+ validateNormalizedOutputSubset(value);
2110
+ }
2111
+ function validateNormalizedCountTotal(value) {
2112
+ 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.");
2113
+ }
2114
+ function validateNormalizedInputSubsets(value) {
2115
+ 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.");
2116
+ }
2117
+ function validateNormalizedOutputSubset(value) {
2118
+ if (value.output !== null && value.reasoning_output !== null && Number(value.reasoning_output) > Number(value.output)) invalid("Ceal normalized Host output subset is inconsistent.");
2119
+ }
2120
+ function validateSourceRange(value) {
2121
+ if (!isOperationRecord(value)) invalid("Ceal Host usage source range is invalid.");
2122
+ requireExactOperationKeys(value, ["source_file_ref", "start_offset", "end_offset"]);
2123
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage source-file reference is invalid.");
2124
+ 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.");
2125
+ }
2126
+ function validateCealHostUsageCoverageGap(value) {
2127
+ if (!isOperationRecord(value)) invalid("Ceal Host usage coverage gap is invalid.");
2128
+ requireExactOperationKeys(value, ["reason", "source_file_ref", "start_offset", "end_offset", "omitted_count"]);
2129
+ if (!isOneOf(HOST_USAGE_COVERAGE_GAP_REASONS, value.reason) || !validUsageGapCount(value.reason, value.omitted_count)) invalid("Ceal Host usage coverage gap is invalid.");
2130
+ if (value.source_file_ref === null) {
2131
+ if (value.start_offset !== null || value.end_offset !== null) invalid("Ceal Host usage coverage gap range is invalid.");
1723
2132
  return;
1724
2133
  }
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);
2134
+ requireSafeRef2(value.source_file_ref, "Ceal Host usage coverage file reference is invalid.");
2135
+ 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.");
2136
+ }
2137
+ function validateCoverageGap(value) {
2138
+ validateCealHostUsageCoverageGap(value);
2139
+ }
2140
+ function validUsageGapCount(reason, value) {
2141
+ return value === null ? reason !== "outbox_capacity" : safeInteger(value) && Number(value) >= 1;
2142
+ }
2143
+ function isOneOf(values, value) {
2144
+ return typeof value === "string" && values.some((candidate) => candidate === value);
2145
+ }
2146
+ function isCealHostUsageBatchReference(value) {
2147
+ return typeof value === "string" && value.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX) && isCealDigest(value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length));
2148
+ }
2149
+ function cealHostUsageBatchObjectDigestFromFileName(value) {
2150
+ if (!value.endsWith(".json")) return null;
2151
+ const digest = value.slice(0, -5);
2152
+ return isCealDigest(digest) ? digest : null;
2153
+ }
2154
+ function cealHostUsageBatchObjectDigestFromReference(value) {
2155
+ return isCealHostUsageBatchReference(value) ? value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length) : null;
2156
+ }
2157
+ function safeInteger(value) {
2158
+ return Number.isSafeInteger(value) && Number(value) >= 0;
2159
+ }
2160
+ function boundedText(value, maximum) {
2161
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters(value);
2162
+ }
2163
+ function hasControlCharacters(value) {
2164
+ for (const character of value) {
2165
+ const code2 = character.codePointAt(0);
2166
+ if (code2 !== void 0 && (code2 < 32 || code2 === 127)) return true;
1729
2167
  }
2168
+ return false;
2169
+ }
2170
+ function sha256(value) {
2171
+ return createHash4("sha256").update(value, "utf8").digest("hex");
1730
2172
  }
1731
2173
 
1732
2174
  // packages/ceal-client-protocol/src/host-prompt-ref.ts
@@ -1833,11 +2275,72 @@ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSch
1833
2275
  var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
1834
2276
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
1835
2277
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
2278
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.refusal_schema_name, fields: hostInvocationAuthenticationContract.refusal_fields });
1836
2279
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
1837
2280
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
1838
2281
  var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
1839
2282
  var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
2283
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
1840
2284
  var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
2285
+ function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
2286
+ const messages = [];
2287
+ let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
2288
+ for (const candidate of newestFirst.slice(0, CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES)) {
2289
+ 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 } : {} };
2290
+ if (encodedMessageWindowBytes([...messages, complete]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) {
2291
+ messages.push(Object.freeze(complete));
2292
+ continue;
2293
+ }
2294
+ const clipped = clipHumanMessageToWindow(messages, candidate);
2295
+ if (clipped === null) {
2296
+ truncated = true;
2297
+ break;
2298
+ }
2299
+ messages.push(Object.freeze(clipped));
2300
+ }
2301
+ return Object.freeze({ messages: Object.freeze(messages), truncated });
2302
+ }
2303
+ function encodedMessageWindowBytes(messages) {
2304
+ return new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2305
+ }
2306
+ function clipHumanMessageToWindow(prefix, candidate) {
2307
+ const clipped = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: "", text_truncated: true };
2308
+ const available = CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES - encodedMessageWindowBytes([...prefix, clipped]);
2309
+ if (available < 0) return null;
2310
+ const text = [];
2311
+ let used = 0;
2312
+ for (const point of candidate.text) {
2313
+ const encodedPoint = JSON.stringify(point);
2314
+ const cost = new TextEncoder().encode(encodedPoint).byteLength - 2;
2315
+ if (used + cost > available) break;
2316
+ text.push(point);
2317
+ used += cost;
2318
+ }
2319
+ const result = { ...clipped, text: text.join("") };
2320
+ return encodedMessageWindowBytes([...prefix, result]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES ? result : null;
2321
+ }
2322
+ function decodeCealHostInvocationHumanMessageWindow(value) {
2323
+ 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();
2324
+ const messages = value.messages.map(decodeHumanMessage);
2325
+ const bytes = new TextEncoder().encode(JSON.stringify(messages)).byteLength;
2326
+ if (bytes > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) throw invalidInvocationContextRequest();
2327
+ return Object.freeze({ messages: Object.freeze(messages), truncated: value.truncated });
2328
+ }
2329
+ function decodeHumanMessage(candidate) {
2330
+ 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();
2331
+ if (candidate.text_truncated !== void 0 && candidate.text_truncated !== true) throw invalidInvocationContextRequest();
2332
+ 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 } : {} });
2333
+ }
2334
+ function safeReference(value) {
2335
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
2336
+ }
2337
+ function exactOptionalKeys(value, required, optional = []) {
2338
+ const keys = Object.keys(value);
2339
+ return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => required.includes(key) || optional.includes(key));
2340
+ }
2341
+ function invalidInvocationContextRequest() {
2342
+ return new TypeError("The Host invocation context request is invalid.");
2343
+ }
1841
2344
  function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1842
2345
  const clientNonce = contract.host_invocation_authentication.client_nonce;
1843
2346
  return {
@@ -1847,40 +2350,20 @@ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTR
1847
2350
  };
1848
2351
  }
1849
2352
  var hostNonceContract = deriveCealHostInvocationNonceContract();
1850
- var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
1851
2353
  var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
1852
2354
  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
2355
  var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
1867
2356
  "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"
2357
+ "request_creation_refused"
1875
2358
  ]);
1876
2359
  var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1877
2360
  "invalid_arguments",
1878
2361
  "options_invalid",
1879
2362
  "session_unavailable",
1880
2363
  "context_unavailable",
2364
+ "activation_wait_exhausted",
1881
2365
  "context_replaced",
1882
2366
  "no_binding",
1883
- "context_stale",
1884
2367
  "context_expired",
1885
2368
  "host_source_refused",
1886
2369
  "host_credential_refused",
@@ -1897,23 +2380,35 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1897
2380
  "relay_failed",
1898
2381
  "host_refusal_invalid"
1899
2382
  ]);
2383
+ var CEAL_HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2384
+ "permission_denied",
2385
+ "socket_missing",
2386
+ "connection_refused",
2387
+ "closed_early",
2388
+ "response_invalid",
2389
+ "timed_out",
2390
+ "cancelled",
2391
+ "unavailable"
2392
+ ]);
1900
2393
  var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1901
2394
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
1902
2395
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
1903
2396
  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" }),
1905
- context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
2397
+ // This reason cannot distinguish a Codex side conversation from a missing
2398
+ // context in a regular session, so guidance must leave that choice to the caller.
2399
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2400
+ activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2401
+ context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
1906
2402
  // `no_binding` now means the producer has no real current Host session. The
1907
2403
  // Host Relay never uses it for an uncreated Gateway Request; there is no
1908
2404
  // useful retry until the consumer is running inside a Host session.
1909
2405
  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
- context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
2406
+ context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
1912
2407
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
1913
2408
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
1914
2409
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
1915
2410
  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" }),
2411
+ contract_mismatch: Object.freeze({ classification: "host_contract_mismatch", next_action: "upgrade_ceal_client" }),
1917
2412
  gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
1918
2413
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
1919
2414
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
@@ -1921,7 +2416,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1921
2416
  relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
1922
2417
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
1923
2418
  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" }),
2419
+ relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
1925
2420
  host_refusal_invalid: Object.freeze({ classification: "host_refusal_invalid", next_action: "answer_with_gap" })
1926
2421
  });
1927
2422
 
@@ -1935,10 +2430,13 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
1935
2430
  "activation_recorded",
1936
2431
  "activation_failed",
1937
2432
  "watcher_scan_failed",
2433
+ "usage_capture_failed",
2434
+ "usage_upload_failed",
1938
2435
  "activation_wait_skipped",
1939
2436
  "activation_wait_engaged",
1940
2437
  "activation_wait_completed",
1941
- "activation_wait_exhausted"
2438
+ "activation_wait_exhausted",
2439
+ "invocation_authentication_failed"
1942
2440
  ]);
1943
2441
  var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1944
2442
  "malformed_line",
@@ -1948,11 +2446,22 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1948
2446
  "size_budget",
1949
2447
  "symlink"
1950
2448
  ]);
2449
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_WATCHER_OPTIONAL_FIELDS = vocabulary(["failure_kind", "cause"]);
2450
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_OPTIONAL_FIELDS = vocabulary(["cause"]);
2451
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE = "^[a-z][a-z0-9_]{0,63}(?::[A-Za-z][A-Za-z0-9_]{0,63})?$";
2452
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES = Object.freeze([
2453
+ ...CEAL_HOST_AUTHENTICATION_CAUSES,
2454
+ ...CEAL_HOST_RELAY_EXCHANGE_FAILURES.map((failure) => `relay_exchange:${failure}`)
2455
+ ]);
2456
+ var hostServiceDiagnosticCausePattern = new RegExp(CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE, "u");
2457
+ function isCealHostServiceDiagnosticCause(value, event) {
2458
+ return typeof value === "string" && hostServiceDiagnosticCausePattern.test(value) && (event !== "invocation_authentication_failed" || CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES.includes(value));
2459
+ }
1951
2460
 
1952
2461
  // packages/ceal-client-protocol/src/client-result-materialization.ts
1953
2462
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
1954
2463
  var REQUIRED_FIELDS2 = Object.freeze(["schema_version", "operation_id", "path", "sha256"]);
1955
- var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "items_path", "row_count", "result_complete", "coverage", "local_result_root", "model_disclosure", "continue_argv", "how_to_read"]);
2464
+ var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "local_result_root", "request_context_argv", "how_to_read"]);
1956
2465
 
1957
2466
  // packages/ceal-client-protocol/src/discovery-manifest.ts
1958
2467
  var DISCOVERY_MANIFEST_KEYS = CEAL_CLIENT_WIRE_CONTRACT.command_response.discovery_manifest_fields;
@@ -2034,12 +2543,14 @@ var ADMIN_SOURCE_OWNERS = vocabulary([
2034
2543
  "resource",
2035
2544
  "prompt",
2036
2545
  "usage",
2546
+ "provider_request_lifecycle",
2037
2547
  "connector",
2038
2548
  "session",
2039
2549
  "knowledge",
2040
2550
  "policy"
2041
2551
  ]);
2042
2552
  var ADMIN_COMPLETENESS_STATES = vocabulary(["complete", "partial", "unknown"]);
2553
+ var ADMIN_PROVIDER_REQUEST_CAPTURE_HEALTH_STATES = vocabulary(["available", "missing", "invalid", "unreadable"]);
2043
2554
  var ADMIN_OPERATION_OUTCOMES = vocabulary(["completed", "failed", "denied", "cancelled", "unknown"]);
2044
2555
  var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
2045
2556
  var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
@@ -2078,7 +2589,7 @@ function waitForAbort(signal, milliseconds) {
2078
2589
  import { execFile } from "node:child_process";
2079
2590
  import { constants } from "node:fs";
2080
2591
  import { lstat, open } from "node:fs/promises";
2081
- import { dirname, win32 as win323 } from "node:path";
2592
+ import { dirname, join as join2, win32 as win323 } from "node:path";
2082
2593
  import { fileURLToPath } from "node:url";
2083
2594
  var SecureFileCustodyError = class extends Error {
2084
2595
  name = "SecureFileCustodyError";
@@ -2096,6 +2607,7 @@ var SecureFileCustodyError = class extends Error {
2096
2607
  }
2097
2608
  };
2098
2609
  var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
2610
+ var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
2099
2611
  var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
2100
2612
  var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
2101
2613
  function secureOpenFlags(flags, platform) {
@@ -2138,18 +2650,46 @@ async function assertWindowsIdentityStable(handle, first, path) {
2138
2650
  }
2139
2651
  async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
2140
2652
  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);
2653
+ const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2142
2654
  if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
2143
2655
  if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
2144
2656
  if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
2145
2657
  throw securefsRefusal(result.stderr);
2146
2658
  }
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();
2659
+ async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
2660
+ const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
2661
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2662
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
2663
+ throw securefsRefusal(result.stderr);
2664
+ }
2665
+ async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
2666
+ 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.");
2667
+ const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
2668
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
2669
+ if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
2670
+ throw securefsRefusal(result.stderr);
2671
+ }
2672
+ async function isPrivateWindowsDirectory(path, custody = {}) {
2673
+ await lstat(path);
2674
+ try {
2675
+ const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
2676
+ if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
2677
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
2678
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
2679
+ const refusal = securefsRefusal(result.stderr);
2680
+ if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
2681
+ throw refusal;
2682
+ } catch (error) {
2683
+ if (error instanceof SecureFileCustodyError) throw error;
2684
+ throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
2685
+ }
2686
+ }
2687
+ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2688
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
2689
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2150
2690
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2151
2691
  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) => {
2692
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2153
2693
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2154
2694
  if (exitCode === null) {
2155
2695
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2157,6 +2697,8 @@ async function runWindowsSecurefs(args, maxBytes, custody) {
2157
2697
  }
2158
2698
  resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
2159
2699
  });
2700
+ child.stdin?.on("error", () => void 0);
2701
+ child.stdin?.end(stdin);
2160
2702
  });
2161
2703
  }
2162
2704
  function securefsRefusal(stderr) {
@@ -2174,9 +2716,9 @@ function securefsRefusal(stderr) {
2174
2716
  if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
2175
2717
  return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
2176
2718
  }
2177
- function resolveInstalledHostExecutable() {
2719
+ function resolveInstalledHostExecutable(platform) {
2178
2720
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2179
- return win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
2721
+ return platform === "win32" ? win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2180
2722
  }
2181
2723
  function isRecord(value) {
2182
2724
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2192,6 +2734,11 @@ function isPrivateFileMode(mode, platform = process.platform, _handle) {
2192
2734
  if (platform === "win32") return false;
2193
2735
  return (mode & 63) === 0;
2194
2736
  }
2737
+ async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
2738
+ if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
2739
+ const entry = await lstat(path);
2740
+ return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
2741
+ }
2195
2742
 
2196
2743
  // host/producer-service.ts
2197
2744
  var SAFE_REF2 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
@@ -2218,7 +2765,8 @@ function parseHostProducerServeArgs(args, platform = process.platform) {
2218
2765
  async function readHostProducerConfig(descriptor, configPath, platform = process.platform, custody = {}) {
2219
2766
  const config = decodeHostProducerConfigText(descriptor, await readProducerConfigText(configPath, platform, hostProducerError, custody), platform);
2220
2767
  const path = platform === "win32" ? win324 : posix3;
2221
- const root = path.resolve(config.outbox_dir, "../../../../..");
2768
+ const registrationStateFile = hostProducerRegistrationStateFile(config.outbox_dir, platform);
2769
+ const root = path.dirname(registrationStateFile);
2222
2770
  try {
2223
2771
  assertHostProducerSourcePaths(root, config, descriptor.producer_id, platform);
2224
2772
  } catch (error) {
@@ -2232,10 +2780,21 @@ function decodeHostProducerConfigText(descriptor, text, platform = process.platf
2232
2780
  const { extra_paths: extras, ...core } = decoded;
2233
2781
  return Object.freeze(descriptor.config({ schema_version: descriptor.schema, ...core }, extras));
2234
2782
  }
2235
- async function serveHostProducer(descriptor, config, signal, dependencies = {}) {
2236
- await serveProducer(descriptor.runtime_options(config), config, signal, dependencies.drain ?? descriptor.drain, dependencies.wait);
2783
+ async function serveHostProducer(descriptor, config, signal, dependencies) {
2784
+ const runtimeOptions = descriptor.runtime_options(config);
2785
+ const serving = serveProducer(runtimeOptions, config, signal, dependencies.drain ?? descriptor.drain, dependencies.wait);
2786
+ if (descriptor.background === void 0 || dependencies.drain !== void 0) {
2787
+ await serving;
2788
+ return;
2789
+ }
2790
+ const background = descriptor.background(config, signal, dependencies);
2791
+ await Promise.all([serving, background]);
2792
+ }
2793
+ function hostProducerRegistrationStateFile(outboxDirectory, platform = process.platform) {
2794
+ const path = platform === "win32" ? win324 : posix3;
2795
+ return path.join(path.resolve(outboxDirectory, "../../../../.."), "registration.json");
2237
2796
  }
2238
- async function runHostProducerCli(descriptor, args, signal, dependencies = {}) {
2797
+ async function runHostProducerCli(descriptor, args, signal, dependencies) {
2239
2798
  await serveHostProducer(descriptor, await readHostProducerConfig(descriptor, parseHostProducerServeArgs(args)), signal, dependencies);
2240
2799
  }
2241
2800
  function hostProducerError(code2, message = code2) {
@@ -2429,9 +2988,958 @@ function boundedMilliseconds(value) {
2429
2988
  return positive(value, 6e4) && Number(value) >= 25;
2430
2989
  }
2431
2990
 
2991
+ // host/relay/src/host-registration-state.ts
2992
+ import { constants as constants3 } from "node:fs";
2993
+ import { dirname as dirname2 } from "node:path";
2994
+ var HOST_REGISTRATION_STATE_SCHEMA = "ceal.host_registration_state.v1";
2995
+ var HOST_REGISTRATION_STATE_KEYS = Object.freeze([
2996
+ "credential_generation",
2997
+ "gateway_request_origin",
2998
+ "host_access_token",
2999
+ "host_installation_ref",
3000
+ "host_source_ref",
3001
+ "registration_attempt_ref",
3002
+ "schema_version",
3003
+ "status"
3004
+ ]);
3005
+ var HOST_REGISTRATION_STATE_MAX_BYTES = 65536;
3006
+ var HostRegistrationStateError = class extends Error {
3007
+ name = "HostRegistrationStateError";
3008
+ code = "credential";
3009
+ };
3010
+ async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
3011
+ let raw;
3012
+ try {
3013
+ await assertPrivateRegistrationDirectory(dirname2(path), platform, custody);
3014
+ raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
3015
+ } catch (error) {
3016
+ throw registrationReadError(error);
3017
+ }
3018
+ 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}`)}.`);
3019
+ let value;
3020
+ try {
3021
+ value = JSON.parse(raw);
3022
+ } catch {
3023
+ throw new HostRegistrationStateError("Host registration state is invalid.");
3024
+ }
3025
+ return decodeHostRegistrationAuthority(value, expectedHostSourceRef);
3026
+ }
3027
+ async function readWindowsRegistration(path, custody) {
3028
+ const bytes = await readPrivateFileWithSecurefs(path, HOST_REGISTRATION_STATE_MAX_BYTES, custody);
3029
+ try {
3030
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
3031
+ } catch {
3032
+ throw new HostRegistrationStateError("Host registration state is invalid.");
3033
+ }
3034
+ }
3035
+ async function readPosixRegistration(path, platform, custody) {
3036
+ const handle = await openNoFollow(path, constants3.O_RDONLY, void 0, platform, custody);
3037
+ try {
3038
+ const stats = await handle.stat();
3039
+ 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.");
3040
+ return await handle.readFile("utf8");
3041
+ } finally {
3042
+ await handle.close();
3043
+ }
3044
+ }
3045
+ function registrationReadError(error) {
3046
+ if (error instanceof HostRegistrationStateError) return error;
3047
+ if (error instanceof SecureFileCustodyError && error.reason === "not_private") return new HostRegistrationStateError("Host registration file is not private to its owner.");
3048
+ return new HostRegistrationStateError("Host registration file is unavailable.");
3049
+ }
3050
+ function decodeHostRegistrationAuthority(value, expectedHostSourceRef) {
3051
+ const keys = HOST_REGISTRATION_STATE_KEYS;
3052
+ const fieldCount = record(value) ? Object.keys(value).length : 0;
3053
+ const missing = record(value) ? keys.filter((key) => !Object.hasOwn(value, key)).length : keys.length;
3054
+ 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" }])}.`);
3055
+ 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>" }])}.`);
3056
+ 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" }])}.`);
3057
+ 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")}.`);
3058
+ return { gateway_request_origin: value.gateway_request_origin, host_access_token: value.host_access_token };
3059
+ }
3060
+ function validRegistrationIdentity(value, expectedHostSourceRef) {
3061
+ 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;
3062
+ }
3063
+ function validRegistrationCredential(value) {
3064
+ return Number.isSafeInteger(value.credential_generation) && Number(value.credential_generation) > 0 && validHostAccessToken(value.host_access_token);
3065
+ }
3066
+ function validHostAccessToken(value) {
3067
+ return typeof value === "string" && CEAL_HOST_ACCESS_TOKEN_PATTERN.test(value);
3068
+ }
3069
+ function validGatewayOrigin(value) {
3070
+ try {
3071
+ if (typeof value !== "string" || /\s|\0/u.test(value)) return false;
3072
+ const parsed = new URL(value);
3073
+ const hostname = parsed.hostname.toLowerCase().replace(/\.+$/u, "");
3074
+ return hostname !== "" && validGatewayPort(parsed.port) && (loopbackHttpOrigin(parsed, hostname) || parsed.protocol === "https:") && cleanOriginPath(parsed) && bareOriginSuffix(value);
3075
+ } catch {
3076
+ return false;
3077
+ }
3078
+ }
3079
+ function loopbackHttpOrigin(parsed, hostname) {
3080
+ return parsed.protocol === "http:" && parsed.port !== "" && (hostname === "127.0.0.1" || hostname === "[::1]");
3081
+ }
3082
+ function validGatewayPort(port) {
3083
+ if (port === "") return true;
3084
+ const numeric = Number(port);
3085
+ return Number.isInteger(numeric) && numeric >= 1 && numeric <= 65535;
3086
+ }
3087
+ function cleanOriginPath(parsed) {
3088
+ return parsed.username === "" && parsed.password === "" && parsed.pathname === "/" && parsed.search === "" && parsed.hash === "";
3089
+ }
3090
+ function bareOriginSuffix(value) {
3091
+ const schemeEnd = value.indexOf("://");
3092
+ const authority = schemeEnd < 0 ? "" : value.slice(schemeEnd + 3);
3093
+ const suffixOffset = authority.search(/[\\/?#]/u);
3094
+ const rawSuffix = suffixOffset < 0 ? "" : authority.slice(suffixOffset);
3095
+ return rawSuffix === "" || rawSuffix === "/";
3096
+ }
3097
+ async function assertPrivateRegistrationDirectory(path, platform, custody) {
3098
+ if (!await isPrivateDirectory(path, platform, custody)) throw new HostRegistrationStateError("Host registration directory is not private to its owner.");
3099
+ }
3100
+ function record(value) {
3101
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3102
+ }
3103
+
3104
+ // host/relay/src/host-usage-facts-store.ts
3105
+ import { createHash as createHash5 } from "node:crypto";
3106
+ import { constants as constants4 } from "node:fs";
3107
+ import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3108
+ import { dirname as dirname4, join as join3 } from "node:path";
3109
+
3110
+ // host/relay/src/durable-atomic-replacement.ts
3111
+ import { lstat as lstat3, mkdir, open as open2, rename, unlink } from "node:fs/promises";
3112
+ import { dirname as dirname3 } from "node:path";
3113
+
3114
+ // host/windows-rename-retry.ts
3115
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
3116
+ var RETRY_WINDOW_MS = 1e4;
3117
+ var RETRY_START_DELAY_MS = 100;
3118
+ var RETRY_MAX_DELAY_MS = 2e3;
3119
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
3120
+ var WindowsRenameRetryError = class extends Error {
3121
+ code = "rename_unavailable";
3122
+ constructor(target, attempts, options = {}) {
3123
+ 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);
3124
+ this.name = "WindowsRenameRetryError";
3125
+ }
3126
+ };
3127
+ function resolveRetrySchedule(tuning) {
3128
+ return {
3129
+ windowMs: tuning.windowMs ?? RETRY_WINDOW_MS,
3130
+ startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
3131
+ maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
3132
+ sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
3133
+ now: tuning.now ?? (() => Date.now())
3134
+ };
3135
+ }
3136
+ async function renameWithWindowsRetry(operation, tuning) {
3137
+ const schedule = resolveRetrySchedule(tuning);
3138
+ const deadline = schedule.now() + schedule.windowMs;
3139
+ let delayMs = schedule.startDelayMs;
3140
+ let attempts = 0;
3141
+ for (; ; ) {
3142
+ attempts += 1;
3143
+ try {
3144
+ await operation();
3145
+ return;
3146
+ } catch (error) {
3147
+ if (tuning.platform !== "win32" || !isRetryableRenameError(error)) throw error;
3148
+ await sleepWithinWindow(schedule, deadline, delayMs, () => new WindowsRenameRetryError(tuning.target, attempts, { cause: error }));
3149
+ delayMs = Math.min(delayMs * 2, schedule.maxDelayMs);
3150
+ }
3151
+ }
3152
+ }
3153
+ async function sleepWithinWindow(schedule, deadline, delayMs, exhausted) {
3154
+ if (schedule.now() >= deadline) throw exhausted();
3155
+ await schedule.sleep(Math.min(delayMs, deadline - schedule.now()));
3156
+ if (schedule.now() >= deadline) throw exhausted();
3157
+ }
3158
+ function isRetryableRenameError(error) {
3159
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && RETRYABLE_CODES.has(error.code);
3160
+ }
3161
+
3162
+ // host/relay/src/durable-atomic-replacement.ts
3163
+ var DEFAULT_PORT = {
3164
+ platform: process.platform,
3165
+ mkdir: (path, options) => mkdir(path, options),
3166
+ lstat: (path) => lstat3(path),
3167
+ open_file: (path) => open2(path, "wx", 384),
3168
+ rename,
3169
+ unlink,
3170
+ open_directory: (path) => open2(path),
3171
+ unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
3172
+ };
3173
+ async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
3174
+ const parent = dirname3(target);
3175
+ await port.mkdir(parent, { recursive: true, mode: 448 });
3176
+ const parentStats = await port.lstat(parent);
3177
+ const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
3178
+ const ownerPrivate = port.platform === "win32" || isOwnedBy(parentStats.uid, expectedUid) && isPrivateFileMode(parentStats.mode, port.platform);
3179
+ 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 }])}.`);
3180
+ const temporary = `${target}.${port.unique_ref()}.new`;
3181
+ let staged;
3182
+ const failures = [];
3183
+ try {
3184
+ staged = await port.open_file(temporary);
3185
+ await staged.writeFile(data, typeof data === "string" ? { encoding: "utf8" } : void 0);
3186
+ await staged.sync();
3187
+ const closing = staged;
3188
+ staged = void 0;
3189
+ await closing.close();
3190
+ await renameWithWindowsRetry(() => port.rename(temporary, target), { ...port.rename_retry, platform: port.platform, target });
3191
+ await syncParentDirectory(parent, port);
3192
+ } catch (error) {
3193
+ failures.push(error);
3194
+ }
3195
+ await closeStaged(staged, failures);
3196
+ await removeTemporary(temporary, port, failures);
3197
+ throwFailures(failures);
3198
+ }
3199
+ async function syncParentDirectory(path, port) {
3200
+ if (port.platform === "win32") return;
3201
+ const handle = await port.open_directory(path);
3202
+ let failure;
3203
+ try {
3204
+ await handle.sync();
3205
+ } catch (error) {
3206
+ if (!directorySyncUnsupported(error)) failure = error;
3207
+ }
3208
+ try {
3209
+ await handle.close();
3210
+ } catch (error) {
3211
+ if (failure === void 0) failure = error;
3212
+ else failure = new AggregateError([failure, error], "Host Relay directory sync and close failed.");
3213
+ }
3214
+ if (failure !== void 0) throw failure;
3215
+ }
3216
+ async function closeStaged(staged, failures) {
3217
+ if (staged !== void 0) try {
3218
+ await staged.close();
3219
+ } catch (error) {
3220
+ failures.push(error);
3221
+ }
3222
+ }
3223
+ async function removeTemporary(path, port, failures) {
3224
+ try {
3225
+ await port.unlink(path);
3226
+ } catch (error) {
3227
+ if (errorCode(error) !== "ENOENT") failures.push(error);
3228
+ }
3229
+ }
3230
+ function throwFailures(failures) {
3231
+ if (failures.length === 1) throw failures[0];
3232
+ if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
3233
+ }
3234
+ function directorySyncUnsupported(error) {
3235
+ return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
3236
+ }
3237
+ function errorCode(error) {
3238
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3239
+ }
3240
+
3241
+ // host/relay/src/host-usage-facts-store.ts
3242
+ var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3243
+ var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3244
+ var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
3245
+ var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
3246
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
3247
+ var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
3248
+ var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
3249
+ var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
3250
+ var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
3251
+ var HostUsageFactsStore = class {
3252
+ root;
3253
+ sessions;
3254
+ batches;
3255
+ platform;
3256
+ custody;
3257
+ afterPendingWrite;
3258
+ afterBatchPublish;
3259
+ sessionDirectoryCursor;
3260
+ constructor(options) {
3261
+ this.root = join3(options.outbox_dir, "usage-facts");
3262
+ this.sessions = join3(this.root, "sessions");
3263
+ this.batches = join3(this.root, "batches");
3264
+ this.platform = options.platform ?? process.platform;
3265
+ this.custody = options.secure_file_custody ?? {};
3266
+ this.afterPendingWrite = options.afterPendingWrite;
3267
+ this.afterBatchPublish = options.afterBatchPublish;
3268
+ }
3269
+ async prepare() {
3270
+ for (const directory of [this.root, this.sessions, this.batches]) {
3271
+ await preparePrivateDirectory(directory, this.platform, this.custody);
3272
+ }
3273
+ }
3274
+ async close() {
3275
+ const cursor = this.sessionDirectoryCursor;
3276
+ this.sessionDirectoryCursor = void 0;
3277
+ await cursor?.close();
3278
+ }
3279
+ async readState(producer, hostSourceRef, hostSessionRef) {
3280
+ await this.prepare();
3281
+ const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3282
+ const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3283
+ if (value === null) return null;
3284
+ validateState(value, producer, hostSourceRef, hostSessionRef);
3285
+ return value;
3286
+ }
3287
+ createState(producer, hostSourceRef, hostSessionRef) {
3288
+ return {
3289
+ schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
3290
+ producer,
3291
+ host_source_ref: hostSourceRef,
3292
+ host_session_ref: hostSessionRef,
3293
+ cursors: {},
3294
+ eligible_batches: [],
3295
+ coverage_gaps: [],
3296
+ coverage_gap_created_at: null
3297
+ };
3298
+ }
3299
+ async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
3300
+ let state = await this.readState(producer, hostSourceRef, hostSessionRef);
3301
+ if (state === null) {
3302
+ state = this.createState(producer, hostSourceRef, hostSessionRef);
3303
+ state = await this.writeCursor(state, sourceSlot, initial);
3304
+ }
3305
+ state = await this.recoverPending(state);
3306
+ if (state.quarantined_reason !== void 0) return null;
3307
+ state = await this.commitCoverageGaps(state, createdAt);
3308
+ const cursor = state.cursors[sourceSlot];
3309
+ return cursor === void 0 ? null : { state, cursor };
3310
+ }
3311
+ async writeCursor(state, sourceSlot, cursor) {
3312
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3313
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3314
+ if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
3315
+ const current = latest.cursors[sourceSlot];
3316
+ if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
3317
+ const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
3318
+ await this.writeState(updated);
3319
+ return updated;
3320
+ });
3321
+ }
3322
+ async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
3323
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3324
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3325
+ return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
3326
+ });
3327
+ }
3328
+ async recoverPending(state) {
3329
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3330
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3331
+ const recovered = await this.finishPendingTransition(latest);
3332
+ await this.sweepOrphanedBatches(recovered);
3333
+ return recovered;
3334
+ });
3335
+ }
3336
+ /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3337
+ async sweepOrphanedBatches(state) {
3338
+ await this.prepare();
3339
+ const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3340
+ await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3341
+ const expected = expectedBatchNames(state);
3342
+ const directory = await opendir(directoryPath);
3343
+ let inspected = 0;
3344
+ let deleted = 0;
3345
+ try {
3346
+ while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
3347
+ const entry = await directory.read();
3348
+ if (entry === null) break;
3349
+ inspected += 1;
3350
+ if (!isOrphanBatchEntry(entry, expected)) continue;
3351
+ await unlink2(join3(directoryPath, entry.name));
3352
+ deleted += 1;
3353
+ }
3354
+ } finally {
3355
+ await directory.close();
3356
+ }
3357
+ if (deleted > 0) await syncDirectory(directoryPath, this.platform);
3358
+ return deleted;
3359
+ }
3360
+ async commitCoverageGaps(state, createdAt) {
3361
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3362
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3363
+ if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
3364
+ const sourceRanges = coverageRanges(latest.coverage_gaps);
3365
+ const canonical = createCealHostUsageBatch({
3366
+ host_source_ref: latest.host_source_ref,
3367
+ host_session_ref: latest.host_session_ref,
3368
+ created_at: latest.coverage_gap_created_at ?? createdAt,
3369
+ source_ranges: sourceRanges,
3370
+ facts: [],
3371
+ coverage_gaps: latest.coverage_gaps
3372
+ });
3373
+ const cursor = firstCursor(latest);
3374
+ if (cursor === null) return latest;
3375
+ return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
3376
+ });
3377
+ }
3378
+ async nextUploadCandidate(producer, hostSourceRef) {
3379
+ await this.prepare();
3380
+ const names = await this.readNextSessionNames();
3381
+ for (const name of names) {
3382
+ const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3383
+ if (state === null) continue;
3384
+ validateStateOwner(state, producer, hostSourceRef);
3385
+ let validated = state;
3386
+ if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
3387
+ else validated = await this.recoverPending(validated);
3388
+ if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
3389
+ const next = validated.eligible_batches[0];
3390
+ if (next === void 0) continue;
3391
+ const batch = await this.readBatch(validated, next.batch_ref);
3392
+ return { state: validated, batch };
3393
+ }
3394
+ return null;
3395
+ }
3396
+ async readNextSessionNames() {
3397
+ this.sessionDirectoryCursor ??= await opendir(this.sessions);
3398
+ const names = [];
3399
+ let inspected = 0;
3400
+ while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
3401
+ const entry = await this.sessionDirectoryCursor.read();
3402
+ if (entry === null) {
3403
+ await this.sessionDirectoryCursor.close();
3404
+ this.sessionDirectoryCursor = void 0;
3405
+ break;
3406
+ }
3407
+ inspected += 1;
3408
+ if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
3409
+ }
3410
+ return names;
3411
+ }
3412
+ async acknowledge(state, batchRef) {
3413
+ await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3414
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3415
+ if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
3416
+ const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
3417
+ if (remaining.length === latest.eligible_batches.length) return;
3418
+ await this.writeState({ ...latest, eligible_batches: remaining });
3419
+ await removeFileIfPresent(this.batchPath(state, batchRef));
3420
+ });
3421
+ }
3422
+ async quarantine(state, reason) {
3423
+ return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
3424
+ const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
3425
+ const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
3426
+ await this.writeState(updated);
3427
+ return updated;
3428
+ });
3429
+ }
3430
+ async retireCursor(state, sourceSlot, cursor, gap) {
3431
+ return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
3432
+ }
3433
+ async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
3434
+ if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
3435
+ if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
3436
+ const queued = await this.publishTransitionBatch(state, batch);
3437
+ const pending = {
3438
+ source_slot: sourceSlot,
3439
+ before_cursor: beforeCursor,
3440
+ after_cursor: afterCursor,
3441
+ batch_ref: queued.batch_ref,
3442
+ batch_bytes: queued.batch_bytes,
3443
+ gap_delta: [...gapDelta, ...queued.overflow_gaps],
3444
+ clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
3445
+ };
3446
+ const prepared = { ...state, pending_transition: pending };
3447
+ await this.writeState(prepared);
3448
+ await this.afterPendingWrite?.();
3449
+ return await this.finishPendingTransition(prepared);
3450
+ }
3451
+ async publishTransitionBatch(state, batch) {
3452
+ if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
3453
+ const serialized = serializeBatch(batch);
3454
+ if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
3455
+ await this.writeImmutableBatch(state, batch, serialized);
3456
+ await this.afterBatchPublish?.();
3457
+ return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
3458
+ }
3459
+ async finishPendingTransition(state) {
3460
+ const pending = state.pending_transition;
3461
+ if (pending === void 0 || state.quarantined_reason !== void 0) return state;
3462
+ const current = state.cursors[pending.source_slot];
3463
+ if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
3464
+ const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
3465
+ await this.writeState(quarantined);
3466
+ return quarantined;
3467
+ }
3468
+ let cursors = state.cursors;
3469
+ if (!cursorMatches(current, pending.after_cursor)) {
3470
+ const next = { ...state.cursors };
3471
+ if (pending.after_cursor === null) delete next[pending.source_slot];
3472
+ else next[pending.source_slot] = pending.after_cursor;
3473
+ cursors = next;
3474
+ }
3475
+ const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
3476
+ const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
3477
+ const { pending_transition: _pendingTransition, ...settledState } = state;
3478
+ const updated = {
3479
+ ...settledState,
3480
+ cursors,
3481
+ eligible_batches: eligible,
3482
+ coverage_gaps: gaps,
3483
+ coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
3484
+ };
3485
+ await this.writeState(updated);
3486
+ return updated;
3487
+ }
3488
+ async writeImmutableBatch(state, batch, bytes) {
3489
+ const path = this.batchPath(state, batch.batch_ref);
3490
+ await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
3491
+ const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3492
+ if (existing !== null) {
3493
+ if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3494
+ await syncExistingFile(path, this.platform);
3495
+ return;
3496
+ }
3497
+ if (this.platform === "win32") {
3498
+ await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
3499
+ return;
3500
+ }
3501
+ let handle;
3502
+ try {
3503
+ handle = await openNoFollow(path, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384, this.platform);
3504
+ await handle.writeFile(bytes);
3505
+ await handle.sync();
3506
+ await handle.close();
3507
+ handle = void 0;
3508
+ await syncDirectory(dirname4(path), this.platform);
3509
+ } catch (error) {
3510
+ await handle?.close().catch(() => void 0);
3511
+ if (errorCode2(error) === "EEXIST") {
3512
+ const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3513
+ if (winner !== null && winner.equals(bytes)) {
3514
+ await syncExistingFile(path, this.platform);
3515
+ return;
3516
+ }
3517
+ throw new Error("Host usage facts batch reference conflicts with existing bytes.");
3518
+ }
3519
+ await removeFileIfPresent(path).catch(() => void 0);
3520
+ throw error;
3521
+ }
3522
+ }
3523
+ async readBatch(state, batchRef) {
3524
+ const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3525
+ if (bytes === null) throw new Error("Host usage facts batch object is missing.");
3526
+ let value;
3527
+ try {
3528
+ value = JSON.parse(bytes.toString("utf8"));
3529
+ } catch {
3530
+ throw new Error("Host usage facts batch object is malformed.");
3531
+ }
3532
+ validateCealHostUsageBatch(value);
3533
+ if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
3534
+ return value;
3535
+ }
3536
+ async writeState(state) {
3537
+ validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
3538
+ const bytes = Buffer.from(JSON.stringify(state), "utf8");
3539
+ if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
3540
+ await this.prepare();
3541
+ const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
3542
+ if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
3543
+ else await durableAtomicReplace(path, bytes);
3544
+ }
3545
+ async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
3546
+ const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3547
+ const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
3548
+ let release;
3549
+ const gate = new Promise((resolve) => {
3550
+ release = resolve;
3551
+ });
3552
+ const tail = previous.then(() => gate);
3553
+ SESSION_TRANSITION_TAILS.set(key, tail);
3554
+ await previous;
3555
+ try {
3556
+ return await run();
3557
+ } finally {
3558
+ release?.();
3559
+ if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
3560
+ }
3561
+ }
3562
+ sessionPath(producer, hostSourceRef, hostSessionRef) {
3563
+ return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3564
+ }
3565
+ batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3566
+ const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3567
+ return join3(this.batches, sessionName.slice(0, -5));
3568
+ }
3569
+ batchPath(state, batchRef) {
3570
+ return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3571
+ }
3572
+ };
3573
+ function serializeBatch(batch) {
3574
+ validateCealHostUsageBatch(batch);
3575
+ return Buffer.from(JSON.stringify(batch), "utf8");
3576
+ }
3577
+ function batchFileName(batchRef) {
3578
+ const digest = cealHostUsageBatchObjectDigestFromReference(batchRef);
3579
+ if (digest === null) throw new TypeError("Host usage facts batch reference is invalid.");
3580
+ return `${digest}.json`;
3581
+ }
3582
+ function expectedBatchNames(state) {
3583
+ const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
3584
+ const pending = state.pending_transition?.batch_ref;
3585
+ if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
3586
+ return expected;
3587
+ }
3588
+ function isOrphanBatchEntry(entry, expected) {
3589
+ return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
3590
+ }
3591
+ function hasOutboxCapacity(state, bytes) {
3592
+ const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
3593
+ return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
3594
+ }
3595
+ function overflowCoverageGaps(batch) {
3596
+ const count = batch.facts.length;
3597
+ const gaps = [...batch.coverage_gaps];
3598
+ 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 });
3599
+ return gaps;
3600
+ }
3601
+ function appendEligible(existing, next) {
3602
+ if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
3603
+ if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
3604
+ return [...existing, next];
3605
+ }
3606
+ function appendCoverageGaps(existing, added) {
3607
+ if (added.length === 0) return existing;
3608
+ const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
3609
+ for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
3610
+ const combined = [...byIdentity.values()];
3611
+ if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
3612
+ const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
3613
+ return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
3614
+ }
3615
+ function coverageRanges(gaps) {
3616
+ const ranges = /* @__PURE__ */ new Map();
3617
+ for (const gap of gaps) {
3618
+ if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
3619
+ const current = ranges.get(gap.source_file_ref);
3620
+ 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 });
3621
+ 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) });
3622
+ }
3623
+ return [...ranges.values()];
3624
+ }
3625
+ function firstCursor(state) {
3626
+ const entry = Object.entries(state.cursors)[0];
3627
+ return entry === void 0 ? null : entry;
3628
+ }
3629
+ function sameCursor(left, right) {
3630
+ return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
3631
+ }
3632
+ function cursorMatches(left, right) {
3633
+ return right === null ? left === void 0 : sameCursor(left, right);
3634
+ }
3635
+ function validateState(value, producer, hostSourceRef, hostSessionRef) {
3636
+ validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
3637
+ validateStateShape(value);
3638
+ validateStateLimits(value);
3639
+ validateStateContents(value);
3640
+ }
3641
+ function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
3642
+ 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.");
3643
+ }
3644
+ function validateStateLimits(value) {
3645
+ 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.");
3646
+ }
3647
+ function validateStateContents(value) {
3648
+ for (const [slot, cursor] of Object.entries(value.cursors)) {
3649
+ validateSourceSlot(slot);
3650
+ validateFileCursor(cursor);
3651
+ }
3652
+ for (const item of value.eligible_batches) validateEligibleBatch(item);
3653
+ if (value.pending_transition !== void 0) validatePending(value.pending_transition);
3654
+ for (const gap of value.coverage_gaps) validateGap(gap);
3655
+ validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
3656
+ }
3657
+ function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
3658
+ if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
3659
+ if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
3660
+ }
3661
+ function validateStateOwner(value, producer, hostSourceRef) {
3662
+ if (!isRecord3(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
3663
+ validateState(value, producer, hostSourceRef, String(value.host_session_ref));
3664
+ }
3665
+ function validateStateShape(value) {
3666
+ const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
3667
+ const optional = ["pending_transition", "quarantined_reason"];
3668
+ 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.");
3669
+ 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.");
3670
+ }
3671
+ function validateFileCursor(value) {
3672
+ 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.");
3673
+ validateCursorIdentity(value);
3674
+ validateCursorOffsets(value);
3675
+ validateCursorContext(value);
3676
+ if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
3677
+ if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
3678
+ }
3679
+ function validateCursorIdentity(value) {
3680
+ 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.");
3681
+ }
3682
+ function validateCursorOffsets(value) {
3683
+ 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.");
3684
+ }
3685
+ function validateCursorContext(value) {
3686
+ 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.");
3687
+ }
3688
+ function validOptionalText(value, maximum) {
3689
+ return value === null || typeof value === "string" && value.length <= maximum;
3690
+ }
3691
+ function validateCodexCounts(value) {
3692
+ 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.");
3693
+ if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
3694
+ }
3695
+ function validatePending(value) {
3696
+ 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.");
3697
+ validatePendingCursors(value);
3698
+ validatePendingBatch(value);
3699
+ validatePendingFields(value);
3700
+ for (const gap of value.gap_delta) validateGap(gap);
3701
+ }
3702
+ function validatePendingCursors(value) {
3703
+ validateSourceSlot(value.source_slot);
3704
+ validateFileCursor(value.before_cursor);
3705
+ if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
3706
+ }
3707
+ function validatePendingBatch(value) {
3708
+ if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
3709
+ }
3710
+ function validatePendingFields(value) {
3711
+ 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.");
3712
+ }
3713
+ function validateEligibleBatch(value) {
3714
+ 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.");
3715
+ }
3716
+ function validateGap(value) {
3717
+ try {
3718
+ validateCealHostUsageCoverageGap(value);
3719
+ } catch {
3720
+ throw new Error("Host usage facts coverage gap is invalid.");
3721
+ }
3722
+ }
3723
+ function validateSourceSlot(value) {
3724
+ if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
3725
+ }
3726
+ async function readOptionalJson(path, maxBytes, platform, custody) {
3727
+ const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
3728
+ if (bytes === null) return null;
3729
+ try {
3730
+ return JSON.parse(bytes.toString("utf8"));
3731
+ } catch {
3732
+ throw new Error("Host usage facts state JSON is malformed.");
3733
+ }
3734
+ }
3735
+ async function readOptionalBytes(path, maxBytes, platform, custody) {
3736
+ if (platform === "win32") {
3737
+ try {
3738
+ return await readPrivateFileWithSecurefs(path, maxBytes, custody);
3739
+ } catch (error) {
3740
+ if (errorCode2(error) === "ENOENT") return null;
3741
+ throw error;
3742
+ }
3743
+ }
3744
+ let handle;
3745
+ try {
3746
+ handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
3747
+ const stats = await handle.stat();
3748
+ 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.");
3749
+ return await handle.readFile();
3750
+ } catch (error) {
3751
+ if (errorCode2(error) === "ENOENT") return null;
3752
+ throw error;
3753
+ } finally {
3754
+ await handle?.close();
3755
+ }
3756
+ }
3757
+ async function preparePrivateDirectory(path, platform, custody) {
3758
+ if (platform === "win32") {
3759
+ await ensurePrivateDirectoryWithSecurefs(path, custody);
3760
+ return;
3761
+ }
3762
+ await mkdir2(path, { recursive: true, mode: 448 });
3763
+ if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3764
+ }
3765
+ async function syncExistingFile(path, platform) {
3766
+ const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
3767
+ try {
3768
+ await handle.sync();
3769
+ } finally {
3770
+ await handle.close();
3771
+ }
3772
+ await syncDirectory(dirname4(path), platform);
3773
+ }
3774
+ async function syncDirectory(path, platform) {
3775
+ if (platform === "win32") return;
3776
+ const handle = await open3(path, constants4.O_RDONLY);
3777
+ try {
3778
+ await handle.sync();
3779
+ } finally {
3780
+ await handle.close();
3781
+ }
3782
+ }
3783
+ async function removeFileIfPresent(path) {
3784
+ try {
3785
+ await unlink2(path);
3786
+ } catch (error) {
3787
+ if (errorCode2(error) !== "ENOENT") throw error;
3788
+ }
3789
+ }
3790
+ function sameKeys(value, expected) {
3791
+ return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
3792
+ }
3793
+ function isRecord3(value) {
3794
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3795
+ }
3796
+ function safeInteger2(value) {
3797
+ return Number.isSafeInteger(value) && Number(value) >= 0;
3798
+ }
3799
+ function validTimestamp(value) {
3800
+ return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
3801
+ }
3802
+ function errorCode2(error) {
3803
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3804
+ }
3805
+ function sha2562(value) {
3806
+ return createHash5("sha256").update(value, "utf8").digest("hex");
3807
+ }
3808
+
3809
+ // host/service-log.ts
3810
+ import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
3811
+ import { dirname as dirname5, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
3812
+
3813
+ // host/service-log-delivery.ts
3814
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
3815
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
3816
+ setImmediate(flush);
3817
+ }, onDeliveryGap = () => void 0) {
3818
+ const pending = [];
3819
+ const highWaterMark = stream.writableHighWaterMark;
3820
+ const byteBudget = highWaterMark + highWaterMark;
3821
+ let pendingBytes = 0;
3822
+ let droppedLines = 0;
3823
+ let flushScheduled = false;
3824
+ let waitingForDrain = false;
3825
+ let closed = !stream.writable;
3826
+ function stop() {
3827
+ if (closed) return;
3828
+ closed = true;
3829
+ pending.length = 0;
3830
+ pendingBytes = 0;
3831
+ stream.off("drain", onDrain);
3832
+ stream.off("close", onTerminal);
3833
+ stream.off("finish", onTerminal);
3834
+ stream.off("error", onError);
3835
+ }
3836
+ function onTerminal() {
3837
+ stop();
3838
+ }
3839
+ function onError() {
3840
+ stop();
3841
+ }
3842
+ function onDrain() {
3843
+ waitingForDrain = false;
3844
+ scheduleFlush();
3845
+ }
3846
+ function scheduleFlush() {
3847
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
3848
+ flushScheduled = true;
3849
+ let scheduling = true;
3850
+ let invokedSynchronously = false;
3851
+ try {
3852
+ schedule(() => {
3853
+ if (scheduling) {
3854
+ invokedSynchronously = true;
3855
+ return;
3856
+ }
3857
+ flushScheduled = false;
3858
+ flush();
3859
+ });
3860
+ } catch {
3861
+ flushScheduled = false;
3862
+ stop();
3863
+ return;
3864
+ }
3865
+ scheduling = false;
3866
+ if (invokedSynchronously) {
3867
+ flushScheduled = false;
3868
+ stop();
3869
+ }
3870
+ }
3871
+ function flush() {
3872
+ if (closed) return;
3873
+ if (!stream.writable) {
3874
+ stop();
3875
+ return;
3876
+ }
3877
+ while (pending.length > 0) {
3878
+ if (stream.writableNeedDrain) {
3879
+ if (!waitingForDrain) {
3880
+ waitingForDrain = true;
3881
+ stream.once("drain", onDrain);
3882
+ }
3883
+ return;
3884
+ }
3885
+ const next = pending.shift();
3886
+ if (next === void 0) return;
3887
+ pendingBytes -= next.bytes;
3888
+ let accepted;
3889
+ try {
3890
+ accepted = stream.write(next.line);
3891
+ } catch {
3892
+ stop();
3893
+ return;
3894
+ }
3895
+ if (!accepted) {
3896
+ waitingForDrain = true;
3897
+ stream.once("drain", onDrain);
3898
+ return;
3899
+ }
3900
+ }
3901
+ if (droppedLines > 0) {
3902
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
3903
+ `;
3904
+ droppedLines = 0;
3905
+ try {
3906
+ onDeliveryGap(line);
3907
+ } catch {
3908
+ }
3909
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
3910
+ pendingBytes += Buffer.byteLength(line, "utf8");
3911
+ flush();
3912
+ }
3913
+ }
3914
+ stream.on("close", onTerminal);
3915
+ stream.on("finish", onTerminal);
3916
+ stream.on("error", onError);
3917
+ return (line) => {
3918
+ if (closed) return;
3919
+ const bytes = Buffer.byteLength(line, "utf8");
3920
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
3921
+ droppedLines += 1;
3922
+ scheduleFlush();
3923
+ return;
3924
+ }
3925
+ pending.push({ line, bytes });
3926
+ pendingBytes += bytes;
3927
+ scheduleFlush();
3928
+ };
3929
+ }
3930
+
3931
+ // host/invocation-authentication-client-command.ts
3932
+ var HOST_OWNED_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){0,7}$/u;
3933
+ function isHostOwnedFailureCode(value) {
3934
+ return typeof value === "string" && HOST_OWNED_CODE.test(value);
3935
+ }
3936
+ var DOCTOR_FLAGS = Object.freeze({
3937
+ "--expected-sha256": "expected_sha256",
3938
+ "--expected-source-commit": "expected_source_commit",
3939
+ "--expected-instance-ref": "expected_instance_ref"
3940
+ });
3941
+
2432
3942
  // 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
3943
  var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
2436
3944
  var HOST_SERVICE_LOG_ARGUMENT = "--ceal-host-service-log";
2437
3945
  var HostServiceLogArgumentError = class extends Error {
@@ -2450,17 +3958,30 @@ function consumeHostServiceLogArgument(args, platform = process.platform) {
2450
3958
  if (indexes.length !== 1 || path === void 0 || !pathApi.isAbsolute(path) || pathApi.normalize(path) !== path) throw new HostServiceLogArgumentError();
2451
3959
  return { args: [...args.slice(0, index), ...args.slice(index + 2)], path };
2452
3960
  }
3961
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
3962
+ void persistHostServiceLogLine(line);
3963
+ });
2453
3964
  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 } : {} })}
3965
+ const details = diagnosticDetails(event, failure_kind, cause);
3966
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
2455
3967
  `;
2456
3968
  try {
2457
3969
  (sink ?? defaultHostServiceDiagnosticSink)(line);
2458
3970
  } catch {
2459
3971
  }
2460
3972
  }
3973
+ function diagnosticDetails(event, failureKind, cause) {
3974
+ if (event === "watcher_scan_failed") return {
3975
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3976
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
3977
+ };
3978
+ return validDiagnosticCause(cause, event) ? { cause } : {};
3979
+ }
3980
+ function validDiagnosticCause(cause, event) {
3981
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
3982
+ }
2461
3983
  function defaultHostServiceDiagnosticSink(line) {
2462
3984
  writeHostServiceLogLine(line);
2463
- process.stderr.write(line);
2464
3985
  }
2465
3986
  var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
2466
3987
  var HOST_SERVICE_LOG_CHECK_INTERVAL_MS = 6e4;
@@ -2489,7 +4010,7 @@ function boundHostServiceLog(environment = process.env) {
2489
4010
  ready.then(() => rotateHostServiceLog(path)).catch((error) => {
2490
4011
  if (reported) return;
2491
4012
  reported = true;
2492
- process.stderr.write(`[host-service-log] rotation_failed code=${errorCode(error)}
4013
+ writeHostServiceLogLine(`[host-service-log] rotation_failed code=${errorCode3(error)}
2493
4014
  `);
2494
4015
  });
2495
4016
  };
@@ -2499,10 +4020,22 @@ function boundHostServiceLog(environment = process.env) {
2499
4020
  return () => clearInterval(timer);
2500
4021
  }
2501
4022
  function writeHostServiceLogLine(line, environment = process.env) {
4023
+ void persistHostServiceLogLine(line, environment);
4024
+ defaultHostServiceLogDelivery(line);
4025
+ }
4026
+ async function writeHostServiceCommandResult(schemaVersion, result, sink) {
4027
+ const line = `${JSON.stringify({ schema_version: schemaVersion, ...result })}
4028
+ `;
4029
+ const serviceLine = `${JSON.stringify({ schema_version: schemaVersion, ok: result.ok, ...!result.ok ? { code: isHostOwnedFailureCode(result.code) ? result.code : "host_failure_unclassified" } : {} })}
4030
+ `;
4031
+ await persistHostServiceLogLine(serviceLine);
4032
+ sink(line);
4033
+ }
4034
+ async function persistHostServiceLogLine(line, environment = process.env) {
2502
4035
  if (process.platform !== "win32") return;
2503
4036
  const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
2504
4037
  if (path === void 0 || !win325.isAbsolute(path) || win325.normalize(path) !== path) return;
2505
- void appendHostServiceLogLine(path, line).catch(() => void 0);
4038
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
2506
4039
  }
2507
4040
  async function appendHostServiceLogLine(path, line) {
2508
4041
  if (!isAbsolute(path)) return;
@@ -2512,10 +4045,10 @@ async function appendHostServiceLogLine(path, line) {
2512
4045
  var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
2513
4046
  var hostServiceLogDirectories = /* @__PURE__ */ new Map();
2514
4047
  function ensureHostServiceLogDirectory(path) {
2515
- const directory = dirname2(path);
4048
+ const directory = dirname5(path);
2516
4049
  const existing = hostServiceLogDirectories.get(directory);
2517
4050
  if (existing !== void 0) return existing;
2518
- const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
4051
+ const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
2519
4052
  hostServiceLogDirectories.delete(directory);
2520
4053
  throw error;
2521
4054
  });
@@ -2523,21 +4056,97 @@ function ensureHostServiceLogDirectory(path) {
2523
4056
  return pending;
2524
4057
  }
2525
4058
  function isNotFound(error) {
2526
- return errorCode(error) === "ENOENT";
4059
+ return errorCode3(error) === "ENOENT";
2527
4060
  }
2528
- function errorCode(error) {
4061
+ function errorCode3(error) {
2529
4062
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unknown";
2530
4063
  }
2531
4064
 
4065
+ // host/relay/src/host-usage-facts-uploader.ts
4066
+ var HostUsageFactsUploader = class {
4067
+ options;
4068
+ store;
4069
+ constructor(options) {
4070
+ if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
4071
+ this.options = options;
4072
+ this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
4073
+ }
4074
+ async close() {
4075
+ await this.store.close();
4076
+ }
4077
+ async uploadOne(signal) {
4078
+ const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4079
+ if (candidate === null) return false;
4080
+ 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);
4081
+ const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4082
+ const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4083
+ const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4084
+ method: "POST",
4085
+ headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4086
+ body: JSON.stringify(candidate.batch),
4087
+ signal: requestSignal
4088
+ });
4089
+ if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
4090
+ await response2.body?.cancel().catch(() => void 0);
4091
+ throw new Error("Gateway did not acknowledge the Host usage facts batch.");
4092
+ }
4093
+ await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
4094
+ return true;
4095
+ }
4096
+ };
4097
+ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4098
+ const uploader = new HostUsageFactsUploader(options);
4099
+ let delay = 500;
4100
+ let failures = 0;
4101
+ try {
4102
+ while (!signal.aborted) {
4103
+ try {
4104
+ await options.capture_next?.();
4105
+ } catch {
4106
+ writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
4107
+ }
4108
+ if (signal.aborted) return;
4109
+ try {
4110
+ const uploaded = await uploader.uploadOne(signal);
4111
+ failures = 0;
4112
+ delay = uploaded ? 100 : 1e3;
4113
+ } catch {
4114
+ if (signal.aborted) return;
4115
+ failures += 1;
4116
+ delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
4117
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4118
+ }
4119
+ if (!signal.aborted) await wait(signal, delay);
4120
+ }
4121
+ } finally {
4122
+ await uploader.close().catch(() => void 0);
4123
+ }
4124
+ }
4125
+
2532
4126
  // host/relay/src/host-producer-core.ts
2533
- import { createHash as createHash4 } from "node:crypto";
4127
+ import { createHash as createHash6 } from "node:crypto";
2534
4128
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
2535
4129
  function isHostTranscriptCursorReason(value) {
2536
4130
  return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
2537
4131
  }
2538
4132
  var TRANSCRIPT_MISSING_REASON = "transcript_missing";
2539
4133
  var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
2540
- var HOST_INVOCATION_TRANSCRIPT_TAIL_MAX_BYTES = 1024 * 1024;
4134
+ var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
4135
+ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
4136
+ const seen = /* @__PURE__ */ new Set();
4137
+ const newestFirst = [];
4138
+ for (const message of [...chronological].reverse()) {
4139
+ if (seen.has(message.host_input_ref)) continue;
4140
+ seen.add(message.host_input_ref);
4141
+ newestFirst.push(message);
4142
+ }
4143
+ for (const message of existing?.messages ?? []) {
4144
+ if (seen.has(message.host_input_ref)) continue;
4145
+ seen.add(message.host_input_ref);
4146
+ newestFirst.push(message);
4147
+ }
4148
+ return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
4149
+ }
2541
4150
  function transcriptScanFailureKind(error, adapterFailureKind) {
2542
4151
  if (transcriptErrorCode(error) === "ELOOP") return "symlink";
2543
4152
  const adapter = adapterFailureKind(error);
@@ -2594,10 +4203,10 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
2594
4203
  return null;
2595
4204
  }
2596
4205
  function transcriptSha256(value) {
2597
- return createHash4("sha256").update(value).digest("hex");
4206
+ return createHash6("sha256").update(value).digest("hex");
2598
4207
  }
2599
4208
  function transcriptObjectSha256(value) {
2600
- return createHash4("sha256").update(JSON.stringify(value), "utf8").digest("hex");
4209
+ return createHash6("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2601
4210
  }
2602
4211
  function isTranscriptRecord(value) {
2603
4212
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2619,7 +4228,7 @@ function createTranscriptWatcherBase(options, owner) {
2619
4228
  outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
2620
4229
  now: options.now ?? (() => /* @__PURE__ */ new Date()),
2621
4230
  log: options.log ?? ((line) => {
2622
- process.stderr.write(`${line}
4231
+ writeHostServiceLogLine(`${line}
2623
4232
  `);
2624
4233
  }),
2625
4234
  producerInstallationRef: options.producer_installation_ref
@@ -2659,7 +4268,13 @@ var HostTranscriptWatcher = class {
2659
4268
  }
2660
4269
  async scanRegistration(registration) {
2661
4270
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
2662
- missing: () => this.retireMissing(registration),
4271
+ missing: async () => {
4272
+ try {
4273
+ return await this.retireMissing(registration);
4274
+ } catch (error) {
4275
+ return this.scanFailed(void 0, registration, error);
4276
+ }
4277
+ },
2663
4278
  failed: (handle, error) => this.scanFailed(handle, registration, error)
2664
4279
  });
2665
4280
  }
@@ -2742,8 +4357,8 @@ var HostProducerDrainCore = class {
2742
4357
  };
2743
4358
 
2744
4359
  // 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";
4360
+ import { mkdir as mkdir4, readdir, readFile, unlink as unlink3 } from "node:fs/promises";
4361
+ import { isAbsolute as isAbsolute3, join as join4 } from "node:path";
2747
4362
 
2748
4363
  // host/invocation-context.ts
2749
4364
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2778,7 +4393,7 @@ function invocationContextFromTurn(identity, promptRef, expiresAt, descriptor) {
2778
4393
  return Object.freeze(context);
2779
4394
  }
2780
4395
  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]));
4396
+ 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
4397
  }
2783
4398
  function exactKeys(value, keys) {
2784
4399
  const actual = Object.keys(value);
@@ -2789,7 +4404,7 @@ function requiredKeys(value, required, optional) {
2789
4404
  const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
2790
4405
  return actual.length >= required.length && actual.length <= allowed.size && required.every((key) => Object.hasOwn(value, key)) && actual.every((key) => allowed.has(key));
2791
4406
  }
2792
- function isRecord3(value) {
4407
+ function isRecord4(value) {
2793
4408
  return value !== null && typeof value === "object" && !Array.isArray(value);
2794
4409
  }
2795
4410
  function safeRef(value) {
@@ -2810,135 +4425,106 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2810
4425
  "frame_too_large"
2811
4426
  ];
2812
4427
 
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";
4428
+ // host/relay/src/host-usage-facts-capture.ts
4429
+ import { constants as constants5 } from "node:fs";
4430
+ var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
4431
+ var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
4432
+ var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
4433
+ var HostUsageTranscriptSourceError = class extends Error {
4434
+ constructor(options) {
4435
+ super("Host usage transcript source could not be read.", options);
4436
+ this.name = "HostUsageTranscriptSourceError";
2828
4437
  }
2829
4438
  };
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
- };
4439
+ async function readHostUsageTranscriptSource(read) {
4440
+ try {
4441
+ return await read();
4442
+ } catch (error) {
4443
+ throw new HostUsageTranscriptSourceError({ cause: error });
4444
+ }
2838
4445
  }
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;
4446
+ async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4447
+ if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4448
+ let failed = false;
4449
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4450
+ const index = (startIndex + attempt) % registrations.length;
4451
+ const registration = registrations[index];
4452
+ if (registration === void 0) continue;
2846
4453
  try {
2847
- await operation();
2848
- return;
4454
+ if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
2849
4455
  } 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);
4456
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4457
+ failed = true;
2853
4458
  }
2854
4459
  }
4460
+ return { captured: false, nextIndex: startIndex, failed };
2855
4461
  }
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 = [];
4462
+ async function openHostUsageTranscriptCursor(input) {
4463
+ const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants5.O_RDONLY));
4464
+ let source;
2886
4465
  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);
4466
+ source = await readHostUsageTranscriptSource(() => input.inspect(handle));
2895
4467
  } catch (error) {
2896
- failures.push(error);
4468
+ await handle.close().catch(() => void 0);
4469
+ throw error;
2897
4470
  }
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;
4471
+ const sourceFileRef2 = hostUsageSourceFileReference(input.source_kind, input.host_source_ref, input.host_session_ref, source.device, source.inode);
4472
+ let prepared;
2906
4473
  try {
2907
- await handle.sync();
4474
+ 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
4475
  } catch (error) {
2909
- if (!directorySyncUnsupported(error)) failure = error;
4476
+ await handle.close().catch(() => void 0);
4477
+ throw error;
2910
4478
  }
2911
- try {
4479
+ if (prepared === null) {
2912
4480
  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);
4481
+ return null;
2931
4482
  }
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;
4483
+ return { handle, source, source_file_ref: sourceFileRef2, ...prepared };
4484
+ }
4485
+ async function readHostUsageTranscriptChunk(handle, offset, size, skippingOversizedLine) {
4486
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(size) || size < offset) throw new TypeError("Host usage transcript range is invalid.");
4487
+ if (size === offset) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
4488
+ if (skippingOversizedLine) return await resumeOversizedLine(handle, offset, size);
4489
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
4490
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
4491
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
4492
+ const chunk = bytes.subarray(0, bytesRead);
4493
+ return completeChunk(chunk, offset);
4494
+ }
4495
+ async function resumeOversizedLine(handle, offset, size) {
4496
+ const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
4497
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
4498
+ if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
4499
+ const chunk = bytes.subarray(0, bytesRead);
4500
+ const delimiter = chunk.indexOf(10);
4501
+ if (delimiter < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
4502
+ return completeChunk(chunk.subarray(delimiter + 1), offset + delimiter + 1);
4503
+ }
4504
+ function completeChunk(chunk, offset) {
4505
+ const parsed = completeLinePrefix(chunk, offset);
4506
+ const oversizedRows = parsed.oversizedRows + (parsed.incompleteOversized ? 1 : 0);
4507
+ const endOffset = parsed.incompleteOversized ? offset + chunk.length : parsed.endOffset;
4508
+ return { lines: parsed.lines, end_offset: endOffset, skipping_oversized_line: parsed.incompleteOversized, oversized_rows: oversizedRows };
4509
+ }
4510
+ function completeLinePrefix(bytes, baseOffset) {
4511
+ const lines = [];
4512
+ let lineStart = 0;
4513
+ let endOffset = baseOffset;
4514
+ let oversizedRows = 0;
4515
+ let rowCount = 0;
4516
+ for (let index = 0; index < bytes.length; index += 1) {
4517
+ if (bytes[index] !== 10) continue;
4518
+ const line = bytes.subarray(lineStart, index);
4519
+ if (line.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES) oversizedRows += 1;
4520
+ else lines.push(line);
4521
+ lineStart = index + 1;
4522
+ endOffset = baseOffset + lineStart;
4523
+ rowCount += 1;
4524
+ if (rowCount >= HOST_USAGE_FACTS_SCAN_MAX_ROWS) return { lines, endOffset, oversizedRows, incompleteOversized: false };
4525
+ }
4526
+ const incomplete = bytes.subarray(lineStart);
4527
+ return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
2942
4528
  }
2943
4529
 
2944
4530
  // host/relay/src/relay-quarantine-store.ts
@@ -2956,16 +4542,6 @@ var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2956
4542
 
2957
4543
  // host/relay/src/relay-ipc.ts
2958
4544
  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
4545
 
2970
4546
  // host/claude/src/claude-types.ts
2971
4547
  var CLAUDE_HOST_ERROR_CODES = ["invalid_input", "payload_rejected", "storage", "configuration"];
@@ -2994,6 +4570,7 @@ var ClaudeHostError = class extends Error {
2994
4570
  };
2995
4571
 
2996
4572
  // host/claude/src/claude-invocation-context.ts
4573
+ import { isAbsolute as isAbsolute2 } from "node:path";
2997
4574
  function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
2998
4575
  return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
2999
4576
  }
@@ -3004,7 +4581,7 @@ function validateClaudeHostInvocationContext(value) {
3004
4581
  validateContextTimes(value);
3005
4582
  }
3006
4583
  function contextShape(value) {
3007
- return record(value) && value.schema_version === CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION && hasHostInvocationContextKeys(value, ["working_directory", "turn_generation_ref"]);
4584
+ return record2(value) && value.schema_version === CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION && hasHostInvocationContextKeys(value, ["working_directory", "turn_generation_ref"]);
3008
4585
  }
3009
4586
  function validateIdentity2(value) {
3010
4587
  if (!validIdentity(value)) throw new ClaudeHostError("storage", "Claude Host invocation identity is malformed.");
@@ -3016,13 +4593,13 @@ function validateContextTimes(value) {
3016
4593
  if (!timestamp(value.expires_at) || !optionalDirectory(value.working_directory)) throw new ClaudeHostError("storage", "Claude Host invocation context is malformed.");
3017
4594
  }
3018
4595
  function validIdentity(value) {
3019
- return record(value) && hasHostInvocationIdentityKeys(value) && [value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2);
4596
+ return record2(value) && hasHostInvocationIdentityKeys(value) && [value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2);
3020
4597
  }
3021
4598
  function optionalSafeRef(value) {
3022
4599
  return value === void 0 || safeRef2(value);
3023
4600
  }
3024
4601
  function optionalDirectory(value) {
3025
- return value === void 0 || typeof value === "string" && value.startsWith("/") && !value.includes("\0") && value.length <= 4096;
4602
+ return value === void 0 || typeof value === "string" && isAbsolute2(value) && !value.includes("\0") && value.length <= 4096;
3026
4603
  }
3027
4604
  function safeRef2(value) {
3028
4605
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
@@ -3030,7 +4607,7 @@ function safeRef2(value) {
3030
4607
  function timestamp(value) {
3031
4608
  return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
3032
4609
  }
3033
- function record(value) {
4610
+ function record2(value) {
3034
4611
  return value !== null && typeof value === "object" && !Array.isArray(value);
3035
4612
  }
3036
4613
 
@@ -3047,18 +4624,18 @@ var ClaudeOutboxStore = class {
3047
4624
  activeContexts;
3048
4625
  turnSelections;
3049
4626
  constructor(directory) {
3050
- if (!directory.startsWith("/")) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
4627
+ if (!isAbsolute3(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
3051
4628
  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");
4629
+ this.envelopes = join4(directory, "envelopes");
4630
+ this.sessions = join4(directory, "sessions");
4631
+ this.registrations = join4(directory, "transcript-registrations");
4632
+ this.cursors = join4(directory, "transcript-cursors");
4633
+ this.activeContexts = join4(directory, "active-contexts");
4634
+ this.turnSelections = join4(directory, "turn-selections");
3058
4635
  }
3059
4636
  async prepare() {
3060
4637
  for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
3061
- await mkdir3(path, { recursive: true, mode: 448 });
4638
+ await mkdir4(path, { recursive: true, mode: 448 });
3062
4639
  }
3063
4640
  }
3064
4641
  async activateInvocationContext(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
@@ -3104,7 +4681,7 @@ var ClaudeOutboxStore = class {
3104
4681
  for (const name of await readdir(this.activeContexts)) {
3105
4682
  if (!name.endsWith(".json")) continue;
3106
4683
  try {
3107
- const value = JSON.parse(await readFile(join2(this.activeContexts, name), "utf8"));
4684
+ const value = JSON.parse(await readFile(join4(this.activeContexts, name), "utf8"));
3108
4685
  validateClaudeHostInvocationContext(value);
3109
4686
  if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
3110
4687
  } catch {
@@ -3124,7 +4701,7 @@ var ClaudeOutboxStore = class {
3124
4701
  for (const name of await readdir(this.envelopes)) {
3125
4702
  if (!name.endsWith(".json")) continue;
3126
4703
  try {
3127
- const value = JSON.parse(await readFile(join2(this.envelopes, name), "utf8"));
4704
+ const value = JSON.parse(await readFile(join4(this.envelopes, name), "utf8"));
3128
4705
  validateEnvelope(value);
3129
4706
  entries.push(value);
3130
4707
  } catch {
@@ -3137,7 +4714,7 @@ var ClaudeOutboxStore = class {
3137
4714
  async removeEnvelope(entry) {
3138
4715
  validateEnvelope(entry);
3139
4716
  try {
3140
- await unlink2(this.envelopePath(entry.submission_ref));
4717
+ await unlink3(this.envelopePath(entry.submission_ref));
3141
4718
  } catch (error) {
3142
4719
  if (code(error) !== "ENOENT") throw error;
3143
4720
  }
@@ -3145,13 +4722,13 @@ var ClaudeOutboxStore = class {
3145
4722
  async saveSession(snapshot) {
3146
4723
  validateSession(snapshot);
3147
4724
  await this.prepare();
3148
- await durableAtomicReplace(join2(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
4725
+ await durableAtomicReplace(join4(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
3149
4726
  }
3150
4727
  async readSession(sourceRef, sessionRef) {
3151
4728
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
3152
4729
  await this.prepare();
3153
4730
  try {
3154
- const value = JSON.parse(await readFile(join2(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
4731
+ const value = JSON.parse(await readFile(join4(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
3155
4732
  validateSession(value);
3156
4733
  return value;
3157
4734
  } catch (error) {
@@ -3186,7 +4763,7 @@ var ClaudeOutboxStore = class {
3186
4763
  for (const name of await readdir(this.registrations)) {
3187
4764
  if (!name.endsWith(".json")) continue;
3188
4765
  try {
3189
- const value = JSON.parse(await readFile(join2(this.registrations, name), "utf8"));
4766
+ const value = JSON.parse(await readFile(join4(this.registrations, name), "utf8"));
3190
4767
  validateRegistration(value);
3191
4768
  registrations.push(value);
3192
4769
  } catch {
@@ -3224,16 +4801,16 @@ var ClaudeOutboxStore = class {
3224
4801
  await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
3225
4802
  }
3226
4803
  envelopePath(ref) {
3227
- return join2(this.envelopes, `${cealRequestSha256(ref)}.json`);
4804
+ return join4(this.envelopes, `${cealRequestSha256(ref)}.json`);
3228
4805
  }
3229
4806
  registrationPath(sourceRef, sessionRef) {
3230
- return join2(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4807
+ return join4(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
3231
4808
  }
3232
4809
  turnSelectionPath(sourceRef, sessionRef) {
3233
- return join2(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4810
+ return join4(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
3234
4811
  }
3235
4812
  cursorPath(sourceRef, sessionRef) {
3236
- return join2(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4813
+ return join4(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
3237
4814
  }
3238
4815
  async readRegistrationFile(path) {
3239
4816
  try {
@@ -3247,13 +4824,13 @@ var ClaudeOutboxStore = class {
3247
4824
  }
3248
4825
  async removeStateFile(path) {
3249
4826
  try {
3250
- await unlink2(path);
4827
+ await unlink3(path);
3251
4828
  } catch (error) {
3252
4829
  if (code(error) !== "ENOENT") throw error;
3253
4830
  }
3254
4831
  }
3255
4832
  activeContextPath(identity) {
3256
- return join2(this.activeContexts, `${invocationContextKey(identity)}.json`);
4833
+ return join4(this.activeContexts, `${invocationContextKey(identity)}.json`);
3257
4834
  }
3258
4835
  };
3259
4836
  function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
@@ -3276,15 +4853,15 @@ function safeRef3(value) {
3276
4853
  function timestamp2(value) {
3277
4854
  return typeof value === "string" && Number.isFinite(Date.parse(value));
3278
4855
  }
3279
- function record2(value) {
4856
+ function record3(value) {
3280
4857
  return value !== null && typeof value === "object" && !Array.isArray(value);
3281
4858
  }
3282
4859
  function code(error) {
3283
- return record2(error) && typeof error.code === "string" ? error.code : null;
4860
+ return record3(error) && typeof error.code === "string" ? error.code : null;
3284
4861
  }
3285
4862
  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"])) {
4863
+ if (!record3(value)) throw new ClaudeHostError("storage", "Claude outbox entry is malformed.");
4864
+ if (!sameKeys2(value, ["schema_version", "identity", "host_input_ref", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"])) {
3288
4865
  throw new ClaudeHostError("storage", `Claude outbox entry key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the outbox entry key set")}).`);
3289
4866
  }
3290
4867
  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 +4884,8 @@ function validateEnvelopeObservations(value) {
3307
4884
  }
3308
4885
  }
3309
4886
  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"])) {
4887
+ if (!record3(value)) throw new ClaudeHostError("storage", "Claude session snapshot is malformed.");
4888
+ if (!sameKeys2(value, ["schema_version", "host_session_ref", "host_source_ref", "observed_at", "value", "expires_at"])) {
3312
4889
  throw new ClaudeHostError("storage", `Claude session snapshot key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the session snapshot key set")}).`);
3313
4890
  }
3314
4891
  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 +4894,8 @@ function validateSession(value) {
3317
4894
  }
3318
4895
  }
3319
4896
  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"])) {
4897
+ if (!record3(value)) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
4898
+ if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "claude_session_id", "transcript_path", "registered_at", "expires_at"], ["cwd"])) {
3322
4899
  throw new ClaudeHostError("storage", `Claude transcript registration key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the registration key set")}).`);
3323
4900
  }
3324
4901
  if (value.schema_version !== CLAUDE_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
@@ -3329,7 +4906,7 @@ function validateRegistration(value) {
3329
4906
  if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
3330
4907
  }
3331
4908
  function validateRegistrationPaths(cwd, transcriptPath) {
3332
- if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute2(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
4909
+ if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute3(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
3333
4910
  throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
3334
4911
  }
3335
4912
  if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
@@ -3337,14 +4914,21 @@ function validateRegistrationPaths(cwd, transcriptPath) {
3337
4914
  }
3338
4915
  }
3339
4916
  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"])) {
4917
+ if (!record3(value)) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
4918
+ 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
4919
  throw new ClaudeHostError("storage", "Claude transcript cursor key set is malformed.");
3343
4920
  }
3344
4921
  if (value.schema_version !== CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
3345
4922
  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
4923
  if (typeof value.transcript_path !== "string" || value.transcript_path.length === 0) throw new ClaudeHostError("storage", "Claude transcript cursor path is malformed.");
3347
4924
  validateCursorPosition(value);
4925
+ if (value.human_message_window !== void 0) {
4926
+ try {
4927
+ decodeCealHostInvocationHumanMessageWindow(value.human_message_window);
4928
+ } catch {
4929
+ throw new ClaudeHostError("storage", "Claude transcript human-message projection is malformed.");
4930
+ }
4931
+ }
3348
4932
  validateCursorTurn(value.open_turn, value.unattributed, value.session_observed);
3349
4933
  validateSubagentCursors(value.subagents);
3350
4934
  if (value.reason !== void 0 && !isHostTranscriptCursorReason(value.reason)) throw new ClaudeHostError("storage", "Claude transcript cursor reason is malformed.");
@@ -3362,13 +4946,13 @@ function validateCursorTurn(openTurn, unattributed, sessionObserved) {
3362
4946
  if (sessionObserved !== void 0 && typeof sessionObserved !== "boolean") throw new ClaudeHostError("storage", "Claude transcript cursor session marker is malformed.");
3363
4947
  }
3364
4948
  function validateSubagentCursors(value) {
3365
- if (!record2(value)) throw new ClaudeHostError("storage", "Claude transcript subagent cursors are malformed.");
4949
+ if (!record3(value)) throw new ClaudeHostError("storage", "Claude transcript subagent cursors are malformed.");
3366
4950
  for (const [name, entry] of Object.entries(value)) validateSubagentEntry(name, entry);
3367
4951
  }
3368
4952
  function validateSubagentEntry(name, entry) {
3369
4953
  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
4954
  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.");
4955
+ 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
4956
  validateSubagentIdentity(entry);
3373
4957
  }
3374
4958
  function validateSubagentIdentity(entry) {
@@ -3384,7 +4968,7 @@ function validCursorPosition(value) {
3384
4968
  return nonNegativeInteger(value.offset) && nonNegativeInteger(value.anchor_start) && typeof value.anchor_sha256 === "string" && /^[a-f0-9]{64}$/u.test(value.anchor_sha256);
3385
4969
  }
3386
4970
  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;
4971
+ 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
4972
  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
4973
  if (!timestamp2(value.started_at) || !timestamp2(value.last_observed_at)) return false;
3390
4974
  if (!validMessageIds(value.message_ids)) return false;
@@ -3397,24 +4981,24 @@ function validMessageIds(value) {
3397
4981
  return new Set(value).size === value.length;
3398
4982
  }
3399
4983
  function validUnattributed(value) {
3400
- if (!record2(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output", "message_ids", "last_observed_at"])) return false;
4984
+ if (!record3(value) || !sameKeys2(value, ["input", "cached_input", "cache_write_input", "output", "message_ids", "last_observed_at"])) return false;
3401
4985
  if (!validMessageIds(value.message_ids) || value.message_ids.length === 0) return false;
3402
4986
  if (!timestamp2(value.last_observed_at)) return false;
3403
4987
  return validTurnCounts(value);
3404
4988
  }
3405
4989
  function validTurnCounts(value) {
3406
- if (!record2(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output"])) return false;
4990
+ if (!record3(value) || !sameKeys2(value, ["input", "cached_input", "cache_write_input", "output"])) return false;
3407
4991
  return [value.input, value.cached_input, value.cache_write_input, value.output].every(nonNegativeInteger);
3408
4992
  }
3409
4993
  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))) {
4994
+ 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
4995
  throw new ClaudeHostError("storage", "Claude Host identity is malformed.");
3412
4996
  }
3413
4997
  }
3414
4998
  function nonNegativeInteger(value) {
3415
4999
  return Number.isSafeInteger(value) && Number(value) >= 0;
3416
5000
  }
3417
- function sameKeys(value, required, optional = []) {
5001
+ function sameKeys2(value, required, optional = []) {
3418
5002
  return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
3419
5003
  }
3420
5004
 
@@ -3442,22 +5026,38 @@ var ClaudeProducer = class {
3442
5026
 
3443
5027
  // host/claude/src/claude-transcript-watcher.ts
3444
5028
  import { readdir as readdir2 } from "node:fs/promises";
3445
- import { join as join3 } from "node:path";
5029
+ import { join as join5 } from "node:path";
3446
5030
 
3447
5031
  // host/claude/src/claude-decoder.ts
3448
- import { createHash as createHash5 } from "node:crypto";
5032
+ import { createHash as createHash7 } from "node:crypto";
3449
5033
  var MAX_HOOK_BYTES = 256 * 1024;
3450
5034
  function decodeClaudeQueuedPromptRow(row, sessionId) {
3451
- if (!record3(row)) return null;
5035
+ if (!record4(row)) return null;
3452
5036
  if (row.type === "user") return decodeArrayTextPrompt(row, sessionId);
3453
5037
  if (row.type === "attachment") return decodeQueuedCommandPrompt(row, sessionId);
3454
5038
  if (row.type === "queue-operation") return decodeQueueEnqueuePrompt(row, sessionId);
3455
5039
  return null;
3456
5040
  }
5041
+ function decodeClaudeHumanMessageRow(row, sessionId) {
5042
+ if (!isClaudeNativeHumanMessageRow(row)) return decodeClaudeQueuedPromptRow(row, sessionId);
5043
+ return decodeClaudeNativeHumanMessage(row, sessionId);
5044
+ }
5045
+ function isClaudeNativeHumanMessageRow(row) {
5046
+ return record4(row) && row.type === "user" && record4(row.message) && typeof row.message.content === "string";
5047
+ }
5048
+ function decodeClaudeNativeHumanMessage(row, sessionId) {
5049
+ if (!sessionMatches(row, sessionId)) return null;
5050
+ if (row.isMeta === true && (!record4(row.origin) || typeof row.origin.kind !== "string")) return null;
5051
+ const identity = queuedRowIdentity(row);
5052
+ if (identity === null) throw new ClaudeHostError("payload_rejected", "Claude transcript human message identity is malformed.");
5053
+ const message = row.message;
5054
+ if (!record4(message) || typeof message.content !== "string") return null;
5055
+ return { turnId: identity.uuid, timestamp: identity.timestamp, content: message.content };
5056
+ }
3457
5057
  function decodeArrayTextPrompt(row, sessionId) {
3458
- if (!record3(row.message) || !Array.isArray(row.message.content)) return null;
5058
+ if (!record4(row.message) || !Array.isArray(row.message.content)) return null;
3459
5059
  if (!sessionMatches(row, sessionId)) return null;
3460
- if (row.isMeta === true && (!record3(row.origin) || typeof row.origin.kind !== "string")) return null;
5060
+ if (row.isMeta === true && (!record4(row.origin) || typeof row.origin.kind !== "string")) return null;
3461
5061
  const texts = arrayTextBlocks(row.message.content);
3462
5062
  if (texts === null) return null;
3463
5063
  const identity = queuedRowIdentity(row);
@@ -3467,13 +5067,13 @@ function decodeArrayTextPrompt(row, sessionId) {
3467
5067
  function arrayTextBlocks(content) {
3468
5068
  const texts = [];
3469
5069
  for (const block of content) {
3470
- if (!record3(block) || block.type !== "text" || typeof block.text !== "string") return null;
5070
+ if (!record4(block) || block.type !== "text" || typeof block.text !== "string") return null;
3471
5071
  texts.push(block.text);
3472
5072
  }
3473
5073
  return texts.length === 0 ? null : texts;
3474
5074
  }
3475
5075
  function decodeQueuedCommandPrompt(row, sessionId) {
3476
- if (!record3(row.attachment) || row.attachment.type !== "queued_command" || row.attachment.commandMode !== "prompt") return null;
5076
+ if (!record4(row.attachment) || row.attachment.type !== "queued_command" || row.attachment.commandMode !== "prompt") return null;
3477
5077
  if (typeof row.attachment.prompt !== "string" || row.attachment.prompt.length === 0) return null;
3478
5078
  if (!sessionMatches(row, sessionId)) return null;
3479
5079
  const identity = queuedRowIdentity(row);
@@ -3496,9 +5096,9 @@ function queuedRowIdentity(row) {
3496
5096
  if (typeof row.timestamp !== "string" || !Number.isFinite(Date.parse(row.timestamp))) return null;
3497
5097
  return { uuid: row.uuid, timestamp: row.timestamp };
3498
5098
  }
3499
- function queueEnqueueTurnId(sessionId, timestamp3, content) {
3500
- return `queue-enqueue:${createHash5("sha256").update(`${sessionId}
3501
- ${timestamp3}
5099
+ function queueEnqueueTurnId(sessionId, timestamp4, content) {
5100
+ return `queue-enqueue:${createHash7("sha256").update(`${sessionId}
5101
+ ${timestamp4}
3502
5102
  ${content}`, "utf8").digest("hex").slice(0, 32)}`;
3503
5103
  }
3504
5104
  function claudeLocalTurnRef(sessionId, turnId) {
@@ -3507,7 +5107,7 @@ function claudeLocalTurnRef(sessionId, turnId) {
3507
5107
  function claudeLocalInputRef(sessionId, turnId) {
3508
5108
  return `claude-input:${cealRequestSha256({ session_id: sessionId, prompt_id: turnId })}`;
3509
5109
  }
3510
- function record3(value) {
5110
+ function record4(value) {
3511
5111
  return value !== null && typeof value === "object" && !Array.isArray(value);
3512
5112
  }
3513
5113
 
@@ -3533,11 +5133,13 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3533
5133
  }
3534
5134
  async scanOpened(handle, registration) {
3535
5135
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
3536
- const cursor = await this.preflight(registration, handle, size, device, inode);
5136
+ const preflight = await this.preflight(registration, handle, size, device, inode);
5137
+ const cursor = preflight.cursor;
3537
5138
  if (cursor === null) return { records: 0, enqueued: 0, quarantined: true };
3538
5139
  if (cursor.status === "quarantined") {
3539
5140
  return { records: 0, enqueued: 0, quarantined: true };
3540
5141
  }
5142
+ if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
3541
5143
  const draft = mutableCursor(cursor);
3542
5144
  await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
3543
5145
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
@@ -3550,6 +5152,15 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3550
5152
  return { records: 0, enqueued: 0, quarantined: true };
3551
5153
  }
3552
5154
  async retireMissing(registration) {
5155
+ const observedAt = this.stamp();
5156
+ if (Date.parse(registration.expires_at) <= Date.parse(observedAt)) return this.retireTranscript(registration);
5157
+ const cursor = await this.store.readTranscriptCursor(registration);
5158
+ if (cursor !== null && isUnmaterializedCursor(cursor, this.sha(Buffer.alloc(0)))) {
5159
+ return { records: 0, enqueued: 0, quarantined: false };
5160
+ }
5161
+ return this.retireTranscript(registration);
5162
+ }
5163
+ retireTranscript(registration) {
3553
5164
  return this.retireMissingTranscript(registration.transcript_path, "Claude", () => this.store.retireTranscriptRegistration(registration));
3554
5165
  }
3555
5166
  initialCursor(registration) {
@@ -3561,6 +5172,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3561
5172
  offset: 0,
3562
5173
  anchor_start: 0,
3563
5174
  anchor_sha256: this.sha(Buffer.alloc(0)),
5175
+ human_message_window: { messages: [], truncated: false },
3564
5176
  subagents: {},
3565
5177
  status: "active",
3566
5178
  updated_at: this.stamp()
@@ -3578,37 +5190,70 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3578
5190
  }
3579
5191
  async preflight(registration, handle, size, device, inode) {
3580
5192
  const existing = await this.store.readTranscriptCursor(registration);
3581
- if (existing?.status === "quarantined") return existing;
5193
+ if (existing?.status === "quarantined") return { cursor: existing, checkpointPending: false };
3582
5194
  const cursor = existing ?? this.initialCursor(registration);
3583
5195
  if (cursor.device === void 0) {
3584
- if (cursor.offset !== 0) return await this.quarantineStored(cursor, device, inode, "transcript_replaced");
3585
- return { ...cursor, device, inode };
5196
+ const pinned = { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
5197
+ const reason2 = this.cursorIdentityReason(pinned, registration.transcript_path, device, inode);
5198
+ if (cursor.offset !== 0 || reason2 !== null) return { cursor: await this.quarantineStored(cursor, device, inode, "transcript_replaced"), checkpointPending: false };
5199
+ return { cursor: pinned, checkpointPending: true };
3586
5200
  }
3587
5201
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
3588
- if (reason !== null) return await this.quarantineStored(cursor, device, inode, reason);
3589
- return cursor;
5202
+ if (reason !== null) return { cursor: await this.quarantineStored(cursor, device, inode, reason), checkpointPending: false };
5203
+ if (cursor.human_message_window !== void 0) return { cursor, checkpointPending: false };
5204
+ return { cursor: { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) }, checkpointPending: true };
5205
+ }
5206
+ async readHumanMessageProjection(registration, handle, watermark) {
5207
+ let offset = 0;
5208
+ let window = { messages: [], truncated: false };
5209
+ while (offset < watermark) {
5210
+ const complete = await this.readChunk(handle, offset, watermark);
5211
+ if (complete === "empty" || complete === "partial") throw new ClaudeHostError("payload_rejected", "Claude transcript projection prefix is incomplete.", "malformed_line");
5212
+ for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
5213
+ let row;
5214
+ try {
5215
+ row = JSON.parse(line);
5216
+ } catch {
5217
+ throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
5218
+ }
5219
+ const prompt = decodeClaudeHumanMessageRow(row, registration.claude_session_id);
5220
+ if (prompt !== null) window = mergeHostInvocationHumanMessageWindow(window, [{
5221
+ host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, prompt.turnId),
5222
+ host_input_ref: claudeLocalInputRef(registration.claude_session_id, prompt.turnId),
5223
+ text: prompt.content
5224
+ }]);
5225
+ }
5226
+ offset += complete.length;
5227
+ }
5228
+ if (offset !== watermark) throw new ClaudeHostError("payload_rejected", "Claude transcript projection prefix does not match its cursor boundary.", "malformed_line");
5229
+ return window;
3590
5230
  }
3591
5231
  async consumeMainChunk(registration, complete, draft) {
3592
5232
  for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3593
5233
  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.");
5234
+ const record5 = parseTranscriptLine(line);
5235
+ if (record5 === null) throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
5236
+ if (isUserTurnLine(record5)) await this.openTurn(registration, draft, record5);
5237
+ else if (isAssistantUsageLine(record5)) this.accumulateUsage(draft, toUsage(record5.uuid, record5.timestamp, record5.message.usage));
5238
+ else if (isAssistantLine(record5) && record5.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude transcript usage is malformed.");
3599
5239
  else {
3600
- const queued = decodeClaudeQueuedPromptRow(record4, registration.claude_session_id);
5240
+ const queued = decodeClaudeQueuedPromptRow(record5, registration.claude_session_id);
3601
5241
  if (queued !== null) await this.openQueuedTurn(registration, draft, queued);
3602
5242
  }
3603
5243
  }
3604
5244
  }
3605
- async openTurn(registration, draft, record4) {
3606
- await this.openPromptTurn(registration, draft, { uuid: record4.uuid, timestamp: record4.timestamp, content: record4.message.content });
5245
+ async openTurn(registration, draft, record5) {
5246
+ await this.openPromptTurn(registration, draft, { uuid: record5.uuid, timestamp: record5.timestamp, content: record5.message.content });
3607
5247
  }
3608
5248
  async openQueuedTurn(registration, draft, queued) {
3609
5249
  await this.openPromptTurn(registration, draft, { uuid: queued.turnId, timestamp: queued.timestamp, content: queued.content });
3610
5250
  }
3611
5251
  async openPromptTurn(registration, draft, prompt) {
5252
+ draft.human_message_window = mergeHostInvocationHumanMessageWindow(draft.human_message_window, [{
5253
+ host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, prompt.uuid),
5254
+ host_input_ref: claudeLocalInputRef(registration.claude_session_id, prompt.uuid),
5255
+ text: prompt.content
5256
+ }]);
3612
5257
  await this.closeTurn(registration, draft, prompt.timestamp);
3613
5258
  const sessionRef = registration.host_session_ref;
3614
5259
  const turnRef = claudeLocalTurnRef(registration.claude_session_id, prompt.uuid);
@@ -3626,7 +5271,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3626
5271
  }
3627
5272
  await this.persistOpenedTurnContext(draft, { uuid: prompt.uuid, timestamp: prompt.timestamp, message: { content: prompt.content } }, inputRef, turnRef, promptRef, identity, observations);
3628
5273
  }
3629
- async persistOpenedTurnContext(draft, record4, inputRef, turnRef, promptRef, identity, observations) {
5274
+ async persistOpenedTurnContext(draft, record5, inputRef, turnRef, promptRef, identity, observations) {
3630
5275
  const expiresAt = this.expire(this.outboxRetentionMs);
3631
5276
  await this.store.putEnvelope({
3632
5277
  schema_version: "ceal.claude_observation_outbox.v1",
@@ -3636,27 +5281,27 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3636
5281
  observations,
3637
5282
  origin_input: true,
3638
5283
  submission_ref: submissionRef("input", turnRef, inputRef, promptRef),
3639
- created_at: record4.timestamp,
5284
+ created_at: record5.timestamp,
3640
5285
  expires_at: expiresAt
3641
5286
  });
3642
5287
  draft.enqueued += 1;
3643
5288
  await this.activateOpenedTurnContext(identity, promptRef, expiresAt);
3644
- this.setOpenedTurn(draft, record4, inputRef, turnRef, promptRef);
5289
+ this.setOpenedTurn(draft, record5, inputRef, turnRef, promptRef);
3645
5290
  }
3646
5291
  async activateOpenedTurnContext(identity, promptRef, expiresAt) {
3647
5292
  const selection = await this.store.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref);
3648
5293
  const turnGenerationRef = selection?.prompt_ref === promptRef ? selection.turn_generation_ref : void 0;
3649
5294
  await this.activateContext(identity, promptRef, turnGenerationRef, expiresAt);
3650
5295
  }
3651
- setOpenedTurn(draft, record4, inputRef, turnRef, promptRef) {
5296
+ setOpenedTurn(draft, record5, inputRef, turnRef, promptRef) {
3652
5297
  const folded = foldUnattributed(draft.unattributed);
3653
5298
  draft.open_turn = {
3654
5299
  turn_key: turnRef,
3655
- user_uuid: record4.uuid,
5300
+ user_uuid: record5.uuid,
3656
5301
  prompt_ref: promptRef,
3657
5302
  host_input_ref: inputRef,
3658
- started_at: record4.timestamp,
3659
- last_observed_at: folded?.last_observed_at ?? record4.timestamp,
5303
+ started_at: record5.timestamp,
5304
+ last_observed_at: folded?.last_observed_at ?? record5.timestamp,
3660
5305
  message_ids: folded?.message_ids ?? [],
3661
5306
  counts: folded?.counts ?? zeroCounts()
3662
5307
  };
@@ -3717,7 +5362,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3717
5362
  return consumed;
3718
5363
  }
3719
5364
  async consumeSubagentFile(draft, directory, name) {
3720
- const path = join3(directory, name);
5365
+ const path = join5(directory, name);
3721
5366
  let handle;
3722
5367
  try {
3723
5368
  handle = await openNoFollow(path);
@@ -3748,10 +5393,10 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3748
5393
  let consumed = 0;
3749
5394
  for (const line of chunk.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3750
5395
  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.");
5396
+ const record5 = parseTranscriptLine(line);
5397
+ if (record5 === null) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript line is not valid JSON.", "malformed_line");
5398
+ if (isAssistantUsageLine(record5)) this.accumulateUsage(draft, toUsage(record5.uuid, record5.timestamp, record5.message.usage));
5399
+ else if (isAssistantLine(record5) && record5.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript usage is malformed.");
3755
5400
  }
3756
5401
  return consumed;
3757
5402
  }
@@ -3810,6 +5455,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3810
5455
  offset: draft.offset,
3811
5456
  anchor_start: anchor.start,
3812
5457
  anchor_sha256: anchor.sha256,
5458
+ human_message_window: draft.human_message_window,
3813
5459
  subagents: draft.subagents,
3814
5460
  ...draft.open_turn === void 0 ? {} : { open_turn: draft.open_turn },
3815
5461
  ...draft.unattributed === void 0 ? {} : { unattributed: draft.unattributed },
@@ -3852,9 +5498,13 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3852
5498
  return await this.store.readTranscriptCursor(registration).catch(() => null) ?? this.initialCursor(registration);
3853
5499
  }
3854
5500
  };
5501
+ function isUnmaterializedCursor(cursor, emptyAnchorSha256) {
5502
+ return cursor.status === "active" && cursor.device === void 0 && cursor.inode === void 0 && cursor.offset === 0 && cursor.anchor_start === 0 && cursor.anchor_sha256 === emptyAnchorSha256;
5503
+ }
3855
5504
  function mutableCursor(cursor) {
3856
5505
  return {
3857
5506
  offset: cursor.offset,
5507
+ human_message_window: cursor.human_message_window ?? { messages: [], truncated: false },
3858
5508
  ...cursor.open_turn === void 0 ? {} : { open_turn: cursor.open_turn },
3859
5509
  ...cursor.unattributed === void 0 ? {} : { unattributed: cursor.unattributed },
3860
5510
  subagents: Object.fromEntries(Object.entries(cursor.subagents).map(([name, entry]) => [name, { ...entry }])),
@@ -3931,32 +5581,32 @@ function parseTranscriptLine(line) {
3931
5581
  return null;
3932
5582
  }
3933
5583
  }
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 };
5584
+ function lineIdentity(record5) {
5585
+ if (typeof record5.uuid !== "string" || record5.uuid.length === 0 || record5.uuid.length > 256) return null;
5586
+ if (typeof record5.timestamp !== "string" || !Number.isFinite(Date.parse(record5.timestamp))) return null;
5587
+ return { uuid: record5.uuid, timestamp: record5.timestamp };
3938
5588
  }
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);
5589
+ function isUserTurnLine(record5) {
5590
+ if (!isTranscriptRecord(record5) || record5.type !== "user") return false;
5591
+ if (!isTranscriptRecord(record5.message) || typeof record5.message.content !== "string") return false;
5592
+ if (record5.isMeta === true && (!isTranscriptRecord(record5.origin) || typeof record5.origin.kind !== "string")) return false;
5593
+ const identity = lineIdentity(record5);
3944
5594
  if (identity === null) throw new ClaudeHostError("payload_rejected", "Claude transcript user line is malformed.");
3945
5595
  return true;
3946
5596
  }
3947
- function isAssistantLine(record4) {
3948
- return isTranscriptRecord(record4) && record4.type === "assistant" && isTranscriptRecord(record4.message);
5597
+ function isAssistantLine(record5) {
5598
+ return isTranscriptRecord(record5) && record5.type === "assistant" && isTranscriptRecord(record5.message);
3949
5599
  }
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.");
5600
+ function isAssistantUsageLine(record5) {
5601
+ if (!isTranscriptRecord(record5)) return false;
5602
+ if (!isAssistantLine(record5) || record5.message.usage === void 0) return false;
5603
+ const identity = lineIdentity(record5);
5604
+ if (identity === null || !isTranscriptRecord(record5.message.usage)) throw new ClaudeHostError("payload_rejected", "Claude transcript usage line is malformed.");
3955
5605
  return true;
3956
5606
  }
3957
5607
  function subagentsDirectory(transcriptPath) {
3958
5608
  const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
3959
- return join3(stem, "subagents");
5609
+ return join5(stem, "subagents");
3960
5610
  }
3961
5611
  function observationRef(hostSourceRef, event, identity, value) {
3962
5612
  return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
@@ -4005,7 +5655,379 @@ async function drainClaudeProducerOnce(options) {
4005
5655
  return { scanned: scan.enqueued, ...await producer.drainOutbox() };
4006
5656
  }
4007
5657
 
5658
+ // host/claude/src/claude-usage-facts-capturer.ts
5659
+ import { createHash as createHash8 } from "node:crypto";
5660
+ import { constants as constants6 } from "node:fs";
5661
+ import { readdir as readdir3 } from "node:fs/promises";
5662
+ import { join as join6 } from "node:path";
5663
+ var ClaudeUsageFactsCapturer = class {
5664
+ sources;
5665
+ usage;
5666
+ now;
5667
+ diagnosticSink;
5668
+ nextRegistrationIndex = 0;
5669
+ nextSourceSlot = "main";
5670
+ nextSubagentIndex = 0;
5671
+ constructor(options) {
5672
+ this.sources = new ClaudeOutboxStore(options.outbox_dir);
5673
+ this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5674
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5675
+ this.diagnosticSink = options.diagnostic_sink;
5676
+ }
5677
+ async captureNext() {
5678
+ const registrations = await this.sources.listTranscriptRegistrations();
5679
+ let failed = false;
5680
+ const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
5681
+ failed = true;
5682
+ }));
5683
+ this.nextRegistrationIndex = result.nextIndex;
5684
+ if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5685
+ return result.captured;
5686
+ }
5687
+ async captureRegistration(registration, onFailure) {
5688
+ const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
5689
+ for (const source of sources) {
5690
+ let captured = false;
5691
+ try {
5692
+ captured = source === "main" ? await this.captureMain(registration) : await this.captureSubagent(registration, onFailure);
5693
+ } catch (error) {
5694
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
5695
+ onFailure();
5696
+ }
5697
+ if (captured) {
5698
+ this.nextSourceSlot = source === "main" ? "subagent" : "main";
5699
+ return true;
5700
+ }
5701
+ }
5702
+ return false;
5703
+ }
5704
+ async captureMain(registration) {
5705
+ const prepared = await openHostUsageTranscriptCursor({
5706
+ path: registration.transcript_path,
5707
+ producer: "claude",
5708
+ source_kind: "claude_transcript",
5709
+ host_source_ref: registration.host_source_ref,
5710
+ host_session_ref: registration.host_session_ref,
5711
+ source_slot: "main",
5712
+ created_at: this.stamp(),
5713
+ store: this.usage,
5714
+ inspect: ownedClaudeTranscriptFile,
5715
+ initial_cursor: initialCursor
5716
+ });
5717
+ if (prepared === null) return false;
5718
+ const { handle: main, source: mainFile, source_file_ref: mainRef, state, cursor } = prepared;
5719
+ try {
5720
+ if (cursor.source_file_ref !== mainRef || cursor.device !== mainFile.device || cursor.inode !== mainFile.inode || mainFile.size < cursor.offset || !await anchorMatches(main, cursor)) {
5721
+ await this.usage.commitScanTransition(state, "main", cursor, initialCursor(mainRef, mainFile.device, mainFile.inode), null, [unscopedGap("source_file_replaced")]);
5722
+ return true;
5723
+ }
5724
+ if (mainFile.size > cursor.offset) return await this.captureFile(main, registration, "main", mainRef, cursor, mainFile.size, state);
5725
+ } finally {
5726
+ await main.close();
5727
+ }
5728
+ return false;
5729
+ }
5730
+ async captureSubagent(registration, onFailure) {
5731
+ const names = await readSubagentNames(registration);
5732
+ let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
5733
+ if (state === null) return false;
5734
+ state = await this.usage.recoverPending(state);
5735
+ if (state.quarantined_reason !== void 0) return false;
5736
+ if (await this.retireMissingSubagent(state, names)) return true;
5737
+ if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
5738
+ return await this.recordExcessSubagentGap(state, names);
5739
+ }
5740
+ async retireMissingSubagent(state, names) {
5741
+ const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
5742
+ for (const [slot, cursor] of Object.entries(state.cursors)) {
5743
+ if (!slot.startsWith("subagent:") || liveSlots.has(slot)) continue;
5744
+ await this.usage.retireCursor(state, slot, cursor, unscopedGap("source_file_retired"));
5745
+ return true;
5746
+ }
5747
+ return false;
5748
+ }
5749
+ async recordExcessSubagentGap(state, names) {
5750
+ const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
5751
+ if (excessCount <= 0) return false;
5752
+ const mainCursor = state.cursors.main;
5753
+ if (mainCursor === void 0) return false;
5754
+ const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
5755
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
5756
+ return true;
5757
+ }
5758
+ async captureListedSubagents(registration, names, state, onFailure) {
5759
+ const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5760
+ for (let attempt = 0; attempt < candidates.length; attempt += 1) {
5761
+ const index = (this.nextSubagentIndex + attempt) % candidates.length;
5762
+ const name = candidates[index];
5763
+ if (name === void 0) continue;
5764
+ try {
5765
+ if (await this.captureSubagentFile(registration, name, state)) {
5766
+ this.nextSubagentIndex = (index + 1) % candidates.length;
5767
+ return true;
5768
+ }
5769
+ } catch (error) {
5770
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
5771
+ onFailure();
5772
+ }
5773
+ }
5774
+ return false;
5775
+ }
5776
+ async captureSubagentFile(registration, name, state) {
5777
+ let handle;
5778
+ try {
5779
+ const opened = await readHostUsageTranscriptSource(() => openNoFollow(join6(subagentsDirectory(registration.transcript_path), name), constants6.O_RDONLY));
5780
+ handle = opened;
5781
+ const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
5782
+ const sourceRef = sourceFileRef(registration, file.device, file.inode);
5783
+ const slot = subagentSlot(name);
5784
+ let current = state.cursors[slot];
5785
+ if (current === void 0) {
5786
+ current = initialCursor(sourceRef, file.device, file.inode);
5787
+ state = await this.usage.writeCursor(state, slot, current);
5788
+ }
5789
+ if (await cursorReplaced(handle, file, sourceRef, current)) {
5790
+ await this.usage.commitScanTransition(state, slot, current, initialCursor(sourceRef, file.device, file.inode), null, [unscopedGap("source_file_replaced")]);
5791
+ return true;
5792
+ }
5793
+ if (file.size > current.offset) return await this.captureFile(handle, registration, slot, sourceRef, current, file.size, state, "subagent");
5794
+ return false;
5795
+ } finally {
5796
+ await handle?.close();
5797
+ }
5798
+ }
5799
+ async captureFile(handle, registration, slot, sourceRef, before, size, state, kind = "main") {
5800
+ const chunk = await readHostUsageTranscriptChunk(handle, before.offset, size, before.skipping_oversized_line);
5801
+ if (chunk.end_offset === before.offset && chunk.lines.length === 0) return false;
5802
+ const processed = processClaudeChunk(chunk.lines, registration, sourceRef, kind, before, chunk.oversized_rows);
5803
+ const after = await updateAnchor(handle, { ...processed.cursor, offset: chunk.end_offset, skipping_oversized_line: chunk.skipping_oversized_line });
5804
+ const gaps = [...processed.gapCounts].map(([reason, omitted_count]) => ({ reason, source_file_ref: sourceRef, start_offset: before.offset, end_offset: chunk.end_offset, omitted_count }));
5805
+ const batch = processed.facts.length === 0 && gaps.length === 0 ? null : createCealHostUsageBatch({
5806
+ host_source_ref: registration.host_source_ref,
5807
+ host_session_ref: registration.host_session_ref,
5808
+ created_at: processed.createdAt,
5809
+ source_ranges: [{ source_file_ref: sourceRef, start_offset: before.offset, end_offset: chunk.end_offset }],
5810
+ facts: processed.facts,
5811
+ coverage_gaps: gaps
5812
+ });
5813
+ await this.usage.commitScanTransition(state, slot, before, after, batch);
5814
+ return true;
5815
+ }
5816
+ stamp() {
5817
+ const value = this.now();
5818
+ if (!Number.isFinite(value.getTime())) throw new Error("Claude usage facts clock is invalid.");
5819
+ return value.toISOString();
5820
+ }
5821
+ };
5822
+ function parseClaudeRow(line, registration, sourceRef, kind, hostTurnRef) {
5823
+ const value = parseRowRecord(line);
5824
+ const userTurn = kind === "main" ? mainUserTurn(value, registration.claude_session_id) : null;
5825
+ if (userTurn !== null) return { timestamp: timestamp3(userTurn.timestamp), turn_id: userTurn.turnId };
5826
+ if (!assistantRow(value)) return { timestamp: rowTimestamp(value) };
5827
+ return parseAssistantRow(value, registration, sourceRef, kind, hostTurnRef);
5828
+ }
5829
+ function mainUserTurn(value, sessionId) {
5830
+ return decodeClaudeHumanMessageRow(value, sessionId);
5831
+ }
5832
+ function parseRowRecord(line) {
5833
+ let value;
5834
+ try {
5835
+ value = JSON.parse(line);
5836
+ } catch {
5837
+ throw new Error("Claude transcript row is malformed.");
5838
+ }
5839
+ if (!isRecord5(value)) throw new Error("Claude transcript row is malformed.");
5840
+ return value;
5841
+ }
5842
+ function assistantRow(value) {
5843
+ return value.type === "assistant" && isRecord5(value.message);
5844
+ }
5845
+ function parseAssistantRow(value, registration, sourceRef, kind, hostTurnRef) {
5846
+ const message = value.message;
5847
+ const terminal = message.stop_reason === "end_turn";
5848
+ if (message.usage === void 0) return { timestamp: rowTimestamp(value), terminal };
5849
+ if (!isRecord5(message.usage)) return { timestamp: rowTimestamp(value), unsupported: true, terminal };
5850
+ const parsed = parseAssistantUsage(value, message, message.usage, registration, sourceRef, kind, hostTurnRef, terminal);
5851
+ return parsed;
5852
+ }
5853
+ function parseAssistantUsage(value, message, usage, registration, sourceRef, kind, hostTurnRef, terminal) {
5854
+ const observedAt = rowTimestamp(value);
5855
+ const values = assistantUsageValues(value, message, usage);
5856
+ if (values === null) return { timestamp: observedAt, unsupported: true, terminal };
5857
+ const { uuid, input, output, cached, cacheWrite, cacheCreation, reportedModel } = values;
5858
+ const normalizedInput = safeSum(input, cached, cacheWrite);
5859
+ if (normalizedInput === void 0) return { timestamp: observedAt, unsupported: true, terminal };
5860
+ const fact = createClaudeFact({ uuid, input, output, cached, cacheWrite, cacheCreation, normalizedInput, reportedModel, observedAt, registration, sourceRef, kind, hostTurnRef, terminal, stopReason: message.stop_reason });
5861
+ return { timestamp: observedAt, fact, terminal };
5862
+ }
5863
+ function assistantUsageValues(value, message, usage) {
5864
+ const uuid = boundedText2(value.uuid, 256);
5865
+ const input = safeCounter(usage.input_tokens);
5866
+ const output = safeCounter(usage.output_tokens);
5867
+ const cached = optionalCounter(usage, "cache_read_input_tokens");
5868
+ const cacheWrite = optionalCounter(usage, "cache_creation_input_tokens");
5869
+ const cacheCreation = cacheCreationUsage(usage.cache_creation);
5870
+ const reportedModel = message.model === void 0 || message.model === null ? null : boundedText2(message.model, 256);
5871
+ if (uuid === null || input === null || output === null || cached.invalid || cacheWrite.invalid || cacheCreation.invalid || invalidReportedModel(message.model, reportedModel)) return null;
5872
+ return { uuid, input, output, cached: cached.value, cacheWrite: cacheWrite.value, cacheCreation: cacheCreation.value, reportedModel };
5873
+ }
5874
+ function cacheCreationUsage(value) {
5875
+ if (value === void 0 || value === null) return { value: null, invalid: false };
5876
+ if (!isRecord5(value)) return { value: null, invalid: true };
5877
+ const oneHour = optionalCounter(value, "ephemeral_1h_input_tokens");
5878
+ const fiveMinutes = optionalCounter(value, "ephemeral_5m_input_tokens");
5879
+ return {
5880
+ value: { ephemeral_1h_input_tokens: oneHour.value, ephemeral_5m_input_tokens: fiveMinutes.value },
5881
+ invalid: oneHour.invalid || fiveMinutes.invalid
5882
+ };
5883
+ }
5884
+ function invalidReportedModel(model, reportedModel) {
5885
+ return model !== void 0 && model !== null && reportedModel === null;
5886
+ }
5887
+ function safeSum(input, cached, cacheWrite) {
5888
+ if (cached === null || cacheWrite === null) return null;
5889
+ const total = input + cached + cacheWrite;
5890
+ return Number.isSafeInteger(total) ? total : void 0;
5891
+ }
5892
+ function createClaudeFact({ uuid, input, output, cached, cacheWrite, cacheCreation, normalizedInput, reportedModel, observedAt, registration, sourceRef, kind, hostTurnRef, terminal, stopReason }) {
5893
+ const sourceUsage = { input_tokens: input, cache_read_input_tokens: cached, cache_creation_input_tokens: cacheWrite, cache_creation: cacheCreation, output_tokens: output };
5894
+ const sourceEventRef = hostUsageSourceEventReference(sourceRef, `claude:${uuid}:${sha2563(JSON.stringify(sourceUsage))}`);
5895
+ const normalizedTotal = normalizedInput === null ? null : safeOutputTotal(normalizedInput, output);
5896
+ return {
5897
+ fact_ref: hostUsageFactReference(sourceRef, sourceEventRef),
5898
+ host_session_ref: registration.host_session_ref,
5899
+ host_turn_ref: kind === "main" ? hostTurnRef : null,
5900
+ source_file_ref: sourceRef,
5901
+ source_event_ref: sourceEventRef,
5902
+ source_event_uuid: uuid,
5903
+ source_file_kind: kind,
5904
+ observed_at: observedAt,
5905
+ producer: "claude_transcript",
5906
+ requested_model: null,
5907
+ reported_model: reportedModel,
5908
+ source_usage: sourceUsage,
5909
+ normalized_usage: { input: normalizedInput, output, total: normalizedTotal, cached_input: cached, cache_write_input: cacheWrite, reasoning_output: null },
5910
+ counter_semantics: "assistant_message",
5911
+ finality: finality(terminal, stopReason),
5912
+ child_inclusion: "unknown",
5913
+ correction_semantics: "unknown"
5914
+ };
5915
+ }
5916
+ function safeOutputTotal(input, output) {
5917
+ const total = input + output;
5918
+ return Number.isSafeInteger(total) ? total : null;
5919
+ }
5920
+ function finality(terminal, stopReason) {
5921
+ return terminal ? "terminal" : stopReason === null || stopReason === void 0 ? "nonterminal" : "unknown";
5922
+ }
5923
+ function processClaudeChunk(lines, registration, sourceRef, kind, initial, oversizedRows) {
5924
+ let cursor = initial;
5925
+ let createdAt = registration.registered_at;
5926
+ const facts = [];
5927
+ const gapCounts = /* @__PURE__ */ new Map();
5928
+ if (oversizedRows > 0) gapCounts.set("unsupported_source_shape", oversizedRows);
5929
+ for (const line of lines) {
5930
+ let parsed;
5931
+ try {
5932
+ parsed = parseClaudeRow(line.toString("utf8"), registration, sourceRef, kind, cursor.host_turn_ref);
5933
+ } catch {
5934
+ addUnsupportedGap(gapCounts);
5935
+ continue;
5936
+ }
5937
+ createdAt = parsed.timestamp;
5938
+ if (parsed.unsupported === true) addUnsupportedGap(gapCounts);
5939
+ if (parsed.fact !== void 0) facts.push(parsed.fact);
5940
+ cursor = updateClaudeTurnCursor(cursor, parsed, registration, kind);
5941
+ }
5942
+ return { cursor, facts, gapCounts, createdAt };
5943
+ }
5944
+ function addUnsupportedGap(gapCounts) {
5945
+ gapCounts.set("unsupported_source_shape", (gapCounts.get("unsupported_source_shape") ?? 0) + 1);
5946
+ }
5947
+ function updateClaudeTurnCursor(cursor, row, registration, kind) {
5948
+ if (kind !== "main") return cursor;
5949
+ 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) };
5950
+ return row.terminal === true ? { ...cursor, native_turn_id: null, host_turn_ref: null } : cursor;
5951
+ }
5952
+ async function readSubagentNames(registration) {
5953
+ try {
5954
+ return (await readHostUsageTranscriptSource(() => readdir3(subagentsDirectory(registration.transcript_path)))).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
5955
+ } catch (error) {
5956
+ const cause = error instanceof HostUsageTranscriptSourceError ? error.cause : error;
5957
+ if (errorCode4(cause) === "ENOENT" || errorCode4(cause) === "ENOTDIR") return [];
5958
+ throw error;
5959
+ }
5960
+ }
5961
+ function initialCursor(sourceFileRef2, device, inode) {
5962
+ 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 };
5963
+ }
5964
+ function sourceFileRef(registration, device, inode) {
5965
+ return hostUsageSourceFileReference("claude_transcript", registration.host_source_ref, registration.host_session_ref, device, inode);
5966
+ }
5967
+ function subagentSlot(name) {
5968
+ return `subagent:${sha2563(name)}`;
5969
+ }
5970
+ function unscopedGap(reason) {
5971
+ return { reason, source_file_ref: null, start_offset: null, end_offset: null, omitted_count: null };
5972
+ }
5973
+ async function anchorMatches(handle, cursor) {
5974
+ const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
5975
+ if (bytes.length === 0) return sha2563("") === cursor.anchor_sha256;
5976
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, cursor.anchor_start));
5977
+ return bytesRead === bytes.length && sha2563(bytes) === cursor.anchor_sha256;
5978
+ }
5979
+ async function cursorReplaced(handle, file, sourceRef, cursor) {
5980
+ return cursor.source_file_ref !== sourceRef || cursor.device !== file.device || cursor.inode !== file.inode || file.size < cursor.offset || !await anchorMatches(handle, cursor);
5981
+ }
5982
+ async function updateAnchor(handle, cursor) {
5983
+ const anchor_start = Math.max(0, cursor.offset - CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
5984
+ const anchor = Buffer.alloc(cursor.offset - anchor_start);
5985
+ if (anchor.length > 0) {
5986
+ const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(anchor, 0, anchor.length, anchor_start));
5987
+ if (bytesRead !== anchor.length) throw new Error("Claude usage facts source changed during anchor read.");
5988
+ }
5989
+ return { ...cursor, anchor_start, anchor_sha256: sha2563(anchor) };
5990
+ }
5991
+ function rowTimestamp(value) {
5992
+ return timestamp3(value.timestamp);
5993
+ }
5994
+ function timestamp3(value) {
5995
+ if (!safeTimestamp(value)) throw new Error("Claude transcript timestamp is malformed.");
5996
+ return value;
5997
+ }
5998
+ function safeTimestamp(value) {
5999
+ return typeof value === "string" && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
6000
+ }
6001
+ function boundedText2(value, maximum) {
6002
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters2(value) ? value : null;
6003
+ }
6004
+ function hasControlCharacters2(value) {
6005
+ for (const character of value) {
6006
+ const code2 = character.codePointAt(0);
6007
+ if (code2 !== void 0 && (code2 < 32 || code2 === 127)) return true;
6008
+ }
6009
+ return false;
6010
+ }
6011
+ function safeCounter(value) {
6012
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
6013
+ }
6014
+ function optionalCounter(value, key) {
6015
+ if (!Object.hasOwn(value, key) || value[key] === null) return { value: null, invalid: false };
6016
+ const count = safeCounter(value[key]);
6017
+ return { value: count, invalid: count === null };
6018
+ }
6019
+ function isRecord5(value) {
6020
+ return value !== null && typeof value === "object" && !Array.isArray(value);
6021
+ }
6022
+ function errorCode4(error) {
6023
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
6024
+ }
6025
+ function sha2563(value) {
6026
+ return createHash8("sha256").update(value).digest("hex");
6027
+ }
6028
+
4008
6029
  // host/claude/src/claude-producer-service.ts
6030
+ var CLAUDE_PRODUCER_COMMAND_SCHEMA = "ceal.claude_producer_command.v1";
4009
6031
  var CLAUDE_PRODUCER_CONFIG_SCHEMA = "ceal.claude_producer_config.v1";
4010
6032
  var CLAUDE_TRANSCRIPTS_ROOT = "claude_transcripts_root";
4011
6033
  var CLAUDE_PRODUCER_DESCRIPTOR = {
@@ -4013,12 +6035,14 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
4013
6035
  producer_id: "claude",
4014
6036
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
4015
6037
  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
6038
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6039
+ drain: drainClaudeProducerOnce,
6040
+ background: (config, signal, dependencies) => {
6041
+ const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
6042
+ return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext(), fetch: dependencies.fetch }, signal);
6043
+ }
4020
6044
  };
4021
- function runClaudeProducerCli(args, signal, dependencies = {}) {
6045
+ function runClaudeProducerCli(args, signal, dependencies) {
4022
6046
  return runHostProducerCli(CLAUDE_PRODUCER_DESCRIPTOR, args, signal, dependencies);
4023
6047
  }
4024
6048
 
@@ -4035,8 +6059,7 @@ async function runProducerCommand(schemaVersion, run) {
4035
6059
  await run(serviceArguments.args, controller.signal);
4036
6060
  } catch (error) {
4037
6061
  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
- `);
6062
+ await writeHostServiceCommandResult(schemaVersion, { ok: false, code: code2 }, (line) => process.stderr.write(line));
4040
6063
  process.exitCode = 1;
4041
6064
  } finally {
4042
6065
  stopLogBound();
@@ -4046,4 +6069,4 @@ async function runProducerCommand(schemaVersion, run) {
4046
6069
  }
4047
6070
 
4048
6071
  // host/claude/bin/ceal-claude-producer.ts
4049
- await runProducerCommand("ceal.claude_producer_command.v1", runClaudeProducerCli);
6072
+ await runProducerCommand(CLAUDE_PRODUCER_COMMAND_SCHEMA, (args, signal) => runClaudeProducerCli(args, signal, { fetch: globalThis.fetch }));