@corca-org/ceal-host-linux-arm64 1.0.20 → 1.0.21

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.
@@ -3,7 +3,7 @@ import { createRequire as __cealCreateRequire } from "node:module";
3
3
  const require = __cealCreateRequire(import.meta.url);
4
4
 
5
5
  // host/producer-service.ts
6
- import { posix as posix3, win32 as win323 } from "node:path";
6
+ import { posix as posix3, win32 as win324 } from "node:path";
7
7
 
8
8
  // host/runtime-source-paths.ts
9
9
  import { createHash } from "node:crypto";
@@ -29,22 +29,17 @@ function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platfor
29
29
  const sourceRoot = path.join(sourcesRoot, sourceId);
30
30
  const runtimeRoot = path.join(stateRoot, "run");
31
31
  const endpoint = platform === "win32" ? `\\\\.\\pipe\\ceal-host-${createHash("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex").slice(0, 24)}` : path.join(runtimeRoot, `${sourceId}.sock`);
32
- assertHostRuntimeIpcLength(endpoint, platform);
33
32
  return { sourceId, sourcesRoot, sourceRoot, relayRoot: path.join(sourceRoot, "relay"), codexOutbox: path.join(sourceRoot, "producers", "codex", "outbox"), claudeOutbox: path.join(sourceRoot, "producers", "claude", "outbox"), endpoint, runtimeRoot };
34
33
  }
35
- function assertHostRuntimeIpcLength(endpoint, platform) {
36
- if (platform === "win32") return;
37
- const maximum = platform === "linux" ? 107 : 103;
38
- if (Buffer.byteLength(endpoint, "utf8") > maximum) throw Object.assign(new TypeError(`ipc_endpoint_too_long: Host IPC path exceeds ${maximum} bytes; use a shorter Host state root.`), { code: "ipc_endpoint_too_long" });
39
- }
40
34
  function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
41
35
  const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
42
- if (config.outbox_dir !== (producer === "codex" ? paths.codexOutbox : paths.claudeOutbox) || config.relay_endpoint !== paths.endpoint) throw new TypeError("Host producer outbox and IPC must belong to its configured source.");
36
+ if (config.outbox_dir !== (producer === "codex" ? paths.codexOutbox : paths.claudeOutbox) || platform !== "win32" && config.relay_endpoint !== paths.endpoint) throw new TypeError("Host producer outbox and IPC must belong to its configured source.");
37
+ return paths.endpoint;
43
38
  }
44
39
 
45
40
  // host/producer-service.ts
46
- import { constants } from "node:fs";
47
- import { lstat, open } from "node:fs/promises";
41
+ import { constants as constants2 } from "node:fs";
42
+ import { lstat as lstat2 } from "node:fs/promises";
48
43
 
49
44
  // packages/ceal-client-protocol/src/canonical-json.ts
50
45
  function cealCanonicalJson(value) {
@@ -73,16 +68,34 @@ function isPlainRecord(value) {
73
68
  return prototype === Object.prototype || prototype === null;
74
69
  }
75
70
 
71
+ // packages/ceal-client-protocol/src/client-wire-contract.ts
72
+ import { createHash as createHash2 } from "node:crypto";
73
+
76
74
  // packages/ceal-client-protocol/client-wire-contract.json
77
75
  var client_wire_contract_default = {
78
76
  schema_version: "ceal.client_wire_contract.v1",
77
+ doctor: {
78
+ schema_version: "ceal.doctor.v1"
79
+ },
80
+ client_commands: {
81
+ doctor: ["doctor"],
82
+ version: ["version"],
83
+ access_group_list: ["access-group", "list"]
84
+ },
85
+ client_environment: {
86
+ environment_prefix: "CEAL",
87
+ context_override_suffixes: ["GATEWAY_ORIGIN", "GATEWAY_TRANSPORT_ORIGIN", "ACCESS_TOKEN", "CONTEXT_STORE_PATH"]
88
+ },
79
89
  canonical_json: {
80
90
  ordering: "utf16_code_unit_ascending"
81
91
  },
82
92
  artifact_descriptor: {
83
- operation_contract_bundle_schema_version: "ceal.operation_contract_bundle.v1",
84
- schema_version: "ceal.verified_artifact_descriptor.v1",
85
- binding_schema_version: "ceal.verified_artifact_binding.v1",
93
+ operation_contract_bundle_schema_name: "ceal.operation_contract_bundle",
94
+ operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
95
+ schema_name: "ceal.verified_artifact_descriptor",
96
+ fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
97
+ binding_schema_name: "ceal.verified_artifact_binding",
98
+ binding_fields: ["schema_version", "kind", "catalog_revision"],
86
99
  kind: "verified_artifact",
87
100
  binding_kind: "catalog",
88
101
  media_type: "application/json",
@@ -98,14 +111,16 @@ var client_wire_contract_default = {
98
111
  length: 72,
99
112
  pattern: "^catalog:[a-f0-9]{64}$"
100
113
  },
101
- envelope_max_bytes: 389
114
+ envelope_max_bytes: 407
102
115
  },
103
116
  command_request: {
104
- schema_version: "ceal.command_request.v1",
117
+ schema_name: "ceal.command_request",
118
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
105
119
  absolute_transport_max_bytes: 65536
106
120
  },
107
121
  command_resolution: {
108
- schema_version: "ceal.gateway_command_resolution.v1",
122
+ schema_name: "ceal.gateway_command_resolution",
123
+ fields: ["schema_version", "kind", "ok", "execution_started", "program", "route", "authority", "routes", "operations", "required_action_sequence", "semantic_options", "result_delivery", "operation", "invocation", "entrypoints", "common_concepts", "withheld", "catalog_revision", "operation_id", "input", "transport", "output", "unresolved_inputs", "unresolved_refusal", "attempted_route", "did_you_mean", "error"],
109
124
  authority: {
110
125
  anonymous: {
111
126
  state: "anonymous",
@@ -145,7 +160,8 @@ var client_wire_contract_default = {
145
160
  }
146
161
  },
147
162
  command_response: {
148
- schema_version: "ceal.command_response.v1",
163
+ schema_name: "ceal.command_response",
164
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
149
165
  descriptor_field: "verified_artifact",
150
166
  required_fields: [
151
167
  "schema_version",
@@ -169,29 +185,41 @@ var client_wire_contract_default = {
169
185
  "required_action_sequence",
170
186
  "withheld"
171
187
  ],
172
- prompt_field: "prompt",
173
- prompt_schema_version: "ceal.prompt.v1",
174
- focused_prompt_document_fields: [
175
- "catalog_revision",
176
- "prompt"
177
- ],
178
- focused_prompt_continuation_document_fields: [
179
- "catalog_revision",
180
- "remaining_work",
181
- "prompt"
182
- ],
183
188
  discovery_command: "discovery",
184
- discovery_manifest_schema_version: "ceal.discovery_manifest.v1",
189
+ discovery_manifest_schema_name: "ceal.discovery_manifest",
190
+ discovery_manifest_fields: ["schema_version", "skill", "authority_scope", "connector_kinds", "personal_connector_kinds", "guide_markdown", "renderer_version", "digest"],
185
191
  discovery_manifest_document_fields: [
186
192
  "discovery_manifest"
187
193
  ],
188
194
  exit_code_max: 125,
189
195
  bare_document_max_bytes: 65536,
190
- complete_max_bytes: 66019
196
+ complete_max_bytes: 66046
197
+ },
198
+ host_invocation_authentication: {
199
+ request_schema_name: "ceal.host_invocation_authentication_request",
200
+ request_fields: [
201
+ "schema_version",
202
+ "client_nonce"
203
+ ],
204
+ result_schema_name: "ceal.host_invocation_authentication_result",
205
+ result_fields: [
206
+ "schema_version",
207
+ "context_token",
208
+ "expires_at"
209
+ ],
210
+ client_nonce: {
211
+ character_class_source: "A-Za-z0-9_-",
212
+ encoded_characters: 43
213
+ }
214
+ },
215
+ gateway_host_invocation_context_request: {
216
+ schema_name: "ceal.gateway_host_invocation_context_request",
217
+ fields: ["schema_version", "client_nonce", "context_expires_at", "request_work_context", "current_prompt", "visible_output_max_bytes"]
191
218
  },
192
219
  resource_stream: {
193
220
  path: "/api/ceal/v2/resources",
194
- request_schema_version: "ceal.resource_stream_request.v1",
221
+ request_schema_name: "ceal.resource_stream_request",
222
+ request_fields: ["schema_version", "resource_ref", "client_nonce", "context_token"],
195
223
  ref_pattern: "^resource:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
196
224
  media_type_pattern: "^[a-z0-9][a-z0-9!#$&^_.+-]{0,63}/[a-z0-9][a-z0-9!#$&^_.+-]{0,63}$",
197
225
  filename_max_bytes: 512,
@@ -208,88 +236,6 @@ var client_wire_contract_default = {
208
236
  }
209
237
  };
210
238
 
211
- // packages/ceal-client-protocol/src/client-wire-contract.ts
212
- var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
213
- var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
214
- var commandResolutionAuthority = commandResolution.authority;
215
- var commandResolutionSemanticOptions = commandResolution.semantic_options;
216
- var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = commandResolution.schema_version;
217
- var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
218
- var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
219
- var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
220
- var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
221
- var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = artifact.operation_contract_bundle_schema_version;
222
- var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = artifact.schema_version;
223
- var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = artifact.binding_schema_version;
224
- var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
225
- var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
226
- var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
227
- var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
228
- var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
229
- var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
230
- var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
231
- var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
232
- var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
233
- var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = request.schema_version;
234
- var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
235
- var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
236
- var CEAL_COMMAND_RESPONSE_PROMPT_FIELD = response.prompt_field;
237
- var CEAL_COMMAND_RESPONSE_PROMPT_SCHEMA_VERSION = response.prompt_schema_version;
238
- var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
239
- var CEAL_COMMAND_RESPONSE_PROMPT_DOCUMENT_FIELDS = Object.freeze([...response.bare_document_fields, response.prompt_field]);
240
- var CEAL_COMMAND_RESPONSE_FOCUSED_PROMPT_DOCUMENT_FIELDS = Object.freeze([...response.focused_prompt_document_fields]);
241
- var CEAL_COMMAND_RESPONSE_FOCUSED_PROMPT_CONTINUATION_DOCUMENT_FIELDS = Object.freeze([...response.focused_prompt_continuation_document_fields]);
242
- var CEAL_COMMAND_RESPONSE_DISCOVERY_COMMAND = response.discovery_command;
243
- var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = response.discovery_manifest_schema_version;
244
- var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_DOCUMENT_FIELDS = Object.freeze([...response.discovery_manifest_document_fields]);
245
-
246
- // packages/ceal-client-protocol/src/vocabulary.ts
247
- function vocabulary(words) {
248
- return Object.freeze(words);
249
- }
250
-
251
- // packages/ceal-client-protocol/src/gateway-response-types.ts
252
- var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
253
- var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
254
- var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
255
- var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
256
- 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"]);
257
- var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
258
- var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
259
- var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
260
- var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
261
- var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "scope_limit_exceeded"]);
262
- var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
263
- var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable"]);
264
- var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
265
- var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
266
- var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
267
- var CEAL_WRITE_ATTRIBUTIONS = vocabulary(["subject", "requester_event", "connector_integration"]);
268
- var CEAL_WRITE_RECEIPT_PROVIDER_STATES = vocabulary(["outcome_unknown", "verified", "not_dispatched"]);
269
- var CEAL_WRITE_RECEIPT_PROVIDER_READBACKS = vocabulary(["outcome_unknown", "verified", "not_applied"]);
270
- var CEAL_PROTOCOL_VERSION = "1.4.0";
271
- var CEAL_OPERATION_ACCESS_SCHEMA_VERSION = "ceal.operation_access.v1";
272
- var CEAL_GATEWAY_CONTINUATION_CURSOR_PHASES = vocabulary(["scan", "delivery", "terminal"]);
273
- var CEAL_GATEWAY_ACTIVE_CALL_PHASES = vocabulary([
274
- "audited_call_pending",
275
- "continuation_read_pending",
276
- "continuation_write_pending",
277
- "provider_pacing_pending",
278
- "corpus_replay_pending",
279
- "corpus_append_pending",
280
- "corpus_fence_pending",
281
- "corpus_content_pending",
282
- "corpus_transaction_pending"
283
- ]);
284
- var CEAL_CONNECTOR_ROUTE_FAILURE_KEYS = vocabulary(["connector_kind", "phase", "schema_version"]);
285
- var CEAL_CLASSIFIED_CONNECTOR_ROUTE_FAILURE_KEYS = vocabulary(["cause", ...CEAL_CONNECTOR_ROUTE_FAILURE_KEYS]);
286
- var CEAL_UNCLASSIFIED_CONNECTOR_ROUTE_FAILURE_KEYS = vocabulary(["connector_kind", "error_class", "phase", "schema_version"]);
287
- var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
288
- "connector_ref",
289
- "connector_revision",
290
- "policy_decision_revision"
291
- ]);
292
-
293
239
  // packages/ceal-client-protocol/src/operation-next-actions.ts
294
240
  var CEAL_REPEAT_REQUEST_NEXT_ACTION = "repeat_request";
295
241
  var CEAL_INSPECT_RECEIPT_NEXT_ACTION = "inspect_receipt";
@@ -356,7 +302,10 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
356
302
  "follow_required_action_sequence",
357
303
  // The command needs caller-owned local materialization (for example an
358
304
  // @path file) before the Gateway can receive the argument.
359
- "materialize_local_argument"
305
+ "materialize_local_argument",
306
+ // A peer's derived schema identifier changed with its field set; install or
307
+ // upgrade the CLI and Host Relay to the Gateway's release before retrying.
308
+ "upgrade_ceal_client"
360
309
  ];
361
310
  var CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS = Object.freeze(CALLER_RECOVERABLE_NEXT_ACTION_VALUES);
362
311
  var NON_REMEDY_NEXT_ACTION_VALUES = [
@@ -469,47 +418,53 @@ var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
469
418
  personal_authorization_required: "connect_personal_account"
470
419
  });
471
420
 
472
- // packages/ceal-client-protocol/src/operation-withheld-cause.ts
473
- var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
421
+ // packages/ceal-client-protocol/src/vocabulary.ts
422
+ function vocabulary(words) {
423
+ return Object.freeze(words);
424
+ }
474
425
 
475
- // packages/ceal-client-protocol/src/operation-contract-types.ts
476
- var CEAL_JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
477
- var CEAL_OPERATION_ERROR_SCHEMA_VERSION = "ceal.operation_error.v1";
478
- var CEAL_ARTIFACT_STAGE_TERMINALS = vocabulary(["chunk_accepted", "artifact_ready", "idempotency_replayed"]);
479
- var CEAL_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
480
- var CEAL_JSON_SCHEMA_TYPES = vocabulary(["object", "array", "string", "integer", "number", "boolean", "null"]);
481
- var OBSERVATION_POSTURES = vocabulary(["direct_readback", "approved_no_readback", "operator_mediated", "excluded"]);
482
- var EFFECT_DOMAINS = vocabulary(["none", "gateway_state", "provider", "external_world"]);
483
- var SAFETY_CLASSES = vocabulary(["routine", "sensitive", "high_impact"]);
484
- var IDEMPOTENCY_CLASSES = vocabulary(["idempotent", "conditionally_idempotent", "non_idempotent"]);
485
- var REVERSIBILITY_CLASSES = vocabulary(["none", "reversible", "compensatable", "irreversible"]);
486
- var COMPENSATION_OWNERS = vocabulary(["none", "connector", "operator"]);
487
- var CANCELLATION_BOUNDARIES = vocabulary(["before_admission", "before_handoff", "after_handoff_reconcile"]);
488
- var HANDOFF_CLASSES = vocabulary(["not_applicable", "submission", "effect"]);
489
- var AUTHORITATIVE_READBACK_CLASSES = vocabulary(["required", "unavailable"]);
490
- var PROVIDER_READBACK_CLASSES = vocabulary(["required", "not_available", "not_applicable"]);
491
- var RECONCILIATION_CLASSES = vocabulary(["none", "automatic", "operator"]);
492
- var NO_READBACK_APPROVAL_CLASSES = vocabulary(["not_applicable", "explicit", "operator"]);
493
- var REPLAY_PREREQUISITES = vocabulary(["never", "fresh_admission", "reconciled_non_application", "operator_approval"]);
494
- var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
495
- var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
496
- var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
497
- var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
498
- var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
499
- var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
500
- var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
501
- var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
502
- var CEAL_OPERATION_RECOVERY_STATUSES = vocabulary(["not_started", "active", "completed"]);
503
- var CEAL_OPERATION_PROVIDER_READBACK_AVAILABILITY = vocabulary(["not_started", "not_applicable", "not_available", "pending", "available"]);
504
- var CEAL_OPERATION_OFFERED_HANDOFF_STATES = vocabulary(["accepted", "rejected", "unknown"]);
505
- var CEAL_OPERATION_RECEIPT_AUTHORITY_KEYS = Object.freeze(["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]);
506
- var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
507
- "approval_not_required_by_policy",
508
- "interactive_pending",
509
- "interactive_granted",
510
- "interactive_denied",
511
- "interactive_expired",
512
- "interactive_unavailable"
426
+ // packages/ceal-client-protocol/src/gateway-response-types.ts
427
+ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
428
+ var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
429
+ var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
430
+ var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
431
+ 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"]);
432
+ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
433
+ var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
434
+ var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
435
+ var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
436
+ var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "scope_limit_exceeded"]);
437
+ var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
438
+ var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable"]);
439
+ var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
440
+ var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
441
+ var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
442
+ var CEAL_WRITE_ATTRIBUTIONS = vocabulary(["subject", "requester_event", "connector_integration"]);
443
+ var CEAL_WRITE_RECEIPT_PROVIDER_STATES = vocabulary(["outcome_unknown", "verified", "not_dispatched"]);
444
+ var CEAL_WRITE_RECEIPT_PROVIDER_READBACKS = vocabulary(["outcome_unknown", "verified", "not_applied"]);
445
+ var CEAL_PROTOCOL_VERSION = "1.4.0";
446
+ var CEAL_OPERATION_ACCESS_SCHEMA_VERSION = "ceal.operation_access.v1";
447
+ var CEAL_GATEWAY_CALL_RESULT_SCHEMA_VERSION = "ceal.gateway_call_result.v1";
448
+ var CEAL_GATEWAY_CONTINUATION_CURSOR_PHASES = vocabulary(["scan", "delivery", "terminal"]);
449
+ var CEAL_GATEWAY_ACTIVE_CALL_PHASES = vocabulary([
450
+ "audited_call_pending",
451
+ "continuation_read_pending",
452
+ "continuation_write_pending",
453
+ "provider_pacing_pending",
454
+ "corpus_replay_pending",
455
+ "corpus_append_pending",
456
+ "corpus_fence_pending",
457
+ "corpus_content_pending",
458
+ "corpus_transaction_pending"
459
+ ]);
460
+ var CEAL_CONNECTOR_ROUTE_FAILURE_KEYS = vocabulary(["connector_kind", "phase", "schema_version"]);
461
+ var CEAL_CLASSIFIED_CONNECTOR_ROUTE_FAILURE_KEYS = vocabulary(["cause", ...CEAL_CONNECTOR_ROUTE_FAILURE_KEYS]);
462
+ var CEAL_UNCLASSIFIED_CONNECTOR_ROUTE_FAILURE_KEYS = vocabulary(["connector_kind", "error_class", "phase", "schema_version"]);
463
+ var CEAL_GATEWAY_AUDIT_CALL_DETAIL_SCHEMA_VERSION = "ceal.gateway_audit_call_detail.v1";
464
+ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
465
+ "connector_ref",
466
+ "connector_revision",
467
+ "policy_decision_revision"
513
468
  ]);
514
469
 
515
470
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
@@ -551,10 +506,10 @@ function assertSafeJsonArray(value, options, depth, count) {
551
506
  if (value.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
552
507
  for (const item of value) assertSafeJsonValue(item, options, depth + 1, count);
553
508
  }
554
- function assertSafeJsonRecord(record5, options, depth, count) {
555
- const entries = Object.entries(record5);
509
+ function assertSafeJsonRecord(record4, options, depth, count) {
510
+ const entries = Object.entries(record4);
556
511
  if (entries.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
557
- const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record5.fields) : null;
512
+ const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record4.fields) : null;
558
513
  for (const [key, child] of entries) {
559
514
  if (key === "credential_material_included" && child !== false) invalidByContext(options);
560
515
  if (!isSafeNegativeMaterialAssertion(key, child)) assertSafeJsonKey(key, options);
@@ -723,51 +678,6 @@ function cut(text) {
723
678
  return text.length <= REFUSAL_VALUE_MAX_CHARS ? text : `${text.slice(0, REFUSAL_VALUE_MAX_CHARS)}...(+${text.length - REFUSAL_VALUE_MAX_CHARS} chars)`;
724
679
  }
725
680
 
726
- // packages/ceal-client-protocol/src/operation-access-class.ts
727
- var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
728
-
729
- // packages/ceal-client-protocol/src/domain-vocabulary.ts
730
- var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
731
- var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
732
- var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
733
- var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
734
- var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
735
- var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
736
- var CEAL_TARGET_VISIBILITIES = vocabulary(["public", "private"]);
737
- var CEAL_PRINCIPAL_KINDS = vocabulary(["human", "runtime"]);
738
- var CEAL_PERSISTED_PRINCIPAL_KINDS = vocabulary(["human", "service", "runtime"]);
739
- var CEAL_ORGANIZATION_ROLES = vocabulary(["member", "admin"]);
740
- var CEAL_CALENDAR_PERIODS = vocabulary(["day", "week", "month"]);
741
- var LABEL_EXPECTATION = `public-safe display text of at most ${CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES} bytes`;
742
-
743
- // packages/ceal-client-protocol/src/safe-json-budget.ts
744
- var SAFE_JSON_MIN_BYTES_PER_NODE = 4;
745
- function safeJsonNodeBudgetForBytes(maxBytes) {
746
- if (!Number.isSafeInteger(maxBytes) || maxBytes < SAFE_JSON_MIN_BYTES_PER_NODE) {
747
- throw new RangeError(`safe-JSON byte cap is invalid: ${refusalFact("maxBytes", maxBytes, `at least ${SAFE_JSON_MIN_BYTES_PER_NODE} bytes`)}`);
748
- }
749
- return Math.floor(maxBytes / SAFE_JSON_MIN_BYTES_PER_NODE);
750
- }
751
-
752
- // packages/ceal-client-protocol/src/protocol-bounds.ts
753
- var CEAL_PROTOCOL_RESPONSE_VALUE_MAX_BYTES = 64 * 1024;
754
- var CEAL_PROTOCOL_RESPONSE_VALUE_MAX_NODES = safeJsonNodeBudgetForBytes(CEAL_PROTOCOL_RESPONSE_VALUE_MAX_BYTES);
755
- var OPERATION_SCHEMA_LITERAL_MAX_BYTES = CEAL_PROTOCOL_RESPONSE_VALUE_MAX_BYTES / 4;
756
- var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
757
- max_depth: 8,
758
- max_properties: 96,
759
- max_string_length: OPERATION_SCHEMA_LITERAL_MAX_BYTES / 4,
760
- max_alternatives: 8,
761
- max_enum_values: 64,
762
- max_literal_bytes: OPERATION_SCHEMA_LITERAL_MAX_BYTES,
763
- /** @basis our_policy -- bounds explanatory schema prose carried in one catalog. */
764
- max_description_characters: 1024,
765
- /** @basis our_policy -- bounds regular-expression compilation input from one schema. */
766
- max_pattern_characters: 256,
767
- /** @basis our_policy -- bounds traversal work inside one already byte-bounded schema literal. */
768
- max_literal_nodes: 512
769
- });
770
-
771
681
  // packages/ceal-client-protocol/src/operation-validation-primitives.ts
772
682
  var ISO_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?([Zz]|([+-])(\d{2}):(\d{2}))$/u;
773
683
  var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
@@ -835,19 +745,330 @@ function requireIsoTimestamp(value, message) {
835
745
  if (!isCealIsoTimestamp(value)) throw new TypeError(message);
836
746
  }
837
747
 
838
- // packages/ceal-client-protocol/src/operation-json-schema.ts
839
- var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
840
-
841
- // packages/ceal-client-protocol/src/operation-contract-validation.ts
842
- var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
843
- var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
844
- var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
845
- var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
748
+ // packages/ceal-client-protocol/src/failure-guidance-table.ts
749
+ var CEAL_FAILURE_REDACTION_CLASSES = vocabulary(["model_safe", "withheld"]);
750
+ var CEAL_GATEWAY_STARTING_FAILURE_CODE = "gateway_starting";
751
+ var CEAL_OWNER_BOOTSTRAP_ABSENT_FAILURE_CODE = "bootstrap_absent";
752
+ var CEAL_OWNER_BOOTSTRAP_UNAVAILABLE_FAILURE_CODE = "bootstrap_unavailable";
753
+ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
754
+ var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
755
+ var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
756
+ var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
757
+ var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
758
+ function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
759
+ return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
760
+ }
761
+ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
762
+ invalid_command: guidance(LOCAL_COMMAND_INVALID, "correct_argument", 400),
763
+ invalid_argument: guidance(LOCAL_COMMAND_INVALID, "correct_argument", 400),
764
+ command_not_found: guidance(LOCAL_COMMAND_INVALID, "correct_argument", 404),
765
+ unknown_operation: guidance("The requested Operation is absent from the current verified catalog; report this as a gap unless a catalog suggestion names a replacement.", "answer_with_gap", 404),
766
+ local_route_unavailable: guidance("The requested local route is unavailable or its descriptor is invalid; report this as a gap.", "answer_with_gap", 404),
767
+ local_route_ambiguous: guidance("The requested local route is ambiguous; no local executable was selected. Report this as a gap.", "answer_with_gap", 400),
768
+ local_execution_unavailable: guidance("The selected local route executable is unavailable; report this as a gap.", "answer_with_gap", 500),
769
+ local_pickup_failed: guidance("The Host Request pickup failed; the Gateway command was not sent. Report this as a gap.", "answer_with_gap", 502),
770
+ invocation_authentication_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
771
+ local_execution_cancellation_unknown: guidance("The selected local route cancellation outcome is unknown; a retry can repeat an effect the cancelled route already completed. Report this as a gap and do not retry.", "answer_with_gap", 409),
772
+ gateway_origin_required: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
773
+ access_token_required: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
774
+ context_pair_required: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
775
+ context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
776
+ context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
777
+ context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
778
+ refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
779
+ refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
780
+ refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
781
+ refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
782
+ refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
783
+ refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
784
+ 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),
785
+ local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
786
+ local_output_outside_result_root: guidance("The selected local output path lies outside this run's result root; only a path inside the result root named here is writable.", "choose_new_output_path", 400),
787
+ local_output_unwritable: guidance("The Ceal client could not write the result file at its local path; the operating system refused the write. When that step followed the Gateway call, the call may already have completed a write effect that a rerun repeats. rerun_outside_agent_sandbox reruns it with escalated execution.", "rerun_outside_agent_sandbox", 500),
788
+ local_output_unavailable: guidance("The Gateway result could not be materialized at the selected local path; report this as a gap.", "answer_with_gap", 500),
789
+ local_materialization_required: guidance("The Gateway result could not be materialized at the selected local path; report this as a gap.", "answer_with_gap", 500),
790
+ contract_artifact_cache_invalid: guidance("The verified contract artifact could not be stored in the private local cache; report this as a gap.", "answer_with_gap", 500),
791
+ response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
792
+ request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
793
+ request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
794
+ gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
795
+ contract_mismatch: guidance("Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.", "upgrade_ceal_client", 409),
796
+ // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
797
+ // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
798
+ // when the wait ends still unserved, moved from the `localFailureText` default branch.
799
+ [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
800
+ gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
801
+ // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
802
+ // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
803
+ internal_error: guidance("The Gateway failed without exposing internal state.", "answer_with_gap", 500),
804
+ // Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
805
+ // the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
806
+ request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
807
+ // Restored verbatim from the retired `localFailureText` `unknown_outcome`
808
+ // case: the outcome is unknown, so a read may be retried while a write
809
+ // must receipt-check first. Collapsing both to "do not repeat the call"
810
+ // forbids the safe read retry the sentence exists to allow.
811
+ 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),
812
+ // Restored verbatim from the retired `localFailureText`
813
+ // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
814
+ // session context unavailable, so the caller repairs or adopts the
815
+ // session instead of reporting a transport gap.
816
+ refresh_unknown_outcome: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
817
+ request_cancelled: guidance("The caller cancelled the request before it completed.", "retry", 400, true),
818
+ expired: guidance("The activation transaction or its administrator approval request expired before completion; repeat the original activation arguments to start a new transaction.", "repeat_original_arguments", 410, true),
819
+ denied: guidance("An administrator denied this device's activation request; ask an administrator whether to reconsider it.", "ask_admin", 403),
820
+ device_approval_pending_limit: guidance("Device approval requests are already waiting for an administrator decision; ask an administrator to decide a pending request before adding another device.", "ask_admin", 429),
821
+ session_already_adopted: guidance("The requested enrollment was not started because this machine already has a live session with the Gateway. Report this as a gap if that local session needs replacement.", "answer_with_gap", 409),
822
+ pending_adoption_limit: guidance("This device's pending activation file is full; another activation is refused while an administrator decision is pending. Report this as a gap.", "answer_with_gap", 429),
823
+ recovery_required: guidance("The Gateway could not safely complete the activation transaction automatically; ask an administrator to recover this transaction.", "ask_admin", 500),
824
+ unsupported_feature: guidance("This Ceal client does not support the Gateway's required activation protocol; ask an administrator to update the client.", "ask_admin", 501),
825
+ // Activation commit codes rendered through the `localFailureText` default before phase 2b; `retryable` is moved from the
826
+ // emitting sites in `cli/internal/client/gateway_installation_activation.go` and `activation.go:483`.
827
+ activation_state_commit_failed: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 500, true),
828
+ activation_response_invalid: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 502, true),
829
+ activation_rejected: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 502),
830
+ activation_failed: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 500),
831
+ activation_binding: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 400),
832
+ activation_crypto: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 500),
833
+ activation_state_invalid: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 500),
834
+ // Long-tail local codes rendered through the `localFailureText` default before phase 2b; sentences moved from that branch.
835
+ invalid_response: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 500),
836
+ invalid_configuration: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 500),
837
+ activation_state_unavailable: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 500),
838
+ activation_code_invalid: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 400),
839
+ activation_code_file_invalid: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 400),
840
+ activation_code_unavailable: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 404),
841
+ bootstrap_file_invalid: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 400),
842
+ bootstrap_not_active: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 409),
843
+ bootstrap_unauthorized: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 401),
844
+ // The Gateway owner-bootstrap store file was never created, so the Gateway
845
+ // holds no owner bootstrap to exchange (`gateway/src/host/owner-bootstrap-http-composition.ts`
846
+ // `absent`, stored at `gateway/src/shared/installation/owner-bootstrap-store.ts:162`);
847
+ // the sentence is the owner-normalized form of that store error. Non-retryable:
848
+ // repeating the exchange cannot create the store; only an administrator
849
+ // placing a bootstrap (fresh gateway setup) changes the outcome.
850
+ [CEAL_OWNER_BOOTSTRAP_ABSENT_FAILURE_CODE]: guidance("The Gateway holds no owner bootstrap to exchange; report this as a gap.", "answer_with_gap", 503),
851
+ // The Gateway owner-bootstrap store file exists but cannot be read, so the
852
+ // exchange cannot proceed (`gateway/src/host/owner-bootstrap-http-composition.ts`
853
+ // `unavailable`, stored at `gateway/src/shared/installation/owner-bootstrap-store.ts:163`);
854
+ // the sentence is the owner-normalized form of that store error. Retryable:
855
+ // unlike `absent`, a later exchange may succeed once the store is readable.
856
+ [CEAL_OWNER_BOOTSTRAP_UNAVAILABLE_FAILURE_CODE]: guidance("The Gateway owner bootstrap store is unavailable; retry the exchange.", "retry", 503, true),
857
+ context_selection_ambiguous: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 400),
858
+ session_authority_unverified: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 401),
859
+ session_authority_mismatch: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 409),
860
+ local_credential_lost: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 401),
861
+ local_capability_invalid: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 500),
862
+ host_unavailable: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503),
863
+ host_activation_failed: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 500),
864
+ doctor_unavailable: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503),
865
+ admin_sign_in_invalid: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 502),
866
+ // `invalid_request` renders through the client default today (local encode/path faults); Gateway-answered
867
+ // envelopes carry the Gateway message verbatim and never read this sentence.
868
+ invalid_request: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 400),
869
+ // Gateway canonical-route codes, sentences moved from their minting adapters; statuses moved from the
870
+ // `valid*Failure` decoder maps in `cli/internal/client/gateway_api.go` and `transport.go`.
871
+ invalid_json: guidance("The Gateway request body must be valid JSON.", "answer_with_gap", 400),
872
+ // Per-route variants name their route; the table holds the one stable guidance and the route's `allow`
873
+ // header stays the measured fact (decided with the operator 2026-10-13).
874
+ method_not_allowed: guidance("The HTTP method is not allowed for this Gateway route.", "answer_with_gap", 405),
875
+ request_target_too_large: guidance("The Gateway request target exceeds its bounded limit.", "reduce_request_size", 414),
876
+ route_not_found: guidance("The Gateway route is not present.", "answer_with_gap", 404),
877
+ artifact_unavailable: guidance("The Gateway artifact is unavailable.", "answer_with_gap", 503),
878
+ discovery_unavailable: guidance("The Gateway discovery manifest is unavailable.", "answer_with_gap", 503),
879
+ serialization_failed: guidance("The Gateway response could not be serialized.", "answer_with_gap", 500),
880
+ request_header_too_large: guidance("A consumed Gateway request header exceeds its bounded limit.", "answer_with_gap", 431),
881
+ request_work_context_missing: guidance("The Gateway command requires a Request work context.", "answer_with_gap", 400),
882
+ request_work_context_invalid: guidance("The Gateway Request work context encoding is invalid.", "answer_with_gap", 400),
883
+ request_work_context_refused: guidance("The Host-only discovery manifest takes no Request work context.", "answer_with_gap", 400),
884
+ // Moved from `gateway/src/operations/http-composition.ts` (`unauthorized`) and `command-runtime.ts:827`
885
+ // (`artifact_stale`); both travel with Gateway messages verbatim online, so these sentences are the
886
+ // owner fallback guidance. `unauthorized` re-authenticates through the session, hence its action.
887
+ unauthorized: guidance("Unauthorized.", "repair_or_adopt_session", 401),
888
+ artifact_stale: guidance("The requested contract artifact is not the current catalog artifact.", "answer_with_gap", 409),
889
+ // Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
890
+ // in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
891
+ // is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
892
+ // and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). The three rows
893
+ // with their own sentences carry the retired policy remedies as Gateway-owned guidance. Statuses are the
894
+ // Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
895
+ // `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
896
+ host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
897
+ host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
898
+ host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
899
+ // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
900
+ // missing exact-turn fact names the fresh Host turn, not a reinstall.
901
+ host_context_unavailable: guidance("The Host has not activated an invocation context for this session yet. Wait for the Host turn hook to register the session, then retry this command.", "retry", 401, true),
902
+ host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
903
+ host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
904
+ host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
905
+ host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
906
+ host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
907
+ host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
908
+ host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
909
+ host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
910
+ // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
911
+ // producer-frame fault names the administrator repair step.
912
+ host_producer_frame_invalid: guidance("Ask an administrator to inspect and repair the producer frame, then start a fresh Host turn.", "ask_admin", 400),
913
+ // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
914
+ // sandboxed Relay socket names the run-alone retry.
915
+ 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),
916
+ host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
917
+ host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
918
+ host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
919
+ host_relay_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
920
+ host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
921
+ });
922
+ var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
846
923
 
847
- // packages/ceal-client-protocol/src/operation-catalog.ts
848
- var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
849
- var CLIENT_AUDIENCES = Object.freeze(["ceal", "cealctl", "agent"]);
850
- var CLIENT_AUDIENCE_SET = new Set(CLIENT_AUDIENCES);
924
+ // packages/ceal-client-protocol/src/client-wire-contract.ts
925
+ var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
926
+ var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
927
+ var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
928
+ var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
929
+ var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
930
+ var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
931
+ function deriveCealClientWireSchemaVersion(schema) {
932
+ if (!/^ceal\.[a-z][a-z0-9_]*$/u.test(schema.schema_name) || !schema.fields.includes("schema_version") || new Set(schema.fields).size !== schema.fields.length || schema.fields.some((field) => typeof field !== "string" || !/^[a-z][a-z0-9_]*$/u.test(field))) {
933
+ throw new TypeError("Client wire schema name or field set is invalid.");
934
+ }
935
+ const fields = schema.fields.filter((field) => field !== "schema_version").sort();
936
+ const hash8 = createHash2("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
937
+ return `${schema.schema_name}.v1.${hash8}`;
938
+ }
939
+ var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
940
+ var commandResolutionAuthority = commandResolution.authority;
941
+ var commandResolutionSemanticOptions = commandResolution.semantic_options;
942
+ var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
943
+ var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
944
+ var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
945
+ var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
946
+ var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
947
+ var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
948
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
949
+ var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
950
+ var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
951
+ var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
952
+ var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
953
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
954
+ var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
955
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
956
+ var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
957
+ var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
958
+ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
959
+ var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
960
+ var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
961
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
962
+ var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
963
+ var CEAL_COMMAND_RESPONSE_DISCOVERY_COMMAND = response.discovery_command;
964
+ var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
965
+ var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
966
+ var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_DOCUMENT_FIELDS = Object.freeze([...response.discovery_manifest_document_fields]);
967
+ var CEAL_RESOURCE_STREAM_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_schema_name, fields: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields });
968
+ var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
969
+
970
+ // packages/ceal-client-protocol/src/operation-withheld-cause.ts
971
+ var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
972
+
973
+ // packages/ceal-client-protocol/src/operation-contract-types.ts
974
+ var CEAL_JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
975
+ var CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION = "ceal.operation_descriptor.v1";
976
+ var CEAL_OPERATION_ERROR_SCHEMA_VERSION = "ceal.operation_error.v1";
977
+ var CEAL_ARTIFACT_STAGE_TERMINALS = vocabulary(["chunk_accepted", "artifact_ready", "idempotency_replayed"]);
978
+ var CEAL_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
979
+ var CEAL_JSON_SCHEMA_TYPES = vocabulary(["object", "array", "string", "integer", "number", "boolean", "null"]);
980
+ var OBSERVATION_POSTURES = vocabulary(["direct_readback", "approved_no_readback", "operator_mediated", "excluded"]);
981
+ var EFFECT_DOMAINS = vocabulary(["none", "gateway_state", "provider", "external_world"]);
982
+ var SAFETY_CLASSES = vocabulary(["routine", "sensitive", "high_impact"]);
983
+ var IDEMPOTENCY_CLASSES = vocabulary(["idempotent", "conditionally_idempotent", "non_idempotent"]);
984
+ var REVERSIBILITY_CLASSES = vocabulary(["none", "reversible", "compensatable", "irreversible"]);
985
+ var COMPENSATION_OWNERS = vocabulary(["none", "connector", "operator"]);
986
+ var CANCELLATION_BOUNDARIES = vocabulary(["before_admission", "before_handoff", "after_handoff_reconcile"]);
987
+ var HANDOFF_CLASSES = vocabulary(["not_applicable", "submission", "effect"]);
988
+ var AUTHORITATIVE_READBACK_CLASSES = vocabulary(["required", "unavailable"]);
989
+ var PROVIDER_READBACK_CLASSES = vocabulary(["required", "not_available", "not_applicable"]);
990
+ var RECONCILIATION_CLASSES = vocabulary(["none", "automatic", "operator"]);
991
+ var NO_READBACK_APPROVAL_CLASSES = vocabulary(["not_applicable", "explicit", "operator"]);
992
+ var REPLAY_PREREQUISITES = vocabulary(["never", "fresh_admission", "reconciled_non_application", "operator_approval"]);
993
+ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
994
+ var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
995
+ var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
996
+ var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
997
+ var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
998
+ var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
999
+ var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
1000
+ var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
1001
+ var CEAL_OPERATION_RECOVERY_STATUSES = vocabulary(["not_started", "active", "completed"]);
1002
+ var CEAL_OPERATION_PROVIDER_READBACK_AVAILABILITY = vocabulary(["not_started", "not_applicable", "not_available", "pending", "available"]);
1003
+ var CEAL_OPERATION_OFFERED_HANDOFF_STATES = vocabulary(["accepted", "rejected", "unknown"]);
1004
+ var CEAL_OPERATION_RECEIPT_AUTHORITY_KEYS = Object.freeze(["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]);
1005
+ var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
1006
+ "approval_not_required_by_policy",
1007
+ "interactive_pending",
1008
+ "interactive_granted",
1009
+ "interactive_denied",
1010
+ "interactive_expired",
1011
+ "interactive_unavailable"
1012
+ ]);
1013
+
1014
+ // packages/ceal-client-protocol/src/operation-access-class.ts
1015
+ var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
1016
+
1017
+ // packages/ceal-client-protocol/src/domain-vocabulary.ts
1018
+ var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
1019
+ var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
1020
+ var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
1021
+ var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
1022
+ var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
1023
+ var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
1024
+ var CEAL_TARGET_VISIBILITIES = vocabulary(["public", "private"]);
1025
+ var CEAL_PRINCIPAL_KINDS = vocabulary(["human", "runtime"]);
1026
+ var CEAL_PERSISTED_PRINCIPAL_KINDS = vocabulary(["human", "service", "runtime"]);
1027
+ var CEAL_ORGANIZATION_ROLES = vocabulary(["member", "admin"]);
1028
+ var CEAL_CALENDAR_PERIODS = vocabulary(["day", "week", "month"]);
1029
+ var LABEL_EXPECTATION = `public-safe display text of at most ${CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES} bytes`;
1030
+
1031
+ // packages/ceal-client-protocol/src/safe-json-budget.ts
1032
+ var SAFE_JSON_MIN_BYTES_PER_NODE = 4;
1033
+ function safeJsonNodeBudgetForBytes(maxBytes) {
1034
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < SAFE_JSON_MIN_BYTES_PER_NODE) {
1035
+ throw new RangeError(`safe-JSON byte cap is invalid: ${refusalFact("maxBytes", maxBytes, `at least ${SAFE_JSON_MIN_BYTES_PER_NODE} bytes`)}`);
1036
+ }
1037
+ return Math.floor(maxBytes / SAFE_JSON_MIN_BYTES_PER_NODE);
1038
+ }
1039
+
1040
+ // packages/ceal-client-protocol/src/protocol-bounds.ts
1041
+ var CEAL_PROTOCOL_RESPONSE_VALUE_MAX_BYTES = 64 * 1024;
1042
+ var CEAL_PROTOCOL_RESPONSE_VALUE_MAX_NODES = safeJsonNodeBudgetForBytes(CEAL_PROTOCOL_RESPONSE_VALUE_MAX_BYTES);
1043
+ var OPERATION_SCHEMA_LITERAL_MAX_BYTES = CEAL_PROTOCOL_RESPONSE_VALUE_MAX_BYTES / 4;
1044
+ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
1045
+ max_depth: 8,
1046
+ max_properties: 96,
1047
+ max_string_length: OPERATION_SCHEMA_LITERAL_MAX_BYTES / 4,
1048
+ max_alternatives: 8,
1049
+ max_enum_values: 64,
1050
+ max_literal_bytes: OPERATION_SCHEMA_LITERAL_MAX_BYTES,
1051
+ /** @basis our_policy -- bounds explanatory schema prose carried in one catalog. */
1052
+ max_description_characters: 1024,
1053
+ /** @basis our_policy -- bounds regular-expression compilation input from one schema. */
1054
+ max_pattern_characters: 256,
1055
+ /** @basis our_policy -- bounds traversal work inside one already byte-bounded schema literal. */
1056
+ max_literal_nodes: 512
1057
+ });
1058
+
1059
+ // packages/ceal-client-protocol/src/operation-json-schema.ts
1060
+ var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1061
+
1062
+ // packages/ceal-client-protocol/src/operation-contract-validation.ts
1063
+ var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
1064
+ var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
1065
+ var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
1066
+ var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
1067
+
1068
+ // packages/ceal-client-protocol/src/operation-catalog.ts
1069
+ var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
1070
+ var CLIENT_AUDIENCES = Object.freeze(["ceal", "cealctl", "agent"]);
1071
+ var CLIENT_AUDIENCE_SET = new Set(CLIENT_AUDIENCES);
851
1072
 
852
1073
  // packages/ceal-client-protocol/src/schema-literals.ts
853
1074
  var CEAL_SCHEMA_LITERALS = [
@@ -876,12 +1097,12 @@ var CEAL_SCHEMA_LITERALS = [
876
1097
  "ceal.enrollment_result.v1",
877
1098
  "ceal.first_activation_causal_join.v1",
878
1099
  "ceal.gateway_announcement_policy.v1",
879
- "ceal.gateway_audit_call_detail.v1",
1100
+ CEAL_GATEWAY_AUDIT_CALL_DETAIL_SCHEMA_VERSION,
880
1101
  "ceal.gateway_audit_event.v1",
881
1102
  "ceal.gateway_audit_readback.v1",
882
1103
  "ceal.gateway_authorization_snapshot.v1",
883
1104
  "ceal.gateway_cache_origin.v1",
884
- "ceal.gateway_call_result.v1",
1105
+ CEAL_GATEWAY_CALL_RESULT_SCHEMA_VERSION,
885
1106
  CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION,
886
1107
  "ceal.gateway_connector_route_failure.v1",
887
1108
  "ceal.gateway_discovery.v1",
@@ -906,7 +1127,7 @@ var CEAL_SCHEMA_LITERALS = [
906
1127
  "ceal.host_observation.v1",
907
1128
  "ceal.host_registration_request.v1",
908
1129
  "ceal.host_registration_result.v1",
909
- "ceal.operation_descriptor.v1",
1130
+ CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
910
1131
  "ceal.operation_error.v1",
911
1132
  "ceal.operation_failure.v1",
912
1133
  "ceal.operation_failure.compact.v1",
@@ -1011,10 +1232,20 @@ var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
1011
1232
  var CEAL_OPAQUE_HANDLE_KINDS = vocabulary(["target", "message", "thread", "artifact", "document", "block", "object"]);
1012
1233
  var CEAL_OPAQUE_REF_KINDS = vocabulary([...CEAL_OPAQUE_HANDLE_KINDS, "result", "operation-receipt", "reply-receipt", "field", "notion-data-source"]);
1013
1234
 
1235
+ // packages/ceal-client-protocol/src/client-environment-generated.ts
1236
+ var CEAL_CLIENT_CONTEXT_OVERRIDE_ENVIRONMENTS = Object.freeze(["CEAL_GATEWAY_ORIGIN", "CEAL_GATEWAY_TRANSPORT_ORIGIN", "CEAL_ACCESS_TOKEN", "CEAL_CONTEXT_STORE_PATH"]);
1237
+
1238
+ // packages/ceal-client-protocol/src/client-process-contract.ts
1239
+ var CEAL_CLIENT_VERSION_SCHEMA_SUFFIX = ".version.v1";
1240
+ var CEAL_CLIENT_VERSION_SCHEMA_VERSION = `ceal${CEAL_CLIENT_VERSION_SCHEMA_SUFFIX}`;
1241
+
1014
1242
  // packages/ceal-client-protocol/src/bare-document.ts
1015
1243
  var REQUIRED_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_fields;
1016
1244
  var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_optional_fields;
1017
1245
 
1246
+ // packages/ceal-client-protocol/src/actor-kind.ts
1247
+ var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
1248
+
1018
1249
  // packages/ceal-client-protocol/src/resource-row.ts
1019
1250
  var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
1020
1251
  var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
@@ -1029,6 +1260,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1029
1260
  "resource_created",
1030
1261
  "review_submitted",
1031
1262
  "comment_created",
1263
+ "reaction_created",
1264
+ "ceal_write_completed",
1032
1265
  "event_start",
1033
1266
  "all_day_start",
1034
1267
  "file_created",
@@ -1063,6 +1296,10 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1063
1296
  "github.review.submitted",
1064
1297
  "github.issue_comment.created",
1065
1298
  "github.review_comment.created",
1299
+ "github.reaction.created",
1300
+ "github.reaction.deleted",
1301
+ "github.pull_request.review_requested",
1302
+ "github.pull_request.review_request_removed",
1066
1303
  "calendar.organized",
1067
1304
  "calendar.accepted_invite",
1068
1305
  "calendar.recorded",
@@ -1084,6 +1321,10 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1084
1321
  "github.pull_request.opened": "resource_created",
1085
1322
  "github.issue.edited": "resource_modified",
1086
1323
  "github.pull_request.edited": "resource_modified",
1324
+ "github.reaction.created": "reaction_created",
1325
+ "github.reaction.deleted": "ceal_write_completed",
1326
+ "github.pull_request.review_requested": "ceal_write_completed",
1327
+ "github.pull_request.review_request_removed": "ceal_write_completed",
1087
1328
  "calendar.organized": "resource_created",
1088
1329
  "drive.file.created": "file_created",
1089
1330
  "drive.file.modified": "file_modified_by_me",
@@ -1107,6 +1348,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1107
1348
  source_url: { required: false, timestamp: false },
1108
1349
  source: { required: true, timestamp: false },
1109
1350
  owner: { required: false, timestamp: false },
1351
+ actor_kind: { required: false, timestamp: false },
1110
1352
  counterparts: { required: false, timestamp: false },
1111
1353
  attachments: { required: false, timestamp: false },
1112
1354
  created_at: { required: false, timestamp: true },
@@ -1114,9 +1356,18 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
1114
1356
  modified_at: { required: false, timestamp: true },
1115
1357
  modified_at_local: { required: false, timestamp: true },
1116
1358
  viewed_by_me_at: { required: false, timestamp: true },
1359
+ modified_by_me_at: { required: false, timestamp: true },
1117
1360
  own_ceal_write: { required: false, timestamp: false },
1118
1361
  owned_by_me: { required: false, timestamp: false },
1362
+ mime_type: { required: false, timestamp: false },
1363
+ size_bytes: { required: false, timestamp: false },
1364
+ version: { required: false, timestamp: false },
1365
+ trashed: { required: false, timestamp: false },
1119
1366
  visibility: { required: false, timestamp: false },
1367
+ archived: { required: false, timestamp: false },
1368
+ tag: { required: false, timestamp: false },
1369
+ labels: { required: false, timestamp: false },
1370
+ labels_incomplete: { required: false, timestamp: false },
1120
1371
  start: { required: false, timestamp: false },
1121
1372
  end: { required: false, timestamp: false },
1122
1373
  status: { required: false, timestamp: false },
@@ -1189,18 +1440,29 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1189
1440
  // The serving gate answers this while the Gateway is still starting and the
1190
1441
  // refresh was never attempted; the same attempt stays retryable. It is never
1191
1442
  // stored by the session owner, only answered at the serving edge.
1192
- "gateway_starting"
1443
+ CEAL_GATEWAY_STARTING_FAILURE_CODE
1444
+ ]);
1445
+ var CEAL_CLIENT_REVOKE_FAILURE_CODES = vocabulary([
1446
+ "refresh_invalid",
1447
+ "refresh_expired",
1448
+ "refresh_replayed",
1449
+ "refresh_revoked"
1193
1450
  ]);
1451
+ var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX = "ceal_personal_";
1452
+ var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX = "ceal_refresh_";
1453
+ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
1454
+ var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1455
+ var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
1194
1456
 
1195
1457
  // packages/ceal-client-protocol/src/request-validation-primitives.ts
1196
- import { createHash as createHash2 } from "node:crypto";
1458
+ import { createHash as createHash3 } from "node:crypto";
1197
1459
  var DIGEST = /^[a-f0-9]{64}$/u;
1198
1460
  var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
1199
1461
  function isCealDigest(value) {
1200
1462
  return typeof value === "string" && DIGEST.test(value);
1201
1463
  }
1202
1464
  function cealRequestSha256(value) {
1203
- return createHash2("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1465
+ return createHash3("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
1204
1466
  }
1205
1467
  function operationRecord(value, message) {
1206
1468
  requireOperationRecord(value, message);
@@ -1216,40 +1478,71 @@ function requirePrefixedRef(value, prefix, message) {
1216
1478
  // packages/ceal-client-protocol/src/request-authority.ts
1217
1479
  var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
1218
1480
  var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
1219
- var CEAL_REQUEST_HOST_BINDING_KEYS = vocabulary(["prompt_ref", "host_session_ref", "host_turn_ref", "host_source_ref"]);
1481
+ var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
1220
1482
  var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
1221
1483
  var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
1222
- var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority", "prompt_ref", "host_session_ref", "host_turn_ref", "host_source_ref"]);
1484
+ var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
1485
+ var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
1486
+ schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1487
+ ceal_request_ref: { type: "string", minLength: 1, maxLength: 128, pattern: "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$" },
1488
+ created_at: { type: "string", minLength: 1, maxLength: 64 },
1489
+ authority: {
1490
+ type: "object",
1491
+ maxProperties: 5,
1492
+ additionalProperties: false,
1493
+ properties: {
1494
+ instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1495
+ access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1496
+ principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1497
+ execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1498
+ authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1499
+ },
1500
+ required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1501
+ }
1502
+ });
1503
+ var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
1504
+ prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1505
+ host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1506
+ host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1507
+ host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1508
+ host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1509
+ });
1510
+ var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
1511
+ caller_call_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Gateway-minted call-group identity for a non-Host caller." },
1512
+ caller_call_input_sha256: { type: "string", minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$", description: "Commitment to the exact input for active non-Host identity-reuse checks; a migrated legacy call group commits to its legacy group key because the original input may no longer exist." }
1513
+ });
1514
+ var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
1515
+ requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1516
+ device_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Device that submitted this Request through its client session, including Host turns when the authenticated Host registration carries the device; absent for older records." }
1517
+ });
1518
+ var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
1519
+ var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
1223
1520
  var CEAL_REQUEST_JSON_SCHEMA = {
1224
1521
  type: "object",
1225
- maxProperties: 11,
1522
+ description: "A Request has exactly one creation identity: the complete Host tuple and prompt reference, or a caller call-group identity. Caller Requests retain no prompt reference or prompt body.",
1523
+ maxProperties: 13,
1226
1524
  additionalProperties: false,
1227
1525
  properties: {
1228
- schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
1229
- ceal_request_ref: { type: "string", minLength: 1, maxLength: 128, pattern: "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$" },
1230
- created_at: { type: "string", minLength: 1, maxLength: 64 },
1231
- authority: {
1526
+ ...CEAL_REQUEST_COMMON_PROPERTIES,
1527
+ ...CEAL_REQUEST_HOST_PROPERTIES,
1528
+ ...CEAL_REQUEST_CALLER_PROPERTIES,
1529
+ ...CEAL_REQUEST_OPTIONAL_PROPERTIES
1530
+ },
1531
+ required: CEAL_REQUEST_KEYS,
1532
+ anyOf: [
1533
+ {
1232
1534
  type: "object",
1233
- maxProperties: 5,
1234
- additionalProperties: false,
1235
- properties: {
1236
- instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1237
- access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1238
- principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1239
- execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1240
- authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
1241
- },
1242
- required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
1535
+ required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
1536
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1537
+ additionalProperties: false
1243
1538
  },
1244
- prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1245
- host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1246
- host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1247
- host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1248
- host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
1249
- requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
1250
- device_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Device that submitted this Request through its client session; absent for Host turns and older records." }
1251
- },
1252
- required: CEAL_REQUEST_KEYS
1539
+ {
1540
+ type: "object",
1541
+ required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
1542
+ properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
1543
+ additionalProperties: false
1544
+ }
1545
+ ]
1253
1546
  };
1254
1547
 
1255
1548
  // packages/ceal-client-protocol/src/request-operands.ts
@@ -1360,16 +1653,12 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
1360
1653
  };
1361
1654
 
1362
1655
  // packages/ceal-client-protocol/src/host-observation.ts
1363
- var CEAL_HOST_INPUT_KINDS = vocabulary(["human", "host_automatic"]);
1364
- function isCealHostInputKind(value) {
1365
- return typeof value === "string" && CEAL_HOST_INPUT_KINDS.some((kind) => kind === value);
1366
- }
1367
1656
  var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
1368
1657
  var HOST_OBSERVATION_PRODUCER = /^[a-z][a-z0-9]{0,31}$/u;
1369
1658
  var HOST_OBSERVATION_DIGEST = /^[a-f0-9]{8,64}$/u;
1370
- function cealHostObservationRef(producer, digest2) {
1371
- if (!HOST_OBSERVATION_PRODUCER.test(producer) || !HOST_OBSERVATION_DIGEST.test(digest2)) invalid("Ceal Host observation reference parts are invalid.");
1372
- return `${CEAL_HOST_OBSERVATION_REF_PREFIX}${producer}-${digest2}`;
1659
+ function cealHostObservationRef(producer, digest) {
1660
+ if (!HOST_OBSERVATION_PRODUCER.test(producer) || !HOST_OBSERVATION_DIGEST.test(digest)) invalid("Ceal Host observation reference parts are invalid.");
1661
+ return `${CEAL_HOST_OBSERVATION_REF_PREFIX}${producer}-${digest}`;
1373
1662
  }
1374
1663
  var HOST_TOKEN_OBSERVATION_BREAKDOWN_KEYS = vocabulary(["cached_input", "cache_write_input", "reasoning_output"]);
1375
1664
  function createHostTokenObservationValue(counts, source) {
@@ -1409,14 +1698,14 @@ function safeCount(value) {
1409
1698
  return Number.isSafeInteger(value) && Number(value) >= 0;
1410
1699
  }
1411
1700
  function validateCealHostObservationDraft(value) {
1412
- const record5 = operationRecord(value, "Ceal Host observation draft is invalid.");
1413
- requirePrefixedRef(record5.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1414
- requireClosedValue(record5.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1415
- requireIsoTimestamp(record5.observed_at, "Ceal Host observation time is invalid.");
1416
- assertHostObservationValue(record5.value, record5.observation_kind);
1701
+ const record4 = operationRecord(value, "Ceal Host observation draft is invalid.");
1702
+ requirePrefixedRef(record4.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
1703
+ requireClosedValue(record4.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
1704
+ requireIsoTimestamp(record4.observed_at, "Ceal Host observation time is invalid.");
1705
+ assertHostObservationValue(record4.value, record4.observation_kind);
1417
1706
  }
1418
1707
  var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
1419
- var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "cost", "timing"]);
1708
+ var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
1420
1709
  function isCealHostPromptObservationValue(value) {
1421
1710
  return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
1422
1711
  }
@@ -1539,16 +1828,41 @@ var CEAL_REQUEST_GRAPH_NODE_PREPARE_READINESS_JSON_SCHEMA = {
1539
1828
  };
1540
1829
 
1541
1830
  // packages/ceal-client-protocol/src/host-invocation-authentication.ts
1542
- var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = "ceal.host_invocation_authentication_result.v1";
1543
- var CEAL_HOST_NONCE_ENCODED_CHARACTERS = 43;
1544
- var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(`^[A-Za-z0-9_-]{${CEAL_HOST_NONCE_ENCODED_CHARACTERS}}$`, "u");
1545
- var CEAL_HOST_CONTEXT_TOKEN_PATTERN = new RegExp(`^ceal_context_[A-Za-z0-9_-]{${CEAL_HOST_NONCE_ENCODED_CHARACTERS}}$`, "u");
1546
- var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_MAX_BYTES = new TextEncoder().encode(`${JSON.stringify({
1547
- schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA,
1548
- context_token: `ceal_context_${"A".repeat(CEAL_HOST_NONCE_ENCODED_CHARACTERS)}`,
1549
- expires_at: (/* @__PURE__ */ new Date("+010000-01-01T00:00:00.000Z")).toISOString()
1550
- })}
1831
+ var hostInvocationAuthenticationContract = CEAL_CLIENT_WIRE_CONTRACT.host_invocation_authentication;
1832
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.request_schema_name, fields: hostInvocationAuthenticationContract.request_fields });
1833
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
1834
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
1835
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
1836
+ var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
1837
+ var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
1838
+ var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
1839
+ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
1840
+ var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
1841
+ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1842
+ const clientNonce = contract.host_invocation_authentication.client_nonce;
1843
+ return {
1844
+ encoded_characters: clientNonce.encoded_characters,
1845
+ client_nonce_pattern_source: `^[${clientNonce.character_class_source}]{${clientNonce.encoded_characters}}$`,
1846
+ context_token_pattern_source: `^${CEAL_HOST_CONTEXT_TOKEN_PREFIX}[${clientNonce.character_class_source}]{${clientNonce.encoded_characters}}$`
1847
+ };
1848
+ }
1849
+ var hostNonceContract = deriveCealHostInvocationNonceContract();
1850
+ var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
1851
+ var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
1852
+ var CEAL_HOST_CONTEXT_TOKEN_PATTERN = new RegExp(hostNonceContract.context_token_pattern_source, "u");
1853
+ var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_MAX_BYTES = deriveCealHostInvocationAuthenticationResultMaxBytes();
1854
+ function deriveCealHostInvocationAuthenticationResultMaxBytes(contract = CEAL_CLIENT_WIRE_CONTRACT) {
1855
+ const hostAuthentication = contract.host_invocation_authentication;
1856
+ const values = {
1857
+ schema_version: deriveCealClientWireSchemaVersion({ schema_name: hostAuthentication.result_schema_name, fields: hostAuthentication.result_fields }),
1858
+ context_token: `${CEAL_HOST_CONTEXT_TOKEN_PREFIX}${"A".repeat(hostAuthentication.client_nonce.encoded_characters)}`,
1859
+ expires_at: (/* @__PURE__ */ new Date("+010000-01-01T00:00:00.000Z")).toISOString()
1860
+ };
1861
+ const fields = hostAuthentication.result_fields;
1862
+ if (fields.some((field) => !Object.hasOwn(values, field))) throw new TypeError("Host invocation result fields have no bounded sample value.");
1863
+ return new TextEncoder().encode(`${JSON.stringify(Object.fromEntries(fields.map((field) => [field, values[field]])))}
1551
1864
  `).byteLength;
1865
+ }
1552
1866
  var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
1553
1867
  "request_authority_unavailable",
1554
1868
  "request_missing",
@@ -1572,6 +1886,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
1572
1886
  "host_credential_refused",
1573
1887
  "gateway_unavailable",
1574
1888
  "gateway_rate_limited",
1889
+ "contract_mismatch",
1575
1890
  "gateway_refused",
1576
1891
  "gateway_response_invalid",
1577
1892
  "producer_frame_invalid",
@@ -1586,19 +1901,23 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
1586
1901
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
1587
1902
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
1588
1903
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1589
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "refresh_host_invocation_context", remedy: "the Host has no invocation context from the current transcript turn; send a new message to start a fresh Host turn, then retry this command on that turn (run `ceal-host install` only if the Host hook registration is missing or drifted)" }),
1590
- context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "refresh_host_invocation_context" }),
1591
- no_binding: Object.freeze({ classification: "host_binding_unavailable", next_action: "refresh_host_invocation_context" }),
1592
- context_stale: Object.freeze({ classification: "host_invocation_context_stale", next_action: "refresh_host_invocation_context" }),
1593
- context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "refresh_host_invocation_context" }),
1904
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
1905
+ context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1906
+ // `no_binding` now means the producer has no real current Host session. The
1907
+ // Host Relay never uses it for an uncreated Gateway Request; there is no
1908
+ // useful retry until the consumer is running inside a Host session.
1909
+ no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
1910
+ context_stale: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
1911
+ context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
1594
1912
  host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
1595
1913
  host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
1596
1914
  gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
1597
1915
  gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
1916
+ contract_mismatch: Object.freeze({ classification: "contract_mismatch", next_action: "upgrade_ceal_client" }),
1598
1917
  gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
1599
1918
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
1600
- producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin", remedy: "ask an administrator to inspect and repair the producer frame, then start a fresh Host turn" }),
1601
- relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox", remedy: "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" }),
1919
+ producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
1920
+ relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
1602
1921
  relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
1603
1922
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
1604
1923
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
@@ -1613,10 +1932,6 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
1613
1932
  "hook_invoked",
1614
1933
  "registration_written",
1615
1934
  "hook_failed",
1616
- "watcher_turn_observed",
1617
- "current_prompt_registered",
1618
- "current_prompt_registration_failed",
1619
- "current_prompt_capacity_exhausted",
1620
1935
  "activation_recorded",
1621
1936
  "activation_failed",
1622
1937
  "watcher_scan_failed",
@@ -1639,6 +1954,9 @@ var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "un
1639
1954
  var REQUIRED_FIELDS2 = Object.freeze(["schema_version", "operation_id", "path", "sha256"]);
1640
1955
  var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "items_path", "row_count", "result_complete", "coverage", "local_result_root", "model_disclosure", "continue_argv", "how_to_read"]);
1641
1956
 
1957
+ // packages/ceal-client-protocol/src/discovery-manifest.ts
1958
+ var DISCOVERY_MANIFEST_KEYS = CEAL_CLIENT_WIRE_CONTRACT.command_response.discovery_manifest_fields;
1959
+
1642
1960
  // packages/ceal-client-protocol/src/gateway-cache-origin-validation.ts
1643
1961
  var CEAL_MAX_CACHE_ORIGIN_AGE_MS = 30 * 24 * 60 * 60 * 1e3;
1644
1962
 
@@ -1697,6 +2015,7 @@ var ADMIN_UNAVAILABLE_REASONS = vocabulary([
1697
2015
  "legacy",
1698
2016
  "invalid_observation",
1699
2017
  "redacted",
2018
+ "organization_setting_disabled",
1700
2019
  "owner_unavailable",
1701
2020
  "unit_unknown",
1702
2021
  "retention_gap",
@@ -1726,15 +2045,13 @@ var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
1726
2045
  var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
1727
2046
  var ADMIN_LINEAGE_NODE_KINDS = vocabulary(["source_read", "synthesis_preview", "approval", "effect", "readback"]);
1728
2047
 
1729
- // packages/ceal-client-protocol/src/actor-kind.ts
1730
- var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
1731
-
1732
2048
  // packages/ceal-client-protocol/src/device-enrollment.ts
1733
2049
  var CEAL_DEVICE_ENROLLMENT_POLL_FAILURE_CODES = Object.freeze(["unsupported_feature", "recovery_required", "expired", "denied"]);
1734
2050
  var POLL_RESULT_KEYS = Object.freeze(["retry_after_ms", "schema_version", "status"]);
1735
2051
 
1736
2052
  // packages/ceal-client-protocol/src/personal-client-session.ts
1737
2053
  var REFRESH_FAILURE_CODES = new Set(CEAL_REFRESH_FAILURE_CODES);
2054
+ var REVOKE_FAILURE_CODES = new Set(CEAL_CLIENT_REVOKE_FAILURE_CODES);
1738
2055
 
1739
2056
  // packages/ceal-client-protocol/src/index.ts
1740
2057
  var MAX_REQUEST_BYTES = 32 * 1024;
@@ -1757,6 +2074,125 @@ function waitForAbort(signal, milliseconds) {
1757
2074
  });
1758
2075
  }
1759
2076
 
2077
+ // host/secure-file.ts
2078
+ import { execFile } from "node:child_process";
2079
+ import { constants } from "node:fs";
2080
+ import { lstat, open } from "node:fs/promises";
2081
+ import { dirname, win32 as win323 } from "node:path";
2082
+ import { fileURLToPath } from "node:url";
2083
+ var SecureFileCustodyError = class extends Error {
2084
+ name = "SecureFileCustodyError";
2085
+ reason;
2086
+ constructor(reason, message) {
2087
+ super(message);
2088
+ this.reason = reason;
2089
+ }
2090
+ get code() {
2091
+ if (this.reason === "reparse_point") return "ELOOP";
2092
+ if (this.reason === "not_found") return "ENOENT";
2093
+ if (this.reason === "too_large") return "secure_file_too_large";
2094
+ if (this.reason === "already_exists") return "EEXIST";
2095
+ return this.reason === "not_private" ? "secure_file_not_private" : "secure_file_unavailable";
2096
+ }
2097
+ };
2098
+ var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
2099
+ var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
2100
+ var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
2101
+ function secureOpenFlags(flags, platform) {
2102
+ if (platform === "win32") return flags;
2103
+ const nofollow = constants.O_NOFOLLOW;
2104
+ if (typeof nofollow === "number" && nofollow !== 0) return flags | nofollow;
2105
+ throw new Error("Secure file reads require O_NOFOLLOW on this platform.");
2106
+ }
2107
+ async function openNoFollow(path, flags = constants.O_RDONLY, mode, platform = process.platform, _custody = {}) {
2108
+ if (platform !== "win32") return await open(path, secureOpenFlags(flags, platform), mode);
2109
+ return await openWindowsIdentityScreened(path, flags, mode);
2110
+ }
2111
+ async function openWindowsIdentityScreened(path, flags, mode) {
2112
+ const handle = await open(path, flags, mode);
2113
+ try {
2114
+ const first = await handle.stat();
2115
+ if (!first.isFile()) throw new SecureFileCustodyError("not_private", "The Windows Host file is not a regular file.");
2116
+ await assertWindowsLinkFree(path, first);
2117
+ await assertWindowsIdentityStable(handle, first, path);
2118
+ return handle;
2119
+ } catch (error) {
2120
+ await handle.close();
2121
+ throw error;
2122
+ }
2123
+ }
2124
+ async function assertWindowsLinkFree(path, first) {
2125
+ const entry = await lstat(path);
2126
+ if (entry.isSymbolicLink() || entry.dev !== first.dev || entry.ino !== first.ino) {
2127
+ throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
2128
+ }
2129
+ }
2130
+ async function assertWindowsIdentityStable(handle, first, path) {
2131
+ const second = await handle.stat();
2132
+ if (second.dev !== first.dev || second.ino !== first.ino || second.size !== first.size || second.mtimeMs !== first.mtimeMs) {
2133
+ throw new SecureFileCustodyError("unavailable", "The Windows Host file changed while its identity was checked.");
2134
+ }
2135
+ const entry = await lstat(path);
2136
+ if (entry.isSymbolicLink()) throw new SecureFileCustodyError("reparse_point", "The Windows Host file path resolves through a reparse point.");
2137
+ if (entry.dev !== second.dev || entry.ino !== second.ino) throw new SecureFileCustodyError("unavailable", "The Windows Host file path no longer names the opened file.");
2138
+ }
2139
+ async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
2140
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
2141
+ const result = await runWindowsSecurefs(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
2142
+ if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
2143
+ if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
2144
+ if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
2145
+ throw securefsRefusal(result.stderr);
2146
+ }
2147
+ async function runWindowsSecurefs(args, maxBytes, custody) {
2148
+ if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args);
2149
+ const executable = custody.securefs_executable ?? resolveInstalledHostExecutable();
2150
+ const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2151
+ return await new Promise((resolve, reject) => {
2152
+ execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
2153
+ const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2154
+ if (exitCode === null) {
2155
+ reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
2156
+ return;
2157
+ }
2158
+ resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
2159
+ });
2160
+ });
2161
+ }
2162
+ function securefsRefusal(stderr) {
2163
+ let value;
2164
+ try {
2165
+ value = JSON.parse(stderr.toString("utf8"));
2166
+ } catch {
2167
+ return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
2168
+ }
2169
+ if (!isRecord(value) || value.schema_version !== WINDOWS_SECUREFS_REFUSAL_SCHEMA || typeof value.code !== "string") return new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an unreadable refusal.");
2170
+ if (value.code === "reparse_point") return new SecureFileCustodyError("reparse_point", "The Windows Host securefs file is a reparse point.");
2171
+ if (value.code === "not_found") return new SecureFileCustodyError("not_found", "The Windows Host securefs file was not found.");
2172
+ if (value.code === "too_large") return new SecureFileCustodyError("too_large", "The Windows Host securefs file exceeds its read bound.");
2173
+ if (value.code === "already_exists") return new SecureFileCustodyError("already_exists", "The Windows Host securefs target already exists.");
2174
+ if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
2175
+ return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
2176
+ }
2177
+ function resolveInstalledHostExecutable() {
2178
+ const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2179
+ return win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
2180
+ }
2181
+ function isRecord(value) {
2182
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2183
+ }
2184
+ function isOwnedBy(uid, expectedUid) {
2185
+ return Number.isSafeInteger(uid) && Number.isSafeInteger(expectedUid) && uid === expectedUid;
2186
+ }
2187
+ function isSelfOwned(uid, platform = process.platform, _handle) {
2188
+ if (platform === "win32" || typeof process.geteuid !== "function") return false;
2189
+ return isOwnedBy(uid, process.geteuid());
2190
+ }
2191
+ function isPrivateFileMode(mode, platform = process.platform, _handle) {
2192
+ if (platform === "win32") return false;
2193
+ return (mode & 63) === 0;
2194
+ }
2195
+
1760
2196
  // host/producer-service.ts
1761
2197
  var SAFE_REF2 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
1762
2198
  var HOST_PRODUCER_SERVE_COMMAND_PREFIX = ["serve", "--config"];
@@ -1769,18 +2205,19 @@ var HostProducerServiceError = class extends Error {
1769
2205
  }
1770
2206
  };
1771
2207
  var HOST_PRODUCER_CONFIG_KEYS = ["schema_version", "host_source_ref", "producer_installation_ref", "producer_epoch", "outbox_dir", "relay_endpoint"];
2208
+ var HOST_PRODUCER_CONFIG_ENDPOINT_KEY = "relay_endpoint";
1772
2209
  var HOST_PRODUCER_TIMING_DEFAULTS = Object.freeze({ reconcile_interval_ms: 250, retry_backoff_ms: 1e3, ipc_timeout_ms: 5e3 });
1773
2210
  function hostProducerExtraPath(extras, key) {
1774
2211
  const value = extras[key];
1775
- if (value === void 0) throw hostProducerError("invalid_config");
2212
+ if (value === void 0) throw hostProducerError("invalid_config", refusalFact(key, "missing", "an absolute path"));
1776
2213
  return value;
1777
2214
  }
1778
2215
  function parseHostProducerServeArgs(args, platform = process.platform) {
1779
2216
  return parseProducerServeArgs(args, platform, hostProducerError);
1780
2217
  }
1781
- async function readHostProducerConfig(descriptor, configPath, platform = process.platform) {
1782
- const config = decodeHostProducerConfigText(descriptor, await readProducerConfigText(configPath, platform, hostProducerError), platform);
1783
- const path = platform === "win32" ? win323 : posix3;
2218
+ async function readHostProducerConfig(descriptor, configPath, platform = process.platform, custody = {}) {
2219
+ const config = decodeHostProducerConfigText(descriptor, await readProducerConfigText(configPath, platform, hostProducerError, custody), platform);
2220
+ const path = platform === "win32" ? win324 : posix3;
1784
2221
  const root = path.resolve(config.outbox_dir, "../../../../..");
1785
2222
  try {
1786
2223
  assertHostProducerSourcePaths(root, config, descriptor.producer_id, platform);
@@ -1809,15 +2246,31 @@ function parseProducerServeArgs(args, platform, error) {
1809
2246
  assertProducerAbsolutePath(args[2], platform, "config", error);
1810
2247
  return args[2];
1811
2248
  }
1812
- async function readProducerConfigText(configPath, platform, error) {
1813
- assertProducerAbsolutePath(configPath, platform, "config", error);
2249
+ async function readProducerConfigText(configPath, platform, error, custody) {
2250
+ assertProducerAbsolutePath(configPath, process.platform, "config", error);
2251
+ if (platform === "win32") {
2252
+ let bytes;
2253
+ try {
2254
+ bytes = await readPrivateFileWithSecurefs(configPath, CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES, custody);
2255
+ } catch (cause) {
2256
+ if (cause instanceof SecureFileCustodyError && cause.reason === "not_private") throw error("config_not_private");
2257
+ if (cause instanceof SecureFileCustodyError && cause.reason === "too_large") throw error("invalid_config", refusalFact("config_bytes", "over_limit", `at most ${CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES}`));
2258
+ if (cause instanceof SecureFileCustodyError && cause.reason === "reparse_point") throw error("invalid_config");
2259
+ throw error("config_unavailable");
2260
+ }
2261
+ if (bytes.byteLength === 0) throw error("invalid_config", refusalFact("config_bytes", 0, `between 1 and ${CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES}`));
2262
+ try {
2263
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2264
+ } catch {
2265
+ throw error("invalid_config");
2266
+ }
2267
+ }
1814
2268
  const pathStat = await configPathStat(configPath, error);
1815
2269
  validateConfigFile(pathStat, platform, error);
1816
- const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
1817
- const handle = await openConfigFile(configPath, constants.O_RDONLY | noFollow, error);
2270
+ const handle = await openConfigFile(configPath, platform, error, custody);
1818
2271
  try {
1819
2272
  const opened = await handle.stat();
1820
- validateConfigFile(opened, platform, error);
2273
+ validateConfigFile(opened, platform, error, handle);
1821
2274
  validateOpenedFile(opened, pathStat, platform, error);
1822
2275
  return await readBoundedConfig(handle, opened.size, error);
1823
2276
  } finally {
@@ -1825,8 +2278,9 @@ async function readProducerConfigText(configPath, platform, error) {
1825
2278
  }
1826
2279
  }
1827
2280
  function decodeProducerConfigCore(text, options) {
2281
+ const ownership = producerConfigKeyOwnership(options.keys, options.platform);
1828
2282
  const value = parseCanonicalJson(text, options.error);
1829
- if (!isRecord(value) || !hasConfigKeys(value, options.keys) || value.schema_version !== options.schema) throw options.error("invalid_config");
2283
+ if (!isRecord2(value) || !hasConfigKeys(value, ownership.required, ownership.tolerated) || value.schema_version !== options.schema) throw options.error("invalid_config", refusalFacts(producerShapeFacts(value, { schema: options.schema, keys: ownership.required, tolerated: ownership.tolerated })));
1830
2284
  const hostSourceRef = typeof value.host_source_ref === "string" ? value.host_source_ref : "";
1831
2285
  const installationRef = typeof value.producer_installation_ref === "string" ? value.producer_installation_ref : "";
1832
2286
  const producerEpoch = validateIdentity(hostSourceRef, installationRef, value.producer_epoch, options.error);
@@ -1844,7 +2298,7 @@ function decodeProducerConfigCore(text, options) {
1844
2298
  producer_installation_ref: installationRef,
1845
2299
  producer_epoch: producerEpoch,
1846
2300
  outbox_dir: value.outbox_dir,
1847
- relay_endpoint: value.relay_endpoint,
2301
+ relay_endpoint: producerConfigEndpoint(value),
1848
2302
  reconcile_interval_ms: intervals[0],
1849
2303
  retry_backoff_ms: intervals[1],
1850
2304
  ipc_timeout_ms: intervals[2]
@@ -1861,8 +2315,15 @@ async function serveProducer(runtimeOptions, timing, signal, drain, wait = (mill
1861
2315
  if (!signal.aborted) await wait(delay, signal);
1862
2316
  }
1863
2317
  }
2318
+ function producerConfigKeyOwnership(keys, platform) {
2319
+ if (platform !== "win32") return { required: keys, tolerated: [] };
2320
+ return { required: keys.filter((key) => key !== HOST_PRODUCER_CONFIG_ENDPOINT_KEY), tolerated: [HOST_PRODUCER_CONFIG_ENDPOINT_KEY] };
2321
+ }
2322
+ function producerConfigEndpoint(value) {
2323
+ return typeof value.relay_endpoint === "string" ? value.relay_endpoint : "";
2324
+ }
1864
2325
  function assertProducerRelayEndpoint(value, platform, error) {
1865
- if (platform === "win32" && typeof value === "string" && /^\\\\\.\\pipe\\[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(value)) return;
2326
+ if (platform === "win32") return;
1866
2327
  assertProducerAbsolutePath(value, platform, "runtime", error);
1867
2328
  }
1868
2329
  function assertProducerAbsolutePath(value, platform, kind, error) {
@@ -1870,26 +2331,27 @@ function assertProducerAbsolutePath(value, platform, kind, error) {
1870
2331
  }
1871
2332
  async function configPathStat(configPath, error) {
1872
2333
  try {
1873
- return await lstat(configPath);
2334
+ return await lstat2(configPath);
1874
2335
  } catch {
1875
2336
  throw error("config_unavailable");
1876
2337
  }
1877
2338
  }
1878
- function validateConfigFile(value, platform, error) {
2339
+ function validateConfigFile(value, platform, error, handle) {
1879
2340
  if (!value.isFile() || value.isSymbolicLink()) throw error("invalid_config", refusalFacts([{ name: "config_is_file", value: value.isFile(), expected: "true" }, { name: "config_is_symlink", value: value.isSymbolicLink(), expected: "false" }]));
1880
2341
  if (value.size <= 0 || value.size > CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES) throw error("invalid_config", refusalFact("config_bytes", value.size, `between 1 and ${CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES}`));
1881
- if (platform !== "win32" && (value.uid !== process.getuid?.() || (value.mode & 63) !== 0)) throw error("config_not_private", refusalFacts([{ name: "platform", value: platform, expected: "win32 or owner-private" }, { name: "config_uid", value: value.uid, expected: "the current user" }, { name: "config_mode", value: value.mode, expected: "owner-private" }]));
2342
+ if (!isSelfOwned(value.uid, platform, handle) || !isPrivateFileMode(value.mode, platform, handle)) throw error("config_not_private", refusalFacts([{ name: "platform", value: platform, expected: "a platform with verifiable owner and private-mode facts" }, { name: "config_uid", value: value.uid, expected: "the current user" }, { name: "config_mode", value: value.mode, expected: "private to its owner" }]));
1882
2343
  }
1883
- async function openConfigFile(configPath, flags, error) {
2344
+ async function openConfigFile(configPath, platform, error, custody) {
1884
2345
  try {
1885
- return await open(configPath, flags);
1886
- } catch {
2346
+ return await openNoFollow(configPath, constants2.O_RDONLY, void 0, platform, custody);
2347
+ } catch (error_) {
2348
+ if (error_ instanceof SecureFileCustodyError) throw error(error_.reason === "not_private" ? "config_not_private" : "invalid_config");
1887
2349
  throw error("config_unavailable");
1888
2350
  }
1889
2351
  }
1890
2352
  function validateOpenedFile(opened, pathStat, platform, error) {
1891
2353
  if (!opened.isFile()) throw error("config_unavailable", refusalFacts([{ name: "opened_is_file", value: opened.isFile(), expected: "true" }, { name: "opened_mode", value: opened.mode.toString(8), expected: "a regular file mode" }]));
1892
- if (platform !== "win32" && (opened.dev !== pathStat.dev || opened.ino !== pathStat.ino)) throw error("config_unavailable", refusalFacts([{ name: "platform", value: platform, expected: "win32, or the same file the path named" }, { name: "opened_device", value: opened.dev, expected: String(pathStat.dev) }, { name: "opened_inode", value: opened.ino, expected: String(pathStat.ino) }]));
2354
+ if (opened.dev !== pathStat.dev || opened.ino !== pathStat.ino) throw error("config_unavailable", refusalFacts([{ name: "platform", value: platform, expected: "the same file the path named" }, { name: "opened_device", value: opened.dev, expected: String(pathStat.dev) }, { name: "opened_inode", value: opened.ino, expected: String(pathStat.ino) }]));
1893
2355
  }
1894
2356
  async function readBoundedConfig(handle, expectedBytes, error) {
1895
2357
  const buffer = Buffer.allocUnsafe(expectedBytes + 1);
@@ -1921,18 +2383,43 @@ function firstDifferenceIndex(left, right) {
1921
2383
  for (let index = 0; index < shared; index += 1) if (left[index] !== right[index]) return index;
1922
2384
  return shared;
1923
2385
  }
2386
+ function producerShapeFacts(value, options) {
2387
+ if (!isRecord2(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
2388
+ const tolerated = options.tolerated ?? [];
2389
+ const allowed = [...options.keys, ...tolerated, ...Object.keys(HOST_PRODUCER_TIMING_DEFAULTS)];
2390
+ const facts = [
2391
+ ...Object.keys(value).filter((key) => !allowed.includes(key)).map((key) => ({ name: key, value: "unknown", expected: `one of ${[...options.keys, ...tolerated].join(", ")}` })),
2392
+ ...options.keys.filter((key) => !Object.hasOwn(value, key)).map((key) => ({ name: key, value: "missing", expected: "present" }))
2393
+ ];
2394
+ if (Object.hasOwn(value, "schema_version") && value.schema_version !== options.schema) facts.push({ name: "schema_version", value: "wrong_type", expected: options.schema });
2395
+ return facts;
2396
+ }
1924
2397
  function validateIdentity(sourceRef, installationRef, epoch, error) {
1925
- if (!SAFE_REF2.test(sourceRef) || !SAFE_REF2.test(installationRef) || !positive(epoch, 2147483647)) throw error("invalid_config");
2398
+ if (!SAFE_REF2.test(sourceRef) || !SAFE_REF2.test(installationRef) || !positive(epoch, 2147483647)) throw error("invalid_config", refusalFacts(producerIdentityFacts(sourceRef, installationRef, epoch)));
1926
2399
  return epoch;
1927
2400
  }
2401
+ function producerIdentityFacts(sourceRef, installationRef, epoch) {
2402
+ const facts = [];
2403
+ if (!SAFE_REF2.test(sourceRef)) facts.push({ name: "host_source_ref", value: "wrong_type", expected: "a safe reference" });
2404
+ if (!SAFE_REF2.test(installationRef)) facts.push({ name: "producer_installation_ref", value: "wrong_type", expected: "a safe reference" });
2405
+ if (!positive(epoch, 2147483647)) facts.push({ name: "producer_epoch", value: "wrong_type", expected: "a positive integer" });
2406
+ return facts;
2407
+ }
1928
2408
  function validateIntervals(reconcile, retry, timeout, error) {
1929
- if (!boundedMilliseconds(reconcile) || !boundedMilliseconds(retry) || !boundedMilliseconds(timeout)) throw error("invalid_config");
2409
+ if (!boundedMilliseconds(reconcile) || !boundedMilliseconds(retry) || !boundedMilliseconds(timeout)) throw error("invalid_config", refusalFacts(producerIntervalFacts(reconcile, retry, timeout)));
1930
2410
  return [reconcile, retry, timeout];
1931
2411
  }
1932
- function hasConfigKeys(value, required) {
1933
- return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || Object.hasOwn(HOST_PRODUCER_TIMING_DEFAULTS, key));
2412
+ function producerIntervalFacts(reconcile, retry, timeout) {
2413
+ const facts = [];
2414
+ if (!boundedMilliseconds(reconcile)) facts.push({ name: "reconcile_interval_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
2415
+ if (!boundedMilliseconds(retry)) facts.push({ name: "retry_backoff_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
2416
+ if (!boundedMilliseconds(timeout)) facts.push({ name: "ipc_timeout_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
2417
+ return facts;
1934
2418
  }
1935
- function isRecord(value) {
2419
+ function hasConfigKeys(value, required, tolerated = []) {
2420
+ return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || tolerated.includes(key) || Object.hasOwn(HOST_PRODUCER_TIMING_DEFAULTS, key));
2421
+ }
2422
+ function isRecord2(value) {
1936
2423
  return value !== null && typeof value === "object" && !Array.isArray(value);
1937
2424
  }
1938
2425
  function positive(value, maximum) {
@@ -1942,557 +2429,115 @@ function boundedMilliseconds(value) {
1942
2429
  return positive(value, 6e4) && Number(value) >= 25;
1943
2430
  }
1944
2431
 
1945
- // host/relay/src/producer-frame.ts
1946
- var HOST_PRODUCER_FRAME_SCHEMA = "ceal.host_producer_frame.v1";
1947
- var HOST_PRODUCER_MAX_JSON_BYTES = 262144;
1948
- var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
1949
- var SAFE_REF3 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
1950
- var PRODUCERS = /* @__PURE__ */ new Set(["codex", "claude"]);
1951
- var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "user_input", "turn_terminal", "producer_status"];
1952
- var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
1953
- function isHostProducerFrameKind(value) {
1954
- return typeof value === "string" && FRAME_KINDS.has(value);
1955
- }
1956
- var HOST_PRODUCER_FRAME_ERROR_CODES = [
1957
- "invalid_frame_encoding",
1958
- "invalid_frame_length",
1959
- "frame_truncated",
1960
- "unsupported_frame_schema",
1961
- "invalid_frame_shape",
1962
- "invalid_producer_identity",
1963
- "frame_too_large"
1964
- ];
1965
- var HostProducerFrameError = class extends Error {
1966
- code;
1967
- constructor(code2, message = code2) {
1968
- super(message);
1969
- this.code = code2;
2432
+ // host/service-log.ts
2433
+ import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
2434
+ import { dirname as dirname2, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
2435
+ var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
2436
+ var HOST_SERVICE_LOG_ARGUMENT = "--ceal-host-service-log";
2437
+ var HostServiceLogArgumentError = class extends Error {
2438
+ constructor() {
2439
+ super("The Host service log argument must occur once with an absolute normalized path.");
2440
+ this.name = "HostServiceLogArgumentError";
1970
2441
  }
1971
2442
  };
1972
- function encodeHostProducerFrame(frame) {
1973
- validateFrame(frame);
1974
- const json = Buffer.from(JSON.stringify(frame), "utf8");
1975
- if (json.byteLength > HOST_PRODUCER_MAX_JSON_BYTES) throw new HostProducerFrameError("frame_too_large", `frame_too_large: ${refusalFact("frame_bytes", json.byteLength, `at most ${HOST_PRODUCER_MAX_JSON_BYTES}`)}`);
1976
- const result = Buffer.allocUnsafe(json.byteLength + HOST_PRODUCER_FRAME_LENGTH_BYTES);
1977
- result.writeUInt32BE(json.byteLength, 0);
1978
- json.copy(result, HOST_PRODUCER_FRAME_LENGTH_BYTES);
1979
- return result;
1980
- }
1981
- function decodeHostProducerFrame(input) {
1982
- if (input.byteLength < HOST_PRODUCER_FRAME_LENGTH_BYTES) throw new HostProducerFrameError("frame_truncated", `frame_truncated: ${refusalFact("frame_bytes", input.byteLength, `at least ${HOST_PRODUCER_FRAME_LENGTH_BYTES}`)}`);
1983
- const length = input.readUInt32BE(0);
1984
- if (length > HOST_PRODUCER_MAX_JSON_BYTES) throw new HostProducerFrameError("frame_too_large", `frame_too_large: ${refusalFact("declared_bytes", length, `at most ${HOST_PRODUCER_MAX_JSON_BYTES}`)}`);
1985
- if (length === 0) throw new HostProducerFrameError("invalid_frame_length");
1986
- if (input.byteLength !== length + HOST_PRODUCER_FRAME_LENGTH_BYTES) throw new HostProducerFrameError(input.byteLength < length + HOST_PRODUCER_FRAME_LENGTH_BYTES ? "frame_truncated" : "invalid_frame_length");
1987
- const bytes = input.subarray(HOST_PRODUCER_FRAME_LENGTH_BYTES);
1988
- const text = new TextDecoder("utf-8", { fatal: true });
1989
- let value;
2443
+ function consumeHostServiceLogArgument(args, platform = process.platform) {
2444
+ const indexes = args.flatMap((value, index2) => value === HOST_SERVICE_LOG_ARGUMENT ? [index2] : []);
2445
+ if (indexes.length === 0) return { args: [...args] };
2446
+ const index = indexes[0];
2447
+ if (index === void 0) throw new HostServiceLogArgumentError();
2448
+ const path = args[index + 1];
2449
+ const pathApi = platform === "win32" ? win325 : posix4;
2450
+ if (indexes.length !== 1 || path === void 0 || !pathApi.isAbsolute(path) || pathApi.normalize(path) !== path) throw new HostServiceLogArgumentError();
2451
+ return { args: [...args.slice(0, index), ...args.slice(index + 2)], path };
2452
+ }
2453
+ function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
2454
+ const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...event === "watcher_scan_failed" && failure_kind !== void 0 ? { failure_kind } : {}, ...event === "watcher_scan_failed" && cause !== void 0 ? { cause } : {} })}
2455
+ `;
1990
2456
  try {
1991
- value = JSON.parse(text.decode(bytes));
1992
- } catch (error) {
1993
- if (error instanceof TypeError) throw new HostProducerFrameError("invalid_frame_encoding");
1994
- throw new HostProducerFrameError("frame_truncated");
2457
+ (sink ?? defaultHostServiceDiagnosticSink)(line);
2458
+ } catch {
1995
2459
  }
1996
- validateFrame(value);
1997
- return value;
1998
- }
1999
- function isHostSafeRef(value) {
2000
- return safeRef(value);
2001
- }
2002
- function validateFrame(value) {
2003
- if (!record(value)) throw new HostProducerFrameError("invalid_frame_shape");
2004
- if (value.schema_version !== HOST_PRODUCER_FRAME_SCHEMA) throw new HostProducerFrameError("unsupported_frame_schema", `unsupported_frame_schema: ${refusalFact("schema_version", value.schema_version, HOST_PRODUCER_FRAME_SCHEMA)}`);
2005
- if (!exactKeys(value, ["schema_version", "producer_id", "producer_installation_ref", "producer_epoch", "sequence", "frame_kind", "occurred_at", "payload"])) throw new HostProducerFrameError("invalid_frame_shape");
2006
- if (!PRODUCERS.has(String(value.producer_id)) || !safeRef(value.producer_installation_ref)) throw new HostProducerFrameError("invalid_producer_identity");
2007
- if (!positive2(value.producer_epoch) || !positive2(value.sequence) || !hostProducerFrameKind(value.frame_kind) || !timestamp(value.occurred_at) || !record(value.payload)) throw new HostProducerFrameError("invalid_frame_shape");
2008
- validatePayload(value.frame_kind, value.payload);
2009
- }
2010
- function validatePayload(kind, value) {
2011
- const valid = kind === "session_started" ? validSession(value) : kind === "turn_started" ? validTurn(value) : kind === "user_input" ? validInput(value) : kind === "turn_terminal" ? validTerminal(value) : validStatus(value);
2012
- if (!valid) throw new HostProducerFrameError("invalid_frame_shape");
2013
- }
2014
- function validSession(value) {
2015
- return exactOptional(value, ["local_session_ref", "working_directory_ref"], ["model", "host_version", "observations"]) && safeRef(value.local_session_ref) && safeRef(value.working_directory_ref) && optionalText(value.model, 256) && optionalText(value.host_version, 256) && validObservations(value.observations);
2016
2460
  }
2017
- function validTurn(value) {
2018
- return exactOptional(value, ["local_session_ref", "local_turn_ref"], ["model", "observations"]) && safeRef(value.local_session_ref) && safeRef(value.local_turn_ref) && optionalText(value.model, 256) && validObservations(value.observations);
2019
- }
2020
- function validInput(value) {
2021
- return exactOptional(value, ["local_session_ref", "local_turn_ref", "local_input_ref", "input_kind", "origin_input", "observations"], ["local_turn_aliases", "context_expires_at"]) && safeRef(value.local_session_ref) && safeRef(value.local_turn_ref) && safeRef(value.local_input_ref) && validInputObservations(value.observations) && isCealHostInputKind(value.input_kind) && typeof value.origin_input === "boolean" && validInputOptionals(value);
2461
+ function defaultHostServiceDiagnosticSink(line) {
2462
+ writeHostServiceLogLine(line);
2463
+ process.stderr.write(line);
2022
2464
  }
2023
- function validInputObservations(value) {
2024
- return validObservations(value) && Array.isArray(value) && value.filter((item) => record(item) && item.observation_kind === "prompt").length === 1;
2465
+ var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
2466
+ var HOST_SERVICE_LOG_CHECK_INTERVAL_MS = 6e4;
2467
+ function hostServiceLogPreviousPath(path) {
2468
+ return `${path}.1`;
2025
2469
  }
2026
- function validInputOptionals(value) {
2027
- return optionalRefs(value.local_turn_aliases) && (value.context_expires_at === void 0 || timestamp(value.context_expires_at));
2470
+ async function rotateHostServiceLog(path, maxBytes = HOST_SERVICE_LOG_MAX_BYTES) {
2471
+ let size;
2472
+ try {
2473
+ size = (await stat(path)).size;
2474
+ } catch (error) {
2475
+ if (isNotFound(error)) return false;
2476
+ throw error;
2477
+ }
2478
+ if (size <= maxBytes) return false;
2479
+ await copyFile(path, hostServiceLogPreviousPath(path));
2480
+ await truncate(path, 0);
2481
+ return true;
2028
2482
  }
2029
- function validTerminal(value) {
2030
- return exactOptional(value, ["local_session_ref", "local_turn_ref", "terminal_state"], ["abort_reason", "duration_ms", "time_to_first_token_ms", "usage", "observations"]) && safeRef(value.local_session_ref) && safeRef(value.local_turn_ref) && validTerminalDisposition(value.terminal_state, value.abort_reason) && optionalNonNegative(value.duration_ms) && optionalNonNegative(value.time_to_first_token_ms) && (value.usage === void 0 || jsonValue(value.usage)) && validObservations(value.observations);
2483
+ function boundHostServiceLog(environment = process.env) {
2484
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
2485
+ if (path === void 0 || !isAbsolute(path)) return () => void 0;
2486
+ let reported = false;
2487
+ const ready = ensureHostServiceLogDirectory(path);
2488
+ const check = () => {
2489
+ ready.then(() => rotateHostServiceLog(path)).catch((error) => {
2490
+ if (reported) return;
2491
+ reported = true;
2492
+ process.stderr.write(`[host-service-log] rotation_failed code=${errorCode(error)}
2493
+ `);
2494
+ });
2495
+ };
2496
+ check();
2497
+ const timer = setInterval(check, HOST_SERVICE_LOG_CHECK_INTERVAL_MS);
2498
+ timer.unref();
2499
+ return () => clearInterval(timer);
2031
2500
  }
2032
- function validTerminalDisposition(state, reason) {
2033
- return (state === "completed" || state === "aborted") && (reason === void 0 || state === "aborted" && safeRef(reason));
2501
+ function writeHostServiceLogLine(line, environment = process.env) {
2502
+ if (process.platform !== "win32") return;
2503
+ const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
2504
+ if (path === void 0 || !win325.isAbsolute(path) || win325.normalize(path) !== path) return;
2505
+ void appendHostServiceLogLine(path, line).catch(() => void 0);
2034
2506
  }
2035
- function validStatus(value) {
2036
- return exactOptional(value, ["status", "reason_code"], ["detail"]) && ["ready", "degraded", "stopping"].includes(String(value.status)) && safeRef(value.reason_code) && optionalText(value.detail, 4096);
2507
+ async function appendHostServiceLogLine(path, line) {
2508
+ if (!isAbsolute(path)) return;
2509
+ await ensureHostServiceLogDirectory(path);
2510
+ await appendFile(path, line);
2037
2511
  }
2038
- function optionalText(value, maxLength) {
2039
- return value === void 0 || typeof value === "string" && value.length > 0 && value.length <= maxLength;
2512
+ var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
2513
+ var hostServiceLogDirectories = /* @__PURE__ */ new Map();
2514
+ function ensureHostServiceLogDirectory(path) {
2515
+ const directory = dirname2(path);
2516
+ const existing = hostServiceLogDirectories.get(directory);
2517
+ if (existing !== void 0) return existing;
2518
+ const pending = mkdir(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
2519
+ hostServiceLogDirectories.delete(directory);
2520
+ throw error;
2521
+ });
2522
+ hostServiceLogDirectories.set(directory, pending);
2523
+ return pending;
2040
2524
  }
2041
- function optionalNonNegative(value) {
2042
- return value === void 0 || typeof value === "number" && Number.isFinite(value) && value >= 0;
2525
+ function isNotFound(error) {
2526
+ return errorCode(error) === "ENOENT";
2043
2527
  }
2044
- function optionalRefs(value) {
2045
- return value === void 0 || Array.isArray(value) && value.length <= 16 && value.every(safeRef);
2046
- }
2047
- function validObservations(value) {
2048
- if (value === void 0) return true;
2049
- if (!Array.isArray(value) || value.length > 32) return false;
2050
- return value.every((item) => {
2051
- try {
2052
- validateCealHostObservationDraft(item);
2053
- return true;
2054
- } catch {
2055
- return false;
2056
- }
2057
- });
2058
- }
2059
- function jsonValue(value, depth = 0) {
2060
- if (depth > 16) return false;
2061
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
2062
- if (typeof value === "number") return Number.isFinite(value);
2063
- if (Array.isArray(value)) return value.length <= 256 && value.every((item) => jsonValue(item, depth + 1));
2064
- return record(value) && Object.keys(value).length <= 256 && Object.entries(value).every(([key, item]) => key.length > 0 && key.length <= 128 && jsonValue(item, depth + 1));
2065
- }
2066
- function record(value) {
2067
- return value !== null && typeof value === "object" && !Array.isArray(value);
2068
- }
2069
- function safeRef(value) {
2070
- return typeof value === "string" && SAFE_REF3.test(value);
2071
- }
2072
- function positive2(value) {
2073
- return Number.isSafeInteger(value) && Number(value) > 0;
2074
- }
2075
- function timestamp(value) {
2076
- return typeof value === "string" && Number.isFinite(Date.parse(value));
2077
- }
2078
- function hostProducerFrameKind(value) {
2079
- return isHostProducerFrameKind(value);
2080
- }
2081
- function exactKeys(value, keys) {
2082
- return JSON.stringify(Object.keys(value).sort()) === JSON.stringify([...keys].sort());
2083
- }
2084
- function exactOptional(value, required, optional) {
2085
- const keys = Object.keys(value);
2086
- return required.every((key) => keys.includes(key)) && keys.every((key) => required.includes(key) || optional.includes(key));
2087
- }
2088
-
2089
- // host/relay/src/host-producer-core.ts
2090
- import { createHash as createHash3 } from "node:crypto";
2091
- import { O_NOFOLLOW, O_RDONLY as O_RDONLY2 } from "node:constants";
2092
- import { mkdir as mkdir2, open as open4, readFile, rename as rename2, writeFile } from "node:fs/promises";
2093
- import { join as join2 } from "node:path";
2094
-
2095
- // host/relay/src/relay-ipc.ts
2096
- import { createConnection, createServer } from "node:net";
2097
-
2098
- // host/relay/src/durable-atomic-replacement.ts
2099
- import { O_RDONLY } from "node:constants";
2100
- import { lstat as lstat2, mkdir, open as open2, rename, unlink } from "node:fs/promises";
2101
- import { dirname } from "node:path";
2102
- var DEFAULT_PORT = {
2103
- platform: process.platform,
2104
- mkdir: (path, options) => mkdir(path, options),
2105
- lstat: (path) => lstat2(path),
2106
- open_file: (path) => open2(path, "wx", 384),
2107
- rename,
2108
- unlink,
2109
- open_directory: (path) => open2(path, O_RDONLY),
2110
- unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
2111
- };
2112
- async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
2113
- const parent = dirname(target);
2114
- await port.mkdir(parent, { recursive: true, mode: 448 });
2115
- const parentStats = await port.lstat(parent);
2116
- if (!parentStats.isDirectory() || parentStats.isSymbolicLink() || !ownerPrivate(parentStats, port.platform)) throw new TypeError(`Host Relay durable-state directory is unsafe: ${refusalFacts([{ name: "parent_stats", value: parentStats, expected: "an owner-private directory" }, { name: "platform", value: port.platform }])}.`);
2117
- const temporary = `${target}.${port.unique_ref()}.new`;
2118
- let staged;
2119
- const failures = [];
2120
- try {
2121
- staged = await port.open_file(temporary);
2122
- await staged.writeFile(data, typeof data === "string" ? { encoding: "utf8" } : void 0);
2123
- await staged.sync();
2124
- const closing = staged;
2125
- staged = void 0;
2126
- await closing.close();
2127
- await port.rename(temporary, target);
2128
- await syncParentDirectory(parent, port);
2129
- } catch (error) {
2130
- failures.push(error);
2131
- }
2132
- await closeStaged(staged, failures);
2133
- await removeTemporary(temporary, port, failures);
2134
- throwFailures(failures);
2135
- }
2136
- async function syncParentDirectory(path, port) {
2137
- if (port.platform === "win32") return;
2138
- const handle = await port.open_directory(path);
2139
- let failure;
2140
- try {
2141
- await handle.sync();
2142
- } catch (error) {
2143
- if (!directorySyncUnsupported(error)) failure = error;
2144
- }
2145
- try {
2146
- await handle.close();
2147
- } catch (error) {
2148
- if (failure === void 0) failure = error;
2149
- else failure = new AggregateError([failure, error], "Host Relay directory sync and close failed.");
2150
- }
2151
- if (failure !== void 0) throw failure;
2152
- }
2153
- function ownerPrivate(stats, platform) {
2154
- if (platform === "win32") return true;
2155
- const uid = typeof process.geteuid === "function" ? process.geteuid() : stats.uid;
2156
- return stats.uid === uid && (stats.mode & 63) === 0;
2157
- }
2158
- async function closeStaged(staged, failures) {
2159
- if (staged !== void 0) try {
2160
- await staged.close();
2161
- } catch (error) {
2162
- failures.push(error);
2163
- }
2164
- }
2165
- async function removeTemporary(path, port, failures) {
2166
- try {
2167
- await port.unlink(path);
2168
- } catch (error) {
2169
- if (errorCode(error) !== "ENOENT") failures.push(error);
2170
- }
2171
- }
2172
- function throwFailures(failures) {
2173
- if (failures.length === 1) throw failures[0];
2174
- if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
2175
- }
2176
- function directorySyncUnsupported(error) {
2177
- return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
2178
- }
2179
- function errorCode(error) {
2180
- return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
2181
- }
2182
-
2183
- // host/relay/src/relay-request-binding-store.ts
2184
- var MAX_STATE_BYTES = 8 * 1024 * 1024;
2185
-
2186
- // host/relay/src/current-prompt-custody.ts
2187
- var HOST_CURRENT_PROMPT_MAX_BYTES = 256 * 1024;
2188
-
2189
- // host/service-log.ts
2190
- import { copyFile, open as open3, stat, truncate } from "node:fs/promises";
2191
- import { isAbsolute } from "node:path";
2192
- var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
2193
- function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
2194
- const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...event === "watcher_scan_failed" && failure_kind !== void 0 ? { failure_kind } : {}, ...event === "watcher_scan_failed" && cause !== void 0 ? { cause } : {} })}
2195
- `;
2196
- try {
2197
- (sink ?? defaultHostServiceDiagnosticSink)(line);
2198
- } catch {
2199
- }
2200
- }
2201
- function defaultHostServiceDiagnosticSink(line) {
2202
- process.stderr.write(line);
2203
- }
2204
- var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
2205
- var HOST_SERVICE_LOG_CHECK_INTERVAL_MS = 6e4;
2206
- function hostServiceLogPreviousPath(path) {
2207
- return `${path}.1`;
2208
- }
2209
- async function rotateHostServiceLog(path, maxBytes = HOST_SERVICE_LOG_MAX_BYTES) {
2210
- let size;
2211
- try {
2212
- size = (await stat(path)).size;
2213
- } catch (error) {
2214
- if (isNotFound(error)) return false;
2215
- throw error;
2216
- }
2217
- if (size <= maxBytes) return false;
2218
- await copyFile(path, hostServiceLogPreviousPath(path));
2219
- await truncate(path, 0);
2220
- return true;
2221
- }
2222
- function boundHostServiceLog(environment = process.env) {
2223
- const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
2224
- if (path === void 0 || !isAbsolute(path)) return () => void 0;
2225
- let reported = false;
2226
- const check = () => {
2227
- rotateHostServiceLog(path).catch((error) => {
2228
- if (reported) return;
2229
- reported = true;
2230
- process.stderr.write(`[host-service-log] rotation_failed code=${errorCode2(error)}
2231
- `);
2232
- });
2233
- };
2234
- check();
2235
- const timer = setInterval(check, HOST_SERVICE_LOG_CHECK_INTERVAL_MS);
2236
- timer.unref();
2237
- return () => clearInterval(timer);
2238
- }
2239
- var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
2240
- function isNotFound(error) {
2241
- return errorCode2(error) === "ENOENT";
2242
- }
2243
- function errorCode2(error) {
2244
- return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unknown";
2245
- }
2246
-
2247
- // host/relay/src/relay-ipc.ts
2248
- var HOST_RELAY_REQUEST_BINDING_KEYS = Object.freeze([
2249
- "schema_version",
2250
- "producer_id",
2251
- "producer_installation_ref",
2252
- "local_session_ref",
2253
- "local_turn_ref",
2254
- "local_turn_aliases",
2255
- "prompt_ref",
2256
- "request_ref",
2257
- "bound_at",
2258
- "host_source_ref",
2259
- "host_session_ref",
2260
- "host_turn_ref",
2261
- "host_input_ref"
2262
- ]);
2263
- var HOST_RELAY_IPC_RESPONSE_SCHEMA = "ceal.host_relay_admission.v1";
2264
- var HOST_RELAY_CURRENT_PROMPT_REGISTER_SCHEMA = "ceal.host_relay_current_prompt_register.v1";
2265
- var HOST_RELAY_CURRENT_PROMPT_RELEASE_SCHEMA = "ceal.host_relay_current_prompt_release.v1";
2266
- var HOST_RELAY_CURRENT_PROMPT_RESULT_SCHEMA = "ceal.host_relay_current_prompt_result.v1";
2267
- var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2268
- var HOST_RELAY_ADMISSION_RESPONSE_MAX_BYTES = 4096;
2269
- var HOST_RELAY_INVOCATION_MINT_REFUSAL_REASONS = vocabulary([
2270
- "context_stale",
2271
- "context_expired",
2272
- "host_source_refused",
2273
- "host_credential_refused",
2274
- "gateway_unavailable",
2275
- "gateway_refused",
2276
- "gateway_response_invalid",
2277
- "gateway_rate_limited",
2278
- "producer_frame_invalid",
2279
- "deadline",
2280
- "cancelled",
2281
- "mint_failed",
2282
- "relay_failed",
2283
- "request_authority_unavailable",
2284
- "request_missing",
2285
- "authority_mismatch",
2286
- "host_source_mismatch",
2287
- "host_session_mismatch",
2288
- "host_turn_mismatch",
2289
- "host_input_mismatch",
2290
- "host_prompt_mismatch"
2291
- ]);
2292
- var HOST_RELAY_DIRECT_WIRE_MINT_REASONS = vocabulary([
2293
- "context_stale",
2294
- "context_expired",
2295
- "host_source_refused",
2296
- "host_credential_refused",
2297
- "gateway_unavailable",
2298
- "gateway_rate_limited",
2299
- "gateway_refused",
2300
- "gateway_response_invalid",
2301
- "producer_frame_invalid"
2302
- ]);
2303
- var HOST_RELAY_INVOCATION_MINT_OUTCOMES = vocabulary(["completed", "caller_cancelled", "deadline", "failed", "no_binding"]);
2304
- var HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2305
- "permission_denied",
2306
- "socket_missing",
2307
- "connection_refused",
2308
- "closed_early",
2309
- "response_invalid",
2310
- "timed_out",
2311
- "cancelled",
2312
- "unavailable"
2313
- ]);
2314
- var HostRelayIpcError = class extends Error {
2315
- code;
2316
- /** Set only when the client-side socket exchange itself failed. */
2317
- failure;
2318
- constructor(code2, message = code2, failure) {
2319
- super(message);
2320
- this.code = code2;
2321
- this.failure = failure;
2322
- }
2323
- };
2324
- var HostRelayCurrentPromptCapacityRefusal = class extends Error {
2325
- constructor() {
2326
- super("current_prompt_capacity_exhausted");
2327
- this.name = "HostRelayCurrentPromptCapacityRefusal";
2328
- }
2329
- };
2330
- function hostRelayExchangeFailure(error) {
2331
- return error instanceof HostRelayIpcError ? error.failure : void 0;
2332
- }
2333
- function socketErrorFailure(error) {
2334
- switch (errorCode3(error)) {
2335
- case "EACCES":
2336
- case "EPERM":
2337
- return "permission_denied";
2338
- case "ENOENT":
2339
- return "socket_missing";
2340
- case "ECONNREFUSED":
2341
- return "connection_refused";
2342
- default:
2343
- return "unavailable";
2344
- }
2345
- }
2346
- var HostRelayIpcAdmissionPort = class {
2347
- endpoint;
2348
- timeout_ms;
2349
- constructor(endpoint, timeoutMs = 5e3) {
2350
- this.endpoint = endpoint;
2351
- this.timeout_ms = timeoutMs;
2352
- }
2353
- async admit(frame) {
2354
- const response2 = await submitHostProducerFrame(this.endpoint, frame, this.timeout_ms);
2355
- if (!relayAdmissionCode(response2.code)) throw new HostRelayIpcError(response2.code);
2356
- return { code: response2.code, admitted_through_sequence: response2.admitted_through_sequence, delivered_through_sequence: response2.delivered_through_sequence };
2357
- }
2358
- };
2359
- var HostRelayCurrentPromptPort = class {
2360
- endpoint;
2361
- timeout_ms;
2362
- constructor(endpoint, timeoutMs = 5e3) {
2363
- this.endpoint = endpoint;
2364
- this.timeout_ms = timeoutMs;
2365
- }
2366
- async register(input) {
2367
- const request2 = { schema_version: HOST_RELAY_CURRENT_PROMPT_REGISTER_SCHEMA, ...input };
2368
- const response2 = await exchange(this.endpoint, encodeLengthPrefixed(request2), this.timeout_ms, decodeCurrentPromptResponseBuffer);
2369
- if (response2.status === "capacity_exhausted") throw new HostRelayCurrentPromptCapacityRefusal();
2370
- if (response2.status !== "registered") throw new HostRelayIpcError("relay_unavailable", response2.status);
2371
- }
2372
- async release(identity) {
2373
- const request2 = { schema_version: HOST_RELAY_CURRENT_PROMPT_RELEASE_SCHEMA, ...identity };
2374
- const response2 = await exchange(this.endpoint, encodeLengthPrefixed(request2), this.timeout_ms, decodeCurrentPromptResponseBuffer);
2375
- if (response2.status !== "released") throw new HostRelayIpcError("relay_unavailable", response2.status, "response_invalid");
2376
- }
2377
- };
2378
- function submitHostProducerFrame(endpoint, frame, timeoutMs = 5e3) {
2379
- return exchange(endpoint, encodeHostProducerFrame(frame), timeoutMs, decodeResponseBuffer);
2380
- }
2381
- function exchange(endpoint, encoded, timeoutMs, decode, signal) {
2382
- return new Promise((resolve, reject) => {
2383
- const socket = createConnection(endpoint);
2384
- let buffer = Buffer.alloc(0);
2385
- let settled = false;
2386
- const aborted = () => finish(new HostRelayIpcError("relay_unavailable", "Host Relay IPC was cancelled.", "cancelled"));
2387
- const finish = (error, response2) => {
2388
- if (settled) return;
2389
- settled = true;
2390
- signal?.removeEventListener("abort", aborted);
2391
- socket.destroy();
2392
- if (error !== null) reject(error);
2393
- else if (response2 !== void 0) resolve(response2);
2394
- };
2395
- if (timeoutMs !== void 0) socket.setTimeout(timeoutMs, () => finish(new HostRelayIpcError("relay_unavailable", "Host Relay IPC timed out.", "timed_out")));
2396
- if (signal?.aborted === true) {
2397
- aborted();
2398
- return;
2399
- }
2400
- signal?.addEventListener("abort", aborted, { once: true });
2401
- socket.once("error", (error) => {
2402
- const failure = socketErrorFailure(error);
2403
- finish(new HostRelayIpcError("relay_unavailable", `Host Relay IPC is unavailable: ${failure}.`, failure));
2404
- });
2405
- socket.once("connect", () => socket.write(encoded));
2406
- socket.on("data", (chunk) => {
2407
- try {
2408
- buffer = Buffer.concat([buffer, Buffer.from(chunk)]);
2409
- const decoded = decode(buffer);
2410
- if (decoded !== null) finish(null, decoded);
2411
- } catch (error) {
2412
- finish(new HostRelayIpcError("relay_unavailable", error instanceof Error ? error.message : "Host Relay IPC response is invalid.", "response_invalid"));
2413
- }
2414
- });
2415
- socket.once("end", () => {
2416
- if (!settled) finish(new HostRelayIpcError("relay_unavailable", "Host Relay IPC closed without a response.", "closed_early"));
2417
- });
2418
- });
2419
- }
2420
- function decodeHostRelayIpcResponse(input) {
2421
- if (input.length < HOST_RELAY_IPC_LENGTH_BYTES) throw new HostRelayIpcError("relay_unavailable", `Host Relay IPC response is truncated: ${refusalFact("response_bytes", input.byteLength, `at least ${HOST_RELAY_IPC_LENGTH_BYTES}`)}.`);
2422
- const length = input.readUInt32BE(0);
2423
- if (length === 0 || length > HOST_RELAY_ADMISSION_RESPONSE_MAX_BYTES || input.length !== length + HOST_RELAY_IPC_LENGTH_BYTES) throw new HostRelayIpcError("relay_unavailable", `Host Relay IPC response length is invalid: ${refusalFacts([{ name: "declared_bytes", value: length, expected: `between 1 and ${HOST_RELAY_ADMISSION_RESPONSE_MAX_BYTES}` }, { name: "received_bytes", value: input.byteLength, expected: `exactly ${length + HOST_RELAY_IPC_LENGTH_BYTES}` }])}.`);
2424
- let value;
2425
- try {
2426
- value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(input.subarray(HOST_RELAY_IPC_LENGTH_BYTES)));
2427
- } catch {
2428
- throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC response is invalid.");
2429
- }
2430
- if (!validResponse(value)) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC response shape is invalid.");
2431
- return value;
2432
- }
2433
- function relayAdmissionCode(value) {
2434
- return value === "admitted" || value === "already_admitted" || value === "producer_epoch_stale" || value === "sequence_gap" || value === "frame_identity_conflict" || value === "producer_queue_full" || value === "relay_queue_full" || value === "producer_already_connected" || value === "invalid_producer_identity";
2435
- }
2436
- function validResponse(value) {
2437
- return record2(value) && value.schema_version === HOST_RELAY_IPC_RESPONSE_SCHEMA && hostRelayIpcCode(value.code) && nonnegative(value.admitted_through_sequence) && nonnegative(value.delivered_through_sequence) && Object.keys(value).length === 4;
2438
- }
2439
- function hostRelayIpcCode(value) {
2440
- return typeof value === "string" && ["admitted", "already_admitted", "producer_epoch_stale", "sequence_gap", "frame_identity_conflict", "producer_queue_full", "relay_queue_full", "invalid_frame_encoding", "invalid_frame_length", "frame_truncated", "unsupported_frame_schema", "invalid_frame_shape", "invalid_producer_identity", "frame_too_large", "producer_already_connected", "relay_unavailable"].includes(value);
2441
- }
2442
- function nonnegative(value) {
2443
- return Number.isSafeInteger(value) && Number(value) >= 0;
2444
- }
2445
- function record2(value) {
2446
- return value !== null && typeof value === "object" && !Array.isArray(value);
2447
- }
2448
- function decodeResponseBuffer(buffer) {
2449
- if (buffer.length < HOST_RELAY_IPC_LENGTH_BYTES) return null;
2450
- const length = buffer.readUInt32BE(0);
2451
- if (length === 0 || length > HOST_RELAY_ADMISSION_RESPONSE_MAX_BYTES) throw new HostRelayIpcError("relay_unavailable", `Host Relay IPC response length is invalid: ${refusalFact("declared_bytes", length, `between 1 and ${HOST_RELAY_ADMISSION_RESPONSE_MAX_BYTES}`)}.`);
2452
- if (buffer.length < length + HOST_RELAY_IPC_LENGTH_BYTES) return null;
2453
- if (buffer.length !== length + HOST_RELAY_IPC_LENGTH_BYTES) throw new HostRelayIpcError("relay_unavailable", `Host Relay IPC returned trailing bytes: ${refusalFacts([{ name: "declared_bytes", value: length, expected: `the received message length minus ${HOST_RELAY_IPC_LENGTH_BYTES}` }, { name: "received_bytes", value: buffer.byteLength, expected: `exactly ${length + HOST_RELAY_IPC_LENGTH_BYTES}` }])}.`);
2454
- return decodeHostRelayIpcResponse(buffer);
2455
- }
2456
- function decodeCurrentPromptResponseBuffer(buffer) {
2457
- const value = decodeLengthPrefixedJson(buffer, HOST_RELAY_ADMISSION_RESPONSE_MAX_BYTES);
2458
- if (value === null) return null;
2459
- if (!record2(value) || !exactKeys2(value, ["schema_version", "status"]) || value.schema_version !== HOST_RELAY_CURRENT_PROMPT_RESULT_SCHEMA || value.status !== "registered" && value.status !== "capacity_exhausted" && value.status !== "current_prompt_unavailable" && value.status !== "released") throw new HostRelayIpcError("relay_unavailable", "Host Relay current-prompt response is invalid.", "response_invalid");
2460
- return { schema_version: HOST_RELAY_CURRENT_PROMPT_RESULT_SCHEMA, status: value.status };
2461
- }
2462
- function decodeLengthPrefixedJson(input, maximum) {
2463
- if (input.length < HOST_RELAY_IPC_LENGTH_BYTES) return null;
2464
- const length = input.readUInt32BE(0);
2465
- if (length === 0 || length > maximum) throw new HostRelayIpcError("relay_unavailable", `Host Relay IPC message length is invalid: ${refusalFact("declared_bytes", length, `between 1 and ${maximum}`)}.`);
2466
- if (input.length < length + HOST_RELAY_IPC_LENGTH_BYTES) return null;
2467
- if (input.length !== length + HOST_RELAY_IPC_LENGTH_BYTES) throw new HostRelayIpcError("relay_unavailable", `Host Relay IPC message has trailing bytes: ${refusalFacts([{ name: "declared_bytes", value: length, expected: `the received message length minus ${HOST_RELAY_IPC_LENGTH_BYTES}` }, { name: "received_bytes", value: input.byteLength, expected: `exactly ${length + HOST_RELAY_IPC_LENGTH_BYTES}` }])}.`);
2468
- try {
2469
- return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(input.subarray(HOST_RELAY_IPC_LENGTH_BYTES)));
2470
- } catch {
2471
- throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC message is invalid.");
2472
- }
2473
- }
2474
- function encodeLengthPrefixed(value) {
2475
- const body = Buffer.from(JSON.stringify(value), "utf8");
2476
- const output = Buffer.allocUnsafe(body.length + HOST_RELAY_IPC_LENGTH_BYTES);
2477
- output.writeUInt32BE(body.length, 0);
2478
- body.copy(output, HOST_RELAY_IPC_LENGTH_BYTES);
2479
- return output;
2480
- }
2481
- function exactKeys2(value, required, optional = []) {
2482
- const keys = Object.keys(value);
2483
- return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => required.includes(key) || optional.includes(key));
2484
- }
2485
- function errorCode3(error) {
2486
- return record2(error) && typeof error.code === "string" ? error.code : null;
2528
+ function errorCode(error) {
2529
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unknown";
2487
2530
  }
2488
2531
 
2489
2532
  // host/relay/src/host-producer-core.ts
2533
+ import { createHash as createHash4 } from "node:crypto";
2490
2534
  var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
2491
2535
  function isHostTranscriptCursorReason(value) {
2492
2536
  return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
2493
2537
  }
2494
2538
  var TRANSCRIPT_MISSING_REASON = "transcript_missing";
2495
2539
  var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
2540
+ var HOST_INVOCATION_TRANSCRIPT_TAIL_MAX_BYTES = 1024 * 1024;
2496
2541
  function transcriptScanFailureKind(error, adapterFailureKind) {
2497
2542
  if (transcriptErrorCode(error) === "ELOOP") return "symlink";
2498
2543
  const adapter = adapterFailureKind(error);
@@ -2502,16 +2547,6 @@ function transcriptScanFailureKind(error, adapterFailureKind) {
2502
2547
  if (code2 !== null && TRANSCRIPT_SCAN_READ_ERROR_ERRNOS.includes(code2)) return "read_error";
2503
2548
  return "other";
2504
2549
  }
2505
- async function registerHostCurrentPromptDiagnosed(register, diagnostic) {
2506
- try {
2507
- await register();
2508
- diagnostic("current_prompt_registered");
2509
- return true;
2510
- } catch (error) {
2511
- if (!(error instanceof HostRelayCurrentPromptCapacityRefusal)) diagnostic("current_prompt_registration_failed");
2512
- throw error;
2513
- }
2514
- }
2515
2550
  function transcriptErrorCode(error) {
2516
2551
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
2517
2552
  }
@@ -2559,10 +2594,10 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
2559
2594
  return null;
2560
2595
  }
2561
2596
  function transcriptSha256(value) {
2562
- return createHash3("sha256").update(value).digest("hex");
2597
+ return createHash4("sha256").update(value).digest("hex");
2563
2598
  }
2564
2599
  function transcriptObjectSha256(value) {
2565
- return createHash3("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2600
+ return createHash4("sha256").update(JSON.stringify(value), "utf8").digest("hex");
2566
2601
  }
2567
2602
  function isTranscriptRecord(value) {
2568
2603
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2623,24 +2658,18 @@ var HostTranscriptWatcher = class {
2623
2658
  return scanTranscriptRegistrations(await this.listRegistrations(), (registration) => this.scanRegistration(registration));
2624
2659
  }
2625
2660
  async scanRegistration(registration) {
2626
- try {
2627
- return await this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
2628
- missing: () => this.retireMissing(registration),
2629
- failed: (handle, error) => this.scanFailed(handle, registration, error)
2630
- });
2631
- } catch (error) {
2632
- if (error instanceof HostRelayCurrentPromptCapacityRefusal) return { records: 0, enqueued: 0, quarantined: false };
2633
- throw error;
2634
- }
2661
+ return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
2662
+ missing: () => this.retireMissing(registration),
2663
+ failed: (handle, error) => this.scanFailed(handle, registration, error)
2664
+ });
2635
2665
  }
2636
2666
  async openTranscript(registration, scan, handlers) {
2637
2667
  let handle;
2638
2668
  try {
2639
- handle = await open4(this.transcriptPathOf(registration), O_RDONLY2 | O_NOFOLLOW);
2669
+ handle = await openNoFollow(this.transcriptPathOf(registration));
2640
2670
  return await scan(handle);
2641
2671
  } catch (error) {
2642
2672
  if (handle === void 0 && isMissingTranscriptError(error)) return handlers.missing();
2643
- if (hostRelayExchangeFailure(error) !== void 0 || error instanceof HostRelayCurrentPromptCapacityRefusal) throw error;
2644
2673
  return handlers.failed(handle, error);
2645
2674
  } finally {
2646
2675
  await handle?.close();
@@ -2670,233 +2699,60 @@ var HostTranscriptWatcher = class {
2670
2699
  objectSha(value) {
2671
2700
  return transcriptObjectSha256(value);
2672
2701
  }
2673
- isRecord(value) {
2674
- return isTranscriptRecord(value);
2675
- }
2676
- readChunk(handle, offset, size) {
2677
- return readTranscriptCompleteChunk(handle, offset, size);
2678
- }
2679
- readAnchor(handle, offset, anchorBytes) {
2680
- return readTranscriptAnchor(handle, offset, anchorBytes);
2681
- }
2682
- cursorIdentityReason(cursor, transcriptPath, device, inode) {
2683
- return transcriptCursorIdentityReason(cursor, transcriptPath, device, inode);
2684
- }
2685
- cursorBoundsReason(handle, cursor, size) {
2686
- return transcriptCursorBoundsReason(handle, cursor, size);
2687
- }
2688
- };
2689
- var HOST_PRODUCER_STATE_IDENTITY = {
2690
- codex: { file_name: "codex-producer-state.json", schema: "ceal.codex_producer_state.v1" },
2691
- claude: { file_name: "claude-producer-state.json", schema: "ceal.claude_producer_state.v1" }
2692
- };
2693
- var HostProducerDrainCore = class {
2694
- host;
2695
- relay;
2696
- statePath;
2697
- stateSchema;
2698
- installationRef;
2699
- epoch;
2700
- now;
2701
- tail = Promise.resolve();
2702
- constructor(host, runtime) {
2703
- if (!isHostSafeRef(runtime.producer_installation_ref)) throw host.fail("configuration", `${host.producer_label} producer installation identity is invalid.`);
2704
- const epoch = runtime.producer_epoch ?? 1;
2705
- if (!Number.isSafeInteger(epoch) || epoch <= 0) throw host.fail("configuration", `${host.producer_label} producer epoch is invalid.`);
2706
- this.host = host;
2707
- this.relay = runtime.relay;
2708
- this.statePath = join2(host.outbox_directory, HOST_PRODUCER_STATE_IDENTITY[host.producer_id].file_name);
2709
- this.stateSchema = HOST_PRODUCER_STATE_IDENTITY[host.producer_id].schema;
2710
- this.installationRef = runtime.producer_installation_ref;
2711
- this.epoch = epoch;
2712
- this.now = runtime.now ?? (() => /* @__PURE__ */ new Date());
2713
- }
2714
- drainOutbox() {
2715
- const run = this.tail.then(() => this.drainLocked());
2716
- this.tail = run.then(() => void 0, () => void 0);
2717
- return run;
2718
- }
2719
- async drainLocked() {
2720
- const read = await this.host.listEnvelopes();
2721
- let admitted = 0;
2722
- let expired = 0;
2723
- let retained = 0;
2724
- for (const envelope of read.entries) {
2725
- const reserved = await this.hasReservation(this.host.submissionRefOf(envelope));
2726
- if (!reserved && Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) {
2727
- await this.host.removeEnvelope(envelope);
2728
- expired += 1;
2729
- continue;
2730
- }
2731
- const frames = await this.reserve(envelope);
2732
- let complete = true;
2733
- for (const frame of frames) {
2734
- const outcome = await this.relay.admit(frame);
2735
- if (outcome.code !== "admitted" && outcome.code !== "already_admitted") {
2736
- complete = false;
2737
- break;
2738
- }
2739
- }
2740
- if (!complete) {
2741
- retained += 1;
2742
- break;
2743
- }
2744
- await this.host.removeEnvelope(envelope);
2745
- await this.release(this.host.submissionRefOf(envelope));
2746
- admitted += 1;
2747
- }
2748
- return { admitted, retained: retained + Math.max(0, read.entries.length - admitted - expired - retained), expired, malformed: read.malformed };
2749
- }
2750
- async hasReservation(submissionRef2) {
2751
- return (await this.readState()).pending[submissionRef2] !== void 0;
2752
- }
2753
- async reserve(envelope) {
2754
- const state = await this.readState();
2755
- const submissionRef2 = this.host.submissionRefOf(envelope);
2756
- const existing = state.pending[submissionRef2];
2757
- if (existing !== void 0) return existing;
2758
- const drafts = await this.host.mapEnvelope(envelope);
2759
- const frames = drafts.map((draft, offset) => ({
2760
- schema_version: "ceal.host_producer_frame.v1",
2761
- producer_id: this.host.producer_id,
2762
- producer_installation_ref: this.installationRef,
2763
- producer_epoch: this.epoch,
2764
- sequence: state.next_sequence + offset,
2765
- frame_kind: draft.frame_kind,
2766
- occurred_at: this.host.createdAtOf(envelope),
2767
- payload: draft.payload
2768
- }));
2769
- await this.writeState({ ...state, next_sequence: state.next_sequence + frames.length, pending: { ...state.pending, [submissionRef2]: frames } });
2770
- return frames;
2771
- }
2772
- async release(submissionRef2) {
2773
- const state = await this.readState();
2774
- if (state.pending[submissionRef2] === void 0) return;
2775
- const pending = { ...state.pending };
2776
- delete pending[submissionRef2];
2777
- await this.writeState({ ...state, pending });
2778
- }
2779
- async readState() {
2780
- try {
2781
- const value = JSON.parse(await readFile(this.statePath, "utf8"));
2782
- return this.decodeState(value);
2783
- } catch (error) {
2784
- if (errorCode4(error) !== "ENOENT") throw error;
2785
- return { schema_version: this.stateSchema, producer_installation_ref: this.installationRef, producer_epoch: this.epoch, next_sequence: 1, pending: {} };
2786
- }
2787
- }
2788
- async writeState(state) {
2789
- await mkdir2(this.host.outbox_directory, { recursive: true, mode: 448 });
2790
- const temporary = `${this.statePath}.${process.pid}.new`;
2791
- await writeFile(temporary, JSON.stringify(state), { mode: 384 });
2792
- await rename2(temporary, this.statePath);
2793
- }
2794
- decodeState(value) {
2795
- const label = this.host.producer_label;
2796
- const fail = (code2, message) => this.host.fail(code2, message);
2797
- if (!isDrainStateHeader(value, this.stateSchema, this.installationRef)) {
2798
- throw fail("storage", `${label} producer state header is malformed or belongs to another installation (${refusalFacts([
2799
- { name: "schema_version", value: isTranscriptRecord(value) ? value.schema_version : void 0, expected: this.stateSchema },
2800
- { name: "producer_installation_ref", value: isTranscriptRecord(value) ? value.producer_installation_ref : void 0, expected: this.installationRef }
2801
- ])}).`);
2802
- }
2803
- if (Number(value.producer_epoch) > this.epoch) throw fail("storage", `${label} producer state epoch is ahead of this installation (${refusalFact("producer_epoch", value.producer_epoch, `at most ${this.epoch}`)}).`);
2804
- const pending = {};
2805
- const storedEpoch = Number(value.producer_epoch);
2806
- for (const [submissionRef2, frames] of Object.entries(value.pending)) {
2807
- if (!isHostSafeRef(submissionRef2) || !Array.isArray(frames) || frames.length === 0) throw fail("storage", `${label} producer pending reservation is malformed.`);
2808
- pending[submissionRef2] = frames.map((frame) => this.decodeStoredFrame(frame, storedEpoch));
2809
- }
2810
- return { schema_version: this.stateSchema, producer_installation_ref: this.installationRef, producer_epoch: this.epoch, next_sequence: Number(value.next_sequence), pending };
2811
- }
2812
- decodeStoredFrame(value, storedEpoch) {
2813
- const label = this.host.producer_label;
2814
- const json = Buffer.from(JSON.stringify(value), "utf8");
2815
- const encoded = Buffer.allocUnsafe(json.length + 4);
2816
- encoded.writeUInt32BE(json.length, 0);
2817
- json.copy(encoded, 4);
2818
- const frame = decodeHostProducerFrame(encoded);
2819
- if (frame.producer_id !== this.host.producer_id || frame.producer_installation_ref !== this.installationRef || frame.producer_epoch > storedEpoch) throw this.host.fail("storage", `${label} producer pending frame identity is malformed (${refusalFacts([
2820
- { name: "producer_id", value: frame.producer_id, expected: this.host.producer_id },
2821
- { name: "producer_installation_ref", value: frame.producer_installation_ref, expected: this.installationRef },
2822
- { name: "producer_epoch", value: frame.producer_epoch, expected: `at most ${storedEpoch}` }
2823
- ])}).`);
2824
- return frame;
2825
- }
2826
- };
2827
- function isDrainStateHeader(value, schema, installationRef) {
2828
- return isTranscriptRecord(value) && value.schema_version === schema && value.producer_installation_ref === installationRef && Number.isSafeInteger(value.producer_epoch) && Number(value.producer_epoch) > 0 && Number.isSafeInteger(value.next_sequence) && Number(value.next_sequence) > 0 && isTranscriptRecord(value.pending);
2829
- }
2830
- function errorCode4(error) {
2831
- return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
2832
- }
2833
-
2834
- // host/relay/src/relay-quarantine-store.ts
2835
- var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
2836
- var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
2837
- var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
2838
-
2839
- // host/relay/src/relay-admission-store.ts
2840
- var DEFAULT_LIMITS = { global_count: 8192, global_bytes: 64 * 1024 * 1024, producer_count: 4096, producer_bytes: 32 * 1024 * 1024 };
2841
- var RETRY_SECONDS = [1, 2, 4, 8, 16, 32, 60];
2842
- var MAX_RETRYABLE_ATTEMPTS = RETRY_SECONDS.length + 10;
2843
-
2844
- // host/claude/src/claude-decoder.ts
2845
- import { createHash as createHash4 } from "node:crypto";
2846
-
2847
- // host/claude/src/claude-types.ts
2848
- var CLAUDE_HOST_ERROR_CODES = ["invalid_input", "payload_rejected", "storage", "configuration"];
2849
- function isClaudeHostErrorCode(value) {
2850
- return typeof value === "string" && CLAUDE_HOST_ERROR_CODES.some((code2) => code2 === value);
2851
- }
2852
- var CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION = "ceal.claude_invocation_context.v1";
2853
- var CLAUDE_OUTBOX_SCHEMA_VERSION = "ceal.claude_observation_outbox.v1";
2854
- var CLAUDE_SESSION_SCHEMA_VERSION = "ceal.claude_session.v1";
2855
- var CLAUDE_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION = "ceal.claude_transcript_registration.v1";
2856
- var CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION = "ceal.claude_transcript_cursor.v1";
2857
- var CLAUDE_DEFAULT_RETENTION_MS = 24 * 60 * 60 * 1e3;
2858
- var CLAUDE_TRANSCRIPT_MAX_TURN_MESSAGES = 1024;
2859
- var CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES = 64;
2860
- var CLAUDE_TRANSCRIPT_ANCHOR_BYTES = 256;
2861
- var ClaudeHostError = class extends Error {
2862
- name = "ClaudeHostError";
2863
- code;
2864
- diagnostic_kind;
2865
- constructor(code2, message, diagnostic_kind) {
2866
- super(message);
2867
- if (!isClaudeHostErrorCode(code2)) throw new TypeError("Claude Host error code is invalid.");
2868
- this.code = code2;
2869
- this.diagnostic_kind = diagnostic_kind;
2702
+ isRecord(value) {
2703
+ return isTranscriptRecord(value);
2704
+ }
2705
+ readChunk(handle, offset, size) {
2706
+ return readTranscriptCompleteChunk(handle, offset, size);
2707
+ }
2708
+ readAnchor(handle, offset, anchorBytes) {
2709
+ return readTranscriptAnchor(handle, offset, anchorBytes);
2710
+ }
2711
+ cursorIdentityReason(cursor, transcriptPath, device, inode) {
2712
+ return transcriptCursorIdentityReason(cursor, transcriptPath, device, inode);
2713
+ }
2714
+ cursorBoundsReason(handle, cursor, size) {
2715
+ return transcriptCursorBoundsReason(handle, cursor, size);
2716
+ }
2717
+ };
2718
+ var HostProducerDrainCore = class {
2719
+ host;
2720
+ now;
2721
+ tail = Promise.resolve();
2722
+ constructor(host, runtime) {
2723
+ this.host = host;
2724
+ this.now = runtime.now ?? (() => /* @__PURE__ */ new Date());
2725
+ }
2726
+ drainOutbox() {
2727
+ const run = this.tail.then(() => this.drainLocked());
2728
+ this.tail = run.then(() => void 0, () => void 0);
2729
+ return run;
2730
+ }
2731
+ async drainLocked() {
2732
+ const read = await this.host.listEnvelopes();
2733
+ let removed = 0;
2734
+ let expired = 0;
2735
+ for (const envelope of read.entries) {
2736
+ if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
2737
+ else removed += 1;
2738
+ await this.host.removeEnvelope(envelope);
2739
+ }
2740
+ return { removed, expired, malformed: read.malformed };
2870
2741
  }
2871
2742
  };
2872
-
2873
- // host/claude/src/claude-decoder.ts
2874
- var MAX_HOOK_BYTES = 256 * 1024;
2875
- function claudeLocalTurnRef(sessionId, turnId) {
2876
- return `claude-turn:${cealRequestSha256({ session_id: sessionId, prompt_id: turnId })}`;
2877
- }
2878
- function claudeLocalInputRef(sessionId, turnId) {
2879
- return `claude-input:${cealRequestSha256({ session_id: sessionId, prompt_id: turnId })}`;
2880
- }
2881
- function claudeWorkspaceRef(cwd) {
2882
- return `workspace:${digest(cwd)}`;
2883
- }
2884
- function digest(value) {
2885
- return createHash4("sha256").update(value, "utf8").digest("hex");
2886
- }
2887
2743
 
2888
2744
  // host/claude/src/claude-outbox.ts
2889
- import { mkdir as mkdir3, readdir, readFile as readFile2, unlink as unlink2 } from "node:fs/promises";
2890
- import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
2745
+ import { mkdir as mkdir3, readdir, readFile, unlink as unlink2 } from "node:fs/promises";
2746
+ import { isAbsolute as isAbsolute2, join as join2 } from "node:path";
2891
2747
 
2892
2748
  // host/invocation-context.ts
2893
- var HOST_INVOCATION_IDENTITY_KEYS = ["host_session_ref", "host_turn_ref", "host_source_ref"];
2749
+ var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
2894
2750
  var HOST_INVOCATION_CONTEXT_REQUIRED_KEYS = ["schema_version", "identity", "prompt_ref", "expires_at"];
2895
2751
  function invocationContextKey(identity) {
2896
2752
  return cealRequestSha256({ host_source_ref: identity.host_source_ref, host_session_ref: identity.host_session_ref });
2897
2753
  }
2898
2754
  function hasHostInvocationIdentityKeys(value) {
2899
- return exactKeys3(value, HOST_INVOCATION_IDENTITY_KEYS);
2755
+ return exactKeys(value, CEAL_HOST_INVOCATION_IDENTITY_KEYS);
2900
2756
  }
2901
2757
  function hasHostInvocationContextKeys(value, optional = []) {
2902
2758
  return requiredKeys(value, HOST_INVOCATION_CONTEXT_REQUIRED_KEYS, optional);
@@ -2922,12 +2778,9 @@ function invocationContextFromTurn(identity, promptRef, expiresAt, descriptor) {
2922
2778
  return Object.freeze(context);
2923
2779
  }
2924
2780
  function isHostInvocationTurnSelection(value) {
2925
- return isRecord2(value) && Object.keys(value).length === 5 && value.schema_version === "ceal.host_invocation_turn_selection.v1" && ["host_source_ref", "host_session_ref", "prompt_ref", "turn_generation_ref"].every((key) => safeRef2(value[key]));
2781
+ return isRecord3(value) && Object.keys(value).length === 5 && value.schema_version === HOST_INVOCATION_TURN_SELECTION_SCHEMA && ["host_source_ref", "host_session_ref", "prompt_ref", "turn_generation_ref"].every((key) => safeRef(value[key]));
2926
2782
  }
2927
- function invocationTurnSelectionMatches(context, selection) {
2928
- return selection === null || context !== null && selection.host_source_ref === context.identity.host_source_ref && selection.host_session_ref === context.identity.host_session_ref && selection.prompt_ref === context.prompt_ref && selection.turn_generation_ref === context.turn_generation_ref;
2929
- }
2930
- function exactKeys3(value, keys) {
2783
+ function exactKeys(value, keys) {
2931
2784
  const actual = Object.keys(value);
2932
2785
  return actual.length === keys.length && keys.every((key) => Object.hasOwn(value, key)) && actual.every((key) => keys.includes(key));
2933
2786
  }
@@ -2936,13 +2789,210 @@ function requiredKeys(value, required, optional) {
2936
2789
  const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
2937
2790
  return actual.length >= required.length && actual.length <= allowed.size && required.every((key) => Object.hasOwn(value, key)) && actual.every((key) => allowed.has(key));
2938
2791
  }
2939
- function isRecord2(value) {
2792
+ function isRecord3(value) {
2940
2793
  return value !== null && typeof value === "object" && !Array.isArray(value);
2941
2794
  }
2942
- function safeRef2(value) {
2795
+ function safeRef(value) {
2943
2796
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
2944
2797
  }
2945
2798
 
2799
+ // host/relay/src/producer-frame.ts
2800
+ var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2801
+ var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "turn_terminal", "producer_status"];
2802
+ var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
2803
+ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2804
+ "invalid_frame_encoding",
2805
+ "invalid_frame_length",
2806
+ "frame_truncated",
2807
+ "unsupported_frame_schema",
2808
+ "invalid_frame_shape",
2809
+ "invalid_producer_identity",
2810
+ "frame_too_large"
2811
+ ];
2812
+
2813
+ // host/relay/src/durable-atomic-replacement.ts
2814
+ import { lstat as lstat3, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
2815
+ import { dirname as dirname3 } from "node:path";
2816
+
2817
+ // host/windows-rename-retry.ts
2818
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
2819
+ var RETRY_WINDOW_MS = 1e4;
2820
+ var RETRY_START_DELAY_MS = 100;
2821
+ var RETRY_MAX_DELAY_MS = 2e3;
2822
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
2823
+ var WindowsRenameRetryError = class extends Error {
2824
+ code = "rename_unavailable";
2825
+ constructor(target, attempts, options = {}) {
2826
+ super(`Windows did not permit renaming into place within the bounded retry window: ${target} (after ${attempts} attempts). Wait for the process holding the path to release it, then rerun the same install or update command.`, options);
2827
+ this.name = "WindowsRenameRetryError";
2828
+ }
2829
+ };
2830
+ function resolveRetrySchedule(tuning) {
2831
+ return {
2832
+ windowMs: tuning.windowMs ?? RETRY_WINDOW_MS,
2833
+ startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
2834
+ maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
2835
+ sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
2836
+ now: tuning.now ?? (() => Date.now())
2837
+ };
2838
+ }
2839
+ async function renameWithWindowsRetry(operation, tuning) {
2840
+ const schedule = resolveRetrySchedule(tuning);
2841
+ const deadline = schedule.now() + schedule.windowMs;
2842
+ let delayMs = schedule.startDelayMs;
2843
+ let attempts = 0;
2844
+ for (; ; ) {
2845
+ attempts += 1;
2846
+ try {
2847
+ await operation();
2848
+ return;
2849
+ } catch (error) {
2850
+ if (tuning.platform !== "win32" || !isRetryableRenameError(error)) throw error;
2851
+ await sleepWithinWindow(schedule, deadline, delayMs, () => new WindowsRenameRetryError(tuning.target, attempts, { cause: error }));
2852
+ delayMs = Math.min(delayMs * 2, schedule.maxDelayMs);
2853
+ }
2854
+ }
2855
+ }
2856
+ async function sleepWithinWindow(schedule, deadline, delayMs, exhausted) {
2857
+ if (schedule.now() >= deadline) throw exhausted();
2858
+ await schedule.sleep(Math.min(delayMs, deadline - schedule.now()));
2859
+ if (schedule.now() >= deadline) throw exhausted();
2860
+ }
2861
+ function isRetryableRenameError(error) {
2862
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && RETRYABLE_CODES.has(error.code);
2863
+ }
2864
+
2865
+ // host/relay/src/durable-atomic-replacement.ts
2866
+ var DEFAULT_PORT = {
2867
+ platform: process.platform,
2868
+ mkdir: (path, options) => mkdir2(path, options),
2869
+ lstat: (path) => lstat3(path),
2870
+ open_file: (path) => open2(path, "wx", 384),
2871
+ rename,
2872
+ unlink,
2873
+ open_directory: (path) => open2(path),
2874
+ unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
2875
+ };
2876
+ async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
2877
+ const parent = dirname3(target);
2878
+ await port.mkdir(parent, { recursive: true, mode: 448 });
2879
+ const parentStats = await port.lstat(parent);
2880
+ const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
2881
+ const ownerPrivate = port.platform === "win32" || isOwnedBy(parentStats.uid, expectedUid) && isPrivateFileMode(parentStats.mode, port.platform);
2882
+ if (!parentStats.isDirectory() || parentStats.isSymbolicLink() || !ownerPrivate) throw new TypeError(`Host Relay durable-state directory is unsafe: ${refusalFacts([{ name: "parent_stats", value: parentStats, expected: "an owner-private directory" }, { name: "platform", value: port.platform }])}.`);
2883
+ const temporary = `${target}.${port.unique_ref()}.new`;
2884
+ let staged;
2885
+ const failures = [];
2886
+ try {
2887
+ staged = await port.open_file(temporary);
2888
+ await staged.writeFile(data, typeof data === "string" ? { encoding: "utf8" } : void 0);
2889
+ await staged.sync();
2890
+ const closing = staged;
2891
+ staged = void 0;
2892
+ await closing.close();
2893
+ await renameWithWindowsRetry(() => port.rename(temporary, target), { ...port.rename_retry, platform: port.platform, target });
2894
+ await syncParentDirectory(parent, port);
2895
+ } catch (error) {
2896
+ failures.push(error);
2897
+ }
2898
+ await closeStaged(staged, failures);
2899
+ await removeTemporary(temporary, port, failures);
2900
+ throwFailures(failures);
2901
+ }
2902
+ async function syncParentDirectory(path, port) {
2903
+ if (port.platform === "win32") return;
2904
+ const handle = await port.open_directory(path);
2905
+ let failure;
2906
+ try {
2907
+ await handle.sync();
2908
+ } catch (error) {
2909
+ if (!directorySyncUnsupported(error)) failure = error;
2910
+ }
2911
+ try {
2912
+ await handle.close();
2913
+ } catch (error) {
2914
+ if (failure === void 0) failure = error;
2915
+ else failure = new AggregateError([failure, error], "Host Relay directory sync and close failed.");
2916
+ }
2917
+ if (failure !== void 0) throw failure;
2918
+ }
2919
+ async function closeStaged(staged, failures) {
2920
+ if (staged !== void 0) try {
2921
+ await staged.close();
2922
+ } catch (error) {
2923
+ failures.push(error);
2924
+ }
2925
+ }
2926
+ async function removeTemporary(path, port, failures) {
2927
+ try {
2928
+ await port.unlink(path);
2929
+ } catch (error) {
2930
+ if (errorCode2(error) !== "ENOENT") failures.push(error);
2931
+ }
2932
+ }
2933
+ function throwFailures(failures) {
2934
+ if (failures.length === 1) throw failures[0];
2935
+ if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
2936
+ }
2937
+ function directorySyncUnsupported(error) {
2938
+ return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode2(error) ?? "");
2939
+ }
2940
+ function errorCode2(error) {
2941
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
2942
+ }
2943
+
2944
+ // host/relay/src/relay-quarantine-store.ts
2945
+ var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
2946
+ var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
2947
+ var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
2948
+
2949
+ // host/relay/src/relay-admission-store.ts
2950
+ var DEFAULT_LIMITS = { global_count: 8192, global_bytes: 64 * 1024 * 1024, producer_count: 4096, producer_bytes: 32 * 1024 * 1024 };
2951
+ var RETRY_SECONDS = [1, 2, 4, 8, 16, 32, 60];
2952
+ var MAX_RETRYABLE_ATTEMPTS = RETRY_SECONDS.length + 10;
2953
+
2954
+ // host/relay/src/relay-pipe-handshake.ts
2955
+ var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2956
+
2957
+ // host/relay/src/relay-ipc.ts
2958
+ var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
2959
+ var HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
2960
+ "permission_denied",
2961
+ "socket_missing",
2962
+ "connection_refused",
2963
+ "closed_early",
2964
+ "response_invalid",
2965
+ "timed_out",
2966
+ "cancelled",
2967
+ "unavailable"
2968
+ ]);
2969
+
2970
+ // host/claude/src/claude-types.ts
2971
+ var CLAUDE_HOST_ERROR_CODES = ["invalid_input", "payload_rejected", "storage", "configuration"];
2972
+ function isClaudeHostErrorCode(value) {
2973
+ return typeof value === "string" && CLAUDE_HOST_ERROR_CODES.some((code2) => code2 === value);
2974
+ }
2975
+ var CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION = "ceal.claude_invocation_context.v1";
2976
+ var CLAUDE_OUTBOX_SCHEMA_VERSION = "ceal.claude_observation_outbox.v1";
2977
+ var CLAUDE_SESSION_SCHEMA_VERSION = "ceal.claude_session.v1";
2978
+ var CLAUDE_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION = "ceal.claude_transcript_registration.v1";
2979
+ var CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION = "ceal.claude_transcript_cursor.v1";
2980
+ var CLAUDE_DEFAULT_RETENTION_MS = 24 * 60 * 60 * 1e3;
2981
+ var CLAUDE_TRANSCRIPT_MAX_TURN_MESSAGES = 1024;
2982
+ var CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES = 64;
2983
+ var CLAUDE_TRANSCRIPT_ANCHOR_BYTES = 256;
2984
+ var ClaudeHostError = class extends Error {
2985
+ name = "ClaudeHostError";
2986
+ code;
2987
+ diagnostic_kind;
2988
+ constructor(code2, message, diagnostic_kind) {
2989
+ super(message);
2990
+ if (!isClaudeHostErrorCode(code2)) throw new TypeError("Claude Host error code is invalid.");
2991
+ this.code = code2;
2992
+ this.diagnostic_kind = diagnostic_kind;
2993
+ }
2994
+ };
2995
+
2946
2996
  // host/claude/src/claude-invocation-context.ts
2947
2997
  function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
2948
2998
  return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
@@ -2954,42 +3004,38 @@ function validateClaudeHostInvocationContext(value) {
2954
3004
  validateContextTimes(value);
2955
3005
  }
2956
3006
  function contextShape(value) {
2957
- return record3(value) && value.schema_version === CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION && hasHostInvocationContextKeys(value, ["request_ref", "bound_at", "working_directory", "turn_generation_ref"]);
3007
+ return record(value) && value.schema_version === CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION && hasHostInvocationContextKeys(value, ["working_directory", "turn_generation_ref"]);
2958
3008
  }
2959
3009
  function validateIdentity2(value) {
2960
3010
  if (!validIdentity(value)) throw new ClaudeHostError("storage", "Claude Host invocation identity is malformed.");
2961
3011
  }
2962
3012
  function validateContextReferences(value) {
2963
- if (!safeRef3(value.prompt_ref) || !optionalSafeRef(value.request_ref) || !optionalSafeRef(value.turn_generation_ref)) throw new ClaudeHostError("storage", "Claude Host invocation context is malformed.");
3013
+ if (!safeRef2(value.prompt_ref) || !optionalSafeRef(value.turn_generation_ref)) throw new ClaudeHostError("storage", "Claude Host invocation context is malformed.");
2964
3014
  }
2965
3015
  function validateContextTimes(value) {
2966
- if (!timestamp2(value.expires_at) || !optionalTimestamp(value.bound_at) || !optionalDirectory(value.working_directory)) throw new ClaudeHostError("storage", "Claude Host invocation context is malformed.");
2967
- if (typeof value.bound_at === "string" && Date.parse(value.bound_at) > Date.parse(String(value.expires_at))) throw new ClaudeHostError("storage", `Claude Host invocation context has invalid binding time (${refusalFact("bound_at", value.bound_at, `at or before ${String(value.expires_at)}`)}).`);
3016
+ if (!timestamp(value.expires_at) || !optionalDirectory(value.working_directory)) throw new ClaudeHostError("storage", "Claude Host invocation context is malformed.");
2968
3017
  }
2969
3018
  function validIdentity(value) {
2970
- return record3(value) && hasHostInvocationIdentityKeys(value) && [value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef3);
3019
+ return record(value) && hasHostInvocationIdentityKeys(value) && [value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2);
2971
3020
  }
2972
3021
  function optionalSafeRef(value) {
2973
- return value === void 0 || safeRef3(value);
2974
- }
2975
- function optionalTimestamp(value) {
2976
- return value === void 0 || timestamp2(value);
3022
+ return value === void 0 || safeRef2(value);
2977
3023
  }
2978
3024
  function optionalDirectory(value) {
2979
3025
  return value === void 0 || typeof value === "string" && value.startsWith("/") && !value.includes("\0") && value.length <= 4096;
2980
3026
  }
2981
- function safeRef3(value) {
3027
+ function safeRef2(value) {
2982
3028
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
2983
3029
  }
2984
- function timestamp2(value) {
3030
+ function timestamp(value) {
2985
3031
  return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
2986
3032
  }
2987
- function record3(value) {
3033
+ function record(value) {
2988
3034
  return value !== null && typeof value === "object" && !Array.isArray(value);
2989
3035
  }
2990
3036
 
2991
3037
  // host/claude/src/claude-outbox.ts
2992
- var SAFE_REF4 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
3038
+ var SAFE_REF3 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
2993
3039
  var CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS = 4096;
2994
3040
  var CLAUDE_TRANSCRIPT_SUBAGENT_NAME_MAX_CHARACTERS = 256;
2995
3041
  var ClaudeOutboxStore = class {
@@ -3003,12 +3049,12 @@ var ClaudeOutboxStore = class {
3003
3049
  constructor(directory) {
3004
3050
  if (!directory.startsWith("/")) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
3005
3051
  this.directory = directory;
3006
- this.envelopes = join3(directory, "envelopes");
3007
- this.sessions = join3(directory, "sessions");
3008
- this.registrations = join3(directory, "transcript-registrations");
3009
- this.cursors = join3(directory, "transcript-cursors");
3010
- this.activeContexts = join3(directory, "active-contexts");
3011
- this.turnSelections = join3(directory, "turn-selections");
3052
+ this.envelopes = join2(directory, "envelopes");
3053
+ this.sessions = join2(directory, "sessions");
3054
+ this.registrations = join2(directory, "transcript-registrations");
3055
+ this.cursors = join2(directory, "transcript-cursors");
3056
+ this.activeContexts = join2(directory, "active-contexts");
3057
+ this.turnSelections = join2(directory, "turn-selections");
3012
3058
  }
3013
3059
  async prepare() {
3014
3060
  for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
@@ -3047,10 +3093,10 @@ var ClaudeOutboxStore = class {
3047
3093
  * a missing one. Every other caller keeps the fail-closed read above.
3048
3094
  */
3049
3095
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
3050
- if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
3096
+ if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
3051
3097
  await this.prepare();
3052
3098
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, readProjectionFile);
3053
- return invocationTurnSelectionMatches(context, await this.readInvocationTurnSelection(hostSourceRef, hostSessionRef)) ? context : null;
3099
+ return context;
3054
3100
  }
3055
3101
  async listInvocationContexts(now = /* @__PURE__ */ new Date()) {
3056
3102
  await this.prepare();
@@ -3058,9 +3104,9 @@ var ClaudeOutboxStore = class {
3058
3104
  for (const name of await readdir(this.activeContexts)) {
3059
3105
  if (!name.endsWith(".json")) continue;
3060
3106
  try {
3061
- const value = JSON.parse(await readFile2(join3(this.activeContexts, name), "utf8"));
3107
+ const value = JSON.parse(await readFile(join2(this.activeContexts, name), "utf8"));
3062
3108
  validateClaudeHostInvocationContext(value);
3063
- if (Date.parse(value.expires_at) > now.getTime() && invocationTurnSelectionMatches(value, await this.readInvocationTurnSelection(value.identity.host_source_ref, value.identity.host_session_ref))) contexts.push(value);
3109
+ if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
3064
3110
  } catch {
3065
3111
  }
3066
3112
  }
@@ -3078,7 +3124,7 @@ var ClaudeOutboxStore = class {
3078
3124
  for (const name of await readdir(this.envelopes)) {
3079
3125
  if (!name.endsWith(".json")) continue;
3080
3126
  try {
3081
- const value = JSON.parse(await readFile2(join3(this.envelopes, name), "utf8"));
3127
+ const value = JSON.parse(await readFile(join2(this.envelopes, name), "utf8"));
3082
3128
  validateEnvelope(value);
3083
3129
  entries.push(value);
3084
3130
  } catch {
@@ -3099,13 +3145,13 @@ var ClaudeOutboxStore = class {
3099
3145
  async saveSession(snapshot) {
3100
3146
  validateSession(snapshot);
3101
3147
  await this.prepare();
3102
- await durableAtomicReplace(join3(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
3148
+ await durableAtomicReplace(join2(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
3103
3149
  }
3104
3150
  async readSession(sourceRef, sessionRef) {
3105
- if (!SAFE_REF4.test(sourceRef) || !SAFE_REF4.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
3151
+ if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
3106
3152
  await this.prepare();
3107
3153
  try {
3108
- const value = JSON.parse(await readFile2(join3(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
3154
+ const value = JSON.parse(await readFile(join2(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
3109
3155
  validateSession(value);
3110
3156
  return value;
3111
3157
  } catch (error) {
@@ -3140,7 +3186,7 @@ var ClaudeOutboxStore = class {
3140
3186
  for (const name of await readdir(this.registrations)) {
3141
3187
  if (!name.endsWith(".json")) continue;
3142
3188
  try {
3143
- const value = JSON.parse(await readFile2(join3(this.registrations, name), "utf8"));
3189
+ const value = JSON.parse(await readFile(join2(this.registrations, name), "utf8"));
3144
3190
  validateRegistration(value);
3145
3191
  registrations.push(value);
3146
3192
  } catch {
@@ -3149,10 +3195,10 @@ var ClaudeOutboxStore = class {
3149
3195
  return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
3150
3196
  }
3151
3197
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
3152
- if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host turn selection identity is invalid.");
3198
+ if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host turn selection identity is invalid.");
3153
3199
  await this.prepare();
3154
3200
  try {
3155
- const value = JSON.parse(await readFile2(this.turnSelectionPath(hostSourceRef, hostSessionRef), "utf8"));
3201
+ const value = JSON.parse(await readFile(this.turnSelectionPath(hostSourceRef, hostSessionRef), "utf8"));
3156
3202
  if (!isHostInvocationTurnSelection(value) || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new ClaudeHostError("storage", "Claude Host turn selection is malformed.");
3157
3203
  return value;
3158
3204
  } catch (error) {
@@ -3164,7 +3210,7 @@ var ClaudeOutboxStore = class {
3164
3210
  validateRegistration(registration);
3165
3211
  await this.prepare();
3166
3212
  try {
3167
- const value = JSON.parse(await readFile2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "utf8"));
3213
+ const value = JSON.parse(await readFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "utf8"));
3168
3214
  validateCursor(value);
3169
3215
  return value;
3170
3216
  } catch (error) {
@@ -3178,20 +3224,20 @@ var ClaudeOutboxStore = class {
3178
3224
  await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
3179
3225
  }
3180
3226
  envelopePath(ref) {
3181
- return join3(this.envelopes, `${cealRequestSha256(ref)}.json`);
3227
+ return join2(this.envelopes, `${cealRequestSha256(ref)}.json`);
3182
3228
  }
3183
3229
  registrationPath(sourceRef, sessionRef) {
3184
- return join3(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
3230
+ return join2(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
3185
3231
  }
3186
3232
  turnSelectionPath(sourceRef, sessionRef) {
3187
- return join3(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
3233
+ return join2(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
3188
3234
  }
3189
3235
  cursorPath(sourceRef, sessionRef) {
3190
- return join3(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
3236
+ return join2(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
3191
3237
  }
3192
3238
  async readRegistrationFile(path) {
3193
3239
  try {
3194
- const value = JSON.parse(await readFile2(path, "utf8"));
3240
+ const value = JSON.parse(await readFile(path, "utf8"));
3195
3241
  validateRegistration(value);
3196
3242
  return value;
3197
3243
  } catch (error) {
@@ -3207,15 +3253,15 @@ var ClaudeOutboxStore = class {
3207
3253
  }
3208
3254
  }
3209
3255
  activeContextPath(identity) {
3210
- return join3(this.activeContexts, `${invocationContextKey(identity)}.json`);
3256
+ return join2(this.activeContexts, `${invocationContextKey(identity)}.json`);
3211
3257
  }
3212
3258
  };
3213
3259
  function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
3214
- if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef) || !(now instanceof Date) || !Number.isFinite(now.getTime())) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
3260
+ if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef) || !(now instanceof Date) || !Number.isFinite(now.getTime())) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
3215
3261
  }
3216
3262
  async function readProjectionFile(file) {
3217
3263
  try {
3218
- const context = JSON.parse(await readFile2(file, "utf8"));
3264
+ const context = JSON.parse(await readFile(file, "utf8"));
3219
3265
  validateClaudeHostInvocationContext(context);
3220
3266
  return context;
3221
3267
  } catch (error) {
@@ -3224,65 +3270,63 @@ async function readProjectionFile(file) {
3224
3270
  throw new ClaudeHostError("storage", "Unable to read the Claude Host invocation context.");
3225
3271
  }
3226
3272
  }
3227
- function safeRef4(value) {
3228
- return typeof value === "string" && SAFE_REF4.test(value);
3273
+ function safeRef3(value) {
3274
+ return typeof value === "string" && SAFE_REF3.test(value);
3229
3275
  }
3230
- function timestamp3(value) {
3276
+ function timestamp2(value) {
3231
3277
  return typeof value === "string" && Number.isFinite(Date.parse(value));
3232
3278
  }
3233
- function record4(value) {
3279
+ function record2(value) {
3234
3280
  return value !== null && typeof value === "object" && !Array.isArray(value);
3235
3281
  }
3236
3282
  function code(error) {
3237
- return record4(error) && typeof error.code === "string" ? error.code : null;
3283
+ return record2(error) && typeof error.code === "string" ? error.code : null;
3238
3284
  }
3239
3285
  function validateEnvelope(value) {
3240
- if (!record4(value)) throw new ClaudeHostError("storage", "Claude outbox entry is malformed.");
3241
- if (!sameKeys(value, ["schema_version", "identity", "host_input_ref", "input_kind", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"], ["request_ref"])) {
3286
+ if (!record2(value)) throw new ClaudeHostError("storage", "Claude outbox entry is malformed.");
3287
+ if (!sameKeys(value, ["schema_version", "identity", "host_input_ref", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"])) {
3242
3288
  throw new ClaudeHostError("storage", `Claude outbox entry key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the outbox entry key set")}).`);
3243
3289
  }
3244
3290
  if (value.schema_version !== CLAUDE_OUTBOX_SCHEMA_VERSION) throw new ClaudeHostError("storage", `Claude outbox entry is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CLAUDE_OUTBOX_SCHEMA_VERSION}`)}).`);
3245
3291
  validateEnvelopeIdentity(value);
3246
3292
  validateEnvelopeObservations(value.observations);
3247
3293
  if (typeof value.origin_input !== "boolean") throw new ClaudeHostError("storage", "Claude outbox origin disposition is malformed.");
3248
- if (!timestamp3(value.created_at) || !timestamp3(value.expires_at)) throw new ClaudeHostError("storage", "Claude outbox timestamps are malformed.");
3294
+ if (!timestamp2(value.created_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude outbox timestamps are malformed.");
3249
3295
  }
3250
3296
  function validateEnvelopeIdentity(value) {
3251
3297
  validateIdentity3(value.identity);
3252
- if (!safeRef4(value.host_input_ref)) throw new ClaudeHostError("storage", "Claude outbox input reference is malformed.");
3253
- if (!isCealHostInputKind(value.input_kind)) throw new ClaudeHostError("storage", "Claude outbox input provenance is malformed.");
3254
- if (!safeRef4(value.prompt_ref) || !safeRef4(value.submission_ref)) throw new ClaudeHostError("storage", "Claude outbox references are malformed.");
3255
- if (value.request_ref !== void 0 && !safeRef4(value.request_ref)) throw new ClaudeHostError("storage", "Claude outbox Request reference is malformed.");
3298
+ if (!safeRef3(value.host_input_ref)) throw new ClaudeHostError("storage", "Claude outbox input reference is malformed.");
3299
+ if (!safeRef3(value.prompt_ref) || !safeRef3(value.submission_ref)) throw new ClaudeHostError("storage", "Claude outbox references are malformed.");
3256
3300
  }
3257
3301
  function validateEnvelopeObservations(value) {
3258
3302
  if (!Array.isArray(value)) throw new ClaudeHostError("storage", "Claude outbox observations are malformed.");
3259
3303
  try {
3260
- for (const observation2 of value) validateCealHostObservationDraft(observation2);
3304
+ for (const observation of value) validateCealHostObservationDraft(observation);
3261
3305
  } catch {
3262
3306
  throw new ClaudeHostError("storage", "Claude outbox observations are malformed.");
3263
3307
  }
3264
3308
  }
3265
3309
  function validateSession(value) {
3266
- if (!record4(value)) throw new ClaudeHostError("storage", "Claude session snapshot is malformed.");
3310
+ if (!record2(value)) throw new ClaudeHostError("storage", "Claude session snapshot is malformed.");
3267
3311
  if (!sameKeys(value, ["schema_version", "host_session_ref", "host_source_ref", "observed_at", "value", "expires_at"])) {
3268
3312
  throw new ClaudeHostError("storage", `Claude session snapshot key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the session snapshot key set")}).`);
3269
3313
  }
3270
3314
  if (value.schema_version !== CLAUDE_SESSION_SCHEMA_VERSION) throw new ClaudeHostError("storage", `Claude session snapshot is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CLAUDE_SESSION_SCHEMA_VERSION}`)}).`);
3271
- if (!safeRef4(value.host_session_ref) || !safeRef4(value.host_source_ref) || !timestamp3(value.observed_at) || !timestamp3(value.expires_at)) {
3315
+ if (!safeRef3(value.host_session_ref) || !safeRef3(value.host_source_ref) || !timestamp2(value.observed_at) || !timestamp2(value.expires_at)) {
3272
3316
  throw new ClaudeHostError("storage", "Claude session snapshot fields are malformed.");
3273
3317
  }
3274
3318
  }
3275
3319
  function validateRegistration(value) {
3276
- if (!record4(value)) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
3320
+ if (!record2(value)) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
3277
3321
  if (!sameKeys(value, ["schema_version", "host_source_ref", "host_session_ref", "claude_session_id", "transcript_path", "registered_at", "expires_at"], ["cwd"])) {
3278
3322
  throw new ClaudeHostError("storage", `Claude transcript registration key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the registration key set")}).`);
3279
3323
  }
3280
3324
  if (value.schema_version !== CLAUDE_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
3281
- if (![value.host_source_ref, value.host_session_ref, value.claude_session_id].every((candidate) => typeof candidate === "string" && SAFE_REF4.test(candidate))) {
3325
+ if (![value.host_source_ref, value.host_session_ref, value.claude_session_id].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) {
3282
3326
  throw new ClaudeHostError("storage", "Claude transcript registration references are malformed.");
3283
3327
  }
3284
3328
  validateRegistrationPaths(value.cwd, value.transcript_path);
3285
- if (!timestamp3(value.registered_at) || !timestamp3(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
3329
+ if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
3286
3330
  }
3287
3331
  function validateRegistrationPaths(cwd, transcriptPath) {
3288
3332
  if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute2(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
@@ -3293,12 +3337,12 @@ function validateRegistrationPaths(cwd, transcriptPath) {
3293
3337
  }
3294
3338
  }
3295
3339
  function validateCursor(value) {
3296
- if (!record4(value)) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
3340
+ if (!record2(value)) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
3297
3341
  if (!sameKeys(value, ["schema_version", "host_source_ref", "host_session_ref", "transcript_path", "offset", "anchor_start", "anchor_sha256", "subagents", "status", "updated_at"], ["device", "inode", "open_turn", "unattributed", "session_observed", "reason"])) {
3298
3342
  throw new ClaudeHostError("storage", "Claude transcript cursor key set is malformed.");
3299
3343
  }
3300
3344
  if (value.schema_version !== CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
3301
- if (![value.host_source_ref, value.host_session_ref].every((candidate) => typeof candidate === "string" && SAFE_REF4.test(candidate))) throw new ClaudeHostError("storage", "Claude transcript cursor references are malformed.");
3345
+ if (![value.host_source_ref, value.host_session_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) throw new ClaudeHostError("storage", "Claude transcript cursor references are malformed.");
3302
3346
  if (typeof value.transcript_path !== "string" || value.transcript_path.length === 0) throw new ClaudeHostError("storage", "Claude transcript cursor path is malformed.");
3303
3347
  validateCursorPosition(value);
3304
3348
  validateCursorTurn(value.open_turn, value.unattributed, value.session_observed);
@@ -3310,7 +3354,7 @@ function validateCursorPosition(value) {
3310
3354
  if (value.device !== void 0 && typeof value.device !== "string") throw new ClaudeHostError("storage", "Claude transcript cursor device is malformed.");
3311
3355
  if (value.inode !== void 0 && typeof value.inode !== "string") throw new ClaudeHostError("storage", "Claude transcript cursor inode is malformed.");
3312
3356
  if (value.device === void 0 && value.offset !== 0) throw new ClaudeHostError("storage", "Claude transcript cursor is unpinned past its start.");
3313
- if (value.status !== "active" && value.status !== "quarantined" || !timestamp3(value.updated_at)) throw new ClaudeHostError("storage", "Claude transcript cursor status is malformed.");
3357
+ if (value.status !== "active" && value.status !== "quarantined" || !timestamp2(value.updated_at)) throw new ClaudeHostError("storage", "Claude transcript cursor status is malformed.");
3314
3358
  }
3315
3359
  function validateCursorTurn(openTurn, unattributed, sessionObserved) {
3316
3360
  if (openTurn !== void 0 && !validOpenTurn(openTurn)) throw new ClaudeHostError("storage", "Claude transcript turn cursor is malformed.");
@@ -3318,13 +3362,13 @@ function validateCursorTurn(openTurn, unattributed, sessionObserved) {
3318
3362
  if (sessionObserved !== void 0 && typeof sessionObserved !== "boolean") throw new ClaudeHostError("storage", "Claude transcript cursor session marker is malformed.");
3319
3363
  }
3320
3364
  function validateSubagentCursors(value) {
3321
- if (!record4(value)) throw new ClaudeHostError("storage", "Claude transcript subagent cursors are malformed.");
3365
+ if (!record2(value)) throw new ClaudeHostError("storage", "Claude transcript subagent cursors are malformed.");
3322
3366
  for (const [name, entry] of Object.entries(value)) validateSubagentEntry(name, entry);
3323
3367
  }
3324
3368
  function validateSubagentEntry(name, entry) {
3325
3369
  if (name.length === 0 || name.length > CLAUDE_TRANSCRIPT_SUBAGENT_NAME_MAX_CHARACTERS || name.includes("/")) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
3326
3370
  if (name.includes("\0")) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
3327
- if (!record4(entry) || !sameKeys(entry, ["offset", "anchor_start", "anchor_sha256"], ["device", "inode"]) || !nonNegativeInteger(entry.offset)) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
3371
+ if (!record2(entry) || !sameKeys(entry, ["offset", "anchor_start", "anchor_sha256"], ["device", "inode"]) || !nonNegativeInteger(entry.offset)) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
3328
3372
  validateSubagentIdentity(entry);
3329
3373
  }
3330
3374
  function validateSubagentIdentity(entry) {
@@ -3340,9 +3384,9 @@ function validCursorPosition(value) {
3340
3384
  return nonNegativeInteger(value.offset) && nonNegativeInteger(value.anchor_start) && typeof value.anchor_sha256 === "string" && /^[a-f0-9]{64}$/u.test(value.anchor_sha256);
3341
3385
  }
3342
3386
  function validOpenTurn(value) {
3343
- if (!record4(value) || !sameKeys(value, ["turn_key", "user_uuid", "prompt_ref", "host_input_ref", "started_at", "last_observed_at", "message_ids", "counts"], ["last_terminal_digest"])) return false;
3344
- if (![value.turn_key, value.user_uuid, value.prompt_ref, value.host_input_ref].every((candidate) => typeof candidate === "string" && SAFE_REF4.test(candidate))) return false;
3345
- if (!timestamp3(value.started_at) || !timestamp3(value.last_observed_at)) return false;
3387
+ if (!record2(value) || !sameKeys(value, ["turn_key", "user_uuid", "prompt_ref", "host_input_ref", "started_at", "last_observed_at", "message_ids", "counts"], ["last_terminal_digest"])) return false;
3388
+ if (![value.turn_key, value.user_uuid, value.prompt_ref, value.host_input_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) return false;
3389
+ if (!timestamp2(value.started_at) || !timestamp2(value.last_observed_at)) return false;
3346
3390
  if (!validMessageIds(value.message_ids)) return false;
3347
3391
  if (!validTurnCounts(value.counts)) return false;
3348
3392
  return value.last_terminal_digest === void 0 || typeof value.last_terminal_digest === "string" && /^[a-f0-9]{64}$/u.test(value.last_terminal_digest);
@@ -3353,17 +3397,17 @@ function validMessageIds(value) {
3353
3397
  return new Set(value).size === value.length;
3354
3398
  }
3355
3399
  function validUnattributed(value) {
3356
- if (!record4(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output", "message_ids", "last_observed_at"])) return false;
3400
+ if (!record2(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output", "message_ids", "last_observed_at"])) return false;
3357
3401
  if (!validMessageIds(value.message_ids) || value.message_ids.length === 0) return false;
3358
- if (!timestamp3(value.last_observed_at)) return false;
3402
+ if (!timestamp2(value.last_observed_at)) return false;
3359
3403
  return validTurnCounts(value);
3360
3404
  }
3361
3405
  function validTurnCounts(value) {
3362
- if (!record4(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output"])) return false;
3406
+ if (!record2(value) || !sameKeys(value, ["input", "cached_input", "cache_write_input", "output"])) return false;
3363
3407
  return [value.input, value.cached_input, value.cache_write_input, value.output].every(nonNegativeInteger);
3364
3408
  }
3365
3409
  function validateIdentity3(value) {
3366
- if (!record4(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every((candidate) => typeof candidate === "string" && SAFE_REF4.test(candidate))) {
3410
+ if (!record2(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) {
3367
3411
  throw new ClaudeHostError("storage", "Claude Host identity is malformed.");
3368
3412
  }
3369
3413
  }
@@ -3376,126 +3420,101 @@ function sameKeys(value, required, optional = []) {
3376
3420
 
3377
3421
  // host/claude/src/claude-producer.ts
3378
3422
  var ClaudeProducer = class {
3379
- producer_id = "claude";
3380
- producer_label = "Claude";
3381
- outbox_directory;
3382
3423
  store;
3383
3424
  core;
3384
3425
  constructor(options) {
3385
3426
  this.store = new ClaudeOutboxStore(options.outbox_dir);
3386
- this.outbox_directory = this.store.directory;
3387
3427
  this.core = new HostProducerDrainCore(this, options);
3388
3428
  }
3389
3429
  drainOutbox() {
3390
3430
  return this.core.drainOutbox();
3391
3431
  }
3392
- fail(code2, message) {
3393
- return new ClaudeHostError(code2, message);
3394
- }
3395
3432
  listEnvelopes() {
3396
3433
  return this.store.listEnvelopes();
3397
3434
  }
3398
3435
  removeEnvelope(envelope) {
3399
3436
  return this.store.removeEnvelope(envelope);
3400
3437
  }
3401
- submissionRefOf(envelope) {
3402
- return envelope.submission_ref;
3403
- }
3404
3438
  expiresAtOf(envelope) {
3405
3439
  return envelope.expires_at;
3406
3440
  }
3407
- createdAtOf(envelope) {
3408
- return envelope.created_at;
3409
- }
3410
- async mapEnvelope(envelope) {
3411
- const prompt = observation(envelope, "prompt");
3412
- if (prompt !== void 0) return this.mapInput(envelope, prompt);
3413
- return [mapTerminal(envelope)];
3414
- }
3415
- async mapInput(envelope, prompt) {
3416
- const drafts = [];
3417
- const session = observation(envelope, "session");
3418
- if (session !== void 0) {
3419
- const registrations = await this.store.listTranscriptRegistrations();
3420
- const registration = registrations.find((item) => item.host_source_ref === envelope.identity.host_source_ref && item.host_session_ref === envelope.identity.host_session_ref);
3421
- const directoryIdentity = registration?.cwd ?? envelope.identity.host_session_ref;
3422
- drafts.push({
3423
- frame_kind: "session_started",
3424
- payload: compact({
3425
- local_session_ref: envelope.identity.host_session_ref,
3426
- working_directory_ref: claudeWorkspaceRef(directoryIdentity),
3427
- model: recordText(session.value, "model"),
3428
- observations: [session]
3429
- })
3430
- });
3431
- }
3432
- const turn = observation(envelope, "turn");
3433
- if (turn !== void 0) drafts.push({
3434
- frame_kind: "turn_started",
3435
- payload: compact({
3436
- local_session_ref: envelope.identity.host_session_ref,
3437
- local_turn_ref: localTurnRef(envelope),
3438
- observations: [turn]
3439
- })
3440
- });
3441
- if (!isCealHostPromptObservationValue(prompt.value)) throw new ClaudeHostError("storage", "Claude prompt observation is malformed.");
3442
- drafts.push({
3443
- frame_kind: "user_input",
3444
- payload: compact({
3445
- local_session_ref: envelope.identity.host_session_ref,
3446
- local_turn_ref: localTurnRef(envelope),
3447
- local_input_ref: envelope.host_input_ref,
3448
- input_kind: envelope.input_kind,
3449
- origin_input: envelope.origin_input,
3450
- observations: [prompt],
3451
- context_expires_at: envelope.expires_at
3452
- })
3453
- });
3454
- return drafts;
3455
- }
3456
3441
  };
3457
- function mapTerminal(envelope) {
3458
- const usage = envelope.observations.filter((item) => ["token", "cost"].includes(item.observation_kind));
3459
- return {
3460
- frame_kind: "turn_terminal",
3461
- payload: compact({
3462
- local_session_ref: envelope.identity.host_session_ref,
3463
- local_turn_ref: localTurnRef(envelope),
3464
- terminal_state: "completed",
3465
- usage: usage.length === 0 ? void 0 : Object.fromEntries(usage.map((item) => [item.observation_kind, item.value])),
3466
- observations: envelope.observations
3467
- })
3468
- };
3469
- }
3470
- function observation(envelope, kind) {
3471
- return envelope.observations.find((item) => item.observation_kind === kind);
3472
- }
3473
- function localTurnRef(envelope) {
3474
- return envelope.identity.host_turn_ref;
3442
+
3443
+ // host/claude/src/claude-transcript-watcher.ts
3444
+ import { readdir as readdir2 } from "node:fs/promises";
3445
+ import { join as join3 } from "node:path";
3446
+
3447
+ // host/claude/src/claude-decoder.ts
3448
+ import { createHash as createHash5 } from "node:crypto";
3449
+ var MAX_HOOK_BYTES = 256 * 1024;
3450
+ function decodeClaudeQueuedPromptRow(row, sessionId) {
3451
+ if (!record3(row)) return null;
3452
+ if (row.type === "user") return decodeArrayTextPrompt(row, sessionId);
3453
+ if (row.type === "attachment") return decodeQueuedCommandPrompt(row, sessionId);
3454
+ if (row.type === "queue-operation") return decodeQueueEnqueuePrompt(row, sessionId);
3455
+ return null;
3475
3456
  }
3476
- function compact(value) {
3477
- return Object.fromEntries(Object.entries(value).filter((entry) => entry[1] !== void 0));
3457
+ function decodeArrayTextPrompt(row, sessionId) {
3458
+ if (!record3(row.message) || !Array.isArray(row.message.content)) return null;
3459
+ if (!sessionMatches(row, sessionId)) return null;
3460
+ if (row.isMeta === true && (!record3(row.origin) || typeof row.origin.kind !== "string")) return null;
3461
+ const texts = arrayTextBlocks(row.message.content);
3462
+ if (texts === null) return null;
3463
+ const identity = queuedRowIdentity(row);
3464
+ if (identity === null) return null;
3465
+ return { turnId: identity.uuid, timestamp: identity.timestamp, content: texts.join("") };
3466
+ }
3467
+ function arrayTextBlocks(content) {
3468
+ const texts = [];
3469
+ for (const block of content) {
3470
+ if (!record3(block) || block.type !== "text" || typeof block.text !== "string") return null;
3471
+ texts.push(block.text);
3472
+ }
3473
+ return texts.length === 0 ? null : texts;
3474
+ }
3475
+ function decodeQueuedCommandPrompt(row, sessionId) {
3476
+ if (!record3(row.attachment) || row.attachment.type !== "queued_command" || row.attachment.commandMode !== "prompt") return null;
3477
+ if (typeof row.attachment.prompt !== "string" || row.attachment.prompt.length === 0) return null;
3478
+ if (!sessionMatches(row, sessionId)) return null;
3479
+ const identity = queuedRowIdentity(row);
3480
+ if (identity === null) return null;
3481
+ return { turnId: identity.uuid, timestamp: identity.timestamp, content: row.attachment.prompt };
3482
+ }
3483
+ function decodeQueueEnqueuePrompt(row, sessionId) {
3484
+ if (row.operation !== "enqueue" || typeof row.content !== "string" || row.content.length === 0) return null;
3485
+ if (!sessionMatches(row, sessionId)) return null;
3486
+ if (typeof row.timestamp !== "string" || !Number.isFinite(Date.parse(row.timestamp))) return null;
3487
+ return { turnId: queueEnqueueTurnId(sessionId, row.timestamp, row.content), timestamp: row.timestamp, content: row.content };
3488
+ }
3489
+ function sessionMatches(row, sessionId) {
3490
+ const hasSessionId = Object.hasOwn(row, "sessionId");
3491
+ const hasSnakeSessionId = Object.hasOwn(row, "session_id");
3492
+ return (hasSessionId || hasSnakeSessionId) && (!hasSessionId || row.sessionId === sessionId) && (!hasSnakeSessionId || row.session_id === sessionId);
3493
+ }
3494
+ function queuedRowIdentity(row) {
3495
+ if (typeof row.uuid !== "string" || row.uuid.length === 0 || row.uuid.length > 256) return null;
3496
+ if (typeof row.timestamp !== "string" || !Number.isFinite(Date.parse(row.timestamp))) return null;
3497
+ return { uuid: row.uuid, timestamp: row.timestamp };
3498
+ }
3499
+ function queueEnqueueTurnId(sessionId, timestamp3, content) {
3500
+ return `queue-enqueue:${createHash5("sha256").update(`${sessionId}
3501
+ ${timestamp3}
3502
+ ${content}`, "utf8").digest("hex").slice(0, 32)}`;
3478
3503
  }
3479
- function asRecord(value) {
3480
- return isRecord3(value) ? value : void 0;
3504
+ function claudeLocalTurnRef(sessionId, turnId) {
3505
+ return `claude-turn:${cealRequestSha256({ session_id: sessionId, prompt_id: turnId })}`;
3481
3506
  }
3482
- function recordText(value, key) {
3483
- const record5 = asRecord(value);
3484
- return typeof record5?.[key] === "string" ? record5[key] : void 0;
3507
+ function claudeLocalInputRef(sessionId, turnId) {
3508
+ return `claude-input:${cealRequestSha256({ session_id: sessionId, prompt_id: turnId })}`;
3485
3509
  }
3486
- function isRecord3(value) {
3510
+ function record3(value) {
3487
3511
  return value !== null && typeof value === "object" && !Array.isArray(value);
3488
3512
  }
3489
3513
 
3490
3514
  // host/claude/src/claude-transcript-watcher.ts
3491
- import { O_NOFOLLOW as O_NOFOLLOW2, O_RDONLY as O_RDONLY3 } from "node:constants";
3492
- import { open as open5, readdir as readdir2 } from "node:fs/promises";
3493
- import { join as join4 } from "node:path";
3494
3515
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
3495
3516
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3496
3517
  store;
3497
- registerCurrentPrompt;
3498
- releaseCurrentPrompt;
3499
3518
  diagnostic;
3500
3519
  constructor(options) {
3501
3520
  super(options, {
@@ -3504,8 +3523,6 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3504
3523
  clock_failure: () => new ClaudeHostError("storage", "Claude watcher clock is invalid.")
3505
3524
  });
3506
3525
  this.store = new ClaudeOutboxStore(options.outbox_dir);
3507
- this.registerCurrentPrompt = options.register_current_prompt;
3508
- this.releaseCurrentPrompt = options.release_current_prompt;
3509
3526
  this.diagnostic = options.diagnostic ?? (() => void 0);
3510
3527
  }
3511
3528
  transcriptPathOf(registration) {
@@ -3519,7 +3536,6 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3519
3536
  const cursor = await this.preflight(registration, handle, size, device, inode);
3520
3537
  if (cursor === null) return { records: 0, enqueued: 0, quarantined: true };
3521
3538
  if (cursor.status === "quarantined") {
3522
- if (cursor.reason !== "transcript_malformed") await this.releaseStoredPromptBestEffort(registration.host_session_ref, cursor);
3523
3539
  return { records: 0, enqueued: 0, quarantined: true };
3524
3540
  }
3525
3541
  const draft = mutableCursor(cursor);
@@ -3534,7 +3550,6 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3534
3550
  return { records: 0, enqueued: 0, quarantined: true };
3535
3551
  }
3536
3552
  async retireMissing(registration) {
3537
- await this.releaseStoredPromptBestEffort(registration.host_session_ref, await this.store.readTranscriptCursor(registration).catch(() => null));
3538
3553
  return this.retireMissingTranscript(registration.transcript_path, "Claude", () => this.store.retireTranscriptRegistration(registration));
3539
3554
  }
3540
3555
  initialCursor(registration) {
@@ -3576,72 +3591,72 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3576
3591
  async consumeMainChunk(registration, complete, draft) {
3577
3592
  for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3578
3593
  draft.consumed += 1;
3579
- const record5 = parseTranscriptLine(line);
3580
- if (record5 === null) throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
3581
- if (isUserTurnLine(record5)) await this.openTurn(registration, draft, record5);
3582
- else if (isAssistantUsageLine(record5)) this.accumulateUsage(draft, toUsage(record5.uuid, record5.timestamp, record5.message.usage));
3583
- else if (isAssistantLine(record5) && record5.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude transcript usage is malformed.");
3584
- if (isAssistantTerminalLine(record5)) await this.releaseOpenTurn(registration, draft);
3594
+ const record4 = parseTranscriptLine(line);
3595
+ if (record4 === null) throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
3596
+ if (isUserTurnLine(record4)) await this.openTurn(registration, draft, record4);
3597
+ else if (isAssistantUsageLine(record4)) this.accumulateUsage(draft, toUsage(record4.uuid, record4.timestamp, record4.message.usage));
3598
+ else if (isAssistantLine(record4) && record4.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude transcript usage is malformed.");
3599
+ else {
3600
+ const queued = decodeClaudeQueuedPromptRow(record4, registration.claude_session_id);
3601
+ if (queued !== null) await this.openQueuedTurn(registration, draft, queued);
3602
+ }
3585
3603
  }
3586
3604
  }
3587
- async openTurn(registration, draft, record5) {
3588
- await this.closeTurn(registration, draft, record5.timestamp);
3605
+ async openTurn(registration, draft, record4) {
3606
+ await this.openPromptTurn(registration, draft, { uuid: record4.uuid, timestamp: record4.timestamp, content: record4.message.content });
3607
+ }
3608
+ async openQueuedTurn(registration, draft, queued) {
3609
+ await this.openPromptTurn(registration, draft, { uuid: queued.turnId, timestamp: queued.timestamp, content: queued.content });
3610
+ }
3611
+ async openPromptTurn(registration, draft, prompt) {
3612
+ await this.closeTurn(registration, draft, prompt.timestamp);
3589
3613
  const sessionRef = registration.host_session_ref;
3590
- const turnRef = claudeLocalTurnRef(registration.claude_session_id, record5.uuid);
3591
- const inputRef = claudeLocalInputRef(registration.claude_session_id, record5.uuid);
3592
- const promptRef = hostProducerPromptRef(this.sha(record5.message.content));
3614
+ const turnRef = claudeLocalTurnRef(registration.claude_session_id, prompt.uuid);
3615
+ const inputRef = claudeLocalInputRef(registration.claude_session_id, prompt.uuid);
3616
+ const promptRef = hostProducerPromptRef(this.sha(prompt.content));
3593
3617
  const identity = { host_source_ref: registration.host_source_ref, host_session_ref: sessionRef, host_turn_ref: turnRef };
3594
3618
  const observations = [
3595
- { observation_ref: observationRef("transcript_user_text", inputRef, record5.message.content), observation_kind: "prompt", observed_at: record5.timestamp, value: { body_sha256: this.sha(record5.message.content) } },
3596
- { observation_ref: observationRef("transcript_turn_started", turnRef, record5.uuid), observation_kind: "turn", observed_at: record5.timestamp, value: { status: "started", host_session_id_sha256: this.sha(registration.claude_session_id), host_turn_ref: turnRef } }
3619
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_user_text", inputRef, prompt.content), observation_kind: "prompt", observed_at: prompt.timestamp, value: { body_sha256: this.sha(prompt.content) } },
3620
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_turn_started", turnRef, prompt.uuid), observation_kind: "turn", observed_at: prompt.timestamp, value: { status: "started", host_session_id_sha256: this.sha(registration.claude_session_id), host_turn_ref: turnRef } }
3597
3621
  ];
3598
3622
  if (!draft.session_observed) {
3599
3623
  const session = await this.store.readSession(registration.host_source_ref, sessionRef);
3600
- if (session !== null) observations.push({ observation_ref: observationRef("transcript_session", sessionRef, session.value), observation_kind: "session", observed_at: record5.timestamp, value: session.value });
3624
+ if (session !== null) observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_session", sessionRef, session.value), observation_kind: "session", observed_at: prompt.timestamp, value: session.value });
3601
3625
  draft.session_observed = true;
3602
3626
  }
3603
- await this.persistOpenedTurnContext(registration, draft, record5, inputRef, turnRef, promptRef, identity, observations);
3627
+ await this.persistOpenedTurnContext(draft, { uuid: prompt.uuid, timestamp: prompt.timestamp, message: { content: prompt.content } }, inputRef, turnRef, promptRef, identity, observations);
3604
3628
  }
3605
- async persistOpenedTurnContext(registration, draft, record5, inputRef, turnRef, promptRef, identity, observations) {
3606
- const sessionRef = registration.host_session_ref;
3629
+ async persistOpenedTurnContext(draft, record4, inputRef, turnRef, promptRef, identity, observations) {
3607
3630
  const expiresAt = this.expire(this.outboxRetentionMs);
3608
- const custodyRegistered = await this.registerPrompt(sessionRef, turnRef, promptRef, record5.message.content, expiresAt);
3609
- if (custodyRegistered) this.diagnostic("watcher_turn_observed");
3610
- try {
3611
- await this.store.putEnvelope({
3612
- schema_version: "ceal.claude_observation_outbox.v1",
3613
- identity,
3614
- host_input_ref: inputRef,
3615
- input_kind: "human",
3616
- prompt_ref: promptRef,
3617
- observations,
3618
- origin_input: true,
3619
- submission_ref: submissionRef("input", turnRef, inputRef, promptRef),
3620
- created_at: record5.timestamp,
3621
- expires_at: expiresAt
3622
- });
3623
- draft.enqueued += 1;
3624
- await this.activateOpenedTurnContext(identity, promptRef, expiresAt);
3625
- this.setOpenedTurn(draft, record5, inputRef, turnRef, promptRef);
3626
- } catch (error) {
3627
- if (custodyRegistered) await this.releasePrompt(sessionRef, { turn_key: turnRef, prompt_ref: promptRef }).catch(() => void 0);
3628
- throw error;
3629
- }
3631
+ await this.store.putEnvelope({
3632
+ schema_version: "ceal.claude_observation_outbox.v1",
3633
+ identity,
3634
+ host_input_ref: inputRef,
3635
+ prompt_ref: promptRef,
3636
+ observations,
3637
+ origin_input: true,
3638
+ submission_ref: submissionRef("input", turnRef, inputRef, promptRef),
3639
+ created_at: record4.timestamp,
3640
+ expires_at: expiresAt
3641
+ });
3642
+ draft.enqueued += 1;
3643
+ await this.activateOpenedTurnContext(identity, promptRef, expiresAt);
3644
+ this.setOpenedTurn(draft, record4, inputRef, turnRef, promptRef);
3630
3645
  }
3631
3646
  async activateOpenedTurnContext(identity, promptRef, expiresAt) {
3632
3647
  const selection = await this.store.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref);
3633
3648
  const turnGenerationRef = selection?.prompt_ref === promptRef ? selection.turn_generation_ref : void 0;
3634
3649
  await this.activateContext(identity, promptRef, turnGenerationRef, expiresAt);
3635
3650
  }
3636
- setOpenedTurn(draft, record5, inputRef, turnRef, promptRef) {
3651
+ setOpenedTurn(draft, record4, inputRef, turnRef, promptRef) {
3637
3652
  const folded = foldUnattributed(draft.unattributed);
3638
3653
  draft.open_turn = {
3639
3654
  turn_key: turnRef,
3640
- user_uuid: record5.uuid,
3655
+ user_uuid: record4.uuid,
3641
3656
  prompt_ref: promptRef,
3642
3657
  host_input_ref: inputRef,
3643
- started_at: record5.timestamp,
3644
- last_observed_at: folded?.last_observed_at ?? record5.timestamp,
3658
+ started_at: record4.timestamp,
3659
+ last_observed_at: folded?.last_observed_at ?? record4.timestamp,
3645
3660
  message_ids: folded?.message_ids ?? [],
3646
3661
  counts: folded?.counts ?? zeroCounts()
3647
3662
  };
@@ -3651,19 +3666,11 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3651
3666
  const turn = draft.open_turn;
3652
3667
  draft.open_turn = void 0;
3653
3668
  if (turn === void 0) return;
3654
- const digest2 = terminalDigest(turn);
3655
- if (digest2 !== turn.last_terminal_digest) {
3656
- await this.putTerminalEnvelope(registration, turn, digest2, turn.message_ids.length === 0 ? at : void 0);
3669
+ const digest = terminalDigest(turn);
3670
+ if (digest !== turn.last_terminal_digest) {
3671
+ await this.putTerminalEnvelope(registration, turn, digest, turn.message_ids.length === 0 ? at : void 0);
3657
3672
  draft.enqueued += 1;
3658
3673
  }
3659
- await this.releasePrompt(registration.host_session_ref, turn);
3660
- }
3661
- async releaseOpenTurn(registration, draft) {
3662
- if (draft.open_turn !== void 0) await this.releasePrompt(registration.host_session_ref, draft.open_turn);
3663
- }
3664
- async releasePrompt(sessionRef, turn) {
3665
- if (this.producerInstallationRef === void 0 || this.releaseCurrentPrompt === void 0) return;
3666
- await this.releaseCurrentPrompt({ producer_id: "claude", producer_installation_ref: this.producerInstallationRef, local_session_ref: sessionRef, local_turn_ref: turn.turn_key, prompt_ref: turn.prompt_ref });
3667
3674
  }
3668
3675
  accumulateUsage(draft, usage) {
3669
3676
  const turn = draft.open_turn;
@@ -3710,10 +3717,10 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3710
3717
  return consumed;
3711
3718
  }
3712
3719
  async consumeSubagentFile(draft, directory, name) {
3713
- const path = join4(directory, name);
3720
+ const path = join3(directory, name);
3714
3721
  let handle;
3715
3722
  try {
3716
- handle = await open5(path, O_RDONLY3 | O_NOFOLLOW2);
3723
+ handle = await openNoFollow(path);
3717
3724
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
3718
3725
  const entry = draft.subagents[name] ?? { offset: 0, anchor_start: 0, anchor_sha256: this.sha(Buffer.alloc(0)) };
3719
3726
  const pinned = await this.preflightSubagent(entry, size, device, inode);
@@ -3741,10 +3748,10 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3741
3748
  let consumed = 0;
3742
3749
  for (const line of chunk.toString("utf8").split("\n").filter((value) => value.length > 0)) {
3743
3750
  consumed += 1;
3744
- const record5 = parseTranscriptLine(line);
3745
- if (record5 === null) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript line is not valid JSON.", "malformed_line");
3746
- if (isAssistantUsageLine(record5)) this.accumulateUsage(draft, toUsage(record5.uuid, record5.timestamp, record5.message.usage));
3747
- else if (isAssistantLine(record5) && record5.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript usage is malformed.");
3751
+ const record4 = parseTranscriptLine(line);
3752
+ if (record4 === null) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript line is not valid JSON.", "malformed_line");
3753
+ if (isAssistantUsageLine(record4)) this.accumulateUsage(draft, toUsage(record4.uuid, record4.timestamp, record4.message.usage));
3754
+ else if (isAssistantLine(record4) && record4.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript usage is malformed.");
3748
3755
  }
3749
3756
  return consumed;
3750
3757
  }
@@ -3766,13 +3773,13 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3766
3773
  async emitOpenTerminal(registration, draft) {
3767
3774
  const turn = draft.open_turn;
3768
3775
  if (turn === void 0 || turn.message_ids.length === 0) return;
3769
- const digest2 = terminalDigest(turn);
3770
- if (digest2 === turn.last_terminal_digest) return;
3771
- await this.putTerminalEnvelope(registration, turn, digest2, void 0);
3776
+ const digest = terminalDigest(turn);
3777
+ if (digest === turn.last_terminal_digest) return;
3778
+ await this.putTerminalEnvelope(registration, turn, digest, void 0);
3772
3779
  draft.enqueued += 1;
3773
- draft.open_turn = { ...turn, last_terminal_digest: digest2 };
3780
+ draft.open_turn = { ...turn, last_terminal_digest: digest };
3774
3781
  }
3775
- async putTerminalEnvelope(registration, turn, digest2, gapAt) {
3782
+ async putTerminalEnvelope(registration, turn, digest, gapAt) {
3776
3783
  const observedAt = gapAt ?? turn.last_observed_at;
3777
3784
  const tokenValue = turn.message_ids.length === 0 ? hostObservationNotRecorded("claude_turn_usage_not_observed") : availableTokenValue(turn.counts);
3778
3785
  const identity = { host_source_ref: registration.host_source_ref, host_session_ref: registration.host_session_ref, host_turn_ref: turn.turn_key };
@@ -3780,15 +3787,13 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3780
3787
  schema_version: "ceal.claude_observation_outbox.v1",
3781
3788
  identity,
3782
3789
  host_input_ref: turn.host_input_ref,
3783
- input_kind: "host_automatic",
3784
3790
  prompt_ref: turn.prompt_ref,
3785
3791
  observations: [
3786
- { observation_ref: observationRef("transcript_terminal", turn.turn_key, digest2), observation_kind: "turn", observed_at: observedAt, value: { status: "stopped", host_session_id_sha256: this.sha(registration.claude_session_id), host_turn_ref: turn.turn_key } },
3787
- { observation_ref: observationRef("transcript_token", turn.turn_key, digest2), observation_kind: "token", observed_at: observedAt, value: tokenValue },
3788
- { observation_ref: observationRef("transcript_cost", turn.turn_key, digest2), observation_kind: "cost", observed_at: observedAt, value: hostObservationNotRecorded("provider_cost_not_observed") }
3792
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_terminal", turn.turn_key, digest), observation_kind: "turn", observed_at: observedAt, value: { status: "stopped", host_session_id_sha256: this.sha(registration.claude_session_id), host_turn_ref: turn.turn_key } },
3793
+ { observation_ref: observationRef(registration.host_source_ref, "transcript_token", turn.turn_key, digest), observation_kind: "token", observed_at: observedAt, value: tokenValue }
3789
3794
  ],
3790
3795
  origin_input: false,
3791
- submission_ref: submissionRef("terminal", turn.turn_key, digest2, turn.prompt_ref),
3796
+ submission_ref: submissionRef("terminal", turn.turn_key, digest, turn.prompt_ref),
3792
3797
  created_at: observedAt,
3793
3798
  expires_at: this.expire(this.outboxRetentionMs)
3794
3799
  });
@@ -3813,30 +3818,6 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3813
3818
  updated_at: this.stamp()
3814
3819
  });
3815
3820
  }
3816
- async registerPrompt(sessionRef, turnRef, promptRef, prompt, expiresAt) {
3817
- if (this.producerInstallationRef === void 0 || this.registerCurrentPrompt === void 0) return false;
3818
- const register = this.registerCurrentPrompt;
3819
- const installationRef = this.producerInstallationRef;
3820
- return registerHostCurrentPromptDiagnosed(
3821
- () => register({
3822
- producer_id: "claude",
3823
- producer_installation_ref: installationRef,
3824
- local_session_ref: sessionRef,
3825
- local_turn_ref: turnRef,
3826
- prompt_ref: promptRef,
3827
- current_prompt: prompt,
3828
- context_expires_at: expiresAt
3829
- }),
3830
- (event) => this.diagnostic(event)
3831
- );
3832
- }
3833
- async releaseStoredPromptBestEffort(sessionRef, cursor) {
3834
- await this.releaseOpenTurnBestEffort(sessionRef, cursor?.open_turn);
3835
- }
3836
- async releaseOpenTurnBestEffort(sessionRef, turn) {
3837
- if (turn === void 0) return;
3838
- await this.releasePrompt(sessionRef, turn).catch(() => void 0);
3839
- }
3840
3821
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
3841
3822
  try {
3842
3823
  await this.store.activateInvocationContext(identity, promptRef, expiresAt, void 0, turnGenerationRef);
@@ -3847,7 +3828,6 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
3847
3828
  }
3848
3829
  }
3849
3830
  async quarantineStored(cursor, device, inode, reason) {
3850
- await this.releaseStoredPromptBestEffort(cursor.host_session_ref, cursor);
3851
3831
  await this.store.writeTranscriptCursor({ ...cursor, device, inode, status: "quarantined", reason, updated_at: this.stamp() });
3852
3832
  return null;
3853
3833
  }
@@ -3951,47 +3931,43 @@ function parseTranscriptLine(line) {
3951
3931
  return null;
3952
3932
  }
3953
3933
  }
3954
- function lineIdentity(record5) {
3955
- if (typeof record5.uuid !== "string" || record5.uuid.length === 0 || record5.uuid.length > 256) return null;
3956
- if (typeof record5.timestamp !== "string" || !Number.isFinite(Date.parse(record5.timestamp))) return null;
3957
- return { uuid: record5.uuid, timestamp: record5.timestamp };
3934
+ function lineIdentity(record4) {
3935
+ if (typeof record4.uuid !== "string" || record4.uuid.length === 0 || record4.uuid.length > 256) return null;
3936
+ if (typeof record4.timestamp !== "string" || !Number.isFinite(Date.parse(record4.timestamp))) return null;
3937
+ return { uuid: record4.uuid, timestamp: record4.timestamp };
3958
3938
  }
3959
- function isUserTurnLine(record5) {
3960
- if (!isTranscriptRecord(record5) || record5.type !== "user") return false;
3961
- if (!isTranscriptRecord(record5.message) || typeof record5.message.content !== "string") return false;
3962
- if (record5.isMeta === true && (!isTranscriptRecord(record5.origin) || typeof record5.origin.kind !== "string")) return false;
3963
- const identity = lineIdentity(record5);
3939
+ function isUserTurnLine(record4) {
3940
+ if (!isTranscriptRecord(record4) || record4.type !== "user") return false;
3941
+ if (!isTranscriptRecord(record4.message) || typeof record4.message.content !== "string") return false;
3942
+ if (record4.isMeta === true && (!isTranscriptRecord(record4.origin) || typeof record4.origin.kind !== "string")) return false;
3943
+ const identity = lineIdentity(record4);
3964
3944
  if (identity === null) throw new ClaudeHostError("payload_rejected", "Claude transcript user line is malformed.");
3965
3945
  return true;
3966
3946
  }
3967
- function isAssistantLine(record5) {
3968
- return isTranscriptRecord(record5) && record5.type === "assistant" && isTranscriptRecord(record5.message);
3969
- }
3970
- function isAssistantTerminalLine(record5) {
3971
- return isAssistantLine(record5) && (record5.message.stop_reason === "end_turn" || record5.message.stop_reason === "stop_sequence");
3947
+ function isAssistantLine(record4) {
3948
+ return isTranscriptRecord(record4) && record4.type === "assistant" && isTranscriptRecord(record4.message);
3972
3949
  }
3973
- function isAssistantUsageLine(record5) {
3974
- if (!isTranscriptRecord(record5)) return false;
3975
- if (!isAssistantLine(record5) || record5.message.usage === void 0) return false;
3976
- const identity = lineIdentity(record5);
3977
- if (identity === null || !isTranscriptRecord(record5.message.usage)) throw new ClaudeHostError("payload_rejected", "Claude transcript usage line is malformed.");
3950
+ function isAssistantUsageLine(record4) {
3951
+ if (!isTranscriptRecord(record4)) return false;
3952
+ if (!isAssistantLine(record4) || record4.message.usage === void 0) return false;
3953
+ const identity = lineIdentity(record4);
3954
+ if (identity === null || !isTranscriptRecord(record4.message.usage)) throw new ClaudeHostError("payload_rejected", "Claude transcript usage line is malformed.");
3978
3955
  return true;
3979
3956
  }
3980
3957
  function subagentsDirectory(transcriptPath) {
3981
3958
  const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
3982
- return join4(stem, "subagents");
3959
+ return join3(stem, "subagents");
3983
3960
  }
3984
- function observationRef(event, identity, value) {
3985
- return cealHostObservationRef("claude", transcriptObjectSha256({ event, identity, value }));
3961
+ function observationRef(hostSourceRef, event, identity, value) {
3962
+ return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
3986
3963
  }
3987
- function submissionRef(kind, turn, digest2, prompt) {
3988
- return `claude-submission:${transcriptObjectSha256({ kind, turn, digest: digest2, prompt })}`;
3964
+ function submissionRef(kind, turn, digest, prompt) {
3965
+ return `claude-submission:${transcriptObjectSha256({ kind, turn, digest, prompt })}`;
3989
3966
  }
3990
3967
  async function ownedClaudeTranscriptFile(handle) {
3991
3968
  const stats = await handle.stat();
3992
- const uid = typeof process.geteuid === "function" ? process.geteuid() : stats.uid;
3993
3969
  if (!stats.isFile()) throw new ClaudeHostError("payload_rejected", "Claude transcript source is not a regular file.");
3994
- if (stats.uid !== uid) throw new ClaudeHostError("payload_rejected", "Claude transcript source is owned by another user.");
3970
+ if (process.platform !== "win32" && !isSelfOwned(stats.uid, process.platform, handle)) throw new ClaudeHostError("payload_rejected", "Claude transcript source is owned by another user.");
3995
3971
  return { size: stats.size, device: String(stats.dev), inode: String(stats.ino) };
3996
3972
  }
3997
3973
  function isNotDirectory(error) {
@@ -4018,18 +3994,14 @@ function isSymlinkTranscript(error) {
4018
3994
 
4019
3995
  // host/claude/src/claude-producer-runtime.ts
4020
3996
  async function drainClaudeProducerOnce(options) {
4021
- const promptPort = new HostRelayCurrentPromptPort(options.relay_endpoint, options.timeout_ms);
4022
3997
  const scan = await new ClaudeTranscriptWatcher({
4023
3998
  outbox_dir: options.outbox_dir,
4024
- producer_installation_ref: options.producer_installation_ref,
4025
- register_current_prompt: (input) => promptPort.register(input),
4026
- release_current_prompt: (identity) => promptPort.release(identity),
4027
3999
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
4028
4000
  }).scanOnce().catch((error) => {
4029
4001
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
4030
4002
  throw error;
4031
4003
  });
4032
- const producer = new ClaudeProducer({ outbox_dir: options.outbox_dir, producer_installation_ref: options.producer_installation_ref, relay: new HostRelayIpcAdmissionPort(options.relay_endpoint, options.timeout_ms), ...options.producer_epoch === void 0 ? {} : { producer_epoch: options.producer_epoch }, ...options.now === void 0 ? {} : { now: options.now } });
4004
+ const producer = new ClaudeProducer({ outbox_dir: options.outbox_dir, ...options.now === void 0 ? {} : { now: options.now } });
4033
4005
  return { scanned: scan.enqueued, ...await producer.drainOutbox() };
4034
4006
  }
4035
4007
 
@@ -4042,11 +4014,7 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
4042
4014
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
4043
4015
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
4044
4016
  runtime_options: (config) => Object.freeze({
4045
- outbox_dir: config.outbox_dir,
4046
- producer_installation_ref: config.producer_installation_ref,
4047
- producer_epoch: config.producer_epoch,
4048
- relay_endpoint: config.relay_endpoint,
4049
- timeout_ms: config.ipc_timeout_ms
4017
+ outbox_dir: config.outbox_dir
4050
4018
  }),
4051
4019
  drain: drainClaudeProducerOnce
4052
4020
  };
@@ -4056,13 +4024,15 @@ function runClaudeProducerCli(args, signal, dependencies = {}) {
4056
4024
 
4057
4025
  // host/producer-command.ts
4058
4026
  async function runProducerCommand(schemaVersion, run) {
4027
+ const serviceArguments = consumeHostServiceLogArgument(process.argv.slice(2));
4028
+ if (serviceArguments.path !== void 0) process.env[HOST_SERVICE_LOG_ENVIRONMENT] = serviceArguments.path;
4059
4029
  const controller = new AbortController();
4060
4030
  const stop = () => controller.abort();
4061
4031
  process.once("SIGINT", stop);
4062
4032
  process.once("SIGTERM", stop);
4063
4033
  const stopLogBound = boundHostServiceLog();
4064
4034
  try {
4065
- await run(process.argv.slice(2), controller.signal);
4035
+ await run(serviceArguments.args, controller.signal);
4066
4036
  } catch (error) {
4067
4037
  const code2 = typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "producer_failed";
4068
4038
  process.stderr.write(`${JSON.stringify({ schema_version: schemaVersion, ok: false, code: code2 })}