@corca-org/ceal-host-win32-x64 1.0.24 → 1.0.26
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.
- package/README.md +2 -2
- package/bin/ceal-host.exe +0 -0
- package/libexec/ceal-host/ceal-host-background.exe +0 -0
- package/libexec/ceal-host/claude-hook.mjs +501 -110
- package/libexec/ceal-host/claude-invocation-authentication.mjs +799 -149
- package/libexec/ceal-host/claude-producer.mjs +1467 -1087
- package/libexec/ceal-host/codex-hook.mjs +461 -115
- package/libexec/ceal-host/codex-invocation-authentication.mjs +1021 -406
- package/libexec/ceal-host/codex-producer.mjs +1429 -1088
- package/libexec/ceal-host/control.mjs +2312 -1296
- package/libexec/ceal-host/node/bin/node.exe +2 -2
- package/package.json +1 -1
- package/share/ceal-host/bundle-manifest.json +15 -22
- package/share/ceal-host/bundle-manifest.sigstore.json +1 -1
- package/libexec/ceal-host/relay.mjs +0 -4873
|
@@ -277,6 +277,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
|
|
|
277
277
|
// (never connected, revoked, or expired). The caller runs that exact
|
|
278
278
|
// Operation, completes the consent it hands back, and retries the same call.
|
|
279
279
|
"connect_personal_account",
|
|
280
|
+
// The refusal names the caller's own preferences update step: the read
|
|
281
|
+
// needs a personal connection the caller holds but has not selected in
|
|
282
|
+
// Ceal preferences, or has not confirmed through the initial review. The
|
|
283
|
+
// caller reads personal.preferences.get, runs personal.preferences.update
|
|
284
|
+
// at the current revision to select it, and retries the same call.
|
|
285
|
+
"update_personal_preferences",
|
|
280
286
|
// The provider or Gateway named a bounded wait; the caller waits that long
|
|
281
287
|
// and submits the same read again.
|
|
282
288
|
"retry_after",
|
|
@@ -427,7 +433,7 @@ var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
|
|
|
427
433
|
var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
|
|
428
434
|
var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
|
|
429
435
|
var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
|
|
430
|
-
var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
|
|
436
|
+
var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "race_recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
|
|
431
437
|
var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
|
|
432
438
|
var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
|
|
433
439
|
var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
|
|
@@ -825,15 +831,19 @@ function requireIsoTimestamp(value, message) {
|
|
|
825
831
|
// packages/ceal-client-protocol/src/failure-guidance-table.ts
|
|
826
832
|
var CEAL_FAILURE_REDACTION_CLASSES = vocabulary(["model_safe", "withheld"]);
|
|
827
833
|
var CEAL_GATEWAY_STARTING_FAILURE_CODE = "gateway_starting";
|
|
834
|
+
var CEAL_GATEWAY_RESTARTING_FAILURE_CODE = "gateway_restarting";
|
|
828
835
|
var CEAL_OWNER_BOOTSTRAP_ABSENT_FAILURE_CODE = "bootstrap_absent";
|
|
829
836
|
var CEAL_OWNER_BOOTSTRAP_UNAVAILABLE_FAILURE_CODE = "bootstrap_unavailable";
|
|
830
837
|
var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
|
|
831
838
|
var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
|
|
832
839
|
var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
|
|
833
840
|
var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
|
|
834
|
-
var
|
|
841
|
+
var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
|
|
842
|
+
var CLIENT_HOST_RELEASE_MISMATCH = `Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry. Update with \`${CEAL_CLIENT_UPGRADE_COMMAND}\`.`;
|
|
835
843
|
var HOST_INSTALL_REPAIR = "The local Host or Relay is missing, stale, or unavailable. Run `ceal-host install`, then `ceal-host discovery sync`, and retry from a new producer conversation.";
|
|
836
|
-
var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn;
|
|
844
|
+
var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn right now; the Host may be restarting. Wait briefly and retry the same command. If you know you are in an ephemeral side conversation, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions without Host session/turn correlation. Otherwise return to the original regular conversation. Host refusal never switches modes. If the retry still fails, report intended Host calls as a gap.";
|
|
845
|
+
var HOST_TRANSCRIPT_UNAVAILABLE = "The Host found no human message in the registered transcript for this turn, so this call has nothing to bind to. Send a new message in the current conversation so the Host re-registers the transcript, then retry the same command. If it still fails, start a new conversation and report intended Host calls as a gap. Host refusal never switches modes.";
|
|
846
|
+
var HOST_RELAY_RESTARTING = "The Host Relay is temporarily unavailable while the Host restarts; wait briefly and retry the same command. If the retry still fails, report this as a gap.";
|
|
837
847
|
var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
|
|
838
848
|
var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
|
|
839
849
|
function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
|
|
@@ -863,6 +873,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
863
873
|
person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Person, then retry this same session refresh.", "ask_admin", 403),
|
|
864
874
|
principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Principal, then retry this same session refresh.", "ask_admin", 403),
|
|
865
875
|
authority_replaced: guidance("The Gateway authority has been replaced; this session is no longer valid here. Run `ceal session adopt --gateway <origin> --email <email>` against the current Gateway to complete mailbox-confirmed recovery.", "repair_or_adopt_session", 409),
|
|
876
|
+
// A stored session that predates the authority-epoch commitment carries no
|
|
877
|
+
// epoch to compare, so it can never refresh: adopt a fresh session instead.
|
|
878
|
+
authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
|
|
866
879
|
refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
|
|
867
880
|
refresh_recovery_unavailable: guidance("The Gateway's durable refresh-recovery key is unavailable. Retry the same refresh attempt after the key is available.", "retry", 503, true),
|
|
868
881
|
refresh_recovery_outcome_unavailable: guidance("The Gateway could not safely recover the outcome of a prior refresh. Ask an administrator to inspect the Gateway session state before retrying or adopting this session.", "ask_admin", 503),
|
|
@@ -884,6 +897,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
884
897
|
contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
|
|
885
898
|
// The serving gate answers before refresh execution, so retrying the same attempt is safe.
|
|
886
899
|
[CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance("The Gateway is still starting; the refresh was not attempted and the refresh token was not consumed. Retry the same refresh attempt after the Gateway is serving.", "retry", 503, true),
|
|
900
|
+
// The serving gate answers before execution while the Gateway is stopping, so retrying the same request is safe.
|
|
901
|
+
[CEAL_GATEWAY_RESTARTING_FAILURE_CODE]: guidance("The Gateway is restarting; the request was not attempted. Retry the same request after the Gateway is serving.", "retry", 503, true),
|
|
887
902
|
gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
|
|
888
903
|
// The serving gate emits this code with no message; the sentence is the owner-normalized form of the
|
|
889
904
|
// `gateway_internal_error` guidance (decided with the operator 2026-10-13).
|
|
@@ -987,10 +1002,11 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
987
1002
|
host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
|
|
988
1003
|
// The bounded Host reason does not prove ephemerality. A Host refusal never
|
|
989
1004
|
// changes mode; standalone remains the separate Client authority path.
|
|
990
|
-
host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "
|
|
1005
|
+
host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
|
|
991
1006
|
host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
|
|
992
1007
|
host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
|
|
993
1008
|
host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
|
|
1009
|
+
host_transcript_unavailable: guidance(HOST_TRANSCRIPT_UNAVAILABLE, "retry", 401, true),
|
|
994
1010
|
host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
|
|
995
1011
|
host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
|
|
996
1012
|
host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
|
|
@@ -1004,7 +1020,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
1004
1020
|
// Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
|
|
1005
1021
|
// sandboxed Relay socket names the run-alone retry.
|
|
1006
1022
|
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),
|
|
1007
|
-
host_relay_unavailable: guidance(
|
|
1023
|
+
host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
|
|
1008
1024
|
host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
|
|
1009
1025
|
host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
|
|
1010
1026
|
host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
|
|
@@ -1269,7 +1285,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
|
|
|
1269
1285
|
max_literal_nodes: 512
|
|
1270
1286
|
});
|
|
1271
1287
|
|
|
1272
|
-
// packages/ceal-client-protocol/src/operation-json-schema.ts
|
|
1288
|
+
// packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
|
|
1273
1289
|
var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
|
|
1274
1290
|
|
|
1275
1291
|
// packages/ceal-client-protocol/src/operation-contract-validation.ts
|
|
@@ -1379,6 +1395,8 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
|
|
|
1379
1395
|
});
|
|
1380
1396
|
|
|
1381
1397
|
// packages/ceal-client-protocol/src/canonical-http-boundary.ts
|
|
1398
|
+
var CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE = "^client-exchange:[a-f0-9]{32}$";
|
|
1399
|
+
var CEAL_HTTP_GATEWAY_REQUEST_REF_PATTERN_SOURCE = "^http-request:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
|
|
1382
1400
|
var CEAL_CANONICAL_HTTP_MAX_RESPONSE_BYTES = CEAL_COMMAND_RESPONSE_MAX_BYTES;
|
|
1383
1401
|
|
|
1384
1402
|
// packages/ceal-client-protocol/src/gateway-installation-activation.ts
|
|
@@ -1403,6 +1421,7 @@ var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUI
|
|
|
1403
1421
|
var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
|
|
1404
1422
|
|
|
1405
1423
|
// packages/ceal-client-protocol/src/resource-read-result.ts
|
|
1424
|
+
var CEAL_RESOURCE_GET_CHILD_REF_KINDS = Object.freeze(["section", "slide", "question"]);
|
|
1406
1425
|
var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
|
|
1407
1426
|
var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
|
|
1408
1427
|
var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
|
|
@@ -1419,7 +1438,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
|
|
|
1419
1438
|
var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
|
|
1420
1439
|
var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
|
|
1421
1440
|
var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
|
|
1422
|
-
var
|
|
1441
|
+
var CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE = `For caller-owned fields, add ${CEAL_OPERATION_INPUT_FLAG} ${shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)}. Use inline JSON for short input; for longer or generated input, put exactly one JSON object in a caller-owned regular non-symlink UTF-8 JSON file and pass --input @path; relative paths resolve from the command working directory.`;
|
|
1442
|
+
var CEAL_MODEL_INPUT_SOURCE_GUIDANCE = `${CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE} On Windows, write the JSON file first; use the program's .cmd launcher with --input and only one quoted @path argument.`;
|
|
1423
1443
|
function shellSingleQuoted(value) {
|
|
1424
1444
|
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
1425
1445
|
}
|
|
@@ -1605,6 +1625,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
|
|
|
1605
1625
|
"github.review.submitted",
|
|
1606
1626
|
"github.issue_comment.created",
|
|
1607
1627
|
"github.review_comment.created",
|
|
1628
|
+
"github.issue_comment.edited",
|
|
1629
|
+
"github.review_comment.edited",
|
|
1608
1630
|
"github.reaction.created",
|
|
1609
1631
|
"github.reaction.deleted",
|
|
1610
1632
|
"github.pull_request.review_requested",
|
|
@@ -1633,6 +1655,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
|
|
|
1633
1655
|
"github.release.published": "release_published",
|
|
1634
1656
|
"github.issue.edited": "resource_modified",
|
|
1635
1657
|
"github.pull_request.edited": "resource_modified",
|
|
1658
|
+
"github.issue_comment.edited": "resource_modified",
|
|
1659
|
+
"github.review_comment.edited": "resource_modified",
|
|
1636
1660
|
"github.reaction.created": "reaction_created",
|
|
1637
1661
|
"github.reaction.deleted": "ceal_write_completed",
|
|
1638
1662
|
"github.pull_request.review_requested": "ceal_write_completed",
|
|
@@ -2295,6 +2319,8 @@ var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
|
|
|
2295
2319
|
var HOST_CONTEXT_EXPIRY_MAX_CHARS = 64;
|
|
2296
2320
|
var CEAL_HOST_INVOCATION_CONTEXT_VISIBLE_OUTPUT_MAX_BYTES = CEAL_CANONICAL_HTTP_MAX_RESPONSE_BYTES;
|
|
2297
2321
|
var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
|
|
2322
|
+
var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_ENTRY_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text", "text_truncated"]);
|
|
2323
|
+
var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_REQUIRED_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text"]);
|
|
2298
2324
|
function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
|
|
2299
2325
|
const messages = [];
|
|
2300
2326
|
let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
|
|
@@ -2426,6 +2452,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
|
|
|
2426
2452
|
"context_replaced",
|
|
2427
2453
|
"no_binding",
|
|
2428
2454
|
"context_expired",
|
|
2455
|
+
"transcript_unavailable",
|
|
2429
2456
|
"host_source_refused",
|
|
2430
2457
|
"host_credential_refused",
|
|
2431
2458
|
"gateway_unavailable",
|
|
@@ -2455,9 +2482,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
|
2455
2482
|
invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
|
|
2456
2483
|
options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
|
|
2457
2484
|
session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
|
|
2458
|
-
//
|
|
2459
|
-
//
|
|
2460
|
-
|
|
2485
|
+
// A missing turn right after a Host restart clears by itself once the
|
|
2486
|
+
// watcher reactivates the turn, so the caller waits briefly and retries;
|
|
2487
|
+
// a caller that knows it is in an ephemeral side conversation keeps the
|
|
2488
|
+
// standalone fallback the guidance names second.
|
|
2489
|
+
context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
|
|
2461
2490
|
activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
|
|
2462
2491
|
context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
|
|
2463
2492
|
// `no_binding` now means the producer has no real current Host session. The
|
|
@@ -2465,6 +2494,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
|
2465
2494
|
// useful retry until the consumer is running inside a Host session.
|
|
2466
2495
|
no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
|
|
2467
2496
|
context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
|
|
2497
|
+
// The registered transcript is readable but names no human message for
|
|
2498
|
+
// this turn, so a Gateway mint could only be refused. The caller sends a
|
|
2499
|
+
// new message so the turn hook re-registers the transcript, then retries;
|
|
2500
|
+
// a retry with no new turn cannot bind anything new.
|
|
2501
|
+
transcript_unavailable: Object.freeze({ classification: "host_transcript_unavailable", next_action: "retry" }),
|
|
2468
2502
|
host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
|
|
2469
2503
|
host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
|
|
2470
2504
|
gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
|
|
@@ -2474,7 +2508,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
|
2474
2508
|
gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
|
|
2475
2509
|
producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
|
|
2476
2510
|
relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
|
|
2477
|
-
relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "
|
|
2511
|
+
relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
|
|
2478
2512
|
transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
|
|
2479
2513
|
mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
|
|
2480
2514
|
relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
|
|
@@ -2601,11 +2635,15 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
|
|
|
2601
2635
|
|
|
2602
2636
|
// packages/ceal-client-protocol/src/operator-diagnostic.ts
|
|
2603
2637
|
var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
|
|
2604
|
-
var
|
|
2638
|
+
var OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES = 8;
|
|
2605
2639
|
var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
|
|
2606
2640
|
var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
|
|
2607
2641
|
var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
|
|
2608
2642
|
var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
|
|
2643
|
+
var LOCAL_OPERATOR_DIAGNOSTIC_PATHS = /* @__PURE__ */ Symbol.for("ceal.local-operator-diagnostic-paths");
|
|
2644
|
+
var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX = /(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)/u;
|
|
2645
|
+
var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START = new RegExp(`^${OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX.source}`, "u");
|
|
2646
|
+
var OPERATOR_DIAGNOSTIC_FREEFORM_PATH_PATTERN = new RegExp(String.raw`(?<![A-Za-z0-9._-]|\[home path redacted\])${OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX.source}((?:(?!; stdout=|; stderr=)[^:\r\n"'<>])*?)( exited \d+)?(?=; stdout=|; stderr=|:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])`, "gu");
|
|
2609
2647
|
function redactOperatorDiagnosticSecrets(value) {
|
|
2610
2648
|
return value.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer [redacted]").replace(/(["']?(?:authorization|[A-Za-z0-9_-]*(?:token|secret|credential|password|key))["']?\s*[:=]\s*)(?!(?:"unknown"|'unknown'|unknown\b))(?:"[^"]*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
|
|
2611
2649
|
}
|
|
@@ -2614,8 +2652,9 @@ function redactOperatorDiagnosticText(value) {
|
|
|
2614
2652
|
return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
|
|
2615
2653
|
}
|
|
2616
2654
|
function renderOperatorDiagnostic(value) {
|
|
2617
|
-
const state = collectDiagnosticState(value);
|
|
2655
|
+
const state = collectDiagnosticState(value, read(value, LOCAL_OPERATOR_DIAGNOSTIC_PATHS) === true);
|
|
2618
2656
|
const fields = [
|
|
2657
|
+
state.truncated ? "causes_truncated=true" : void 0,
|
|
2619
2658
|
state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
|
|
2620
2659
|
state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
|
|
2621
2660
|
state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
|
|
@@ -2625,23 +2664,27 @@ function renderOperatorDiagnostic(value) {
|
|
|
2625
2664
|
const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
|
|
2626
2665
|
return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
|
|
2627
2666
|
}
|
|
2628
|
-
function collectDiagnosticState(value) {
|
|
2629
|
-
const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
|
|
2667
|
+
function collectDiagnosticState(value, preserveLocalAbsolutePaths) {
|
|
2668
|
+
const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0, truncated: false };
|
|
2630
2669
|
const visited = /* @__PURE__ */ new Set(), pending = [value];
|
|
2631
|
-
|
|
2670
|
+
let inspected = 0;
|
|
2671
|
+
while (pending.length > 0 && inspected < OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES) {
|
|
2632
2672
|
const current = pending.shift();
|
|
2633
|
-
if (current
|
|
2673
|
+
if (current === void 0 || isObject(current) && visited.has(current)) continue;
|
|
2674
|
+
inspected += 1;
|
|
2675
|
+
visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths);
|
|
2634
2676
|
}
|
|
2677
|
+
state.truncated ||= pending.length > 0;
|
|
2635
2678
|
return state;
|
|
2636
2679
|
}
|
|
2637
|
-
function visitDiagnosticNode(current, state, pending, visited) {
|
|
2680
|
+
function visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths) {
|
|
2638
2681
|
if (isObject(current)) {
|
|
2639
2682
|
if (visited.has(current)) return;
|
|
2640
2683
|
visited.add(current);
|
|
2641
2684
|
}
|
|
2642
2685
|
captureProcessEvidence(current, state);
|
|
2643
|
-
appendCause(current, state.causes);
|
|
2644
|
-
enqueueCauseChildren(current, state
|
|
2686
|
+
appendCause(current, state.causes, preserveLocalAbsolutePaths);
|
|
2687
|
+
enqueueCauseChildren(current, state, pending);
|
|
2645
2688
|
}
|
|
2646
2689
|
function captureProcessEvidence(current, state) {
|
|
2647
2690
|
if (state.status === void 0) state.status = safeStatus(read(current, "status"));
|
|
@@ -2649,10 +2692,9 @@ function captureProcessEvidence(current, state) {
|
|
|
2649
2692
|
if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
|
|
2650
2693
|
if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
|
|
2651
2694
|
}
|
|
2652
|
-
function appendCause(current, causes) {
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
causes.push(errorCause(current));
|
|
2695
|
+
function appendCause(current, causes, preserveLocalAbsolutePaths) {
|
|
2696
|
+
if (current instanceof Error) {
|
|
2697
|
+
causes.push(errorCause(current, preserveLocalAbsolutePaths));
|
|
2656
2698
|
return;
|
|
2657
2699
|
}
|
|
2658
2700
|
if (!isObject(current)) {
|
|
@@ -2660,7 +2702,7 @@ function appendCause(current, causes) {
|
|
|
2660
2702
|
if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
|
|
2661
2703
|
}
|
|
2662
2704
|
}
|
|
2663
|
-
function errorCause(error) {
|
|
2705
|
+
function errorCause(error, preserveLocalAbsolutePaths) {
|
|
2664
2706
|
const name = safeText(read(error, "name")) ?? "Error";
|
|
2665
2707
|
const message = safeText(read(error, "message"));
|
|
2666
2708
|
const codeValue = read(error, "code");
|
|
@@ -2668,14 +2710,29 @@ function errorCause(error) {
|
|
|
2668
2710
|
const errnoValue = read(error, "errno");
|
|
2669
2711
|
const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
|
|
2670
2712
|
const syscall = safeText(read(error, "syscall"));
|
|
2671
|
-
const path = safePath(read(error, "path"));
|
|
2713
|
+
const path = safePath(read(error, "path"), preserveLocalAbsolutePaths);
|
|
2672
2714
|
return Object.freeze({ error_class: name, ...message === void 0 ? {} : { message }, ...code2 === void 0 ? {} : { code: code2 }, ...errno === void 0 ? {} : { errno }, ...syscall === void 0 ? {} : { syscall }, ...path === void 0 ? {} : { path } });
|
|
2673
2715
|
}
|
|
2674
|
-
function enqueueCauseChildren(current,
|
|
2716
|
+
function enqueueCauseChildren(current, state, pending) {
|
|
2675
2717
|
const cause = read(current, "cause");
|
|
2676
2718
|
if (cause !== void 0) pending.push(cause);
|
|
2677
2719
|
const errors = read(current, "errors");
|
|
2678
|
-
if (Array.isArray(errors))
|
|
2720
|
+
if (Array.isArray(errors)) {
|
|
2721
|
+
const remaining = OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES - state.causes.length;
|
|
2722
|
+
const length = read(errors, "length");
|
|
2723
|
+
if (typeof length !== "number") {
|
|
2724
|
+
state.truncated = true;
|
|
2725
|
+
return;
|
|
2726
|
+
}
|
|
2727
|
+
state.truncated ||= length > remaining;
|
|
2728
|
+
for (let index = 0; index < Math.min(length, remaining); index += 1) {
|
|
2729
|
+
try {
|
|
2730
|
+
pending.push(errors[index]);
|
|
2731
|
+
} catch {
|
|
2732
|
+
state.truncated = true;
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2679
2736
|
}
|
|
2680
2737
|
function isObject(value) {
|
|
2681
2738
|
return typeof value === "object" && value !== null;
|
|
@@ -2704,10 +2761,11 @@ function safeText(value) {
|
|
|
2704
2761
|
const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
|
|
2705
2762
|
return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
|
|
2706
2763
|
}
|
|
2707
|
-
function safePath(value) {
|
|
2764
|
+
function safePath(value, preserveLocalAbsolutePaths) {
|
|
2708
2765
|
if (typeof value !== "string") return void 0;
|
|
2709
2766
|
const safe = safeDiagnosticText(value);
|
|
2710
2767
|
if (safe.length === 0) return void 0;
|
|
2768
|
+
if (!preserveLocalAbsolutePaths && hasAbsolutePathPrefix(value) && !safe.startsWith("[home path redacted]")) return "[path redacted]";
|
|
2711
2769
|
if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
|
|
2712
2770
|
const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
|
|
2713
2771
|
const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
|
|
@@ -2779,7 +2837,10 @@ function redactUrls(value) {
|
|
|
2779
2837
|
return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
|
|
2780
2838
|
}
|
|
2781
2839
|
function redactFilePaths(value) {
|
|
2782
|
-
return value.replaceAll(
|
|
2840
|
+
return value.replaceAll(OPERATOR_DIAGNOSTIC_FREEFORM_PATH_PATTERN, "[path redacted]$2");
|
|
2841
|
+
}
|
|
2842
|
+
function hasAbsolutePathPrefix(value) {
|
|
2843
|
+
return OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START.test(value);
|
|
2783
2844
|
}
|
|
2784
2845
|
function homePathRange(value, match, prefixLength) {
|
|
2785
2846
|
const index = match.index;
|
|
@@ -2958,30 +3019,24 @@ function hostClientProbeRefusal(probe, subject) {
|
|
|
2958
3019
|
}
|
|
2959
3020
|
|
|
2960
3021
|
// host/invocation-authentication-command.ts
|
|
2961
|
-
import {
|
|
3022
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
3023
|
+
import { performance as performance2 } from "node:perf_hooks";
|
|
2962
3024
|
|
|
2963
3025
|
// host/relay/src/producer-frame.ts
|
|
2964
3026
|
var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
|
|
2965
3027
|
var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "turn_terminal", "producer_status"];
|
|
2966
3028
|
var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
|
|
2967
|
-
var HOST_PRODUCER_FRAME_ERROR_CODES = [
|
|
2968
|
-
"invalid_frame_encoding",
|
|
2969
|
-
"invalid_frame_length",
|
|
2970
|
-
"frame_truncated",
|
|
2971
|
-
"unsupported_frame_schema",
|
|
2972
|
-
"invalid_frame_shape",
|
|
2973
|
-
"invalid_producer_identity",
|
|
2974
|
-
"frame_too_large"
|
|
2975
|
-
];
|
|
2976
3029
|
|
|
2977
3030
|
// host/relay/src/host-producer-core.ts
|
|
2978
3031
|
import { createHash as createHash4 } from "node:crypto";
|
|
3032
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3033
|
+
import { lstat as lstat2, readdir, stat as stat2 } from "node:fs/promises";
|
|
2979
3034
|
|
|
2980
3035
|
// host/secure-file.ts
|
|
2981
3036
|
import { execFile } from "node:child_process";
|
|
2982
3037
|
import { constants } from "node:fs";
|
|
2983
3038
|
import { lstat, open } from "node:fs/promises";
|
|
2984
|
-
import { dirname, join as join2, win32 } from "node:path";
|
|
3039
|
+
import { dirname, join as join2, parse, win32 } from "node:path";
|
|
2985
3040
|
import { fileURLToPath } from "node:url";
|
|
2986
3041
|
var SecureFileCustodyError = class extends Error {
|
|
2987
3042
|
name = "SecureFileCustodyError";
|
|
@@ -3090,7 +3145,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
|
|
|
3090
3145
|
const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
|
|
3091
3146
|
const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
|
|
3092
3147
|
return await new Promise((resolve, reject) => {
|
|
3093
|
-
const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
|
|
3148
|
+
const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: parse(executable).root }, (error, stdout, stderr) => {
|
|
3094
3149
|
const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
|
|
3095
3150
|
if (exitCode === null) {
|
|
3096
3151
|
reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
|
|
@@ -3341,7 +3396,9 @@ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
|
|
|
3341
3396
|
seen.add(message.host_input_ref);
|
|
3342
3397
|
newestFirst.push(message);
|
|
3343
3398
|
}
|
|
3344
|
-
|
|
3399
|
+
const currentTurn = newestFirst[0]?.host_turn_ref;
|
|
3400
|
+
const currentTurnFirst = currentTurn === void 0 ? newestFirst : newestFirst.filter((message) => message.host_turn_ref === currentTurn);
|
|
3401
|
+
return boundCealHostInvocationHumanMessageWindow(currentTurnFirst, existing?.truncated ?? false);
|
|
3345
3402
|
}
|
|
3346
3403
|
async function readRegisteredHostInvocationHumanMessageWindow(readRegistration, readCursor, identity, decodeLine) {
|
|
3347
3404
|
try {
|
|
@@ -3455,6 +3512,15 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
|
|
|
3455
3512
|
if (cursor.offset > 0 && !await transcriptAnchorMatches(handle, cursor)) return "transcript_rewritten";
|
|
3456
3513
|
return null;
|
|
3457
3514
|
}
|
|
3515
|
+
async function statObservedPathSignature(path) {
|
|
3516
|
+
try {
|
|
3517
|
+
const info = await lstat2(path, { bigint: true });
|
|
3518
|
+
if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) return null;
|
|
3519
|
+
return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
3520
|
+
} catch {
|
|
3521
|
+
return null;
|
|
3522
|
+
}
|
|
3523
|
+
}
|
|
3458
3524
|
function transcriptSha256(value) {
|
|
3459
3525
|
return createHash4("sha256").update(value).digest("hex");
|
|
3460
3526
|
}
|
|
@@ -3487,27 +3553,71 @@ function createTranscriptWatcherBase(options, owner) {
|
|
|
3487
3553
|
producerInstallationRef: options.producer_installation_ref
|
|
3488
3554
|
};
|
|
3489
3555
|
}
|
|
3490
|
-
async function scanTranscriptRegistrations(registrations, scanOne) {
|
|
3556
|
+
async function scanTranscriptRegistrations(registrations, scanOne, totalRegistrations, signal) {
|
|
3491
3557
|
let records = 0;
|
|
3492
3558
|
let enqueued = 0;
|
|
3493
3559
|
let quarantined = 0;
|
|
3560
|
+
let scanned = 0;
|
|
3494
3561
|
for (const registration of registrations) {
|
|
3562
|
+
if (signal?.aborted) break;
|
|
3563
|
+
scanned += 1;
|
|
3495
3564
|
const result = await scanOne(registration);
|
|
3496
3565
|
records += result.records;
|
|
3497
3566
|
enqueued += result.enqueued;
|
|
3498
3567
|
if (result.quarantined) quarantined += 1;
|
|
3499
3568
|
}
|
|
3500
|
-
return { registrations:
|
|
3569
|
+
return { registrations: totalRegistrations ?? scanned, records, enqueued, quarantined };
|
|
3570
|
+
}
|
|
3571
|
+
var HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS = 1000000000n;
|
|
3572
|
+
var HostRegistrationInventory = class {
|
|
3573
|
+
signature;
|
|
3574
|
+
registrations;
|
|
3575
|
+
nowNs;
|
|
3576
|
+
observeDirectory;
|
|
3577
|
+
constructor(options = {}) {
|
|
3578
|
+
this.nowNs = options.nowNs ?? (() => BigInt(Date.now()) * 1000000n);
|
|
3579
|
+
this.observeDirectory = options.observeDirectory ?? hostRegistrationDirectorySignature;
|
|
3580
|
+
}
|
|
3581
|
+
async read(directory, load) {
|
|
3582
|
+
const observation = await this.observeDirectory(directory);
|
|
3583
|
+
const nowNs = this.nowNs();
|
|
3584
|
+
const racy = nowNs - observation.mtimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS || nowNs - observation.ctimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS;
|
|
3585
|
+
if (this.registrations !== void 0 && this.signature === observation.signature && !racy) return this.registrations;
|
|
3586
|
+
const registrations = await load();
|
|
3587
|
+
this.signature = observation.signature;
|
|
3588
|
+
this.registrations = registrations;
|
|
3589
|
+
return registrations;
|
|
3590
|
+
}
|
|
3591
|
+
};
|
|
3592
|
+
async function hostRegistrationDirectorySignature(directory) {
|
|
3593
|
+
try {
|
|
3594
|
+
const info = await stat2(directory, { bigint: true });
|
|
3595
|
+
return {
|
|
3596
|
+
signature: `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`,
|
|
3597
|
+
mtimeNs: info.mtimeNs,
|
|
3598
|
+
ctimeNs: info.ctimeNs
|
|
3599
|
+
};
|
|
3600
|
+
} catch (error) {
|
|
3601
|
+
if (isMissingTranscriptError(error)) return { signature: "missing", mtimeNs: 0n, ctimeNs: 0n };
|
|
3602
|
+
throw error;
|
|
3603
|
+
}
|
|
3501
3604
|
}
|
|
3502
3605
|
function formatRetiredTranscriptLog(producerLabel, transcriptPath) {
|
|
3503
3606
|
return `${producerLabel} retired a transcript registration: transcript_path=${JSON.stringify(transcriptPath)}, reason=${TRANSCRIPT_MISSING_REASON}.`;
|
|
3504
3607
|
}
|
|
3608
|
+
var HOST_TRANSCRIPT_RECONCILIATION_BATCH = 100;
|
|
3505
3609
|
var HostTranscriptWatcher = class {
|
|
3506
3610
|
outboxRetentionMs;
|
|
3507
3611
|
now;
|
|
3508
3612
|
log;
|
|
3509
3613
|
producerInstallationRef;
|
|
3510
3614
|
clockFailure;
|
|
3615
|
+
transcriptObservations = /* @__PURE__ */ new Map();
|
|
3616
|
+
registrationSnapshot;
|
|
3617
|
+
// Advisory scheduling only: listRegistrations remains the registration authority.
|
|
3618
|
+
hotRegistrations = /* @__PURE__ */ new Set();
|
|
3619
|
+
reconciliation;
|
|
3620
|
+
reconciliationRemaining = 0;
|
|
3511
3621
|
constructor(options, owner) {
|
|
3512
3622
|
const base = createTranscriptWatcherBase(options, owner);
|
|
3513
3623
|
this.outboxRetentionMs = base.outboxRetentionMs;
|
|
@@ -3516,8 +3626,97 @@ var HostTranscriptWatcher = class {
|
|
|
3516
3626
|
this.producerInstallationRef = base.producerInstallationRef;
|
|
3517
3627
|
this.clockFailure = owner.clock_failure;
|
|
3518
3628
|
}
|
|
3519
|
-
async scanOnce() {
|
|
3520
|
-
|
|
3629
|
+
async scanOnce(signal) {
|
|
3630
|
+
if (signal?.aborted) return { registrations: this.registrationSnapshot?.length ?? 0, records: 0, enqueued: 0, quarantined: 0 };
|
|
3631
|
+
const registrations = await this.listRegistrations();
|
|
3632
|
+
this.reconcileSnapshot(registrations);
|
|
3633
|
+
return scanTranscriptRegistrations(this.scanCandidates(), (observation) => this.observeRegistration(observation, signal), registrations.length, signal);
|
|
3634
|
+
}
|
|
3635
|
+
async observeRegistration(observation, signal) {
|
|
3636
|
+
const registration = observation.registration;
|
|
3637
|
+
const signature = await this.scanFingerprint(registration);
|
|
3638
|
+
if (signal?.aborted) return { records: 0, enqueued: 0, quarantined: false };
|
|
3639
|
+
this.hotRegistrations.delete(observation);
|
|
3640
|
+
if (signature !== null && observation.signature === signature) return { records: 0, enqueued: 0, quarantined: false };
|
|
3641
|
+
this.hotRegistrations.add(observation);
|
|
3642
|
+
const result = await this.scanRegistration(registration);
|
|
3643
|
+
if (result.quarantined || result.retry === true) observation.signature = void 0;
|
|
3644
|
+
else {
|
|
3645
|
+
observation.signature = signature ?? void 0;
|
|
3646
|
+
if (result.records === 0) this.hotRegistrations.delete(observation);
|
|
3647
|
+
}
|
|
3648
|
+
return result;
|
|
3649
|
+
}
|
|
3650
|
+
*scanCandidates() {
|
|
3651
|
+
const hotSlice = [];
|
|
3652
|
+
for (const observation of this.hotRegistrations) {
|
|
3653
|
+
hotSlice.push(observation);
|
|
3654
|
+
if (hotSlice.length === HOST_TRANSCRIPT_RECONCILIATION_BATCH) break;
|
|
3655
|
+
}
|
|
3656
|
+
const observed = /* @__PURE__ */ new Set();
|
|
3657
|
+
for (let count = 0; count < Math.min(this.transcriptObservations.size, HOST_TRANSCRIPT_RECONCILIATION_BATCH); count += 1) {
|
|
3658
|
+
const observation = this.nextReconciliation();
|
|
3659
|
+
if (observation === void 0) break;
|
|
3660
|
+
observed.add(observation);
|
|
3661
|
+
yield observation;
|
|
3662
|
+
}
|
|
3663
|
+
for (const observation of hotSlice) if (!observed.has(observation)) yield observation;
|
|
3664
|
+
}
|
|
3665
|
+
nextReconciliation() {
|
|
3666
|
+
if (this.reconciliationRemaining === 0 || this.reconciliation === void 0) {
|
|
3667
|
+
this.reconciliation = this.transcriptObservations.values();
|
|
3668
|
+
this.reconciliationRemaining = this.transcriptObservations.size;
|
|
3669
|
+
}
|
|
3670
|
+
let next = this.reconciliation.next();
|
|
3671
|
+
if (next.done) {
|
|
3672
|
+
this.reconciliation = this.transcriptObservations.values();
|
|
3673
|
+
this.reconciliationRemaining = this.transcriptObservations.size;
|
|
3674
|
+
next = this.reconciliation.next();
|
|
3675
|
+
}
|
|
3676
|
+
this.reconciliationRemaining -= 1;
|
|
3677
|
+
return next.value;
|
|
3678
|
+
}
|
|
3679
|
+
reconcileSnapshot(registrations) {
|
|
3680
|
+
if (this.registrationSnapshot === registrations) return;
|
|
3681
|
+
const retained = /* @__PURE__ */ new Set();
|
|
3682
|
+
const hot = /* @__PURE__ */ new Set();
|
|
3683
|
+
for (const registration of registrations) {
|
|
3684
|
+
const key = this.registrationKey(registration);
|
|
3685
|
+
retained.add(key);
|
|
3686
|
+
let observation = this.transcriptObservations.get(key);
|
|
3687
|
+
if (observation === void 0) {
|
|
3688
|
+
observation = { registration, signature: void 0 };
|
|
3689
|
+
this.transcriptObservations.set(key, observation);
|
|
3690
|
+
hot.add(observation);
|
|
3691
|
+
} else {
|
|
3692
|
+
if (!isDeepStrictEqual(observation.registration, registration)) {
|
|
3693
|
+
observation.signature = void 0;
|
|
3694
|
+
hot.add(observation);
|
|
3695
|
+
}
|
|
3696
|
+
observation.registration = registration;
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
for (const [key, observation] of this.transcriptObservations) {
|
|
3700
|
+
if (!retained.has(key)) {
|
|
3701
|
+
this.transcriptObservations.delete(key);
|
|
3702
|
+
this.hotRegistrations.delete(observation);
|
|
3703
|
+
}
|
|
3704
|
+
}
|
|
3705
|
+
for (const observation of this.hotRegistrations) hot.add(observation);
|
|
3706
|
+
this.hotRegistrations = hot;
|
|
3707
|
+
this.registrationSnapshot = registrations;
|
|
3708
|
+
}
|
|
3709
|
+
async scanFingerprint(registration) {
|
|
3710
|
+
return this.transcriptSignature(registration);
|
|
3711
|
+
}
|
|
3712
|
+
async transcriptSignature(registration) {
|
|
3713
|
+
try {
|
|
3714
|
+
const info = await lstat2(this.transcriptPathOf(registration), { bigint: true });
|
|
3715
|
+
if (!info.isFile() || info.isSymbolicLink()) return null;
|
|
3716
|
+
return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${info.mode}:${info.uid}`;
|
|
3717
|
+
} catch {
|
|
3718
|
+
return null;
|
|
3719
|
+
}
|
|
3521
3720
|
}
|
|
3522
3721
|
async scanRegistration(registration) {
|
|
3523
3722
|
return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
|
|
@@ -3583,6 +3782,14 @@ var HostTranscriptWatcher = class {
|
|
|
3583
3782
|
return transcriptCursorBoundsReason(handle, cursor, size);
|
|
3584
3783
|
}
|
|
3585
3784
|
};
|
|
3785
|
+
async function listHostOutboxDirectoryNames(directory) {
|
|
3786
|
+
try {
|
|
3787
|
+
return await readdir(directory);
|
|
3788
|
+
} catch (error) {
|
|
3789
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
|
|
3790
|
+
throw error;
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3586
3793
|
var HostProducerDrainCore = class {
|
|
3587
3794
|
host;
|
|
3588
3795
|
now;
|
|
@@ -3610,7 +3817,7 @@ var HostProducerDrainCore = class {
|
|
|
3610
3817
|
};
|
|
3611
3818
|
|
|
3612
3819
|
// host/relay/src/durable-atomic-replacement.ts
|
|
3613
|
-
import { lstat as
|
|
3820
|
+
import { lstat as lstat3, mkdir as mkdir2, open as open2, rename, unlink } from "node:fs/promises";
|
|
3614
3821
|
import { dirname as dirname3 } from "node:path";
|
|
3615
3822
|
|
|
3616
3823
|
// host/windows-rename-retry.ts
|
|
@@ -3632,7 +3839,7 @@ function resolveRetrySchedule(tuning) {
|
|
|
3632
3839
|
startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
|
|
3633
3840
|
maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
|
|
3634
3841
|
sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
|
|
3635
|
-
now: tuning.now ?? (() =>
|
|
3842
|
+
now: tuning.now ?? (() => performance.now())
|
|
3636
3843
|
};
|
|
3637
3844
|
}
|
|
3638
3845
|
async function renameWithWindowsRetry(operation, tuning) {
|
|
@@ -3665,7 +3872,7 @@ function isRetryableRenameError(error) {
|
|
|
3665
3872
|
var DEFAULT_PORT = {
|
|
3666
3873
|
platform: process.platform,
|
|
3667
3874
|
mkdir: (path, options) => mkdir2(path, options),
|
|
3668
|
-
lstat: (path) =>
|
|
3875
|
+
lstat: (path) => lstat3(path),
|
|
3669
3876
|
open_file: (path) => open2(path, "wx", 384),
|
|
3670
3877
|
rename,
|
|
3671
3878
|
unlink,
|
|
@@ -3763,6 +3970,8 @@ var HostUsageFactsStore = class {
|
|
|
3763
3970
|
afterPendingWrite;
|
|
3764
3971
|
afterBatchPublish;
|
|
3765
3972
|
sessionDirectoryCursor;
|
|
3973
|
+
uploadScanSignature;
|
|
3974
|
+
uploadScanEmpty = false;
|
|
3766
3975
|
constructor(options) {
|
|
3767
3976
|
this.root = join3(options.outbox_dir, "usage-facts");
|
|
3768
3977
|
this.sessions = join3(this.root, "sessions");
|
|
@@ -3782,8 +3991,11 @@ var HostUsageFactsStore = class {
|
|
|
3782
3991
|
this.sessionDirectoryCursor = void 0;
|
|
3783
3992
|
await cursor?.close();
|
|
3784
3993
|
}
|
|
3994
|
+
/** The durable path behind one session's usage state, so idle fast paths can poll it without reading it. */
|
|
3995
|
+
statePath(producer, hostSourceRef, hostSessionRef) {
|
|
3996
|
+
return this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
3997
|
+
}
|
|
3785
3998
|
async readState(producer, hostSourceRef, hostSessionRef) {
|
|
3786
|
-
await this.prepare();
|
|
3787
3999
|
const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
3788
4000
|
const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
3789
4001
|
if (value === null) return null;
|
|
@@ -3841,11 +4053,15 @@ var HostUsageFactsStore = class {
|
|
|
3841
4053
|
}
|
|
3842
4054
|
/** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
|
|
3843
4055
|
async sweepOrphanedBatches(state) {
|
|
3844
|
-
await this.prepare();
|
|
3845
4056
|
const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
|
|
3846
|
-
await preparePrivateDirectory(directoryPath, this.platform, this.custody);
|
|
3847
4057
|
const expected = expectedBatchNames(state);
|
|
3848
|
-
|
|
4058
|
+
let directory;
|
|
4059
|
+
try {
|
|
4060
|
+
directory = await opendir(directoryPath);
|
|
4061
|
+
} catch (error) {
|
|
4062
|
+
if (errorCode3(error) === "ENOENT") return 0;
|
|
4063
|
+
throw error;
|
|
4064
|
+
}
|
|
3849
4065
|
let inspected = 0;
|
|
3850
4066
|
let deleted = 0;
|
|
3851
4067
|
try {
|
|
@@ -3882,7 +4098,14 @@ var HostUsageFactsStore = class {
|
|
|
3882
4098
|
});
|
|
3883
4099
|
}
|
|
3884
4100
|
async nextUploadCandidate(producer, hostSourceRef) {
|
|
3885
|
-
await this.
|
|
4101
|
+
const signature = await statObservedPathSignature(this.sessions);
|
|
4102
|
+
if (signature !== null && signature === this.uploadScanSignature && this.uploadScanEmpty) return null;
|
|
4103
|
+
const candidate = await this.scanUploadCandidates(producer, hostSourceRef);
|
|
4104
|
+
this.uploadScanSignature = signature ?? void 0;
|
|
4105
|
+
this.uploadScanEmpty = candidate === null;
|
|
4106
|
+
return candidate;
|
|
4107
|
+
}
|
|
4108
|
+
async scanUploadCandidates(producer, hostSourceRef) {
|
|
3886
4109
|
const names = await this.readNextSessionNames();
|
|
3887
4110
|
for (const name of names) {
|
|
3888
4111
|
const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
@@ -3900,7 +4123,14 @@ var HostUsageFactsStore = class {
|
|
|
3900
4123
|
return null;
|
|
3901
4124
|
}
|
|
3902
4125
|
async readNextSessionNames() {
|
|
3903
|
-
this.sessionDirectoryCursor
|
|
4126
|
+
if (this.sessionDirectoryCursor === void 0) {
|
|
4127
|
+
try {
|
|
4128
|
+
this.sessionDirectoryCursor = await opendir(this.sessions);
|
|
4129
|
+
} catch (error) {
|
|
4130
|
+
if (errorCode3(error) === "ENOENT") return [];
|
|
4131
|
+
throw error;
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
3904
4134
|
const names = [];
|
|
3905
4135
|
let inspected = 0;
|
|
3906
4136
|
while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
|
|
@@ -4314,6 +4544,8 @@ function sha2562(value) {
|
|
|
4314
4544
|
|
|
4315
4545
|
// host/relay/src/host-usage-facts-capture.ts
|
|
4316
4546
|
import { constants as constants3 } from "node:fs";
|
|
4547
|
+
import { lstat as lstat4 } from "node:fs/promises";
|
|
4548
|
+
import { dirname as dirname5 } from "node:path";
|
|
4317
4549
|
var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
|
|
4318
4550
|
var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
|
|
4319
4551
|
var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
|
|
@@ -4363,6 +4595,55 @@ var HostUsageRegistrationCapture = class {
|
|
|
4363
4595
|
return captured;
|
|
4364
4596
|
}
|
|
4365
4597
|
};
|
|
4598
|
+
var HostUsageIdleGate = class {
|
|
4599
|
+
seen = /* @__PURE__ */ new Map();
|
|
4600
|
+
statPath;
|
|
4601
|
+
constructor(options = {}) {
|
|
4602
|
+
this.statPath = options.statPath ?? statIdleGatePath;
|
|
4603
|
+
}
|
|
4604
|
+
/**
|
|
4605
|
+
* Check whether the path is unchanged since the last confirmed check, without recording anything.
|
|
4606
|
+
* The caller confirms the returned signature only after the capture for it succeeded without a
|
|
4607
|
+
* source error, so a failed read leaves the source eligible on the next tick while a fully-read,
|
|
4608
|
+
* unchanged source keeps skipping its open plus state-read probe.
|
|
4609
|
+
*/
|
|
4610
|
+
async checkUnchanged(key, path) {
|
|
4611
|
+
const signature = await this.statPath(path);
|
|
4612
|
+
if (signature === null) {
|
|
4613
|
+
this.seen.delete(key);
|
|
4614
|
+
return { unchanged: false, signature };
|
|
4615
|
+
}
|
|
4616
|
+
if (this.seen.get(key) === signature) return { unchanged: true, signature };
|
|
4617
|
+
return { unchanged: false, signature };
|
|
4618
|
+
}
|
|
4619
|
+
/** Remember a signature only after its capture succeeded, so failures stay eligible. */
|
|
4620
|
+
confirmUnchanged(key, signature) {
|
|
4621
|
+
if (signature === null) return;
|
|
4622
|
+
this.seen.set(key, signature);
|
|
4623
|
+
}
|
|
4624
|
+
};
|
|
4625
|
+
async function statIdleGatePath(path) {
|
|
4626
|
+
const direct = await statObservedPathSignature(path);
|
|
4627
|
+
if (direct !== null) return direct;
|
|
4628
|
+
try {
|
|
4629
|
+
await lstat4(path);
|
|
4630
|
+
return null;
|
|
4631
|
+
} catch (error) {
|
|
4632
|
+
const code2 = transcriptErrorCode(error);
|
|
4633
|
+
if (code2 !== "ENOENT" && code2 !== "ENOTDIR") return null;
|
|
4634
|
+
return await missingPathAnchor(path);
|
|
4635
|
+
}
|
|
4636
|
+
}
|
|
4637
|
+
async function missingPathAnchor(path) {
|
|
4638
|
+
let ancestor = dirname5(path);
|
|
4639
|
+
for (let depth = 0; depth < 4; depth += 1) {
|
|
4640
|
+
if (ancestor === dirname5(ancestor)) return null;
|
|
4641
|
+
const anchor = await statObservedPathSignature(ancestor);
|
|
4642
|
+
if (anchor !== null) return `missing:${anchor}`;
|
|
4643
|
+
ancestor = dirname5(ancestor);
|
|
4644
|
+
}
|
|
4645
|
+
return null;
|
|
4646
|
+
}
|
|
4366
4647
|
async function openHostUsageTranscriptCursor(input) {
|
|
4367
4648
|
const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
|
|
4368
4649
|
let source;
|
|
@@ -4433,7 +4714,7 @@ function completeLinePrefix(bytes, baseOffset) {
|
|
|
4433
4714
|
|
|
4434
4715
|
// host/relay/src/host-registration-state.ts
|
|
4435
4716
|
import { constants as constants4 } from "node:fs";
|
|
4436
|
-
import { dirname as
|
|
4717
|
+
import { dirname as dirname6 } from "node:path";
|
|
4437
4718
|
|
|
4438
4719
|
// host/runtime-source-paths.ts
|
|
4439
4720
|
import { createHash as createHash6 } from "node:crypto";
|
|
@@ -4525,7 +4806,7 @@ var HostRegistrationStateError = class extends Error {
|
|
|
4525
4806
|
async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
|
|
4526
4807
|
let raw;
|
|
4527
4808
|
try {
|
|
4528
|
-
await assertPrivateRegistrationDirectory(
|
|
4809
|
+
await assertPrivateRegistrationDirectory(dirname6(path), platform, custody);
|
|
4529
4810
|
raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
|
|
4530
4811
|
} catch (error) {
|
|
4531
4812
|
throw registrationReadError(error);
|
|
@@ -4642,6 +4923,10 @@ var HostUsageFactsUploader = class {
|
|
|
4642
4923
|
async close() {
|
|
4643
4924
|
await this.store.close();
|
|
4644
4925
|
}
|
|
4926
|
+
/** The start owner prepares the store once, so idle ticks below never re-prepare. */
|
|
4927
|
+
async prepare() {
|
|
4928
|
+
await this.store.prepare();
|
|
4929
|
+
}
|
|
4645
4930
|
async uploadOne(signal) {
|
|
4646
4931
|
const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
|
|
4647
4932
|
if (candidate === null) return false;
|
|
@@ -4664,6 +4949,11 @@ var HostUsageFactsUploader = class {
|
|
|
4664
4949
|
};
|
|
4665
4950
|
async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
|
|
4666
4951
|
const uploader = new HostUsageFactsUploader(options);
|
|
4952
|
+
try {
|
|
4953
|
+
await uploader.prepare();
|
|
4954
|
+
} catch {
|
|
4955
|
+
writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
|
|
4956
|
+
}
|
|
4667
4957
|
let delay = 500;
|
|
4668
4958
|
let failures = 0;
|
|
4669
4959
|
try {
|
|
@@ -4691,15 +4981,16 @@ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
|
|
|
4691
4981
|
}
|
|
4692
4982
|
}
|
|
4693
4983
|
|
|
4694
|
-
// host/relay/src/relay-quarantine-store.ts
|
|
4695
|
-
var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
|
|
4696
|
-
var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
|
|
4697
|
-
var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
|
|
4698
|
-
|
|
4699
4984
|
// host/relay/src/relay-admission-store.ts
|
|
4700
|
-
var
|
|
4701
|
-
|
|
4702
|
-
|
|
4985
|
+
var RELAY_ADMISSION_CODES = vocabulary(["admitted", "already_admitted", "producer_epoch_stale", "sequence_gap", "frame_identity_conflict", "producer_queue_full", "relay_queue_full", "producer_already_connected", "invalid_producer_identity"]);
|
|
4986
|
+
|
|
4987
|
+
// host/relay/src/host-relay-config.ts
|
|
4988
|
+
var HOST_RELAY_CONFIG_MIN_BYTES = Buffer.byteLength("{}", "utf8");
|
|
4989
|
+
var HOST_RELAY_INVOCATION_MINT_LOG_LINE = new RegExp(String.raw`^\[host-relay-invocation-mint\] timestamp=(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[.]\d{3}Z) outcome=(completed|failed) stage=(registration|gateway_request|gateway_response) latency_ms=(\d{1,16})(?: gateway_origin_host=([A-Za-z0-9.:[\]-]{1,255}))?(?: client_exchange_ref=(${CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE.slice(1, -1)}))?(?: gateway_http_request_ref=(${CEAL_HTTP_GATEWAY_REQUEST_REF_PATTERN_SOURCE.slice(1, -1)}))?(?: reason=([a-z][a-z0-9_]{0,63}))?(?: gateway_status=([1-5][0-9]{2}))?$`, "u");
|
|
4990
|
+
|
|
4991
|
+
// host/relay/src/relay-endpoint-ownership.ts
|
|
4992
|
+
import { lstat as lstat5, mkdir as mkdir4, unlink as unlink3 } from "node:fs/promises";
|
|
4993
|
+
import { dirname as dirname7 } from "node:path";
|
|
4703
4994
|
|
|
4704
4995
|
// host/relay/src/relay-ipc-error.ts
|
|
4705
4996
|
var HostRelayIpcError = class extends Error {
|
|
@@ -4720,13 +5011,11 @@ function relayIpcErrorCode(error) {
|
|
|
4720
5011
|
}
|
|
4721
5012
|
|
|
4722
5013
|
// host/relay/src/relay-endpoint-ownership.ts
|
|
4723
|
-
import { lstat as lstat3, mkdir as mkdir4, unlink as unlink3 } from "node:fs/promises";
|
|
4724
|
-
import { dirname as dirname6 } from "node:path";
|
|
4725
5014
|
function currentUid(fallback) {
|
|
4726
5015
|
return typeof process.geteuid === "function" ? process.geteuid() : fallback;
|
|
4727
5016
|
}
|
|
4728
5017
|
async function assertCompactRelayClientParent(endpoint) {
|
|
4729
|
-
const parent =
|
|
5018
|
+
const parent = dirname7(endpoint);
|
|
4730
5019
|
if (process.platform !== "darwin" || !isMacosHostRelayIpcDirectory(parent)) return;
|
|
4731
5020
|
if (parent !== macosHostRelayIpcDirectory()) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC directory does not belong to the effective user.");
|
|
4732
5021
|
await assertPrivateEndpointDirectory(parent);
|
|
@@ -4734,7 +5023,7 @@ async function assertCompactRelayClientParent(endpoint) {
|
|
|
4734
5023
|
async function assertPrivateEndpointDirectory(parent) {
|
|
4735
5024
|
let stats;
|
|
4736
5025
|
try {
|
|
4737
|
-
stats = await
|
|
5026
|
+
stats = await lstat5(parent);
|
|
4738
5027
|
} catch (error) {
|
|
4739
5028
|
throw endpointInspectionError(error, "Host Relay IPC endpoint parent is unavailable; leaving it untouched.");
|
|
4740
5029
|
}
|
|
@@ -4747,13 +5036,13 @@ function endpointInspectionError(error, message) {
|
|
|
4747
5036
|
}
|
|
4748
5037
|
|
|
4749
5038
|
// host/relay/src/relay-ipc.ts
|
|
4750
|
-
import { createConnection
|
|
5039
|
+
import { createConnection } from "node:net";
|
|
4751
5040
|
|
|
4752
5041
|
// host/relay/src/relay-pipe-handshake.ts
|
|
4753
5042
|
import { createHmac, randomBytes } from "node:crypto";
|
|
4754
5043
|
import { constants as constants5 } from "node:fs";
|
|
4755
5044
|
import { link, unlink as unlink4 } from "node:fs/promises";
|
|
4756
|
-
import { dirname as
|
|
5045
|
+
import { dirname as dirname8, join as join4 } from "node:path";
|
|
4757
5046
|
var RELAY_PIPE_HANDSHAKE_TIMEOUT_MS = 5e3;
|
|
4758
5047
|
var RELAY_PIPE_KEY_BYTES = 32;
|
|
4759
5048
|
var RELAY_PIPE_KEY_FILENAME = "relay-pipe.key";
|
|
@@ -4773,7 +5062,7 @@ var RelayPipeHandshakeError = class extends Error {
|
|
|
4773
5062
|
}
|
|
4774
5063
|
};
|
|
4775
5064
|
function relayPipeStateRootForOutboxDir(outboxDir) {
|
|
4776
|
-
return join4(
|
|
5065
|
+
return join4(dirname8(dirname8(dirname8(outboxDir))), "relay");
|
|
4777
5066
|
}
|
|
4778
5067
|
function relayPipeKeyPath(relayStateRoot) {
|
|
4779
5068
|
return join4(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
|
|
@@ -4787,7 +5076,7 @@ async function loadRelayPipeKey(relayStateRoot, platform = process.platform, cus
|
|
|
4787
5076
|
}
|
|
4788
5077
|
async function loadWindowsRelayPipeKey(path, custody) {
|
|
4789
5078
|
try {
|
|
4790
|
-
await ensurePrivateDirectoryWithSecurefs(
|
|
5079
|
+
await ensurePrivateDirectoryWithSecurefs(dirname8(path), custody);
|
|
4791
5080
|
const existing = await readRelayPipeKey(path, "win32", custody);
|
|
4792
5081
|
if (existing !== null) return existing;
|
|
4793
5082
|
await createRandomPrivateFileWithSecurefs(path, RELAY_PIPE_KEY_BYTES, custody);
|
|
@@ -5216,7 +5505,7 @@ var HostInvocationAuthenticationRefusal = class extends Error {
|
|
|
5216
5505
|
}
|
|
5217
5506
|
};
|
|
5218
5507
|
var INSTALLED_HOST_INVOCATION_AUTHENTICATION_DEPENDENCIES = {
|
|
5219
|
-
process_elapsed_ms: () =>
|
|
5508
|
+
process_elapsed_ms: () => performance2.now(),
|
|
5220
5509
|
load_pipe_key: async (outboxDirectory) => process.platform === "win32" ? loadRelayPipeKey(relayPipeStateRootForOutboxDir(outboxDirectory)) : void 0,
|
|
5221
5510
|
create_relay_port: (endpoint, pipeKey, timeoutMs) => new HostRelayInvocationContextPort(endpoint, pipeKey, timeoutMs)
|
|
5222
5511
|
};
|
|
@@ -5286,24 +5575,142 @@ async function authenticateHostInvocation(descriptor, input, options) {
|
|
|
5286
5575
|
const request2 = decodeCealHostInvocationAuthenticationRequest({ schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA, client_nonce: input[2] });
|
|
5287
5576
|
const config = validateOptions(options);
|
|
5288
5577
|
const now = config.now ?? (() => /* @__PURE__ */ new Date());
|
|
5289
|
-
const
|
|
5578
|
+
const store = descriptor.create_store(config.outbox_dir);
|
|
5579
|
+
const resolved = resolveIdentity(descriptor, config);
|
|
5580
|
+
if (resolved.status === "session_unavailable") throw new TypeError("no_binding");
|
|
5581
|
+
const toolCallId = resolveToolCallId(descriptor, config);
|
|
5582
|
+
const selection = await readHookSelection(store, resolved.identity);
|
|
5583
|
+
if (selection === null) {
|
|
5584
|
+
const callTime = await trySelectionlessCallTimeBinding(descriptor, store, resolved.identity, config, toolCallId);
|
|
5585
|
+
if (callTime !== null) return authenticateCallTimeBinding(descriptor, store, callTime, request2.client_nonce, config, now);
|
|
5586
|
+
} else if (!waitPossible(config) && !await hasLiveInvocationContext(store, resolved.identity, now)) {
|
|
5587
|
+
const direct = await tryDirectCallTimeBinding(descriptor, store, resolved.identity, selection, config, toolCallId);
|
|
5588
|
+
if (direct !== null) return authenticateCallTimeBinding(descriptor, store, direct, request2.client_nonce, config, now);
|
|
5589
|
+
}
|
|
5590
|
+
return authenticateHookGated(descriptor, store, request2.client_nonce, config, now, toolCallId);
|
|
5591
|
+
}
|
|
5592
|
+
function selectCallTimeBinding(window, toolCallId) {
|
|
5593
|
+
const newest = window.messages[0];
|
|
5594
|
+
if (newest === void 0) return null;
|
|
5595
|
+
return { message: newest, mode: toolCallId === void 0 ? "newest_message" : "tool_call" };
|
|
5596
|
+
}
|
|
5597
|
+
async function authenticateCallTimeBinding(descriptor, store, callTime, clientNonce, config, now) {
|
|
5290
5598
|
if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
|
|
5291
|
-
const query = await invocationMintQuery(descriptor, store,
|
|
5599
|
+
const query = await invocationMintQuery(descriptor, store, { identity: callTime.binding, expires_at: callTime.expires_at }, clientNonce, config, callTime.window);
|
|
5600
|
+
const response2 = await mintedResult(config.mint_invocation_context, query);
|
|
5601
|
+
const completedAt = now();
|
|
5602
|
+
const newest = await rereadCallTimeNewest(descriptor, store, callTime.binding, config);
|
|
5603
|
+
if (newest === null || newest.host_turn_ref !== callTime.binding.host_turn_ref || newest.host_input_ref !== callTime.window.messages[0]?.host_input_ref) throw new TypeError("context_replaced");
|
|
5604
|
+
return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
|
|
5605
|
+
}
|
|
5606
|
+
async function authenticateHookGated(descriptor, store, clientNonce, config, now, toolCallId) {
|
|
5607
|
+
const { current } = await currentInvocation(descriptor, config, now, store);
|
|
5608
|
+
if (config.mint_invocation_context === void 0) throw new TypeError("relay_failed");
|
|
5609
|
+
const window = await readCallTimeWindow(descriptor, store, current.identity, config);
|
|
5610
|
+
const selected = selectCallTimeBinding(window, toolCallId);
|
|
5611
|
+
if (selected !== null && selected.message.host_turn_ref !== current.identity.host_turn_ref) {
|
|
5612
|
+
const selection = await readHookSelection(store, current.identity);
|
|
5613
|
+
if (selection === null || transcriptCatchesHookSelection(selection, selected.message)) {
|
|
5614
|
+
return authenticateCallTimeBinding(descriptor, store, {
|
|
5615
|
+
binding: { ...current.identity, host_turn_ref: selected.message.host_turn_ref },
|
|
5616
|
+
expires_at: current.expires_at,
|
|
5617
|
+
window,
|
|
5618
|
+
mode: selected.mode
|
|
5619
|
+
}, clientNonce, config, now);
|
|
5620
|
+
}
|
|
5621
|
+
}
|
|
5622
|
+
const query = await invocationMintQuery(descriptor, store, current, clientNonce, config, window);
|
|
5292
5623
|
const response2 = await mintedResult(config.mint_invocation_context, query);
|
|
5293
5624
|
const completedAt = now();
|
|
5294
5625
|
const rechecked = await store.readInvocationContext(current.identity.host_source_ref, current.identity.host_session_ref, completedAt);
|
|
5295
5626
|
if (rechecked === null || !sameTurn(current, rechecked)) throw new TypeError("context_replaced");
|
|
5296
5627
|
return decodeCealHostInvocationAuthenticationResult(response2.result, completedAt);
|
|
5297
5628
|
}
|
|
5298
|
-
async function
|
|
5299
|
-
const
|
|
5629
|
+
async function trySelectionlessCallTimeBinding(descriptor, store, identity, config, toolCallId) {
|
|
5630
|
+
const registration = await liveTranscriptRegistration(store, identity);
|
|
5631
|
+
if (registration === null) return null;
|
|
5632
|
+
let window;
|
|
5633
|
+
try {
|
|
5634
|
+
window = await readCallTimeWindow(descriptor, store, identity, config);
|
|
5635
|
+
} catch {
|
|
5636
|
+
throw new TypeError("transient_retryable");
|
|
5637
|
+
}
|
|
5638
|
+
const selected = selectCallTimeBinding(window, toolCallId);
|
|
5639
|
+
if (selected === null) return null;
|
|
5640
|
+
return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
|
|
5641
|
+
}
|
|
5642
|
+
async function tryDirectCallTimeBinding(descriptor, store, identity, selection, config, toolCallId) {
|
|
5643
|
+
let window;
|
|
5644
|
+
try {
|
|
5645
|
+
window = await readCallTimeWindow(descriptor, store, identity, config);
|
|
5646
|
+
} catch {
|
|
5647
|
+
return null;
|
|
5648
|
+
}
|
|
5649
|
+
const selected = selectCallTimeBinding(window, toolCallId);
|
|
5650
|
+
if (selected === null || !transcriptCatchesHookSelection(selection, selected.message)) return null;
|
|
5651
|
+
const registration = await liveTranscriptRegistration(store, identity);
|
|
5652
|
+
if (registration === null) return null;
|
|
5653
|
+
return { binding: { ...identity, host_turn_ref: selected.message.host_turn_ref }, expires_at: registration.expires_at, window, mode: selected.mode };
|
|
5654
|
+
}
|
|
5655
|
+
async function readCallTimeWindow(descriptor, store, identity, config) {
|
|
5656
|
+
return await (config.read_human_message_window?.(identity) ?? descriptor.read_human_message_window?.({ store, identity }) ?? Promise.resolve({ messages: [], truncated: false }));
|
|
5657
|
+
}
|
|
5658
|
+
function transcriptCatchesHookSelection(selection, newest) {
|
|
5659
|
+
if (newest.text_truncated === true) return false;
|
|
5660
|
+
return hostProducerPromptRef(createHash7("sha256").update(newest.text, "utf8").digest("hex")) === selection.prompt_ref;
|
|
5661
|
+
}
|
|
5662
|
+
async function readHookSelection(store, identity) {
|
|
5663
|
+
try {
|
|
5664
|
+
return await store.readInvocationTurnSelection?.(identity.host_source_ref, identity.host_session_ref) ?? null;
|
|
5665
|
+
} catch {
|
|
5666
|
+
return null;
|
|
5667
|
+
}
|
|
5668
|
+
}
|
|
5669
|
+
async function hasLiveInvocationContext(store, identity, now) {
|
|
5670
|
+
try {
|
|
5671
|
+
return await store.readInvocationContext(identity.host_source_ref, identity.host_session_ref, now()) !== null;
|
|
5672
|
+
} catch {
|
|
5673
|
+
return false;
|
|
5674
|
+
}
|
|
5675
|
+
}
|
|
5676
|
+
function waitPossible(config) {
|
|
5677
|
+
return (config.context_activation_wait_ms ?? 0) > 0;
|
|
5678
|
+
}
|
|
5679
|
+
async function liveTranscriptRegistration(store, identity) {
|
|
5680
|
+
try {
|
|
5681
|
+
const registration = await store.readTranscriptRegistration?.(identity.host_source_ref, identity.host_session_ref) ?? null;
|
|
5682
|
+
if (registration !== null && Date.parse(registration.expires_at) > Date.now()) return registration;
|
|
5683
|
+
} catch {
|
|
5684
|
+
}
|
|
5685
|
+
return null;
|
|
5686
|
+
}
|
|
5687
|
+
async function rereadCallTimeNewest(descriptor, store, identity, config) {
|
|
5688
|
+
try {
|
|
5689
|
+
return (await readCallTimeWindow(descriptor, store, identity, config)).messages[0] ?? null;
|
|
5690
|
+
} catch {
|
|
5691
|
+
return null;
|
|
5692
|
+
}
|
|
5693
|
+
}
|
|
5694
|
+
function resolveToolCallId(descriptor, options) {
|
|
5695
|
+
if (options.tool_call_id !== void 0) return validToolCallId(options.tool_call_id) ? options.tool_call_id : void 0;
|
|
5696
|
+
if (descriptor.tool_call_id_env === void 0) return void 0;
|
|
5697
|
+
const value = process.env[descriptor.tool_call_id_env];
|
|
5698
|
+
return validToolCallId(value) ? value : void 0;
|
|
5699
|
+
}
|
|
5700
|
+
function validToolCallId(value) {
|
|
5701
|
+
return typeof value === "string" && value.length > 0 && value.length <= 256 && !value.includes("\0");
|
|
5702
|
+
}
|
|
5703
|
+
async function invocationMintQuery(descriptor, store, current, clientNonce, options, windowOverride) {
|
|
5704
|
+
const readWindow = windowOverride === void 0 ? options.read_human_message_window?.(current.identity) ?? descriptor.read_human_message_window?.({ store, identity: current.identity }) ?? Promise.resolve({ messages: [], truncated: false }) : Promise.resolve(windowOverride);
|
|
5705
|
+
const window = await readWindow;
|
|
5706
|
+
if (window.messages.length === 0) throw new TypeError("transcript_unavailable");
|
|
5300
5707
|
return {
|
|
5301
5708
|
producer_id: descriptor.producer_id,
|
|
5302
5709
|
producer_installation_ref: options.producer_installation_ref,
|
|
5303
5710
|
client_nonce: clientNonce,
|
|
5304
5711
|
context_expires_at: current.expires_at,
|
|
5305
5712
|
host_binding: { ...current.identity },
|
|
5306
|
-
human_message_window:
|
|
5713
|
+
human_message_window: window,
|
|
5307
5714
|
...await visibleOutputBudget(descriptor)
|
|
5308
5715
|
};
|
|
5309
5716
|
}
|
|
@@ -5328,12 +5735,11 @@ async function mintedResult(mint, query) {
|
|
|
5328
5735
|
function validGenericGatewayRefusalStatus2(value) {
|
|
5329
5736
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 400 && value < 500 && value !== 401 && value !== 429;
|
|
5330
5737
|
}
|
|
5331
|
-
async function currentInvocation(descriptor, config, now) {
|
|
5332
|
-
const store = descriptor.create_store(config.outbox_dir);
|
|
5738
|
+
async function currentInvocation(descriptor, config, now, store) {
|
|
5333
5739
|
const identity = resolveIdentity(descriptor, config);
|
|
5334
5740
|
if (identity.status === "session_unavailable") throw new TypeError("no_binding");
|
|
5335
5741
|
const waitBudgetMs = config.context_activation_wait_ms ?? 0;
|
|
5336
|
-
const monotonicNow = config.monotonic_now ?? (() =>
|
|
5742
|
+
const monotonicNow = config.monotonic_now ?? (() => performance2.now());
|
|
5337
5743
|
const deadline = monotonicNow() + waitBudgetMs;
|
|
5338
5744
|
let firstCheck = true;
|
|
5339
5745
|
let waitEngaged = false;
|
|
@@ -5346,7 +5752,7 @@ async function currentInvocation(descriptor, config, now) {
|
|
|
5346
5752
|
const current = await readLiveSessionContext(store, identity.identity.host_source_ref, identity.identity.host_session_ref, observedAt);
|
|
5347
5753
|
if (current !== null) {
|
|
5348
5754
|
recordActivationWaitCompletion(descriptor.producer_id, waitEngaged, config.diagnostic_sink);
|
|
5349
|
-
return {
|
|
5755
|
+
return { current };
|
|
5350
5756
|
}
|
|
5351
5757
|
await rejectWhenActivationWaitIsUnavailable(descriptor, store, identity.identity, waitEngaged, waitBudgetMs, config.diagnostic_sink);
|
|
5352
5758
|
const remainingMs = deadline - monotonicNow();
|
|
@@ -5420,7 +5826,7 @@ function waitForContextActivation(milliseconds) {
|
|
|
5420
5826
|
});
|
|
5421
5827
|
}
|
|
5422
5828
|
function validateOptions(options) {
|
|
5423
|
-
if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || !validOptionalSession(options.session_id)) {
|
|
5829
|
+
if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0 || typeof options.host_source_ref !== "string" || !SAFE_REF.test(options.host_source_ref) || typeof options.producer_installation_ref !== "string" || !SAFE_REF.test(options.producer_installation_ref) || !validContextActivationWait(options.context_activation_wait_ms) || options.tool_call_id !== void 0 && typeof options.tool_call_id !== "string" || !validOptionalSession(options.session_id)) {
|
|
5424
5830
|
throw new TypeError("options_invalid");
|
|
5425
5831
|
}
|
|
5426
5832
|
return options;
|
|
@@ -5445,7 +5851,7 @@ function writeResult(value, sink) {
|
|
|
5445
5851
|
// host/producer-service.ts
|
|
5446
5852
|
import { posix as posix4, win32 as win325 } from "node:path";
|
|
5447
5853
|
import { constants as constants6 } from "node:fs";
|
|
5448
|
-
import { lstat as
|
|
5854
|
+
import { lstat as lstat6 } from "node:fs/promises";
|
|
5449
5855
|
var SAFE_REF2 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
|
5450
5856
|
var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
|
|
5451
5857
|
var HostProducerServiceError = class extends Error {
|
|
@@ -5574,7 +5980,7 @@ function assertProducerAbsolutePath(value, platform, kind, error) {
|
|
|
5574
5980
|
}
|
|
5575
5981
|
async function configPathStat(configPath, error) {
|
|
5576
5982
|
try {
|
|
5577
|
-
return await
|
|
5983
|
+
return await lstat6(configPath);
|
|
5578
5984
|
} catch {
|
|
5579
5985
|
throw error("config_unavailable");
|
|
5580
5986
|
}
|
|
@@ -5673,7 +6079,7 @@ function boundedMilliseconds(value) {
|
|
|
5673
6079
|
}
|
|
5674
6080
|
|
|
5675
6081
|
// host/claude/src/claude-decoder.ts
|
|
5676
|
-
import { createHash as
|
|
6082
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
5677
6083
|
|
|
5678
6084
|
// host/claude/src/claude-types.ts
|
|
5679
6085
|
var CLAUDE_SESSION_ID_ENVIRONMENT = "CLAUDE_CODE_SESSION_ID";
|
|
@@ -5770,7 +6176,7 @@ function queuedRowIdentity(row) {
|
|
|
5770
6176
|
return { uuid: row.uuid, timestamp: row.timestamp };
|
|
5771
6177
|
}
|
|
5772
6178
|
function queueEnqueueTurnId(sessionId, timestamp4, content) {
|
|
5773
|
-
return `queue-enqueue:${
|
|
6179
|
+
return `queue-enqueue:${createHash8("sha256").update(`${sessionId}
|
|
5774
6180
|
${timestamp4}
|
|
5775
6181
|
${content}`, "utf8").digest("hex").slice(0, 32)}`;
|
|
5776
6182
|
}
|
|
@@ -5784,14 +6190,14 @@ function claudeLocalInputRef(sessionId, turnId) {
|
|
|
5784
6190
|
return `claude-input:${cealRequestSha256({ session_id: sessionId, prompt_id: turnId })}`;
|
|
5785
6191
|
}
|
|
5786
6192
|
function digest(value) {
|
|
5787
|
-
return
|
|
6193
|
+
return createHash8("sha256").update(value, "utf8").digest("hex");
|
|
5788
6194
|
}
|
|
5789
6195
|
function record3(value) {
|
|
5790
6196
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
5791
6197
|
}
|
|
5792
6198
|
|
|
5793
6199
|
// host/claude/src/claude-outbox.ts
|
|
5794
|
-
import { mkdir as mkdir5,
|
|
6200
|
+
import { mkdir as mkdir5, readFile, stat as stat3, unlink as unlink5 } from "node:fs/promises";
|
|
5795
6201
|
import { isAbsolute as isAbsolute3, join as join5 } from "node:path";
|
|
5796
6202
|
|
|
5797
6203
|
// host/invocation-context.ts
|
|
@@ -5899,6 +6305,7 @@ var ClaudeOutboxStore = class {
|
|
|
5899
6305
|
directory;
|
|
5900
6306
|
activeContexts;
|
|
5901
6307
|
turnSelections;
|
|
6308
|
+
registrationInventory = new HostRegistrationInventory();
|
|
5902
6309
|
constructor(directory) {
|
|
5903
6310
|
if (!isAbsolute3(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
|
|
5904
6311
|
this.directory = directory;
|
|
@@ -5935,6 +6342,7 @@ var ClaudeOutboxStore = class {
|
|
|
5935
6342
|
const path = this.activeContextPath(identity);
|
|
5936
6343
|
const active = await readProjectionFile(path);
|
|
5937
6344
|
if (active === null || active.prompt_ref !== promptRef || active.identity.host_turn_ref !== identity.host_turn_ref) return false;
|
|
6345
|
+
await this.prepare();
|
|
5938
6346
|
const updated = { ...active, turn_generation_ref: turnGenerationRef };
|
|
5939
6347
|
validateClaudeHostInvocationContext(updated);
|
|
5940
6348
|
await durableAtomicReplace(path, JSON.stringify(updated));
|
|
@@ -5947,14 +6355,12 @@ var ClaudeOutboxStore = class {
|
|
|
5947
6355
|
*/
|
|
5948
6356
|
async readRawInvocationContext(hostSourceRef, hostSessionRef) {
|
|
5949
6357
|
if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
|
|
5950
|
-
await this.prepare();
|
|
5951
6358
|
const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, readProjectionFile);
|
|
5952
6359
|
return context;
|
|
5953
6360
|
}
|
|
5954
6361
|
async listInvocationContexts(now = /* @__PURE__ */ new Date()) {
|
|
5955
|
-
await this.prepare();
|
|
5956
6362
|
const contexts = [];
|
|
5957
|
-
for (const name of await
|
|
6363
|
+
for (const name of await listHostOutboxDirectoryNames(this.activeContexts)) {
|
|
5958
6364
|
if (!name.endsWith(".json")) continue;
|
|
5959
6365
|
try {
|
|
5960
6366
|
const value = JSON.parse(await readFile(join5(this.activeContexts, name), "utf8"));
|
|
@@ -5971,10 +6377,9 @@ var ClaudeOutboxStore = class {
|
|
|
5971
6377
|
await durableAtomicReplace(this.envelopePath(entry.submission_ref), JSON.stringify(entry));
|
|
5972
6378
|
}
|
|
5973
6379
|
async listEnvelopes() {
|
|
5974
|
-
await this.prepare();
|
|
5975
6380
|
const entries = [];
|
|
5976
6381
|
let malformed = 0;
|
|
5977
|
-
for (const name of await
|
|
6382
|
+
for (const name of await listHostOutboxDirectoryNames(this.envelopes)) {
|
|
5978
6383
|
if (!name.endsWith(".json")) continue;
|
|
5979
6384
|
try {
|
|
5980
6385
|
const value = JSON.parse(await readFile(join5(this.envelopes, name), "utf8"));
|
|
@@ -6002,14 +6407,14 @@ var ClaudeOutboxStore = class {
|
|
|
6002
6407
|
}
|
|
6003
6408
|
async readSession(sourceRef, sessionRef) {
|
|
6004
6409
|
if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
|
|
6005
|
-
await this.prepare();
|
|
6006
6410
|
try {
|
|
6007
6411
|
const value = JSON.parse(await readFile(join5(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
|
|
6008
6412
|
validateSession(value);
|
|
6009
6413
|
return value;
|
|
6010
6414
|
} catch (error) {
|
|
6011
6415
|
if (code(error) === "ENOENT") return null;
|
|
6012
|
-
|
|
6416
|
+
if (error instanceof ClaudeHostError || code(error) !== null) throw error;
|
|
6417
|
+
throw new ClaudeHostError("storage", "Claude session snapshot is malformed.");
|
|
6013
6418
|
}
|
|
6014
6419
|
}
|
|
6015
6420
|
async registerTranscript(registration) {
|
|
@@ -6035,47 +6440,56 @@ var ClaudeOutboxStore = class {
|
|
|
6035
6440
|
}
|
|
6036
6441
|
async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
|
|
6037
6442
|
if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
|
|
6038
|
-
await this.prepare();
|
|
6039
6443
|
const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
|
|
6040
6444
|
if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw new ClaudeHostError("storage", "Claude transcript registration identity does not match its session.");
|
|
6041
6445
|
return registration;
|
|
6042
6446
|
}
|
|
6043
6447
|
async listTranscriptRegistrations() {
|
|
6044
|
-
|
|
6045
|
-
|
|
6046
|
-
|
|
6047
|
-
|
|
6048
|
-
|
|
6049
|
-
|
|
6050
|
-
|
|
6051
|
-
|
|
6052
|
-
|
|
6448
|
+
return this.registrationInventory.read(this.registrations, async () => {
|
|
6449
|
+
const registrations = [];
|
|
6450
|
+
for (const name of await listHostOutboxDirectoryNames(this.registrations)) {
|
|
6451
|
+
if (!name.endsWith(".json")) continue;
|
|
6452
|
+
try {
|
|
6453
|
+
const value = JSON.parse(await readFile(join5(this.registrations, name), "utf8"));
|
|
6454
|
+
validateRegistration(value);
|
|
6455
|
+
registrations.push(value);
|
|
6456
|
+
} catch {
|
|
6457
|
+
}
|
|
6053
6458
|
}
|
|
6054
|
-
|
|
6055
|
-
|
|
6459
|
+
return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
|
|
6460
|
+
});
|
|
6056
6461
|
}
|
|
6057
6462
|
async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
|
|
6058
6463
|
if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host turn selection identity is invalid.");
|
|
6059
|
-
await this.prepare();
|
|
6060
6464
|
try {
|
|
6061
6465
|
const value = JSON.parse(await readFile(this.turnSelectionPath(hostSourceRef, hostSessionRef), "utf8"));
|
|
6062
6466
|
if (!isHostInvocationTurnSelection(value) || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new ClaudeHostError("storage", "Claude Host turn selection is malformed.");
|
|
6063
6467
|
return value;
|
|
6064
6468
|
} catch (error) {
|
|
6065
6469
|
if (code(error) === "ENOENT") return null;
|
|
6066
|
-
|
|
6470
|
+
if (error instanceof ClaudeHostError || code(error) !== null) throw error;
|
|
6471
|
+
throw new ClaudeHostError("storage", "Unable to read the Claude Host turn selection.");
|
|
6067
6472
|
}
|
|
6068
6473
|
}
|
|
6069
6474
|
async readTranscriptCursor(registration) {
|
|
6070
6475
|
validateRegistration(registration);
|
|
6071
|
-
await this.prepare();
|
|
6072
6476
|
try {
|
|
6073
6477
|
const value = JSON.parse(await readFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "utf8"));
|
|
6074
6478
|
validateCursor(value);
|
|
6075
6479
|
return value;
|
|
6076
6480
|
} catch (error) {
|
|
6077
6481
|
if (code(error) === "ENOENT") return null;
|
|
6078
|
-
|
|
6482
|
+
if (error instanceof ClaudeHostError || code(error) !== null) throw error;
|
|
6483
|
+
throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
|
|
6484
|
+
}
|
|
6485
|
+
}
|
|
6486
|
+
async transcriptCursorFingerprint(registration) {
|
|
6487
|
+
validateRegistration(registration);
|
|
6488
|
+
try {
|
|
6489
|
+
const info = await stat3(this.cursorPath(registration.host_source_ref, registration.host_session_ref), { bigint: true });
|
|
6490
|
+
return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
6491
|
+
} catch {
|
|
6492
|
+
return "missing";
|
|
6079
6493
|
}
|
|
6080
6494
|
}
|
|
6081
6495
|
async writeTranscriptCursor(cursor) {
|
|
@@ -6102,7 +6516,8 @@ var ClaudeOutboxStore = class {
|
|
|
6102
6516
|
return value;
|
|
6103
6517
|
} catch (error) {
|
|
6104
6518
|
if (code(error) === "ENOENT") return null;
|
|
6105
|
-
|
|
6519
|
+
if (error instanceof ClaudeHostError || code(error) !== null) throw error;
|
|
6520
|
+
throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
|
|
6106
6521
|
}
|
|
6107
6522
|
}
|
|
6108
6523
|
async removeStateFile(path) {
|
|
@@ -6126,7 +6541,7 @@ async function readProjectionFile(file) {
|
|
|
6126
6541
|
return context;
|
|
6127
6542
|
} catch (error) {
|
|
6128
6543
|
if (code(error) === "ENOENT") return null;
|
|
6129
|
-
if (error instanceof ClaudeHostError) throw error;
|
|
6544
|
+
if (error instanceof ClaudeHostError || code(error) !== null) throw error;
|
|
6130
6545
|
throw new ClaudeHostError("storage", "Unable to read the Claude Host invocation context.");
|
|
6131
6546
|
}
|
|
6132
6547
|
}
|
|
@@ -6308,8 +6723,8 @@ var ClaudeProducer = class {
|
|
|
6308
6723
|
};
|
|
6309
6724
|
|
|
6310
6725
|
// host/claude/src/claude-transcript-watcher.ts
|
|
6311
|
-
import { readdir as readdir2 } from "node:fs/promises";
|
|
6312
|
-
import { isDeepStrictEqual } from "node:util";
|
|
6726
|
+
import { readdir as readdir2, stat as stat4 } from "node:fs/promises";
|
|
6727
|
+
import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
|
|
6313
6728
|
import { join as join6 } from "node:path";
|
|
6314
6729
|
|
|
6315
6730
|
// host/claude/src/claude-subagent-overflow-checkpoint.ts
|
|
@@ -6345,6 +6760,7 @@ var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
|
|
|
6345
6760
|
var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
6346
6761
|
store;
|
|
6347
6762
|
overflow = new ClaudeSubagentOverflowCheckpoint();
|
|
6763
|
+
prunedRegistrations;
|
|
6348
6764
|
diagnostic;
|
|
6349
6765
|
constructor(options) {
|
|
6350
6766
|
super(options, {
|
|
@@ -6358,9 +6774,21 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
6358
6774
|
transcriptPathOf(registration) {
|
|
6359
6775
|
return registration.transcript_path;
|
|
6360
6776
|
}
|
|
6777
|
+
registrationKey(registration) {
|
|
6778
|
+
return `${registration.host_source_ref}\0${registration.host_session_ref}`;
|
|
6779
|
+
}
|
|
6780
|
+
async scanFingerprint(registration) {
|
|
6781
|
+
const transcript = await super.scanFingerprint(registration);
|
|
6782
|
+
if (transcript === null) return null;
|
|
6783
|
+
const subagents = await subagentsFingerprint(registration.transcript_path);
|
|
6784
|
+
return subagents === null ? null : `${transcript}|${subagents}|${await this.store.transcriptCursorFingerprint(registration)}`;
|
|
6785
|
+
}
|
|
6361
6786
|
async listRegistrations() {
|
|
6362
6787
|
const registrations = await this.store.listTranscriptRegistrations();
|
|
6363
|
-
this.
|
|
6788
|
+
if (registrations !== this.prunedRegistrations) {
|
|
6789
|
+
this.overflow.prune(registrations);
|
|
6790
|
+
this.prunedRegistrations = registrations;
|
|
6791
|
+
}
|
|
6364
6792
|
return registrations;
|
|
6365
6793
|
}
|
|
6366
6794
|
async scanOpened(handle, registration) {
|
|
@@ -6373,13 +6801,14 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
6373
6801
|
}
|
|
6374
6802
|
if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
|
|
6375
6803
|
const draft = mutableCursor(cursor);
|
|
6376
|
-
await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
|
|
6377
|
-
return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
|
|
6804
|
+
const retry = await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
|
|
6805
|
+
return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false, ...retry ? { retry: true } : {} };
|
|
6378
6806
|
}
|
|
6379
6807
|
async scanFailed(handle, registration, error) {
|
|
6380
6808
|
this.diagnostic("watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(handle, error));
|
|
6381
6809
|
if (handle === void 0 && isSymlinkTranscript(error)) return await this.quarantineUnopened(registration, "transcript_malformed");
|
|
6382
6810
|
if (error instanceof ClaudeHostError && error.code === "payload_rejected") return await this.quarantineDraft(await this.preservedCursor(registration));
|
|
6811
|
+
if (!(error instanceof ClaudeHostError) && transcriptErrorCode(error) !== null) return { records: 0, enqueued: 0, quarantined: false, retry: true };
|
|
6383
6812
|
await this.quarantineFailure(registration, handle);
|
|
6384
6813
|
return { records: 0, enqueued: 0, quarantined: true };
|
|
6385
6814
|
}
|
|
@@ -6416,9 +6845,12 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
6416
6845
|
await this.consumeMainChunk(registration, main2, draft);
|
|
6417
6846
|
draft.offset += main2.length;
|
|
6418
6847
|
}
|
|
6419
|
-
|
|
6848
|
+
const mainRetry = main2 !== "empty" && main2 !== "partial" && draft.offset < size;
|
|
6849
|
+
const subagents = await this.consumeSubagents(registration, draft);
|
|
6850
|
+
draft.consumed += subagents.consumed;
|
|
6420
6851
|
await this.emitOpenTerminal(registration, draft);
|
|
6421
6852
|
await this.commitCursor(registration, handle, previous, draft, device, inode);
|
|
6853
|
+
return mainRetry || subagents.retry;
|
|
6422
6854
|
}
|
|
6423
6855
|
async preflight(registration, handle, size, device, inode) {
|
|
6424
6856
|
const existing = await this.store.readTranscriptCursor(registration);
|
|
@@ -6580,13 +7012,15 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
6580
7012
|
} catch (error) {
|
|
6581
7013
|
if (isMissingTranscriptError(error) || isNotDirectory(error)) {
|
|
6582
7014
|
this.overflow.clear(registration);
|
|
6583
|
-
return 0;
|
|
7015
|
+
return { consumed: 0, retry: false };
|
|
6584
7016
|
}
|
|
7017
|
+
if (transcriptErrorCode(error) !== null) throw error;
|
|
6585
7018
|
throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
|
|
6586
7019
|
}
|
|
6587
7020
|
const listed = new Set(names);
|
|
6588
7021
|
for (const name of Object.keys(draft.subagents)) if (!listed.has(name)) delete draft.subagents[name];
|
|
6589
|
-
|
|
7022
|
+
const overflow = names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
|
|
7023
|
+
const reported = await this.overflow.observe(registration, names, () => {
|
|
6590
7024
|
const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
|
|
6591
7025
|
try {
|
|
6592
7026
|
this.log(line);
|
|
@@ -6595,12 +7029,15 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
6595
7029
|
}
|
|
6596
7030
|
return true;
|
|
6597
7031
|
});
|
|
7032
|
+
let retry = overflow && !reported;
|
|
6598
7033
|
names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
|
|
6599
7034
|
let consumed = 0;
|
|
6600
7035
|
for (const name of names) {
|
|
6601
|
-
|
|
7036
|
+
const result = await this.consumeSubagentFile(draft, directory, name);
|
|
7037
|
+
consumed += result.consumed;
|
|
7038
|
+
retry ||= result.retry;
|
|
6602
7039
|
}
|
|
6603
|
-
return consumed;
|
|
7040
|
+
return { consumed, retry };
|
|
6604
7041
|
}
|
|
6605
7042
|
async consumeSubagentFile(draft, directory, name) {
|
|
6606
7043
|
const path = join6(directory, name);
|
|
@@ -6613,19 +7050,20 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
6613
7050
|
const chunk = await this.readChunk(handle, pinned.offset, size);
|
|
6614
7051
|
if (chunk === "empty" || chunk === "partial") {
|
|
6615
7052
|
draft.subagents[name] = pinned;
|
|
6616
|
-
return 0;
|
|
7053
|
+
return { consumed: 0, retry: false };
|
|
6617
7054
|
}
|
|
6618
7055
|
const consumed = this.consumeSubagentLines(draft, chunk);
|
|
6619
7056
|
const offset = pinned.offset + chunk.length;
|
|
6620
7057
|
const anchor = await this.readAnchor(handle, offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
|
|
6621
7058
|
draft.subagents[name] = { device, inode, offset, anchor_start: anchor.start, anchor_sha256: anchor.sha256 };
|
|
6622
|
-
return consumed;
|
|
7059
|
+
return { consumed, retry: offset < size };
|
|
6623
7060
|
} catch (error) {
|
|
6624
7061
|
if (isMissingTranscriptError(error)) {
|
|
6625
7062
|
delete draft.subagents[name];
|
|
6626
|
-
return 0;
|
|
7063
|
+
return { consumed: 0, retry: false };
|
|
6627
7064
|
}
|
|
6628
|
-
|
|
7065
|
+
if (error instanceof ClaudeHostError || transcriptErrorCode(error) !== null) throw error;
|
|
7066
|
+
throw new ClaudeHostError("payload_rejected", "Claude subagent transcript is unavailable.");
|
|
6629
7067
|
} finally {
|
|
6630
7068
|
await handle?.close();
|
|
6631
7069
|
}
|
|
@@ -6757,7 +7195,7 @@ function mutableCursor(cursor) {
|
|
|
6757
7195
|
};
|
|
6758
7196
|
}
|
|
6759
7197
|
function sameCursorContent(left, right) {
|
|
6760
|
-
return
|
|
7198
|
+
return isDeepStrictEqual2({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
|
|
6761
7199
|
}
|
|
6762
7200
|
function zeroCounts() {
|
|
6763
7201
|
return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
|
|
@@ -6850,6 +7288,20 @@ function isAssistantUsageLine(record6) {
|
|
|
6850
7288
|
if (identity === null || !isTranscriptRecord(record6.message.usage)) throw new ClaudeHostError("payload_rejected", "Claude transcript usage line is malformed.");
|
|
6851
7289
|
return true;
|
|
6852
7290
|
}
|
|
7291
|
+
async function subagentsFingerprint(transcriptPath) {
|
|
7292
|
+
const directory = subagentsDirectory(transcriptPath);
|
|
7293
|
+
try {
|
|
7294
|
+
const names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
|
|
7295
|
+
const entries = [];
|
|
7296
|
+
for (const name of names) {
|
|
7297
|
+
const info = await stat4(join6(directory, name), { bigint: true });
|
|
7298
|
+
entries.push(`${name}:${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`);
|
|
7299
|
+
}
|
|
7300
|
+
return entries.join("|");
|
|
7301
|
+
} catch (error) {
|
|
7302
|
+
return isMissingTranscriptError(error) || isNotDirectory(error) ? "missing" : null;
|
|
7303
|
+
}
|
|
7304
|
+
}
|
|
6853
7305
|
function subagentsDirectory(transcriptPath) {
|
|
6854
7306
|
const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
|
|
6855
7307
|
return join6(stem, "subagents");
|
|
@@ -6895,8 +7347,8 @@ function createClaudeProducerWatcher(outboxDir) {
|
|
|
6895
7347
|
diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
|
|
6896
7348
|
});
|
|
6897
7349
|
}
|
|
6898
|
-
async function drainClaudeProducerOnce(options) {
|
|
6899
|
-
const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
|
|
7350
|
+
async function drainClaudeProducerOnce(options, signal) {
|
|
7351
|
+
const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce(signal).catch((error) => {
|
|
6900
7352
|
writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
|
|
6901
7353
|
throw error;
|
|
6902
7354
|
});
|
|
@@ -6905,7 +7357,7 @@ async function drainClaudeProducerOnce(options) {
|
|
|
6905
7357
|
}
|
|
6906
7358
|
|
|
6907
7359
|
// host/claude/src/claude-usage-facts-capturer.ts
|
|
6908
|
-
import { createHash as
|
|
7360
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
6909
7361
|
import { constants as constants7 } from "node:fs";
|
|
6910
7362
|
import { readdir as readdir3 } from "node:fs/promises";
|
|
6911
7363
|
import { join as join7 } from "node:path";
|
|
@@ -6914,6 +7366,7 @@ var ClaudeUsageFactsCapturer = class {
|
|
|
6914
7366
|
usage;
|
|
6915
7367
|
now;
|
|
6916
7368
|
registrations;
|
|
7369
|
+
idleGate;
|
|
6917
7370
|
nextSourceSlot = "main";
|
|
6918
7371
|
nextSubagentIndex = 0;
|
|
6919
7372
|
overflow = new ClaudeSubagentOverflowCheckpoint();
|
|
@@ -6922,6 +7375,7 @@ var ClaudeUsageFactsCapturer = class {
|
|
|
6922
7375
|
this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
|
|
6923
7376
|
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
6924
7377
|
this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
|
|
7378
|
+
this.idleGate = new HostUsageIdleGate();
|
|
6925
7379
|
}
|
|
6926
7380
|
async captureNext() {
|
|
6927
7381
|
const registrations = await this.sources.listTranscriptRegistrations();
|
|
@@ -6946,6 +7400,20 @@ var ClaudeUsageFactsCapturer = class {
|
|
|
6946
7400
|
return false;
|
|
6947
7401
|
}
|
|
6948
7402
|
async captureMain(registration) {
|
|
7403
|
+
const transcriptKey = claudeUsageIdleKey(registration, "main");
|
|
7404
|
+
const stateKey = claudeUsageIdleKey(registration, "state");
|
|
7405
|
+
const transcriptCheck = await this.idleGate.checkUnchanged(transcriptKey, registration.transcript_path);
|
|
7406
|
+
let stateCheck;
|
|
7407
|
+
if (transcriptCheck.unchanged) {
|
|
7408
|
+
stateCheck = await this.idleGate.checkUnchanged(stateKey, this.usage.statePath("claude", registration.host_source_ref, registration.host_session_ref));
|
|
7409
|
+
if (stateCheck.unchanged) return false;
|
|
7410
|
+
}
|
|
7411
|
+
const captured = await this.scanMain(registration);
|
|
7412
|
+
this.idleGate.confirmUnchanged(transcriptKey, transcriptCheck.signature);
|
|
7413
|
+
if (stateCheck !== void 0) this.idleGate.confirmUnchanged(stateKey, stateCheck.signature);
|
|
7414
|
+
return captured;
|
|
7415
|
+
}
|
|
7416
|
+
async scanMain(registration) {
|
|
6949
7417
|
const prepared = await openHostUsageTranscriptCursor({
|
|
6950
7418
|
path: registration.transcript_path,
|
|
6951
7419
|
producer: "claude",
|
|
@@ -6974,6 +7442,13 @@ var ClaudeUsageFactsCapturer = class {
|
|
|
6974
7442
|
async captureSubagent(registration, onFailure) {
|
|
6975
7443
|
const names = await readSubagentNames(registration);
|
|
6976
7444
|
if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
|
|
7445
|
+
const idle = await this.checkSubagentsUnchanged(registration, names);
|
|
7446
|
+
if (idle.unchanged) return false;
|
|
7447
|
+
const captured = await this.scanSubagents(registration, names, onFailure);
|
|
7448
|
+
for (const pending of idle.pending) this.idleGate.confirmUnchanged(pending.key, pending.signature);
|
|
7449
|
+
return captured;
|
|
7450
|
+
}
|
|
7451
|
+
async scanSubagents(registration, names, onFailure) {
|
|
6977
7452
|
let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
|
|
6978
7453
|
if (state === null) return false;
|
|
6979
7454
|
state = await this.usage.recoverPending(state);
|
|
@@ -6982,6 +7457,24 @@ var ClaudeUsageFactsCapturer = class {
|
|
|
6982
7457
|
if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
|
|
6983
7458
|
return await this.recordExcessSubagentGap(registration, state, names);
|
|
6984
7459
|
}
|
|
7460
|
+
async checkSubagentsUnchanged(registration, names) {
|
|
7461
|
+
const pending = [];
|
|
7462
|
+
if (names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) return { unchanged: false, pending };
|
|
7463
|
+
const check = async (slot, path) => {
|
|
7464
|
+
const key = claudeUsageIdleKey(registration, slot);
|
|
7465
|
+
const result = await this.idleGate.checkUnchanged(key, path);
|
|
7466
|
+
if (result.unchanged) return true;
|
|
7467
|
+
pending.push({ key, signature: result.signature });
|
|
7468
|
+
return false;
|
|
7469
|
+
};
|
|
7470
|
+
if (!await check("state", this.usage.statePath("claude", registration.host_source_ref, registration.host_session_ref))) return { unchanged: false, pending };
|
|
7471
|
+
const directory = subagentsDirectory(registration.transcript_path);
|
|
7472
|
+
if (!await check("subagents", directory)) return { unchanged: false, pending };
|
|
7473
|
+
for (const name of names) {
|
|
7474
|
+
if (!await check(subagentSlot(name), join7(directory, name))) return { unchanged: false, pending };
|
|
7475
|
+
}
|
|
7476
|
+
return { unchanged: true, pending };
|
|
7477
|
+
}
|
|
6985
7478
|
async retireMissingSubagent(state, names) {
|
|
6986
7479
|
const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
|
|
6987
7480
|
for (const [slot, cursor] of Object.entries(state.cursors)) {
|
|
@@ -7212,6 +7705,9 @@ function sourceFileRef(registration, device, inode) {
|
|
|
7212
7705
|
function subagentSlot(name) {
|
|
7213
7706
|
return `subagent:${sha2563(name)}`;
|
|
7214
7707
|
}
|
|
7708
|
+
function claudeUsageIdleKey(registration, slot) {
|
|
7709
|
+
return `${registration.host_source_ref}\0${registration.host_session_ref}\0${slot}`;
|
|
7710
|
+
}
|
|
7215
7711
|
function unscopedGap(reason) {
|
|
7216
7712
|
return { reason, source_file_ref: null, start_offset: null, end_offset: null, omitted_count: null };
|
|
7217
7713
|
}
|
|
@@ -7268,7 +7764,7 @@ function errorCode5(error) {
|
|
|
7268
7764
|
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
7269
7765
|
}
|
|
7270
7766
|
function sha2563(value) {
|
|
7271
|
-
return
|
|
7767
|
+
return createHash9("sha256").update(value).digest("hex");
|
|
7272
7768
|
}
|
|
7273
7769
|
|
|
7274
7770
|
// host/claude/src/claude-producer-service.ts
|
|
@@ -7370,10 +7866,9 @@ async function readClaudeInvocationHumanMessageWindow(input) {
|
|
|
7370
7866
|
}
|
|
7371
7867
|
|
|
7372
7868
|
// host/client-doctor.ts
|
|
7373
|
-
import { createHash as createHash9 } from "node:crypto";
|
|
7374
7869
|
import { execFile as execFile2 } from "node:child_process";
|
|
7375
|
-
import { access, open as open4,
|
|
7376
|
-
import { delimiter, extname, isAbsolute as
|
|
7870
|
+
import { access, open as open4, realpath, stat as stat5 } from "node:fs/promises";
|
|
7871
|
+
import { delimiter, extname, isAbsolute as isAbsolute5, join as join11 } from "node:path";
|
|
7377
7872
|
import { promisify } from "node:util";
|
|
7378
7873
|
|
|
7379
7874
|
// host/environment.ts
|
|
@@ -7392,7 +7887,7 @@ var WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET = "A-Za-z0-9._=-";
|
|
|
7392
7887
|
var WINDOWS_FIXED_CMD_ARGUMENT_REFUSAL_PATTERN = `[^${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]`;
|
|
7393
7888
|
var WINDOWS_FIXED_CMD_ARGUMENT = new RegExp(`^[${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]+$`, "u");
|
|
7394
7889
|
function validateHostCommandVector(vector, windowsConsumer = "cmd") {
|
|
7395
|
-
if (typeof vector.executable !== "string" || invalidText(vector.executable)) throw new TypeError(`Host command vector executable is invalid (${refusalFact("executable_kind", typeof vector.executable, "non-empty text without a NUL, newline or control character")}).`);
|
|
7890
|
+
if (typeof vector.executable !== "string" || vector.executable === "" || invalidText(vector.executable)) throw new TypeError(`Host command vector executable is invalid (${refusalFact("executable_kind", typeof vector.executable, "non-empty text without a NUL, newline or control character")}).`);
|
|
7396
7891
|
if (vector.args.length > HOST_COMMAND_ARGUMENT_MAX) throw new TypeError(`Host command vector has too many arguments (${refusalFact("argument_count", vector.args.length, `at most ${HOST_COMMAND_ARGUMENT_MAX}`)}).`);
|
|
7397
7892
|
const offending = vector.args.findIndex((argument) => typeof argument !== "string" || invalidText(argument));
|
|
7398
7893
|
if (offending >= 0) throw new TypeError(`Host command vector argument is invalid (${refusalFact("argument_index", offending, "no argument with a NUL, newline or control character")}).`);
|
|
@@ -7455,6 +7950,161 @@ function quoteWindowsExecArgument(value) {
|
|
|
7455
7950
|
return `"${escaped}"`;
|
|
7456
7951
|
}
|
|
7457
7952
|
|
|
7953
|
+
// host/lifecycle/src/host-bundle-manifest.ts
|
|
7954
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
7955
|
+
var HOST_BUNDLE_MAX_SELECTED_BYTES = 256 * 1024 * 1024;
|
|
7956
|
+
var HOST_BUNDLE_MAX_SIGSTORE_BYTES = 16 * 1024 * 1024;
|
|
7957
|
+
var HOST_BUNDLE_TARGETS = Object.freeze(["linux-x64", "linux-arm64", "darwin-arm64", "windows-x64"]);
|
|
7958
|
+
var HOST_BUNDLE_COMPONENTS = Object.freeze(["lifecycle", "relay", "codex", "claude"]);
|
|
7959
|
+
var HOST_BUNDLE_PRODUCERS = Object.freeze(["codex", "claude"]);
|
|
7960
|
+
var HOST_RUNTIME_COMPONENTS = Object.freeze(["relay", "codex", "claude"]);
|
|
7961
|
+
var HOST_BUNDLE_PRIVATE_RUNTIME_ROOT = "libexec/ceal-host";
|
|
7962
|
+
var HOST_WINDOWS_BACKGROUND_RELATIVE_PATH = `${HOST_BUNDLE_PRIVATE_RUNTIME_ROOT}/ceal-host-background.exe`;
|
|
7963
|
+
var HOST_BUNDLE_FILE_KEYS = Object.freeze(["executable", "owners", "path", "sha256"]);
|
|
7964
|
+
var HOST_BUNDLE_SUPPORTED_REQUIRED_FEATURES = Object.freeze([]);
|
|
7965
|
+
var HOST_BUNDLE_REFERENCE_STATUS = Object.freeze({ authority: "non_authoritative", transaction: "incomplete" });
|
|
7966
|
+
async function digestOpenHandleSha256(handle) {
|
|
7967
|
+
const hash = createHash10("sha256");
|
|
7968
|
+
let bytes = 0;
|
|
7969
|
+
for await (const chunk of handle.createReadStream({ autoClose: false })) {
|
|
7970
|
+
bytes += chunk.length;
|
|
7971
|
+
hash.update(chunk);
|
|
7972
|
+
}
|
|
7973
|
+
return { sha256: hash.digest("hex"), bytes };
|
|
7974
|
+
}
|
|
7975
|
+
async function digestFileSha256(path) {
|
|
7976
|
+
let handle;
|
|
7977
|
+
try {
|
|
7978
|
+
handle = await openNoFollow(path);
|
|
7979
|
+
return await digestOpenHandleSha256(handle);
|
|
7980
|
+
} finally {
|
|
7981
|
+
await handle?.close().catch(() => void 0);
|
|
7982
|
+
}
|
|
7983
|
+
}
|
|
7984
|
+
|
|
7985
|
+
// host/spawn-working-directory.ts
|
|
7986
|
+
import { lstatSync, mkdirSync, realpathSync } from "node:fs";
|
|
7987
|
+
import { tmpdir } from "node:os";
|
|
7988
|
+
import { basename, dirname as dirname9, isAbsolute as isAbsolute4, join as join10, normalize, parse as parse2, sep } from "node:path";
|
|
7989
|
+
function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
|
|
7990
|
+
const candidates = [];
|
|
7991
|
+
const explicit = candidateDir(stateRoot);
|
|
7992
|
+
if (explicit !== void 0) candidates.push(explicit);
|
|
7993
|
+
const fallback = defaultHostStateRoot();
|
|
7994
|
+
if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
|
|
7995
|
+
const temporary = candidateDir(join10(tmpdir(), "ceal-spawn-cwd"));
|
|
7996
|
+
if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
|
|
7997
|
+
const usable = firstKeptOutside(candidates, keepOutside);
|
|
7998
|
+
if (usable.directory !== void 0) return usable.directory;
|
|
7999
|
+
const osFallback = candidateDir(tmpdir());
|
|
8000
|
+
if (osFallback !== void 0 && keptOutside(osFallback, keepOutside)) return osFallback;
|
|
8001
|
+
throw new SpawnWorkingDirectoryRefusedError(keepOutside, usable.lastCreationError);
|
|
8002
|
+
}
|
|
8003
|
+
function firstKeptOutside(candidates, keepOutside) {
|
|
8004
|
+
let lastCreationError;
|
|
8005
|
+
for (const dir of candidates) {
|
|
8006
|
+
if (!keptOutside(dir, keepOutside)) continue;
|
|
8007
|
+
try {
|
|
8008
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
8009
|
+
return { directory: dir };
|
|
8010
|
+
} catch (error) {
|
|
8011
|
+
lastCreationError = error;
|
|
8012
|
+
}
|
|
8013
|
+
}
|
|
8014
|
+
return { lastCreationError };
|
|
8015
|
+
}
|
|
8016
|
+
var SpawnWorkingDirectoryRefusedError = class extends Error {
|
|
8017
|
+
avoided;
|
|
8018
|
+
constructor(keepOutside, lastCreationError) {
|
|
8019
|
+
super(lastCreationError === void 0 ? `spawn working directory: every candidate lies inside avoided tree(s) ${JSON.stringify(keepOutside.join(", "))}; refusing a working directory that would block the activation rename` : `spawn working directory: no usable candidate; last creation error: ${lastCreationError instanceof Error ? lastCreationError.message : String(lastCreationError)}`, { cause: lastCreationError });
|
|
8020
|
+
this.name = "SpawnWorkingDirectoryRefusedError";
|
|
8021
|
+
this.avoided = [...keepOutside];
|
|
8022
|
+
}
|
|
8023
|
+
};
|
|
8024
|
+
function candidateDir(dir) {
|
|
8025
|
+
if (dir === void 0 || dir === "") return void 0;
|
|
8026
|
+
if (!isAbsolute4(dir) || normalize(dir) !== dir || parse2(dir).root === dir) return void 0;
|
|
8027
|
+
return normalize(dir);
|
|
8028
|
+
}
|
|
8029
|
+
function defaultHostStateRoot() {
|
|
8030
|
+
if (process.platform === "win32") {
|
|
8031
|
+
const localAppData = nonEmptyEnv("LOCALAPPDATA");
|
|
8032
|
+
if (localAppData === void 0) return void 0;
|
|
8033
|
+
return candidateDir(join10(localAppData, "Ceal", "Host"));
|
|
8034
|
+
}
|
|
8035
|
+
if (process.platform === "darwin") {
|
|
8036
|
+
const home2 = nonEmptyEnv("HOME");
|
|
8037
|
+
if (home2 === void 0) return void 0;
|
|
8038
|
+
return candidateDir(join10(home2, "Library", "Application Support", "Ceal", "Host"));
|
|
8039
|
+
}
|
|
8040
|
+
const xdg = nonEmptyEnv("XDG_STATE_HOME");
|
|
8041
|
+
if (xdg !== void 0) {
|
|
8042
|
+
const root = candidateDir(join10(xdg, "ceal", "host"));
|
|
8043
|
+
if (root !== void 0) return root;
|
|
8044
|
+
}
|
|
8045
|
+
const home = nonEmptyEnv("HOME");
|
|
8046
|
+
if (home === void 0) return void 0;
|
|
8047
|
+
return candidateDir(join10(home, ".local", "state", "ceal", "host"));
|
|
8048
|
+
}
|
|
8049
|
+
function nonEmptyEnv(name) {
|
|
8050
|
+
const value = process.env[name];
|
|
8051
|
+
return value === void 0 || value === "" ? void 0 : value;
|
|
8052
|
+
}
|
|
8053
|
+
function keptOutside(dir, keepOutside) {
|
|
8054
|
+
const resolvedDir = resolveExistingPrefix(dir);
|
|
8055
|
+
if (resolvedDir === void 0) return false;
|
|
8056
|
+
for (const tree of keepOutside) {
|
|
8057
|
+
const clean = candidateDir(tree);
|
|
8058
|
+
if (clean === void 0) continue;
|
|
8059
|
+
const resolvedTree = resolveExistingPrefix(clean);
|
|
8060
|
+
if (resolvedTree === void 0) return false;
|
|
8061
|
+
if (insideDir(resolvedDir, resolvedTree)) return false;
|
|
8062
|
+
}
|
|
8063
|
+
return true;
|
|
8064
|
+
}
|
|
8065
|
+
function isMissingError(error) {
|
|
8066
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
8067
|
+
}
|
|
8068
|
+
function resolveExistingPrefix(path) {
|
|
8069
|
+
let probe = normalize(path);
|
|
8070
|
+
const missing = [];
|
|
8071
|
+
for (; ; ) {
|
|
8072
|
+
let exists = false;
|
|
8073
|
+
try {
|
|
8074
|
+
lstatSync(probe);
|
|
8075
|
+
exists = true;
|
|
8076
|
+
} catch (error) {
|
|
8077
|
+
if (!isMissingError(error)) return void 0;
|
|
8078
|
+
}
|
|
8079
|
+
if (exists) {
|
|
8080
|
+
let resolved;
|
|
8081
|
+
try {
|
|
8082
|
+
resolved = realpathSync.native(probe);
|
|
8083
|
+
} catch {
|
|
8084
|
+
return void 0;
|
|
8085
|
+
}
|
|
8086
|
+
for (let index = missing.length - 1; index >= 0; index -= 1) {
|
|
8087
|
+
const segment = missing[index];
|
|
8088
|
+
if (segment !== void 0) resolved = join10(resolved, segment);
|
|
8089
|
+
}
|
|
8090
|
+
return normalize(resolved);
|
|
8091
|
+
}
|
|
8092
|
+
const parent = dirname9(probe);
|
|
8093
|
+
if (parent === probe) return void 0;
|
|
8094
|
+
missing.push(basename(probe));
|
|
8095
|
+
probe = parent;
|
|
8096
|
+
}
|
|
8097
|
+
}
|
|
8098
|
+
function insideDir(dir, tree) {
|
|
8099
|
+
if (sameDir(dir, tree)) return true;
|
|
8100
|
+
if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
|
|
8101
|
+
return dir.startsWith(tree + sep);
|
|
8102
|
+
}
|
|
8103
|
+
function sameDir(left, right) {
|
|
8104
|
+
if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
|
|
8105
|
+
return left === right;
|
|
8106
|
+
}
|
|
8107
|
+
|
|
7458
8108
|
// host/client-doctor.ts
|
|
7459
8109
|
var execFileAsync = promisify(execFile2);
|
|
7460
8110
|
var GIT_OID = /^[a-f0-9]{40}$/u;
|
|
@@ -7536,12 +8186,12 @@ async function resolveCealExecutable(command, environment, platform = process.pl
|
|
|
7536
8186
|
try {
|
|
7537
8187
|
await access(candidate);
|
|
7538
8188
|
const path = await realpath(candidate);
|
|
7539
|
-
const metadata = await
|
|
8189
|
+
const metadata = await stat5(path);
|
|
7540
8190
|
if (!metadata.isFile()) continue;
|
|
7541
8191
|
const launcherKind = await inspectLauncherKind(path);
|
|
7542
8192
|
if (launcherKind !== void 0) return resolveLauncherBinary(path, launcherKind, environment, platform);
|
|
7543
|
-
if (platform === "win32" && !
|
|
7544
|
-
return { path, sha256:
|
|
8193
|
+
if (platform === "win32" && !isAbsolute5(command) && extname(path) === "") continue;
|
|
8194
|
+
return { path, sha256: (await digestFileSha256(path)).sha256 };
|
|
7545
8195
|
} catch {
|
|
7546
8196
|
}
|
|
7547
8197
|
}
|
|
@@ -7563,7 +8213,7 @@ async function inspectLauncherKind(path) {
|
|
|
7563
8213
|
}
|
|
7564
8214
|
async function resolveLauncherBinary(launcherPath, kind, environment, platform) {
|
|
7565
8215
|
const invocation = hostScriptLauncherInvocation(launcherPath, CEAL_CLIENT_DOCTOR_COMMAND, kind, platform, environment);
|
|
7566
|
-
const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
|
|
8216
|
+
const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, cwd: resolveCealSpawnWorkingDirectory(), ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
|
|
7567
8217
|
let parsed;
|
|
7568
8218
|
try {
|
|
7569
8219
|
parsed = JSON.parse(result.stdout);
|
|
@@ -7572,20 +8222,20 @@ async function resolveLauncherBinary(launcherPath, kind, environment, platform)
|
|
|
7572
8222
|
}
|
|
7573
8223
|
if (!isRecord8(parsed) || parsed.schema_version !== CEAL_CLIENT_DOCTOR_SCHEMA_VERSION || parsed.ok !== true || typeof parsed.binary_path !== "string" || parsed.binary_path.length === 0) throw new Error("launcher doctor did not report a binary path");
|
|
7574
8224
|
const binaryPath = await realpath(parsed.binary_path);
|
|
7575
|
-
const metadata = await
|
|
8225
|
+
const metadata = await stat5(binaryPath);
|
|
7576
8226
|
if (!metadata.isFile()) throw new Error("launcher doctor reported a non-file binary path");
|
|
7577
|
-
return { path: binaryPath, sha256:
|
|
8227
|
+
return { path: binaryPath, sha256: (await digestFileSha256(binaryPath)).sha256 };
|
|
7578
8228
|
}
|
|
7579
8229
|
function executableCandidates(command, environment, platform) {
|
|
7580
|
-
if (
|
|
8230
|
+
if (isAbsolute5(command)) return [command];
|
|
7581
8231
|
const pathValue = environmentValue(environment, "PATH", platform) ?? "";
|
|
7582
8232
|
const directories = pathValue.split(delimiter).filter((entry) => entry.length > 0);
|
|
7583
|
-
if (platform !== "win32" || extname(command) !== "") return directories.map((entry) =>
|
|
7584
|
-
return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) =>
|
|
8233
|
+
if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join11(entry, command));
|
|
8234
|
+
return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join11(entry, `${command}${suffix}`)));
|
|
7585
8235
|
}
|
|
7586
8236
|
async function executeCealCommand(executable, args, environment) {
|
|
7587
8237
|
try {
|
|
7588
|
-
const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8" });
|
|
8238
|
+
const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8", cwd: resolveCealSpawnWorkingDirectory() });
|
|
7589
8239
|
return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
|
|
7590
8240
|
} catch (error) {
|
|
7591
8241
|
if (isRecord8(error)) return { exit_code: typeof error.code === "number" ? error.code : 1, stdout: typeof error.stdout === "string" ? error.stdout : "", stderr: typeof error.stderr === "string" ? error.stderr : "" };
|