@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.
@@ -4,6 +4,7 @@ const require = __cealCreateRequire(import.meta.url);
4
4
 
5
5
  // host/claude/src/claude-types.ts
6
6
  var CLAUDE_HOOK_EVENTS = ["SessionStart", "UserPromptSubmit"];
7
+ var CLAUDE_SESSION_ID_ENVIRONMENT = "CLAUDE_CODE_SESSION_ID";
7
8
  var CLAUDE_HOST_ERROR_CODES = ["invalid_input", "payload_rejected", "storage", "configuration"];
8
9
  function isClaudeHostErrorCode(value) {
9
10
  return typeof value === "string" && CLAUDE_HOST_ERROR_CODES.some((code2) => code2 === value);
@@ -36,6 +37,15 @@ function isClaudeHookEvent(value) {
36
37
  import { createHash as createHash4 } from "node:crypto";
37
38
  import { isAbsolute } from "node:path";
38
39
 
40
+ // packages/ceal-client-protocol/src/vocabulary.ts
41
+ function vocabulary(words) {
42
+ return Object.freeze(words);
43
+ }
44
+
45
+ // packages/ceal-client-protocol/src/host-usage-fields.ts
46
+ var CEAL_CODEX_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
47
+ var CEAL_CLAUDE_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"]);
48
+
39
49
  // packages/ceal-client-protocol/src/canonical-json.ts
40
50
  function cealCanonicalJson(value) {
41
51
  if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
@@ -110,7 +120,7 @@ var client_wire_contract_default = {
110
120
  },
111
121
  command_request: {
112
122
  schema_name: "ceal.command_request",
113
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
123
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
114
124
  absolute_transport_max_bytes: 65536
115
125
  },
116
126
  command_resolution: {
@@ -156,7 +166,7 @@ var client_wire_contract_default = {
156
166
  },
157
167
  command_response: {
158
168
  schema_name: "ceal.command_response",
159
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
169
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
160
170
  descriptor_field: "verified_artifact",
161
171
  request_context_field: "request_context",
162
172
  required_fields: [
@@ -169,7 +179,8 @@ var client_wire_contract_default = {
169
179
  "visible_output_max_bytes",
170
180
  "local_delivery",
171
181
  "verified_artifact",
172
- "request_context"
182
+ "request_context",
183
+ "result_file"
173
184
  ],
174
185
  bare_document_fields: [
175
186
  "invocation",
@@ -210,8 +221,11 @@ var client_wire_contract_default = {
210
221
  "ok",
211
222
  "code",
212
223
  "reason",
213
- "gateway_status"
224
+ "gateway_status",
225
+ "retry_after_ms"
214
226
  ],
227
+ refusal_required_fields: ["schema_version", "ok", "code", "reason"],
228
+ refusal_optional_fields: ["gateway_status", "retry_after_ms"],
215
229
  client_nonce: {
216
230
  character_class_source: "A-Za-z0-9_-",
217
231
  encoded_characters: 43
@@ -430,16 +444,14 @@ var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
430
444
  personal_authorization_required: "connect_personal_account"
431
445
  });
432
446
 
433
- // packages/ceal-client-protocol/src/vocabulary.ts
434
- function vocabulary(words) {
435
- return Object.freeze(words);
436
- }
437
-
438
447
  // packages/ceal-client-protocol/src/gateway-response-types.ts
439
448
  var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
440
449
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
441
450
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
442
451
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
452
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
453
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
454
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
443
455
  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"]);
444
456
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
445
457
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -480,6 +492,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
480
492
  ]);
481
493
 
482
494
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
495
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
496
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
497
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
498
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
499
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
500
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
501
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
502
+ function escapePathPattern(value) {
503
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
504
+ }
505
+ function machineHomePathPatterns(flags) {
506
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
507
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
508
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
509
+ }
483
510
  var CealProtocolValidationError = class extends Error {
484
511
  name = "CealProtocolValidationError";
485
512
  code;
@@ -833,8 +860,9 @@ var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask a
833
860
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
834
861
  var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
835
862
  var HOST_INSTALL_REPAIR = "The local Host or Relay is missing, stale, or unavailable. Run `ceal-host install`, then `ceal-host discovery sync`, and retry from a new producer conversation.";
836
- var HOST_CONTEXT_UNAVAILABLE = "The Host could not select or activate the current recorded turn. This does not explain why or prove ephemerality. For an independently identified ephemeral Codex side conversation, invoke the command as `ceal --standalone ...`; it uses the local Ceal session and Gateway permissions without Host session/turn audit linkage. Host refusal never switches modes. For intended Host calls, restart the producer and start a new conversation; report the error if it persists.";
863
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
837
864
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
865
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
838
866
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
839
867
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
840
868
  }
@@ -855,13 +883,18 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
855
883
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
856
884
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
857
885
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
858
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
859
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
860
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
861
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
862
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
863
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
864
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
886
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
887
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
888
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
889
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
890
+ 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),
891
+ 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),
892
+ 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),
893
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
894
+ 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),
895
+ 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),
896
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
897
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
865
898
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
866
899
  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),
867
900
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -876,23 +909,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
876
909
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
877
910
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
878
911
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
879
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
880
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
881
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
882
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
912
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
913
+ [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),
883
914
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
884
915
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
885
916
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
886
917
  internal_error: guidance("The Gateway failed without exposing internal state.", "answer_with_gap", 500),
887
918
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
888
- // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
919
+ // the static client variant was retired when the client started reading this table.
889
920
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
890
921
  gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
891
- // Restored verbatim from the retired `localFailureText` `unknown_outcome`
892
- // case: the outcome is unknown, so a read may be retried while a write
893
- // must receipt-check first. Collapsing both to "do not repeat the call"
894
- // forbids the safe read retry the sentence exists to allow.
895
- 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),
922
+ // The safe move varies by request. Keep the sentence conditional on the
923
+ // same `retryable` and `next_action` facts the response exposes.
924
+ unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
925
+ // 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.
926
+ 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),
896
927
  // Restored verbatim from the retired `localFailureText`
897
928
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
898
929
  // session context unavailable, so the caller repairs or adopts the
@@ -973,8 +1004,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
973
1004
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
974
1005
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
975
1006
  // is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
976
- // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). Cause-specific
977
- // sentences carry the retired policy remedies; `gateway_refused` reuses the release-upgrade guidance above.
1007
+ // and `retryable` from `hostAuthenticationFailureForCause` (the table's explicit retry verdict). Cause-specific
1008
+ // sentences carry only remedies proved by the Host or Relay cause; generic Gateway refusals do not prove a release mismatch.
978
1009
  // Statuses are the
979
1010
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
980
1011
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
@@ -984,21 +1015,23 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
984
1015
  // The bounded Host reason does not prove ephemerality. A Host refusal never
985
1016
  // changes mode; standalone remains the separate Client authority path.
986
1017
  host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
987
- host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
988
- host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
1018
+ 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),
1019
+ 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),
1020
+ 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),
989
1021
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
990
1022
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
991
1023
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
992
1024
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
993
- host_mint_gateway_refused: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
1025
+ host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
994
1026
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1027
+ host_contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
995
1028
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
996
1029
  // producer-frame fault names the administrator repair step.
997
1030
  host_producer_frame_invalid: guidance("Ask an administrator to inspect and repair the producer frame, then start a fresh Host turn.", "ask_admin", 400),
998
1031
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
999
1032
  // sandboxed Relay socket names the run-alone retry.
1000
1033
  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),
1001
- host_relay_unavailable: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 503),
1034
+ host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1002
1035
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
1003
1036
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
1004
1037
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1036,7 +1069,7 @@ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
1036
1069
  var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
1037
1070
  var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
1038
1071
  var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
1039
- var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
1072
+ var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_applicable", "not_offered", "offered", "accepted", "rejected", "unknown"]);
1040
1073
  var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
1041
1074
  var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
1042
1075
  var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
@@ -1207,6 +1240,7 @@ var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
1207
1240
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
1208
1241
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
1209
1242
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
1243
+ var CEAL_PROVIDER_BOUNDARY_FIELDS = vocabulary(["provider_boundary_ref", "provider_boundary_kind", "provider_boundary_label", "provider_native_id", "provider_boundary_evidence"]);
1210
1244
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
1211
1245
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
1212
1246
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1252,7 +1286,7 @@ var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1252
1286
  var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
1253
1287
  var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
1254
1288
  var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
1255
- var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
1289
+ var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary", "standard_names"]);
1256
1290
 
1257
1291
  // packages/ceal-client-protocol/src/operation-catalog.ts
1258
1292
  var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
@@ -1348,6 +1382,7 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1348
1382
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
1349
1383
  gateway_access_group_connector_calendar_scope_audit: (root) => join(root, "profile-connector-calendar-scope-audit.jsonl"),
1350
1384
  gateway_access_group_connector_readiness_audit: (root) => join(root, "profile-connector-readiness.audit.jsonl"),
1385
+ gateway_deployment_events: (root) => join(root, "gateway-deployments.jsonl"),
1351
1386
  gateway_organization_audit_ledger: (root) => join(root, "organization-ledger.jsonl"),
1352
1387
  gateway_personal_client_audit: (root) => join(root, "audit.jsonl"),
1353
1388
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
@@ -1374,6 +1409,11 @@ var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_L
1374
1409
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1375
1410
  var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1376
1411
 
1412
+ // packages/ceal-client-protocol/src/resource-read-result.ts
1413
+ var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
1414
+ var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
1415
+ var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1416
+
1377
1417
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
1378
1418
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
1379
1419
 
@@ -1458,6 +1498,7 @@ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1458
1498
  { provider: "google-workspace", result_kind: "calendar_event_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "htmlLink", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
1459
1499
  { provider: "google-workspace", result_kind: "drive_document_calendar_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink or htmlLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
1460
1500
  { 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" },
1501
+ { 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" },
1461
1502
  { provider: "google-workspace", result_kind: "spreadsheet_write_result", field: "spreadsheet_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
1462
1503
  { provider: "google-workspace", result_kind: "calendar_meet_link_write_result", field: "meet_url", status: "required_when_provider_supplies", provider_shape: "verified conferenceData entryPoint uri", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
1463
1504
  { 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" },
@@ -1532,6 +1573,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1532
1573
  "review_submitted",
1533
1574
  "comment_created",
1534
1575
  "reaction_created",
1576
+ "pull_request_merged",
1577
+ "release_published",
1535
1578
  "ceal_write_completed",
1536
1579
  "event_start",
1537
1580
  "all_day_start",
@@ -1543,7 +1586,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1543
1586
  "page_last_edited",
1544
1587
  "resource_modified"
1545
1588
  ]);
1546
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
1589
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
1547
1590
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
1548
1591
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
1549
1592
  "provider_page_budget",
@@ -1564,6 +1607,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1564
1607
  "github.pull_request.opened",
1565
1608
  "github.issue.edited",
1566
1609
  "github.pull_request.edited",
1610
+ "github.pull_request.merged",
1611
+ "github.release.published",
1567
1612
  "github.review.submitted",
1568
1613
  "github.issue_comment.created",
1569
1614
  "github.review_comment.created",
@@ -1577,6 +1622,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1577
1622
  "drive.file.created",
1578
1623
  "drive.file.modified",
1579
1624
  "drive.file.viewed",
1625
+ "mail.sent",
1580
1626
  "notion.page.created",
1581
1627
  "notion.page.edited"
1582
1628
  ]);
@@ -1590,6 +1636,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1590
1636
  "github.review_comment.created": "comment_created",
1591
1637
  "github.issue.opened": "resource_created",
1592
1638
  "github.pull_request.opened": "resource_created",
1639
+ "github.pull_request.merged": "pull_request_merged",
1640
+ "github.release.published": "release_published",
1593
1641
  "github.issue.edited": "resource_modified",
1594
1642
  "github.pull_request.edited": "resource_modified",
1595
1643
  "github.reaction.created": "reaction_created",
@@ -1600,6 +1648,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1600
1648
  "drive.file.created": "file_created",
1601
1649
  "drive.file.modified": "file_modified_by_me",
1602
1650
  "drive.file.viewed": "file_viewed_by_me",
1651
+ "mail.sent": "message_created",
1603
1652
  "notion.page.created": "page_created",
1604
1653
  "notion.page.edited": "page_last_edited"
1605
1654
  });
@@ -1627,6 +1676,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1627
1676
  created_at: { required: false, timestamp: true },
1628
1677
  created_at_local: { required: false, timestamp: true },
1629
1678
  modified_at: { required: false, timestamp: true },
1679
+ observed_at: { required: false, timestamp: true },
1630
1680
  modified_at_local: { required: false, timestamp: true },
1631
1681
  viewed_by_me_at: { required: false, timestamp: true },
1632
1682
  modified_by_me_at: { required: false, timestamp: true },
@@ -1654,9 +1704,6 @@ var RESOURCE_ROW_REQUIRED_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(
1654
1704
  var RESOURCE_ROW_KEYS = new Set(Object.keys(RESOURCE_ROW_KEY_RULES));
1655
1705
  var RESOURCE_ROW_TIMESTAMP_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(([key, rule]) => rule.timestamp ? [key] : []);
1656
1706
 
1657
- // packages/ceal-client-protocol/src/resource-read-result.ts
1658
- var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1659
-
1660
1707
  // packages/ceal-client-protocol/src/excluded-target-coverage.ts
1661
1708
  var CEAL_EXCLUDED_TARGET_COVERAGE_MAX_ENTRIES = 64;
1662
1709
  function cealExcludedTargetCoverageJsonSchema() {
@@ -1712,6 +1759,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1712
1759
  "principal_inactive",
1713
1760
  "authority_replaced",
1714
1761
  "refresh_recovery_unavailable",
1762
+ "refresh_recovery_outcome_unavailable",
1763
+ "refresh_state_unavailable",
1715
1764
  "refresh_recovery_expired",
1716
1765
  // The serving gate answers this while the Gateway is still starting and the
1717
1766
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -1963,7 +2012,7 @@ function validateBatchContents(value) {
1963
2012
  if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
1964
2013
  const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
1965
2014
  for (const fact of facts) {
1966
- validateFact(fact, value.host_session_ref);
2015
+ validateCealHostUsageFact(fact, value.host_session_ref);
1967
2016
  if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
1968
2017
  }
1969
2018
  for (const gap of gaps) {
@@ -1996,7 +2045,7 @@ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, d
1996
2045
  for (const part of [producer, hostSourceRef, hostSessionRef, device, inode]) if (typeof part !== "string" || part.length === 0 || part.length > 512) invalid("Ceal Host usage file identity is invalid.");
1997
2046
  return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
1998
2047
  }
1999
- function validateFact(value, sessionRef) {
2048
+ function validateCealHostUsageFact(value, sessionRef) {
2000
2049
  if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
2001
2050
  requireFactByteLimit(value);
2002
2051
  if (value.producer === "codex_transcript") validateCodexFact(value);
@@ -2060,7 +2109,7 @@ function validCorrectionSemantics(value) {
2060
2109
  }
2061
2110
  function validateCodexUsageCounts(value) {
2062
2111
  if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
2063
- requireExactOperationKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
2112
+ requireExactOperationKeys(value, CEAL_CODEX_USAGE_COUNT_FIELDS);
2064
2113
  for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
2065
2114
  if (Number(value.total_tokens) !== Number(value.input_tokens) + Number(value.output_tokens) || Number(value.cached_input_tokens) + Number(value.cache_write_input_tokens) > Number(value.input_tokens) || Number(value.reasoning_output_tokens) > Number(value.output_tokens)) invalid("Ceal Codex usage fields are inconsistent.");
2066
2115
  }
@@ -2328,6 +2377,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
2328
2377
  "options_invalid",
2329
2378
  "session_unavailable",
2330
2379
  "context_unavailable",
2380
+ "activation_wait_exhausted",
2331
2381
  "context_replaced",
2332
2382
  "no_binding",
2333
2383
  "context_expired",
@@ -2363,22 +2413,23 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2363
2413
  // This reason cannot distinguish a Codex side conversation from a missing
2364
2414
  // context in a regular session, so guidance must leave that choice to the caller.
2365
2415
  context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2366
- context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
2416
+ activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2417
+ context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2367
2418
  // `no_binding` now means the producer has no real current Host session. The
2368
2419
  // Host Relay never uses it for an uncreated Gateway Request; there is no
2369
2420
  // useful retry until the consumer is running inside a Host session.
2370
2421
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2371
- context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
2422
+ context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
2372
2423
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
2373
2424
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
2374
2425
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
2375
2426
  gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
2376
- contract_mismatch: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2377
- gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "upgrade_ceal_client" }),
2427
+ contract_mismatch: Object.freeze({ classification: "host_contract_mismatch", next_action: "upgrade_ceal_client" }),
2428
+ gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
2378
2429
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2379
2430
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2380
2431
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2381
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2432
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2382
2433
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2383
2434
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2384
2435
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2426,7 +2477,7 @@ function isCealHostServiceDiagnosticCause(value, event) {
2426
2477
  // packages/ceal-client-protocol/src/client-result-materialization.ts
2427
2478
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
2428
2479
  var REQUIRED_FIELDS2 = Object.freeze(["schema_version", "operation_id", "path", "sha256"]);
2429
- var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "items_path", "row_count", "result_complete", "coverage", "local_result_root", "model_disclosure", "continue_argv", "how_to_read"]);
2480
+ var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "local_result_root", "request_context_argv", "how_to_read"]);
2430
2481
 
2431
2482
  // packages/ceal-client-protocol/src/session-start-affordance.ts
2432
2483
  var CEAL_SESSION_ENTRY_INVOCATION = "ceal";
@@ -2471,6 +2522,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2471
2522
  maximum: CEAL_PROTOCOL_VERSION
2472
2523
  });
2473
2524
 
2525
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
2526
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2527
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2528
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2529
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2530
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2531
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2532
+ function redactOperatorDiagnosticSecrets(value) {
2533
+ 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]");
2534
+ }
2535
+ function redactOperatorDiagnosticText(value) {
2536
+ const normalized = normalizeCealSingleLineText(value);
2537
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2538
+ }
2539
+ function renderOperatorDiagnostic(value) {
2540
+ const state = collectDiagnosticState(value);
2541
+ const fields = [
2542
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2543
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2544
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
2545
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
2546
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
2547
+ ].filter((field) => field !== void 0);
2548
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2549
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2550
+ }
2551
+ function collectDiagnosticState(value) {
2552
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2553
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
2554
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2555
+ const current = pending.shift();
2556
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2557
+ }
2558
+ return state;
2559
+ }
2560
+ function visitDiagnosticNode(current, state, pending, visited) {
2561
+ if (isObject(current)) {
2562
+ if (visited.has(current)) return;
2563
+ visited.add(current);
2564
+ }
2565
+ captureProcessEvidence(current, state);
2566
+ appendCause(current, state.causes);
2567
+ enqueueCauseChildren(current, state.causes.length, pending);
2568
+ }
2569
+ function captureProcessEvidence(current, state) {
2570
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
2571
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
2572
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2573
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2574
+ }
2575
+ function appendCause(current, causes) {
2576
+ const errors = read(current, "errors");
2577
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2578
+ causes.push(errorCause(current));
2579
+ return;
2580
+ }
2581
+ if (!isObject(current)) {
2582
+ const message = safeText(current);
2583
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2584
+ }
2585
+ }
2586
+ function errorCause(error) {
2587
+ const name = safeText(read(error, "name")) ?? "Error";
2588
+ const message = safeText(read(error, "message"));
2589
+ const codeValue = read(error, "code");
2590
+ const code2 = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
2591
+ const errnoValue = read(error, "errno");
2592
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2593
+ const syscall = safeText(read(error, "syscall"));
2594
+ const path = safePath(read(error, "path"));
2595
+ 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 } });
2596
+ }
2597
+ function enqueueCauseChildren(current, causeCount, pending) {
2598
+ const cause = read(current, "cause");
2599
+ if (cause !== void 0) pending.push(cause);
2600
+ const errors = read(current, "errors");
2601
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2602
+ }
2603
+ function isObject(value) {
2604
+ return typeof value === "object" && value !== null;
2605
+ }
2606
+ function formatCause(cause) {
2607
+ const fields = [
2608
+ cause.error_class,
2609
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
2610
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
2611
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
2612
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
2613
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
2614
+ ].filter((field) => field !== void 0);
2615
+ return fields.join(" ");
2616
+ }
2617
+ function tail(value) {
2618
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
2619
+ return safeDiagnosticText(clipped);
2620
+ }
2621
+ function safeText(value) {
2622
+ if (typeof value !== "string") return void 0;
2623
+ const safe = safeDiagnosticText(value);
2624
+ if (safe.length === 0) return void 0;
2625
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
2626
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
2627
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2628
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2629
+ }
2630
+ function safePath(value) {
2631
+ if (typeof value !== "string") return void 0;
2632
+ const safe = safeDiagnosticText(value);
2633
+ if (safe.length === 0) return void 0;
2634
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2635
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2636
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
2637
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2638
+ }
2639
+ function safeDiagnosticText(value) {
2640
+ return redactOperatorDiagnosticText(String(value));
2641
+ }
2642
+ function outputText(value) {
2643
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
2644
+ if (value instanceof Uint8Array) {
2645
+ try {
2646
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
2647
+ } catch {
2648
+ return void 0;
2649
+ }
2650
+ }
2651
+ return void 0;
2652
+ }
2653
+ function safeStatus(value) {
2654
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2655
+ return typeof value === "string" ? safeText(value) : void 0;
2656
+ }
2657
+ function safeExitCode(value) {
2658
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
2659
+ }
2660
+ function read(value, key) {
2661
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
2662
+ try {
2663
+ return Reflect.get(value, key);
2664
+ } catch {
2665
+ return void 0;
2666
+ }
2667
+ }
2668
+ function redactHomePaths(value) {
2669
+ const paths = [
2670
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
2671
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
2672
+ ];
2673
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
2674
+ let output = "";
2675
+ let cursor = 0;
2676
+ for (const path of paths) {
2677
+ if (path.start < cursor) continue;
2678
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
2679
+ cursor = path.end;
2680
+ }
2681
+ return output + value.slice(cursor);
2682
+ }
2683
+ function configuredHomePathPatterns() {
2684
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
2685
+ return homes.flatMap((home) => {
2686
+ const root = home.replace(/[\\/]+$/gu, "");
2687
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
2688
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
2689
+ return [{ pattern, prefixLength: root.length }];
2690
+ });
2691
+ }
2692
+ function matchedHomePrefixLength(value) {
2693
+ let separators = 0;
2694
+ for (let index = 0; index < value.length; index += 1) {
2695
+ if (value[index] !== "/" && value[index] !== "\\") continue;
2696
+ separators += 1;
2697
+ if (separators === 3) return index;
2698
+ }
2699
+ return value.length;
2700
+ }
2701
+ function redactUrls(value) {
2702
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2703
+ }
2704
+ function redactFilePaths(value) {
2705
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2706
+ }
2707
+ function homePathRange(value, match, prefixLength) {
2708
+ const index = match.index;
2709
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
2710
+ const start = index;
2711
+ let end = start + match[0].length;
2712
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
2713
+ if (quote !== void 0) {
2714
+ const closing = value.indexOf(quote, end);
2715
+ if (closing >= 0) end = closing;
2716
+ }
2717
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
2718
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
2719
+ }
2720
+ function truncateUtf8(value, maxBytes) {
2721
+ if (byteLength(value) <= maxBytes) return value;
2722
+ let output = "";
2723
+ for (const character of value) {
2724
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
2725
+ output += character;
2726
+ }
2727
+ return `${output}…`;
2728
+ }
2729
+
2474
2730
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
2475
2731
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
2476
2732
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -2848,7 +3104,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2848
3104
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2849
3105
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2850
3106
  return await new Promise((resolve2, reject) => {
2851
- const child = execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
3107
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2852
3108
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2853
3109
  if (exitCode === null) {
2854
3110
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2899,6 +3155,192 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
2899
3155
  return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
2900
3156
  }
2901
3157
 
3158
+ // host/service-log.ts
3159
+ import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
3160
+ import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win322 } from "node:path";
3161
+
3162
+ // host/service-log-delivery.ts
3163
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
3164
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
3165
+ setImmediate(flush);
3166
+ }, onDeliveryGap = () => void 0) {
3167
+ const pending = [];
3168
+ const highWaterMark = stream.writableHighWaterMark;
3169
+ const byteBudget = highWaterMark + highWaterMark;
3170
+ let pendingBytes = 0;
3171
+ let droppedLines = 0;
3172
+ let flushScheduled = false;
3173
+ let waitingForDrain = false;
3174
+ let closed = !stream.writable;
3175
+ function stop() {
3176
+ if (closed) return;
3177
+ closed = true;
3178
+ pending.length = 0;
3179
+ pendingBytes = 0;
3180
+ stream.off("drain", onDrain);
3181
+ stream.off("close", onTerminal);
3182
+ stream.off("finish", onTerminal);
3183
+ stream.off("error", onError);
3184
+ }
3185
+ function onTerminal() {
3186
+ stop();
3187
+ }
3188
+ function onError() {
3189
+ stop();
3190
+ }
3191
+ function onDrain() {
3192
+ waitingForDrain = false;
3193
+ scheduleFlush();
3194
+ }
3195
+ function scheduleFlush() {
3196
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
3197
+ flushScheduled = true;
3198
+ let scheduling = true;
3199
+ let invokedSynchronously = false;
3200
+ try {
3201
+ schedule(() => {
3202
+ if (scheduling) {
3203
+ invokedSynchronously = true;
3204
+ return;
3205
+ }
3206
+ flushScheduled = false;
3207
+ flush();
3208
+ });
3209
+ } catch {
3210
+ flushScheduled = false;
3211
+ stop();
3212
+ return;
3213
+ }
3214
+ scheduling = false;
3215
+ if (invokedSynchronously) {
3216
+ flushScheduled = false;
3217
+ stop();
3218
+ }
3219
+ }
3220
+ function flush() {
3221
+ if (closed) return;
3222
+ if (!stream.writable) {
3223
+ stop();
3224
+ return;
3225
+ }
3226
+ while (pending.length > 0) {
3227
+ if (stream.writableNeedDrain) {
3228
+ if (!waitingForDrain) {
3229
+ waitingForDrain = true;
3230
+ stream.once("drain", onDrain);
3231
+ }
3232
+ return;
3233
+ }
3234
+ const next = pending.shift();
3235
+ if (next === void 0) return;
3236
+ pendingBytes -= next.bytes;
3237
+ let accepted;
3238
+ try {
3239
+ accepted = stream.write(next.line);
3240
+ } catch {
3241
+ stop();
3242
+ return;
3243
+ }
3244
+ if (!accepted) {
3245
+ waitingForDrain = true;
3246
+ stream.once("drain", onDrain);
3247
+ return;
3248
+ }
3249
+ }
3250
+ if (droppedLines > 0) {
3251
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
3252
+ `;
3253
+ droppedLines = 0;
3254
+ try {
3255
+ onDeliveryGap(line);
3256
+ } catch {
3257
+ }
3258
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
3259
+ pendingBytes += Buffer.byteLength(line, "utf8");
3260
+ flush();
3261
+ }
3262
+ }
3263
+ stream.on("close", onTerminal);
3264
+ stream.on("finish", onTerminal);
3265
+ stream.on("error", onError);
3266
+ return (line) => {
3267
+ if (closed) return;
3268
+ const bytes = Buffer.byteLength(line, "utf8");
3269
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
3270
+ droppedLines += 1;
3271
+ scheduleFlush();
3272
+ return;
3273
+ }
3274
+ pending.push({ line, bytes });
3275
+ pendingBytes += bytes;
3276
+ scheduleFlush();
3277
+ };
3278
+ }
3279
+
3280
+ // host/invocation-authentication-client-command.ts
3281
+ var DOCTOR_FLAGS = Object.freeze({
3282
+ "--expected-sha256": "expected_sha256",
3283
+ "--expected-source-commit": "expected_source_commit",
3284
+ "--expected-instance-ref": "expected_instance_ref"
3285
+ });
3286
+
3287
+ // host/service-log.ts
3288
+ var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
3289
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
3290
+ void persistHostServiceLogLine(line);
3291
+ });
3292
+ function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
3293
+ const details = diagnosticDetails(event, failure_kind, cause);
3294
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
3295
+ `;
3296
+ try {
3297
+ (sink ?? defaultHostServiceDiagnosticSink)(line);
3298
+ } catch {
3299
+ }
3300
+ }
3301
+ function diagnosticDetails(event, failureKind, cause) {
3302
+ if (event === "watcher_scan_failed") return {
3303
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3304
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
3305
+ };
3306
+ return validDiagnosticCause(cause, event) ? { cause } : {};
3307
+ }
3308
+ function validDiagnosticCause(cause, event) {
3309
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
3310
+ }
3311
+ function defaultHostServiceDiagnosticSink(line) {
3312
+ writeHostServiceLogLine(line);
3313
+ }
3314
+ var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
3315
+ function writeHostServiceLogLine(line, environment = process.env) {
3316
+ void persistHostServiceLogLine(line, environment);
3317
+ defaultHostServiceLogDelivery(line);
3318
+ }
3319
+ async function persistHostServiceLogLine(line, environment = process.env) {
3320
+ if (process.platform !== "win32") return;
3321
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
3322
+ if (path === void 0 || !win322.isAbsolute(path) || win322.normalize(path) !== path) return;
3323
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
3324
+ }
3325
+ async function appendHostServiceLogLine(path, line) {
3326
+ if (!isAbsolute2(path)) return;
3327
+ await ensureHostServiceLogDirectory(path);
3328
+ await appendFile(path, line);
3329
+ }
3330
+ var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
3331
+ var hostServiceLogDirectories = /* @__PURE__ */ new Map();
3332
+ function ensureHostServiceLogDirectory(path) {
3333
+ const directory = dirname2(path);
3334
+ const existing = hostServiceLogDirectories.get(directory);
3335
+ if (existing !== void 0) return existing;
3336
+ const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
3337
+ hostServiceLogDirectories.delete(directory);
3338
+ throw error;
3339
+ });
3340
+ hostServiceLogDirectories.set(directory, pending);
3341
+ return pending;
3342
+ }
3343
+
2902
3344
  // host/relay/src/host-producer-core.ts
2903
3345
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
2904
3346
  function isHostTranscriptCursorReason(value) {
@@ -2944,9 +3386,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
2944
3386
  let lastNewline = -1;
2945
3387
  while (position < size) {
2946
3388
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
2947
- const read = await handle.read(buffer, 0, buffer.length, position);
2948
- if (read.bytesRead === 0) break;
2949
- const chunk = buffer.subarray(0, read.bytesRead);
3389
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
3390
+ if (read2.bytesRead === 0) break;
3391
+ const chunk = buffer.subarray(0, read2.bytesRead);
2950
3392
  chunks.push(chunk);
2951
3393
  const newline = chunk.lastIndexOf(10);
2952
3394
  if (newline >= 0) lastNewline = total + newline;
@@ -3003,7 +3445,7 @@ function createTranscriptWatcherBase(options, owner) {
3003
3445
  outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
3004
3446
  now: options.now ?? (() => /* @__PURE__ */ new Date()),
3005
3447
  log: options.log ?? ((line) => {
3006
- process.stderr.write(`${line}
3448
+ writeHostServiceLogLine(`${line}
3007
3449
  `);
3008
3450
  }),
3009
3451
  producerInstallationRef: options.producer_installation_ref
@@ -3043,7 +3485,13 @@ var HostTranscriptWatcher = class {
3043
3485
  }
3044
3486
  async scanRegistration(registration) {
3045
3487
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
3046
- missing: () => this.retireMissing(registration),
3488
+ missing: async () => {
3489
+ try {
3490
+ return await this.retireMissing(registration);
3491
+ } catch (error) {
3492
+ return this.scanFailed(void 0, registration, error);
3493
+ }
3494
+ },
3047
3495
  failed: (handle, error) => this.scanFailed(handle, registration, error)
3048
3496
  });
3049
3497
  }
@@ -3113,21 +3561,21 @@ var HostProducerDrainCore = class {
3113
3561
  return run;
3114
3562
  }
3115
3563
  async drainLocked() {
3116
- const read = await this.host.listEnvelopes();
3564
+ const read2 = await this.host.listEnvelopes();
3117
3565
  let removed = 0;
3118
3566
  let expired = 0;
3119
- for (const envelope of read.entries) {
3567
+ for (const envelope of read2.entries) {
3120
3568
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
3121
3569
  else removed += 1;
3122
3570
  await this.host.removeEnvelope(envelope);
3123
3571
  }
3124
- return { removed, expired, malformed: read.malformed };
3572
+ return { removed, expired, malformed: read2.malformed };
3125
3573
  }
3126
3574
  };
3127
3575
 
3128
3576
  // host/relay/src/durable-atomic-replacement.ts
3129
- import { lstat as lstat2, mkdir, open as open2, rename, unlink } from "node:fs/promises";
3130
- import { dirname as dirname2 } from "node:path";
3577
+ import { lstat as lstat2, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
3578
+ import { dirname as dirname3 } from "node:path";
3131
3579
 
3132
3580
  // host/windows-rename-retry.ts
3133
3581
  import { setTimeout as setTimeout2 } from "node:timers/promises";
@@ -3180,7 +3628,7 @@ function isRetryableRenameError(error) {
3180
3628
  // host/relay/src/durable-atomic-replacement.ts
3181
3629
  var DEFAULT_PORT = {
3182
3630
  platform: process.platform,
3183
- mkdir: (path, options) => mkdir(path, options),
3631
+ mkdir: (path, options) => mkdir2(path, options),
3184
3632
  lstat: (path) => lstat2(path),
3185
3633
  open_file: (path) => open2(path, "wx", 384),
3186
3634
  rename,
@@ -3189,7 +3637,7 @@ var DEFAULT_PORT = {
3189
3637
  unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
3190
3638
  };
3191
3639
  async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
3192
- const parent = dirname2(target);
3640
+ const parent = dirname3(target);
3193
3641
  await port.mkdir(parent, { recursive: true, mode: 448 });
3194
3642
  const parentStats = await port.lstat(parent);
3195
3643
  const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
@@ -3259,8 +3707,8 @@ function errorCode(error) {
3259
3707
  // host/relay/src/host-usage-facts-store.ts
3260
3708
  import { createHash as createHash6 } from "node:crypto";
3261
3709
  import { constants as constants2 } from "node:fs";
3262
- import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3263
- import { dirname as dirname3, join as join3 } from "node:path";
3710
+ import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3711
+ import { dirname as dirname4, join as join3 } from "node:path";
3264
3712
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3265
3713
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3266
3714
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -3509,7 +3957,7 @@ var HostUsageFactsStore = class {
3509
3957
  }
3510
3958
  async writeImmutableBatch(state, batch, bytes) {
3511
3959
  const path = this.batchPath(state, batch.batch_ref);
3512
- await preparePrivateDirectory(dirname3(path), this.platform, this.custody);
3960
+ await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
3513
3961
  const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3514
3962
  if (existing !== null) {
3515
3963
  if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
@@ -3527,7 +3975,7 @@ var HostUsageFactsStore = class {
3527
3975
  await handle.sync();
3528
3976
  await handle.close();
3529
3977
  handle = void 0;
3530
- await syncDirectory(dirname3(path), this.platform);
3978
+ await syncDirectory(dirname4(path), this.platform);
3531
3979
  } catch (error) {
3532
3980
  await handle?.close().catch(() => void 0);
3533
3981
  if (errorCode2(error) === "EEXIST") {
@@ -3571,14 +4019,14 @@ var HostUsageFactsStore = class {
3571
4019
  const gate = new Promise((resolve2) => {
3572
4020
  release = resolve2;
3573
4021
  });
3574
- const tail = previous.then(() => gate);
3575
- SESSION_TRANSITION_TAILS.set(key, tail);
4022
+ const tail2 = previous.then(() => gate);
4023
+ SESSION_TRANSITION_TAILS.set(key, tail2);
3576
4024
  await previous;
3577
4025
  try {
3578
4026
  return await run();
3579
4027
  } finally {
3580
4028
  release?.();
3581
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
4029
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3582
4030
  }
3583
4031
  }
3584
4032
  sessionPath(producer, hostSourceRef, hostSessionRef) {
@@ -3781,7 +4229,7 @@ async function preparePrivateDirectory(path, platform, custody) {
3781
4229
  await ensurePrivateDirectoryWithSecurefs(path, custody);
3782
4230
  return;
3783
4231
  }
3784
- await mkdir2(path, { recursive: true, mode: 448 });
4232
+ await mkdir3(path, { recursive: true, mode: 448 });
3785
4233
  if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3786
4234
  }
3787
4235
  async function syncExistingFile(path, platform) {
@@ -3791,7 +4239,7 @@ async function syncExistingFile(path, platform) {
3791
4239
  } finally {
3792
4240
  await handle.close();
3793
4241
  }
3794
- await syncDirectory(dirname3(path), platform);
4242
+ await syncDirectory(dirname4(path), platform);
3795
4243
  }
3796
4244
  async function syncDirectory(path, platform) {
3797
4245
  if (platform === "win32") return;
@@ -3839,29 +4287,46 @@ var HostUsageTranscriptSourceError = class extends Error {
3839
4287
  this.name = "HostUsageTranscriptSourceError";
3840
4288
  }
3841
4289
  };
3842
- async function readHostUsageTranscriptSource(read) {
4290
+ async function readHostUsageTranscriptSource(read2) {
3843
4291
  try {
3844
- return await read();
4292
+ return await read2();
3845
4293
  } catch (error) {
3846
4294
  throw new HostUsageTranscriptSourceError({ cause: error });
3847
4295
  }
3848
4296
  }
3849
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
3850
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
3851
- let failed = false;
3852
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
3853
- const index = (startIndex + attempt) % registrations.length;
3854
- const registration = registrations[index];
3855
- if (registration === void 0) continue;
3856
- try {
3857
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
3858
- } catch (error) {
3859
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4297
+ var HostUsageRegistrationCapture = class {
4298
+ nextIndex = 0;
4299
+ producer;
4300
+ diagnosticSink;
4301
+ constructor(producer, diagnosticSink) {
4302
+ this.producer = producer;
4303
+ this.diagnosticSink = diagnosticSink;
4304
+ }
4305
+ async captureNext(registrations, capture) {
4306
+ let failed = false;
4307
+ let captured = false;
4308
+ const onFailure = () => {
3860
4309
  failed = true;
4310
+ };
4311
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4312
+ const index = (this.nextIndex + attempt) % registrations.length;
4313
+ const registration = registrations[index];
4314
+ if (registration === void 0) continue;
4315
+ try {
4316
+ captured = await capture(registration, onFailure);
4317
+ if (captured) {
4318
+ this.nextIndex = (index + 1) % registrations.length;
4319
+ break;
4320
+ }
4321
+ } catch (error) {
4322
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4323
+ onFailure();
4324
+ }
3861
4325
  }
4326
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
4327
+ return captured;
3862
4328
  }
3863
- return { captured: false, nextIndex: startIndex, failed };
3864
- }
4329
+ };
3865
4330
  async function openHostUsageTranscriptCursor(input) {
3866
4331
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
3867
4332
  let source;
@@ -3932,16 +4397,16 @@ function completeLinePrefix(bytes, baseOffset) {
3932
4397
 
3933
4398
  // host/relay/src/host-registration-state.ts
3934
4399
  import { constants as constants4 } from "node:fs";
3935
- import { dirname as dirname4 } from "node:path";
4400
+ import { dirname as dirname5 } from "node:path";
3936
4401
 
3937
4402
  // host/runtime-source-paths.ts
3938
4403
  import { createHash as createHash7 } from "node:crypto";
3939
- import { posix as posix2, win32 as win323 } from "node:path";
4404
+ import { posix as posix3, win32 as win324 } from "node:path";
3940
4405
 
3941
4406
  // host/absolute-path.ts
3942
- import { posix, win32 as win322 } from "node:path";
4407
+ import { posix as posix2, win32 as win323 } from "node:path";
3943
4408
  function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
3944
- const pathApi = flavor === "win32" || flavor === "windows" ? win322 : posix;
4409
+ const pathApi = flavor === "win32" || flavor === "windows" ? win323 : posix2;
3945
4410
  return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
3946
4411
  }
3947
4412
 
@@ -3962,7 +4427,7 @@ function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
3962
4427
  function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
3963
4428
  const sourceId = hostSourceUuid(sourceRef);
3964
4429
  if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
3965
- const path = platform === "win32" ? win323 : posix2;
4430
+ const path = platform === "win32" ? win324 : posix3;
3966
4431
  const sourcesRoot = path.join(stateRoot, "sources");
3967
4432
  const sourceRoot = path.join(sourcesRoot, sourceId);
3968
4433
  const runtimeRoot = path.join(stateRoot, "run");
@@ -3973,7 +4438,7 @@ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platfor
3973
4438
  function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
3974
4439
  if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
3975
4440
  const digest2 = createHash7("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
3976
- return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix2.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
4441
+ return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix3.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
3977
4442
  }
3978
4443
  function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
3979
4444
  const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
@@ -4001,7 +4466,7 @@ var HostRegistrationStateError = class extends Error {
4001
4466
  async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
4002
4467
  let raw;
4003
4468
  try {
4004
- await assertPrivateRegistrationDirectory(dirname4(path), platform, custody);
4469
+ await assertPrivateRegistrationDirectory(dirname5(path), platform, custody);
4005
4470
  raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
4006
4471
  } catch (error) {
4007
4472
  throw registrationReadError(error);
@@ -4106,192 +4571,6 @@ function waitForAbort(signal, milliseconds) {
4106
4571
  });
4107
4572
  }
4108
4573
 
4109
- // host/service-log.ts
4110
- import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
4111
- import { dirname as dirname5, isAbsolute as isAbsolute2, posix as posix3, win32 as win324 } from "node:path";
4112
-
4113
- // host/service-log-delivery.ts
4114
- var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
4115
- function createHostServiceLogDelivery(stream, schedule = (flush) => {
4116
- setImmediate(flush);
4117
- }, onDeliveryGap = () => void 0) {
4118
- const pending = [];
4119
- const highWaterMark = stream.writableHighWaterMark;
4120
- const byteBudget = highWaterMark + highWaterMark;
4121
- let pendingBytes = 0;
4122
- let droppedLines = 0;
4123
- let flushScheduled = false;
4124
- let waitingForDrain = false;
4125
- let closed = !stream.writable;
4126
- function stop() {
4127
- if (closed) return;
4128
- closed = true;
4129
- pending.length = 0;
4130
- pendingBytes = 0;
4131
- stream.off("drain", onDrain);
4132
- stream.off("close", onTerminal);
4133
- stream.off("finish", onTerminal);
4134
- stream.off("error", onError);
4135
- }
4136
- function onTerminal() {
4137
- stop();
4138
- }
4139
- function onError() {
4140
- stop();
4141
- }
4142
- function onDrain() {
4143
- waitingForDrain = false;
4144
- scheduleFlush();
4145
- }
4146
- function scheduleFlush() {
4147
- if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
4148
- flushScheduled = true;
4149
- let scheduling = true;
4150
- let invokedSynchronously = false;
4151
- try {
4152
- schedule(() => {
4153
- if (scheduling) {
4154
- invokedSynchronously = true;
4155
- return;
4156
- }
4157
- flushScheduled = false;
4158
- flush();
4159
- });
4160
- } catch {
4161
- flushScheduled = false;
4162
- stop();
4163
- return;
4164
- }
4165
- scheduling = false;
4166
- if (invokedSynchronously) {
4167
- flushScheduled = false;
4168
- stop();
4169
- }
4170
- }
4171
- function flush() {
4172
- if (closed) return;
4173
- if (!stream.writable) {
4174
- stop();
4175
- return;
4176
- }
4177
- while (pending.length > 0) {
4178
- if (stream.writableNeedDrain) {
4179
- if (!waitingForDrain) {
4180
- waitingForDrain = true;
4181
- stream.once("drain", onDrain);
4182
- }
4183
- return;
4184
- }
4185
- const next = pending.shift();
4186
- if (next === void 0) return;
4187
- pendingBytes -= next.bytes;
4188
- let accepted;
4189
- try {
4190
- accepted = stream.write(next.line);
4191
- } catch {
4192
- stop();
4193
- return;
4194
- }
4195
- if (!accepted) {
4196
- waitingForDrain = true;
4197
- stream.once("drain", onDrain);
4198
- return;
4199
- }
4200
- }
4201
- if (droppedLines > 0) {
4202
- const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
4203
- `;
4204
- droppedLines = 0;
4205
- try {
4206
- onDeliveryGap(line);
4207
- } catch {
4208
- }
4209
- pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
4210
- pendingBytes += Buffer.byteLength(line, "utf8");
4211
- flush();
4212
- }
4213
- }
4214
- stream.on("close", onTerminal);
4215
- stream.on("finish", onTerminal);
4216
- stream.on("error", onError);
4217
- return (line) => {
4218
- if (closed) return;
4219
- const bytes = Buffer.byteLength(line, "utf8");
4220
- if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
4221
- droppedLines += 1;
4222
- scheduleFlush();
4223
- return;
4224
- }
4225
- pending.push({ line, bytes });
4226
- pendingBytes += bytes;
4227
- scheduleFlush();
4228
- };
4229
- }
4230
-
4231
- // host/invocation-authentication-client-command.ts
4232
- var DOCTOR_FLAGS = Object.freeze({
4233
- "--expected-sha256": "expected_sha256",
4234
- "--expected-source-commit": "expected_source_commit",
4235
- "--expected-instance-ref": "expected_instance_ref"
4236
- });
4237
-
4238
- // host/service-log.ts
4239
- var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
4240
- var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
4241
- void persistHostServiceLogLine(line);
4242
- });
4243
- function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
4244
- const details = diagnosticDetails(event, failure_kind, cause);
4245
- const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
4246
- `;
4247
- try {
4248
- (sink ?? defaultHostServiceDiagnosticSink)(line);
4249
- } catch {
4250
- }
4251
- }
4252
- function diagnosticDetails(event, failureKind, cause) {
4253
- if (event === "watcher_scan_failed") return {
4254
- ...failureKind === void 0 ? {} : { failure_kind: failureKind },
4255
- ...validDiagnosticCause(cause, event) ? { cause } : {}
4256
- };
4257
- return validDiagnosticCause(cause, event) ? { cause } : {};
4258
- }
4259
- function validDiagnosticCause(cause, event) {
4260
- return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
4261
- }
4262
- function defaultHostServiceDiagnosticSink(line) {
4263
- writeHostServiceLogLine(line);
4264
- }
4265
- var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
4266
- function writeHostServiceLogLine(line, environment = process.env) {
4267
- void persistHostServiceLogLine(line, environment);
4268
- defaultHostServiceLogDelivery(line);
4269
- }
4270
- async function persistHostServiceLogLine(line, environment = process.env) {
4271
- if (process.platform !== "win32") return;
4272
- const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
4273
- if (path === void 0 || !win324.isAbsolute(path) || win324.normalize(path) !== path) return;
4274
- await appendHostServiceLogLine(path, line).catch(() => void 0);
4275
- }
4276
- async function appendHostServiceLogLine(path, line) {
4277
- if (!isAbsolute2(path)) return;
4278
- await ensureHostServiceLogDirectory(path);
4279
- await appendFile(path, line);
4280
- }
4281
- var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
4282
- var hostServiceLogDirectories = /* @__PURE__ */ new Map();
4283
- function ensureHostServiceLogDirectory(path) {
4284
- const directory = dirname5(path);
4285
- const existing = hostServiceLogDirectories.get(directory);
4286
- if (existing !== void 0) return existing;
4287
- const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
4288
- hostServiceLogDirectories.delete(directory);
4289
- throw error;
4290
- });
4291
- hostServiceLogDirectories.set(directory, pending);
4292
- return pending;
4293
- }
4294
-
4295
4574
  // host/relay/src/host-usage-facts-uploader.ts
4296
4575
  var HostUsageFactsUploader = class {
4297
4576
  options;
@@ -4310,7 +4589,7 @@ var HostUsageFactsUploader = class {
4310
4589
  const registration = await readHostRegistrationAuthority(this.options.registration_state_file, this.options.host_source_ref, this.options.store_options?.platform, this.options.store_options?.secure_file_custody);
4311
4590
  const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4312
4591
  const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4313
- const response2 = await (this.options.fetch ?? fetch)(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4592
+ const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4314
4593
  method: "POST",
4315
4594
  headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4316
4595
  body: JSON.stringify(candidate.batch),
@@ -4557,6 +4836,13 @@ var ClaudeOutboxStore = class {
4557
4836
  await this.removeStateFile(this.registrationPath(registration.host_source_ref, registration.host_session_ref));
4558
4837
  await this.removeStateFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref));
4559
4838
  }
4839
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
4840
+ if (!SAFE_REF2.test(hostSourceRef) || !SAFE_REF2.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
4841
+ await this.prepare();
4842
+ const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
4843
+ 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.");
4844
+ return registration;
4845
+ }
4560
4846
  async listTranscriptRegistrations() {
4561
4847
  await this.prepare();
4562
4848
  const registrations = [];
@@ -4804,10 +5090,42 @@ function sameKeys2(value, required, optional = []) {
4804
5090
 
4805
5091
  // host/claude/src/claude-transcript-watcher.ts
4806
5092
  import { readdir as readdir2 } from "node:fs/promises";
5093
+ import { isDeepStrictEqual } from "node:util";
4807
5094
  import { join as join5 } from "node:path";
5095
+
5096
+ // host/claude/src/claude-subagent-overflow-checkpoint.ts
5097
+ var ClaudeSubagentOverflowCheckpoint = class {
5098
+ observed = /* @__PURE__ */ new Map();
5099
+ prune(registrations) {
5100
+ const current = new Set(registrations.map(registrationKey));
5101
+ for (const key of this.observed.keys()) if (!current.has(key)) this.observed.delete(key);
5102
+ }
5103
+ clear(registration) {
5104
+ this.observed.delete(registrationKey(registration));
5105
+ }
5106
+ /** Names follow the producer's sorted inventory; only omitted names define overflow. */
5107
+ async observe(registration, names, report) {
5108
+ const key = registrationKey(registration);
5109
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
5110
+ this.clear(registration);
5111
+ return false;
5112
+ }
5113
+ const digest2 = transcriptObjectSha256(names.slice(CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES));
5114
+ if (this.observed.get(key) === digest2) return false;
5115
+ if (!await report()) return false;
5116
+ this.observed.set(key, digest2);
5117
+ return true;
5118
+ }
5119
+ };
5120
+ function registrationKey(registration) {
5121
+ return JSON.stringify([registration.host_source_ref, registration.host_session_ref, registration.transcript_path]);
5122
+ }
5123
+
5124
+ // host/claude/src/claude-transcript-watcher.ts
4808
5125
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
4809
5126
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4810
5127
  store;
5128
+ overflow = new ClaudeSubagentOverflowCheckpoint();
4811
5129
  diagnostic;
4812
5130
  constructor(options) {
4813
5131
  super(options, {
@@ -4822,17 +5140,21 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4822
5140
  return registration.transcript_path;
4823
5141
  }
4824
5142
  async listRegistrations() {
4825
- return this.store.listTranscriptRegistrations();
5143
+ const registrations = await this.store.listTranscriptRegistrations();
5144
+ this.overflow.prune(registrations);
5145
+ return registrations;
4826
5146
  }
4827
5147
  async scanOpened(handle, registration) {
4828
5148
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
4829
- const cursor = await this.preflight(registration, handle, size, device, inode);
5149
+ const preflight = await this.preflight(registration, handle, size, device, inode);
5150
+ const cursor = preflight.cursor;
4830
5151
  if (cursor === null) return { records: 0, enqueued: 0, quarantined: true };
4831
5152
  if (cursor.status === "quarantined") {
4832
5153
  return { records: 0, enqueued: 0, quarantined: true };
4833
5154
  }
5155
+ if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
4834
5156
  const draft = mutableCursor(cursor);
4835
- await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
5157
+ await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
4836
5158
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
4837
5159
  }
4838
5160
  async scanFailed(handle, registration, error) {
@@ -4843,6 +5165,15 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4843
5165
  return { records: 0, enqueued: 0, quarantined: true };
4844
5166
  }
4845
5167
  async retireMissing(registration) {
5168
+ const observedAt = this.stamp();
5169
+ if (Date.parse(registration.expires_at) <= Date.parse(observedAt)) return this.retireTranscript(registration);
5170
+ const cursor = await this.store.readTranscriptCursor(registration);
5171
+ if (cursor !== null && isUnmaterializedCursor(cursor, this.sha(Buffer.alloc(0)))) {
5172
+ return { records: 0, enqueued: 0, quarantined: false };
5173
+ }
5174
+ return this.retireTranscript(registration);
5175
+ }
5176
+ retireTranscript(registration) {
4846
5177
  return this.retireMissingTranscript(registration.transcript_path, "Claude", () => this.store.retireTranscriptRegistration(registration));
4847
5178
  }
4848
5179
  initialCursor(registration) {
@@ -4860,7 +5191,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4860
5191
  updated_at: this.stamp()
4861
5192
  };
4862
5193
  }
4863
- async scanOpenedTranscript(registration, handle, draft, size, device, inode) {
5194
+ async scanOpenedTranscript(registration, handle, previous, draft, size, device, inode) {
4864
5195
  const main2 = await this.readChunk(handle, draft.offset, size);
4865
5196
  if (main2 !== "empty" && main2 !== "partial") {
4866
5197
  await this.consumeMainChunk(registration, main2, draft);
@@ -4868,20 +5199,22 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4868
5199
  }
4869
5200
  draft.consumed += await this.consumeSubagents(registration, draft);
4870
5201
  await this.emitOpenTerminal(registration, draft);
4871
- await this.commitCursor(registration, handle, draft, device, inode);
5202
+ await this.commitCursor(registration, handle, previous, draft, device, inode);
4872
5203
  }
4873
5204
  async preflight(registration, handle, size, device, inode) {
4874
5205
  const existing = await this.store.readTranscriptCursor(registration);
4875
- if (existing?.status === "quarantined") return existing;
5206
+ if (existing?.status === "quarantined") return { cursor: existing, checkpointPending: false };
4876
5207
  const cursor = existing ?? this.initialCursor(registration);
4877
5208
  if (cursor.device === void 0) {
4878
- if (cursor.offset !== 0) return await this.quarantineStored(cursor, device, inode, "transcript_replaced");
4879
- return { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
5209
+ const pinned = { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
5210
+ const reason2 = this.cursorIdentityReason(pinned, registration.transcript_path, device, inode);
5211
+ if (cursor.offset !== 0 || reason2 !== null) return { cursor: await this.quarantineStored(cursor, device, inode, "transcript_replaced"), checkpointPending: false };
5212
+ return { cursor: pinned, checkpointPending: true };
4880
5213
  }
4881
5214
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
4882
- if (reason !== null) return await this.quarantineStored(cursor, device, inode, reason);
4883
- if (cursor.human_message_window !== void 0) return cursor;
4884
- return { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) };
5215
+ if (reason !== null) return { cursor: await this.quarantineStored(cursor, device, inode, reason), checkpointPending: false };
5216
+ if (cursor.human_message_window !== void 0) return { cursor, checkpointPending: false };
5217
+ return { cursor: { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) }, checkpointPending: true };
4885
5218
  }
4886
5219
  async readHumanMessageProjection(registration, handle, watermark) {
4887
5220
  let offset = 0;
@@ -5026,15 +5359,24 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5026
5359
  try {
5027
5360
  names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
5028
5361
  } catch (error) {
5029
- if (isMissingTranscriptError(error) || isNotDirectory(error)) return 0;
5362
+ if (isMissingTranscriptError(error) || isNotDirectory(error)) {
5363
+ this.overflow.clear(registration);
5364
+ return 0;
5365
+ }
5030
5366
  throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
5031
5367
  }
5032
5368
  const listed = new Set(names);
5033
5369
  for (const name of Object.keys(draft.subagents)) if (!listed.has(name)) delete draft.subagents[name];
5034
- if (names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
5035
- this.log(`Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`);
5036
- names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5037
- }
5370
+ await this.overflow.observe(registration, names, () => {
5371
+ const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
5372
+ try {
5373
+ this.log(line);
5374
+ } catch {
5375
+ return false;
5376
+ }
5377
+ return true;
5378
+ });
5379
+ names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5038
5380
  let consumed = 0;
5039
5381
  for (const name of names) {
5040
5382
  consumed += await this.consumeSubagentFile(draft, directory, name);
@@ -5123,9 +5465,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5123
5465
  expires_at: this.expire(this.outboxRetentionMs)
5124
5466
  });
5125
5467
  }
5126
- async commitCursor(registration, handle, draft, device, inode) {
5468
+ async commitCursor(registration, handle, previous, draft, device, inode) {
5127
5469
  const anchor = await this.readAnchor(handle, draft.offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
5128
- await this.store.writeTranscriptCursor({
5470
+ const cursor = {
5129
5471
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
5130
5472
  host_source_ref: registration.host_source_ref,
5131
5473
  host_session_ref: registration.host_session_ref,
@@ -5142,7 +5484,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5142
5484
  ...draft.session_observed ? { session_observed: true } : {},
5143
5485
  status: "active",
5144
5486
  updated_at: this.stamp()
5145
- });
5487
+ };
5488
+ if (sameCursorContent(cursor, previous)) return;
5489
+ await this.store.writeTranscriptCursor(cursor);
5146
5490
  }
5147
5491
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
5148
5492
  try {
@@ -5178,6 +5522,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5178
5522
  return await this.store.readTranscriptCursor(registration).catch(() => null) ?? this.initialCursor(registration);
5179
5523
  }
5180
5524
  };
5525
+ function isUnmaterializedCursor(cursor, emptyAnchorSha256) {
5526
+ return cursor.status === "active" && cursor.device === void 0 && cursor.inode === void 0 && cursor.offset === 0 && cursor.anchor_start === 0 && cursor.anchor_sha256 === emptyAnchorSha256;
5527
+ }
5181
5528
  function mutableCursor(cursor) {
5182
5529
  return {
5183
5530
  offset: cursor.offset,
@@ -5190,6 +5537,9 @@ function mutableCursor(cursor) {
5190
5537
  enqueued: 0
5191
5538
  };
5192
5539
  }
5540
+ function sameCursorContent(left, right) {
5541
+ return isDeepStrictEqual({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
5542
+ }
5193
5543
  function zeroCounts() {
5194
5544
  return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
5195
5545
  }
@@ -5328,25 +5678,20 @@ var ClaudeUsageFactsCapturer = class {
5328
5678
  sources;
5329
5679
  usage;
5330
5680
  now;
5331
- diagnosticSink;
5332
- nextRegistrationIndex = 0;
5681
+ registrations;
5333
5682
  nextSourceSlot = "main";
5334
5683
  nextSubagentIndex = 0;
5684
+ overflow = new ClaudeSubagentOverflowCheckpoint();
5335
5685
  constructor(options) {
5336
5686
  this.sources = new ClaudeOutboxStore(options.outbox_dir);
5337
5687
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5338
5688
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5339
- this.diagnosticSink = options.diagnostic_sink;
5689
+ this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
5340
5690
  }
5341
5691
  async captureNext() {
5342
5692
  const registrations = await this.sources.listTranscriptRegistrations();
5343
- let failed = false;
5344
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
5345
- failed = true;
5346
- }));
5347
- this.nextRegistrationIndex = result.nextIndex;
5348
- if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5349
- return result.captured;
5693
+ this.overflow.prune(registrations);
5694
+ return await this.registrations.captureNext(registrations, (registration, onFailure) => this.captureRegistration(registration, onFailure));
5350
5695
  }
5351
5696
  async captureRegistration(registration, onFailure) {
5352
5697
  const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
@@ -5393,13 +5738,14 @@ var ClaudeUsageFactsCapturer = class {
5393
5738
  }
5394
5739
  async captureSubagent(registration, onFailure) {
5395
5740
  const names = await readSubagentNames(registration);
5741
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
5396
5742
  let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
5397
5743
  if (state === null) return false;
5398
5744
  state = await this.usage.recoverPending(state);
5399
5745
  if (state.quarantined_reason !== void 0) return false;
5400
5746
  if (await this.retireMissingSubagent(state, names)) return true;
5401
5747
  if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
5402
- return await this.recordExcessSubagentGap(state, names);
5748
+ return await this.recordExcessSubagentGap(registration, state, names);
5403
5749
  }
5404
5750
  async retireMissingSubagent(state, names) {
5405
5751
  const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
@@ -5410,14 +5756,14 @@ var ClaudeUsageFactsCapturer = class {
5410
5756
  }
5411
5757
  return false;
5412
5758
  }
5413
- async recordExcessSubagentGap(state, names) {
5414
- const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
5415
- if (excessCount <= 0) return false;
5759
+ async recordExcessSubagentGap(registration, state, names) {
5416
5760
  const mainCursor = state.cursors.main;
5417
5761
  if (mainCursor === void 0) return false;
5418
- const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
5419
- await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
5420
- return true;
5762
+ return await this.overflow.observe(registration, names, async () => {
5763
+ 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 };
5764
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
5765
+ return true;
5766
+ });
5421
5767
  }
5422
5768
  async captureListedSubagents(registration, names, state, onFailure) {
5423
5769
  const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
@@ -5756,8 +6102,8 @@ var ClaudeHookAdapter = class {
5756
6102
  registered_at: observedAt,
5757
6103
  expires_at: expiresAt
5758
6104
  };
5759
- const existing = (await this.store.listTranscriptRegistrations()).find((candidate) => candidate.host_source_ref === registration.host_source_ref && candidate.host_session_ref === registration.host_session_ref);
5760
- if (existing === void 0) {
6105
+ const existing = await this.store.readTranscriptRegistration(registration.host_source_ref, registration.host_session_ref);
6106
+ if (existing === null) {
5761
6107
  await this.store.writeTranscriptCursor((await captureClaudeTranscriptBaseline(registration, this.now, void 0, this.platform, this.custody)).cursor);
5762
6108
  }
5763
6109
  await this.store.registerTranscript(registration);
@@ -5790,11 +6136,11 @@ var ClaudeHookAdapter = class {
5790
6136
  const promptRef = hostProducerPromptRef(createHash9("sha256").update(input.prompt, "utf8").digest("hex"));
5791
6137
  const turnGenerationRef = this.randomUuid();
5792
6138
  const selection = { schema_version: HOST_INVOCATION_TURN_SELECTION_SCHEMA, host_source_ref: this.optionsSourceRef, host_session_ref: hostSessionRef, prompt_ref: promptRef, turn_generation_ref: turnGenerationRef };
5793
- const existing = (await this.store.listTranscriptRegistrations()).find((candidate) => candidate.host_source_ref === registration.host_source_ref && candidate.host_session_ref === registration.host_session_ref);
6139
+ const existing = await this.store.readTranscriptRegistration(registration.host_source_ref, registration.host_session_ref);
5794
6140
  const baseline = await captureClaudeTranscriptBaseline(registration, this.now, input.prompt, this.platform, this.custody);
5795
6141
  const transcriptTurnRef = baseline.current_turn_ref;
5796
6142
  await this.store.writeInvocationTurnSelection(selection);
5797
- if (existing === void 0) await this.store.writeTranscriptCursor(baseline.cursor);
6143
+ if (existing === null) await this.store.writeTranscriptCursor(baseline.cursor);
5798
6144
  else await refreshCurrentTurnCursor(this.store, registration, baseline, promptRef, turnGenerationRef, transcriptTurnRef);
5799
6145
  await this.store.registerTranscript(registration);
5800
6146
  return { event: input.event, disposition: "ignored", reason: "transcript_registered", local_session_ref: hostSessionRef, ...transcriptTurnRef === void 0 ? {} : { local_turn_ref: transcriptTurnRef } };
@@ -5877,8 +6223,10 @@ var CLAUDE_BASELINE_SCAN_LINES = 128;
5877
6223
  async function readRecentClaudeTranscriptLines(handle, size) {
5878
6224
  if (size === 0) return null;
5879
6225
  const start = Math.max(0, size - CLAUDE_BASELINE_SCAN_BYTES);
5880
- const buffer = Buffer.alloc(size - start);
5881
- await handle.read(buffer, 0, buffer.length, start);
6226
+ const readStart = Math.max(0, start - 1);
6227
+ const tail2 = Buffer.alloc(size - readStart);
6228
+ await handle.read(tail2, 0, tail2.length, readStart);
6229
+ const buffer = tail2.subarray(start - readStart);
5882
6230
  const lines = [];
5883
6231
  let lineStart = 0;
5884
6232
  for (let index = 0; index < buffer.length; index += 1) {
@@ -5888,7 +6236,7 @@ async function readRecentClaudeTranscriptLines(handle, size) {
5888
6236
  }
5889
6237
  if (lineStart < buffer.length) lines.push({ start: start + lineStart, text: buffer.subarray(lineStart).toString("utf8"), complete: false });
5890
6238
  if (lines.length === 0) return null;
5891
- const whole = start > 0 ? lines.slice(1) : lines;
6239
+ const whole = start === 0 || tail2[0] === 10 ? lines : lines.slice(1);
5892
6240
  if (whole.length === 0) return null;
5893
6241
  return whole.slice(-CLAUDE_BASELINE_SCAN_LINES);
5894
6242
  }
@@ -6018,11 +6366,14 @@ var ClaudeProducer = class {
6018
6366
  };
6019
6367
 
6020
6368
  // host/claude/src/claude-producer-runtime.ts
6021
- async function drainClaudeProducerOnce(options) {
6022
- const scan = await new ClaudeTranscriptWatcher({
6023
- outbox_dir: options.outbox_dir,
6369
+ function createClaudeProducerWatcher(outboxDir) {
6370
+ return new ClaudeTranscriptWatcher({
6371
+ outbox_dir: outboxDir,
6024
6372
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
6025
- }).scanOnce().catch((error) => {
6373
+ });
6374
+ }
6375
+ async function drainClaudeProducerOnce(options) {
6376
+ const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
6026
6377
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
6027
6378
  throw error;
6028
6379
  });
@@ -6210,7 +6561,7 @@ function parseCanonicalJson(text, error) {
6210
6561
  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) }])}`);
6211
6562
  return value;
6212
6563
  } catch (parseError) {
6213
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
6564
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
6214
6565
  }
6215
6566
  }
6216
6567
  function firstDifferenceIndex(left, right) {
@@ -6272,11 +6623,11 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
6272
6623
  producer_id: "claude",
6273
6624
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
6274
6625
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
6275
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6626
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createClaudeProducerWatcher(config.outbox_dir) }),
6276
6627
  drain: drainClaudeProducerOnce,
6277
- background: (config, signal) => {
6628
+ background: (config, signal, dependencies) => {
6278
6629
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
6279
- return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext() }, signal);
6630
+ 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);
6280
6631
  }
6281
6632
  };
6282
6633
 
@@ -6363,7 +6714,7 @@ var execFileAsync = promisify(execFile2);
6363
6714
 
6364
6715
  // host/claude/src/claude-installer.ts
6365
6716
  var ACTIVE_CLAUDE_HOOK_EVENTS = new Set(CLAUDE_HOOK_EVENTS);
6366
- var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: "CLAUDE_CODE_ENTRYPOINT", value: "cli" });
6717
+ var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: CLAUDE_SESSION_ID_ENVIRONMENT, value: Object.freeze({ environment: CLAUDE_SESSION_ID_ENVIRONMENT }) });
6367
6718
  var CLAUDE_CLIENT_ALLOW_RULE = `Bash(${CEAL_SESSION_ENTRY_INVOCATION}:*)`;
6368
6719
 
6369
6720
  // host/claude/bin/ceal-claude-hook.ts