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

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.
@@ -2,6 +2,18 @@
2
2
  import { createRequire as __cealCreateRequire } from "node:module";
3
3
  const require = __cealCreateRequire(import.meta.url);
4
4
 
5
+ // packages/ceal-client-protocol/src/vocabulary.ts
6
+ function vocabulary(words) {
7
+ return Object.freeze(words);
8
+ }
9
+ function isVocabularyWord(words, value) {
10
+ return words.some((word) => word === value);
11
+ }
12
+
13
+ // packages/ceal-client-protocol/src/host-usage-fields.ts
14
+ var CEAL_CODEX_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
15
+ var CEAL_CLAUDE_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"]);
16
+
5
17
  // packages/ceal-client-protocol/src/canonical-json.ts
6
18
  function cealCanonicalJson(value) {
7
19
  if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
@@ -76,7 +88,7 @@ var client_wire_contract_default = {
76
88
  },
77
89
  command_request: {
78
90
  schema_name: "ceal.command_request",
79
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
91
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
80
92
  absolute_transport_max_bytes: 65536
81
93
  },
82
94
  command_resolution: {
@@ -122,7 +134,7 @@ var client_wire_contract_default = {
122
134
  },
123
135
  command_response: {
124
136
  schema_name: "ceal.command_response",
125
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
137
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
126
138
  descriptor_field: "verified_artifact",
127
139
  request_context_field: "request_context",
128
140
  required_fields: [
@@ -135,7 +147,8 @@ var client_wire_contract_default = {
135
147
  "visible_output_max_bytes",
136
148
  "local_delivery",
137
149
  "verified_artifact",
138
- "request_context"
150
+ "request_context",
151
+ "result_file"
139
152
  ],
140
153
  bare_document_fields: [
141
154
  "invocation",
@@ -176,8 +189,11 @@ var client_wire_contract_default = {
176
189
  "ok",
177
190
  "code",
178
191
  "reason",
179
- "gateway_status"
192
+ "gateway_status",
193
+ "retry_after_ms"
180
194
  ],
195
+ refusal_required_fields: ["schema_version", "ok", "code", "reason"],
196
+ refusal_optional_fields: ["gateway_status", "retry_after_ms"],
181
197
  client_nonce: {
182
198
  character_class_source: "A-Za-z0-9_-",
183
199
  encoded_characters: 43
@@ -396,19 +412,14 @@ var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
396
412
  personal_authorization_required: "connect_personal_account"
397
413
  });
398
414
 
399
- // packages/ceal-client-protocol/src/vocabulary.ts
400
- function vocabulary(words) {
401
- return Object.freeze(words);
402
- }
403
- function isVocabularyWord(words, value) {
404
- return words.some((word) => word === value);
405
- }
406
-
407
415
  // packages/ceal-client-protocol/src/gateway-response-types.ts
408
416
  var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
409
417
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
410
418
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
411
419
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
420
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
421
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
422
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
412
423
  var CEAL_GATEWAY_READ_REUSE_DISPOSITIONS = vocabulary(["response_cache_hit", "corpus_hit", "corpus_hit_after_revalidation", "corpus_partial_provider_supplement", "provider_direct", "provider_continuation", "reuse_unavailable"]);
413
424
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
414
425
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -449,6 +460,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
449
460
  ]);
450
461
 
451
462
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
463
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
464
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
465
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
466
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
467
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
468
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
469
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
470
+ function escapePathPattern(value) {
471
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
472
+ }
473
+ function machineHomePathPatterns(flags) {
474
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
475
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
476
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
477
+ }
452
478
  var CealProtocolValidationError = class extends Error {
453
479
  name = "CealProtocolValidationError";
454
480
  code;
@@ -807,8 +833,9 @@ var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask a
807
833
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
808
834
  var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
809
835
  var HOST_INSTALL_REPAIR = "The local Host or Relay is missing, stale, or unavailable. Run `ceal-host install`, then `ceal-host discovery sync`, and retry from a new producer conversation.";
810
- 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.";
836
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
811
837
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
838
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
812
839
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
813
840
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
814
841
  }
@@ -829,13 +856,18 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
829
856
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
830
857
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
831
858
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
832
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
833
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
834
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
835
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
836
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
837
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
838
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
859
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
860
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
861
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
862
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
863
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Person, then retry this same session refresh.", "ask_admin", 403),
864
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Principal, then retry this same session refresh.", "ask_admin", 403),
865
+ authority_replaced: guidance("The Gateway authority has been replaced; this session is no longer valid here. Run `ceal session adopt --gateway <origin> --email <email>` against the current Gateway to complete mailbox-confirmed recovery.", "repair_or_adopt_session", 409),
866
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
867
+ refresh_recovery_unavailable: guidance("The Gateway's durable refresh-recovery key is unavailable. Retry the same refresh attempt after the key is available.", "retry", 503, true),
868
+ refresh_recovery_outcome_unavailable: guidance("The Gateway could not safely recover the outcome of a prior refresh. Ask an administrator to inspect the Gateway session state before retrying or adopting this session.", "ask_admin", 503),
869
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
870
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
839
871
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
840
872
  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),
841
873
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -850,23 +882,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
850
882
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
851
883
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
852
884
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
853
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
854
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
855
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
856
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
885
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
886
+ [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance("The Gateway is still starting; the refresh was not attempted and the refresh token was not consumed. Retry the same refresh attempt after the Gateway is serving.", "retry", 503, true),
857
887
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
858
888
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
859
889
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
860
890
  internal_error: guidance("The Gateway failed without exposing internal state.", "answer_with_gap", 500),
861
891
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
862
- // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
892
+ // the static client variant was retired when the client started reading this table.
863
893
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
864
894
  gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
865
- // Restored verbatim from the retired `localFailureText` `unknown_outcome`
866
- // case: the outcome is unknown, so a read may be retried while a write
867
- // must receipt-check first. Collapsing both to "do not repeat the call"
868
- // forbids the safe read retry the sentence exists to allow.
869
- unknown_outcome: guidance("The transport outcome is unknown: a read may be retried; for a write, check write_receipt.get before repeating.", "answer_with_gap", 500),
895
+ // The safe move varies by request. Keep the sentence conditional on the
896
+ // same `retryable` and `next_action` facts the response exposes.
897
+ unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
898
+ // A provider write the Gateway command deadline cut after its dispatch: the write left and its receipt is still settling, so the caller reads the receipt instead of repeating the write.
899
+ write_in_progress: guidance("The provider write was dispatched but the Gateway command deadline cut the wait before its outcome settled. Do not repeat the write; read the durable receipt named by write_request_ref with write_receipt.get.", "write_receipt.get", 500),
870
900
  // Restored verbatim from the retired `localFailureText`
871
901
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
872
902
  // session context unavailable, so the caller repairs or adopts the
@@ -947,8 +977,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
947
977
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
948
978
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
949
979
  // is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
950
- // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). Cause-specific
951
- // sentences carry the retired policy remedies; `gateway_refused` reuses the release-upgrade guidance above.
980
+ // and `retryable` from `hostAuthenticationFailureForCause` (the table's explicit retry verdict). Cause-specific
981
+ // sentences carry only remedies proved by the Host or Relay cause; generic Gateway refusals do not prove a release mismatch.
952
982
  // Statuses are the
953
983
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
954
984
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
@@ -958,21 +988,23 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
958
988
  // The bounded Host reason does not prove ephemerality. A Host refusal never
959
989
  // changes mode; standalone remains the separate Client authority path.
960
990
  host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
961
- host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
962
- host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
991
+ host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
992
+ host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
993
+ host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
963
994
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
964
995
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
965
996
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
966
997
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
967
- host_mint_gateway_refused: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
998
+ host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
968
999
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1000
+ host_contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
969
1001
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
970
1002
  // producer-frame fault names the administrator repair step.
971
1003
  host_producer_frame_invalid: guidance("Ask an administrator to inspect and repair the producer frame, then start a fresh Host turn.", "ask_admin", 400),
972
1004
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
973
1005
  // sandboxed Relay socket names the run-alone retry.
974
1006
  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),
975
- host_relay_unavailable: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 503),
1007
+ host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
976
1008
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
977
1009
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
978
1010
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1015,7 +1047,7 @@ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
1015
1047
  var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
1016
1048
  var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
1017
1049
  var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
1018
- var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
1050
+ var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_applicable", "not_offered", "offered", "accepted", "rejected", "unknown"]);
1019
1051
  var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
1020
1052
  var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
1021
1053
  var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
@@ -1198,6 +1230,7 @@ var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
1198
1230
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
1199
1231
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
1200
1232
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
1233
+ var CEAL_PROVIDER_BOUNDARY_FIELDS = vocabulary(["provider_boundary_ref", "provider_boundary_kind", "provider_boundary_label", "provider_native_id", "provider_boundary_evidence"]);
1201
1234
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
1202
1235
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
1203
1236
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1243,7 +1276,7 @@ var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1243
1276
  var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
1244
1277
  var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
1245
1278
  var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
1246
- var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
1279
+ var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary", "standard_names"]);
1247
1280
 
1248
1281
  // packages/ceal-client-protocol/src/operation-catalog.ts
1249
1282
  var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
@@ -1339,6 +1372,7 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1339
1372
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
1340
1373
  gateway_access_group_connector_calendar_scope_audit: (root) => join(root, "profile-connector-calendar-scope-audit.jsonl"),
1341
1374
  gateway_access_group_connector_readiness_audit: (root) => join(root, "profile-connector-readiness.audit.jsonl"),
1375
+ gateway_deployment_events: (root) => join(root, "gateway-deployments.jsonl"),
1342
1376
  gateway_organization_audit_ledger: (root) => join(root, "organization-ledger.jsonl"),
1343
1377
  gateway_personal_client_audit: (root) => join(root, "audit.jsonl"),
1344
1378
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
@@ -1368,6 +1402,11 @@ var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_L
1368
1402
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1369
1403
  var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1370
1404
 
1405
+ // packages/ceal-client-protocol/src/resource-read-result.ts
1406
+ var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
1407
+ var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
1408
+ var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1409
+
1371
1410
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
1372
1411
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
1373
1412
 
@@ -1452,6 +1491,7 @@ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1452
1491
  { 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" },
1453
1492
  { 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" },
1454
1493
  { 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" },
1494
+ { provider: "google-workspace", result_kind: "form_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified Forms responderUri", source: "https://developers.google.com/workspace/forms/api/reference/rest/v1/forms" },
1455
1495
  { 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" },
1456
1496
  { 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" },
1457
1497
  { 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" },
@@ -1526,6 +1566,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1526
1566
  "review_submitted",
1527
1567
  "comment_created",
1528
1568
  "reaction_created",
1569
+ "pull_request_merged",
1570
+ "release_published",
1529
1571
  "ceal_write_completed",
1530
1572
  "event_start",
1531
1573
  "all_day_start",
@@ -1537,7 +1579,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1537
1579
  "page_last_edited",
1538
1580
  "resource_modified"
1539
1581
  ]);
1540
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
1582
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
1541
1583
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
1542
1584
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
1543
1585
  "provider_page_budget",
@@ -1558,6 +1600,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1558
1600
  "github.pull_request.opened",
1559
1601
  "github.issue.edited",
1560
1602
  "github.pull_request.edited",
1603
+ "github.pull_request.merged",
1604
+ "github.release.published",
1561
1605
  "github.review.submitted",
1562
1606
  "github.issue_comment.created",
1563
1607
  "github.review_comment.created",
@@ -1571,6 +1615,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1571
1615
  "drive.file.created",
1572
1616
  "drive.file.modified",
1573
1617
  "drive.file.viewed",
1618
+ "mail.sent",
1574
1619
  "notion.page.created",
1575
1620
  "notion.page.edited"
1576
1621
  ]);
@@ -1584,6 +1629,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1584
1629
  "github.review_comment.created": "comment_created",
1585
1630
  "github.issue.opened": "resource_created",
1586
1631
  "github.pull_request.opened": "resource_created",
1632
+ "github.pull_request.merged": "pull_request_merged",
1633
+ "github.release.published": "release_published",
1587
1634
  "github.issue.edited": "resource_modified",
1588
1635
  "github.pull_request.edited": "resource_modified",
1589
1636
  "github.reaction.created": "reaction_created",
@@ -1594,6 +1641,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1594
1641
  "drive.file.created": "file_created",
1595
1642
  "drive.file.modified": "file_modified_by_me",
1596
1643
  "drive.file.viewed": "file_viewed_by_me",
1644
+ "mail.sent": "message_created",
1597
1645
  "notion.page.created": "page_created",
1598
1646
  "notion.page.edited": "page_last_edited"
1599
1647
  });
@@ -1621,6 +1669,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1621
1669
  created_at: { required: false, timestamp: true },
1622
1670
  created_at_local: { required: false, timestamp: true },
1623
1671
  modified_at: { required: false, timestamp: true },
1672
+ observed_at: { required: false, timestamp: true },
1624
1673
  modified_at_local: { required: false, timestamp: true },
1625
1674
  viewed_by_me_at: { required: false, timestamp: true },
1626
1675
  modified_by_me_at: { required: false, timestamp: true },
@@ -1648,9 +1697,6 @@ var RESOURCE_ROW_REQUIRED_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(
1648
1697
  var RESOURCE_ROW_KEYS = new Set(Object.keys(RESOURCE_ROW_KEY_RULES));
1649
1698
  var RESOURCE_ROW_TIMESTAMP_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(([key, rule]) => rule.timestamp ? [key] : []);
1650
1699
 
1651
- // packages/ceal-client-protocol/src/resource-read-result.ts
1652
- var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1653
-
1654
1700
  // packages/ceal-client-protocol/src/excluded-target-coverage.ts
1655
1701
  var CEAL_EXCLUDED_TARGET_COVERAGE_MAX_ENTRIES = 64;
1656
1702
  function cealExcludedTargetCoverageJsonSchema() {
@@ -1706,6 +1752,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1706
1752
  "principal_inactive",
1707
1753
  "authority_replaced",
1708
1754
  "refresh_recovery_unavailable",
1755
+ "refresh_recovery_outcome_unavailable",
1756
+ "refresh_state_unavailable",
1709
1757
  "refresh_recovery_expired",
1710
1758
  // The serving gate answers this while the Gateway is still starting and the
1711
1759
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -1957,7 +2005,7 @@ function validateBatchContents(value) {
1957
2005
  if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
1958
2006
  const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
1959
2007
  for (const fact of facts) {
1960
- validateFact(fact, value.host_session_ref);
2008
+ validateCealHostUsageFact(fact, value.host_session_ref);
1961
2009
  if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
1962
2010
  }
1963
2011
  for (const gap of gaps) {
@@ -1990,7 +2038,7 @@ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, d
1990
2038
  for (const part of [producer, hostSourceRef, hostSessionRef, device, inode]) if (typeof part !== "string" || part.length === 0 || part.length > 512) invalid("Ceal Host usage file identity is invalid.");
1991
2039
  return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
1992
2040
  }
1993
- function validateFact(value, sessionRef) {
2041
+ function validateCealHostUsageFact(value, sessionRef) {
1994
2042
  if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
1995
2043
  requireFactByteLimit(value);
1996
2044
  if (value.producer === "codex_transcript") validateCodexFact(value);
@@ -2054,7 +2102,7 @@ function validCorrectionSemantics(value) {
2054
2102
  }
2055
2103
  function validateCodexUsageCounts(value) {
2056
2104
  if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
2057
- requireExactOperationKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
2105
+ requireExactOperationKeys(value, CEAL_CODEX_USAGE_COUNT_FIELDS);
2058
2106
  for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
2059
2107
  if (Number(value.total_tokens) !== Number(value.input_tokens) + Number(value.output_tokens) || Number(value.cached_input_tokens) + Number(value.cache_write_input_tokens) > Number(value.input_tokens) || Number(value.reasoning_output_tokens) > Number(value.output_tokens)) invalid("Ceal Codex usage fields are inconsistent.");
2060
2108
  }
@@ -2374,6 +2422,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
2374
2422
  "options_invalid",
2375
2423
  "session_unavailable",
2376
2424
  "context_unavailable",
2425
+ "activation_wait_exhausted",
2377
2426
  "context_replaced",
2378
2427
  "no_binding",
2379
2428
  "context_expired",
@@ -2409,22 +2458,23 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2409
2458
  // This reason cannot distinguish a Codex side conversation from a missing
2410
2459
  // context in a regular session, so guidance must leave that choice to the caller.
2411
2460
  context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2412
- context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
2461
+ activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2462
+ context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2413
2463
  // `no_binding` now means the producer has no real current Host session. The
2414
2464
  // Host Relay never uses it for an uncreated Gateway Request; there is no
2415
2465
  // useful retry until the consumer is running inside a Host session.
2416
2466
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2417
- context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
2467
+ context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
2418
2468
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
2419
2469
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
2420
2470
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
2421
2471
  gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
2422
- contract_mismatch: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2423
- gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "upgrade_ceal_client" }),
2472
+ contract_mismatch: Object.freeze({ classification: "host_contract_mismatch", next_action: "upgrade_ceal_client" }),
2473
+ gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
2424
2474
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2425
2475
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2426
2476
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2427
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2477
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2428
2478
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2429
2479
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2430
2480
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2507,7 +2557,7 @@ function isCealHostServiceDiagnosticCause(value, event) {
2507
2557
  // packages/ceal-client-protocol/src/client-result-materialization.ts
2508
2558
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
2509
2559
  var REQUIRED_FIELDS2 = Object.freeze(["schema_version", "operation_id", "path", "sha256"]);
2510
- var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "items_path", "row_count", "result_complete", "coverage", "local_result_root", "model_disclosure", "continue_argv", "how_to_read"]);
2560
+ var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "local_result_root", "request_context_argv", "how_to_read"]);
2511
2561
 
2512
2562
  // packages/ceal-client-protocol/src/discovery-manifest.ts
2513
2563
  var DISCOVERY_MANIFEST_KEYS = CEAL_CLIENT_WIRE_CONTRACT.command_response.discovery_manifest_fields;
@@ -2549,6 +2599,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2549
2599
  maximum: CEAL_PROTOCOL_VERSION
2550
2600
  });
2551
2601
 
2602
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
2603
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2604
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2605
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2606
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2607
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2608
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2609
+ function redactOperatorDiagnosticSecrets(value) {
2610
+ return value.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer [redacted]").replace(/(["']?(?:authorization|[A-Za-z0-9_-]*(?:token|secret|credential|password|key))["']?\s*[:=]\s*)(?!(?:"unknown"|'unknown'|unknown\b))(?:"[^"]*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
2611
+ }
2612
+ function redactOperatorDiagnosticText(value) {
2613
+ const normalized = normalizeCealSingleLineText(value);
2614
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2615
+ }
2616
+ function renderOperatorDiagnostic(value) {
2617
+ const state = collectDiagnosticState(value);
2618
+ const fields = [
2619
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2620
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2621
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
2622
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
2623
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
2624
+ ].filter((field) => field !== void 0);
2625
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2626
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2627
+ }
2628
+ function collectDiagnosticState(value) {
2629
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2630
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
2631
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2632
+ const current = pending.shift();
2633
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2634
+ }
2635
+ return state;
2636
+ }
2637
+ function visitDiagnosticNode(current, state, pending, visited) {
2638
+ if (isObject(current)) {
2639
+ if (visited.has(current)) return;
2640
+ visited.add(current);
2641
+ }
2642
+ captureProcessEvidence(current, state);
2643
+ appendCause(current, state.causes);
2644
+ enqueueCauseChildren(current, state.causes.length, pending);
2645
+ }
2646
+ function captureProcessEvidence(current, state) {
2647
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
2648
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
2649
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2650
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2651
+ }
2652
+ function appendCause(current, causes) {
2653
+ const errors = read(current, "errors");
2654
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2655
+ causes.push(errorCause(current));
2656
+ return;
2657
+ }
2658
+ if (!isObject(current)) {
2659
+ const message = safeText(current);
2660
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2661
+ }
2662
+ }
2663
+ function errorCause(error) {
2664
+ const name = safeText(read(error, "name")) ?? "Error";
2665
+ const message = safeText(read(error, "message"));
2666
+ const codeValue = read(error, "code");
2667
+ const code2 = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
2668
+ const errnoValue = read(error, "errno");
2669
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2670
+ const syscall = safeText(read(error, "syscall"));
2671
+ const path = safePath(read(error, "path"));
2672
+ return Object.freeze({ error_class: name, ...message === void 0 ? {} : { message }, ...code2 === void 0 ? {} : { code: code2 }, ...errno === void 0 ? {} : { errno }, ...syscall === void 0 ? {} : { syscall }, ...path === void 0 ? {} : { path } });
2673
+ }
2674
+ function enqueueCauseChildren(current, causeCount, pending) {
2675
+ const cause = read(current, "cause");
2676
+ if (cause !== void 0) pending.push(cause);
2677
+ const errors = read(current, "errors");
2678
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2679
+ }
2680
+ function isObject(value) {
2681
+ return typeof value === "object" && value !== null;
2682
+ }
2683
+ function formatCause(cause) {
2684
+ const fields = [
2685
+ cause.error_class,
2686
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
2687
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
2688
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
2689
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
2690
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
2691
+ ].filter((field) => field !== void 0);
2692
+ return fields.join(" ");
2693
+ }
2694
+ function tail(value) {
2695
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
2696
+ return safeDiagnosticText(clipped);
2697
+ }
2698
+ function safeText(value) {
2699
+ if (typeof value !== "string") return void 0;
2700
+ const safe = safeDiagnosticText(value);
2701
+ if (safe.length === 0) return void 0;
2702
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
2703
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
2704
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2705
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2706
+ }
2707
+ function safePath(value) {
2708
+ if (typeof value !== "string") return void 0;
2709
+ const safe = safeDiagnosticText(value);
2710
+ if (safe.length === 0) return void 0;
2711
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2712
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2713
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
2714
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2715
+ }
2716
+ function safeDiagnosticText(value) {
2717
+ return redactOperatorDiagnosticText(String(value));
2718
+ }
2719
+ function outputText(value) {
2720
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
2721
+ if (value instanceof Uint8Array) {
2722
+ try {
2723
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
2724
+ } catch {
2725
+ return void 0;
2726
+ }
2727
+ }
2728
+ return void 0;
2729
+ }
2730
+ function safeStatus(value) {
2731
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2732
+ return typeof value === "string" ? safeText(value) : void 0;
2733
+ }
2734
+ function safeExitCode(value) {
2735
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
2736
+ }
2737
+ function read(value, key) {
2738
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
2739
+ try {
2740
+ return Reflect.get(value, key);
2741
+ } catch {
2742
+ return void 0;
2743
+ }
2744
+ }
2745
+ function redactHomePaths(value) {
2746
+ const paths = [
2747
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
2748
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
2749
+ ];
2750
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
2751
+ let output = "";
2752
+ let cursor = 0;
2753
+ for (const path of paths) {
2754
+ if (path.start < cursor) continue;
2755
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
2756
+ cursor = path.end;
2757
+ }
2758
+ return output + value.slice(cursor);
2759
+ }
2760
+ function configuredHomePathPatterns() {
2761
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
2762
+ return homes.flatMap((home) => {
2763
+ const root = home.replace(/[\\/]+$/gu, "");
2764
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
2765
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
2766
+ return [{ pattern, prefixLength: root.length }];
2767
+ });
2768
+ }
2769
+ function matchedHomePrefixLength(value) {
2770
+ let separators = 0;
2771
+ for (let index = 0; index < value.length; index += 1) {
2772
+ if (value[index] !== "/" && value[index] !== "\\") continue;
2773
+ separators += 1;
2774
+ if (separators === 3) return index;
2775
+ }
2776
+ return value.length;
2777
+ }
2778
+ function redactUrls(value) {
2779
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2780
+ }
2781
+ function redactFilePaths(value) {
2782
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2783
+ }
2784
+ function homePathRange(value, match, prefixLength) {
2785
+ const index = match.index;
2786
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
2787
+ const start = index;
2788
+ let end = start + match[0].length;
2789
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
2790
+ if (quote !== void 0) {
2791
+ const closing = value.indexOf(quote, end);
2792
+ if (closing >= 0) end = closing;
2793
+ }
2794
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
2795
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
2796
+ }
2797
+ function truncateUtf8(value, maxBytes) {
2798
+ if (byteLength(value) <= maxBytes) return value;
2799
+ let output = "";
2800
+ for (const character of value) {
2801
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
2802
+ output += character;
2803
+ }
2804
+ return `${output}…`;
2805
+ }
2806
+
2552
2807
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
2553
2808
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
2554
2809
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -2689,10 +2944,10 @@ function failureDetail(error) {
2689
2944
  function errorCode(error) {
2690
2945
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
2691
2946
  }
2692
- function hostClientProbe(result, read) {
2947
+ function hostClientProbe(result, read2) {
2693
2948
  if (result === null) return { kind: "unreachable" };
2694
2949
  if (result.exit_code !== 0) return { kind: "refused", exit_code: result.exit_code };
2695
- const value = read(result);
2950
+ const value = read2(result);
2696
2951
  return value === null ? { kind: "unreadable" } : { kind: "value", value };
2697
2952
  }
2698
2953
  function hostClientProbeRefusal(probe, subject) {
@@ -2835,7 +3090,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2835
3090
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2836
3091
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2837
3092
  return await new Promise((resolve, reject) => {
2838
- const child = execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
3093
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2839
3094
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2840
3095
  if (exitCode === null) {
2841
3096
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2886,6 +3141,185 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
2886
3141
  return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
2887
3142
  }
2888
3143
 
3144
+ // host/service-log.ts
3145
+ import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
3146
+ import { dirname as dirname2, isAbsolute, posix, win32 as win322 } from "node:path";
3147
+
3148
+ // host/service-log-delivery.ts
3149
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
3150
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
3151
+ setImmediate(flush);
3152
+ }, onDeliveryGap = () => void 0) {
3153
+ const pending = [];
3154
+ const highWaterMark = stream.writableHighWaterMark;
3155
+ const byteBudget = highWaterMark + highWaterMark;
3156
+ let pendingBytes = 0;
3157
+ let droppedLines = 0;
3158
+ let flushScheduled = false;
3159
+ let waitingForDrain = false;
3160
+ let closed = !stream.writable;
3161
+ function stop() {
3162
+ if (closed) return;
3163
+ closed = true;
3164
+ pending.length = 0;
3165
+ pendingBytes = 0;
3166
+ stream.off("drain", onDrain);
3167
+ stream.off("close", onTerminal);
3168
+ stream.off("finish", onTerminal);
3169
+ stream.off("error", onError);
3170
+ }
3171
+ function onTerminal() {
3172
+ stop();
3173
+ }
3174
+ function onError() {
3175
+ stop();
3176
+ }
3177
+ function onDrain() {
3178
+ waitingForDrain = false;
3179
+ scheduleFlush();
3180
+ }
3181
+ function scheduleFlush() {
3182
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
3183
+ flushScheduled = true;
3184
+ let scheduling = true;
3185
+ let invokedSynchronously = false;
3186
+ try {
3187
+ schedule(() => {
3188
+ if (scheduling) {
3189
+ invokedSynchronously = true;
3190
+ return;
3191
+ }
3192
+ flushScheduled = false;
3193
+ flush();
3194
+ });
3195
+ } catch {
3196
+ flushScheduled = false;
3197
+ stop();
3198
+ return;
3199
+ }
3200
+ scheduling = false;
3201
+ if (invokedSynchronously) {
3202
+ flushScheduled = false;
3203
+ stop();
3204
+ }
3205
+ }
3206
+ function flush() {
3207
+ if (closed) return;
3208
+ if (!stream.writable) {
3209
+ stop();
3210
+ return;
3211
+ }
3212
+ while (pending.length > 0) {
3213
+ if (stream.writableNeedDrain) {
3214
+ if (!waitingForDrain) {
3215
+ waitingForDrain = true;
3216
+ stream.once("drain", onDrain);
3217
+ }
3218
+ return;
3219
+ }
3220
+ const next = pending.shift();
3221
+ if (next === void 0) return;
3222
+ pendingBytes -= next.bytes;
3223
+ let accepted;
3224
+ try {
3225
+ accepted = stream.write(next.line);
3226
+ } catch {
3227
+ stop();
3228
+ return;
3229
+ }
3230
+ if (!accepted) {
3231
+ waitingForDrain = true;
3232
+ stream.once("drain", onDrain);
3233
+ return;
3234
+ }
3235
+ }
3236
+ if (droppedLines > 0) {
3237
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
3238
+ `;
3239
+ droppedLines = 0;
3240
+ try {
3241
+ onDeliveryGap(line);
3242
+ } catch {
3243
+ }
3244
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
3245
+ pendingBytes += Buffer.byteLength(line, "utf8");
3246
+ flush();
3247
+ }
3248
+ }
3249
+ stream.on("close", onTerminal);
3250
+ stream.on("finish", onTerminal);
3251
+ stream.on("error", onError);
3252
+ return (line) => {
3253
+ if (closed) return;
3254
+ const bytes = Buffer.byteLength(line, "utf8");
3255
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
3256
+ droppedLines += 1;
3257
+ scheduleFlush();
3258
+ return;
3259
+ }
3260
+ pending.push({ line, bytes });
3261
+ pendingBytes += bytes;
3262
+ scheduleFlush();
3263
+ };
3264
+ }
3265
+
3266
+ // host/service-log.ts
3267
+ var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
3268
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
3269
+ void persistHostServiceLogLine(line);
3270
+ });
3271
+ function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
3272
+ const details = diagnosticDetails(event, failure_kind, cause);
3273
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
3274
+ `;
3275
+ try {
3276
+ (sink ?? defaultHostServiceDiagnosticSink)(line);
3277
+ } catch {
3278
+ }
3279
+ }
3280
+ function diagnosticDetails(event, failureKind, cause) {
3281
+ if (event === "watcher_scan_failed") return {
3282
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3283
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
3284
+ };
3285
+ return validDiagnosticCause(cause, event) ? { cause } : {};
3286
+ }
3287
+ function validDiagnosticCause(cause, event) {
3288
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
3289
+ }
3290
+ function defaultHostServiceDiagnosticSink(line) {
3291
+ writeHostServiceLogLine(line);
3292
+ }
3293
+ var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
3294
+ function writeHostServiceLogLine(line, environment = process.env) {
3295
+ void persistHostServiceLogLine(line, environment);
3296
+ defaultHostServiceLogDelivery(line);
3297
+ }
3298
+ async function persistHostServiceLogLine(line, environment = process.env) {
3299
+ if (process.platform !== "win32") return;
3300
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
3301
+ if (path === void 0 || !win322.isAbsolute(path) || win322.normalize(path) !== path) return;
3302
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
3303
+ }
3304
+ async function appendHostServiceLogLine(path, line) {
3305
+ if (!isAbsolute(path)) return;
3306
+ await ensureHostServiceLogDirectory(path);
3307
+ await appendFile(path, line);
3308
+ }
3309
+ var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
3310
+ var hostServiceLogDirectories = /* @__PURE__ */ new Map();
3311
+ function ensureHostServiceLogDirectory(path) {
3312
+ const directory = dirname2(path);
3313
+ const existing = hostServiceLogDirectories.get(directory);
3314
+ if (existing !== void 0) return existing;
3315
+ const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
3316
+ hostServiceLogDirectories.delete(directory);
3317
+ throw error;
3318
+ });
3319
+ hostServiceLogDirectories.set(directory, pending);
3320
+ return pending;
3321
+ }
3322
+
2889
3323
  // host/relay/src/host-producer-core.ts
2890
3324
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
2891
3325
  function isHostTranscriptCursorReason(value) {
@@ -2909,9 +3343,9 @@ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
2909
3343
  }
2910
3344
  return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
2911
3345
  }
2912
- async function readRegisteredHostInvocationHumanMessageWindow(listRegistrations, readCursor, identity, decodeLine) {
3346
+ async function readRegisteredHostInvocationHumanMessageWindow(readRegistration, readCursor, identity, decodeLine) {
2913
3347
  try {
2914
- const registration = await findLiveHostInvocationRegistration(listRegistrations, identity);
3348
+ const registration = await findLiveHostInvocationRegistration(readRegistration, identity);
2915
3349
  const cursor = await readCursor(registration);
2916
3350
  assertUsableHostInvocationHumanMessageCursor(cursor, registration);
2917
3351
  return await readHostInvocationHumanMessageWindow(registration, cursor, (line) => decodeLine(line, registration, cursor));
@@ -2919,9 +3353,9 @@ async function readRegisteredHostInvocationHumanMessageWindow(listRegistrations,
2919
3353
  throw new TypeError("context_unavailable");
2920
3354
  }
2921
3355
  }
2922
- async function findLiveHostInvocationRegistration(listRegistrations, identity) {
2923
- const registration = (await listRegistrations()).find((candidate) => candidate.host_source_ref === identity.host_source_ref && candidate.host_session_ref === identity.host_session_ref && Date.parse(candidate.expires_at) > Date.now());
2924
- if (registration === void 0) throw new TypeError("context_unavailable");
3356
+ async function findLiveHostInvocationRegistration(readRegistration, identity) {
3357
+ const registration = await readRegistration(identity);
3358
+ if (registration === null || registration.host_source_ref !== identity.host_source_ref || registration.host_session_ref !== identity.host_session_ref || !(Date.parse(registration.expires_at) > Date.now())) throw new TypeError("context_unavailable");
2925
3359
  return registration;
2926
3360
  }
2927
3361
  function assertUsableHostInvocationHumanMessageCursor(cursor, registration) {
@@ -2988,9 +3422,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
2988
3422
  let lastNewline = -1;
2989
3423
  while (position < size) {
2990
3424
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
2991
- const read = await handle.read(buffer, 0, buffer.length, position);
2992
- if (read.bytesRead === 0) break;
2993
- const chunk = buffer.subarray(0, read.bytesRead);
3425
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
3426
+ if (read2.bytesRead === 0) break;
3427
+ const chunk = buffer.subarray(0, read2.bytesRead);
2994
3428
  chunks.push(chunk);
2995
3429
  const newline = chunk.lastIndexOf(10);
2996
3430
  if (newline >= 0) lastNewline = total + newline;
@@ -3047,7 +3481,7 @@ function createTranscriptWatcherBase(options, owner) {
3047
3481
  outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
3048
3482
  now: options.now ?? (() => /* @__PURE__ */ new Date()),
3049
3483
  log: options.log ?? ((line) => {
3050
- process.stderr.write(`${line}
3484
+ writeHostServiceLogLine(`${line}
3051
3485
  `);
3052
3486
  }),
3053
3487
  producerInstallationRef: options.producer_installation_ref
@@ -3087,7 +3521,13 @@ var HostTranscriptWatcher = class {
3087
3521
  }
3088
3522
  async scanRegistration(registration) {
3089
3523
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
3090
- missing: () => this.retireMissing(registration),
3524
+ missing: async () => {
3525
+ try {
3526
+ return await this.retireMissing(registration);
3527
+ } catch (error) {
3528
+ return this.scanFailed(void 0, registration, error);
3529
+ }
3530
+ },
3091
3531
  failed: (handle, error) => this.scanFailed(handle, registration, error)
3092
3532
  });
3093
3533
  }
@@ -3157,21 +3597,21 @@ var HostProducerDrainCore = class {
3157
3597
  return run;
3158
3598
  }
3159
3599
  async drainLocked() {
3160
- const read = await this.host.listEnvelopes();
3600
+ const read2 = await this.host.listEnvelopes();
3161
3601
  let removed = 0;
3162
3602
  let expired = 0;
3163
- for (const envelope of read.entries) {
3603
+ for (const envelope of read2.entries) {
3164
3604
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
3165
3605
  else removed += 1;
3166
3606
  await this.host.removeEnvelope(envelope);
3167
3607
  }
3168
- return { removed, expired, malformed: read.malformed };
3608
+ return { removed, expired, malformed: read2.malformed };
3169
3609
  }
3170
3610
  };
3171
3611
 
3172
3612
  // host/relay/src/durable-atomic-replacement.ts
3173
- import { lstat as lstat2, mkdir, open as open2, rename, unlink } from "node:fs/promises";
3174
- import { dirname as dirname2 } from "node:path";
3613
+ import { lstat as lstat2, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
3614
+ import { dirname as dirname3 } from "node:path";
3175
3615
 
3176
3616
  // host/windows-rename-retry.ts
3177
3617
  import { setTimeout as setTimeout2 } from "node:timers/promises";
@@ -3224,7 +3664,7 @@ function isRetryableRenameError(error) {
3224
3664
  // host/relay/src/durable-atomic-replacement.ts
3225
3665
  var DEFAULT_PORT = {
3226
3666
  platform: process.platform,
3227
- mkdir: (path, options) => mkdir(path, options),
3667
+ mkdir: (path, options) => mkdir2(path, options),
3228
3668
  lstat: (path) => lstat2(path),
3229
3669
  open_file: (path) => open2(path, "wx", 384),
3230
3670
  rename,
@@ -3233,7 +3673,7 @@ var DEFAULT_PORT = {
3233
3673
  unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
3234
3674
  };
3235
3675
  async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
3236
- const parent = dirname2(target);
3676
+ const parent = dirname3(target);
3237
3677
  await port.mkdir(parent, { recursive: true, mode: 448 });
3238
3678
  const parentStats = await port.lstat(parent);
3239
3679
  const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
@@ -3303,8 +3743,8 @@ function errorCode2(error) {
3303
3743
  // host/relay/src/host-usage-facts-store.ts
3304
3744
  import { createHash as createHash5 } from "node:crypto";
3305
3745
  import { constants as constants2 } from "node:fs";
3306
- import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3307
- import { dirname as dirname3, join as join3 } from "node:path";
3746
+ import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3747
+ import { dirname as dirname4, join as join3 } from "node:path";
3308
3748
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3309
3749
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3310
3750
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -3553,7 +3993,7 @@ var HostUsageFactsStore = class {
3553
3993
  }
3554
3994
  async writeImmutableBatch(state, batch, bytes) {
3555
3995
  const path = this.batchPath(state, batch.batch_ref);
3556
- await preparePrivateDirectory(dirname3(path), this.platform, this.custody);
3996
+ await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
3557
3997
  const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3558
3998
  if (existing !== null) {
3559
3999
  if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
@@ -3571,7 +4011,7 @@ var HostUsageFactsStore = class {
3571
4011
  await handle.sync();
3572
4012
  await handle.close();
3573
4013
  handle = void 0;
3574
- await syncDirectory(dirname3(path), this.platform);
4014
+ await syncDirectory(dirname4(path), this.platform);
3575
4015
  } catch (error) {
3576
4016
  await handle?.close().catch(() => void 0);
3577
4017
  if (errorCode3(error) === "EEXIST") {
@@ -3615,14 +4055,14 @@ var HostUsageFactsStore = class {
3615
4055
  const gate = new Promise((resolve) => {
3616
4056
  release = resolve;
3617
4057
  });
3618
- const tail = previous.then(() => gate);
3619
- SESSION_TRANSITION_TAILS.set(key, tail);
4058
+ const tail2 = previous.then(() => gate);
4059
+ SESSION_TRANSITION_TAILS.set(key, tail2);
3620
4060
  await previous;
3621
4061
  try {
3622
4062
  return await run();
3623
4063
  } finally {
3624
4064
  release?.();
3625
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
4065
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3626
4066
  }
3627
4067
  }
3628
4068
  sessionPath(producer, hostSourceRef, hostSessionRef) {
@@ -3825,7 +4265,7 @@ async function preparePrivateDirectory(path, platform, custody) {
3825
4265
  await ensurePrivateDirectoryWithSecurefs(path, custody);
3826
4266
  return;
3827
4267
  }
3828
- await mkdir2(path, { recursive: true, mode: 448 });
4268
+ await mkdir3(path, { recursive: true, mode: 448 });
3829
4269
  if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3830
4270
  }
3831
4271
  async function syncExistingFile(path, platform) {
@@ -3835,7 +4275,7 @@ async function syncExistingFile(path, platform) {
3835
4275
  } finally {
3836
4276
  await handle.close();
3837
4277
  }
3838
- await syncDirectory(dirname3(path), platform);
4278
+ await syncDirectory(dirname4(path), platform);
3839
4279
  }
3840
4280
  async function syncDirectory(path, platform) {
3841
4281
  if (platform === "win32") return;
@@ -3883,29 +4323,46 @@ var HostUsageTranscriptSourceError = class extends Error {
3883
4323
  this.name = "HostUsageTranscriptSourceError";
3884
4324
  }
3885
4325
  };
3886
- async function readHostUsageTranscriptSource(read) {
4326
+ async function readHostUsageTranscriptSource(read2) {
3887
4327
  try {
3888
- return await read();
4328
+ return await read2();
3889
4329
  } catch (error) {
3890
4330
  throw new HostUsageTranscriptSourceError({ cause: error });
3891
4331
  }
3892
4332
  }
3893
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
3894
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
3895
- let failed = false;
3896
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
3897
- const index = (startIndex + attempt) % registrations.length;
3898
- const registration = registrations[index];
3899
- if (registration === void 0) continue;
3900
- try {
3901
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
3902
- } catch (error) {
3903
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4333
+ var HostUsageRegistrationCapture = class {
4334
+ nextIndex = 0;
4335
+ producer;
4336
+ diagnosticSink;
4337
+ constructor(producer, diagnosticSink) {
4338
+ this.producer = producer;
4339
+ this.diagnosticSink = diagnosticSink;
4340
+ }
4341
+ async captureNext(registrations, capture) {
4342
+ let failed = false;
4343
+ let captured = false;
4344
+ const onFailure = () => {
3904
4345
  failed = true;
4346
+ };
4347
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4348
+ const index = (this.nextIndex + attempt) % registrations.length;
4349
+ const registration = registrations[index];
4350
+ if (registration === void 0) continue;
4351
+ try {
4352
+ captured = await capture(registration, onFailure);
4353
+ if (captured) {
4354
+ this.nextIndex = (index + 1) % registrations.length;
4355
+ break;
4356
+ }
4357
+ } catch (error) {
4358
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4359
+ onFailure();
4360
+ }
3905
4361
  }
4362
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
4363
+ return captured;
3906
4364
  }
3907
- return { captured: false, nextIndex: startIndex, failed };
3908
- }
4365
+ };
3909
4366
  async function openHostUsageTranscriptCursor(input) {
3910
4367
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
3911
4368
  let source;
@@ -3976,16 +4433,16 @@ function completeLinePrefix(bytes, baseOffset) {
3976
4433
 
3977
4434
  // host/relay/src/host-registration-state.ts
3978
4435
  import { constants as constants4 } from "node:fs";
3979
- import { dirname as dirname4 } from "node:path";
4436
+ import { dirname as dirname5 } from "node:path";
3980
4437
 
3981
4438
  // host/runtime-source-paths.ts
3982
4439
  import { createHash as createHash6 } from "node:crypto";
3983
- import { posix as posix2, win32 as win323 } from "node:path";
4440
+ import { posix as posix3, win32 as win324 } from "node:path";
3984
4441
 
3985
4442
  // host/absolute-path.ts
3986
- import { posix, win32 as win322 } from "node:path";
4443
+ import { posix as posix2, win32 as win323 } from "node:path";
3987
4444
  function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
3988
- const pathApi = flavor === "win32" || flavor === "windows" ? win322 : posix;
4445
+ const pathApi = flavor === "win32" || flavor === "windows" ? win323 : posix2;
3989
4446
  return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
3990
4447
  }
3991
4448
 
@@ -4029,7 +4486,7 @@ function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
4029
4486
  function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
4030
4487
  const sourceId = hostSourceUuid(sourceRef);
4031
4488
  if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
4032
- const path = platform === "win32" ? win323 : posix2;
4489
+ const path = platform === "win32" ? win324 : posix3;
4033
4490
  const sourcesRoot = path.join(stateRoot, "sources");
4034
4491
  const sourceRoot = path.join(sourcesRoot, sourceId);
4035
4492
  const runtimeRoot = path.join(stateRoot, "run");
@@ -4040,7 +4497,7 @@ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platfor
4040
4497
  function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
4041
4498
  if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
4042
4499
  const digest2 = createHash6("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
4043
- return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix2.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
4500
+ return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix3.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
4044
4501
  }
4045
4502
  function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
4046
4503
  const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
@@ -4068,7 +4525,7 @@ var HostRegistrationStateError = class extends Error {
4068
4525
  async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
4069
4526
  let raw;
4070
4527
  try {
4071
- await assertPrivateRegistrationDirectory(dirname4(path), platform, custody);
4528
+ await assertPrivateRegistrationDirectory(dirname5(path), platform, custody);
4072
4529
  raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
4073
4530
  } catch (error) {
4074
4531
  throw registrationReadError(error);
@@ -4173,185 +4630,6 @@ function waitForAbort(signal, milliseconds) {
4173
4630
  });
4174
4631
  }
4175
4632
 
4176
- // host/service-log.ts
4177
- import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
4178
- import { dirname as dirname5, isAbsolute, posix as posix3, win32 as win324 } from "node:path";
4179
-
4180
- // host/service-log-delivery.ts
4181
- var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
4182
- function createHostServiceLogDelivery(stream, schedule = (flush) => {
4183
- setImmediate(flush);
4184
- }, onDeliveryGap = () => void 0) {
4185
- const pending = [];
4186
- const highWaterMark = stream.writableHighWaterMark;
4187
- const byteBudget = highWaterMark + highWaterMark;
4188
- let pendingBytes = 0;
4189
- let droppedLines = 0;
4190
- let flushScheduled = false;
4191
- let waitingForDrain = false;
4192
- let closed = !stream.writable;
4193
- function stop() {
4194
- if (closed) return;
4195
- closed = true;
4196
- pending.length = 0;
4197
- pendingBytes = 0;
4198
- stream.off("drain", onDrain);
4199
- stream.off("close", onTerminal);
4200
- stream.off("finish", onTerminal);
4201
- stream.off("error", onError);
4202
- }
4203
- function onTerminal() {
4204
- stop();
4205
- }
4206
- function onError() {
4207
- stop();
4208
- }
4209
- function onDrain() {
4210
- waitingForDrain = false;
4211
- scheduleFlush();
4212
- }
4213
- function scheduleFlush() {
4214
- if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
4215
- flushScheduled = true;
4216
- let scheduling = true;
4217
- let invokedSynchronously = false;
4218
- try {
4219
- schedule(() => {
4220
- if (scheduling) {
4221
- invokedSynchronously = true;
4222
- return;
4223
- }
4224
- flushScheduled = false;
4225
- flush();
4226
- });
4227
- } catch {
4228
- flushScheduled = false;
4229
- stop();
4230
- return;
4231
- }
4232
- scheduling = false;
4233
- if (invokedSynchronously) {
4234
- flushScheduled = false;
4235
- stop();
4236
- }
4237
- }
4238
- function flush() {
4239
- if (closed) return;
4240
- if (!stream.writable) {
4241
- stop();
4242
- return;
4243
- }
4244
- while (pending.length > 0) {
4245
- if (stream.writableNeedDrain) {
4246
- if (!waitingForDrain) {
4247
- waitingForDrain = true;
4248
- stream.once("drain", onDrain);
4249
- }
4250
- return;
4251
- }
4252
- const next = pending.shift();
4253
- if (next === void 0) return;
4254
- pendingBytes -= next.bytes;
4255
- let accepted;
4256
- try {
4257
- accepted = stream.write(next.line);
4258
- } catch {
4259
- stop();
4260
- return;
4261
- }
4262
- if (!accepted) {
4263
- waitingForDrain = true;
4264
- stream.once("drain", onDrain);
4265
- return;
4266
- }
4267
- }
4268
- if (droppedLines > 0) {
4269
- const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
4270
- `;
4271
- droppedLines = 0;
4272
- try {
4273
- onDeliveryGap(line);
4274
- } catch {
4275
- }
4276
- pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
4277
- pendingBytes += Buffer.byteLength(line, "utf8");
4278
- flush();
4279
- }
4280
- }
4281
- stream.on("close", onTerminal);
4282
- stream.on("finish", onTerminal);
4283
- stream.on("error", onError);
4284
- return (line) => {
4285
- if (closed) return;
4286
- const bytes = Buffer.byteLength(line, "utf8");
4287
- if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
4288
- droppedLines += 1;
4289
- scheduleFlush();
4290
- return;
4291
- }
4292
- pending.push({ line, bytes });
4293
- pendingBytes += bytes;
4294
- scheduleFlush();
4295
- };
4296
- }
4297
-
4298
- // host/service-log.ts
4299
- var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
4300
- var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
4301
- void persistHostServiceLogLine(line);
4302
- });
4303
- function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
4304
- const details = diagnosticDetails(event, failure_kind, cause);
4305
- const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
4306
- `;
4307
- try {
4308
- (sink ?? defaultHostServiceDiagnosticSink)(line);
4309
- } catch {
4310
- }
4311
- }
4312
- function diagnosticDetails(event, failureKind, cause) {
4313
- if (event === "watcher_scan_failed") return {
4314
- ...failureKind === void 0 ? {} : { failure_kind: failureKind },
4315
- ...validDiagnosticCause(cause, event) ? { cause } : {}
4316
- };
4317
- return validDiagnosticCause(cause, event) ? { cause } : {};
4318
- }
4319
- function validDiagnosticCause(cause, event) {
4320
- return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
4321
- }
4322
- function defaultHostServiceDiagnosticSink(line) {
4323
- writeHostServiceLogLine(line);
4324
- }
4325
- var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
4326
- function writeHostServiceLogLine(line, environment = process.env) {
4327
- void persistHostServiceLogLine(line, environment);
4328
- defaultHostServiceLogDelivery(line);
4329
- }
4330
- async function persistHostServiceLogLine(line, environment = process.env) {
4331
- if (process.platform !== "win32") return;
4332
- const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
4333
- if (path === void 0 || !win324.isAbsolute(path) || win324.normalize(path) !== path) return;
4334
- await appendHostServiceLogLine(path, line).catch(() => void 0);
4335
- }
4336
- async function appendHostServiceLogLine(path, line) {
4337
- if (!isAbsolute(path)) return;
4338
- await ensureHostServiceLogDirectory(path);
4339
- await appendFile(path, line);
4340
- }
4341
- var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
4342
- var hostServiceLogDirectories = /* @__PURE__ */ new Map();
4343
- function ensureHostServiceLogDirectory(path) {
4344
- const directory = dirname5(path);
4345
- const existing = hostServiceLogDirectories.get(directory);
4346
- if (existing !== void 0) return existing;
4347
- const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
4348
- hostServiceLogDirectories.delete(directory);
4349
- throw error;
4350
- });
4351
- hostServiceLogDirectories.set(directory, pending);
4352
- return pending;
4353
- }
4354
-
4355
4633
  // host/relay/src/host-usage-facts-uploader.ts
4356
4634
  var HostUsageFactsUploader = class {
4357
4635
  options;
@@ -4370,7 +4648,7 @@ var HostUsageFactsUploader = class {
4370
4648
  const registration = await readHostRegistrationAuthority(this.options.registration_state_file, this.options.host_source_ref, this.options.store_options?.platform, this.options.store_options?.secure_file_custody);
4371
4649
  const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4372
4650
  const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4373
- const response2 = await (this.options.fetch ?? fetch)(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4651
+ const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4374
4652
  method: "POST",
4375
4653
  headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4376
4654
  body: JSON.stringify(candidate.batch),
@@ -4937,36 +5215,67 @@ var HostInvocationAuthenticationRefusal = class extends Error {
4937
5215
  if (diagnosticCause !== void 0) this.diagnostic_cause = diagnosticCause;
4938
5216
  }
4939
5217
  };
4940
- function installedHostInvocationAuthenticationCommandOptions(config, contextBudgetMs, maxContextWaitMs) {
5218
+ var INSTALLED_HOST_INVOCATION_AUTHENTICATION_DEPENDENCIES = {
5219
+ process_elapsed_ms: () => performance.now(),
5220
+ load_pipe_key: async (outboxDirectory) => process.platform === "win32" ? loadRelayPipeKey(relayPipeStateRootForOutboxDir(outboxDirectory)) : void 0,
5221
+ create_relay_port: (endpoint, pipeKey, timeoutMs) => new HostRelayInvocationContextPort(endpoint, pipeKey, timeoutMs)
5222
+ };
5223
+ function installedHostInvocationAuthenticationCommandOptions(config, contextBudgetMs, maxContextWaitMs, dependencies) {
4941
5224
  let pipeKey;
4942
5225
  const loadPipeKey = () => {
4943
- if (pipeKey === void 0) pipeKey = process.platform === "win32" ? loadRelayPipeKey(relayPipeStateRootForOutboxDir(config.outbox_dir)) : Promise.resolve(void 0);
5226
+ if (pipeKey === void 0) pipeKey = dependencies.load_pipe_key(config.outbox_dir);
4944
5227
  return pipeKey;
4945
5228
  };
5229
+ const remainingBudget = () => remainingAuthenticationBudget(contextBudgetMs, dependencies.process_elapsed_ms());
4946
5230
  return {
4947
5231
  host_source_ref: config.host_source_ref,
4948
5232
  outbox_dir: config.outbox_dir,
4949
5233
  producer_installation_ref: config.producer_installation_ref,
4950
- context_activation_wait_ms: boundedContextActivationWait(contextBudgetMs, config.ipc_timeout_ms, maxContextWaitMs),
4951
- mint_invocation_context: async (input) => new HostRelayInvocationContextPort(config.relay_endpoint, await loadPipeKey(), config.ipc_timeout_ms).mintInvocationContext(input)
5234
+ context_activation_wait_ms: boundedContextActivationWait(remainingBudget() ?? 0, config.ipc_timeout_ms, maxContextWaitMs),
5235
+ monotonic_now: dependencies.process_elapsed_ms,
5236
+ ...dependencies.wait === void 0 ? {} : { wait: dependencies.wait },
5237
+ ...dependencies.output_sink === void 0 ? {} : { output_sink: dependencies.output_sink },
5238
+ ...dependencies.diagnostic_sink === void 0 ? {} : { diagnostic_sink: dependencies.diagnostic_sink },
5239
+ mint_invocation_context: async (input) => {
5240
+ requireMintExchangeTimeout(remainingBudget(), config.ipc_timeout_ms);
5241
+ const loadedPipeKey = await loadPipeKey();
5242
+ const timeoutMs = requireMintExchangeTimeout(remainingBudget(), config.ipc_timeout_ms);
5243
+ return dependencies.create_relay_port(config.relay_endpoint, loadedPipeKey, timeoutMs).mintInvocationContext(input);
5244
+ }
4952
5245
  };
4953
5246
  }
4954
- async function runHostInvocationAuthenticationCommand(descriptor, args, options) {
5247
+ function remainingAuthenticationBudget(contextBudgetMs, processElapsedMs) {
5248
+ if (contextBudgetMs === void 0) return void 0;
5249
+ return Math.max(0, Math.floor(contextBudgetMs - processElapsedMs));
5250
+ }
5251
+ function requireMintExchangeTimeout(remainingBudgetMs, directTimeoutMs) {
5252
+ if (remainingBudgetMs === void 0) return directTimeoutMs;
5253
+ const timeoutMs = remainingBudgetMs - HOST_AUTHENTICATION_COMPLETION_RESERVE_MS;
5254
+ if (timeoutMs <= 0) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC timed out before minting could start.", "timed_out");
5255
+ return timeoutMs;
5256
+ }
5257
+ async function runHostInvocationAuthenticationCommand(descriptor, args, options, installedDependencies = INSTALLED_HOST_INVOCATION_AUTHENTICATION_DEPENDENCIES) {
4955
5258
  let sink = options?.output_sink;
5259
+ let diagnosticSink = options?.diagnostic_sink;
4956
5260
  try {
4957
- const resolved = await resolveOptions(descriptor, args, options);
5261
+ const resolved = await resolveOptions(descriptor, args, options, installedDependencies);
4958
5262
  sink = resolved.options.output_sink;
5263
+ diagnosticSink = resolved.options.diagnostic_sink;
4959
5264
  writeResult(await authenticateHostInvocation(descriptor, resolved.input, resolved.options), sink);
4960
5265
  return 0;
4961
5266
  } catch (error) {
4962
- const reason = authenticationRefusalReason(error);
4963
- const refusal = error instanceof HostInvocationAuthenticationRefusal ? error : void 0;
4964
- const gatewayStatus = refusal?.reason === "gateway_refused" && validGenericGatewayRefusalStatus2(refusal.gateway_status) ? refusal.gateway_status : void 0;
4965
- writeHostServiceDiagnostic(descriptor.producer_id, "invocation_authentication_failed", void 0, refusal?.diagnostic_cause ?? reason, options?.diagnostic_sink);
4966
- writeResult({ schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA, ok: false, code: "invocation_authentication_unavailable", reason, ...gatewayStatus === void 0 ? {} : { gateway_status: gatewayStatus } }, sink);
4967
- return 2;
5267
+ return writeAuthenticationFailure(descriptor.producer_id, error, sink, diagnosticSink);
4968
5268
  }
4969
5269
  }
5270
+ function writeAuthenticationFailure(producerId, error, sink, diagnosticSink) {
5271
+ const reason = authenticationRefusalReason(error);
5272
+ const refusal = error instanceof HostInvocationAuthenticationRefusal ? error : void 0;
5273
+ const gatewayStatus = refusal?.reason === "gateway_refused" && validGenericGatewayRefusalStatus2(refusal.gateway_status) ? refusal.gateway_status : void 0;
5274
+ const retryAfterMs = reason === "activation_wait_exhausted" ? INVOCATION_CONTEXT_POLL_INTERVAL_MS : void 0;
5275
+ writeHostServiceDiagnostic(producerId, "invocation_authentication_failed", void 0, refusal?.diagnostic_cause ?? reason, diagnosticSink);
5276
+ writeResult({ schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA, ok: false, code: "invocation_authentication_unavailable", reason, ...gatewayStatus === void 0 ? {} : { gateway_status: gatewayStatus }, ...retryAfterMs === void 0 ? {} : { retry_after_ms: retryAfterMs } }, sink);
5277
+ return 2;
5278
+ }
4970
5279
  function authenticationRefusalReason(error) {
4971
5280
  const message = error instanceof Error ? error.message : "";
4972
5281
  if (!REFUSAL_REASON_PATTERN.test(message)) return "host_refusal_invalid";
@@ -5030,8 +5339,7 @@ async function currentInvocation(descriptor, config, now) {
5030
5339
  let waitEngaged = false;
5031
5340
  while (true) {
5032
5341
  if (!firstCheck && monotonicNow() >= deadline) {
5033
- recordActivationWaitExhaustion(descriptor.producer_id, waitEngaged, waitBudgetMs, config.diagnostic_sink);
5034
- throw new TypeError("context_unavailable");
5342
+ throw activationWaitExhausted(descriptor.producer_id, waitEngaged, waitBudgetMs, config.diagnostic_sink);
5035
5343
  }
5036
5344
  firstCheck = false;
5037
5345
  const observedAt = now();
@@ -5043,8 +5351,7 @@ async function currentInvocation(descriptor, config, now) {
5043
5351
  await rejectWhenActivationWaitIsUnavailable(descriptor, store, identity.identity, waitEngaged, waitBudgetMs, config.diagnostic_sink);
5044
5352
  const remainingMs = deadline - monotonicNow();
5045
5353
  if (remainingMs <= 0) {
5046
- recordActivationWaitExhaustion(descriptor.producer_id, waitEngaged, waitBudgetMs, config.diagnostic_sink);
5047
- throw new TypeError("context_unavailable");
5354
+ throw activationWaitExhausted(descriptor.producer_id, waitEngaged, waitBudgetMs, config.diagnostic_sink);
5048
5355
  }
5049
5356
  recordActivationWaitEngagement(descriptor.producer_id, waitEngaged, config.diagnostic_sink);
5050
5357
  waitEngaged = true;
@@ -5052,9 +5359,13 @@ async function currentInvocation(descriptor, config, now) {
5052
5359
  await (config.wait ?? waitForContextActivation)(intervalMs);
5053
5360
  }
5054
5361
  }
5362
+ function activationWaitExhausted(producerId, waitEngaged, waitBudgetMs, diagnosticSink) {
5363
+ recordActivationWaitExhaustion(producerId, waitEngaged, waitBudgetMs, diagnosticSink);
5364
+ return new TypeError(waitEngaged ? "activation_wait_exhausted" : "context_unavailable");
5365
+ }
5055
5366
  async function rejectWhenActivationWaitIsUnavailable(descriptor, store, identity, waitEngaged, waitBudgetMs, sink) {
5056
- if (waitEngaged || waitBudgetMs <= 0 || descriptor.can_wait_for_context_activation === void 0) return;
5057
- if (await descriptor.can_wait_for_context_activation({ store, identity })) return;
5367
+ if (waitEngaged || waitBudgetMs <= 0) return;
5368
+ if (descriptor.can_wait_for_context_activation !== void 0 && await descriptor.can_wait_for_context_activation({ store, identity })) return;
5058
5369
  writeHostServiceDiagnostic(descriptor.producer_id, "activation_wait_skipped", void 0, void 0, sink);
5059
5370
  throw new TypeError("context_unavailable");
5060
5371
  }
@@ -5083,18 +5394,18 @@ function resolveIdentity(descriptor, options) {
5083
5394
  if (isHostSessionId(sessionId)) return { status: "ready", identity: { host_source_ref: options.host_source_ref, host_session_ref: descriptor.session_ref(options.host_source_ref, sessionId) } };
5084
5395
  return { status: "session_unavailable" };
5085
5396
  }
5086
- async function resolveOptions(descriptor, args, options) {
5397
+ async function resolveOptions(descriptor, args, options, installedDependencies) {
5087
5398
  if (options !== void 0) return { input: [...args], options };
5088
5399
  const configPath = descriptor.parse_config_flag(args);
5089
5400
  const config = await descriptor.read_producer_config(configPath);
5090
5401
  return {
5091
5402
  input: args.filter((argument) => !argument.startsWith(`${descriptor.config_flag}=`)),
5092
- options: installedHostInvocationAuthenticationCommandOptions(config, authenticationBudgetMsFromEnvironment(), descriptor.context_activation_wait_max_ms)
5403
+ options: installedHostInvocationAuthenticationCommandOptions(config, authenticationBudgetMsFromEnvironment(), descriptor.context_activation_wait_max_ms, installedDependencies)
5093
5404
  };
5094
5405
  }
5095
5406
  function authenticationBudgetMsFromEnvironment() {
5096
5407
  const value = process.env[CEAL_HOST_AUTHENTICATION_BUDGET_ENVIRONMENT];
5097
- if (value === void 0) return 0;
5408
+ if (value === void 0) return void 0;
5098
5409
  if (!CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN.test(value)) throw new TypeError("invalid_arguments");
5099
5410
  return Number(value);
5100
5411
  }
@@ -5307,7 +5618,7 @@ function parseCanonicalJson(text, error) {
5307
5618
  if (canonical !== text.trim()) throw new Error(`noncanonical: ${refusalFacts([{ name: "config_bytes", value: Buffer.byteLength(text.trim(), "utf8"), expected: `the ${Buffer.byteLength(canonical, "utf8")} bytes of its canonical form` }, { name: "first_difference_index", value: firstDifferenceIndex(text.trim(), canonical) }])}`);
5308
5619
  return value;
5309
5620
  } catch (parseError) {
5310
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
5621
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
5311
5622
  }
5312
5623
  }
5313
5624
  function firstDifferenceIndex(left, right) {
@@ -5722,6 +6033,13 @@ var ClaudeOutboxStore = class {
5722
6033
  await this.removeStateFile(this.registrationPath(registration.host_source_ref, registration.host_session_ref));
5723
6034
  await this.removeStateFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref));
5724
6035
  }
6036
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
6037
+ if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
6038
+ await this.prepare();
6039
+ const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
6040
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw new ClaudeHostError("storage", "Claude transcript registration identity does not match its session.");
6041
+ return registration;
6042
+ }
5725
6043
  async listTranscriptRegistrations() {
5726
6044
  await this.prepare();
5727
6045
  const registrations = [];
@@ -5991,10 +6309,42 @@ var ClaudeProducer = class {
5991
6309
 
5992
6310
  // host/claude/src/claude-transcript-watcher.ts
5993
6311
  import { readdir as readdir2 } from "node:fs/promises";
6312
+ import { isDeepStrictEqual } from "node:util";
5994
6313
  import { join as join6 } from "node:path";
6314
+
6315
+ // host/claude/src/claude-subagent-overflow-checkpoint.ts
6316
+ var ClaudeSubagentOverflowCheckpoint = class {
6317
+ observed = /* @__PURE__ */ new Map();
6318
+ prune(registrations) {
6319
+ const current = new Set(registrations.map(registrationKey));
6320
+ for (const key of this.observed.keys()) if (!current.has(key)) this.observed.delete(key);
6321
+ }
6322
+ clear(registration) {
6323
+ this.observed.delete(registrationKey(registration));
6324
+ }
6325
+ /** Names follow the producer's sorted inventory; only omitted names define overflow. */
6326
+ async observe(registration, names, report) {
6327
+ const key = registrationKey(registration);
6328
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
6329
+ this.clear(registration);
6330
+ return false;
6331
+ }
6332
+ const digest2 = transcriptObjectSha256(names.slice(CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES));
6333
+ if (this.observed.get(key) === digest2) return false;
6334
+ if (!await report()) return false;
6335
+ this.observed.set(key, digest2);
6336
+ return true;
6337
+ }
6338
+ };
6339
+ function registrationKey(registration) {
6340
+ return JSON.stringify([registration.host_source_ref, registration.host_session_ref, registration.transcript_path]);
6341
+ }
6342
+
6343
+ // host/claude/src/claude-transcript-watcher.ts
5995
6344
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
5996
6345
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5997
6346
  store;
6347
+ overflow = new ClaudeSubagentOverflowCheckpoint();
5998
6348
  diagnostic;
5999
6349
  constructor(options) {
6000
6350
  super(options, {
@@ -6009,17 +6359,21 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6009
6359
  return registration.transcript_path;
6010
6360
  }
6011
6361
  async listRegistrations() {
6012
- return this.store.listTranscriptRegistrations();
6362
+ const registrations = await this.store.listTranscriptRegistrations();
6363
+ this.overflow.prune(registrations);
6364
+ return registrations;
6013
6365
  }
6014
6366
  async scanOpened(handle, registration) {
6015
6367
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
6016
- const cursor = await this.preflight(registration, handle, size, device, inode);
6368
+ const preflight = await this.preflight(registration, handle, size, device, inode);
6369
+ const cursor = preflight.cursor;
6017
6370
  if (cursor === null) return { records: 0, enqueued: 0, quarantined: true };
6018
6371
  if (cursor.status === "quarantined") {
6019
6372
  return { records: 0, enqueued: 0, quarantined: true };
6020
6373
  }
6374
+ if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
6021
6375
  const draft = mutableCursor(cursor);
6022
- await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
6376
+ await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
6023
6377
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
6024
6378
  }
6025
6379
  async scanFailed(handle, registration, error) {
@@ -6030,6 +6384,15 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6030
6384
  return { records: 0, enqueued: 0, quarantined: true };
6031
6385
  }
6032
6386
  async retireMissing(registration) {
6387
+ const observedAt = this.stamp();
6388
+ if (Date.parse(registration.expires_at) <= Date.parse(observedAt)) return this.retireTranscript(registration);
6389
+ const cursor = await this.store.readTranscriptCursor(registration);
6390
+ if (cursor !== null && isUnmaterializedCursor(cursor, this.sha(Buffer.alloc(0)))) {
6391
+ return { records: 0, enqueued: 0, quarantined: false };
6392
+ }
6393
+ return this.retireTranscript(registration);
6394
+ }
6395
+ retireTranscript(registration) {
6033
6396
  return this.retireMissingTranscript(registration.transcript_path, "Claude", () => this.store.retireTranscriptRegistration(registration));
6034
6397
  }
6035
6398
  initialCursor(registration) {
@@ -6047,7 +6410,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6047
6410
  updated_at: this.stamp()
6048
6411
  };
6049
6412
  }
6050
- async scanOpenedTranscript(registration, handle, draft, size, device, inode) {
6413
+ async scanOpenedTranscript(registration, handle, previous, draft, size, device, inode) {
6051
6414
  const main2 = await this.readChunk(handle, draft.offset, size);
6052
6415
  if (main2 !== "empty" && main2 !== "partial") {
6053
6416
  await this.consumeMainChunk(registration, main2, draft);
@@ -6055,20 +6418,22 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6055
6418
  }
6056
6419
  draft.consumed += await this.consumeSubagents(registration, draft);
6057
6420
  await this.emitOpenTerminal(registration, draft);
6058
- await this.commitCursor(registration, handle, draft, device, inode);
6421
+ await this.commitCursor(registration, handle, previous, draft, device, inode);
6059
6422
  }
6060
6423
  async preflight(registration, handle, size, device, inode) {
6061
6424
  const existing = await this.store.readTranscriptCursor(registration);
6062
- if (existing?.status === "quarantined") return existing;
6425
+ if (existing?.status === "quarantined") return { cursor: existing, checkpointPending: false };
6063
6426
  const cursor = existing ?? this.initialCursor(registration);
6064
6427
  if (cursor.device === void 0) {
6065
- if (cursor.offset !== 0) return await this.quarantineStored(cursor, device, inode, "transcript_replaced");
6066
- return { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
6428
+ const pinned = { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
6429
+ const reason2 = this.cursorIdentityReason(pinned, registration.transcript_path, device, inode);
6430
+ if (cursor.offset !== 0 || reason2 !== null) return { cursor: await this.quarantineStored(cursor, device, inode, "transcript_replaced"), checkpointPending: false };
6431
+ return { cursor: pinned, checkpointPending: true };
6067
6432
  }
6068
6433
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
6069
- if (reason !== null) return await this.quarantineStored(cursor, device, inode, reason);
6070
- if (cursor.human_message_window !== void 0) return cursor;
6071
- return { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) };
6434
+ if (reason !== null) return { cursor: await this.quarantineStored(cursor, device, inode, reason), checkpointPending: false };
6435
+ if (cursor.human_message_window !== void 0) return { cursor, checkpointPending: false };
6436
+ return { cursor: { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) }, checkpointPending: true };
6072
6437
  }
6073
6438
  async readHumanMessageProjection(registration, handle, watermark) {
6074
6439
  let offset = 0;
@@ -6213,15 +6578,24 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6213
6578
  try {
6214
6579
  names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
6215
6580
  } catch (error) {
6216
- if (isMissingTranscriptError(error) || isNotDirectory(error)) return 0;
6581
+ if (isMissingTranscriptError(error) || isNotDirectory(error)) {
6582
+ this.overflow.clear(registration);
6583
+ return 0;
6584
+ }
6217
6585
  throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
6218
6586
  }
6219
6587
  const listed = new Set(names);
6220
6588
  for (const name of Object.keys(draft.subagents)) if (!listed.has(name)) delete draft.subagents[name];
6221
- if (names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
6222
- this.log(`Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`);
6223
- names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
6224
- }
6589
+ await this.overflow.observe(registration, names, () => {
6590
+ const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
6591
+ try {
6592
+ this.log(line);
6593
+ } catch {
6594
+ return false;
6595
+ }
6596
+ return true;
6597
+ });
6598
+ names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
6225
6599
  let consumed = 0;
6226
6600
  for (const name of names) {
6227
6601
  consumed += await this.consumeSubagentFile(draft, directory, name);
@@ -6310,9 +6684,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6310
6684
  expires_at: this.expire(this.outboxRetentionMs)
6311
6685
  });
6312
6686
  }
6313
- async commitCursor(registration, handle, draft, device, inode) {
6687
+ async commitCursor(registration, handle, previous, draft, device, inode) {
6314
6688
  const anchor = await this.readAnchor(handle, draft.offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
6315
- await this.store.writeTranscriptCursor({
6689
+ const cursor = {
6316
6690
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
6317
6691
  host_source_ref: registration.host_source_ref,
6318
6692
  host_session_ref: registration.host_session_ref,
@@ -6329,7 +6703,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6329
6703
  ...draft.session_observed ? { session_observed: true } : {},
6330
6704
  status: "active",
6331
6705
  updated_at: this.stamp()
6332
- });
6706
+ };
6707
+ if (sameCursorContent(cursor, previous)) return;
6708
+ await this.store.writeTranscriptCursor(cursor);
6333
6709
  }
6334
6710
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
6335
6711
  try {
@@ -6365,6 +6741,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6365
6741
  return await this.store.readTranscriptCursor(registration).catch(() => null) ?? this.initialCursor(registration);
6366
6742
  }
6367
6743
  };
6744
+ function isUnmaterializedCursor(cursor, emptyAnchorSha256) {
6745
+ return cursor.status === "active" && cursor.device === void 0 && cursor.inode === void 0 && cursor.offset === 0 && cursor.anchor_start === 0 && cursor.anchor_sha256 === emptyAnchorSha256;
6746
+ }
6368
6747
  function mutableCursor(cursor) {
6369
6748
  return {
6370
6749
  offset: cursor.offset,
@@ -6377,6 +6756,9 @@ function mutableCursor(cursor) {
6377
6756
  enqueued: 0
6378
6757
  };
6379
6758
  }
6759
+ function sameCursorContent(left, right) {
6760
+ return isDeepStrictEqual({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
6761
+ }
6380
6762
  function zeroCounts() {
6381
6763
  return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
6382
6764
  }
@@ -6507,11 +6889,14 @@ function isSymlinkTranscript(error) {
6507
6889
  }
6508
6890
 
6509
6891
  // host/claude/src/claude-producer-runtime.ts
6510
- async function drainClaudeProducerOnce(options) {
6511
- const scan = await new ClaudeTranscriptWatcher({
6512
- outbox_dir: options.outbox_dir,
6892
+ function createClaudeProducerWatcher(outboxDir) {
6893
+ return new ClaudeTranscriptWatcher({
6894
+ outbox_dir: outboxDir,
6513
6895
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
6514
- }).scanOnce().catch((error) => {
6896
+ });
6897
+ }
6898
+ async function drainClaudeProducerOnce(options) {
6899
+ const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
6515
6900
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
6516
6901
  throw error;
6517
6902
  });
@@ -6528,25 +6913,20 @@ var ClaudeUsageFactsCapturer = class {
6528
6913
  sources;
6529
6914
  usage;
6530
6915
  now;
6531
- diagnosticSink;
6532
- nextRegistrationIndex = 0;
6916
+ registrations;
6533
6917
  nextSourceSlot = "main";
6534
6918
  nextSubagentIndex = 0;
6919
+ overflow = new ClaudeSubagentOverflowCheckpoint();
6535
6920
  constructor(options) {
6536
6921
  this.sources = new ClaudeOutboxStore(options.outbox_dir);
6537
6922
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
6538
6923
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
6539
- this.diagnosticSink = options.diagnostic_sink;
6924
+ this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
6540
6925
  }
6541
6926
  async captureNext() {
6542
6927
  const registrations = await this.sources.listTranscriptRegistrations();
6543
- let failed = false;
6544
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
6545
- failed = true;
6546
- }));
6547
- this.nextRegistrationIndex = result.nextIndex;
6548
- if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
6549
- return result.captured;
6928
+ this.overflow.prune(registrations);
6929
+ return await this.registrations.captureNext(registrations, (registration, onFailure) => this.captureRegistration(registration, onFailure));
6550
6930
  }
6551
6931
  async captureRegistration(registration, onFailure) {
6552
6932
  const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
@@ -6593,13 +6973,14 @@ var ClaudeUsageFactsCapturer = class {
6593
6973
  }
6594
6974
  async captureSubagent(registration, onFailure) {
6595
6975
  const names = await readSubagentNames(registration);
6976
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
6596
6977
  let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
6597
6978
  if (state === null) return false;
6598
6979
  state = await this.usage.recoverPending(state);
6599
6980
  if (state.quarantined_reason !== void 0) return false;
6600
6981
  if (await this.retireMissingSubagent(state, names)) return true;
6601
6982
  if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
6602
- return await this.recordExcessSubagentGap(state, names);
6983
+ return await this.recordExcessSubagentGap(registration, state, names);
6603
6984
  }
6604
6985
  async retireMissingSubagent(state, names) {
6605
6986
  const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
@@ -6610,14 +6991,14 @@ var ClaudeUsageFactsCapturer = class {
6610
6991
  }
6611
6992
  return false;
6612
6993
  }
6613
- async recordExcessSubagentGap(state, names) {
6614
- const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
6615
- if (excessCount <= 0) return false;
6994
+ async recordExcessSubagentGap(registration, state, names) {
6616
6995
  const mainCursor = state.cursors.main;
6617
6996
  if (mainCursor === void 0) return false;
6618
- const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
6619
- await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
6620
- return true;
6997
+ return await this.overflow.observe(registration, names, async () => {
6998
+ const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES };
6999
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
7000
+ return true;
7001
+ });
6621
7002
  }
6622
7003
  async captureListedSubagents(registration, names, state, onFailure) {
6623
7004
  const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
@@ -6898,11 +7279,11 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
6898
7279
  producer_id: "claude",
6899
7280
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
6900
7281
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
6901
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
7282
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createClaudeProducerWatcher(config.outbox_dir) }),
6902
7283
  drain: drainClaudeProducerOnce,
6903
- background: (config, signal) => {
7284
+ background: (config, signal, dependencies) => {
6904
7285
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
6905
- return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext() }, signal);
7286
+ return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext(), fetch: dependencies.fetch }, signal);
6906
7287
  }
6907
7288
  };
6908
7289
 
@@ -6972,7 +7353,7 @@ function runClaudeInvocationAuthenticationCommand(args, options) {
6972
7353
  return runHostInvocationAuthenticationCommand(CLAUDE_INVOCATION_AUTHENTICATION_DESCRIPTOR, args, options);
6973
7354
  }
6974
7355
  async function readClaudeInvocationHumanMessageWindow(input) {
6975
- return readRegisteredHostInvocationHumanMessageWindow(() => input.store.listTranscriptRegistrations(), (registration) => input.store.readTranscriptCursor(registration), input.identity, (line, registration) => {
7356
+ return readRegisteredHostInvocationHumanMessageWindow((identity) => input.store.readTranscriptRegistration(identity.host_source_ref, identity.host_session_ref), (registration) => input.store.readTranscriptCursor(registration), input.identity, (line, registration) => {
6976
7357
  let row;
6977
7358
  try {
6978
7359
  row = JSON.parse(line);
@@ -7110,7 +7491,7 @@ async function inspectExecutable(options, environment, component) {
7110
7491
  try {
7111
7492
  executable = await (options.resolve_executable ?? resolveCealExecutable)(options.executable ?? "ceal", environment);
7112
7493
  } catch (error) {
7113
- return inspectedFailure("ceal_unavailable", `The ${component} Host cannot resolve an executable Ceal client from its current environment (${refusalFact("error", error)}).`, `Install the intended Ceal client in the Host PATH, restart ${component}, and run this doctor again.`);
7494
+ return inspectedFailure("ceal_unavailable", `The ${component} Host cannot resolve an executable Ceal client from its current environment (${renderOperatorDiagnostic(error)}).`, `Install the intended Ceal client in the Host PATH, restart ${component}, and run this doctor again.`);
7114
7495
  }
7115
7496
  if (!validExpectations(options) || options.expected_sha256 !== void 0 && executable.sha256 !== options.expected_sha256) return inspectedFailure("ceal_identity_mismatch", `The Ceal executable visible to the ${component} Host does not match the intended candidate.`, `Install the exact candidate bytes, restart ${component}, and run this doctor with the expected identity.`);
7116
7497
  return { ok: true, value: executable };