@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.
@@ -88,7 +88,7 @@ var client_wire_contract_default = {
88
88
  },
89
89
  command_request: {
90
90
  schema_name: "ceal.command_request",
91
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
91
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
92
92
  absolute_transport_max_bytes: 65536
93
93
  },
94
94
  command_resolution: {
@@ -134,7 +134,7 @@ var client_wire_contract_default = {
134
134
  },
135
135
  command_response: {
136
136
  schema_name: "ceal.command_response",
137
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
137
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
138
138
  descriptor_field: "verified_artifact",
139
139
  request_context_field: "request_context",
140
140
  required_fields: [
@@ -147,7 +147,8 @@ var client_wire_contract_default = {
147
147
  "visible_output_max_bytes",
148
148
  "local_delivery",
149
149
  "verified_artifact",
150
- "request_context"
150
+ "request_context",
151
+ "result_file"
151
152
  ],
152
153
  bare_document_fields: [
153
154
  "invocation",
@@ -276,6 +277,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
276
277
  // (never connected, revoked, or expired). The caller runs that exact
277
278
  // Operation, completes the consent it hands back, and retries the same call.
278
279
  "connect_personal_account",
280
+ // The refusal names the caller's own preferences update step: the read
281
+ // needs a personal connection the caller holds but has not selected in
282
+ // Ceal preferences, or has not confirmed through the initial review. The
283
+ // caller reads personal.preferences.get, runs personal.preferences.update
284
+ // at the current revision to select it, and retries the same call.
285
+ "update_personal_preferences",
279
286
  // The provider or Gateway named a bounded wait; the caller waits that long
280
287
  // and submits the same read again.
281
288
  "retry_after",
@@ -416,6 +423,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
416
423
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
417
424
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
418
425
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
426
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
427
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
428
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
419
429
  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"]);
420
430
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
421
431
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -456,6 +466,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
456
466
  ]);
457
467
 
458
468
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
469
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
470
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
471
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
472
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
473
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
474
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
475
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
476
+ function escapePathPattern(value) {
477
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
478
+ }
479
+ function machineHomePathPatterns(flags) {
480
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
481
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
482
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
483
+ }
459
484
  var CealProtocolValidationError = class extends Error {
460
485
  name = "CealProtocolValidationError";
461
486
  code;
@@ -812,10 +837,13 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
812
837
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
813
838
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
814
839
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
815
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
840
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
841
+ 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}\`.`;
816
842
  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.";
817
- 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.";
843
+ 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.";
844
+ 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.";
818
845
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
846
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
819
847
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
820
848
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
821
849
  }
@@ -836,13 +864,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
836
864
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
837
865
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
838
866
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
839
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
840
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
841
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
842
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
843
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
844
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
845
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
867
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
868
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
869
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
870
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
871
+ 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),
872
+ 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),
873
+ 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),
874
+ // A stored session that predates the authority-epoch commitment carries no
875
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
876
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
877
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
878
+ 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),
879
+ 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),
880
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
881
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
846
882
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
847
883
  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),
848
884
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -857,10 +893,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
857
893
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
858
894
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
859
895
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
860
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
861
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
862
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
863
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
896
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
897
+ [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),
864
898
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
865
899
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
866
900
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -872,6 +906,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
872
906
  // The safe move varies by request. Keep the sentence conditional on the
873
907
  // same `retryable` and `next_action` facts the response exposes.
874
908
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
909
+ // 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.
910
+ 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),
875
911
  // Restored verbatim from the retired `localFailureText`
876
912
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
877
913
  // session context unavailable, so the caller repairs or adopts the
@@ -962,7 +998,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
962
998
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
963
999
  // The bounded Host reason does not prove ephemerality. A Host refusal never
964
1000
  // changes mode; standalone remains the separate Client authority path.
965
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
1001
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
966
1002
  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),
967
1003
  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),
968
1004
  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),
@@ -979,7 +1015,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
979
1015
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
980
1016
  // sandboxed Relay socket names the run-alone retry.
981
1017
  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),
982
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1018
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
983
1019
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
984
1020
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
985
1021
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1244,7 +1280,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
1244
1280
  max_literal_nodes: 512
1245
1281
  });
1246
1282
 
1247
- // packages/ceal-client-protocol/src/operation-json-schema.ts
1283
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
1248
1284
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1249
1285
 
1250
1286
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -1394,7 +1430,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
1394
1430
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
1395
1431
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
1396
1432
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
1397
- 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.`;
1433
+ 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.`;
1434
+ 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.`;
1398
1435
  function shellSingleQuoted(value) {
1399
1436
  return `'${value.replaceAll("'", "'\\''")}'`;
1400
1437
  }
@@ -1541,6 +1578,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1541
1578
  "review_submitted",
1542
1579
  "comment_created",
1543
1580
  "reaction_created",
1581
+ "pull_request_merged",
1582
+ "release_published",
1544
1583
  "ceal_write_completed",
1545
1584
  "event_start",
1546
1585
  "all_day_start",
@@ -1552,7 +1591,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1552
1591
  "page_last_edited",
1553
1592
  "resource_modified"
1554
1593
  ]);
1555
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
1594
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
1556
1595
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
1557
1596
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
1558
1597
  "provider_page_budget",
@@ -1573,6 +1612,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1573
1612
  "github.pull_request.opened",
1574
1613
  "github.issue.edited",
1575
1614
  "github.pull_request.edited",
1615
+ "github.pull_request.merged",
1616
+ "github.release.published",
1576
1617
  "github.review.submitted",
1577
1618
  "github.issue_comment.created",
1578
1619
  "github.review_comment.created",
@@ -1586,6 +1627,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1586
1627
  "drive.file.created",
1587
1628
  "drive.file.modified",
1588
1629
  "drive.file.viewed",
1630
+ "mail.sent",
1589
1631
  "notion.page.created",
1590
1632
  "notion.page.edited"
1591
1633
  ]);
@@ -1599,6 +1641,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1599
1641
  "github.review_comment.created": "comment_created",
1600
1642
  "github.issue.opened": "resource_created",
1601
1643
  "github.pull_request.opened": "resource_created",
1644
+ "github.pull_request.merged": "pull_request_merged",
1645
+ "github.release.published": "release_published",
1602
1646
  "github.issue.edited": "resource_modified",
1603
1647
  "github.pull_request.edited": "resource_modified",
1604
1648
  "github.reaction.created": "reaction_created",
@@ -1609,6 +1653,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1609
1653
  "drive.file.created": "file_created",
1610
1654
  "drive.file.modified": "file_modified_by_me",
1611
1655
  "drive.file.viewed": "file_viewed_by_me",
1656
+ "mail.sent": "message_created",
1612
1657
  "notion.page.created": "page_created",
1613
1658
  "notion.page.edited": "page_last_edited"
1614
1659
  });
@@ -1719,6 +1764,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1719
1764
  "principal_inactive",
1720
1765
  "authority_replaced",
1721
1766
  "refresh_recovery_unavailable",
1767
+ "refresh_recovery_outcome_unavailable",
1768
+ "refresh_state_unavailable",
1722
1769
  "refresh_recovery_expired",
1723
1770
  // The serving gate answers this while the Gateway is still starting and the
1724
1771
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -2420,9 +2467,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2420
2467
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
2421
2468
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
2422
2469
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2423
- // This reason cannot distinguish a Codex side conversation from a missing
2424
- // context in a regular session, so guidance must leave that choice to the caller.
2425
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2470
+ // A missing turn right after a Host restart clears by itself once the
2471
+ // watcher reactivates the turn, so the caller waits briefly and retries;
2472
+ // a caller that knows it is in an ephemeral side conversation keeps the
2473
+ // standalone fallback the guidance names second.
2474
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
2426
2475
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2427
2476
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2428
2477
  // `no_binding` now means the producer has no real current Host session. The
@@ -2439,7 +2488,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2439
2488
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2440
2489
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2441
2490
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2442
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2491
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
2443
2492
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2444
2493
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2445
2494
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2564,6 +2613,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2564
2613
  maximum: CEAL_PROTOCOL_VERSION
2565
2614
  });
2566
2615
 
2616
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
2617
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2618
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2619
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2620
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2621
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2622
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2623
+ function redactOperatorDiagnosticSecrets(value) {
2624
+ 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]");
2625
+ }
2626
+ function redactOperatorDiagnosticText(value) {
2627
+ const normalized = normalizeCealSingleLineText(value);
2628
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2629
+ }
2630
+ function renderOperatorDiagnostic(value) {
2631
+ const state = collectDiagnosticState(value);
2632
+ const fields = [
2633
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2634
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2635
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
2636
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
2637
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
2638
+ ].filter((field) => field !== void 0);
2639
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2640
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2641
+ }
2642
+ function collectDiagnosticState(value) {
2643
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2644
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
2645
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2646
+ const current = pending.shift();
2647
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2648
+ }
2649
+ return state;
2650
+ }
2651
+ function visitDiagnosticNode(current, state, pending, visited) {
2652
+ if (isObject(current)) {
2653
+ if (visited.has(current)) return;
2654
+ visited.add(current);
2655
+ }
2656
+ captureProcessEvidence(current, state);
2657
+ appendCause(current, state.causes);
2658
+ enqueueCauseChildren(current, state.causes.length, pending);
2659
+ }
2660
+ function captureProcessEvidence(current, state) {
2661
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
2662
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
2663
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2664
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2665
+ }
2666
+ function appendCause(current, causes) {
2667
+ const errors = read(current, "errors");
2668
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2669
+ causes.push(errorCause(current));
2670
+ return;
2671
+ }
2672
+ if (!isObject(current)) {
2673
+ const message = safeText(current);
2674
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2675
+ }
2676
+ }
2677
+ function errorCause(error) {
2678
+ const name = safeText(read(error, "name")) ?? "Error";
2679
+ const message = safeText(read(error, "message"));
2680
+ const codeValue = read(error, "code");
2681
+ const code2 = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
2682
+ const errnoValue = read(error, "errno");
2683
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2684
+ const syscall = safeText(read(error, "syscall"));
2685
+ const path = safePath(read(error, "path"));
2686
+ 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 } });
2687
+ }
2688
+ function enqueueCauseChildren(current, causeCount, pending) {
2689
+ const cause = read(current, "cause");
2690
+ if (cause !== void 0) pending.push(cause);
2691
+ const errors = read(current, "errors");
2692
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2693
+ }
2694
+ function isObject(value) {
2695
+ return typeof value === "object" && value !== null;
2696
+ }
2697
+ function formatCause(cause) {
2698
+ const fields = [
2699
+ cause.error_class,
2700
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
2701
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
2702
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
2703
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
2704
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
2705
+ ].filter((field) => field !== void 0);
2706
+ return fields.join(" ");
2707
+ }
2708
+ function tail(value) {
2709
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
2710
+ return safeDiagnosticText(clipped);
2711
+ }
2712
+ function safeText(value) {
2713
+ if (typeof value !== "string") return void 0;
2714
+ const safe = safeDiagnosticText(value);
2715
+ if (safe.length === 0) return void 0;
2716
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
2717
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
2718
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2719
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2720
+ }
2721
+ function safePath(value) {
2722
+ if (typeof value !== "string") return void 0;
2723
+ const safe = safeDiagnosticText(value);
2724
+ if (safe.length === 0) return void 0;
2725
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2726
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2727
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
2728
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2729
+ }
2730
+ function safeDiagnosticText(value) {
2731
+ return redactOperatorDiagnosticText(String(value));
2732
+ }
2733
+ function outputText(value) {
2734
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
2735
+ if (value instanceof Uint8Array) {
2736
+ try {
2737
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
2738
+ } catch {
2739
+ return void 0;
2740
+ }
2741
+ }
2742
+ return void 0;
2743
+ }
2744
+ function safeStatus(value) {
2745
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2746
+ return typeof value === "string" ? safeText(value) : void 0;
2747
+ }
2748
+ function safeExitCode(value) {
2749
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
2750
+ }
2751
+ function read(value, key) {
2752
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
2753
+ try {
2754
+ return Reflect.get(value, key);
2755
+ } catch {
2756
+ return void 0;
2757
+ }
2758
+ }
2759
+ function redactHomePaths(value) {
2760
+ const paths = [
2761
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
2762
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
2763
+ ];
2764
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
2765
+ let output = "";
2766
+ let cursor = 0;
2767
+ for (const path of paths) {
2768
+ if (path.start < cursor) continue;
2769
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
2770
+ cursor = path.end;
2771
+ }
2772
+ return output + value.slice(cursor);
2773
+ }
2774
+ function configuredHomePathPatterns() {
2775
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
2776
+ return homes.flatMap((home) => {
2777
+ const root = home.replace(/[\\/]+$/gu, "");
2778
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
2779
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
2780
+ return [{ pattern, prefixLength: root.length }];
2781
+ });
2782
+ }
2783
+ function matchedHomePrefixLength(value) {
2784
+ let separators = 0;
2785
+ for (let index = 0; index < value.length; index += 1) {
2786
+ if (value[index] !== "/" && value[index] !== "\\") continue;
2787
+ separators += 1;
2788
+ if (separators === 3) return index;
2789
+ }
2790
+ return value.length;
2791
+ }
2792
+ function redactUrls(value) {
2793
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2794
+ }
2795
+ function redactFilePaths(value) {
2796
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2797
+ }
2798
+ function homePathRange(value, match, prefixLength) {
2799
+ const index = match.index;
2800
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
2801
+ const start = index;
2802
+ let end = start + match[0].length;
2803
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
2804
+ if (quote !== void 0) {
2805
+ const closing = value.indexOf(quote, end);
2806
+ if (closing >= 0) end = closing;
2807
+ }
2808
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
2809
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
2810
+ }
2811
+ function truncateUtf8(value, maxBytes) {
2812
+ if (byteLength(value) <= maxBytes) return value;
2813
+ let output = "";
2814
+ for (const character of value) {
2815
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
2816
+ output += character;
2817
+ }
2818
+ return `${output}…`;
2819
+ }
2820
+
2567
2821
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
2568
2822
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
2569
2823
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -2704,10 +2958,10 @@ function failureDetail(error) {
2704
2958
  function errorCode(error) {
2705
2959
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
2706
2960
  }
2707
- function hostClientProbe(result, read) {
2961
+ function hostClientProbe(result, read2) {
2708
2962
  if (result === null) return { kind: "unreachable" };
2709
2963
  if (result.exit_code !== 0) return { kind: "refused", exit_code: result.exit_code };
2710
- const value = read(result);
2964
+ const value = read2(result);
2711
2965
  return value === null ? { kind: "unreadable" } : { kind: "value", value };
2712
2966
  }
2713
2967
  function hostClientProbeRefusal(probe, subject) {
@@ -2718,6 +2972,7 @@ function hostClientProbeRefusal(probe, subject) {
2718
2972
  }
2719
2973
 
2720
2974
  // host/invocation-authentication-command.ts
2975
+ import { createHash as createHash7 } from "node:crypto";
2721
2976
  import { performance } from "node:perf_hooks";
2722
2977
 
2723
2978
  // host/relay/src/producer-frame.ts
@@ -2736,13 +2991,86 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2736
2991
 
2737
2992
  // host/relay/src/host-producer-core.ts
2738
2993
  import { createHash as createHash4 } from "node:crypto";
2994
+ import { readdir } from "node:fs/promises";
2739
2995
 
2740
2996
  // host/secure-file.ts
2741
2997
  import { execFile } from "node:child_process";
2742
2998
  import { constants } from "node:fs";
2743
2999
  import { lstat, open } from "node:fs/promises";
2744
- import { dirname, join as join2, win32 } from "node:path";
3000
+ import { dirname, join as join3, win32 } from "node:path";
2745
3001
  import { fileURLToPath } from "node:url";
3002
+
3003
+ // host/spawn-working-directory.ts
3004
+ import { mkdirSync } from "node:fs";
3005
+ import { tmpdir } from "node:os";
3006
+ import { isAbsolute, join as join2, normalize, parse, sep } from "node:path";
3007
+ function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
3008
+ const candidates = [];
3009
+ const explicit = candidateDir(stateRoot);
3010
+ if (explicit !== void 0) candidates.push(explicit);
3011
+ const fallback = defaultHostStateRoot();
3012
+ if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
3013
+ const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
3014
+ if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
3015
+ for (const dir of candidates) {
3016
+ if (!keptOutside(dir, keepOutside)) continue;
3017
+ try {
3018
+ mkdirSync(dir, { recursive: true, mode: 448 });
3019
+ return dir;
3020
+ } catch {
3021
+ continue;
3022
+ }
3023
+ }
3024
+ return tmpdir();
3025
+ }
3026
+ function candidateDir(dir) {
3027
+ if (dir === void 0 || dir === "") return void 0;
3028
+ if (!isAbsolute(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
3029
+ return normalize(dir);
3030
+ }
3031
+ function defaultHostStateRoot() {
3032
+ if (process.platform === "win32") {
3033
+ const localAppData = nonEmptyEnv("LOCALAPPDATA");
3034
+ if (localAppData === void 0) return void 0;
3035
+ return candidateDir(join2(localAppData, "Ceal", "Host"));
3036
+ }
3037
+ if (process.platform === "darwin") {
3038
+ const home2 = nonEmptyEnv("HOME");
3039
+ if (home2 === void 0) return void 0;
3040
+ return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
3041
+ }
3042
+ const xdg = nonEmptyEnv("XDG_STATE_HOME");
3043
+ if (xdg !== void 0) {
3044
+ const root = candidateDir(join2(xdg, "ceal", "host"));
3045
+ if (root !== void 0) return root;
3046
+ }
3047
+ const home = nonEmptyEnv("HOME");
3048
+ if (home === void 0) return void 0;
3049
+ return candidateDir(join2(home, ".local", "state", "ceal", "host"));
3050
+ }
3051
+ function nonEmptyEnv(name) {
3052
+ const value = process.env[name];
3053
+ return value === void 0 || value === "" ? void 0 : value;
3054
+ }
3055
+ function keptOutside(dir, keepOutside) {
3056
+ for (const tree of keepOutside) {
3057
+ const clean = candidateDir(tree);
3058
+ if (clean === void 0) continue;
3059
+ if (insideDir(dir, clean)) return false;
3060
+ }
3061
+ return true;
3062
+ }
3063
+ function insideDir(dir, tree) {
3064
+ if (sameDir(dir, tree)) return true;
3065
+ if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
3066
+ return dir.startsWith(tree + sep);
3067
+ }
3068
+ function sameDir(left, right) {
3069
+ if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
3070
+ return left === right;
3071
+ }
3072
+
3073
+ // host/secure-file.ts
2746
3074
  var SecureFileCustodyError = class extends Error {
2747
3075
  name = "SecureFileCustodyError";
2748
3076
  reason;
@@ -2850,7 +3178,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2850
3178
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2851
3179
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2852
3180
  return await new Promise((resolve, reject) => {
2853
- const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
3181
+ 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) => {
2854
3182
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2855
3183
  if (exitCode === null) {
2856
3184
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2879,7 +3207,7 @@ function securefsRefusal(stderr) {
2879
3207
  }
2880
3208
  function resolveInstalledHostExecutable(platform) {
2881
3209
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2882
- return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3210
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2883
3211
  }
2884
3212
  function isRecord(value) {
2885
3213
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2903,7 +3231,7 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
2903
3231
 
2904
3232
  // host/service-log.ts
2905
3233
  import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
2906
- import { dirname as dirname2, isAbsolute, posix, win32 as win322 } from "node:path";
3234
+ import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win322 } from "node:path";
2907
3235
 
2908
3236
  // host/service-log-delivery.ts
2909
3237
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -3062,7 +3390,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
3062
3390
  await appendHostServiceLogLine(path, line).catch(() => void 0);
3063
3391
  }
3064
3392
  async function appendHostServiceLogLine(path, line) {
3065
- if (!isAbsolute(path)) return;
3393
+ if (!isAbsolute2(path)) return;
3066
3394
  await ensureHostServiceLogDirectory(path);
3067
3395
  await appendFile(path, line);
3068
3396
  }
@@ -3103,9 +3431,9 @@ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
3103
3431
  }
3104
3432
  return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
3105
3433
  }
3106
- async function readRegisteredHostInvocationHumanMessageWindow(listRegistrations, readCursor, identity, decodeLine) {
3434
+ async function readRegisteredHostInvocationHumanMessageWindow(readRegistration, readCursor, identity, decodeLine) {
3107
3435
  try {
3108
- const registration = await findLiveHostInvocationRegistration(listRegistrations, identity);
3436
+ const registration = await findLiveHostInvocationRegistration(readRegistration, identity);
3109
3437
  const cursor = await readCursor(registration);
3110
3438
  assertUsableHostInvocationHumanMessageCursor(cursor, registration);
3111
3439
  return await readHostInvocationHumanMessageWindow(registration, cursor, (line) => decodeLine(line, registration, cursor));
@@ -3113,9 +3441,9 @@ async function readRegisteredHostInvocationHumanMessageWindow(listRegistrations,
3113
3441
  throw new TypeError("context_unavailable");
3114
3442
  }
3115
3443
  }
3116
- async function findLiveHostInvocationRegistration(listRegistrations, identity) {
3117
- const registration = (await listRegistrations()).find((candidate) => candidate.host_source_ref === identity.host_source_ref && candidate.host_session_ref === identity.host_session_ref && Date.parse(candidate.expires_at) > Date.now());
3118
- if (registration === void 0) throw new TypeError("context_unavailable");
3444
+ async function findLiveHostInvocationRegistration(readRegistration, identity) {
3445
+ const registration = await readRegistration(identity);
3446
+ if (registration === null || registration.host_source_ref !== identity.host_source_ref || registration.host_session_ref !== identity.host_session_ref || !(Date.parse(registration.expires_at) > Date.now())) throw new TypeError("context_unavailable");
3119
3447
  return registration;
3120
3448
  }
3121
3449
  function assertUsableHostInvocationHumanMessageCursor(cursor, registration) {
@@ -3182,9 +3510,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
3182
3510
  let lastNewline = -1;
3183
3511
  while (position < size) {
3184
3512
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
3185
- const read = await handle.read(buffer, 0, buffer.length, position);
3186
- if (read.bytesRead === 0) break;
3187
- const chunk = buffer.subarray(0, read.bytesRead);
3513
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
3514
+ if (read2.bytesRead === 0) break;
3515
+ const chunk = buffer.subarray(0, read2.bytesRead);
3188
3516
  chunks.push(chunk);
3189
3517
  const newline = chunk.lastIndexOf(10);
3190
3518
  if (newline >= 0) lastNewline = total + newline;
@@ -3343,6 +3671,14 @@ var HostTranscriptWatcher = class {
3343
3671
  return transcriptCursorBoundsReason(handle, cursor, size);
3344
3672
  }
3345
3673
  };
3674
+ async function listHostOutboxDirectoryNames(directory) {
3675
+ try {
3676
+ return await readdir(directory);
3677
+ } catch (error) {
3678
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
3679
+ throw error;
3680
+ }
3681
+ }
3346
3682
  var HostProducerDrainCore = class {
3347
3683
  host;
3348
3684
  now;
@@ -3357,15 +3693,15 @@ var HostProducerDrainCore = class {
3357
3693
  return run;
3358
3694
  }
3359
3695
  async drainLocked() {
3360
- const read = await this.host.listEnvelopes();
3696
+ const read2 = await this.host.listEnvelopes();
3361
3697
  let removed = 0;
3362
3698
  let expired = 0;
3363
- for (const envelope of read.entries) {
3699
+ for (const envelope of read2.entries) {
3364
3700
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
3365
3701
  else removed += 1;
3366
3702
  await this.host.removeEnvelope(envelope);
3367
3703
  }
3368
- return { removed, expired, malformed: read.malformed };
3704
+ return { removed, expired, malformed: read2.malformed };
3369
3705
  }
3370
3706
  };
3371
3707
 
@@ -3504,7 +3840,7 @@ function errorCode2(error) {
3504
3840
  import { createHash as createHash5 } from "node:crypto";
3505
3841
  import { constants as constants2 } from "node:fs";
3506
3842
  import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3507
- import { dirname as dirname4, join as join3 } from "node:path";
3843
+ import { dirname as dirname4, join as join4 } from "node:path";
3508
3844
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3509
3845
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3510
3846
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -3524,9 +3860,9 @@ var HostUsageFactsStore = class {
3524
3860
  afterBatchPublish;
3525
3861
  sessionDirectoryCursor;
3526
3862
  constructor(options) {
3527
- this.root = join3(options.outbox_dir, "usage-facts");
3528
- this.sessions = join3(this.root, "sessions");
3529
- this.batches = join3(this.root, "batches");
3863
+ this.root = join4(options.outbox_dir, "usage-facts");
3864
+ this.sessions = join4(this.root, "sessions");
3865
+ this.batches = join4(this.root, "batches");
3530
3866
  this.platform = options.platform ?? process.platform;
3531
3867
  this.custody = options.secure_file_custody ?? {};
3532
3868
  this.afterPendingWrite = options.afterPendingWrite;
@@ -3543,7 +3879,6 @@ var HostUsageFactsStore = class {
3543
3879
  await cursor?.close();
3544
3880
  }
3545
3881
  async readState(producer, hostSourceRef, hostSessionRef) {
3546
- await this.prepare();
3547
3882
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3548
3883
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3549
3884
  if (value === null) return null;
@@ -3601,11 +3936,15 @@ var HostUsageFactsStore = class {
3601
3936
  }
3602
3937
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3603
3938
  async sweepOrphanedBatches(state) {
3604
- await this.prepare();
3605
3939
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3606
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3607
3940
  const expected = expectedBatchNames(state);
3608
- const directory = await opendir(directoryPath);
3941
+ let directory;
3942
+ try {
3943
+ directory = await opendir(directoryPath);
3944
+ } catch (error) {
3945
+ if (errorCode3(error) === "ENOENT") return 0;
3946
+ throw error;
3947
+ }
3609
3948
  let inspected = 0;
3610
3949
  let deleted = 0;
3611
3950
  try {
@@ -3614,7 +3953,7 @@ var HostUsageFactsStore = class {
3614
3953
  if (entry === null) break;
3615
3954
  inspected += 1;
3616
3955
  if (!isOrphanBatchEntry(entry, expected)) continue;
3617
- await unlink2(join3(directoryPath, entry.name));
3956
+ await unlink2(join4(directoryPath, entry.name));
3618
3957
  deleted += 1;
3619
3958
  }
3620
3959
  } finally {
@@ -3642,10 +3981,9 @@ var HostUsageFactsStore = class {
3642
3981
  });
3643
3982
  }
3644
3983
  async nextUploadCandidate(producer, hostSourceRef) {
3645
- await this.prepare();
3646
3984
  const names = await this.readNextSessionNames();
3647
3985
  for (const name of names) {
3648
- const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3986
+ const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3649
3987
  if (state === null) continue;
3650
3988
  validateStateOwner(state, producer, hostSourceRef);
3651
3989
  let validated = state;
@@ -3660,7 +3998,14 @@ var HostUsageFactsStore = class {
3660
3998
  return null;
3661
3999
  }
3662
4000
  async readNextSessionNames() {
3663
- this.sessionDirectoryCursor ??= await opendir(this.sessions);
4001
+ if (this.sessionDirectoryCursor === void 0) {
4002
+ try {
4003
+ this.sessionDirectoryCursor = await opendir(this.sessions);
4004
+ } catch (error) {
4005
+ if (errorCode3(error) === "ENOENT") return [];
4006
+ throw error;
4007
+ }
4008
+ }
3664
4009
  const names = [];
3665
4010
  let inspected = 0;
3666
4011
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -3815,25 +4160,25 @@ var HostUsageFactsStore = class {
3815
4160
  const gate = new Promise((resolve) => {
3816
4161
  release = resolve;
3817
4162
  });
3818
- const tail = previous.then(() => gate);
3819
- SESSION_TRANSITION_TAILS.set(key, tail);
4163
+ const tail2 = previous.then(() => gate);
4164
+ SESSION_TRANSITION_TAILS.set(key, tail2);
3820
4165
  await previous;
3821
4166
  try {
3822
4167
  return await run();
3823
4168
  } finally {
3824
4169
  release?.();
3825
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
4170
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3826
4171
  }
3827
4172
  }
3828
4173
  sessionPath(producer, hostSourceRef, hostSessionRef) {
3829
- return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
4174
+ return join4(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3830
4175
  }
3831
4176
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3832
4177
  const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3833
- return join3(this.batches, sessionName.slice(0, -5));
4178
+ return join4(this.batches, sessionName.slice(0, -5));
3834
4179
  }
3835
4180
  batchPath(state, batchRef) {
3836
- return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
4181
+ return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3837
4182
  }
3838
4183
  };
3839
4184
  function serializeBatch(batch) {
@@ -4083,29 +4428,46 @@ var HostUsageTranscriptSourceError = class extends Error {
4083
4428
  this.name = "HostUsageTranscriptSourceError";
4084
4429
  }
4085
4430
  };
4086
- async function readHostUsageTranscriptSource(read) {
4431
+ async function readHostUsageTranscriptSource(read2) {
4087
4432
  try {
4088
- return await read();
4433
+ return await read2();
4089
4434
  } catch (error) {
4090
4435
  throw new HostUsageTranscriptSourceError({ cause: error });
4091
4436
  }
4092
4437
  }
4093
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4094
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4095
- let failed = false;
4096
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4097
- const index = (startIndex + attempt) % registrations.length;
4098
- const registration = registrations[index];
4099
- if (registration === void 0) continue;
4100
- try {
4101
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
4102
- } catch (error) {
4103
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4438
+ var HostUsageRegistrationCapture = class {
4439
+ nextIndex = 0;
4440
+ producer;
4441
+ diagnosticSink;
4442
+ constructor(producer, diagnosticSink) {
4443
+ this.producer = producer;
4444
+ this.diagnosticSink = diagnosticSink;
4445
+ }
4446
+ async captureNext(registrations, capture) {
4447
+ let failed = false;
4448
+ let captured = false;
4449
+ const onFailure = () => {
4104
4450
  failed = true;
4451
+ };
4452
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4453
+ const index = (this.nextIndex + attempt) % registrations.length;
4454
+ const registration = registrations[index];
4455
+ if (registration === void 0) continue;
4456
+ try {
4457
+ captured = await capture(registration, onFailure);
4458
+ if (captured) {
4459
+ this.nextIndex = (index + 1) % registrations.length;
4460
+ break;
4461
+ }
4462
+ } catch (error) {
4463
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4464
+ onFailure();
4465
+ }
4105
4466
  }
4467
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
4468
+ return captured;
4106
4469
  }
4107
- return { captured: false, nextIndex: startIndex, failed };
4108
- }
4470
+ };
4109
4471
  async function openHostUsageTranscriptCursor(input) {
4110
4472
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
4111
4473
  let source;
@@ -4385,6 +4747,10 @@ var HostUsageFactsUploader = class {
4385
4747
  async close() {
4386
4748
  await this.store.close();
4387
4749
  }
4750
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
4751
+ async prepare() {
4752
+ await this.store.prepare();
4753
+ }
4388
4754
  async uploadOne(signal) {
4389
4755
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4390
4756
  if (candidate === null) return false;
@@ -4407,6 +4773,11 @@ var HostUsageFactsUploader = class {
4407
4773
  };
4408
4774
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4409
4775
  const uploader = new HostUsageFactsUploader(options);
4776
+ try {
4777
+ await uploader.prepare();
4778
+ } catch {
4779
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4780
+ }
4410
4781
  let delay = 500;
4411
4782
  let failures = 0;
4412
4783
  try {
@@ -4496,7 +4867,7 @@ import { createConnection, createServer } from "node:net";
4496
4867
  import { createHmac, randomBytes } from "node:crypto";
4497
4868
  import { constants as constants5 } from "node:fs";
4498
4869
  import { link, unlink as unlink4 } from "node:fs/promises";
4499
- import { dirname as dirname7, join as join4 } from "node:path";
4870
+ import { dirname as dirname7, join as join5 } from "node:path";
4500
4871
  var RELAY_PIPE_HANDSHAKE_TIMEOUT_MS = 5e3;
4501
4872
  var RELAY_PIPE_KEY_BYTES = 32;
4502
4873
  var RELAY_PIPE_KEY_FILENAME = "relay-pipe.key";
@@ -4516,10 +4887,10 @@ var RelayPipeHandshakeError = class extends Error {
4516
4887
  }
4517
4888
  };
4518
4889
  function relayPipeStateRootForOutboxDir(outboxDir) {
4519
- return join4(dirname7(dirname7(dirname7(outboxDir))), "relay");
4890
+ return join5(dirname7(dirname7(dirname7(outboxDir))), "relay");
4520
4891
  }
4521
4892
  function relayPipeKeyPath(relayStateRoot) {
4522
- return join4(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
4893
+ return join5(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
4523
4894
  }
4524
4895
  async function loadRelayPipeKey(relayStateRoot, platform = process.platform, custody = {}) {
4525
4896
  const path = relayPipeKeyPath(relayStateRoot);
@@ -5029,17 +5400,133 @@ async function authenticateHostInvocation(descriptor, input, options) {
5029
5400
  const request2 = decodeCealHostInvocationAuthenticationRequest({ schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA, client_nonce: input[2] });
5030
5401
  const config = validateOptions(options);
5031
5402
  const now = config.now ?? (() => /* @__PURE__ */ new Date());
5032
- const { store, current } = await currentInvocation(descriptor, config, now);
5403
+ const store = descriptor.create_store(config.outbox_dir);
5404
+ const resolved = resolveIdentity(descriptor, config);
5405
+ if (resolved.status === "session_unavailable") throw new TypeError("no_binding");
5406
+ const toolCallId = resolveToolCallId(descriptor, config);
5407
+ const selection = await readHookSelection(store, resolved.identity);
5408
+ if (selection === null) {
5409
+ const callTime = await trySelectionlessCallTimeBinding(descriptor, store, resolved.identity, config, toolCallId);
5410
+ if (callTime !== null) return authenticateCallTimeBinding(descriptor, store, callTime, request2.client_nonce, config, now);
5411
+ } else if (!waitPossible(config) && !await hasLiveInvocationContext(store, resolved.identity, now)) {
5412
+ const direct = await tryDirectCallTimeBinding(descriptor, store, resolved.identity, selection, config, toolCallId);
5413
+ if (direct !== null) return authenticateCallTimeBinding(descriptor, store, direct, request2.client_nonce, config, now);
5414
+ }
5415
+ return authenticateHookGated(descriptor, store, request2.client_nonce, config, now, toolCallId);
5416
+ }
5417
+ function selectCallTimeBinding(window, toolCallId) {
5418
+ const newest = window.messages[0];
5419
+ if (newest === void 0) return null;
5420
+ return { message: newest, mode: toolCallId === void 0 ? "newest_message" : "tool_call" };
5421
+ }
5422
+ async function authenticateCallTimeBinding(descriptor, store, callTime, clientNonce, config, now) {
5423
+ if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
5424
+ const query = await invocationMintQuery(descriptor, store, { identity: callTime.binding, expires_at: callTime.expires_at }, clientNonce, config, callTime.window);
5425
+ const response2 = await mintedResult(config.mint_invocation_context, query);
5426
+ const completedAt = now();
5427
+ const newest = await rereadCallTimeNewest(descriptor, store, callTime.binding, config);
5428
+ if (newest === null || newest.host_turn_ref !== callTime.binding.host_turn_ref || newest.host_input_ref !== callTime.window.messages[0]?.host_input_ref) throw new TypeError("context_replaced");
5429
+ return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
5430
+ }
5431
+ async function authenticateHookGated(descriptor, store, clientNonce, config, now, toolCallId) {
5432
+ const { current } = await currentInvocation(descriptor, config, now, store);
5033
5433
  if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
5034
- const query = await invocationMintQuery(descriptor, store, current, request2.client_nonce, config);
5434
+ const window = await readCallTimeWindow(descriptor, store, current.identity, config);
5435
+ const selected = selectCallTimeBinding(window, toolCallId);
5436
+ if (selected !== null && selected.message.host_turn_ref !== current.identity.host_turn_ref) {
5437
+ const selection = await readHookSelection(store, current.identity);
5438
+ if (selection === null || transcriptCatchesHookSelection(selection, selected.message)) {
5439
+ return authenticateCallTimeBinding(descriptor, store, {
5440
+ binding: { ...current.identity, host_turn_ref: selected.message.host_turn_ref },
5441
+ expires_at: current.expires_at,
5442
+ window,
5443
+ mode: selected.mode
5444
+ }, clientNonce, config, now);
5445
+ }
5446
+ }
5447
+ const query = await invocationMintQuery(descriptor, store, current, clientNonce, config, window);
5035
5448
  const response2 = await mintedResult(config.mint_invocation_context, query);
5036
5449
  const completedAt = now();
5037
5450
  const rechecked = await store.readInvocationContext(current.identity.host_source_ref, current.identity.host_session_ref, completedAt);
5038
5451
  if (rechecked === null || !sameTurn(current, rechecked)) throw new TypeError("context_replaced");
5039
5452
  return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
5040
5453
  }
5041
- async function invocationMintQuery(descriptor, store, current, clientNonce, options) {
5042
- const readWindow = options.read_human_message_window?.(current.identity) ?? descriptor.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false });
5454
+ async function trySelectionlessCallTimeBinding(descriptor, store, identity, config, toolCallId) {
5455
+ const registration = await liveTranscriptRegistration(store, identity);
5456
+ if (registration === null) return null;
5457
+ let window;
5458
+ try {
5459
+ window = await readCallTimeWindow(descriptor, store, identity, config);
5460
+ } catch {
5461
+ throw new TypeError("transient_retryable");
5462
+ }
5463
+ const selected = selectCallTimeBinding(window, toolCallId);
5464
+ if (selected === null) return null;
5465
+ return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
5466
+ }
5467
+ async function tryDirectCallTimeBinding(descriptor, store, identity, selection, config, toolCallId) {
5468
+ let window;
5469
+ try {
5470
+ window = await readCallTimeWindow(descriptor, store, identity, config);
5471
+ } catch {
5472
+ return null;
5473
+ }
5474
+ const selected = selectCallTimeBinding(window, toolCallId);
5475
+ if (selected === null || !transcriptCatchesHookSelection(selection, selected.message)) return null;
5476
+ const registration = await liveTranscriptRegistration(store, identity);
5477
+ if (registration === null) return null;
5478
+ return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
5479
+ }
5480
+ async function readCallTimeWindow(descriptor, store, identity, config) {
5481
+ return await (config.read_human_message_window?.(identity) ?? descriptor.read_human_message_window?.({ store, identity }) ?? Promise.resolve({ messages: [], truncated: false }));
5482
+ }
5483
+ function transcriptCatchesHookSelection(selection, newest) {
5484
+ if (newest.text_truncated === true) return false;
5485
+ return hostProducerPromptRef(createHash7("sha256").update(newest.text, "utf8").digest("hex")) === selection.prompt_ref;
5486
+ }
5487
+ async function readHookSelection(store, identity) {
5488
+ try {
5489
+ return await store.readInvocationTurnSelection?.(identity.host_source_ref, identity.host_session_ref) ?? null;
5490
+ } catch {
5491
+ return null;
5492
+ }
5493
+ }
5494
+ async function hasLiveInvocationContext(store, identity, now) {
5495
+ try {
5496
+ return await store.readInvocationContext(identity.host_source_ref, identity.host_session_ref, now()) !== null;
5497
+ } catch {
5498
+ return false;
5499
+ }
5500
+ }
5501
+ function waitPossible(config) {
5502
+ return (config.context_activation_wait_ms ?? 0) > 0;
5503
+ }
5504
+ async function liveTranscriptRegistration(store, identity) {
5505
+ try {
5506
+ const registration = await store.readTranscriptRegistration?.(identity.host_source_ref, identity.host_session_ref) ?? null;
5507
+ if (registration !== null && Date.parse(registration.expires_at) > Date.now()) return registration;
5508
+ } catch {
5509
+ }
5510
+ return null;
5511
+ }
5512
+ async function rereadCallTimeNewest(descriptor, store, identity, config) {
5513
+ try {
5514
+ return (await readCallTimeWindow(descriptor, store, identity, config)).messages[0] ?? null;
5515
+ } catch {
5516
+ return null;
5517
+ }
5518
+ }
5519
+ function resolveToolCallId(descriptor, options) {
5520
+ if (options.tool_call_id !== void 0) return validToolCallId(options.tool_call_id) ? options.tool_call_id : void 0;
5521
+ if (descriptor.tool_call_id_env === void 0) return void 0;
5522
+ const value = process.env[descriptor.tool_call_id_env];
5523
+ return validToolCallId(value) ? value : void 0;
5524
+ }
5525
+ function validToolCallId(value) {
5526
+ return typeof value === "string" && value.length > 0 && value.length <= 256 && !value.includes("\0");
5527
+ }
5528
+ async function invocationMintQuery(descriptor, store, current, clientNonce, options, windowOverride) {
5529
+ const readWindow = windowOverride === void 0 ? options.read_human_message_window?.(current.identity) ?? descriptor.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false }) : Promise.resolve(windowOverride);
5043
5530
  return {
5044
5531
  producer_id: descriptor.producer_id,
5045
5532
  producer_installation_ref: options.producer_installation_ref,
@@ -5071,8 +5558,7 @@ async function mintedResult(mint, query) {
5071
5558
  function validGenericGatewayRefusalStatus2(value) {
5072
5559
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 400 && value < 500 && value !== 401 && value !== 429;
5073
5560
  }
5074
- async function currentInvocation(descriptor, config, now) {
5075
- const store = descriptor.create_store(config.outbox_dir);
5561
+ async function currentInvocation(descriptor, config, now, store) {
5076
5562
  const identity = resolveIdentity(descriptor, config);
5077
5563
  if (identity.status === "session_unavailable") throw new TypeError("no_binding");
5078
5564
  const waitBudgetMs = config.context_activation_wait_ms ?? 0;
@@ -5089,7 +5575,7 @@ async function currentInvocation(descriptor, config, now) {
5089
5575
  const current = await readLiveSessionContext(store, identity.identity.host_source_ref, identity.identity.host_session_ref, observedAt);
5090
5576
  if (current !== null) {
5091
5577
  recordActivationWaitCompletion(descriptor.producer_id, waitEngaged, config.diagnostic_sink);
5092
- return { store, current };
5578
+ return { current };
5093
5579
  }
5094
5580
  await rejectWhenActivationWaitIsUnavailable(descriptor, store, identity.identity, waitEngaged, waitBudgetMs, config.diagnostic_sink);
5095
5581
  const remainingMs = deadline - monotonicNow();
@@ -5163,7 +5649,7 @@ function waitForContextActivation(milliseconds) {
5163
5649
  });
5164
5650
  }
5165
5651
  function validateOptions(options) {
5166
- if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || !validOptionalSession(options.session_id)) {
5652
+ if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || options.tool_call_id !== void 0 && typeof options.tool_call_id !== "string" || !validOptionalSession(options.session_id)) {
5167
5653
  throw new TypeError("options_invalid");
5168
5654
  }
5169
5655
  return options;
@@ -5361,7 +5847,7 @@ function parseCanonicalJson(text, error) {
5361
5847
  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) }])}`);
5362
5848
  return value;
5363
5849
  } catch (parseError) {
5364
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
5850
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
5365
5851
  }
5366
5852
  }
5367
5853
  function firstDifferenceIndex(left, right) {
@@ -5416,7 +5902,7 @@ function boundedMilliseconds(value) {
5416
5902
  }
5417
5903
 
5418
5904
  // host/claude/src/claude-decoder.ts
5419
- import { createHash as createHash7 } from "node:crypto";
5905
+ import { createHash as createHash8 } from "node:crypto";
5420
5906
 
5421
5907
  // host/claude/src/claude-types.ts
5422
5908
  var CLAUDE_SESSION_ID_ENVIRONMENT = "CLAUDE_CODE_SESSION_ID";
@@ -5513,7 +5999,7 @@ function queuedRowIdentity(row) {
5513
5999
  return { uuid: row.uuid, timestamp: row.timestamp };
5514
6000
  }
5515
6001
  function queueEnqueueTurnId(sessionId, timestamp4, content) {
5516
- return `queue-enqueue:${createHash7("sha256").update(`${sessionId}
6002
+ return `queue-enqueue:${createHash8("sha256").update(`${sessionId}
5517
6003
  ${timestamp4}
5518
6004
  ${content}`, "utf8").digest("hex").slice(0, 32)}`;
5519
6005
  }
@@ -5527,15 +6013,15 @@ function claudeLocalInputRef(sessionId, turnId) {
5527
6013
  return `claude-input:${cealRequestSha256({ session_id: sessionId, prompt_id: turnId })}`;
5528
6014
  }
5529
6015
  function digest(value) {
5530
- return createHash7("sha256").update(value, "utf8").digest("hex");
6016
+ return createHash8("sha256").update(value, "utf8").digest("hex");
5531
6017
  }
5532
6018
  function record3(value) {
5533
6019
  return value !== null && typeof value === "object" && !Array.isArray(value);
5534
6020
  }
5535
6021
 
5536
6022
  // host/claude/src/claude-outbox.ts
5537
- import { mkdir as mkdir5, readdir, readFile, unlink as unlink5 } from "node:fs/promises";
5538
- import { isAbsolute as isAbsolute3, join as join5 } from "node:path";
6023
+ import { mkdir as mkdir5, readFile, unlink as unlink5 } from "node:fs/promises";
6024
+ import { isAbsolute as isAbsolute4, join as join6 } from "node:path";
5539
6025
 
5540
6026
  // host/invocation-context.ts
5541
6027
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -5589,7 +6075,7 @@ function safeRef2(value) {
5589
6075
  }
5590
6076
 
5591
6077
  // host/claude/src/claude-invocation-context.ts
5592
- import { isAbsolute as isAbsolute2 } from "node:path";
6078
+ import { isAbsolute as isAbsolute3 } from "node:path";
5593
6079
  function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
5594
6080
  return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
5595
6081
  }
@@ -5618,7 +6104,7 @@ function optionalSafeRef(value) {
5618
6104
  return value === void 0 || safeRef3(value);
5619
6105
  }
5620
6106
  function optionalDirectory(value) {
5621
- return value === void 0 || typeof value === "string" && isAbsolute2(value) && !value.includes("\0") && value.length <= 4096;
6107
+ return value === void 0 || typeof value === "string" && isAbsolute3(value) && !value.includes("\0") && value.length <= 4096;
5622
6108
  }
5623
6109
  function safeRef3(value) {
5624
6110
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
@@ -5643,14 +6129,14 @@ var ClaudeOutboxStore = class {
5643
6129
  activeContexts;
5644
6130
  turnSelections;
5645
6131
  constructor(directory) {
5646
- if (!isAbsolute3(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
6132
+ if (!isAbsolute4(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
5647
6133
  this.directory = directory;
5648
- this.envelopes = join5(directory, "envelopes");
5649
- this.sessions = join5(directory, "sessions");
5650
- this.registrations = join5(directory, "transcript-registrations");
5651
- this.cursors = join5(directory, "transcript-cursors");
5652
- this.activeContexts = join5(directory, "active-contexts");
5653
- this.turnSelections = join5(directory, "turn-selections");
6134
+ this.envelopes = join6(directory, "envelopes");
6135
+ this.sessions = join6(directory, "sessions");
6136
+ this.registrations = join6(directory, "transcript-registrations");
6137
+ this.cursors = join6(directory, "transcript-cursors");
6138
+ this.activeContexts = join6(directory, "active-contexts");
6139
+ this.turnSelections = join6(directory, "turn-selections");
5654
6140
  }
5655
6141
  async prepare() {
5656
6142
  for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
@@ -5678,6 +6164,7 @@ var ClaudeOutboxStore = class {
5678
6164
  const path = this.activeContextPath(identity);
5679
6165
  const active = await readProjectionFile(path);
5680
6166
  if (active === null || active.prompt_ref !== promptRef || active.identity.host_turn_ref !== identity.host_turn_ref) return false;
6167
+ await this.prepare();
5681
6168
  const updated = { ...active, turn_generation_ref: turnGenerationRef };
5682
6169
  validateClaudeHostInvocationContext(updated);
5683
6170
  await durableAtomicReplace(path, JSON.stringify(updated));
@@ -5690,17 +6177,15 @@ var ClaudeOutboxStore = class {
5690
6177
  */
5691
6178
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
5692
6179
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
5693
- await this.prepare();
5694
6180
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, readProjectionFile);
5695
6181
  return context;
5696
6182
  }
5697
6183
  async listInvocationContexts(now = /* @__PURE__ */ new Date()) {
5698
- await this.prepare();
5699
6184
  const contexts = [];
5700
- for (const name of await readdir(this.activeContexts)) {
6185
+ for (const name of await listHostOutboxDirectoryNames(this.activeContexts)) {
5701
6186
  if (!name.endsWith(".json")) continue;
5702
6187
  try {
5703
- const value = JSON.parse(await readFile(join5(this.activeContexts, name), "utf8"));
6188
+ const value = JSON.parse(await readFile(join6(this.activeContexts, name), "utf8"));
5704
6189
  validateClaudeHostInvocationContext(value);
5705
6190
  if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
5706
6191
  } catch {
@@ -5714,13 +6199,12 @@ var ClaudeOutboxStore = class {
5714
6199
  await durableAtomicReplace(this.envelopePath(entry.submission_ref), JSON.stringify(entry));
5715
6200
  }
5716
6201
  async listEnvelopes() {
5717
- await this.prepare();
5718
6202
  const entries = [];
5719
6203
  let malformed = 0;
5720
- for (const name of await readdir(this.envelopes)) {
6204
+ for (const name of await listHostOutboxDirectoryNames(this.envelopes)) {
5721
6205
  if (!name.endsWith(".json")) continue;
5722
6206
  try {
5723
- const value = JSON.parse(await readFile(join5(this.envelopes, name), "utf8"));
6207
+ const value = JSON.parse(await readFile(join6(this.envelopes, name), "utf8"));
5724
6208
  validateEnvelope(value);
5725
6209
  entries.push(value);
5726
6210
  } catch {
@@ -5741,13 +6225,12 @@ var ClaudeOutboxStore = class {
5741
6225
  async saveSession(snapshot) {
5742
6226
  validateSession(snapshot);
5743
6227
  await this.prepare();
5744
- await durableAtomicReplace(join5(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
6228
+ await durableAtomicReplace(join6(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
5745
6229
  }
5746
6230
  async readSession(sourceRef, sessionRef) {
5747
6231
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
5748
- await this.prepare();
5749
6232
  try {
5750
- const value = JSON.parse(await readFile(join5(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
6233
+ const value = JSON.parse(await readFile(join6(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
5751
6234
  validateSession(value);
5752
6235
  return value;
5753
6236
  } catch (error) {
@@ -5776,13 +6259,18 @@ var ClaudeOutboxStore = class {
5776
6259
  await this.removeStateFile(this.registrationPath(registration.host_source_ref, registration.host_session_ref));
5777
6260
  await this.removeStateFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref));
5778
6261
  }
6262
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
6263
+ if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
6264
+ const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
6265
+ 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.");
6266
+ return registration;
6267
+ }
5779
6268
  async listTranscriptRegistrations() {
5780
- await this.prepare();
5781
6269
  const registrations = [];
5782
- for (const name of await readdir(this.registrations)) {
6270
+ for (const name of await listHostOutboxDirectoryNames(this.registrations)) {
5783
6271
  if (!name.endsWith(".json")) continue;
5784
6272
  try {
5785
- const value = JSON.parse(await readFile(join5(this.registrations, name), "utf8"));
6273
+ const value = JSON.parse(await readFile(join6(this.registrations, name), "utf8"));
5786
6274
  validateRegistration(value);
5787
6275
  registrations.push(value);
5788
6276
  } catch {
@@ -5792,7 +6280,6 @@ var ClaudeOutboxStore = class {
5792
6280
  }
5793
6281
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
5794
6282
  if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host turn selection identity is invalid.");
5795
- await this.prepare();
5796
6283
  try {
5797
6284
  const value = JSON.parse(await readFile(this.turnSelectionPath(hostSourceRef, hostSessionRef), "utf8"));
5798
6285
  if (!isHostInvocationTurnSelection(value) || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new ClaudeHostError("storage", "Claude Host turn selection is malformed.");
@@ -5804,7 +6291,6 @@ var ClaudeOutboxStore = class {
5804
6291
  }
5805
6292
  async readTranscriptCursor(registration) {
5806
6293
  validateRegistration(registration);
5807
- await this.prepare();
5808
6294
  try {
5809
6295
  const value = JSON.parse(await readFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "utf8"));
5810
6296
  validateCursor(value);
@@ -5820,16 +6306,16 @@ var ClaudeOutboxStore = class {
5820
6306
  await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
5821
6307
  }
5822
6308
  envelopePath(ref) {
5823
- return join5(this.envelopes, `${cealRequestSha256(ref)}.json`);
6309
+ return join6(this.envelopes, `${cealRequestSha256(ref)}.json`);
5824
6310
  }
5825
6311
  registrationPath(sourceRef, sessionRef) {
5826
- return join5(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
6312
+ return join6(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
5827
6313
  }
5828
6314
  turnSelectionPath(sourceRef, sessionRef) {
5829
- return join5(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
6315
+ return join6(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
5830
6316
  }
5831
6317
  cursorPath(sourceRef, sessionRef) {
5832
- return join5(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
6318
+ return join6(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
5833
6319
  }
5834
6320
  async readRegistrationFile(path) {
5835
6321
  try {
@@ -5849,7 +6335,7 @@ var ClaudeOutboxStore = class {
5849
6335
  }
5850
6336
  }
5851
6337
  activeContextPath(identity) {
5852
- return join5(this.activeContexts, `${invocationContextKey(identity)}.json`);
6338
+ return join6(this.activeContexts, `${invocationContextKey(identity)}.json`);
5853
6339
  }
5854
6340
  };
5855
6341
  function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
@@ -5925,7 +6411,7 @@ function validateRegistration(value) {
5925
6411
  if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
5926
6412
  }
5927
6413
  function validateRegistrationPaths(cwd, transcriptPath) {
5928
- if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute3(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
6414
+ if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute4(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
5929
6415
  throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
5930
6416
  }
5931
6417
  if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
@@ -6045,10 +6531,42 @@ var ClaudeProducer = class {
6045
6531
 
6046
6532
  // host/claude/src/claude-transcript-watcher.ts
6047
6533
  import { readdir as readdir2 } from "node:fs/promises";
6048
- import { join as join6 } from "node:path";
6534
+ import { isDeepStrictEqual } from "node:util";
6535
+ import { join as join7 } from "node:path";
6536
+
6537
+ // host/claude/src/claude-subagent-overflow-checkpoint.ts
6538
+ var ClaudeSubagentOverflowCheckpoint = class {
6539
+ observed = /* @__PURE__ */ new Map();
6540
+ prune(registrations) {
6541
+ const current = new Set(registrations.map(registrationKey));
6542
+ for (const key of this.observed.keys()) if (!current.has(key)) this.observed.delete(key);
6543
+ }
6544
+ clear(registration) {
6545
+ this.observed.delete(registrationKey(registration));
6546
+ }
6547
+ /** Names follow the producer's sorted inventory; only omitted names define overflow. */
6548
+ async observe(registration, names, report) {
6549
+ const key = registrationKey(registration);
6550
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
6551
+ this.clear(registration);
6552
+ return false;
6553
+ }
6554
+ const digest2 = transcriptObjectSha256(names.slice(CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES));
6555
+ if (this.observed.get(key) === digest2) return false;
6556
+ if (!await report()) return false;
6557
+ this.observed.set(key, digest2);
6558
+ return true;
6559
+ }
6560
+ };
6561
+ function registrationKey(registration) {
6562
+ return JSON.stringify([registration.host_source_ref, registration.host_session_ref, registration.transcript_path]);
6563
+ }
6564
+
6565
+ // host/claude/src/claude-transcript-watcher.ts
6049
6566
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
6050
6567
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6051
6568
  store;
6569
+ overflow = new ClaudeSubagentOverflowCheckpoint();
6052
6570
  diagnostic;
6053
6571
  constructor(options) {
6054
6572
  super(options, {
@@ -6063,7 +6581,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6063
6581
  return registration.transcript_path;
6064
6582
  }
6065
6583
  async listRegistrations() {
6066
- return this.store.listTranscriptRegistrations();
6584
+ const registrations = await this.store.listTranscriptRegistrations();
6585
+ this.overflow.prune(registrations);
6586
+ return registrations;
6067
6587
  }
6068
6588
  async scanOpened(handle, registration) {
6069
6589
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
@@ -6075,7 +6595,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6075
6595
  }
6076
6596
  if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
6077
6597
  const draft = mutableCursor(cursor);
6078
- await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
6598
+ await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
6079
6599
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
6080
6600
  }
6081
6601
  async scanFailed(handle, registration, error) {
@@ -6112,7 +6632,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6112
6632
  updated_at: this.stamp()
6113
6633
  };
6114
6634
  }
6115
- async scanOpenedTranscript(registration, handle, draft, size, device, inode) {
6635
+ async scanOpenedTranscript(registration, handle, previous, draft, size, device, inode) {
6116
6636
  const main2 = await this.readChunk(handle, draft.offset, size);
6117
6637
  if (main2 !== "empty" && main2 !== "partial") {
6118
6638
  await this.consumeMainChunk(registration, main2, draft);
@@ -6120,7 +6640,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6120
6640
  }
6121
6641
  draft.consumed += await this.consumeSubagents(registration, draft);
6122
6642
  await this.emitOpenTerminal(registration, draft);
6123
- await this.commitCursor(registration, handle, draft, device, inode);
6643
+ await this.commitCursor(registration, handle, previous, draft, device, inode);
6124
6644
  }
6125
6645
  async preflight(registration, handle, size, device, inode) {
6126
6646
  const existing = await this.store.readTranscriptCursor(registration);
@@ -6280,15 +6800,24 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6280
6800
  try {
6281
6801
  names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
6282
6802
  } catch (error) {
6283
- if (isMissingTranscriptError(error) || isNotDirectory(error)) return 0;
6803
+ if (isMissingTranscriptError(error) || isNotDirectory(error)) {
6804
+ this.overflow.clear(registration);
6805
+ return 0;
6806
+ }
6284
6807
  throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
6285
6808
  }
6286
6809
  const listed = new Set(names);
6287
6810
  for (const name of Object.keys(draft.subagents)) if (!listed.has(name)) delete draft.subagents[name];
6288
- if (names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
6289
- this.log(`Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`);
6290
- names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
6291
- }
6811
+ await this.overflow.observe(registration, names, () => {
6812
+ const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
6813
+ try {
6814
+ this.log(line);
6815
+ } catch {
6816
+ return false;
6817
+ }
6818
+ return true;
6819
+ });
6820
+ names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
6292
6821
  let consumed = 0;
6293
6822
  for (const name of names) {
6294
6823
  consumed += await this.consumeSubagentFile(draft, directory, name);
@@ -6296,7 +6825,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6296
6825
  return consumed;
6297
6826
  }
6298
6827
  async consumeSubagentFile(draft, directory, name) {
6299
- const path = join6(directory, name);
6828
+ const path = join7(directory, name);
6300
6829
  let handle;
6301
6830
  try {
6302
6831
  handle = await openNoFollow(path);
@@ -6377,9 +6906,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6377
6906
  expires_at: this.expire(this.outboxRetentionMs)
6378
6907
  });
6379
6908
  }
6380
- async commitCursor(registration, handle, draft, device, inode) {
6909
+ async commitCursor(registration, handle, previous, draft, device, inode) {
6381
6910
  const anchor = await this.readAnchor(handle, draft.offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
6382
- await this.store.writeTranscriptCursor({
6911
+ const cursor = {
6383
6912
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
6384
6913
  host_source_ref: registration.host_source_ref,
6385
6914
  host_session_ref: registration.host_session_ref,
@@ -6396,7 +6925,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
6396
6925
  ...draft.session_observed ? { session_observed: true } : {},
6397
6926
  status: "active",
6398
6927
  updated_at: this.stamp()
6399
- });
6928
+ };
6929
+ if (sameCursorContent(cursor, previous)) return;
6930
+ await this.store.writeTranscriptCursor(cursor);
6400
6931
  }
6401
6932
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
6402
6933
  try {
@@ -6447,6 +6978,9 @@ function mutableCursor(cursor) {
6447
6978
  enqueued: 0
6448
6979
  };
6449
6980
  }
6981
+ function sameCursorContent(left, right) {
6982
+ return isDeepStrictEqual({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
6983
+ }
6450
6984
  function zeroCounts() {
6451
6985
  return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
6452
6986
  }
@@ -6540,7 +7074,7 @@ function isAssistantUsageLine(record6) {
6540
7074
  }
6541
7075
  function subagentsDirectory(transcriptPath) {
6542
7076
  const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
6543
- return join6(stem, "subagents");
7077
+ return join7(stem, "subagents");
6544
7078
  }
6545
7079
  function observationRef(hostSourceRef, event, identity, value) {
6546
7080
  return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
@@ -6577,11 +7111,14 @@ function isSymlinkTranscript(error) {
6577
7111
  }
6578
7112
 
6579
7113
  // host/claude/src/claude-producer-runtime.ts
6580
- async function drainClaudeProducerOnce(options) {
6581
- const scan = await new ClaudeTranscriptWatcher({
6582
- outbox_dir: options.outbox_dir,
7114
+ function createClaudeProducerWatcher(outboxDir) {
7115
+ return new ClaudeTranscriptWatcher({
7116
+ outbox_dir: outboxDir,
6583
7117
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
6584
- }).scanOnce().catch((error) => {
7118
+ });
7119
+ }
7120
+ async function drainClaudeProducerOnce(options) {
7121
+ const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
6585
7122
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
6586
7123
  throw error;
6587
7124
  });
@@ -6590,33 +7127,28 @@ async function drainClaudeProducerOnce(options) {
6590
7127
  }
6591
7128
 
6592
7129
  // host/claude/src/claude-usage-facts-capturer.ts
6593
- import { createHash as createHash8 } from "node:crypto";
7130
+ import { createHash as createHash9 } from "node:crypto";
6594
7131
  import { constants as constants7 } from "node:fs";
6595
7132
  import { readdir as readdir3 } from "node:fs/promises";
6596
- import { join as join7 } from "node:path";
7133
+ import { join as join8 } from "node:path";
6597
7134
  var ClaudeUsageFactsCapturer = class {
6598
7135
  sources;
6599
7136
  usage;
6600
7137
  now;
6601
- diagnosticSink;
6602
- nextRegistrationIndex = 0;
7138
+ registrations;
6603
7139
  nextSourceSlot = "main";
6604
7140
  nextSubagentIndex = 0;
7141
+ overflow = new ClaudeSubagentOverflowCheckpoint();
6605
7142
  constructor(options) {
6606
7143
  this.sources = new ClaudeOutboxStore(options.outbox_dir);
6607
7144
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
6608
7145
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
6609
- this.diagnosticSink = options.diagnostic_sink;
7146
+ this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
6610
7147
  }
6611
7148
  async captureNext() {
6612
7149
  const registrations = await this.sources.listTranscriptRegistrations();
6613
- let failed = false;
6614
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
6615
- failed = true;
6616
- }));
6617
- this.nextRegistrationIndex = result.nextIndex;
6618
- if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
6619
- return result.captured;
7150
+ this.overflow.prune(registrations);
7151
+ return await this.registrations.captureNext(registrations, (registration, onFailure) => this.captureRegistration(registration, onFailure));
6620
7152
  }
6621
7153
  async captureRegistration(registration, onFailure) {
6622
7154
  const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
@@ -6663,13 +7195,14 @@ var ClaudeUsageFactsCapturer = class {
6663
7195
  }
6664
7196
  async captureSubagent(registration, onFailure) {
6665
7197
  const names = await readSubagentNames(registration);
7198
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
6666
7199
  let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
6667
7200
  if (state === null) return false;
6668
7201
  state = await this.usage.recoverPending(state);
6669
7202
  if (state.quarantined_reason !== void 0) return false;
6670
7203
  if (await this.retireMissingSubagent(state, names)) return true;
6671
7204
  if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
6672
- return await this.recordExcessSubagentGap(state, names);
7205
+ return await this.recordExcessSubagentGap(registration, state, names);
6673
7206
  }
6674
7207
  async retireMissingSubagent(state, names) {
6675
7208
  const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
@@ -6680,14 +7213,14 @@ var ClaudeUsageFactsCapturer = class {
6680
7213
  }
6681
7214
  return false;
6682
7215
  }
6683
- async recordExcessSubagentGap(state, names) {
6684
- const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
6685
- if (excessCount <= 0) return false;
7216
+ async recordExcessSubagentGap(registration, state, names) {
6686
7217
  const mainCursor = state.cursors.main;
6687
7218
  if (mainCursor === void 0) return false;
6688
- const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
6689
- await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
6690
- return true;
7219
+ return await this.overflow.observe(registration, names, async () => {
7220
+ 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 };
7221
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
7222
+ return true;
7223
+ });
6691
7224
  }
6692
7225
  async captureListedSubagents(registration, names, state, onFailure) {
6693
7226
  const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
@@ -6710,7 +7243,7 @@ var ClaudeUsageFactsCapturer = class {
6710
7243
  async captureSubagentFile(registration, name, state) {
6711
7244
  let handle;
6712
7245
  try {
6713
- const opened = await readHostUsageTranscriptSource(() => openNoFollow(join7(subagentsDirectory(registration.transcript_path), name), constants7.O_RDONLY));
7246
+ const opened = await readHostUsageTranscriptSource(() => openNoFollow(join8(subagentsDirectory(registration.transcript_path), name), constants7.O_RDONLY));
6714
7247
  handle = opened;
6715
7248
  const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
6716
7249
  const sourceRef = sourceFileRef(registration, file.device, file.inode);
@@ -6957,7 +7490,7 @@ function errorCode5(error) {
6957
7490
  return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
6958
7491
  }
6959
7492
  function sha2563(value) {
6960
- return createHash8("sha256").update(value).digest("hex");
7493
+ return createHash9("sha256").update(value).digest("hex");
6961
7494
  }
6962
7495
 
6963
7496
  // host/claude/src/claude-producer-service.ts
@@ -6968,7 +7501,7 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
6968
7501
  producer_id: "claude",
6969
7502
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
6970
7503
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
6971
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
7504
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createClaudeProducerWatcher(config.outbox_dir) }),
6972
7505
  drain: drainClaudeProducerOnce,
6973
7506
  background: (config, signal, dependencies) => {
6974
7507
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
@@ -6979,14 +7512,14 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
6979
7512
  // host/claude/src/claude-visible-output-budget.ts
6980
7513
  import { readFile as readFile2 } from "node:fs/promises";
6981
7514
  import { homedir } from "node:os";
6982
- import { join as join9 } from "node:path";
7515
+ import { join as join10 } from "node:path";
6983
7516
 
6984
7517
  // host/claude/src/claude-runtime-paths.ts
6985
- import { join as join8 } from "node:path";
7518
+ import { join as join9 } from "node:path";
6986
7519
  var CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT = "CLAUDE_CONFIG_DIR";
6987
7520
  var CLAUDE_HOME_DEFAULT_DIRECTORY = ".claude";
6988
7521
  function resolveClaudeConfigHome(environment, home) {
6989
- return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join8(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
7522
+ return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join9(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
6990
7523
  }
6991
7524
 
6992
7525
  // host/claude/src/claude-visible-output-budget.ts
@@ -7000,9 +7533,9 @@ async function resolveClaudeVisibleOutputMaxBytes(environment = process.env, wor
7000
7533
  }
7001
7534
  async function projectOrUserInlineLimit(environment, workingDirectory) {
7002
7535
  const configHome = resolveClaudeConfigHome(environment, homedir());
7003
- const userLimit = await settingsInlineLimit(join9(configHome, "settings.json"));
7004
- const projectLimit = await settingsInlineLimit(join9(workingDirectory, ".claude", "settings.json"));
7005
- const localLimit = await settingsInlineLimit(join9(workingDirectory, ".claude", "settings.local.json"));
7536
+ const userLimit = await settingsInlineLimit(join10(configHome, "settings.json"));
7537
+ const projectLimit = await settingsInlineLimit(join10(workingDirectory, ".claude", "settings.json"));
7538
+ const localLimit = await settingsInlineLimit(join10(workingDirectory, ".claude", "settings.local.json"));
7006
7539
  const candidate = localLimit ?? projectLimit ?? userLimit;
7007
7540
  return candidate === void 0 ? void 0 : Math.min(candidate, CLAUDE_MAX_INLINE_OUTPUT_MAX_CHARS);
7008
7541
  }
@@ -7042,7 +7575,7 @@ function runClaudeInvocationAuthenticationCommand(args, options) {
7042
7575
  return runHostInvocationAuthenticationCommand(CLAUDE_INVOCATION_AUTHENTICATION_DESCRIPTOR, args, options);
7043
7576
  }
7044
7577
  async function readClaudeInvocationHumanMessageWindow(input) {
7045
- return readRegisteredHostInvocationHumanMessageWindow(() => input.store.listTranscriptRegistrations(), (registration) => input.store.readTranscriptCursor(registration), input.identity, (line, registration) => {
7578
+ return readRegisteredHostInvocationHumanMessageWindow((identity) => input.store.readTranscriptRegistration(identity.host_source_ref, identity.host_session_ref), (registration) => input.store.readTranscriptCursor(registration), input.identity, (line, registration) => {
7046
7579
  let row;
7047
7580
  try {
7048
7581
  row = JSON.parse(line);
@@ -7059,10 +7592,10 @@ async function readClaudeInvocationHumanMessageWindow(input) {
7059
7592
  }
7060
7593
 
7061
7594
  // host/client-doctor.ts
7062
- import { createHash as createHash9 } from "node:crypto";
7595
+ import { createHash as createHash10 } from "node:crypto";
7063
7596
  import { execFile as execFile2 } from "node:child_process";
7064
7597
  import { access, open as open4, readFile as readFile3, realpath, stat as stat2 } from "node:fs/promises";
7065
- import { delimiter, extname, isAbsolute as isAbsolute4, join as join10 } from "node:path";
7598
+ import { delimiter, extname, isAbsolute as isAbsolute5, join as join11 } from "node:path";
7066
7599
  import { promisify } from "node:util";
7067
7600
 
7068
7601
  // host/environment.ts
@@ -7180,7 +7713,7 @@ async function inspectExecutable(options, environment, component) {
7180
7713
  try {
7181
7714
  executable = await (options.resolve_executable ?? resolveCealExecutable)(options.executable ?? "ceal", environment);
7182
7715
  } catch (error) {
7183
- return inspectedFailure("ceal_unavailable", `The ${component} Host cannot resolve an executable Ceal client from its current environment (${refusalFact("error", error)}).`, `Install the intended Ceal client in the Host PATH, restart ${component}, and run this doctor again.`);
7716
+ return inspectedFailure("ceal_unavailable", `The ${component} Host cannot resolve an executable Ceal client from its current environment (${renderOperatorDiagnostic(error)}).`, `Install the intended Ceal client in the Host PATH, restart ${component}, and run this doctor again.`);
7184
7717
  }
7185
7718
  if (!validExpectations(options) || options.expected_sha256 !== void 0 && executable.sha256 !== options.expected_sha256) return inspectedFailure("ceal_identity_mismatch", `The Ceal executable visible to the ${component} Host does not match the intended candidate.`, `Install the exact candidate bytes, restart ${component}, and run this doctor with the expected identity.`);
7186
7719
  return { ok: true, value: executable };
@@ -7229,8 +7762,8 @@ async function resolveCealExecutable(command, environment, platform = process.pl
7229
7762
  if (!metadata.isFile()) continue;
7230
7763
  const launcherKind = await inspectLauncherKind(path);
7231
7764
  if (launcherKind !== void 0) return resolveLauncherBinary(path, launcherKind, environment, platform);
7232
- if (platform === "win32" && !isAbsolute4(command) && extname(path) === "") continue;
7233
- return { path, sha256: createHash9("sha256").update(await readFile3(path)).digest("hex") };
7765
+ if (platform === "win32" && !isAbsolute5(command) && extname(path) === "") continue;
7766
+ return { path, sha256: createHash10("sha256").update(await readFile3(path)).digest("hex") };
7234
7767
  } catch {
7235
7768
  }
7236
7769
  }
@@ -7252,7 +7785,7 @@ async function inspectLauncherKind(path) {
7252
7785
  }
7253
7786
  async function resolveLauncherBinary(launcherPath, kind, environment, platform) {
7254
7787
  const invocation = hostScriptLauncherInvocation(launcherPath, CEAL_CLIENT_DOCTOR_COMMAND, kind, platform, environment);
7255
- const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
7788
+ const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, cwd: resolveCealSpawnWorkingDirectory(), ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
7256
7789
  let parsed;
7257
7790
  try {
7258
7791
  parsed = JSON.parse(result.stdout);
@@ -7263,18 +7796,18 @@ async function resolveLauncherBinary(launcherPath, kind, environment, platform)
7263
7796
  const binaryPath = await realpath(parsed.binary_path);
7264
7797
  const metadata = await stat2(binaryPath);
7265
7798
  if (!metadata.isFile()) throw new Error("launcher doctor reported a non-file binary path");
7266
- return { path: binaryPath, sha256: createHash9("sha256").update(await readFile3(binaryPath)).digest("hex") };
7799
+ return { path: binaryPath, sha256: createHash10("sha256").update(await readFile3(binaryPath)).digest("hex") };
7267
7800
  }
7268
7801
  function executableCandidates(command, environment, platform) {
7269
- if (isAbsolute4(command)) return [command];
7802
+ if (isAbsolute5(command)) return [command];
7270
7803
  const pathValue = environmentValue(environment, "PATH", platform) ?? "";
7271
7804
  const directories = pathValue.split(delimiter).filter((entry) => entry.length > 0);
7272
- if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join10(entry, command));
7273
- return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join10(entry, `${command}${suffix}`)));
7805
+ if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join11(entry, command));
7806
+ return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join11(entry, `${command}${suffix}`)));
7274
7807
  }
7275
7808
  async function executeCealCommand(executable, args, environment) {
7276
7809
  try {
7277
- const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8" });
7810
+ const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8", cwd: resolveCealSpawnWorkingDirectory() });
7278
7811
  return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
7279
7812
  } catch (error) {
7280
7813
  if (isRecord8(error)) return { exit_code: typeof error.code === "number" ? error.code : 1, stdout: typeof error.stdout === "string" ? error.stdout : "", stderr: typeof error.stderr === "string" ? error.stderr : "" };