@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
|
@@ -328,6 +328,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
|
|
|
328
328
|
// (never connected, revoked, or expired). The caller runs that exact
|
|
329
329
|
// Operation, completes the consent it hands back, and retries the same call.
|
|
330
330
|
"connect_personal_account",
|
|
331
|
+
// The refusal names the caller's own preferences update step: the read
|
|
332
|
+
// needs a personal connection the caller holds but has not selected in
|
|
333
|
+
// Ceal preferences, or has not confirmed through the initial review. The
|
|
334
|
+
// caller reads personal.preferences.get, runs personal.preferences.update
|
|
335
|
+
// at the current revision to select it, and retries the same call.
|
|
336
|
+
"update_personal_preferences",
|
|
331
337
|
// The provider or Gateway named a bounded wait; the caller waits that long
|
|
332
338
|
// and submits the same read again.
|
|
333
339
|
"retry_after",
|
|
@@ -478,7 +484,7 @@ var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
|
|
|
478
484
|
var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
|
|
479
485
|
var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
|
|
480
486
|
var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
|
|
481
|
-
var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
|
|
487
|
+
var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "race_recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
|
|
482
488
|
var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
|
|
483
489
|
var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
|
|
484
490
|
var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
|
|
@@ -871,15 +877,19 @@ function requireIsoTimestamp(value, message) {
|
|
|
871
877
|
// packages/ceal-client-protocol/src/failure-guidance-table.ts
|
|
872
878
|
var CEAL_FAILURE_REDACTION_CLASSES = vocabulary(["model_safe", "withheld"]);
|
|
873
879
|
var CEAL_GATEWAY_STARTING_FAILURE_CODE = "gateway_starting";
|
|
880
|
+
var CEAL_GATEWAY_RESTARTING_FAILURE_CODE = "gateway_restarting";
|
|
874
881
|
var CEAL_OWNER_BOOTSTRAP_ABSENT_FAILURE_CODE = "bootstrap_absent";
|
|
875
882
|
var CEAL_OWNER_BOOTSTRAP_UNAVAILABLE_FAILURE_CODE = "bootstrap_unavailable";
|
|
876
883
|
var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
|
|
877
884
|
var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
|
|
878
885
|
var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
|
|
879
886
|
var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
|
|
880
|
-
var
|
|
887
|
+
var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
|
|
888
|
+
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}\`.`;
|
|
881
889
|
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.";
|
|
882
|
-
var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn;
|
|
890
|
+
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.";
|
|
891
|
+
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.";
|
|
892
|
+
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.";
|
|
883
893
|
var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
|
|
884
894
|
var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
|
|
885
895
|
function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
|
|
@@ -909,6 +919,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
909
919
|
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),
|
|
910
920
|
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),
|
|
911
921
|
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),
|
|
922
|
+
// A stored session that predates the authority-epoch commitment carries no
|
|
923
|
+
// epoch to compare, so it can never refresh: adopt a fresh session instead.
|
|
924
|
+
authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
|
|
912
925
|
refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
|
|
913
926
|
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),
|
|
914
927
|
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),
|
|
@@ -930,6 +943,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
930
943
|
contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
|
|
931
944
|
// The serving gate answers before refresh execution, so retrying the same attempt is safe.
|
|
932
945
|
[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),
|
|
946
|
+
// The serving gate answers before execution while the Gateway is stopping, so retrying the same request is safe.
|
|
947
|
+
[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),
|
|
933
948
|
gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
|
|
934
949
|
// The serving gate emits this code with no message; the sentence is the owner-normalized form of the
|
|
935
950
|
// `gateway_internal_error` guidance (decided with the operator 2026-10-13).
|
|
@@ -1033,10 +1048,11 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
1033
1048
|
host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
|
|
1034
1049
|
// The bounded Host reason does not prove ephemerality. A Host refusal never
|
|
1035
1050
|
// changes mode; standalone remains the separate Client authority path.
|
|
1036
|
-
host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "
|
|
1051
|
+
host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
|
|
1037
1052
|
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),
|
|
1038
1053
|
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),
|
|
1039
1054
|
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),
|
|
1055
|
+
host_transcript_unavailable: guidance(HOST_TRANSCRIPT_UNAVAILABLE, "retry", 401, true),
|
|
1040
1056
|
host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
|
|
1041
1057
|
host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
|
|
1042
1058
|
host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
|
|
@@ -1050,7 +1066,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
1050
1066
|
// Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
|
|
1051
1067
|
// sandboxed Relay socket names the run-alone retry.
|
|
1052
1068
|
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),
|
|
1053
|
-
host_relay_unavailable: guidance(
|
|
1069
|
+
host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
|
|
1054
1070
|
host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
|
|
1055
1071
|
host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
|
|
1056
1072
|
host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
|
|
@@ -1298,7 +1314,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
|
|
|
1298
1314
|
max_literal_nodes: 512
|
|
1299
1315
|
});
|
|
1300
1316
|
|
|
1301
|
-
// packages/ceal-client-protocol/src/operation-json-schema.ts
|
|
1317
|
+
// packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
|
|
1302
1318
|
var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
|
|
1303
1319
|
|
|
1304
1320
|
// packages/ceal-client-protocol/src/operation-contract-validation.ts
|
|
@@ -1407,6 +1423,10 @@ var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
|
|
|
1407
1423
|
gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
|
|
1408
1424
|
});
|
|
1409
1425
|
|
|
1426
|
+
// packages/ceal-client-protocol/src/canonical-http-boundary.ts
|
|
1427
|
+
var CEAL_HTTP_CLIENT_EXCHANGE_REF_PATTERN_SOURCE = "^client-exchange:[a-f0-9]{32}$";
|
|
1428
|
+
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}$";
|
|
1429
|
+
|
|
1410
1430
|
// packages/ceal-client-protocol/src/gateway-installation-activation.ts
|
|
1411
1431
|
var CEAL_GATEWAY_INSTALLATION_ACTIVATION_CODE_DATA_CHARACTERS = 32;
|
|
1412
1432
|
var CEAL_GATEWAY_INSTALLATION_ACTIVATION_CODE_CHECK_CHARACTERS = 8;
|
|
@@ -1429,6 +1449,7 @@ var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUI
|
|
|
1429
1449
|
var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
|
|
1430
1450
|
|
|
1431
1451
|
// packages/ceal-client-protocol/src/resource-read-result.ts
|
|
1452
|
+
var CEAL_RESOURCE_GET_CHILD_REF_KINDS = Object.freeze(["section", "slide", "question"]);
|
|
1432
1453
|
var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
|
|
1433
1454
|
var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
|
|
1434
1455
|
var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
|
|
@@ -1445,7 +1466,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
|
|
|
1445
1466
|
var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
|
|
1446
1467
|
var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
|
|
1447
1468
|
var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
|
|
1448
|
-
var
|
|
1469
|
+
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.`;
|
|
1470
|
+
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.`;
|
|
1449
1471
|
function shellSingleQuoted(value) {
|
|
1450
1472
|
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
1451
1473
|
}
|
|
@@ -1631,6 +1653,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
|
|
|
1631
1653
|
"github.review.submitted",
|
|
1632
1654
|
"github.issue_comment.created",
|
|
1633
1655
|
"github.review_comment.created",
|
|
1656
|
+
"github.issue_comment.edited",
|
|
1657
|
+
"github.review_comment.edited",
|
|
1634
1658
|
"github.reaction.created",
|
|
1635
1659
|
"github.reaction.deleted",
|
|
1636
1660
|
"github.pull_request.review_requested",
|
|
@@ -1659,6 +1683,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
|
|
|
1659
1683
|
"github.release.published": "release_published",
|
|
1660
1684
|
"github.issue.edited": "resource_modified",
|
|
1661
1685
|
"github.pull_request.edited": "resource_modified",
|
|
1686
|
+
"github.issue_comment.edited": "resource_modified",
|
|
1687
|
+
"github.review_comment.edited": "resource_modified",
|
|
1662
1688
|
"github.reaction.created": "reaction_created",
|
|
1663
1689
|
"github.reaction.deleted": "ceal_write_completed",
|
|
1664
1690
|
"github.pull_request.review_requested": "ceal_write_completed",
|
|
@@ -2317,6 +2343,8 @@ var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
|
|
|
2317
2343
|
var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
|
|
2318
2344
|
var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
|
|
2319
2345
|
var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
|
|
2346
|
+
var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_ENTRY_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text", "text_truncated"]);
|
|
2347
|
+
var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_REQUIRED_KEYS = vocabulary(["host_turn_ref", "host_input_ref", "text"]);
|
|
2320
2348
|
function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
|
|
2321
2349
|
const messages = [];
|
|
2322
2350
|
let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
|
|
@@ -2400,6 +2428,7 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
|
|
|
2400
2428
|
"context_replaced",
|
|
2401
2429
|
"no_binding",
|
|
2402
2430
|
"context_expired",
|
|
2431
|
+
"transcript_unavailable",
|
|
2403
2432
|
"host_source_refused",
|
|
2404
2433
|
"host_credential_refused",
|
|
2405
2434
|
"gateway_unavailable",
|
|
@@ -2429,9 +2458,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
|
2429
2458
|
invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
|
|
2430
2459
|
options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
|
|
2431
2460
|
session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
|
|
2432
|
-
//
|
|
2433
|
-
//
|
|
2434
|
-
|
|
2461
|
+
// A missing turn right after a Host restart clears by itself once the
|
|
2462
|
+
// watcher reactivates the turn, so the caller waits briefly and retries;
|
|
2463
|
+
// a caller that knows it is in an ephemeral side conversation keeps the
|
|
2464
|
+
// standalone fallback the guidance names second.
|
|
2465
|
+
context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
|
|
2435
2466
|
activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
|
|
2436
2467
|
context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
|
|
2437
2468
|
// `no_binding` now means the producer has no real current Host session. The
|
|
@@ -2439,6 +2470,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
|
2439
2470
|
// useful retry until the consumer is running inside a Host session.
|
|
2440
2471
|
no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
|
|
2441
2472
|
context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
|
|
2473
|
+
// The registered transcript is readable but names no human message for
|
|
2474
|
+
// this turn, so a Gateway mint could only be refused. The caller sends a
|
|
2475
|
+
// new message so the turn hook re-registers the transcript, then retries;
|
|
2476
|
+
// a retry with no new turn cannot bind anything new.
|
|
2477
|
+
transcript_unavailable: Object.freeze({ classification: "host_transcript_unavailable", next_action: "retry" }),
|
|
2442
2478
|
host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
|
|
2443
2479
|
host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
|
|
2444
2480
|
gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
|
|
@@ -2448,7 +2484,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
|
2448
2484
|
gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
|
|
2449
2485
|
producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
|
|
2450
2486
|
relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
|
|
2451
|
-
relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "
|
|
2487
|
+
relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
|
|
2452
2488
|
transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
|
|
2453
2489
|
mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
|
|
2454
2490
|
relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
|
|
@@ -2540,11 +2576,15 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
|
|
|
2540
2576
|
|
|
2541
2577
|
// packages/ceal-client-protocol/src/operator-diagnostic.ts
|
|
2542
2578
|
var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
|
|
2543
|
-
var
|
|
2579
|
+
var OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES = 8;
|
|
2544
2580
|
var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
|
|
2545
2581
|
var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
|
|
2546
2582
|
var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
|
|
2547
2583
|
var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
|
|
2584
|
+
var LOCAL_OPERATOR_DIAGNOSTIC_PATHS = /* @__PURE__ */ Symbol.for("ceal.local-operator-diagnostic-paths");
|
|
2585
|
+
var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX = /(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)/u;
|
|
2586
|
+
var OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START = new RegExp(`^${OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_PREFIX.source}`, "u");
|
|
2587
|
+
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");
|
|
2548
2588
|
function redactOperatorDiagnosticSecrets(value) {
|
|
2549
2589
|
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]");
|
|
2550
2590
|
}
|
|
@@ -2553,8 +2593,9 @@ function redactOperatorDiagnosticText(value) {
|
|
|
2553
2593
|
return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
|
|
2554
2594
|
}
|
|
2555
2595
|
function renderOperatorDiagnostic(value) {
|
|
2556
|
-
const state = collectDiagnosticState(value);
|
|
2596
|
+
const state = collectDiagnosticState(value, read(value, LOCAL_OPERATOR_DIAGNOSTIC_PATHS) === true);
|
|
2557
2597
|
const fields = [
|
|
2598
|
+
state.truncated ? "causes_truncated=true" : void 0,
|
|
2558
2599
|
state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
|
|
2559
2600
|
state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
|
|
2560
2601
|
state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
|
|
@@ -2564,23 +2605,27 @@ function renderOperatorDiagnostic(value) {
|
|
|
2564
2605
|
const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
|
|
2565
2606
|
return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
|
|
2566
2607
|
}
|
|
2567
|
-
function collectDiagnosticState(value) {
|
|
2568
|
-
const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
|
|
2608
|
+
function collectDiagnosticState(value, preserveLocalAbsolutePaths) {
|
|
2609
|
+
const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0, truncated: false };
|
|
2569
2610
|
const visited = /* @__PURE__ */ new Set(), pending = [value];
|
|
2570
|
-
|
|
2611
|
+
let inspected = 0;
|
|
2612
|
+
while (pending.length > 0 && inspected < OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES) {
|
|
2571
2613
|
const current = pending.shift();
|
|
2572
|
-
if (current
|
|
2614
|
+
if (current === void 0 || isObject(current) && visited.has(current)) continue;
|
|
2615
|
+
inspected += 1;
|
|
2616
|
+
visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths);
|
|
2573
2617
|
}
|
|
2618
|
+
state.truncated ||= pending.length > 0;
|
|
2574
2619
|
return state;
|
|
2575
2620
|
}
|
|
2576
|
-
function visitDiagnosticNode(current, state, pending, visited) {
|
|
2621
|
+
function visitDiagnosticNode(current, state, pending, visited, preserveLocalAbsolutePaths) {
|
|
2577
2622
|
if (isObject(current)) {
|
|
2578
2623
|
if (visited.has(current)) return;
|
|
2579
2624
|
visited.add(current);
|
|
2580
2625
|
}
|
|
2581
2626
|
captureProcessEvidence(current, state);
|
|
2582
|
-
appendCause(current, state.causes);
|
|
2583
|
-
enqueueCauseChildren(current, state
|
|
2627
|
+
appendCause(current, state.causes, preserveLocalAbsolutePaths);
|
|
2628
|
+
enqueueCauseChildren(current, state, pending);
|
|
2584
2629
|
}
|
|
2585
2630
|
function captureProcessEvidence(current, state) {
|
|
2586
2631
|
if (state.status === void 0) state.status = safeStatus(read(current, "status"));
|
|
@@ -2588,10 +2633,9 @@ function captureProcessEvidence(current, state) {
|
|
|
2588
2633
|
if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
|
|
2589
2634
|
if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
|
|
2590
2635
|
}
|
|
2591
|
-
function appendCause(current, causes) {
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
causes.push(errorCause(current));
|
|
2636
|
+
function appendCause(current, causes, preserveLocalAbsolutePaths) {
|
|
2637
|
+
if (current instanceof Error) {
|
|
2638
|
+
causes.push(errorCause(current, preserveLocalAbsolutePaths));
|
|
2595
2639
|
return;
|
|
2596
2640
|
}
|
|
2597
2641
|
if (!isObject(current)) {
|
|
@@ -2599,7 +2643,7 @@ function appendCause(current, causes) {
|
|
|
2599
2643
|
if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
|
|
2600
2644
|
}
|
|
2601
2645
|
}
|
|
2602
|
-
function errorCause(error) {
|
|
2646
|
+
function errorCause(error, preserveLocalAbsolutePaths) {
|
|
2603
2647
|
const name = safeText(read(error, "name")) ?? "Error";
|
|
2604
2648
|
const message = safeText(read(error, "message"));
|
|
2605
2649
|
const codeValue = read(error, "code");
|
|
@@ -2607,14 +2651,29 @@ function errorCause(error) {
|
|
|
2607
2651
|
const errnoValue = read(error, "errno");
|
|
2608
2652
|
const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
|
|
2609
2653
|
const syscall = safeText(read(error, "syscall"));
|
|
2610
|
-
const path = safePath(read(error, "path"));
|
|
2654
|
+
const path = safePath(read(error, "path"), preserveLocalAbsolutePaths);
|
|
2611
2655
|
return Object.freeze({ error_class: name, ...message === void 0 ? {} : { message }, ...code === void 0 ? {} : { code }, ...errno === void 0 ? {} : { errno }, ...syscall === void 0 ? {} : { syscall }, ...path === void 0 ? {} : { path } });
|
|
2612
2656
|
}
|
|
2613
|
-
function enqueueCauseChildren(current,
|
|
2657
|
+
function enqueueCauseChildren(current, state, pending) {
|
|
2614
2658
|
const cause = read(current, "cause");
|
|
2615
2659
|
if (cause !== void 0) pending.push(cause);
|
|
2616
2660
|
const errors = read(current, "errors");
|
|
2617
|
-
if (Array.isArray(errors))
|
|
2661
|
+
if (Array.isArray(errors)) {
|
|
2662
|
+
const remaining = OPERATOR_DIAGNOSTIC_MAX_CAUSE_NODES - state.causes.length;
|
|
2663
|
+
const length = read(errors, "length");
|
|
2664
|
+
if (typeof length !== "number") {
|
|
2665
|
+
state.truncated = true;
|
|
2666
|
+
return;
|
|
2667
|
+
}
|
|
2668
|
+
state.truncated ||= length > remaining;
|
|
2669
|
+
for (let index = 0; index < Math.min(length, remaining); index += 1) {
|
|
2670
|
+
try {
|
|
2671
|
+
pending.push(errors[index]);
|
|
2672
|
+
} catch {
|
|
2673
|
+
state.truncated = true;
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2618
2677
|
}
|
|
2619
2678
|
function isObject(value) {
|
|
2620
2679
|
return typeof value === "object" && value !== null;
|
|
@@ -2643,10 +2702,11 @@ function safeText(value) {
|
|
|
2643
2702
|
const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
|
|
2644
2703
|
return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
|
|
2645
2704
|
}
|
|
2646
|
-
function safePath(value) {
|
|
2705
|
+
function safePath(value, preserveLocalAbsolutePaths) {
|
|
2647
2706
|
if (typeof value !== "string") return void 0;
|
|
2648
2707
|
const safe = safeDiagnosticText(value);
|
|
2649
2708
|
if (safe.length === 0) return void 0;
|
|
2709
|
+
if (!preserveLocalAbsolutePaths && hasAbsolutePathPrefix(value) && !safe.startsWith("[home path redacted]")) return "[path redacted]";
|
|
2650
2710
|
if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
|
|
2651
2711
|
const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
|
|
2652
2712
|
const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
|
|
@@ -2718,7 +2778,10 @@ function redactUrls(value) {
|
|
|
2718
2778
|
return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
|
|
2719
2779
|
}
|
|
2720
2780
|
function redactFilePaths(value) {
|
|
2721
|
-
return value.replaceAll(
|
|
2781
|
+
return value.replaceAll(OPERATOR_DIAGNOSTIC_FREEFORM_PATH_PATTERN, "[path redacted]$2");
|
|
2782
|
+
}
|
|
2783
|
+
function hasAbsolutePathPrefix(value) {
|
|
2784
|
+
return OPERATOR_DIAGNOSTIC_ABSOLUTE_PATH_START.test(value);
|
|
2722
2785
|
}
|
|
2723
2786
|
function homePathRange(value, match, prefixLength) {
|
|
2724
2787
|
const index = match.index;
|
|
@@ -2829,7 +2892,7 @@ function waitForAbort(signal, milliseconds) {
|
|
|
2829
2892
|
import { execFile } from "node:child_process";
|
|
2830
2893
|
import { constants } from "node:fs";
|
|
2831
2894
|
import { lstat, open } from "node:fs/promises";
|
|
2832
|
-
import { dirname, join as join2, win32 as win323 } from "node:path";
|
|
2895
|
+
import { dirname, join as join2, parse, win32 as win323 } from "node:path";
|
|
2833
2896
|
import { fileURLToPath } from "node:url";
|
|
2834
2897
|
var SecureFileCustodyError = class extends Error {
|
|
2835
2898
|
name = "SecureFileCustodyError";
|
|
@@ -2929,7 +2992,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
|
|
|
2929
2992
|
const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
|
|
2930
2993
|
const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
|
|
2931
2994
|
return await new Promise((resolve, reject2) => {
|
|
2932
|
-
const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
|
|
2995
|
+
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) => {
|
|
2933
2996
|
const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
|
|
2934
2997
|
if (exitCode === null) {
|
|
2935
2998
|
reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
|
|
@@ -3107,7 +3170,7 @@ async function serveProducer(runtimeOptions, timing, signal, drain, wait = (mill
|
|
|
3107
3170
|
while (!signal.aborted) {
|
|
3108
3171
|
let delay = timing.reconcile_interval_ms;
|
|
3109
3172
|
try {
|
|
3110
|
-
await drain(runtimeOptions);
|
|
3173
|
+
await drain(runtimeOptions, signal);
|
|
3111
3174
|
} catch {
|
|
3112
3175
|
delay = timing.retry_backoff_ms;
|
|
3113
3176
|
}
|
|
@@ -3342,10 +3405,10 @@ function record(value) {
|
|
|
3342
3405
|
}
|
|
3343
3406
|
|
|
3344
3407
|
// host/relay/src/host-usage-facts-store.ts
|
|
3345
|
-
import { createHash as
|
|
3408
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
3346
3409
|
import { constants as constants4 } from "node:fs";
|
|
3347
|
-
import { mkdir as
|
|
3348
|
-
import { dirname as
|
|
3410
|
+
import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
|
|
3411
|
+
import { dirname as dirname5, join as join3 } from "node:path";
|
|
3349
3412
|
|
|
3350
3413
|
// host/relay/src/durable-atomic-replacement.ts
|
|
3351
3414
|
import { lstat as lstat3, mkdir, open as open2, rename, unlink } from "node:fs/promises";
|
|
@@ -3370,7 +3433,7 @@ function resolveRetrySchedule(tuning) {
|
|
|
3370
3433
|
startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
|
|
3371
3434
|
maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
|
|
3372
3435
|
sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
|
|
3373
|
-
now: tuning.now ?? (() =>
|
|
3436
|
+
now: tuning.now ?? (() => performance.now())
|
|
3374
3437
|
};
|
|
3375
3438
|
}
|
|
3376
3439
|
async function renameWithWindowsRetry(operation, tuning) {
|
|
@@ -3478,1127 +3541,1315 @@ function errorCode(error) {
|
|
|
3478
3541
|
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
3479
3542
|
}
|
|
3480
3543
|
|
|
3481
|
-
// host/relay/src/host-
|
|
3482
|
-
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
|
|
3487
|
-
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
3491
|
-
var
|
|
3492
|
-
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
}
|
|
3513
|
-
}
|
|
3514
|
-
async close() {
|
|
3515
|
-
const cursor = this.sessionDirectoryCursor;
|
|
3516
|
-
this.sessionDirectoryCursor = void 0;
|
|
3517
|
-
await cursor?.close();
|
|
3518
|
-
}
|
|
3519
|
-
async readState(producer, hostSourceRef, hostSessionRef) {
|
|
3520
|
-
await this.prepare();
|
|
3521
|
-
const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
3522
|
-
const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
3523
|
-
if (value === null) return null;
|
|
3524
|
-
validateState(value, producer, hostSourceRef, hostSessionRef);
|
|
3525
|
-
return value;
|
|
3526
|
-
}
|
|
3527
|
-
createState(producer, hostSourceRef, hostSessionRef) {
|
|
3528
|
-
return {
|
|
3529
|
-
schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
|
|
3530
|
-
producer,
|
|
3531
|
-
host_source_ref: hostSourceRef,
|
|
3532
|
-
host_session_ref: hostSessionRef,
|
|
3533
|
-
cursors: {},
|
|
3534
|
-
eligible_batches: [],
|
|
3535
|
-
coverage_gaps: [],
|
|
3536
|
-
coverage_gap_created_at: null
|
|
3537
|
-
};
|
|
3538
|
-
}
|
|
3539
|
-
async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
|
|
3540
|
-
let state = await this.readState(producer, hostSourceRef, hostSessionRef);
|
|
3541
|
-
if (state === null) {
|
|
3542
|
-
state = this.createState(producer, hostSourceRef, hostSessionRef);
|
|
3543
|
-
state = await this.writeCursor(state, sourceSlot, initial);
|
|
3544
|
-
}
|
|
3545
|
-
state = await this.recoverPending(state);
|
|
3546
|
-
if (state.quarantined_reason !== void 0) return null;
|
|
3547
|
-
state = await this.commitCoverageGaps(state, createdAt);
|
|
3548
|
-
const cursor = state.cursors[sourceSlot];
|
|
3549
|
-
return cursor === void 0 ? null : { state, cursor };
|
|
3544
|
+
// host/relay/src/host-producer-core.ts
|
|
3545
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
3546
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3547
|
+
import { lstat as lstat4, readdir, stat as stat2 } from "node:fs/promises";
|
|
3548
|
+
|
|
3549
|
+
// host/service-log.ts
|
|
3550
|
+
import { copyFile, mkdir as mkdir2, stat, truncate, appendFile } from "node:fs/promises";
|
|
3551
|
+
import { dirname as dirname4, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
|
|
3552
|
+
|
|
3553
|
+
// host/service-log-delivery.ts
|
|
3554
|
+
var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
|
|
3555
|
+
function createHostServiceLogDelivery(stream, schedule = (flush) => {
|
|
3556
|
+
setImmediate(flush);
|
|
3557
|
+
}, onDeliveryGap = () => void 0) {
|
|
3558
|
+
const pending = [];
|
|
3559
|
+
const highWaterMark = stream.writableHighWaterMark;
|
|
3560
|
+
const byteBudget = highWaterMark + highWaterMark;
|
|
3561
|
+
let pendingBytes = 0;
|
|
3562
|
+
let droppedLines = 0;
|
|
3563
|
+
let flushScheduled = false;
|
|
3564
|
+
let waitingForDrain = false;
|
|
3565
|
+
let closed = !stream.writable;
|
|
3566
|
+
function stop() {
|
|
3567
|
+
if (closed) return;
|
|
3568
|
+
closed = true;
|
|
3569
|
+
pending.length = 0;
|
|
3570
|
+
pendingBytes = 0;
|
|
3571
|
+
stream.off("drain", onDrain);
|
|
3572
|
+
stream.off("close", onTerminal);
|
|
3573
|
+
stream.off("finish", onTerminal);
|
|
3574
|
+
stream.off("error", onError);
|
|
3550
3575
|
}
|
|
3551
|
-
|
|
3552
|
-
|
|
3553
|
-
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3554
|
-
if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
|
|
3555
|
-
const current = latest.cursors[sourceSlot];
|
|
3556
|
-
if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
|
|
3557
|
-
const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
|
|
3558
|
-
await this.writeState(updated);
|
|
3559
|
-
return updated;
|
|
3560
|
-
});
|
|
3576
|
+
function onTerminal() {
|
|
3577
|
+
stop();
|
|
3561
3578
|
}
|
|
3562
|
-
|
|
3563
|
-
|
|
3564
|
-
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3565
|
-
return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
|
|
3566
|
-
});
|
|
3579
|
+
function onError() {
|
|
3580
|
+
stop();
|
|
3567
3581
|
}
|
|
3568
|
-
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
const recovered = await this.finishPendingTransition(latest);
|
|
3572
|
-
await this.sweepOrphanedBatches(recovered);
|
|
3573
|
-
return recovered;
|
|
3574
|
-
});
|
|
3582
|
+
function onDrain() {
|
|
3583
|
+
waitingForDrain = false;
|
|
3584
|
+
scheduleFlush();
|
|
3575
3585
|
}
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
3579
|
-
|
|
3580
|
-
|
|
3581
|
-
const expected = expectedBatchNames(state);
|
|
3582
|
-
const directory = await opendir(directoryPath);
|
|
3583
|
-
let inspected = 0;
|
|
3584
|
-
let deleted = 0;
|
|
3586
|
+
function scheduleFlush() {
|
|
3587
|
+
if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
|
|
3588
|
+
flushScheduled = true;
|
|
3589
|
+
let scheduling = true;
|
|
3590
|
+
let invokedSynchronously = false;
|
|
3585
3591
|
try {
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
}
|
|
3594
|
-
} finally {
|
|
3595
|
-
await directory.close();
|
|
3596
|
-
}
|
|
3597
|
-
if (deleted > 0) await syncDirectory(directoryPath, this.platform);
|
|
3598
|
-
return deleted;
|
|
3599
|
-
}
|
|
3600
|
-
async commitCoverageGaps(state, createdAt) {
|
|
3601
|
-
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3602
|
-
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3603
|
-
if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
|
|
3604
|
-
const sourceRanges = coverageRanges(latest.coverage_gaps);
|
|
3605
|
-
const canonical = createCealHostUsageBatch({
|
|
3606
|
-
host_source_ref: latest.host_source_ref,
|
|
3607
|
-
host_session_ref: latest.host_session_ref,
|
|
3608
|
-
created_at: latest.coverage_gap_created_at ?? createdAt,
|
|
3609
|
-
source_ranges: sourceRanges,
|
|
3610
|
-
facts: [],
|
|
3611
|
-
coverage_gaps: latest.coverage_gaps
|
|
3592
|
+
schedule(() => {
|
|
3593
|
+
if (scheduling) {
|
|
3594
|
+
invokedSynchronously = true;
|
|
3595
|
+
return;
|
|
3596
|
+
}
|
|
3597
|
+
flushScheduled = false;
|
|
3598
|
+
flush();
|
|
3612
3599
|
});
|
|
3613
|
-
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
|
|
3617
|
-
|
|
3618
|
-
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
3623
|
-
if (state === null) continue;
|
|
3624
|
-
validateStateOwner(state, producer, hostSourceRef);
|
|
3625
|
-
let validated = state;
|
|
3626
|
-
if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
|
|
3627
|
-
else validated = await this.recoverPending(validated);
|
|
3628
|
-
if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
|
|
3629
|
-
const next = validated.eligible_batches[0];
|
|
3630
|
-
if (next === void 0) continue;
|
|
3631
|
-
const batch = await this.readBatch(validated, next.batch_ref);
|
|
3632
|
-
return { state: validated, batch };
|
|
3600
|
+
} catch {
|
|
3601
|
+
flushScheduled = false;
|
|
3602
|
+
stop();
|
|
3603
|
+
return;
|
|
3604
|
+
}
|
|
3605
|
+
scheduling = false;
|
|
3606
|
+
if (invokedSynchronously) {
|
|
3607
|
+
flushScheduled = false;
|
|
3608
|
+
stop();
|
|
3633
3609
|
}
|
|
3634
|
-
return null;
|
|
3635
3610
|
}
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
|
|
3640
|
-
|
|
3641
|
-
|
|
3642
|
-
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
|
|
3611
|
+
function flush() {
|
|
3612
|
+
if (closed) return;
|
|
3613
|
+
if (!stream.writable) {
|
|
3614
|
+
stop();
|
|
3615
|
+
return;
|
|
3616
|
+
}
|
|
3617
|
+
while (pending.length > 0) {
|
|
3618
|
+
if (stream.writableNeedDrain) {
|
|
3619
|
+
if (!waitingForDrain) {
|
|
3620
|
+
waitingForDrain = true;
|
|
3621
|
+
stream.once("drain", onDrain);
|
|
3622
|
+
}
|
|
3623
|
+
return;
|
|
3624
|
+
}
|
|
3625
|
+
const next = pending.shift();
|
|
3626
|
+
if (next === void 0) return;
|
|
3627
|
+
pendingBytes -= next.bytes;
|
|
3628
|
+
let accepted;
|
|
3629
|
+
try {
|
|
3630
|
+
accepted = stream.write(next.line);
|
|
3631
|
+
} catch {
|
|
3632
|
+
stop();
|
|
3633
|
+
return;
|
|
3634
|
+
}
|
|
3635
|
+
if (!accepted) {
|
|
3636
|
+
waitingForDrain = true;
|
|
3637
|
+
stream.once("drain", onDrain);
|
|
3638
|
+
return;
|
|
3646
3639
|
}
|
|
3647
|
-
inspected += 1;
|
|
3648
|
-
if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
|
|
3649
3640
|
}
|
|
3650
|
-
|
|
3651
|
-
|
|
3652
|
-
|
|
3653
|
-
|
|
3654
|
-
|
|
3655
|
-
|
|
3656
|
-
|
|
3657
|
-
if (remaining.length === latest.eligible_batches.length) return;
|
|
3658
|
-
await this.writeState({ ...latest, eligible_batches: remaining });
|
|
3659
|
-
await removeFileIfPresent(this.batchPath(state, batchRef));
|
|
3660
|
-
});
|
|
3661
|
-
}
|
|
3662
|
-
async quarantine(state, reason) {
|
|
3663
|
-
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3664
|
-
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3665
|
-
const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
|
|
3666
|
-
await this.writeState(updated);
|
|
3667
|
-
return updated;
|
|
3668
|
-
});
|
|
3669
|
-
}
|
|
3670
|
-
async retireCursor(state, sourceSlot, cursor, gap) {
|
|
3671
|
-
return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
|
|
3672
|
-
}
|
|
3673
|
-
async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
|
|
3674
|
-
if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
|
|
3675
|
-
if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
|
|
3676
|
-
const queued = await this.publishTransitionBatch(state, batch);
|
|
3677
|
-
const pending = {
|
|
3678
|
-
source_slot: sourceSlot,
|
|
3679
|
-
before_cursor: beforeCursor,
|
|
3680
|
-
after_cursor: afterCursor,
|
|
3681
|
-
batch_ref: queued.batch_ref,
|
|
3682
|
-
batch_bytes: queued.batch_bytes,
|
|
3683
|
-
gap_delta: [...gapDelta, ...queued.overflow_gaps],
|
|
3684
|
-
clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
|
|
3685
|
-
};
|
|
3686
|
-
const prepared = { ...state, pending_transition: pending };
|
|
3687
|
-
await this.writeState(prepared);
|
|
3688
|
-
await this.afterPendingWrite?.();
|
|
3689
|
-
return await this.finishPendingTransition(prepared);
|
|
3690
|
-
}
|
|
3691
|
-
async publishTransitionBatch(state, batch) {
|
|
3692
|
-
if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
|
|
3693
|
-
const serialized = serializeBatch(batch);
|
|
3694
|
-
if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
|
|
3695
|
-
await this.writeImmutableBatch(state, batch, serialized);
|
|
3696
|
-
await this.afterBatchPublish?.();
|
|
3697
|
-
return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
|
|
3698
|
-
}
|
|
3699
|
-
async finishPendingTransition(state) {
|
|
3700
|
-
const pending = state.pending_transition;
|
|
3701
|
-
if (pending === void 0 || state.quarantined_reason !== void 0) return state;
|
|
3702
|
-
const current = state.cursors[pending.source_slot];
|
|
3703
|
-
if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
|
|
3704
|
-
const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
|
|
3705
|
-
await this.writeState(quarantined);
|
|
3706
|
-
return quarantined;
|
|
3707
|
-
}
|
|
3708
|
-
let cursors = state.cursors;
|
|
3709
|
-
if (!cursorMatches(current, pending.after_cursor)) {
|
|
3710
|
-
const next = { ...state.cursors };
|
|
3711
|
-
if (pending.after_cursor === null) delete next[pending.source_slot];
|
|
3712
|
-
else next[pending.source_slot] = pending.after_cursor;
|
|
3713
|
-
cursors = next;
|
|
3714
|
-
}
|
|
3715
|
-
const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
|
|
3716
|
-
const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
|
|
3717
|
-
const { pending_transition: _pendingTransition, ...settledState } = state;
|
|
3718
|
-
const updated = {
|
|
3719
|
-
...settledState,
|
|
3720
|
-
cursors,
|
|
3721
|
-
eligible_batches: eligible,
|
|
3722
|
-
coverage_gaps: gaps,
|
|
3723
|
-
coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
3724
|
-
};
|
|
3725
|
-
await this.writeState(updated);
|
|
3726
|
-
return updated;
|
|
3727
|
-
}
|
|
3728
|
-
async writeImmutableBatch(state, batch, bytes) {
|
|
3729
|
-
const path = this.batchPath(state, batch.batch_ref);
|
|
3730
|
-
await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
|
|
3731
|
-
const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
3732
|
-
if (existing !== null) {
|
|
3733
|
-
if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
|
|
3734
|
-
await syncExistingFile(path, this.platform);
|
|
3735
|
-
return;
|
|
3736
|
-
}
|
|
3737
|
-
if (this.platform === "win32") {
|
|
3738
|
-
await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
|
|
3739
|
-
return;
|
|
3740
|
-
}
|
|
3741
|
-
let handle;
|
|
3742
|
-
try {
|
|
3743
|
-
handle = await openNoFollow(path, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384, this.platform);
|
|
3744
|
-
await handle.writeFile(bytes);
|
|
3745
|
-
await handle.sync();
|
|
3746
|
-
await handle.close();
|
|
3747
|
-
handle = void 0;
|
|
3748
|
-
await syncDirectory(dirname4(path), this.platform);
|
|
3749
|
-
} catch (error) {
|
|
3750
|
-
await handle?.close().catch(() => void 0);
|
|
3751
|
-
if (errorCode2(error) === "EEXIST") {
|
|
3752
|
-
const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
3753
|
-
if (winner !== null && winner.equals(bytes)) {
|
|
3754
|
-
await syncExistingFile(path, this.platform);
|
|
3755
|
-
return;
|
|
3756
|
-
}
|
|
3757
|
-
throw new Error("Host usage facts batch reference conflicts with existing bytes.");
|
|
3641
|
+
if (droppedLines > 0) {
|
|
3642
|
+
const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
|
|
3643
|
+
`;
|
|
3644
|
+
droppedLines = 0;
|
|
3645
|
+
try {
|
|
3646
|
+
onDeliveryGap(line);
|
|
3647
|
+
} catch {
|
|
3758
3648
|
}
|
|
3759
|
-
|
|
3760
|
-
|
|
3761
|
-
|
|
3762
|
-
}
|
|
3763
|
-
async readBatch(state, batchRef) {
|
|
3764
|
-
const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
3765
|
-
if (bytes === null) throw new Error("Host usage facts batch object is missing.");
|
|
3766
|
-
let value;
|
|
3767
|
-
try {
|
|
3768
|
-
value = JSON.parse(bytes.toString("utf8"));
|
|
3769
|
-
} catch {
|
|
3770
|
-
throw new Error("Host usage facts batch object is malformed.");
|
|
3649
|
+
pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
|
|
3650
|
+
pendingBytes += Buffer.byteLength(line, "utf8");
|
|
3651
|
+
flush();
|
|
3771
3652
|
}
|
|
3772
|
-
validateCealHostUsageBatch(value);
|
|
3773
|
-
if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
|
|
3774
|
-
return value;
|
|
3775
|
-
}
|
|
3776
|
-
async writeState(state) {
|
|
3777
|
-
validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
|
|
3778
|
-
const bytes = Buffer.from(JSON.stringify(state), "utf8");
|
|
3779
|
-
if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
|
|
3780
|
-
await this.prepare();
|
|
3781
|
-
const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
|
|
3782
|
-
if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
|
|
3783
|
-
else await durableAtomicReplace(path, bytes);
|
|
3784
3653
|
}
|
|
3785
|
-
|
|
3786
|
-
|
|
3787
|
-
|
|
3788
|
-
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
3795
|
-
try {
|
|
3796
|
-
return await run();
|
|
3797
|
-
} finally {
|
|
3798
|
-
release?.();
|
|
3799
|
-
if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
|
|
3654
|
+
stream.on("close", onTerminal);
|
|
3655
|
+
stream.on("finish", onTerminal);
|
|
3656
|
+
stream.on("error", onError);
|
|
3657
|
+
return (line) => {
|
|
3658
|
+
if (closed) return;
|
|
3659
|
+
const bytes = Buffer.byteLength(line, "utf8");
|
|
3660
|
+
if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
|
|
3661
|
+
droppedLines += 1;
|
|
3662
|
+
scheduleFlush();
|
|
3663
|
+
return;
|
|
3800
3664
|
}
|
|
3801
|
-
|
|
3802
|
-
|
|
3803
|
-
|
|
3804
|
-
}
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
|
|
3808
|
-
|
|
3809
|
-
|
|
3810
|
-
|
|
3665
|
+
pending.push({ line, bytes });
|
|
3666
|
+
pendingBytes += bytes;
|
|
3667
|
+
scheduleFlush();
|
|
3668
|
+
};
|
|
3669
|
+
}
|
|
3670
|
+
|
|
3671
|
+
// host/invocation-authentication-client-command.ts
|
|
3672
|
+
var HOST_OWNED_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){0,7}$/u;
|
|
3673
|
+
function isHostOwnedFailureCode(value) {
|
|
3674
|
+
return typeof value === "string" && HOST_OWNED_CODE.test(value);
|
|
3675
|
+
}
|
|
3676
|
+
var DOCTOR_FLAGS = Object.freeze({
|
|
3677
|
+
"--expected-sha256": "expected_sha256",
|
|
3678
|
+
"--expected-source-commit": "expected_source_commit",
|
|
3679
|
+
"--expected-instance-ref": "expected_instance_ref"
|
|
3680
|
+
});
|
|
3681
|
+
|
|
3682
|
+
// host/service-log.ts
|
|
3683
|
+
var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
|
|
3684
|
+
var HOST_SERVICE_LOG_ARGUMENT = "--ceal-host-service-log";
|
|
3685
|
+
var HostServiceLogArgumentError = class extends Error {
|
|
3686
|
+
constructor() {
|
|
3687
|
+
super("The Host service log argument must occur once with an absolute normalized path.");
|
|
3688
|
+
this.name = "HostServiceLogArgumentError";
|
|
3811
3689
|
}
|
|
3812
3690
|
};
|
|
3813
|
-
function
|
|
3814
|
-
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
const
|
|
3819
|
-
|
|
3820
|
-
|
|
3691
|
+
function consumeHostServiceLogArgument(args, platform = process.platform) {
|
|
3692
|
+
const indexes = args.flatMap((value, index2) => value === HOST_SERVICE_LOG_ARGUMENT ? [index2] : []);
|
|
3693
|
+
if (indexes.length === 0) return { args: [...args] };
|
|
3694
|
+
const index = indexes[0];
|
|
3695
|
+
if (index === void 0) throw new HostServiceLogArgumentError();
|
|
3696
|
+
const path = args[index + 1];
|
|
3697
|
+
const pathApi = platform === "win32" ? win325 : posix4;
|
|
3698
|
+
if (indexes.length !== 1 || path === void 0 || !pathApi.isAbsolute(path) || pathApi.normalize(path) !== path) throw new HostServiceLogArgumentError();
|
|
3699
|
+
return { args: [...args.slice(0, index), ...args.slice(index + 2)], path };
|
|
3821
3700
|
}
|
|
3822
|
-
|
|
3823
|
-
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
|
|
3701
|
+
var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
|
|
3702
|
+
void persistHostServiceLogLine(line);
|
|
3703
|
+
});
|
|
3704
|
+
function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
|
|
3705
|
+
const details = diagnosticDetails(event, failure_kind, cause);
|
|
3706
|
+
const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
|
|
3707
|
+
`;
|
|
3708
|
+
try {
|
|
3709
|
+
(sink ?? defaultHostServiceDiagnosticSink)(line);
|
|
3710
|
+
} catch {
|
|
3711
|
+
}
|
|
3827
3712
|
}
|
|
3828
|
-
function
|
|
3829
|
-
|
|
3713
|
+
function diagnosticDetails(event, failureKind, cause) {
|
|
3714
|
+
if (event === "watcher_scan_failed") return {
|
|
3715
|
+
...failureKind === void 0 ? {} : { failure_kind: failureKind },
|
|
3716
|
+
...validDiagnosticCause(cause, event) ? { cause } : {}
|
|
3717
|
+
};
|
|
3718
|
+
return validDiagnosticCause(cause, event) ? { cause } : {};
|
|
3830
3719
|
}
|
|
3831
|
-
function
|
|
3832
|
-
|
|
3833
|
-
return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
|
|
3720
|
+
function validDiagnosticCause(cause, event) {
|
|
3721
|
+
return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
|
|
3834
3722
|
}
|
|
3835
|
-
function
|
|
3836
|
-
|
|
3837
|
-
const gaps = [...batch.coverage_gaps];
|
|
3838
|
-
if (count > 0) gaps.push({ reason: "outbox_capacity", source_file_ref: batch.source_ranges[0]?.source_file_ref ?? null, start_offset: batch.source_ranges[0]?.start_offset ?? null, end_offset: batch.source_ranges[0]?.end_offset ?? null, omitted_count: count });
|
|
3839
|
-
return gaps;
|
|
3723
|
+
function defaultHostServiceDiagnosticSink(line) {
|
|
3724
|
+
writeHostServiceLogLine(line);
|
|
3840
3725
|
}
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
|
|
3844
|
-
return
|
|
3726
|
+
var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
|
|
3727
|
+
var HOST_SERVICE_LOG_CHECK_INTERVAL_MS = 6e4;
|
|
3728
|
+
function hostServiceLogPreviousPath(path) {
|
|
3729
|
+
return `${path}.1`;
|
|
3845
3730
|
}
|
|
3846
|
-
function
|
|
3847
|
-
|
|
3848
|
-
|
|
3849
|
-
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
3853
|
-
return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
|
|
3854
|
-
}
|
|
3855
|
-
function coverageRanges(gaps) {
|
|
3856
|
-
const ranges = /* @__PURE__ */ new Map();
|
|
3857
|
-
for (const gap of gaps) {
|
|
3858
|
-
if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
|
|
3859
|
-
const current = ranges.get(gap.source_file_ref);
|
|
3860
|
-
if (current === void 0) ranges.set(gap.source_file_ref, { source_file_ref: gap.source_file_ref, start_offset: gap.start_offset, end_offset: gap.end_offset });
|
|
3861
|
-
else ranges.set(gap.source_file_ref, { ...current, start_offset: Math.min(current.start_offset, gap.start_offset), end_offset: Math.max(current.end_offset, gap.end_offset) });
|
|
3731
|
+
async function rotateHostServiceLog(path, maxBytes = HOST_SERVICE_LOG_MAX_BYTES) {
|
|
3732
|
+
let size;
|
|
3733
|
+
try {
|
|
3734
|
+
size = (await stat(path)).size;
|
|
3735
|
+
} catch (error) {
|
|
3736
|
+
if (isNotFound(error)) return false;
|
|
3737
|
+
throw error;
|
|
3862
3738
|
}
|
|
3863
|
-
|
|
3864
|
-
|
|
3865
|
-
|
|
3866
|
-
|
|
3867
|
-
return entry === void 0 ? null : entry;
|
|
3868
|
-
}
|
|
3869
|
-
function sameCursor(left, right) {
|
|
3870
|
-
return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
|
|
3871
|
-
}
|
|
3872
|
-
function cursorMatches(left, right) {
|
|
3873
|
-
return right === null ? left === void 0 : sameCursor(left, right);
|
|
3874
|
-
}
|
|
3875
|
-
function validateState(value, producer, hostSourceRef, hostSessionRef) {
|
|
3876
|
-
validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
|
|
3877
|
-
validateStateShape(value);
|
|
3878
|
-
validateStateLimits(value);
|
|
3879
|
-
validateStateContents(value);
|
|
3739
|
+
if (size <= maxBytes) return false;
|
|
3740
|
+
await copyFile(path, hostServiceLogPreviousPath(path));
|
|
3741
|
+
await truncate(path, 0);
|
|
3742
|
+
return true;
|
|
3880
3743
|
}
|
|
3881
|
-
function
|
|
3882
|
-
|
|
3744
|
+
function boundHostServiceLog(environment = process.env) {
|
|
3745
|
+
const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
|
|
3746
|
+
if (path === void 0 || !isAbsolute(path)) return () => void 0;
|
|
3747
|
+
let reported = false;
|
|
3748
|
+
const ready = ensureHostServiceLogDirectory(path);
|
|
3749
|
+
const check = () => {
|
|
3750
|
+
ready.then(() => rotateHostServiceLog(path)).catch((error) => {
|
|
3751
|
+
if (reported) return;
|
|
3752
|
+
reported = true;
|
|
3753
|
+
writeHostServiceLogLine(`[host-service-log] rotation_failed code=${errorCode2(error)}
|
|
3754
|
+
`);
|
|
3755
|
+
});
|
|
3756
|
+
};
|
|
3757
|
+
check();
|
|
3758
|
+
const timer = setInterval(check, HOST_SERVICE_LOG_CHECK_INTERVAL_MS);
|
|
3759
|
+
timer.unref();
|
|
3760
|
+
return () => clearInterval(timer);
|
|
3883
3761
|
}
|
|
3884
|
-
function
|
|
3885
|
-
|
|
3762
|
+
function writeHostServiceLogLine(line, environment = process.env) {
|
|
3763
|
+
void persistHostServiceLogLine(line, environment);
|
|
3764
|
+
defaultHostServiceLogDelivery(line);
|
|
3886
3765
|
}
|
|
3887
|
-
function
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
for (const gap of value.coverage_gaps) validateGap(gap);
|
|
3895
|
-
validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
|
|
3766
|
+
async function writeHostServiceCommandResult(schemaVersion, result, sink) {
|
|
3767
|
+
const line = `${JSON.stringify({ schema_version: schemaVersion, ...result })}
|
|
3768
|
+
`;
|
|
3769
|
+
const serviceLine = `${JSON.stringify({ schema_version: schemaVersion, ok: result.ok, ...!result.ok ? { code: isHostOwnedFailureCode(result.code) ? result.code : "host_failure_unclassified" } : {} })}
|
|
3770
|
+
`;
|
|
3771
|
+
await persistHostServiceLogLine(serviceLine);
|
|
3772
|
+
sink(line);
|
|
3896
3773
|
}
|
|
3897
|
-
function
|
|
3898
|
-
if (
|
|
3899
|
-
|
|
3774
|
+
async function persistHostServiceLogLine(line, environment = process.env) {
|
|
3775
|
+
if (process.platform !== "win32") return;
|
|
3776
|
+
const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
|
|
3777
|
+
if (path === void 0 || !win325.isAbsolute(path) || win325.normalize(path) !== path) return;
|
|
3778
|
+
await appendHostServiceLogLine(path, line).catch(() => void 0);
|
|
3900
3779
|
}
|
|
3901
|
-
function
|
|
3902
|
-
if (!
|
|
3903
|
-
|
|
3780
|
+
async function appendHostServiceLogLine(path, line) {
|
|
3781
|
+
if (!isAbsolute(path)) return;
|
|
3782
|
+
await ensureHostServiceLogDirectory(path);
|
|
3783
|
+
await appendFile(path, line);
|
|
3904
3784
|
}
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3785
|
+
var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
|
|
3786
|
+
var hostServiceLogDirectories = /* @__PURE__ */ new Map();
|
|
3787
|
+
function ensureHostServiceLogDirectory(path) {
|
|
3788
|
+
const directory = dirname4(path);
|
|
3789
|
+
const existing = hostServiceLogDirectories.get(directory);
|
|
3790
|
+
if (existing !== void 0) return existing;
|
|
3791
|
+
const pending = mkdir2(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
|
|
3792
|
+
hostServiceLogDirectories.delete(directory);
|
|
3793
|
+
throw error;
|
|
3794
|
+
});
|
|
3795
|
+
hostServiceLogDirectories.set(directory, pending);
|
|
3796
|
+
return pending;
|
|
3910
3797
|
}
|
|
3911
|
-
function
|
|
3912
|
-
|
|
3913
|
-
validateCursorIdentity(value);
|
|
3914
|
-
validateCursorOffsets(value);
|
|
3915
|
-
validateCursorContext(value);
|
|
3916
|
-
if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
|
|
3917
|
-
if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
|
|
3798
|
+
function isNotFound(error) {
|
|
3799
|
+
return errorCode2(error) === "ENOENT";
|
|
3918
3800
|
}
|
|
3919
|
-
function
|
|
3920
|
-
|
|
3801
|
+
function errorCode2(error) {
|
|
3802
|
+
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unknown";
|
|
3921
3803
|
}
|
|
3922
|
-
|
|
3923
|
-
|
|
3804
|
+
|
|
3805
|
+
// host/relay/src/host-producer-core.ts
|
|
3806
|
+
var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
|
|
3807
|
+
function isHostTranscriptCursorReason(value) {
|
|
3808
|
+
return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
|
|
3924
3809
|
}
|
|
3925
|
-
|
|
3926
|
-
|
|
3810
|
+
var TRANSCRIPT_MISSING_REASON = "transcript_missing";
|
|
3811
|
+
var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
|
|
3812
|
+
var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
|
|
3813
|
+
function mergeHostInvocationHumanMessageWindow(existing, chronological) {
|
|
3814
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3815
|
+
const newestFirst = [];
|
|
3816
|
+
for (const message of [...chronological].reverse()) {
|
|
3817
|
+
if (seen.has(message.host_input_ref)) continue;
|
|
3818
|
+
seen.add(message.host_input_ref);
|
|
3819
|
+
newestFirst.push(message);
|
|
3820
|
+
}
|
|
3821
|
+
for (const message of existing?.messages ?? []) {
|
|
3822
|
+
if (seen.has(message.host_input_ref)) continue;
|
|
3823
|
+
seen.add(message.host_input_ref);
|
|
3824
|
+
newestFirst.push(message);
|
|
3825
|
+
}
|
|
3826
|
+
const currentTurn = newestFirst[0]?.host_turn_ref;
|
|
3827
|
+
const currentTurnFirst = currentTurn === void 0 ? newestFirst : newestFirst.filter((message) => message.host_turn_ref === currentTurn);
|
|
3828
|
+
return boundCealHostInvocationHumanMessageWindow(currentTurnFirst, existing?.truncated ?? false);
|
|
3927
3829
|
}
|
|
3928
|
-
function
|
|
3929
|
-
|
|
3830
|
+
function transcriptScanFailureKind(error, adapterFailureKind) {
|
|
3831
|
+
if (transcriptErrorCode(error) === "ELOOP") return "symlink";
|
|
3832
|
+
const adapter = adapterFailureKind(error);
|
|
3833
|
+
if (adapter !== void 0) return adapter;
|
|
3834
|
+
const code = transcriptErrorCode(error);
|
|
3835
|
+
if (code === "EFBIG") return "size_budget";
|
|
3836
|
+
if (code !== null && TRANSCRIPT_SCAN_READ_ERROR_ERRNOS.includes(code)) return "read_error";
|
|
3837
|
+
return "other";
|
|
3930
3838
|
}
|
|
3931
|
-
function
|
|
3932
|
-
|
|
3933
|
-
if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
|
|
3839
|
+
function transcriptErrorCode(error) {
|
|
3840
|
+
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
|
|
3934
3841
|
}
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3842
|
+
var HOST_TRANSCRIPT_READ_CHUNK_BYTES = 256 * 1024;
|
|
3843
|
+
async function readTranscriptCompleteChunk(handle, offset, size) {
|
|
3844
|
+
const available = Math.max(0, size - offset);
|
|
3845
|
+
if (available === 0) return "empty";
|
|
3846
|
+
const chunks = [];
|
|
3847
|
+
let position = offset;
|
|
3848
|
+
let total = 0;
|
|
3849
|
+
let lastNewline = -1;
|
|
3850
|
+
while (position < size) {
|
|
3851
|
+
const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
|
|
3852
|
+
const read2 = await handle.read(buffer, 0, buffer.length, position);
|
|
3853
|
+
if (read2.bytesRead === 0) break;
|
|
3854
|
+
const chunk = buffer.subarray(0, read2.bytesRead);
|
|
3855
|
+
chunks.push(chunk);
|
|
3856
|
+
const newline = chunk.lastIndexOf(10);
|
|
3857
|
+
if (newline >= 0) lastNewline = total + newline;
|
|
3858
|
+
total += chunk.length;
|
|
3859
|
+
position += chunk.length;
|
|
3860
|
+
if (lastNewline >= 0) break;
|
|
3861
|
+
}
|
|
3862
|
+
if (lastNewline < 0) return "partial";
|
|
3863
|
+
return Buffer.concat(chunks, total).subarray(0, lastNewline + 1);
|
|
3941
3864
|
}
|
|
3942
|
-
function
|
|
3943
|
-
|
|
3944
|
-
|
|
3945
|
-
if (
|
|
3865
|
+
async function readTranscriptAnchor(handle, offset, anchorBytes) {
|
|
3866
|
+
const start = Math.max(0, offset - anchorBytes);
|
|
3867
|
+
const anchor = Buffer.alloc(offset - start);
|
|
3868
|
+
if (anchor.length > 0) await handle.read(anchor, 0, anchor.length, start);
|
|
3869
|
+
return { start, sha256: transcriptSha256(anchor) };
|
|
3946
3870
|
}
|
|
3947
|
-
function
|
|
3948
|
-
|
|
3871
|
+
async function transcriptAnchorMatches(handle, cursor) {
|
|
3872
|
+
const buffer = Buffer.alloc(cursor.offset - cursor.anchor_start);
|
|
3873
|
+
if (buffer.length > 0) await handle.read(buffer, 0, buffer.length, cursor.anchor_start);
|
|
3874
|
+
return transcriptSha256(buffer) === cursor.anchor_sha256;
|
|
3949
3875
|
}
|
|
3950
|
-
function
|
|
3951
|
-
if (
|
|
3876
|
+
function transcriptCursorIdentityReason(cursor, transcriptPath, device, inode) {
|
|
3877
|
+
if (cursor.device !== device || cursor.inode !== inode || cursor.transcript_path !== transcriptPath) return "transcript_replaced";
|
|
3878
|
+
return null;
|
|
3952
3879
|
}
|
|
3953
|
-
function
|
|
3954
|
-
if (
|
|
3880
|
+
async function transcriptCursorBoundsReason(handle, cursor, size) {
|
|
3881
|
+
if (size < cursor.offset) return "transcript_truncated";
|
|
3882
|
+
if (cursor.offset > 0 && !await transcriptAnchorMatches(handle, cursor)) return "transcript_rewritten";
|
|
3883
|
+
return null;
|
|
3955
3884
|
}
|
|
3956
|
-
function
|
|
3885
|
+
async function statObservedPathSignature(path) {
|
|
3957
3886
|
try {
|
|
3958
|
-
|
|
3887
|
+
const info = await lstat4(path, { bigint: true });
|
|
3888
|
+
if (info.isSymbolicLink() || !info.isFile() && !info.isDirectory()) return null;
|
|
3889
|
+
return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
3959
3890
|
} catch {
|
|
3960
|
-
|
|
3891
|
+
return null;
|
|
3961
3892
|
}
|
|
3962
3893
|
}
|
|
3963
|
-
function
|
|
3964
|
-
|
|
3894
|
+
function transcriptSha256(value) {
|
|
3895
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
3965
3896
|
}
|
|
3966
|
-
|
|
3967
|
-
|
|
3968
|
-
if (bytes === null) return null;
|
|
3969
|
-
try {
|
|
3970
|
-
return JSON.parse(bytes.toString("utf8"));
|
|
3971
|
-
} catch {
|
|
3972
|
-
throw new Error("Host usage facts state JSON is malformed.");
|
|
3973
|
-
}
|
|
3897
|
+
function transcriptObjectSha256(value) {
|
|
3898
|
+
return createHash5("sha256").update(JSON.stringify(value), "utf8").digest("hex");
|
|
3974
3899
|
}
|
|
3975
|
-
|
|
3976
|
-
|
|
3977
|
-
try {
|
|
3978
|
-
return await readPrivateFileWithSecurefs(path, maxBytes, custody);
|
|
3979
|
-
} catch (error) {
|
|
3980
|
-
if (errorCode2(error) === "ENOENT") return null;
|
|
3981
|
-
throw error;
|
|
3982
|
-
}
|
|
3983
|
-
}
|
|
3984
|
-
let handle;
|
|
3985
|
-
try {
|
|
3986
|
-
handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
|
|
3987
|
-
const stats = await handle.stat();
|
|
3988
|
-
if (!stats.isFile() || !isSelfOwned(stats.uid, platform, handle) || !isPrivateFileMode(stats.mode, platform, handle) || stats.size > maxBytes) throw new Error("Host usage facts file custody or size is invalid.");
|
|
3989
|
-
return await handle.readFile();
|
|
3990
|
-
} catch (error) {
|
|
3991
|
-
if (errorCode2(error) === "ENOENT") return null;
|
|
3992
|
-
throw error;
|
|
3993
|
-
} finally {
|
|
3994
|
-
await handle?.close();
|
|
3995
|
-
}
|
|
3900
|
+
function isTranscriptRecord(value) {
|
|
3901
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3996
3902
|
}
|
|
3997
|
-
|
|
3998
|
-
|
|
3999
|
-
await ensurePrivateDirectoryWithSecurefs(path, custody);
|
|
4000
|
-
return;
|
|
4001
|
-
}
|
|
4002
|
-
await mkdir2(path, { recursive: true, mode: 448 });
|
|
4003
|
-
if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
|
|
3903
|
+
function isMissingTranscriptError(error) {
|
|
3904
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
4004
3905
|
}
|
|
4005
|
-
|
|
4006
|
-
const
|
|
4007
|
-
|
|
4008
|
-
|
|
4009
|
-
} finally {
|
|
4010
|
-
await handle.close();
|
|
4011
|
-
}
|
|
4012
|
-
await syncDirectory(dirname4(path), platform);
|
|
3906
|
+
function transcriptTimestamp(now, fail) {
|
|
3907
|
+
const value = now();
|
|
3908
|
+
if (!Number.isFinite(value.getTime())) throw fail();
|
|
3909
|
+
return value.toISOString();
|
|
4013
3910
|
}
|
|
4014
|
-
|
|
4015
|
-
|
|
4016
|
-
|
|
4017
|
-
|
|
4018
|
-
|
|
4019
|
-
|
|
4020
|
-
|
|
3911
|
+
function transcriptExpiration(now, retentionMs, fail) {
|
|
3912
|
+
return new Date(Date.parse(transcriptTimestamp(now, fail)) + retentionMs).toISOString();
|
|
3913
|
+
}
|
|
3914
|
+
function createTranscriptWatcherBase(options, owner) {
|
|
3915
|
+
if (typeof options.outbox_dir !== "string" || options.outbox_dir.length === 0) throw owner.invalid_outbox();
|
|
3916
|
+
return {
|
|
3917
|
+
outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
|
|
3918
|
+
now: options.now ?? (() => /* @__PURE__ */ new Date()),
|
|
3919
|
+
log: options.log ?? ((line) => {
|
|
3920
|
+
writeHostServiceLogLine(`${line}
|
|
3921
|
+
`);
|
|
3922
|
+
}),
|
|
3923
|
+
producerInstallationRef: options.producer_installation_ref
|
|
3924
|
+
};
|
|
3925
|
+
}
|
|
3926
|
+
async function scanTranscriptRegistrations(registrations, scanOne, totalRegistrations, signal) {
|
|
3927
|
+
let records = 0;
|
|
3928
|
+
let enqueued = 0;
|
|
3929
|
+
let quarantined = 0;
|
|
3930
|
+
let scanned = 0;
|
|
3931
|
+
for (const registration of registrations) {
|
|
3932
|
+
if (signal?.aborted) break;
|
|
3933
|
+
scanned += 1;
|
|
3934
|
+
const result = await scanOne(registration);
|
|
3935
|
+
records += result.records;
|
|
3936
|
+
enqueued += result.enqueued;
|
|
3937
|
+
if (result.quarantined) quarantined += 1;
|
|
4021
3938
|
}
|
|
3939
|
+
return { registrations: totalRegistrations ?? scanned, records, enqueued, quarantined };
|
|
4022
3940
|
}
|
|
4023
|
-
|
|
3941
|
+
var HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS = 1000000000n;
|
|
3942
|
+
var HostRegistrationInventory = class {
|
|
3943
|
+
signature;
|
|
3944
|
+
registrations;
|
|
3945
|
+
nowNs;
|
|
3946
|
+
observeDirectory;
|
|
3947
|
+
constructor(options = {}) {
|
|
3948
|
+
this.nowNs = options.nowNs ?? (() => BigInt(Date.now()) * 1000000n);
|
|
3949
|
+
this.observeDirectory = options.observeDirectory ?? hostRegistrationDirectorySignature;
|
|
3950
|
+
}
|
|
3951
|
+
async read(directory, load) {
|
|
3952
|
+
const observation = await this.observeDirectory(directory);
|
|
3953
|
+
const nowNs = this.nowNs();
|
|
3954
|
+
const racy = nowNs - observation.mtimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS || nowNs - observation.ctimeNs <= HOST_REGISTRATION_DIRECTORY_RACY_WINDOW_NS;
|
|
3955
|
+
if (this.registrations !== void 0 && this.signature === observation.signature && !racy) return this.registrations;
|
|
3956
|
+
const registrations = await load();
|
|
3957
|
+
this.signature = observation.signature;
|
|
3958
|
+
this.registrations = registrations;
|
|
3959
|
+
return registrations;
|
|
3960
|
+
}
|
|
3961
|
+
};
|
|
3962
|
+
async function hostRegistrationDirectorySignature(directory) {
|
|
4024
3963
|
try {
|
|
4025
|
-
await
|
|
3964
|
+
const info = await stat2(directory, { bigint: true });
|
|
3965
|
+
return {
|
|
3966
|
+
signature: `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`,
|
|
3967
|
+
mtimeNs: info.mtimeNs,
|
|
3968
|
+
ctimeNs: info.ctimeNs
|
|
3969
|
+
};
|
|
4026
3970
|
} catch (error) {
|
|
4027
|
-
if (
|
|
3971
|
+
if (isMissingTranscriptError(error)) return { signature: "missing", mtimeNs: 0n, ctimeNs: 0n };
|
|
3972
|
+
throw error;
|
|
4028
3973
|
}
|
|
4029
3974
|
}
|
|
4030
|
-
function
|
|
4031
|
-
return
|
|
4032
|
-
}
|
|
4033
|
-
function isRecord3(value) {
|
|
4034
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4035
|
-
}
|
|
4036
|
-
function safeInteger2(value) {
|
|
4037
|
-
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
4038
|
-
}
|
|
4039
|
-
function validTimestamp(value) {
|
|
4040
|
-
return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
4041
|
-
}
|
|
4042
|
-
function errorCode2(error) {
|
|
4043
|
-
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
4044
|
-
}
|
|
4045
|
-
function sha2562(value) {
|
|
4046
|
-
return createHash5("sha256").update(value, "utf8").digest("hex");
|
|
3975
|
+
function formatRetiredTranscriptLog(producerLabel, transcriptPath) {
|
|
3976
|
+
return `${producerLabel} retired a transcript registration: transcript_path=${JSON.stringify(transcriptPath)}, reason=${TRANSCRIPT_MISSING_REASON}.`;
|
|
4047
3977
|
}
|
|
4048
|
-
|
|
4049
|
-
|
|
4050
|
-
|
|
4051
|
-
|
|
4052
|
-
|
|
4053
|
-
|
|
4054
|
-
|
|
4055
|
-
|
|
4056
|
-
|
|
4057
|
-
|
|
4058
|
-
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
|
|
4062
|
-
|
|
4063
|
-
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
|
|
4067
|
-
|
|
4068
|
-
closed = true;
|
|
4069
|
-
pending.length = 0;
|
|
4070
|
-
pendingBytes = 0;
|
|
4071
|
-
stream.off("drain", onDrain);
|
|
4072
|
-
stream.off("close", onTerminal);
|
|
4073
|
-
stream.off("finish", onTerminal);
|
|
4074
|
-
stream.off("error", onError);
|
|
4075
|
-
}
|
|
4076
|
-
function onTerminal() {
|
|
4077
|
-
stop();
|
|
4078
|
-
}
|
|
4079
|
-
function onError() {
|
|
4080
|
-
stop();
|
|
3978
|
+
var HOST_TRANSCRIPT_RECONCILIATION_BATCH = 100;
|
|
3979
|
+
var HostTranscriptWatcher = class {
|
|
3980
|
+
outboxRetentionMs;
|
|
3981
|
+
now;
|
|
3982
|
+
log;
|
|
3983
|
+
producerInstallationRef;
|
|
3984
|
+
clockFailure;
|
|
3985
|
+
transcriptObservations = /* @__PURE__ */ new Map();
|
|
3986
|
+
registrationSnapshot;
|
|
3987
|
+
// Advisory scheduling only: listRegistrations remains the registration authority.
|
|
3988
|
+
hotRegistrations = /* @__PURE__ */ new Set();
|
|
3989
|
+
reconciliation;
|
|
3990
|
+
reconciliationRemaining = 0;
|
|
3991
|
+
constructor(options, owner) {
|
|
3992
|
+
const base = createTranscriptWatcherBase(options, owner);
|
|
3993
|
+
this.outboxRetentionMs = base.outboxRetentionMs;
|
|
3994
|
+
this.now = base.now;
|
|
3995
|
+
this.log = base.log;
|
|
3996
|
+
this.producerInstallationRef = base.producerInstallationRef;
|
|
3997
|
+
this.clockFailure = owner.clock_failure;
|
|
4081
3998
|
}
|
|
4082
|
-
|
|
4083
|
-
|
|
4084
|
-
|
|
3999
|
+
async scanOnce(signal) {
|
|
4000
|
+
if (signal?.aborted) return { registrations: this.registrationSnapshot?.length ?? 0, records: 0, enqueued: 0, quarantined: 0 };
|
|
4001
|
+
const registrations = await this.listRegistrations();
|
|
4002
|
+
this.reconcileSnapshot(registrations);
|
|
4003
|
+
return scanTranscriptRegistrations(this.scanCandidates(), (observation) => this.observeRegistration(observation, signal), registrations.length, signal);
|
|
4004
|
+
}
|
|
4005
|
+
async observeRegistration(observation, signal) {
|
|
4006
|
+
const registration = observation.registration;
|
|
4007
|
+
const signature = await this.scanFingerprint(registration);
|
|
4008
|
+
if (signal?.aborted) return { records: 0, enqueued: 0, quarantined: false };
|
|
4009
|
+
this.hotRegistrations.delete(observation);
|
|
4010
|
+
if (signature !== null && observation.signature === signature) return { records: 0, enqueued: 0, quarantined: false };
|
|
4011
|
+
this.hotRegistrations.add(observation);
|
|
4012
|
+
const result = await this.scanRegistration(registration);
|
|
4013
|
+
if (result.quarantined || result.retry === true) observation.signature = void 0;
|
|
4014
|
+
else {
|
|
4015
|
+
observation.signature = signature ?? void 0;
|
|
4016
|
+
if (result.records === 0) this.hotRegistrations.delete(observation);
|
|
4017
|
+
}
|
|
4018
|
+
return result;
|
|
4085
4019
|
}
|
|
4086
|
-
|
|
4087
|
-
|
|
4088
|
-
|
|
4089
|
-
|
|
4090
|
-
|
|
4091
|
-
try {
|
|
4092
|
-
schedule(() => {
|
|
4093
|
-
if (scheduling) {
|
|
4094
|
-
invokedSynchronously = true;
|
|
4095
|
-
return;
|
|
4096
|
-
}
|
|
4097
|
-
flushScheduled = false;
|
|
4098
|
-
flush();
|
|
4099
|
-
});
|
|
4100
|
-
} catch {
|
|
4101
|
-
flushScheduled = false;
|
|
4102
|
-
stop();
|
|
4103
|
-
return;
|
|
4020
|
+
*scanCandidates() {
|
|
4021
|
+
const hotSlice = [];
|
|
4022
|
+
for (const observation of this.hotRegistrations) {
|
|
4023
|
+
hotSlice.push(observation);
|
|
4024
|
+
if (hotSlice.length === HOST_TRANSCRIPT_RECONCILIATION_BATCH) break;
|
|
4104
4025
|
}
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
|
|
4108
|
-
|
|
4026
|
+
const observed = /* @__PURE__ */ new Set();
|
|
4027
|
+
for (let count = 0; count < Math.min(this.transcriptObservations.size, HOST_TRANSCRIPT_RECONCILIATION_BATCH); count += 1) {
|
|
4028
|
+
const observation = this.nextReconciliation();
|
|
4029
|
+
if (observation === void 0) break;
|
|
4030
|
+
observed.add(observation);
|
|
4031
|
+
yield observation;
|
|
4109
4032
|
}
|
|
4033
|
+
for (const observation of hotSlice) if (!observed.has(observation)) yield observation;
|
|
4110
4034
|
}
|
|
4111
|
-
|
|
4112
|
-
if (
|
|
4113
|
-
|
|
4114
|
-
|
|
4115
|
-
return;
|
|
4035
|
+
nextReconciliation() {
|
|
4036
|
+
if (this.reconciliationRemaining === 0 || this.reconciliation === void 0) {
|
|
4037
|
+
this.reconciliation = this.transcriptObservations.values();
|
|
4038
|
+
this.reconciliationRemaining = this.transcriptObservations.size;
|
|
4116
4039
|
}
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
|
|
4040
|
+
let next = this.reconciliation.next();
|
|
4041
|
+
if (next.done) {
|
|
4042
|
+
this.reconciliation = this.transcriptObservations.values();
|
|
4043
|
+
this.reconciliationRemaining = this.transcriptObservations.size;
|
|
4044
|
+
next = this.reconciliation.next();
|
|
4045
|
+
}
|
|
4046
|
+
this.reconciliationRemaining -= 1;
|
|
4047
|
+
return next.value;
|
|
4048
|
+
}
|
|
4049
|
+
reconcileSnapshot(registrations) {
|
|
4050
|
+
if (this.registrationSnapshot === registrations) return;
|
|
4051
|
+
const retained = /* @__PURE__ */ new Set();
|
|
4052
|
+
const hot = /* @__PURE__ */ new Set();
|
|
4053
|
+
for (const registration of registrations) {
|
|
4054
|
+
const key = this.registrationKey(registration);
|
|
4055
|
+
retained.add(key);
|
|
4056
|
+
let observation = this.transcriptObservations.get(key);
|
|
4057
|
+
if (observation === void 0) {
|
|
4058
|
+
observation = { registration, signature: void 0 };
|
|
4059
|
+
this.transcriptObservations.set(key, observation);
|
|
4060
|
+
hot.add(observation);
|
|
4061
|
+
} else {
|
|
4062
|
+
if (!isDeepStrictEqual(observation.registration, registration)) {
|
|
4063
|
+
observation.signature = void 0;
|
|
4064
|
+
hot.add(observation);
|
|
4122
4065
|
}
|
|
4123
|
-
|
|
4124
|
-
}
|
|
4125
|
-
const next = pending.shift();
|
|
4126
|
-
if (next === void 0) return;
|
|
4127
|
-
pendingBytes -= next.bytes;
|
|
4128
|
-
let accepted;
|
|
4129
|
-
try {
|
|
4130
|
-
accepted = stream.write(next.line);
|
|
4131
|
-
} catch {
|
|
4132
|
-
stop();
|
|
4133
|
-
return;
|
|
4134
|
-
}
|
|
4135
|
-
if (!accepted) {
|
|
4136
|
-
waitingForDrain = true;
|
|
4137
|
-
stream.once("drain", onDrain);
|
|
4138
|
-
return;
|
|
4066
|
+
observation.registration = registration;
|
|
4139
4067
|
}
|
|
4140
4068
|
}
|
|
4141
|
-
|
|
4142
|
-
|
|
4143
|
-
|
|
4144
|
-
|
|
4145
|
-
try {
|
|
4146
|
-
onDeliveryGap(line);
|
|
4147
|
-
} catch {
|
|
4069
|
+
for (const [key, observation] of this.transcriptObservations) {
|
|
4070
|
+
if (!retained.has(key)) {
|
|
4071
|
+
this.transcriptObservations.delete(key);
|
|
4072
|
+
this.hotRegistrations.delete(observation);
|
|
4148
4073
|
}
|
|
4149
|
-
pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
|
|
4150
|
-
pendingBytes += Buffer.byteLength(line, "utf8");
|
|
4151
|
-
flush();
|
|
4152
4074
|
}
|
|
4075
|
+
for (const observation of this.hotRegistrations) hot.add(observation);
|
|
4076
|
+
this.hotRegistrations = hot;
|
|
4077
|
+
this.registrationSnapshot = registrations;
|
|
4153
4078
|
}
|
|
4154
|
-
|
|
4155
|
-
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
|
|
4161
|
-
|
|
4162
|
-
|
|
4163
|
-
return;
|
|
4079
|
+
async scanFingerprint(registration) {
|
|
4080
|
+
return this.transcriptSignature(registration);
|
|
4081
|
+
}
|
|
4082
|
+
async transcriptSignature(registration) {
|
|
4083
|
+
try {
|
|
4084
|
+
const info = await lstat4(this.transcriptPathOf(registration), { bigint: true });
|
|
4085
|
+
if (!info.isFile() || info.isSymbolicLink()) return null;
|
|
4086
|
+
return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${info.mode}:${info.uid}`;
|
|
4087
|
+
} catch {
|
|
4088
|
+
return null;
|
|
4164
4089
|
}
|
|
4165
|
-
pending.push({ line, bytes });
|
|
4166
|
-
pendingBytes += bytes;
|
|
4167
|
-
scheduleFlush();
|
|
4168
|
-
};
|
|
4169
|
-
}
|
|
4170
|
-
|
|
4171
|
-
// host/invocation-authentication-client-command.ts
|
|
4172
|
-
var HOST_OWNED_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){0,7}$/u;
|
|
4173
|
-
function isHostOwnedFailureCode(value) {
|
|
4174
|
-
return typeof value === "string" && HOST_OWNED_CODE.test(value);
|
|
4175
|
-
}
|
|
4176
|
-
var DOCTOR_FLAGS = Object.freeze({
|
|
4177
|
-
"--expected-sha256": "expected_sha256",
|
|
4178
|
-
"--expected-source-commit": "expected_source_commit",
|
|
4179
|
-
"--expected-instance-ref": "expected_instance_ref"
|
|
4180
|
-
});
|
|
4181
|
-
|
|
4182
|
-
// host/service-log.ts
|
|
4183
|
-
var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
|
|
4184
|
-
var HOST_SERVICE_LOG_ARGUMENT = "--ceal-host-service-log";
|
|
4185
|
-
var HostServiceLogArgumentError = class extends Error {
|
|
4186
|
-
constructor() {
|
|
4187
|
-
super("The Host service log argument must occur once with an absolute normalized path.");
|
|
4188
|
-
this.name = "HostServiceLogArgumentError";
|
|
4189
4090
|
}
|
|
4190
|
-
|
|
4191
|
-
|
|
4192
|
-
|
|
4193
|
-
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
|
|
4197
|
-
|
|
4198
|
-
|
|
4199
|
-
|
|
4200
|
-
}
|
|
4201
|
-
var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
|
|
4202
|
-
void persistHostServiceLogLine(line);
|
|
4203
|
-
});
|
|
4204
|
-
function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
|
|
4205
|
-
const details = diagnosticDetails(event, failure_kind, cause);
|
|
4206
|
-
const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
|
|
4207
|
-
`;
|
|
4208
|
-
try {
|
|
4209
|
-
(sink ?? defaultHostServiceDiagnosticSink)(line);
|
|
4210
|
-
} catch {
|
|
4091
|
+
async scanRegistration(registration) {
|
|
4092
|
+
return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
|
|
4093
|
+
missing: async () => {
|
|
4094
|
+
try {
|
|
4095
|
+
return await this.retireMissing(registration);
|
|
4096
|
+
} catch (error) {
|
|
4097
|
+
return this.scanFailed(void 0, registration, error);
|
|
4098
|
+
}
|
|
4099
|
+
},
|
|
4100
|
+
failed: (handle, error) => this.scanFailed(handle, registration, error)
|
|
4101
|
+
});
|
|
4211
4102
|
}
|
|
4212
|
-
|
|
4213
|
-
|
|
4214
|
-
|
|
4215
|
-
|
|
4216
|
-
|
|
4217
|
-
|
|
4218
|
-
|
|
4219
|
-
|
|
4220
|
-
|
|
4221
|
-
|
|
4222
|
-
}
|
|
4223
|
-
|
|
4224
|
-
|
|
4225
|
-
|
|
4226
|
-
|
|
4227
|
-
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
async
|
|
4232
|
-
|
|
4103
|
+
async openTranscript(registration, scan, handlers) {
|
|
4104
|
+
let handle;
|
|
4105
|
+
try {
|
|
4106
|
+
handle = await openNoFollow(this.transcriptPathOf(registration));
|
|
4107
|
+
return await scan(handle);
|
|
4108
|
+
} catch (error) {
|
|
4109
|
+
if (handle === void 0 && isMissingTranscriptError(error)) return handlers.missing();
|
|
4110
|
+
return handlers.failed(handle, error);
|
|
4111
|
+
} finally {
|
|
4112
|
+
await handle?.close();
|
|
4113
|
+
}
|
|
4114
|
+
}
|
|
4115
|
+
/**
|
|
4116
|
+
* A transcript the Host deleted never comes back, so retrying its
|
|
4117
|
+
* registration once per reconcile interval is a failure with no end.
|
|
4118
|
+
* Retire it at the scan that finds it missing and say so once. Only
|
|
4119
|
+
* ENOENT means gone; a permission or busy failure is about this moment,
|
|
4120
|
+
* not about the file, and keeps the registration for the next scan.
|
|
4121
|
+
*/
|
|
4122
|
+
async retireMissingTranscript(transcriptPath, producerLabel, retire) {
|
|
4123
|
+
await retire();
|
|
4124
|
+
this.log(formatRetiredTranscriptLog(producerLabel, transcriptPath));
|
|
4125
|
+
return { records: 0, enqueued: 0, quarantined: false };
|
|
4126
|
+
}
|
|
4127
|
+
stamp() {
|
|
4128
|
+
return transcriptTimestamp(this.now, this.clockFailure);
|
|
4129
|
+
}
|
|
4130
|
+
expire(retentionMs) {
|
|
4131
|
+
return transcriptExpiration(this.now, retentionMs, this.clockFailure);
|
|
4132
|
+
}
|
|
4133
|
+
sha(value) {
|
|
4134
|
+
return transcriptSha256(value);
|
|
4135
|
+
}
|
|
4136
|
+
objectSha(value) {
|
|
4137
|
+
return transcriptObjectSha256(value);
|
|
4138
|
+
}
|
|
4139
|
+
isRecord(value) {
|
|
4140
|
+
return isTranscriptRecord(value);
|
|
4141
|
+
}
|
|
4142
|
+
readChunk(handle, offset, size) {
|
|
4143
|
+
return readTranscriptCompleteChunk(handle, offset, size);
|
|
4144
|
+
}
|
|
4145
|
+
readAnchor(handle, offset, anchorBytes) {
|
|
4146
|
+
return readTranscriptAnchor(handle, offset, anchorBytes);
|
|
4147
|
+
}
|
|
4148
|
+
cursorIdentityReason(cursor, transcriptPath, device, inode) {
|
|
4149
|
+
return transcriptCursorIdentityReason(cursor, transcriptPath, device, inode);
|
|
4150
|
+
}
|
|
4151
|
+
cursorBoundsReason(handle, cursor, size) {
|
|
4152
|
+
return transcriptCursorBoundsReason(handle, cursor, size);
|
|
4153
|
+
}
|
|
4154
|
+
};
|
|
4155
|
+
async function listHostOutboxDirectoryNames(directory) {
|
|
4233
4156
|
try {
|
|
4234
|
-
|
|
4157
|
+
return await readdir(directory);
|
|
4235
4158
|
} catch (error) {
|
|
4236
|
-
if (
|
|
4159
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
|
|
4237
4160
|
throw error;
|
|
4238
4161
|
}
|
|
4239
|
-
if (size <= maxBytes) return false;
|
|
4240
|
-
await copyFile(path, hostServiceLogPreviousPath(path));
|
|
4241
|
-
await truncate(path, 0);
|
|
4242
|
-
return true;
|
|
4243
|
-
}
|
|
4244
|
-
function boundHostServiceLog(environment = process.env) {
|
|
4245
|
-
const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
|
|
4246
|
-
if (path === void 0 || !isAbsolute(path)) return () => void 0;
|
|
4247
|
-
let reported = false;
|
|
4248
|
-
const ready = ensureHostServiceLogDirectory(path);
|
|
4249
|
-
const check = () => {
|
|
4250
|
-
ready.then(() => rotateHostServiceLog(path)).catch((error) => {
|
|
4251
|
-
if (reported) return;
|
|
4252
|
-
reported = true;
|
|
4253
|
-
writeHostServiceLogLine(`[host-service-log] rotation_failed code=${errorCode3(error)}
|
|
4254
|
-
`);
|
|
4255
|
-
});
|
|
4256
|
-
};
|
|
4257
|
-
check();
|
|
4258
|
-
const timer = setInterval(check, HOST_SERVICE_LOG_CHECK_INTERVAL_MS);
|
|
4259
|
-
timer.unref();
|
|
4260
|
-
return () => clearInterval(timer);
|
|
4261
|
-
}
|
|
4262
|
-
function writeHostServiceLogLine(line, environment = process.env) {
|
|
4263
|
-
void persistHostServiceLogLine(line, environment);
|
|
4264
|
-
defaultHostServiceLogDelivery(line);
|
|
4265
|
-
}
|
|
4266
|
-
async function writeHostServiceCommandResult(schemaVersion, result, sink) {
|
|
4267
|
-
const line = `${JSON.stringify({ schema_version: schemaVersion, ...result })}
|
|
4268
|
-
`;
|
|
4269
|
-
const serviceLine = `${JSON.stringify({ schema_version: schemaVersion, ok: result.ok, ...!result.ok ? { code: isHostOwnedFailureCode(result.code) ? result.code : "host_failure_unclassified" } : {} })}
|
|
4270
|
-
`;
|
|
4271
|
-
await persistHostServiceLogLine(serviceLine);
|
|
4272
|
-
sink(line);
|
|
4273
|
-
}
|
|
4274
|
-
async function persistHostServiceLogLine(line, environment = process.env) {
|
|
4275
|
-
if (process.platform !== "win32") return;
|
|
4276
|
-
const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
|
|
4277
|
-
if (path === void 0 || !win325.isAbsolute(path) || win325.normalize(path) !== path) return;
|
|
4278
|
-
await appendHostServiceLogLine(path, line).catch(() => void 0);
|
|
4279
|
-
}
|
|
4280
|
-
async function appendHostServiceLogLine(path, line) {
|
|
4281
|
-
if (!isAbsolute(path)) return;
|
|
4282
|
-
await ensureHostServiceLogDirectory(path);
|
|
4283
|
-
await appendFile(path, line);
|
|
4284
|
-
}
|
|
4285
|
-
var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
|
|
4286
|
-
var hostServiceLogDirectories = /* @__PURE__ */ new Map();
|
|
4287
|
-
function ensureHostServiceLogDirectory(path) {
|
|
4288
|
-
const directory = dirname5(path);
|
|
4289
|
-
const existing = hostServiceLogDirectories.get(directory);
|
|
4290
|
-
if (existing !== void 0) return existing;
|
|
4291
|
-
const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
|
|
4292
|
-
hostServiceLogDirectories.delete(directory);
|
|
4293
|
-
throw error;
|
|
4294
|
-
});
|
|
4295
|
-
hostServiceLogDirectories.set(directory, pending);
|
|
4296
|
-
return pending;
|
|
4297
|
-
}
|
|
4298
|
-
function isNotFound(error) {
|
|
4299
|
-
return errorCode3(error) === "ENOENT";
|
|
4300
|
-
}
|
|
4301
|
-
function errorCode3(error) {
|
|
4302
|
-
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unknown";
|
|
4303
4162
|
}
|
|
4163
|
+
var HostProducerDrainCore = class {
|
|
4164
|
+
host;
|
|
4165
|
+
now;
|
|
4166
|
+
tail = Promise.resolve();
|
|
4167
|
+
constructor(host, runtime) {
|
|
4168
|
+
this.host = host;
|
|
4169
|
+
this.now = runtime.now ?? (() => /* @__PURE__ */ new Date());
|
|
4170
|
+
}
|
|
4171
|
+
drainOutbox() {
|
|
4172
|
+
const run = this.tail.then(() => this.drainLocked());
|
|
4173
|
+
this.tail = run.then(() => void 0, () => void 0);
|
|
4174
|
+
return run;
|
|
4175
|
+
}
|
|
4176
|
+
async drainLocked() {
|
|
4177
|
+
const read2 = await this.host.listEnvelopes();
|
|
4178
|
+
let removed = 0;
|
|
4179
|
+
let expired = 0;
|
|
4180
|
+
for (const envelope of read2.entries) {
|
|
4181
|
+
if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
|
|
4182
|
+
else removed += 1;
|
|
4183
|
+
await this.host.removeEnvelope(envelope);
|
|
4184
|
+
}
|
|
4185
|
+
return { removed, expired, malformed: read2.malformed };
|
|
4186
|
+
}
|
|
4187
|
+
};
|
|
4304
4188
|
|
|
4305
|
-
// host/relay/src/host-usage-facts-
|
|
4306
|
-
var
|
|
4307
|
-
|
|
4308
|
-
|
|
4189
|
+
// host/relay/src/host-usage-facts-store.ts
|
|
4190
|
+
var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
|
|
4191
|
+
var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
|
|
4192
|
+
var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
|
|
4193
|
+
var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
|
|
4194
|
+
var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
|
|
4195
|
+
var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
|
|
4196
|
+
var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
|
|
4197
|
+
var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
|
|
4198
|
+
var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
|
|
4199
|
+
var HostUsageFactsStore = class {
|
|
4200
|
+
root;
|
|
4201
|
+
sessions;
|
|
4202
|
+
batches;
|
|
4203
|
+
platform;
|
|
4204
|
+
custody;
|
|
4205
|
+
afterPendingWrite;
|
|
4206
|
+
afterBatchPublish;
|
|
4207
|
+
sessionDirectoryCursor;
|
|
4208
|
+
uploadScanSignature;
|
|
4209
|
+
uploadScanEmpty = false;
|
|
4309
4210
|
constructor(options) {
|
|
4310
|
-
|
|
4311
|
-
this.
|
|
4312
|
-
this.
|
|
4211
|
+
this.root = join3(options.outbox_dir, "usage-facts");
|
|
4212
|
+
this.sessions = join3(this.root, "sessions");
|
|
4213
|
+
this.batches = join3(this.root, "batches");
|
|
4214
|
+
this.platform = options.platform ?? process.platform;
|
|
4215
|
+
this.custody = options.secure_file_custody ?? {};
|
|
4216
|
+
this.afterPendingWrite = options.afterPendingWrite;
|
|
4217
|
+
this.afterBatchPublish = options.afterBatchPublish;
|
|
4218
|
+
}
|
|
4219
|
+
async prepare() {
|
|
4220
|
+
for (const directory of [this.root, this.sessions, this.batches]) {
|
|
4221
|
+
await preparePrivateDirectory(directory, this.platform, this.custody);
|
|
4222
|
+
}
|
|
4313
4223
|
}
|
|
4314
4224
|
async close() {
|
|
4315
|
-
|
|
4225
|
+
const cursor = this.sessionDirectoryCursor;
|
|
4226
|
+
this.sessionDirectoryCursor = void 0;
|
|
4227
|
+
await cursor?.close();
|
|
4316
4228
|
}
|
|
4317
|
-
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
const
|
|
4323
|
-
const
|
|
4324
|
-
|
|
4325
|
-
|
|
4326
|
-
|
|
4327
|
-
|
|
4229
|
+
/** The durable path behind one session's usage state, so idle fast paths can poll it without reading it. */
|
|
4230
|
+
statePath(producer, hostSourceRef, hostSessionRef) {
|
|
4231
|
+
return this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
4232
|
+
}
|
|
4233
|
+
async readState(producer, hostSourceRef, hostSessionRef) {
|
|
4234
|
+
const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
4235
|
+
const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
4236
|
+
if (value === null) return null;
|
|
4237
|
+
validateState(value, producer, hostSourceRef, hostSessionRef);
|
|
4238
|
+
return value;
|
|
4239
|
+
}
|
|
4240
|
+
createState(producer, hostSourceRef, hostSessionRef) {
|
|
4241
|
+
return {
|
|
4242
|
+
schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
|
|
4243
|
+
producer,
|
|
4244
|
+
host_source_ref: hostSourceRef,
|
|
4245
|
+
host_session_ref: hostSessionRef,
|
|
4246
|
+
cursors: {},
|
|
4247
|
+
eligible_batches: [],
|
|
4248
|
+
coverage_gaps: [],
|
|
4249
|
+
coverage_gap_created_at: null
|
|
4250
|
+
};
|
|
4251
|
+
}
|
|
4252
|
+
async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
|
|
4253
|
+
let state = await this.readState(producer, hostSourceRef, hostSessionRef);
|
|
4254
|
+
if (state === null) {
|
|
4255
|
+
state = this.createState(producer, hostSourceRef, hostSessionRef);
|
|
4256
|
+
state = await this.writeCursor(state, sourceSlot, initial);
|
|
4257
|
+
}
|
|
4258
|
+
state = await this.recoverPending(state);
|
|
4259
|
+
if (state.quarantined_reason !== void 0) return null;
|
|
4260
|
+
state = await this.commitCoverageGaps(state, createdAt);
|
|
4261
|
+
const cursor = state.cursors[sourceSlot];
|
|
4262
|
+
return cursor === void 0 ? null : { state, cursor };
|
|
4263
|
+
}
|
|
4264
|
+
async writeCursor(state, sourceSlot, cursor) {
|
|
4265
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
4266
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
4267
|
+
if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
|
|
4268
|
+
const current = latest.cursors[sourceSlot];
|
|
4269
|
+
if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
|
|
4270
|
+
const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
|
|
4271
|
+
await this.writeState(updated);
|
|
4272
|
+
return updated;
|
|
4328
4273
|
});
|
|
4329
|
-
|
|
4330
|
-
|
|
4331
|
-
|
|
4274
|
+
}
|
|
4275
|
+
async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
|
|
4276
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
4277
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
4278
|
+
return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
|
|
4279
|
+
});
|
|
4280
|
+
}
|
|
4281
|
+
async recoverPending(state) {
|
|
4282
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
4283
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
4284
|
+
const recovered = await this.finishPendingTransition(latest);
|
|
4285
|
+
await this.sweepOrphanedBatches(recovered);
|
|
4286
|
+
return recovered;
|
|
4287
|
+
});
|
|
4288
|
+
}
|
|
4289
|
+
/** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
|
|
4290
|
+
async sweepOrphanedBatches(state) {
|
|
4291
|
+
const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
|
|
4292
|
+
const expected = expectedBatchNames(state);
|
|
4293
|
+
let directory;
|
|
4294
|
+
try {
|
|
4295
|
+
directory = await opendir(directoryPath);
|
|
4296
|
+
} catch (error) {
|
|
4297
|
+
if (errorCode3(error) === "ENOENT") return 0;
|
|
4298
|
+
throw error;
|
|
4332
4299
|
}
|
|
4333
|
-
|
|
4334
|
-
|
|
4300
|
+
let inspected = 0;
|
|
4301
|
+
let deleted = 0;
|
|
4302
|
+
try {
|
|
4303
|
+
while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
|
|
4304
|
+
const entry = await directory.read();
|
|
4305
|
+
if (entry === null) break;
|
|
4306
|
+
inspected += 1;
|
|
4307
|
+
if (!isOrphanBatchEntry(entry, expected)) continue;
|
|
4308
|
+
await unlink2(join3(directoryPath, entry.name));
|
|
4309
|
+
deleted += 1;
|
|
4310
|
+
}
|
|
4311
|
+
} finally {
|
|
4312
|
+
await directory.close();
|
|
4313
|
+
}
|
|
4314
|
+
if (deleted > 0) await syncDirectory(directoryPath, this.platform);
|
|
4315
|
+
return deleted;
|
|
4335
4316
|
}
|
|
4336
|
-
|
|
4337
|
-
|
|
4338
|
-
|
|
4339
|
-
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
|
|
4317
|
+
async commitCoverageGaps(state, createdAt) {
|
|
4318
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
4319
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
4320
|
+
if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
|
|
4321
|
+
const sourceRanges = coverageRanges(latest.coverage_gaps);
|
|
4322
|
+
const canonical = createCealHostUsageBatch({
|
|
4323
|
+
host_source_ref: latest.host_source_ref,
|
|
4324
|
+
host_session_ref: latest.host_session_ref,
|
|
4325
|
+
created_at: latest.coverage_gap_created_at ?? createdAt,
|
|
4326
|
+
source_ranges: sourceRanges,
|
|
4327
|
+
facts: [],
|
|
4328
|
+
coverage_gaps: latest.coverage_gaps
|
|
4329
|
+
});
|
|
4330
|
+
const cursor = firstCursor(latest);
|
|
4331
|
+
if (cursor === null) return latest;
|
|
4332
|
+
return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
|
|
4333
|
+
});
|
|
4334
|
+
}
|
|
4335
|
+
async nextUploadCandidate(producer, hostSourceRef) {
|
|
4336
|
+
const signature = await statObservedPathSignature(this.sessions);
|
|
4337
|
+
if (signature !== null && signature === this.uploadScanSignature && this.uploadScanEmpty) return null;
|
|
4338
|
+
const candidate = await this.scanUploadCandidates(producer, hostSourceRef);
|
|
4339
|
+
this.uploadScanSignature = signature ?? void 0;
|
|
4340
|
+
this.uploadScanEmpty = candidate === null;
|
|
4341
|
+
return candidate;
|
|
4342
|
+
}
|
|
4343
|
+
async scanUploadCandidates(producer, hostSourceRef) {
|
|
4344
|
+
const names = await this.readNextSessionNames();
|
|
4345
|
+
for (const name of names) {
|
|
4346
|
+
const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
4347
|
+
if (state === null) continue;
|
|
4348
|
+
validateStateOwner(state, producer, hostSourceRef);
|
|
4349
|
+
let validated = state;
|
|
4350
|
+
if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
|
|
4351
|
+
else validated = await this.recoverPending(validated);
|
|
4352
|
+
if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
|
|
4353
|
+
const next = validated.eligible_batches[0];
|
|
4354
|
+
if (next === void 0) continue;
|
|
4355
|
+
const batch = await this.readBatch(validated, next.batch_ref);
|
|
4356
|
+
return { state: validated, batch };
|
|
4357
|
+
}
|
|
4358
|
+
return null;
|
|
4359
|
+
}
|
|
4360
|
+
async readNextSessionNames() {
|
|
4361
|
+
if (this.sessionDirectoryCursor === void 0) {
|
|
4343
4362
|
try {
|
|
4344
|
-
await
|
|
4345
|
-
} catch {
|
|
4346
|
-
|
|
4363
|
+
this.sessionDirectoryCursor = await opendir(this.sessions);
|
|
4364
|
+
} catch (error) {
|
|
4365
|
+
if (errorCode3(error) === "ENOENT") return [];
|
|
4366
|
+
throw error;
|
|
4347
4367
|
}
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4356
|
-
|
|
4357
|
-
writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
|
|
4368
|
+
}
|
|
4369
|
+
const names = [];
|
|
4370
|
+
let inspected = 0;
|
|
4371
|
+
while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
|
|
4372
|
+
const entry = await this.sessionDirectoryCursor.read();
|
|
4373
|
+
if (entry === null) {
|
|
4374
|
+
await this.sessionDirectoryCursor.close();
|
|
4375
|
+
this.sessionDirectoryCursor = void 0;
|
|
4376
|
+
break;
|
|
4358
4377
|
}
|
|
4359
|
-
|
|
4378
|
+
inspected += 1;
|
|
4379
|
+
if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
|
|
4380
|
+
}
|
|
4381
|
+
return names;
|
|
4382
|
+
}
|
|
4383
|
+
async acknowledge(state, batchRef) {
|
|
4384
|
+
await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
4385
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
4386
|
+
if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
|
|
4387
|
+
const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
|
|
4388
|
+
if (remaining.length === latest.eligible_batches.length) return;
|
|
4389
|
+
await this.writeState({ ...latest, eligible_batches: remaining });
|
|
4390
|
+
await removeFileIfPresent(this.batchPath(state, batchRef));
|
|
4391
|
+
});
|
|
4392
|
+
}
|
|
4393
|
+
async quarantine(state, reason) {
|
|
4394
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
4395
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
4396
|
+
const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
|
|
4397
|
+
await this.writeState(updated);
|
|
4398
|
+
return updated;
|
|
4399
|
+
});
|
|
4400
|
+
}
|
|
4401
|
+
async retireCursor(state, sourceSlot, cursor, gap) {
|
|
4402
|
+
return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
|
|
4403
|
+
}
|
|
4404
|
+
async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
|
|
4405
|
+
if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
|
|
4406
|
+
if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
|
|
4407
|
+
const queued = await this.publishTransitionBatch(state, batch);
|
|
4408
|
+
const pending = {
|
|
4409
|
+
source_slot: sourceSlot,
|
|
4410
|
+
before_cursor: beforeCursor,
|
|
4411
|
+
after_cursor: afterCursor,
|
|
4412
|
+
batch_ref: queued.batch_ref,
|
|
4413
|
+
batch_bytes: queued.batch_bytes,
|
|
4414
|
+
gap_delta: [...gapDelta, ...queued.overflow_gaps],
|
|
4415
|
+
clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
|
|
4416
|
+
};
|
|
4417
|
+
const prepared = { ...state, pending_transition: pending };
|
|
4418
|
+
await this.writeState(prepared);
|
|
4419
|
+
await this.afterPendingWrite?.();
|
|
4420
|
+
return await this.finishPendingTransition(prepared);
|
|
4421
|
+
}
|
|
4422
|
+
async publishTransitionBatch(state, batch) {
|
|
4423
|
+
if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
|
|
4424
|
+
const serialized = serializeBatch(batch);
|
|
4425
|
+
if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
|
|
4426
|
+
await this.writeImmutableBatch(state, batch, serialized);
|
|
4427
|
+
await this.afterBatchPublish?.();
|
|
4428
|
+
return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
|
|
4429
|
+
}
|
|
4430
|
+
async finishPendingTransition(state) {
|
|
4431
|
+
const pending = state.pending_transition;
|
|
4432
|
+
if (pending === void 0 || state.quarantined_reason !== void 0) return state;
|
|
4433
|
+
const current = state.cursors[pending.source_slot];
|
|
4434
|
+
if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
|
|
4435
|
+
const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
|
|
4436
|
+
await this.writeState(quarantined);
|
|
4437
|
+
return quarantined;
|
|
4438
|
+
}
|
|
4439
|
+
let cursors = state.cursors;
|
|
4440
|
+
if (!cursorMatches(current, pending.after_cursor)) {
|
|
4441
|
+
const next = { ...state.cursors };
|
|
4442
|
+
if (pending.after_cursor === null) delete next[pending.source_slot];
|
|
4443
|
+
else next[pending.source_slot] = pending.after_cursor;
|
|
4444
|
+
cursors = next;
|
|
4445
|
+
}
|
|
4446
|
+
const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
|
|
4447
|
+
const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
|
|
4448
|
+
const { pending_transition: _pendingTransition, ...settledState } = state;
|
|
4449
|
+
const updated = {
|
|
4450
|
+
...settledState,
|
|
4451
|
+
cursors,
|
|
4452
|
+
eligible_batches: eligible,
|
|
4453
|
+
coverage_gaps: gaps,
|
|
4454
|
+
coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
4455
|
+
};
|
|
4456
|
+
await this.writeState(updated);
|
|
4457
|
+
return updated;
|
|
4458
|
+
}
|
|
4459
|
+
async writeImmutableBatch(state, batch, bytes) {
|
|
4460
|
+
const path = this.batchPath(state, batch.batch_ref);
|
|
4461
|
+
await preparePrivateDirectory(dirname5(path), this.platform, this.custody);
|
|
4462
|
+
const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
4463
|
+
if (existing !== null) {
|
|
4464
|
+
if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
|
|
4465
|
+
await syncExistingFile(path, this.platform);
|
|
4466
|
+
return;
|
|
4467
|
+
}
|
|
4468
|
+
if (this.platform === "win32") {
|
|
4469
|
+
await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
|
|
4470
|
+
return;
|
|
4471
|
+
}
|
|
4472
|
+
let handle;
|
|
4473
|
+
try {
|
|
4474
|
+
handle = await openNoFollow(path, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384, this.platform);
|
|
4475
|
+
await handle.writeFile(bytes);
|
|
4476
|
+
await handle.sync();
|
|
4477
|
+
await handle.close();
|
|
4478
|
+
handle = void 0;
|
|
4479
|
+
await syncDirectory(dirname5(path), this.platform);
|
|
4480
|
+
} catch (error) {
|
|
4481
|
+
await handle?.close().catch(() => void 0);
|
|
4482
|
+
if (errorCode3(error) === "EEXIST") {
|
|
4483
|
+
const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
4484
|
+
if (winner !== null && winner.equals(bytes)) {
|
|
4485
|
+
await syncExistingFile(path, this.platform);
|
|
4486
|
+
return;
|
|
4487
|
+
}
|
|
4488
|
+
throw new Error("Host usage facts batch reference conflicts with existing bytes.");
|
|
4489
|
+
}
|
|
4490
|
+
await removeFileIfPresent(path).catch(() => void 0);
|
|
4491
|
+
throw error;
|
|
4492
|
+
}
|
|
4493
|
+
}
|
|
4494
|
+
async readBatch(state, batchRef) {
|
|
4495
|
+
const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
4496
|
+
if (bytes === null) throw new Error("Host usage facts batch object is missing.");
|
|
4497
|
+
let value;
|
|
4498
|
+
try {
|
|
4499
|
+
value = JSON.parse(bytes.toString("utf8"));
|
|
4500
|
+
} catch {
|
|
4501
|
+
throw new Error("Host usage facts batch object is malformed.");
|
|
4502
|
+
}
|
|
4503
|
+
validateCealHostUsageBatch(value);
|
|
4504
|
+
if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
|
|
4505
|
+
return value;
|
|
4506
|
+
}
|
|
4507
|
+
async writeState(state) {
|
|
4508
|
+
validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
|
|
4509
|
+
const bytes = Buffer.from(JSON.stringify(state), "utf8");
|
|
4510
|
+
if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
|
|
4511
|
+
await this.prepare();
|
|
4512
|
+
const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
|
|
4513
|
+
if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
|
|
4514
|
+
else await durableAtomicReplace(path, bytes);
|
|
4515
|
+
}
|
|
4516
|
+
async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
|
|
4517
|
+
const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
4518
|
+
const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
|
|
4519
|
+
let release;
|
|
4520
|
+
const gate = new Promise((resolve) => {
|
|
4521
|
+
release = resolve;
|
|
4522
|
+
});
|
|
4523
|
+
const tail2 = previous.then(() => gate);
|
|
4524
|
+
SESSION_TRANSITION_TAILS.set(key, tail2);
|
|
4525
|
+
await previous;
|
|
4526
|
+
try {
|
|
4527
|
+
return await run();
|
|
4528
|
+
} finally {
|
|
4529
|
+
release?.();
|
|
4530
|
+
if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
|
|
4360
4531
|
}
|
|
4361
|
-
} finally {
|
|
4362
|
-
await uploader.close().catch(() => void 0);
|
|
4363
4532
|
}
|
|
4533
|
+
sessionPath(producer, hostSourceRef, hostSessionRef) {
|
|
4534
|
+
return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
|
|
4535
|
+
}
|
|
4536
|
+
batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
|
|
4537
|
+
const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
|
|
4538
|
+
return join3(this.batches, sessionName.slice(0, -5));
|
|
4539
|
+
}
|
|
4540
|
+
batchPath(state, batchRef) {
|
|
4541
|
+
return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
|
|
4542
|
+
}
|
|
4543
|
+
};
|
|
4544
|
+
function serializeBatch(batch) {
|
|
4545
|
+
validateCealHostUsageBatch(batch);
|
|
4546
|
+
return Buffer.from(JSON.stringify(batch), "utf8");
|
|
4364
4547
|
}
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
function isHostTranscriptCursorReason(value) {
|
|
4370
|
-
return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
|
|
4548
|
+
function batchFileName(batchRef) {
|
|
4549
|
+
const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
|
|
4550
|
+
if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
|
|
4551
|
+
return `${digest2}.json`;
|
|
4371
4552
|
}
|
|
4372
|
-
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
4384
|
-
|
|
4385
|
-
|
|
4386
|
-
|
|
4553
|
+
function expectedBatchNames(state) {
|
|
4554
|
+
const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
|
|
4555
|
+
const pending = state.pending_transition?.batch_ref;
|
|
4556
|
+
if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
|
|
4557
|
+
return expected;
|
|
4558
|
+
}
|
|
4559
|
+
function isOrphanBatchEntry(entry, expected) {
|
|
4560
|
+
return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
|
|
4561
|
+
}
|
|
4562
|
+
function hasOutboxCapacity(state, bytes) {
|
|
4563
|
+
const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
|
|
4564
|
+
return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
|
|
4565
|
+
}
|
|
4566
|
+
function overflowCoverageGaps(batch) {
|
|
4567
|
+
const count = batch.facts.length;
|
|
4568
|
+
const gaps = [...batch.coverage_gaps];
|
|
4569
|
+
if (count > 0) gaps.push({ reason: "outbox_capacity", source_file_ref: batch.source_ranges[0]?.source_file_ref ?? null, start_offset: batch.source_ranges[0]?.start_offset ?? null, end_offset: batch.source_ranges[0]?.end_offset ?? null, omitted_count: count });
|
|
4570
|
+
return gaps;
|
|
4571
|
+
}
|
|
4572
|
+
function appendEligible(existing, next) {
|
|
4573
|
+
if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
|
|
4574
|
+
if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
|
|
4575
|
+
return [...existing, next];
|
|
4576
|
+
}
|
|
4577
|
+
function appendCoverageGaps(existing, added) {
|
|
4578
|
+
if (added.length === 0) return existing;
|
|
4579
|
+
const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
|
|
4580
|
+
for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
|
|
4581
|
+
const combined = [...byIdentity.values()];
|
|
4582
|
+
if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
|
|
4583
|
+
const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
|
|
4584
|
+
return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
|
|
4585
|
+
}
|
|
4586
|
+
function coverageRanges(gaps) {
|
|
4587
|
+
const ranges = /* @__PURE__ */ new Map();
|
|
4588
|
+
for (const gap of gaps) {
|
|
4589
|
+
if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
|
|
4590
|
+
const current = ranges.get(gap.source_file_ref);
|
|
4591
|
+
if (current === void 0) ranges.set(gap.source_file_ref, { source_file_ref: gap.source_file_ref, start_offset: gap.start_offset, end_offset: gap.end_offset });
|
|
4592
|
+
else ranges.set(gap.source_file_ref, { ...current, start_offset: Math.min(current.start_offset, gap.start_offset), end_offset: Math.max(current.end_offset, gap.end_offset) });
|
|
4387
4593
|
}
|
|
4388
|
-
return
|
|
4594
|
+
return [...ranges.values()];
|
|
4389
4595
|
}
|
|
4390
|
-
function
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
if (adapter !== void 0) return adapter;
|
|
4394
|
-
const code = transcriptErrorCode(error);
|
|
4395
|
-
if (code === "EFBIG") return "size_budget";
|
|
4396
|
-
if (code !== null && TRANSCRIPT_SCAN_READ_ERROR_ERRNOS.includes(code)) return "read_error";
|
|
4397
|
-
return "other";
|
|
4596
|
+
function firstCursor(state) {
|
|
4597
|
+
const entry = Object.entries(state.cursors)[0];
|
|
4598
|
+
return entry === void 0 ? null : entry;
|
|
4398
4599
|
}
|
|
4399
|
-
function
|
|
4400
|
-
return
|
|
4600
|
+
function sameCursor(left, right) {
|
|
4601
|
+
return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
|
|
4401
4602
|
}
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
4408
|
-
|
|
4409
|
-
|
|
4410
|
-
|
|
4411
|
-
|
|
4412
|
-
|
|
4413
|
-
|
|
4414
|
-
|
|
4415
|
-
|
|
4416
|
-
|
|
4417
|
-
|
|
4418
|
-
|
|
4419
|
-
|
|
4420
|
-
|
|
4603
|
+
function cursorMatches(left, right) {
|
|
4604
|
+
return right === null ? left === void 0 : sameCursor(left, right);
|
|
4605
|
+
}
|
|
4606
|
+
function validateState(value, producer, hostSourceRef, hostSessionRef) {
|
|
4607
|
+
validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
|
|
4608
|
+
validateStateShape(value);
|
|
4609
|
+
validateStateLimits(value);
|
|
4610
|
+
validateStateContents(value);
|
|
4611
|
+
}
|
|
4612
|
+
function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
|
|
4613
|
+
if (!isRecord3(value) || value.schema_version !== HOST_USAGE_FACTS_STATE_SCHEMA || value.producer !== producer || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new Error("Host usage facts state identity is invalid.");
|
|
4614
|
+
}
|
|
4615
|
+
function validateStateLimits(value) {
|
|
4616
|
+
if (Object.keys(value.cursors).length > HOST_USAGE_FACTS_MAX_SOURCE_CURSORS || value.eligible_batches.length > HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES || value.coverage_gaps.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) throw new Error("Host usage facts state exceeds its bounds.");
|
|
4617
|
+
}
|
|
4618
|
+
function validateStateContents(value) {
|
|
4619
|
+
for (const [slot, cursor] of Object.entries(value.cursors)) {
|
|
4620
|
+
validateSourceSlot(slot);
|
|
4621
|
+
validateFileCursor(cursor);
|
|
4421
4622
|
}
|
|
4422
|
-
|
|
4423
|
-
|
|
4623
|
+
for (const item of value.eligible_batches) validateEligibleBatch(item);
|
|
4624
|
+
if (value.pending_transition !== void 0) validatePending(value.pending_transition);
|
|
4625
|
+
for (const gap of value.coverage_gaps) validateGap(gap);
|
|
4626
|
+
validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
|
|
4424
4627
|
}
|
|
4425
|
-
|
|
4426
|
-
|
|
4427
|
-
|
|
4428
|
-
if (anchor.length > 0) await handle.read(anchor, 0, anchor.length, start);
|
|
4429
|
-
return { start, sha256: transcriptSha256(anchor) };
|
|
4628
|
+
function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
|
|
4629
|
+
if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
|
|
4630
|
+
if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
|
|
4430
4631
|
}
|
|
4431
|
-
|
|
4432
|
-
|
|
4433
|
-
|
|
4434
|
-
return transcriptSha256(buffer) === cursor.anchor_sha256;
|
|
4632
|
+
function validateStateOwner(value, producer, hostSourceRef) {
|
|
4633
|
+
if (!isRecord3(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
|
|
4634
|
+
validateState(value, producer, hostSourceRef, String(value.host_session_ref));
|
|
4435
4635
|
}
|
|
4436
|
-
function
|
|
4437
|
-
|
|
4438
|
-
|
|
4636
|
+
function validateStateShape(value) {
|
|
4637
|
+
const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
|
|
4638
|
+
const optional = ["pending_transition", "quarantined_reason"];
|
|
4639
|
+
if (required.some((key) => !Object.hasOwn(value, key)) || Object.keys(value).some((key) => !required.includes(key) && !optional.includes(key))) throw new Error("Host usage facts state keys are invalid.");
|
|
4640
|
+
if (!isRecord3(value.cursors) || !Array.isArray(value.eligible_batches) || !Array.isArray(value.coverage_gaps) || value.coverage_gap_created_at !== null && typeof value.coverage_gap_created_at !== "string") throw new Error("Host usage facts state collections are invalid.");
|
|
4439
4641
|
}
|
|
4440
|
-
|
|
4441
|
-
if (
|
|
4442
|
-
|
|
4443
|
-
|
|
4642
|
+
function validateFileCursor(value) {
|
|
4643
|
+
if (!isRecord3(value) || !sameKeys(value, ["source_file_ref", "device", "inode", "offset", "anchor_start", "anchor_sha256", "last_ordinal", "host_turn_ref", "native_turn_id", "requested_model", "codex_total_usage", "skipping_oversized_line"])) throw new Error("Host usage facts source cursor is invalid.");
|
|
4644
|
+
validateCursorIdentity(value);
|
|
4645
|
+
validateCursorOffsets(value);
|
|
4646
|
+
validateCursorContext(value);
|
|
4647
|
+
if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
|
|
4648
|
+
if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
|
|
4444
4649
|
}
|
|
4445
|
-
function
|
|
4446
|
-
|
|
4650
|
+
function validateCursorIdentity(value) {
|
|
4651
|
+
if (![value.source_file_ref, value.device, value.inode].every((part) => typeof part === "string" && part.length > 0 && part.length <= HOST_USAGE_FACTS_REF_MAX_LENGTH)) throw new Error("Host usage facts source cursor identity is invalid.");
|
|
4447
4652
|
}
|
|
4448
|
-
function
|
|
4449
|
-
|
|
4653
|
+
function validateCursorOffsets(value) {
|
|
4654
|
+
if (!/^host-source-file:[a-f0-9]{64}$/u.test(String(value.source_file_ref)) || !safeInteger2(value.offset) || !safeInteger2(value.anchor_start) || Number(value.anchor_start) > Number(value.offset) || !/^[a-f0-9]{64}$/u.test(String(value.anchor_sha256)) || value.last_ordinal !== null && !safeInteger2(value.last_ordinal)) throw new Error("Host usage facts source cursor fields are invalid.");
|
|
4450
4655
|
}
|
|
4451
|
-
function
|
|
4452
|
-
|
|
4656
|
+
function validateCursorContext(value) {
|
|
4657
|
+
if (!validOptionalText(value.host_turn_ref, HOST_USAGE_FACTS_REF_MAX_LENGTH) || !validOptionalText(value.native_turn_id, HOST_USAGE_FACTS_REF_MAX_LENGTH) || !validOptionalText(value.requested_model, 256)) throw new Error("Host usage facts source context is invalid.");
|
|
4453
4658
|
}
|
|
4454
|
-
function
|
|
4455
|
-
return
|
|
4659
|
+
function validOptionalText(value, maximum) {
|
|
4660
|
+
return value === null || typeof value === "string" && value.length <= maximum;
|
|
4456
4661
|
}
|
|
4457
|
-
function
|
|
4458
|
-
|
|
4459
|
-
if (!
|
|
4460
|
-
return value.toISOString();
|
|
4662
|
+
function validateCodexCounts(value) {
|
|
4663
|
+
if (!isRecord3(value) || !sameKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) throw new Error("Host usage facts cumulative usage is invalid.");
|
|
4664
|
+
if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
|
|
4461
4665
|
}
|
|
4462
|
-
function
|
|
4463
|
-
|
|
4666
|
+
function validatePending(value) {
|
|
4667
|
+
if (!isRecord3(value) || !sameKeys(value, ["source_slot", "before_cursor", "after_cursor", "batch_ref", "batch_bytes", "gap_delta", "clear_coverage_gaps"])) throw new Error("Host usage facts pending transition is invalid.");
|
|
4668
|
+
validatePendingCursors(value);
|
|
4669
|
+
validatePendingBatch(value);
|
|
4670
|
+
validatePendingFields(value);
|
|
4671
|
+
for (const gap of value.gap_delta) validateGap(gap);
|
|
4464
4672
|
}
|
|
4465
|
-
function
|
|
4466
|
-
|
|
4467
|
-
|
|
4468
|
-
|
|
4469
|
-
now: options.now ?? (() => /* @__PURE__ */ new Date()),
|
|
4470
|
-
log: options.log ?? ((line) => {
|
|
4471
|
-
writeHostServiceLogLine(`${line}
|
|
4472
|
-
`);
|
|
4473
|
-
}),
|
|
4474
|
-
producerInstallationRef: options.producer_installation_ref
|
|
4475
|
-
};
|
|
4673
|
+
function validatePendingCursors(value) {
|
|
4674
|
+
validateSourceSlot(value.source_slot);
|
|
4675
|
+
validateFileCursor(value.before_cursor);
|
|
4676
|
+
if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
|
|
4476
4677
|
}
|
|
4477
|
-
|
|
4478
|
-
|
|
4479
|
-
let enqueued = 0;
|
|
4480
|
-
let quarantined = 0;
|
|
4481
|
-
for (const registration of registrations) {
|
|
4482
|
-
const result = await scanOne(registration);
|
|
4483
|
-
records += result.records;
|
|
4484
|
-
enqueued += result.enqueued;
|
|
4485
|
-
if (result.quarantined) quarantined += 1;
|
|
4486
|
-
}
|
|
4487
|
-
return { registrations: registrations.length, records, enqueued, quarantined };
|
|
4678
|
+
function validatePendingBatch(value) {
|
|
4679
|
+
if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
|
|
4488
4680
|
}
|
|
4489
|
-
function
|
|
4490
|
-
|
|
4681
|
+
function validatePendingFields(value) {
|
|
4682
|
+
if (!safeInteger2(value.batch_bytes) || !Array.isArray(value.gap_delta) || value.gap_delta.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS || typeof value.clear_coverage_gaps !== "boolean") throw new Error("Host usage facts pending transition fields are invalid.");
|
|
4491
4683
|
}
|
|
4492
|
-
|
|
4493
|
-
|
|
4494
|
-
|
|
4495
|
-
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
this.outboxRetentionMs = base.outboxRetentionMs;
|
|
4501
|
-
this.now = base.now;
|
|
4502
|
-
this.log = base.log;
|
|
4503
|
-
this.producerInstallationRef = base.producerInstallationRef;
|
|
4504
|
-
this.clockFailure = owner.clock_failure;
|
|
4505
|
-
}
|
|
4506
|
-
async scanOnce() {
|
|
4507
|
-
return scanTranscriptRegistrations(await this.listRegistrations(), (registration) => this.scanRegistration(registration));
|
|
4684
|
+
function validateEligibleBatch(value) {
|
|
4685
|
+
if (!isRecord3(value) || !sameKeys(value, ["batch_ref", "bytes"]) || !isCealHostUsageBatchReference(value.batch_ref) || !safeInteger2(value.bytes) || Number(value.bytes) < 1 || Number(value.bytes) > CEAL_HOST_USAGE_BATCH_MAX_BYTES) throw new Error("Host usage facts eligible batch is invalid.");
|
|
4686
|
+
}
|
|
4687
|
+
function validateGap(value) {
|
|
4688
|
+
try {
|
|
4689
|
+
validateCealHostUsageCoverageGap(value);
|
|
4690
|
+
} catch {
|
|
4691
|
+
throw new Error("Host usage facts coverage gap is invalid.");
|
|
4508
4692
|
}
|
|
4509
|
-
|
|
4510
|
-
|
|
4511
|
-
|
|
4512
|
-
|
|
4513
|
-
|
|
4514
|
-
|
|
4515
|
-
|
|
4516
|
-
|
|
4517
|
-
|
|
4518
|
-
|
|
4519
|
-
|
|
4693
|
+
}
|
|
4694
|
+
function validateSourceSlot(value) {
|
|
4695
|
+
if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
|
|
4696
|
+
}
|
|
4697
|
+
async function readOptionalJson(path, maxBytes, platform, custody) {
|
|
4698
|
+
const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
|
|
4699
|
+
if (bytes === null) return null;
|
|
4700
|
+
try {
|
|
4701
|
+
return JSON.parse(bytes.toString("utf8"));
|
|
4702
|
+
} catch {
|
|
4703
|
+
throw new Error("Host usage facts state JSON is malformed.");
|
|
4520
4704
|
}
|
|
4521
|
-
|
|
4522
|
-
|
|
4705
|
+
}
|
|
4706
|
+
async function readOptionalBytes(path, maxBytes, platform, custody) {
|
|
4707
|
+
if (platform === "win32") {
|
|
4523
4708
|
try {
|
|
4524
|
-
|
|
4525
|
-
return await scan(handle);
|
|
4709
|
+
return await readPrivateFileWithSecurefs(path, maxBytes, custody);
|
|
4526
4710
|
} catch (error) {
|
|
4527
|
-
if (
|
|
4528
|
-
|
|
4529
|
-
} finally {
|
|
4530
|
-
await handle?.close();
|
|
4711
|
+
if (errorCode3(error) === "ENOENT") return null;
|
|
4712
|
+
throw error;
|
|
4531
4713
|
}
|
|
4532
4714
|
}
|
|
4533
|
-
|
|
4534
|
-
|
|
4535
|
-
|
|
4536
|
-
|
|
4537
|
-
|
|
4538
|
-
|
|
4539
|
-
|
|
4540
|
-
|
|
4541
|
-
|
|
4542
|
-
|
|
4543
|
-
|
|
4544
|
-
}
|
|
4545
|
-
stamp() {
|
|
4546
|
-
return transcriptTimestamp(this.now, this.clockFailure);
|
|
4715
|
+
let handle;
|
|
4716
|
+
try {
|
|
4717
|
+
handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
|
|
4718
|
+
const stats = await handle.stat();
|
|
4719
|
+
if (!stats.isFile() || !isSelfOwned(stats.uid, platform, handle) || !isPrivateFileMode(stats.mode, platform, handle) || stats.size > maxBytes) throw new Error("Host usage facts file custody or size is invalid.");
|
|
4720
|
+
return await handle.readFile();
|
|
4721
|
+
} catch (error) {
|
|
4722
|
+
if (errorCode3(error) === "ENOENT") return null;
|
|
4723
|
+
throw error;
|
|
4724
|
+
} finally {
|
|
4725
|
+
await handle?.close();
|
|
4547
4726
|
}
|
|
4548
|
-
|
|
4549
|
-
|
|
4727
|
+
}
|
|
4728
|
+
async function preparePrivateDirectory(path, platform, custody) {
|
|
4729
|
+
if (platform === "win32") {
|
|
4730
|
+
await ensurePrivateDirectoryWithSecurefs(path, custody);
|
|
4731
|
+
return;
|
|
4550
4732
|
}
|
|
4551
|
-
|
|
4552
|
-
|
|
4733
|
+
await mkdir3(path, { recursive: true, mode: 448 });
|
|
4734
|
+
if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
|
|
4735
|
+
}
|
|
4736
|
+
async function syncExistingFile(path, platform) {
|
|
4737
|
+
const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
|
|
4738
|
+
try {
|
|
4739
|
+
await handle.sync();
|
|
4740
|
+
} finally {
|
|
4741
|
+
await handle.close();
|
|
4553
4742
|
}
|
|
4554
|
-
|
|
4555
|
-
|
|
4743
|
+
await syncDirectory(dirname5(path), platform);
|
|
4744
|
+
}
|
|
4745
|
+
async function syncDirectory(path, platform) {
|
|
4746
|
+
if (platform === "win32") return;
|
|
4747
|
+
const handle = await open3(path, constants4.O_RDONLY);
|
|
4748
|
+
try {
|
|
4749
|
+
await handle.sync();
|
|
4750
|
+
} finally {
|
|
4751
|
+
await handle.close();
|
|
4556
4752
|
}
|
|
4557
|
-
|
|
4558
|
-
|
|
4753
|
+
}
|
|
4754
|
+
async function removeFileIfPresent(path) {
|
|
4755
|
+
try {
|
|
4756
|
+
await unlink2(path);
|
|
4757
|
+
} catch (error) {
|
|
4758
|
+
if (errorCode3(error) !== "ENOENT") throw error;
|
|
4559
4759
|
}
|
|
4560
|
-
|
|
4561
|
-
|
|
4760
|
+
}
|
|
4761
|
+
function sameKeys(value, expected) {
|
|
4762
|
+
return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
|
|
4763
|
+
}
|
|
4764
|
+
function isRecord3(value) {
|
|
4765
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4766
|
+
}
|
|
4767
|
+
function safeInteger2(value) {
|
|
4768
|
+
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
4769
|
+
}
|
|
4770
|
+
function validTimestamp(value) {
|
|
4771
|
+
return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
4772
|
+
}
|
|
4773
|
+
function errorCode3(error) {
|
|
4774
|
+
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
4775
|
+
}
|
|
4776
|
+
function sha2562(value) {
|
|
4777
|
+
return createHash6("sha256").update(value, "utf8").digest("hex");
|
|
4778
|
+
}
|
|
4779
|
+
|
|
4780
|
+
// host/relay/src/host-usage-facts-uploader.ts
|
|
4781
|
+
var HostUsageFactsUploader = class {
|
|
4782
|
+
options;
|
|
4783
|
+
store;
|
|
4784
|
+
constructor(options) {
|
|
4785
|
+
if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
|
|
4786
|
+
this.options = options;
|
|
4787
|
+
this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
|
|
4562
4788
|
}
|
|
4563
|
-
|
|
4564
|
-
|
|
4789
|
+
async close() {
|
|
4790
|
+
await this.store.close();
|
|
4565
4791
|
}
|
|
4566
|
-
|
|
4567
|
-
|
|
4792
|
+
/** The start owner prepares the store once, so idle ticks below never re-prepare. */
|
|
4793
|
+
async prepare() {
|
|
4794
|
+
await this.store.prepare();
|
|
4568
4795
|
}
|
|
4569
|
-
|
|
4570
|
-
|
|
4796
|
+
async uploadOne(signal) {
|
|
4797
|
+
const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
|
|
4798
|
+
if (candidate === null) return false;
|
|
4799
|
+
const registration = await readHostRegistrationAuthority(this.options.registration_state_file, this.options.host_source_ref, this.options.store_options?.platform, this.options.store_options?.secure_file_custody);
|
|
4800
|
+
const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
|
|
4801
|
+
const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
|
|
4802
|
+
const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
|
|
4803
|
+
method: "POST",
|
|
4804
|
+
headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
|
|
4805
|
+
body: JSON.stringify(candidate.batch),
|
|
4806
|
+
signal: requestSignal
|
|
4807
|
+
});
|
|
4808
|
+
if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
|
|
4809
|
+
await response2.body?.cancel().catch(() => void 0);
|
|
4810
|
+
throw new Error("Gateway did not acknowledge the Host usage facts batch.");
|
|
4811
|
+
}
|
|
4812
|
+
await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
|
|
4813
|
+
return true;
|
|
4571
4814
|
}
|
|
4572
4815
|
};
|
|
4573
|
-
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
|
|
4577
|
-
|
|
4578
|
-
|
|
4579
|
-
this.now = runtime.now ?? (() => /* @__PURE__ */ new Date());
|
|
4580
|
-
}
|
|
4581
|
-
drainOutbox() {
|
|
4582
|
-
const run = this.tail.then(() => this.drainLocked());
|
|
4583
|
-
this.tail = run.then(() => void 0, () => void 0);
|
|
4584
|
-
return run;
|
|
4816
|
+
async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
|
|
4817
|
+
const uploader = new HostUsageFactsUploader(options);
|
|
4818
|
+
try {
|
|
4819
|
+
await uploader.prepare();
|
|
4820
|
+
} catch {
|
|
4821
|
+
writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
|
|
4585
4822
|
}
|
|
4586
|
-
|
|
4587
|
-
|
|
4588
|
-
|
|
4589
|
-
|
|
4590
|
-
|
|
4591
|
-
|
|
4592
|
-
|
|
4593
|
-
|
|
4823
|
+
let delay = 500;
|
|
4824
|
+
let failures = 0;
|
|
4825
|
+
try {
|
|
4826
|
+
while (!signal.aborted) {
|
|
4827
|
+
try {
|
|
4828
|
+
await options.capture_next?.();
|
|
4829
|
+
} catch {
|
|
4830
|
+
writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
|
|
4831
|
+
}
|
|
4832
|
+
if (signal.aborted) return;
|
|
4833
|
+
try {
|
|
4834
|
+
const uploaded = await uploader.uploadOne(signal);
|
|
4835
|
+
failures = 0;
|
|
4836
|
+
delay = uploaded ? 100 : 1e3;
|
|
4837
|
+
} catch {
|
|
4838
|
+
if (signal.aborted) return;
|
|
4839
|
+
failures += 1;
|
|
4840
|
+
delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
|
|
4841
|
+
writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
|
|
4842
|
+
}
|
|
4843
|
+
if (!signal.aborted) await wait(signal, delay);
|
|
4594
4844
|
}
|
|
4595
|
-
|
|
4845
|
+
} finally {
|
|
4846
|
+
await uploader.close().catch(() => void 0);
|
|
4596
4847
|
}
|
|
4597
|
-
}
|
|
4848
|
+
}
|
|
4598
4849
|
|
|
4599
4850
|
// host/codex/src/codex-outbox.ts
|
|
4600
|
-
import { mkdir as mkdir4, open as open4,
|
|
4601
|
-
import { dirname as
|
|
4851
|
+
import { mkdir as mkdir4, open as open4, rename as rename2, stat as stat3, unlink as unlink3 } from "node:fs/promises";
|
|
4852
|
+
import { dirname as dirname7, isAbsolute as isAbsolute2, join as join4 } from "node:path";
|
|
4602
4853
|
|
|
4603
4854
|
// host/invocation-context.ts
|
|
4604
4855
|
var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
|
|
@@ -4655,18 +4906,11 @@ function safeRef(value) {
|
|
|
4655
4906
|
var HOST_PRODUCER_FRAME_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
|
|
4656
4907
|
var HOST_PRODUCER_FRAME_KINDS = ["session_started", "turn_started", "turn_terminal", "producer_status"];
|
|
4657
4908
|
var FRAME_KINDS = new Set(HOST_PRODUCER_FRAME_KINDS);
|
|
4658
|
-
var HOST_PRODUCER_FRAME_ERROR_CODES = [
|
|
4659
|
-
"invalid_frame_encoding",
|
|
4660
|
-
"invalid_frame_length",
|
|
4661
|
-
"frame_truncated",
|
|
4662
|
-
"unsupported_frame_schema",
|
|
4663
|
-
"invalid_frame_shape",
|
|
4664
|
-
"invalid_producer_identity",
|
|
4665
|
-
"frame_too_large"
|
|
4666
|
-
];
|
|
4667
4909
|
|
|
4668
4910
|
// host/relay/src/host-usage-facts-capture.ts
|
|
4669
4911
|
import { constants as constants5 } from "node:fs";
|
|
4912
|
+
import { lstat as lstat5 } from "node:fs/promises";
|
|
4913
|
+
import { dirname as dirname6 } from "node:path";
|
|
4670
4914
|
var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
|
|
4671
4915
|
var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
|
|
4672
4916
|
var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
|
|
@@ -4716,6 +4960,55 @@ var HostUsageRegistrationCapture = class {
|
|
|
4716
4960
|
return captured;
|
|
4717
4961
|
}
|
|
4718
4962
|
};
|
|
4963
|
+
var HostUsageIdleGate = class {
|
|
4964
|
+
seen = /* @__PURE__ */ new Map();
|
|
4965
|
+
statPath;
|
|
4966
|
+
constructor(options = {}) {
|
|
4967
|
+
this.statPath = options.statPath ?? statIdleGatePath;
|
|
4968
|
+
}
|
|
4969
|
+
/**
|
|
4970
|
+
* Check whether the path is unchanged since the last confirmed check, without recording anything.
|
|
4971
|
+
* The caller confirms the returned signature only after the capture for it succeeded without a
|
|
4972
|
+
* source error, so a failed read leaves the source eligible on the next tick while a fully-read,
|
|
4973
|
+
* unchanged source keeps skipping its open plus state-read probe.
|
|
4974
|
+
*/
|
|
4975
|
+
async checkUnchanged(key, path) {
|
|
4976
|
+
const signature = await this.statPath(path);
|
|
4977
|
+
if (signature === null) {
|
|
4978
|
+
this.seen.delete(key);
|
|
4979
|
+
return { unchanged: false, signature };
|
|
4980
|
+
}
|
|
4981
|
+
if (this.seen.get(key) === signature) return { unchanged: true, signature };
|
|
4982
|
+
return { unchanged: false, signature };
|
|
4983
|
+
}
|
|
4984
|
+
/** Remember a signature only after its capture succeeded, so failures stay eligible. */
|
|
4985
|
+
confirmUnchanged(key, signature) {
|
|
4986
|
+
if (signature === null) return;
|
|
4987
|
+
this.seen.set(key, signature);
|
|
4988
|
+
}
|
|
4989
|
+
};
|
|
4990
|
+
async function statIdleGatePath(path) {
|
|
4991
|
+
const direct = await statObservedPathSignature(path);
|
|
4992
|
+
if (direct !== null) return direct;
|
|
4993
|
+
try {
|
|
4994
|
+
await lstat5(path);
|
|
4995
|
+
return null;
|
|
4996
|
+
} catch (error) {
|
|
4997
|
+
const code = transcriptErrorCode(error);
|
|
4998
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
4999
|
+
return await missingPathAnchor(path);
|
|
5000
|
+
}
|
|
5001
|
+
}
|
|
5002
|
+
async function missingPathAnchor(path) {
|
|
5003
|
+
let ancestor = dirname6(path);
|
|
5004
|
+
for (let depth = 0; depth < 4; depth += 1) {
|
|
5005
|
+
if (ancestor === dirname6(ancestor)) return null;
|
|
5006
|
+
const anchor = await statObservedPathSignature(ancestor);
|
|
5007
|
+
if (anchor !== null) return `missing:${anchor}`;
|
|
5008
|
+
ancestor = dirname6(ancestor);
|
|
5009
|
+
}
|
|
5010
|
+
return null;
|
|
5011
|
+
}
|
|
4719
5012
|
async function openHostUsageTranscriptCursor(input) {
|
|
4720
5013
|
const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants5.O_RDONLY));
|
|
4721
5014
|
let source;
|
|
@@ -4784,15 +5077,12 @@ function completeLinePrefix(bytes, baseOffset) {
|
|
|
4784
5077
|
return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
|
|
4785
5078
|
}
|
|
4786
5079
|
|
|
4787
|
-
// host/relay/src/relay-quarantine-store.ts
|
|
4788
|
-
var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
|
|
4789
|
-
var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
|
|
4790
|
-
var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
|
|
4791
|
-
|
|
4792
5080
|
// host/relay/src/relay-admission-store.ts
|
|
4793
|
-
var
|
|
4794
|
-
|
|
4795
|
-
|
|
5081
|
+
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"]);
|
|
5082
|
+
|
|
5083
|
+
// host/relay/src/host-relay-config.ts
|
|
5084
|
+
var HOST_RELAY_CONFIG_MIN_BYTES = Buffer.byteLength("{}", "utf8");
|
|
5085
|
+
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");
|
|
4796
5086
|
|
|
4797
5087
|
// host/relay/src/relay-pipe-handshake.ts
|
|
4798
5088
|
var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
|
|
@@ -4867,6 +5157,7 @@ var CodexOutboxStore = class {
|
|
|
4867
5157
|
turnSelectionsDirectory;
|
|
4868
5158
|
registrationsDirectory;
|
|
4869
5159
|
cursorsDirectory;
|
|
5160
|
+
registrationInventory = new HostRegistrationInventory();
|
|
4870
5161
|
constructor(directory) {
|
|
4871
5162
|
if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
|
|
4872
5163
|
this.directory = directory;
|
|
@@ -4888,10 +5179,9 @@ var CodexOutboxStore = class {
|
|
|
4888
5179
|
await writeAtomicJson(this.entryPath(entry.submission_ref), entry);
|
|
4889
5180
|
}
|
|
4890
5181
|
async list() {
|
|
4891
|
-
await this.prepare();
|
|
4892
5182
|
const entries = [];
|
|
4893
5183
|
let malformed = 0;
|
|
4894
|
-
for (const name of await
|
|
5184
|
+
for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
|
|
4895
5185
|
if (!name.endsWith(".json")) continue;
|
|
4896
5186
|
try {
|
|
4897
5187
|
const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
|
|
@@ -4939,7 +5229,6 @@ var CodexOutboxStore = class {
|
|
|
4939
5229
|
}
|
|
4940
5230
|
async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
|
|
4941
5231
|
if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
|
|
4942
|
-
await this.prepare();
|
|
4943
5232
|
return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
|
|
4944
5233
|
}
|
|
4945
5234
|
async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
|
|
@@ -4948,6 +5237,7 @@ var CodexOutboxStore = class {
|
|
|
4948
5237
|
const path = this.activeContextPath(identity);
|
|
4949
5238
|
const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
|
|
4950
5239
|
if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
|
|
5240
|
+
await this.prepare();
|
|
4951
5241
|
await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
|
|
4952
5242
|
return true;
|
|
4953
5243
|
}
|
|
@@ -4964,7 +5254,6 @@ var CodexOutboxStore = class {
|
|
|
4964
5254
|
*/
|
|
4965
5255
|
async readRawInvocationContext(hostSourceRef, hostSessionRef) {
|
|
4966
5256
|
if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
|
|
4967
|
-
await this.prepare();
|
|
4968
5257
|
const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
|
|
4969
5258
|
return context;
|
|
4970
5259
|
}
|
|
@@ -4988,7 +5277,6 @@ var CodexOutboxStore = class {
|
|
|
4988
5277
|
async readSession(sourceRef, sessionRef) {
|
|
4989
5278
|
const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
|
|
4990
5279
|
if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
|
|
4991
|
-
await this.prepare();
|
|
4992
5280
|
return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
|
|
4993
5281
|
}
|
|
4994
5282
|
async registerTranscript(registration) {
|
|
@@ -5016,30 +5304,38 @@ var CodexOutboxStore = class {
|
|
|
5016
5304
|
}
|
|
5017
5305
|
async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
|
|
5018
5306
|
const path = this.registrationPath(hostSourceRef, hostSessionRef);
|
|
5019
|
-
await this.prepare();
|
|
5020
5307
|
const registration = await readOptionalJson2(path, validateRegistration);
|
|
5021
5308
|
if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
|
|
5022
5309
|
return registration;
|
|
5023
5310
|
}
|
|
5024
5311
|
async listTranscriptRegistrations() {
|
|
5025
|
-
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
|
|
5030
|
-
|
|
5031
|
-
|
|
5032
|
-
|
|
5033
|
-
|
|
5312
|
+
return this.registrationInventory.read(this.registrationsDirectory, async () => {
|
|
5313
|
+
const registrations = [];
|
|
5314
|
+
for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
|
|
5315
|
+
if (!name.endsWith(".json")) continue;
|
|
5316
|
+
try {
|
|
5317
|
+
const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
|
|
5318
|
+
validateRegistration(value);
|
|
5319
|
+
registrations.push(value);
|
|
5320
|
+
} catch {
|
|
5321
|
+
}
|
|
5034
5322
|
}
|
|
5035
|
-
|
|
5036
|
-
|
|
5323
|
+
return registrations.sort((left, right) => left.registered_at.localeCompare(right.registered_at));
|
|
5324
|
+
});
|
|
5037
5325
|
}
|
|
5038
5326
|
async readTranscriptCursor(registration) {
|
|
5039
5327
|
validateRegistration(registration);
|
|
5040
|
-
await this.prepare();
|
|
5041
5328
|
return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
|
|
5042
5329
|
}
|
|
5330
|
+
async transcriptCursorFingerprint(registration) {
|
|
5331
|
+
validateRegistration(registration);
|
|
5332
|
+
try {
|
|
5333
|
+
const info = await stat3(this.cursorPath(registration.host_source_ref, registration.host_session_ref), { bigint: true });
|
|
5334
|
+
return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
5335
|
+
} catch {
|
|
5336
|
+
return "missing";
|
|
5337
|
+
}
|
|
5338
|
+
}
|
|
5043
5339
|
async writeTranscriptCursor(cursor) {
|
|
5044
5340
|
validateCursor(cursor);
|
|
5045
5341
|
await this.prepare();
|
|
@@ -5050,7 +5346,6 @@ var CodexOutboxStore = class {
|
|
|
5050
5346
|
const read2 = await this.list();
|
|
5051
5347
|
const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
|
|
5052
5348
|
if (envelope !== null) return envelopeMatch(envelope);
|
|
5053
|
-
await this.prepare();
|
|
5054
5349
|
return null;
|
|
5055
5350
|
}
|
|
5056
5351
|
async hasPriorTurn(sourceRef, sessionRef) {
|
|
@@ -5120,7 +5415,7 @@ async function writeAtomicJson(path, value) {
|
|
|
5120
5415
|
await handle.close();
|
|
5121
5416
|
}
|
|
5122
5417
|
await rename2(temp, path);
|
|
5123
|
-
await syncDirectory2(
|
|
5418
|
+
await syncDirectory2(dirname7(path));
|
|
5124
5419
|
} catch (error) {
|
|
5125
5420
|
try {
|
|
5126
5421
|
await unlink3(temp);
|
|
@@ -5155,14 +5450,14 @@ async function readOptionalJson2(path, validate) {
|
|
|
5155
5450
|
async function ensureOwnerDirectory(path) {
|
|
5156
5451
|
try {
|
|
5157
5452
|
try {
|
|
5158
|
-
const stats2 = await
|
|
5453
|
+
const stats2 = await stat3(path);
|
|
5159
5454
|
if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
|
|
5160
5455
|
return;
|
|
5161
5456
|
} catch (error) {
|
|
5162
5457
|
if (!isNotFound2(error)) throw error;
|
|
5163
5458
|
}
|
|
5164
5459
|
await mkdir4(path, { recursive: true, mode: 448 });
|
|
5165
|
-
const stats = await
|
|
5460
|
+
const stats = await stat3(path);
|
|
5166
5461
|
if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
|
|
5167
5462
|
} catch (error) {
|
|
5168
5463
|
if (error instanceof CodexHostAdapterError) throw error;
|
|
@@ -5492,32 +5787,51 @@ function decodeTokenUsage(value) {
|
|
|
5492
5787
|
}
|
|
5493
5788
|
function decodeResponseItem(payload, ordinal, timestamp3) {
|
|
5494
5789
|
if (payload.type !== "message" || payload.role !== "user") return { kind: "ignored", ordinal, timestamp: timestamp3 };
|
|
5495
|
-
const
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
|
|
5790
|
+
const attribution = userMessageAttribution(payload.internal_chat_message_metadata_passthrough);
|
|
5791
|
+
if (attribution === null) return { kind: "ignored", ordinal, timestamp: timestamp3 };
|
|
5792
|
+
const prompt = userTextContent(payload.content, attribution.content_item_kinds);
|
|
5793
|
+
if (prompt === null) return { kind: "ignored", ordinal, timestamp: timestamp3 };
|
|
5499
5794
|
return {
|
|
5500
5795
|
kind: "user_text",
|
|
5501
5796
|
ordinal,
|
|
5502
5797
|
timestamp: timestamp3,
|
|
5503
|
-
prompt,
|
|
5504
|
-
content_item_kind:
|
|
5798
|
+
prompt: prompt.text,
|
|
5799
|
+
content_item_kind: prompt.kind,
|
|
5505
5800
|
message_id: safeRef3(payload.id, "Codex user message identity is invalid."),
|
|
5506
|
-
turn_id: safeRef3(
|
|
5801
|
+
turn_id: safeRef3(attribution.turn_id, "Codex user message task identity is invalid.")
|
|
5507
5802
|
};
|
|
5508
5803
|
}
|
|
5509
|
-
function
|
|
5510
|
-
|
|
5804
|
+
function userMessageAttribution(value) {
|
|
5805
|
+
if (!isRecord7(value)) return null;
|
|
5806
|
+
if (typeof value.turn_id !== "string" || !SAFE_REF5.test(value.turn_id)) return null;
|
|
5807
|
+
return { turn_id: value.turn_id, content_item_kinds: Array.isArray(value.content_item_kinds) ? value.content_item_kinds : void 0 };
|
|
5511
5808
|
}
|
|
5512
|
-
function
|
|
5513
|
-
if (!isRecord7(value) || !Array.isArray(value.content_item_kinds)) reject("Codex user message provenance is malformed.");
|
|
5514
|
-
return { ...value, content_item_kinds: value.content_item_kinds };
|
|
5515
|
-
}
|
|
5516
|
-
function userTextContent(value) {
|
|
5809
|
+
function userTextContent(value, kinds) {
|
|
5517
5810
|
if (!Array.isArray(value)) reject(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
|
|
5518
|
-
if (
|
|
5519
|
-
|
|
5520
|
-
|
|
5811
|
+
if (kinds === void 0) {
|
|
5812
|
+
if (value.length !== 1) return null;
|
|
5813
|
+
return { text: userTextEntry(value[0]), kind: "user.text" };
|
|
5814
|
+
}
|
|
5815
|
+
if (kinds.length !== value.length) return null;
|
|
5816
|
+
const match = singleAlignedTextKind(kinds);
|
|
5817
|
+
if (match === null) return null;
|
|
5818
|
+
if (kinds.length === 1) return { text: userTextEntry(value[match.index]), kind: match.kind };
|
|
5819
|
+
if (!isRecord7(value[match.index]) || value[match.index].type !== "input_text") return null;
|
|
5820
|
+
return { text: boundedText2(value[match.index].text, MAX_PROMPT_BYTES, "Codex user text is invalid."), kind: match.kind };
|
|
5821
|
+
}
|
|
5822
|
+
function singleAlignedTextKind(kinds) {
|
|
5823
|
+
let match = null;
|
|
5824
|
+
for (let index = 0; index < kinds.length; index += 1) {
|
|
5825
|
+
const kind = kinds[index];
|
|
5826
|
+
if (kind !== "user.text" && kind !== "goal.internal_context") continue;
|
|
5827
|
+
if (match !== null) return null;
|
|
5828
|
+
match = { index, kind };
|
|
5829
|
+
}
|
|
5830
|
+
return match;
|
|
5831
|
+
}
|
|
5832
|
+
function userTextEntry(value) {
|
|
5833
|
+
if (!isRecord7(value) || value.type !== "input_text") reject(`Codex user text content is malformed (${refusalFact("item_type", isRecord7(value) ? value.type : typeof value, "input_text")}).`);
|
|
5834
|
+
return boundedText2(value.text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
|
|
5521
5835
|
}
|
|
5522
5836
|
function safeOrdinal(value) {
|
|
5523
5837
|
if (!Number.isSafeInteger(value) || Number(value) < 0) reject("Codex transcript ordinal is invalid.");
|
|
@@ -5624,9 +5938,16 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
5624
5938
|
transcriptPathOf(registration) {
|
|
5625
5939
|
return registration.transcript_path;
|
|
5626
5940
|
}
|
|
5941
|
+
registrationKey(registration) {
|
|
5942
|
+
return `${registration.host_source_ref}\0${registration.host_session_ref}`;
|
|
5943
|
+
}
|
|
5627
5944
|
async listRegistrations() {
|
|
5628
5945
|
return this.store.listTranscriptRegistrations();
|
|
5629
5946
|
}
|
|
5947
|
+
async scanFingerprint(registration) {
|
|
5948
|
+
const transcript = await super.scanFingerprint(registration);
|
|
5949
|
+
return transcript === null ? null : `${transcript}|${await this.store.transcriptCursorFingerprint(registration)}`;
|
|
5950
|
+
}
|
|
5630
5951
|
async scanOpened(handle, registration) {
|
|
5631
5952
|
const { size, device, inode } = await ownedCodexTranscriptFile(handle);
|
|
5632
5953
|
const preflight = await this.preflight(registration, handle, size, device, inode);
|
|
@@ -5636,7 +5957,7 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
5636
5957
|
if (complete === "empty" || complete === "partial") {
|
|
5637
5958
|
return { records: 0, enqueued: 0, quarantined: false };
|
|
5638
5959
|
}
|
|
5639
|
-
return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
|
|
5960
|
+
return { ...await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode), retry: preflight.cursor.offset + complete.length < size };
|
|
5640
5961
|
}
|
|
5641
5962
|
async scanFailed(handle, registration, error) {
|
|
5642
5963
|
this.diagnostic("watcher_scan_failed", codexTranscriptScanFailureKind(error));
|
|
@@ -5955,11 +6276,14 @@ function assertRecordSequence(registration, cursor, records, lastOrdinal, record
|
|
|
5955
6276
|
}
|
|
5956
6277
|
|
|
5957
6278
|
// host/codex/src/codex-producer-runtime.ts
|
|
5958
|
-
|
|
5959
|
-
|
|
5960
|
-
outbox_dir:
|
|
6279
|
+
function createCodexProducerWatcher(outboxDir) {
|
|
6280
|
+
return new CodexTranscriptWatcher({
|
|
6281
|
+
outbox_dir: outboxDir,
|
|
5961
6282
|
diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
|
|
5962
|
-
})
|
|
6283
|
+
});
|
|
6284
|
+
}
|
|
6285
|
+
async function drainCodexProducerOnce(options, signal) {
|
|
6286
|
+
const scan = await (options.watcher ?? createCodexProducerWatcher(options.outbox_dir)).scanOnce(signal).catch((error) => {
|
|
5963
6287
|
writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
|
|
5964
6288
|
throw error;
|
|
5965
6289
|
});
|
|
@@ -5974,17 +6298,34 @@ var CodexUsageFactsCapturer = class {
|
|
|
5974
6298
|
usage;
|
|
5975
6299
|
now;
|
|
5976
6300
|
registrations;
|
|
6301
|
+
idleGate;
|
|
5977
6302
|
constructor(options) {
|
|
5978
6303
|
this.sources = new CodexOutboxStore(options.outbox_dir);
|
|
5979
6304
|
this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
|
|
5980
6305
|
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
5981
6306
|
this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
|
|
6307
|
+
this.idleGate = new HostUsageIdleGate();
|
|
5982
6308
|
}
|
|
5983
6309
|
async captureNext() {
|
|
5984
6310
|
const registrations = await this.sources.listTranscriptRegistrations();
|
|
5985
6311
|
return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
|
|
5986
6312
|
}
|
|
5987
6313
|
async captureRegistration(registration) {
|
|
6314
|
+
const idleKey = `${registration.host_source_ref}\0${registration.host_session_ref}`;
|
|
6315
|
+
const transcriptKey = `${idleKey}\0transcript`;
|
|
6316
|
+
const stateKey = `${idleKey}\0state`;
|
|
6317
|
+
const transcriptCheck = await this.idleGate.checkUnchanged(transcriptKey, registration.transcript_path);
|
|
6318
|
+
let stateCheck;
|
|
6319
|
+
if (transcriptCheck.unchanged) {
|
|
6320
|
+
stateCheck = await this.idleGate.checkUnchanged(stateKey, this.usage.statePath("codex", registration.host_source_ref, registration.host_session_ref));
|
|
6321
|
+
if (stateCheck.unchanged) return false;
|
|
6322
|
+
}
|
|
6323
|
+
const captured = await this.scanRegistration(registration);
|
|
6324
|
+
this.idleGate.confirmUnchanged(transcriptKey, transcriptCheck.signature);
|
|
6325
|
+
if (stateCheck !== void 0) this.idleGate.confirmUnchanged(stateKey, stateCheck.signature);
|
|
6326
|
+
return captured;
|
|
6327
|
+
}
|
|
6328
|
+
async scanRegistration(registration) {
|
|
5988
6329
|
const prepared = await openHostUsageTranscriptCursor({
|
|
5989
6330
|
path: registration.transcript_path,
|
|
5990
6331
|
producer: "codex",
|
|
@@ -6201,7 +6542,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
|
|
|
6201
6542
|
producer_id: "codex",
|
|
6202
6543
|
extra_paths: [CODEX_SESSIONS_ROOT],
|
|
6203
6544
|
config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
|
|
6204
|
-
runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
|
|
6545
|
+
runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createCodexProducerWatcher(config.outbox_dir) }),
|
|
6205
6546
|
drain: drainCodexProducerOnce,
|
|
6206
6547
|
background: (config, signal, dependencies) => {
|
|
6207
6548
|
const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });
|