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

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.
@@ -139,7 +139,7 @@ var client_wire_contract_default = {
139
139
  },
140
140
  command_request: {
141
141
  schema_name: "ceal.command_request",
142
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
142
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
143
143
  absolute_transport_max_bytes: 65536
144
144
  },
145
145
  command_resolution: {
@@ -185,7 +185,7 @@ var client_wire_contract_default = {
185
185
  },
186
186
  command_response: {
187
187
  schema_name: "ceal.command_response",
188
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
188
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
189
189
  descriptor_field: "verified_artifact",
190
190
  request_context_field: "request_context",
191
191
  required_fields: [
@@ -198,7 +198,8 @@ var client_wire_contract_default = {
198
198
  "visible_output_max_bytes",
199
199
  "local_delivery",
200
200
  "verified_artifact",
201
- "request_context"
201
+ "request_context",
202
+ "result_file"
202
203
  ],
203
204
  bare_document_fields: [
204
205
  "invocation",
@@ -327,6 +328,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
327
328
  // (never connected, revoked, or expired). The caller runs that exact
328
329
  // Operation, completes the consent it hands back, and retries the same call.
329
330
  "connect_personal_account",
331
+ // The refusal names the caller's own preferences update step: the read
332
+ // needs a personal connection the caller holds but has not selected in
333
+ // Ceal preferences, or has not confirmed through the initial review. The
334
+ // caller reads personal.preferences.get, runs personal.preferences.update
335
+ // at the current revision to select it, and retries the same call.
336
+ "update_personal_preferences",
330
337
  // The provider or Gateway named a bounded wait; the caller waits that long
331
338
  // and submits the same read again.
332
339
  "retry_after",
@@ -467,6 +474,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
467
474
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
468
475
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
469
476
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
477
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
478
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
479
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
470
480
  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"]);
471
481
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
472
482
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -507,6 +517,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
507
517
  ]);
508
518
 
509
519
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
520
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
521
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
522
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
523
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
524
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
525
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
526
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
527
+ function escapePathPattern(value) {
528
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
529
+ }
530
+ function machineHomePathPatterns(flags) {
531
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
532
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
533
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
534
+ }
510
535
  var CealProtocolValidationError = class extends Error {
511
536
  name = "CealProtocolValidationError";
512
537
  code;
@@ -858,10 +883,13 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
858
883
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
859
884
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
860
885
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
861
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
886
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
887
+ var CLIENT_HOST_RELEASE_MISMATCH = `Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry. Update with \`${CEAL_CLIENT_UPGRADE_COMMAND}\`.`;
862
888
  var HOST_INSTALL_REPAIR = "The local Host or Relay is missing, stale, or unavailable. Run `ceal-host install`, then `ceal-host discovery sync`, and retry from a new producer conversation.";
863
- var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
889
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn right now; the Host may be restarting. Wait briefly and retry the same command. If you know you are in an ephemeral side conversation, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions without Host session/turn correlation. Otherwise return to the original regular conversation. Host refusal never switches modes. If the retry still fails, report intended Host calls as a gap.";
890
+ var HOST_RELAY_RESTARTING = "The Host Relay is temporarily unavailable while the Host restarts; wait briefly and retry the same command. If the retry still fails, report this as a gap.";
864
891
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
892
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
865
893
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
866
894
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
867
895
  }
@@ -882,13 +910,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
882
910
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
883
911
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
884
912
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
885
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
886
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
887
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
888
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
889
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
890
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
891
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
913
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
914
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
915
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
916
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
917
+ 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),
918
+ 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),
919
+ 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),
920
+ // A stored session that predates the authority-epoch commitment carries no
921
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
922
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
923
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
924
+ 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),
925
+ 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),
926
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
927
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
892
928
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
893
929
  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),
894
930
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -903,10 +939,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
903
939
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
904
940
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
905
941
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
906
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
907
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
908
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
909
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
942
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
943
+ [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),
910
944
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
911
945
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
912
946
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -918,6 +952,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
918
952
  // The safe move varies by request. Keep the sentence conditional on the
919
953
  // same `retryable` and `next_action` facts the response exposes.
920
954
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
955
+ // 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.
956
+ 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),
921
957
  // Restored verbatim from the retired `localFailureText`
922
958
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
923
959
  // session context unavailable, so the caller repairs or adopts the
@@ -1008,7 +1044,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1008
1044
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
1009
1045
  // The bounded Host reason does not prove ephemerality. A Host refusal never
1010
1046
  // changes mode; standalone remains the separate Client authority path.
1011
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
1047
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
1012
1048
  host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
1013
1049
  host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
1014
1050
  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),
@@ -1025,7 +1061,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1025
1061
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
1026
1062
  // sandboxed Relay socket names the run-alone retry.
1027
1063
  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),
1028
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1064
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
1029
1065
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
1030
1066
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
1031
1067
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1273,7 +1309,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
1273
1309
  max_literal_nodes: 512
1274
1310
  });
1275
1311
 
1276
- // packages/ceal-client-protocol/src/operation-json-schema.ts
1312
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
1277
1313
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1278
1314
 
1279
1315
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -1420,7 +1456,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
1420
1456
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
1421
1457
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
1422
1458
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
1423
- var CEAL_MODEL_INPUT_SOURCE_GUIDANCE = `For caller-owned fields, add ${CEAL_OPERATION_INPUT_FLAG} ${shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)}. Use inline JSON for short input; for longer or generated input, put exactly one JSON object in a caller-owned regular non-symlink UTF-8 JSON file and pass --input @path; relative paths resolve from the command working directory.`;
1459
+ var CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE = `For caller-owned fields, add ${CEAL_OPERATION_INPUT_FLAG} ${shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)}. Use inline JSON for short input; for longer or generated input, put exactly one JSON object in a caller-owned regular non-symlink UTF-8 JSON file and pass --input @path; relative paths resolve from the command working directory.`;
1460
+ var CEAL_MODEL_INPUT_SOURCE_GUIDANCE = `${CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE} On Windows, write the JSON file first; use the program's .cmd launcher with --input and only one quoted @path argument.`;
1424
1461
  function shellSingleQuoted(value) {
1425
1462
  return `'${value.replaceAll("'", "'\\''")}'`;
1426
1463
  }
@@ -1567,6 +1604,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1567
1604
  "review_submitted",
1568
1605
  "comment_created",
1569
1606
  "reaction_created",
1607
+ "pull_request_merged",
1608
+ "release_published",
1570
1609
  "ceal_write_completed",
1571
1610
  "event_start",
1572
1611
  "all_day_start",
@@ -1578,7 +1617,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1578
1617
  "page_last_edited",
1579
1618
  "resource_modified"
1580
1619
  ]);
1581
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
1620
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
1582
1621
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
1583
1622
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
1584
1623
  "provider_page_budget",
@@ -1599,6 +1638,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1599
1638
  "github.pull_request.opened",
1600
1639
  "github.issue.edited",
1601
1640
  "github.pull_request.edited",
1641
+ "github.pull_request.merged",
1642
+ "github.release.published",
1602
1643
  "github.review.submitted",
1603
1644
  "github.issue_comment.created",
1604
1645
  "github.review_comment.created",
@@ -1612,6 +1653,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1612
1653
  "drive.file.created",
1613
1654
  "drive.file.modified",
1614
1655
  "drive.file.viewed",
1656
+ "mail.sent",
1615
1657
  "notion.page.created",
1616
1658
  "notion.page.edited"
1617
1659
  ]);
@@ -1625,6 +1667,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1625
1667
  "github.review_comment.created": "comment_created",
1626
1668
  "github.issue.opened": "resource_created",
1627
1669
  "github.pull_request.opened": "resource_created",
1670
+ "github.pull_request.merged": "pull_request_merged",
1671
+ "github.release.published": "release_published",
1628
1672
  "github.issue.edited": "resource_modified",
1629
1673
  "github.pull_request.edited": "resource_modified",
1630
1674
  "github.reaction.created": "reaction_created",
@@ -1635,6 +1679,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1635
1679
  "drive.file.created": "file_created",
1636
1680
  "drive.file.modified": "file_modified_by_me",
1637
1681
  "drive.file.viewed": "file_viewed_by_me",
1682
+ "mail.sent": "message_created",
1638
1683
  "notion.page.created": "page_created",
1639
1684
  "notion.page.edited": "page_last_edited"
1640
1685
  });
@@ -1745,6 +1790,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1745
1790
  "principal_inactive",
1746
1791
  "authority_replaced",
1747
1792
  "refresh_recovery_unavailable",
1793
+ "refresh_recovery_outcome_unavailable",
1794
+ "refresh_state_unavailable",
1748
1795
  "refresh_recovery_expired",
1749
1796
  // The serving gate answers this while the Gateway is still starting and the
1750
1797
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -2394,9 +2441,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2394
2441
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
2395
2442
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
2396
2443
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2397
- // This reason cannot distinguish a Codex side conversation from a missing
2398
- // context in a regular session, so guidance must leave that choice to the caller.
2399
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2444
+ // A missing turn right after a Host restart clears by itself once the
2445
+ // watcher reactivates the turn, so the caller waits briefly and retries;
2446
+ // a caller that knows it is in an ephemeral side conversation keeps the
2447
+ // standalone fallback the guidance names second.
2448
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
2400
2449
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2401
2450
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2402
2451
  // `no_binding` now means the producer has no real current Host session. The
@@ -2413,7 +2462,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2413
2462
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2414
2463
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2415
2464
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2416
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2465
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
2417
2466
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2418
2467
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2419
2468
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2503,6 +2552,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2503
2552
  maximum: CEAL_PROTOCOL_VERSION
2504
2553
  });
2505
2554
 
2555
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
2556
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2557
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2558
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2559
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2560
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2561
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2562
+ function redactOperatorDiagnosticSecrets(value) {
2563
+ 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]");
2564
+ }
2565
+ function redactOperatorDiagnosticText(value) {
2566
+ const normalized = normalizeCealSingleLineText(value);
2567
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2568
+ }
2569
+ function renderOperatorDiagnostic(value) {
2570
+ const state = collectDiagnosticState(value);
2571
+ const fields = [
2572
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2573
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2574
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
2575
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
2576
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
2577
+ ].filter((field) => field !== void 0);
2578
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2579
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2580
+ }
2581
+ function collectDiagnosticState(value) {
2582
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2583
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
2584
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2585
+ const current = pending.shift();
2586
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2587
+ }
2588
+ return state;
2589
+ }
2590
+ function visitDiagnosticNode(current, state, pending, visited) {
2591
+ if (isObject(current)) {
2592
+ if (visited.has(current)) return;
2593
+ visited.add(current);
2594
+ }
2595
+ captureProcessEvidence(current, state);
2596
+ appendCause(current, state.causes);
2597
+ enqueueCauseChildren(current, state.causes.length, pending);
2598
+ }
2599
+ function captureProcessEvidence(current, state) {
2600
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
2601
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
2602
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2603
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2604
+ }
2605
+ function appendCause(current, causes) {
2606
+ const errors = read(current, "errors");
2607
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2608
+ causes.push(errorCause(current));
2609
+ return;
2610
+ }
2611
+ if (!isObject(current)) {
2612
+ const message = safeText(current);
2613
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2614
+ }
2615
+ }
2616
+ function errorCause(error) {
2617
+ const name = safeText(read(error, "name")) ?? "Error";
2618
+ const message = safeText(read(error, "message"));
2619
+ const codeValue = read(error, "code");
2620
+ const code2 = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
2621
+ const errnoValue = read(error, "errno");
2622
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2623
+ const syscall = safeText(read(error, "syscall"));
2624
+ const path = safePath(read(error, "path"));
2625
+ 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 } });
2626
+ }
2627
+ function enqueueCauseChildren(current, causeCount, pending) {
2628
+ const cause = read(current, "cause");
2629
+ if (cause !== void 0) pending.push(cause);
2630
+ const errors = read(current, "errors");
2631
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2632
+ }
2633
+ function isObject(value) {
2634
+ return typeof value === "object" && value !== null;
2635
+ }
2636
+ function formatCause(cause) {
2637
+ const fields = [
2638
+ cause.error_class,
2639
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
2640
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
2641
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
2642
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
2643
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
2644
+ ].filter((field) => field !== void 0);
2645
+ return fields.join(" ");
2646
+ }
2647
+ function tail(value) {
2648
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
2649
+ return safeDiagnosticText(clipped);
2650
+ }
2651
+ function safeText(value) {
2652
+ if (typeof value !== "string") return void 0;
2653
+ const safe = safeDiagnosticText(value);
2654
+ if (safe.length === 0) return void 0;
2655
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
2656
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
2657
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2658
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2659
+ }
2660
+ function safePath(value) {
2661
+ if (typeof value !== "string") return void 0;
2662
+ const safe = safeDiagnosticText(value);
2663
+ if (safe.length === 0) return void 0;
2664
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2665
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2666
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
2667
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2668
+ }
2669
+ function safeDiagnosticText(value) {
2670
+ return redactOperatorDiagnosticText(String(value));
2671
+ }
2672
+ function outputText(value) {
2673
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
2674
+ if (value instanceof Uint8Array) {
2675
+ try {
2676
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
2677
+ } catch {
2678
+ return void 0;
2679
+ }
2680
+ }
2681
+ return void 0;
2682
+ }
2683
+ function safeStatus(value) {
2684
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2685
+ return typeof value === "string" ? safeText(value) : void 0;
2686
+ }
2687
+ function safeExitCode(value) {
2688
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
2689
+ }
2690
+ function read(value, key) {
2691
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
2692
+ try {
2693
+ return Reflect.get(value, key);
2694
+ } catch {
2695
+ return void 0;
2696
+ }
2697
+ }
2698
+ function redactHomePaths(value) {
2699
+ const paths = [
2700
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
2701
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
2702
+ ];
2703
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
2704
+ let output = "";
2705
+ let cursor = 0;
2706
+ for (const path of paths) {
2707
+ if (path.start < cursor) continue;
2708
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
2709
+ cursor = path.end;
2710
+ }
2711
+ return output + value.slice(cursor);
2712
+ }
2713
+ function configuredHomePathPatterns() {
2714
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
2715
+ return homes.flatMap((home) => {
2716
+ const root = home.replace(/[\\/]+$/gu, "");
2717
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
2718
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
2719
+ return [{ pattern, prefixLength: root.length }];
2720
+ });
2721
+ }
2722
+ function matchedHomePrefixLength(value) {
2723
+ let separators = 0;
2724
+ for (let index = 0; index < value.length; index += 1) {
2725
+ if (value[index] !== "/" && value[index] !== "\\") continue;
2726
+ separators += 1;
2727
+ if (separators === 3) return index;
2728
+ }
2729
+ return value.length;
2730
+ }
2731
+ function redactUrls(value) {
2732
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2733
+ }
2734
+ function redactFilePaths(value) {
2735
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2736
+ }
2737
+ function homePathRange(value, match, prefixLength) {
2738
+ const index = match.index;
2739
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
2740
+ const start = index;
2741
+ let end = start + match[0].length;
2742
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
2743
+ if (quote !== void 0) {
2744
+ const closing = value.indexOf(quote, end);
2745
+ if (closing >= 0) end = closing;
2746
+ }
2747
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
2748
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
2749
+ }
2750
+ function truncateUtf8(value, maxBytes) {
2751
+ if (byteLength(value) <= maxBytes) return value;
2752
+ let output = "";
2753
+ for (const character of value) {
2754
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
2755
+ output += character;
2756
+ }
2757
+ return `${output}…`;
2758
+ }
2759
+
2506
2760
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
2507
2761
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
2508
2762
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -2589,8 +2843,80 @@ function waitForAbort(signal, milliseconds) {
2589
2843
  import { execFile } from "node:child_process";
2590
2844
  import { constants } from "node:fs";
2591
2845
  import { lstat, open } from "node:fs/promises";
2592
- import { dirname, join as join2, win32 as win323 } from "node:path";
2846
+ import { dirname, join as join3, win32 as win323 } from "node:path";
2593
2847
  import { fileURLToPath } from "node:url";
2848
+
2849
+ // host/spawn-working-directory.ts
2850
+ import { mkdirSync } from "node:fs";
2851
+ import { tmpdir } from "node:os";
2852
+ import { isAbsolute, join as join2, normalize, parse, sep } from "node:path";
2853
+ function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
2854
+ const candidates = [];
2855
+ const explicit = candidateDir(stateRoot);
2856
+ if (explicit !== void 0) candidates.push(explicit);
2857
+ const fallback = defaultHostStateRoot();
2858
+ if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
2859
+ const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
2860
+ if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
2861
+ for (const dir of candidates) {
2862
+ if (!keptOutside(dir, keepOutside)) continue;
2863
+ try {
2864
+ mkdirSync(dir, { recursive: true, mode: 448 });
2865
+ return dir;
2866
+ } catch {
2867
+ continue;
2868
+ }
2869
+ }
2870
+ return tmpdir();
2871
+ }
2872
+ function candidateDir(dir) {
2873
+ if (dir === void 0 || dir === "") return void 0;
2874
+ if (!isAbsolute(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
2875
+ return normalize(dir);
2876
+ }
2877
+ function defaultHostStateRoot() {
2878
+ if (process.platform === "win32") {
2879
+ const localAppData = nonEmptyEnv("LOCALAPPDATA");
2880
+ if (localAppData === void 0) return void 0;
2881
+ return candidateDir(join2(localAppData, "Ceal", "Host"));
2882
+ }
2883
+ if (process.platform === "darwin") {
2884
+ const home2 = nonEmptyEnv("HOME");
2885
+ if (home2 === void 0) return void 0;
2886
+ return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
2887
+ }
2888
+ const xdg = nonEmptyEnv("XDG_STATE_HOME");
2889
+ if (xdg !== void 0) {
2890
+ const root = candidateDir(join2(xdg, "ceal", "host"));
2891
+ if (root !== void 0) return root;
2892
+ }
2893
+ const home = nonEmptyEnv("HOME");
2894
+ if (home === void 0) return void 0;
2895
+ return candidateDir(join2(home, ".local", "state", "ceal", "host"));
2896
+ }
2897
+ function nonEmptyEnv(name) {
2898
+ const value = process.env[name];
2899
+ return value === void 0 || value === "" ? void 0 : value;
2900
+ }
2901
+ function keptOutside(dir, keepOutside) {
2902
+ for (const tree of keepOutside) {
2903
+ const clean = candidateDir(tree);
2904
+ if (clean === void 0) continue;
2905
+ if (insideDir(dir, clean)) return false;
2906
+ }
2907
+ return true;
2908
+ }
2909
+ function insideDir(dir, tree) {
2910
+ if (sameDir(dir, tree)) return true;
2911
+ if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
2912
+ return dir.startsWith(tree + sep);
2913
+ }
2914
+ function sameDir(left, right) {
2915
+ if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
2916
+ return left === right;
2917
+ }
2918
+
2919
+ // host/secure-file.ts
2594
2920
  var SecureFileCustodyError = class extends Error {
2595
2921
  name = "SecureFileCustodyError";
2596
2922
  reason;
@@ -2689,7 +3015,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2689
3015
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2690
3016
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2691
3017
  return await new Promise((resolve, reject) => {
2692
- const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
3018
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: resolveCealSpawnWorkingDirectory() }, (error, stdout, stderr) => {
2693
3019
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2694
3020
  if (exitCode === null) {
2695
3021
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2718,7 +3044,7 @@ function securefsRefusal(stderr) {
2718
3044
  }
2719
3045
  function resolveInstalledHostExecutable(platform) {
2720
3046
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2721
- return platform === "win32" ? win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3047
+ return platform === "win32" ? win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2722
3048
  }
2723
3049
  function isRecord(value) {
2724
3050
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2934,7 +3260,7 @@ function parseCanonicalJson(text, error) {
2934
3260
  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) }])}`);
2935
3261
  return value;
2936
3262
  } catch (parseError) {
2937
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
3263
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
2938
3264
  }
2939
3265
  }
2940
3266
  function firstDifferenceIndex(left, right) {
@@ -3105,7 +3431,7 @@ function record(value) {
3105
3431
  import { createHash as createHash5 } from "node:crypto";
3106
3432
  import { constants as constants4 } from "node:fs";
3107
3433
  import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3108
- import { dirname as dirname4, join as join3 } from "node:path";
3434
+ import { dirname as dirname4, join as join4 } from "node:path";
3109
3435
 
3110
3436
  // host/relay/src/durable-atomic-replacement.ts
3111
3437
  import { lstat as lstat3, mkdir, open as open2, rename, unlink } from "node:fs/promises";
@@ -3258,9 +3584,9 @@ var HostUsageFactsStore = class {
3258
3584
  afterBatchPublish;
3259
3585
  sessionDirectoryCursor;
3260
3586
  constructor(options) {
3261
- this.root = join3(options.outbox_dir, "usage-facts");
3262
- this.sessions = join3(this.root, "sessions");
3263
- this.batches = join3(this.root, "batches");
3587
+ this.root = join4(options.outbox_dir, "usage-facts");
3588
+ this.sessions = join4(this.root, "sessions");
3589
+ this.batches = join4(this.root, "batches");
3264
3590
  this.platform = options.platform ?? process.platform;
3265
3591
  this.custody = options.secure_file_custody ?? {};
3266
3592
  this.afterPendingWrite = options.afterPendingWrite;
@@ -3277,7 +3603,6 @@ var HostUsageFactsStore = class {
3277
3603
  await cursor?.close();
3278
3604
  }
3279
3605
  async readState(producer, hostSourceRef, hostSessionRef) {
3280
- await this.prepare();
3281
3606
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3282
3607
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3283
3608
  if (value === null) return null;
@@ -3335,11 +3660,15 @@ var HostUsageFactsStore = class {
3335
3660
  }
3336
3661
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3337
3662
  async sweepOrphanedBatches(state) {
3338
- await this.prepare();
3339
3663
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3340
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3341
3664
  const expected = expectedBatchNames(state);
3342
- const directory = await opendir(directoryPath);
3665
+ let directory;
3666
+ try {
3667
+ directory = await opendir(directoryPath);
3668
+ } catch (error) {
3669
+ if (errorCode2(error) === "ENOENT") return 0;
3670
+ throw error;
3671
+ }
3343
3672
  let inspected = 0;
3344
3673
  let deleted = 0;
3345
3674
  try {
@@ -3348,7 +3677,7 @@ var HostUsageFactsStore = class {
3348
3677
  if (entry === null) break;
3349
3678
  inspected += 1;
3350
3679
  if (!isOrphanBatchEntry(entry, expected)) continue;
3351
- await unlink2(join3(directoryPath, entry.name));
3680
+ await unlink2(join4(directoryPath, entry.name));
3352
3681
  deleted += 1;
3353
3682
  }
3354
3683
  } finally {
@@ -3376,10 +3705,9 @@ var HostUsageFactsStore = class {
3376
3705
  });
3377
3706
  }
3378
3707
  async nextUploadCandidate(producer, hostSourceRef) {
3379
- await this.prepare();
3380
3708
  const names = await this.readNextSessionNames();
3381
3709
  for (const name of names) {
3382
- const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3710
+ const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3383
3711
  if (state === null) continue;
3384
3712
  validateStateOwner(state, producer, hostSourceRef);
3385
3713
  let validated = state;
@@ -3394,7 +3722,14 @@ var HostUsageFactsStore = class {
3394
3722
  return null;
3395
3723
  }
3396
3724
  async readNextSessionNames() {
3397
- this.sessionDirectoryCursor ??= await opendir(this.sessions);
3725
+ if (this.sessionDirectoryCursor === void 0) {
3726
+ try {
3727
+ this.sessionDirectoryCursor = await opendir(this.sessions);
3728
+ } catch (error) {
3729
+ if (errorCode2(error) === "ENOENT") return [];
3730
+ throw error;
3731
+ }
3732
+ }
3398
3733
  const names = [];
3399
3734
  let inspected = 0;
3400
3735
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -3549,25 +3884,25 @@ var HostUsageFactsStore = class {
3549
3884
  const gate = new Promise((resolve) => {
3550
3885
  release = resolve;
3551
3886
  });
3552
- const tail = previous.then(() => gate);
3553
- SESSION_TRANSITION_TAILS.set(key, tail);
3887
+ const tail2 = previous.then(() => gate);
3888
+ SESSION_TRANSITION_TAILS.set(key, tail2);
3554
3889
  await previous;
3555
3890
  try {
3556
3891
  return await run();
3557
3892
  } finally {
3558
3893
  release?.();
3559
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
3894
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3560
3895
  }
3561
3896
  }
3562
3897
  sessionPath(producer, hostSourceRef, hostSessionRef) {
3563
- return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3898
+ return join4(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3564
3899
  }
3565
3900
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3566
3901
  const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3567
- return join3(this.batches, sessionName.slice(0, -5));
3902
+ return join4(this.batches, sessionName.slice(0, -5));
3568
3903
  }
3569
3904
  batchPath(state, batchRef) {
3570
- return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3905
+ return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3571
3906
  }
3572
3907
  };
3573
3908
  function serializeBatch(batch) {
@@ -3808,7 +4143,7 @@ function sha2562(value) {
3808
4143
 
3809
4144
  // host/service-log.ts
3810
4145
  import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
3811
- import { dirname as dirname5, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
4146
+ import { dirname as dirname5, isAbsolute as isAbsolute2, posix as posix4, win32 as win325 } from "node:path";
3812
4147
 
3813
4148
  // host/service-log-delivery.ts
3814
4149
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -4003,7 +4338,7 @@ async function rotateHostServiceLog(path, maxBytes = HOST_SERVICE_LOG_MAX_BYTES)
4003
4338
  }
4004
4339
  function boundHostServiceLog(environment = process.env) {
4005
4340
  const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
4006
- if (path === void 0 || !isAbsolute(path)) return () => void 0;
4341
+ if (path === void 0 || !isAbsolute2(path)) return () => void 0;
4007
4342
  let reported = false;
4008
4343
  const ready = ensureHostServiceLogDirectory(path);
4009
4344
  const check = () => {
@@ -4038,7 +4373,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
4038
4373
  await appendHostServiceLogLine(path, line).catch(() => void 0);
4039
4374
  }
4040
4375
  async function appendHostServiceLogLine(path, line) {
4041
- if (!isAbsolute(path)) return;
4376
+ if (!isAbsolute2(path)) return;
4042
4377
  await ensureHostServiceLogDirectory(path);
4043
4378
  await appendFile(path, line);
4044
4379
  }
@@ -4074,6 +4409,10 @@ var HostUsageFactsUploader = class {
4074
4409
  async close() {
4075
4410
  await this.store.close();
4076
4411
  }
4412
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
4413
+ async prepare() {
4414
+ await this.store.prepare();
4415
+ }
4077
4416
  async uploadOne(signal) {
4078
4417
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4079
4418
  if (candidate === null) return false;
@@ -4096,6 +4435,11 @@ var HostUsageFactsUploader = class {
4096
4435
  };
4097
4436
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4098
4437
  const uploader = new HostUsageFactsUploader(options);
4438
+ try {
4439
+ await uploader.prepare();
4440
+ } catch {
4441
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4442
+ }
4099
4443
  let delay = 500;
4100
4444
  let failures = 0;
4101
4445
  try {
@@ -4125,6 +4469,7 @@ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4125
4469
 
4126
4470
  // host/relay/src/host-producer-core.ts
4127
4471
  import { createHash as createHash6 } from "node:crypto";
4472
+ import { readdir } from "node:fs/promises";
4128
4473
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
4129
4474
  function isHostTranscriptCursorReason(value) {
4130
4475
  return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
@@ -4169,9 +4514,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
4169
4514
  let lastNewline = -1;
4170
4515
  while (position < size) {
4171
4516
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
4172
- const read = await handle.read(buffer, 0, buffer.length, position);
4173
- if (read.bytesRead === 0) break;
4174
- const chunk = buffer.subarray(0, read.bytesRead);
4517
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
4518
+ if (read2.bytesRead === 0) break;
4519
+ const chunk = buffer.subarray(0, read2.bytesRead);
4175
4520
  chunks.push(chunk);
4176
4521
  const newline = chunk.lastIndexOf(10);
4177
4522
  if (newline >= 0) lastNewline = total + newline;
@@ -4330,6 +4675,14 @@ var HostTranscriptWatcher = class {
4330
4675
  return transcriptCursorBoundsReason(handle, cursor, size);
4331
4676
  }
4332
4677
  };
4678
+ async function listHostOutboxDirectoryNames(directory) {
4679
+ try {
4680
+ return await readdir(directory);
4681
+ } catch (error) {
4682
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
4683
+ throw error;
4684
+ }
4685
+ }
4333
4686
  var HostProducerDrainCore = class {
4334
4687
  host;
4335
4688
  now;
@@ -4344,21 +4697,21 @@ var HostProducerDrainCore = class {
4344
4697
  return run;
4345
4698
  }
4346
4699
  async drainLocked() {
4347
- const read = await this.host.listEnvelopes();
4700
+ const read2 = await this.host.listEnvelopes();
4348
4701
  let removed = 0;
4349
4702
  let expired = 0;
4350
- for (const envelope of read.entries) {
4703
+ for (const envelope of read2.entries) {
4351
4704
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
4352
4705
  else removed += 1;
4353
4706
  await this.host.removeEnvelope(envelope);
4354
4707
  }
4355
- return { removed, expired, malformed: read.malformed };
4708
+ return { removed, expired, malformed: read2.malformed };
4356
4709
  }
4357
4710
  };
4358
4711
 
4359
4712
  // host/claude/src/claude-outbox.ts
4360
- import { mkdir as mkdir4, readdir, readFile, unlink as unlink3 } from "node:fs/promises";
4361
- import { isAbsolute as isAbsolute3, join as join4 } from "node:path";
4713
+ import { mkdir as mkdir4, readFile, unlink as unlink3 } from "node:fs/promises";
4714
+ import { isAbsolute as isAbsolute4, join as join5 } from "node:path";
4362
4715
 
4363
4716
  // host/invocation-context.ts
4364
4717
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -4436,29 +4789,46 @@ var HostUsageTranscriptSourceError = class extends Error {
4436
4789
  this.name = "HostUsageTranscriptSourceError";
4437
4790
  }
4438
4791
  };
4439
- async function readHostUsageTranscriptSource(read) {
4792
+ async function readHostUsageTranscriptSource(read2) {
4440
4793
  try {
4441
- return await read();
4794
+ return await read2();
4442
4795
  } catch (error) {
4443
4796
  throw new HostUsageTranscriptSourceError({ cause: error });
4444
4797
  }
4445
4798
  }
4446
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4447
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4448
- let failed = false;
4449
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4450
- const index = (startIndex + attempt) % registrations.length;
4451
- const registration = registrations[index];
4452
- if (registration === void 0) continue;
4453
- try {
4454
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
4455
- } catch (error) {
4456
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4799
+ var HostUsageRegistrationCapture = class {
4800
+ nextIndex = 0;
4801
+ producer;
4802
+ diagnosticSink;
4803
+ constructor(producer, diagnosticSink) {
4804
+ this.producer = producer;
4805
+ this.diagnosticSink = diagnosticSink;
4806
+ }
4807
+ async captureNext(registrations, capture) {
4808
+ let failed = false;
4809
+ let captured = false;
4810
+ const onFailure = () => {
4457
4811
  failed = true;
4812
+ };
4813
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4814
+ const index = (this.nextIndex + attempt) % registrations.length;
4815
+ const registration = registrations[index];
4816
+ if (registration === void 0) continue;
4817
+ try {
4818
+ captured = await capture(registration, onFailure);
4819
+ if (captured) {
4820
+ this.nextIndex = (index + 1) % registrations.length;
4821
+ break;
4822
+ }
4823
+ } catch (error) {
4824
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4825
+ onFailure();
4826
+ }
4458
4827
  }
4828
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
4829
+ return captured;
4459
4830
  }
4460
- return { captured: false, nextIndex: startIndex, failed };
4461
- }
4831
+ };
4462
4832
  async function openHostUsageTranscriptCursor(input) {
4463
4833
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants5.O_RDONLY));
4464
4834
  let source;
@@ -4570,7 +4940,7 @@ var ClaudeHostError = class extends Error {
4570
4940
  };
4571
4941
 
4572
4942
  // host/claude/src/claude-invocation-context.ts
4573
- import { isAbsolute as isAbsolute2 } from "node:path";
4943
+ import { isAbsolute as isAbsolute3 } from "node:path";
4574
4944
  function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
4575
4945
  return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
4576
4946
  }
@@ -4599,7 +4969,7 @@ function optionalSafeRef(value) {
4599
4969
  return value === void 0 || safeRef2(value);
4600
4970
  }
4601
4971
  function optionalDirectory(value) {
4602
- return value === void 0 || typeof value === "string" && isAbsolute2(value) && !value.includes("\0") && value.length <= 4096;
4972
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && !value.includes("\0") && value.length <= 4096;
4603
4973
  }
4604
4974
  function safeRef2(value) {
4605
4975
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
@@ -4624,14 +4994,14 @@ var ClaudeOutboxStore = class {
4624
4994
  activeContexts;
4625
4995
  turnSelections;
4626
4996
  constructor(directory) {
4627
- if (!isAbsolute3(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
4997
+ if (!isAbsolute4(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
4628
4998
  this.directory = directory;
4629
- this.envelopes = join4(directory, "envelopes");
4630
- this.sessions = join4(directory, "sessions");
4631
- this.registrations = join4(directory, "transcript-registrations");
4632
- this.cursors = join4(directory, "transcript-cursors");
4633
- this.activeContexts = join4(directory, "active-contexts");
4634
- this.turnSelections = join4(directory, "turn-selections");
4999
+ this.envelopes = join5(directory, "envelopes");
5000
+ this.sessions = join5(directory, "sessions");
5001
+ this.registrations = join5(directory, "transcript-registrations");
5002
+ this.cursors = join5(directory, "transcript-cursors");
5003
+ this.activeContexts = join5(directory, "active-contexts");
5004
+ this.turnSelections = join5(directory, "turn-selections");
4635
5005
  }
4636
5006
  async prepare() {
4637
5007
  for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
@@ -4659,6 +5029,7 @@ var ClaudeOutboxStore = class {
4659
5029
  const path = this.activeContextPath(identity);
4660
5030
  const active = await readProjectionFile(path);
4661
5031
  if (active === null || active.prompt_ref !== promptRef || active.identity.host_turn_ref !== identity.host_turn_ref) return false;
5032
+ await this.prepare();
4662
5033
  const updated = { ...active, turn_generation_ref: turnGenerationRef };
4663
5034
  validateClaudeHostInvocationContext(updated);
4664
5035
  await durableAtomicReplace(path, JSON.stringify(updated));
@@ -4671,17 +5042,15 @@ var ClaudeOutboxStore = class {
4671
5042
  */
4672
5043
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
4673
5044
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
4674
- await this.prepare();
4675
5045
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, readProjectionFile);
4676
5046
  return context;
4677
5047
  }
4678
5048
  async listInvocationContexts(now = /* @__PURE__ */ new Date()) {
4679
- await this.prepare();
4680
5049
  const contexts = [];
4681
- for (const name of await readdir(this.activeContexts)) {
5050
+ for (const name of await listHostOutboxDirectoryNames(this.activeContexts)) {
4682
5051
  if (!name.endsWith(".json")) continue;
4683
5052
  try {
4684
- const value = JSON.parse(await readFile(join4(this.activeContexts, name), "utf8"));
5053
+ const value = JSON.parse(await readFile(join5(this.activeContexts, name), "utf8"));
4685
5054
  validateClaudeHostInvocationContext(value);
4686
5055
  if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
4687
5056
  } catch {
@@ -4695,13 +5064,12 @@ var ClaudeOutboxStore = class {
4695
5064
  await durableAtomicReplace(this.envelopePath(entry.submission_ref), JSON.stringify(entry));
4696
5065
  }
4697
5066
  async listEnvelopes() {
4698
- await this.prepare();
4699
5067
  const entries = [];
4700
5068
  let malformed = 0;
4701
- for (const name of await readdir(this.envelopes)) {
5069
+ for (const name of await listHostOutboxDirectoryNames(this.envelopes)) {
4702
5070
  if (!name.endsWith(".json")) continue;
4703
5071
  try {
4704
- const value = JSON.parse(await readFile(join4(this.envelopes, name), "utf8"));
5072
+ const value = JSON.parse(await readFile(join5(this.envelopes, name), "utf8"));
4705
5073
  validateEnvelope(value);
4706
5074
  entries.push(value);
4707
5075
  } catch {
@@ -4722,13 +5090,12 @@ var ClaudeOutboxStore = class {
4722
5090
  async saveSession(snapshot) {
4723
5091
  validateSession(snapshot);
4724
5092
  await this.prepare();
4725
- await durableAtomicReplace(join4(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
5093
+ await durableAtomicReplace(join5(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
4726
5094
  }
4727
5095
  async readSession(sourceRef, sessionRef) {
4728
5096
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
4729
- await this.prepare();
4730
5097
  try {
4731
- const value = JSON.parse(await readFile(join4(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
5098
+ const value = JSON.parse(await readFile(join5(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
4732
5099
  validateSession(value);
4733
5100
  return value;
4734
5101
  } catch (error) {
@@ -4757,13 +5124,18 @@ var ClaudeOutboxStore = class {
4757
5124
  await this.removeStateFile(this.registrationPath(registration.host_source_ref, registration.host_session_ref));
4758
5125
  await this.removeStateFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref));
4759
5126
  }
5127
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
5128
+ if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
5129
+ const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
5130
+ 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.");
5131
+ return registration;
5132
+ }
4760
5133
  async listTranscriptRegistrations() {
4761
- await this.prepare();
4762
5134
  const registrations = [];
4763
- for (const name of await readdir(this.registrations)) {
5135
+ for (const name of await listHostOutboxDirectoryNames(this.registrations)) {
4764
5136
  if (!name.endsWith(".json")) continue;
4765
5137
  try {
4766
- const value = JSON.parse(await readFile(join4(this.registrations, name), "utf8"));
5138
+ const value = JSON.parse(await readFile(join5(this.registrations, name), "utf8"));
4767
5139
  validateRegistration(value);
4768
5140
  registrations.push(value);
4769
5141
  } catch {
@@ -4773,7 +5145,6 @@ var ClaudeOutboxStore = class {
4773
5145
  }
4774
5146
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
4775
5147
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host turn selection identity is invalid.");
4776
- await this.prepare();
4777
5148
  try {
4778
5149
  const value = JSON.parse(await readFile(this.turnSelectionPath(hostSourceRef, hostSessionRef), "utf8"));
4779
5150
  if (!isHostInvocationTurnSelection(value) || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new ClaudeHostError("storage", "Claude Host turn selection is malformed.");
@@ -4785,7 +5156,6 @@ var ClaudeOutboxStore = class {
4785
5156
  }
4786
5157
  async readTranscriptCursor(registration) {
4787
5158
  validateRegistration(registration);
4788
- await this.prepare();
4789
5159
  try {
4790
5160
  const value = JSON.parse(await readFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "utf8"));
4791
5161
  validateCursor(value);
@@ -4801,16 +5171,16 @@ var ClaudeOutboxStore = class {
4801
5171
  await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
4802
5172
  }
4803
5173
  envelopePath(ref) {
4804
- return join4(this.envelopes, `${cealRequestSha256(ref)}.json`);
5174
+ return join5(this.envelopes, `${cealRequestSha256(ref)}.json`);
4805
5175
  }
4806
5176
  registrationPath(sourceRef, sessionRef) {
4807
- return join4(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
5177
+ return join5(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4808
5178
  }
4809
5179
  turnSelectionPath(sourceRef, sessionRef) {
4810
- return join4(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
5180
+ return join5(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4811
5181
  }
4812
5182
  cursorPath(sourceRef, sessionRef) {
4813
- return join4(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
5183
+ return join5(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4814
5184
  }
4815
5185
  async readRegistrationFile(path) {
4816
5186
  try {
@@ -4830,7 +5200,7 @@ var ClaudeOutboxStore = class {
4830
5200
  }
4831
5201
  }
4832
5202
  activeContextPath(identity) {
4833
- return join4(this.activeContexts, `${invocationContextKey(identity)}.json`);
5203
+ return join5(this.activeContexts, `${invocationContextKey(identity)}.json`);
4834
5204
  }
4835
5205
  };
4836
5206
  function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
@@ -4906,7 +5276,7 @@ function validateRegistration(value) {
4906
5276
  if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
4907
5277
  }
4908
5278
  function validateRegistrationPaths(cwd, transcriptPath) {
4909
- if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute3(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
5279
+ if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute4(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
4910
5280
  throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
4911
5281
  }
4912
5282
  if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
@@ -5026,7 +5396,8 @@ var ClaudeProducer = class {
5026
5396
 
5027
5397
  // host/claude/src/claude-transcript-watcher.ts
5028
5398
  import { readdir as readdir2 } from "node:fs/promises";
5029
- import { join as join5 } from "node:path";
5399
+ import { isDeepStrictEqual } from "node:util";
5400
+ import { join as join6 } from "node:path";
5030
5401
 
5031
5402
  // host/claude/src/claude-decoder.ts
5032
5403
  import { createHash as createHash7 } from "node:crypto";
@@ -5111,10 +5482,39 @@ function record4(value) {
5111
5482
  return value !== null && typeof value === "object" && !Array.isArray(value);
5112
5483
  }
5113
5484
 
5485
+ // host/claude/src/claude-subagent-overflow-checkpoint.ts
5486
+ var ClaudeSubagentOverflowCheckpoint = class {
5487
+ observed = /* @__PURE__ */ new Map();
5488
+ prune(registrations) {
5489
+ const current = new Set(registrations.map(registrationKey));
5490
+ for (const key of this.observed.keys()) if (!current.has(key)) this.observed.delete(key);
5491
+ }
5492
+ clear(registration) {
5493
+ this.observed.delete(registrationKey(registration));
5494
+ }
5495
+ /** Names follow the producer's sorted inventory; only omitted names define overflow. */
5496
+ async observe(registration, names, report) {
5497
+ const key = registrationKey(registration);
5498
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
5499
+ this.clear(registration);
5500
+ return false;
5501
+ }
5502
+ const digest = transcriptObjectSha256(names.slice(CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES));
5503
+ if (this.observed.get(key) === digest) return false;
5504
+ if (!await report()) return false;
5505
+ this.observed.set(key, digest);
5506
+ return true;
5507
+ }
5508
+ };
5509
+ function registrationKey(registration) {
5510
+ return JSON.stringify([registration.host_source_ref, registration.host_session_ref, registration.transcript_path]);
5511
+ }
5512
+
5114
5513
  // host/claude/src/claude-transcript-watcher.ts
5115
5514
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
5116
5515
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5117
5516
  store;
5517
+ overflow = new ClaudeSubagentOverflowCheckpoint();
5118
5518
  diagnostic;
5119
5519
  constructor(options) {
5120
5520
  super(options, {
@@ -5129,7 +5529,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5129
5529
  return registration.transcript_path;
5130
5530
  }
5131
5531
  async listRegistrations() {
5132
- return this.store.listTranscriptRegistrations();
5532
+ const registrations = await this.store.listTranscriptRegistrations();
5533
+ this.overflow.prune(registrations);
5534
+ return registrations;
5133
5535
  }
5134
5536
  async scanOpened(handle, registration) {
5135
5537
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
@@ -5141,7 +5543,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5141
5543
  }
5142
5544
  if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
5143
5545
  const draft = mutableCursor(cursor);
5144
- await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
5546
+ await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
5145
5547
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
5146
5548
  }
5147
5549
  async scanFailed(handle, registration, error) {
@@ -5178,7 +5580,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5178
5580
  updated_at: this.stamp()
5179
5581
  };
5180
5582
  }
5181
- async scanOpenedTranscript(registration, handle, draft, size, device, inode) {
5583
+ async scanOpenedTranscript(registration, handle, previous, draft, size, device, inode) {
5182
5584
  const main = await this.readChunk(handle, draft.offset, size);
5183
5585
  if (main !== "empty" && main !== "partial") {
5184
5586
  await this.consumeMainChunk(registration, main, draft);
@@ -5186,7 +5588,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5186
5588
  }
5187
5589
  draft.consumed += await this.consumeSubagents(registration, draft);
5188
5590
  await this.emitOpenTerminal(registration, draft);
5189
- await this.commitCursor(registration, handle, draft, device, inode);
5591
+ await this.commitCursor(registration, handle, previous, draft, device, inode);
5190
5592
  }
5191
5593
  async preflight(registration, handle, size, device, inode) {
5192
5594
  const existing = await this.store.readTranscriptCursor(registration);
@@ -5346,15 +5748,24 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5346
5748
  try {
5347
5749
  names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
5348
5750
  } catch (error) {
5349
- if (isMissingTranscriptError(error) || isNotDirectory(error)) return 0;
5751
+ if (isMissingTranscriptError(error) || isNotDirectory(error)) {
5752
+ this.overflow.clear(registration);
5753
+ return 0;
5754
+ }
5350
5755
  throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
5351
5756
  }
5352
5757
  const listed = new Set(names);
5353
5758
  for (const name of Object.keys(draft.subagents)) if (!listed.has(name)) delete draft.subagents[name];
5354
- if (names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
5355
- this.log(`Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`);
5356
- names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5357
- }
5759
+ await this.overflow.observe(registration, names, () => {
5760
+ const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
5761
+ try {
5762
+ this.log(line);
5763
+ } catch {
5764
+ return false;
5765
+ }
5766
+ return true;
5767
+ });
5768
+ names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5358
5769
  let consumed = 0;
5359
5770
  for (const name of names) {
5360
5771
  consumed += await this.consumeSubagentFile(draft, directory, name);
@@ -5362,7 +5773,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5362
5773
  return consumed;
5363
5774
  }
5364
5775
  async consumeSubagentFile(draft, directory, name) {
5365
- const path = join5(directory, name);
5776
+ const path = join6(directory, name);
5366
5777
  let handle;
5367
5778
  try {
5368
5779
  handle = await openNoFollow(path);
@@ -5443,9 +5854,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5443
5854
  expires_at: this.expire(this.outboxRetentionMs)
5444
5855
  });
5445
5856
  }
5446
- async commitCursor(registration, handle, draft, device, inode) {
5857
+ async commitCursor(registration, handle, previous, draft, device, inode) {
5447
5858
  const anchor = await this.readAnchor(handle, draft.offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
5448
- await this.store.writeTranscriptCursor({
5859
+ const cursor = {
5449
5860
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
5450
5861
  host_source_ref: registration.host_source_ref,
5451
5862
  host_session_ref: registration.host_session_ref,
@@ -5462,7 +5873,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5462
5873
  ...draft.session_observed ? { session_observed: true } : {},
5463
5874
  status: "active",
5464
5875
  updated_at: this.stamp()
5465
- });
5876
+ };
5877
+ if (sameCursorContent(cursor, previous)) return;
5878
+ await this.store.writeTranscriptCursor(cursor);
5466
5879
  }
5467
5880
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
5468
5881
  try {
@@ -5513,6 +5926,9 @@ function mutableCursor(cursor) {
5513
5926
  enqueued: 0
5514
5927
  };
5515
5928
  }
5929
+ function sameCursorContent(left, right) {
5930
+ return isDeepStrictEqual({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
5931
+ }
5516
5932
  function zeroCounts() {
5517
5933
  return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
5518
5934
  }
@@ -5606,7 +6022,7 @@ function isAssistantUsageLine(record5) {
5606
6022
  }
5607
6023
  function subagentsDirectory(transcriptPath) {
5608
6024
  const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
5609
- return join5(stem, "subagents");
6025
+ return join6(stem, "subagents");
5610
6026
  }
5611
6027
  function observationRef(hostSourceRef, event, identity, value) {
5612
6028
  return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
@@ -5643,11 +6059,14 @@ function isSymlinkTranscript(error) {
5643
6059
  }
5644
6060
 
5645
6061
  // host/claude/src/claude-producer-runtime.ts
5646
- async function drainClaudeProducerOnce(options) {
5647
- const scan = await new ClaudeTranscriptWatcher({
5648
- outbox_dir: options.outbox_dir,
6062
+ function createClaudeProducerWatcher(outboxDir) {
6063
+ return new ClaudeTranscriptWatcher({
6064
+ outbox_dir: outboxDir,
5649
6065
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
5650
- }).scanOnce().catch((error) => {
6066
+ });
6067
+ }
6068
+ async function drainClaudeProducerOnce(options) {
6069
+ const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
5651
6070
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
5652
6071
  throw error;
5653
6072
  });
@@ -5659,30 +6078,25 @@ async function drainClaudeProducerOnce(options) {
5659
6078
  import { createHash as createHash8 } from "node:crypto";
5660
6079
  import { constants as constants6 } from "node:fs";
5661
6080
  import { readdir as readdir3 } from "node:fs/promises";
5662
- import { join as join6 } from "node:path";
6081
+ import { join as join7 } from "node:path";
5663
6082
  var ClaudeUsageFactsCapturer = class {
5664
6083
  sources;
5665
6084
  usage;
5666
6085
  now;
5667
- diagnosticSink;
5668
- nextRegistrationIndex = 0;
6086
+ registrations;
5669
6087
  nextSourceSlot = "main";
5670
6088
  nextSubagentIndex = 0;
6089
+ overflow = new ClaudeSubagentOverflowCheckpoint();
5671
6090
  constructor(options) {
5672
6091
  this.sources = new ClaudeOutboxStore(options.outbox_dir);
5673
6092
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5674
6093
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5675
- this.diagnosticSink = options.diagnostic_sink;
6094
+ this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
5676
6095
  }
5677
6096
  async captureNext() {
5678
6097
  const registrations = await this.sources.listTranscriptRegistrations();
5679
- let failed = false;
5680
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
5681
- failed = true;
5682
- }));
5683
- this.nextRegistrationIndex = result.nextIndex;
5684
- if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5685
- return result.captured;
6098
+ this.overflow.prune(registrations);
6099
+ return await this.registrations.captureNext(registrations, (registration, onFailure) => this.captureRegistration(registration, onFailure));
5686
6100
  }
5687
6101
  async captureRegistration(registration, onFailure) {
5688
6102
  const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
@@ -5729,13 +6143,14 @@ var ClaudeUsageFactsCapturer = class {
5729
6143
  }
5730
6144
  async captureSubagent(registration, onFailure) {
5731
6145
  const names = await readSubagentNames(registration);
6146
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
5732
6147
  let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
5733
6148
  if (state === null) return false;
5734
6149
  state = await this.usage.recoverPending(state);
5735
6150
  if (state.quarantined_reason !== void 0) return false;
5736
6151
  if (await this.retireMissingSubagent(state, names)) return true;
5737
6152
  if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
5738
- return await this.recordExcessSubagentGap(state, names);
6153
+ return await this.recordExcessSubagentGap(registration, state, names);
5739
6154
  }
5740
6155
  async retireMissingSubagent(state, names) {
5741
6156
  const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
@@ -5746,14 +6161,14 @@ var ClaudeUsageFactsCapturer = class {
5746
6161
  }
5747
6162
  return false;
5748
6163
  }
5749
- async recordExcessSubagentGap(state, names) {
5750
- const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
5751
- if (excessCount <= 0) return false;
6164
+ async recordExcessSubagentGap(registration, state, names) {
5752
6165
  const mainCursor = state.cursors.main;
5753
6166
  if (mainCursor === void 0) return false;
5754
- const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
5755
- await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
5756
- return true;
6167
+ return await this.overflow.observe(registration, names, async () => {
6168
+ 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 };
6169
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
6170
+ return true;
6171
+ });
5757
6172
  }
5758
6173
  async captureListedSubagents(registration, names, state, onFailure) {
5759
6174
  const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
@@ -5776,7 +6191,7 @@ var ClaudeUsageFactsCapturer = class {
5776
6191
  async captureSubagentFile(registration, name, state) {
5777
6192
  let handle;
5778
6193
  try {
5779
- const opened = await readHostUsageTranscriptSource(() => openNoFollow(join6(subagentsDirectory(registration.transcript_path), name), constants6.O_RDONLY));
6194
+ const opened = await readHostUsageTranscriptSource(() => openNoFollow(join7(subagentsDirectory(registration.transcript_path), name), constants6.O_RDONLY));
5780
6195
  handle = opened;
5781
6196
  const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
5782
6197
  const sourceRef = sourceFileRef(registration, file.device, file.inode);
@@ -6035,7 +6450,7 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
6035
6450
  producer_id: "claude",
6036
6451
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
6037
6452
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
6038
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6453
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createClaudeProducerWatcher(config.outbox_dir) }),
6039
6454
  drain: drainClaudeProducerOnce,
6040
6455
  background: (config, signal, dependencies) => {
6041
6456
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });