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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2124,6 +2124,15 @@ import { lstat, mkdir, unlink } from "node:fs/promises";
2124
2124
  import { createConnection } from "node:net";
2125
2125
  import { dirname } from "node:path";
2126
2126
 
2127
+ // packages/ceal-client-protocol/src/vocabulary.ts
2128
+ function vocabulary(words) {
2129
+ return Object.freeze(words);
2130
+ }
2131
+
2132
+ // packages/ceal-client-protocol/src/host-usage-fields.ts
2133
+ var CEAL_CODEX_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
2134
+ var CEAL_CLAUDE_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"]);
2135
+
2127
2136
  // packages/ceal-client-protocol/src/canonical-json.ts
2128
2137
  function cealCanonicalJson(value) {
2129
2138
  if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
@@ -2198,7 +2207,7 @@ var client_wire_contract_default = {
2198
2207
  },
2199
2208
  command_request: {
2200
2209
  schema_name: "ceal.command_request",
2201
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
2210
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
2202
2211
  absolute_transport_max_bytes: 65536
2203
2212
  },
2204
2213
  command_resolution: {
@@ -2244,7 +2253,7 @@ var client_wire_contract_default = {
2244
2253
  },
2245
2254
  command_response: {
2246
2255
  schema_name: "ceal.command_response",
2247
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
2256
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
2248
2257
  descriptor_field: "verified_artifact",
2249
2258
  request_context_field: "request_context",
2250
2259
  required_fields: [
@@ -2257,7 +2266,8 @@ var client_wire_contract_default = {
2257
2266
  "visible_output_max_bytes",
2258
2267
  "local_delivery",
2259
2268
  "verified_artifact",
2260
- "request_context"
2269
+ "request_context",
2270
+ "result_file"
2261
2271
  ],
2262
2272
  bare_document_fields: [
2263
2273
  "invocation",
@@ -2298,8 +2308,11 @@ var client_wire_contract_default = {
2298
2308
  "ok",
2299
2309
  "code",
2300
2310
  "reason",
2301
- "gateway_status"
2311
+ "gateway_status",
2312
+ "retry_after_ms"
2302
2313
  ],
2314
+ refusal_required_fields: ["schema_version", "ok", "code", "reason"],
2315
+ refusal_optional_fields: ["gateway_status", "retry_after_ms"],
2303
2316
  client_nonce: {
2304
2317
  character_class_source: "A-Za-z0-9_-",
2305
2318
  encoded_characters: 43
@@ -2518,16 +2531,14 @@ var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
2518
2531
  personal_authorization_required: "connect_personal_account"
2519
2532
  });
2520
2533
 
2521
- // packages/ceal-client-protocol/src/vocabulary.ts
2522
- function vocabulary(words) {
2523
- return Object.freeze(words);
2524
- }
2525
-
2526
2534
  // packages/ceal-client-protocol/src/gateway-response-types.ts
2527
2535
  var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
2528
2536
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
2529
2537
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
2530
2538
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
2539
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
2540
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
2541
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
2531
2542
  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"]);
2532
2543
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
2533
2544
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -2568,6 +2579,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
2568
2579
  ]);
2569
2580
 
2570
2581
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
2582
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
2583
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
2584
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
2585
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
2586
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
2587
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
2588
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
2589
+ function escapePathPattern(value) {
2590
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
2591
+ }
2592
+ function machineHomePathPatterns(flags) {
2593
+ const posix12 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
2594
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
2595
+ return [new RegExp(posix12, flags), new RegExp(windows, flags)];
2596
+ }
2571
2597
  var CealProtocolValidationError = class extends Error {
2572
2598
  name = "CealProtocolValidationError";
2573
2599
  code;
@@ -2921,8 +2947,9 @@ var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask a
2921
2947
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
2922
2948
  var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
2923
2949
  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.";
2924
- var HOST_CONTEXT_UNAVAILABLE = "The Host could not select or activate the current recorded turn. This does not explain why or prove ephemerality. For an independently identified ephemeral Codex side conversation, invoke the command as `ceal --standalone ...`; it uses the local Ceal session and Gateway permissions without Host session/turn audit linkage. Host refusal never switches modes. For intended Host calls, restart the producer and start a new conversation; report the error if it persists.";
2950
+ 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.";
2925
2951
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
2952
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
2926
2953
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
2927
2954
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
2928
2955
  }
@@ -2943,13 +2970,18 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2943
2970
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2944
2971
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2945
2972
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2946
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2947
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2948
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2949
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2950
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2951
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2952
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2973
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2974
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2975
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2976
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2977
+ 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),
2978
+ 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),
2979
+ 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),
2980
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2981
+ 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),
2982
+ 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),
2983
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
2984
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2953
2985
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2954
2986
  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),
2955
2987
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -2964,23 +2996,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2964
2996
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
2965
2997
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
2966
2998
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
2967
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
2968
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
2969
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
2970
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
2999
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
3000
+ [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),
2971
3001
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
2972
3002
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
2973
3003
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
2974
3004
  internal_error: guidance("The Gateway failed without exposing internal state.", "answer_with_gap", 500),
2975
3005
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
2976
- // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
3006
+ // the static client variant was retired when the client started reading this table.
2977
3007
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
2978
3008
  gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
2979
- // Restored verbatim from the retired `localFailureText` `unknown_outcome`
2980
- // case: the outcome is unknown, so a read may be retried while a write
2981
- // must receipt-check first. Collapsing both to "do not repeat the call"
2982
- // forbids the safe read retry the sentence exists to allow.
2983
- unknown_outcome: guidance("The transport outcome is unknown: a read may be retried; for a write, check write_receipt.get before repeating.", "answer_with_gap", 500),
3009
+ // The safe move varies by request. Keep the sentence conditional on the
3010
+ // same `retryable` and `next_action` facts the response exposes.
3011
+ unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
3012
+ // 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.
3013
+ 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),
2984
3014
  // Restored verbatim from the retired `localFailureText`
2985
3015
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
2986
3016
  // session context unavailable, so the caller repairs or adopts the
@@ -3061,8 +3091,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
3061
3091
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
3062
3092
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
3063
3093
  // is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
3064
- // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). Cause-specific
3065
- // sentences carry the retired policy remedies; `gateway_refused` reuses the release-upgrade guidance above.
3094
+ // and `retryable` from `hostAuthenticationFailureForCause` (the table's explicit retry verdict). Cause-specific
3095
+ // sentences carry only remedies proved by the Host or Relay cause; generic Gateway refusals do not prove a release mismatch.
3066
3096
  // Statuses are the
3067
3097
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
3068
3098
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
@@ -3072,21 +3102,23 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
3072
3102
  // The bounded Host reason does not prove ephemerality. A Host refusal never
3073
3103
  // changes mode; standalone remains the separate Client authority path.
3074
3104
  host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
3075
- host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
3076
- host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
3105
+ 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),
3106
+ 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),
3107
+ 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),
3077
3108
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
3078
3109
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
3079
3110
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
3080
3111
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
3081
- host_mint_gateway_refused: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
3112
+ host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
3082
3113
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
3114
+ host_contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
3083
3115
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
3084
3116
  // producer-frame fault names the administrator repair step.
3085
3117
  host_producer_frame_invalid: guidance("Ask an administrator to inspect and repair the producer frame, then start a fresh Host turn.", "ask_admin", 400),
3086
3118
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
3087
3119
  // sandboxed Relay socket names the run-alone retry.
3088
3120
  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),
3089
- host_relay_unavailable: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 503),
3121
+ host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
3090
3122
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
3091
3123
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
3092
3124
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -3124,7 +3156,7 @@ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
3124
3156
  var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
3125
3157
  var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
3126
3158
  var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
3127
- var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
3159
+ var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_applicable", "not_offered", "offered", "accepted", "rejected", "unknown"]);
3128
3160
  var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
3129
3161
  var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
3130
3162
  var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
@@ -3295,6 +3327,7 @@ var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
3295
3327
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
3296
3328
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
3297
3329
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
3330
+ var CEAL_PROVIDER_BOUNDARY_FIELDS = vocabulary(["provider_boundary_ref", "provider_boundary_kind", "provider_boundary_label", "provider_native_id", "provider_boundary_evidence"]);
3298
3331
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
3299
3332
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
3300
3333
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -3340,7 +3373,7 @@ var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
3340
3373
  var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
3341
3374
  var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
3342
3375
  var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
3343
- var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
3376
+ var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary", "standard_names"]);
3344
3377
 
3345
3378
  // packages/ceal-client-protocol/src/operation-catalog.ts
3346
3379
  var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
@@ -3436,6 +3469,7 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
3436
3469
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
3437
3470
  gateway_access_group_connector_calendar_scope_audit: (root) => join(root, "profile-connector-calendar-scope-audit.jsonl"),
3438
3471
  gateway_access_group_connector_readiness_audit: (root) => join(root, "profile-connector-readiness.audit.jsonl"),
3472
+ gateway_deployment_events: (root) => join(root, "gateway-deployments.jsonl"),
3439
3473
  gateway_organization_audit_ledger: (root) => join(root, "organization-ledger.jsonl"),
3440
3474
  gateway_personal_client_audit: (root) => join(root, "audit.jsonl"),
3441
3475
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
@@ -3466,6 +3500,11 @@ var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_L
3466
3500
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
3467
3501
  var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
3468
3502
 
3503
+ // packages/ceal-client-protocol/src/resource-read-result.ts
3504
+ var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
3505
+ var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
3506
+ var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
3507
+
3469
3508
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
3470
3509
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
3471
3510
 
@@ -3553,6 +3592,7 @@ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
3553
3592
  { provider: "google-workspace", result_kind: "calendar_event_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "htmlLink", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
3554
3593
  { provider: "google-workspace", result_kind: "drive_document_calendar_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink or htmlLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
3555
3594
  { provider: "google-workspace", result_kind: "drive_file_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
3595
+ { provider: "google-workspace", result_kind: "form_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified Forms responderUri", source: "https://developers.google.com/workspace/forms/api/reference/rest/v1/forms" },
3556
3596
  { provider: "google-workspace", result_kind: "spreadsheet_write_result", field: "spreadsheet_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
3557
3597
  { provider: "google-workspace", result_kind: "calendar_meet_link_write_result", field: "meet_url", status: "required_when_provider_supplies", provider_shape: "verified conferenceData entryPoint uri", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
3558
3598
  { provider: "google-workspace", result_kind: "gmail_message_read_row", field: "source_url", status: "not_available", reason: "The Gmail API Message representation exposes id and threadId but no human UI URL; cite by title and date.", source: "https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.messages#Message" },
@@ -3627,6 +3667,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3627
3667
  "review_submitted",
3628
3668
  "comment_created",
3629
3669
  "reaction_created",
3670
+ "pull_request_merged",
3671
+ "release_published",
3630
3672
  "ceal_write_completed",
3631
3673
  "event_start",
3632
3674
  "all_day_start",
@@ -3638,7 +3680,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3638
3680
  "page_last_edited",
3639
3681
  "resource_modified"
3640
3682
  ]);
3641
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
3683
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
3642
3684
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
3643
3685
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
3644
3686
  "provider_page_budget",
@@ -3659,6 +3701,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3659
3701
  "github.pull_request.opened",
3660
3702
  "github.issue.edited",
3661
3703
  "github.pull_request.edited",
3704
+ "github.pull_request.merged",
3705
+ "github.release.published",
3662
3706
  "github.review.submitted",
3663
3707
  "github.issue_comment.created",
3664
3708
  "github.review_comment.created",
@@ -3672,6 +3716,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3672
3716
  "drive.file.created",
3673
3717
  "drive.file.modified",
3674
3718
  "drive.file.viewed",
3719
+ "mail.sent",
3675
3720
  "notion.page.created",
3676
3721
  "notion.page.edited"
3677
3722
  ]);
@@ -3685,6 +3730,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3685
3730
  "github.review_comment.created": "comment_created",
3686
3731
  "github.issue.opened": "resource_created",
3687
3732
  "github.pull_request.opened": "resource_created",
3733
+ "github.pull_request.merged": "pull_request_merged",
3734
+ "github.release.published": "release_published",
3688
3735
  "github.issue.edited": "resource_modified",
3689
3736
  "github.pull_request.edited": "resource_modified",
3690
3737
  "github.reaction.created": "reaction_created",
@@ -3695,6 +3742,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3695
3742
  "drive.file.created": "file_created",
3696
3743
  "drive.file.modified": "file_modified_by_me",
3697
3744
  "drive.file.viewed": "file_viewed_by_me",
3745
+ "mail.sent": "message_created",
3698
3746
  "notion.page.created": "page_created",
3699
3747
  "notion.page.edited": "page_last_edited"
3700
3748
  });
@@ -3722,6 +3770,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
3722
3770
  created_at: { required: false, timestamp: true },
3723
3771
  created_at_local: { required: false, timestamp: true },
3724
3772
  modified_at: { required: false, timestamp: true },
3773
+ observed_at: { required: false, timestamp: true },
3725
3774
  modified_at_local: { required: false, timestamp: true },
3726
3775
  viewed_by_me_at: { required: false, timestamp: true },
3727
3776
  modified_by_me_at: { required: false, timestamp: true },
@@ -3749,9 +3798,6 @@ var RESOURCE_ROW_REQUIRED_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(
3749
3798
  var RESOURCE_ROW_KEYS = new Set(Object.keys(RESOURCE_ROW_KEY_RULES));
3750
3799
  var RESOURCE_ROW_TIMESTAMP_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(([key, rule]) => rule.timestamp ? [key] : []);
3751
3800
 
3752
- // packages/ceal-client-protocol/src/resource-read-result.ts
3753
- var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
3754
-
3755
3801
  // packages/ceal-client-protocol/src/excluded-target-coverage.ts
3756
3802
  var CEAL_EXCLUDED_TARGET_COVERAGE_MAX_ENTRIES = 64;
3757
3803
  function cealExcludedTargetCoverageJsonSchema() {
@@ -3807,6 +3853,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
3807
3853
  "principal_inactive",
3808
3854
  "authority_replaced",
3809
3855
  "refresh_recovery_unavailable",
3856
+ "refresh_recovery_outcome_unavailable",
3857
+ "refresh_state_unavailable",
3810
3858
  "refresh_recovery_expired",
3811
3859
  // The serving gate answers this while the Gateway is still starting and the
3812
3860
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -4059,7 +4107,7 @@ function validateBatchContents(value) {
4059
4107
  if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
4060
4108
  const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
4061
4109
  for (const fact of facts) {
4062
- validateFact(fact, value.host_session_ref);
4110
+ validateCealHostUsageFact(fact, value.host_session_ref);
4063
4111
  if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
4064
4112
  }
4065
4113
  for (const gap of gaps) {
@@ -4092,7 +4140,7 @@ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, d
4092
4140
  for (const part of [producer, hostSourceRef, hostSessionRef, device, inode]) if (typeof part !== "string" || part.length === 0 || part.length > 512) invalid("Ceal Host usage file identity is invalid.");
4093
4141
  return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
4094
4142
  }
4095
- function validateFact(value, sessionRef) {
4143
+ function validateCealHostUsageFact(value, sessionRef) {
4096
4144
  if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
4097
4145
  requireFactByteLimit(value);
4098
4146
  if (value.producer === "codex_transcript") validateCodexFact(value);
@@ -4156,7 +4204,7 @@ function validCorrectionSemantics(value) {
4156
4204
  }
4157
4205
  function validateCodexUsageCounts(value) {
4158
4206
  if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
4159
- requireExactOperationKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
4207
+ requireExactOperationKeys(value, CEAL_CODEX_USAGE_COUNT_FIELDS);
4160
4208
  for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
4161
4209
  if (Number(value.total_tokens) !== Number(value.input_tokens) + Number(value.output_tokens) || Number(value.cached_input_tokens) + Number(value.cache_write_input_tokens) > Number(value.input_tokens) || Number(value.reasoning_output_tokens) > Number(value.output_tokens)) invalid("Ceal Codex usage fields are inconsistent.");
4162
4210
  }
@@ -4424,6 +4472,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
4424
4472
  "options_invalid",
4425
4473
  "session_unavailable",
4426
4474
  "context_unavailable",
4475
+ "activation_wait_exhausted",
4427
4476
  "context_replaced",
4428
4477
  "no_binding",
4429
4478
  "context_expired",
@@ -4459,22 +4508,23 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
4459
4508
  // This reason cannot distinguish a Codex side conversation from a missing
4460
4509
  // context in a regular session, so guidance must leave that choice to the caller.
4461
4510
  context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
4462
- context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
4511
+ activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
4512
+ context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
4463
4513
  // `no_binding` now means the producer has no real current Host session. The
4464
4514
  // Host Relay never uses it for an uncreated Gateway Request; there is no
4465
4515
  // useful retry until the consumer is running inside a Host session.
4466
4516
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
4467
- context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
4517
+ context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
4468
4518
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
4469
4519
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
4470
4520
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
4471
4521
  gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
4472
- contract_mismatch: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
4473
- gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "upgrade_ceal_client" }),
4522
+ contract_mismatch: Object.freeze({ classification: "host_contract_mismatch", next_action: "upgrade_ceal_client" }),
4523
+ gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
4474
4524
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
4475
4525
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
4476
4526
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
4477
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
4527
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
4478
4528
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
4479
4529
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
4480
4530
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -4522,11 +4572,10 @@ function isCealHostServiceDiagnosticCause(value, event) {
4522
4572
  // packages/ceal-client-protocol/src/client-result-materialization.ts
4523
4573
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
4524
4574
  var REQUIRED_FIELDS2 = Object.freeze(["schema_version", "operation_id", "path", "sha256"]);
4525
- var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "items_path", "row_count", "result_complete", "coverage", "local_result_root", "model_disclosure", "continue_argv", "how_to_read"]);
4575
+ var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "local_result_root", "request_context_argv", "how_to_read"]);
4526
4576
 
4527
4577
  // packages/ceal-client-protocol/src/session-start-affordance.ts
4528
4578
  var CEAL_SESSION_ENTRY_INVOCATION = "ceal";
4529
- var HOST_HOOK_TIMEOUT_SECONDS = 1;
4530
4579
 
4531
4580
  // packages/ceal-client-protocol/src/discovery-manifest.ts
4532
4581
  var DISCOVERY_MANIFEST_KEYS = CEAL_CLIENT_WIRE_CONTRACT.command_response.discovery_manifest_fields;
@@ -4568,6 +4617,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
4568
4617
  maximum: CEAL_PROTOCOL_VERSION
4569
4618
  });
4570
4619
 
4620
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
4621
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
4622
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
4623
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
4624
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
4625
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
4626
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
4627
+ function redactOperatorDiagnosticSecrets(value) {
4628
+ 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]");
4629
+ }
4630
+ function redactOperatorDiagnosticText(value) {
4631
+ const normalized = normalizeCealSingleLineText(value);
4632
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
4633
+ }
4634
+ function renderOperatorDiagnostic(value) {
4635
+ const state = collectDiagnosticState(value);
4636
+ const fields = [
4637
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
4638
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
4639
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
4640
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
4641
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
4642
+ ].filter((field) => field !== void 0);
4643
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
4644
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
4645
+ }
4646
+ function collectDiagnosticState(value) {
4647
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
4648
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
4649
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
4650
+ const current = pending.shift();
4651
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
4652
+ }
4653
+ return state;
4654
+ }
4655
+ function visitDiagnosticNode(current, state, pending, visited) {
4656
+ if (isObject(current)) {
4657
+ if (visited.has(current)) return;
4658
+ visited.add(current);
4659
+ }
4660
+ captureProcessEvidence(current, state);
4661
+ appendCause(current, state.causes);
4662
+ enqueueCauseChildren(current, state.causes.length, pending);
4663
+ }
4664
+ function captureProcessEvidence(current, state) {
4665
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
4666
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
4667
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
4668
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
4669
+ }
4670
+ function appendCause(current, causes) {
4671
+ const errors = read(current, "errors");
4672
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
4673
+ causes.push(errorCause(current));
4674
+ return;
4675
+ }
4676
+ if (!isObject(current)) {
4677
+ const message = safeText(current);
4678
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
4679
+ }
4680
+ }
4681
+ function errorCause(error) {
4682
+ const name = safeText(read(error, "name")) ?? "Error";
4683
+ const message = safeText(read(error, "message"));
4684
+ const codeValue = read(error, "code");
4685
+ const code2 = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
4686
+ const errnoValue = read(error, "errno");
4687
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
4688
+ const syscall = safeText(read(error, "syscall"));
4689
+ const path = safePath(read(error, "path"));
4690
+ 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 } });
4691
+ }
4692
+ function enqueueCauseChildren(current, causeCount, pending) {
4693
+ const cause = read(current, "cause");
4694
+ if (cause !== void 0) pending.push(cause);
4695
+ const errors = read(current, "errors");
4696
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
4697
+ }
4698
+ function isObject(value) {
4699
+ return typeof value === "object" && value !== null;
4700
+ }
4701
+ function formatCause(cause) {
4702
+ const fields = [
4703
+ cause.error_class,
4704
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
4705
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
4706
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
4707
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
4708
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
4709
+ ].filter((field) => field !== void 0);
4710
+ return fields.join(" ");
4711
+ }
4712
+ function tail(value) {
4713
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
4714
+ return safeDiagnosticText(clipped);
4715
+ }
4716
+ function safeText(value) {
4717
+ if (typeof value !== "string") return void 0;
4718
+ const safe = safeDiagnosticText(value);
4719
+ if (safe.length === 0) return void 0;
4720
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
4721
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
4722
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
4723
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4724
+ }
4725
+ function safePath(value) {
4726
+ if (typeof value !== "string") return void 0;
4727
+ const safe = safeDiagnosticText(value);
4728
+ if (safe.length === 0) return void 0;
4729
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
4730
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
4731
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
4732
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4733
+ }
4734
+ function safeDiagnosticText(value) {
4735
+ return redactOperatorDiagnosticText(String(value));
4736
+ }
4737
+ function outputText(value) {
4738
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
4739
+ if (value instanceof Uint8Array) {
4740
+ try {
4741
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
4742
+ } catch {
4743
+ return void 0;
4744
+ }
4745
+ }
4746
+ return void 0;
4747
+ }
4748
+ function safeStatus(value) {
4749
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4750
+ return typeof value === "string" ? safeText(value) : void 0;
4751
+ }
4752
+ function safeExitCode(value) {
4753
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
4754
+ }
4755
+ function read(value, key) {
4756
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
4757
+ try {
4758
+ return Reflect.get(value, key);
4759
+ } catch {
4760
+ return void 0;
4761
+ }
4762
+ }
4763
+ function redactHomePaths(value) {
4764
+ const paths = [
4765
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
4766
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
4767
+ ];
4768
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
4769
+ let output = "";
4770
+ let cursor = 0;
4771
+ for (const path of paths) {
4772
+ if (path.start < cursor) continue;
4773
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
4774
+ cursor = path.end;
4775
+ }
4776
+ return output + value.slice(cursor);
4777
+ }
4778
+ function configuredHomePathPatterns() {
4779
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
4780
+ return homes.flatMap((home) => {
4781
+ const root = home.replace(/[\\/]+$/gu, "");
4782
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
4783
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
4784
+ return [{ pattern, prefixLength: root.length }];
4785
+ });
4786
+ }
4787
+ function matchedHomePrefixLength(value) {
4788
+ let separators = 0;
4789
+ for (let index = 0; index < value.length; index += 1) {
4790
+ if (value[index] !== "/" && value[index] !== "\\") continue;
4791
+ separators += 1;
4792
+ if (separators === 3) return index;
4793
+ }
4794
+ return value.length;
4795
+ }
4796
+ function redactUrls(value) {
4797
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
4798
+ }
4799
+ function redactFilePaths(value) {
4800
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
4801
+ }
4802
+ function homePathRange(value, match, prefixLength) {
4803
+ const index = match.index;
4804
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
4805
+ const start = index;
4806
+ let end = start + match[0].length;
4807
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
4808
+ if (quote !== void 0) {
4809
+ const closing = value.indexOf(quote, end);
4810
+ if (closing >= 0) end = closing;
4811
+ }
4812
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
4813
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
4814
+ }
4815
+ function truncateUtf8(value, maxBytes) {
4816
+ if (byteLength(value) <= maxBytes) return value;
4817
+ let output = "";
4818
+ for (const character of value) {
4819
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
4820
+ output += character;
4821
+ }
4822
+ return `${output}…`;
4823
+ }
4824
+
4571
4825
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
4572
4826
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
4573
4827
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -4659,11 +4913,11 @@ function withRelayEndpointLock(endpoint, run) {
4659
4913
  const gate = new Promise((resolve) => {
4660
4914
  release = resolve;
4661
4915
  });
4662
- const tail = prior.then(() => gate);
4663
- relayEndpointLocks.set(endpoint, tail);
4916
+ const tail2 = prior.then(() => gate);
4917
+ relayEndpointLocks.set(endpoint, tail2);
4664
4918
  return prior.then(run).finally(() => {
4665
4919
  release?.();
4666
- if (relayEndpointLocks.get(endpoint) === tail) relayEndpointLocks.delete(endpoint);
4920
+ if (relayEndpointLocks.get(endpoint) === tail2) relayEndpointLocks.delete(endpoint);
4667
4921
  });
4668
4922
  }
4669
4923
  function currentUid(fallback) {
@@ -4982,7 +5236,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
4982
5236
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
4983
5237
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
4984
5238
  return await new Promise((resolve, reject2) => {
4985
- const child = execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
5239
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
4986
5240
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
4987
5241
  if (exitCode === null) {
4988
5242
  reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -5344,7 +5598,7 @@ function parseCanonicalJson(text, error) {
5344
5598
  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) }])}`);
5345
5599
  return value;
5346
5600
  } catch (parseError) {
5347
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
5601
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
5348
5602
  }
5349
5603
  }
5350
5604
  function firstDifferenceIndex(left, right) {
@@ -5855,14 +6109,14 @@ var HostUsageFactsStore = class {
5855
6109
  const gate = new Promise((resolve) => {
5856
6110
  release = resolve;
5857
6111
  });
5858
- const tail = previous.then(() => gate);
5859
- SESSION_TRANSITION_TAILS.set(key, tail);
6112
+ const tail2 = previous.then(() => gate);
6113
+ SESSION_TRANSITION_TAILS.set(key, tail2);
5860
6114
  await previous;
5861
6115
  try {
5862
6116
  return await run();
5863
6117
  } finally {
5864
6118
  release?.();
5865
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
6119
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
5866
6120
  }
5867
6121
  }
5868
6122
  sessionPath(producer, hostSourceRef, hostSessionRef) {
@@ -6357,7 +6611,7 @@ var HostUsageFactsUploader = class {
6357
6611
  const registration = await readHostRegistrationAuthority(this.options.registration_state_file, this.options.host_source_ref, this.options.store_options?.platform, this.options.store_options?.secure_file_custody);
6358
6612
  const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
6359
6613
  const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
6360
- const response2 = await (this.options.fetch ?? fetch)(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
6614
+ const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
6361
6615
  method: "POST",
6362
6616
  headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
6363
6617
  body: JSON.stringify(candidate.batch),
@@ -6446,9 +6700,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
6446
6700
  let lastNewline = -1;
6447
6701
  while (position < size) {
6448
6702
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
6449
- const read = await handle.read(buffer, 0, buffer.length, position);
6450
- if (read.bytesRead === 0) break;
6451
- const chunk = buffer.subarray(0, read.bytesRead);
6703
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
6704
+ if (read2.bytesRead === 0) break;
6705
+ const chunk = buffer.subarray(0, read2.bytesRead);
6452
6706
  chunks.push(chunk);
6453
6707
  const newline = chunk.lastIndexOf(10);
6454
6708
  if (newline >= 0) lastNewline = total + newline;
@@ -6505,7 +6759,7 @@ function createTranscriptWatcherBase(options, owner) {
6505
6759
  outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
6506
6760
  now: options.now ?? (() => /* @__PURE__ */ new Date()),
6507
6761
  log: options.log ?? ((line) => {
6508
- process.stderr.write(`${line}
6762
+ writeHostServiceLogLine(`${line}
6509
6763
  `);
6510
6764
  }),
6511
6765
  producerInstallationRef: options.producer_installation_ref
@@ -6545,7 +6799,13 @@ var HostTranscriptWatcher = class {
6545
6799
  }
6546
6800
  async scanRegistration(registration) {
6547
6801
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
6548
- missing: () => this.retireMissing(registration),
6802
+ missing: async () => {
6803
+ try {
6804
+ return await this.retireMissing(registration);
6805
+ } catch (error) {
6806
+ return this.scanFailed(void 0, registration, error);
6807
+ }
6808
+ },
6549
6809
  failed: (handle, error) => this.scanFailed(handle, registration, error)
6550
6810
  });
6551
6811
  }
@@ -6615,15 +6875,15 @@ var HostProducerDrainCore = class {
6615
6875
  return run;
6616
6876
  }
6617
6877
  async drainLocked() {
6618
- const read = await this.host.listEnvelopes();
6878
+ const read2 = await this.host.listEnvelopes();
6619
6879
  let removed = 0;
6620
6880
  let expired = 0;
6621
- for (const envelope of read.entries) {
6881
+ for (const envelope of read2.entries) {
6622
6882
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
6623
6883
  else removed += 1;
6624
6884
  await this.host.removeEnvelope(envelope);
6625
6885
  }
6626
- return { removed, expired, malformed: read.malformed };
6886
+ return { removed, expired, malformed: read2.malformed };
6627
6887
  }
6628
6888
  };
6629
6889
 
@@ -6711,29 +6971,46 @@ var HostUsageTranscriptSourceError = class extends Error {
6711
6971
  this.name = "HostUsageTranscriptSourceError";
6712
6972
  }
6713
6973
  };
6714
- async function readHostUsageTranscriptSource(read) {
6974
+ async function readHostUsageTranscriptSource(read2) {
6715
6975
  try {
6716
- return await read();
6976
+ return await read2();
6717
6977
  } catch (error) {
6718
6978
  throw new HostUsageTranscriptSourceError({ cause: error });
6719
6979
  }
6720
6980
  }
6721
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
6722
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
6723
- let failed = false;
6724
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
6725
- const index = (startIndex + attempt) % registrations.length;
6726
- const registration = registrations[index];
6727
- if (registration === void 0) continue;
6728
- try {
6729
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
6730
- } catch (error) {
6731
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
6981
+ var HostUsageRegistrationCapture = class {
6982
+ nextIndex = 0;
6983
+ producer;
6984
+ diagnosticSink;
6985
+ constructor(producer, diagnosticSink) {
6986
+ this.producer = producer;
6987
+ this.diagnosticSink = diagnosticSink;
6988
+ }
6989
+ async captureNext(registrations, capture) {
6990
+ let failed = false;
6991
+ let captured = false;
6992
+ const onFailure = () => {
6732
6993
  failed = true;
6994
+ };
6995
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
6996
+ const index = (this.nextIndex + attempt) % registrations.length;
6997
+ const registration = registrations[index];
6998
+ if (registration === void 0) continue;
6999
+ try {
7000
+ captured = await capture(registration, onFailure);
7001
+ if (captured) {
7002
+ this.nextIndex = (index + 1) % registrations.length;
7003
+ break;
7004
+ }
7005
+ } catch (error) {
7006
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
7007
+ onFailure();
7008
+ }
6733
7009
  }
7010
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
7011
+ return captured;
6734
7012
  }
6735
- return { captured: false, nextIndex: startIndex, failed };
6736
- }
7013
+ };
6737
7014
  async function openHostUsageTranscriptCursor(input) {
6738
7015
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants6.O_RDONLY));
6739
7016
  let source;
@@ -6821,6 +7098,7 @@ var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
6821
7098
  // host/claude/src/claude-types.ts
6822
7099
  var CLAUDE_HOOK_EVENTS = ["SessionStart", "UserPromptSubmit"];
6823
7100
  var CLAUDE_PRIOR_HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "Stop", "StopFailure"];
7101
+ var CLAUDE_SESSION_ID_ENVIRONMENT = "CLAUDE_CODE_SESSION_ID";
6824
7102
  var CLAUDE_HOST_ERROR_CODES = ["invalid_input", "payload_rejected", "storage", "configuration"];
6825
7103
  function isClaudeHostErrorCode(value) {
6826
7104
  return typeof value === "string" && CLAUDE_HOST_ERROR_CODES.some((code2) => code2 === value);
@@ -7034,6 +7312,13 @@ var ClaudeOutboxStore = class {
7034
7312
  await this.removeStateFile(this.registrationPath(registration.host_source_ref, registration.host_session_ref));
7035
7313
  await this.removeStateFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref));
7036
7314
  }
7315
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
7316
+ if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
7317
+ await this.prepare();
7318
+ const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
7319
+ 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.");
7320
+ return registration;
7321
+ }
7037
7322
  async listTranscriptRegistrations() {
7038
7323
  await this.prepare();
7039
7324
  const registrations = [];
@@ -7303,6 +7588,7 @@ var ClaudeProducer = class {
7303
7588
 
7304
7589
  // host/claude/src/claude-transcript-watcher.ts
7305
7590
  import { readdir as readdir2 } from "node:fs/promises";
7591
+ import { isDeepStrictEqual } from "node:util";
7306
7592
  import { join as join5 } from "node:path";
7307
7593
 
7308
7594
  // host/claude/src/claude-decoder.ts
@@ -7388,10 +7674,39 @@ function record4(value) {
7388
7674
  return value !== null && typeof value === "object" && !Array.isArray(value);
7389
7675
  }
7390
7676
 
7677
+ // host/claude/src/claude-subagent-overflow-checkpoint.ts
7678
+ var ClaudeSubagentOverflowCheckpoint = class {
7679
+ observed = /* @__PURE__ */ new Map();
7680
+ prune(registrations) {
7681
+ const current = new Set(registrations.map(registrationKey));
7682
+ for (const key of this.observed.keys()) if (!current.has(key)) this.observed.delete(key);
7683
+ }
7684
+ clear(registration) {
7685
+ this.observed.delete(registrationKey(registration));
7686
+ }
7687
+ /** Names follow the producer's sorted inventory; only omitted names define overflow. */
7688
+ async observe(registration, names, report) {
7689
+ const key = registrationKey(registration);
7690
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
7691
+ this.clear(registration);
7692
+ return false;
7693
+ }
7694
+ const digest2 = transcriptObjectSha256(names.slice(CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES));
7695
+ if (this.observed.get(key) === digest2) return false;
7696
+ if (!await report()) return false;
7697
+ this.observed.set(key, digest2);
7698
+ return true;
7699
+ }
7700
+ };
7701
+ function registrationKey(registration) {
7702
+ return JSON.stringify([registration.host_source_ref, registration.host_session_ref, registration.transcript_path]);
7703
+ }
7704
+
7391
7705
  // host/claude/src/claude-transcript-watcher.ts
7392
7706
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
7393
7707
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7394
7708
  store;
7709
+ overflow = new ClaudeSubagentOverflowCheckpoint();
7395
7710
  diagnostic;
7396
7711
  constructor(options) {
7397
7712
  super(options, {
@@ -7406,17 +7721,21 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7406
7721
  return registration.transcript_path;
7407
7722
  }
7408
7723
  async listRegistrations() {
7409
- return this.store.listTranscriptRegistrations();
7724
+ const registrations = await this.store.listTranscriptRegistrations();
7725
+ this.overflow.prune(registrations);
7726
+ return registrations;
7410
7727
  }
7411
7728
  async scanOpened(handle, registration) {
7412
7729
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
7413
- const cursor = await this.preflight(registration, handle, size, device, inode);
7730
+ const preflight = await this.preflight(registration, handle, size, device, inode);
7731
+ const cursor = preflight.cursor;
7414
7732
  if (cursor === null) return { records: 0, enqueued: 0, quarantined: true };
7415
7733
  if (cursor.status === "quarantined") {
7416
7734
  return { records: 0, enqueued: 0, quarantined: true };
7417
7735
  }
7736
+ if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
7418
7737
  const draft = mutableCursor(cursor);
7419
- await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
7738
+ await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
7420
7739
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
7421
7740
  }
7422
7741
  async scanFailed(handle, registration, error) {
@@ -7427,6 +7746,15 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7427
7746
  return { records: 0, enqueued: 0, quarantined: true };
7428
7747
  }
7429
7748
  async retireMissing(registration) {
7749
+ const observedAt = this.stamp();
7750
+ if (Date.parse(registration.expires_at) <= Date.parse(observedAt)) return this.retireTranscript(registration);
7751
+ const cursor = await this.store.readTranscriptCursor(registration);
7752
+ if (cursor !== null && isUnmaterializedCursor(cursor, this.sha(Buffer.alloc(0)))) {
7753
+ return { records: 0, enqueued: 0, quarantined: false };
7754
+ }
7755
+ return this.retireTranscript(registration);
7756
+ }
7757
+ retireTranscript(registration) {
7430
7758
  return this.retireMissingTranscript(registration.transcript_path, "Claude", () => this.store.retireTranscriptRegistration(registration));
7431
7759
  }
7432
7760
  initialCursor(registration) {
@@ -7444,7 +7772,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7444
7772
  updated_at: this.stamp()
7445
7773
  };
7446
7774
  }
7447
- async scanOpenedTranscript(registration, handle, draft, size, device, inode) {
7775
+ async scanOpenedTranscript(registration, handle, previous, draft, size, device, inode) {
7448
7776
  const main = await this.readChunk(handle, draft.offset, size);
7449
7777
  if (main !== "empty" && main !== "partial") {
7450
7778
  await this.consumeMainChunk(registration, main, draft);
@@ -7452,20 +7780,22 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7452
7780
  }
7453
7781
  draft.consumed += await this.consumeSubagents(registration, draft);
7454
7782
  await this.emitOpenTerminal(registration, draft);
7455
- await this.commitCursor(registration, handle, draft, device, inode);
7783
+ await this.commitCursor(registration, handle, previous, draft, device, inode);
7456
7784
  }
7457
7785
  async preflight(registration, handle, size, device, inode) {
7458
7786
  const existing = await this.store.readTranscriptCursor(registration);
7459
- if (existing?.status === "quarantined") return existing;
7787
+ if (existing?.status === "quarantined") return { cursor: existing, checkpointPending: false };
7460
7788
  const cursor = existing ?? this.initialCursor(registration);
7461
7789
  if (cursor.device === void 0) {
7462
- if (cursor.offset !== 0) return await this.quarantineStored(cursor, device, inode, "transcript_replaced");
7463
- return { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
7790
+ const pinned = { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
7791
+ const reason2 = this.cursorIdentityReason(pinned, registration.transcript_path, device, inode);
7792
+ if (cursor.offset !== 0 || reason2 !== null) return { cursor: await this.quarantineStored(cursor, device, inode, "transcript_replaced"), checkpointPending: false };
7793
+ return { cursor: pinned, checkpointPending: true };
7464
7794
  }
7465
7795
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
7466
- if (reason !== null) return await this.quarantineStored(cursor, device, inode, reason);
7467
- if (cursor.human_message_window !== void 0) return cursor;
7468
- return { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) };
7796
+ if (reason !== null) return { cursor: await this.quarantineStored(cursor, device, inode, reason), checkpointPending: false };
7797
+ if (cursor.human_message_window !== void 0) return { cursor, checkpointPending: false };
7798
+ return { cursor: { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) }, checkpointPending: true };
7469
7799
  }
7470
7800
  async readHumanMessageProjection(registration, handle, watermark) {
7471
7801
  let offset = 0;
@@ -7610,15 +7940,24 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7610
7940
  try {
7611
7941
  names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
7612
7942
  } catch (error) {
7613
- if (isMissingTranscriptError(error) || isNotDirectory(error)) return 0;
7943
+ if (isMissingTranscriptError(error) || isNotDirectory(error)) {
7944
+ this.overflow.clear(registration);
7945
+ return 0;
7946
+ }
7614
7947
  throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
7615
7948
  }
7616
7949
  const listed = new Set(names);
7617
7950
  for (const name of Object.keys(draft.subagents)) if (!listed.has(name)) delete draft.subagents[name];
7618
- if (names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
7619
- this.log(`Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`);
7620
- names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
7621
- }
7951
+ await this.overflow.observe(registration, names, () => {
7952
+ const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
7953
+ try {
7954
+ this.log(line);
7955
+ } catch {
7956
+ return false;
7957
+ }
7958
+ return true;
7959
+ });
7960
+ names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
7622
7961
  let consumed = 0;
7623
7962
  for (const name of names) {
7624
7963
  consumed += await this.consumeSubagentFile(draft, directory, name);
@@ -7707,9 +8046,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7707
8046
  expires_at: this.expire(this.outboxRetentionMs)
7708
8047
  });
7709
8048
  }
7710
- async commitCursor(registration, handle, draft, device, inode) {
8049
+ async commitCursor(registration, handle, previous, draft, device, inode) {
7711
8050
  const anchor = await this.readAnchor(handle, draft.offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
7712
- await this.store.writeTranscriptCursor({
8051
+ const cursor = {
7713
8052
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
7714
8053
  host_source_ref: registration.host_source_ref,
7715
8054
  host_session_ref: registration.host_session_ref,
@@ -7726,7 +8065,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7726
8065
  ...draft.session_observed ? { session_observed: true } : {},
7727
8066
  status: "active",
7728
8067
  updated_at: this.stamp()
7729
- });
8068
+ };
8069
+ if (sameCursorContent(cursor, previous)) return;
8070
+ await this.store.writeTranscriptCursor(cursor);
7730
8071
  }
7731
8072
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
7732
8073
  try {
@@ -7762,6 +8103,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7762
8103
  return await this.store.readTranscriptCursor(registration).catch(() => null) ?? this.initialCursor(registration);
7763
8104
  }
7764
8105
  };
8106
+ function isUnmaterializedCursor(cursor, emptyAnchorSha256) {
8107
+ return cursor.status === "active" && cursor.device === void 0 && cursor.inode === void 0 && cursor.offset === 0 && cursor.anchor_start === 0 && cursor.anchor_sha256 === emptyAnchorSha256;
8108
+ }
7765
8109
  function mutableCursor(cursor) {
7766
8110
  return {
7767
8111
  offset: cursor.offset,
@@ -7774,6 +8118,9 @@ function mutableCursor(cursor) {
7774
8118
  enqueued: 0
7775
8119
  };
7776
8120
  }
8121
+ function sameCursorContent(left, right) {
8122
+ return isDeepStrictEqual({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
8123
+ }
7777
8124
  function zeroCounts() {
7778
8125
  return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
7779
8126
  }
@@ -7904,11 +8251,14 @@ function isSymlinkTranscript(error) {
7904
8251
  }
7905
8252
 
7906
8253
  // host/claude/src/claude-producer-runtime.ts
7907
- async function drainClaudeProducerOnce(options) {
7908
- const scan = await new ClaudeTranscriptWatcher({
7909
- outbox_dir: options.outbox_dir,
8254
+ function createClaudeProducerWatcher(outboxDir) {
8255
+ return new ClaudeTranscriptWatcher({
8256
+ outbox_dir: outboxDir,
7910
8257
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
7911
- }).scanOnce().catch((error) => {
8258
+ });
8259
+ }
8260
+ async function drainClaudeProducerOnce(options) {
8261
+ const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
7912
8262
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
7913
8263
  throw error;
7914
8264
  });
@@ -7925,25 +8275,20 @@ var ClaudeUsageFactsCapturer = class {
7925
8275
  sources;
7926
8276
  usage;
7927
8277
  now;
7928
- diagnosticSink;
7929
- nextRegistrationIndex = 0;
8278
+ registrations;
7930
8279
  nextSourceSlot = "main";
7931
8280
  nextSubagentIndex = 0;
8281
+ overflow = new ClaudeSubagentOverflowCheckpoint();
7932
8282
  constructor(options) {
7933
8283
  this.sources = new ClaudeOutboxStore(options.outbox_dir);
7934
8284
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
7935
8285
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
7936
- this.diagnosticSink = options.diagnostic_sink;
8286
+ this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
7937
8287
  }
7938
8288
  async captureNext() {
7939
8289
  const registrations = await this.sources.listTranscriptRegistrations();
7940
- let failed = false;
7941
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
7942
- failed = true;
7943
- }));
7944
- this.nextRegistrationIndex = result.nextIndex;
7945
- if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
7946
- return result.captured;
8290
+ this.overflow.prune(registrations);
8291
+ return await this.registrations.captureNext(registrations, (registration, onFailure) => this.captureRegistration(registration, onFailure));
7947
8292
  }
7948
8293
  async captureRegistration(registration, onFailure) {
7949
8294
  const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
@@ -7990,13 +8335,14 @@ var ClaudeUsageFactsCapturer = class {
7990
8335
  }
7991
8336
  async captureSubagent(registration, onFailure) {
7992
8337
  const names = await readSubagentNames(registration);
8338
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
7993
8339
  let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
7994
8340
  if (state === null) return false;
7995
8341
  state = await this.usage.recoverPending(state);
7996
8342
  if (state.quarantined_reason !== void 0) return false;
7997
8343
  if (await this.retireMissingSubagent(state, names)) return true;
7998
8344
  if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
7999
- return await this.recordExcessSubagentGap(state, names);
8345
+ return await this.recordExcessSubagentGap(registration, state, names);
8000
8346
  }
8001
8347
  async retireMissingSubagent(state, names) {
8002
8348
  const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
@@ -8007,14 +8353,14 @@ var ClaudeUsageFactsCapturer = class {
8007
8353
  }
8008
8354
  return false;
8009
8355
  }
8010
- async recordExcessSubagentGap(state, names) {
8011
- const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
8012
- if (excessCount <= 0) return false;
8356
+ async recordExcessSubagentGap(registration, state, names) {
8013
8357
  const mainCursor = state.cursors.main;
8014
8358
  if (mainCursor === void 0) return false;
8015
- const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
8016
- await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
8017
- return true;
8359
+ return await this.overflow.observe(registration, names, async () => {
8360
+ 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 };
8361
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
8362
+ return true;
8363
+ });
8018
8364
  }
8019
8365
  async captureListedSubagents(registration, names, state, onFailure) {
8020
8366
  const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
@@ -8295,11 +8641,11 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
8295
8641
  producer_id: "claude",
8296
8642
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
8297
8643
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
8298
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
8644
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createClaudeProducerWatcher(config.outbox_dir) }),
8299
8645
  drain: drainClaudeProducerOnce,
8300
- background: (config, signal) => {
8646
+ background: (config, signal, dependencies) => {
8301
8647
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
8302
- return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext() }, signal);
8648
+ return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext(), fetch: dependencies.fetch }, signal);
8303
8649
  }
8304
8650
  };
8305
8651
 
@@ -8528,6 +8874,13 @@ var CodexOutboxStore = class {
8528
8874
  await removeOwnerState(this.registrationPath(registration.host_source_ref, registration.host_session_ref), "registration");
8529
8875
  await removeOwnerState(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "cursor");
8530
8876
  }
8877
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
8878
+ const path = this.registrationPath(hostSourceRef, hostSessionRef);
8879
+ await this.prepare();
8880
+ const registration = await readOptionalJson2(path, validateRegistration2);
8881
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
8882
+ return registration;
8883
+ }
8531
8884
  async listTranscriptRegistrations() {
8532
8885
  await this.prepare();
8533
8886
  const registrations = [];
@@ -8554,16 +8907,16 @@ var CodexOutboxStore = class {
8554
8907
  }
8555
8908
  async findByAlias(sourceRef, sessionRef, alias) {
8556
8909
  if (!SAFE_REF5.test(sourceRef) || !SAFE_REF5.test(sessionRef) || !SAFE_REF5.test(alias)) return null;
8557
- const read = await this.list();
8558
- const envelope = findEnvelopeByAlias(read.entries, sourceRef, sessionRef, alias);
8910
+ const read2 = await this.list();
8911
+ const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
8559
8912
  if (envelope !== null) return envelopeMatch(envelope);
8560
8913
  await this.prepare();
8561
8914
  return null;
8562
8915
  }
8563
8916
  async hasPriorTurn(sourceRef, sessionRef) {
8564
8917
  if (!SAFE_REF5.test(sourceRef) || !SAFE_REF5.test(sessionRef)) return false;
8565
- const read = await this.list();
8566
- if (read.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
8918
+ const read2 = await this.list();
8919
+ if (read2.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
8567
8920
  return false;
8568
8921
  }
8569
8922
  entryPath(submissionRef2) {
@@ -8619,7 +8972,7 @@ async function writeAtomicJson(path, value) {
8619
8972
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
8620
8973
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
8621
8974
  try {
8622
- const handle = await open4(temp, "wx");
8975
+ const handle = await open4(temp, "wx", 384);
8623
8976
  try {
8624
8977
  await handle.writeFile(text, "utf8");
8625
8978
  await handle.sync();
@@ -8661,13 +9014,20 @@ async function readOptionalJson2(path, validate) {
8661
9014
  }
8662
9015
  async function ensureOwnerDirectory(path) {
8663
9016
  try {
8664
- await stat2(path);
9017
+ try {
9018
+ const stats2 = await stat2(path);
9019
+ if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
9020
+ return;
9021
+ } catch (error) {
9022
+ if (!isNotFound2(error)) throw error;
9023
+ }
9024
+ await mkdir6(path, { recursive: true, mode: 448 });
9025
+ const stats = await stat2(path);
9026
+ if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8665
9027
  } catch (error) {
8666
- if (!isNotFound2(error)) throw storageError("Codex owner state directory is unavailable.");
8667
- await mkdir6(path, { recursive: true });
9028
+ if (error instanceof CodexHostAdapterError) throw error;
9029
+ throw storageError("Codex owner state directory is unavailable.");
8668
9030
  }
8669
- const stats = await stat2(path);
8670
- if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8671
9031
  }
8672
9032
  async function readOwnerStateFile(path) {
8673
9033
  let handle;
@@ -9139,9 +9499,9 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
9139
9499
  const { size, device, inode } = await ownedCodexTranscriptFile(handle);
9140
9500
  const preflight = await this.preflight(registration, handle, size, device, inode);
9141
9501
  if (preflight.cursor === null) return preflight.result;
9502
+ if (preflight.checkpointPending) await this.commitCursor(registration, handle, preflight.cursor, 0, device, inode, preflight.cursor.last_ordinal, preflight.cursor.active_task, preflight.cursor.human_message_window ?? { messages: [], truncated: false });
9142
9503
  const complete = await this.readChunk(handle, preflight.cursor.offset, size);
9143
9504
  if (complete === "empty" || complete === "partial") {
9144
- if (preflight.projectionInitialized) await this.commitCursor(registration, handle, preflight.cursor, 0, device, inode, preflight.cursor.last_ordinal, preflight.cursor.active_task, preflight.cursor.human_message_window ?? { messages: [], truncated: false });
9145
9505
  return { records: 0, enqueued: 0, quarantined: false };
9146
9506
  }
9147
9507
  return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
@@ -9158,17 +9518,17 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
9158
9518
  const existing = await this.store.readTranscriptCursor(registration);
9159
9519
  let cursor = existing ?? codexTranscriptInitialCursor(registration, device, inode, this.now);
9160
9520
  if (cursor.status === "quarantined") {
9161
- return { cursor: null, projectionInitialized: false, result: { records: 0, enqueued: 0, quarantined: true } };
9521
+ return { cursor: null, checkpointPending: false, result: { records: 0, enqueued: 0, quarantined: true } };
9162
9522
  }
9163
9523
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
9164
9524
  if (reason === null) {
9165
- if (cursor.human_message_window !== void 0) return { cursor, projectionInitialized: false, result: { records: 0, enqueued: 0, quarantined: false } };
9525
+ if (cursor.human_message_window !== void 0) return { cursor, checkpointPending: existing === null, result: { records: 0, enqueued: 0, quarantined: false } };
9166
9526
  const humanWindow = await this.readHumanMessageProjection(handle, registration, cursor);
9167
- return { cursor: { ...cursor, human_message_window: humanWindow }, projectionInitialized: existing !== null, result: { records: 0, enqueued: 0, quarantined: false } };
9527
+ return { cursor: { ...cursor, human_message_window: humanWindow }, checkpointPending: true, result: { records: 0, enqueued: 0, quarantined: false } };
9168
9528
  }
9169
9529
  await this.quarantine(registration, cursor, device, inode, reason);
9170
9530
  this.diagnostic("watcher_scan_failed", "other", `cursor_${reason}`);
9171
- return { cursor: null, projectionInitialized: false, result: { records: 0, enqueued: 0, quarantined: true } };
9531
+ return { cursor: null, checkpointPending: false, result: { records: 0, enqueued: 0, quarantined: true } };
9172
9532
  }
9173
9533
  async readHumanMessageProjection(handle, registration, cursor) {
9174
9534
  return readCodexHumanMessageProjection(registration, cursor, (offset, size) => this.readChunk(handle, offset, size));
@@ -9481,20 +9841,16 @@ var CodexUsageFactsCapturer = class {
9481
9841
  sources;
9482
9842
  usage;
9483
9843
  now;
9484
- diagnosticSink;
9485
- nextRegistrationIndex = 0;
9844
+ registrations;
9486
9845
  constructor(options) {
9487
9846
  this.sources = new CodexOutboxStore(options.outbox_dir);
9488
9847
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
9489
9848
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
9490
- this.diagnosticSink = options.diagnostic_sink;
9849
+ this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
9491
9850
  }
9492
9851
  async captureNext() {
9493
9852
  const registrations = await this.sources.listTranscriptRegistrations();
9494
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
9495
- this.nextRegistrationIndex = result.nextIndex;
9496
- if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
9497
- return result.captured;
9853
+ return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
9498
9854
  }
9499
9855
  async captureRegistration(registration) {
9500
9856
  const prepared = await openHostUsageTranscriptCursor({
@@ -9662,12 +10018,11 @@ function normalizedCounts(selected) {
9662
10018
  function nullCounts() {
9663
10019
  return { input: null, output: null, total: null, cached_input: null, cache_write_input: null, reasoning_output: null };
9664
10020
  }
9665
- var USAGE_COUNT_FIELDS = ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
9666
10021
  function isRegression(current, previous) {
9667
- return USAGE_COUNT_FIELDS.some((key) => current[key] < previous[key]);
10022
+ return CEAL_CODEX_USAGE_COUNT_FIELDS.some((key) => current[key] < previous[key]);
9668
10023
  }
9669
10024
  function sameCounts(left, right) {
9670
- return USAGE_COUNT_FIELDS.every((key) => left[key] === right[key]);
10025
+ return CEAL_CODEX_USAGE_COUNT_FIELDS.every((key) => left[key] === right[key]);
9671
10026
  }
9672
10027
  function buildCoverageGaps(sourceFileRef2, startOffset, endOffset, counts) {
9673
10028
  return [...counts].map(([reason, omittedCount]) => coverageGap(reason, sourceFileRef2, startOffset, endOffset, omittedCount));
@@ -9716,9 +10071,9 @@ var CODEX_PRODUCER_DESCRIPTOR = {
9716
10071
  config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
9717
10072
  runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
9718
10073
  drain: drainCodexProducerOnce,
9719
- background: (config, signal) => {
10074
+ background: (config, signal, dependencies) => {
9720
10075
  const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });
9721
- return runHostUsageFactsUploader({ producer: "codex", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext() }, signal);
10076
+ return runHostUsageFactsUploader({ producer: "codex", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext(), fetch: dependencies.fetch }, signal);
9722
10077
  }
9723
10078
  };
9724
10079
 
@@ -9948,6 +10303,7 @@ var HOST_BUNDLE_COMPONENTS = Object.freeze(["lifecycle", "relay", "codex", "clau
9948
10303
  var HOST_BUNDLE_PRODUCERS = Object.freeze(["codex", "claude"]);
9949
10304
  var HOST_RUNTIME_COMPONENTS = Object.freeze(["relay", "codex", "claude"]);
9950
10305
  var HOST_BUNDLE_PRIVATE_RUNTIME_ROOT = "libexec/ceal-host";
10306
+ var HOST_WINDOWS_BACKGROUND_RELATIVE_PATH = `${HOST_BUNDLE_PRIVATE_RUNTIME_ROOT}/ceal-host-background.exe`;
9951
10307
  var HOST_BUNDLE_FILE_KEYS = Object.freeze(["executable", "owners", "path", "sha256"]);
9952
10308
  var HOST_BUNDLE_SUPPORTED_REQUIRED_FEATURES = Object.freeze([]);
9953
10309
  var HOST_BUNDLE_REFERENCE_STATUS = Object.freeze({ authority: "non_authoritative", transaction: "incomplete" });
@@ -10280,7 +10636,7 @@ function boundedDiagnosticLines(lines) {
10280
10636
  let totalBytes = 0;
10281
10637
  for (const line of lines.slice(0, HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_LINES)) {
10282
10638
  const safe = normalizeDiagnosticLine(line);
10283
- const value = truncateUtf8(safe, HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_LINE_BYTES);
10639
+ const value = truncateUtf82(safe, HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_LINE_BYTES);
10284
10640
  const bytes = Buffer2.byteLength(value, "utf8") + (bounded.length === 0 ? 0 : 1);
10285
10641
  if (totalBytes + bytes > HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_BYTES) break;
10286
10642
  bounded.push(value);
@@ -10290,16 +10646,13 @@ function boundedDiagnosticLines(lines) {
10290
10646
  }
10291
10647
  function normalizeDiagnosticLine(line) {
10292
10648
  let normalized = "";
10293
- for (const character of redactDiagnosticSecrets(line)) {
10649
+ for (const character of redactOperatorDiagnosticSecrets(line)) {
10294
10650
  const point = character.codePointAt(0) ?? 0;
10295
10651
  normalized += point <= 31 || point === 127 ? " " : character;
10296
10652
  }
10297
10653
  return normalized.replace(/\s+/gu, " ").trim();
10298
10654
  }
10299
- function redactDiagnosticSecrets(value) {
10300
- 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*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
10301
- }
10302
- function truncateUtf8(value, maxBytes) {
10655
+ function truncateUtf82(value, maxBytes) {
10303
10656
  if (Buffer2.byteLength(value, "utf8") <= maxBytes) return value;
10304
10657
  let output = "";
10305
10658
  let bytes = 0;
@@ -10381,7 +10734,7 @@ function formatWindowsPowerShellCmdScriptCommand(launcherPath2, args, environmen
10381
10734
  const commandProcessor = windowsSystemCommandProcessor(environment);
10382
10735
  validateWindowsCmdScriptVector(commandProcessor, [], "cmd");
10383
10736
  const command = `${quoteWindowsArgument(launcherPath2)} ${args.map(quoteWindowsArgument).join(" ")}`.trimEnd();
10384
- const invocation = ["&", commandProcessor, "/d", "/v:off", "/s", "/c", `"${command}"`].map((value, index) => index === 0 ? value : quotePowerShellLiteral(value)).join(" ");
10737
+ const invocation = ["&", commandProcessor, "/d", "/v:off", "/s", "/c", command].map((value, index) => index === 0 ? value : quotePowerShellLiteral(value)).join(" ");
10385
10738
  return boundedHostCommand(`$LASTEXITCODE = 1; ${invocation}; exit $LASTEXITCODE`);
10386
10739
  }
10387
10740
  function validateWindowsCmdScriptVector(launcherPath2, args, consumer) {
@@ -10456,7 +10809,7 @@ function hostEntryCommand({ entryRoot, module: module2, configFlag, configFile,
10456
10809
  }
10457
10810
  async function installHostEntryLinks(entryRoot, targets, platform = process.platform, custody = {}, renameRetry = {}) {
10458
10811
  assertAbsolute(entryRoot, targets);
10459
- assertWindowsBatchTargetsAscii(targets, platform);
10812
+ assertWindowsEntryPaths(entryRoot, targets, platform);
10460
10813
  await assertEntryRootProven(entryRoot, platform, custody);
10461
10814
  await Promise.all([assertCanonicalDirectory(targets.runtime, "runtime"), assertCanonicalDirectory(targets.services, "services")]);
10462
10815
  if (platform === "win32") await assertLegacyLinkOrAbsent(join10(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
@@ -10464,9 +10817,14 @@ async function installHostEntryLinks(entryRoot, targets, platform = process.plat
10464
10817
  await preparePrivateEntryRoot(entryRoot);
10465
10818
  return reconcileEntryLaunchers(entryRoot, targets, platform, custody, renameRetry);
10466
10819
  }
10467
- function assertWindowsBatchTargetsAscii(targets, platform) {
10820
+ function assertWindowsEntryPaths(entryRoot, targets, platform) {
10468
10821
  if (platform !== "win32") return;
10469
10822
  if (hasNonAsciiCharacter(targets.runtime) || hasNonAsciiCharacter(targets.services)) throw new HostEntryLinkError("entry_target_invalid", "Windows Host launcher targets must use ASCII paths.", ["target_non_ascii"]);
10823
+ try {
10824
+ validateHostCommandVector({ executable: launcherPath(entryRoot, platform), args: [] });
10825
+ } catch {
10826
+ throw new HostEntryLinkError("entry_target_invalid", "Windows Host entry path cannot be serialized safely as a hook command.", ["entry_command_invalid"]);
10827
+ }
10470
10828
  }
10471
10829
  function hasNonAsciiCharacter(value) {
10472
10830
  for (const character of value) if (character.charCodeAt(0) > 127) return true;
@@ -10588,26 +10946,31 @@ function renderLauncher(targets, platform) {
10588
10946
  "setlocal DisableDelayedExpansion",
10589
10947
  `set "CEAL_RUNTIME=${batchLiteral(targets.runtime)}"`,
10590
10948
  `set "CEAL_SERVICES=${batchLiteral(targets.services)}"`,
10591
- 'if "%~1"=="" exit /b 64',
10592
- 'if not "%~1"=="%~nx1" exit /b 64',
10949
+ 'if "%~1"=="" goto ceal_refuse_arguments',
10950
+ 'if not "%~1"=="%~nx1" goto ceal_refuse_arguments',
10593
10951
  'set "CEAL_MODULE=%~1"',
10952
+ 'if "%~2"=="" goto ceal_refuse_arguments',
10953
+ 'set "CEAL_FLAG="',
10954
+ 'set "CEAL_CONFIG="',
10594
10955
  'for /f "tokens=1,* delims==" %%A in ("%~2") do (',
10595
10956
  ' set "CEAL_FLAG=%%A"',
10596
10957
  ' set "CEAL_CONFIG=%%B"',
10597
10958
  ")",
10598
- 'if /i not "%CEAL_FLAG%"=="--ceal-host-config" exit /b 64',
10599
- 'if "%CEAL_CONFIG%"=="" exit /b 64',
10600
- 'for %%A in ("%CEAL_CONFIG%") do if not "%%~nxA"=="%CEAL_CONFIG%" exit /b 64',
10959
+ 'if /i not "%CEAL_FLAG%"=="--ceal-host-config" goto ceal_refuse_arguments',
10960
+ 'if "%CEAL_CONFIG%"=="" goto ceal_refuse_arguments',
10961
+ 'for %%A in ("%CEAL_CONFIG%") do if not "%%~nxA"=="%CEAL_CONFIG%" goto ceal_refuse_arguments',
10601
10962
  'set "CEAL_FORWARD="',
10602
10963
  ":ceal_forward_arguments",
10603
10964
  'if "%~3"=="" goto ceal_launch',
10604
10965
  'set "CEAL_ARGUMENT=%~3"',
10966
+ "if not defined SystemRoot goto ceal_refuse_validator",
10967
+ 'if not exist "%SystemRoot%\\System32\\findstr.exe" goto ceal_refuse_validator',
10605
10968
  "setlocal EnableDelayedExpansion",
10606
- `echo(!CEAL_ARGUMENT!|findstr /r /c:"${WINDOWS_FIXED_CMD_ARGUMENT_REFUSAL_PATTERN}" >nul`,
10607
- "if errorlevel 2 exit /b 64",
10608
- "if not errorlevel 1 exit /b 64",
10969
+ `echo(!CEAL_ARGUMENT!|"%SystemRoot%\\System32\\findstr.exe" /r /c:"${WINDOWS_FIXED_CMD_ARGUMENT_REFUSAL_PATTERN}" >nul 2>nul`,
10970
+ "if errorlevel 2 goto ceal_refuse_validator",
10971
+ "if not errorlevel 1 goto ceal_refuse_arguments",
10609
10972
  "endlocal",
10610
- 'if not "%CEAL_ARGUMENT:!=%"=="%CEAL_ARGUMENT%" exit /b 64',
10973
+ 'if not "%CEAL_ARGUMENT:!=%"=="%CEAL_ARGUMENT%" goto ceal_refuse_arguments',
10611
10974
  'call :ceal_append_argument "%~3"',
10612
10975
  "shift",
10613
10976
  "goto ceal_forward_arguments",
@@ -10617,6 +10980,12 @@ function renderLauncher(targets, platform) {
10617
10980
  ":ceal_launch",
10618
10981
  '"%CEAL_RUNTIME%\\node\\bin\\node.exe" "%CEAL_RUNTIME%\\%CEAL_MODULE%" "%CEAL_FLAG%=%CEAL_SERVICES%\\%CEAL_CONFIG%" %CEAL_FORWARD%',
10619
10982
  "exit /b %ERRORLEVEL%",
10983
+ ":ceal_refuse_arguments",
10984
+ "echo ceal_host_entry_launcher_refused:invalid_arguments 1>&2",
10985
+ "exit /b 64",
10986
+ ":ceal_refuse_validator",
10987
+ "echo ceal_host_entry_launcher_refused:validator_unavailable 1>&2",
10988
+ "exit /b 64",
10620
10989
  ""
10621
10990
  ].join("\r\n");
10622
10991
  }
@@ -10964,7 +11333,7 @@ function resolveClaudeConfigHome(environment, home) {
10964
11333
  // host/claude/src/claude-installer.ts
10965
11334
  var OWNER = "ceal-claude-host-observation-v1";
10966
11335
  var ACTIVE_CLAUDE_HOOK_EVENTS = new Set(CLAUDE_HOOK_EVENTS);
10967
- var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: "CLAUDE_CODE_ENTRYPOINT", value: "cli" });
11336
+ var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: CLAUDE_SESSION_ID_ENVIRONMENT, value: Object.freeze({ environment: CLAUDE_SESSION_ID_ENVIRONMENT }) });
10968
11337
  var CLAUDE_CLIENT_ALLOW_RULE = `Bash(${CEAL_SESSION_ENTRY_INVOCATION}:*)`;
10969
11338
  var PERMISSION_OWNERSHIP_SCHEMA = "ceal.claude_permission_ownership.v1";
10970
11339
  function resolveClaudeSettingsPath(claudeHome, environment = process.env) {
@@ -11043,7 +11412,7 @@ async function installClaudeLocalCapability(path, authenticationCommand, custody
11043
11412
  try {
11044
11413
  validateHostCommandVector(authenticationCommand);
11045
11414
  } catch (error) {
11046
- throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11415
+ throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11047
11416
  }
11048
11417
  await inspectExecutable(authenticationCommand.executable);
11049
11418
  const next = claudeLocalCapabilityDescriptor(authenticationCommand);
@@ -11079,7 +11448,7 @@ async function removeClaudeLocalCapability(path, authenticationCommand, custody
11079
11448
  validateHostCommandVector(authenticationCommand);
11080
11449
  descriptor2 = claudeLocalCapabilityDescriptor(authenticationCommand);
11081
11450
  } catch (error) {
11082
- throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11451
+ throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11083
11452
  }
11084
11453
  const result = await removeOwnedLocalCapability(path, descriptor2, custody);
11085
11454
  if (result === "unsafe" || result === "unavailable") throw new ClaudeHostError("storage", `Claude local capability descriptor ${result === "unsafe" ? "is unsafe" : "custody could not be proved"}.`);
@@ -11135,7 +11504,9 @@ function removeOwnedHooks(settings) {
11135
11504
  return Object.keys(nextHooks).length === 0 ? withoutKey(settings, "hooks") : { ...settings, hooks: nextHooks };
11136
11505
  }
11137
11506
  function managedEntry(command, event) {
11138
- return { hooks: [{ type: "command", command: formatHostCommand({ ...command, args: [...command.args, `--ceal-hook-owner=${OWNER}`, `--ceal-hook-event=${event}`] }, process.platform === "win32" ? "windows" : "posix"), timeout: HOST_HOOK_TIMEOUT_SECONDS }] };
11507
+ const args = [...command.args, `--ceal-hook-owner=${OWNER}`, `--ceal-hook-event=${event}`];
11508
+ if (process.platform === "win32" && command.executable.toLowerCase().endsWith(".cmd")) return { hooks: [{ type: "command", command: formatWindowsPowerShellCmdScriptCommand(command.executable, args), shell: "powershell" }] };
11509
+ return { hooks: [{ type: "command", command: formatHostCommand({ ...command, args }, process.platform === "win32" ? "windows" : "posix") }] };
11139
11510
  }
11140
11511
  function ownedEntries(settings, event, command) {
11141
11512
  return eventEntries(hooksRecord(settings), event).filter((entry) => JSON.stringify(entry) === JSON.stringify(managedEntry(command, event)));
@@ -11213,9 +11584,11 @@ function validateOptions(options) {
11213
11584
  const settingsPath = options.settings_path ?? resolveClaudeSettingsPath(options.claude_home);
11214
11585
  if (!isAbsolute7(settingsPath) || !isAbsolute7(options.permission_ownership_path) || !isAbsolute7(options.hook_executable) || options.hook_executable.includes("\0") || options.hook_executable.includes("\n") || options.hook_executable.includes('"')) throw new ClaudeHostError("configuration", "Claude installer paths must be absolute and shell-safe.");
11215
11586
  try {
11216
- validateHostCommandVector(resolveHookCommand(options));
11587
+ const command = resolveHookCommand(options);
11588
+ validateHostCommandVector(command);
11589
+ managedEntry(command, "SessionStart");
11217
11590
  } catch (error) {
11218
- throw new ClaudeHostError("configuration", `Claude hook command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11591
+ throw new ClaudeHostError("configuration", `Claude hook command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11219
11592
  }
11220
11593
  return { ...options, settings_path: settingsPath };
11221
11594
  }
@@ -11434,7 +11807,7 @@ function validateInstallerOptions(options) {
11434
11807
  try {
11435
11808
  validateHostCommandVector(resolveHookCommand2(options));
11436
11809
  } catch (error) {
11437
- throw new CodexHostAdapterError("configuration", `Codex hook command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11810
+ throw new CodexHostAdapterError("configuration", `Codex hook command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11438
11811
  }
11439
11812
  if (options.feature_enabled === false) throw new CodexHostAdapterError("unsupported", `Codex ${CODEX_HOOK_FEATURE} feature is disabled.`);
11440
11813
  return { ...options, config_path: configPath };
@@ -11457,7 +11830,7 @@ async function validateAuthenticationCommand(command) {
11457
11830
  try {
11458
11831
  validateHostCommandVector(command);
11459
11832
  } catch (error) {
11460
- throw configurationError(`Codex invocation authentication command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11833
+ throw configurationError(`Codex invocation authentication command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11461
11834
  }
11462
11835
  try {
11463
11836
  const stats = await lstat9(command.executable);
@@ -11658,7 +12031,7 @@ function normalizeHookGroups(entries) {
11658
12031
  return groups;
11659
12032
  }
11660
12033
  function ownedHookEntry(command, event) {
11661
- return { type: "command", command: hookCommand(command, event, "posix"), commandWindows: hookCommand(command, event, "windows"), timeout: HOST_HOOK_TIMEOUT_SECONDS, async: false };
12034
+ return { type: "command", command: hookCommand(command, event, "posix"), commandWindows: hookCommand(command, event, "windows"), async: false };
11662
12035
  }
11663
12036
  function mergeOwnedHooks2(config, command) {
11664
12037
  const hooks = isRecord10(config.hooks) ? { ...config.hooks } : {};
@@ -12039,7 +12412,7 @@ async function requireHostRuntimeManagerPreflight(options) {
12039
12412
  async function requireCurrentAccountHome(options) {
12040
12413
  const environment = options.environment ?? process.env;
12041
12414
  const environmentName = options.platform === "win32" ? "USERPROFILE" : "HOME";
12042
- const configuredHome = environment[environmentName];
12415
+ const configuredHome = environmentValue(environment, environmentName, options.platform);
12043
12416
  let accountHome = options.account_home;
12044
12417
  if (accountHome === void 0) {
12045
12418
  try {
@@ -12168,7 +12541,7 @@ function assertCommand(command) {
12168
12541
  try {
12169
12542
  validateHostCommandVector(command, "direct-exec");
12170
12543
  } catch (error) {
12171
- throw new HostRuntimeServiceContractError("invalid_observation", `Host service command observation is invalid (${refusalFact("error", error)}).`);
12544
+ throw new HostRuntimeServiceContractError("invalid_observation", `Host service command observation is invalid (${renderOperatorDiagnostic(error)}).`);
12172
12545
  }
12173
12546
  }
12174
12547
  function absoluteNormalizedPath(value, label, path) {
@@ -12790,7 +13163,7 @@ function createWindowsHostRuntimeServiceAdapter(input) {
12790
13163
  schema_version: WINDOWS_SERVICE_REQUEST_SCHEMA,
12791
13164
  operation: "reconcile",
12792
13165
  prefix: target.prefix,
12793
- target_services: target.services.map((service) => wireService(service, logDirectory))
13166
+ target_services: target.services.map((service) => wireService(target.prefix, service, logDirectory))
12794
13167
  });
12795
13168
  },
12796
13169
  async restart({ target, service }) {
@@ -12805,7 +13178,7 @@ function createWindowsHostRuntimeServiceAdapter(input) {
12805
13178
  schema_version: WINDOWS_SERVICE_REQUEST_SCHEMA,
12806
13179
  operation: "restart",
12807
13180
  prefix: target.prefix,
12808
- service: wireService(service, logDirectory)
13181
+ service: wireService(target.prefix, service, logDirectory)
12809
13182
  });
12810
13183
  },
12811
13184
  async quiesce({ previous }) {
@@ -12815,7 +13188,7 @@ function createWindowsHostRuntimeServiceAdapter(input) {
12815
13188
  schema_version: WINDOWS_SERVICE_REQUEST_SCHEMA,
12816
13189
  operation: "quiesce",
12817
13190
  prefix: previous.prefix,
12818
- target_services: previous.services.map((service) => wireService(service, logDirectory))
13191
+ target_services: previous.services.map((service) => wireService(previous.prefix, service, logDirectory))
12819
13192
  });
12820
13193
  },
12821
13194
  async inspect({ target, timeout_ms }) {
@@ -12824,7 +13197,7 @@ function createWindowsHostRuntimeServiceAdapter(input) {
12824
13197
  schema_version: WINDOWS_SERVICE_REQUEST_SCHEMA,
12825
13198
  operation: "inspect",
12826
13199
  prefix: target.prefix,
12827
- target_services: target.services.map((service) => wireService(service, logDirectory))
13200
+ target_services: target.services.map((service) => wireService(target.prefix, service, logDirectory))
12828
13201
  }, timeout_ms);
12829
13202
  return parseObservations(result, target);
12830
13203
  },
@@ -12848,24 +13221,26 @@ function resolveWindowsPowerShell(windowsDirectory) {
12848
13221
  }
12849
13222
  return win3211.join(windowsDirectory, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
12850
13223
  }
12851
- function wireService(service, logDirectory) {
12852
- validateWindowsService(service);
13224
+ function wireService(prefix, service, logDirectory) {
13225
+ validateWindowsService(prefix, service);
12853
13226
  const argumentsWithLog = logDirectory === void 0 ? [...service.command.args] : [...service.command.args, HOST_SERVICE_LOG_ARGUMENT, hostServiceLogPath(win3211, logDirectory, service.component)];
12854
13227
  return {
12855
13228
  component: service.component,
12856
- executable: service.command.executable,
13229
+ executable: win3211.join(prefix, ...HOST_WINDOWS_BACKGROUND_RELATIVE_PATH.split("/")),
12857
13230
  // Task Scheduler ExecAction launches the executable directly, never
12858
13231
  // through cmd.exe, so `%` and `!` in user paths stay literal here.
12859
- arguments: argumentsWithLog.map(quoteWindowsExecArgument).join(" ")
13232
+ arguments: [service.command.executable, ...argumentsWithLog].map(quoteWindowsExecArgument).join(" ")
12860
13233
  };
12861
13234
  }
12862
- function validateWindowsService(service) {
13235
+ function validateWindowsService(prefix, service) {
12863
13236
  try {
12864
13237
  validateHostCommandVector(service.command, "direct-exec");
12865
13238
  } catch (error) {
12866
- throw invalidServiceSet(`Windows service command vectors must satisfy the Host command contract: ${refusalFact("error", error)}.`);
13239
+ throw invalidServiceSet(`Windows service command vectors must satisfy the Host command contract: ${renderOperatorDiagnostic(error)}.`);
12867
13240
  }
12868
13241
  if (!win3211.isAbsolute(service.command.executable) || win3211.normalize(service.command.executable) !== service.command.executable) throw invalidServiceSet("Windows service executables must be absolute normalized paths.");
13242
+ const expectedNode = win3211.join(prefix, ...HOST_BUNDLE_PRIVATE_RUNTIME_ROOT.split("/"), "node", "bin", "node.exe");
13243
+ if (service.command.executable.toLowerCase() !== expectedNode.toLowerCase()) throw invalidServiceSet("Windows services must use the installation's exact private Node executable.");
12869
13244
  }
12870
13245
  function assertWindowsServiceSets(previous, target) {
12871
13246
  assertWindowsServiceSet(previous);
@@ -12877,7 +13252,7 @@ function assertWindowsServiceSet(set) {
12877
13252
  if (new Set(set.services.map(({ component }) => component)).size !== set.services.length) throw invalidServiceSet("Windows service sets cannot contain duplicate components.");
12878
13253
  for (const service of set.services) {
12879
13254
  if (!HOST_RUNTIME_SERVICE_COMPONENTS.includes(service.component)) throw invalidServiceSet("Windows service sets contain an unsupported component.");
12880
- validateWindowsService(service);
13255
+ validateWindowsService(set.prefix, service);
12881
13256
  }
12882
13257
  }
12883
13258
  async function invoke(runner, powershell, request2, timeout_ms = HOST_RUNTIME_SERVICE_COMMAND_TIMEOUT_MS) {
@@ -13004,17 +13379,22 @@ function Find-WantedService([string]$component) {
13004
13379
  return $null
13005
13380
  }
13006
13381
 
13007
- function Stop-CealTaskIfRunning($task) {
13008
- if ([int]$task.State -ne 4) { return }
13382
+ function Test-CealTaskActive($task) {
13383
+ # TASK_STATE_QUEUED (2) still owns an instance that may start; READY (3) does not.
13384
+ return [int]$task.State -in 2,4
13385
+ }
13386
+
13387
+ function Stop-CealTaskIfActive($task) {
13388
+ if (-not (Test-CealTaskActive $task)) { return }
13009
13389
  try { $task.Stop(0) }
13010
- catch { if ([int]$task.State -eq 4) { throw } }
13390
+ catch { if (Test-CealTaskActive $task) { throw } }
13011
13391
  }
13012
13392
 
13013
13393
  function Stop-CealTaskAndWait($task, [string]$operation) {
13014
- Stop-CealTaskIfRunning $task
13394
+ Stop-CealTaskIfActive $task
13015
13395
  $stopDeadline = (Get-Date).AddMilliseconds(${WINDOWS_TASK_STOP_WAIT_MS})
13016
- while ([int]$task.State -eq 4 -and (Get-Date) -lt $stopDeadline) { Start-Sleep -Milliseconds ${WINDOWS_TASK_STATE_POLL_INTERVAL_MS} }
13017
- if ([int]$task.State -eq 4) { throw ('The Ceal Host task did not stop before ' + $operation + '.') }
13396
+ while ((Test-CealTaskActive $task) -and (Get-Date) -lt $stopDeadline) { Start-Sleep -Milliseconds ${WINDOWS_TASK_STATE_POLL_INTERVAL_MS} }
13397
+ if (Test-CealTaskActive $task) { throw ('The Ceal Host task did not stop before ' + $operation + '.') }
13018
13398
  }
13019
13399
 
13020
13400
  function Test-CealSid([string]$value) {
@@ -13078,7 +13458,7 @@ if ([string]$request.operation -ceq 'reconcile') {
13078
13458
  if ($null -ne $task) { Stop-CealTaskAndWait $task 'replacement' }
13079
13459
  $task = Register-CealTask $wanted
13080
13460
  }
13081
- if ($task.State -ne 4) { [void]$task.Run($null) }
13461
+ if (-not (Test-CealTaskActive $task)) { [void]$task.Run($null) }
13082
13462
  }
13083
13463
  @{ schema_version = 'ceal.host_windows_service_result.v1'; ok = $true } | ConvertTo-Json -Compress
13084
13464
  exit 0
@@ -13107,8 +13487,9 @@ if ([string]$request.operation -ceq 'inspect') {
13107
13487
  $wanted = Find-WantedService $component
13108
13488
  $task = Find-CealTask $component
13109
13489
  if ($null -eq $task) { [ordered]@{ component = $component; state = 'absent'; definition_matches = $false }; continue }
13110
- $state = switch ([int]$task.State) { 4 { 'running' } 1 { 'stopped' } 2 { 'stopped' } 3 { 'stopped' } default { 'unknown' } }
13111
- [ordered]@{ component = $component; state = $state; definition_matches = [bool](Test-CealDefinition $task $wanted); last_task_result = [long]$task.LastTaskResult; startup_pending = ([int]$task.State -eq 2) }
13490
+ $taskState = [int]$task.State
13491
+ $state = switch ($taskState) { 4 { 'running' } 1 { 'stopped' } 2 { 'stopped' } 3 { 'stopped' } default { 'unknown' } }
13492
+ [ordered]@{ component = $component; state = $state; definition_matches = [bool](Test-CealDefinition $task $wanted); last_task_result = [long]$task.LastTaskResult; startup_pending = ($taskState -eq 2) }
13112
13493
  }
13113
13494
  [ordered]@{ schema_version = 'ceal.host_windows_service_result.v1'; ok = $true; observations = @($observations) } | ConvertTo-Json -Compress -Depth 5
13114
13495
  exit 0
@@ -13549,7 +13930,7 @@ async function ownedUnitPresent(path, identity, component) {
13549
13930
  } catch (error) {
13550
13931
  if (hasCode(error, "ENOENT")) return false;
13551
13932
  if (isAdapterError(error)) throw error;
13552
- throw projectionError(refusalFact("error", error));
13933
+ throw projectionError(renderOperatorDiagnostic(error));
13553
13934
  }
13554
13935
  }
13555
13936
  async function replaceOwnedUnit(directory, identity, service) {
@@ -13568,7 +13949,7 @@ async function replaceOwnedUnit(directory, identity, service) {
13568
13949
  await syncDirectory3(directory);
13569
13950
  } catch (error) {
13570
13951
  await unlink10(temporary).catch(() => void 0);
13571
- throw projectionError(refusalFact("error", error));
13952
+ throw projectionError(renderOperatorDiagnostic(error));
13572
13953
  }
13573
13954
  }
13574
13955
  async function removeOwnedUnit(directory, identity, component) {
@@ -13715,10 +14096,12 @@ function createInstalledHostRuntimeControlDependencies(options = {}) {
13715
14096
  const environment = options.environment ?? process.env;
13716
14097
  const platform = options.platform ?? process.platform;
13717
14098
  const owner = new InstalledHostRuntimeConfigurationOwner(resolveStateRoot(environment, platform), platform, options.custody ?? {});
14099
+ const codexHome = environmentValue(environment, "CODEX_HOME", platform);
14100
+ const claudeHome = environmentValue(environment, "CLAUDE_CONFIG_DIR", platform);
13718
14101
  const hooks = options.hooks ?? new InstalledHostRuntimeHookAdapter({
13719
- user_home: (platform === "win32" ? environment.USERPROFILE : environment.HOME) ?? homedir5(),
13720
- ...environment.CODEX_HOME === void 0 ? {} : { codex_home: environment.CODEX_HOME },
13721
- ...environment.CLAUDE_CONFIG_DIR === void 0 ? {} : { claude_home: environment.CLAUDE_CONFIG_DIR },
14102
+ user_home: environmentValue(environment, platform === "win32" ? "USERPROFILE" : "HOME", platform) ?? homedir5(),
14103
+ ...codexHome === void 0 ? {} : { codex_home: codexHome },
14104
+ ...claudeHome === void 0 ? {} : { claude_home: claudeHome },
13722
14105
  state_root: owner.stateRoot,
13723
14106
  custody: options.custody,
13724
14107
  config_paths: { codex: owner.configPaths.codex, claude: owner.configPaths.claude }
@@ -13961,7 +14344,7 @@ function processFailure(error) {
13961
14344
  return { exit_code: code2, stdout, stderr, ...timedOut ? { timed_out: true } : {} };
13962
14345
  }
13963
14346
  function resolveStateRoot(environment, platform) {
13964
- const value = environment[STATE_ROOT_ENVIRONMENT];
14347
+ const value = environmentValue(environment, STATE_ROOT_ENVIRONMENT, platform);
13965
14348
  const path = platform === "win32" ? win3212 : posix11;
13966
14349
  if (value === void 0 || value.length === 0 || value.length > HOST_STATE_ROOT_MAX_CHARACTERS || value.includes("\0") || !path.isAbsolute(value) || path.normalize(value) !== value || path.parse(value).root === value) throw new InstalledHostRuntimeCompositionError("state_root_unavailable", `The Go-owned Host state root is unavailable (${refusalFact("state_root", value, `a normalized absolute non-root path of at most ${HOST_STATE_ROOT_MAX_CHARACTERS} characters`)}).`);
13967
14350
  return value;