@corca-org/ceal-host-win32-x64 1.0.21 → 1.0.22
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/bin/ceal-host.exe +0 -0
- package/libexec/ceal-host/claude-hook.mjs +2457 -470
- package/libexec/ceal-host/claude-invocation-authentication.mjs +2664 -593
- package/libexec/ceal-host/claude-producer.mjs +2464 -479
- package/libexec/ceal-host/codex-hook.mjs +2527 -544
- package/libexec/ceal-host/codex-invocation-authentication.mjs +3052 -960
- package/libexec/ceal-host/codex-producer.mjs +2426 -444
- package/libexec/ceal-host/control.mjs +6402 -3340
- package/libexec/ceal-host/relay.mjs +864 -399
- package/package.json +1 -1
- package/share/ceal-host/bundle-manifest.json +12 -12
- package/share/ceal-host/bundle-manifest.sigstore.json +1 -1
|
@@ -30,7 +30,7 @@ function isPlainRecord(value) {
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
// packages/ceal-client-protocol/src/client-wire-contract.ts
|
|
33
|
-
import { createHash } from "node:crypto";
|
|
33
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
34
34
|
|
|
35
35
|
// packages/ceal-client-protocol/client-wire-contract.json
|
|
36
36
|
var client_wire_contract_default = {
|
|
@@ -51,7 +51,7 @@ var client_wire_contract_default = {
|
|
|
51
51
|
ordering: "utf16_code_unit_ascending"
|
|
52
52
|
},
|
|
53
53
|
artifact_descriptor: {
|
|
54
|
-
operation_contract_bundle_schema_name: "ceal.
|
|
54
|
+
operation_contract_bundle_schema_name: "ceal.operation_contract_bundle_v2",
|
|
55
55
|
operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
|
|
56
56
|
schema_name: "ceal.verified_artifact_descriptor",
|
|
57
57
|
fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
|
|
@@ -76,7 +76,7 @@ var client_wire_contract_default = {
|
|
|
76
76
|
},
|
|
77
77
|
command_request: {
|
|
78
78
|
schema_name: "ceal.command_request",
|
|
79
|
-
fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
|
|
79
|
+
fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
|
|
80
80
|
absolute_transport_max_bytes: 65536
|
|
81
81
|
},
|
|
82
82
|
command_resolution: {
|
|
@@ -122,8 +122,9 @@ var client_wire_contract_default = {
|
|
|
122
122
|
},
|
|
123
123
|
command_response: {
|
|
124
124
|
schema_name: "ceal.command_response",
|
|
125
|
-
fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
|
|
125
|
+
fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
|
|
126
126
|
descriptor_field: "verified_artifact",
|
|
127
|
+
request_context_field: "request_context",
|
|
127
128
|
required_fields: [
|
|
128
129
|
"schema_version",
|
|
129
130
|
"exit_code",
|
|
@@ -133,7 +134,8 @@ var client_wire_contract_default = {
|
|
|
133
134
|
"operation_id",
|
|
134
135
|
"visible_output_max_bytes",
|
|
135
136
|
"local_delivery",
|
|
136
|
-
"verified_artifact"
|
|
137
|
+
"verified_artifact",
|
|
138
|
+
"request_context"
|
|
137
139
|
],
|
|
138
140
|
bare_document_fields: [
|
|
139
141
|
"invocation",
|
|
@@ -154,7 +156,7 @@ var client_wire_contract_default = {
|
|
|
154
156
|
],
|
|
155
157
|
exit_code_max: 125,
|
|
156
158
|
bare_document_max_bytes: 65536,
|
|
157
|
-
complete_max_bytes:
|
|
159
|
+
complete_max_bytes: 66195
|
|
158
160
|
},
|
|
159
161
|
host_invocation_authentication: {
|
|
160
162
|
request_schema_name: "ceal.host_invocation_authentication_request",
|
|
@@ -168,6 +170,14 @@ var client_wire_contract_default = {
|
|
|
168
170
|
"context_token",
|
|
169
171
|
"expires_at"
|
|
170
172
|
],
|
|
173
|
+
refusal_schema_name: "ceal.host_invocation_authentication_refusal",
|
|
174
|
+
refusal_fields: [
|
|
175
|
+
"schema_version",
|
|
176
|
+
"ok",
|
|
177
|
+
"code",
|
|
178
|
+
"reason",
|
|
179
|
+
"gateway_status"
|
|
180
|
+
],
|
|
171
181
|
client_nonce: {
|
|
172
182
|
character_class_source: "A-Za-z0-9_-",
|
|
173
183
|
encoded_characters: 43
|
|
@@ -206,6 +216,8 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
|
|
|
206
216
|
"choose_new_output_path",
|
|
207
217
|
"choose_new_idempotency_key",
|
|
208
218
|
"restart_search",
|
|
219
|
+
// The requested temporal key is absent on some observed rows; repeating the same interval without `order` can return those rows.
|
|
220
|
+
"search_without_order",
|
|
209
221
|
"repeat_original_arguments",
|
|
210
222
|
// The occurrence this call addressed is settled and cannot move again -- a
|
|
211
223
|
// denied effect approval, an expired continuation -- so the caller runs the
|
|
@@ -264,6 +276,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
|
|
|
264
276
|
// The command needs caller-owned local materialization (for example an
|
|
265
277
|
// @path file) before the Gateway can receive the argument.
|
|
266
278
|
"materialize_local_argument",
|
|
279
|
+
// A missing or stale local Host bundle is repaired through its installed lifecycle and discovery owners.
|
|
280
|
+
"install_ceal_host",
|
|
281
|
+
// An explicit Client store override points at a missing file; unsetting it selects the one canonical default store without creating a second credential store.
|
|
282
|
+
"unset_context_store_path",
|
|
283
|
+
// The producer app must reload its installed Host hook before it can start a conversation with invocation context.
|
|
284
|
+
"restart_producer_app",
|
|
267
285
|
// A peer's derived schema identifier changed with its field set; install or
|
|
268
286
|
// upgrade the CLI and Host Relay to the Gateway's release before retrying.
|
|
269
287
|
"upgrade_ceal_client"
|
|
@@ -372,7 +390,6 @@ var NON_MODEL_ACTION_TO_MODEL_ACTION = Object.freeze({
|
|
|
372
390
|
});
|
|
373
391
|
var RETRY_PROMISE_NEXT_ACTIONS = ["retry", "retry_after"];
|
|
374
392
|
var RETRY_PROMISE = new Set(RETRY_PROMISE_NEXT_ACTIONS);
|
|
375
|
-
var RECOVERABLE = new Set(CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS);
|
|
376
393
|
var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
|
|
377
394
|
provider_permission: "ask_admin",
|
|
378
395
|
access_level: "ask_admin",
|
|
@@ -397,9 +414,9 @@ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "s
|
|
|
397
414
|
var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
|
|
398
415
|
var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
|
|
399
416
|
var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
|
|
400
|
-
var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "scope_limit_exceeded"]);
|
|
417
|
+
var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
|
|
401
418
|
var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
|
|
402
|
-
var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable"]);
|
|
419
|
+
var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
|
|
403
420
|
var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
|
|
404
421
|
var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
|
|
405
422
|
var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
|
|
@@ -470,10 +487,10 @@ function assertSafeJsonArray(value, options, depth, count) {
|
|
|
470
487
|
if (value.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
|
|
471
488
|
for (const item of value) assertSafeJsonValue(item, options, depth + 1, count);
|
|
472
489
|
}
|
|
473
|
-
function assertSafeJsonRecord(
|
|
474
|
-
const entries = Object.entries(
|
|
490
|
+
function assertSafeJsonRecord(record6, options, depth, count) {
|
|
491
|
+
const entries = Object.entries(record6);
|
|
475
492
|
if (entries.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
|
|
476
|
-
const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(
|
|
493
|
+
const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record6.fields) : null;
|
|
477
494
|
for (const [key, child] of entries) {
|
|
478
495
|
if (key === "credential_material_included" && child !== false) invalidByContext(options);
|
|
479
496
|
if (!isSafeNegativeMaterialAssertion(key, child)) assertSafeJsonKey(key, options);
|
|
@@ -523,16 +540,21 @@ function isSafeExternalHttpsUrl(value) {
|
|
|
523
540
|
return false;
|
|
524
541
|
}
|
|
525
542
|
}
|
|
543
|
+
var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE = "^https://[^\\s/@?#]+(?:[/?#][^\\s]*)?$";
|
|
544
|
+
var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN = new RegExp(SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE, "u");
|
|
526
545
|
function isSafeExternalHttpsUrlInput(value) {
|
|
527
546
|
return typeof value === "string" && byteLength(value) <= 2048;
|
|
528
547
|
}
|
|
529
|
-
function isSafeExternalHttpsUrlShape(url) {
|
|
530
|
-
return url.protocol === "https:" && url.username === "" && url.password === "" && url.hash === "";
|
|
548
|
+
function isSafeExternalHttpsUrlShape(url, allowFragment = false) {
|
|
549
|
+
return url.protocol === "https:" && url.hostname.length > 0 && url.username === "" && url.password === "" && (allowFragment || url.hash === "");
|
|
531
550
|
}
|
|
532
551
|
function isSafeResultContent(value, key) {
|
|
533
552
|
const maximum = key === "text" ? 8192 : 1024;
|
|
534
553
|
return typeof value === "string" && byteLength(value) <= maximum && firstDisallowedControl(value, "multi_line") === null;
|
|
535
554
|
}
|
|
555
|
+
function requireSafeRef(value) {
|
|
556
|
+
if (typeof value !== "string" || !SAFE_REF.test(value)) invalidRequestOrResponse();
|
|
557
|
+
}
|
|
536
558
|
var CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES = 512;
|
|
537
559
|
function normalizeCealSingleLineText(value) {
|
|
538
560
|
return value.split("").map((character) => hasControlCharacter(character) ? " " : character).join("").trim();
|
|
@@ -649,6 +671,7 @@ function cut(text) {
|
|
|
649
671
|
|
|
650
672
|
// packages/ceal-client-protocol/src/operation-validation-primitives.ts
|
|
651
673
|
var ISO_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?([Zz]|([+-])(\d{2}):(\d{2}))$/u;
|
|
674
|
+
var EXPANDED_CANONICAL_ISO_TIMESTAMP = /^([+-])(\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/u;
|
|
652
675
|
var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
|
|
653
676
|
var CEAL_CALENDAR_DATE = new RegExp(CEAL_CALENDAR_DATE_PATTERN_SOURCE, "u");
|
|
654
677
|
function isOperationRecord(value) {
|
|
@@ -659,13 +682,46 @@ function isOperationRecord(value) {
|
|
|
659
682
|
function requireOperationRecord(value, message) {
|
|
660
683
|
if (!isOperationRecord(value)) throw new TypeError(message);
|
|
661
684
|
}
|
|
685
|
+
function requireExactOperationKeys(value, required, optional = [], message = "Operation contract has an invalid shape.") {
|
|
686
|
+
const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
|
|
687
|
+
if (required.some((key) => !Object.hasOwn(value, key))) throw new TypeError(message);
|
|
688
|
+
if (Object.keys(value).some((key) => !allowed.has(key))) throw new TypeError(message);
|
|
689
|
+
}
|
|
662
690
|
function requireClosedValue(value, members, message) {
|
|
663
691
|
if (typeof value !== "string" || !members.includes(value)) throw new TypeError(message);
|
|
664
692
|
}
|
|
665
693
|
function isCealIsoTimestamp(value) {
|
|
666
694
|
return typeof value === "string" && parseCealIsoTimestamp(value) !== null;
|
|
667
695
|
}
|
|
696
|
+
function canonicalCealIsoTimestamp(epochNanoseconds) {
|
|
697
|
+
const wholeSeconds = floorDivide(epochNanoseconds, 1000000000n);
|
|
698
|
+
const fractionalNanoseconds = epochNanoseconds - wholeSeconds * 1000000000n;
|
|
699
|
+
const utc = new Date(Number(wholeSeconds * 1000n));
|
|
700
|
+
const date = utc.toISOString().split(".")[0];
|
|
701
|
+
if (date === void 0) throw new TypeError("Ceal timestamp formatter returned an invalid ISO string");
|
|
702
|
+
const fraction = fractionalNanoseconds.toString().padStart(9, "0").replace(/0+$/u, "").padEnd(3, "0");
|
|
703
|
+
return date + "." + fraction + "Z";
|
|
704
|
+
}
|
|
705
|
+
var CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE = "0000-01-01T00:00:00.000000000+23:59";
|
|
706
|
+
var CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE = "9999-12-31T23:59:59.999999999-23:59";
|
|
707
|
+
var CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE);
|
|
708
|
+
var CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE);
|
|
709
|
+
var CEAL_INSTANT_INDEX_SPAN = CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS - CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS;
|
|
710
|
+
var CEAL_INSTANT_INDEX_KEY_WIDTH = CEAL_INSTANT_INDEX_SPAN.toString().length;
|
|
711
|
+
var CEAL_INSTANT_INDEX_KEY_PATTERN = new RegExp(`^\\d{${CEAL_INSTANT_INDEX_KEY_WIDTH}}$`, "u");
|
|
712
|
+
function requiredTimestampEpochNanoseconds(value) {
|
|
713
|
+
const parsed = parseFourDigitCealIsoTimestamp(value);
|
|
714
|
+
if (parsed === null) throw new Error("Ceal instant-index range basis is outside the timestamp grammar");
|
|
715
|
+
return parsed.epochNanoseconds;
|
|
716
|
+
}
|
|
668
717
|
function parseCealIsoTimestamp(value) {
|
|
718
|
+
const ordinary = parseFourDigitCealIsoTimestamp(value);
|
|
719
|
+
if (ordinary !== null) return ordinary;
|
|
720
|
+
const expanded = parseExpandedCanonicalCealIsoTimestamp(value);
|
|
721
|
+
if (expanded === null || expanded.epochNanoseconds < CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS || expanded.epochNanoseconds > CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS) return null;
|
|
722
|
+
return canonicalCealIsoTimestamp(expanded.epochNanoseconds) === value ? expanded : null;
|
|
723
|
+
}
|
|
724
|
+
function parseFourDigitCealIsoTimestamp(value) {
|
|
669
725
|
const fields = parseCealIsoTimestampFields(value);
|
|
670
726
|
if (fields === null || !validCalendarDate(fields) || !validClockTime(fields) || !validUtcOffset(fields)) return null;
|
|
671
727
|
const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
|
|
@@ -674,6 +730,28 @@ function parseCealIsoTimestamp(value) {
|
|
|
674
730
|
epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
|
|
675
731
|
};
|
|
676
732
|
}
|
|
733
|
+
function parseExpandedCanonicalCealIsoTimestamp(value) {
|
|
734
|
+
const match = EXPANDED_CANONICAL_ISO_TIMESTAMP.exec(value);
|
|
735
|
+
if (match === null) return null;
|
|
736
|
+
const fields = {
|
|
737
|
+
year: (match[1] === "-" ? -1 : 1) * Number(match[2]),
|
|
738
|
+
month: Number(match[3]),
|
|
739
|
+
day: Number(match[4]),
|
|
740
|
+
hour: Number(match[5]),
|
|
741
|
+
minute: Number(match[6]),
|
|
742
|
+
second: Number(match[7]),
|
|
743
|
+
fraction: match[8] ?? "",
|
|
744
|
+
offsetSign: 0,
|
|
745
|
+
offsetHour: 0,
|
|
746
|
+
offsetMinute: 0
|
|
747
|
+
};
|
|
748
|
+
if (!validCalendarDate(fields) || !validClockTime(fields)) return null;
|
|
749
|
+
const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
|
|
750
|
+
if (!Number.isFinite(epochMilliseconds)) return null;
|
|
751
|
+
return {
|
|
752
|
+
epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
|
|
753
|
+
};
|
|
754
|
+
}
|
|
677
755
|
function parseCealIsoTimestampFields(value) {
|
|
678
756
|
const match = ISO_TIMESTAMP.exec(value);
|
|
679
757
|
if (match === null) return null;
|
|
@@ -706,6 +784,10 @@ function cealFieldsEpochMilliseconds(fields) {
|
|
|
706
784
|
const offsetMilliseconds = fields.offsetSign * (fields.offsetHour * 60 + fields.offsetMinute) * 6e4;
|
|
707
785
|
return localMilliseconds - offsetMilliseconds;
|
|
708
786
|
}
|
|
787
|
+
function floorDivide(value, divisor) {
|
|
788
|
+
const quotient = value / divisor;
|
|
789
|
+
return value % divisor < 0n ? quotient - 1n : quotient;
|
|
790
|
+
}
|
|
709
791
|
function daysInMonth(year, month) {
|
|
710
792
|
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
711
793
|
return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
|
|
@@ -723,6 +805,9 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
|
|
|
723
805
|
var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
|
|
724
806
|
var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
|
|
725
807
|
var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
|
|
808
|
+
var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
|
|
809
|
+
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.";
|
|
810
|
+
var HOST_CONTEXT_UNAVAILABLE = "The Host could not select or activate the current recorded turn. This does not explain why or prove ephemerality. For an independently identified ephemeral Codex side conversation, invoke the command as `ceal --standalone ...`; it uses the local Ceal session and Gateway permissions without Host session/turn audit linkage. Host refusal never switches modes. For intended Host calls, restart the producer and start a new conversation; report the error if it persists.";
|
|
726
811
|
var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
|
|
727
812
|
function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
|
|
728
813
|
return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
|
|
@@ -748,6 +833,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
748
833
|
refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
749
834
|
refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
750
835
|
refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
836
|
+
person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
|
|
837
|
+
principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
|
|
751
838
|
refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
752
839
|
refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
753
840
|
session_store_unwritable: guidance("The Ceal client could not write its local session store; the operating system refused the write (EACCES, EPERM, or EROFS). rerun_outside_agent_sandbox reruns it with escalated execution.", "rerun_outside_agent_sandbox", 500),
|
|
@@ -760,8 +847,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
760
847
|
response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
|
|
761
848
|
request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
|
|
762
849
|
request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
|
|
850
|
+
resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
|
|
763
851
|
gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
|
|
764
|
-
contract_mismatch: guidance(
|
|
852
|
+
contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
|
|
765
853
|
// `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
|
|
766
854
|
// (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
|
|
767
855
|
// when the wait ends still unserved, moved from the `localFailureText` default branch.
|
|
@@ -773,6 +861,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
773
861
|
// Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
|
|
774
862
|
// the client variant of this sentence in `localFailureText` was retired when the client started reading this table.
|
|
775
863
|
request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
|
|
864
|
+
gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
|
|
776
865
|
// Restored verbatim from the retired `localFailureText` `unknown_outcome`
|
|
777
866
|
// case: the outcome is unknown, so a read may be retried while a write
|
|
778
867
|
// must receipt-check first. Collapsing both to "do not repeat the call"
|
|
@@ -858,23 +947,24 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
858
947
|
// Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
|
|
859
948
|
// in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
|
|
860
949
|
// is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
|
|
861
|
-
// and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`).
|
|
862
|
-
//
|
|
950
|
+
// and `retryable` from `hostAuthenticationFailureForCause` (`failure.nextAction == "retry"`). Cause-specific
|
|
951
|
+
// sentences carry the retired policy remedies; `gateway_refused` reuses the release-upgrade guidance above.
|
|
952
|
+
// Statuses are the
|
|
863
953
|
// Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
|
|
864
954
|
// `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
|
|
865
955
|
host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
|
|
866
956
|
host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
|
|
867
957
|
host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
|
|
868
|
-
//
|
|
869
|
-
//
|
|
870
|
-
host_context_unavailable: guidance(
|
|
958
|
+
// The bounded Host reason does not prove ephemerality. A Host refusal never
|
|
959
|
+
// changes mode; standalone remains the separate Client authority path.
|
|
960
|
+
host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
|
|
871
961
|
host_invocation_context_stale: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
|
|
872
962
|
host_invocation_context_expired: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 401, true),
|
|
873
963
|
host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
|
|
874
964
|
host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
|
|
875
965
|
host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
|
|
876
966
|
host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
|
|
877
|
-
host_mint_gateway_refused: guidance(
|
|
967
|
+
host_mint_gateway_refused: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
|
|
878
968
|
host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
|
|
879
969
|
// Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
|
|
880
970
|
// producer-frame fault names the administrator repair step.
|
|
@@ -882,10 +972,10 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
882
972
|
// Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
|
|
883
973
|
// sandboxed Relay socket names the run-alone retry.
|
|
884
974
|
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),
|
|
885
|
-
host_relay_unavailable: guidance(
|
|
975
|
+
host_relay_unavailable: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 503),
|
|
886
976
|
host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
|
|
887
977
|
host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
|
|
888
|
-
host_relay_failed: guidance(
|
|
978
|
+
host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
|
|
889
979
|
host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
|
|
890
980
|
});
|
|
891
981
|
function cealFailureGuidanceForCode(code2) {
|
|
@@ -895,6 +985,154 @@ function cealFailureGuidanceForCode(code2) {
|
|
|
895
985
|
}
|
|
896
986
|
var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
|
|
897
987
|
|
|
988
|
+
// packages/ceal-client-protocol/src/request-validation-primitives.ts
|
|
989
|
+
import { createHash } from "node:crypto";
|
|
990
|
+
|
|
991
|
+
// packages/ceal-client-protocol/src/operation-withheld-cause.ts
|
|
992
|
+
var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
|
|
993
|
+
|
|
994
|
+
// packages/ceal-client-protocol/src/operation-contract-types.ts
|
|
995
|
+
var CEAL_JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
|
|
996
|
+
var CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION = "ceal.operation_descriptor.v1";
|
|
997
|
+
var CEAL_OPERATION_ERROR_SCHEMA_VERSION = "ceal.operation_error.v1";
|
|
998
|
+
var CEAL_ARTIFACT_STAGE_TERMINALS = vocabulary(["chunk_accepted", "artifact_ready", "idempotency_replayed"]);
|
|
999
|
+
var CEAL_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
|
|
1000
|
+
var CEAL_JSON_SCHEMA_TYPES = vocabulary(["object", "array", "string", "integer", "number", "boolean", "null"]);
|
|
1001
|
+
var OBSERVATION_POSTURES = vocabulary(["direct_readback", "approved_no_readback", "operator_mediated", "excluded"]);
|
|
1002
|
+
var EFFECT_DOMAINS = vocabulary(["none", "gateway_state", "provider", "external_world"]);
|
|
1003
|
+
var SAFETY_CLASSES = vocabulary(["routine", "sensitive", "high_impact"]);
|
|
1004
|
+
var IDEMPOTENCY_CLASSES = vocabulary(["idempotent", "conditionally_idempotent", "non_idempotent"]);
|
|
1005
|
+
var REVERSIBILITY_CLASSES = vocabulary(["none", "reversible", "compensatable", "irreversible"]);
|
|
1006
|
+
var COMPENSATION_OWNERS = vocabulary(["none", "connector", "operator"]);
|
|
1007
|
+
var CANCELLATION_BOUNDARIES = vocabulary(["before_admission", "before_handoff", "after_handoff_reconcile"]);
|
|
1008
|
+
var HANDOFF_CLASSES = vocabulary(["not_applicable", "submission", "effect"]);
|
|
1009
|
+
var AUTHORITATIVE_READBACK_CLASSES = vocabulary(["required", "unavailable"]);
|
|
1010
|
+
var PROVIDER_READBACK_CLASSES = vocabulary(["required", "not_available", "not_applicable"]);
|
|
1011
|
+
var RECONCILIATION_CLASSES = vocabulary(["none", "automatic", "operator"]);
|
|
1012
|
+
var NO_READBACK_APPROVAL_CLASSES = vocabulary(["not_applicable", "explicit", "operator"]);
|
|
1013
|
+
var REPLAY_PREREQUISITES = vocabulary(["never", "fresh_admission", "reconciled_non_application", "operator_approval"]);
|
|
1014
|
+
var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
|
|
1015
|
+
var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
|
|
1016
|
+
var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
|
|
1017
|
+
var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
|
|
1018
|
+
var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
|
|
1019
|
+
var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
|
|
1020
|
+
var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
|
|
1021
|
+
var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
|
|
1022
|
+
var CEAL_OPERATION_RECOVERY_STATUSES = vocabulary(["not_started", "active", "completed"]);
|
|
1023
|
+
var CEAL_OPERATION_PROVIDER_READBACK_AVAILABILITY = vocabulary(["not_started", "not_applicable", "not_available", "pending", "available"]);
|
|
1024
|
+
var CEAL_OPERATION_OFFERED_HANDOFF_STATES = vocabulary(["accepted", "rejected", "unknown"]);
|
|
1025
|
+
var CEAL_OPERATION_RECEIPT_AUTHORITY_KEYS = Object.freeze(["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]);
|
|
1026
|
+
var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
|
|
1027
|
+
"approval_not_required_by_policy",
|
|
1028
|
+
"interactive_pending",
|
|
1029
|
+
"interactive_granted",
|
|
1030
|
+
"interactive_denied",
|
|
1031
|
+
"interactive_expired",
|
|
1032
|
+
"interactive_unavailable"
|
|
1033
|
+
]);
|
|
1034
|
+
|
|
1035
|
+
// packages/ceal-client-protocol/src/request-validation-primitives.ts
|
|
1036
|
+
var DIGEST = /^[a-f0-9]{64}$/u;
|
|
1037
|
+
var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
|
|
1038
|
+
function isCealDigest(value) {
|
|
1039
|
+
return typeof value === "string" && DIGEST.test(value);
|
|
1040
|
+
}
|
|
1041
|
+
function cealRequestSha256(value) {
|
|
1042
|
+
return createHash("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
|
|
1043
|
+
}
|
|
1044
|
+
function operationRecord(value, message) {
|
|
1045
|
+
requireOperationRecord(value, message);
|
|
1046
|
+
return value;
|
|
1047
|
+
}
|
|
1048
|
+
function invalid(message) {
|
|
1049
|
+
throw new TypeError(message);
|
|
1050
|
+
}
|
|
1051
|
+
function requirePrefixedRef(value, prefix, message) {
|
|
1052
|
+
if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
|
|
1053
|
+
}
|
|
1054
|
+
function requireSafeRef2(value, message) {
|
|
1055
|
+
try {
|
|
1056
|
+
requireSafeRef(value);
|
|
1057
|
+
} catch {
|
|
1058
|
+
invalid(message);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
// packages/ceal-client-protocol/src/request-authority.ts
|
|
1063
|
+
var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
|
|
1064
|
+
var CEAL_REQUEST_REF_MAX_CHARACTERS = 128;
|
|
1065
|
+
var CEAL_REQUEST_REF_PATTERN_SOURCE = "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$";
|
|
1066
|
+
var CEAL_REQUEST_REF_PATTERN = new RegExp(CEAL_REQUEST_REF_PATTERN_SOURCE, "u");
|
|
1067
|
+
var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
|
|
1068
|
+
var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
|
|
1069
|
+
var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
|
|
1070
|
+
var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
|
|
1071
|
+
var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
|
|
1072
|
+
var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
|
|
1073
|
+
schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
|
|
1074
|
+
ceal_request_ref: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_REF_MAX_CHARACTERS, pattern: CEAL_REQUEST_REF_PATTERN_SOURCE },
|
|
1075
|
+
created_at: { type: "string", minLength: 1, maxLength: 64 },
|
|
1076
|
+
authority: {
|
|
1077
|
+
type: "object",
|
|
1078
|
+
maxProperties: 5,
|
|
1079
|
+
additionalProperties: false,
|
|
1080
|
+
properties: {
|
|
1081
|
+
instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1082
|
+
access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1083
|
+
principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1084
|
+
execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1085
|
+
authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
|
|
1086
|
+
},
|
|
1087
|
+
required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
|
|
1088
|
+
}
|
|
1089
|
+
});
|
|
1090
|
+
var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
|
|
1091
|
+
prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1092
|
+
host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1093
|
+
host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1094
|
+
host_source_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Original authenticated Host turn reference before Gateway Request call-group identity is derived; absent for older Requests." },
|
|
1095
|
+
host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1096
|
+
host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
|
|
1097
|
+
});
|
|
1098
|
+
var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
|
|
1099
|
+
caller_call_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Gateway-minted call-group identity for a non-Host caller." },
|
|
1100
|
+
caller_call_input_sha256: { type: "string", minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$", description: "Commitment to the exact input for active non-Host identity-reuse checks; a migrated legacy call group commits to its legacy group key because the original input may no longer exist." }
|
|
1101
|
+
});
|
|
1102
|
+
var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
|
|
1103
|
+
requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
|
|
1104
|
+
device_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Device that submitted this Request through its client session, including Host turns when the authenticated Host registration carries the device; absent for older records." }
|
|
1105
|
+
});
|
|
1106
|
+
var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
|
|
1107
|
+
var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
|
|
1108
|
+
var CEAL_REQUEST_JSON_SCHEMA = {
|
|
1109
|
+
type: "object",
|
|
1110
|
+
description: "A Request has exactly one creation identity: the complete Host tuple and prompt reference, or a caller call-group identity. Caller Requests retain no prompt reference or prompt body.",
|
|
1111
|
+
maxProperties: 14,
|
|
1112
|
+
additionalProperties: false,
|
|
1113
|
+
properties: {
|
|
1114
|
+
...CEAL_REQUEST_COMMON_PROPERTIES,
|
|
1115
|
+
...CEAL_REQUEST_HOST_PROPERTIES,
|
|
1116
|
+
...CEAL_REQUEST_CALLER_PROPERTIES,
|
|
1117
|
+
...CEAL_REQUEST_OPTIONAL_PROPERTIES
|
|
1118
|
+
},
|
|
1119
|
+
required: CEAL_REQUEST_KEYS,
|
|
1120
|
+
anyOf: [
|
|
1121
|
+
{
|
|
1122
|
+
type: "object",
|
|
1123
|
+
required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
|
|
1124
|
+
properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
|
|
1125
|
+
additionalProperties: false
|
|
1126
|
+
},
|
|
1127
|
+
{
|
|
1128
|
+
type: "object",
|
|
1129
|
+
required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
|
|
1130
|
+
properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
|
|
1131
|
+
additionalProperties: false
|
|
1132
|
+
}
|
|
1133
|
+
]
|
|
1134
|
+
};
|
|
1135
|
+
|
|
898
1136
|
// packages/ceal-client-protocol/src/client-wire-contract.ts
|
|
899
1137
|
var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
|
|
900
1138
|
var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
|
|
@@ -907,7 +1145,7 @@ function deriveCealClientWireSchemaVersion(schema) {
|
|
|
907
1145
|
throw new TypeError("Client wire schema name or field set is invalid.");
|
|
908
1146
|
}
|
|
909
1147
|
const fields = schema.fields.filter((field) => field !== "schema_version").sort();
|
|
910
|
-
const hash8 =
|
|
1148
|
+
const hash8 = createHash2("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
|
|
911
1149
|
return `${schema.schema_name}.v1.${hash8}`;
|
|
912
1150
|
}
|
|
913
1151
|
var CealClientWireContractMismatchError = class extends Error {
|
|
@@ -945,57 +1183,14 @@ var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(requ
|
|
|
945
1183
|
var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
|
|
946
1184
|
var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
|
|
947
1185
|
var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
|
|
948
|
-
var CEAL_COMMAND_RESPONSE_DISCOVERY_COMMAND = response.discovery_command;
|
|
949
1186
|
var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
|
|
950
1187
|
var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
|
|
951
|
-
var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_DOCUMENT_FIELDS = Object.freeze([...response.discovery_manifest_document_fields]);
|
|
952
1188
|
var CEAL_COMMAND_RESPONSE_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
|
|
953
1189
|
var CEAL_RESOURCE_STREAM_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_schema_name, fields: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields });
|
|
954
1190
|
var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
|
|
955
1191
|
|
|
956
|
-
// packages/ceal-client-protocol/src/
|
|
957
|
-
var
|
|
958
|
-
|
|
959
|
-
// packages/ceal-client-protocol/src/operation-contract-types.ts
|
|
960
|
-
var CEAL_JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
|
|
961
|
-
var CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION = "ceal.operation_descriptor.v1";
|
|
962
|
-
var CEAL_OPERATION_ERROR_SCHEMA_VERSION = "ceal.operation_error.v1";
|
|
963
|
-
var CEAL_ARTIFACT_STAGE_TERMINALS = vocabulary(["chunk_accepted", "artifact_ready", "idempotency_replayed"]);
|
|
964
|
-
var CEAL_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
|
|
965
|
-
var CEAL_JSON_SCHEMA_TYPES = vocabulary(["object", "array", "string", "integer", "number", "boolean", "null"]);
|
|
966
|
-
var OBSERVATION_POSTURES = vocabulary(["direct_readback", "approved_no_readback", "operator_mediated", "excluded"]);
|
|
967
|
-
var EFFECT_DOMAINS = vocabulary(["none", "gateway_state", "provider", "external_world"]);
|
|
968
|
-
var SAFETY_CLASSES = vocabulary(["routine", "sensitive", "high_impact"]);
|
|
969
|
-
var IDEMPOTENCY_CLASSES = vocabulary(["idempotent", "conditionally_idempotent", "non_idempotent"]);
|
|
970
|
-
var REVERSIBILITY_CLASSES = vocabulary(["none", "reversible", "compensatable", "irreversible"]);
|
|
971
|
-
var COMPENSATION_OWNERS = vocabulary(["none", "connector", "operator"]);
|
|
972
|
-
var CANCELLATION_BOUNDARIES = vocabulary(["before_admission", "before_handoff", "after_handoff_reconcile"]);
|
|
973
|
-
var HANDOFF_CLASSES = vocabulary(["not_applicable", "submission", "effect"]);
|
|
974
|
-
var AUTHORITATIVE_READBACK_CLASSES = vocabulary(["required", "unavailable"]);
|
|
975
|
-
var PROVIDER_READBACK_CLASSES = vocabulary(["required", "not_available", "not_applicable"]);
|
|
976
|
-
var RECONCILIATION_CLASSES = vocabulary(["none", "automatic", "operator"]);
|
|
977
|
-
var NO_READBACK_APPROVAL_CLASSES = vocabulary(["not_applicable", "explicit", "operator"]);
|
|
978
|
-
var REPLAY_PREREQUISITES = vocabulary(["never", "fresh_admission", "reconciled_non_application", "operator_approval"]);
|
|
979
|
-
var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
|
|
980
|
-
var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
|
|
981
|
-
var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
|
|
982
|
-
var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
|
|
983
|
-
var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
|
|
984
|
-
var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
|
|
985
|
-
var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
|
|
986
|
-
var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
|
|
987
|
-
var CEAL_OPERATION_RECOVERY_STATUSES = vocabulary(["not_started", "active", "completed"]);
|
|
988
|
-
var CEAL_OPERATION_PROVIDER_READBACK_AVAILABILITY = vocabulary(["not_started", "not_applicable", "not_available", "pending", "available"]);
|
|
989
|
-
var CEAL_OPERATION_OFFERED_HANDOFF_STATES = vocabulary(["accepted", "rejected", "unknown"]);
|
|
990
|
-
var CEAL_OPERATION_RECEIPT_AUTHORITY_KEYS = Object.freeze(["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]);
|
|
991
|
-
var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
|
|
992
|
-
"approval_not_required_by_policy",
|
|
993
|
-
"interactive_pending",
|
|
994
|
-
"interactive_granted",
|
|
995
|
-
"interactive_denied",
|
|
996
|
-
"interactive_expired",
|
|
997
|
-
"interactive_unavailable"
|
|
998
|
-
]);
|
|
1192
|
+
// packages/ceal-client-protocol/src/access-level-vocabulary.ts
|
|
1193
|
+
var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
|
|
999
1194
|
|
|
1000
1195
|
// packages/ceal-client-protocol/src/operation-access-class.ts
|
|
1001
1196
|
var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
|
|
@@ -1003,7 +1198,6 @@ var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
|
|
|
1003
1198
|
// packages/ceal-client-protocol/src/domain-vocabulary.ts
|
|
1004
1199
|
var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
|
|
1005
1200
|
var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
|
|
1006
|
-
var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
|
|
1007
1201
|
var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
|
|
1008
1202
|
var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
|
|
1009
1203
|
var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
|
|
@@ -1111,6 +1305,7 @@ var CEAL_SCHEMA_LITERALS = [
|
|
|
1111
1305
|
"ceal.gateway_write_receipt_readback.v1",
|
|
1112
1306
|
"ceal.gateway_write_request_receipt.v1",
|
|
1113
1307
|
"ceal.host_observation.v1",
|
|
1308
|
+
"ceal.host_usage_batch.v1",
|
|
1114
1309
|
"ceal.host_registration_request.v1",
|
|
1115
1310
|
"ceal.host_registration_result.v1",
|
|
1116
1311
|
CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
|
|
@@ -1139,7 +1334,6 @@ var CEAL_SCHEMA_LITERAL_SET = new Set(CEAL_SCHEMA_LITERALS);
|
|
|
1139
1334
|
import { join } from "node:path";
|
|
1140
1335
|
var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
|
|
1141
1336
|
bounded_store_sidecar: (root) => `${root}.jsonl`,
|
|
1142
|
-
gateway_audit_archive: (root) => `${root}.jsonl`,
|
|
1143
1337
|
gateway_access_group_connector_control_audit: (root) => `${root}.audit.jsonl`,
|
|
1144
1338
|
gateway_access_group_connector_scope_audit: (root) => join(root, "profile-connector-scope-audit.jsonl"),
|
|
1145
1339
|
gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
|
|
@@ -1172,6 +1366,7 @@ var CEAL_LOWERCASE_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
|
|
|
1172
1366
|
var CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN = new RegExp(`^host-registration-attempt:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
|
|
1173
1367
|
var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
|
|
1174
1368
|
var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
|
|
1369
|
+
var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
|
|
1175
1370
|
|
|
1176
1371
|
// packages/ceal-client-protocol/src/operation-result-completeness.ts
|
|
1177
1372
|
var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
|
|
@@ -1190,7 +1385,7 @@ function shellSingleQuoted(value) {
|
|
|
1190
1385
|
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
1191
1386
|
}
|
|
1192
1387
|
var CEAL_OPERATION_CONTRACT_REQUIRED_FIELDS = Object.freeze(["input_schema", "result_schema"]);
|
|
1193
|
-
var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["summary", "input_resolution"]);
|
|
1388
|
+
var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["branches", "summary", "input_resolution"]);
|
|
1194
1389
|
var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
|
|
1195
1390
|
$schema: CEAL_JSON_SCHEMA_2020_12,
|
|
1196
1391
|
$id: "https://ceal.dev/schemas/verified-artifact-descriptor.v1.schema.json",
|
|
@@ -1235,11 +1430,92 @@ var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_o
|
|
|
1235
1430
|
// packages/ceal-client-protocol/src/actor-kind.ts
|
|
1236
1431
|
var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
|
|
1237
1432
|
|
|
1433
|
+
// packages/ceal-client-protocol/src/provider-link-policy.ts
|
|
1434
|
+
var PROVIDER_LINK_RESULT_FIELDS = Object.freeze({
|
|
1435
|
+
read_row: Object.freeze({ human_link: "source_url", parent_context: Object.freeze(["thread_ref"]) }),
|
|
1436
|
+
write_result: Object.freeze({ human_links: Object.freeze(["user_openable_url", "url", "spreadsheet_url", "meet_url"]) })
|
|
1437
|
+
});
|
|
1438
|
+
var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
|
|
1439
|
+
{ provider: "slack", result_kind: "message_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "message permalink or the existing canonical workspace/channel/timestamp permalink", source: "https://docs.slack.dev/reference/methods/chat.getPermalink/" },
|
|
1440
|
+
{ provider: "slack", result_kind: "message_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "chat.getPermalink result permalink", source: "https://docs.slack.dev/reference/methods/chat.getPermalink/" },
|
|
1441
|
+
{ provider: "slack", result_kind: "message_update_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "chat.getPermalink result permalink after verified readback", source: "https://docs.slack.dev/reference/methods/chat.getPermalink/" },
|
|
1442
|
+
{ provider: "slack", result_kind: "file_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "file permalink; url_private and url_private_download are excluded", source: "https://docs.slack.dev/reference/objects/file-object/" },
|
|
1443
|
+
{ provider: "slack", result_kind: "file_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "file permalink; url_private and url_private_download are excluded", source: "https://docs.slack.dev/reference/objects/file-object/" },
|
|
1444
|
+
{ provider: "notion", result_kind: "page_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "page url matching the returned page id", source: "https://developers.notion.com/reference/page" },
|
|
1445
|
+
{ provider: "notion", result_kind: "page_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "page url matching the verified page id", source: "https://developers.notion.com/reference/page" },
|
|
1446
|
+
{ provider: "github", result_kind: "issue_pull_request_code_release_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "html_url", source: "https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28" },
|
|
1447
|
+
{ provider: "github", result_kind: "issue_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback html_url", source: "https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28" },
|
|
1448
|
+
{ provider: "github", result_kind: "issue_update_write_result", field: "url", status: "required_when_provider_supplies", provider_shape: "verified readback html_url; replay receipts omit links without provider readback", source: "https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28" },
|
|
1449
|
+
{ provider: "github", result_kind: "pull_request_review_write_result", field: "url", status: "required_when_provider_supplies", provider_shape: "submitted review html_url", source: "https://docs.github.com/en/rest/pulls/reviews" },
|
|
1450
|
+
{ provider: "github", result_kind: "comment_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "issue comment html_url from provider readback", source: "https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28" },
|
|
1451
|
+
{ provider: "google-workspace", result_kind: "drive_file_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
|
|
1452
|
+
{ provider: "google-workspace", result_kind: "calendar_event_read_row", field: "source_url", status: "required_when_provider_supplies", provider_shape: "htmlLink", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
|
|
1453
|
+
{ provider: "google-workspace", result_kind: "drive_document_calendar_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink or htmlLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
|
|
1454
|
+
{ provider: "google-workspace", result_kind: "drive_file_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
|
|
1455
|
+
{ provider: "google-workspace", result_kind: "spreadsheet_write_result", field: "spreadsheet_url", status: "required_when_provider_supplies", provider_shape: "verified readback webViewLink", source: "https://developers.google.com/workspace/drive/api/reference/rest/v3/files" },
|
|
1456
|
+
{ provider: "google-workspace", result_kind: "calendar_meet_link_write_result", field: "meet_url", status: "required_when_provider_supplies", provider_shape: "verified conferenceData entryPoint uri", source: "https://developers.google.com/workspace/calendar/api/v3/reference/events" },
|
|
1457
|
+
{ provider: "google-workspace", result_kind: "gmail_message_read_row", field: "source_url", status: "not_available", reason: "The Gmail API Message representation exposes id and threadId but no human UI URL; cite by title and date.", source: "https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.messages#Message" },
|
|
1458
|
+
{ provider: "google-workspace", result_kind: "gmail_message_write_result", field: "user_openable_url", status: "not_available", reason: "The Gmail API Message representation exposes id and threadId but no human UI URL; no URL is reconstructed.", source: "https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.messages#Message" }
|
|
1459
|
+
]);
|
|
1460
|
+
var PROVIDER_LINK_HOSTS = Object.freeze({
|
|
1461
|
+
notion: Object.freeze(["notion.so", "www.notion.so", "notion.com", "www.notion.com", "app.notion.com"]),
|
|
1462
|
+
google_workspace: Object.freeze([
|
|
1463
|
+
"calendar.google.com",
|
|
1464
|
+
"contacts.google.com",
|
|
1465
|
+
"docs.google.com",
|
|
1466
|
+
"drive.google.com",
|
|
1467
|
+
"forms.google.com",
|
|
1468
|
+
"mail.google.com",
|
|
1469
|
+
"meet.google.com",
|
|
1470
|
+
"sites.google.com",
|
|
1471
|
+
"www.google.com"
|
|
1472
|
+
])
|
|
1473
|
+
});
|
|
1474
|
+
var NOTION_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.notion);
|
|
1475
|
+
var GOOGLE_WORKSPACE_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.google_workspace);
|
|
1476
|
+
var PROVIDER_RESOURCE_SOURCE_URL_SCHEMA = Object.freeze({
|
|
1477
|
+
type: "string",
|
|
1478
|
+
minLength: 1,
|
|
1479
|
+
maxLength: 2048,
|
|
1480
|
+
pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
|
|
1481
|
+
description: "A provider-owned human link for this exact resource; include it when available. Rows without a provider UI link, such as Gmail messages, are cited by title and date."
|
|
1482
|
+
});
|
|
1483
|
+
var PROVIDER_USER_OPENABLE_URL_SCHEMA = Object.freeze({
|
|
1484
|
+
type: "string",
|
|
1485
|
+
minLength: 1,
|
|
1486
|
+
maxLength: 2048,
|
|
1487
|
+
pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
|
|
1488
|
+
description: "The provider-owned human URL for the written resource, when the provider response or verified readback supplies one. Ceal does not construct a fallback URL."
|
|
1489
|
+
});
|
|
1490
|
+
|
|
1238
1491
|
// packages/ceal-client-protocol/src/resource-row.ts
|
|
1239
1492
|
var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
|
|
1240
1493
|
var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
|
|
1241
1494
|
var CEAL_RESOURCE_SEARCH_DIRECTIONS = vocabulary(["ascending", "descending"]);
|
|
1242
|
-
var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
|
|
1495
|
+
var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
|
|
1496
|
+
"query",
|
|
1497
|
+
"modified_since",
|
|
1498
|
+
"since",
|
|
1499
|
+
"until",
|
|
1500
|
+
"filetype",
|
|
1501
|
+
"authored_by_me",
|
|
1502
|
+
"authored_by",
|
|
1503
|
+
"edited_by",
|
|
1504
|
+
"include_replies",
|
|
1505
|
+
"kinds",
|
|
1506
|
+
"container_ref",
|
|
1507
|
+
"container_refs",
|
|
1508
|
+
"container_names",
|
|
1509
|
+
"addressed_to_me",
|
|
1510
|
+
"unread",
|
|
1511
|
+
"archived",
|
|
1512
|
+
"state",
|
|
1513
|
+
"event_types",
|
|
1514
|
+
"starred",
|
|
1515
|
+
"trashed",
|
|
1516
|
+
"permission"
|
|
1517
|
+
]);
|
|
1518
|
+
var CEAL_RESOURCE_SEARCH_STATES = vocabulary(["open", "closed", "draft", "prerelease", "confirmed", "tentative", "cancelled"]);
|
|
1243
1519
|
var CEAL_RESOURCE_TIME_BASES = vocabulary(["created", "modified", "viewed"]);
|
|
1244
1520
|
var CEAL_REPOSITORY_VISIBILITIES = vocabulary(["public", "private", "internal"]);
|
|
1245
1521
|
var CEAL_ACTIVITY_V3_KINDS = vocabulary(["authored", "edited", "messaged", "responded"]);
|
|
@@ -1335,6 +1611,8 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
|
|
|
1335
1611
|
container_label: { required: true, timestamp: false },
|
|
1336
1612
|
container_ref: { required: false, timestamp: false },
|
|
1337
1613
|
source_url: { required: false, timestamp: false },
|
|
1614
|
+
thread_ref: { required: false, timestamp: false },
|
|
1615
|
+
reply_count: { required: false, timestamp: false },
|
|
1338
1616
|
source: { required: true, timestamp: false },
|
|
1339
1617
|
owner: { required: false, timestamp: false },
|
|
1340
1618
|
actor_kind: { required: false, timestamp: false },
|
|
@@ -1360,6 +1638,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
|
|
|
1360
1638
|
start: { required: false, timestamp: false },
|
|
1361
1639
|
end: { required: false, timestamp: false },
|
|
1362
1640
|
status: { required: false, timestamp: false },
|
|
1641
|
+
event_type: { required: false, timestamp: false },
|
|
1363
1642
|
snippet: { required: false, timestamp: false },
|
|
1364
1643
|
dated_notes: { required: false, timestamp: false },
|
|
1365
1644
|
state: { required: true, timestamp: false },
|
|
@@ -1423,6 +1702,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
|
|
|
1423
1702
|
"refresh_inactive",
|
|
1424
1703
|
"refresh_replayed",
|
|
1425
1704
|
"refresh_revoked",
|
|
1705
|
+
"person_inactive",
|
|
1706
|
+
"principal_inactive",
|
|
1426
1707
|
"authority_replaced",
|
|
1427
1708
|
"refresh_recovery_unavailable",
|
|
1428
1709
|
"refresh_recovery_expired",
|
|
@@ -1443,116 +1724,25 @@ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
|
|
|
1443
1724
|
var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
|
|
1444
1725
|
var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
|
|
1445
1726
|
|
|
1446
|
-
// packages/ceal-client-protocol/src/request-
|
|
1447
|
-
|
|
1448
|
-
var
|
|
1449
|
-
var
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
}
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
}
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
}
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
}
|
|
1466
|
-
|
|
1467
|
-
// packages/ceal-client-protocol/src/request-authority.ts
|
|
1468
|
-
var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
|
|
1469
|
-
var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
|
|
1470
|
-
var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
|
|
1471
|
-
var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
|
|
1472
|
-
var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
|
|
1473
|
-
var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
|
|
1474
|
-
var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
|
|
1475
|
-
schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
|
|
1476
|
-
ceal_request_ref: { type: "string", minLength: 1, maxLength: 128, pattern: "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$" },
|
|
1477
|
-
created_at: { type: "string", minLength: 1, maxLength: 64 },
|
|
1478
|
-
authority: {
|
|
1479
|
-
type: "object",
|
|
1480
|
-
maxProperties: 5,
|
|
1481
|
-
additionalProperties: false,
|
|
1482
|
-
properties: {
|
|
1483
|
-
instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1484
|
-
access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1485
|
-
principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1486
|
-
execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1487
|
-
authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
|
|
1488
|
-
},
|
|
1489
|
-
required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
|
|
1490
|
-
}
|
|
1491
|
-
});
|
|
1492
|
-
var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
|
|
1493
|
-
prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1494
|
-
host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1495
|
-
host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1496
|
-
host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1497
|
-
host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
|
|
1498
|
-
});
|
|
1499
|
-
var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
|
|
1500
|
-
caller_call_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Gateway-minted call-group identity for a non-Host caller." },
|
|
1501
|
-
caller_call_input_sha256: { type: "string", minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$", description: "Commitment to the exact input for active non-Host identity-reuse checks; a migrated legacy call group commits to its legacy group key because the original input may no longer exist." }
|
|
1502
|
-
});
|
|
1503
|
-
var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
|
|
1504
|
-
requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
|
|
1505
|
-
device_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Device that submitted this Request through its client session, including Host turns when the authenticated Host registration carries the device; absent for older records." }
|
|
1506
|
-
});
|
|
1507
|
-
var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
|
|
1508
|
-
var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
|
|
1509
|
-
var CEAL_REQUEST_JSON_SCHEMA = {
|
|
1510
|
-
type: "object",
|
|
1511
|
-
description: "A Request has exactly one creation identity: the complete Host tuple and prompt reference, or a caller call-group identity. Caller Requests retain no prompt reference or prompt body.",
|
|
1512
|
-
maxProperties: 13,
|
|
1513
|
-
additionalProperties: false,
|
|
1514
|
-
properties: {
|
|
1515
|
-
...CEAL_REQUEST_COMMON_PROPERTIES,
|
|
1516
|
-
...CEAL_REQUEST_HOST_PROPERTIES,
|
|
1517
|
-
...CEAL_REQUEST_CALLER_PROPERTIES,
|
|
1518
|
-
...CEAL_REQUEST_OPTIONAL_PROPERTIES
|
|
1519
|
-
},
|
|
1520
|
-
required: CEAL_REQUEST_KEYS,
|
|
1521
|
-
anyOf: [
|
|
1522
|
-
{
|
|
1523
|
-
type: "object",
|
|
1524
|
-
required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
|
|
1525
|
-
properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
|
|
1526
|
-
additionalProperties: false
|
|
1527
|
-
},
|
|
1528
|
-
{
|
|
1529
|
-
type: "object",
|
|
1530
|
-
required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
|
|
1531
|
-
properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
|
|
1532
|
-
additionalProperties: false
|
|
1533
|
-
}
|
|
1534
|
-
]
|
|
1535
|
-
};
|
|
1536
|
-
|
|
1537
|
-
// packages/ceal-client-protocol/src/request-operands.ts
|
|
1538
|
-
var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
|
|
1539
|
-
var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
|
|
1540
|
-
var CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH = 1024;
|
|
1541
|
-
var CEAL_REQUEST_RESOLVER_SELECTION_JSON_SCHEMA = {
|
|
1542
|
-
type: "object",
|
|
1543
|
-
maxProperties: 2,
|
|
1544
|
-
additionalProperties: false,
|
|
1545
|
-
properties: {
|
|
1546
|
-
property: { type: "string", minLength: 1, maxLength: 128 },
|
|
1547
|
-
selectors: {
|
|
1548
|
-
type: "object",
|
|
1549
|
-
maxProperties: CEAL_REQUEST_MAX_SELECTOR_PROPERTIES,
|
|
1550
|
-
properties: {},
|
|
1551
|
-
additionalProperties: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH }
|
|
1552
|
-
}
|
|
1553
|
-
},
|
|
1554
|
-
required: ["property", "selectors"]
|
|
1555
|
-
};
|
|
1727
|
+
// packages/ceal-client-protocol/src/request-operands.ts
|
|
1728
|
+
var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
|
|
1729
|
+
var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
|
|
1730
|
+
var CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH = 1024;
|
|
1731
|
+
var CEAL_REQUEST_RESOLVER_SELECTION_JSON_SCHEMA = {
|
|
1732
|
+
type: "object",
|
|
1733
|
+
maxProperties: 2,
|
|
1734
|
+
additionalProperties: false,
|
|
1735
|
+
properties: {
|
|
1736
|
+
property: { type: "string", minLength: 1, maxLength: 128 },
|
|
1737
|
+
selectors: {
|
|
1738
|
+
type: "object",
|
|
1739
|
+
maxProperties: CEAL_REQUEST_MAX_SELECTOR_PROPERTIES,
|
|
1740
|
+
properties: {},
|
|
1741
|
+
additionalProperties: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_MAX_SELECTOR_VALUE_LENGTH }
|
|
1742
|
+
}
|
|
1743
|
+
},
|
|
1744
|
+
required: ["property", "selectors"]
|
|
1745
|
+
};
|
|
1556
1746
|
|
|
1557
1747
|
// packages/ceal-client-protocol/src/request-graph.ts
|
|
1558
1748
|
var CEAL_REQUEST_MAX_GRAPH_NODES = 128;
|
|
@@ -1641,6 +1831,27 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
|
|
|
1641
1831
|
required: ["schema_version", "order", "nodes", "call_budget"]
|
|
1642
1832
|
};
|
|
1643
1833
|
|
|
1834
|
+
// packages/ceal-client-protocol/src/host-observation-validation.ts
|
|
1835
|
+
var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
|
|
1836
|
+
var HOST_RESERVED_KEY = /^(?:access_group|admission|approval|audit|authorization|cancellation|capability|effect|grant|occurrence|operation|policy|profile|provider_readback|receipt|reconciliation|replay|target|write_request)(?:_|$)/iu;
|
|
1837
|
+
function validateCealHostObservationValue(value) {
|
|
1838
|
+
if (value === void 0) throw new TypeError("Ceal Host observation value is invalid.");
|
|
1839
|
+
assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
|
|
1840
|
+
if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) throw new TypeError("Ceal Host observation value is oversized.");
|
|
1841
|
+
inspectHostKeys(value);
|
|
1842
|
+
}
|
|
1843
|
+
function inspectHostKeys(value) {
|
|
1844
|
+
if (Array.isArray(value)) {
|
|
1845
|
+
for (const entry of value) inspectHostKeys(entry);
|
|
1846
|
+
return;
|
|
1847
|
+
}
|
|
1848
|
+
if (value === null || typeof value !== "object") return;
|
|
1849
|
+
for (const [key, child] of Object.entries(value)) {
|
|
1850
|
+
if (HOST_RESERVED_KEY.test(key)) throw new TypeError("Ceal Host observation cannot restate Gateway-owned facts.");
|
|
1851
|
+
inspectHostKeys(child);
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1644
1855
|
// packages/ceal-client-protocol/src/host-observation.ts
|
|
1645
1856
|
var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
|
|
1646
1857
|
var HOST_OBSERVATION_PRODUCER = /^[a-z][a-z0-9]{0,31}$/u;
|
|
@@ -1687,35 +1898,238 @@ function safeCount(value) {
|
|
|
1687
1898
|
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
1688
1899
|
}
|
|
1689
1900
|
function validateCealHostObservationDraft(value) {
|
|
1690
|
-
const
|
|
1691
|
-
requirePrefixedRef(
|
|
1692
|
-
requireClosedValue(
|
|
1693
|
-
requireIsoTimestamp(
|
|
1694
|
-
assertHostObservationValue(
|
|
1901
|
+
const record6 = operationRecord(value, "Ceal Host observation draft is invalid.");
|
|
1902
|
+
requirePrefixedRef(record6.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
|
|
1903
|
+
requireClosedValue(record6.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
|
|
1904
|
+
requireIsoTimestamp(record6.observed_at, "Ceal Host observation time is invalid.");
|
|
1905
|
+
assertHostObservationValue(record6.value, record6.observation_kind);
|
|
1695
1906
|
}
|
|
1696
|
-
var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
|
|
1697
1907
|
var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
|
|
1698
1908
|
function isCealHostPromptObservationValue(value) {
|
|
1699
1909
|
return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
|
|
1700
1910
|
}
|
|
1701
|
-
var HOST_RESERVED_KEY = /^(?:access_group|admission|approval|audit|authorization|cancellation|capability|effect|grant|occurrence|operation|policy|profile|provider_readback|receipt|reconciliation|replay|target|write_request)(?:_|$)/iu;
|
|
1702
1911
|
function assertHostObservationValue(value, kind) {
|
|
1703
1912
|
if (value === void 0) invalid("Ceal Host observation value is invalid.");
|
|
1704
1913
|
if (kind === "prompt" && !isCealHostPromptObservationValue(value)) invalid("Ceal Host prompt observation must contain only its body digest.");
|
|
1705
|
-
|
|
1706
|
-
if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) invalid("Ceal Host observation value is oversized.");
|
|
1707
|
-
inspectHostKeys(value);
|
|
1914
|
+
validateCealHostObservationValue(value);
|
|
1708
1915
|
}
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1916
|
+
|
|
1917
|
+
// packages/ceal-client-protocol/src/host-usage-facts.ts
|
|
1918
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
1919
|
+
var CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION = "ceal.host_usage_batch.v1";
|
|
1920
|
+
var CEAL_HOST_USAGE_BATCH_REF_PREFIX = "host-usage-batch:";
|
|
1921
|
+
var CEAL_HOST_USAGE_INGRESS_PATH = "/api/ceal/v2/host-usage-batches";
|
|
1922
|
+
var CEAL_HOST_USAGE_BATCH_MAX_BYTES = 1024 * 1024;
|
|
1923
|
+
var CEAL_HOST_USAGE_FACT_MAX_BYTES = 64 * 1024;
|
|
1924
|
+
var CEAL_HOST_USAGE_BATCH_MAX_FACTS = 256;
|
|
1925
|
+
var CEAL_HOST_USAGE_BATCH_MAX_GAPS = 16;
|
|
1926
|
+
var CEAL_HOST_USAGE_BATCH_ACK_STATUS = 204;
|
|
1927
|
+
var CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES = 65;
|
|
1928
|
+
var CODEX_COUNTER_SEMANTICS = ["last_delta_total_cumulative", "total_cumulative_only", "unknown"];
|
|
1929
|
+
var CODEX_CUMULATIVE_TRANSITIONS = ["baseline", "advanced", "same", "reset_or_correction", "not_observed"];
|
|
1930
|
+
var HOST_USAGE_COVERAGE_GAP_REASONS = ["source_usage_unavailable", "source_file_replaced", "source_file_retired", "outbox_capacity", "unsupported_source_shape"];
|
|
1931
|
+
function createCealHostUsageBatch(input) {
|
|
1932
|
+
const body = { schema_version: CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION, ...input };
|
|
1933
|
+
const batch = { ...body, batch_ref: `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}` };
|
|
1934
|
+
validateCealHostUsageBatch(batch);
|
|
1935
|
+
return batch;
|
|
1936
|
+
}
|
|
1937
|
+
function validateCealHostUsageBatch(value) {
|
|
1938
|
+
if (!isOperationRecord(value)) invalid("Ceal Host usage batch is invalid.");
|
|
1939
|
+
requireExactOperationKeys(value, ["schema_version", "batch_ref", "host_source_ref", "host_session_ref", "created_at", "source_ranges", "facts", "coverage_gaps"]);
|
|
1940
|
+
if (value.schema_version !== CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION || typeof value.batch_ref !== "string" || !value.batch_ref.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX)) invalid("Ceal Host usage batch is invalid.");
|
|
1941
|
+
const { batch_ref: _ref, ...body } = value;
|
|
1942
|
+
if (value.batch_ref !== `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}`) invalid("Ceal Host usage batch reference is invalid.");
|
|
1943
|
+
validateBatchMetadata(value);
|
|
1944
|
+
validateBatchContents(value);
|
|
1945
|
+
if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_BATCH_MAX_BYTES) invalid("Ceal Host usage batch exceeds its byte limit.");
|
|
1946
|
+
}
|
|
1947
|
+
function validateBatchMetadata(value) {
|
|
1948
|
+
requireSafeRef2(value.host_source_ref, "Ceal Host usage source is invalid.");
|
|
1949
|
+
requireSafeRef2(value.host_session_ref, "Ceal Host usage session is invalid.");
|
|
1950
|
+
requireIsoTimestamp(value.created_at, "Ceal Host usage batch time is invalid.");
|
|
1951
|
+
if (!Array.isArray(value.source_ranges) || value.source_ranges.length > CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES) invalid("Ceal Host usage source ranges are invalid.");
|
|
1952
|
+
for (const range of value.source_ranges) validateSourceRange(range);
|
|
1953
|
+
}
|
|
1954
|
+
function validateBatchContents(value) {
|
|
1955
|
+
const facts = validateBatchFacts(value.facts);
|
|
1956
|
+
const gaps = validateBatchGaps(value.coverage_gaps);
|
|
1957
|
+
if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
|
|
1958
|
+
const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
|
|
1959
|
+
for (const fact of facts) {
|
|
1960
|
+
validateFact(fact, value.host_session_ref);
|
|
1961
|
+
if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
|
|
1962
|
+
}
|
|
1963
|
+
for (const gap of gaps) {
|
|
1964
|
+
validateCoverageGap(gap);
|
|
1965
|
+
if (gap.source_file_ref !== null && !sourceFiles.has(gap.source_file_ref)) invalid("Ceal Host usage coverage gap is outside its source ranges.");
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
function validateBatchFacts(value) {
|
|
1969
|
+
if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_FACTS) invalid("Ceal Host usage fact count is invalid.");
|
|
1970
|
+
return value;
|
|
1971
|
+
}
|
|
1972
|
+
function validateBatchGaps(value) {
|
|
1973
|
+
if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) invalid("Ceal Host usage coverage is invalid.");
|
|
1974
|
+
return value;
|
|
1975
|
+
}
|
|
1976
|
+
function sourceRangeFileRef(value) {
|
|
1977
|
+
return isOperationRecord(value) ? value.source_file_ref : null;
|
|
1978
|
+
}
|
|
1979
|
+
function hostUsageFactReference(sourceFileRef2, sourceEventRef) {
|
|
1980
|
+
requireSafeRef2(sourceFileRef2, "Ceal Host usage file reference is invalid.");
|
|
1981
|
+
requireSafeRef2(sourceEventRef, "Ceal Host usage event reference is invalid.");
|
|
1982
|
+
return `host-usage-fact:${sha256(JSON.stringify({ source_file_ref: sourceFileRef2, source_event_ref: sourceEventRef }))}`;
|
|
1983
|
+
}
|
|
1984
|
+
function hostUsageSourceEventReference(sourceFileRef2, sourceEventIdentity) {
|
|
1985
|
+
requireSafeRef2(sourceFileRef2, "Ceal Host usage file reference is invalid.");
|
|
1986
|
+
if (typeof sourceEventIdentity !== "string" || sourceEventIdentity.length === 0 || sourceEventIdentity.length > 1024) invalid("Ceal Host usage event identity is invalid.");
|
|
1987
|
+
return `host-source-event:${sha256(JSON.stringify({ source_file_ref: sourceFileRef2, source_event_identity: sourceEventIdentity }))}`;
|
|
1988
|
+
}
|
|
1989
|
+
function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, device, inode) {
|
|
1990
|
+
for (const part of [producer, hostSourceRef, hostSessionRef, device, inode]) if (typeof part !== "string" || part.length === 0 || part.length > 512) invalid("Ceal Host usage file identity is invalid.");
|
|
1991
|
+
return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
|
|
1992
|
+
}
|
|
1993
|
+
function validateFact(value, sessionRef) {
|
|
1994
|
+
if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
|
|
1995
|
+
requireFactByteLimit(value);
|
|
1996
|
+
if (value.producer === "codex_transcript") validateCodexFact(value);
|
|
1997
|
+
else if (value.producer === "claude_transcript") validateClaudeFact(value);
|
|
1998
|
+
else invalid("Ceal Host usage producer is invalid.");
|
|
1999
|
+
if (value.host_session_ref !== sessionRef) invalid("Ceal Host usage session does not match its batch.");
|
|
2000
|
+
requireSafeRef2(value.source_file_ref, "Ceal Host usage file reference is invalid.");
|
|
2001
|
+
requireSafeRef2(value.source_event_ref, "Ceal Host usage event reference is invalid.");
|
|
2002
|
+
if (value.host_turn_ref !== null) requireSafeRef2(value.host_turn_ref, "Ceal Host usage turn reference is invalid.");
|
|
2003
|
+
if (value.requested_model !== null && !boundedText(value.requested_model, 256)) invalid("Ceal Host requested model is invalid.");
|
|
2004
|
+
if (value.reported_model !== null && !boundedText(value.reported_model, 256)) invalid("Ceal Host reported model is invalid.");
|
|
2005
|
+
if (value.fact_ref !== hostUsageFactReference(value.source_file_ref, value.source_event_ref)) invalid("Ceal Host usage identity is invalid.");
|
|
2006
|
+
}
|
|
2007
|
+
function requireFactByteLimit(value) {
|
|
2008
|
+
if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_FACT_MAX_BYTES) invalid("Ceal Host usage fact exceeds its byte limit.");
|
|
2009
|
+
}
|
|
2010
|
+
function validateCodexFact(value) {
|
|
2011
|
+
if (!isOperationRecord(value)) invalid("Ceal Codex usage fact is invalid.");
|
|
2012
|
+
requireExactOperationKeys(value, ["fact_ref", "host_session_ref", "host_turn_ref", "source_file_ref", "source_event_ref", "source_event_ordinal", "observed_at", "producer", "requested_model", "reported_model", "source_usage", "normalized_usage", "counter_semantics", "cumulative_transition", "finality", "correction_semantics"]);
|
|
2013
|
+
if (value.producer !== "codex_transcript" || !safeInteger(value.source_event_ordinal)) invalid("Ceal Codex usage fact is invalid.");
|
|
2014
|
+
requireIsoTimestamp(value.observed_at, "Ceal Codex usage time is invalid.");
|
|
2015
|
+
if (!isOperationRecord(value.source_usage)) invalid("Ceal Codex source usage is invalid.");
|
|
2016
|
+
requireExactOperationKeys(value.source_usage, ["last_token_usage", "total_token_usage"]);
|
|
2017
|
+
if (value.source_usage.last_token_usage !== null) validateCodexUsageCounts(value.source_usage.last_token_usage);
|
|
2018
|
+
if (value.source_usage.total_token_usage !== null) validateCodexUsageCounts(value.source_usage.total_token_usage);
|
|
2019
|
+
if (!isOneOf(CODEX_COUNTER_SEMANTICS, value.counter_semantics) || !isOneOf(CODEX_CUMULATIVE_TRANSITIONS, value.cumulative_transition) || value.finality !== "unknown" || !["not_observed", "unknown"].includes(String(value.correction_semantics))) invalid("Ceal Codex usage semantics are invalid.");
|
|
2020
|
+
validateNormalizedUsage(value.normalized_usage);
|
|
2021
|
+
}
|
|
2022
|
+
function validateClaudeFact(value) {
|
|
2023
|
+
if (!isOperationRecord(value)) invalid("Ceal Claude usage fact is invalid.");
|
|
2024
|
+
requireExactOperationKeys(value, ["fact_ref", "host_session_ref", "host_turn_ref", "source_file_ref", "source_event_ref", "source_event_uuid", "source_file_kind", "observed_at", "producer", "requested_model", "reported_model", "source_usage", "normalized_usage", "counter_semantics", "finality", "child_inclusion", "correction_semantics"]);
|
|
2025
|
+
validateClaudeIdentity(value);
|
|
2026
|
+
requireIsoTimestamp(value.observed_at, "Ceal Claude usage time is invalid.");
|
|
2027
|
+
validateClaudeSourceUsage(value.source_usage);
|
|
2028
|
+
validateClaudeSemantics(value);
|
|
2029
|
+
validateNormalizedUsage(value.normalized_usage);
|
|
2030
|
+
}
|
|
2031
|
+
function validateClaudeIdentity(value) {
|
|
2032
|
+
if (value.producer !== "claude_transcript" || !boundedText(value.source_event_uuid, 256) || !["main", "subagent"].includes(String(value.source_file_kind))) invalid("Ceal Claude usage fact is invalid.");
|
|
2033
|
+
}
|
|
2034
|
+
function validateClaudeSourceUsage(value) {
|
|
2035
|
+
if (!isOperationRecord(value)) invalid("Ceal Claude source usage is invalid.");
|
|
2036
|
+
requireExactOperationKeys(value, ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"], ["cache_creation"]);
|
|
2037
|
+
for (const key of ["input_tokens", "output_tokens"]) if (!safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
|
|
2038
|
+
for (const key of ["cache_read_input_tokens", "cache_creation_input_tokens"]) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
|
|
2039
|
+
if (value.cache_creation !== void 0 && value.cache_creation !== null) validateClaudeCacheCreationUsage(value.cache_creation);
|
|
2040
|
+
}
|
|
2041
|
+
function validateClaudeCacheCreationUsage(value) {
|
|
2042
|
+
if (!isOperationRecord(value)) invalid("Ceal Claude cache creation usage is invalid.");
|
|
2043
|
+
requireExactOperationKeys(value, ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]);
|
|
2044
|
+
for (const key of ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal Claude cache creation usage is invalid.");
|
|
2045
|
+
}
|
|
2046
|
+
function validateClaudeSemantics(value) {
|
|
2047
|
+
if (value.counter_semantics !== "assistant_message" || !validClaudeFinality(value.finality) || value.child_inclusion !== "unknown" || !validCorrectionSemantics(value.correction_semantics)) invalid("Ceal Claude usage semantics are invalid.");
|
|
2048
|
+
}
|
|
2049
|
+
function validClaudeFinality(value) {
|
|
2050
|
+
return value === "terminal" || value === "nonterminal" || value === "unknown";
|
|
2051
|
+
}
|
|
2052
|
+
function validCorrectionSemantics(value) {
|
|
2053
|
+
return value === "not_observed" || value === "unknown";
|
|
2054
|
+
}
|
|
2055
|
+
function validateCodexUsageCounts(value) {
|
|
2056
|
+
if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
|
|
2057
|
+
requireExactOperationKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
|
|
2058
|
+
for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
|
|
2059
|
+
if (Number(value.total_tokens) !== Number(value.input_tokens) + Number(value.output_tokens) || Number(value.cached_input_tokens) + Number(value.cache_write_input_tokens) > Number(value.input_tokens) || Number(value.reasoning_output_tokens) > Number(value.output_tokens)) invalid("Ceal Codex usage fields are inconsistent.");
|
|
2060
|
+
}
|
|
2061
|
+
function validateNormalizedUsage(value) {
|
|
2062
|
+
if (!isOperationRecord(value)) invalid("Ceal normalized Host usage is invalid.");
|
|
2063
|
+
requireExactOperationKeys(value, ["input", "output", "total", "cached_input", "cache_write_input", "reasoning_output"]);
|
|
2064
|
+
for (const key of Object.keys(value)) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal normalized Host usage is invalid.");
|
|
2065
|
+
validateNormalizedTotals(value);
|
|
2066
|
+
}
|
|
2067
|
+
function validateNormalizedTotals(value) {
|
|
2068
|
+
validateNormalizedCountTotal(value);
|
|
2069
|
+
validateNormalizedInputSubsets(value);
|
|
2070
|
+
validateNormalizedOutputSubset(value);
|
|
2071
|
+
}
|
|
2072
|
+
function validateNormalizedCountTotal(value) {
|
|
2073
|
+
if (value.input !== null && value.output !== null && value.total !== null && Number(value.total) !== Number(value.input) + Number(value.output)) invalid("Ceal normalized Host usage total is inconsistent.");
|
|
2074
|
+
}
|
|
2075
|
+
function validateNormalizedInputSubsets(value) {
|
|
2076
|
+
if (value.input !== null && value.cached_input !== null && value.cache_write_input !== null && Number(value.cached_input) + Number(value.cache_write_input) > Number(value.input)) invalid("Ceal normalized Host input subsets are inconsistent.");
|
|
2077
|
+
}
|
|
2078
|
+
function validateNormalizedOutputSubset(value) {
|
|
2079
|
+
if (value.output !== null && value.reasoning_output !== null && Number(value.reasoning_output) > Number(value.output)) invalid("Ceal normalized Host output subset is inconsistent.");
|
|
2080
|
+
}
|
|
2081
|
+
function validateSourceRange(value) {
|
|
2082
|
+
if (!isOperationRecord(value)) invalid("Ceal Host usage source range is invalid.");
|
|
2083
|
+
requireExactOperationKeys(value, ["source_file_ref", "start_offset", "end_offset"]);
|
|
2084
|
+
requireSafeRef2(value.source_file_ref, "Ceal Host usage source-file reference is invalid.");
|
|
2085
|
+
if (!safeInteger(value.start_offset) || !safeInteger(value.end_offset) || Number(value.end_offset) <= Number(value.start_offset)) invalid("Ceal Host usage source range is invalid.");
|
|
2086
|
+
}
|
|
2087
|
+
function validateCealHostUsageCoverageGap(value) {
|
|
2088
|
+
if (!isOperationRecord(value)) invalid("Ceal Host usage coverage gap is invalid.");
|
|
2089
|
+
requireExactOperationKeys(value, ["reason", "source_file_ref", "start_offset", "end_offset", "omitted_count"]);
|
|
2090
|
+
if (!isOneOf(HOST_USAGE_COVERAGE_GAP_REASONS, value.reason) || !validUsageGapCount(value.reason, value.omitted_count)) invalid("Ceal Host usage coverage gap is invalid.");
|
|
2091
|
+
if (value.source_file_ref === null) {
|
|
2092
|
+
if (value.start_offset !== null || value.end_offset !== null) invalid("Ceal Host usage coverage gap range is invalid.");
|
|
1712
2093
|
return;
|
|
1713
2094
|
}
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
2095
|
+
requireSafeRef2(value.source_file_ref, "Ceal Host usage coverage file reference is invalid.");
|
|
2096
|
+
if (!safeInteger(value.start_offset) || !safeInteger(value.end_offset) || Number(value.end_offset) <= Number(value.start_offset)) invalid("Ceal Host usage coverage gap range is invalid.");
|
|
2097
|
+
}
|
|
2098
|
+
function validateCoverageGap(value) {
|
|
2099
|
+
validateCealHostUsageCoverageGap(value);
|
|
2100
|
+
}
|
|
2101
|
+
function validUsageGapCount(reason, value) {
|
|
2102
|
+
return value === null ? reason !== "outbox_capacity" : safeInteger(value) && Number(value) >= 1;
|
|
2103
|
+
}
|
|
2104
|
+
function isOneOf(values, value) {
|
|
2105
|
+
return typeof value === "string" && values.some((candidate) => candidate === value);
|
|
2106
|
+
}
|
|
2107
|
+
function isCealHostUsageBatchReference(value) {
|
|
2108
|
+
return typeof value === "string" && value.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX) && isCealDigest(value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length));
|
|
2109
|
+
}
|
|
2110
|
+
function cealHostUsageBatchObjectDigestFromFileName(value) {
|
|
2111
|
+
if (!value.endsWith(".json")) return null;
|
|
2112
|
+
const digest2 = value.slice(0, -5);
|
|
2113
|
+
return isCealDigest(digest2) ? digest2 : null;
|
|
2114
|
+
}
|
|
2115
|
+
function cealHostUsageBatchObjectDigestFromReference(value) {
|
|
2116
|
+
return isCealHostUsageBatchReference(value) ? value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length) : null;
|
|
2117
|
+
}
|
|
2118
|
+
function safeInteger(value) {
|
|
2119
|
+
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
2120
|
+
}
|
|
2121
|
+
function boundedText(value, maximum) {
|
|
2122
|
+
return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters(value);
|
|
2123
|
+
}
|
|
2124
|
+
function hasControlCharacters(value) {
|
|
2125
|
+
for (const character of value) {
|
|
2126
|
+
const code2 = character.codePointAt(0);
|
|
2127
|
+
if (code2 !== void 0 && (code2 < 32 || code2 === 127)) return true;
|
|
1718
2128
|
}
|
|
2129
|
+
return false;
|
|
2130
|
+
}
|
|
2131
|
+
function sha256(value) {
|
|
2132
|
+
return createHash3("sha256").update(value, "utf8").digest("hex");
|
|
1719
2133
|
}
|
|
1720
2134
|
|
|
1721
2135
|
// packages/ceal-client-protocol/src/host-prompt-ref.ts
|
|
@@ -1822,6 +2236,7 @@ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSch
|
|
|
1822
2236
|
var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
|
|
1823
2237
|
var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
|
|
1824
2238
|
var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
|
|
2239
|
+
var CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.refusal_schema_name, fields: hostInvocationAuthenticationContract.refusal_fields });
|
|
1825
2240
|
var CEAL_HOST_AUTHENTICATION_BUDGET_ENVIRONMENT = "CEAL_HOST_AUTHENTICATION_BUDGET_MS";
|
|
1826
2241
|
var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
|
|
1827
2242
|
var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
|
|
@@ -1836,15 +2251,39 @@ function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated
|
|
|
1836
2251
|
const messages = [];
|
|
1837
2252
|
let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
|
|
1838
2253
|
for (const candidate of newestFirst.slice(0, CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES)) {
|
|
1839
|
-
const
|
|
1840
|
-
if (
|
|
2254
|
+
const complete = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: candidate.text, ...candidate.text_truncated === true ? { text_truncated: candidate.text_truncated } : {} };
|
|
2255
|
+
if (encodedMessageWindowBytes([...messages, complete]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) {
|
|
2256
|
+
messages.push(Object.freeze(complete));
|
|
2257
|
+
continue;
|
|
2258
|
+
}
|
|
2259
|
+
const clipped = clipHumanMessageToWindow(messages, candidate);
|
|
2260
|
+
if (clipped === null) {
|
|
1841
2261
|
truncated = true;
|
|
1842
2262
|
break;
|
|
1843
2263
|
}
|
|
1844
|
-
messages.push(Object.freeze(
|
|
2264
|
+
messages.push(Object.freeze(clipped));
|
|
1845
2265
|
}
|
|
1846
2266
|
return Object.freeze({ messages: Object.freeze(messages), truncated });
|
|
1847
2267
|
}
|
|
2268
|
+
function encodedMessageWindowBytes(messages) {
|
|
2269
|
+
return new TextEncoder().encode(JSON.stringify(messages)).byteLength;
|
|
2270
|
+
}
|
|
2271
|
+
function clipHumanMessageToWindow(prefix, candidate) {
|
|
2272
|
+
const clipped = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: "", text_truncated: true };
|
|
2273
|
+
const available = CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES - encodedMessageWindowBytes([...prefix, clipped]);
|
|
2274
|
+
if (available < 0) return null;
|
|
2275
|
+
const text = [];
|
|
2276
|
+
let used = 0;
|
|
2277
|
+
for (const point of candidate.text) {
|
|
2278
|
+
const encodedPoint = JSON.stringify(point);
|
|
2279
|
+
const cost = new TextEncoder().encode(encodedPoint).byteLength - 2;
|
|
2280
|
+
if (used + cost > available) break;
|
|
2281
|
+
text.push(point);
|
|
2282
|
+
used += cost;
|
|
2283
|
+
}
|
|
2284
|
+
const result = { ...clipped, text: text.join("") };
|
|
2285
|
+
return encodedMessageWindowBytes([...prefix, result]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES ? result : null;
|
|
2286
|
+
}
|
|
1848
2287
|
function decodeCealHostInvocationContextRequest(value) {
|
|
1849
2288
|
if (!isCealJsonRecord(value)) throw invalidInvocationContextRequest();
|
|
1850
2289
|
requireCealClientWireSchemaVersion(value.schema_version, CEAL_HOST_INVOCATION_CONTEXT_REQUEST_SCHEMA);
|
|
@@ -1852,7 +2291,7 @@ function decodeCealHostInvocationContextRequest(value) {
|
|
|
1852
2291
|
const clientNonce = requireClientNonce(value.client_nonce);
|
|
1853
2292
|
const expiresAt = requireContextExpiration(value.context_expires_at);
|
|
1854
2293
|
const hostBinding = requireHostBinding(value.host_binding);
|
|
1855
|
-
const messageWindow =
|
|
2294
|
+
const messageWindow = decodeCealHostInvocationHumanMessageWindow(value.human_message_window);
|
|
1856
2295
|
const lastRequestRef = optionalSafeReference(value.last_seen_request_ref);
|
|
1857
2296
|
const visibleOutputMaxBytes = optionalVisibleOutputBudget(value.visible_output_max_bytes);
|
|
1858
2297
|
return Object.freeze({
|
|
@@ -1883,7 +2322,7 @@ function requireHostBinding(value) {
|
|
|
1883
2322
|
if (!isCealJsonRecord(value) || !exactOptionalKeys(value, ["host_source_ref", "host_session_ref", "host_turn_ref"], []) || !safeReference(value.host_source_ref) || !safeReference(value.host_session_ref) || !safeReference(value.host_turn_ref)) throw invalidInvocationContextRequest();
|
|
1884
2323
|
return { host_source_ref: value.host_source_ref, host_session_ref: value.host_session_ref, host_turn_ref: value.host_turn_ref };
|
|
1885
2324
|
}
|
|
1886
|
-
function
|
|
2325
|
+
function decodeCealHostInvocationHumanMessageWindow(value) {
|
|
1887
2326
|
if (!isCealJsonRecord(value) || !exactOptionalKeys(value, ["messages", "truncated"], []) || !Array.isArray(value.messages) || value.messages.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES || typeof value.truncated !== "boolean") throw invalidInvocationContextRequest();
|
|
1888
2327
|
const messages = value.messages.map(decodeHumanMessage);
|
|
1889
2328
|
const bytes = new TextEncoder().encode(JSON.stringify(messages)).byteLength;
|
|
@@ -1891,8 +2330,9 @@ function requireHumanMessageWindow(value) {
|
|
|
1891
2330
|
return Object.freeze({ messages: Object.freeze(messages), truncated: value.truncated });
|
|
1892
2331
|
}
|
|
1893
2332
|
function decodeHumanMessage(candidate) {
|
|
1894
|
-
if (!isCealJsonRecord(candidate) || !exactOptionalKeys(candidate, ["host_turn_ref", "host_input_ref", "text"], []) || !safeReference(candidate.host_turn_ref) || !safeReference(candidate.host_input_ref) || typeof candidate.text !== "string") throw invalidInvocationContextRequest();
|
|
1895
|
-
|
|
2333
|
+
if (!isCealJsonRecord(candidate) || !exactOptionalKeys(candidate, ["host_turn_ref", "host_input_ref", "text"], ["text_truncated"]) || !safeReference(candidate.host_turn_ref) || !safeReference(candidate.host_input_ref) || typeof candidate.text !== "string") throw invalidInvocationContextRequest();
|
|
2334
|
+
if (candidate.text_truncated !== void 0 && candidate.text_truncated !== true) throw invalidInvocationContextRequest();
|
|
2335
|
+
return Object.freeze({ host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: candidate.text, ...candidate.text_truncated === true ? { text_truncated: candidate.text_truncated } : {} });
|
|
1896
2336
|
}
|
|
1897
2337
|
function optionalSafeReference(value) {
|
|
1898
2338
|
if (value === void 0) return void 0;
|
|
@@ -1923,31 +2363,11 @@ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTR
|
|
|
1923
2363
|
};
|
|
1924
2364
|
}
|
|
1925
2365
|
var hostNonceContract = deriveCealHostInvocationNonceContract();
|
|
1926
|
-
var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
|
|
1927
2366
|
var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
|
|
1928
2367
|
var CEAL_HOST_CONTEXT_TOKEN_PATTERN = new RegExp(hostNonceContract.context_token_pattern_source, "u");
|
|
1929
|
-
var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_MAX_BYTES = deriveCealHostInvocationAuthenticationResultMaxBytes();
|
|
1930
|
-
function deriveCealHostInvocationAuthenticationResultMaxBytes(contract = CEAL_CLIENT_WIRE_CONTRACT) {
|
|
1931
|
-
const hostAuthentication = contract.host_invocation_authentication;
|
|
1932
|
-
const values = {
|
|
1933
|
-
schema_version: deriveCealClientWireSchemaVersion({ schema_name: hostAuthentication.result_schema_name, fields: hostAuthentication.result_fields }),
|
|
1934
|
-
context_token: `${CEAL_HOST_CONTEXT_TOKEN_PREFIX}${"A".repeat(hostAuthentication.client_nonce.encoded_characters)}`,
|
|
1935
|
-
expires_at: (/* @__PURE__ */ new Date("+010000-01-01T00:00:00.000Z")).toISOString()
|
|
1936
|
-
};
|
|
1937
|
-
const fields = hostAuthentication.result_fields;
|
|
1938
|
-
if (fields.some((field) => !Object.hasOwn(values, field))) throw new TypeError("Host invocation result fields have no bounded sample value.");
|
|
1939
|
-
return new TextEncoder().encode(`${JSON.stringify(Object.fromEntries(fields.map((field) => [field, values[field]])))}
|
|
1940
|
-
`).byteLength;
|
|
1941
|
-
}
|
|
1942
2368
|
var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
|
|
1943
2369
|
"request_authority_unavailable",
|
|
1944
|
-
"
|
|
1945
|
-
"authority_mismatch",
|
|
1946
|
-
"host_source_mismatch",
|
|
1947
|
-
"host_session_mismatch",
|
|
1948
|
-
"host_turn_mismatch",
|
|
1949
|
-
"host_input_mismatch",
|
|
1950
|
-
"host_prompt_mismatch"
|
|
2370
|
+
"request_creation_refused"
|
|
1951
2371
|
]);
|
|
1952
2372
|
var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
|
|
1953
2373
|
"invalid_arguments",
|
|
@@ -1956,7 +2376,6 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
|
|
|
1956
2376
|
"context_unavailable",
|
|
1957
2377
|
"context_replaced",
|
|
1958
2378
|
"no_binding",
|
|
1959
|
-
"context_stale",
|
|
1960
2379
|
"context_expired",
|
|
1961
2380
|
"host_source_refused",
|
|
1962
2381
|
"host_credential_refused",
|
|
@@ -1973,31 +2392,42 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
|
|
|
1973
2392
|
"relay_failed",
|
|
1974
2393
|
"host_refusal_invalid"
|
|
1975
2394
|
]);
|
|
2395
|
+
var CEAL_HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
|
|
2396
|
+
"permission_denied",
|
|
2397
|
+
"socket_missing",
|
|
2398
|
+
"connection_refused",
|
|
2399
|
+
"closed_early",
|
|
2400
|
+
"response_invalid",
|
|
2401
|
+
"timed_out",
|
|
2402
|
+
"cancelled",
|
|
2403
|
+
"unavailable"
|
|
2404
|
+
]);
|
|
1976
2405
|
var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
1977
2406
|
invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
|
|
1978
2407
|
options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
|
|
1979
2408
|
session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
|
|
1980
|
-
|
|
2409
|
+
// This reason cannot distinguish a Codex side conversation from a missing
|
|
2410
|
+
// context in a regular session, so guidance must leave that choice to the caller.
|
|
2411
|
+
context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
|
|
1981
2412
|
context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
|
|
1982
2413
|
// `no_binding` now means the producer has no real current Host session. The
|
|
1983
2414
|
// Host Relay never uses it for an uncreated Gateway Request; there is no
|
|
1984
2415
|
// useful retry until the consumer is running inside a Host session.
|
|
1985
2416
|
no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
|
|
1986
|
-
context_stale: Object.freeze({ classification: "host_invocation_context_stale", next_action: "retry" }),
|
|
1987
2417
|
context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
|
|
1988
2418
|
host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
|
|
1989
2419
|
host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
|
|
1990
2420
|
gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
|
|
1991
2421
|
gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
|
|
1992
|
-
contract_mismatch: Object.freeze({ classification: "
|
|
1993
|
-
gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "
|
|
2422
|
+
contract_mismatch: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
|
|
2423
|
+
gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "upgrade_ceal_client" }),
|
|
1994
2424
|
gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
|
|
1995
2425
|
producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
|
|
1996
2426
|
relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
|
|
1997
|
-
relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "
|
|
2427
|
+
relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "install_ceal_host" }),
|
|
1998
2428
|
transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
|
|
1999
2429
|
mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
|
|
2000
|
-
relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "
|
|
2430
|
+
relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
|
|
2001
2431
|
host_refusal_invalid: Object.freeze({ classification: "host_refusal_invalid", next_action: "answer_with_gap" })
|
|
2002
2432
|
});
|
|
2003
2433
|
function isCealHostAuthenticationCause(value) {
|
|
@@ -2028,8 +2458,8 @@ function decodeHostInvocationAuthenticationResult(value, fields, now) {
|
|
|
2028
2458
|
return Object.freeze({ schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA, context_token: value.context_token, expires_at: value.expires_at });
|
|
2029
2459
|
}
|
|
2030
2460
|
function validFutureTimestamp(value, now) {
|
|
2031
|
-
const
|
|
2032
|
-
return Number.isFinite(
|
|
2461
|
+
const timestamp4 = Date.parse(value);
|
|
2462
|
+
return Number.isFinite(timestamp4) && new Date(timestamp4).toISOString() === value && timestamp4 > now.getTime();
|
|
2033
2463
|
}
|
|
2034
2464
|
function exactKeys(value, expected) {
|
|
2035
2465
|
const keys = Object.keys(value);
|
|
@@ -2046,10 +2476,13 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
|
|
|
2046
2476
|
"activation_recorded",
|
|
2047
2477
|
"activation_failed",
|
|
2048
2478
|
"watcher_scan_failed",
|
|
2479
|
+
"usage_capture_failed",
|
|
2480
|
+
"usage_upload_failed",
|
|
2049
2481
|
"activation_wait_skipped",
|
|
2050
2482
|
"activation_wait_engaged",
|
|
2051
2483
|
"activation_wait_completed",
|
|
2052
|
-
"activation_wait_exhausted"
|
|
2484
|
+
"activation_wait_exhausted",
|
|
2485
|
+
"invocation_authentication_failed"
|
|
2053
2486
|
]);
|
|
2054
2487
|
var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
|
|
2055
2488
|
"malformed_line",
|
|
@@ -2059,6 +2492,17 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
|
|
|
2059
2492
|
"size_budget",
|
|
2060
2493
|
"symlink"
|
|
2061
2494
|
]);
|
|
2495
|
+
var CEAL_HOST_SERVICE_DIAGNOSTIC_WATCHER_OPTIONAL_FIELDS = vocabulary(["failure_kind", "cause"]);
|
|
2496
|
+
var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_OPTIONAL_FIELDS = vocabulary(["cause"]);
|
|
2497
|
+
var CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE = "^[a-z][a-z0-9_]{0,63}(?::[A-Za-z][A-Za-z0-9_]{0,63})?$";
|
|
2498
|
+
var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES = Object.freeze([
|
|
2499
|
+
...CEAL_HOST_AUTHENTICATION_CAUSES,
|
|
2500
|
+
...CEAL_HOST_RELAY_EXCHANGE_FAILURES.map((failure2) => `relay_exchange:${failure2}`)
|
|
2501
|
+
]);
|
|
2502
|
+
var hostServiceDiagnosticCausePattern = new RegExp(CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE, "u");
|
|
2503
|
+
function isCealHostServiceDiagnosticCause(value, event) {
|
|
2504
|
+
return typeof value === "string" && hostServiceDiagnosticCausePattern.test(value) && (event !== "invocation_authentication_failed" || CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES.includes(value));
|
|
2505
|
+
}
|
|
2062
2506
|
|
|
2063
2507
|
// packages/ceal-client-protocol/src/client-result-materialization.ts
|
|
2064
2508
|
var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
|
|
@@ -2145,12 +2589,14 @@ var ADMIN_SOURCE_OWNERS = vocabulary([
|
|
|
2145
2589
|
"resource",
|
|
2146
2590
|
"prompt",
|
|
2147
2591
|
"usage",
|
|
2592
|
+
"provider_request_lifecycle",
|
|
2148
2593
|
"connector",
|
|
2149
2594
|
"session",
|
|
2150
2595
|
"knowledge",
|
|
2151
2596
|
"policy"
|
|
2152
2597
|
]);
|
|
2153
2598
|
var ADMIN_COMPLETENESS_STATES = vocabulary(["complete", "partial", "unknown"]);
|
|
2599
|
+
var ADMIN_PROVIDER_REQUEST_CAPTURE_HEALTH_STATES = vocabulary(["available", "missing", "invalid", "unreadable"]);
|
|
2154
2600
|
var ADMIN_OPERATION_OUTCOMES = vocabulary(["completed", "failed", "denied", "cancelled", "unknown"]);
|
|
2155
2601
|
var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
|
|
2156
2602
|
var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
|
|
@@ -2174,13 +2620,16 @@ var FAILURE_RESPONSE_KEYS = Object.freeze(["error", "ok", "proof_ref_or_unavaila
|
|
|
2174
2620
|
// host/invocation-authentication-client-command.ts
|
|
2175
2621
|
var MAX_DETAIL_CHARACTERS = 240;
|
|
2176
2622
|
var HOST_OWNED_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){0,7}$/u;
|
|
2623
|
+
function isHostOwnedFailureCode(value) {
|
|
2624
|
+
return typeof value === "string" && HOST_OWNED_CODE.test(value);
|
|
2625
|
+
}
|
|
2177
2626
|
function hostTerminalFailure(error, component) {
|
|
2178
2627
|
const code2 = errorCode(error);
|
|
2179
2628
|
const detail = failureDetail(error);
|
|
2180
2629
|
if (code2 === "ENOENT") return { code: "host_dependency_unavailable", message: `A command or file the ${component} Host needs is unavailable: ${detail}`, next_action: "Install the missing dependency or restore the missing file, then rerun this command." };
|
|
2181
2630
|
if (code2 === "EACCES" || code2 === "EPERM") return { code: "host_permission_denied", message: `The ${component} Host was refused access to a local path: ${detail}`, next_action: "Repair the ownership or mode of the named path, then rerun this command." };
|
|
2182
2631
|
if (code2 === "ENOSPC") return { code: "host_storage_unavailable", message: `The ${component} Host could not write local state: ${detail}`, next_action: "Free local disk space, then rerun this command." };
|
|
2183
|
-
if (
|
|
2632
|
+
if (isHostOwnedFailureCode(code2)) return { code: code2, message: `The ${component} Host command failed: ${detail}`, next_action: `Resolve the named failure above; run \`ceal-host doctor\` only if it reports installed ${component} Host drift.` };
|
|
2184
2633
|
return { code: "host_failure_unclassified", message: `The ${component} Host command failed for a cause it cannot classify: ${detail}`, next_action: `Run \`ceal-host doctor\`; if it reports no drift then the ${component} Host configuration is not the cause, and the message above is the only evidence of what is.` };
|
|
2185
2634
|
}
|
|
2186
2635
|
var DOCTOR_FLAGS = Object.freeze({
|
|
@@ -2271,13 +2720,13 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
|
|
|
2271
2720
|
];
|
|
2272
2721
|
|
|
2273
2722
|
// host/relay/src/host-producer-core.ts
|
|
2274
|
-
import { createHash as
|
|
2723
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
2275
2724
|
|
|
2276
2725
|
// host/secure-file.ts
|
|
2277
2726
|
import { execFile } from "node:child_process";
|
|
2278
2727
|
import { constants } from "node:fs";
|
|
2279
2728
|
import { lstat, open } from "node:fs/promises";
|
|
2280
|
-
import { dirname, win32 } from "node:path";
|
|
2729
|
+
import { dirname, join as join2, win32 } from "node:path";
|
|
2281
2730
|
import { fileURLToPath } from "node:url";
|
|
2282
2731
|
var SecureFileCustodyError = class extends Error {
|
|
2283
2732
|
name = "SecureFileCustodyError";
|
|
@@ -2296,6 +2745,7 @@ var SecureFileCustodyError = class extends Error {
|
|
|
2296
2745
|
};
|
|
2297
2746
|
var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
|
|
2298
2747
|
var WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES = 4096;
|
|
2748
|
+
var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
|
|
2299
2749
|
var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
|
|
2300
2750
|
var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
|
|
2301
2751
|
function secureOpenFlags(flags, platform) {
|
|
@@ -2338,7 +2788,7 @@ async function assertWindowsIdentityStable(handle, first, path) {
|
|
|
2338
2788
|
}
|
|
2339
2789
|
async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
|
|
2340
2790
|
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
|
|
2341
|
-
const result = await
|
|
2791
|
+
const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
|
|
2342
2792
|
if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
|
|
2343
2793
|
if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
|
|
2344
2794
|
if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
|
|
@@ -2346,18 +2796,46 @@ async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
|
|
|
2346
2796
|
}
|
|
2347
2797
|
async function createRandomPrivateFileWithSecurefs(path, byteLength2, custody = {}) {
|
|
2348
2798
|
if (!Number.isSafeInteger(byteLength2) || byteLength2 < 1 || byteLength2 > WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES) throw new TypeError(`The securefs random-file size must be between 1 and ${WINDOWS_SECUREFS_MAX_RANDOM_FILE_BYTES} bytes.`);
|
|
2349
|
-
const result = await
|
|
2799
|
+
const result = await runSecurefsCommand(["internal", "securefs", "create-random-private-file", path, String(byteLength2)], 0, custody);
|
|
2350
2800
|
if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
|
|
2351
2801
|
if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned unexpected creation bytes.");
|
|
2352
2802
|
if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid creation result.");
|
|
2353
2803
|
throw securefsRefusal(result.stderr);
|
|
2354
2804
|
}
|
|
2355
|
-
async function
|
|
2356
|
-
|
|
2357
|
-
|
|
2805
|
+
async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
|
|
2806
|
+
const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
|
|
2807
|
+
if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
|
|
2808
|
+
if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
|
|
2809
|
+
throw securefsRefusal(result.stderr);
|
|
2810
|
+
}
|
|
2811
|
+
async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
|
|
2812
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > WINDOWS_SECUREFS_MAX_WRITE_BYTES || bytes.byteLength > maxBytes) throw new TypeError("The securefs write bound or payload is invalid.");
|
|
2813
|
+
const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
|
|
2814
|
+
if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
|
|
2815
|
+
if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
|
|
2816
|
+
throw securefsRefusal(result.stderr);
|
|
2817
|
+
}
|
|
2818
|
+
async function isPrivateWindowsDirectory(path, custody = {}) {
|
|
2819
|
+
await lstat(path);
|
|
2820
|
+
try {
|
|
2821
|
+
const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
|
|
2822
|
+
if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
|
|
2823
|
+
if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
|
|
2824
|
+
if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
|
|
2825
|
+
const refusal = securefsRefusal(result.stderr);
|
|
2826
|
+
if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
|
|
2827
|
+
throw refusal;
|
|
2828
|
+
} catch (error) {
|
|
2829
|
+
if (error instanceof SecureFileCustodyError) throw error;
|
|
2830
|
+
throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
async function runSecurefsCommand(args, maxBytes, custody, stdin) {
|
|
2834
|
+
if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
|
|
2835
|
+
const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
|
|
2358
2836
|
const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
|
|
2359
2837
|
return await new Promise((resolve, reject) => {
|
|
2360
|
-
execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
|
|
2838
|
+
const child = execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
|
|
2361
2839
|
const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
|
|
2362
2840
|
if (exitCode === null) {
|
|
2363
2841
|
reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
|
|
@@ -2365,6 +2843,8 @@ async function runWindowsSecurefs(args, maxBytes, custody) {
|
|
|
2365
2843
|
}
|
|
2366
2844
|
resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
|
|
2367
2845
|
});
|
|
2846
|
+
child.stdin?.on("error", () => void 0);
|
|
2847
|
+
child.stdin?.end(stdin);
|
|
2368
2848
|
});
|
|
2369
2849
|
}
|
|
2370
2850
|
function securefsRefusal(stderr) {
|
|
@@ -2382,9 +2862,9 @@ function securefsRefusal(stderr) {
|
|
|
2382
2862
|
if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
|
|
2383
2863
|
return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
|
|
2384
2864
|
}
|
|
2385
|
-
function resolveInstalledHostExecutable() {
|
|
2865
|
+
function resolveInstalledHostExecutable(platform) {
|
|
2386
2866
|
const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
|
|
2387
|
-
return win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
|
|
2867
|
+
return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
|
|
2388
2868
|
}
|
|
2389
2869
|
function isRecord(value) {
|
|
2390
2870
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -2400,6 +2880,11 @@ function isPrivateFileMode(mode, platform = process.platform, _handle) {
|
|
|
2400
2880
|
if (platform === "win32") return false;
|
|
2401
2881
|
return (mode & 63) === 0;
|
|
2402
2882
|
}
|
|
2883
|
+
async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
|
|
2884
|
+
if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
|
|
2885
|
+
const entry = await lstat(path);
|
|
2886
|
+
return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
|
|
2887
|
+
}
|
|
2403
2888
|
|
|
2404
2889
|
// host/relay/src/host-producer-core.ts
|
|
2405
2890
|
var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
|
|
@@ -2408,65 +2893,78 @@ function isHostTranscriptCursorReason(value) {
|
|
|
2408
2893
|
}
|
|
2409
2894
|
var TRANSCRIPT_MISSING_REASON = "transcript_missing";
|
|
2410
2895
|
var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
|
|
2411
|
-
var
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
const
|
|
2896
|
+
var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
|
|
2897
|
+
function mergeHostInvocationHumanMessageWindow(existing, chronological) {
|
|
2898
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2899
|
+
const newestFirst = [];
|
|
2900
|
+
for (const message of [...chronological].reverse()) {
|
|
2901
|
+
if (seen.has(message.host_input_ref)) continue;
|
|
2902
|
+
seen.add(message.host_input_ref);
|
|
2903
|
+
newestFirst.push(message);
|
|
2904
|
+
}
|
|
2905
|
+
for (const message of existing?.messages ?? []) {
|
|
2906
|
+
if (seen.has(message.host_input_ref)) continue;
|
|
2907
|
+
seen.add(message.host_input_ref);
|
|
2908
|
+
newestFirst.push(message);
|
|
2909
|
+
}
|
|
2910
|
+
return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
|
|
2911
|
+
}
|
|
2912
|
+
async function readRegisteredHostInvocationHumanMessageWindow(listRegistrations, readCursor, identity, decodeLine) {
|
|
2913
|
+
try {
|
|
2914
|
+
const registration = await findLiveHostInvocationRegistration(listRegistrations, identity);
|
|
2915
|
+
const cursor = await readCursor(registration);
|
|
2916
|
+
assertUsableHostInvocationHumanMessageCursor(cursor, registration);
|
|
2917
|
+
return await readHostInvocationHumanMessageWindow(registration, cursor, (line) => decodeLine(line, registration, cursor));
|
|
2918
|
+
} catch {
|
|
2919
|
+
throw new TypeError("context_unavailable");
|
|
2920
|
+
}
|
|
2921
|
+
}
|
|
2922
|
+
async function findLiveHostInvocationRegistration(listRegistrations, identity) {
|
|
2923
|
+
const registration = (await listRegistrations()).find((candidate) => candidate.host_source_ref === identity.host_source_ref && candidate.host_session_ref === identity.host_session_ref && Date.parse(candidate.expires_at) > Date.now());
|
|
2924
|
+
if (registration === void 0) throw new TypeError("context_unavailable");
|
|
2925
|
+
return registration;
|
|
2926
|
+
}
|
|
2927
|
+
function assertUsableHostInvocationHumanMessageCursor(cursor, registration) {
|
|
2928
|
+
if (cursor === null || cursor.status !== "active" || cursor.human_message_window === void 0 || cursor.host_source_ref !== registration.host_source_ref || cursor.host_session_ref !== registration.host_session_ref || cursor.transcript_path !== registration.transcript_path) throw new TypeError("context_unavailable");
|
|
2929
|
+
}
|
|
2930
|
+
async function readHostInvocationHumanMessageWindow(registration, cursor, decodeLine) {
|
|
2931
|
+
const handle = await openNoFollow(registration.transcript_path);
|
|
2415
2932
|
try {
|
|
2416
2933
|
const stats = await handle.stat();
|
|
2417
|
-
|
|
2418
|
-
const
|
|
2419
|
-
const
|
|
2420
|
-
|
|
2421
|
-
return
|
|
2934
|
+
await assertHostInvocationHumanMessageSource(registration, cursor, handle, stats);
|
|
2935
|
+
const capturedSize = stats.size;
|
|
2936
|
+
const delta = await readHostInvocationHumanMessageDelta(handle, cursor.offset, capturedSize, decodeLine);
|
|
2937
|
+
if ((await handle.stat()).size < capturedSize) throw new TypeError("context_unavailable");
|
|
2938
|
+
return mergeHostInvocationHumanMessageWindow(cursor.human_message_window, delta);
|
|
2422
2939
|
} finally {
|
|
2423
2940
|
await handle.close();
|
|
2424
2941
|
}
|
|
2425
2942
|
}
|
|
2426
|
-
async function
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
const { bytesRead } = await handle.read(output, offset, output.length - offset, start + offset);
|
|
2431
|
-
if (bytesRead === 0) break;
|
|
2432
|
-
offset += bytesRead;
|
|
2433
|
-
}
|
|
2434
|
-
return output.subarray(0, offset);
|
|
2435
|
-
}
|
|
2436
|
-
function dropPartialLeadingTranscriptRecord(bytes) {
|
|
2437
|
-
if (bytes.length === 0) return bytes;
|
|
2438
|
-
const newline = bytes.indexOf(10);
|
|
2439
|
-
return newline < 0 ? Buffer.alloc(0) : bytes.subarray(newline + 1);
|
|
2943
|
+
async function assertHostInvocationHumanMessageSource(registration, cursor, handle, stats) {
|
|
2944
|
+
if (!stats.isFile() || process.platform !== "win32" && !isSelfOwned(stats.uid)) throw new TypeError("context_unavailable");
|
|
2945
|
+
const reason = transcriptCursorIdentityReason(cursor, registration.transcript_path, String(stats.dev), String(stats.ino)) ?? await transcriptCursorBoundsReason(handle, cursor, stats.size);
|
|
2946
|
+
if (reason !== null || cursor.device === void 0 || cursor.inode === void 0 || stats.size - cursor.offset > HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES) throw new TypeError("context_unavailable");
|
|
2440
2947
|
}
|
|
2441
|
-
async function
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2948
|
+
async function readHostInvocationHumanMessageDelta(handle, start, capturedSize, decodeLine) {
|
|
2949
|
+
const delta = [];
|
|
2950
|
+
let offset = start;
|
|
2951
|
+
while (offset < capturedSize) {
|
|
2952
|
+
const complete = await readTranscriptCompleteChunk(handle, offset, capturedSize);
|
|
2953
|
+
if (complete === "empty" || complete === "partial") throw new TypeError("context_unavailable");
|
|
2954
|
+
decodeHostInvocationHumanMessageChunk(complete, decodeLine, delta);
|
|
2955
|
+
offset += complete.length;
|
|
2448
2956
|
}
|
|
2957
|
+
return delta;
|
|
2449
2958
|
}
|
|
2450
|
-
|
|
2451
|
-
const
|
|
2452
|
-
|
|
2453
|
-
const
|
|
2454
|
-
if (incompleteTail) lines.pop();
|
|
2455
|
-
let truncated = tail.truncated || incompleteTail;
|
|
2456
|
-
const newestFirst = [];
|
|
2457
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2458
|
-
for (const line of lines.reverse()) {
|
|
2959
|
+
function decodeHostInvocationHumanMessageChunk(complete, decodeLine, delta) {
|
|
2960
|
+
const lines = new TextDecoder("utf-8", { fatal: true }).decode(complete).split("\n");
|
|
2961
|
+
if (lines.at(-1) !== "") throw new TypeError("context_unavailable");
|
|
2962
|
+
for (const line of lines.slice(0, -1)) {
|
|
2459
2963
|
if (line.length === 0) continue;
|
|
2460
2964
|
const message = decodeLine(line);
|
|
2461
|
-
if (message === "malformed")
|
|
2462
|
-
|
|
2463
|
-
continue;
|
|
2464
|
-
}
|
|
2465
|
-
if (message === null || seen.has(message.host_input_ref)) continue;
|
|
2466
|
-
seen.add(message.host_input_ref);
|
|
2467
|
-
newestFirst.push(message);
|
|
2965
|
+
if (message === "malformed") throw new TypeError("context_unavailable");
|
|
2966
|
+
if (message !== null) delta.push(message);
|
|
2468
2967
|
}
|
|
2469
|
-
return boundCealHostInvocationHumanMessageWindow(newestFirst, truncated);
|
|
2470
2968
|
}
|
|
2471
2969
|
function transcriptScanFailureKind(error, adapterFailureKind) {
|
|
2472
2970
|
if (transcriptErrorCode(error) === "ELOOP") return "symlink";
|
|
@@ -2524,10 +3022,10 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
|
|
|
2524
3022
|
return null;
|
|
2525
3023
|
}
|
|
2526
3024
|
function transcriptSha256(value) {
|
|
2527
|
-
return
|
|
3025
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
2528
3026
|
}
|
|
2529
3027
|
function transcriptObjectSha256(value) {
|
|
2530
|
-
return
|
|
3028
|
+
return createHash4("sha256").update(JSON.stringify(value), "utf8").digest("hex");
|
|
2531
3029
|
}
|
|
2532
3030
|
function isTranscriptRecord(value) {
|
|
2533
3031
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -2802,24 +3300,1182 @@ function errorCode2(error) {
|
|
|
2802
3300
|
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
2803
3301
|
}
|
|
2804
3302
|
|
|
2805
|
-
// host/relay/src/
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
var
|
|
2812
|
-
var
|
|
2813
|
-
var
|
|
3303
|
+
// host/relay/src/host-usage-facts-store.ts
|
|
3304
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
3305
|
+
import { constants as constants2 } from "node:fs";
|
|
3306
|
+
import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
|
|
3307
|
+
import { dirname as dirname3, join as join3 } from "node:path";
|
|
3308
|
+
var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
|
|
3309
|
+
var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
|
|
3310
|
+
var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
|
|
3311
|
+
var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
|
|
3312
|
+
var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
|
|
3313
|
+
var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
|
|
3314
|
+
var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
|
|
3315
|
+
var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
|
|
3316
|
+
var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
|
|
3317
|
+
var HostUsageFactsStore = class {
|
|
3318
|
+
root;
|
|
3319
|
+
sessions;
|
|
3320
|
+
batches;
|
|
3321
|
+
platform;
|
|
3322
|
+
custody;
|
|
3323
|
+
afterPendingWrite;
|
|
3324
|
+
afterBatchPublish;
|
|
3325
|
+
sessionDirectoryCursor;
|
|
3326
|
+
constructor(options) {
|
|
3327
|
+
this.root = join3(options.outbox_dir, "usage-facts");
|
|
3328
|
+
this.sessions = join3(this.root, "sessions");
|
|
3329
|
+
this.batches = join3(this.root, "batches");
|
|
3330
|
+
this.platform = options.platform ?? process.platform;
|
|
3331
|
+
this.custody = options.secure_file_custody ?? {};
|
|
3332
|
+
this.afterPendingWrite = options.afterPendingWrite;
|
|
3333
|
+
this.afterBatchPublish = options.afterBatchPublish;
|
|
3334
|
+
}
|
|
3335
|
+
async prepare() {
|
|
3336
|
+
for (const directory of [this.root, this.sessions, this.batches]) {
|
|
3337
|
+
await preparePrivateDirectory(directory, this.platform, this.custody);
|
|
3338
|
+
}
|
|
3339
|
+
}
|
|
3340
|
+
async close() {
|
|
3341
|
+
const cursor = this.sessionDirectoryCursor;
|
|
3342
|
+
this.sessionDirectoryCursor = void 0;
|
|
3343
|
+
await cursor?.close();
|
|
3344
|
+
}
|
|
3345
|
+
async readState(producer, hostSourceRef, hostSessionRef) {
|
|
3346
|
+
await this.prepare();
|
|
3347
|
+
const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
3348
|
+
const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
3349
|
+
if (value === null) return null;
|
|
3350
|
+
validateState(value, producer, hostSourceRef, hostSessionRef);
|
|
3351
|
+
return value;
|
|
3352
|
+
}
|
|
3353
|
+
createState(producer, hostSourceRef, hostSessionRef) {
|
|
3354
|
+
return {
|
|
3355
|
+
schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
|
|
3356
|
+
producer,
|
|
3357
|
+
host_source_ref: hostSourceRef,
|
|
3358
|
+
host_session_ref: hostSessionRef,
|
|
3359
|
+
cursors: {},
|
|
3360
|
+
eligible_batches: [],
|
|
3361
|
+
coverage_gaps: [],
|
|
3362
|
+
coverage_gap_created_at: null
|
|
3363
|
+
};
|
|
3364
|
+
}
|
|
3365
|
+
async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
|
|
3366
|
+
let state = await this.readState(producer, hostSourceRef, hostSessionRef);
|
|
3367
|
+
if (state === null) {
|
|
3368
|
+
state = this.createState(producer, hostSourceRef, hostSessionRef);
|
|
3369
|
+
state = await this.writeCursor(state, sourceSlot, initial);
|
|
3370
|
+
}
|
|
3371
|
+
state = await this.recoverPending(state);
|
|
3372
|
+
if (state.quarantined_reason !== void 0) return null;
|
|
3373
|
+
state = await this.commitCoverageGaps(state, createdAt);
|
|
3374
|
+
const cursor = state.cursors[sourceSlot];
|
|
3375
|
+
return cursor === void 0 ? null : { state, cursor };
|
|
3376
|
+
}
|
|
3377
|
+
async writeCursor(state, sourceSlot, cursor) {
|
|
3378
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3379
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3380
|
+
if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
|
|
3381
|
+
const current = latest.cursors[sourceSlot];
|
|
3382
|
+
if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
|
|
3383
|
+
const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
|
|
3384
|
+
await this.writeState(updated);
|
|
3385
|
+
return updated;
|
|
3386
|
+
});
|
|
3387
|
+
}
|
|
3388
|
+
async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
|
|
3389
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3390
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3391
|
+
return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
|
|
3392
|
+
});
|
|
3393
|
+
}
|
|
3394
|
+
async recoverPending(state) {
|
|
3395
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3396
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3397
|
+
const recovered = await this.finishPendingTransition(latest);
|
|
3398
|
+
await this.sweepOrphanedBatches(recovered);
|
|
3399
|
+
return recovered;
|
|
3400
|
+
});
|
|
3401
|
+
}
|
|
3402
|
+
/** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
|
|
3403
|
+
async sweepOrphanedBatches(state) {
|
|
3404
|
+
await this.prepare();
|
|
3405
|
+
const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
|
|
3406
|
+
await preparePrivateDirectory(directoryPath, this.platform, this.custody);
|
|
3407
|
+
const expected = expectedBatchNames(state);
|
|
3408
|
+
const directory = await opendir(directoryPath);
|
|
3409
|
+
let inspected = 0;
|
|
3410
|
+
let deleted = 0;
|
|
3411
|
+
try {
|
|
3412
|
+
while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
|
|
3413
|
+
const entry = await directory.read();
|
|
3414
|
+
if (entry === null) break;
|
|
3415
|
+
inspected += 1;
|
|
3416
|
+
if (!isOrphanBatchEntry(entry, expected)) continue;
|
|
3417
|
+
await unlink2(join3(directoryPath, entry.name));
|
|
3418
|
+
deleted += 1;
|
|
3419
|
+
}
|
|
3420
|
+
} finally {
|
|
3421
|
+
await directory.close();
|
|
3422
|
+
}
|
|
3423
|
+
if (deleted > 0) await syncDirectory(directoryPath, this.platform);
|
|
3424
|
+
return deleted;
|
|
3425
|
+
}
|
|
3426
|
+
async commitCoverageGaps(state, createdAt) {
|
|
3427
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3428
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3429
|
+
if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
|
|
3430
|
+
const sourceRanges = coverageRanges(latest.coverage_gaps);
|
|
3431
|
+
const canonical = createCealHostUsageBatch({
|
|
3432
|
+
host_source_ref: latest.host_source_ref,
|
|
3433
|
+
host_session_ref: latest.host_session_ref,
|
|
3434
|
+
created_at: latest.coverage_gap_created_at ?? createdAt,
|
|
3435
|
+
source_ranges: sourceRanges,
|
|
3436
|
+
facts: [],
|
|
3437
|
+
coverage_gaps: latest.coverage_gaps
|
|
3438
|
+
});
|
|
3439
|
+
const cursor = firstCursor(latest);
|
|
3440
|
+
if (cursor === null) return latest;
|
|
3441
|
+
return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
|
|
3442
|
+
});
|
|
3443
|
+
}
|
|
3444
|
+
async nextUploadCandidate(producer, hostSourceRef) {
|
|
3445
|
+
await this.prepare();
|
|
3446
|
+
const names = await this.readNextSessionNames();
|
|
3447
|
+
for (const name of names) {
|
|
3448
|
+
const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
3449
|
+
if (state === null) continue;
|
|
3450
|
+
validateStateOwner(state, producer, hostSourceRef);
|
|
3451
|
+
let validated = state;
|
|
3452
|
+
if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
|
|
3453
|
+
else validated = await this.recoverPending(validated);
|
|
3454
|
+
if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
|
|
3455
|
+
const next = validated.eligible_batches[0];
|
|
3456
|
+
if (next === void 0) continue;
|
|
3457
|
+
const batch = await this.readBatch(validated, next.batch_ref);
|
|
3458
|
+
return { state: validated, batch };
|
|
3459
|
+
}
|
|
3460
|
+
return null;
|
|
3461
|
+
}
|
|
3462
|
+
async readNextSessionNames() {
|
|
3463
|
+
this.sessionDirectoryCursor ??= await opendir(this.sessions);
|
|
3464
|
+
const names = [];
|
|
3465
|
+
let inspected = 0;
|
|
3466
|
+
while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
|
|
3467
|
+
const entry = await this.sessionDirectoryCursor.read();
|
|
3468
|
+
if (entry === null) {
|
|
3469
|
+
await this.sessionDirectoryCursor.close();
|
|
3470
|
+
this.sessionDirectoryCursor = void 0;
|
|
3471
|
+
break;
|
|
3472
|
+
}
|
|
3473
|
+
inspected += 1;
|
|
3474
|
+
if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
|
|
3475
|
+
}
|
|
3476
|
+
return names;
|
|
3477
|
+
}
|
|
3478
|
+
async acknowledge(state, batchRef) {
|
|
3479
|
+
await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3480
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3481
|
+
if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
|
|
3482
|
+
const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
|
|
3483
|
+
if (remaining.length === latest.eligible_batches.length) return;
|
|
3484
|
+
await this.writeState({ ...latest, eligible_batches: remaining });
|
|
3485
|
+
await removeFileIfPresent(this.batchPath(state, batchRef));
|
|
3486
|
+
});
|
|
3487
|
+
}
|
|
3488
|
+
async quarantine(state, reason) {
|
|
3489
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3490
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3491
|
+
const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
|
|
3492
|
+
await this.writeState(updated);
|
|
3493
|
+
return updated;
|
|
3494
|
+
});
|
|
3495
|
+
}
|
|
3496
|
+
async retireCursor(state, sourceSlot, cursor, gap) {
|
|
3497
|
+
return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
|
|
3498
|
+
}
|
|
3499
|
+
async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
|
|
3500
|
+
if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
|
|
3501
|
+
if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
|
|
3502
|
+
const queued = await this.publishTransitionBatch(state, batch);
|
|
3503
|
+
const pending = {
|
|
3504
|
+
source_slot: sourceSlot,
|
|
3505
|
+
before_cursor: beforeCursor,
|
|
3506
|
+
after_cursor: afterCursor,
|
|
3507
|
+
batch_ref: queued.batch_ref,
|
|
3508
|
+
batch_bytes: queued.batch_bytes,
|
|
3509
|
+
gap_delta: [...gapDelta, ...queued.overflow_gaps],
|
|
3510
|
+
clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
|
|
3511
|
+
};
|
|
3512
|
+
const prepared = { ...state, pending_transition: pending };
|
|
3513
|
+
await this.writeState(prepared);
|
|
3514
|
+
await this.afterPendingWrite?.();
|
|
3515
|
+
return await this.finishPendingTransition(prepared);
|
|
3516
|
+
}
|
|
3517
|
+
async publishTransitionBatch(state, batch) {
|
|
3518
|
+
if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
|
|
3519
|
+
const serialized = serializeBatch(batch);
|
|
3520
|
+
if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
|
|
3521
|
+
await this.writeImmutableBatch(state, batch, serialized);
|
|
3522
|
+
await this.afterBatchPublish?.();
|
|
3523
|
+
return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
|
|
3524
|
+
}
|
|
3525
|
+
async finishPendingTransition(state) {
|
|
3526
|
+
const pending = state.pending_transition;
|
|
3527
|
+
if (pending === void 0 || state.quarantined_reason !== void 0) return state;
|
|
3528
|
+
const current = state.cursors[pending.source_slot];
|
|
3529
|
+
if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
|
|
3530
|
+
const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
|
|
3531
|
+
await this.writeState(quarantined);
|
|
3532
|
+
return quarantined;
|
|
3533
|
+
}
|
|
3534
|
+
let cursors = state.cursors;
|
|
3535
|
+
if (!cursorMatches(current, pending.after_cursor)) {
|
|
3536
|
+
const next = { ...state.cursors };
|
|
3537
|
+
if (pending.after_cursor === null) delete next[pending.source_slot];
|
|
3538
|
+
else next[pending.source_slot] = pending.after_cursor;
|
|
3539
|
+
cursors = next;
|
|
3540
|
+
}
|
|
3541
|
+
const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
|
|
3542
|
+
const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
|
|
3543
|
+
const { pending_transition: _pendingTransition, ...settledState } = state;
|
|
3544
|
+
const updated = {
|
|
3545
|
+
...settledState,
|
|
3546
|
+
cursors,
|
|
3547
|
+
eligible_batches: eligible,
|
|
3548
|
+
coverage_gaps: gaps,
|
|
3549
|
+
coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
3550
|
+
};
|
|
3551
|
+
await this.writeState(updated);
|
|
3552
|
+
return updated;
|
|
3553
|
+
}
|
|
3554
|
+
async writeImmutableBatch(state, batch, bytes) {
|
|
3555
|
+
const path = this.batchPath(state, batch.batch_ref);
|
|
3556
|
+
await preparePrivateDirectory(dirname3(path), this.platform, this.custody);
|
|
3557
|
+
const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
3558
|
+
if (existing !== null) {
|
|
3559
|
+
if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
|
|
3560
|
+
await syncExistingFile(path, this.platform);
|
|
3561
|
+
return;
|
|
3562
|
+
}
|
|
3563
|
+
if (this.platform === "win32") {
|
|
3564
|
+
await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
|
|
3565
|
+
return;
|
|
3566
|
+
}
|
|
3567
|
+
let handle;
|
|
3568
|
+
try {
|
|
3569
|
+
handle = await openNoFollow(path, constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY, 384, this.platform);
|
|
3570
|
+
await handle.writeFile(bytes);
|
|
3571
|
+
await handle.sync();
|
|
3572
|
+
await handle.close();
|
|
3573
|
+
handle = void 0;
|
|
3574
|
+
await syncDirectory(dirname3(path), this.platform);
|
|
3575
|
+
} catch (error) {
|
|
3576
|
+
await handle?.close().catch(() => void 0);
|
|
3577
|
+
if (errorCode3(error) === "EEXIST") {
|
|
3578
|
+
const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
3579
|
+
if (winner !== null && winner.equals(bytes)) {
|
|
3580
|
+
await syncExistingFile(path, this.platform);
|
|
3581
|
+
return;
|
|
3582
|
+
}
|
|
3583
|
+
throw new Error("Host usage facts batch reference conflicts with existing bytes.");
|
|
3584
|
+
}
|
|
3585
|
+
await removeFileIfPresent(path).catch(() => void 0);
|
|
3586
|
+
throw error;
|
|
3587
|
+
}
|
|
3588
|
+
}
|
|
3589
|
+
async readBatch(state, batchRef) {
|
|
3590
|
+
const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
3591
|
+
if (bytes === null) throw new Error("Host usage facts batch object is missing.");
|
|
3592
|
+
let value;
|
|
3593
|
+
try {
|
|
3594
|
+
value = JSON.parse(bytes.toString("utf8"));
|
|
3595
|
+
} catch {
|
|
3596
|
+
throw new Error("Host usage facts batch object is malformed.");
|
|
3597
|
+
}
|
|
3598
|
+
validateCealHostUsageBatch(value);
|
|
3599
|
+
if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
|
|
3600
|
+
return value;
|
|
3601
|
+
}
|
|
3602
|
+
async writeState(state) {
|
|
3603
|
+
validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
|
|
3604
|
+
const bytes = Buffer.from(JSON.stringify(state), "utf8");
|
|
3605
|
+
if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
|
|
3606
|
+
await this.prepare();
|
|
3607
|
+
const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
|
|
3608
|
+
if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
|
|
3609
|
+
else await durableAtomicReplace(path, bytes);
|
|
3610
|
+
}
|
|
3611
|
+
async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
|
|
3612
|
+
const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
3613
|
+
const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
|
|
3614
|
+
let release;
|
|
3615
|
+
const gate = new Promise((resolve) => {
|
|
3616
|
+
release = resolve;
|
|
3617
|
+
});
|
|
3618
|
+
const tail = previous.then(() => gate);
|
|
3619
|
+
SESSION_TRANSITION_TAILS.set(key, tail);
|
|
3620
|
+
await previous;
|
|
3621
|
+
try {
|
|
3622
|
+
return await run();
|
|
3623
|
+
} finally {
|
|
3624
|
+
release?.();
|
|
3625
|
+
if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
|
|
3626
|
+
}
|
|
3627
|
+
}
|
|
3628
|
+
sessionPath(producer, hostSourceRef, hostSessionRef) {
|
|
3629
|
+
return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
|
|
3630
|
+
}
|
|
3631
|
+
batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
|
|
3632
|
+
const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
|
|
3633
|
+
return join3(this.batches, sessionName.slice(0, -5));
|
|
3634
|
+
}
|
|
3635
|
+
batchPath(state, batchRef) {
|
|
3636
|
+
return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
|
|
3637
|
+
}
|
|
3638
|
+
};
|
|
3639
|
+
function serializeBatch(batch) {
|
|
3640
|
+
validateCealHostUsageBatch(batch);
|
|
3641
|
+
return Buffer.from(JSON.stringify(batch), "utf8");
|
|
3642
|
+
}
|
|
3643
|
+
function batchFileName(batchRef) {
|
|
3644
|
+
const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
|
|
3645
|
+
if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
|
|
3646
|
+
return `${digest2}.json`;
|
|
3647
|
+
}
|
|
3648
|
+
function expectedBatchNames(state) {
|
|
3649
|
+
const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
|
|
3650
|
+
const pending = state.pending_transition?.batch_ref;
|
|
3651
|
+
if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
|
|
3652
|
+
return expected;
|
|
3653
|
+
}
|
|
3654
|
+
function isOrphanBatchEntry(entry, expected) {
|
|
3655
|
+
return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
|
|
3656
|
+
}
|
|
3657
|
+
function hasOutboxCapacity(state, bytes) {
|
|
3658
|
+
const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
|
|
3659
|
+
return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
|
|
3660
|
+
}
|
|
3661
|
+
function overflowCoverageGaps(batch) {
|
|
3662
|
+
const count = batch.facts.length;
|
|
3663
|
+
const gaps = [...batch.coverage_gaps];
|
|
3664
|
+
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 });
|
|
3665
|
+
return gaps;
|
|
3666
|
+
}
|
|
3667
|
+
function appendEligible(existing, next) {
|
|
3668
|
+
if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
|
|
3669
|
+
if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
|
|
3670
|
+
return [...existing, next];
|
|
3671
|
+
}
|
|
3672
|
+
function appendCoverageGaps(existing, added) {
|
|
3673
|
+
if (added.length === 0) return existing;
|
|
3674
|
+
const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
|
|
3675
|
+
for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
|
|
3676
|
+
const combined = [...byIdentity.values()];
|
|
3677
|
+
if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
|
|
3678
|
+
const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
|
|
3679
|
+
return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
|
|
3680
|
+
}
|
|
3681
|
+
function coverageRanges(gaps) {
|
|
3682
|
+
const ranges = /* @__PURE__ */ new Map();
|
|
3683
|
+
for (const gap of gaps) {
|
|
3684
|
+
if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
|
|
3685
|
+
const current = ranges.get(gap.source_file_ref);
|
|
3686
|
+
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 });
|
|
3687
|
+
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) });
|
|
3688
|
+
}
|
|
3689
|
+
return [...ranges.values()];
|
|
3690
|
+
}
|
|
3691
|
+
function firstCursor(state) {
|
|
3692
|
+
const entry = Object.entries(state.cursors)[0];
|
|
3693
|
+
return entry === void 0 ? null : entry;
|
|
3694
|
+
}
|
|
3695
|
+
function sameCursor(left, right) {
|
|
3696
|
+
return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
|
|
3697
|
+
}
|
|
3698
|
+
function cursorMatches(left, right) {
|
|
3699
|
+
return right === null ? left === void 0 : sameCursor(left, right);
|
|
3700
|
+
}
|
|
3701
|
+
function validateState(value, producer, hostSourceRef, hostSessionRef) {
|
|
3702
|
+
validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
|
|
3703
|
+
validateStateShape(value);
|
|
3704
|
+
validateStateLimits(value);
|
|
3705
|
+
validateStateContents(value);
|
|
3706
|
+
}
|
|
3707
|
+
function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
|
|
3708
|
+
if (!isRecord2(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.");
|
|
3709
|
+
}
|
|
3710
|
+
function validateStateLimits(value) {
|
|
3711
|
+
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.");
|
|
3712
|
+
}
|
|
3713
|
+
function validateStateContents(value) {
|
|
3714
|
+
for (const [slot, cursor] of Object.entries(value.cursors)) {
|
|
3715
|
+
validateSourceSlot(slot);
|
|
3716
|
+
validateFileCursor(cursor);
|
|
3717
|
+
}
|
|
3718
|
+
for (const item of value.eligible_batches) validateEligibleBatch(item);
|
|
3719
|
+
if (value.pending_transition !== void 0) validatePending(value.pending_transition);
|
|
3720
|
+
for (const gap of value.coverage_gaps) validateGap(gap);
|
|
3721
|
+
validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
|
|
3722
|
+
}
|
|
3723
|
+
function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
|
|
3724
|
+
if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
|
|
3725
|
+
if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
|
|
3726
|
+
}
|
|
3727
|
+
function validateStateOwner(value, producer, hostSourceRef) {
|
|
3728
|
+
if (!isRecord2(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
|
|
3729
|
+
validateState(value, producer, hostSourceRef, String(value.host_session_ref));
|
|
3730
|
+
}
|
|
3731
|
+
function validateStateShape(value) {
|
|
3732
|
+
const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
|
|
3733
|
+
const optional = ["pending_transition", "quarantined_reason"];
|
|
3734
|
+
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.");
|
|
3735
|
+
if (!isRecord2(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.");
|
|
3736
|
+
}
|
|
3737
|
+
function validateFileCursor(value) {
|
|
3738
|
+
if (!isRecord2(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.");
|
|
3739
|
+
validateCursorIdentity(value);
|
|
3740
|
+
validateCursorOffsets(value);
|
|
3741
|
+
validateCursorContext(value);
|
|
3742
|
+
if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
|
|
3743
|
+
if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
|
|
3744
|
+
}
|
|
3745
|
+
function validateCursorIdentity(value) {
|
|
3746
|
+
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.");
|
|
3747
|
+
}
|
|
3748
|
+
function validateCursorOffsets(value) {
|
|
3749
|
+
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.");
|
|
3750
|
+
}
|
|
3751
|
+
function validateCursorContext(value) {
|
|
3752
|
+
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.");
|
|
3753
|
+
}
|
|
3754
|
+
function validOptionalText(value, maximum) {
|
|
3755
|
+
return value === null || typeof value === "string" && value.length <= maximum;
|
|
3756
|
+
}
|
|
3757
|
+
function validateCodexCounts(value) {
|
|
3758
|
+
if (!isRecord2(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.");
|
|
3759
|
+
if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
|
|
3760
|
+
}
|
|
3761
|
+
function validatePending(value) {
|
|
3762
|
+
if (!isRecord2(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.");
|
|
3763
|
+
validatePendingCursors(value);
|
|
3764
|
+
validatePendingBatch(value);
|
|
3765
|
+
validatePendingFields(value);
|
|
3766
|
+
for (const gap of value.gap_delta) validateGap(gap);
|
|
3767
|
+
}
|
|
3768
|
+
function validatePendingCursors(value) {
|
|
3769
|
+
validateSourceSlot(value.source_slot);
|
|
3770
|
+
validateFileCursor(value.before_cursor);
|
|
3771
|
+
if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
|
|
3772
|
+
}
|
|
3773
|
+
function validatePendingBatch(value) {
|
|
3774
|
+
if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
|
|
3775
|
+
}
|
|
3776
|
+
function validatePendingFields(value) {
|
|
3777
|
+
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.");
|
|
3778
|
+
}
|
|
3779
|
+
function validateEligibleBatch(value) {
|
|
3780
|
+
if (!isRecord2(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.");
|
|
3781
|
+
}
|
|
3782
|
+
function validateGap(value) {
|
|
3783
|
+
try {
|
|
3784
|
+
validateCealHostUsageCoverageGap(value);
|
|
3785
|
+
} catch {
|
|
3786
|
+
throw new Error("Host usage facts coverage gap is invalid.");
|
|
3787
|
+
}
|
|
3788
|
+
}
|
|
3789
|
+
function validateSourceSlot(value) {
|
|
3790
|
+
if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
|
|
3791
|
+
}
|
|
3792
|
+
async function readOptionalJson(path, maxBytes, platform, custody) {
|
|
3793
|
+
const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
|
|
3794
|
+
if (bytes === null) return null;
|
|
3795
|
+
try {
|
|
3796
|
+
return JSON.parse(bytes.toString("utf8"));
|
|
3797
|
+
} catch {
|
|
3798
|
+
throw new Error("Host usage facts state JSON is malformed.");
|
|
3799
|
+
}
|
|
3800
|
+
}
|
|
3801
|
+
async function readOptionalBytes(path, maxBytes, platform, custody) {
|
|
3802
|
+
if (platform === "win32") {
|
|
3803
|
+
try {
|
|
3804
|
+
return await readPrivateFileWithSecurefs(path, maxBytes, custody);
|
|
3805
|
+
} catch (error) {
|
|
3806
|
+
if (errorCode3(error) === "ENOENT") return null;
|
|
3807
|
+
throw error;
|
|
3808
|
+
}
|
|
3809
|
+
}
|
|
3810
|
+
let handle;
|
|
3811
|
+
try {
|
|
3812
|
+
handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
|
|
3813
|
+
const stats = await handle.stat();
|
|
3814
|
+
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.");
|
|
3815
|
+
return await handle.readFile();
|
|
3816
|
+
} catch (error) {
|
|
3817
|
+
if (errorCode3(error) === "ENOENT") return null;
|
|
3818
|
+
throw error;
|
|
3819
|
+
} finally {
|
|
3820
|
+
await handle?.close();
|
|
3821
|
+
}
|
|
3822
|
+
}
|
|
3823
|
+
async function preparePrivateDirectory(path, platform, custody) {
|
|
3824
|
+
if (platform === "win32") {
|
|
3825
|
+
await ensurePrivateDirectoryWithSecurefs(path, custody);
|
|
3826
|
+
return;
|
|
3827
|
+
}
|
|
3828
|
+
await mkdir2(path, { recursive: true, mode: 448 });
|
|
3829
|
+
if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
|
|
3830
|
+
}
|
|
3831
|
+
async function syncExistingFile(path, platform) {
|
|
3832
|
+
const handle = await openNoFollow(path, constants2.O_RDONLY, void 0, platform);
|
|
3833
|
+
try {
|
|
3834
|
+
await handle.sync();
|
|
3835
|
+
} finally {
|
|
3836
|
+
await handle.close();
|
|
3837
|
+
}
|
|
3838
|
+
await syncDirectory(dirname3(path), platform);
|
|
3839
|
+
}
|
|
3840
|
+
async function syncDirectory(path, platform) {
|
|
3841
|
+
if (platform === "win32") return;
|
|
3842
|
+
const handle = await open3(path, constants2.O_RDONLY);
|
|
3843
|
+
try {
|
|
3844
|
+
await handle.sync();
|
|
3845
|
+
} finally {
|
|
3846
|
+
await handle.close();
|
|
3847
|
+
}
|
|
3848
|
+
}
|
|
3849
|
+
async function removeFileIfPresent(path) {
|
|
3850
|
+
try {
|
|
3851
|
+
await unlink2(path);
|
|
3852
|
+
} catch (error) {
|
|
3853
|
+
if (errorCode3(error) !== "ENOENT") throw error;
|
|
3854
|
+
}
|
|
3855
|
+
}
|
|
3856
|
+
function sameKeys(value, expected) {
|
|
3857
|
+
return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
|
|
3858
|
+
}
|
|
3859
|
+
function isRecord2(value) {
|
|
3860
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3861
|
+
}
|
|
3862
|
+
function safeInteger2(value) {
|
|
3863
|
+
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
3864
|
+
}
|
|
3865
|
+
function validTimestamp(value) {
|
|
3866
|
+
return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
3867
|
+
}
|
|
3868
|
+
function errorCode3(error) {
|
|
3869
|
+
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
3870
|
+
}
|
|
3871
|
+
function sha2562(value) {
|
|
3872
|
+
return createHash5("sha256").update(value, "utf8").digest("hex");
|
|
3873
|
+
}
|
|
3874
|
+
|
|
3875
|
+
// host/relay/src/host-usage-facts-capture.ts
|
|
3876
|
+
import { constants as constants3 } from "node:fs";
|
|
3877
|
+
var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
|
|
3878
|
+
var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
|
|
3879
|
+
var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
|
|
3880
|
+
var HostUsageTranscriptSourceError = class extends Error {
|
|
3881
|
+
constructor(options) {
|
|
3882
|
+
super("Host usage transcript source could not be read.", options);
|
|
3883
|
+
this.name = "HostUsageTranscriptSourceError";
|
|
3884
|
+
}
|
|
3885
|
+
};
|
|
3886
|
+
async function readHostUsageTranscriptSource(read) {
|
|
3887
|
+
try {
|
|
3888
|
+
return await read();
|
|
3889
|
+
} catch (error) {
|
|
3890
|
+
throw new HostUsageTranscriptSourceError({ cause: error });
|
|
3891
|
+
}
|
|
3892
|
+
}
|
|
3893
|
+
async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
|
|
3894
|
+
if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
|
|
3895
|
+
let failed = false;
|
|
3896
|
+
for (let attempt = 0; attempt < registrations.length; attempt += 1) {
|
|
3897
|
+
const index = (startIndex + attempt) % registrations.length;
|
|
3898
|
+
const registration = registrations[index];
|
|
3899
|
+
if (registration === void 0) continue;
|
|
3900
|
+
try {
|
|
3901
|
+
if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
|
|
3902
|
+
} catch (error) {
|
|
3903
|
+
if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
|
|
3904
|
+
failed = true;
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3907
|
+
return { captured: false, nextIndex: startIndex, failed };
|
|
3908
|
+
}
|
|
3909
|
+
async function openHostUsageTranscriptCursor(input) {
|
|
3910
|
+
const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
|
|
3911
|
+
let source;
|
|
3912
|
+
try {
|
|
3913
|
+
source = await readHostUsageTranscriptSource(() => input.inspect(handle));
|
|
3914
|
+
} catch (error) {
|
|
3915
|
+
await handle.close().catch(() => void 0);
|
|
3916
|
+
throw error;
|
|
3917
|
+
}
|
|
3918
|
+
const sourceFileRef2 = hostUsageSourceFileReference(input.source_kind, input.host_source_ref, input.host_session_ref, source.device, source.inode);
|
|
3919
|
+
let prepared;
|
|
3920
|
+
try {
|
|
3921
|
+
prepared = await input.store.prepareSourceCursor(input.producer, input.host_source_ref, input.host_session_ref, input.source_slot, input.initial_cursor(sourceFileRef2, source.device, source.inode), input.created_at);
|
|
3922
|
+
} catch (error) {
|
|
3923
|
+
await handle.close().catch(() => void 0);
|
|
3924
|
+
throw error;
|
|
3925
|
+
}
|
|
3926
|
+
if (prepared === null) {
|
|
3927
|
+
await handle.close();
|
|
3928
|
+
return null;
|
|
3929
|
+
}
|
|
3930
|
+
return { handle, source, source_file_ref: sourceFileRef2, ...prepared };
|
|
3931
|
+
}
|
|
3932
|
+
async function readHostUsageTranscriptChunk(handle, offset, size, skippingOversizedLine) {
|
|
3933
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(size) || size < offset) throw new TypeError("Host usage transcript range is invalid.");
|
|
3934
|
+
if (size === offset) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
|
|
3935
|
+
if (skippingOversizedLine) return await resumeOversizedLine(handle, offset, size);
|
|
3936
|
+
const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
|
|
3937
|
+
const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
|
|
3938
|
+
if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
|
|
3939
|
+
const chunk = bytes.subarray(0, bytesRead);
|
|
3940
|
+
return completeChunk(chunk, offset);
|
|
3941
|
+
}
|
|
3942
|
+
async function resumeOversizedLine(handle, offset, size) {
|
|
3943
|
+
const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
|
|
3944
|
+
const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
|
|
3945
|
+
if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
|
|
3946
|
+
const chunk = bytes.subarray(0, bytesRead);
|
|
3947
|
+
const delimiter2 = chunk.indexOf(10);
|
|
3948
|
+
if (delimiter2 < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
|
|
3949
|
+
return completeChunk(chunk.subarray(delimiter2 + 1), offset + delimiter2 + 1);
|
|
3950
|
+
}
|
|
3951
|
+
function completeChunk(chunk, offset) {
|
|
3952
|
+
const parsed = completeLinePrefix(chunk, offset);
|
|
3953
|
+
const oversizedRows = parsed.oversizedRows + (parsed.incompleteOversized ? 1 : 0);
|
|
3954
|
+
const endOffset = parsed.incompleteOversized ? offset + chunk.length : parsed.endOffset;
|
|
3955
|
+
return { lines: parsed.lines, end_offset: endOffset, skipping_oversized_line: parsed.incompleteOversized, oversized_rows: oversizedRows };
|
|
3956
|
+
}
|
|
3957
|
+
function completeLinePrefix(bytes, baseOffset) {
|
|
3958
|
+
const lines = [];
|
|
3959
|
+
let lineStart = 0;
|
|
3960
|
+
let endOffset = baseOffset;
|
|
3961
|
+
let oversizedRows = 0;
|
|
3962
|
+
let rowCount = 0;
|
|
3963
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
3964
|
+
if (bytes[index] !== 10) continue;
|
|
3965
|
+
const line = bytes.subarray(lineStart, index);
|
|
3966
|
+
if (line.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES) oversizedRows += 1;
|
|
3967
|
+
else lines.push(line);
|
|
3968
|
+
lineStart = index + 1;
|
|
3969
|
+
endOffset = baseOffset + lineStart;
|
|
3970
|
+
rowCount += 1;
|
|
3971
|
+
if (rowCount >= HOST_USAGE_FACTS_SCAN_MAX_ROWS) return { lines, endOffset, oversizedRows, incompleteOversized: false };
|
|
3972
|
+
}
|
|
3973
|
+
const incomplete = bytes.subarray(lineStart);
|
|
3974
|
+
return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
|
|
3975
|
+
}
|
|
3976
|
+
|
|
3977
|
+
// host/relay/src/host-registration-state.ts
|
|
3978
|
+
import { constants as constants4 } from "node:fs";
|
|
3979
|
+
import { dirname as dirname4 } from "node:path";
|
|
3980
|
+
|
|
3981
|
+
// host/runtime-source-paths.ts
|
|
3982
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
3983
|
+
import { posix as posix2, win32 as win323 } from "node:path";
|
|
3984
|
+
|
|
3985
|
+
// host/absolute-path.ts
|
|
3986
|
+
import { posix, win32 as win322 } from "node:path";
|
|
3987
|
+
function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
|
|
3988
|
+
const pathApi = flavor === "win32" || flavor === "windows" ? win322 : posix;
|
|
3989
|
+
return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
|
|
3990
|
+
}
|
|
3991
|
+
|
|
3992
|
+
// host/unix-socket-path.ts
|
|
3993
|
+
var PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES = 103;
|
|
3994
|
+
var LINUX_UNIX_SOCKET_PATH_MAX_BYTES = 107;
|
|
3995
|
+
var HostUnixSocketPathError = class extends Error {
|
|
3996
|
+
code = "ipc_endpoint_too_long";
|
|
3997
|
+
role;
|
|
3998
|
+
bytes;
|
|
3999
|
+
maximum_bytes;
|
|
4000
|
+
constructor(role, bytes, maximum_bytes) {
|
|
4001
|
+
super(`ipc_endpoint_too_long: Host IPC ${role} has ${bytes} UTF-8 bytes; maximum is ${maximum_bytes}.`);
|
|
4002
|
+
this.name = "HostUnixSocketPathError";
|
|
4003
|
+
this.role = role;
|
|
4004
|
+
this.bytes = bytes;
|
|
4005
|
+
this.maximum_bytes = maximum_bytes;
|
|
4006
|
+
}
|
|
4007
|
+
};
|
|
4008
|
+
function assertHostUnixSocketPath(endpoint, role, platform = process.platform) {
|
|
4009
|
+
if (platform === "win32") return;
|
|
4010
|
+
const maximum = platform === "linux" ? LINUX_UNIX_SOCKET_PATH_MAX_BYTES : PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES;
|
|
4011
|
+
const bytes = Buffer.byteLength(endpoint, "utf8");
|
|
4012
|
+
if (bytes > maximum) throw new HostUnixSocketPathError(role, bytes, maximum);
|
|
4013
|
+
}
|
|
4014
|
+
|
|
4015
|
+
// host/runtime-source-paths.ts
|
|
4016
|
+
var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
|
|
4017
|
+
function hostSourceUuid(sourceRef) {
|
|
4018
|
+
return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
|
|
4019
|
+
}
|
|
4020
|
+
var DARWIN_UID_MAX = 4294967295;
|
|
4021
|
+
var MACOS_HOST_RELAY_IPC_ROOT_PREFIX = "/private/tmp/ceal-host-";
|
|
4022
|
+
function isMacosHostRelayIpcDirectory(path) {
|
|
4023
|
+
return path.startsWith(MACOS_HOST_RELAY_IPC_ROOT_PREFIX) && /^[0-9]+$/u.test(path.slice(MACOS_HOST_RELAY_IPC_ROOT_PREFIX.length));
|
|
4024
|
+
}
|
|
4025
|
+
function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
|
|
4026
|
+
if (!Number.isInteger(uid) || uid < 0 || uid > DARWIN_UID_MAX) throw new TypeError("Host runtime effective user identity is invalid.");
|
|
4027
|
+
return `${MACOS_HOST_RELAY_IPC_ROOT_PREFIX}${uid}`;
|
|
4028
|
+
}
|
|
4029
|
+
function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
|
|
4030
|
+
const sourceId = hostSourceUuid(sourceRef);
|
|
4031
|
+
if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
|
|
4032
|
+
const path = platform === "win32" ? win323 : posix2;
|
|
4033
|
+
const sourcesRoot = path.join(stateRoot, "sources");
|
|
4034
|
+
const sourceRoot = path.join(sourcesRoot, sourceId);
|
|
4035
|
+
const runtimeRoot = path.join(stateRoot, "run");
|
|
4036
|
+
const rootedEndpoint = path.join(runtimeRoot, `${sourceId}.sock`);
|
|
4037
|
+
const endpoint = projectRelayEndpoint(stateRoot, sourceRef, rootedEndpoint, platform, uid);
|
|
4038
|
+
return { sourceId, sourcesRoot, sourceRoot, relayRoot: path.join(sourceRoot, "relay"), codexOutbox: path.join(sourceRoot, "producers", "codex", "outbox"), claudeOutbox: path.join(sourceRoot, "producers", "claude", "outbox"), endpoint, runtimeRoot };
|
|
4039
|
+
}
|
|
4040
|
+
function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
|
|
4041
|
+
if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
|
|
4042
|
+
const digest2 = createHash6("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
|
|
4043
|
+
return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix2.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
|
|
4044
|
+
}
|
|
4045
|
+
function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
|
|
4046
|
+
const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
|
|
4047
|
+
if (config.outbox_dir !== (producer === "codex" ? paths.codexOutbox : paths.claudeOutbox) || platform !== "win32" && config.relay_endpoint !== paths.endpoint) throw new TypeError("Host producer outbox and IPC must belong to its configured source.");
|
|
4048
|
+
return paths.endpoint;
|
|
4049
|
+
}
|
|
4050
|
+
|
|
4051
|
+
// host/relay/src/host-registration-state.ts
|
|
4052
|
+
var HOST_REGISTRATION_STATE_SCHEMA = "ceal.host_registration_state.v1";
|
|
4053
|
+
var HOST_REGISTRATION_STATE_KEYS = Object.freeze([
|
|
4054
|
+
"credential_generation",
|
|
4055
|
+
"gateway_request_origin",
|
|
4056
|
+
"host_access_token",
|
|
4057
|
+
"host_installation_ref",
|
|
4058
|
+
"host_source_ref",
|
|
4059
|
+
"registration_attempt_ref",
|
|
4060
|
+
"schema_version",
|
|
4061
|
+
"status"
|
|
4062
|
+
]);
|
|
4063
|
+
var HOST_REGISTRATION_STATE_MAX_BYTES = 65536;
|
|
4064
|
+
var HostRegistrationStateError = class extends Error {
|
|
4065
|
+
name = "HostRegistrationStateError";
|
|
4066
|
+
code = "credential";
|
|
4067
|
+
};
|
|
4068
|
+
async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
|
|
4069
|
+
let raw;
|
|
4070
|
+
try {
|
|
4071
|
+
await assertPrivateRegistrationDirectory(dirname4(path), platform, custody);
|
|
4072
|
+
raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
|
|
4073
|
+
} catch (error) {
|
|
4074
|
+
throw registrationReadError(error);
|
|
4075
|
+
}
|
|
4076
|
+
if (Buffer.byteLength(raw, "utf8") > HOST_REGISTRATION_STATE_MAX_BYTES) throw new HostRegistrationStateError(`Host registration state is invalid: ${refusalFact("registration_state_bytes", Buffer.byteLength(raw, "utf8"), `at most ${HOST_REGISTRATION_STATE_MAX_BYTES}`)}.`);
|
|
4077
|
+
let value;
|
|
4078
|
+
try {
|
|
4079
|
+
value = JSON.parse(raw);
|
|
4080
|
+
} catch {
|
|
4081
|
+
throw new HostRegistrationStateError("Host registration state is invalid.");
|
|
4082
|
+
}
|
|
4083
|
+
return decodeHostRegistrationAuthority(value, expectedHostSourceRef);
|
|
4084
|
+
}
|
|
4085
|
+
async function readWindowsRegistration(path, custody) {
|
|
4086
|
+
const bytes = await readPrivateFileWithSecurefs(path, HOST_REGISTRATION_STATE_MAX_BYTES, custody);
|
|
4087
|
+
try {
|
|
4088
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
4089
|
+
} catch {
|
|
4090
|
+
throw new HostRegistrationStateError("Host registration state is invalid.");
|
|
4091
|
+
}
|
|
4092
|
+
}
|
|
4093
|
+
async function readPosixRegistration(path, platform, custody) {
|
|
4094
|
+
const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform, custody);
|
|
4095
|
+
try {
|
|
4096
|
+
const stats = await handle.stat();
|
|
4097
|
+
if (!stats.isFile() || !isSelfOwned(stats.uid, platform, handle) || !isPrivateFileMode(stats.mode, platform, handle)) throw new HostRegistrationStateError("Host registration file is not private to its owner.");
|
|
4098
|
+
return await handle.readFile("utf8");
|
|
4099
|
+
} finally {
|
|
4100
|
+
await handle.close();
|
|
4101
|
+
}
|
|
4102
|
+
}
|
|
4103
|
+
function registrationReadError(error) {
|
|
4104
|
+
if (error instanceof HostRegistrationStateError) return error;
|
|
4105
|
+
if (error instanceof SecureFileCustodyError && error.reason === "not_private") return new HostRegistrationStateError("Host registration file is not private to its owner.");
|
|
4106
|
+
return new HostRegistrationStateError("Host registration file is unavailable.");
|
|
4107
|
+
}
|
|
4108
|
+
function decodeHostRegistrationAuthority(value, expectedHostSourceRef) {
|
|
4109
|
+
const keys = HOST_REGISTRATION_STATE_KEYS;
|
|
4110
|
+
const fieldCount = record(value) ? Object.keys(value).length : 0;
|
|
4111
|
+
const missing = record(value) ? keys.filter((key) => !Object.hasOwn(value, key)).length : keys.length;
|
|
4112
|
+
if (!record(value) || fieldCount !== keys.length || missing !== 0) throw new HostRegistrationStateError(`Host registration state is invalid or does not match this Relay: ${refusalFacts([{ name: "registration_field_count", value: fieldCount, expected: `exactly ${keys.length}` }, { name: "missing_registration_field_count", value: missing, expected: "0" }])}.`);
|
|
4113
|
+
if (!validRegistrationIdentity(value, expectedHostSourceRef)) throw new HostRegistrationStateError(`Host registration state is invalid or does not match this Relay: ${refusalFacts([{ name: "schema_version", value: value.schema_version, expected: HOST_REGISTRATION_STATE_SCHEMA }, { name: "status", value: value.status, expected: "active" }, { name: "host_source_ref", value: value.host_source_ref, expected: expectedHostSourceRef }, { name: "registration_attempt_ref", value: value.registration_attempt_ref, expected: "host-registration-attempt:<uuid>" }, { name: "host_installation_ref", value: value.host_installation_ref, expected: "host-installation:<uuid>" }])}.`);
|
|
4114
|
+
if (!validRegistrationCredential(value)) throw new HostRegistrationStateError(`Host registration state is invalid or does not match this Relay: ${refusalFacts([{ name: "credential_generation", value: value.credential_generation, expected: "a positive safe integer" }, { name: "host_access_token_matches_registered_shape", value: validHostAccessToken(value.host_access_token), expected: "true" }])}.`);
|
|
4115
|
+
if (!validGatewayOrigin(value.gateway_request_origin)) throw new HostRegistrationStateError(`Host registration state is invalid or does not match this Relay: ${refusalFact("gateway_request_origin", value.gateway_request_origin, "an HTTPS origin or explicit-port loopback HTTP origin")}.`);
|
|
4116
|
+
return { gateway_request_origin: value.gateway_request_origin, host_access_token: value.host_access_token };
|
|
4117
|
+
}
|
|
4118
|
+
function validRegistrationIdentity(value, expectedHostSourceRef) {
|
|
4119
|
+
return value.schema_version === HOST_REGISTRATION_STATE_SCHEMA && value.status === "active" && value.host_source_ref === expectedHostSourceRef && typeof value.registration_attempt_ref === "string" && CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN.test(value.registration_attempt_ref) && typeof value.host_installation_ref === "string" && CEAL_HOST_INSTALLATION_REF_PATTERN.test(value.host_installation_ref) && typeof value.host_source_ref === "string" && hostSourceUuid(value.host_source_ref) !== null;
|
|
4120
|
+
}
|
|
4121
|
+
function validRegistrationCredential(value) {
|
|
4122
|
+
return Number.isSafeInteger(value.credential_generation) && Number(value.credential_generation) > 0 && validHostAccessToken(value.host_access_token);
|
|
4123
|
+
}
|
|
4124
|
+
function validHostAccessToken(value) {
|
|
4125
|
+
return typeof value === "string" && CEAL_HOST_ACCESS_TOKEN_PATTERN.test(value);
|
|
4126
|
+
}
|
|
4127
|
+
function validGatewayOrigin(value) {
|
|
4128
|
+
try {
|
|
4129
|
+
if (typeof value !== "string" || /\s|\0/u.test(value)) return false;
|
|
4130
|
+
const parsed = new URL(value);
|
|
4131
|
+
const hostname = parsed.hostname.toLowerCase().replace(/\.+$/u, "");
|
|
4132
|
+
return hostname !== "" && validGatewayPort(parsed.port) && (loopbackHttpOrigin(parsed, hostname) || parsed.protocol === "https:") && cleanOriginPath(parsed) && bareOriginSuffix(value);
|
|
4133
|
+
} catch {
|
|
4134
|
+
return false;
|
|
4135
|
+
}
|
|
4136
|
+
}
|
|
4137
|
+
function loopbackHttpOrigin(parsed, hostname) {
|
|
4138
|
+
return parsed.protocol === "http:" && parsed.port !== "" && (hostname === "127.0.0.1" || hostname === "[::1]");
|
|
4139
|
+
}
|
|
4140
|
+
function validGatewayPort(port) {
|
|
4141
|
+
if (port === "") return true;
|
|
4142
|
+
const numeric = Number(port);
|
|
4143
|
+
return Number.isInteger(numeric) && numeric >= 1 && numeric <= 65535;
|
|
4144
|
+
}
|
|
4145
|
+
function cleanOriginPath(parsed) {
|
|
4146
|
+
return parsed.username === "" && parsed.password === "" && parsed.pathname === "/" && parsed.search === "" && parsed.hash === "";
|
|
4147
|
+
}
|
|
4148
|
+
function bareOriginSuffix(value) {
|
|
4149
|
+
const schemeEnd = value.indexOf("://");
|
|
4150
|
+
const authority = schemeEnd < 0 ? "" : value.slice(schemeEnd + 3);
|
|
4151
|
+
const suffixOffset = authority.search(/[\\/?#]/u);
|
|
4152
|
+
const rawSuffix = suffixOffset < 0 ? "" : authority.slice(suffixOffset);
|
|
4153
|
+
return rawSuffix === "" || rawSuffix === "/";
|
|
4154
|
+
}
|
|
4155
|
+
async function assertPrivateRegistrationDirectory(path, platform, custody) {
|
|
4156
|
+
if (!await isPrivateDirectory(path, platform, custody)) throw new HostRegistrationStateError("Host registration directory is not private to its owner.");
|
|
4157
|
+
}
|
|
4158
|
+
function record(value) {
|
|
4159
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4160
|
+
}
|
|
4161
|
+
|
|
4162
|
+
// host/abortable-wait.ts
|
|
4163
|
+
function waitForAbort(signal, milliseconds) {
|
|
4164
|
+
if (signal.aborted) return Promise.resolve();
|
|
4165
|
+
return new Promise((resolve) => {
|
|
4166
|
+
const timer = setTimeout(finish, milliseconds);
|
|
4167
|
+
function finish() {
|
|
4168
|
+
clearTimeout(timer);
|
|
4169
|
+
signal.removeEventListener("abort", finish);
|
|
4170
|
+
resolve();
|
|
4171
|
+
}
|
|
4172
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
4173
|
+
});
|
|
4174
|
+
}
|
|
4175
|
+
|
|
4176
|
+
// host/service-log.ts
|
|
4177
|
+
import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
|
|
4178
|
+
import { dirname as dirname5, isAbsolute, posix as posix3, win32 as win324 } from "node:path";
|
|
4179
|
+
|
|
4180
|
+
// host/service-log-delivery.ts
|
|
4181
|
+
var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
|
|
4182
|
+
function createHostServiceLogDelivery(stream, schedule = (flush) => {
|
|
4183
|
+
setImmediate(flush);
|
|
4184
|
+
}, onDeliveryGap = () => void 0) {
|
|
4185
|
+
const pending = [];
|
|
4186
|
+
const highWaterMark = stream.writableHighWaterMark;
|
|
4187
|
+
const byteBudget = highWaterMark + highWaterMark;
|
|
4188
|
+
let pendingBytes = 0;
|
|
4189
|
+
let droppedLines = 0;
|
|
4190
|
+
let flushScheduled = false;
|
|
4191
|
+
let waitingForDrain = false;
|
|
4192
|
+
let closed = !stream.writable;
|
|
4193
|
+
function stop() {
|
|
4194
|
+
if (closed) return;
|
|
4195
|
+
closed = true;
|
|
4196
|
+
pending.length = 0;
|
|
4197
|
+
pendingBytes = 0;
|
|
4198
|
+
stream.off("drain", onDrain);
|
|
4199
|
+
stream.off("close", onTerminal);
|
|
4200
|
+
stream.off("finish", onTerminal);
|
|
4201
|
+
stream.off("error", onError);
|
|
4202
|
+
}
|
|
4203
|
+
function onTerminal() {
|
|
4204
|
+
stop();
|
|
4205
|
+
}
|
|
4206
|
+
function onError() {
|
|
4207
|
+
stop();
|
|
4208
|
+
}
|
|
4209
|
+
function onDrain() {
|
|
4210
|
+
waitingForDrain = false;
|
|
4211
|
+
scheduleFlush();
|
|
4212
|
+
}
|
|
4213
|
+
function scheduleFlush() {
|
|
4214
|
+
if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
|
|
4215
|
+
flushScheduled = true;
|
|
4216
|
+
let scheduling = true;
|
|
4217
|
+
let invokedSynchronously = false;
|
|
4218
|
+
try {
|
|
4219
|
+
schedule(() => {
|
|
4220
|
+
if (scheduling) {
|
|
4221
|
+
invokedSynchronously = true;
|
|
4222
|
+
return;
|
|
4223
|
+
}
|
|
4224
|
+
flushScheduled = false;
|
|
4225
|
+
flush();
|
|
4226
|
+
});
|
|
4227
|
+
} catch {
|
|
4228
|
+
flushScheduled = false;
|
|
4229
|
+
stop();
|
|
4230
|
+
return;
|
|
4231
|
+
}
|
|
4232
|
+
scheduling = false;
|
|
4233
|
+
if (invokedSynchronously) {
|
|
4234
|
+
flushScheduled = false;
|
|
4235
|
+
stop();
|
|
4236
|
+
}
|
|
4237
|
+
}
|
|
4238
|
+
function flush() {
|
|
4239
|
+
if (closed) return;
|
|
4240
|
+
if (!stream.writable) {
|
|
4241
|
+
stop();
|
|
4242
|
+
return;
|
|
4243
|
+
}
|
|
4244
|
+
while (pending.length > 0) {
|
|
4245
|
+
if (stream.writableNeedDrain) {
|
|
4246
|
+
if (!waitingForDrain) {
|
|
4247
|
+
waitingForDrain = true;
|
|
4248
|
+
stream.once("drain", onDrain);
|
|
4249
|
+
}
|
|
4250
|
+
return;
|
|
4251
|
+
}
|
|
4252
|
+
const next = pending.shift();
|
|
4253
|
+
if (next === void 0) return;
|
|
4254
|
+
pendingBytes -= next.bytes;
|
|
4255
|
+
let accepted;
|
|
4256
|
+
try {
|
|
4257
|
+
accepted = stream.write(next.line);
|
|
4258
|
+
} catch {
|
|
4259
|
+
stop();
|
|
4260
|
+
return;
|
|
4261
|
+
}
|
|
4262
|
+
if (!accepted) {
|
|
4263
|
+
waitingForDrain = true;
|
|
4264
|
+
stream.once("drain", onDrain);
|
|
4265
|
+
return;
|
|
4266
|
+
}
|
|
4267
|
+
}
|
|
4268
|
+
if (droppedLines > 0) {
|
|
4269
|
+
const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
|
|
4270
|
+
`;
|
|
4271
|
+
droppedLines = 0;
|
|
4272
|
+
try {
|
|
4273
|
+
onDeliveryGap(line);
|
|
4274
|
+
} catch {
|
|
4275
|
+
}
|
|
4276
|
+
pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
|
|
4277
|
+
pendingBytes += Buffer.byteLength(line, "utf8");
|
|
4278
|
+
flush();
|
|
4279
|
+
}
|
|
4280
|
+
}
|
|
4281
|
+
stream.on("close", onTerminal);
|
|
4282
|
+
stream.on("finish", onTerminal);
|
|
4283
|
+
stream.on("error", onError);
|
|
4284
|
+
return (line) => {
|
|
4285
|
+
if (closed) return;
|
|
4286
|
+
const bytes = Buffer.byteLength(line, "utf8");
|
|
4287
|
+
if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
|
|
4288
|
+
droppedLines += 1;
|
|
4289
|
+
scheduleFlush();
|
|
4290
|
+
return;
|
|
4291
|
+
}
|
|
4292
|
+
pending.push({ line, bytes });
|
|
4293
|
+
pendingBytes += bytes;
|
|
4294
|
+
scheduleFlush();
|
|
4295
|
+
};
|
|
4296
|
+
}
|
|
4297
|
+
|
|
4298
|
+
// host/service-log.ts
|
|
4299
|
+
var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
|
|
4300
|
+
var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
|
|
4301
|
+
void persistHostServiceLogLine(line);
|
|
4302
|
+
});
|
|
4303
|
+
function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
|
|
4304
|
+
const details = diagnosticDetails(event, failure_kind, cause);
|
|
4305
|
+
const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
|
|
4306
|
+
`;
|
|
4307
|
+
try {
|
|
4308
|
+
(sink ?? defaultHostServiceDiagnosticSink)(line);
|
|
4309
|
+
} catch {
|
|
4310
|
+
}
|
|
4311
|
+
}
|
|
4312
|
+
function diagnosticDetails(event, failureKind, cause) {
|
|
4313
|
+
if (event === "watcher_scan_failed") return {
|
|
4314
|
+
...failureKind === void 0 ? {} : { failure_kind: failureKind },
|
|
4315
|
+
...validDiagnosticCause(cause, event) ? { cause } : {}
|
|
4316
|
+
};
|
|
4317
|
+
return validDiagnosticCause(cause, event) ? { cause } : {};
|
|
4318
|
+
}
|
|
4319
|
+
function validDiagnosticCause(cause, event) {
|
|
4320
|
+
return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
|
|
4321
|
+
}
|
|
4322
|
+
function defaultHostServiceDiagnosticSink(line) {
|
|
4323
|
+
writeHostServiceLogLine(line);
|
|
4324
|
+
}
|
|
4325
|
+
var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
|
|
4326
|
+
function writeHostServiceLogLine(line, environment = process.env) {
|
|
4327
|
+
void persistHostServiceLogLine(line, environment);
|
|
4328
|
+
defaultHostServiceLogDelivery(line);
|
|
4329
|
+
}
|
|
4330
|
+
async function persistHostServiceLogLine(line, environment = process.env) {
|
|
4331
|
+
if (process.platform !== "win32") return;
|
|
4332
|
+
const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
|
|
4333
|
+
if (path === void 0 || !win324.isAbsolute(path) || win324.normalize(path) !== path) return;
|
|
4334
|
+
await appendHostServiceLogLine(path, line).catch(() => void 0);
|
|
4335
|
+
}
|
|
4336
|
+
async function appendHostServiceLogLine(path, line) {
|
|
4337
|
+
if (!isAbsolute(path)) return;
|
|
4338
|
+
await ensureHostServiceLogDirectory(path);
|
|
4339
|
+
await appendFile(path, line);
|
|
4340
|
+
}
|
|
4341
|
+
var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
|
|
4342
|
+
var hostServiceLogDirectories = /* @__PURE__ */ new Map();
|
|
4343
|
+
function ensureHostServiceLogDirectory(path) {
|
|
4344
|
+
const directory = dirname5(path);
|
|
4345
|
+
const existing = hostServiceLogDirectories.get(directory);
|
|
4346
|
+
if (existing !== void 0) return existing;
|
|
4347
|
+
const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
|
|
4348
|
+
hostServiceLogDirectories.delete(directory);
|
|
4349
|
+
throw error;
|
|
4350
|
+
});
|
|
4351
|
+
hostServiceLogDirectories.set(directory, pending);
|
|
4352
|
+
return pending;
|
|
4353
|
+
}
|
|
4354
|
+
|
|
4355
|
+
// host/relay/src/host-usage-facts-uploader.ts
|
|
4356
|
+
var HostUsageFactsUploader = class {
|
|
4357
|
+
options;
|
|
4358
|
+
store;
|
|
4359
|
+
constructor(options) {
|
|
4360
|
+
if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
|
|
4361
|
+
this.options = options;
|
|
4362
|
+
this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
|
|
4363
|
+
}
|
|
4364
|
+
async close() {
|
|
4365
|
+
await this.store.close();
|
|
4366
|
+
}
|
|
4367
|
+
async uploadOne(signal) {
|
|
4368
|
+
const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
|
|
4369
|
+
if (candidate === null) return false;
|
|
4370
|
+
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);
|
|
4371
|
+
const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
|
|
4372
|
+
const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
|
|
4373
|
+
const response2 = await (this.options.fetch ?? fetch)(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
|
|
4374
|
+
method: "POST",
|
|
4375
|
+
headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
|
|
4376
|
+
body: JSON.stringify(candidate.batch),
|
|
4377
|
+
signal: requestSignal
|
|
4378
|
+
});
|
|
4379
|
+
if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
|
|
4380
|
+
await response2.body?.cancel().catch(() => void 0);
|
|
4381
|
+
throw new Error("Gateway did not acknowledge the Host usage facts batch.");
|
|
4382
|
+
}
|
|
4383
|
+
await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
|
|
4384
|
+
return true;
|
|
4385
|
+
}
|
|
4386
|
+
};
|
|
4387
|
+
async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
|
|
4388
|
+
const uploader = new HostUsageFactsUploader(options);
|
|
4389
|
+
let delay = 500;
|
|
4390
|
+
let failures = 0;
|
|
4391
|
+
try {
|
|
4392
|
+
while (!signal.aborted) {
|
|
4393
|
+
try {
|
|
4394
|
+
await options.capture_next?.();
|
|
4395
|
+
} catch {
|
|
4396
|
+
writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
|
|
4397
|
+
}
|
|
4398
|
+
if (signal.aborted) return;
|
|
4399
|
+
try {
|
|
4400
|
+
const uploaded = await uploader.uploadOne(signal);
|
|
4401
|
+
failures = 0;
|
|
4402
|
+
delay = uploaded ? 100 : 1e3;
|
|
4403
|
+
} catch {
|
|
4404
|
+
if (signal.aborted) return;
|
|
4405
|
+
failures += 1;
|
|
4406
|
+
delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
|
|
4407
|
+
writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
|
|
4408
|
+
}
|
|
4409
|
+
if (!signal.aborted) await wait(signal, delay);
|
|
4410
|
+
}
|
|
4411
|
+
} finally {
|
|
4412
|
+
await uploader.close().catch(() => void 0);
|
|
4413
|
+
}
|
|
4414
|
+
}
|
|
4415
|
+
|
|
4416
|
+
// host/relay/src/relay-quarantine-store.ts
|
|
4417
|
+
var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
|
|
4418
|
+
var RELAY_QUARANTINE_FRAME_REASONS = ["frame_identity_conflict", "sequence_gap", "gateway_refused"];
|
|
4419
|
+
var RELAY_QUARANTINE_REASONS = [...RELAY_QUARANTINE_FRAME_REASONS, ...HOST_PRODUCER_FRAME_ERROR_CODES];
|
|
4420
|
+
|
|
4421
|
+
// host/relay/src/relay-admission-store.ts
|
|
4422
|
+
var DEFAULT_LIMITS = { global_count: 8192, global_bytes: 64 * 1024 * 1024, producer_count: 4096, producer_bytes: 32 * 1024 * 1024 };
|
|
4423
|
+
var RETRY_SECONDS = [1, 2, 4, 8, 16, 32, 60];
|
|
4424
|
+
var MAX_RETRYABLE_ATTEMPTS = RETRY_SECONDS.length + 10;
|
|
4425
|
+
|
|
4426
|
+
// host/relay/src/relay-ipc-error.ts
|
|
4427
|
+
var HostRelayIpcError = class extends Error {
|
|
4428
|
+
code;
|
|
4429
|
+
/** Set only when the client-side socket exchange itself failed. */
|
|
4430
|
+
failure;
|
|
4431
|
+
constructor(code2, message = code2, failure2) {
|
|
4432
|
+
super(message);
|
|
4433
|
+
this.code = code2;
|
|
4434
|
+
this.failure = failure2;
|
|
4435
|
+
}
|
|
4436
|
+
};
|
|
4437
|
+
function hostRelayExchangeFailure(error) {
|
|
4438
|
+
return error instanceof HostRelayIpcError ? error.failure : void 0;
|
|
4439
|
+
}
|
|
4440
|
+
function relayIpcErrorCode(error) {
|
|
4441
|
+
return error !== null && typeof error === "object" && !Array.isArray(error) && "code" in error && typeof error.code === "string" ? error.code : null;
|
|
4442
|
+
}
|
|
4443
|
+
|
|
4444
|
+
// host/relay/src/relay-endpoint-ownership.ts
|
|
4445
|
+
import { lstat as lstat3, mkdir as mkdir4, unlink as unlink3 } from "node:fs/promises";
|
|
4446
|
+
import { dirname as dirname6 } from "node:path";
|
|
4447
|
+
function currentUid(fallback) {
|
|
4448
|
+
return typeof process.geteuid === "function" ? process.geteuid() : fallback;
|
|
4449
|
+
}
|
|
4450
|
+
async function assertCompactRelayClientParent(endpoint) {
|
|
4451
|
+
const parent = dirname6(endpoint);
|
|
4452
|
+
if (process.platform !== "darwin" || !isMacosHostRelayIpcDirectory(parent)) return;
|
|
4453
|
+
if (parent !== macosHostRelayIpcDirectory()) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC directory does not belong to the effective user.");
|
|
4454
|
+
await assertPrivateEndpointDirectory(parent);
|
|
4455
|
+
}
|
|
4456
|
+
async function assertPrivateEndpointDirectory(parent) {
|
|
4457
|
+
let stats;
|
|
4458
|
+
try {
|
|
4459
|
+
stats = await lstat3(parent);
|
|
4460
|
+
} catch (error) {
|
|
4461
|
+
throw endpointInspectionError(error, "Host Relay IPC endpoint parent is unavailable; leaving it untouched.");
|
|
4462
|
+
}
|
|
4463
|
+
if (!stats.isDirectory() || stats.uid !== currentUid(stats.uid) || (stats.mode & 63) !== 0) throw new HostRelayIpcError("relay_unavailable", "Host Relay IPC endpoint parent is not an owner-private directory; leaving it untouched.");
|
|
4464
|
+
}
|
|
4465
|
+
function endpointInspectionError(error, message) {
|
|
4466
|
+
const code2 = relayIpcErrorCode(error);
|
|
4467
|
+
const failure2 = code2 === "ENOENT" ? "socket_missing" : code2 === "EACCES" || code2 === "EPERM" ? "permission_denied" : "unavailable";
|
|
4468
|
+
return new HostRelayIpcError("relay_unavailable", message, failure2);
|
|
4469
|
+
}
|
|
2814
4470
|
|
|
2815
4471
|
// host/relay/src/relay-ipc.ts
|
|
2816
4472
|
import { createConnection, createServer } from "node:net";
|
|
2817
4473
|
|
|
2818
4474
|
// host/relay/src/relay-pipe-handshake.ts
|
|
2819
4475
|
import { createHmac, randomBytes } from "node:crypto";
|
|
2820
|
-
import { constants as
|
|
2821
|
-
import { link, unlink as
|
|
2822
|
-
import { dirname as
|
|
4476
|
+
import { constants as constants5 } from "node:fs";
|
|
4477
|
+
import { link, unlink as unlink4 } from "node:fs/promises";
|
|
4478
|
+
import { dirname as dirname7, join as join4 } from "node:path";
|
|
2823
4479
|
var RELAY_PIPE_HANDSHAKE_TIMEOUT_MS = 5e3;
|
|
2824
4480
|
var RELAY_PIPE_KEY_BYTES = 32;
|
|
2825
4481
|
var RELAY_PIPE_KEY_FILENAME = "relay-pipe.key";
|
|
@@ -2839,10 +4495,10 @@ var RelayPipeHandshakeError = class extends Error {
|
|
|
2839
4495
|
}
|
|
2840
4496
|
};
|
|
2841
4497
|
function relayPipeStateRootForOutboxDir(outboxDir) {
|
|
2842
|
-
return
|
|
4498
|
+
return join4(dirname7(dirname7(dirname7(outboxDir))), "relay");
|
|
2843
4499
|
}
|
|
2844
4500
|
function relayPipeKeyPath(relayStateRoot) {
|
|
2845
|
-
return
|
|
4501
|
+
return join4(relayStateRoot, RELAY_PIPE_KEY_FILENAME);
|
|
2846
4502
|
}
|
|
2847
4503
|
async function loadRelayPipeKey(relayStateRoot, platform = process.platform, custody = {}) {
|
|
2848
4504
|
const path = relayPipeKeyPath(relayStateRoot);
|
|
@@ -2852,12 +4508,13 @@ async function loadRelayPipeKey(relayStateRoot, platform = process.platform, cus
|
|
|
2852
4508
|
return await createPosixRelayPipeKey(path, platform, custody);
|
|
2853
4509
|
}
|
|
2854
4510
|
async function loadWindowsRelayPipeKey(path, custody) {
|
|
2855
|
-
const existing = await readRelayPipeKey(path, "win32", custody);
|
|
2856
|
-
if (existing !== null) return existing;
|
|
2857
4511
|
try {
|
|
4512
|
+
await ensurePrivateDirectoryWithSecurefs(dirname7(path), custody);
|
|
4513
|
+
const existing = await readRelayPipeKey(path, "win32", custody);
|
|
4514
|
+
if (existing !== null) return existing;
|
|
2858
4515
|
await createRandomPrivateFileWithSecurefs(path, RELAY_PIPE_KEY_BYTES, custody);
|
|
2859
4516
|
} catch (error) {
|
|
2860
|
-
if (
|
|
4517
|
+
if (errorCode4(error) === "EEXIST") return await readWinnerPipeKey(path, "win32", custody);
|
|
2861
4518
|
throw new RelayPipeHandshakeError("pipe_key_unavailable", `Host Relay pipe key is unavailable at ${path}; delete it and restart the Host Relay.`);
|
|
2862
4519
|
}
|
|
2863
4520
|
return await readWinnerPipeKey(path, "win32", custody);
|
|
@@ -2867,9 +4524,9 @@ async function createPosixRelayPipeKey(path, platform, custody) {
|
|
|
2867
4524
|
const staging = `${path}.${randomBytes(8).toString("hex")}.tmp`;
|
|
2868
4525
|
let handle;
|
|
2869
4526
|
try {
|
|
2870
|
-
handle = await openNoFollow(staging,
|
|
4527
|
+
handle = await openNoFollow(staging, constants5.O_WRONLY | constants5.O_CREAT | constants5.O_EXCL, 384);
|
|
2871
4528
|
} catch (error) {
|
|
2872
|
-
if (
|
|
4529
|
+
if (errorCode4(error) !== "EEXIST") throw new RelayPipeHandshakeError("pipe_key_unavailable", `Host Relay pipe key is unavailable at ${path}.`);
|
|
2873
4530
|
return await readWinnerPipeKey(path, platform, custody);
|
|
2874
4531
|
}
|
|
2875
4532
|
try {
|
|
@@ -2883,10 +4540,10 @@ async function createPosixRelayPipeKey(path, platform, custody) {
|
|
|
2883
4540
|
try {
|
|
2884
4541
|
await link(staging, path);
|
|
2885
4542
|
} catch (error) {
|
|
2886
|
-
if (
|
|
4543
|
+
if (errorCode4(error) !== "EEXIST") throw new RelayPipeHandshakeError("pipe_key_unavailable", `Host Relay pipe key is unavailable at ${path}.`);
|
|
2887
4544
|
return await readWinnerPipeKey(path, platform, custody);
|
|
2888
4545
|
} finally {
|
|
2889
|
-
await
|
|
4546
|
+
await unlink4(staging).catch(() => void 0);
|
|
2890
4547
|
}
|
|
2891
4548
|
return Buffer.from(key);
|
|
2892
4549
|
}
|
|
@@ -2904,7 +4561,7 @@ async function readWindowsRelayPipeKey(path, custody) {
|
|
|
2904
4561
|
try {
|
|
2905
4562
|
key = await readPrivateFileWithSecurefs(path, RELAY_PIPE_KEY_BYTES, custody);
|
|
2906
4563
|
} catch (error) {
|
|
2907
|
-
if (
|
|
4564
|
+
if (errorCode4(error) === "ENOENT" || errorCode4(error) === "ELOOP") return null;
|
|
2908
4565
|
throw new RelayPipeHandshakeError("pipe_key_unavailable", `Host Relay pipe key is unavailable at ${path}; delete it and restart the Host Relay.`);
|
|
2909
4566
|
}
|
|
2910
4567
|
if (key.byteLength !== RELAY_PIPE_KEY_BYTES) throw new RelayPipeHandshakeError("pipe_key_unavailable", `Host Relay pipe key at ${path} has ${key.byteLength} bytes; want ${RELAY_PIPE_KEY_BYTES}. Delete the file and restart the Host Relay.`);
|
|
@@ -2915,7 +4572,7 @@ async function readPosixRelayPipeKey(path) {
|
|
|
2915
4572
|
try {
|
|
2916
4573
|
handle = await openNoFollow(path);
|
|
2917
4574
|
} catch (error) {
|
|
2918
|
-
if (
|
|
4575
|
+
if (errorCode4(error) === "ENOENT" || errorCode4(error) === "ELOOP") return null;
|
|
2919
4576
|
throw new RelayPipeHandshakeError("pipe_key_unavailable", `Host Relay pipe key is unavailable at ${path}.`);
|
|
2920
4577
|
}
|
|
2921
4578
|
try {
|
|
@@ -3047,7 +4704,7 @@ async function conductPipeClientHandshake(socket, key, timeoutMs = RELAY_PIPE_HA
|
|
|
3047
4704
|
const clientNonce = createPipeClientNonce();
|
|
3048
4705
|
await Promise.race([writePipeFrame(socket, encodePipeFrame({ schema_version: RELAY_PIPE_HELLO_SCHEMA, client_nonce: clientNonce })), bound.done]);
|
|
3049
4706
|
const challenge = await Promise.race([waiter.wait(), bound.done]);
|
|
3050
|
-
if (!
|
|
4707
|
+
if (!isRecord3(challenge.value) || challenge.value.schema_version !== RELAY_PIPE_CHALLENGE_SCHEMA || !validNonce(challenge.value.server_nonce) || typeof challenge.value.server_proof !== "string") {
|
|
3051
4708
|
throw new RelayPipeHandshakeError("pipe_server_unproven", "Host Relay pipe server proof is invalid; aborting before sending any request.");
|
|
3052
4709
|
}
|
|
3053
4710
|
const serverNonce = challenge.value.server_nonce;
|
|
@@ -3068,43 +4725,20 @@ function timingSafeEqualHex(left, right) {
|
|
|
3068
4725
|
for (let index = 0; index < left.length; index += 1) diff |= left.charCodeAt(index) ^ right.charCodeAt(index);
|
|
3069
4726
|
return diff === 0;
|
|
3070
4727
|
}
|
|
3071
|
-
function
|
|
4728
|
+
function isRecord3(value) {
|
|
3072
4729
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3073
4730
|
}
|
|
3074
|
-
function
|
|
4731
|
+
function errorCode4(error) {
|
|
3075
4732
|
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
3076
4733
|
}
|
|
3077
4734
|
|
|
3078
4735
|
// host/relay/src/relay-ipc.ts
|
|
3079
4736
|
var HOST_RELAY_INVOCATION_CONTEXT_QUERY_SCHEMA = "ceal.host_relay_invocation_context_query.v2";
|
|
3080
|
-
var HOST_RELAY_INVOCATION_CONTEXT_RESULT_SCHEMA = "ceal.host_relay_invocation_context_result.
|
|
4737
|
+
var HOST_RELAY_INVOCATION_CONTEXT_RESULT_SCHEMA = "ceal.host_relay_invocation_context_result.v3";
|
|
3081
4738
|
var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
|
|
3082
4739
|
var HOST_RELAY_QUERY_RESPONSE_MAX_BYTES = 8192;
|
|
3083
|
-
var HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
|
|
3084
|
-
"permission_denied",
|
|
3085
|
-
"socket_missing",
|
|
3086
|
-
"connection_refused",
|
|
3087
|
-
"closed_early",
|
|
3088
|
-
"response_invalid",
|
|
3089
|
-
"timed_out",
|
|
3090
|
-
"cancelled",
|
|
3091
|
-
"unavailable"
|
|
3092
|
-
]);
|
|
3093
|
-
var HostRelayIpcError = class extends Error {
|
|
3094
|
-
code;
|
|
3095
|
-
/** Set only when the client-side socket exchange itself failed. */
|
|
3096
|
-
failure;
|
|
3097
|
-
constructor(code2, message = code2, failure2) {
|
|
3098
|
-
super(message);
|
|
3099
|
-
this.code = code2;
|
|
3100
|
-
this.failure = failure2;
|
|
3101
|
-
}
|
|
3102
|
-
};
|
|
3103
|
-
function hostRelayExchangeFailure(error) {
|
|
3104
|
-
return error instanceof HostRelayIpcError ? error.failure : void 0;
|
|
3105
|
-
}
|
|
3106
4740
|
function socketErrorFailure(error) {
|
|
3107
|
-
switch (
|
|
4741
|
+
switch (relayIpcErrorCode(error)) {
|
|
3108
4742
|
case "EACCES":
|
|
3109
4743
|
case "EPERM":
|
|
3110
4744
|
return "permission_denied";
|
|
@@ -3132,7 +4766,9 @@ var HostRelayInvocationContextPort = class {
|
|
|
3132
4766
|
function queryHostRelayInvocationContext(endpoint, query, timeoutMs, signal, pipeKey) {
|
|
3133
4767
|
return exchange(endpoint, encodeInvocationContextQuery(query), timeoutMs, decodeInvocationContextResponseBuffer, signal, pipeKey);
|
|
3134
4768
|
}
|
|
3135
|
-
function exchange(endpoint, encoded, timeoutMs, decode, signal, pipeKey) {
|
|
4769
|
+
async function exchange(endpoint, encoded, timeoutMs, decode, signal, pipeKey) {
|
|
4770
|
+
assertHostUnixSocketPath(endpoint, "endpoint");
|
|
4771
|
+
await assertCompactRelayClientParent(endpoint);
|
|
3136
4772
|
return new Promise((resolve, reject) => {
|
|
3137
4773
|
const socket = createConnection(endpoint);
|
|
3138
4774
|
let buffer = Buffer.alloc(0);
|
|
@@ -3190,7 +4826,7 @@ function exchange(endpoint, encoded, timeoutMs, decode, signal, pipeKey) {
|
|
|
3190
4826
|
}
|
|
3191
4827
|
});
|
|
3192
4828
|
}
|
|
3193
|
-
function
|
|
4829
|
+
function record2(value) {
|
|
3194
4830
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3195
4831
|
}
|
|
3196
4832
|
function decodeInvocationContextResponseBuffer(buffer) {
|
|
@@ -3225,20 +4861,24 @@ function validQueryEnvelope(value) {
|
|
|
3225
4861
|
return typeof value.client_nonce === "string" && CEAL_HOST_CLIENT_NONCE_PATTERN.test(value.client_nonce) && typeof value.context_expires_at === "string" && (value.visible_output_max_bytes === void 0 || validVisibleOutputBudget(value.visible_output_max_bytes));
|
|
3226
4862
|
}
|
|
3227
4863
|
function validQueryIdentity(value, schema) {
|
|
3228
|
-
return
|
|
4864
|
+
return record2(value) && value.schema_version === schema && (value.producer_id === "codex" || value.producer_id === "claude") && safeRef(value.producer_installation_ref);
|
|
3229
4865
|
}
|
|
3230
4866
|
function validVisibleOutputBudget(value) {
|
|
3231
4867
|
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value <= CEAL_CANONICAL_HTTP_MAX_RESPONSE_BYTES;
|
|
3232
4868
|
}
|
|
3233
4869
|
function validInvocationContextResponse(value) {
|
|
3234
|
-
if (!
|
|
4870
|
+
if (!record2(value) || value.schema_version !== HOST_RELAY_INVOCATION_CONTEXT_RESULT_SCHEMA) return false;
|
|
3235
4871
|
return value.status === "refused" ? validInvocationContextRefusal(value) : validReadyInvocationContext(value);
|
|
3236
4872
|
}
|
|
3237
4873
|
function validInvocationContextRefusal(value) {
|
|
4874
|
+
if (value.reason === "gateway_refused") return exactKeys2(value, ["schema_version", "status", "reason", "gateway_status"]) && validGenericGatewayRefusalStatus(value.gateway_status);
|
|
3238
4875
|
return exactKeys2(value, ["schema_version", "status", "reason"]) && isCealHostAuthenticationCause(value.reason) && value.reason !== "no_binding";
|
|
3239
4876
|
}
|
|
4877
|
+
function validGenericGatewayRefusalStatus(value) {
|
|
4878
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 400 && value < 500 && value !== 401 && value !== 429;
|
|
4879
|
+
}
|
|
3240
4880
|
function validReadyInvocationContext(value) {
|
|
3241
|
-
if (value.status !== "ready" || !exactKeys2(value, ["schema_version", "status", "request_ref", "result"]) || !safeRef(value.request_ref) || !value.request_ref.startsWith("ceal-request:") || !
|
|
4881
|
+
if (value.status !== "ready" || !exactKeys2(value, ["schema_version", "status", "request_ref", "result"]) || !safeRef(value.request_ref) || !value.request_ref.startsWith("ceal-request:") || !record2(value.result)) return false;
|
|
3242
4882
|
const result = value.result;
|
|
3243
4883
|
return exactKeys2(result, ["schema_version", "context_token", "expires_at"]) && result.schema_version === CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA && typeof result.context_token === "string" && CEAL_HOST_CONTEXT_TOKEN_PATTERN.test(result.context_token) && typeof result.expires_at === "string" && Number.isFinite(Date.parse(result.expires_at));
|
|
3244
4884
|
}
|
|
@@ -3268,54 +4908,17 @@ function exactKeys2(value, required, optional = []) {
|
|
|
3268
4908
|
function safeRef(value) {
|
|
3269
4909
|
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
|
|
3270
4910
|
}
|
|
3271
|
-
function errorCode4(error) {
|
|
3272
|
-
return record(error) && typeof error.code === "string" ? error.code : null;
|
|
3273
|
-
}
|
|
3274
|
-
|
|
3275
|
-
// host/service-log.ts
|
|
3276
|
-
import { copyFile, mkdir as mkdir2, stat, truncate, appendFile } from "node:fs/promises";
|
|
3277
|
-
import { dirname as dirname4, isAbsolute, posix, win32 as win322 } from "node:path";
|
|
3278
|
-
var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
|
|
3279
|
-
function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
|
|
3280
|
-
const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...event === "watcher_scan_failed" && failure_kind !== void 0 ? { failure_kind } : {}, ...event === "watcher_scan_failed" && cause !== void 0 ? { cause } : {} })}
|
|
3281
|
-
`;
|
|
3282
|
-
try {
|
|
3283
|
-
(sink ?? defaultHostServiceDiagnosticSink)(line);
|
|
3284
|
-
} catch {
|
|
3285
|
-
}
|
|
3286
|
-
}
|
|
3287
|
-
function defaultHostServiceDiagnosticSink(line) {
|
|
3288
|
-
writeHostServiceLogLine(line);
|
|
3289
|
-
process.stderr.write(line);
|
|
3290
|
-
}
|
|
3291
|
-
var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
|
|
3292
|
-
function writeHostServiceLogLine(line, environment = process.env) {
|
|
3293
|
-
if (process.platform !== "win32") return;
|
|
3294
|
-
const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
|
|
3295
|
-
if (path === void 0 || !win322.isAbsolute(path) || win322.normalize(path) !== path) return;
|
|
3296
|
-
void appendHostServiceLogLine(path, line).catch(() => void 0);
|
|
3297
|
-
}
|
|
3298
|
-
async function appendHostServiceLogLine(path, line) {
|
|
3299
|
-
if (!isAbsolute(path)) return;
|
|
3300
|
-
await ensureHostServiceLogDirectory(path);
|
|
3301
|
-
await appendFile(path, line);
|
|
3302
|
-
}
|
|
3303
|
-
var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
|
|
3304
|
-
var hostServiceLogDirectories = /* @__PURE__ */ new Map();
|
|
3305
|
-
function ensureHostServiceLogDirectory(path) {
|
|
3306
|
-
const directory = dirname4(path);
|
|
3307
|
-
const existing = hostServiceLogDirectories.get(directory);
|
|
3308
|
-
if (existing !== void 0) return existing;
|
|
3309
|
-
const pending = mkdir2(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
|
|
3310
|
-
hostServiceLogDirectories.delete(directory);
|
|
3311
|
-
throw error;
|
|
3312
|
-
});
|
|
3313
|
-
hostServiceLogDirectories.set(directory, pending);
|
|
3314
|
-
return pending;
|
|
3315
|
-
}
|
|
3316
4911
|
|
|
3317
4912
|
// host/local-capability-descriptor.ts
|
|
3318
4913
|
var HOST_LOCAL_CAPABILITY_AUTHENTICATION_SUFFIX = Object.freeze(["authenticate", "--client-nonce"]);
|
|
4914
|
+
var LOCAL_CAPABILITY_CUSTODY_REFUSALS = Object.freeze({
|
|
4915
|
+
not_private: "is not private to the current user.",
|
|
4916
|
+
reparse_point: "must not be a reparse point.",
|
|
4917
|
+
not_found: "custody could not be proved.",
|
|
4918
|
+
too_large: "custody could not be proved.",
|
|
4919
|
+
already_exists: "custody could not be proved.",
|
|
4920
|
+
unavailable: "custody could not be proved."
|
|
4921
|
+
});
|
|
3319
4922
|
|
|
3320
4923
|
// host/invocation-authentication-command.ts
|
|
3321
4924
|
var HOST_CONTEXT_ACTIVATION_WAIT_MAX_MS = 2e4;
|
|
@@ -3323,6 +4926,17 @@ var CLAUDE_CONTEXT_ACTIVATION_WAIT_MAX_MS = HOST_CONTEXT_ACTIVATION_WAIT_MAX_MS;
|
|
|
3323
4926
|
var HOST_AUTHENTICATION_COMPLETION_RESERVE_MS = 5e3;
|
|
3324
4927
|
var INVOCATION_CONTEXT_POLL_INTERVAL_MS = 250;
|
|
3325
4928
|
var REFUSAL_REASON_PATTERN = /^[a-z][a-z0-9_]{0,63}$/u;
|
|
4929
|
+
var HostInvocationAuthenticationRefusal = class extends Error {
|
|
4930
|
+
reason;
|
|
4931
|
+
gateway_status;
|
|
4932
|
+
diagnostic_cause;
|
|
4933
|
+
constructor(reason, gatewayStatus, diagnosticCause) {
|
|
4934
|
+
super(reason);
|
|
4935
|
+
this.reason = reason;
|
|
4936
|
+
if (gatewayStatus !== void 0) this.gateway_status = gatewayStatus;
|
|
4937
|
+
if (diagnosticCause !== void 0) this.diagnostic_cause = diagnosticCause;
|
|
4938
|
+
}
|
|
4939
|
+
};
|
|
3326
4940
|
function installedHostInvocationAuthenticationCommandOptions(config, contextBudgetMs, maxContextWaitMs) {
|
|
3327
4941
|
let pipeKey;
|
|
3328
4942
|
const loadPipeKey = () => {
|
|
@@ -3345,7 +4959,11 @@ async function runHostInvocationAuthenticationCommand(descriptor, args, options)
|
|
|
3345
4959
|
writeResult(await authenticateHostInvocation(descriptor, resolved.input, resolved.options), sink);
|
|
3346
4960
|
return 0;
|
|
3347
4961
|
} catch (error) {
|
|
3348
|
-
|
|
4962
|
+
const reason = authenticationRefusalReason(error);
|
|
4963
|
+
const refusal = error instanceof HostInvocationAuthenticationRefusal ? error : void 0;
|
|
4964
|
+
const gatewayStatus = refusal?.reason === "gateway_refused" && validGenericGatewayRefusalStatus2(refusal.gateway_status) ? refusal.gateway_status : void 0;
|
|
4965
|
+
writeHostServiceDiagnostic(descriptor.producer_id, "invocation_authentication_failed", void 0, refusal?.diagnostic_cause ?? reason, options?.diagnostic_sink);
|
|
4966
|
+
writeResult({ schema_version: CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA, ok: false, code: "invocation_authentication_unavailable", reason, ...gatewayStatus === void 0 ? {} : { gateway_status: gatewayStatus } }, sink);
|
|
3349
4967
|
return 2;
|
|
3350
4968
|
}
|
|
3351
4969
|
}
|
|
@@ -3389,11 +5007,18 @@ async function mintedResult(mint, query) {
|
|
|
3389
5007
|
try {
|
|
3390
5008
|
response2 = await mint(query);
|
|
3391
5009
|
} catch (error) {
|
|
3392
|
-
|
|
5010
|
+
const exchangeFailure = hostRelayExchangeFailure(error) ?? "unavailable";
|
|
5011
|
+
throw new HostInvocationAuthenticationRefusal(cealHostAuthenticationCauseForExchangeFailure(exchangeFailure), void 0, `relay_exchange:${exchangeFailure}`);
|
|
5012
|
+
}
|
|
5013
|
+
if (response2.status !== "ready") {
|
|
5014
|
+
const reason = isCealHostAuthenticationCause(response2.reason) && response2.reason !== "no_binding" ? response2.reason : "host_refusal_invalid";
|
|
5015
|
+
throw new HostInvocationAuthenticationRefusal(reason, response2.gateway_status);
|
|
3393
5016
|
}
|
|
3394
|
-
if (response2.status !== "ready") throw new TypeError(isCealHostAuthenticationCause(response2.reason) && response2.reason !== "no_binding" ? response2.reason : "host_refusal_invalid");
|
|
3395
5017
|
return response2;
|
|
3396
5018
|
}
|
|
5019
|
+
function validGenericGatewayRefusalStatus2(value) {
|
|
5020
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 400 && value < 500 && value !== 401 && value !== 429;
|
|
5021
|
+
}
|
|
3397
5022
|
async function currentInvocation(descriptor, config, now) {
|
|
3398
5023
|
const store = descriptor.create_store(config.outbox_dir);
|
|
3399
5024
|
const identity = resolveIdentity(descriptor, config);
|
|
@@ -3415,6 +5040,7 @@ async function currentInvocation(descriptor, config, now) {
|
|
|
3415
5040
|
recordActivationWaitCompletion(descriptor.producer_id, waitEngaged, config.diagnostic_sink);
|
|
3416
5041
|
return { store, current };
|
|
3417
5042
|
}
|
|
5043
|
+
await rejectWhenActivationWaitIsUnavailable(descriptor, store, identity.identity, waitEngaged, waitBudgetMs, config.diagnostic_sink);
|
|
3418
5044
|
const remainingMs = deadline - monotonicNow();
|
|
3419
5045
|
if (remainingMs <= 0) {
|
|
3420
5046
|
recordActivationWaitExhaustion(descriptor.producer_id, waitEngaged, waitBudgetMs, config.diagnostic_sink);
|
|
@@ -3426,6 +5052,12 @@ async function currentInvocation(descriptor, config, now) {
|
|
|
3426
5052
|
await (config.wait ?? waitForContextActivation)(intervalMs);
|
|
3427
5053
|
}
|
|
3428
5054
|
}
|
|
5055
|
+
async function rejectWhenActivationWaitIsUnavailable(descriptor, store, identity, waitEngaged, waitBudgetMs, sink) {
|
|
5056
|
+
if (waitEngaged || waitBudgetMs <= 0 || descriptor.can_wait_for_context_activation === void 0) return;
|
|
5057
|
+
if (await descriptor.can_wait_for_context_activation({ store, identity })) return;
|
|
5058
|
+
writeHostServiceDiagnostic(descriptor.producer_id, "activation_wait_skipped", void 0, void 0, sink);
|
|
5059
|
+
throw new TypeError("context_unavailable");
|
|
5060
|
+
}
|
|
3429
5061
|
function recordActivationWaitExhaustion(producer, engaged, budgetMs, sink) {
|
|
3430
5062
|
if (engaged || budgetMs > 0) writeHostServiceDiagnostic(producer, "activation_wait_exhausted", void 0, void 0, sink);
|
|
3431
5063
|
else writeHostServiceDiagnostic(producer, "activation_wait_skipped", void 0, void 0, sink);
|
|
@@ -3501,42 +5133,8 @@ function writeResult(value, sink) {
|
|
|
3501
5133
|
|
|
3502
5134
|
// host/producer-service.ts
|
|
3503
5135
|
import { posix as posix4, win32 as win325 } from "node:path";
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
import { createHash as createHash4 } from "node:crypto";
|
|
3507
|
-
import { posix as posix3, win32 as win324 } from "node:path";
|
|
3508
|
-
|
|
3509
|
-
// host/absolute-path.ts
|
|
3510
|
-
import { posix as posix2, win32 as win323 } from "node:path";
|
|
3511
|
-
function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allowRoot = false) {
|
|
3512
|
-
const pathApi = flavor === "win32" || flavor === "windows" ? win323 : posix2;
|
|
3513
|
-
return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
|
|
3514
|
-
}
|
|
3515
|
-
|
|
3516
|
-
// host/runtime-source-paths.ts
|
|
3517
|
-
var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
|
|
3518
|
-
function hostSourceUuid(sourceRef) {
|
|
3519
|
-
return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
|
|
3520
|
-
}
|
|
3521
|
-
function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform) {
|
|
3522
|
-
const sourceId = hostSourceUuid(sourceRef);
|
|
3523
|
-
if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
|
|
3524
|
-
const path = platform === "win32" ? win324 : posix3;
|
|
3525
|
-
const sourcesRoot = path.join(stateRoot, "sources");
|
|
3526
|
-
const sourceRoot = path.join(sourcesRoot, sourceId);
|
|
3527
|
-
const runtimeRoot = path.join(stateRoot, "run");
|
|
3528
|
-
const endpoint = platform === "win32" ? `\\\\.\\pipe\\ceal-host-${createHash4("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex").slice(0, 24)}` : path.join(runtimeRoot, `${sourceId}.sock`);
|
|
3529
|
-
return { sourceId, sourcesRoot, sourceRoot, relayRoot: path.join(sourceRoot, "relay"), codexOutbox: path.join(sourceRoot, "producers", "codex", "outbox"), claudeOutbox: path.join(sourceRoot, "producers", "claude", "outbox"), endpoint, runtimeRoot };
|
|
3530
|
-
}
|
|
3531
|
-
function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
|
|
3532
|
-
const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
|
|
3533
|
-
if (config.outbox_dir !== (producer === "codex" ? paths.codexOutbox : paths.claudeOutbox) || platform !== "win32" && config.relay_endpoint !== paths.endpoint) throw new TypeError("Host producer outbox and IPC must belong to its configured source.");
|
|
3534
|
-
return paths.endpoint;
|
|
3535
|
-
}
|
|
3536
|
-
|
|
3537
|
-
// host/producer-service.ts
|
|
3538
|
-
import { constants as constants3 } from "node:fs";
|
|
3539
|
-
import { lstat as lstat3 } from "node:fs/promises";
|
|
5136
|
+
import { constants as constants6 } from "node:fs";
|
|
5137
|
+
import { lstat as lstat4 } from "node:fs/promises";
|
|
3540
5138
|
var SAFE_REF2 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
|
3541
5139
|
var HOST_PRODUCER_CONFIG_FLAG = "--ceal-host-config";
|
|
3542
5140
|
var HostProducerServiceError = class extends Error {
|
|
@@ -3561,7 +5159,8 @@ function parseHostProducerConfigFlag(args, platform = process.platform) {
|
|
|
3561
5159
|
async function readHostProducerConfig(descriptor, configPath, platform = process.platform, custody = {}) {
|
|
3562
5160
|
const config = decodeHostProducerConfigText(descriptor, await readProducerConfigText(configPath, platform, hostProducerError, custody), platform);
|
|
3563
5161
|
const path = platform === "win32" ? win325 : posix4;
|
|
3564
|
-
const
|
|
5162
|
+
const registrationStateFile = hostProducerRegistrationStateFile(config.outbox_dir, platform);
|
|
5163
|
+
const root = path.dirname(registrationStateFile);
|
|
3565
5164
|
try {
|
|
3566
5165
|
assertHostProducerSourcePaths(root, config, descriptor.producer_id, platform);
|
|
3567
5166
|
} catch (error) {
|
|
@@ -3575,6 +5174,10 @@ function decodeHostProducerConfigText(descriptor, text, platform = process.platf
|
|
|
3575
5174
|
const { extra_paths: extras, ...core } = decoded;
|
|
3576
5175
|
return Object.freeze(descriptor.config({ schema_version: descriptor.schema, ...core }, extras));
|
|
3577
5176
|
}
|
|
5177
|
+
function hostProducerRegistrationStateFile(outboxDirectory, platform = process.platform) {
|
|
5178
|
+
const path = platform === "win32" ? win325 : posix4;
|
|
5179
|
+
return path.join(path.resolve(outboxDirectory, "../../../../.."), "registration.json");
|
|
5180
|
+
}
|
|
3578
5181
|
function hostProducerError(code2, message = code2) {
|
|
3579
5182
|
return new HostProducerServiceError(code2, message);
|
|
3580
5183
|
}
|
|
@@ -3620,7 +5223,7 @@ async function readProducerConfigText(configPath, platform, error, custody) {
|
|
|
3620
5223
|
function decodeProducerConfigCore(text, options) {
|
|
3621
5224
|
const ownership = producerConfigKeyOwnership(options.keys, options.platform);
|
|
3622
5225
|
const value = parseCanonicalJson(text, options.error);
|
|
3623
|
-
if (!
|
|
5226
|
+
if (!isRecord4(value) || !hasConfigKeys(value, ownership.required, ownership.tolerated) || value.schema_version !== options.schema) throw options.error("invalid_config", refusalFacts(producerShapeFacts(value, { schema: options.schema, keys: ownership.required, tolerated: ownership.tolerated })));
|
|
3624
5227
|
const hostSourceRef = typeof value.host_source_ref === "string" ? value.host_source_ref : "";
|
|
3625
5228
|
const installationRef = typeof value.producer_installation_ref === "string" ? value.producer_installation_ref : "";
|
|
3626
5229
|
const producerEpoch = validateIdentity(hostSourceRef, installationRef, value.producer_epoch, options.error);
|
|
@@ -3660,7 +5263,7 @@ function assertProducerAbsolutePath(value, platform, kind, error) {
|
|
|
3660
5263
|
}
|
|
3661
5264
|
async function configPathStat(configPath, error) {
|
|
3662
5265
|
try {
|
|
3663
|
-
return await
|
|
5266
|
+
return await lstat4(configPath);
|
|
3664
5267
|
} catch {
|
|
3665
5268
|
throw error("config_unavailable");
|
|
3666
5269
|
}
|
|
@@ -3672,7 +5275,7 @@ function validateConfigFile(value, platform, error, handle) {
|
|
|
3672
5275
|
}
|
|
3673
5276
|
async function openConfigFile(configPath, platform, error, custody) {
|
|
3674
5277
|
try {
|
|
3675
|
-
return await openNoFollow(configPath,
|
|
5278
|
+
return await openNoFollow(configPath, constants6.O_RDONLY, void 0, platform, custody);
|
|
3676
5279
|
} catch (error_) {
|
|
3677
5280
|
if (error_ instanceof SecureFileCustodyError) throw error(error_.reason === "not_private" ? "config_not_private" : "invalid_config");
|
|
3678
5281
|
throw error("config_unavailable");
|
|
@@ -3713,7 +5316,7 @@ function firstDifferenceIndex(left, right) {
|
|
|
3713
5316
|
return shared;
|
|
3714
5317
|
}
|
|
3715
5318
|
function producerShapeFacts(value, options) {
|
|
3716
|
-
if (!
|
|
5319
|
+
if (!isRecord4(value)) return [{ name: "config", value: "wrong_type", expected: "a record" }];
|
|
3717
5320
|
const tolerated = options.tolerated ?? [];
|
|
3718
5321
|
const allowed = [...options.keys, ...tolerated, ...Object.keys(HOST_PRODUCER_TIMING_DEFAULTS)];
|
|
3719
5322
|
const facts = [
|
|
@@ -3748,7 +5351,7 @@ function producerIntervalFacts(reconcile, retry, timeout) {
|
|
|
3748
5351
|
function hasConfigKeys(value, required, tolerated = []) {
|
|
3749
5352
|
return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || tolerated.includes(key) || Object.hasOwn(HOST_PRODUCER_TIMING_DEFAULTS, key));
|
|
3750
5353
|
}
|
|
3751
|
-
function
|
|
5354
|
+
function isRecord4(value) {
|
|
3752
5355
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3753
5356
|
}
|
|
3754
5357
|
function positive(value, maximum) {
|
|
@@ -3759,7 +5362,7 @@ function boundedMilliseconds(value) {
|
|
|
3759
5362
|
}
|
|
3760
5363
|
|
|
3761
5364
|
// host/claude/src/claude-decoder.ts
|
|
3762
|
-
import { createHash as
|
|
5365
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
3763
5366
|
|
|
3764
5367
|
// host/claude/src/claude-types.ts
|
|
3765
5368
|
var CLAUDE_SESSION_ID_ENVIRONMENT = "CLAUDE_CODE_SESSION_ID";
|
|
@@ -3791,7 +5394,7 @@ var ClaudeHostError = class extends Error {
|
|
|
3791
5394
|
// host/claude/src/claude-decoder.ts
|
|
3792
5395
|
var MAX_HOOK_BYTES = 256 * 1024;
|
|
3793
5396
|
function decodeClaudeQueuedPromptRow(row, sessionId) {
|
|
3794
|
-
if (!
|
|
5397
|
+
if (!record3(row)) return null;
|
|
3795
5398
|
if (row.type === "user") return decodeArrayTextPrompt(row, sessionId);
|
|
3796
5399
|
if (row.type === "attachment") return decodeQueuedCommandPrompt(row, sessionId);
|
|
3797
5400
|
if (row.type === "queue-operation") return decodeQueueEnqueuePrompt(row, sessionId);
|
|
@@ -3802,21 +5405,21 @@ function decodeClaudeHumanMessageRow(row, sessionId) {
|
|
|
3802
5405
|
return decodeClaudeNativeHumanMessage(row, sessionId);
|
|
3803
5406
|
}
|
|
3804
5407
|
function isClaudeNativeHumanMessageRow(row) {
|
|
3805
|
-
return
|
|
5408
|
+
return record3(row) && row.type === "user" && record3(row.message) && typeof row.message.content === "string";
|
|
3806
5409
|
}
|
|
3807
5410
|
function decodeClaudeNativeHumanMessage(row, sessionId) {
|
|
3808
5411
|
if (!sessionMatches(row, sessionId)) return null;
|
|
3809
|
-
if (row.isMeta === true && (!
|
|
5412
|
+
if (row.isMeta === true && (!record3(row.origin) || typeof row.origin.kind !== "string")) return null;
|
|
3810
5413
|
const identity = queuedRowIdentity(row);
|
|
3811
5414
|
if (identity === null) throw new ClaudeHostError("payload_rejected", "Claude transcript human message identity is malformed.");
|
|
3812
5415
|
const message = row.message;
|
|
3813
|
-
if (!
|
|
5416
|
+
if (!record3(message) || typeof message.content !== "string") return null;
|
|
3814
5417
|
return { turnId: identity.uuid, timestamp: identity.timestamp, content: message.content };
|
|
3815
5418
|
}
|
|
3816
5419
|
function decodeArrayTextPrompt(row, sessionId) {
|
|
3817
|
-
if (!
|
|
5420
|
+
if (!record3(row.message) || !Array.isArray(row.message.content)) return null;
|
|
3818
5421
|
if (!sessionMatches(row, sessionId)) return null;
|
|
3819
|
-
if (row.isMeta === true && (!
|
|
5422
|
+
if (row.isMeta === true && (!record3(row.origin) || typeof row.origin.kind !== "string")) return null;
|
|
3820
5423
|
const texts = arrayTextBlocks(row.message.content);
|
|
3821
5424
|
if (texts === null) return null;
|
|
3822
5425
|
const identity = queuedRowIdentity(row);
|
|
@@ -3826,13 +5429,13 @@ function decodeArrayTextPrompt(row, sessionId) {
|
|
|
3826
5429
|
function arrayTextBlocks(content) {
|
|
3827
5430
|
const texts = [];
|
|
3828
5431
|
for (const block of content) {
|
|
3829
|
-
if (!
|
|
5432
|
+
if (!record3(block) || block.type !== "text" || typeof block.text !== "string") return null;
|
|
3830
5433
|
texts.push(block.text);
|
|
3831
5434
|
}
|
|
3832
5435
|
return texts.length === 0 ? null : texts;
|
|
3833
5436
|
}
|
|
3834
5437
|
function decodeQueuedCommandPrompt(row, sessionId) {
|
|
3835
|
-
if (!
|
|
5438
|
+
if (!record3(row.attachment) || row.attachment.type !== "queued_command" || row.attachment.commandMode !== "prompt") return null;
|
|
3836
5439
|
if (typeof row.attachment.prompt !== "string" || row.attachment.prompt.length === 0) return null;
|
|
3837
5440
|
if (!sessionMatches(row, sessionId)) return null;
|
|
3838
5441
|
const identity = queuedRowIdentity(row);
|
|
@@ -3855,9 +5458,9 @@ function queuedRowIdentity(row) {
|
|
|
3855
5458
|
if (typeof row.timestamp !== "string" || !Number.isFinite(Date.parse(row.timestamp))) return null;
|
|
3856
5459
|
return { uuid: row.uuid, timestamp: row.timestamp };
|
|
3857
5460
|
}
|
|
3858
|
-
function queueEnqueueTurnId(sessionId,
|
|
3859
|
-
return `queue-enqueue:${
|
|
3860
|
-
${
|
|
5461
|
+
function queueEnqueueTurnId(sessionId, timestamp4, content) {
|
|
5462
|
+
return `queue-enqueue:${createHash7("sha256").update(`${sessionId}
|
|
5463
|
+
${timestamp4}
|
|
3861
5464
|
${content}`, "utf8").digest("hex").slice(0, 32)}`;
|
|
3862
5465
|
}
|
|
3863
5466
|
function claudeLocalSessionRef(sessionId) {
|
|
@@ -3870,15 +5473,15 @@ function claudeLocalInputRef(sessionId, turnId) {
|
|
|
3870
5473
|
return `claude-input:${cealRequestSha256({ session_id: sessionId, prompt_id: turnId })}`;
|
|
3871
5474
|
}
|
|
3872
5475
|
function digest(value) {
|
|
3873
|
-
return
|
|
5476
|
+
return createHash7("sha256").update(value, "utf8").digest("hex");
|
|
3874
5477
|
}
|
|
3875
|
-
function
|
|
5478
|
+
function record3(value) {
|
|
3876
5479
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3877
5480
|
}
|
|
3878
5481
|
|
|
3879
5482
|
// host/claude/src/claude-outbox.ts
|
|
3880
|
-
import { mkdir as
|
|
3881
|
-
import { isAbsolute as
|
|
5483
|
+
import { mkdir as mkdir5, readdir, readFile, unlink as unlink5 } from "node:fs/promises";
|
|
5484
|
+
import { isAbsolute as isAbsolute3, join as join5 } from "node:path";
|
|
3882
5485
|
|
|
3883
5486
|
// host/invocation-context.ts
|
|
3884
5487
|
var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
|
|
@@ -3913,7 +5516,7 @@ function invocationContextFromTurn(identity, promptRef, expiresAt, descriptor) {
|
|
|
3913
5516
|
return Object.freeze(context);
|
|
3914
5517
|
}
|
|
3915
5518
|
function isHostInvocationTurnSelection(value) {
|
|
3916
|
-
return
|
|
5519
|
+
return isRecord5(value) && Object.keys(value).length === 5 && value.schema_version === HOST_INVOCATION_TURN_SELECTION_SCHEMA && ["host_source_ref", "host_session_ref", "prompt_ref", "turn_generation_ref"].every((key) => safeRef2(value[key]));
|
|
3917
5520
|
}
|
|
3918
5521
|
function exactKeys3(value, keys) {
|
|
3919
5522
|
const actual = Object.keys(value);
|
|
@@ -3924,7 +5527,7 @@ function requiredKeys(value, required, optional) {
|
|
|
3924
5527
|
const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
|
|
3925
5528
|
return actual.length >= required.length && actual.length <= allowed.size && required.every((key) => Object.hasOwn(value, key)) && actual.every((key) => allowed.has(key));
|
|
3926
5529
|
}
|
|
3927
|
-
function
|
|
5530
|
+
function isRecord5(value) {
|
|
3928
5531
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3929
5532
|
}
|
|
3930
5533
|
function safeRef2(value) {
|
|
@@ -3932,6 +5535,7 @@ function safeRef2(value) {
|
|
|
3932
5535
|
}
|
|
3933
5536
|
|
|
3934
5537
|
// host/claude/src/claude-invocation-context.ts
|
|
5538
|
+
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
3935
5539
|
function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
|
|
3936
5540
|
return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
|
|
3937
5541
|
}
|
|
@@ -3942,7 +5546,7 @@ function validateClaudeHostInvocationContext(value) {
|
|
|
3942
5546
|
validateContextTimes(value);
|
|
3943
5547
|
}
|
|
3944
5548
|
function contextShape(value) {
|
|
3945
|
-
return
|
|
5549
|
+
return record4(value) && value.schema_version === CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION && hasHostInvocationContextKeys(value, ["working_directory", "turn_generation_ref"]);
|
|
3946
5550
|
}
|
|
3947
5551
|
function validateIdentity2(value) {
|
|
3948
5552
|
if (!validIdentity(value)) throw new ClaudeHostError("storage", "Claude Host invocation identity is malformed.");
|
|
@@ -3954,13 +5558,13 @@ function validateContextTimes(value) {
|
|
|
3954
5558
|
if (!timestamp(value.expires_at) || !optionalDirectory(value.working_directory)) throw new ClaudeHostError("storage", "Claude Host invocation context is malformed.");
|
|
3955
5559
|
}
|
|
3956
5560
|
function validIdentity(value) {
|
|
3957
|
-
return
|
|
5561
|
+
return record4(value) && hasHostInvocationIdentityKeys(value) && [value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef3);
|
|
3958
5562
|
}
|
|
3959
5563
|
function optionalSafeRef(value) {
|
|
3960
5564
|
return value === void 0 || safeRef3(value);
|
|
3961
5565
|
}
|
|
3962
5566
|
function optionalDirectory(value) {
|
|
3963
|
-
return value === void 0 || typeof value === "string" && value
|
|
5567
|
+
return value === void 0 || typeof value === "string" && isAbsolute2(value) && !value.includes("\0") && value.length <= 4096;
|
|
3964
5568
|
}
|
|
3965
5569
|
function safeRef3(value) {
|
|
3966
5570
|
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
|
|
@@ -3968,7 +5572,7 @@ function safeRef3(value) {
|
|
|
3968
5572
|
function timestamp(value) {
|
|
3969
5573
|
return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
|
|
3970
5574
|
}
|
|
3971
|
-
function
|
|
5575
|
+
function record4(value) {
|
|
3972
5576
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3973
5577
|
}
|
|
3974
5578
|
|
|
@@ -3985,18 +5589,18 @@ var ClaudeOutboxStore = class {
|
|
|
3985
5589
|
activeContexts;
|
|
3986
5590
|
turnSelections;
|
|
3987
5591
|
constructor(directory) {
|
|
3988
|
-
if (!directory
|
|
5592
|
+
if (!isAbsolute3(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
|
|
3989
5593
|
this.directory = directory;
|
|
3990
|
-
this.envelopes =
|
|
3991
|
-
this.sessions =
|
|
3992
|
-
this.registrations =
|
|
3993
|
-
this.cursors =
|
|
3994
|
-
this.activeContexts =
|
|
3995
|
-
this.turnSelections =
|
|
5594
|
+
this.envelopes = join5(directory, "envelopes");
|
|
5595
|
+
this.sessions = join5(directory, "sessions");
|
|
5596
|
+
this.registrations = join5(directory, "transcript-registrations");
|
|
5597
|
+
this.cursors = join5(directory, "transcript-cursors");
|
|
5598
|
+
this.activeContexts = join5(directory, "active-contexts");
|
|
5599
|
+
this.turnSelections = join5(directory, "turn-selections");
|
|
3996
5600
|
}
|
|
3997
5601
|
async prepare() {
|
|
3998
5602
|
for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
|
|
3999
|
-
await
|
|
5603
|
+
await mkdir5(path, { recursive: true, mode: 448 });
|
|
4000
5604
|
}
|
|
4001
5605
|
}
|
|
4002
5606
|
async activateInvocationContext(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
|
|
@@ -4042,7 +5646,7 @@ var ClaudeOutboxStore = class {
|
|
|
4042
5646
|
for (const name of await readdir(this.activeContexts)) {
|
|
4043
5647
|
if (!name.endsWith(".json")) continue;
|
|
4044
5648
|
try {
|
|
4045
|
-
const value = JSON.parse(await readFile(
|
|
5649
|
+
const value = JSON.parse(await readFile(join5(this.activeContexts, name), "utf8"));
|
|
4046
5650
|
validateClaudeHostInvocationContext(value);
|
|
4047
5651
|
if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
|
|
4048
5652
|
} catch {
|
|
@@ -4062,7 +5666,7 @@ var ClaudeOutboxStore = class {
|
|
|
4062
5666
|
for (const name of await readdir(this.envelopes)) {
|
|
4063
5667
|
if (!name.endsWith(".json")) continue;
|
|
4064
5668
|
try {
|
|
4065
|
-
const value = JSON.parse(await readFile(
|
|
5669
|
+
const value = JSON.parse(await readFile(join5(this.envelopes, name), "utf8"));
|
|
4066
5670
|
validateEnvelope(value);
|
|
4067
5671
|
entries.push(value);
|
|
4068
5672
|
} catch {
|
|
@@ -4075,7 +5679,7 @@ var ClaudeOutboxStore = class {
|
|
|
4075
5679
|
async removeEnvelope(entry) {
|
|
4076
5680
|
validateEnvelope(entry);
|
|
4077
5681
|
try {
|
|
4078
|
-
await
|
|
5682
|
+
await unlink5(this.envelopePath(entry.submission_ref));
|
|
4079
5683
|
} catch (error) {
|
|
4080
5684
|
if (code(error) !== "ENOENT") throw error;
|
|
4081
5685
|
}
|
|
@@ -4083,13 +5687,13 @@ var ClaudeOutboxStore = class {
|
|
|
4083
5687
|
async saveSession(snapshot) {
|
|
4084
5688
|
validateSession(snapshot);
|
|
4085
5689
|
await this.prepare();
|
|
4086
|
-
await durableAtomicReplace(
|
|
5690
|
+
await durableAtomicReplace(join5(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
|
|
4087
5691
|
}
|
|
4088
5692
|
async readSession(sourceRef, sessionRef) {
|
|
4089
5693
|
if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
|
|
4090
5694
|
await this.prepare();
|
|
4091
5695
|
try {
|
|
4092
|
-
const value = JSON.parse(await readFile(
|
|
5696
|
+
const value = JSON.parse(await readFile(join5(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
|
|
4093
5697
|
validateSession(value);
|
|
4094
5698
|
return value;
|
|
4095
5699
|
} catch (error) {
|
|
@@ -4124,7 +5728,7 @@ var ClaudeOutboxStore = class {
|
|
|
4124
5728
|
for (const name of await readdir(this.registrations)) {
|
|
4125
5729
|
if (!name.endsWith(".json")) continue;
|
|
4126
5730
|
try {
|
|
4127
|
-
const value = JSON.parse(await readFile(
|
|
5731
|
+
const value = JSON.parse(await readFile(join5(this.registrations, name), "utf8"));
|
|
4128
5732
|
validateRegistration(value);
|
|
4129
5733
|
registrations.push(value);
|
|
4130
5734
|
} catch {
|
|
@@ -4162,16 +5766,16 @@ var ClaudeOutboxStore = class {
|
|
|
4162
5766
|
await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
|
|
4163
5767
|
}
|
|
4164
5768
|
envelopePath(ref) {
|
|
4165
|
-
return
|
|
5769
|
+
return join5(this.envelopes, `${cealRequestSha256(ref)}.json`);
|
|
4166
5770
|
}
|
|
4167
5771
|
registrationPath(sourceRef, sessionRef) {
|
|
4168
|
-
return
|
|
5772
|
+
return join5(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
|
|
4169
5773
|
}
|
|
4170
5774
|
turnSelectionPath(sourceRef, sessionRef) {
|
|
4171
|
-
return
|
|
5775
|
+
return join5(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
|
|
4172
5776
|
}
|
|
4173
5777
|
cursorPath(sourceRef, sessionRef) {
|
|
4174
|
-
return
|
|
5778
|
+
return join5(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
|
|
4175
5779
|
}
|
|
4176
5780
|
async readRegistrationFile(path) {
|
|
4177
5781
|
try {
|
|
@@ -4185,13 +5789,13 @@ var ClaudeOutboxStore = class {
|
|
|
4185
5789
|
}
|
|
4186
5790
|
async removeStateFile(path) {
|
|
4187
5791
|
try {
|
|
4188
|
-
await
|
|
5792
|
+
await unlink5(path);
|
|
4189
5793
|
} catch (error) {
|
|
4190
5794
|
if (code(error) !== "ENOENT") throw error;
|
|
4191
5795
|
}
|
|
4192
5796
|
}
|
|
4193
5797
|
activeContextPath(identity) {
|
|
4194
|
-
return
|
|
5798
|
+
return join5(this.activeContexts, `${invocationContextKey(identity)}.json`);
|
|
4195
5799
|
}
|
|
4196
5800
|
};
|
|
4197
5801
|
function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
|
|
@@ -4214,15 +5818,15 @@ function safeRef4(value) {
|
|
|
4214
5818
|
function timestamp2(value) {
|
|
4215
5819
|
return typeof value === "string" && Number.isFinite(Date.parse(value));
|
|
4216
5820
|
}
|
|
4217
|
-
function
|
|
5821
|
+
function record5(value) {
|
|
4218
5822
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4219
5823
|
}
|
|
4220
5824
|
function code(error) {
|
|
4221
|
-
return
|
|
5825
|
+
return record5(error) && typeof error.code === "string" ? error.code : null;
|
|
4222
5826
|
}
|
|
4223
5827
|
function validateEnvelope(value) {
|
|
4224
|
-
if (!
|
|
4225
|
-
if (!
|
|
5828
|
+
if (!record5(value)) throw new ClaudeHostError("storage", "Claude outbox entry is malformed.");
|
|
5829
|
+
if (!sameKeys2(value, ["schema_version", "identity", "host_input_ref", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"])) {
|
|
4226
5830
|
throw new ClaudeHostError("storage", `Claude outbox entry key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the outbox entry key set")}).`);
|
|
4227
5831
|
}
|
|
4228
5832
|
if (value.schema_version !== CLAUDE_OUTBOX_SCHEMA_VERSION) throw new ClaudeHostError("storage", `Claude outbox entry is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CLAUDE_OUTBOX_SCHEMA_VERSION}`)}).`);
|
|
@@ -4245,8 +5849,8 @@ function validateEnvelopeObservations(value) {
|
|
|
4245
5849
|
}
|
|
4246
5850
|
}
|
|
4247
5851
|
function validateSession(value) {
|
|
4248
|
-
if (!
|
|
4249
|
-
if (!
|
|
5852
|
+
if (!record5(value)) throw new ClaudeHostError("storage", "Claude session snapshot is malformed.");
|
|
5853
|
+
if (!sameKeys2(value, ["schema_version", "host_session_ref", "host_source_ref", "observed_at", "value", "expires_at"])) {
|
|
4250
5854
|
throw new ClaudeHostError("storage", `Claude session snapshot key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the session snapshot key set")}).`);
|
|
4251
5855
|
}
|
|
4252
5856
|
if (value.schema_version !== CLAUDE_SESSION_SCHEMA_VERSION) throw new ClaudeHostError("storage", `Claude session snapshot is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CLAUDE_SESSION_SCHEMA_VERSION}`)}).`);
|
|
@@ -4255,8 +5859,8 @@ function validateSession(value) {
|
|
|
4255
5859
|
}
|
|
4256
5860
|
}
|
|
4257
5861
|
function validateRegistration(value) {
|
|
4258
|
-
if (!
|
|
4259
|
-
if (!
|
|
5862
|
+
if (!record5(value)) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
|
|
5863
|
+
if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "claude_session_id", "transcript_path", "registered_at", "expires_at"], ["cwd"])) {
|
|
4260
5864
|
throw new ClaudeHostError("storage", `Claude transcript registration key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the registration key set")}).`);
|
|
4261
5865
|
}
|
|
4262
5866
|
if (value.schema_version !== CLAUDE_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript registration is malformed.");
|
|
@@ -4267,7 +5871,7 @@ function validateRegistration(value) {
|
|
|
4267
5871
|
if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
|
|
4268
5872
|
}
|
|
4269
5873
|
function validateRegistrationPaths(cwd, transcriptPath) {
|
|
4270
|
-
if (cwd !== void 0 && (typeof cwd !== "string" || !
|
|
5874
|
+
if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute3(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
|
|
4271
5875
|
throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
|
|
4272
5876
|
}
|
|
4273
5877
|
if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
|
|
@@ -4275,14 +5879,21 @@ function validateRegistrationPaths(cwd, transcriptPath) {
|
|
|
4275
5879
|
}
|
|
4276
5880
|
}
|
|
4277
5881
|
function validateCursor(value) {
|
|
4278
|
-
if (!
|
|
4279
|
-
if (!
|
|
5882
|
+
if (!record5(value)) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
|
|
5883
|
+
if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "transcript_path", "offset", "anchor_start", "anchor_sha256", "subagents", "status", "updated_at"], ["device", "human_message_window", "inode", "open_turn", "unattributed", "session_observed", "reason"])) {
|
|
4280
5884
|
throw new ClaudeHostError("storage", "Claude transcript cursor key set is malformed.");
|
|
4281
5885
|
}
|
|
4282
5886
|
if (value.schema_version !== CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION) throw new ClaudeHostError("storage", "Claude transcript cursor is malformed.");
|
|
4283
5887
|
if (![value.host_source_ref, value.host_session_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) throw new ClaudeHostError("storage", "Claude transcript cursor references are malformed.");
|
|
4284
5888
|
if (typeof value.transcript_path !== "string" || value.transcript_path.length === 0) throw new ClaudeHostError("storage", "Claude transcript cursor path is malformed.");
|
|
4285
5889
|
validateCursorPosition(value);
|
|
5890
|
+
if (value.human_message_window !== void 0) {
|
|
5891
|
+
try {
|
|
5892
|
+
decodeCealHostInvocationHumanMessageWindow(value.human_message_window);
|
|
5893
|
+
} catch {
|
|
5894
|
+
throw new ClaudeHostError("storage", "Claude transcript human-message projection is malformed.");
|
|
5895
|
+
}
|
|
5896
|
+
}
|
|
4286
5897
|
validateCursorTurn(value.open_turn, value.unattributed, value.session_observed);
|
|
4287
5898
|
validateSubagentCursors(value.subagents);
|
|
4288
5899
|
if (value.reason !== void 0 && !isHostTranscriptCursorReason(value.reason)) throw new ClaudeHostError("storage", "Claude transcript cursor reason is malformed.");
|
|
@@ -4300,13 +5911,13 @@ function validateCursorTurn(openTurn, unattributed, sessionObserved) {
|
|
|
4300
5911
|
if (sessionObserved !== void 0 && typeof sessionObserved !== "boolean") throw new ClaudeHostError("storage", "Claude transcript cursor session marker is malformed.");
|
|
4301
5912
|
}
|
|
4302
5913
|
function validateSubagentCursors(value) {
|
|
4303
|
-
if (!
|
|
5914
|
+
if (!record5(value)) throw new ClaudeHostError("storage", "Claude transcript subagent cursors are malformed.");
|
|
4304
5915
|
for (const [name, entry] of Object.entries(value)) validateSubagentEntry(name, entry);
|
|
4305
5916
|
}
|
|
4306
5917
|
function validateSubagentEntry(name, entry) {
|
|
4307
5918
|
if (name.length === 0 || name.length > CLAUDE_TRANSCRIPT_SUBAGENT_NAME_MAX_CHARACTERS || name.includes("/")) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
|
|
4308
5919
|
if (name.includes("\0")) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
|
|
4309
|
-
if (!
|
|
5920
|
+
if (!record5(entry) || !sameKeys2(entry, ["offset", "anchor_start", "anchor_sha256"], ["device", "inode"]) || !nonNegativeInteger(entry.offset)) throw new ClaudeHostError("storage", "Claude transcript subagent cursor is malformed.");
|
|
4310
5921
|
validateSubagentIdentity(entry);
|
|
4311
5922
|
}
|
|
4312
5923
|
function validateSubagentIdentity(entry) {
|
|
@@ -4322,7 +5933,7 @@ function validCursorPosition(value) {
|
|
|
4322
5933
|
return nonNegativeInteger(value.offset) && nonNegativeInteger(value.anchor_start) && typeof value.anchor_sha256 === "string" && /^[a-f0-9]{64}$/u.test(value.anchor_sha256);
|
|
4323
5934
|
}
|
|
4324
5935
|
function validOpenTurn(value) {
|
|
4325
|
-
if (!
|
|
5936
|
+
if (!record5(value) || !sameKeys2(value, ["turn_key", "user_uuid", "prompt_ref", "host_input_ref", "started_at", "last_observed_at", "message_ids", "counts"], ["last_terminal_digest"])) return false;
|
|
4326
5937
|
if (![value.turn_key, value.user_uuid, value.prompt_ref, value.host_input_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) return false;
|
|
4327
5938
|
if (!timestamp2(value.started_at) || !timestamp2(value.last_observed_at)) return false;
|
|
4328
5939
|
if (!validMessageIds(value.message_ids)) return false;
|
|
@@ -4335,24 +5946,24 @@ function validMessageIds(value) {
|
|
|
4335
5946
|
return new Set(value).size === value.length;
|
|
4336
5947
|
}
|
|
4337
5948
|
function validUnattributed(value) {
|
|
4338
|
-
if (!
|
|
5949
|
+
if (!record5(value) || !sameKeys2(value, ["input", "cached_input", "cache_write_input", "output", "message_ids", "last_observed_at"])) return false;
|
|
4339
5950
|
if (!validMessageIds(value.message_ids) || value.message_ids.length === 0) return false;
|
|
4340
5951
|
if (!timestamp2(value.last_observed_at)) return false;
|
|
4341
5952
|
return validTurnCounts(value);
|
|
4342
5953
|
}
|
|
4343
5954
|
function validTurnCounts(value) {
|
|
4344
|
-
if (!
|
|
5955
|
+
if (!record5(value) || !sameKeys2(value, ["input", "cached_input", "cache_write_input", "output"])) return false;
|
|
4345
5956
|
return [value.input, value.cached_input, value.cache_write_input, value.output].every(nonNegativeInteger);
|
|
4346
5957
|
}
|
|
4347
5958
|
function validateIdentity3(value) {
|
|
4348
|
-
if (!
|
|
5959
|
+
if (!record5(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) {
|
|
4349
5960
|
throw new ClaudeHostError("storage", "Claude Host identity is malformed.");
|
|
4350
5961
|
}
|
|
4351
5962
|
}
|
|
4352
5963
|
function nonNegativeInteger(value) {
|
|
4353
5964
|
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
4354
5965
|
}
|
|
4355
|
-
function
|
|
5966
|
+
function sameKeys2(value, required, optional = []) {
|
|
4356
5967
|
return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
|
|
4357
5968
|
}
|
|
4358
5969
|
|
|
@@ -4380,7 +5991,7 @@ var ClaudeProducer = class {
|
|
|
4380
5991
|
|
|
4381
5992
|
// host/claude/src/claude-transcript-watcher.ts
|
|
4382
5993
|
import { readdir as readdir2 } from "node:fs/promises";
|
|
4383
|
-
import { join as
|
|
5994
|
+
import { join as join6 } from "node:path";
|
|
4384
5995
|
var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
|
|
4385
5996
|
var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
4386
5997
|
store;
|
|
@@ -4430,6 +6041,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
4430
6041
|
offset: 0,
|
|
4431
6042
|
anchor_start: 0,
|
|
4432
6043
|
anchor_sha256: this.sha(Buffer.alloc(0)),
|
|
6044
|
+
human_message_window: { messages: [], truncated: false },
|
|
4433
6045
|
subagents: {},
|
|
4434
6046
|
status: "active",
|
|
4435
6047
|
updated_at: this.stamp()
|
|
@@ -4451,33 +6063,64 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
4451
6063
|
const cursor = existing ?? this.initialCursor(registration);
|
|
4452
6064
|
if (cursor.device === void 0) {
|
|
4453
6065
|
if (cursor.offset !== 0) return await this.quarantineStored(cursor, device, inode, "transcript_replaced");
|
|
4454
|
-
return { ...cursor, device, inode };
|
|
6066
|
+
return { ...cursor, device, inode, human_message_window: cursor.human_message_window ?? { messages: [], truncated: false } };
|
|
4455
6067
|
}
|
|
4456
6068
|
const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
|
|
4457
6069
|
if (reason !== null) return await this.quarantineStored(cursor, device, inode, reason);
|
|
4458
|
-
return cursor;
|
|
6070
|
+
if (cursor.human_message_window !== void 0) return cursor;
|
|
6071
|
+
return { ...cursor, human_message_window: await this.readHumanMessageProjection(registration, handle, cursor.offset) };
|
|
6072
|
+
}
|
|
6073
|
+
async readHumanMessageProjection(registration, handle, watermark) {
|
|
6074
|
+
let offset = 0;
|
|
6075
|
+
let window = { messages: [], truncated: false };
|
|
6076
|
+
while (offset < watermark) {
|
|
6077
|
+
const complete = await this.readChunk(handle, offset, watermark);
|
|
6078
|
+
if (complete === "empty" || complete === "partial") throw new ClaudeHostError("payload_rejected", "Claude transcript projection prefix is incomplete.", "malformed_line");
|
|
6079
|
+
for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
|
|
6080
|
+
let row;
|
|
6081
|
+
try {
|
|
6082
|
+
row = JSON.parse(line);
|
|
6083
|
+
} catch {
|
|
6084
|
+
throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
|
|
6085
|
+
}
|
|
6086
|
+
const prompt = decodeClaudeHumanMessageRow(row, registration.claude_session_id);
|
|
6087
|
+
if (prompt !== null) window = mergeHostInvocationHumanMessageWindow(window, [{
|
|
6088
|
+
host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, prompt.turnId),
|
|
6089
|
+
host_input_ref: claudeLocalInputRef(registration.claude_session_id, prompt.turnId),
|
|
6090
|
+
text: prompt.content
|
|
6091
|
+
}]);
|
|
6092
|
+
}
|
|
6093
|
+
offset += complete.length;
|
|
6094
|
+
}
|
|
6095
|
+
if (offset !== watermark) throw new ClaudeHostError("payload_rejected", "Claude transcript projection prefix does not match its cursor boundary.", "malformed_line");
|
|
6096
|
+
return window;
|
|
4459
6097
|
}
|
|
4460
6098
|
async consumeMainChunk(registration, complete, draft) {
|
|
4461
6099
|
for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
|
|
4462
6100
|
draft.consumed += 1;
|
|
4463
|
-
const
|
|
4464
|
-
if (
|
|
4465
|
-
if (isUserTurnLine(
|
|
4466
|
-
else if (isAssistantUsageLine(
|
|
4467
|
-
else if (isAssistantLine(
|
|
6101
|
+
const record6 = parseTranscriptLine(line);
|
|
6102
|
+
if (record6 === null) throw new ClaudeHostError("payload_rejected", "Claude transcript line is not valid JSON.", "malformed_line");
|
|
6103
|
+
if (isUserTurnLine(record6)) await this.openTurn(registration, draft, record6);
|
|
6104
|
+
else if (isAssistantUsageLine(record6)) this.accumulateUsage(draft, toUsage(record6.uuid, record6.timestamp, record6.message.usage));
|
|
6105
|
+
else if (isAssistantLine(record6) && record6.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude transcript usage is malformed.");
|
|
4468
6106
|
else {
|
|
4469
|
-
const queued = decodeClaudeQueuedPromptRow(
|
|
6107
|
+
const queued = decodeClaudeQueuedPromptRow(record6, registration.claude_session_id);
|
|
4470
6108
|
if (queued !== null) await this.openQueuedTurn(registration, draft, queued);
|
|
4471
6109
|
}
|
|
4472
6110
|
}
|
|
4473
6111
|
}
|
|
4474
|
-
async openTurn(registration, draft,
|
|
4475
|
-
await this.openPromptTurn(registration, draft, { uuid:
|
|
6112
|
+
async openTurn(registration, draft, record6) {
|
|
6113
|
+
await this.openPromptTurn(registration, draft, { uuid: record6.uuid, timestamp: record6.timestamp, content: record6.message.content });
|
|
4476
6114
|
}
|
|
4477
6115
|
async openQueuedTurn(registration, draft, queued) {
|
|
4478
6116
|
await this.openPromptTurn(registration, draft, { uuid: queued.turnId, timestamp: queued.timestamp, content: queued.content });
|
|
4479
6117
|
}
|
|
4480
6118
|
async openPromptTurn(registration, draft, prompt) {
|
|
6119
|
+
draft.human_message_window = mergeHostInvocationHumanMessageWindow(draft.human_message_window, [{
|
|
6120
|
+
host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, prompt.uuid),
|
|
6121
|
+
host_input_ref: claudeLocalInputRef(registration.claude_session_id, prompt.uuid),
|
|
6122
|
+
text: prompt.content
|
|
6123
|
+
}]);
|
|
4481
6124
|
await this.closeTurn(registration, draft, prompt.timestamp);
|
|
4482
6125
|
const sessionRef = registration.host_session_ref;
|
|
4483
6126
|
const turnRef = claudeLocalTurnRef(registration.claude_session_id, prompt.uuid);
|
|
@@ -4495,7 +6138,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
4495
6138
|
}
|
|
4496
6139
|
await this.persistOpenedTurnContext(draft, { uuid: prompt.uuid, timestamp: prompt.timestamp, message: { content: prompt.content } }, inputRef, turnRef, promptRef, identity, observations);
|
|
4497
6140
|
}
|
|
4498
|
-
async persistOpenedTurnContext(draft,
|
|
6141
|
+
async persistOpenedTurnContext(draft, record6, inputRef, turnRef, promptRef, identity, observations) {
|
|
4499
6142
|
const expiresAt = this.expire(this.outboxRetentionMs);
|
|
4500
6143
|
await this.store.putEnvelope({
|
|
4501
6144
|
schema_version: "ceal.claude_observation_outbox.v1",
|
|
@@ -4505,27 +6148,27 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
4505
6148
|
observations,
|
|
4506
6149
|
origin_input: true,
|
|
4507
6150
|
submission_ref: submissionRef("input", turnRef, inputRef, promptRef),
|
|
4508
|
-
created_at:
|
|
6151
|
+
created_at: record6.timestamp,
|
|
4509
6152
|
expires_at: expiresAt
|
|
4510
6153
|
});
|
|
4511
6154
|
draft.enqueued += 1;
|
|
4512
6155
|
await this.activateOpenedTurnContext(identity, promptRef, expiresAt);
|
|
4513
|
-
this.setOpenedTurn(draft,
|
|
6156
|
+
this.setOpenedTurn(draft, record6, inputRef, turnRef, promptRef);
|
|
4514
6157
|
}
|
|
4515
6158
|
async activateOpenedTurnContext(identity, promptRef, expiresAt) {
|
|
4516
6159
|
const selection = await this.store.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref);
|
|
4517
6160
|
const turnGenerationRef = selection?.prompt_ref === promptRef ? selection.turn_generation_ref : void 0;
|
|
4518
6161
|
await this.activateContext(identity, promptRef, turnGenerationRef, expiresAt);
|
|
4519
6162
|
}
|
|
4520
|
-
setOpenedTurn(draft,
|
|
6163
|
+
setOpenedTurn(draft, record6, inputRef, turnRef, promptRef) {
|
|
4521
6164
|
const folded = foldUnattributed(draft.unattributed);
|
|
4522
6165
|
draft.open_turn = {
|
|
4523
6166
|
turn_key: turnRef,
|
|
4524
|
-
user_uuid:
|
|
6167
|
+
user_uuid: record6.uuid,
|
|
4525
6168
|
prompt_ref: promptRef,
|
|
4526
6169
|
host_input_ref: inputRef,
|
|
4527
|
-
started_at:
|
|
4528
|
-
last_observed_at: folded?.last_observed_at ??
|
|
6170
|
+
started_at: record6.timestamp,
|
|
6171
|
+
last_observed_at: folded?.last_observed_at ?? record6.timestamp,
|
|
4529
6172
|
message_ids: folded?.message_ids ?? [],
|
|
4530
6173
|
counts: folded?.counts ?? zeroCounts()
|
|
4531
6174
|
};
|
|
@@ -4586,7 +6229,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
4586
6229
|
return consumed;
|
|
4587
6230
|
}
|
|
4588
6231
|
async consumeSubagentFile(draft, directory, name) {
|
|
4589
|
-
const path =
|
|
6232
|
+
const path = join6(directory, name);
|
|
4590
6233
|
let handle;
|
|
4591
6234
|
try {
|
|
4592
6235
|
handle = await openNoFollow(path);
|
|
@@ -4617,10 +6260,10 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
4617
6260
|
let consumed = 0;
|
|
4618
6261
|
for (const line of chunk.toString("utf8").split("\n").filter((value) => value.length > 0)) {
|
|
4619
6262
|
consumed += 1;
|
|
4620
|
-
const
|
|
4621
|
-
if (
|
|
4622
|
-
if (isAssistantUsageLine(
|
|
4623
|
-
else if (isAssistantLine(
|
|
6263
|
+
const record6 = parseTranscriptLine(line);
|
|
6264
|
+
if (record6 === null) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript line is not valid JSON.", "malformed_line");
|
|
6265
|
+
if (isAssistantUsageLine(record6)) this.accumulateUsage(draft, toUsage(record6.uuid, record6.timestamp, record6.message.usage));
|
|
6266
|
+
else if (isAssistantLine(record6) && record6.message.usage !== void 0) throw new ClaudeHostError("payload_rejected", "Claude subagent transcript usage is malformed.");
|
|
4624
6267
|
}
|
|
4625
6268
|
return consumed;
|
|
4626
6269
|
}
|
|
@@ -4679,6 +6322,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
4679
6322
|
offset: draft.offset,
|
|
4680
6323
|
anchor_start: anchor.start,
|
|
4681
6324
|
anchor_sha256: anchor.sha256,
|
|
6325
|
+
human_message_window: draft.human_message_window,
|
|
4682
6326
|
subagents: draft.subagents,
|
|
4683
6327
|
...draft.open_turn === void 0 ? {} : { open_turn: draft.open_turn },
|
|
4684
6328
|
...draft.unattributed === void 0 ? {} : { unattributed: draft.unattributed },
|
|
@@ -4724,6 +6368,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
4724
6368
|
function mutableCursor(cursor) {
|
|
4725
6369
|
return {
|
|
4726
6370
|
offset: cursor.offset,
|
|
6371
|
+
human_message_window: cursor.human_message_window ?? { messages: [], truncated: false },
|
|
4727
6372
|
...cursor.open_turn === void 0 ? {} : { open_turn: cursor.open_turn },
|
|
4728
6373
|
...cursor.unattributed === void 0 ? {} : { unattributed: cursor.unattributed },
|
|
4729
6374
|
subagents: Object.fromEntries(Object.entries(cursor.subagents).map(([name, entry]) => [name, { ...entry }])),
|
|
@@ -4800,32 +6445,32 @@ function parseTranscriptLine(line) {
|
|
|
4800
6445
|
return null;
|
|
4801
6446
|
}
|
|
4802
6447
|
}
|
|
4803
|
-
function lineIdentity(
|
|
4804
|
-
if (typeof
|
|
4805
|
-
if (typeof
|
|
4806
|
-
return { uuid:
|
|
6448
|
+
function lineIdentity(record6) {
|
|
6449
|
+
if (typeof record6.uuid !== "string" || record6.uuid.length === 0 || record6.uuid.length > 256) return null;
|
|
6450
|
+
if (typeof record6.timestamp !== "string" || !Number.isFinite(Date.parse(record6.timestamp))) return null;
|
|
6451
|
+
return { uuid: record6.uuid, timestamp: record6.timestamp };
|
|
4807
6452
|
}
|
|
4808
|
-
function isUserTurnLine(
|
|
4809
|
-
if (!isTranscriptRecord(
|
|
4810
|
-
if (!isTranscriptRecord(
|
|
4811
|
-
if (
|
|
4812
|
-
const identity = lineIdentity(
|
|
6453
|
+
function isUserTurnLine(record6) {
|
|
6454
|
+
if (!isTranscriptRecord(record6) || record6.type !== "user") return false;
|
|
6455
|
+
if (!isTranscriptRecord(record6.message) || typeof record6.message.content !== "string") return false;
|
|
6456
|
+
if (record6.isMeta === true && (!isTranscriptRecord(record6.origin) || typeof record6.origin.kind !== "string")) return false;
|
|
6457
|
+
const identity = lineIdentity(record6);
|
|
4813
6458
|
if (identity === null) throw new ClaudeHostError("payload_rejected", "Claude transcript user line is malformed.");
|
|
4814
6459
|
return true;
|
|
4815
6460
|
}
|
|
4816
|
-
function isAssistantLine(
|
|
4817
|
-
return isTranscriptRecord(
|
|
6461
|
+
function isAssistantLine(record6) {
|
|
6462
|
+
return isTranscriptRecord(record6) && record6.type === "assistant" && isTranscriptRecord(record6.message);
|
|
4818
6463
|
}
|
|
4819
|
-
function isAssistantUsageLine(
|
|
4820
|
-
if (!isTranscriptRecord(
|
|
4821
|
-
if (!isAssistantLine(
|
|
4822
|
-
const identity = lineIdentity(
|
|
4823
|
-
if (identity === null || !isTranscriptRecord(
|
|
6464
|
+
function isAssistantUsageLine(record6) {
|
|
6465
|
+
if (!isTranscriptRecord(record6)) return false;
|
|
6466
|
+
if (!isAssistantLine(record6) || record6.message.usage === void 0) return false;
|
|
6467
|
+
const identity = lineIdentity(record6);
|
|
6468
|
+
if (identity === null || !isTranscriptRecord(record6.message.usage)) throw new ClaudeHostError("payload_rejected", "Claude transcript usage line is malformed.");
|
|
4824
6469
|
return true;
|
|
4825
6470
|
}
|
|
4826
6471
|
function subagentsDirectory(transcriptPath) {
|
|
4827
6472
|
const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
|
|
4828
|
-
return
|
|
6473
|
+
return join6(stem, "subagents");
|
|
4829
6474
|
}
|
|
4830
6475
|
function observationRef(hostSourceRef, event, identity, value) {
|
|
4831
6476
|
return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
|
|
@@ -4874,6 +6519,377 @@ async function drainClaudeProducerOnce(options) {
|
|
|
4874
6519
|
return { scanned: scan.enqueued, ...await producer.drainOutbox() };
|
|
4875
6520
|
}
|
|
4876
6521
|
|
|
6522
|
+
// host/claude/src/claude-usage-facts-capturer.ts
|
|
6523
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
6524
|
+
import { constants as constants7 } from "node:fs";
|
|
6525
|
+
import { readdir as readdir3 } from "node:fs/promises";
|
|
6526
|
+
import { join as join7 } from "node:path";
|
|
6527
|
+
var ClaudeUsageFactsCapturer = class {
|
|
6528
|
+
sources;
|
|
6529
|
+
usage;
|
|
6530
|
+
now;
|
|
6531
|
+
diagnosticSink;
|
|
6532
|
+
nextRegistrationIndex = 0;
|
|
6533
|
+
nextSourceSlot = "main";
|
|
6534
|
+
nextSubagentIndex = 0;
|
|
6535
|
+
constructor(options) {
|
|
6536
|
+
this.sources = new ClaudeOutboxStore(options.outbox_dir);
|
|
6537
|
+
this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
|
|
6538
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
6539
|
+
this.diagnosticSink = options.diagnostic_sink;
|
|
6540
|
+
}
|
|
6541
|
+
async captureNext() {
|
|
6542
|
+
const registrations = await this.sources.listTranscriptRegistrations();
|
|
6543
|
+
let failed = false;
|
|
6544
|
+
const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
|
|
6545
|
+
failed = true;
|
|
6546
|
+
}));
|
|
6547
|
+
this.nextRegistrationIndex = result.nextIndex;
|
|
6548
|
+
if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
|
|
6549
|
+
return result.captured;
|
|
6550
|
+
}
|
|
6551
|
+
async captureRegistration(registration, onFailure) {
|
|
6552
|
+
const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
|
|
6553
|
+
for (const source of sources) {
|
|
6554
|
+
let captured = false;
|
|
6555
|
+
try {
|
|
6556
|
+
captured = source === "main" ? await this.captureMain(registration) : await this.captureSubagent(registration, onFailure);
|
|
6557
|
+
} catch (error) {
|
|
6558
|
+
if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
|
|
6559
|
+
onFailure();
|
|
6560
|
+
}
|
|
6561
|
+
if (captured) {
|
|
6562
|
+
this.nextSourceSlot = source === "main" ? "subagent" : "main";
|
|
6563
|
+
return true;
|
|
6564
|
+
}
|
|
6565
|
+
}
|
|
6566
|
+
return false;
|
|
6567
|
+
}
|
|
6568
|
+
async captureMain(registration) {
|
|
6569
|
+
const prepared = await openHostUsageTranscriptCursor({
|
|
6570
|
+
path: registration.transcript_path,
|
|
6571
|
+
producer: "claude",
|
|
6572
|
+
source_kind: "claude_transcript",
|
|
6573
|
+
host_source_ref: registration.host_source_ref,
|
|
6574
|
+
host_session_ref: registration.host_session_ref,
|
|
6575
|
+
source_slot: "main",
|
|
6576
|
+
created_at: this.stamp(),
|
|
6577
|
+
store: this.usage,
|
|
6578
|
+
inspect: ownedClaudeTranscriptFile,
|
|
6579
|
+
initial_cursor: initialCursor
|
|
6580
|
+
});
|
|
6581
|
+
if (prepared === null) return false;
|
|
6582
|
+
const { handle: main2, source: mainFile, source_file_ref: mainRef, state, cursor } = prepared;
|
|
6583
|
+
try {
|
|
6584
|
+
if (cursor.source_file_ref !== mainRef || cursor.device !== mainFile.device || cursor.inode !== mainFile.inode || mainFile.size < cursor.offset || !await anchorMatches(main2, cursor)) {
|
|
6585
|
+
await this.usage.commitScanTransition(state, "main", cursor, initialCursor(mainRef, mainFile.device, mainFile.inode), null, [unscopedGap("source_file_replaced")]);
|
|
6586
|
+
return true;
|
|
6587
|
+
}
|
|
6588
|
+
if (mainFile.size > cursor.offset) return await this.captureFile(main2, registration, "main", mainRef, cursor, mainFile.size, state);
|
|
6589
|
+
} finally {
|
|
6590
|
+
await main2.close();
|
|
6591
|
+
}
|
|
6592
|
+
return false;
|
|
6593
|
+
}
|
|
6594
|
+
async captureSubagent(registration, onFailure) {
|
|
6595
|
+
const names = await readSubagentNames(registration);
|
|
6596
|
+
let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
|
|
6597
|
+
if (state === null) return false;
|
|
6598
|
+
state = await this.usage.recoverPending(state);
|
|
6599
|
+
if (state.quarantined_reason !== void 0) return false;
|
|
6600
|
+
if (await this.retireMissingSubagent(state, names)) return true;
|
|
6601
|
+
if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
|
|
6602
|
+
return await this.recordExcessSubagentGap(state, names);
|
|
6603
|
+
}
|
|
6604
|
+
async retireMissingSubagent(state, names) {
|
|
6605
|
+
const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
|
|
6606
|
+
for (const [slot, cursor] of Object.entries(state.cursors)) {
|
|
6607
|
+
if (!slot.startsWith("subagent:") || liveSlots.has(slot)) continue;
|
|
6608
|
+
await this.usage.retireCursor(state, slot, cursor, unscopedGap("source_file_retired"));
|
|
6609
|
+
return true;
|
|
6610
|
+
}
|
|
6611
|
+
return false;
|
|
6612
|
+
}
|
|
6613
|
+
async recordExcessSubagentGap(state, names) {
|
|
6614
|
+
const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
|
|
6615
|
+
if (excessCount <= 0) return false;
|
|
6616
|
+
const mainCursor = state.cursors.main;
|
|
6617
|
+
if (mainCursor === void 0) return false;
|
|
6618
|
+
const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
|
|
6619
|
+
await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
|
|
6620
|
+
return true;
|
|
6621
|
+
}
|
|
6622
|
+
async captureListedSubagents(registration, names, state, onFailure) {
|
|
6623
|
+
const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
|
|
6624
|
+
for (let attempt = 0; attempt < candidates.length; attempt += 1) {
|
|
6625
|
+
const index = (this.nextSubagentIndex + attempt) % candidates.length;
|
|
6626
|
+
const name = candidates[index];
|
|
6627
|
+
if (name === void 0) continue;
|
|
6628
|
+
try {
|
|
6629
|
+
if (await this.captureSubagentFile(registration, name, state)) {
|
|
6630
|
+
this.nextSubagentIndex = (index + 1) % candidates.length;
|
|
6631
|
+
return true;
|
|
6632
|
+
}
|
|
6633
|
+
} catch (error) {
|
|
6634
|
+
if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
|
|
6635
|
+
onFailure();
|
|
6636
|
+
}
|
|
6637
|
+
}
|
|
6638
|
+
return false;
|
|
6639
|
+
}
|
|
6640
|
+
async captureSubagentFile(registration, name, state) {
|
|
6641
|
+
let handle;
|
|
6642
|
+
try {
|
|
6643
|
+
const opened = await readHostUsageTranscriptSource(() => openNoFollow(join7(subagentsDirectory(registration.transcript_path), name), constants7.O_RDONLY));
|
|
6644
|
+
handle = opened;
|
|
6645
|
+
const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
|
|
6646
|
+
const sourceRef = sourceFileRef(registration, file.device, file.inode);
|
|
6647
|
+
const slot = subagentSlot(name);
|
|
6648
|
+
let current = state.cursors[slot];
|
|
6649
|
+
if (current === void 0) {
|
|
6650
|
+
current = initialCursor(sourceRef, file.device, file.inode);
|
|
6651
|
+
state = await this.usage.writeCursor(state, slot, current);
|
|
6652
|
+
}
|
|
6653
|
+
if (await cursorReplaced(handle, file, sourceRef, current)) {
|
|
6654
|
+
await this.usage.commitScanTransition(state, slot, current, initialCursor(sourceRef, file.device, file.inode), null, [unscopedGap("source_file_replaced")]);
|
|
6655
|
+
return true;
|
|
6656
|
+
}
|
|
6657
|
+
if (file.size > current.offset) return await this.captureFile(handle, registration, slot, sourceRef, current, file.size, state, "subagent");
|
|
6658
|
+
return false;
|
|
6659
|
+
} finally {
|
|
6660
|
+
await handle?.close();
|
|
6661
|
+
}
|
|
6662
|
+
}
|
|
6663
|
+
async captureFile(handle, registration, slot, sourceRef, before, size, state, kind = "main") {
|
|
6664
|
+
const chunk = await readHostUsageTranscriptChunk(handle, before.offset, size, before.skipping_oversized_line);
|
|
6665
|
+
if (chunk.end_offset === before.offset && chunk.lines.length === 0) return false;
|
|
6666
|
+
const processed = processClaudeChunk(chunk.lines, registration, sourceRef, kind, before, chunk.oversized_rows);
|
|
6667
|
+
const after = await updateAnchor(handle, { ...processed.cursor, offset: chunk.end_offset, skipping_oversized_line: chunk.skipping_oversized_line });
|
|
6668
|
+
const gaps = [...processed.gapCounts].map(([reason, omitted_count]) => ({ reason, source_file_ref: sourceRef, start_offset: before.offset, end_offset: chunk.end_offset, omitted_count }));
|
|
6669
|
+
const batch = processed.facts.length === 0 && gaps.length === 0 ? null : createCealHostUsageBatch({
|
|
6670
|
+
host_source_ref: registration.host_source_ref,
|
|
6671
|
+
host_session_ref: registration.host_session_ref,
|
|
6672
|
+
created_at: processed.createdAt,
|
|
6673
|
+
source_ranges: [{ source_file_ref: sourceRef, start_offset: before.offset, end_offset: chunk.end_offset }],
|
|
6674
|
+
facts: processed.facts,
|
|
6675
|
+
coverage_gaps: gaps
|
|
6676
|
+
});
|
|
6677
|
+
await this.usage.commitScanTransition(state, slot, before, after, batch);
|
|
6678
|
+
return true;
|
|
6679
|
+
}
|
|
6680
|
+
stamp() {
|
|
6681
|
+
const value = this.now();
|
|
6682
|
+
if (!Number.isFinite(value.getTime())) throw new Error("Claude usage facts clock is invalid.");
|
|
6683
|
+
return value.toISOString();
|
|
6684
|
+
}
|
|
6685
|
+
};
|
|
6686
|
+
function parseClaudeRow(line, registration, sourceRef, kind, hostTurnRef) {
|
|
6687
|
+
const value = parseRowRecord(line);
|
|
6688
|
+
const userTurn = kind === "main" ? mainUserTurn(value, registration.claude_session_id) : null;
|
|
6689
|
+
if (userTurn !== null) return { timestamp: timestamp3(userTurn.timestamp), turn_id: userTurn.turnId };
|
|
6690
|
+
if (!assistantRow(value)) return { timestamp: rowTimestamp(value) };
|
|
6691
|
+
return parseAssistantRow(value, registration, sourceRef, kind, hostTurnRef);
|
|
6692
|
+
}
|
|
6693
|
+
function mainUserTurn(value, sessionId) {
|
|
6694
|
+
return decodeClaudeHumanMessageRow(value, sessionId);
|
|
6695
|
+
}
|
|
6696
|
+
function parseRowRecord(line) {
|
|
6697
|
+
let value;
|
|
6698
|
+
try {
|
|
6699
|
+
value = JSON.parse(line);
|
|
6700
|
+
} catch {
|
|
6701
|
+
throw new Error("Claude transcript row is malformed.");
|
|
6702
|
+
}
|
|
6703
|
+
if (!isRecord6(value)) throw new Error("Claude transcript row is malformed.");
|
|
6704
|
+
return value;
|
|
6705
|
+
}
|
|
6706
|
+
function assistantRow(value) {
|
|
6707
|
+
return value.type === "assistant" && isRecord6(value.message);
|
|
6708
|
+
}
|
|
6709
|
+
function parseAssistantRow(value, registration, sourceRef, kind, hostTurnRef) {
|
|
6710
|
+
const message = value.message;
|
|
6711
|
+
const terminal = message.stop_reason === "end_turn";
|
|
6712
|
+
if (message.usage === void 0) return { timestamp: rowTimestamp(value), terminal };
|
|
6713
|
+
if (!isRecord6(message.usage)) return { timestamp: rowTimestamp(value), unsupported: true, terminal };
|
|
6714
|
+
const parsed = parseAssistantUsage(value, message, message.usage, registration, sourceRef, kind, hostTurnRef, terminal);
|
|
6715
|
+
return parsed;
|
|
6716
|
+
}
|
|
6717
|
+
function parseAssistantUsage(value, message, usage, registration, sourceRef, kind, hostTurnRef, terminal) {
|
|
6718
|
+
const observedAt = rowTimestamp(value);
|
|
6719
|
+
const values = assistantUsageValues(value, message, usage);
|
|
6720
|
+
if (values === null) return { timestamp: observedAt, unsupported: true, terminal };
|
|
6721
|
+
const { uuid, input, output, cached, cacheWrite, cacheCreation, reportedModel } = values;
|
|
6722
|
+
const normalizedInput = safeSum(input, cached, cacheWrite);
|
|
6723
|
+
if (normalizedInput === void 0) return { timestamp: observedAt, unsupported: true, terminal };
|
|
6724
|
+
const fact = createClaudeFact({ uuid, input, output, cached, cacheWrite, cacheCreation, normalizedInput, reportedModel, observedAt, registration, sourceRef, kind, hostTurnRef, terminal, stopReason: message.stop_reason });
|
|
6725
|
+
return { timestamp: observedAt, fact, terminal };
|
|
6726
|
+
}
|
|
6727
|
+
function assistantUsageValues(value, message, usage) {
|
|
6728
|
+
const uuid = boundedText2(value.uuid, 256);
|
|
6729
|
+
const input = safeCounter(usage.input_tokens);
|
|
6730
|
+
const output = safeCounter(usage.output_tokens);
|
|
6731
|
+
const cached = optionalCounter(usage, "cache_read_input_tokens");
|
|
6732
|
+
const cacheWrite = optionalCounter(usage, "cache_creation_input_tokens");
|
|
6733
|
+
const cacheCreation = cacheCreationUsage(usage.cache_creation);
|
|
6734
|
+
const reportedModel = message.model === void 0 || message.model === null ? null : boundedText2(message.model, 256);
|
|
6735
|
+
if (uuid === null || input === null || output === null || cached.invalid || cacheWrite.invalid || cacheCreation.invalid || invalidReportedModel(message.model, reportedModel)) return null;
|
|
6736
|
+
return { uuid, input, output, cached: cached.value, cacheWrite: cacheWrite.value, cacheCreation: cacheCreation.value, reportedModel };
|
|
6737
|
+
}
|
|
6738
|
+
function cacheCreationUsage(value) {
|
|
6739
|
+
if (value === void 0 || value === null) return { value: null, invalid: false };
|
|
6740
|
+
if (!isRecord6(value)) return { value: null, invalid: true };
|
|
6741
|
+
const oneHour = optionalCounter(value, "ephemeral_1h_input_tokens");
|
|
6742
|
+
const fiveMinutes = optionalCounter(value, "ephemeral_5m_input_tokens");
|
|
6743
|
+
return {
|
|
6744
|
+
value: { ephemeral_1h_input_tokens: oneHour.value, ephemeral_5m_input_tokens: fiveMinutes.value },
|
|
6745
|
+
invalid: oneHour.invalid || fiveMinutes.invalid
|
|
6746
|
+
};
|
|
6747
|
+
}
|
|
6748
|
+
function invalidReportedModel(model, reportedModel) {
|
|
6749
|
+
return model !== void 0 && model !== null && reportedModel === null;
|
|
6750
|
+
}
|
|
6751
|
+
function safeSum(input, cached, cacheWrite) {
|
|
6752
|
+
if (cached === null || cacheWrite === null) return null;
|
|
6753
|
+
const total = input + cached + cacheWrite;
|
|
6754
|
+
return Number.isSafeInteger(total) ? total : void 0;
|
|
6755
|
+
}
|
|
6756
|
+
function createClaudeFact({ uuid, input, output, cached, cacheWrite, cacheCreation, normalizedInput, reportedModel, observedAt, registration, sourceRef, kind, hostTurnRef, terminal, stopReason }) {
|
|
6757
|
+
const sourceUsage = { input_tokens: input, cache_read_input_tokens: cached, cache_creation_input_tokens: cacheWrite, cache_creation: cacheCreation, output_tokens: output };
|
|
6758
|
+
const sourceEventRef = hostUsageSourceEventReference(sourceRef, `claude:${uuid}:${sha2563(JSON.stringify(sourceUsage))}`);
|
|
6759
|
+
const normalizedTotal = normalizedInput === null ? null : safeOutputTotal(normalizedInput, output);
|
|
6760
|
+
return {
|
|
6761
|
+
fact_ref: hostUsageFactReference(sourceRef, sourceEventRef),
|
|
6762
|
+
host_session_ref: registration.host_session_ref,
|
|
6763
|
+
host_turn_ref: kind === "main" ? hostTurnRef : null,
|
|
6764
|
+
source_file_ref: sourceRef,
|
|
6765
|
+
source_event_ref: sourceEventRef,
|
|
6766
|
+
source_event_uuid: uuid,
|
|
6767
|
+
source_file_kind: kind,
|
|
6768
|
+
observed_at: observedAt,
|
|
6769
|
+
producer: "claude_transcript",
|
|
6770
|
+
requested_model: null,
|
|
6771
|
+
reported_model: reportedModel,
|
|
6772
|
+
source_usage: sourceUsage,
|
|
6773
|
+
normalized_usage: { input: normalizedInput, output, total: normalizedTotal, cached_input: cached, cache_write_input: cacheWrite, reasoning_output: null },
|
|
6774
|
+
counter_semantics: "assistant_message",
|
|
6775
|
+
finality: finality(terminal, stopReason),
|
|
6776
|
+
child_inclusion: "unknown",
|
|
6777
|
+
correction_semantics: "unknown"
|
|
6778
|
+
};
|
|
6779
|
+
}
|
|
6780
|
+
function safeOutputTotal(input, output) {
|
|
6781
|
+
const total = input + output;
|
|
6782
|
+
return Number.isSafeInteger(total) ? total : null;
|
|
6783
|
+
}
|
|
6784
|
+
function finality(terminal, stopReason) {
|
|
6785
|
+
return terminal ? "terminal" : stopReason === null || stopReason === void 0 ? "nonterminal" : "unknown";
|
|
6786
|
+
}
|
|
6787
|
+
function processClaudeChunk(lines, registration, sourceRef, kind, initial, oversizedRows) {
|
|
6788
|
+
let cursor = initial;
|
|
6789
|
+
let createdAt = registration.registered_at;
|
|
6790
|
+
const facts = [];
|
|
6791
|
+
const gapCounts = /* @__PURE__ */ new Map();
|
|
6792
|
+
if (oversizedRows > 0) gapCounts.set("unsupported_source_shape", oversizedRows);
|
|
6793
|
+
for (const line of lines) {
|
|
6794
|
+
let parsed;
|
|
6795
|
+
try {
|
|
6796
|
+
parsed = parseClaudeRow(line.toString("utf8"), registration, sourceRef, kind, cursor.host_turn_ref);
|
|
6797
|
+
} catch {
|
|
6798
|
+
addUnsupportedGap(gapCounts);
|
|
6799
|
+
continue;
|
|
6800
|
+
}
|
|
6801
|
+
createdAt = parsed.timestamp;
|
|
6802
|
+
if (parsed.unsupported === true) addUnsupportedGap(gapCounts);
|
|
6803
|
+
if (parsed.fact !== void 0) facts.push(parsed.fact);
|
|
6804
|
+
cursor = updateClaudeTurnCursor(cursor, parsed, registration, kind);
|
|
6805
|
+
}
|
|
6806
|
+
return { cursor, facts, gapCounts, createdAt };
|
|
6807
|
+
}
|
|
6808
|
+
function addUnsupportedGap(gapCounts) {
|
|
6809
|
+
gapCounts.set("unsupported_source_shape", (gapCounts.get("unsupported_source_shape") ?? 0) + 1);
|
|
6810
|
+
}
|
|
6811
|
+
function updateClaudeTurnCursor(cursor, row, registration, kind) {
|
|
6812
|
+
if (kind !== "main") return cursor;
|
|
6813
|
+
if (row.turn_id !== void 0) return { ...cursor, native_turn_id: row.turn_id, host_turn_ref: claudeLocalTurnRef(registration.claude_session_id, row.turn_id) };
|
|
6814
|
+
return row.terminal === true ? { ...cursor, native_turn_id: null, host_turn_ref: null } : cursor;
|
|
6815
|
+
}
|
|
6816
|
+
async function readSubagentNames(registration) {
|
|
6817
|
+
try {
|
|
6818
|
+
return (await readHostUsageTranscriptSource(() => readdir3(subagentsDirectory(registration.transcript_path)))).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
|
|
6819
|
+
} catch (error) {
|
|
6820
|
+
const cause = error instanceof HostUsageTranscriptSourceError ? error.cause : error;
|
|
6821
|
+
if (errorCode5(cause) === "ENOENT" || errorCode5(cause) === "ENOTDIR") return [];
|
|
6822
|
+
throw error;
|
|
6823
|
+
}
|
|
6824
|
+
}
|
|
6825
|
+
function initialCursor(sourceFileRef2, device, inode) {
|
|
6826
|
+
return { source_file_ref: sourceFileRef2, device, inode, offset: 0, anchor_start: 0, anchor_sha256: sha2563(""), last_ordinal: null, host_turn_ref: null, native_turn_id: null, requested_model: null, codex_total_usage: null, skipping_oversized_line: false };
|
|
6827
|
+
}
|
|
6828
|
+
function sourceFileRef(registration, device, inode) {
|
|
6829
|
+
return hostUsageSourceFileReference("claude_transcript", registration.host_source_ref, registration.host_session_ref, device, inode);
|
|
6830
|
+
}
|
|
6831
|
+
function subagentSlot(name) {
|
|
6832
|
+
return `subagent:${sha2563(name)}`;
|
|
6833
|
+
}
|
|
6834
|
+
function unscopedGap(reason) {
|
|
6835
|
+
return { reason, source_file_ref: null, start_offset: null, end_offset: null, omitted_count: null };
|
|
6836
|
+
}
|
|
6837
|
+
async function anchorMatches(handle, cursor) {
|
|
6838
|
+
const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
|
|
6839
|
+
if (bytes.length === 0) return sha2563("") === cursor.anchor_sha256;
|
|
6840
|
+
const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, cursor.anchor_start));
|
|
6841
|
+
return bytesRead === bytes.length && sha2563(bytes) === cursor.anchor_sha256;
|
|
6842
|
+
}
|
|
6843
|
+
async function cursorReplaced(handle, file, sourceRef, cursor) {
|
|
6844
|
+
return cursor.source_file_ref !== sourceRef || cursor.device !== file.device || cursor.inode !== file.inode || file.size < cursor.offset || !await anchorMatches(handle, cursor);
|
|
6845
|
+
}
|
|
6846
|
+
async function updateAnchor(handle, cursor) {
|
|
6847
|
+
const anchor_start = Math.max(0, cursor.offset - CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
|
|
6848
|
+
const anchor = Buffer.alloc(cursor.offset - anchor_start);
|
|
6849
|
+
if (anchor.length > 0) {
|
|
6850
|
+
const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(anchor, 0, anchor.length, anchor_start));
|
|
6851
|
+
if (bytesRead !== anchor.length) throw new Error("Claude usage facts source changed during anchor read.");
|
|
6852
|
+
}
|
|
6853
|
+
return { ...cursor, anchor_start, anchor_sha256: sha2563(anchor) };
|
|
6854
|
+
}
|
|
6855
|
+
function rowTimestamp(value) {
|
|
6856
|
+
return timestamp3(value.timestamp);
|
|
6857
|
+
}
|
|
6858
|
+
function timestamp3(value) {
|
|
6859
|
+
if (!safeTimestamp(value)) throw new Error("Claude transcript timestamp is malformed.");
|
|
6860
|
+
return value;
|
|
6861
|
+
}
|
|
6862
|
+
function safeTimestamp(value) {
|
|
6863
|
+
return typeof value === "string" && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
6864
|
+
}
|
|
6865
|
+
function boundedText2(value, maximum) {
|
|
6866
|
+
return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters2(value) ? value : null;
|
|
6867
|
+
}
|
|
6868
|
+
function hasControlCharacters2(value) {
|
|
6869
|
+
for (const character of value) {
|
|
6870
|
+
const code2 = character.codePointAt(0);
|
|
6871
|
+
if (code2 !== void 0 && (code2 < 32 || code2 === 127)) return true;
|
|
6872
|
+
}
|
|
6873
|
+
return false;
|
|
6874
|
+
}
|
|
6875
|
+
function safeCounter(value) {
|
|
6876
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
6877
|
+
}
|
|
6878
|
+
function optionalCounter(value, key) {
|
|
6879
|
+
if (!Object.hasOwn(value, key) || value[key] === null) return { value: null, invalid: false };
|
|
6880
|
+
const count = safeCounter(value[key]);
|
|
6881
|
+
return { value: count, invalid: count === null };
|
|
6882
|
+
}
|
|
6883
|
+
function isRecord6(value) {
|
|
6884
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
6885
|
+
}
|
|
6886
|
+
function errorCode5(error) {
|
|
6887
|
+
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
6888
|
+
}
|
|
6889
|
+
function sha2563(value) {
|
|
6890
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
6891
|
+
}
|
|
6892
|
+
|
|
4877
6893
|
// host/claude/src/claude-producer-service.ts
|
|
4878
6894
|
var CLAUDE_PRODUCER_CONFIG_SCHEMA = "ceal.claude_producer_config.v1";
|
|
4879
6895
|
var CLAUDE_TRANSCRIPTS_ROOT = "claude_transcripts_root";
|
|
@@ -4882,23 +6898,25 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
|
|
|
4882
6898
|
producer_id: "claude",
|
|
4883
6899
|
extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
|
|
4884
6900
|
config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
|
|
4885
|
-
runtime_options: (config) => Object.freeze({
|
|
4886
|
-
|
|
4887
|
-
|
|
4888
|
-
|
|
6901
|
+
runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
|
|
6902
|
+
drain: drainClaudeProducerOnce,
|
|
6903
|
+
background: (config, signal) => {
|
|
6904
|
+
const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
|
|
6905
|
+
return runHostUsageFactsUploader({ producer: "claude", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext() }, signal);
|
|
6906
|
+
}
|
|
4889
6907
|
};
|
|
4890
6908
|
|
|
4891
6909
|
// host/claude/src/claude-visible-output-budget.ts
|
|
4892
6910
|
import { readFile as readFile2 } from "node:fs/promises";
|
|
4893
6911
|
import { homedir } from "node:os";
|
|
4894
|
-
import { join as
|
|
6912
|
+
import { join as join9 } from "node:path";
|
|
4895
6913
|
|
|
4896
6914
|
// host/claude/src/claude-runtime-paths.ts
|
|
4897
|
-
import { join as
|
|
6915
|
+
import { join as join8 } from "node:path";
|
|
4898
6916
|
var CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT = "CLAUDE_CONFIG_DIR";
|
|
4899
6917
|
var CLAUDE_HOME_DEFAULT_DIRECTORY = ".claude";
|
|
4900
6918
|
function resolveClaudeConfigHome(environment, home) {
|
|
4901
|
-
return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] ||
|
|
6919
|
+
return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join8(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
|
|
4902
6920
|
}
|
|
4903
6921
|
|
|
4904
6922
|
// host/claude/src/claude-visible-output-budget.ts
|
|
@@ -4912,16 +6930,16 @@ async function resolveClaudeVisibleOutputMaxBytes(environment = process.env, wor
|
|
|
4912
6930
|
}
|
|
4913
6931
|
async function projectOrUserInlineLimit(environment, workingDirectory) {
|
|
4914
6932
|
const configHome = resolveClaudeConfigHome(environment, homedir());
|
|
4915
|
-
const userLimit = await settingsInlineLimit(
|
|
4916
|
-
const projectLimit = await settingsInlineLimit(
|
|
4917
|
-
const localLimit = await settingsInlineLimit(
|
|
6933
|
+
const userLimit = await settingsInlineLimit(join9(configHome, "settings.json"));
|
|
6934
|
+
const projectLimit = await settingsInlineLimit(join9(workingDirectory, ".claude", "settings.json"));
|
|
6935
|
+
const localLimit = await settingsInlineLimit(join9(workingDirectory, ".claude", "settings.local.json"));
|
|
4918
6936
|
const candidate = localLimit ?? projectLimit ?? userLimit;
|
|
4919
6937
|
return candidate === void 0 ? void 0 : Math.min(candidate, CLAUDE_MAX_INLINE_OUTPUT_MAX_CHARS);
|
|
4920
6938
|
}
|
|
4921
6939
|
async function settingsInlineLimit(path) {
|
|
4922
6940
|
try {
|
|
4923
6941
|
const parsed = JSON.parse(await readFile2(path, "utf8"));
|
|
4924
|
-
if (!
|
|
6942
|
+
if (!isRecord7(parsed)) return void 0;
|
|
4925
6943
|
return positiveInteger(parsed.bashOutputMaxChars);
|
|
4926
6944
|
} catch {
|
|
4927
6945
|
return void 0;
|
|
@@ -4932,7 +6950,7 @@ function positiveInteger(value) {
|
|
|
4932
6950
|
const parsed = typeof normalized === "string" && normalized.length > 0 ? Number(normalized) : normalized;
|
|
4933
6951
|
return typeof parsed === "number" && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : void 0;
|
|
4934
6952
|
}
|
|
4935
|
-
function
|
|
6953
|
+
function isRecord7(value) {
|
|
4936
6954
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4937
6955
|
}
|
|
4938
6956
|
|
|
@@ -4941,6 +6959,7 @@ var CLAUDE_INVOCATION_AUTHENTICATION_DESCRIPTOR = {
|
|
|
4941
6959
|
producer_id: "claude",
|
|
4942
6960
|
context_activation_wait_max_ms: CLAUDE_CONTEXT_ACTIVATION_WAIT_MAX_MS,
|
|
4943
6961
|
create_store: (directory) => new ClaudeOutboxStore(directory),
|
|
6962
|
+
can_wait_for_context_activation: async ({ store, identity }) => await store.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref) !== null,
|
|
4944
6963
|
session_id_env: CLAUDE_SESSION_ID_ENVIRONMENT,
|
|
4945
6964
|
session_ref: (_hostSourceRef, sessionId) => claudeLocalSessionRef(sessionId),
|
|
4946
6965
|
config_flag: HOST_PRODUCER_CONFIG_FLAG,
|
|
@@ -4953,7 +6972,7 @@ function runClaudeInvocationAuthenticationCommand(args, options) {
|
|
|
4953
6972
|
return runHostInvocationAuthenticationCommand(CLAUDE_INVOCATION_AUTHENTICATION_DESCRIPTOR, args, options);
|
|
4954
6973
|
}
|
|
4955
6974
|
async function readClaudeInvocationHumanMessageWindow(input) {
|
|
4956
|
-
return readRegisteredHostInvocationHumanMessageWindow(() => input.store.listTranscriptRegistrations(), input.identity, (line, registration) => {
|
|
6975
|
+
return readRegisteredHostInvocationHumanMessageWindow(() => input.store.listTranscriptRegistrations(), (registration) => input.store.readTranscriptCursor(registration), input.identity, (line, registration) => {
|
|
4957
6976
|
let row;
|
|
4958
6977
|
try {
|
|
4959
6978
|
row = JSON.parse(line);
|
|
@@ -4970,41 +6989,79 @@ async function readClaudeInvocationHumanMessageWindow(input) {
|
|
|
4970
6989
|
}
|
|
4971
6990
|
|
|
4972
6991
|
// host/client-doctor.ts
|
|
4973
|
-
import { createHash as
|
|
6992
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
4974
6993
|
import { execFile as execFile2 } from "node:child_process";
|
|
4975
|
-
import { access, open as
|
|
4976
|
-
import { delimiter, isAbsolute as
|
|
6994
|
+
import { access, open as open4, readFile as readFile3, realpath, stat as stat2 } from "node:fs/promises";
|
|
6995
|
+
import { delimiter, extname, isAbsolute as isAbsolute4, join as join10 } from "node:path";
|
|
4977
6996
|
import { promisify } from "node:util";
|
|
4978
6997
|
|
|
6998
|
+
// host/environment.ts
|
|
6999
|
+
function environmentValue(environment, name, platform) {
|
|
7000
|
+
const keys = Object.keys(environment);
|
|
7001
|
+
if (platform === "win32") keys.sort();
|
|
7002
|
+
const selected = keys.find((key) => environment[key] !== void 0 && (platform === "win32" ? key.toUpperCase() === name.toUpperCase() : key === name));
|
|
7003
|
+
return selected === void 0 ? void 0 : environment[selected];
|
|
7004
|
+
}
|
|
7005
|
+
|
|
4979
7006
|
// host/command-vector.ts
|
|
4980
7007
|
import { win32 as win326 } from "node:path";
|
|
7008
|
+
var HOST_COMMAND_ARGUMENT_MAX = 64;
|
|
4981
7009
|
var MAX_COMMAND_BYTES = 4096;
|
|
7010
|
+
var WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET = "A-Za-z0-9._=-";
|
|
7011
|
+
var WINDOWS_FIXED_CMD_ARGUMENT_REFUSAL_PATTERN = `[^${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]`;
|
|
7012
|
+
var WINDOWS_FIXED_CMD_ARGUMENT = new RegExp(`^[${WINDOWS_FIXED_CMD_ARGUMENT_ALPHABET}]+$`, "u");
|
|
7013
|
+
function validateHostCommandVector(vector, windowsConsumer = "cmd") {
|
|
7014
|
+
if (typeof vector.executable !== "string" || invalidText(vector.executable)) throw new TypeError(`Host command vector executable is invalid (${refusalFact("executable_kind", typeof vector.executable, "non-empty text without a NUL, newline or control character")}).`);
|
|
7015
|
+
if (vector.args.length > HOST_COMMAND_ARGUMENT_MAX) throw new TypeError(`Host command vector has too many arguments (${refusalFact("argument_count", vector.args.length, `at most ${HOST_COMMAND_ARGUMENT_MAX}`)}).`);
|
|
7016
|
+
const offending = vector.args.findIndex((argument) => typeof argument !== "string" || invalidText(argument));
|
|
7017
|
+
if (offending >= 0) throw new TypeError(`Host command vector argument is invalid (${refusalFact("argument_index", offending, "no argument with a NUL, newline or control character")}).`);
|
|
7018
|
+
formatHostCommand(vector, "posix");
|
|
7019
|
+
formatWindowsCommand(vector, windowsConsumer);
|
|
7020
|
+
}
|
|
4982
7021
|
function formatHostCommand(vector, platform) {
|
|
4983
7022
|
return formatWith(vector, platform === "windows" ? quoteWindowsArgument : quotePosixArgument);
|
|
4984
7023
|
}
|
|
4985
|
-
function hostScriptLauncherInvocation(launcherPath, args, platform = process.platform, environment = process.env) {
|
|
4986
|
-
if (
|
|
4987
|
-
if (platform === "win32" &&
|
|
4988
|
-
|
|
4989
|
-
executable: environment.ComSpec ?? "cmd.exe",
|
|
4990
|
-
args: ["/d", "/s", "/c", `call ${formatHostCommand({ executable: launcherPath, args }, "windows")}`],
|
|
4991
|
-
windowsVerbatimArguments: true
|
|
4992
|
-
};
|
|
4993
|
-
}
|
|
4994
|
-
if (platform === "win32" && /\.ps1$/iu.test(launcherPath)) {
|
|
7024
|
+
function hostScriptLauncherInvocation(launcherPath, args, kind, platform = process.platform, environment = process.env) {
|
|
7025
|
+
if (kind === "node") return { executable: process.execPath, args: [launcherPath, ...args] };
|
|
7026
|
+
if (platform === "win32" && kind === "cmd") return windowsCmdLauncherInvocation(launcherPath, args, environment);
|
|
7027
|
+
if (platform === "win32" && kind === "powershell") {
|
|
4995
7028
|
return {
|
|
4996
|
-
executable: win326.join(environment
|
|
4997
|
-
args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-File", launcherPath, ...args]
|
|
7029
|
+
executable: win326.join(environmentValue(environment, "SystemRoot", platform) ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
|
|
7030
|
+
args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", launcherPath, ...args]
|
|
4998
7031
|
};
|
|
4999
7032
|
}
|
|
5000
7033
|
return { executable: launcherPath, args };
|
|
5001
7034
|
}
|
|
7035
|
+
function windowsCmdLauncherInvocation(launcherPath, args, environment) {
|
|
7036
|
+
validateWindowsCmdScriptVector(launcherPath, args, "direct-exec");
|
|
7037
|
+
const variable = "CEAL_HOST_SCRIPT_LAUNCHER_PATH";
|
|
7038
|
+
const command = `"%${variable}%" ${args.map(quoteWindowsArgument).join(" ")}`.trimEnd();
|
|
7039
|
+
return { ...windowsCmdInvocation(environment, `"${command}"`), environment: { [variable]: launcherPath }, windowsVerbatimArguments: true };
|
|
7040
|
+
}
|
|
7041
|
+
function validateWindowsCmdScriptVector(launcherPath, args, consumer) {
|
|
7042
|
+
if (invalidText(launcherPath) || launcherPath.includes('"')) throw new TypeError("Host script launcher path is invalid.");
|
|
7043
|
+
validateHostCommandVector({ executable: launcherPath, args }, consumer);
|
|
7044
|
+
}
|
|
7045
|
+
function windowsCmdInvocation(environment, command) {
|
|
7046
|
+
return { executable: windowsAmbientCommandProcessor(environment), args: ["/d", "/v:off", "/s", "/c", command] };
|
|
7047
|
+
}
|
|
7048
|
+
function windowsAmbientCommandProcessor(environment) {
|
|
7049
|
+
return environmentValue(environment, "ComSpec", "win32") ?? "cmd.exe";
|
|
7050
|
+
}
|
|
7051
|
+
function formatWindowsCommand(vector, windowsConsumer) {
|
|
7052
|
+
return formatWith(vector, windowsConsumer === "cmd" ? quoteWindowsArgument : quoteWindowsExecArgument);
|
|
7053
|
+
}
|
|
5002
7054
|
function formatWith(vector, quote) {
|
|
5003
|
-
|
|
7055
|
+
return boundedHostCommand([vector.executable, ...vector.args].map(quote).join(" "));
|
|
7056
|
+
}
|
|
7057
|
+
function boundedHostCommand(command) {
|
|
5004
7058
|
const commandBytes = Buffer.byteLength(command, "utf8");
|
|
5005
7059
|
if (commandBytes > MAX_COMMAND_BYTES) throw new TypeError(`Host command vector is too large (${refusalFact("bytes", commandBytes, `at most ${MAX_COMMAND_BYTES} UTF-8 bytes`)}).`);
|
|
5006
7060
|
return command;
|
|
5007
7061
|
}
|
|
7062
|
+
function invalidText(value) {
|
|
7063
|
+
return value.includes("\0") || value.includes("\n") || value.includes("\r");
|
|
7064
|
+
}
|
|
5008
7065
|
function quotePosixArgument(value) {
|
|
5009
7066
|
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
5010
7067
|
}
|
|
@@ -5084,59 +7141,73 @@ async function inspectCanonicalContext(options, executable, environment, run, co
|
|
|
5084
7141
|
function inspectedFailure(code2, message, nextAction) {
|
|
5085
7142
|
return { ok: false, failure: failure(code2, message, nextAction) };
|
|
5086
7143
|
}
|
|
5087
|
-
function canonicalClientEnvironment(input) {
|
|
7144
|
+
function canonicalClientEnvironment(input, platform = process.platform) {
|
|
5088
7145
|
const environment = { ...input };
|
|
5089
|
-
|
|
7146
|
+
const overrides = new Set(CEAL_ENVIRONMENT_OVERRIDES.map((name) => platform === "win32" ? name.toUpperCase() : name));
|
|
7147
|
+
for (const name of Object.keys(environment)) {
|
|
7148
|
+
if (overrides.has(platform === "win32" ? name.toUpperCase() : name)) delete environment[name];
|
|
7149
|
+
}
|
|
5090
7150
|
return environment;
|
|
5091
7151
|
}
|
|
5092
|
-
async function resolveCealExecutable(command, environment) {
|
|
5093
|
-
const candidates =
|
|
7152
|
+
async function resolveCealExecutable(command, environment, platform = process.platform) {
|
|
7153
|
+
const candidates = executableCandidates(command, environment, platform);
|
|
5094
7154
|
for (const candidate of candidates) {
|
|
5095
7155
|
try {
|
|
5096
7156
|
await access(candidate);
|
|
5097
7157
|
const path = await realpath(candidate);
|
|
5098
7158
|
const metadata = await stat2(path);
|
|
5099
7159
|
if (!metadata.isFile()) continue;
|
|
5100
|
-
|
|
5101
|
-
|
|
7160
|
+
const launcherKind = await inspectLauncherKind(path);
|
|
7161
|
+
if (launcherKind !== void 0) return resolveLauncherBinary(path, launcherKind, environment, platform);
|
|
7162
|
+
if (platform === "win32" && !isAbsolute4(command) && extname(path) === "") continue;
|
|
7163
|
+
return { path, sha256: createHash9("sha256").update(await readFile3(path)).digest("hex") };
|
|
5102
7164
|
} catch {
|
|
5103
7165
|
}
|
|
5104
7166
|
}
|
|
5105
7167
|
throw new Error("ceal executable unavailable");
|
|
5106
7168
|
}
|
|
5107
|
-
async function
|
|
5108
|
-
if (/\.(?:
|
|
5109
|
-
|
|
7169
|
+
async function inspectLauncherKind(path) {
|
|
7170
|
+
if (/\.(?:cjs|js|mjs)$/iu.test(path)) return "node";
|
|
7171
|
+
if (/\.(?:bat|cmd)$/iu.test(path)) return "cmd";
|
|
7172
|
+
if (/\.ps1$/iu.test(path)) return "powershell";
|
|
7173
|
+
const handle = await open4(path, "r");
|
|
5110
7174
|
try {
|
|
5111
7175
|
const buffer = Buffer.alloc(128);
|
|
5112
7176
|
const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, 0);
|
|
5113
7177
|
const prefix = buffer.subarray(0, bytesRead).toString("utf8");
|
|
5114
|
-
return prefix.startsWith("#!") && /\bnode\b/u.test(prefix.split("\n", 1)[0] ?? "");
|
|
7178
|
+
return prefix.startsWith("#!") && /\bnode\b/u.test(prefix.split("\n", 1)[0] ?? "") ? "node" : void 0;
|
|
5115
7179
|
} finally {
|
|
5116
7180
|
await handle.close();
|
|
5117
7181
|
}
|
|
5118
7182
|
}
|
|
5119
|
-
async function resolveLauncherBinary(launcherPath, environment) {
|
|
5120
|
-
const invocation = hostScriptLauncherInvocation(launcherPath, CEAL_CLIENT_DOCTOR_COMMAND,
|
|
5121
|
-
const result = await execFileAsync(invocation.executable, [...invocation.args], { env: environment, timeout: 15e3, encoding: "utf8", windowsHide: false, ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
|
|
7183
|
+
async function resolveLauncherBinary(launcherPath, kind, environment, platform) {
|
|
7184
|
+
const invocation = hostScriptLauncherInvocation(launcherPath, CEAL_CLIENT_DOCTOR_COMMAND, kind, platform, environment);
|
|
7185
|
+
const result = await execFileAsync(invocation.executable, [...invocation.args], { env: { ...environment, ...invocation.environment }, timeout: 15e3, encoding: "utf8", windowsHide: false, ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
|
|
5122
7186
|
let parsed;
|
|
5123
7187
|
try {
|
|
5124
7188
|
parsed = JSON.parse(result.stdout);
|
|
5125
7189
|
} catch {
|
|
5126
7190
|
throw new Error("launcher doctor returned unreadable output");
|
|
5127
7191
|
}
|
|
5128
|
-
if (!
|
|
7192
|
+
if (!isRecord8(parsed) || parsed.schema_version !== CEAL_CLIENT_DOCTOR_SCHEMA_VERSION || parsed.ok !== true || typeof parsed.binary_path !== "string" || parsed.binary_path.length === 0) throw new Error("launcher doctor did not report a binary path");
|
|
5129
7193
|
const binaryPath = await realpath(parsed.binary_path);
|
|
5130
7194
|
const metadata = await stat2(binaryPath);
|
|
5131
7195
|
if (!metadata.isFile()) throw new Error("launcher doctor reported a non-file binary path");
|
|
5132
|
-
return { path: binaryPath, sha256:
|
|
7196
|
+
return { path: binaryPath, sha256: createHash9("sha256").update(await readFile3(binaryPath)).digest("hex") };
|
|
7197
|
+
}
|
|
7198
|
+
function executableCandidates(command, environment, platform) {
|
|
7199
|
+
if (isAbsolute4(command)) return [command];
|
|
7200
|
+
const pathValue = environmentValue(environment, "PATH", platform) ?? "";
|
|
7201
|
+
const directories = pathValue.split(delimiter).filter((entry) => entry.length > 0);
|
|
7202
|
+
if (platform !== "win32" || extname(command) !== "") return directories.map((entry) => join10(entry, command));
|
|
7203
|
+
return directories.flatMap((entry) => [".exe", ".ps1", ".cmd", ".bat", ""].map((suffix) => join10(entry, `${command}${suffix}`)));
|
|
5133
7204
|
}
|
|
5134
7205
|
async function executeCealCommand(executable, args, environment) {
|
|
5135
7206
|
try {
|
|
5136
7207
|
const result = await execFileAsync(executable, [...args], { env: environment, timeout: 15e3, encoding: "utf8" });
|
|
5137
7208
|
return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
|
|
5138
7209
|
} catch (error) {
|
|
5139
|
-
if (
|
|
7210
|
+
if (isRecord8(error)) return { exit_code: typeof error.code === "number" ? error.code : 1, stdout: typeof error.stdout === "string" ? error.stdout : "", stderr: typeof error.stderr === "string" ? error.stderr : "" };
|
|
5140
7211
|
throw error;
|
|
5141
7212
|
}
|
|
5142
7213
|
}
|
|
@@ -5147,19 +7218,19 @@ function commandDocument(result) {
|
|
|
5147
7218
|
if (result === null) return null;
|
|
5148
7219
|
try {
|
|
5149
7220
|
const value = JSON.parse(result.stdout);
|
|
5150
|
-
return
|
|
7221
|
+
return isRecord8(value) ? value : null;
|
|
5151
7222
|
} catch {
|
|
5152
7223
|
return null;
|
|
5153
7224
|
}
|
|
5154
7225
|
}
|
|
5155
7226
|
function selectedContext(value) {
|
|
5156
7227
|
if (value?.schema_version !== "ceal.access-group.v1" || value.ok !== true || !Array.isArray(value.contexts)) return null;
|
|
5157
|
-
const selected = value.contexts.filter((item) =>
|
|
7228
|
+
const selected = value.contexts.filter((item) => isRecord8(item) && item.selected === true);
|
|
5158
7229
|
if (selected.length !== 1) return null;
|
|
5159
7230
|
return selectedContextRecord(selected[0]);
|
|
5160
7231
|
}
|
|
5161
7232
|
function selectedContextRecord(item) {
|
|
5162
|
-
if (!
|
|
7233
|
+
if (!isRecord8(item) || typeof item.name !== "string" || typeof item.instance_ref !== "string") return null;
|
|
5163
7234
|
if (!SAFE_REF4.test(item.instance_ref)) return null;
|
|
5164
7235
|
return { name: item.name, instance_ref: item.instance_ref };
|
|
5165
7236
|
}
|
|
@@ -5174,7 +7245,7 @@ function validExpectations(options) {
|
|
|
5174
7245
|
function failure(code2, message, next_action) {
|
|
5175
7246
|
return { ok: false, status: "failure", error: { code: code2, message, next_action } };
|
|
5176
7247
|
}
|
|
5177
|
-
function
|
|
7248
|
+
function isRecord8(value) {
|
|
5178
7249
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
5179
7250
|
}
|
|
5180
7251
|
|