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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,7 @@ const require = __cealCreateRequire(import.meta.url);
4
4
 
5
5
  // host/claude/src/claude-types.ts
6
6
  var CLAUDE_HOOK_EVENTS = ["SessionStart", "UserPromptSubmit"];
7
+ var CLAUDE_SESSION_ID_ENVIRONMENT = "CLAUDE_CODE_SESSION_ID";
7
8
  var CLAUDE_HOST_ERROR_CODES = ["invalid_input", "payload_rejected", "storage", "configuration"];
8
9
  function isClaudeHostErrorCode(value) {
9
10
  return typeof value === "string" && CLAUDE_HOST_ERROR_CODES.some((code2) => code2 === value);
@@ -36,6 +37,15 @@ function isClaudeHookEvent(value) {
36
37
  import { createHash as createHash4 } from "node:crypto";
37
38
  import { isAbsolute } from "node:path";
38
39
 
40
+ // packages/ceal-client-protocol/src/vocabulary.ts
41
+ function vocabulary(words) {
42
+ return Object.freeze(words);
43
+ }
44
+
45
+ // packages/ceal-client-protocol/src/host-usage-fields.ts
46
+ var CEAL_CODEX_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
47
+ var CEAL_CLAUDE_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"]);
48
+
39
49
  // packages/ceal-client-protocol/src/canonical-json.ts
40
50
  function cealCanonicalJson(value) {
41
51
  if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
@@ -210,8 +220,11 @@ var client_wire_contract_default = {
210
220
  "ok",
211
221
  "code",
212
222
  "reason",
213
- "gateway_status"
223
+ "gateway_status",
224
+ "retry_after_ms"
214
225
  ],
226
+ refusal_required_fields: ["schema_version", "ok", "code", "reason"],
227
+ refusal_optional_fields: ["gateway_status", "retry_after_ms"],
215
228
  client_nonce: {
216
229
  character_class_source: "A-Za-z0-9_-",
217
230
  encoded_characters: 43
@@ -430,11 +443,6 @@ var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
430
443
  personal_authorization_required: "connect_personal_account"
431
444
  });
432
445
 
433
- // packages/ceal-client-protocol/src/vocabulary.ts
434
- function vocabulary(words) {
435
- return Object.freeze(words);
436
- }
437
-
438
446
  // packages/ceal-client-protocol/src/gateway-response-types.ts
439
447
  var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
440
448
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
@@ -833,7 +841,7 @@ var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask a
833
841
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
834
842
  var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
835
843
  var HOST_INSTALL_REPAIR = "The local Host or Relay is missing, stale, or unavailable. Run `ceal-host install`, then `ceal-host discovery sync`, and retry from a new producer conversation.";
836
- var HOST_CONTEXT_UNAVAILABLE = "The Host could not select or activate the current recorded turn. This does not explain why or prove ephemerality. For an independently identified ephemeral Codex side conversation, invoke the command as `ceal --standalone ...`; it uses the local Ceal session and Gateway permissions without Host session/turn audit linkage. Host refusal never switches modes. For intended Host calls, restart the producer and start a new conversation; report the error if it persists.";
844
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
837
845
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
838
846
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
839
847
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
@@ -885,14 +893,12 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
885
893
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
886
894
  internal_error: guidance("The Gateway failed without exposing internal state.", "answer_with_gap", 500),
887
895
  // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
888
- // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
896
+ // the static client variant was retired when the client started reading this table.
889
897
  request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
890
898
  gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
891
- // Restored verbatim from the retired `localFailureText` `unknown_outcome`
892
- // case: the outcome is unknown, so a read may be retried while a write
893
- // must receipt-check first. Collapsing both to "do not repeat the call"
894
- // forbids the safe read retry the sentence exists to allow.
895
- unknown_outcome: guidance("The transport outcome is unknown: a read may be retried; for a write, check write_receipt.get before repeating.", "answer_with_gap", 500),
899
+ // The safe move varies by request. Keep the sentence conditional on the
900
+ // same `retryable` and `next_action` facts the response exposes.
901
+ unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
896
902
  // Restored verbatim from the retired `localFailureText`
897
903
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
898
904
  // session context unavailable, so the caller repairs or adopts the
@@ -973,8 +979,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
973
979
  // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
974
980
  // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
975
981
  // is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
976
- // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). Cause-specific
977
- // sentences carry the retired policy remedies; `gateway_refused` reuses the release-upgrade guidance above.
982
+ // and `retryable` from `hostAuthenticationFailureForCause` (the table's explicit retry verdict). Cause-specific
983
+ // sentences carry only remedies proved by the Host or Relay cause; generic Gateway refusals do not prove a release mismatch.
978
984
  // Statuses are the
979
985
  // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
980
986
  // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
@@ -984,21 +990,23 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
984
990
  // The bounded Host reason does not prove ephemerality. A Host refusal never
985
991
  // changes mode; standalone remains the separate Client authority path.
986
992
  host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
987
- host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
988
- host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
993
+ 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),
994
+ 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),
995
+ host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
989
996
  host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
990
997
  host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
991
998
  host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
992
999
  host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
993
- host_mint_gateway_refused: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
1000
+ host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
994
1001
  host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
1002
+ host_contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
995
1003
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
996
1004
  // producer-frame fault names the administrator repair step.
997
1005
  host_producer_frame_invalid: guidance("Ask an administrator to inspect and repair the producer frame, then start a fresh Host turn.", "ask_admin", 400),
998
1006
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
999
1007
  // sandboxed Relay socket names the run-alone retry.
1000
1008
  host_relay_permission_denied: guidance("An agent sandbox denied the Host Relay socket; run `ceal` as the only command, with no pipe, redirect, or `&&`, so the Host allow rule runs it outside the sandbox.", "rerun_outside_agent_sandbox", 403),
1001
- host_relay_unavailable: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 503),
1009
+ host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1002
1010
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
1003
1011
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
1004
1012
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1036,7 +1044,7 @@ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
1036
1044
  var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
1037
1045
  var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
1038
1046
  var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
1039
- var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
1047
+ var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_applicable", "not_offered", "offered", "accepted", "rejected", "unknown"]);
1040
1048
  var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
1041
1049
  var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
1042
1050
  var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
@@ -1207,6 +1215,7 @@ var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
1207
1215
  // packages/ceal-client-protocol/src/domain-vocabulary.ts
1208
1216
  var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
1209
1217
  var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
1218
+ var CEAL_PROVIDER_BOUNDARY_FIELDS = vocabulary(["provider_boundary_ref", "provider_boundary_kind", "provider_boundary_label", "provider_native_id", "provider_boundary_evidence"]);
1210
1219
  var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
1211
1220
  var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
1212
1221
  var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
@@ -1252,7 +1261,7 @@ var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1252
1261
  var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
1253
1262
  var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
1254
1263
  var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
1255
- var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
1264
+ var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary", "standard_names"]);
1256
1265
 
1257
1266
  // packages/ceal-client-protocol/src/operation-catalog.ts
1258
1267
  var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
@@ -1348,6 +1357,7 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
1348
1357
  gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
1349
1358
  gateway_access_group_connector_calendar_scope_audit: (root) => join(root, "profile-connector-calendar-scope-audit.jsonl"),
1350
1359
  gateway_access_group_connector_readiness_audit: (root) => join(root, "profile-connector-readiness.audit.jsonl"),
1360
+ gateway_deployment_events: (root) => join(root, "gateway-deployments.jsonl"),
1351
1361
  gateway_organization_audit_ledger: (root) => join(root, "organization-ledger.jsonl"),
1352
1362
  gateway_personal_client_audit: (root) => join(root, "audit.jsonl"),
1353
1363
  gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
@@ -1374,6 +1384,11 @@ var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_L
1374
1384
  var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
1375
1385
  var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
1376
1386
 
1387
+ // packages/ceal-client-protocol/src/resource-read-result.ts
1388
+ var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
1389
+ var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
1390
+ var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1391
+
1377
1392
  // packages/ceal-client-protocol/src/operation-result-completeness.ts
1378
1393
  var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
1379
1394
 
@@ -1458,6 +1473,7 @@ var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
1458
1473
  { provider: "google-workspace", result_kind: "calendar_event_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "htmlLink", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
1459
1474
  { provider: "google-workspace", result_kind: "drive_document_calendar_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink or htmlLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
1460
1475
  { 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" },
1476
+ { provider: "google-workspace", result_kind: "form_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified Forms responderUri", source: "https://developers.google.com/workspace/forms/api/reference/rest/v1/forms" },
1461
1477
  { provider: "google-workspace", result_kind: "spreadsheet_write_result", field: "spreadsheet_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
1462
1478
  { provider: "google-workspace", result_kind: "calendar_meet_link_write_result", field: "meet_url", status: "required_when_provider_supplies", provider_shape: "verified conferenceData entryPoint uri", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
1463
1479
  { 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" },
@@ -1627,6 +1643,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1627
1643
  created_at: { required: false, timestamp: true },
1628
1644
  created_at_local: { required: false, timestamp: true },
1629
1645
  modified_at: { required: false, timestamp: true },
1646
+ observed_at: { required: false, timestamp: true },
1630
1647
  modified_at_local: { required: false, timestamp: true },
1631
1648
  viewed_by_me_at: { required: false, timestamp: true },
1632
1649
  modified_by_me_at: { required: false, timestamp: true },
@@ -1654,9 +1671,6 @@ var RESOURCE_ROW_REQUIRED_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(
1654
1671
  var RESOURCE_ROW_KEYS = new Set(Object.keys(RESOURCE_ROW_KEY_RULES));
1655
1672
  var RESOURCE_ROW_TIMESTAMP_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(([key, rule]) => rule.timestamp ? [key] : []);
1656
1673
 
1657
- // packages/ceal-client-protocol/src/resource-read-result.ts
1658
- var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
1659
-
1660
1674
  // packages/ceal-client-protocol/src/excluded-target-coverage.ts
1661
1675
  var CEAL_EXCLUDED_TARGET_COVERAGE_MAX_ENTRIES = 64;
1662
1676
  function cealExcludedTargetCoverageJsonSchema() {
@@ -1963,7 +1977,7 @@ function validateBatchContents(value) {
1963
1977
  if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
1964
1978
  const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
1965
1979
  for (const fact of facts) {
1966
- validateFact(fact, value.host_session_ref);
1980
+ validateCealHostUsageFact(fact, value.host_session_ref);
1967
1981
  if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
1968
1982
  }
1969
1983
  for (const gap of gaps) {
@@ -1996,7 +2010,7 @@ function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, d
1996
2010
  for (const part of [producer, hostSourceRef, hostSessionRef, device, inode]) if (typeof part !== "string" || part.length === 0 || part.length > 512) invalid("Ceal Host usage file identity is invalid.");
1997
2011
  return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
1998
2012
  }
1999
- function validateFact(value, sessionRef) {
2013
+ function validateCealHostUsageFact(value, sessionRef) {
2000
2014
  if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
2001
2015
  requireFactByteLimit(value);
2002
2016
  if (value.producer === "codex_transcript") validateCodexFact(value);
@@ -2060,7 +2074,7 @@ function validCorrectionSemantics(value) {
2060
2074
  }
2061
2075
  function validateCodexUsageCounts(value) {
2062
2076
  if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
2063
- requireExactOperationKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
2077
+ requireExactOperationKeys(value, CEAL_CODEX_USAGE_COUNT_FIELDS);
2064
2078
  for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
2065
2079
  if (Number(value.total_tokens) !== Number(value.input_tokens) + Number(value.output_tokens) || Number(value.cached_input_tokens) + Number(value.cache_write_input_tokens) > Number(value.input_tokens) || Number(value.reasoning_output_tokens) > Number(value.output_tokens)) invalid("Ceal Codex usage fields are inconsistent.");
2066
2080
  }
@@ -2328,6 +2342,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
2328
2342
  "options_invalid",
2329
2343
  "session_unavailable",
2330
2344
  "context_unavailable",
2345
+ "activation_wait_exhausted",
2331
2346
  "context_replaced",
2332
2347
  "no_binding",
2333
2348
  "context_expired",
@@ -2363,22 +2378,23 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2363
2378
  // This reason cannot distinguish a Codex side conversation from a missing
2364
2379
  // context in a regular session, so guidance must leave that choice to the caller.
2365
2380
  context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2366
- context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
2381
+ activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2382
+ context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2367
2383
  // `no_binding` now means the producer has no real current Host session. The
2368
2384
  // Host Relay never uses it for an uncreated Gateway Request; there is no
2369
2385
  // useful retry until the consumer is running inside a Host session.
2370
2386
  no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2371
- context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
2387
+ context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
2372
2388
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
2373
2389
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
2374
2390
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
2375
2391
  gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
2376
- contract_mismatch: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2377
- gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "upgrade_ceal_client" }),
2392
+ contract_mismatch: Object.freeze({ classification: "host_contract_mismatch", next_action: "upgrade_ceal_client" }),
2393
+ gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
2378
2394
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2379
2395
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2380
2396
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2381
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
2397
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2382
2398
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2383
2399
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2384
2400
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2426,7 +2442,7 @@ function isCealHostServiceDiagnosticCause(value, event) {
2426
2442
  // packages/ceal-client-protocol/src/client-result-materialization.ts
2427
2443
  var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
2428
2444
  var REQUIRED_FIELDS2 = Object.freeze(["schema_version", "operation_id", "path", "sha256"]);
2429
- var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "items_path", "row_count", "result_complete", "coverage", "local_result_root", "model_disclosure", "continue_argv", "how_to_read"]);
2445
+ var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "local_result_root", "request_context_argv", "how_to_read"]);
2430
2446
 
2431
2447
  // packages/ceal-client-protocol/src/session-start-affordance.ts
2432
2448
  var CEAL_SESSION_ENTRY_INVOCATION = "ceal";
@@ -2848,7 +2864,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2848
2864
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2849
2865
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2850
2866
  return await new Promise((resolve2, reject) => {
2851
- const child = execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2867
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2852
2868
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2853
2869
  if (exitCode === null) {
2854
2870
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2899,6 +2915,192 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
2899
2915
  return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
2900
2916
  }
2901
2917
 
2918
+ // host/service-log.ts
2919
+ import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
2920
+ import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win322 } from "node:path";
2921
+
2922
+ // host/service-log-delivery.ts
2923
+ var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
2924
+ function createHostServiceLogDelivery(stream, schedule = (flush) => {
2925
+ setImmediate(flush);
2926
+ }, onDeliveryGap = () => void 0) {
2927
+ const pending = [];
2928
+ const highWaterMark = stream.writableHighWaterMark;
2929
+ const byteBudget = highWaterMark + highWaterMark;
2930
+ let pendingBytes = 0;
2931
+ let droppedLines = 0;
2932
+ let flushScheduled = false;
2933
+ let waitingForDrain = false;
2934
+ let closed = !stream.writable;
2935
+ function stop() {
2936
+ if (closed) return;
2937
+ closed = true;
2938
+ pending.length = 0;
2939
+ pendingBytes = 0;
2940
+ stream.off("drain", onDrain);
2941
+ stream.off("close", onTerminal);
2942
+ stream.off("finish", onTerminal);
2943
+ stream.off("error", onError);
2944
+ }
2945
+ function onTerminal() {
2946
+ stop();
2947
+ }
2948
+ function onError() {
2949
+ stop();
2950
+ }
2951
+ function onDrain() {
2952
+ waitingForDrain = false;
2953
+ scheduleFlush();
2954
+ }
2955
+ function scheduleFlush() {
2956
+ if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
2957
+ flushScheduled = true;
2958
+ let scheduling = true;
2959
+ let invokedSynchronously = false;
2960
+ try {
2961
+ schedule(() => {
2962
+ if (scheduling) {
2963
+ invokedSynchronously = true;
2964
+ return;
2965
+ }
2966
+ flushScheduled = false;
2967
+ flush();
2968
+ });
2969
+ } catch {
2970
+ flushScheduled = false;
2971
+ stop();
2972
+ return;
2973
+ }
2974
+ scheduling = false;
2975
+ if (invokedSynchronously) {
2976
+ flushScheduled = false;
2977
+ stop();
2978
+ }
2979
+ }
2980
+ function flush() {
2981
+ if (closed) return;
2982
+ if (!stream.writable) {
2983
+ stop();
2984
+ return;
2985
+ }
2986
+ while (pending.length > 0) {
2987
+ if (stream.writableNeedDrain) {
2988
+ if (!waitingForDrain) {
2989
+ waitingForDrain = true;
2990
+ stream.once("drain", onDrain);
2991
+ }
2992
+ return;
2993
+ }
2994
+ const next = pending.shift();
2995
+ if (next === void 0) return;
2996
+ pendingBytes -= next.bytes;
2997
+ let accepted;
2998
+ try {
2999
+ accepted = stream.write(next.line);
3000
+ } catch {
3001
+ stop();
3002
+ return;
3003
+ }
3004
+ if (!accepted) {
3005
+ waitingForDrain = true;
3006
+ stream.once("drain", onDrain);
3007
+ return;
3008
+ }
3009
+ }
3010
+ if (droppedLines > 0) {
3011
+ const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
3012
+ `;
3013
+ droppedLines = 0;
3014
+ try {
3015
+ onDeliveryGap(line);
3016
+ } catch {
3017
+ }
3018
+ pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
3019
+ pendingBytes += Buffer.byteLength(line, "utf8");
3020
+ flush();
3021
+ }
3022
+ }
3023
+ stream.on("close", onTerminal);
3024
+ stream.on("finish", onTerminal);
3025
+ stream.on("error", onError);
3026
+ return (line) => {
3027
+ if (closed) return;
3028
+ const bytes = Buffer.byteLength(line, "utf8");
3029
+ if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
3030
+ droppedLines += 1;
3031
+ scheduleFlush();
3032
+ return;
3033
+ }
3034
+ pending.push({ line, bytes });
3035
+ pendingBytes += bytes;
3036
+ scheduleFlush();
3037
+ };
3038
+ }
3039
+
3040
+ // host/invocation-authentication-client-command.ts
3041
+ var DOCTOR_FLAGS = Object.freeze({
3042
+ "--expected-sha256": "expected_sha256",
3043
+ "--expected-source-commit": "expected_source_commit",
3044
+ "--expected-instance-ref": "expected_instance_ref"
3045
+ });
3046
+
3047
+ // host/service-log.ts
3048
+ var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
3049
+ var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
3050
+ void persistHostServiceLogLine(line);
3051
+ });
3052
+ function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
3053
+ const details = diagnosticDetails(event, failure_kind, cause);
3054
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
3055
+ `;
3056
+ try {
3057
+ (sink ?? defaultHostServiceDiagnosticSink)(line);
3058
+ } catch {
3059
+ }
3060
+ }
3061
+ function diagnosticDetails(event, failureKind, cause) {
3062
+ if (event === "watcher_scan_failed") return {
3063
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3064
+ ...validDiagnosticCause(cause, event) ? { cause } : {}
3065
+ };
3066
+ return validDiagnosticCause(cause, event) ? { cause } : {};
3067
+ }
3068
+ function validDiagnosticCause(cause, event) {
3069
+ return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
3070
+ }
3071
+ function defaultHostServiceDiagnosticSink(line) {
3072
+ writeHostServiceLogLine(line);
3073
+ }
3074
+ var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
3075
+ function writeHostServiceLogLine(line, environment = process.env) {
3076
+ void persistHostServiceLogLine(line, environment);
3077
+ defaultHostServiceLogDelivery(line);
3078
+ }
3079
+ async function persistHostServiceLogLine(line, environment = process.env) {
3080
+ if (process.platform !== "win32") return;
3081
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
3082
+ if (path === void 0 || !win322.isAbsolute(path) || win322.normalize(path) !== path) return;
3083
+ await appendHostServiceLogLine(path, line).catch(() => void 0);
3084
+ }
3085
+ async function appendHostServiceLogLine(path, line) {
3086
+ if (!isAbsolute2(path)) return;
3087
+ await ensureHostServiceLogDirectory(path);
3088
+ await appendFile(path, line);
3089
+ }
3090
+ var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
3091
+ var hostServiceLogDirectories = /* @__PURE__ */ new Map();
3092
+ function ensureHostServiceLogDirectory(path) {
3093
+ const directory = dirname2(path);
3094
+ const existing = hostServiceLogDirectories.get(directory);
3095
+ if (existing !== void 0) return existing;
3096
+ const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
3097
+ hostServiceLogDirectories.delete(directory);
3098
+ throw error;
3099
+ });
3100
+ hostServiceLogDirectories.set(directory, pending);
3101
+ return pending;
3102
+ }
3103
+
2902
3104
  // host/relay/src/host-producer-core.ts
2903
3105
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
2904
3106
  function isHostTranscriptCursorReason(value) {
@@ -3003,7 +3205,7 @@ function createTranscriptWatcherBase(options, owner) {
3003
3205
  outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
3004
3206
  now: options.now ?? (() => /* @__PURE__ */ new Date()),
3005
3207
  log: options.log ?? ((line) => {
3006
- process.stderr.write(`${line}
3208
+ writeHostServiceLogLine(`${line}
3007
3209
  `);
3008
3210
  }),
3009
3211
  producerInstallationRef: options.producer_installation_ref
@@ -3043,7 +3245,13 @@ var HostTranscriptWatcher = class {
3043
3245
  }
3044
3246
  async scanRegistration(registration) {
3045
3247
  return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
3046
- missing: () => this.retireMissing(registration),
3248
+ missing: async () => {
3249
+ try {
3250
+ return await this.retireMissing(registration);
3251
+ } catch (error) {
3252
+ return this.scanFailed(void 0, registration, error);
3253
+ }
3254
+ },
3047
3255
  failed: (handle, error) => this.scanFailed(handle, registration, error)
3048
3256
  });
3049
3257
  }
@@ -3126,8 +3334,8 @@ var HostProducerDrainCore = class {
3126
3334
  };
3127
3335
 
3128
3336
  // host/relay/src/durable-atomic-replacement.ts
3129
- import { lstat as lstat2, mkdir, open as open2, rename, unlink } from "node:fs/promises";
3130
- import { dirname as dirname2 } from "node:path";
3337
+ import { lstat as lstat2, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
3338
+ import { dirname as dirname3 } from "node:path";
3131
3339
 
3132
3340
  // host/windows-rename-retry.ts
3133
3341
  import { setTimeout as setTimeout2 } from "node:timers/promises";
@@ -3180,7 +3388,7 @@ function isRetryableRenameError(error) {
3180
3388
  // host/relay/src/durable-atomic-replacement.ts
3181
3389
  var DEFAULT_PORT = {
3182
3390
  platform: process.platform,
3183
- mkdir: (path, options) => mkdir(path, options),
3391
+ mkdir: (path, options) => mkdir2(path, options),
3184
3392
  lstat: (path) => lstat2(path),
3185
3393
  open_file: (path) => open2(path, "wx", 384),
3186
3394
  rename,
@@ -3189,7 +3397,7 @@ var DEFAULT_PORT = {
3189
3397
  unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
3190
3398
  };
3191
3399
  async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
3192
- const parent = dirname2(target);
3400
+ const parent = dirname3(target);
3193
3401
  await port.mkdir(parent, { recursive: true, mode: 448 });
3194
3402
  const parentStats = await port.lstat(parent);
3195
3403
  const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
@@ -3259,8 +3467,8 @@ function errorCode(error) {
3259
3467
  // host/relay/src/host-usage-facts-store.ts
3260
3468
  import { createHash as createHash6 } from "node:crypto";
3261
3469
  import { constants as constants2 } from "node:fs";
3262
- import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3263
- import { dirname as dirname3, join as join3 } from "node:path";
3470
+ import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3471
+ import { dirname as dirname4, join as join3 } from "node:path";
3264
3472
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3265
3473
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3266
3474
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -3509,7 +3717,7 @@ var HostUsageFactsStore = class {
3509
3717
  }
3510
3718
  async writeImmutableBatch(state, batch, bytes) {
3511
3719
  const path = this.batchPath(state, batch.batch_ref);
3512
- await preparePrivateDirectory(dirname3(path), this.platform, this.custody);
3720
+ await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
3513
3721
  const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
3514
3722
  if (existing !== null) {
3515
3723
  if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
@@ -3527,7 +3735,7 @@ var HostUsageFactsStore = class {
3527
3735
  await handle.sync();
3528
3736
  await handle.close();
3529
3737
  handle = void 0;
3530
- await syncDirectory(dirname3(path), this.platform);
3738
+ await syncDirectory(dirname4(path), this.platform);
3531
3739
  } catch (error) {
3532
3740
  await handle?.close().catch(() => void 0);
3533
3741
  if (errorCode2(error) === "EEXIST") {
@@ -3781,7 +3989,7 @@ async function preparePrivateDirectory(path, platform, custody) {
3781
3989
  await ensurePrivateDirectoryWithSecurefs(path, custody);
3782
3990
  return;
3783
3991
  }
3784
- await mkdir2(path, { recursive: true, mode: 448 });
3992
+ await mkdir3(path, { recursive: true, mode: 448 });
3785
3993
  if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
3786
3994
  }
3787
3995
  async function syncExistingFile(path, platform) {
@@ -3791,7 +3999,7 @@ async function syncExistingFile(path, platform) {
3791
3999
  } finally {
3792
4000
  await handle.close();
3793
4001
  }
3794
- await syncDirectory(dirname3(path), platform);
4002
+ await syncDirectory(dirname4(path), platform);
3795
4003
  }
3796
4004
  async function syncDirectory(path, platform) {
3797
4005
  if (platform === "win32") return;
@@ -3932,16 +4140,16 @@ function completeLinePrefix(bytes, baseOffset) {
3932
4140
 
3933
4141
  // host/relay/src/host-registration-state.ts
3934
4142
  import { constants as constants4 } from "node:fs";
3935
- import { dirname as dirname4 } from "node:path";
4143
+ import { dirname as dirname5 } from "node:path";
3936
4144
 
3937
4145
  // host/runtime-source-paths.ts
3938
4146
  import { createHash as createHash7 } from "node:crypto";
3939
- import { posix as posix2, win32 as win323 } from "node:path";
4147
+ import { posix as posix3, win32 as win324 } from "node:path";
3940
4148
 
3941
4149
  // host/absolute-path.ts
3942
- import { posix, win32 as win322 } from "node:path";
4150
+ import { posix as posix2, win32 as win323 } from "node:path";
3943
4151
  function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
3944
- const pathApi = flavor === "win32" || flavor === "windows" ? win322 : posix;
4152
+ const pathApi = flavor === "win32" || flavor === "windows" ? win323 : posix2;
3945
4153
  return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
3946
4154
  }
3947
4155
 
@@ -3962,7 +4170,7 @@ function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
3962
4170
  function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
3963
4171
  const sourceId = hostSourceUuid(sourceRef);
3964
4172
  if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
3965
- const path = platform === "win32" ? win323 : posix2;
4173
+ const path = platform === "win32" ? win324 : posix3;
3966
4174
  const sourcesRoot = path.join(stateRoot, "sources");
3967
4175
  const sourceRoot = path.join(sourcesRoot, sourceId);
3968
4176
  const runtimeRoot = path.join(stateRoot, "run");
@@ -3973,7 +4181,7 @@ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platfor
3973
4181
  function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
3974
4182
  if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
3975
4183
  const digest2 = createHash7("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
3976
- return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix2.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
4184
+ return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix3.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
3977
4185
  }
3978
4186
  function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
3979
4187
  const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
@@ -4001,7 +4209,7 @@ var HostRegistrationStateError = class extends Error {
4001
4209
  async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
4002
4210
  let raw;
4003
4211
  try {
4004
- await assertPrivateRegistrationDirectory(dirname4(path), platform, custody);
4212
+ await assertPrivateRegistrationDirectory(dirname5(path), platform, custody);
4005
4213
  raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
4006
4214
  } catch (error) {
4007
4215
  throw registrationReadError(error);
@@ -4106,192 +4314,6 @@ function waitForAbort(signal, milliseconds) {
4106
4314
  });
4107
4315
  }
4108
4316
 
4109
- // host/service-log.ts
4110
- import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
4111
- import { dirname as dirname5, isAbsolute as isAbsolute2, posix as posix3, win32 as win324 } from "node:path";
4112
-
4113
- // host/service-log-delivery.ts
4114
- var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
4115
- function createHostServiceLogDelivery(stream, schedule = (flush) => {
4116
- setImmediate(flush);
4117
- }, onDeliveryGap = () => void 0) {
4118
- const pending = [];
4119
- const highWaterMark = stream.writableHighWaterMark;
4120
- const byteBudget = highWaterMark + highWaterMark;
4121
- let pendingBytes = 0;
4122
- let droppedLines = 0;
4123
- let flushScheduled = false;
4124
- let waitingForDrain = false;
4125
- let closed = !stream.writable;
4126
- function stop() {
4127
- if (closed) return;
4128
- closed = true;
4129
- pending.length = 0;
4130
- pendingBytes = 0;
4131
- stream.off("drain", onDrain);
4132
- stream.off("close", onTerminal);
4133
- stream.off("finish", onTerminal);
4134
- stream.off("error", onError);
4135
- }
4136
- function onTerminal() {
4137
- stop();
4138
- }
4139
- function onError() {
4140
- stop();
4141
- }
4142
- function onDrain() {
4143
- waitingForDrain = false;
4144
- scheduleFlush();
4145
- }
4146
- function scheduleFlush() {
4147
- if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
4148
- flushScheduled = true;
4149
- let scheduling = true;
4150
- let invokedSynchronously = false;
4151
- try {
4152
- schedule(() => {
4153
- if (scheduling) {
4154
- invokedSynchronously = true;
4155
- return;
4156
- }
4157
- flushScheduled = false;
4158
- flush();
4159
- });
4160
- } catch {
4161
- flushScheduled = false;
4162
- stop();
4163
- return;
4164
- }
4165
- scheduling = false;
4166
- if (invokedSynchronously) {
4167
- flushScheduled = false;
4168
- stop();
4169
- }
4170
- }
4171
- function flush() {
4172
- if (closed) return;
4173
- if (!stream.writable) {
4174
- stop();
4175
- return;
4176
- }
4177
- while (pending.length > 0) {
4178
- if (stream.writableNeedDrain) {
4179
- if (!waitingForDrain) {
4180
- waitingForDrain = true;
4181
- stream.once("drain", onDrain);
4182
- }
4183
- return;
4184
- }
4185
- const next = pending.shift();
4186
- if (next === void 0) return;
4187
- pendingBytes -= next.bytes;
4188
- let accepted;
4189
- try {
4190
- accepted = stream.write(next.line);
4191
- } catch {
4192
- stop();
4193
- return;
4194
- }
4195
- if (!accepted) {
4196
- waitingForDrain = true;
4197
- stream.once("drain", onDrain);
4198
- return;
4199
- }
4200
- }
4201
- if (droppedLines > 0) {
4202
- const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
4203
- `;
4204
- droppedLines = 0;
4205
- try {
4206
- onDeliveryGap(line);
4207
- } catch {
4208
- }
4209
- pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
4210
- pendingBytes += Buffer.byteLength(line, "utf8");
4211
- flush();
4212
- }
4213
- }
4214
- stream.on("close", onTerminal);
4215
- stream.on("finish", onTerminal);
4216
- stream.on("error", onError);
4217
- return (line) => {
4218
- if (closed) return;
4219
- const bytes = Buffer.byteLength(line, "utf8");
4220
- if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
4221
- droppedLines += 1;
4222
- scheduleFlush();
4223
- return;
4224
- }
4225
- pending.push({ line, bytes });
4226
- pendingBytes += bytes;
4227
- scheduleFlush();
4228
- };
4229
- }
4230
-
4231
- // host/invocation-authentication-client-command.ts
4232
- var DOCTOR_FLAGS = Object.freeze({
4233
- "--expected-sha256": "expected_sha256",
4234
- "--expected-source-commit": "expected_source_commit",
4235
- "--expected-instance-ref": "expected_instance_ref"
4236
- });
4237
-
4238
- // host/service-log.ts
4239
- var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
4240
- var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
4241
- void persistHostServiceLogLine(line);
4242
- });
4243
- function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
4244
- const details = diagnosticDetails(event, failure_kind, cause);
4245
- const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
4246
- `;
4247
- try {
4248
- (sink ?? defaultHostServiceDiagnosticSink)(line);
4249
- } catch {
4250
- }
4251
- }
4252
- function diagnosticDetails(event, failureKind, cause) {
4253
- if (event === "watcher_scan_failed") return {
4254
- ...failureKind === void 0 ? {} : { failure_kind: failureKind },
4255
- ...validDiagnosticCause(cause, event) ? { cause } : {}
4256
- };
4257
- return validDiagnosticCause(cause, event) ? { cause } : {};
4258
- }
4259
- function validDiagnosticCause(cause, event) {
4260
- return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
4261
- }
4262
- function defaultHostServiceDiagnosticSink(line) {
4263
- writeHostServiceLogLine(line);
4264
- }
4265
- var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
4266
- function writeHostServiceLogLine(line, environment = process.env) {
4267
- void persistHostServiceLogLine(line, environment);
4268
- defaultHostServiceLogDelivery(line);
4269
- }
4270
- async function persistHostServiceLogLine(line, environment = process.env) {
4271
- if (process.platform !== "win32") return;
4272
- const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
4273
- if (path === void 0 || !win324.isAbsolute(path) || win324.normalize(path) !== path) return;
4274
- await appendHostServiceLogLine(path, line).catch(() => void 0);
4275
- }
4276
- async function appendHostServiceLogLine(path, line) {
4277
- if (!isAbsolute2(path)) return;
4278
- await ensureHostServiceLogDirectory(path);
4279
- await appendFile(path, line);
4280
- }
4281
- var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
4282
- var hostServiceLogDirectories = /* @__PURE__ */ new Map();
4283
- function ensureHostServiceLogDirectory(path) {
4284
- const directory = dirname5(path);
4285
- const existing = hostServiceLogDirectories.get(directory);
4286
- if (existing !== void 0) return existing;
4287
- const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
4288
- hostServiceLogDirectories.delete(directory);
4289
- throw error;
4290
- });
4291
- hostServiceLogDirectories.set(directory, pending);
4292
- return pending;
4293
- }
4294
-
4295
4317
  // host/relay/src/host-usage-facts-uploader.ts
4296
4318
  var HostUsageFactsUploader = class {
4297
4319
  options;
@@ -4310,7 +4332,7 @@ var HostUsageFactsUploader = class {
4310
4332
  const registration = await readHostRegistrationAuthority(this.options.registration_state_file, this.options.host_source_ref, this.options.store_options?.platform, this.options.store_options?.secure_file_custody);
4311
4333
  const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
4312
4334
  const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
4313
- const response2 = await (this.options.fetch ?? fetch)(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4335
+ const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
4314
4336
  method: "POST",
4315
4337
  headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
4316
4338
  body: JSON.stringify(candidate.batch),
@@ -4826,11 +4848,13 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4826
4848
  }
4827
4849
  async scanOpened(handle, registration) {
4828
4850
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
4829
- const cursor = await this.preflight(registration, handle, size, device, inode);
4851
+ const preflight = await this.preflight(registration, handle, size, device, inode);
4852
+ const cursor = preflight.cursor;
4830
4853
  if (cursor === null) return { records: 0, enqueued: 0, quarantined: true };
4831
4854
  if (cursor.status === "quarantined") {
4832
4855
  return { records: 0, enqueued: 0, quarantined: true };
4833
4856
  }
4857
+ if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
4834
4858
  const draft = mutableCursor(cursor);
4835
4859
  await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
4836
4860
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
@@ -4843,6 +4867,15 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4843
4867
  return { records: 0, enqueued: 0, quarantined: true };
4844
4868
  }
4845
4869
  async retireMissing(registration) {
4870
+ const observedAt = this.stamp();
4871
+ if (Date.parse(registration.expires_at) <= Date.parse(observedAt)) return this.retireTranscript(registration);
4872
+ const cursor = await this.store.readTranscriptCursor(registration);
4873
+ if (cursor !== null && isUnmaterializedCursor(cursor, this.sha(Buffer.alloc(0)))) {
4874
+ return { records: 0, enqueued: 0, quarantined: false };
4875
+ }
4876
+ return this.retireTranscript(registration);
4877
+ }
4878
+ retireTranscript(registration) {
4846
4879
  return this.retireMissingTranscript(registration.transcript_path, "Claude", () => this.store.retireTranscriptRegistration(registration));
4847
4880
  }
4848
4881
  initialCursor(registration) {
@@ -4872,16 +4905,18 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4872
4905
  }
4873
4906
  async preflight(registration, handle, size, device, inode) {
4874
4907
  const existing = await this.store.readTranscriptCursor(registration);
4875
- if (existing?.status === "quarantined") return existing;
4908
+ if (existing?.status === "quarantined") return { cursor: existing, checkpointPending: false };
4876
4909
  const cursor = existing ?? this.initialCursor(registration);
4877
4910
  if (cursor.device === void 0) {
4878
- if (cursor.offset !== 0) return await this.quarantineStored(cursor, device, inode, "transcript_replaced");
4879
- return { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
4911
+ const pinned = { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
4912
+ const reason2 = this.cursorIdentityReason(pinned, registration.transcript_path, device, inode);
4913
+ if (cursor.offset !== 0 || reason2 !== null) return { cursor: await this.quarantineStored(cursor, device, inode, "transcript_replaced"), checkpointPending: false };
4914
+ return { cursor: pinned, checkpointPending: true };
4880
4915
  }
4881
4916
  const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
4882
- if (reason !== null) return await this.quarantineStored(cursor, device, inode, reason);
4883
- if (cursor.human_message_window !== void 0) return cursor;
4884
- return { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) };
4917
+ if (reason !== null) return { cursor: await this.quarantineStored(cursor, device, inode, reason), checkpointPending: false };
4918
+ if (cursor.human_message_window !== void 0) return { cursor, checkpointPending: false };
4919
+ return { cursor: { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) }, checkpointPending: true };
4885
4920
  }
4886
4921
  async readHumanMessageProjection(registration, handle, watermark) {
4887
4922
  let offset = 0;
@@ -5178,6 +5213,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5178
5213
  return await this.store.readTranscriptCursor(registration).catch(() => null) ?? this.initialCursor(registration);
5179
5214
  }
5180
5215
  };
5216
+ function isUnmaterializedCursor(cursor, emptyAnchorSha256) {
5217
+ return cursor.status === "active" && cursor.device === void 0 && cursor.inode === void 0 && cursor.offset === 0 && cursor.anchor_start === 0 && cursor.anchor_sha256 === emptyAnchorSha256;
5218
+ }
5181
5219
  function mutableCursor(cursor) {
5182
5220
  return {
5183
5221
  offset: cursor.offset,
@@ -6274,9 +6312,9 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
6274
6312
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
6275
6313
  runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6276
6314
  drain: drainClaudeProducerOnce,
6277
- background: (config, signal) => {
6315
+ background: (config, signal, dependencies) => {
6278
6316
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
6279
- return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext() }, signal);
6317
+ return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext(), fetch: dependencies.fetch }, signal);
6280
6318
  }
6281
6319
  };
6282
6320
 
@@ -6363,7 +6401,7 @@ var execFileAsync = promisify(execFile2);
6363
6401
 
6364
6402
  // host/claude/src/claude-installer.ts
6365
6403
  var ACTIVE_CLAUDE_HOOK_EVENTS = new Set(CLAUDE_HOOK_EVENTS);
6366
- var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: "CLAUDE_CODE_ENTRYPOINT", value: "cli" });
6404
+ var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: CLAUDE_SESSION_ID_ENVIRONMENT, value: Object.freeze({ environment: CLAUDE_SESSION_ID_ENVIRONMENT }) });
6367
6405
  var CLAUDE_CLIENT_ALLOW_RULE = `Bash(${CEAL_SESSION_ENTRY_INVOCATION}:*)`;
6368
6406
 
6369
6407
  // host/claude/bin/ceal-claude-hook.ts