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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,7 +30,7 @@ function isPlainRecord(value) {
30
30
  }
31
31
 
32
32
  // packages/ceal-client-protocol/src/client-wire-contract.ts
33
- import { createHash } from "node:crypto";
33
+ import { createHash as createHash2 } from "node:crypto";
34
34
 
35
35
  // packages/ceal-client-protocol/client-wire-contract.json
36
36
  var client_wire_contract_default = {
@@ -51,7 +51,7 @@ var client_wire_contract_default = {
51
51
  ordering: "utf16_code_unit_ascending"
52
52
  },
53
53
  artifact_descriptor: {
54
- operation_contract_bundle_schema_name: "ceal.operation_contract_bundle",
54
+ operation_contract_bundle_schema_name: "ceal.operation_contract_bundle_v2",
55
55
  operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
56
56
  schema_name: "ceal.verified_artifact_descriptor",
57
57
  fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
@@ -76,7 +76,7 @@ var client_wire_contract_default = {
76
76
  },
77
77
  command_request: {
78
78
  schema_name: "ceal.command_request",
79
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
79
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
80
80
  absolute_transport_max_bytes: 65536
81
81
  },
82
82
  command_resolution: {
@@ -122,8 +122,9 @@ var client_wire_contract_default = {
122
122
  },
123
123
  command_response: {
124
124
  schema_name: "ceal.command_response",
125
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
125
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
126
126
  descriptor_field: "verified_artifact",
127
+ request_context_field: "request_context",
127
128
  required_fields: [
128
129
  "schema_version",
129
130
  "exit_code",
@@ -133,7 +134,8 @@ var client_wire_contract_default = {
133
134
  "operation_id",
134
135
  "visible_output_max_bytes",
135
136
  "local_delivery",
136
- "verified_artifact"
137
+ "verified_artifact",
138
+ "request_context"
137
139
  ],
138
140
  bare_document_fields: [
139
141
  "invocation",
@@ -154,7 +156,7 @@ var client_wire_contract_default = {
154
156
  ],
155
157
  exit_code_max: 125,
156
158
  bare_document_max_bytes: 65536,
157
- complete_max_bytes: 66046
159
+ complete_max_bytes: 66195
158
160
  },
159
161
  host_invocation_authentication: {
160
162
  request_schema_name: "ceal.host_invocation_authentication_request",
@@ -168,6 +170,14 @@ var client_wire_contract_default = {
168
170
  "context_token",
169
171
  "expires_at"
170
172
  ],
173
+ refusal_schema_name: "ceal.host_invocation_authentication_refusal",
174
+ refusal_fields: [
175
+ "schema_version",
176
+ "ok",
177
+ "code",
178
+ "reason",
179
+ "gateway_status"
180
+ ],
171
181
  client_nonce: {
172
182
  character_class_source: "A-Za-z0-9_-",
173
183
  encoded_characters: 43
@@ -206,6 +216,8 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
206
216
  "choose_new_output_path",
207
217
  "choose_new_idempotency_key",
208
218
  "restart_search",
219
+ // The requested temporal key is absent on some observed rows; repeating the same interval without `order` can return those rows.
220
+ "search_without_order",
209
221
  "repeat_original_arguments",
210
222
  // The occurrence this call addressed is settled and cannot move again -- a
211
223
  // denied effect approval, an expired continuation -- so the caller runs the
@@ -264,6 +276,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
264
276
  // The command needs caller-owned local materialization (for example an
265
277
  // @path file) before the Gateway can receive the argument.
266
278
  "materialize_local_argument",
279
+ // A missing or stale local Host bundle is repaired through its installed lifecycle and discovery owners.
280
+ "install_ceal_host",
281
+ // An explicit Client store override points at a missing file; unsetting it selects the one canonical default store without creating a second credential store.
282
+ "unset_context_store_path",
283
+ // The producer app must reload its installed Host hook before it can start a conversation with invocation context.
284
+ "restart_producer_app",
267
285
  // A peer's derived schema identifier changed with its field set; install or
268
286
  // upgrade the CLI and Host Relay to the Gateway's release before retrying.
269
287
  "upgrade_ceal_client"
@@ -372,7 +390,6 @@ var NON_MODEL_ACTION_TO_MODEL_ACTION = Object.freeze({
372
390
  });
373
391
  var RETRY_PROMISE_NEXT_ACTIONS = ["retry", "retry_after"];
374
392
  var RETRY_PROMISE = new Set(RETRY_PROMISE_NEXT_ACTIONS);
375
- var RECOVERABLE = new Set(CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS);
376
393
  var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
377
394
  provider_permission: "ask_admin",
378
395
  access_level: "ask_admin",
@@ -397,9 +414,9 @@ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "s
397
414
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
398
415
  var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
399
416
  var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
400
- var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "scope_limit_exceeded"]);
417
+ var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
401
418
  var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
402
- var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable"]);
419
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
403
420
  var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
404
421
  var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
405
422
  var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
@@ -523,11 +540,13 @@ function isSafeExternalHttpsUrl(value) {
523
540
  return false;
524
541
  }
525
542
  }
543
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE = "^https://[^\\s/@?#]+(?:[/?#][^\\s]*)?$";
544
+ var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN = new RegExp(SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE, "u");
526
545
  function isSafeExternalHttpsUrlInput(value) {
527
546
  return typeof value === "string" && byteLength(value) <= 2048;
528
547
  }
529
- function isSafeExternalHttpsUrlShape(url) {
530
- return url.protocol === "https:" && url.username === "" && url.password === "" && url.hash === "";
548
+ function isSafeExternalHttpsUrlShape(url, allowFragment = false) {
549
+ return url.protocol === "https:" && url.hostname.length > 0 && url.username === "" && url.password === "" && (allowFragment || url.hash === "");
531
550
  }
532
551
  function isSafeResultContent(value, key) {
533
552
  const maximum = key === "text" ? 8192 : 1024;
@@ -649,6 +668,7 @@ function cut(text) {
649
668
 
650
669
  // packages/ceal-client-protocol/src/operation-validation-primitives.ts
651
670
  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;
671
+ var EXPANDED_CANONICAL_ISO_TIMESTAMP = /^([+-])(\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/u;
652
672
  var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
653
673
  var CEAL_CALENDAR_DATE = new RegExp(CEAL_CALENDAR_DATE_PATTERN_SOURCE, "u");
654
674
  function isOperationRecord(value) {
@@ -665,7 +685,35 @@ function requireClosedValue(value, members, message) {
665
685
  function isCealIsoTimestamp(value) {
666
686
  return typeof value === "string" && parseCealIsoTimestamp(value) !== null;
667
687
  }
688
+ function canonicalCealIsoTimestamp(epochNanoseconds) {
689
+ const wholeSeconds = floorDivide(epochNanoseconds, 1000000000n);
690
+ const fractionalNanoseconds = epochNanoseconds - wholeSeconds * 1000000000n;
691
+ const utc = new Date(Number(wholeSeconds * 1000n));
692
+ const date = utc.toISOString().split(".")[0];
693
+ if (date === void 0) throw new TypeError("Ceal timestamp formatter returned an invalid ISO string");
694
+ const fraction = fractionalNanoseconds.toString().padStart(9, "0").replace(/0+$/u, "").padEnd(3, "0");
695
+ return date + "." + fraction + "Z";
696
+ }
697
+ var CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE = "0000-01-01T00:00:00.000000000+23:59";
698
+ var CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE = "9999-12-31T23:59:59.999999999-23:59";
699
+ var CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE);
700
+ var CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE);
701
+ var CEAL_INSTANT_INDEX_SPAN = CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS - CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS;
702
+ var CEAL_INSTANT_INDEX_KEY_WIDTH = CEAL_INSTANT_INDEX_SPAN.toString().length;
703
+ var CEAL_INSTANT_INDEX_KEY_PATTERN = new RegExp(`^\\d{${CEAL_INSTANT_INDEX_KEY_WIDTH}}$`, "u");
704
+ function requiredTimestampEpochNanoseconds(value) {
705
+ const parsed = parseFourDigitCealIsoTimestamp(value);
706
+ if (parsed === null) throw new Error("Ceal instant-index range basis is outside the timestamp grammar");
707
+ return parsed.epochNanoseconds;
708
+ }
668
709
  function parseCealIsoTimestamp(value) {
710
+ const ordinary = parseFourDigitCealIsoTimestamp(value);
711
+ if (ordinary !== null) return ordinary;
712
+ const expanded = parseExpandedCanonicalCealIsoTimestamp(value);
713
+ if (expanded === null || expanded.epochNanoseconds < CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS || expanded.epochNanoseconds > CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS) return null;
714
+ return canonicalCealIsoTimestamp(expanded.epochNanoseconds) === value ? expanded : null;
715
+ }
716
+ function parseFourDigitCealIsoTimestamp(value) {
669
717
  const fields = parseCealIsoTimestampFields(value);
670
718
  if (fields === null || !validCalendarDate(fields) || !validClockTime(fields) || !validUtcOffset(fields)) return null;
671
719
  const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
@@ -674,6 +722,28 @@ function parseCealIsoTimestamp(value) {
674
722
  epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
675
723
  };
676
724
  }
725
+ function parseExpandedCanonicalCealIsoTimestamp(value) {
726
+ const match = EXPANDED_CANONICAL_ISO_TIMESTAMP.exec(value);
727
+ if (match === null) return null;
728
+ const fields = {
729
+ year: (match[1] === "-" ? -1 : 1) * Number(match[2]),
730
+ month: Number(match[3]),
731
+ day: Number(match[4]),
732
+ hour: Number(match[5]),
733
+ minute: Number(match[6]),
734
+ second: Number(match[7]),
735
+ fraction: match[8] ?? "",
736
+ offsetSign: 0,
737
+ offsetHour: 0,
738
+ offsetMinute: 0
739
+ };
740
+ if (!validCalendarDate(fields) || !validClockTime(fields)) return null;
741
+ const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
742
+ if (!Number.isFinite(epochMilliseconds)) return null;
743
+ return {
744
+ epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
745
+ };
746
+ }
677
747
  function parseCealIsoTimestampFields(value) {
678
748
  const match = ISO_TIMESTAMP.exec(value);
679
749
  if (match === null) return null;
@@ -706,6 +776,10 @@ function cealFieldsEpochMilliseconds(fields) {
706
776
  const offsetMilliseconds = fields.offsetSign * (fields.offsetHour * 60 + fields.offsetMinute) * 6e4;
707
777
  return localMilliseconds - offsetMilliseconds;
708
778
  }
779
+ function floorDivide(value, divisor) {
780
+ const quotient = value / divisor;
781
+ return value % divisor < 0n ? quotient - 1n : quotient;
782
+ }
709
783
  function daysInMonth(year, month) {
710
784
  const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
711
785
  return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
@@ -723,6 +797,9 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
723
797
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
724
798
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
725
799
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
800
+ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
801
+ 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.";
802
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select or activate the current recorded turn. This does not explain why or prove ephemerality. For an independently identified ephemeral Codex side conversation, invoke the command as `ceal --standalone ...`; it uses the local Ceal session and Gateway permissions without Host session/turn audit linkage. Host refusal never switches modes. For intended Host calls, restart the producer and start a new conversation; report the error if it persists.";
726
803
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
727
804
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
728
805
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
@@ -748,6 +825,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
748
825
  refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
749
826
  refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
750
827
  refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
828
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
829
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
751
830
  refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
752
831
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
753
832
  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),
@@ -760,8 +839,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
760
839
  response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
761
840
  request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
762
841
  request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
842
+ resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
763
843
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
764
- 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),
844
+ contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
765
845
  // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
766
846
  // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
767
847
  // when the wait ends still unserved, moved from the `localFailureText` default branch.
@@ -773,6 +853,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
773
853
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
774
854
  // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
775
855
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
856
+ gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
776
857
  // Restored verbatim from the retired `localFailureText` `unknown_outcome`
777
858
  // case: the outcome is unknown, so a read may be retried while a write
778
859
  // must receipt-check first. Collapsing both to "do not repeat the call"
@@ -858,23 +939,24 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
858
939
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
859
940
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
860
941
  // is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
861
- // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). The three rows
862
- // with their own sentences carry the retired policy remedies as Gateway-owned guidance. Statuses are the
942
+ // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). Cause-specific
943
+ // sentences carry the retired policy remedies; `gateway_refused` reuses the release-upgrade guidance above.
944
+ // Statuses are the
863
945
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
864
946
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
865
947
  host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
866
948
  host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
867
949
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
868
- // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
869
- // missing exact-turn fact names the fresh Host turn, not a reinstall.
870
- 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),
950
+ // The bounded Host reason does not prove ephemerality. A Host refusal never
951
+ // changes mode; standalone remains the separate Client authority path.
952
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
871
953
  host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
872
954
  host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
873
955
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
874
956
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
875
957
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
876
958
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
877
- host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
959
+ host_mint_gateway_refused: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
878
960
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
879
961
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
880
962
  // producer-frame fault names the administrator repair step.
@@ -882,10 +964,10 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
882
964
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
883
965
  // sandboxed Relay socket names the run-alone retry.
884
966
  host_relay_permission_denied: guidance("An agent sandbox denied the Host Relay socket; run `ceal` as the only command, with no pipe, redirect, or `&&`, so the Host allow rule runs it outside the sandbox.", "rerun_outside_agent_sandbox", 403),
885
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
967
+ host_relay_unavailable: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 503),
886
968
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
887
969
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
888
- host_relay_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
970
+ host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
889
971
  host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
890
972
  });
891
973
  function cealFailureGuidanceForCode(code) {
@@ -895,6 +977,147 @@ function cealFailureGuidanceForCode(code) {
895
977
  }
896
978
  var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
897
979
 
980
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
981
+ import { createHash } from "node:crypto";
982
+
983
+ // packages/ceal-client-protocol/src/operation-withheld-cause.ts
984
+ var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
985
+
986
+ // packages/ceal-client-protocol/src/operation-contract-types.ts
987
+ var CEAL_JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
988
+ var CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION = "ceal.operation_descriptor.v1";
989
+ var CEAL_OPERATION_ERROR_SCHEMA_VERSION = "ceal.operation_error.v1";
990
+ var CEAL_ARTIFACT_STAGE_TERMINALS = vocabulary(["chunk_accepted", "artifact_ready", "idempotency_replayed"]);
991
+ var CEAL_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
992
+ var CEAL_JSON_SCHEMA_TYPES = vocabulary(["object", "array", "string", "integer", "number", "boolean", "null"]);
993
+ var OBSERVATION_POSTURES = vocabulary(["direct_readback", "approved_no_readback", "operator_mediated", "excluded"]);
994
+ var EFFECT_DOMAINS = vocabulary(["none", "gateway_state", "provider", "external_world"]);
995
+ var SAFETY_CLASSES = vocabulary(["routine", "sensitive", "high_impact"]);
996
+ var IDEMPOTENCY_CLASSES = vocabulary(["idempotent", "conditionally_idempotent", "non_idempotent"]);
997
+ var REVERSIBILITY_CLASSES = vocabulary(["none", "reversible", "compensatable", "irreversible"]);
998
+ var COMPENSATION_OWNERS = vocabulary(["none", "connector", "operator"]);
999
+ var CANCELLATION_BOUNDARIES = vocabulary(["before_admission", "before_handoff", "after_handoff_reconcile"]);
1000
+ var HANDOFF_CLASSES = vocabulary(["not_applicable", "submission", "effect"]);
1001
+ var AUTHORITATIVE_READBACK_CLASSES = vocabulary(["required", "unavailable"]);
1002
+ var PROVIDER_READBACK_CLASSES = vocabulary(["required", "not_available", "not_applicable"]);
1003
+ var RECONCILIATION_CLASSES = vocabulary(["none", "automatic", "operator"]);
1004
+ var NO_READBACK_APPROVAL_CLASSES = vocabulary(["not_applicable", "explicit", "operator"]);
1005
+ var REPLAY_PREREQUISITES = vocabulary(["never", "fresh_admission", "reconciled_non_application", "operator_approval"]);
1006
+ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
1007
+ var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
1008
+ var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
1009
+ var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
1010
+ var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
1011
+ var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
1012
+ var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
1013
+ var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
1014
+ var CEAL_OPERATION_RECOVERY_STATUSES = vocabulary(["not_started", "active", "completed"]);
1015
+ var CEAL_OPERATION_PROVIDER_READBACK_AVAILABILITY = vocabulary(["not_started", "not_applicable", "not_available", "pending", "available"]);
1016
+ var CEAL_OPERATION_OFFERED_HANDOFF_STATES = vocabulary(["accepted", "rejected", "unknown"]);
1017
+ var CEAL_OPERATION_RECEIPT_AUTHORITY_KEYS = Object.freeze(["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]);
1018
+ var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
1019
+ "approval_not_required_by_policy",
1020
+ "interactive_pending",
1021
+ "interactive_granted",
1022
+ "interactive_denied",
1023
+ "interactive_expired",
1024
+ "interactive_unavailable"
1025
+ ]);
1026
+
1027
+ // packages/ceal-client-protocol/src/request-validation-primitives.ts
1028
+ var DIGEST = /^[a-f0-9]{64}$/u;
1029
+ var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1030
+ function isCealDigest(value) {
1031
+ return typeof value === "string" && DIGEST.test(value);
1032
+ }
1033
+ function cealRequestSha256(value) {
1034
+ return createHash("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1035
+ }
1036
+ function operationRecord(value, message) {
1037
+ requireOperationRecord(value, message);
1038
+ return value;
1039
+ }
1040
+ function invalid(message) {
1041
+ throw new TypeError(message);
1042
+ }
1043
+ function requirePrefixedRef(value, prefix, message) {
1044
+ if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1045
+ }
1046
+
1047
+ // packages/ceal-client-protocol/src/request-authority.ts
1048
+ var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1049
+ var CEAL_REQUEST_REF_MAX_CHARACTERS = 128;
1050
+ var CEAL_REQUEST_REF_PATTERN_SOURCE = "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$";
1051
+ var CEAL_REQUEST_REF_PATTERN = new RegExp(CEAL_REQUEST_REF_PATTERN_SOURCE, "u");
1052
+ var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1053
+ var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1054
+ var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1055
+ var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1056
+ var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1057
+ var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1058
+ schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1059
+ ceal_request_ref: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_REF_MAX_CHARACTERS, pattern: CEAL_REQUEST_REF_PATTERN_SOURCE },
1060
+ created_at: { type: "string", minLength: 1, maxLength: 64 },
1061
+ authority: {
1062
+ type: "object",
1063
+ maxProperties: 5,
1064
+ additionalProperties: false,
1065
+ properties: {
1066
+ instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1067
+ access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1068
+ principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1069
+ execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1070
+ authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1071
+ },
1072
+ required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1073
+ }
1074
+ });
1075
+ var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1076
+ prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1077
+ host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1078
+ host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1079
+ 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." },
1080
+ host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1081
+ host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1082
+ });
1083
+ var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1084
+ 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." },
1085
+ 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." }
1086
+ });
1087
+ var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1088
+ requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1089
+ 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." }
1090
+ });
1091
+ var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1092
+ var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1093
+ var CEAL_REQUEST_JSON_SCHEMA = {
1094
+ type: "object",
1095
+ 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.",
1096
+ maxProperties: 14,
1097
+ additionalProperties: false,
1098
+ properties: {
1099
+ ...CEAL_REQUEST_COMMON_PROPERTIES,
1100
+ ...CEAL_REQUEST_HOST_PROPERTIES,
1101
+ ...CEAL_REQUEST_CALLER_PROPERTIES,
1102
+ ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1103
+ },
1104
+ required: CEAL_REQUEST_KEYS,
1105
+ anyOf: [
1106
+ {
1107
+ type: "object",
1108
+ required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1109
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1110
+ additionalProperties: false
1111
+ },
1112
+ {
1113
+ type: "object",
1114
+ required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1115
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1116
+ additionalProperties: false
1117
+ }
1118
+ ]
1119
+ };
1120
+
898
1121
  // packages/ceal-client-protocol/src/client-wire-contract.ts
899
1122
  var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
900
1123
  var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
@@ -907,7 +1130,7 @@ function deriveCealClientWireSchemaVersion(schema) {
907
1130
  throw new TypeError("Client wire schema name or field set is invalid.");
908
1131
  }
909
1132
  const fields = schema.fields.filter((field) => field !== "schema_version").sort();
910
- const hash8 = createHash("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
1133
+ const hash8 = createHash2("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
911
1134
  return `${schema.schema_name}.v1.${hash8}`;
912
1135
  }
913
1136
  var CealClientWireContractMismatchError = class extends Error {
@@ -945,57 +1168,14 @@ var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(requ
945
1168
  var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
946
1169
  var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
947
1170
  var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
948
- var CEAL_COMMAND_RESPONSE_DISCOVERY_COMMAND = response.discovery_command;
949
1171
  var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
950
1172
  var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
951
- var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_DOCUMENT_FIELDS = Object.freeze([...response.discovery_manifest_document_fields]);
952
1173
  var CEAL_COMMAND_RESPONSE_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
953
1174
  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 });
954
1175
  var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
955
1176
 
956
- // packages/ceal-client-protocol/src/operation-withheld-cause.ts
957
- var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
958
-
959
- // packages/ceal-client-protocol/src/operation-contract-types.ts
960
- var CEAL_JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
961
- var CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION = "ceal.operation_descriptor.v1";
962
- var CEAL_OPERATION_ERROR_SCHEMA_VERSION = "ceal.operation_error.v1";
963
- var CEAL_ARTIFACT_STAGE_TERMINALS = vocabulary(["chunk_accepted", "artifact_ready", "idempotency_replayed"]);
964
- var CEAL_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
965
- var CEAL_JSON_SCHEMA_TYPES = vocabulary(["object", "array", "string", "integer", "number", "boolean", "null"]);
966
- var OBSERVATION_POSTURES = vocabulary(["direct_readback", "approved_no_readback", "operator_mediated", "excluded"]);
967
- var EFFECT_DOMAINS = vocabulary(["none", "gateway_state", "provider", "external_world"]);
968
- var SAFETY_CLASSES = vocabulary(["routine", "sensitive", "high_impact"]);
969
- var IDEMPOTENCY_CLASSES = vocabulary(["idempotent", "conditionally_idempotent", "non_idempotent"]);
970
- var REVERSIBILITY_CLASSES = vocabulary(["none", "reversible", "compensatable", "irreversible"]);
971
- var COMPENSATION_OWNERS = vocabulary(["none", "connector", "operator"]);
972
- var CANCELLATION_BOUNDARIES = vocabulary(["before_admission", "before_handoff", "after_handoff_reconcile"]);
973
- var HANDOFF_CLASSES = vocabulary(["not_applicable", "submission", "effect"]);
974
- var AUTHORITATIVE_READBACK_CLASSES = vocabulary(["required", "unavailable"]);
975
- var PROVIDER_READBACK_CLASSES = vocabulary(["required", "not_available", "not_applicable"]);
976
- var RECONCILIATION_CLASSES = vocabulary(["none", "automatic", "operator"]);
977
- var NO_READBACK_APPROVAL_CLASSES = vocabulary(["not_applicable", "explicit", "operator"]);
978
- var REPLAY_PREREQUISITES = vocabulary(["never", "fresh_admission", "reconciled_non_application", "operator_approval"]);
979
- var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
980
- var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
981
- var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
982
- var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
983
- var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
984
- var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
985
- var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
986
- var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
987
- var CEAL_OPERATION_RECOVERY_STATUSES = vocabulary(["not_started", "active", "completed"]);
988
- var CEAL_OPERATION_PROVIDER_READBACK_AVAILABILITY = vocabulary(["not_started", "not_applicable", "not_available", "pending", "available"]);
989
- var CEAL_OPERATION_OFFERED_HANDOFF_STATES = vocabulary(["accepted", "rejected", "unknown"]);
990
- var CEAL_OPERATION_RECEIPT_AUTHORITY_KEYS = Object.freeze(["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]);
991
- var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
992
- "approval_not_required_by_policy",
993
- "interactive_pending",
994
- "interactive_granted",
995
- "interactive_denied",
996
- "interactive_expired",
997
- "interactive_unavailable"
998
- ]);
1177
+ // packages/ceal-client-protocol/src/access-level-vocabulary.ts
1178
+ var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
999
1179
 
1000
1180
  // packages/ceal-client-protocol/src/operation-access-class.ts
1001
1181
  var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
@@ -1003,7 +1183,6 @@ var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
1003
1183
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
1004
1184
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
1005
1185
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
1006
- var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1007
1186
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
1008
1187
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
1009
1188
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1111,6 +1290,7 @@ var CEAL_SCHEMA_LITERALS = [
1111
1290
  "ceal.gateway_write_receipt_readback.v1",
1112
1291
  "ceal.gateway_write_request_receipt.v1",
1113
1292
  "ceal.host_observation.v1",
1293
+ "ceal.host_usage_batch.v1",
1114
1294
  "ceal.host_registration_request.v1",
1115
1295
  "ceal.host_registration_result.v1",
1116
1296
  CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
@@ -1139,7 +1319,6 @@ var CEAL_SCHEMA_LITERAL_SET = new Set(CEAL_SCHEMA_LITERALS);
1139
1319
  import { join } from "node:path";
1140
1320
  var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1141
1321
  bounded_store_sidecar: (root) => `${root}.jsonl`,
1142
- gateway_audit_archive: (root) => `${root}.jsonl`,
1143
1322
  gateway_access_group_connector_control_audit: (root) => `${root}.audit.jsonl`,
1144
1323
  gateway_access_group_connector_scope_audit: (root) => join(root, "profile-connector-scope-audit.jsonl"),
1145
1324
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
@@ -1151,6 +1330,10 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1151
1330
  });
1152
1331
 
1153
1332
  // packages/ceal-client-protocol/src/canonical-http-boundary.ts
1333
+ var CEAL_HTTP_CLIENT_EXCHANGE_REF_HEADER = "x-ceal-client-exchange-ref";
1334
+ var CEAL_HTTP_GATEWAY_REQUEST_REF_HEADER = "x-ceal-gateway-http-request-ref";
1335
+ var CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE = "^client-exchange:[a-f0-9]{32}$";
1336
+ var CEAL_HTTP_GATEWAY_REQUEST_REF_PATTERN_SOURCE = "^http-request:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
1154
1337
  var CEAL_CANONICAL_HTTP_MAX_RESPONSE_BYTES = CEAL_COMMAND_RESPONSE_MAX_BYTES;
1155
1338
 
1156
1339
  // packages/ceal-client-protocol/src/gateway-installation-activation.ts
@@ -1191,7 +1374,7 @@ function shellSingleQuoted(value) {
1191
1374
  return `'${value.replaceAll("'", "'\\''")}'`;
1192
1375
  }
1193
1376
  var CEAL_OPERATION_CONTRACT_REQUIRED_FIELDS = Object.freeze(["input_schema", "result_schema"]);
1194
- var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["summary", "input_resolution"]);
1377
+ var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["branches", "summary", "input_resolution"]);
1195
1378
  var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
1196
1379
  $schema: CEAL_JSON_SCHEMA_2020_12,
1197
1380
  $id: "https://ceal.dev/schemas/verified-artifact-descriptor.v1.schema.json",
@@ -1236,11 +1419,92 @@ var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_o
1236
1419
  // packages/ceal-client-protocol/src/actor-kind.ts
1237
1420
  var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
1238
1421
 
1422
+ // packages/ceal-client-protocol/src/provider-link-policy.ts
1423
+ var PROVIDER_LINK_RESULT_FIELDS = Object.freeze({
1424
+ read_row: Object.freeze({ human_link: "source_url", parent_context: Object.freeze(["thread_ref"]) }),
1425
+ write_result: Object.freeze({ human_links: Object.freeze(["user_openable_url", "url", "spreadsheet_url", "meet_url"]) })
1426
+ });
1427
+ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1428
+ { 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/" },
1429
+ { 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/" },
1430
+ { 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/" },
1431
+ { 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/" },
1432
+ { 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/" },
1433
+ { 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" },
1434
+ { 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" },
1435
+ { 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" },
1436
+ { 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" },
1437
+ { 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" },
1438
+ { 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" },
1439
+ { 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" },
1440
+ { 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" },
1441
+ { 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" },
1442
+ { 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" },
1443
+ { 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" },
1444
+ { 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" },
1445
+ { 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" },
1446
+ { 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" },
1447
+ { 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" }
1448
+ ]);
1449
+ var PROVIDER_LINK_HOSTS = Object.freeze({
1450
+ notion: Object.freeze(["notion.so", "www.notion.so", "notion.com", "www.notion.com", "app.notion.com"]),
1451
+ google_workspace: Object.freeze([
1452
+ "calendar.google.com",
1453
+ "contacts.google.com",
1454
+ "docs.google.com",
1455
+ "drive.google.com",
1456
+ "forms.google.com",
1457
+ "mail.google.com",
1458
+ "meet.google.com",
1459
+ "sites.google.com",
1460
+ "www.google.com"
1461
+ ])
1462
+ });
1463
+ var NOTION_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.notion);
1464
+ var GOOGLE_WORKSPACE_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.google_workspace);
1465
+ var PROVIDER_RESOURCE_SOURCE_URL_SCHEMA = Object.freeze({
1466
+ type: "string",
1467
+ minLength: 1,
1468
+ maxLength: 2048,
1469
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1470
+ 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."
1471
+ });
1472
+ var PROVIDER_USER_OPENABLE_URL_SCHEMA = Object.freeze({
1473
+ type: "string",
1474
+ minLength: 1,
1475
+ maxLength: 2048,
1476
+ pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
1477
+ 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."
1478
+ });
1479
+
1239
1480
  // packages/ceal-client-protocol/src/resource-row.ts
1240
1481
  var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
1241
1482
  var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
1242
1483
  var CEAL_RESOURCE_SEARCH_DIRECTIONS = vocabulary(["ascending", "descending"]);
1243
- 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"]);
1484
+ var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
1485
+ "query",
1486
+ "modified_since",
1487
+ "since",
1488
+ "until",
1489
+ "filetype",
1490
+ "authored_by_me",
1491
+ "authored_by",
1492
+ "edited_by",
1493
+ "include_replies",
1494
+ "kinds",
1495
+ "container_ref",
1496
+ "container_refs",
1497
+ "container_names",
1498
+ "addressed_to_me",
1499
+ "unread",
1500
+ "archived",
1501
+ "state",
1502
+ "event_types",
1503
+ "starred",
1504
+ "trashed",
1505
+ "permission"
1506
+ ]);
1507
+ var CEAL_RESOURCE_SEARCH_STATES = vocabulary(["open", "closed", "draft", "prerelease", "confirmed", "tentative", "cancelled"]);
1244
1508
  var CEAL_RESOURCE_TIME_BASES = vocabulary(["created", "modified", "viewed"]);
1245
1509
  var CEAL_REPOSITORY_VISIBILITIES = vocabulary(["public", "private", "internal"]);
1246
1510
  var CEAL_ACTIVITY_V3_KINDS = vocabulary(["authored", "edited", "messaged", "responded"]);
@@ -1336,6 +1600,8 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1336
1600
  container_label: { required: true, timestamp: false },
1337
1601
  container_ref: { required: false, timestamp: false },
1338
1602
  source_url: { required: false, timestamp: false },
1603
+ thread_ref: { required: false, timestamp: false },
1604
+ reply_count: { required: false, timestamp: false },
1339
1605
  source: { required: true, timestamp: false },
1340
1606
  owner: { required: false, timestamp: false },
1341
1607
  actor_kind: { required: false, timestamp: false },
@@ -1361,6 +1627,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1361
1627
  start: { required: false, timestamp: false },
1362
1628
  end: { required: false, timestamp: false },
1363
1629
  status: { required: false, timestamp: false },
1630
+ event_type: { required: false, timestamp: false },
1364
1631
  snippet: { required: false, timestamp: false },
1365
1632
  dated_notes: { required: false, timestamp: false },
1366
1633
  state: { required: true, timestamp: false },
@@ -1424,6 +1691,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1424
1691
  "refresh_inactive",
1425
1692
  "refresh_replayed",
1426
1693
  "refresh_revoked",
1694
+ "person_inactive",
1695
+ "principal_inactive",
1427
1696
  "authority_replaced",
1428
1697
  "refresh_recovery_unavailable",
1429
1698
  "refresh_recovery_expired",
@@ -1444,97 +1713,6 @@ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
1444
1713
  var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1445
1714
  var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1446
1715
 
1447
- // packages/ceal-client-protocol/src/request-validation-primitives.ts
1448
- import { createHash as createHash2 } from "node:crypto";
1449
- var DIGEST = /^[a-f0-9]{64}$/u;
1450
- var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1451
- function isCealDigest(value) {
1452
- return typeof value === "string" && DIGEST.test(value);
1453
- }
1454
- function cealRequestSha256(value) {
1455
- return createHash2("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1456
- }
1457
- function operationRecord(value, message) {
1458
- requireOperationRecord(value, message);
1459
- return value;
1460
- }
1461
- function invalid(message) {
1462
- throw new TypeError(message);
1463
- }
1464
- function requirePrefixedRef(value, prefix, message) {
1465
- if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
1466
- }
1467
-
1468
- // packages/ceal-client-protocol/src/request-authority.ts
1469
- var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1470
- var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1471
- var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1472
- var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1473
- var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1474
- var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1475
- var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1476
- schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1477
- ceal_request_ref: { type: "string", minLength: 1, maxLength: 128, pattern: "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$" },
1478
- created_at: { type: "string", minLength: 1, maxLength: 64 },
1479
- authority: {
1480
- type: "object",
1481
- maxProperties: 5,
1482
- additionalProperties: false,
1483
- properties: {
1484
- instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1485
- access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1486
- principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1487
- execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1488
- authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1489
- },
1490
- required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1491
- }
1492
- });
1493
- var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1494
- prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1495
- host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1496
- host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1497
- host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1498
- host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1499
- });
1500
- var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1501
- 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." },
1502
- 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." }
1503
- });
1504
- var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1505
- requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1506
- 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." }
1507
- });
1508
- var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1509
- var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1510
- var CEAL_REQUEST_JSON_SCHEMA = {
1511
- type: "object",
1512
- 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.",
1513
- maxProperties: 13,
1514
- additionalProperties: false,
1515
- properties: {
1516
- ...CEAL_REQUEST_COMMON_PROPERTIES,
1517
- ...CEAL_REQUEST_HOST_PROPERTIES,
1518
- ...CEAL_REQUEST_CALLER_PROPERTIES,
1519
- ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1520
- },
1521
- required: CEAL_REQUEST_KEYS,
1522
- anyOf: [
1523
- {
1524
- type: "object",
1525
- required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1526
- properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1527
- additionalProperties: false
1528
- },
1529
- {
1530
- type: "object",
1531
- required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1532
- properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1533
- additionalProperties: false
1534
- }
1535
- ]
1536
- };
1537
-
1538
1716
  // packages/ceal-client-protocol/src/request-operands.ts
1539
1717
  var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
1540
1718
  var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
@@ -1642,6 +1820,27 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
1642
1820
  required: ["schema_version", "order", "nodes", "call_budget"]
1643
1821
  };
1644
1822
 
1823
+ // packages/ceal-client-protocol/src/host-observation-validation.ts
1824
+ var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1825
+ 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;
1826
+ function validateCealHostObservationValue(value) {
1827
+ if (value === void 0) throw new TypeError("Ceal Host observation value is invalid.");
1828
+ assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1829
+ if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) throw new TypeError("Ceal Host observation value is oversized.");
1830
+ inspectHostKeys(value);
1831
+ }
1832
+ function inspectHostKeys(value) {
1833
+ if (Array.isArray(value)) {
1834
+ for (const entry2 of value) inspectHostKeys(entry2);
1835
+ return;
1836
+ }
1837
+ if (value === null || typeof value !== "object") return;
1838
+ for (const [key, child] of Object.entries(value)) {
1839
+ if (HOST_RESERVED_KEY.test(key)) throw new TypeError("Ceal Host observation cannot restate Gateway-owned facts.");
1840
+ inspectHostKeys(child);
1841
+ }
1842
+ }
1843
+
1645
1844
  // packages/ceal-client-protocol/src/host-observation.ts
1646
1845
  var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
1647
1846
  var HOST_TOKEN_OBSERVATION_BREAKDOWN_KEYS = vocabulary(["cached_input", "cache_write_input", "reasoning_output"]);
@@ -1652,31 +1851,20 @@ function validateCealHostObservationDraft(value) {
1652
1851
  requireIsoTimestamp(record6.observed_at, "Ceal Host observation time is invalid.");
1653
1852
  assertHostObservationValue(record6.value, record6.observation_kind);
1654
1853
  }
1655
- var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1656
1854
  var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
1657
1855
  function isCealHostPromptObservationValue(value) {
1658
1856
  return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
1659
1857
  }
1660
- 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;
1661
1858
  function assertHostObservationValue(value, kind) {
1662
1859
  if (value === void 0) invalid("Ceal Host observation value is invalid.");
1663
1860
  if (kind === "prompt" && !isCealHostPromptObservationValue(value)) invalid("Ceal Host prompt observation must contain only its body digest.");
1664
- assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
1665
- if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) invalid("Ceal Host observation value is oversized.");
1666
- inspectHostKeys(value);
1667
- }
1668
- function inspectHostKeys(value) {
1669
- if (Array.isArray(value)) {
1670
- for (const entry2 of value) inspectHostKeys(entry2);
1671
- return;
1672
- }
1673
- if (value === null || typeof value !== "object") return;
1674
- for (const [key, child] of Object.entries(value)) {
1675
- if (HOST_RESERVED_KEY.test(key)) invalid("Ceal Host observation cannot restate Gateway-owned facts.");
1676
- inspectHostKeys(child);
1677
- }
1861
+ validateCealHostObservationValue(value);
1678
1862
  }
1679
1863
 
1864
+ // packages/ceal-client-protocol/src/host-usage-facts.ts
1865
+ var CEAL_HOST_USAGE_BATCH_MAX_BYTES = 1024 * 1024;
1866
+ var CEAL_HOST_USAGE_FACT_MAX_BYTES = 64 * 1024;
1867
+
1680
1868
  // packages/ceal-client-protocol/src/host-prompt-ref.ts
1681
1869
  var CEAL_HOST_PROMPT_DIGEST_PATTERN = "^[a-f0-9]{64}$";
1682
1870
  var PROMPT_DIGEST = new RegExp(CEAL_HOST_PROMPT_DIGEST_PATTERN, "u");
@@ -1777,6 +1965,7 @@ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSch
1777
1965
  var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
1778
1966
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
1779
1967
  var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
1968
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.refusal_schema_name, fields: hostInvocationAuthenticationContract.refusal_fields });
1780
1969
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
1781
1970
  var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
1782
1971
  var CEAL_HOST_INVOCATION_CONTEXT_PATH = "/api/ceal/v2/host-invocation-context";
@@ -1794,7 +1983,7 @@ function decodeCealHostInvocationContextRequest(value) {
1794
1983
  const clientNonce = requireClientNonce(value.client_nonce);
1795
1984
  const expiresAt = requireContextExpiration(value.context_expires_at);
1796
1985
  const hostBinding = requireHostBinding(value.host_binding);
1797
- const messageWindow = requireHumanMessageWindow(value.human_message_window);
1986
+ const messageWindow = decodeCealHostInvocationHumanMessageWindow(value.human_message_window);
1798
1987
  const lastRequestRef = optionalSafeReference(value.last_seen_request_ref);
1799
1988
  const visibleOutputMaxBytes = optionalVisibleOutputBudget(value.visible_output_max_bytes);
1800
1989
  return Object.freeze({
@@ -1825,7 +2014,7 @@ function requireHostBinding(value) {
1825
2014
  if (!isCealJsonRecord(value) || !exactOptionalKeys(value, ["host_source_ref", "host_session_ref", "host_turn_ref"], []) || !safeReference(value.host_source_ref) || !safeReference(value.host_session_ref) || !safeReference(value.host_turn_ref)) throw invalidInvocationContextRequest();
1826
2015
  return { host_source_ref: value.host_source_ref, host_session_ref: value.host_session_ref, host_turn_ref: value.host_turn_ref };
1827
2016
  }
1828
- function requireHumanMessageWindow(value) {
2017
+ function decodeCealHostInvocationHumanMessageWindow(value) {
1829
2018
  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();
1830
2019
  const messages = value.messages.map(decodeHumanMessage);
1831
2020
  const bytes2 = new TextEncoder().encode(JSON.stringify(messages)).byteLength;
@@ -1833,8 +2022,9 @@ function requireHumanMessageWindow(value) {
1833
2022
  return Object.freeze({ messages: Object.freeze(messages), truncated: value.truncated });
1834
2023
  }
1835
2024
  function decodeHumanMessage(candidate) {
1836
- if (!isCealJsonRecord(candidate) || !exactOptionalKeys(candidate, ["host_turn_ref", "host_input_ref", "text"], []) || !safeReference(candidate.host_turn_ref) || !safeReference(candidate.host_input_ref) || typeof candidate.text !== "string") throw invalidInvocationContextRequest();
1837
- return Object.freeze({ host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: candidate.text });
2025
+ 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();
2026
+ if (candidate.text_truncated !== void 0 && candidate.text_truncated !== true) throw invalidInvocationContextRequest();
2027
+ 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 } : {} });
1838
2028
  }
1839
2029
  function optionalSafeReference(value) {
1840
2030
  if (value === void 0) return void 0;
@@ -1865,31 +2055,11 @@ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTR
1865
2055
  };
1866
2056
  }
1867
2057
  var hostNonceContract = deriveCealHostInvocationNonceContract();
1868
- var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
1869
2058
  var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
1870
2059
  var CEAL_HOST_CONTEXT_TOKEN_PATTERN = new RegExp(hostNonceContract.context_token_pattern_source, "u");
1871
- var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_MAX_BYTES = deriveCealHostInvocationAuthenticationResultMaxBytes();
1872
- function deriveCealHostInvocationAuthenticationResultMaxBytes(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1873
- const hostAuthentication = contract.host_invocation_authentication;
1874
- const values = {
1875
- schema_version: deriveCealClientWireSchemaVersion({ schema_name: hostAuthentication.result_schema_name, fields: hostAuthentication.result_fields }),
1876
- context_token: `${CEAL_HOST_CONTEXT_TOKEN_PREFIX}${"A".repeat(hostAuthentication.client_nonce.encoded_characters)}`,
1877
- expires_at: (/* @__PURE__ */ new Date("+010000-01-01T00:00:00.000Z")).toISOString()
1878
- };
1879
- const fields = hostAuthentication.result_fields;
1880
- if (fields.some((field) => !Object.hasOwn(values, field))) throw new TypeError("Host invocation result fields have no bounded sample value.");
1881
- return new TextEncoder().encode(`${JSON.stringify(Object.fromEntries(fields.map((field) => [field, values[field]])))}
1882
- `).byteLength;
1883
- }
1884
2060
  var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
1885
2061
  "request_authority_unavailable",
1886
- "request_missing",
1887
- "authority_mismatch",
1888
- "host_source_mismatch",
1889
- "host_session_mismatch",
1890
- "host_turn_mismatch",
1891
- "host_input_mismatch",
1892
- "host_prompt_mismatch"
2062
+ "request_creation_refused"
1893
2063
  ]);
1894
2064
  var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1895
2065
  "invalid_arguments",
@@ -1898,7 +2068,6 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1898
2068
  "context_unavailable",
1899
2069
  "context_replaced",
1900
2070
  "no_binding",
1901
- "context_stale",
1902
2071
  "context_expired",
1903
2072
  "host_source_refused",
1904
2073
  "host_credential_refused",
@@ -1915,31 +2084,42 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1915
2084
  "relay_failed",
1916
2085
  "host_refusal_invalid"
1917
2086
  ]);
2087
+ var CEAL_HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2088
+ "permission_denied",
2089
+ "socket_missing",
2090
+ "connection_refused",
2091
+ "closed_early",
2092
+ "response_invalid",
2093
+ "timed_out",
2094
+ "cancelled",
2095
+ "unavailable"
2096
+ ]);
1918
2097
  var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1919
2098
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
1920
2099
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
1921
2100
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1922
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
2101
+ // This reason cannot distinguish a Codex side conversation from a missing
2102
+ // context in a regular session, so guidance must leave that choice to the caller.
2103
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
1923
2104
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1924
2105
  // `no_binding` now means the producer has no real current Host session. The
1925
2106
  // Host Relay never uses it for an uncreated Gateway Request; there is no
1926
2107
  // useful retry until the consumer is running inside a Host session.
1927
2108
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1928
- context_stale: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1929
2109
  context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
1930
2110
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
1931
2111
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
1932
2112
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
1933
2113
  gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
1934
- contract_mismatch: Object.freeze({ classification: "contract_mismatch", next_action: "upgrade_ceal_client" }),
1935
- gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
2114
+ contract_mismatch: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2115
+ gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "upgrade_ceal_client" }),
1936
2116
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
1937
2117
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
1938
2118
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
1939
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2119
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
1940
2120
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
1941
2121
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
1942
- relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "answer_with_gap" }),
2122
+ relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
1943
2123
  host_refusal_invalid: Object.freeze({ classification: "host_refusal_invalid", next_action: "answer_with_gap" })
1944
2124
  });
1945
2125
  function decodeCealHostInvocationAuthenticationResult(value, now = /* @__PURE__ */ new Date()) {
@@ -1971,10 +2151,13 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
1971
2151
  "activation_recorded",
1972
2152
  "activation_failed",
1973
2153
  "watcher_scan_failed",
2154
+ "usage_capture_failed",
2155
+ "usage_upload_failed",
1974
2156
  "activation_wait_skipped",
1975
2157
  "activation_wait_engaged",
1976
2158
  "activation_wait_completed",
1977
- "activation_wait_exhausted"
2159
+ "activation_wait_exhausted",
2160
+ "invocation_authentication_failed"
1978
2161
  ]);
1979
2162
  var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1980
2163
  "malformed_line",
@@ -1984,6 +2167,14 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
1984
2167
  "size_budget",
1985
2168
  "symlink"
1986
2169
  ]);
2170
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_WATCHER_OPTIONAL_FIELDS = vocabulary(["failure_kind", "cause"]);
2171
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_OPTIONAL_FIELDS = vocabulary(["cause"]);
2172
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE = "^[a-z][a-z0-9_]{0,63}(?::[A-Za-z][A-Za-z0-9_]{0,63})?$";
2173
+ var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES = Object.freeze([
2174
+ ...CEAL_HOST_AUTHENTICATION_CAUSES,
2175
+ ...CEAL_HOST_RELAY_EXCHANGE_FAILURES.map((failure) => `relay_exchange:${failure}`)
2176
+ ]);
2177
+ var hostServiceDiagnosticCausePattern = new RegExp(CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE, "u");
1987
2178
 
1988
2179
  // packages/ceal-client-protocol/src/client-result-materialization.ts
1989
2180
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
@@ -2070,12 +2261,14 @@ var ADMIN_SOURCE_OWNERS = vocabulary([
2070
2261
  "resource",
2071
2262
  "prompt",
2072
2263
  "usage",
2264
+ "provider_request_lifecycle",
2073
2265
  "connector",
2074
2266
  "session",
2075
2267
  "knowledge",
2076
2268
  "policy"
2077
2269
  ]);
2078
2270
  var ADMIN_COMPLETENESS_STATES = vocabulary(["complete", "partial", "unknown"]);
2271
+ var ADMIN_PROVIDER_REQUEST_CAPTURE_HEALTH_STATES = vocabulary(["available", "missing", "invalid", "unreadable"]);
2079
2272
  var ADMIN_OPERATION_OUTCOMES = vocabulary(["completed", "failed", "denied", "cancelled", "unknown"]);
2080
2273
  var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
2081
2274
  var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
@@ -2099,13 +2292,16 @@ var FAILURE_RESPONSE_KEYS = Object.freeze(["error", "ok", "proof_ref_or_unavaila
2099
2292
  // host/invocation-authentication-client-command.ts
2100
2293
  var MAX_DETAIL_CHARACTERS = 240;
2101
2294
  var HOST_OWNED_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){0,7}$/u;
2295
+ function isHostOwnedFailureCode(value) {
2296
+ return typeof value === "string" && HOST_OWNED_CODE.test(value);
2297
+ }
2102
2298
  function hostTerminalFailure(error, component) {
2103
2299
  const code = errorCode(error);
2104
2300
  const detail = failureDetail(error);
2105
2301
  if (code === "ENOENT") return { code: "host_dependency_unavailable", message: `A command or file the ${component} Host needs is unavailable: ${detail}`, next_action: "Install the missing dependency or restore the missing file, then rerun this command." };
2106
2302
  if (code === "EACCES" || code === "EPERM") return { code: "host_permission_denied", message: `The ${component} Host was refused access to a local path: ${detail}`, next_action: "Repair the ownership or mode of the named path, then rerun this command." };
2107
2303
  if (code === "ENOSPC") return { code: "host_storage_unavailable", message: `The ${component} Host could not write local state: ${detail}`, next_action: "Free local disk space, then rerun this command." };
2108
- if (code !== null && HOST_OWNED_CODE.test(code)) return { code, message: `The ${component} Host command failed: ${detail}`, next_action: `Resolve the named failure above; run \`ceal-host doctor\` only if it reports installed ${component} Host drift.` };
2304
+ if (isHostOwnedFailureCode(code)) return { code, message: `The ${component} Host command failed: ${detail}`, next_action: `Resolve the named failure above; run \`ceal-host doctor\` only if it reports installed ${component} Host drift.` };
2109
2305
  return { code: "host_failure_unclassified", message: `The ${component} Host command failed for a cause it cannot classify: ${detail}`, next_action: `Run \`ceal-host doctor\`; if it reports no drift then the ${component} Host configuration is not the cause, and the message above is the only evidence of what is.` };
2110
2306
  }
2111
2307
  var DOCTOR_FLAGS = Object.freeze({
@@ -2130,7 +2326,7 @@ import { dirname as dirname2, isAbsolute, posix, win32 as win322 } from "node:pa
2130
2326
  import { execFile } from "node:child_process";
2131
2327
  import { constants } from "node:fs";
2132
2328
  import { lstat, open } from "node:fs/promises";
2133
- import { dirname, win32 } from "node:path";
2329
+ import { dirname, join as join2, win32 } from "node:path";
2134
2330
  import { fileURLToPath } from "node:url";
2135
2331
  var SecureFileCustodyError = class extends Error {
2136
2332
  name = "SecureFileCustodyError";
@@ -2191,7 +2387,7 @@ async function assertWindowsIdentityStable(handle, first, path) {
2191
2387
  }
2192
2388
  async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
2193
2389
  if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
2194
- const result2 = await runWindowsSecurefs(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2390
+ const result2 = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2195
2391
  if (result2.exit_code === 0 && result2.stderr.length === 0 && result2.stdout.length <= maxBytes) return result2.stdout;
2196
2392
  if (result2.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
2197
2393
  if (result2.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
@@ -2199,16 +2395,22 @@ async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
2199
2395
  }
2200
2396
  async function createRandomPrivateFileWithSecurefs(path, byteLength2, custody = {}) {
2201
2397
  if (!Number.isSafeInteger(byteLength2) || byteLength2 < 1 || byteLength2 > WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES) throw new TypeError(`The securefs random-file size must be between 1 and ${WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES} bytes.`);
2202
- const result2 = await runWindowsSecurefs(["internal", "securefs", "create-random-private-file", path, String(byteLength2)], 0, custody);
2398
+ const result2 = await runSecurefsCommand(["internal", "securefs", "create-random-private-file", path, String(byteLength2)], 0, custody);
2203
2399
  if (result2.exit_code === 0 && result2.stdout.length === 0 && result2.stderr.length === 0) return;
2204
2400
  if (result2.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned unexpected creation bytes.");
2205
2401
  if (result2.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid creation result.");
2206
2402
  throw securefsRefusal(result2.stderr);
2207
2403
  }
2404
+ async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
2405
+ const result2 = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
2406
+ if (result2.exit_code === 0 && result2.stdout.length === 0 && result2.stderr.length === 0) return;
2407
+ if (result2.stdout.length !== 0 || result2.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
2408
+ throw securefsRefusal(result2.stderr);
2409
+ }
2208
2410
  async function isPrivateWindowsDirectory(path, custody = {}) {
2209
2411
  await lstat(path);
2210
2412
  try {
2211
- const result2 = await runWindowsSecurefs(["internal", "securefs", "verify-private-dir", path], 0, custody);
2413
+ const result2 = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
2212
2414
  if (result2.exit_code === 0 && result2.stdout.length === 0 && result2.stderr.length === 0) return true;
2213
2415
  if (result2.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
2214
2416
  if (result2.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
@@ -2220,12 +2422,12 @@ async function isPrivateWindowsDirectory(path, custody = {}) {
2220
2422
  throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
2221
2423
  }
2222
2424
  }
2223
- async function runWindowsSecurefs(args, maxBytes, custody) {
2224
- if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args);
2225
- const executable = custody.securefs_executable ?? resolveInstalledHostExecutable();
2425
+ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2426
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
2427
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2226
2428
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2227
2429
  return await new Promise((resolve, reject) => {
2228
- execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2430
+ const child = execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2229
2431
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2230
2432
  if (exitCode === null) {
2231
2433
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2233,6 +2435,8 @@ async function runWindowsSecurefs(args, maxBytes, custody) {
2233
2435
  }
2234
2436
  resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
2235
2437
  });
2438
+ child.stdin?.on("error", () => void 0);
2439
+ child.stdin?.end(stdin);
2236
2440
  });
2237
2441
  }
2238
2442
  function securefsRefusal(stderr) {
@@ -2250,9 +2454,9 @@ function securefsRefusal(stderr) {
2250
2454
  if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
2251
2455
  return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
2252
2456
  }
2253
- function resolveInstalledHostExecutable() {
2457
+ function resolveInstalledHostExecutable(platform) {
2254
2458
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2255
- return win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
2459
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2256
2460
  }
2257
2461
  function isRecord(value) {
2258
2462
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2274,6 +2478,124 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
2274
2478
  return entry2.isDirectory() && !entry2.isSymbolicLink() && isSelfOwned(entry2.uid, platform) && isPrivateFileMode(entry2.mode, platform);
2275
2479
  }
2276
2480
 
2481
+ // host/service-log-delivery.ts
2482
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
2483
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
2484
+ setImmediate(flush);
2485
+ }, onDeliveryGap = () => void 0) {
2486
+ const pending = [];
2487
+ const highWaterMark = stream.writableHighWaterMark;
2488
+ const byteBudget = highWaterMark + highWaterMark;
2489
+ let pendingBytes = 0;
2490
+ let droppedLines = 0;
2491
+ let flushScheduled = false;
2492
+ let waitingForDrain = false;
2493
+ let closed = !stream.writable;
2494
+ function stop2() {
2495
+ if (closed) return;
2496
+ closed = true;
2497
+ pending.length = 0;
2498
+ pendingBytes = 0;
2499
+ stream.off("drain", onDrain);
2500
+ stream.off("close", onTerminal);
2501
+ stream.off("finish", onTerminal);
2502
+ stream.off("error", onError);
2503
+ }
2504
+ function onTerminal() {
2505
+ stop2();
2506
+ }
2507
+ function onError() {
2508
+ stop2();
2509
+ }
2510
+ function onDrain() {
2511
+ waitingForDrain = false;
2512
+ scheduleFlush();
2513
+ }
2514
+ function scheduleFlush() {
2515
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
2516
+ flushScheduled = true;
2517
+ let scheduling = true;
2518
+ let invokedSynchronously = false;
2519
+ try {
2520
+ schedule(() => {
2521
+ if (scheduling) {
2522
+ invokedSynchronously = true;
2523
+ return;
2524
+ }
2525
+ flushScheduled = false;
2526
+ flush();
2527
+ });
2528
+ } catch {
2529
+ flushScheduled = false;
2530
+ stop2();
2531
+ return;
2532
+ }
2533
+ scheduling = false;
2534
+ if (invokedSynchronously) {
2535
+ flushScheduled = false;
2536
+ stop2();
2537
+ }
2538
+ }
2539
+ function flush() {
2540
+ if (closed) return;
2541
+ if (!stream.writable) {
2542
+ stop2();
2543
+ return;
2544
+ }
2545
+ while (pending.length > 0) {
2546
+ if (stream.writableNeedDrain) {
2547
+ if (!waitingForDrain) {
2548
+ waitingForDrain = true;
2549
+ stream.once("drain", onDrain);
2550
+ }
2551
+ return;
2552
+ }
2553
+ const next = pending.shift();
2554
+ if (next === void 0) return;
2555
+ pendingBytes -= next.bytes;
2556
+ let accepted;
2557
+ try {
2558
+ accepted = stream.write(next.line);
2559
+ } catch {
2560
+ stop2();
2561
+ return;
2562
+ }
2563
+ if (!accepted) {
2564
+ waitingForDrain = true;
2565
+ stream.once("drain", onDrain);
2566
+ return;
2567
+ }
2568
+ }
2569
+ if (droppedLines > 0) {
2570
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
2571
+ `;
2572
+ droppedLines = 0;
2573
+ try {
2574
+ onDeliveryGap(line);
2575
+ } catch {
2576
+ }
2577
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
2578
+ pendingBytes += Buffer.byteLength(line, "utf8");
2579
+ flush();
2580
+ }
2581
+ }
2582
+ stream.on("close", onTerminal);
2583
+ stream.on("finish", onTerminal);
2584
+ stream.on("error", onError);
2585
+ return (line) => {
2586
+ if (closed) return;
2587
+ const bytes2 = Buffer.byteLength(line, "utf8");
2588
+ if (bytes2 > highWaterMark || stream.writableLength + pendingBytes + bytes2 > byteBudget) {
2589
+ droppedLines += 1;
2590
+ scheduleFlush();
2591
+ return;
2592
+ }
2593
+ pending.push({ line, bytes: bytes2 });
2594
+ pendingBytes += bytes2;
2595
+ scheduleFlush();
2596
+ };
2597
+ }
2598
+
2277
2599
  // host/service-log.ts
2278
2600
  var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
2279
2601
  var HOST_SERVICE_LOG_ARGUMENT = "--ceal-host-service-log";
@@ -2293,6 +2615,9 @@ function consumeHostServiceLogArgument(args, platform = process.platform) {
2293
2615
  if (indexes.length !== 1 || path === void 0 || !pathApi.isAbsolute(path) || pathApi.normalize(path) !== path) throw new HostServiceLogArgumentError();
2294
2616
  return { args: [...args.slice(0, index), ...args.slice(index + 2)], path };
2295
2617
  }
2618
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
2619
+ void persistHostServiceLogLine(line);
2620
+ });
2296
2621
  var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
2297
2622
  var HOST_SERVICE_LOG_CHECK_INTERVAL_MS = 6e4;
2298
2623
  function hostServiceLogPreviousPath(path) {
@@ -2320,7 +2645,7 @@ function boundHostServiceLog(environment = process.env) {
2320
2645
  ready.then(() => rotateHostServiceLog(path)).catch((error) => {
2321
2646
  if (reported) return;
2322
2647
  reported = true;
2323
- process.stderr.write(`[host-service-log] rotation_failed code=${errorCode2(error)}
2648
+ writeHostServiceLogLine(`[host-service-log] rotation_failed code=${errorCode2(error)}
2324
2649
  `);
2325
2650
  });
2326
2651
  };
@@ -2330,10 +2655,22 @@ function boundHostServiceLog(environment = process.env) {
2330
2655
  return () => clearInterval(timer);
2331
2656
  }
2332
2657
  function writeHostServiceLogLine(line, environment = process.env) {
2658
+ void persistHostServiceLogLine(line, environment);
2659
+ defaultHostServiceLogDelivery(line);
2660
+ }
2661
+ async function writeHostServiceCommandResult(schemaVersion, result2, sink) {
2662
+ const line = `${JSON.stringify({ schema_version: schemaVersion, ...result2 })}
2663
+ `;
2664
+ const serviceLine = `${JSON.stringify({ schema_version: schemaVersion, ok: result2.ok, ...!result2.ok ? { code: isHostOwnedFailureCode(result2.code) ? result2.code : "host_failure_unclassified" } : {} })}
2665
+ `;
2666
+ await persistHostServiceLogLine(serviceLine);
2667
+ sink(line);
2668
+ }
2669
+ async function persistHostServiceLogLine(line, environment = process.env) {
2333
2670
  if (process.platform !== "win32") return;
2334
2671
  const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
2335
2672
  if (path === void 0 || !win322.isAbsolute(path) || win322.normalize(path) !== path) return;
2336
- void appendHostServiceLogLine(path, line).catch(() => void 0);
2673
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
2337
2674
  }
2338
2675
  async function appendHostServiceLogLine(path, line) {
2339
2676
  if (!isAbsolute(path)) return;
@@ -2371,21 +2708,59 @@ function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allow
2371
2708
  return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
2372
2709
  }
2373
2710
 
2711
+ // host/unix-socket-path.ts
2712
+ var PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES = 103;
2713
+ var LINUX_UNIX_SOCKET_PATH_MAX_BYTES = 107;
2714
+ var HostUnixSocketPathError = class extends Error {
2715
+ code = "ipc_endpoint_too_long";
2716
+ role;
2717
+ bytes;
2718
+ maximum_bytes;
2719
+ constructor(role, bytes2, maximum_bytes) {
2720
+ super(`ipc_endpoint_too_long: Host IPC ${role} has ${bytes2} UTF-8 bytes; maximum is ${maximum_bytes}.`);
2721
+ this.name = "HostUnixSocketPathError";
2722
+ this.role = role;
2723
+ this.bytes = bytes2;
2724
+ this.maximum_bytes = maximum_bytes;
2725
+ }
2726
+ };
2727
+ function assertHostUnixSocketPath(endpoint, role, platform = process.platform) {
2728
+ if (platform === "win32") return;
2729
+ const maximum = platform === "linux" ? LINUX_UNIX_SOCKET_PATH_MAX_BYTES : PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES;
2730
+ const bytes2 = Buffer.byteLength(endpoint, "utf8");
2731
+ if (bytes2 > maximum) throw new HostUnixSocketPathError(role, bytes2, maximum);
2732
+ }
2733
+
2374
2734
  // host/runtime-source-paths.ts
2375
2735
  var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
2376
2736
  function hostSourceUuid(sourceRef) {
2377
2737
  return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
2378
2738
  }
2379
- function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform) {
2739
+ var DARWIN_UID_MAX = 4294967295;
2740
+ var MACOS_HOST_RELAY_IPC_ROOT_PREFIX = "/private/tmp/ceal-host-";
2741
+ function isMacosHostRelayIpcDirectory(path) {
2742
+ return path.startsWith(MACOS_HOST_RELAY_IPC_ROOT_PREFIX) && /^[0-9]+$/u.test(path.slice(MACOS_HOST_RELAY_IPC_ROOT_PREFIX.length));
2743
+ }
2744
+ function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
2745
+ if (!Number.isInteger(uid) || uid < 0 || uid > DARWIN_UID_MAX) throw new TypeError("Host runtime effective user identity is invalid.");
2746
+ return `${MACOS_HOST_RELAY_IPC_ROOT_PREFIX}${uid}`;
2747
+ }
2748
+ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
2380
2749
  const sourceId = hostSourceUuid(sourceRef);
2381
2750
  if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
2382
2751
  const path = platform === "win32" ? win324 : posix3;
2383
2752
  const sourcesRoot = path.join(stateRoot, "sources");
2384
2753
  const sourceRoot = path.join(sourcesRoot, sourceId);
2385
2754
  const runtimeRoot = path.join(stateRoot, "run");
2386
- const endpoint = platform === "win32" ? `\\\\.\\pipe\\ceal-host-${createHash3("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex").slice(0, 24)}` : path.join(runtimeRoot, `${sourceId}.sock`);
2755
+ const rootedEndpoint = path.join(runtimeRoot, `${sourceId}.sock`);
2756
+ const endpoint = projectRelayEndpoint(stateRoot, sourceRef, rootedEndpoint, platform, uid);
2387
2757
  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 };
2388
2758
  }
2759
+ function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
2760
+ if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
2761
+ const digest = createHash3("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
2762
+ return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest.slice(0, 24)}` : posix3.join(macosHostRelayIpcDirectory(uid), `${digest}.sock`);
2763
+ }
2389
2764
  function assertHostRelaySourcePaths(stateRoot, config, platform = process.platform) {
2390
2765
  const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
2391
2766
  if (config.state_root !== paths.relayRoot || platform !== "win32" && config.ipc_endpoint !== paths.endpoint) throw new TypeError("Host Relay state and IPC must belong to its configured source.");
@@ -2393,8 +2768,9 @@ function assertHostRelaySourcePaths(stateRoot, config, platform = process.platfo
2393
2768
  }
2394
2769
 
2395
2770
  // host/relay/src/host-relay-runtime.ts
2771
+ import { randomUUID } from "node:crypto";
2396
2772
  import { constants as constants4 } from "node:fs";
2397
- import { dirname as dirname7, join as join6 } from "node:path";
2773
+ import { dirname as dirname8, join as join7 } from "node:path";
2398
2774
 
2399
2775
  // host/abortable-wait.ts
2400
2776
  function waitForAbort(signal, milliseconds) {
@@ -2647,7 +3023,7 @@ function exactOptional(value, required, optional) {
2647
3023
 
2648
3024
  // host/relay/src/relay-admission-store.ts
2649
3025
  import { readFile as readFile2 } from "node:fs/promises";
2650
- import { join as join3 } from "node:path";
3026
+ import { join as join4 } from "node:path";
2651
3027
 
2652
3028
  // host/relay/src/durable-atomic-replacement.ts
2653
3029
  import { lstat as lstat2, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
@@ -2783,7 +3159,7 @@ function errorCode3(error) {
2783
3159
  // host/relay/src/relay-quarantine-store.ts
2784
3160
  import { createHash as createHash5 } from "node:crypto";
2785
3161
  import { readFile } from "node:fs/promises";
2786
- import { join as join2 } from "node:path";
3162
+ import { join as join3 } from "node:path";
2787
3163
  var RELAY_QUARANTINE_SCHEMA = "ceal.host_relay_quarantine_state.v1";
2788
3164
  var RELAY_QUARANTINE_MAX_RECORDS = 512;
2789
3165
  var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
@@ -2837,14 +3213,14 @@ var RelayQuarantineStore = class {
2837
3213
  const records = state.producers[producerId];
2838
3214
  records.push(record6);
2839
3215
  while (records.length > this.maxRecords || totalBytes(records) > this.maxBytes) records.shift();
2840
- await durableAtomicReplace(join2(this.root, "quarantine.json"), JSON.stringify(state));
3216
+ await durableAtomicReplace(join3(this.root, "quarantine.json"), JSON.stringify(state));
2841
3217
  });
2842
3218
  this.tail = run.then(() => void 0, () => void 0);
2843
3219
  await run;
2844
3220
  }
2845
3221
  async readState() {
2846
3222
  try {
2847
- return decodeState(JSON.parse(await readFile(join2(this.root, "quarantine.json"), "utf8")));
3223
+ return decodeState(JSON.parse(await readFile(join3(this.root, "quarantine.json"), "utf8")));
2848
3224
  } catch (error) {
2849
3225
  if (errorCode4(error) === "ENOENT") return emptyState();
2850
3226
  throw error;
@@ -2909,7 +3285,7 @@ var RelayAdmissionStore = class {
2909
3285
  quarantine;
2910
3286
  limits;
2911
3287
  faultHooks;
2912
- constructor(root, limits = DEFAULT_LIMITS, faultHooks = {}, quarantine = new RelayQuarantineStore(join3(root, "quarantine"))) {
3288
+ constructor(root, limits = DEFAULT_LIMITS, faultHooks = {}, quarantine = new RelayQuarantineStore(join4(root, "quarantine"))) {
2913
3289
  this.root = root;
2914
3290
  this.quarantine = quarantine;
2915
3291
  this.limits = limits;
@@ -3021,14 +3397,14 @@ var RelayAdmissionStore = class {
3021
3397
  }
3022
3398
  async read() {
3023
3399
  try {
3024
- return decodeState2(JSON.parse(await readFile2(join3(this.root, "admission.json"), "utf8")));
3400
+ return decodeState2(JSON.parse(await readFile2(join4(this.root, "admission.json"), "utf8")));
3025
3401
  } catch (error) {
3026
3402
  if (errorCode5(error) === "ENOENT") return { schema_version: "ceal.host_relay_admission_state.v1", installations: {}, entries: [] };
3027
3403
  throw error;
3028
3404
  }
3029
3405
  }
3030
3406
  async write(state) {
3031
- await durableAtomicReplace(join3(this.root, "admission.json"), JSON.stringify(state));
3407
+ await durableAtomicReplace(join4(this.root, "admission.json"), JSON.stringify(state));
3032
3408
  }
3033
3409
  };
3034
3410
  function installationKey(frame) {
@@ -3171,7 +3547,7 @@ function poisonSequenceInRange(entryValue, installation2) {
3171
3547
  import { createHmac, randomBytes } from "node:crypto";
3172
3548
  import { constants as constants2 } from "node:fs";
3173
3549
  import { link, unlink as unlink2 } from "node:fs/promises";
3174
- import { dirname as dirname4, join as join4 } from "node:path";
3550
+ import { dirname as dirname4, join as join5 } from "node:path";
3175
3551
  var RELAY_PIPE_HANDSHAKE_TIMEOUT_MS = 5e3;
3176
3552
  var RELAY_PIPE_KEY_BYTES = 32;
3177
3553
  var RELAY_PIPE_KEY_FILENAME = "relay-pipe.key";
@@ -3191,7 +3567,7 @@ var RelayPipeHandshakeError = class extends Error {
3191
3567
  }
3192
3568
  };
3193
3569
  function relayPipeKeyPath(relayStateRoot) {
3194
- return join4(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
3570
+ return join5(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
3195
3571
  }
3196
3572
  async function loadRelayPipeKey(relayStateRoot, platform = process.platform, custody = {}) {
3197
3573
  const path = relayPipeKeyPath(relayStateRoot);
@@ -3201,9 +3577,10 @@ async function loadRelayPipeKey(relayStateRoot, platform = process.platform, cus
3201
3577
  return await createPosixRelayPipeKey(path, platform, custody);
3202
3578
  }
3203
3579
  async function loadWindowsRelayPipeKey(path, custody) {
3204
- const existing = await readRelayPipeKey(path, "win32", custody);
3205
- if (existing !== null) return existing;
3206
3580
  try {
3581
+ await ensurePrivateDirectoryWithSecurefs(dirname4(path), custody);
3582
+ const existing = await readRelayPipeKey(path, "win32", custody);
3583
+ if (existing !== null) return existing;
3207
3584
  await createRandomPrivateFileWithSecurefs(path, RELAY_PIPE_KEY_BYTES, custody);
3208
3585
  } catch (error) {
3209
3586
  if (errorCode6(error) === "EEXIST") return await readWinnerPipeKey(path, "win32", custody);
@@ -3428,24 +3805,7 @@ function errorCode6(error) {
3428
3805
  return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3429
3806
  }
3430
3807
 
3431
- // host/relay/src/relay-ipc.ts
3432
- import { chmod, lstat as lstat3, rename as rename2, unlink as unlink3 } from "node:fs/promises";
3433
- import { createConnection, createServer } from "node:net";
3434
- import { dirname as dirname5, join as join5 } from "node:path";
3435
- var HOST_RELAY_IPC_RESPONSE_SCHEMA = "ceal.host_relay_admission.v1";
3436
- var HOST_RELAY_INVOCATION_CONTEXT_QUERY_SCHEMA = "ceal.host_relay_invocation_context_query.v2";
3437
- var HOST_RELAY_INVOCATION_CONTEXT_RESULT_SCHEMA = "ceal.host_relay_invocation_context_result.v2";
3438
- var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
3439
- var HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
3440
- "permission_denied",
3441
- "socket_missing",
3442
- "connection_refused",
3443
- "closed_early",
3444
- "response_invalid",
3445
- "timed_out",
3446
- "cancelled",
3447
- "unavailable"
3448
- ]);
3808
+ // host/relay/src/relay-ipc-error.ts
3449
3809
  var HostRelayIpcError = class extends Error {
3450
3810
  code;
3451
3811
  /** Set only when the client-side socket exchange itself failed. */
@@ -3456,17 +3816,165 @@ var HostRelayIpcError = class extends Error {
3456
3816
  this.failure = failure;
3457
3817
  }
3458
3818
  };
3819
+ function relayIpcErrorCode(error) {
3820
+ return error !== null && typeof error === "object" && !Array.isArray(error) && "code" in error && typeof error.code === "string" ? error.code : null;
3821
+ }
3822
+
3823
+ // host/relay/src/relay-endpoint-ownership.ts
3824
+ import { lstat as lstat3, mkdir as mkdir3, unlink as unlink3 } from "node:fs/promises";
3825
+ import { createConnection } from "node:net";
3826
+ import { dirname as dirname5 } from "node:path";
3827
+ var relayEndpointLocks = /* @__PURE__ */ new Map();
3828
+ function withRelayEndpointLock(endpoint, run) {
3829
+ const prior = relayEndpointLocks.get(endpoint) ?? Promise.resolve();
3830
+ let release;
3831
+ const gate = new Promise((resolve) => {
3832
+ release = resolve;
3833
+ });
3834
+ const tail = prior.then(() => gate);
3835
+ relayEndpointLocks.set(endpoint, tail);
3836
+ return prior.then(run).finally(() => {
3837
+ release?.();
3838
+ if (relayEndpointLocks.get(endpoint) === tail) relayEndpointLocks.delete(endpoint);
3839
+ });
3840
+ }
3841
+ function currentUid(fallback) {
3842
+ return typeof process.geteuid === "function" ? process.geteuid() : fallback;
3843
+ }
3844
+ async function assertTrustedEndpointParent(endpoint, createManagedParent = false) {
3845
+ const parent = dirname5(endpoint);
3846
+ if (process.platform === "darwin" && isMacosHostRelayIpcDirectory(parent)) {
3847
+ if (parent !== macosHostRelayIpcDirectory()) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC directory does not belong to the effective user; leaving it untouched.");
3848
+ await assertMacosIpcSystemAnchor();
3849
+ if (createManagedParent) {
3850
+ try {
3851
+ await mkdir3(parent, { mode: 448 });
3852
+ } catch (error) {
3853
+ if (relayIpcErrorCode(error) !== "EEXIST") throw endpointInspectionError(error, "Host Relay IPC private directory could not be created.");
3854
+ }
3855
+ }
3856
+ }
3857
+ await assertPrivateEndpointDirectory(parent);
3858
+ }
3859
+ async function assertPrivateEndpointDirectory(parent) {
3860
+ let stats;
3861
+ try {
3862
+ stats = await lstat3(parent);
3863
+ } catch (error) {
3864
+ throw endpointInspectionError(error, "Host Relay IPC endpoint parent is unavailable; leaving it untouched.");
3865
+ }
3866
+ if (!stats.isDirectory() || stats.uid !== currentUid(stats.uid) || (stats.mode & 63) !== 0) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint parent is not an owner-private directory; leaving it untouched.");
3867
+ }
3868
+ async function assertMacosIpcSystemAnchor() {
3869
+ for (const path of ["/", "/private", "/private/tmp"]) {
3870
+ const stats = await lstat3(path);
3871
+ const permissionsSafe = path === "/private/tmp" ? (stats.mode & 512) !== 0 : (stats.mode & 18) === 0;
3872
+ if (!stats.isDirectory() || stats.uid !== 0 || !permissionsSafe) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC system anchor is not a root-owned physical directory with safe permissions; leaving it untouched.");
3873
+ }
3874
+ }
3875
+ async function assertTrustedEndpointSocket(endpoint, allowMissing = false) {
3876
+ assertHostUnixSocketPath(endpoint, "endpoint");
3877
+ await assertTrustedEndpointParent(endpoint);
3878
+ const observed = await readEndpointStats(endpoint);
3879
+ if (observed === null) {
3880
+ if (allowMissing) return null;
3881
+ throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC is unavailable: socket_missing.", "socket_missing");
3882
+ }
3883
+ if (!observed.isSocket()) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint is not a socket; leaving it untouched.");
3884
+ if (observed.uid !== currentUid(observed.uid)) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint is not owned by the current uid; leaving it untouched.");
3885
+ return observed;
3886
+ }
3887
+ function endpointInspectionError(error, message) {
3888
+ const code = relayIpcErrorCode(error);
3889
+ const failure = code === "ENOENT" ? "socket_missing" : code === "EACCES" || code === "EPERM" ? "permission_denied" : "unavailable";
3890
+ return new HostRelayIpcError("relay_unavailable", message, failure);
3891
+ }
3892
+ var HOST_RELAY_ENDPOINT_PROBE_TIMEOUT_MS = 1e3;
3893
+ async function probeRelayEndpoint(endpoint) {
3894
+ if (await assertTrustedEndpointSocket(endpoint, true) === null) return "missing";
3895
+ return new Promise((resolve) => {
3896
+ let settled = false;
3897
+ const socket = createConnection(endpoint);
3898
+ const finish = (outcome) => {
3899
+ if (settled) return;
3900
+ settled = true;
3901
+ clearTimeout(timer);
3902
+ socket.destroy();
3903
+ resolve(outcome);
3904
+ };
3905
+ const timer = setTimeout(() => finish("ambiguous"), HOST_RELAY_ENDPOINT_PROBE_TIMEOUT_MS);
3906
+ timer.unref?.();
3907
+ socket.once("connect", () => finish("live"));
3908
+ socket.once("error", (error) => {
3909
+ const code = relayIpcErrorCode(error);
3910
+ if (code === "ECONNREFUSED") finish("stale");
3911
+ else if (code === "ENOENT") finish("missing");
3912
+ else finish("ambiguous");
3913
+ });
3914
+ });
3915
+ }
3916
+ async function removeStaleRelayEndpoint(endpoint, testHooks) {
3917
+ const observed = await assertTrustedEndpointSocket(endpoint, true);
3918
+ if (observed === null) return;
3919
+ const captured = { uid: observed.uid, dev: observed.dev, ino: observed.ino };
3920
+ await requireStaleEndpoint(endpoint);
3921
+ await testHooks?.beforeRemoveStaleEndpoint?.(endpoint);
3922
+ const current = await readEndpointStats(endpoint);
3923
+ if (current === null) return;
3924
+ requireSameEndpointIdentity(current, captured, "Host Relay IPC endpoint changed before cleanup; leaving it untouched.");
3925
+ await unlinkRelayEndpoint(endpoint);
3926
+ }
3927
+ async function requireStaleEndpoint(endpoint) {
3928
+ switch (await probeRelayEndpoint(endpoint)) {
3929
+ case "missing":
3930
+ case "stale":
3931
+ return;
3932
+ case "live":
3933
+ throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint is already served by a live Relay; leaving it untouched.");
3934
+ case "ambiguous":
3935
+ throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint liveness is ambiguous; leaving it untouched.");
3936
+ }
3937
+ }
3938
+ async function readEndpointStats(endpoint) {
3939
+ try {
3940
+ return await lstat3(endpoint);
3941
+ } catch (error) {
3942
+ if (relayIpcErrorCode(error) === "ENOENT") return null;
3943
+ throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint identity is ambiguous; leaving it untouched.");
3944
+ }
3945
+ }
3946
+ function requireSameEndpointIdentity(current, owned, message) {
3947
+ if (!current.isSocket() || current.uid !== owned.uid || current.dev !== owned.dev || current.ino !== owned.ino) throw new HostRelayIpcError("relay_unavailable", message);
3948
+ }
3949
+ async function unlinkRelayEndpoint(endpoint) {
3950
+ try {
3951
+ await unlink3(endpoint);
3952
+ } catch (error) {
3953
+ if (relayIpcErrorCode(error) !== "ENOENT") throw error;
3954
+ }
3955
+ }
3956
+
3957
+ // host/relay/src/relay-ipc.ts
3958
+ import { chmod, lstat as lstat4, rename as rename2, unlink as unlink4 } from "node:fs/promises";
3959
+ import { createConnection as createConnection2, createServer } from "node:net";
3960
+ import { dirname as dirname6, join as join6 } from "node:path";
3961
+ var HOST_RELAY_IPC_RESPONSE_SCHEMA = "ceal.host_relay_admission.v1";
3962
+ var HOST_RELAY_INVOCATION_CONTEXT_QUERY_SCHEMA = "ceal.host_relay_invocation_context_query.v2";
3963
+ var HOST_RELAY_INVOCATION_CONTEXT_RESULT_SCHEMA = "ceal.host_relay_invocation_context_result.v3";
3964
+ var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
3459
3965
  async function startHostRelayIpcServer(options) {
3966
+ assertHostUnixSocketPath(options.endpoint, "endpoint");
3460
3967
  return withRelayEndpointLock(options.endpoint, async () => {
3461
3968
  const lastSeenRequestBySession = /* @__PURE__ */ new Map();
3462
3969
  if (process.platform === "win32") return startWindowsPipeServer(options, lastSeenRequestBySession);
3463
- await assertTrustedEndpointParent(options.endpoint);
3970
+ const staging = stagingRelayEndpoint(options.endpoint);
3971
+ assertHostUnixSocketPath(staging, "staging");
3972
+ await assertTrustedEndpointParent(options.endpoint, true);
3464
3973
  await removeStaleRelayEndpoint(options.endpoint, options.testHooks);
3465
3974
  const active = /* @__PURE__ */ new Map();
3466
3975
  const sockets = /* @__PURE__ */ new Set();
3467
3976
  const quarantine = options.quarantine ?? options.admission.quarantine;
3468
3977
  const server = createServer((socket) => serveSocket(socket, options, quarantine, active, sockets, Buffer.alloc(0), lastSeenRequestBySession));
3469
- const staging = stagingRelayEndpoint(options.endpoint);
3470
3978
  await listenStagingRelayEndpoint(server, sockets, staging);
3471
3979
  let owned;
3472
3980
  try {
@@ -3528,7 +4036,7 @@ async function resolveWindowsPipeListenOutcome(endpoint, error, probe = windowsP
3528
4036
  return mapWindowsPipeListenError(endpoint, error);
3529
4037
  }
3530
4038
  function pipeNameHeldError(error) {
3531
- const code = errorCode7(error);
4039
+ const code = relayIpcErrorCode(error);
3532
4040
  return code === "EADDRINUSE" || code === "EACCES";
3533
4041
  }
3534
4042
  function windowsPipeHolderIsLive(endpoint) {
@@ -3537,7 +4045,7 @@ function windowsPipeHolderIsLive(endpoint) {
3537
4045
  probe.destroy();
3538
4046
  resolve(false);
3539
4047
  }, RELAY_PIPE_HANDSHAKE_TIMEOUT_MS);
3540
- const probe = createConnection(endpoint);
4048
+ const probe = createConnection2(endpoint);
3541
4049
  probe.once("connect", () => {
3542
4050
  clearTimeout(timer);
3543
4051
  probe.destroy();
@@ -3551,7 +4059,7 @@ function windowsPipeHolderIsLive(endpoint) {
3551
4059
  });
3552
4060
  }
3553
4061
  function mapWindowsPipeListenError(endpoint, error) {
3554
- const code = errorCode7(error);
4062
+ const code = relayIpcErrorCode(error);
3555
4063
  if (pipeNameHeldError(error)) {
3556
4064
  return new HostRelayIpcError("relay_unavailable", `relay pipe name held by another process: the Host Relay pipe name ${endpoint} is already served (error ${code}); stop the process holding it, then restart the Host Relay.`);
3557
4065
  }
@@ -3757,111 +4265,19 @@ function listen(server, endpoint) {
3757
4265
  async function closeServer(server, sockets, endpoint) {
3758
4266
  for (const socket of sockets) socket.destroy();
3759
4267
  await new Promise((resolve) => server.close(() => resolve()));
3760
- if (process.platform !== "win32") await unlink3(endpoint).catch(() => void 0);
3761
- }
3762
- var relayEndpointLocks = /* @__PURE__ */ new Map();
3763
- function withRelayEndpointLock(endpoint, run) {
3764
- const prior = relayEndpointLocks.get(endpoint) ?? Promise.resolve();
3765
- let release;
3766
- const gate = new Promise((resolve) => {
3767
- release = resolve;
3768
- });
3769
- const tail = prior.then(() => gate);
3770
- relayEndpointLocks.set(endpoint, tail);
3771
- return prior.then(run).finally(() => {
3772
- release?.();
3773
- if (relayEndpointLocks.get(endpoint) === tail) relayEndpointLocks.delete(endpoint);
3774
- });
3775
- }
3776
- function currentUid(fallback) {
3777
- return typeof process.geteuid === "function" ? process.geteuid() : fallback;
3778
- }
3779
- async function assertTrustedEndpointParent(endpoint) {
3780
- const parent = dirname5(endpoint);
3781
- let stats;
3782
- try {
3783
- stats = await lstat3(parent);
3784
- } catch {
3785
- throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint parent is unavailable; leaving it untouched.");
3786
- }
3787
- if (!stats.isDirectory() || stats.uid !== currentUid(stats.uid) || (stats.mode & 63) !== 0) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint parent is not an owner-private directory; leaving it untouched.");
3788
- }
3789
- var HOST_RELAY_ENDPOINT_PROBE_TIMEOUT_MS = 1e3;
3790
- function probeRelayEndpoint(endpoint) {
3791
- return new Promise((resolve) => {
3792
- let settled = false;
3793
- const socket = createConnection(endpoint);
3794
- const finish = (outcome) => {
3795
- if (settled) return;
3796
- settled = true;
3797
- clearTimeout(timer);
3798
- socket.destroy();
3799
- resolve(outcome);
3800
- };
3801
- const timer = setTimeout(() => finish("ambiguous"), HOST_RELAY_ENDPOINT_PROBE_TIMEOUT_MS);
3802
- timer.unref?.();
3803
- socket.once("connect", () => finish("live"));
3804
- socket.once("error", (error) => {
3805
- const code = errorCode7(error);
3806
- if (code === "ECONNREFUSED") finish("stale");
3807
- else if (code === "ENOENT") finish("missing");
3808
- else finish("ambiguous");
3809
- });
3810
- });
3811
- }
3812
- async function removeStaleRelayEndpoint(endpoint, testHooks) {
3813
- const observed = await readEndpointStats(endpoint);
3814
- if (observed === null) return;
3815
- if (!observed.isSocket()) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint is already present and is not a socket; leaving it untouched.");
3816
- if (observed.uid !== currentUid(observed.uid)) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint is not owned by the current uid; leaving it untouched.");
3817
- const captured = { uid: observed.uid, dev: observed.dev, ino: observed.ino };
3818
- await requireStaleEndpoint(endpoint);
3819
- await testHooks?.beforeRemoveStaleEndpoint?.(endpoint);
3820
- const current = await readEndpointStats(endpoint);
3821
- if (current === null) return;
3822
- requireSameEndpointIdentity(current, captured, "Host Relay IPC endpoint changed before cleanup; leaving it untouched.");
3823
- await unlinkRelayEndpoint(endpoint);
3824
- }
3825
- async function requireStaleEndpoint(endpoint) {
3826
- switch (await probeRelayEndpoint(endpoint)) {
3827
- case "missing":
3828
- case "stale":
3829
- return;
3830
- case "live":
3831
- throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint is already served by a live Relay; leaving it untouched.");
3832
- case "ambiguous":
3833
- throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint liveness is ambiguous; leaving it untouched.");
3834
- }
3835
- }
3836
- async function readEndpointStats(endpoint) {
3837
- try {
3838
- return await lstat3(endpoint);
3839
- } catch (error) {
3840
- if (errorCode7(error) === "ENOENT") return null;
3841
- throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint identity is ambiguous; leaving it untouched.");
3842
- }
3843
- }
3844
- function requireSameEndpointIdentity(current, owned, message) {
3845
- if (!current.isSocket() || current.uid !== owned.uid || current.dev !== owned.dev || current.ino !== owned.ino) throw new HostRelayIpcError("relay_unavailable", message);
3846
- }
3847
- async function unlinkRelayEndpoint(endpoint) {
3848
- try {
3849
- await unlink3(endpoint);
3850
- } catch (error) {
3851
- if (errorCode7(error) !== "ENOENT") throw error;
3852
- }
4268
+ if (process.platform !== "win32") await unlink4(endpoint).catch(() => void 0);
3853
4269
  }
3854
4270
  var relayStagingSequence = 0;
3855
4271
  function stagingRelayEndpoint(canonical) {
3856
- const parent = dirname5(canonical);
4272
+ const parent = dirname6(canonical);
3857
4273
  const pid = process.pid.toString(36);
3858
4274
  const sequence = (relayStagingSequence++ % (36 * 36)).toString(36);
3859
- return join5(parent, `.r${pid}${sequence}`);
4275
+ return join6(parent, `.r${pid}${sequence}`);
3860
4276
  }
3861
4277
  async function readStagingRelayEndpointIdentity(staging) {
3862
4278
  let created;
3863
4279
  try {
3864
- created = await lstat3(staging);
4280
+ created = await lstat4(staging);
3865
4281
  } catch {
3866
4282
  throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint is unavailable after listen; leaving it untouched.");
3867
4283
  }
@@ -3913,13 +4329,10 @@ async function abandonRelayServer(server, sockets) {
3913
4329
  server.close(() => resolve());
3914
4330
  });
3915
4331
  }
3916
- function errorCode7(error) {
3917
- return record3(error) && typeof error.code === "string" ? error.code : null;
3918
- }
3919
4332
 
3920
4333
  // host/relay/src/host-registration-state.ts
3921
4334
  import { constants as constants3 } from "node:fs";
3922
- import { dirname as dirname6 } from "node:path";
4335
+ import { dirname as dirname7 } from "node:path";
3923
4336
  var HOST_REGISTRATION_STATE_SCHEMA = "ceal.host_registration_state.v1";
3924
4337
  var HOST_REGISTRATION_STATE_KEYS = Object.freeze([
3925
4338
  "credential_generation",
@@ -3939,7 +4352,7 @@ var HostRegistrationStateError = class extends Error {
3939
4352
  async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
3940
4353
  let raw;
3941
4354
  try {
3942
- await assertPrivateRegistrationDirectory(dirname6(path), platform, custody);
4355
+ await assertPrivateRegistrationDirectory(dirname7(path), platform, custody);
3943
4356
  raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
3944
4357
  } catch (error) {
3945
4358
  throw registrationReadError(error);
@@ -4047,7 +4460,7 @@ async function readHostRelayConfig(path, platform = process.platform, custody =
4047
4460
  if (!isAbsoluteNormalizedNonRootPath(path, process.platform, true)) throw new HostRelayConfigError("invalid_config_path", `invalid_config_path: Host Relay config path is invalid: ${refusalFact("config_path", path, "absolute, normalized, and non-root")}.`);
4048
4461
  let handle;
4049
4462
  try {
4050
- await assertPrivateRelayConfigDirectory(dirname7(path), platform, custody);
4463
+ await assertPrivateRelayConfigDirectory(dirname8(path), platform, custody);
4051
4464
  let text;
4052
4465
  if (platform === "win32") {
4053
4466
  const bytes2 = await readPrivateFileWithSecurefs(path, HOST_RELAY_CONFIG_MAX_BYTES, custody);
@@ -4070,7 +4483,6 @@ async function readHostRelayConfig(path, platform = process.platform, custody =
4070
4483
  }
4071
4484
  const decoded = decodeHostRelayConfig(value);
4072
4485
  const config = resolveRelayIpcEndpoint(decoded);
4073
- validateHostRelaySourcePaths(config);
4074
4486
  return config;
4075
4487
  } catch (error) {
4076
4488
  throw relayConfigReadError(error);
@@ -4105,13 +4517,9 @@ async function assertPrivateRelayConfigDirectory(path, platform, custody) {
4105
4517
  }
4106
4518
  }
4107
4519
  function resolveRelayIpcEndpoint(decoded) {
4108
- if (process.platform !== "win32") return decoded;
4109
- const endpoint = assertHostRelaySourcePaths(dirname7(decoded.registration_state_file), decoded);
4110
- return endpoint === decoded.ipc_endpoint ? decoded : { ...decoded, ipc_endpoint: endpoint };
4111
- }
4112
- function validateHostRelaySourcePaths(config) {
4113
4520
  try {
4114
- assertHostRelaySourcePaths(dirname7(config.registration_state_file), config);
4521
+ const endpoint = assertHostRelaySourcePaths(dirname8(decoded.registration_state_file), decoded);
4522
+ return endpoint === decoded.ipc_endpoint ? decoded : { ...decoded, ipc_endpoint: endpoint };
4115
4523
  } catch (error) {
4116
4524
  throw new HostRelayConfigError("invalid_config", error instanceof Error ? error.message : "Host Relay source tuple is invalid.");
4117
4525
  }
@@ -4158,21 +4566,52 @@ function validConfigRuntime(value, platform) {
4158
4566
  return isAbsoluteNormalizedNonRootPath(value.state_root, platform, true) && (platform === "win32" || isAbsoluteNormalizedNonRootPath(value.ipc_endpoint, platform, true)) && boundedInteger(value.drain_interval_ms, 50, 3e4, true);
4159
4567
  }
4160
4568
  var HOST_RELAY_INVOCATION_MINT_LOG_TAG = "[host-relay-invocation-mint]";
4161
- function formatHostRelayInvocationMintLine(result2) {
4162
- return `${HOST_RELAY_INVOCATION_MINT_LOG_TAG} outcome=${result2.status === "ready" ? "completed" : "failed"}${result2.status === "refused" ? ` reason=${result2.reason}` : ""}`;
4569
+ var HOST_RELAY_INVOCATION_MINT_LOG_LINE = new RegExp(String.raw`^\[host-relay-invocation-mint\] timestamp=(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[.]\d{3}Z) outcome=(completed|failed) stage=(registration|gateway_request|gateway_response) latency_ms=(\d{1,16})(?: gateway_origin_host=([A-Za-z0-9.:[\]-]{1,255}))?(?: client_exchange_ref=(${CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE.slice(1, -1)}))?(?: gateway_http_request_ref=(${CEAL_HTTP_GATEWAY_REQUEST_REF_PATTERN_SOURCE.slice(1, -1)}))?(?: reason=([a-z][a-z0-9_]{0,63}))?(?: gateway_status=([1-5][0-9]{2}))?$`, "u");
4570
+ var HOST_RELAY_INVOCATION_MINT_REASON_PATTERN = /^[a-z][a-z0-9_]{0,63}$/u;
4571
+ var HOST_RELAY_INVOCATION_MINT_ORIGIN_HOST_PATTERN = /^[A-Za-z0-9.:[\]-]{1,255}$/u;
4572
+ var HOST_RELAY_CLIENT_EXCHANGE_REF_PATTERN = new RegExp(CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE, "u");
4573
+ var HOST_RELAY_GATEWAY_HTTP_REQUEST_REF_PATTERN = new RegExp(CEAL_HTTP_GATEWAY_REQUEST_REF_PATTERN_SOURCE, "u");
4574
+ function formatHostRelayInvocationMintLine(result2, context) {
4575
+ const gatewayStatus = gatewayMintStatus(result2);
4576
+ const originHost = boundedOriginHost(context.gateway_origin_host);
4577
+ const clientExchangeRef = boundedDiagnosticRef(context.client_exchange_ref, HOST_RELAY_CLIENT_EXCHANGE_REF_PATTERN);
4578
+ const gatewayHttpRequestRef = boundedDiagnosticRef(context.gateway_http_request_ref, HOST_RELAY_GATEWAY_HTTP_REQUEST_REF_PATTERN);
4579
+ const latency = boundedLatency(context.latency_ms);
4580
+ const reason = relayRefusalReason(result2);
4581
+ const outcome = result2.status === "ready" ? "completed" : "failed";
4582
+ return `${HOST_RELAY_INVOCATION_MINT_LOG_TAG} timestamp=${context.timestamp} outcome=${outcome} stage=${context.stage} latency_ms=${latency}${optionalField("gateway_origin_host", originHost)}${optionalField("client_exchange_ref", clientExchangeRef)}${optionalField("gateway_http_request_ref", gatewayHttpRequestRef)}${optionalField("reason", reason)}${optionalField("gateway_status", gatewayStatus)}`;
4583
+ }
4584
+ function gatewayMintStatus(result2) {
4585
+ if (result2.status !== "refused" || result2.reason !== "gateway_refused") return void 0;
4586
+ return result2.gateway_status;
4587
+ }
4588
+ function boundedOriginHost(value) {
4589
+ if (value === void 0 || !HOST_RELAY_INVOCATION_MINT_ORIGIN_HOST_PATTERN.test(value)) return void 0;
4590
+ return value;
4591
+ }
4592
+ function boundedDiagnosticRef(value, pattern) {
4593
+ if (value === void 0 || !pattern.test(value)) return void 0;
4594
+ return value;
4595
+ }
4596
+ function boundedLatency(value) {
4597
+ if (!Number.isSafeInteger(value) || value < 0) return 0;
4598
+ return value;
4599
+ }
4600
+ function relayRefusalReason(result2) {
4601
+ if (result2.status !== "refused") return void 0;
4602
+ return HOST_RELAY_INVOCATION_MINT_REASON_PATTERN.test(result2.reason) ? result2.reason : "host_refusal_invalid";
4603
+ }
4604
+ function optionalField(name, value) {
4605
+ return value === void 0 ? "" : ` ${name}=${value}`;
4163
4606
  }
4164
4607
  function reportInvocationMintLine(line) {
4165
- try {
4166
- process.stderr.write(line);
4167
- } catch {
4168
- }
4169
4608
  writeHostServiceLogLine(line);
4170
4609
  }
4171
4610
  async function serveHostRelay(config, signal, dependencies = {}) {
4172
- const admission = new RelayAdmissionStore(join6(config.state_root, "admission"));
4611
+ const admission = new RelayAdmissionStore(join7(config.state_root, "admission"));
4173
4612
  let server;
4174
4613
  try {
4175
- const pipeKey = process.platform === "win32" ? await loadRelayPipeKey(config.state_root) : void 0;
4614
+ const pipeKey = process.platform === "win32" ? await loadRelayPipeKey(config.state_root, process.platform, dependencies.custody) : void 0;
4176
4615
  server = await startHostRelayRuntimeIpc(config, admission, dependencies, pipeKey);
4177
4616
  await waitForRelayShutdown(config, signal, dependencies);
4178
4617
  } catch (error) {
@@ -4191,38 +4630,59 @@ async function startHostRelayRuntimeIpc(config, admission, dependencies, pipeKey
4191
4630
  admission,
4192
4631
  ...pipeKey === void 0 ? {} : { pipeKey },
4193
4632
  mintInvocationContext: async (input, signal) => {
4633
+ const started = performance.now();
4634
+ const observation = { stage: "registration" };
4635
+ const logResult = (result3) => {
4636
+ const context = { timestamp: (/* @__PURE__ */ new Date()).toISOString(), stage: observation.stage, latency_ms: Math.max(0, Math.round(performance.now() - started)), ...observation.gateway_origin_host === void 0 ? {} : { gateway_origin_host: observation.gateway_origin_host }, ...observation.client_exchange_ref === void 0 ? {} : { client_exchange_ref: observation.client_exchange_ref }, ...observation.gateway_http_request_ref === void 0 ? {} : { gateway_http_request_ref: observation.gateway_http_request_ref } };
4637
+ (dependencies.logInvocationMint ?? reportInvocationMintLine)(`${formatHostRelayInvocationMintLine(result3, context)}
4638
+ `);
4639
+ };
4194
4640
  let result2;
4195
4641
  try {
4196
- result2 = await mintInvocationContextAtGateway(config, input, signal, dependencies.fetch ?? fetch);
4642
+ result2 = await mintInvocationContextAtGateway(config, input, signal, dependencies.fetch ?? fetch, observation, dependencies.custody);
4197
4643
  } catch (error) {
4198
- const refused = { schema_version: "ceal.host_relay_invocation_context_result.v2", status: "refused", reason: "gateway_unavailable" };
4199
- (dependencies.logInvocationMint ?? reportInvocationMintLine)(`${formatHostRelayInvocationMintLine(refused)}
4200
- `);
4644
+ const refused = { schema_version: HOST_RELAY_INVOCATION_CONTEXT_RESULT_SCHEMA, status: "refused", reason: "gateway_unavailable" };
4645
+ logResult(refused);
4201
4646
  throw error;
4202
4647
  }
4203
- (dependencies.logInvocationMint ?? reportInvocationMintLine)(`${formatHostRelayInvocationMintLine(result2)}
4204
- `);
4648
+ logResult(result2);
4205
4649
  return result2;
4206
4650
  }
4207
4651
  });
4208
4652
  }
4209
- async function mintInvocationContextAtGateway(config, input, signal, fetchGateway) {
4653
+ async function mintInvocationContextAtGateway(config, input, signal, fetchGateway, observation, custody = {}) {
4654
+ let registration;
4655
+ try {
4656
+ registration = await readHostRegistrationAuthority(config.registration_state_file, config.host_source_ref, process.platform, custody);
4657
+ } catch {
4658
+ return mintRefusal("relay_unavailable");
4659
+ }
4210
4660
  try {
4211
- const registration = await readHostRegistrationAuthority(config.registration_state_file, config.host_source_ref);
4212
- return gatewayMintPost(registration, input, signal, fetchGateway);
4661
+ observation.gateway_origin_host = new URL(registration.gateway_request_origin).hostname;
4662
+ observation.stage = "gateway_request";
4663
+ const result2 = await gatewayMintPost(registration, input, signal, fetchGateway, observation);
4664
+ observation.stage = "gateway_response";
4665
+ return result2;
4213
4666
  } catch (error) {
4214
4667
  return gatewayMintFailure(signal, error);
4215
4668
  }
4216
4669
  }
4217
- async function gatewayMintPost(registration, input, signal, fetchGateway) {
4670
+ async function gatewayMintPost(registration, input, signal, fetchGateway, observation) {
4218
4671
  const serialized = JSON.stringify(gatewayMintBody(input));
4219
4672
  if (Buffer.byteLength(serialized, "utf8") > CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES) return mintRefusal("producer_frame_invalid");
4673
+ const clientExchangeRef = `client-exchange:${randomUUID().replaceAll("-", "")}`;
4674
+ observation.client_exchange_ref = clientExchangeRef;
4220
4675
  const response2 = await fetchGateway(`${registration.gateway_request_origin}${CEAL_HOST_INVOCATION_CONTEXT_PATH}`, {
4221
4676
  method: "POST",
4222
- headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4677
+ headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json", [CEAL_HTTP_CLIENT_EXCHANGE_REF_HEADER]: clientExchangeRef },
4223
4678
  body: serialized,
4224
4679
  signal
4225
4680
  });
4681
+ try {
4682
+ const gatewayHttpRequestRef = response2.headers.get(CEAL_HTTP_GATEWAY_REQUEST_REF_HEADER);
4683
+ if (gatewayHttpRequestRef !== null && HOST_RELAY_GATEWAY_HTTP_REQUEST_REF_PATTERN.test(gatewayHttpRequestRef)) observation.gateway_http_request_ref = gatewayHttpRequestRef;
4684
+ } catch {
4685
+ }
4226
4686
  const raw = await readBoundedResponseText(response2, 8192);
4227
4687
  return decodeGatewayMintResponse(response2, raw);
4228
4688
  }
@@ -4245,18 +4705,21 @@ function decodeGatewayMintResponse(response2, raw) {
4245
4705
  } catch {
4246
4706
  value = null;
4247
4707
  }
4248
- if (!response2.ok) return mintRefusal(gatewayMintRefusal(response2.status, value));
4708
+ if (!response2.ok) {
4709
+ const reason = gatewayMintRefusal(response2.status, value);
4710
+ return mintRefusal(reason, reason === "gateway_refused" ? response2.status : void 0);
4711
+ }
4249
4712
  if (!isMintResult(value)) return mintRefusal("gateway_response_invalid");
4250
4713
  const requestRef = response2.headers.get("ceal-request-ref");
4251
4714
  if (requestRef === null || !/^ceal-request:[a-f0-9-]{36}$/u.test(requestRef)) return mintRefusal("gateway_response_invalid");
4252
4715
  const result2 = decodeCealHostInvocationAuthenticationResult(value, /* @__PURE__ */ new Date());
4253
- return { schema_version: "ceal.host_relay_invocation_context_result.v2", status: "ready", request_ref: requestRef, result: result2 };
4716
+ return { schema_version: HOST_RELAY_INVOCATION_CONTEXT_RESULT_SCHEMA, status: "ready", request_ref: requestRef, result: result2 };
4254
4717
  }
4255
4718
  function gatewayMintFailure(signal, _error) {
4256
4719
  return mintRefusal(signal.aborted ? "transient_retryable" : "gateway_unavailable");
4257
4720
  }
4258
- function mintRefusal(reason) {
4259
- return { schema_version: "ceal.host_relay_invocation_context_result.v2", status: "refused", reason };
4721
+ function mintRefusal(reason, gatewayStatus) {
4722
+ return { schema_version: HOST_RELAY_INVOCATION_CONTEXT_RESULT_SCHEMA, status: "refused", reason, ...gatewayStatus === void 0 ? {} : { gateway_status: gatewayStatus } };
4260
4723
  }
4261
4724
  async function readBoundedResponseText(response2, maximumBytes) {
4262
4725
  if (response2.body === null) return null;
@@ -4293,7 +4756,10 @@ function gatewayMintRefusal(status, value) {
4293
4756
  if (status === 403 && record5(value)) {
4294
4757
  if (value.error_code === "host_source_refused") return "host_source_refused";
4295
4758
  if (value.error_code === "context_expired") return "context_expired";
4296
- if (value.error_code === "request_context_refused") return "context_stale";
4759
+ if (value.error_code === "request_context_refused") {
4760
+ if (isVocabularyWord(CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS, value.reason) && value.reason === "request_authority_unavailable") return "gateway_unavailable";
4761
+ return "mint_failed";
4762
+ }
4297
4763
  }
4298
4764
  if (status === 429) return "gateway_rate_limited";
4299
4765
  if (status >= 500) return "gateway_unavailable";
@@ -4334,6 +4800,7 @@ function exactOptionalKeys2(value, required, optional) {
4334
4800
  }
4335
4801
 
4336
4802
  // host/relay/bin/ceal-host-relay.ts
4803
+ var RELAY_COMMAND_SCHEMA = "ceal.host_relay_command.v1";
4337
4804
  var serviceArguments = consumeHostServiceLogArgument(process.argv.slice(2));
4338
4805
  if (serviceArguments.path !== void 0) process.env[HOST_SERVICE_LOG_ENVIRONMENT] = serviceArguments.path;
4339
4806
  var controller = new AbortController();
@@ -4341,13 +4808,11 @@ var stop = () => controller.abort();
4341
4808
  process.once("SIGINT", stop);
4342
4809
  process.once("SIGTERM", stop);
4343
4810
  var stopLogBound = boundHostServiceLog();
4344
- void runHostRelayCli(serviceArguments.args, controller.signal).then((result2) => {
4345
- process.stdout.write(`${JSON.stringify({ schema_version: "ceal.host_relay_command.v1", ...result2 })}
4346
- `);
4811
+ void runHostRelayCli(serviceArguments.args, controller.signal).then(async (result2) => {
4812
+ await writeHostServiceCommandResult(RELAY_COMMAND_SCHEMA, result2, (line) => process.stdout.write(line));
4347
4813
  process.exitCode = result2.ok ? 0 : 1;
4348
- }).catch((error) => {
4349
- process.stdout.write(`${JSON.stringify({ schema_version: "ceal.host_relay_command.v1", ok: false, ...hostTerminalFailure(error, "Relay") })}
4350
- `);
4814
+ }).catch(async (error) => {
4815
+ await writeHostServiceCommandResult(RELAY_COMMAND_SCHEMA, { ok: false, ...hostTerminalFailure(error, "Relay") }, (line) => process.stdout.write(line));
4351
4816
  process.exitCode = 1;
4352
4817
  }).finally(() => {
4353
4818
  stopLogBound();