@corca-org/ceal-host-win32-x64 1.0.21 → 1.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ceal-host.exe +0 -0
- package/libexec/ceal-host/ceal-host-background.exe +0 -0
- package/libexec/ceal-host/claude-hook.mjs +2508 -483
- package/libexec/ceal-host/claude-invocation-authentication.mjs +2775 -634
- package/libexec/ceal-host/claude-producer.mjs +2510 -487
- package/libexec/ceal-host/codex-hook.mjs +2533 -530
- package/libexec/ceal-host/codex-invocation-authentication.mjs +3099 -954
- package/libexec/ceal-host/codex-producer.mjs +2450 -448
- package/libexec/ceal-host/control.mjs +5867 -2751
- package/libexec/ceal-host/relay.mjs +899 -420
- package/package.json +1 -1
- package/share/ceal-host/bundle-manifest.json +22 -12
- package/share/ceal-host/bundle-manifest.sigstore.json +1 -1
|
@@ -16,21 +16,36 @@ function isAbsoluteNormalizedNonRootPath(value, flavor = process.platform, allow
|
|
|
16
16
|
return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && pathApi.isAbsolute(value) && pathApi.normalize(value) === value && (allowRoot || pathApi.parse(value).root !== value);
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
// host/unix-socket-path.ts
|
|
20
|
+
var PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES = 103;
|
|
21
|
+
|
|
19
22
|
// host/runtime-source-paths.ts
|
|
20
23
|
var HOST_SOURCE_ID = /^host-source:([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$/u;
|
|
21
24
|
function hostSourceUuid(sourceRef) {
|
|
22
25
|
return HOST_SOURCE_ID.exec(sourceRef)?.[1] ?? null;
|
|
23
26
|
}
|
|
24
|
-
|
|
27
|
+
var DARWIN_UID_MAX = 4294967295;
|
|
28
|
+
var MACOS_HOST_RELAY_IPC_ROOT_PREFIX = "/private/tmp/ceal-host-";
|
|
29
|
+
function macosHostRelayIpcDirectory(uid = process.geteuid?.() ?? -1) {
|
|
30
|
+
if (!Number.isInteger(uid) || uid < 0 || uid > DARWIN_UID_MAX) throw new TypeError("Host runtime effective user identity is invalid.");
|
|
31
|
+
return `${MACOS_HOST_RELAY_IPC_ROOT_PREFIX}${uid}`;
|
|
32
|
+
}
|
|
33
|
+
function hostRuntimeSourcePaths(stateRoot, sourceRef, platform = process.platform, uid = process.geteuid?.() ?? -1) {
|
|
25
34
|
const sourceId = hostSourceUuid(sourceRef);
|
|
26
35
|
if (!isAbsoluteNormalizedNonRootPath(stateRoot, platform) || sourceId === null) throw new TypeError("Host runtime source identity is invalid.");
|
|
27
36
|
const path = platform === "win32" ? win322 : posix2;
|
|
28
37
|
const sourcesRoot = path.join(stateRoot, "sources");
|
|
29
38
|
const sourceRoot = path.join(sourcesRoot, sourceId);
|
|
30
39
|
const runtimeRoot = path.join(stateRoot, "run");
|
|
31
|
-
const
|
|
40
|
+
const rootedEndpoint = path.join(runtimeRoot, `${sourceId}.sock`);
|
|
41
|
+
const endpoint = projectRelayEndpoint(stateRoot, sourceRef, rootedEndpoint, platform, uid);
|
|
32
42
|
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 };
|
|
33
43
|
}
|
|
44
|
+
function projectRelayEndpoint(stateRoot, sourceRef, rooted, platform, uid) {
|
|
45
|
+
if (platform !== "win32" && (platform !== "darwin" || Buffer.byteLength(rooted, "utf8") <= PORTABLE_UNIX_SOCKET_PATH_MAX_BYTES)) return rooted;
|
|
46
|
+
const digest2 = createHash("sha256").update(`${stateRoot}\0${sourceRef}`).digest("hex");
|
|
47
|
+
return platform === "win32" ? `\\\\.\\pipe\\ceal-host-${digest2.slice(0, 24)}` : posix2.join(macosHostRelayIpcDirectory(uid), `${digest2}.sock`);
|
|
48
|
+
}
|
|
34
49
|
function assertHostProducerSourcePaths(stateRoot, config, producer, platform = process.platform) {
|
|
35
50
|
const paths = hostRuntimeSourcePaths(stateRoot, config.host_source_ref, platform);
|
|
36
51
|
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.");
|
|
@@ -41,6 +56,15 @@ function assertHostProducerSourcePaths(stateRoot, config, producer, platform = p
|
|
|
41
56
|
import { constants as constants2 } from "node:fs";
|
|
42
57
|
import { lstat as lstat2 } from "node:fs/promises";
|
|
43
58
|
|
|
59
|
+
// packages/ceal-client-protocol/src/vocabulary.ts
|
|
60
|
+
function vocabulary(words) {
|
|
61
|
+
return Object.freeze(words);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// packages/ceal-client-protocol/src/host-usage-fields.ts
|
|
65
|
+
var CEAL_CODEX_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"]);
|
|
66
|
+
var CEAL_CLAUDE_USAGE_COUNT_FIELDS = vocabulary(["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"]);
|
|
67
|
+
|
|
44
68
|
// packages/ceal-client-protocol/src/canonical-json.ts
|
|
45
69
|
function cealCanonicalJson(value) {
|
|
46
70
|
if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
|
|
@@ -69,7 +93,7 @@ function isPlainRecord(value) {
|
|
|
69
93
|
}
|
|
70
94
|
|
|
71
95
|
// packages/ceal-client-protocol/src/client-wire-contract.ts
|
|
72
|
-
import { createHash as
|
|
96
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
73
97
|
|
|
74
98
|
// packages/ceal-client-protocol/client-wire-contract.json
|
|
75
99
|
var client_wire_contract_default = {
|
|
@@ -90,7 +114,7 @@ var client_wire_contract_default = {
|
|
|
90
114
|
ordering: "utf16_code_unit_ascending"
|
|
91
115
|
},
|
|
92
116
|
artifact_descriptor: {
|
|
93
|
-
operation_contract_bundle_schema_name: "ceal.
|
|
117
|
+
operation_contract_bundle_schema_name: "ceal.operation_contract_bundle_v2",
|
|
94
118
|
operation_contract_bundle_fields: ["schema_version", "catalog_revision", "operations", "failure_guidance"],
|
|
95
119
|
schema_name: "ceal.verified_artifact_descriptor",
|
|
96
120
|
fields: ["schema_version", "kind", "media_type", "byte_count", "sha256", "binding"],
|
|
@@ -115,7 +139,7 @@ var client_wire_contract_default = {
|
|
|
115
139
|
},
|
|
116
140
|
command_request: {
|
|
117
141
|
schema_name: "ceal.command_request",
|
|
118
|
-
fields: ["schema_version", "argv", "operation", "client_nonce", "context_token"],
|
|
142
|
+
fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
|
|
119
143
|
absolute_transport_max_bytes: 65536
|
|
120
144
|
},
|
|
121
145
|
command_resolution: {
|
|
@@ -161,8 +185,9 @@ var client_wire_contract_default = {
|
|
|
161
185
|
},
|
|
162
186
|
command_response: {
|
|
163
187
|
schema_name: "ceal.command_response",
|
|
164
|
-
fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact"],
|
|
188
|
+
fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
|
|
165
189
|
descriptor_field: "verified_artifact",
|
|
190
|
+
request_context_field: "request_context",
|
|
166
191
|
required_fields: [
|
|
167
192
|
"schema_version",
|
|
168
193
|
"exit_code",
|
|
@@ -172,7 +197,8 @@ var client_wire_contract_default = {
|
|
|
172
197
|
"operation_id",
|
|
173
198
|
"visible_output_max_bytes",
|
|
174
199
|
"local_delivery",
|
|
175
|
-
"verified_artifact"
|
|
200
|
+
"verified_artifact",
|
|
201
|
+
"request_context"
|
|
176
202
|
],
|
|
177
203
|
bare_document_fields: [
|
|
178
204
|
"invocation",
|
|
@@ -193,7 +219,7 @@ var client_wire_contract_default = {
|
|
|
193
219
|
],
|
|
194
220
|
exit_code_max: 125,
|
|
195
221
|
bare_document_max_bytes: 65536,
|
|
196
|
-
complete_max_bytes:
|
|
222
|
+
complete_max_bytes: 66195
|
|
197
223
|
},
|
|
198
224
|
host_invocation_authentication: {
|
|
199
225
|
request_schema_name: "ceal.host_invocation_authentication_request",
|
|
@@ -207,6 +233,17 @@ var client_wire_contract_default = {
|
|
|
207
233
|
"context_token",
|
|
208
234
|
"expires_at"
|
|
209
235
|
],
|
|
236
|
+
refusal_schema_name: "ceal.host_invocation_authentication_refusal",
|
|
237
|
+
refusal_fields: [
|
|
238
|
+
"schema_version",
|
|
239
|
+
"ok",
|
|
240
|
+
"code",
|
|
241
|
+
"reason",
|
|
242
|
+
"gateway_status",
|
|
243
|
+
"retry_after_ms"
|
|
244
|
+
],
|
|
245
|
+
refusal_required_fields: ["schema_version", "ok", "code", "reason"],
|
|
246
|
+
refusal_optional_fields: ["gateway_status", "retry_after_ms"],
|
|
210
247
|
client_nonce: {
|
|
211
248
|
character_class_source: "A-Za-z0-9_-",
|
|
212
249
|
encoded_characters: 43
|
|
@@ -245,6 +282,8 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
|
|
|
245
282
|
"choose_new_output_path",
|
|
246
283
|
"choose_new_idempotency_key",
|
|
247
284
|
"restart_search",
|
|
285
|
+
// The requested temporal key is absent on some observed rows; repeating the same interval without `order` can return those rows.
|
|
286
|
+
"search_without_order",
|
|
248
287
|
"repeat_original_arguments",
|
|
249
288
|
// The occurrence this call addressed is settled and cannot move again -- a
|
|
250
289
|
// denied effect approval, an expired continuation -- so the caller runs the
|
|
@@ -303,6 +342,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
|
|
|
303
342
|
// The command needs caller-owned local materialization (for example an
|
|
304
343
|
// @path file) before the Gateway can receive the argument.
|
|
305
344
|
"materialize_local_argument",
|
|
345
|
+
// A missing or stale local Host bundle is repaired through its installed lifecycle and discovery owners.
|
|
346
|
+
"install_ceal_host",
|
|
347
|
+
// An explicit Client store override points at a missing file; unsetting it selects the one canonical default store without creating a second credential store.
|
|
348
|
+
"unset_context_store_path",
|
|
349
|
+
// The producer app must reload its installed Host hook before it can start a conversation with invocation context.
|
|
350
|
+
"restart_producer_app",
|
|
306
351
|
// A peer's derived schema identifier changed with its field set; install or
|
|
307
352
|
// upgrade the CLI and Host Relay to the Gateway's release before retrying.
|
|
308
353
|
"upgrade_ceal_client"
|
|
@@ -411,18 +456,12 @@ var NON_MODEL_ACTION_TO_MODEL_ACTION = Object.freeze({
|
|
|
411
456
|
});
|
|
412
457
|
var RETRY_PROMISE_NEXT_ACTIONS = ["retry", "retry_after"];
|
|
413
458
|
var RETRY_PROMISE = new Set(RETRY_PROMISE_NEXT_ACTIONS);
|
|
414
|
-
var RECOVERABLE = new Set(CEAL_CALLER_RECOVERABLE_NEXT_ACTIONS);
|
|
415
459
|
var CEAL_OPERATION_WITHHELD_NEXT_ACTIONS = Object.freeze({
|
|
416
460
|
provider_permission: "ask_admin",
|
|
417
461
|
access_level: "ask_admin",
|
|
418
462
|
personal_authorization_required: "connect_personal_account"
|
|
419
463
|
});
|
|
420
464
|
|
|
421
|
-
// packages/ceal-client-protocol/src/vocabulary.ts
|
|
422
|
-
function vocabulary(words) {
|
|
423
|
-
return Object.freeze(words);
|
|
424
|
-
}
|
|
425
|
-
|
|
426
465
|
// packages/ceal-client-protocol/src/gateway-response-types.ts
|
|
427
466
|
var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavailable", "unknown"]);
|
|
428
467
|
var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
|
|
@@ -433,9 +472,9 @@ var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "s
|
|
|
433
472
|
var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
|
|
434
473
|
var CEAL_POLICY_DECISIONS = vocabulary(["allowed", "denied", "not_evaluated"]);
|
|
435
474
|
var CEAL_CONNECTOR_ROUTE_PHASES = vocabulary(["scope_observation", "target_selection", "route_resolution"]);
|
|
436
|
-
var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "scope_limit_exceeded"]);
|
|
475
|
+
var CEAL_CONNECTOR_ROUTE_CAUSES = vocabulary(["provider_throttled", "provider_unavailable", "binding_invalid", "personal_binding_unproven", "scope_limit_exceeded"]);
|
|
437
476
|
var CEAL_WRITE_SOURCE_KINDS = vocabulary(["authenticated_registered_client", "provider_authenticated_event"]);
|
|
438
|
-
var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable"]);
|
|
477
|
+
var CEAL_REFRESH_DELIVERIES = vocabulary(["initial", "recovery", "replay", "terminal_failure", "recovery_unavailable", "authority_inactive"]);
|
|
439
478
|
var CEAL_CLIENT_OPERATIONS = vocabulary(["handshake", "discover", "call", "readback"]);
|
|
440
479
|
var CEAL_WRITE_IDEMPOTENCY_POSTURES = vocabulary(["required", "optional", "not_required"]);
|
|
441
480
|
var CEAL_WRITE_PROVIDER_READBACK_POSTURES = vocabulary(["required", "best_effort", "not_available"]);
|
|
@@ -506,10 +545,10 @@ function assertSafeJsonArray(value, options, depth, count) {
|
|
|
506
545
|
if (value.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
|
|
507
546
|
for (const item of value) assertSafeJsonValue(item, options, depth + 1, count);
|
|
508
547
|
}
|
|
509
|
-
function assertSafeJsonRecord(
|
|
510
|
-
const entries = Object.entries(
|
|
548
|
+
function assertSafeJsonRecord(record2, options, depth, count) {
|
|
549
|
+
const entries = Object.entries(record2);
|
|
511
550
|
if (entries.length > CEAL_WIRE_SAFE_ARRAY_MAX_ITEMS) invalidByContext(options);
|
|
512
|
-
const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(
|
|
551
|
+
const sourceUrlColumn = options.allowHttpsUrl ? compactSourceUrlColumn(record2.fields) : null;
|
|
513
552
|
for (const [key, child] of entries) {
|
|
514
553
|
if (key === "credential_material_included" && child !== false) invalidByContext(options);
|
|
515
554
|
if (!isSafeNegativeMaterialAssertion(key, child)) assertSafeJsonKey(key, options);
|
|
@@ -559,16 +598,21 @@ function isSafeExternalHttpsUrl(value) {
|
|
|
559
598
|
return false;
|
|
560
599
|
}
|
|
561
600
|
}
|
|
601
|
+
var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE = "^https://[^\\s/@?#]+(?:[/?#][^\\s]*)?$";
|
|
602
|
+
var SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN = new RegExp(SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE, "u");
|
|
562
603
|
function isSafeExternalHttpsUrlInput(value) {
|
|
563
604
|
return typeof value === "string" && byteLength(value) <= 2048;
|
|
564
605
|
}
|
|
565
|
-
function isSafeExternalHttpsUrlShape(url) {
|
|
566
|
-
return url.protocol === "https:" && url.username === "" && url.password === "" && url.hash === "";
|
|
606
|
+
function isSafeExternalHttpsUrlShape(url, allowFragment = false) {
|
|
607
|
+
return url.protocol === "https:" && url.hostname.length > 0 && url.username === "" && url.password === "" && (allowFragment || url.hash === "");
|
|
567
608
|
}
|
|
568
609
|
function isSafeResultContent(value, key) {
|
|
569
610
|
const maximum = key === "text" ? 8192 : 1024;
|
|
570
611
|
return typeof value === "string" && byteLength(value) <= maximum && firstDisallowedControl(value, "multi_line") === null;
|
|
571
612
|
}
|
|
613
|
+
function requireSafeRef(value) {
|
|
614
|
+
if (typeof value !== "string" || !SAFE_REF.test(value)) invalidRequestOrResponse();
|
|
615
|
+
}
|
|
572
616
|
var CEAL_PUBLIC_DISPLAY_NAME_MAX_BYTES = 512;
|
|
573
617
|
function normalizeCealSingleLineText(value) {
|
|
574
618
|
return value.split("").map((character) => hasControlCharacter(character) ? " " : character).join("").trim();
|
|
@@ -680,6 +724,7 @@ function cut(text) {
|
|
|
680
724
|
|
|
681
725
|
// packages/ceal-client-protocol/src/operation-validation-primitives.ts
|
|
682
726
|
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;
|
|
727
|
+
var EXPANDED_CANONICAL_ISO_TIMESTAMP = /^([+-])(\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/u;
|
|
683
728
|
var CEAL_CALENDAR_DATE_PATTERN_SOURCE = "^\\d{4}-\\d{2}-\\d{2}$";
|
|
684
729
|
var CEAL_CALENDAR_DATE = new RegExp(CEAL_CALENDAR_DATE_PATTERN_SOURCE, "u");
|
|
685
730
|
function isOperationRecord(value) {
|
|
@@ -690,13 +735,46 @@ function isOperationRecord(value) {
|
|
|
690
735
|
function requireOperationRecord(value, message) {
|
|
691
736
|
if (!isOperationRecord(value)) throw new TypeError(message);
|
|
692
737
|
}
|
|
738
|
+
function requireExactOperationKeys(value, required, optional = [], message = "Operation contract has an invalid shape.") {
|
|
739
|
+
const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
|
|
740
|
+
if (required.some((key) => !Object.hasOwn(value, key))) throw new TypeError(message);
|
|
741
|
+
if (Object.keys(value).some((key) => !allowed.has(key))) throw new TypeError(message);
|
|
742
|
+
}
|
|
693
743
|
function requireClosedValue(value, members, message) {
|
|
694
744
|
if (typeof value !== "string" || !members.includes(value)) throw new TypeError(message);
|
|
695
745
|
}
|
|
696
746
|
function isCealIsoTimestamp(value) {
|
|
697
747
|
return typeof value === "string" && parseCealIsoTimestamp(value) !== null;
|
|
698
748
|
}
|
|
749
|
+
function canonicalCealIsoTimestamp(epochNanoseconds) {
|
|
750
|
+
const wholeSeconds = floorDivide(epochNanoseconds, 1000000000n);
|
|
751
|
+
const fractionalNanoseconds = epochNanoseconds - wholeSeconds * 1000000000n;
|
|
752
|
+
const utc = new Date(Number(wholeSeconds * 1000n));
|
|
753
|
+
const date = utc.toISOString().split(".")[0];
|
|
754
|
+
if (date === void 0) throw new TypeError("Ceal timestamp formatter returned an invalid ISO string");
|
|
755
|
+
const fraction = fractionalNanoseconds.toString().padStart(9, "0").replace(/0+$/u, "").padEnd(3, "0");
|
|
756
|
+
return date + "." + fraction + "Z";
|
|
757
|
+
}
|
|
758
|
+
var CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE = "0000-01-01T00:00:00.000000000+23:59";
|
|
759
|
+
var CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE = "9999-12-31T23:59:59.999999999-23:59";
|
|
760
|
+
var CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MIN_SOURCE);
|
|
761
|
+
var CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS = requiredTimestampEpochNanoseconds(CEAL_TIMESTAMP_DOMAIN_MAX_SOURCE);
|
|
762
|
+
var CEAL_INSTANT_INDEX_SPAN = CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS - CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS;
|
|
763
|
+
var CEAL_INSTANT_INDEX_KEY_WIDTH = CEAL_INSTANT_INDEX_SPAN.toString().length;
|
|
764
|
+
var CEAL_INSTANT_INDEX_KEY_PATTERN = new RegExp(`^\\d{${CEAL_INSTANT_INDEX_KEY_WIDTH}}$`, "u");
|
|
765
|
+
function requiredTimestampEpochNanoseconds(value) {
|
|
766
|
+
const parsed = parseFourDigitCealIsoTimestamp(value);
|
|
767
|
+
if (parsed === null) throw new Error("Ceal instant-index range basis is outside the timestamp grammar");
|
|
768
|
+
return parsed.epochNanoseconds;
|
|
769
|
+
}
|
|
699
770
|
function parseCealIsoTimestamp(value) {
|
|
771
|
+
const ordinary = parseFourDigitCealIsoTimestamp(value);
|
|
772
|
+
if (ordinary !== null) return ordinary;
|
|
773
|
+
const expanded = parseExpandedCanonicalCealIsoTimestamp(value);
|
|
774
|
+
if (expanded === null || expanded.epochNanoseconds < CEAL_TIMESTAMP_DOMAIN_MIN_EPOCH_NS || expanded.epochNanoseconds > CEAL_TIMESTAMP_DOMAIN_MAX_EPOCH_NS) return null;
|
|
775
|
+
return canonicalCealIsoTimestamp(expanded.epochNanoseconds) === value ? expanded : null;
|
|
776
|
+
}
|
|
777
|
+
function parseFourDigitCealIsoTimestamp(value) {
|
|
700
778
|
const fields = parseCealIsoTimestampFields(value);
|
|
701
779
|
if (fields === null || !validCalendarDate(fields) || !validClockTime(fields) || !validUtcOffset(fields)) return null;
|
|
702
780
|
const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
|
|
@@ -705,6 +783,28 @@ function parseCealIsoTimestamp(value) {
|
|
|
705
783
|
epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
|
|
706
784
|
};
|
|
707
785
|
}
|
|
786
|
+
function parseExpandedCanonicalCealIsoTimestamp(value) {
|
|
787
|
+
const match = EXPANDED_CANONICAL_ISO_TIMESTAMP.exec(value);
|
|
788
|
+
if (match === null) return null;
|
|
789
|
+
const fields = {
|
|
790
|
+
year: (match[1] === "-" ? -1 : 1) * Number(match[2]),
|
|
791
|
+
month: Number(match[3]),
|
|
792
|
+
day: Number(match[4]),
|
|
793
|
+
hour: Number(match[5]),
|
|
794
|
+
minute: Number(match[6]),
|
|
795
|
+
second: Number(match[7]),
|
|
796
|
+
fraction: match[8] ?? "",
|
|
797
|
+
offsetSign: 0,
|
|
798
|
+
offsetHour: 0,
|
|
799
|
+
offsetMinute: 0
|
|
800
|
+
};
|
|
801
|
+
if (!validCalendarDate(fields) || !validClockTime(fields)) return null;
|
|
802
|
+
const epochMilliseconds = cealFieldsEpochMilliseconds(fields);
|
|
803
|
+
if (!Number.isFinite(epochMilliseconds)) return null;
|
|
804
|
+
return {
|
|
805
|
+
epochNanoseconds: BigInt(epochMilliseconds) * 1000000n + BigInt(fields.fraction.padEnd(9, "0") || "0")
|
|
806
|
+
};
|
|
807
|
+
}
|
|
708
808
|
function parseCealIsoTimestampFields(value) {
|
|
709
809
|
const match = ISO_TIMESTAMP.exec(value);
|
|
710
810
|
if (match === null) return null;
|
|
@@ -737,6 +837,10 @@ function cealFieldsEpochMilliseconds(fields) {
|
|
|
737
837
|
const offsetMilliseconds = fields.offsetSign * (fields.offsetHour * 60 + fields.offsetMinute) * 6e4;
|
|
738
838
|
return localMilliseconds - offsetMilliseconds;
|
|
739
839
|
}
|
|
840
|
+
function floorDivide(value, divisor) {
|
|
841
|
+
const quotient = value / divisor;
|
|
842
|
+
return value % divisor < 0n ? quotient - 1n : quotient;
|
|
843
|
+
}
|
|
740
844
|
function daysInMonth(year, month) {
|
|
741
845
|
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
742
846
|
return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
|
|
@@ -754,6 +858,9 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
|
|
|
754
858
|
var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
|
|
755
859
|
var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
|
|
756
860
|
var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
|
|
861
|
+
var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
|
|
862
|
+
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.";
|
|
863
|
+
var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
|
|
757
864
|
var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
|
|
758
865
|
function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
|
|
759
866
|
return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
|
|
@@ -779,6 +886,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
779
886
|
refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
780
887
|
refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
781
888
|
refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
889
|
+
person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
|
|
890
|
+
principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
|
|
782
891
|
refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
783
892
|
refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
|
|
784
893
|
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),
|
|
@@ -791,8 +900,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
791
900
|
response_encoding_failed: guidance("The local response could not be encoded; report this as a gap.", "answer_with_gap", 500),
|
|
792
901
|
request_timeout: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 504),
|
|
793
902
|
request_failed: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 502),
|
|
903
|
+
resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
|
|
794
904
|
gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
|
|
795
|
-
contract_mismatch: guidance(
|
|
905
|
+
contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
|
|
796
906
|
// `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
|
|
797
907
|
// (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
|
|
798
908
|
// when the wait ends still unserved, moved from the `localFailureText` default branch.
|
|
@@ -802,13 +912,12 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
802
912
|
// `gateway_internal_error` guidance (decided with the operator 2026-10-13).
|
|
803
913
|
internal_error: guidance("The Gateway failed without exposing internal state.", "answer_with_gap", 500),
|
|
804
914
|
// Owned by the Gateway canonical adapter (`gateway/core/src/gateway-canonical-operation-http-adapter.ts`):
|
|
805
|
-
// the client variant
|
|
915
|
+
// the static client variant was retired when the client started reading this table.
|
|
806
916
|
request_body_too_large: guidance("The Gateway request body exceeds its bounded limit.", "reduce_request_size", 413),
|
|
807
|
-
|
|
808
|
-
//
|
|
809
|
-
//
|
|
810
|
-
|
|
811
|
-
unknown_outcome: guidance("The transport outcome is unknown: a read may be retried; for a write, check write_receipt.get before repeating.", "answer_with_gap", 500),
|
|
917
|
+
gateway_response_too_large: guidance("The Gateway response exceeds its bounded limit; reduce the requested page or result size.", "reduce_request_size", 500),
|
|
918
|
+
// The safe move varies by request. Keep the sentence conditional on the
|
|
919
|
+
// same `retryable` and `next_action` facts the response exposes.
|
|
920
|
+
unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
|
|
812
921
|
// Restored verbatim from the retired `localFailureText`
|
|
813
922
|
// `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
|
|
814
923
|
// session context unavailable, so the caller repairs or adopts the
|
|
@@ -889,24 +998,27 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
889
998
|
// Host mint classifications. The CLI emits `invocation_authentication_unavailable` with the classification
|
|
890
999
|
// in its detail fact; rows without their own sentence share that code's moved sentence, while `next_action`
|
|
891
1000
|
// is moved from `canonicalHostAuthenticationNextActions` (generated from `CEAL_HOST_AUTHENTICATION_POLICY`)
|
|
892
|
-
// and `retryable` from `hostAuthenticationFailureForCause` (
|
|
893
|
-
//
|
|
1001
|
+
// and `retryable` from `hostAuthenticationFailureForCause` (the table's explicit retry verdict). Cause-specific
|
|
1002
|
+
// sentences carry only remedies proved by the Host or Relay cause; generic Gateway refusals do not prove a release mismatch.
|
|
1003
|
+
// Statuses are the
|
|
894
1004
|
// Gateway-owned mapping decided with the operator 2026-10-13. This covers every wire cause the maps at
|
|
895
1005
|
// `host/invocation-authentication-command.ts:217-242` emit, through their policy classifications.
|
|
896
1006
|
host_arguments_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 400),
|
|
897
1007
|
host_configuration_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
|
|
898
1008
|
host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
|
|
899
|
-
//
|
|
900
|
-
//
|
|
901
|
-
host_context_unavailable: guidance(
|
|
902
|
-
|
|
903
|
-
|
|
1009
|
+
// The bounded Host reason does not prove ephemerality. A Host refusal never
|
|
1010
|
+
// changes mode; standalone remains the separate Client authority path.
|
|
1011
|
+
host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
|
|
1012
|
+
host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
|
|
1013
|
+
host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
|
|
1014
|
+
host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
|
|
904
1015
|
host_source_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 403),
|
|
905
1016
|
host_registration_credential_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 403),
|
|
906
1017
|
host_mint_gateway_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "ask_admin", 503),
|
|
907
1018
|
host_mint_gateway_rate_limited: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 429),
|
|
908
1019
|
host_mint_gateway_refused: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
|
|
909
1020
|
host_mint_gateway_response_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 502),
|
|
1021
|
+
host_contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 502),
|
|
910
1022
|
// Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
|
|
911
1023
|
// producer-frame fault names the administrator repair step.
|
|
912
1024
|
host_producer_frame_invalid: guidance("Ask an administrator to inspect and repair the producer frame, then start a fresh Host turn.", "ask_admin", 400),
|
|
@@ -916,56 +1028,13 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
916
1028
|
host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
|
|
917
1029
|
host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
|
|
918
1030
|
host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
|
|
919
|
-
host_relay_failed: guidance(
|
|
1031
|
+
host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
|
|
920
1032
|
host_refusal_invalid: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500)
|
|
921
1033
|
});
|
|
922
1034
|
var FAILURE_GUIDANCE_ENTRY_KEYS = Object.freeze(["message", "next_action", "http_status", "retryable", "redaction_class"]);
|
|
923
1035
|
|
|
924
|
-
// packages/ceal-client-protocol/src/
|
|
925
|
-
|
|
926
|
-
var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
|
|
927
|
-
var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
|
|
928
|
-
var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
|
|
929
|
-
var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
|
|
930
|
-
var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
|
|
931
|
-
function deriveCealClientWireSchemaVersion(schema) {
|
|
932
|
-
if (!/^ceal\.[a-z][a-z0-9_]*$/u.test(schema.schema_name) || !schema.fields.includes("schema_version") || new Set(schema.fields).size !== schema.fields.length || schema.fields.some((field) => typeof field !== "string" || !/^[a-z][a-z0-9_]*$/u.test(field))) {
|
|
933
|
-
throw new TypeError("Client wire schema name or field set is invalid.");
|
|
934
|
-
}
|
|
935
|
-
const fields = schema.fields.filter((field) => field !== "schema_version").sort();
|
|
936
|
-
const hash8 = createHash2("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
|
|
937
|
-
return `${schema.schema_name}.v1.${hash8}`;
|
|
938
|
-
}
|
|
939
|
-
var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
|
|
940
|
-
var commandResolutionAuthority = commandResolution.authority;
|
|
941
|
-
var commandResolutionSemanticOptions = commandResolution.semantic_options;
|
|
942
|
-
var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
|
|
943
|
-
var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
|
|
944
|
-
var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
|
|
945
|
-
var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
|
|
946
|
-
var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
|
|
947
|
-
var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
|
|
948
|
-
var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
|
|
949
|
-
var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
|
|
950
|
-
var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
|
|
951
|
-
var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
|
|
952
|
-
var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
|
|
953
|
-
var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
|
|
954
|
-
var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
|
|
955
|
-
var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
|
|
956
|
-
var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
|
|
957
|
-
var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
|
|
958
|
-
var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
|
|
959
|
-
var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
|
|
960
|
-
var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
|
|
961
|
-
var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
|
|
962
|
-
var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
|
|
963
|
-
var CEAL_COMMAND_RESPONSE_DISCOVERY_COMMAND = response.discovery_command;
|
|
964
|
-
var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
|
|
965
|
-
var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
|
|
966
|
-
var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_DOCUMENT_FIELDS = Object.freeze([...response.discovery_manifest_document_fields]);
|
|
967
|
-
var CEAL_RESOURCE_STREAM_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_schema_name, fields: CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields });
|
|
968
|
-
var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
|
|
1036
|
+
// packages/ceal-client-protocol/src/request-validation-primitives.ts
|
|
1037
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
969
1038
|
|
|
970
1039
|
// packages/ceal-client-protocol/src/operation-withheld-cause.ts
|
|
971
1040
|
var CEAL_OPERATION_WITHHELD_CAUSES = vocabulary(["provider_permission", "access_level", "personal_authorization_required"]);
|
|
@@ -994,7 +1063,7 @@ var UNKNOWN_OUTCOMES = vocabulary(["reconcile", "operator_action", "excluded"]);
|
|
|
994
1063
|
var RECOVERY_OWNERS = vocabulary(["gateway", "connector", "operator"]);
|
|
995
1064
|
var CEAL_OPERATION_ADMISSION_STATES = vocabulary(["proposed", "refused", "admitted"]);
|
|
996
1065
|
var CEAL_OPERATION_EXECUTION_STATES = vocabulary(["not_started", "started", "completed"]);
|
|
997
|
-
var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_offered", "offered", "accepted", "rejected", "unknown"]);
|
|
1066
|
+
var CEAL_OPERATION_PROVIDER_HANDOFF_STATES = vocabulary(["not_applicable", "not_offered", "offered", "accepted", "rejected", "unknown"]);
|
|
998
1067
|
var CEAL_OPERATION_EFFECT_STATES = vocabulary(["none", "applied", "failed", "unknown", "compensated"]);
|
|
999
1068
|
var CEAL_OPERATION_OBSERVATION_STATES = vocabulary(["not_started", "not_required", "pending", "observed", "unavailable"]);
|
|
1000
1069
|
var CEAL_OPERATION_RECOVERY_KINDS = vocabulary(["none", "reconcile", "compensate", "operator_action"]);
|
|
@@ -1011,13 +1080,161 @@ var CEAL_OPERATION_APPROVAL_DISPOSITIONS = vocabulary([
|
|
|
1011
1080
|
"interactive_unavailable"
|
|
1012
1081
|
]);
|
|
1013
1082
|
|
|
1083
|
+
// packages/ceal-client-protocol/src/request-validation-primitives.ts
|
|
1084
|
+
var DIGEST = /^[a-f0-9]{64}$/u;
|
|
1085
|
+
var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
|
|
1086
|
+
function isCealDigest(value) {
|
|
1087
|
+
return typeof value === "string" && DIGEST.test(value);
|
|
1088
|
+
}
|
|
1089
|
+
function cealRequestSha256(value) {
|
|
1090
|
+
return createHash2("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
|
|
1091
|
+
}
|
|
1092
|
+
function operationRecord(value, message) {
|
|
1093
|
+
requireOperationRecord(value, message);
|
|
1094
|
+
return value;
|
|
1095
|
+
}
|
|
1096
|
+
function invalid(message) {
|
|
1097
|
+
throw new TypeError(message);
|
|
1098
|
+
}
|
|
1099
|
+
function requirePrefixedRef(value, prefix, message) {
|
|
1100
|
+
if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
|
|
1101
|
+
}
|
|
1102
|
+
function requireSafeRef2(value, message) {
|
|
1103
|
+
try {
|
|
1104
|
+
requireSafeRef(value);
|
|
1105
|
+
} catch {
|
|
1106
|
+
invalid(message);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
// packages/ceal-client-protocol/src/request-authority.ts
|
|
1111
|
+
var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
|
|
1112
|
+
var CEAL_REQUEST_REF_MAX_CHARACTERS = 128;
|
|
1113
|
+
var CEAL_REQUEST_REF_PATTERN_SOURCE = "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$";
|
|
1114
|
+
var CEAL_REQUEST_REF_PATTERN = new RegExp(CEAL_REQUEST_REF_PATTERN_SOURCE, "u");
|
|
1115
|
+
var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
|
|
1116
|
+
var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
|
|
1117
|
+
var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
|
|
1118
|
+
var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
|
|
1119
|
+
var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
|
|
1120
|
+
var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
|
|
1121
|
+
schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
|
|
1122
|
+
ceal_request_ref: { type: "string", minLength: 1, maxLength: CEAL_REQUEST_REF_MAX_CHARACTERS, pattern: CEAL_REQUEST_REF_PATTERN_SOURCE },
|
|
1123
|
+
created_at: { type: "string", minLength: 1, maxLength: 64 },
|
|
1124
|
+
authority: {
|
|
1125
|
+
type: "object",
|
|
1126
|
+
maxProperties: 5,
|
|
1127
|
+
additionalProperties: false,
|
|
1128
|
+
properties: {
|
|
1129
|
+
instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1130
|
+
access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1131
|
+
principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1132
|
+
execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1133
|
+
authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
|
|
1134
|
+
},
|
|
1135
|
+
required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
|
|
1136
|
+
}
|
|
1137
|
+
});
|
|
1138
|
+
var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
|
|
1139
|
+
prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1140
|
+
host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1141
|
+
host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1142
|
+
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." },
|
|
1143
|
+
host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1144
|
+
host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
|
|
1145
|
+
});
|
|
1146
|
+
var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
|
|
1147
|
+
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." },
|
|
1148
|
+
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." }
|
|
1149
|
+
});
|
|
1150
|
+
var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
|
|
1151
|
+
requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
|
|
1152
|
+
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." }
|
|
1153
|
+
});
|
|
1154
|
+
var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
|
|
1155
|
+
var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
|
|
1156
|
+
var CEAL_REQUEST_JSON_SCHEMA = {
|
|
1157
|
+
type: "object",
|
|
1158
|
+
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.",
|
|
1159
|
+
maxProperties: 14,
|
|
1160
|
+
additionalProperties: false,
|
|
1161
|
+
properties: {
|
|
1162
|
+
...CEAL_REQUEST_COMMON_PROPERTIES,
|
|
1163
|
+
...CEAL_REQUEST_HOST_PROPERTIES,
|
|
1164
|
+
...CEAL_REQUEST_CALLER_PROPERTIES,
|
|
1165
|
+
...CEAL_REQUEST_OPTIONAL_PROPERTIES
|
|
1166
|
+
},
|
|
1167
|
+
required: CEAL_REQUEST_KEYS,
|
|
1168
|
+
anyOf: [
|
|
1169
|
+
{
|
|
1170
|
+
type: "object",
|
|
1171
|
+
required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
|
|
1172
|
+
properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
|
|
1173
|
+
additionalProperties: false
|
|
1174
|
+
},
|
|
1175
|
+
{
|
|
1176
|
+
type: "object",
|
|
1177
|
+
required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
|
|
1178
|
+
properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
|
|
1179
|
+
additionalProperties: false
|
|
1180
|
+
}
|
|
1181
|
+
]
|
|
1182
|
+
};
|
|
1183
|
+
|
|
1184
|
+
// packages/ceal-client-protocol/src/client-wire-contract.ts
|
|
1185
|
+
var CEAL_CLIENT_WIRE_CONTRACT = Object.freeze(client_wire_contract_default);
|
|
1186
|
+
var CEAL_CLIENT_DOCTOR_SCHEMA_VERSION = CEAL_CLIENT_WIRE_CONTRACT.doctor.schema_version;
|
|
1187
|
+
var clientCommands = CEAL_CLIENT_WIRE_CONTRACT.client_commands;
|
|
1188
|
+
var CEAL_CLIENT_DOCTOR_COMMAND = Object.freeze([...clientCommands.doctor]);
|
|
1189
|
+
var CEAL_CLIENT_VERSION_COMMAND = Object.freeze([...clientCommands.version]);
|
|
1190
|
+
var CEAL_CLIENT_ACCESS_GROUP_LIST_COMMAND = Object.freeze([...clientCommands.access_group_list]);
|
|
1191
|
+
function deriveCealClientWireSchemaVersion(schema) {
|
|
1192
|
+
if (!/^ceal\.[a-z][a-z0-9_]*$/u.test(schema.schema_name) || !schema.fields.includes("schema_version") || new Set(schema.fields).size !== schema.fields.length || schema.fields.some((field) => typeof field !== "string" || !/^[a-z][a-z0-9_]*$/u.test(field))) {
|
|
1193
|
+
throw new TypeError("Client wire schema name or field set is invalid.");
|
|
1194
|
+
}
|
|
1195
|
+
const fields = schema.fields.filter((field) => field !== "schema_version").sort();
|
|
1196
|
+
const hash8 = createHash3("sha256").update(cealCanonicalJson(fields), "utf8").digest("hex").slice(0, 8);
|
|
1197
|
+
return `${schema.schema_name}.v1.${hash8}`;
|
|
1198
|
+
}
|
|
1199
|
+
var commandResolution = CEAL_CLIENT_WIRE_CONTRACT.command_resolution;
|
|
1200
|
+
var commandResolutionAuthority = commandResolution.authority;
|
|
1201
|
+
var commandResolutionSemanticOptions = commandResolution.semantic_options;
|
|
1202
|
+
var CEAL_GATEWAY_COMMAND_RESOLUTION_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(commandResolution);
|
|
1203
|
+
var CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES = CEAL_CLIENT_WIRE_CONTRACT.encoded_json_document.max_bytes;
|
|
1204
|
+
var artifact = CEAL_CLIENT_WIRE_CONTRACT.artifact_descriptor;
|
|
1205
|
+
var request = CEAL_CLIENT_WIRE_CONTRACT.command_request;
|
|
1206
|
+
var response = CEAL_CLIENT_WIRE_CONTRACT.command_response;
|
|
1207
|
+
var CEAL_OPERATION_CONTRACT_BUNDLE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.operation_contract_bundle_schema_name, fields: artifact.operation_contract_bundle_fields });
|
|
1208
|
+
var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(artifact);
|
|
1209
|
+
var CEAL_VERIFIED_ARTIFACT_BINDING_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: artifact.binding_schema_name, fields: artifact.binding_fields });
|
|
1210
|
+
var CEAL_VERIFIED_ARTIFACT_KIND = artifact.kind;
|
|
1211
|
+
var CEAL_VERIFIED_ARTIFACT_BINDING_KIND = artifact.binding_kind;
|
|
1212
|
+
var CEAL_VERIFIED_ARTIFACT_MEDIA_TYPE = artifact.media_type;
|
|
1213
|
+
var CEAL_VERIFIED_ARTIFACT_DIGEST_LENGTH = artifact.digest.length;
|
|
1214
|
+
var CEAL_VERIFIED_ARTIFACT_DIGEST_PATTERN = artifact.digest.pattern;
|
|
1215
|
+
var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_LENGTH = artifact.catalog_revision.length;
|
|
1216
|
+
var CEAL_VERIFIED_ARTIFACT_CATALOG_REVISION_PATTERN = artifact.catalog_revision.pattern;
|
|
1217
|
+
var CEAL_VERIFIED_ARTIFACT_MAX_BYTES = CEAL_ENCODED_JSON_DOCUMENT_MAX_BYTES;
|
|
1218
|
+
var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_MAX_BYTES = artifact.envelope_max_bytes;
|
|
1219
|
+
var CEAL_COMMAND_REQUEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(request);
|
|
1220
|
+
var CEAL_COMMAND_REQUEST_MAX_BYTES = request.absolute_transport_max_bytes;
|
|
1221
|
+
var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_MAX_BYTES = response.bare_document_max_bytes;
|
|
1222
|
+
var CEAL_COMMAND_RESPONSE_BARE_DOCUMENT_OPTIONAL_FIELDS = Object.freeze([...response.bare_document_optional_fields]);
|
|
1223
|
+
var CEAL_COMMAND_RESPONSE_DISCOVERY_MANIFEST_SCHEMA_VERSION = deriveCealClientWireSchemaVersion({ schema_name: response.discovery_manifest_schema_name, fields: response.discovery_manifest_fields });
|
|
1224
|
+
var CEAL_COMMAND_RESPONSE_SCHEMA_VERSION = deriveCealClientWireSchemaVersion(response);
|
|
1225
|
+
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 });
|
|
1226
|
+
var CEAL_RESOURCE_STREAM_REQUEST_FIELDS = Object.freeze([...CEAL_CLIENT_WIRE_CONTRACT.resource_stream.request_fields]);
|
|
1227
|
+
|
|
1228
|
+
// packages/ceal-client-protocol/src/access-level-vocabulary.ts
|
|
1229
|
+
var CEAL_ACCESS_LEVELS = vocabulary(["none", "read", "read_write"]);
|
|
1230
|
+
|
|
1014
1231
|
// packages/ceal-client-protocol/src/operation-access-class.ts
|
|
1015
1232
|
var CEAL_OPERATION_ACCESS_CLASSES = vocabulary(["read", "write"]);
|
|
1016
1233
|
|
|
1017
1234
|
// packages/ceal-client-protocol/src/domain-vocabulary.ts
|
|
1018
1235
|
var CEAL_CONNECTOR_STATUSES = vocabulary(["active", "disabled", "disconnected"]);
|
|
1019
1236
|
var CEAL_CONNECTOR_CUSTODIES = vocabulary(["organization", "personal"]);
|
|
1020
|
-
var
|
|
1237
|
+
var CEAL_PROVIDER_BOUNDARY_FIELDS = vocabulary(["provider_boundary_ref", "provider_boundary_kind", "provider_boundary_label", "provider_native_id", "provider_boundary_evidence"]);
|
|
1021
1238
|
var CEAL_PERSONAL_ACCESS_CEILINGS = vocabulary(["disabled", "read", "read_write"]);
|
|
1022
1239
|
var CEAL_TARGET_REF_PATTERN = "^[^\\p{Cc}]+$";
|
|
1023
1240
|
var TARGET_REF = new RegExp(CEAL_TARGET_REF_PATTERN, "u");
|
|
@@ -1063,7 +1280,7 @@ var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
|
|
|
1063
1280
|
var CEAL_OPERATION_AUTHORITY_POLICY_KEYS = Object.freeze(["access_group", "instance_binding", "target", "admission_recheck"]);
|
|
1064
1281
|
var MAX_OPERATION_INPUT_RESOLVER_BINDINGS = 96;
|
|
1065
1282
|
var CEAL_OPERATION_DESCRIPTOR_REQUIRED_ENVELOPE_KEYS = Object.freeze(["schema_version", "id", "input_contract", "result_contract", "policy"]);
|
|
1066
|
-
var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary"]);
|
|
1283
|
+
var CEAL_OPERATION_DESCRIPTOR_OPTIONAL_ENVELOPE_KEYS = Object.freeze(["input_resolution", "summary", "standard_names"]);
|
|
1067
1284
|
|
|
1068
1285
|
// packages/ceal-client-protocol/src/operation-catalog.ts
|
|
1069
1286
|
var CEAL_OPERATION_CATALOG_SCHEMA_VERSION = "ceal.catalog.v3";
|
|
@@ -1125,6 +1342,7 @@ var CEAL_SCHEMA_LITERALS = [
|
|
|
1125
1342
|
"ceal.gateway_write_receipt_readback.v1",
|
|
1126
1343
|
"ceal.gateway_write_request_receipt.v1",
|
|
1127
1344
|
"ceal.host_observation.v1",
|
|
1345
|
+
"ceal.host_usage_batch.v1",
|
|
1128
1346
|
"ceal.host_registration_request.v1",
|
|
1129
1347
|
"ceal.host_registration_result.v1",
|
|
1130
1348
|
CEAL_OPERATION_DESCRIPTOR_SCHEMA_VERSION,
|
|
@@ -1153,12 +1371,12 @@ var CEAL_SCHEMA_LITERAL_SET = new Set(CEAL_SCHEMA_LITERALS);
|
|
|
1153
1371
|
import { join } from "node:path";
|
|
1154
1372
|
var CEAL_BOUNDED_SERIES_CATALOG = Object.freeze({
|
|
1155
1373
|
bounded_store_sidecar: (root) => `${root}.jsonl`,
|
|
1156
|
-
gateway_audit_archive: (root) => `${root}.jsonl`,
|
|
1157
1374
|
gateway_access_group_connector_control_audit: (root) => `${root}.audit.jsonl`,
|
|
1158
1375
|
gateway_access_group_connector_scope_audit: (root) => join(root, "profile-connector-scope-audit.jsonl"),
|
|
1159
1376
|
gateway_access_group_connector_activity_scope_audit: (root) => join(root, "profile-connector-activity-scope-audit.jsonl"),
|
|
1160
1377
|
gateway_access_group_connector_calendar_scope_audit: (root) => join(root, "profile-connector-calendar-scope-audit.jsonl"),
|
|
1161
1378
|
gateway_access_group_connector_readiness_audit: (root) => join(root, "profile-connector-readiness.audit.jsonl"),
|
|
1379
|
+
gateway_deployment_events: (root) => join(root, "gateway-deployments.jsonl"),
|
|
1162
1380
|
gateway_organization_audit_ledger: (root) => join(root, "organization-ledger.jsonl"),
|
|
1163
1381
|
gateway_personal_client_audit: (root) => join(root, "audit.jsonl"),
|
|
1164
1382
|
gateway_personal_client_access_audit: (root) => join(root, "access-audit.jsonl")
|
|
@@ -1183,6 +1401,12 @@ var CEAL_LOWERCASE_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
|
|
|
1183
1401
|
var CEAL_HOST_REGISTRATION_ATTEMPT_REF_PATTERN = new RegExp(`^host-registration-attempt:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
|
|
1184
1402
|
var CEAL_HOST_INSTALLATION_REF_PATTERN = new RegExp(`^host-installation:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
|
|
1185
1403
|
var CEAL_HOST_SOURCE_REF_PATTERN = new RegExp(`^host-source:${CEAL_LOWERCASE_UUID_PATTERN}$`, "u");
|
|
1404
|
+
var CEAL_HOST_ACCESS_TOKEN_PATTERN = /^ceal_host_[A-Za-z0-9_-]{43}$/u;
|
|
1405
|
+
|
|
1406
|
+
// packages/ceal-client-protocol/src/resource-read-result.ts
|
|
1407
|
+
var CEAL_RESOURCE_GET_NOTION_CONTENT_GAP_KINDS = Object.freeze(["subtree", "media", "property_schema", "properties"]);
|
|
1408
|
+
var CEAL_RESOURCE_SEARCH_PROVIDER_STATUSES = vocabulary(["done", "pending", "deferred"]);
|
|
1409
|
+
var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
|
|
1186
1410
|
|
|
1187
1411
|
// packages/ceal-client-protocol/src/operation-result-completeness.ts
|
|
1188
1412
|
var CEAL_READ_VALUE_CONTINUATION_KEYS = vocabulary(["continuation", "continuation_ref", "next_cursor"]);
|
|
@@ -1201,7 +1425,7 @@ function shellSingleQuoted(value) {
|
|
|
1201
1425
|
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
1202
1426
|
}
|
|
1203
1427
|
var CEAL_OPERATION_CONTRACT_REQUIRED_FIELDS = Object.freeze(["input_schema", "result_schema"]);
|
|
1204
|
-
var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["summary", "input_resolution"]);
|
|
1428
|
+
var CEAL_OPERATION_CONTRACT_OPTIONAL_FIELDS = Object.freeze(["branches", "summary", "input_resolution"]);
|
|
1205
1429
|
var CEAL_VERIFIED_ARTIFACT_DESCRIPTOR_JSON_SCHEMA = Object.freeze({
|
|
1206
1430
|
$schema: CEAL_JSON_SCHEMA_2020_12,
|
|
1207
1431
|
$id: "https://ceal.dev/schemas/verified-artifact-descriptor.v1.schema.json",
|
|
@@ -1246,11 +1470,93 @@ var OPTIONAL_FIELDS = CEAL_CLIENT_WIRE_CONTRACT.command_response.bare_document_o
|
|
|
1246
1470
|
// packages/ceal-client-protocol/src/actor-kind.ts
|
|
1247
1471
|
var CEAL_ACTOR_KINDS = vocabulary(["human", "bot", "app", "unknown"]);
|
|
1248
1472
|
|
|
1473
|
+
// packages/ceal-client-protocol/src/provider-link-policy.ts
|
|
1474
|
+
var PROVIDER_LINK_RESULT_FIELDS = Object.freeze({
|
|
1475
|
+
read_row: Object.freeze({ human_link: "source_url", parent_context: Object.freeze(["thread_ref"]) }),
|
|
1476
|
+
write_result: Object.freeze({ human_links: Object.freeze(["user_openable_url", "url", "spreadsheet_url", "meet_url"]) })
|
|
1477
|
+
});
|
|
1478
|
+
var PROVIDER_LINK_CONFORMANCE_TABLE = Object.freeze([
|
|
1479
|
+
{ 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/" },
|
|
1480
|
+
{ 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/" },
|
|
1481
|
+
{ 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/" },
|
|
1482
|
+
{ 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/" },
|
|
1483
|
+
{ 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/" },
|
|
1484
|
+
{ 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" },
|
|
1485
|
+
{ 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" },
|
|
1486
|
+
{ 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" },
|
|
1487
|
+
{ 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" },
|
|
1488
|
+
{ 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" },
|
|
1489
|
+
{ 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" },
|
|
1490
|
+
{ 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" },
|
|
1491
|
+
{ 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" },
|
|
1492
|
+
{ 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" },
|
|
1493
|
+
{ 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" },
|
|
1494
|
+
{ 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" },
|
|
1495
|
+
{ provider: "google-workspace", result_kind: "form_write_result", field: "user_openable_url", status: "required_when_provider_supplies", provider_shape: "verified Forms responderUri", source: "https://developers.google.com/workspace/forms/api/reference/rest/v1/forms" },
|
|
1496
|
+
{ 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" },
|
|
1497
|
+
{ 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" },
|
|
1498
|
+
{ 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" },
|
|
1499
|
+
{ 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" }
|
|
1500
|
+
]);
|
|
1501
|
+
var PROVIDER_LINK_HOSTS = Object.freeze({
|
|
1502
|
+
notion: Object.freeze(["notion.so", "www.notion.so", "notion.com", "www.notion.com", "app.notion.com"]),
|
|
1503
|
+
google_workspace: Object.freeze([
|
|
1504
|
+
"calendar.google.com",
|
|
1505
|
+
"contacts.google.com",
|
|
1506
|
+
"docs.google.com",
|
|
1507
|
+
"drive.google.com",
|
|
1508
|
+
"forms.google.com",
|
|
1509
|
+
"mail.google.com",
|
|
1510
|
+
"meet.google.com",
|
|
1511
|
+
"sites.google.com",
|
|
1512
|
+
"www.google.com"
|
|
1513
|
+
])
|
|
1514
|
+
});
|
|
1515
|
+
var NOTION_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.notion);
|
|
1516
|
+
var GOOGLE_WORKSPACE_SOURCE_HOSTS = new Set(PROVIDER_LINK_HOSTS.google_workspace);
|
|
1517
|
+
var PROVIDER_RESOURCE_SOURCE_URL_SCHEMA = Object.freeze({
|
|
1518
|
+
type: "string",
|
|
1519
|
+
minLength: 1,
|
|
1520
|
+
maxLength: 2048,
|
|
1521
|
+
pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
|
|
1522
|
+
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."
|
|
1523
|
+
});
|
|
1524
|
+
var PROVIDER_USER_OPENABLE_URL_SCHEMA = Object.freeze({
|
|
1525
|
+
type: "string",
|
|
1526
|
+
minLength: 1,
|
|
1527
|
+
maxLength: 2048,
|
|
1528
|
+
pattern: SAFE_EXTERNAL_HTTPS_URL_WITH_FRAGMENT_PATTERN_SOURCE,
|
|
1529
|
+
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."
|
|
1530
|
+
});
|
|
1531
|
+
|
|
1249
1532
|
// packages/ceal-client-protocol/src/resource-row.ts
|
|
1250
1533
|
var CEAL_RESOURCE_ROW_TITLE_MATCH_DISPOSITIONS = vocabulary(["exact", "not_exact", "unknown"]);
|
|
1251
1534
|
var CEAL_RESOURCE_SEARCH_ORDERS = vocabulary(["relevance", "modified", "viewed", "created"]);
|
|
1252
1535
|
var CEAL_RESOURCE_SEARCH_DIRECTIONS = vocabulary(["ascending", "descending"]);
|
|
1253
|
-
var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
|
|
1536
|
+
var CEAL_RESOURCE_SEARCH_FILTERS = vocabulary([
|
|
1537
|
+
"query",
|
|
1538
|
+
"modified_since",
|
|
1539
|
+
"since",
|
|
1540
|
+
"until",
|
|
1541
|
+
"filetype",
|
|
1542
|
+
"authored_by_me",
|
|
1543
|
+
"authored_by",
|
|
1544
|
+
"edited_by",
|
|
1545
|
+
"include_replies",
|
|
1546
|
+
"kinds",
|
|
1547
|
+
"container_ref",
|
|
1548
|
+
"container_refs",
|
|
1549
|
+
"container_names",
|
|
1550
|
+
"addressed_to_me",
|
|
1551
|
+
"unread",
|
|
1552
|
+
"archived",
|
|
1553
|
+
"state",
|
|
1554
|
+
"event_types",
|
|
1555
|
+
"starred",
|
|
1556
|
+
"trashed",
|
|
1557
|
+
"permission"
|
|
1558
|
+
]);
|
|
1559
|
+
var CEAL_RESOURCE_SEARCH_STATES = vocabulary(["open", "closed", "draft", "prerelease", "confirmed", "tentative", "cancelled"]);
|
|
1254
1560
|
var CEAL_RESOURCE_TIME_BASES = vocabulary(["created", "modified", "viewed"]);
|
|
1255
1561
|
var CEAL_REPOSITORY_VISIBILITIES = vocabulary(["public", "private", "internal"]);
|
|
1256
1562
|
var CEAL_ACTIVITY_V3_KINDS = vocabulary(["authored", "edited", "messaged", "responded"]);
|
|
@@ -1346,6 +1652,8 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
|
|
|
1346
1652
|
container_label: { required: true, timestamp: false },
|
|
1347
1653
|
container_ref: { required: false, timestamp: false },
|
|
1348
1654
|
source_url: { required: false, timestamp: false },
|
|
1655
|
+
thread_ref: { required: false, timestamp: false },
|
|
1656
|
+
reply_count: { required: false, timestamp: false },
|
|
1349
1657
|
source: { required: true, timestamp: false },
|
|
1350
1658
|
owner: { required: false, timestamp: false },
|
|
1351
1659
|
actor_kind: { required: false, timestamp: false },
|
|
@@ -1354,6 +1662,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
|
|
|
1354
1662
|
created_at: { required: false, timestamp: true },
|
|
1355
1663
|
created_at_local: { required: false, timestamp: true },
|
|
1356
1664
|
modified_at: { required: false, timestamp: true },
|
|
1665
|
+
observed_at: { required: false, timestamp: true },
|
|
1357
1666
|
modified_at_local: { required: false, timestamp: true },
|
|
1358
1667
|
viewed_by_me_at: { required: false, timestamp: true },
|
|
1359
1668
|
modified_by_me_at: { required: false, timestamp: true },
|
|
@@ -1371,6 +1680,7 @@ var RESOURCE_ROW_KEY_RULES = Object.freeze({
|
|
|
1371
1680
|
start: { required: false, timestamp: false },
|
|
1372
1681
|
end: { required: false, timestamp: false },
|
|
1373
1682
|
status: { required: false, timestamp: false },
|
|
1683
|
+
event_type: { required: false, timestamp: false },
|
|
1374
1684
|
snippet: { required: false, timestamp: false },
|
|
1375
1685
|
dated_notes: { required: false, timestamp: false },
|
|
1376
1686
|
state: { required: true, timestamp: false },
|
|
@@ -1380,9 +1690,6 @@ var RESOURCE_ROW_REQUIRED_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(
|
|
|
1380
1690
|
var RESOURCE_ROW_KEYS = new Set(Object.keys(RESOURCE_ROW_KEY_RULES));
|
|
1381
1691
|
var RESOURCE_ROW_TIMESTAMP_KEYS = Object.entries(RESOURCE_ROW_KEY_RULES).flatMap(([key, rule]) => rule.timestamp ? [key] : []);
|
|
1382
1692
|
|
|
1383
|
-
// packages/ceal-client-protocol/src/resource-read-result.ts
|
|
1384
|
-
var CEAL_RESOURCE_GET_COVERAGE_NEXT_ACTIONS = vocabulary(["reduce_request_size", "read_resource_again"]);
|
|
1385
|
-
|
|
1386
1693
|
// packages/ceal-client-protocol/src/excluded-target-coverage.ts
|
|
1387
1694
|
var CEAL_EXCLUDED_TARGET_COVERAGE_MAX_ENTRIES = 64;
|
|
1388
1695
|
function cealExcludedTargetCoverageJsonSchema() {
|
|
@@ -1434,6 +1741,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
|
|
|
1434
1741
|
"refresh_inactive",
|
|
1435
1742
|
"refresh_replayed",
|
|
1436
1743
|
"refresh_revoked",
|
|
1744
|
+
"person_inactive",
|
|
1745
|
+
"principal_inactive",
|
|
1437
1746
|
"authority_replaced",
|
|
1438
1747
|
"refresh_recovery_unavailable",
|
|
1439
1748
|
"refresh_recovery_expired",
|
|
@@ -1454,97 +1763,6 @@ var PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN = "[A-Za-z0-9_-]{43}";
|
|
|
1454
1763
|
var CEAL_PERSONAL_CLIENT_ACCESS_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_ACCESS_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
|
|
1455
1764
|
var CEAL_PERSONAL_CLIENT_REFRESH_TOKEN = new RegExp(`^${CEAL_PERSONAL_CLIENT_REFRESH_TOKEN_PREFIX}${PERSONAL_CLIENT_TOKEN_SUFFIX_PATTERN}$`, "u");
|
|
1456
1765
|
|
|
1457
|
-
// packages/ceal-client-protocol/src/request-validation-primitives.ts
|
|
1458
|
-
import { createHash as createHash3 } from "node:crypto";
|
|
1459
|
-
var DIGEST = /^[a-f0-9]{64}$/u;
|
|
1460
|
-
var CEAL_SHA256_DIGEST_PATTERN = DIGEST.source;
|
|
1461
|
-
function isCealDigest(value) {
|
|
1462
|
-
return typeof value === "string" && DIGEST.test(value);
|
|
1463
|
-
}
|
|
1464
|
-
function cealRequestSha256(value) {
|
|
1465
|
-
return createHash3("sha256").update(cealCanonicalJson(value), "utf8").digest("hex");
|
|
1466
|
-
}
|
|
1467
|
-
function operationRecord(value, message) {
|
|
1468
|
-
requireOperationRecord(value, message);
|
|
1469
|
-
return value;
|
|
1470
|
-
}
|
|
1471
|
-
function invalid(message) {
|
|
1472
|
-
throw new TypeError(message);
|
|
1473
|
-
}
|
|
1474
|
-
function requirePrefixedRef(value, prefix, message) {
|
|
1475
|
-
if (typeof value !== "string" || !SAFE_REF.test(value) || !value.startsWith(prefix)) invalid(message);
|
|
1476
|
-
}
|
|
1477
|
-
|
|
1478
|
-
// packages/ceal-client-protocol/src/request-authority.ts
|
|
1479
|
-
var CEAL_REQUEST_SCHEMA_VERSION = "ceal.request.v1";
|
|
1480
|
-
var CEAL_REQUEST_ARTIFACT_OWNERS = vocabulary(["gateway", "host", "connector"]);
|
|
1481
|
-
var CEAL_HOST_INVOCATION_IDENTITY_KEYS = vocabulary(["host_session_ref", "host_turn_ref", "host_source_ref"]);
|
|
1482
|
-
var CEAL_REQUEST_ARTIFACT_RETENTION_CLASSES = vocabulary(["request", "source", "result"]);
|
|
1483
|
-
var CANCELLATION_STATES = vocabulary(["requested", "cancelled"]);
|
|
1484
|
-
var CEAL_REQUEST_KEYS = Object.freeze(["schema_version", "ceal_request_ref", "created_at", "authority"]);
|
|
1485
|
-
var CEAL_REQUEST_COMMON_PROPERTIES = Object.freeze({
|
|
1486
|
-
schema_version: { type: "string", const: CEAL_REQUEST_SCHEMA_VERSION, maxLength: 32 },
|
|
1487
|
-
ceal_request_ref: { type: "string", minLength: 1, maxLength: 128, pattern: "^ceal-request:[A-Za-z0-9][A-Za-z0-9._:-]{0,114}$" },
|
|
1488
|
-
created_at: { type: "string", minLength: 1, maxLength: 64 },
|
|
1489
|
-
authority: {
|
|
1490
|
-
type: "object",
|
|
1491
|
-
maxProperties: 5,
|
|
1492
|
-
additionalProperties: false,
|
|
1493
|
-
properties: {
|
|
1494
|
-
instance_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1495
|
-
access_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1496
|
-
principal_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1497
|
-
execution_subject_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1498
|
-
authority_revision_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
|
|
1499
|
-
},
|
|
1500
|
-
required: ["instance_ref", "access_group_ref", "principal_ref", "execution_subject_ref", "authority_revision_ref"]
|
|
1501
|
-
}
|
|
1502
|
-
});
|
|
1503
|
-
var CEAL_REQUEST_HOST_PROPERTIES = Object.freeze({
|
|
1504
|
-
prompt_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1505
|
-
host_session_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1506
|
-
host_turn_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1507
|
-
host_input_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source },
|
|
1508
|
-
host_source_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source }
|
|
1509
|
-
});
|
|
1510
|
-
var CEAL_REQUEST_CALLER_PROPERTIES = Object.freeze({
|
|
1511
|
-
caller_call_group_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Gateway-minted call-group identity for a non-Host caller." },
|
|
1512
|
-
caller_call_input_sha256: { type: "string", minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$", description: "Commitment to the exact input for active non-Host identity-reuse checks; a migrated legacy call group commits to its legacy group key because the original input may no longer exist." }
|
|
1513
|
-
});
|
|
1514
|
-
var CEAL_REQUEST_OPTIONAL_PROPERTIES = Object.freeze({
|
|
1515
|
-
requester_timezone: { type: "string", minLength: 1, maxLength: 128, description: "IANA timezone observed for the requester on this Request." },
|
|
1516
|
-
device_ref: { type: "string", minLength: 1, maxLength: 128, pattern: SAFE_REF.source, description: "Device that submitted this Request through its client session, including Host turns when the authenticated Host registration carries the device; absent for older records." }
|
|
1517
|
-
});
|
|
1518
|
-
var CEAL_REQUEST_HOST_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, ...CEAL_HOST_INVOCATION_IDENTITY_KEYS, "prompt_ref"]);
|
|
1519
|
-
var CEAL_REQUEST_CALLER_REQUIRED_KEYS = Object.freeze([...CEAL_REQUEST_KEYS, "caller_call_group_ref", "caller_call_input_sha256"]);
|
|
1520
|
-
var CEAL_REQUEST_JSON_SCHEMA = {
|
|
1521
|
-
type: "object",
|
|
1522
|
-
description: "A Request has exactly one creation identity: the complete Host tuple and prompt reference, or a caller call-group identity. Caller Requests retain no prompt reference or prompt body.",
|
|
1523
|
-
maxProperties: 13,
|
|
1524
|
-
additionalProperties: false,
|
|
1525
|
-
properties: {
|
|
1526
|
-
...CEAL_REQUEST_COMMON_PROPERTIES,
|
|
1527
|
-
...CEAL_REQUEST_HOST_PROPERTIES,
|
|
1528
|
-
...CEAL_REQUEST_CALLER_PROPERTIES,
|
|
1529
|
-
...CEAL_REQUEST_OPTIONAL_PROPERTIES
|
|
1530
|
-
},
|
|
1531
|
-
required: CEAL_REQUEST_KEYS,
|
|
1532
|
-
anyOf: [
|
|
1533
|
-
{
|
|
1534
|
-
type: "object",
|
|
1535
|
-
required: CEAL_REQUEST_HOST_REQUIRED_KEYS,
|
|
1536
|
-
properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_HOST_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
|
|
1537
|
-
additionalProperties: false
|
|
1538
|
-
},
|
|
1539
|
-
{
|
|
1540
|
-
type: "object",
|
|
1541
|
-
required: CEAL_REQUEST_CALLER_REQUIRED_KEYS,
|
|
1542
|
-
properties: { ...CEAL_REQUEST_COMMON_PROPERTIES, ...CEAL_REQUEST_CALLER_PROPERTIES, ...CEAL_REQUEST_OPTIONAL_PROPERTIES },
|
|
1543
|
-
additionalProperties: false
|
|
1544
|
-
}
|
|
1545
|
-
]
|
|
1546
|
-
};
|
|
1547
|
-
|
|
1548
1766
|
// packages/ceal-client-protocol/src/request-operands.ts
|
|
1549
1767
|
var CEAL_REQUEST_MAX_RESOLVER_SELECTIONS = 128;
|
|
1550
1768
|
var CEAL_REQUEST_MAX_SELECTOR_PROPERTIES = 16;
|
|
@@ -1652,6 +1870,27 @@ var CEAL_REQUEST_RUN_BATCH_JSON_SCHEMA = {
|
|
|
1652
1870
|
required: ["schema_version", "order", "nodes", "call_budget"]
|
|
1653
1871
|
};
|
|
1654
1872
|
|
|
1873
|
+
// packages/ceal-client-protocol/src/host-observation-validation.ts
|
|
1874
|
+
var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
|
|
1875
|
+
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;
|
|
1876
|
+
function validateCealHostObservationValue(value) {
|
|
1877
|
+
if (value === void 0) throw new TypeError("Ceal Host observation value is invalid.");
|
|
1878
|
+
assertSafeJsonValue(value, { forbidAuthorityKeys: true, maxNodes: 512 });
|
|
1879
|
+
if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) throw new TypeError("Ceal Host observation value is oversized.");
|
|
1880
|
+
inspectHostKeys(value);
|
|
1881
|
+
}
|
|
1882
|
+
function inspectHostKeys(value) {
|
|
1883
|
+
if (Array.isArray(value)) {
|
|
1884
|
+
for (const entry of value) inspectHostKeys(entry);
|
|
1885
|
+
return;
|
|
1886
|
+
}
|
|
1887
|
+
if (value === null || typeof value !== "object") return;
|
|
1888
|
+
for (const [key, child] of Object.entries(value)) {
|
|
1889
|
+
if (HOST_RESERVED_KEY.test(key)) throw new TypeError("Ceal Host observation cannot restate Gateway-owned facts.");
|
|
1890
|
+
inspectHostKeys(child);
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1655
1894
|
// packages/ceal-client-protocol/src/host-observation.ts
|
|
1656
1895
|
var CEAL_HOST_OBSERVATION_REF_PREFIX = "host-observation:";
|
|
1657
1896
|
var HOST_OBSERVATION_PRODUCER = /^[a-z][a-z0-9]{0,31}$/u;
|
|
@@ -1698,35 +1937,238 @@ function safeCount(value) {
|
|
|
1698
1937
|
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
1699
1938
|
}
|
|
1700
1939
|
function validateCealHostObservationDraft(value) {
|
|
1701
|
-
const
|
|
1702
|
-
requirePrefixedRef(
|
|
1703
|
-
requireClosedValue(
|
|
1704
|
-
requireIsoTimestamp(
|
|
1705
|
-
assertHostObservationValue(
|
|
1940
|
+
const record2 = operationRecord(value, "Ceal Host observation draft is invalid.");
|
|
1941
|
+
requirePrefixedRef(record2.observation_ref, CEAL_HOST_OBSERVATION_REF_PREFIX, "Ceal Host observation reference is invalid.");
|
|
1942
|
+
requireClosedValue(record2.observation_kind, CEAL_HOST_OBSERVATION_KINDS, "Ceal Host observation kind is invalid.");
|
|
1943
|
+
requireIsoTimestamp(record2.observed_at, "Ceal Host observation time is invalid.");
|
|
1944
|
+
assertHostObservationValue(record2.value, record2.observation_kind);
|
|
1706
1945
|
}
|
|
1707
|
-
var CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES = 64 * 1024;
|
|
1708
1946
|
var CEAL_HOST_OBSERVATION_KINDS = vocabulary(["prompt", "session", "turn", "model", "token", "timing"]);
|
|
1709
1947
|
function isCealHostPromptObservationValue(value) {
|
|
1710
1948
|
return isOperationRecord(value) && Object.keys(value).length === 1 && isCealDigest(value.body_sha256);
|
|
1711
1949
|
}
|
|
1712
|
-
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;
|
|
1713
1950
|
function assertHostObservationValue(value, kind) {
|
|
1714
1951
|
if (value === void 0) invalid("Ceal Host observation value is invalid.");
|
|
1715
1952
|
if (kind === "prompt" && !isCealHostPromptObservationValue(value)) invalid("Ceal Host prompt observation must contain only its body digest.");
|
|
1716
|
-
|
|
1717
|
-
if (byteLength(JSON.stringify(value) ?? "") > CEAL_REQUEST_MAX_OBSERVATION_VALUE_BYTES) invalid("Ceal Host observation value is oversized.");
|
|
1718
|
-
inspectHostKeys(value);
|
|
1953
|
+
validateCealHostObservationValue(value);
|
|
1719
1954
|
}
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1955
|
+
|
|
1956
|
+
// packages/ceal-client-protocol/src/host-usage-facts.ts
|
|
1957
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
1958
|
+
var CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION = "ceal.host_usage_batch.v1";
|
|
1959
|
+
var CEAL_HOST_USAGE_BATCH_REF_PREFIX = "host-usage-batch:";
|
|
1960
|
+
var CEAL_HOST_USAGE_INGRESS_PATH = "/api/ceal/v2/host-usage-batches";
|
|
1961
|
+
var CEAL_HOST_USAGE_BATCH_MAX_BYTES = 1024 * 1024;
|
|
1962
|
+
var CEAL_HOST_USAGE_FACT_MAX_BYTES = 64 * 1024;
|
|
1963
|
+
var CEAL_HOST_USAGE_BATCH_MAX_FACTS = 256;
|
|
1964
|
+
var CEAL_HOST_USAGE_BATCH_MAX_GAPS = 16;
|
|
1965
|
+
var CEAL_HOST_USAGE_BATCH_ACK_STATUS = 204;
|
|
1966
|
+
var CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES = 65;
|
|
1967
|
+
var CODEX_COUNTER_SEMANTICS = ["last_delta_total_cumulative", "total_cumulative_only", "unknown"];
|
|
1968
|
+
var CODEX_CUMULATIVE_TRANSITIONS = ["baseline", "advanced", "same", "reset_or_correction", "not_observed"];
|
|
1969
|
+
var HOST_USAGE_COVERAGE_GAP_REASONS = ["source_usage_unavailable", "source_file_replaced", "source_file_retired", "outbox_capacity", "unsupported_source_shape"];
|
|
1970
|
+
function createCealHostUsageBatch(input) {
|
|
1971
|
+
const body = { schema_version: CEAL_HOST_USAGE_BATCH_SCHEMA_VERSION, ...input };
|
|
1972
|
+
const batch = { ...body, batch_ref: `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}` };
|
|
1973
|
+
validateCealHostUsageBatch(batch);
|
|
1974
|
+
return batch;
|
|
1975
|
+
}
|
|
1976
|
+
function validateCealHostUsageBatch(value) {
|
|
1977
|
+
if (!isOperationRecord(value)) invalid("Ceal Host usage batch is invalid.");
|
|
1978
|
+
requireExactOperationKeys(value, ["schema_version", "batch_ref", "host_source_ref", "host_session_ref", "created_at", "source_ranges", "facts", "coverage_gaps"]);
|
|
1979
|
+
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.");
|
|
1980
|
+
const { batch_ref: _ref, ...body } = value;
|
|
1981
|
+
if (value.batch_ref !== `${CEAL_HOST_USAGE_BATCH_REF_PREFIX}${sha256(JSON.stringify(body))}`) invalid("Ceal Host usage batch reference is invalid.");
|
|
1982
|
+
validateBatchMetadata(value);
|
|
1983
|
+
validateBatchContents(value);
|
|
1984
|
+
if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_BATCH_MAX_BYTES) invalid("Ceal Host usage batch exceeds its byte limit.");
|
|
1985
|
+
}
|
|
1986
|
+
function validateBatchMetadata(value) {
|
|
1987
|
+
requireSafeRef2(value.host_source_ref, "Ceal Host usage source is invalid.");
|
|
1988
|
+
requireSafeRef2(value.host_session_ref, "Ceal Host usage session is invalid.");
|
|
1989
|
+
requireIsoTimestamp(value.created_at, "Ceal Host usage batch time is invalid.");
|
|
1990
|
+
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.");
|
|
1991
|
+
for (const range of value.source_ranges) validateSourceRange(range);
|
|
1992
|
+
}
|
|
1993
|
+
function validateBatchContents(value) {
|
|
1994
|
+
const facts = validateBatchFacts(value.facts);
|
|
1995
|
+
const gaps = validateBatchGaps(value.coverage_gaps);
|
|
1996
|
+
if (facts.length === 0 && gaps.length === 0 || facts.length > 0 && value.source_ranges.length === 0) invalid("Ceal Host usage coverage is invalid.");
|
|
1997
|
+
const sourceFiles = new Set(value.source_ranges.map((range) => sourceRangeFileRef(range)));
|
|
1998
|
+
for (const fact of facts) {
|
|
1999
|
+
validateCealHostUsageFact(fact, value.host_session_ref);
|
|
2000
|
+
if (!sourceFiles.has(fact.source_file_ref)) invalid("Ceal Host usage fact is outside its source ranges.");
|
|
2001
|
+
}
|
|
2002
|
+
for (const gap of gaps) {
|
|
2003
|
+
validateCoverageGap(gap);
|
|
2004
|
+
if (gap.source_file_ref !== null && !sourceFiles.has(gap.source_file_ref)) invalid("Ceal Host usage coverage gap is outside its source ranges.");
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
function validateBatchFacts(value) {
|
|
2008
|
+
if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_FACTS) invalid("Ceal Host usage fact count is invalid.");
|
|
2009
|
+
return value;
|
|
2010
|
+
}
|
|
2011
|
+
function validateBatchGaps(value) {
|
|
2012
|
+
if (!Array.isArray(value) || value.length > CEAL_HOST_USAGE_BATCH_MAX_GAPS) invalid("Ceal Host usage coverage is invalid.");
|
|
2013
|
+
return value;
|
|
2014
|
+
}
|
|
2015
|
+
function sourceRangeFileRef(value) {
|
|
2016
|
+
return isOperationRecord(value) ? value.source_file_ref : null;
|
|
2017
|
+
}
|
|
2018
|
+
function hostUsageFactReference(sourceFileRef, sourceEventRef) {
|
|
2019
|
+
requireSafeRef2(sourceFileRef, "Ceal Host usage file reference is invalid.");
|
|
2020
|
+
requireSafeRef2(sourceEventRef, "Ceal Host usage event reference is invalid.");
|
|
2021
|
+
return `host-usage-fact:${sha256(JSON.stringify({ source_file_ref: sourceFileRef, source_event_ref: sourceEventRef }))}`;
|
|
2022
|
+
}
|
|
2023
|
+
function hostUsageSourceEventReference(sourceFileRef, sourceEventIdentity) {
|
|
2024
|
+
requireSafeRef2(sourceFileRef, "Ceal Host usage file reference is invalid.");
|
|
2025
|
+
if (typeof sourceEventIdentity !== "string" || sourceEventIdentity.length === 0 || sourceEventIdentity.length > 1024) invalid("Ceal Host usage event identity is invalid.");
|
|
2026
|
+
return `host-source-event:${sha256(JSON.stringify({ source_file_ref: sourceFileRef, source_event_identity: sourceEventIdentity }))}`;
|
|
2027
|
+
}
|
|
2028
|
+
function hostUsageSourceFileReference(producer, hostSourceRef, hostSessionRef, device, inode) {
|
|
2029
|
+
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.");
|
|
2030
|
+
return `host-source-file:${sha256(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef, device, inode }))}`;
|
|
2031
|
+
}
|
|
2032
|
+
function validateCealHostUsageFact(value, sessionRef) {
|
|
2033
|
+
if (!isOperationRecord(value)) invalid("Ceal Host usage fact is invalid.");
|
|
2034
|
+
requireFactByteLimit(value);
|
|
2035
|
+
if (value.producer === "codex_transcript") validateCodexFact(value);
|
|
2036
|
+
else if (value.producer === "claude_transcript") validateClaudeFact(value);
|
|
2037
|
+
else invalid("Ceal Host usage producer is invalid.");
|
|
2038
|
+
if (value.host_session_ref !== sessionRef) invalid("Ceal Host usage session does not match its batch.");
|
|
2039
|
+
requireSafeRef2(value.source_file_ref, "Ceal Host usage file reference is invalid.");
|
|
2040
|
+
requireSafeRef2(value.source_event_ref, "Ceal Host usage event reference is invalid.");
|
|
2041
|
+
if (value.host_turn_ref !== null) requireSafeRef2(value.host_turn_ref, "Ceal Host usage turn reference is invalid.");
|
|
2042
|
+
if (value.requested_model !== null && !boundedText(value.requested_model, 256)) invalid("Ceal Host requested model is invalid.");
|
|
2043
|
+
if (value.reported_model !== null && !boundedText(value.reported_model, 256)) invalid("Ceal Host reported model is invalid.");
|
|
2044
|
+
if (value.fact_ref !== hostUsageFactReference(value.source_file_ref, value.source_event_ref)) invalid("Ceal Host usage identity is invalid.");
|
|
2045
|
+
}
|
|
2046
|
+
function requireFactByteLimit(value) {
|
|
2047
|
+
if (Buffer.byteLength(JSON.stringify(value), "utf8") > CEAL_HOST_USAGE_FACT_MAX_BYTES) invalid("Ceal Host usage fact exceeds its byte limit.");
|
|
2048
|
+
}
|
|
2049
|
+
function validateCodexFact(value) {
|
|
2050
|
+
if (!isOperationRecord(value)) invalid("Ceal Codex usage fact is invalid.");
|
|
2051
|
+
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"]);
|
|
2052
|
+
if (value.producer !== "codex_transcript" || !safeInteger(value.source_event_ordinal)) invalid("Ceal Codex usage fact is invalid.");
|
|
2053
|
+
requireIsoTimestamp(value.observed_at, "Ceal Codex usage time is invalid.");
|
|
2054
|
+
if (!isOperationRecord(value.source_usage)) invalid("Ceal Codex source usage is invalid.");
|
|
2055
|
+
requireExactOperationKeys(value.source_usage, ["last_token_usage", "total_token_usage"]);
|
|
2056
|
+
if (value.source_usage.last_token_usage !== null) validateCodexUsageCounts(value.source_usage.last_token_usage);
|
|
2057
|
+
if (value.source_usage.total_token_usage !== null) validateCodexUsageCounts(value.source_usage.total_token_usage);
|
|
2058
|
+
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.");
|
|
2059
|
+
validateNormalizedUsage(value.normalized_usage);
|
|
2060
|
+
}
|
|
2061
|
+
function validateClaudeFact(value) {
|
|
2062
|
+
if (!isOperationRecord(value)) invalid("Ceal Claude usage fact is invalid.");
|
|
2063
|
+
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"]);
|
|
2064
|
+
validateClaudeIdentity(value);
|
|
2065
|
+
requireIsoTimestamp(value.observed_at, "Ceal Claude usage time is invalid.");
|
|
2066
|
+
validateClaudeSourceUsage(value.source_usage);
|
|
2067
|
+
validateClaudeSemantics(value);
|
|
2068
|
+
validateNormalizedUsage(value.normalized_usage);
|
|
2069
|
+
}
|
|
2070
|
+
function validateClaudeIdentity(value) {
|
|
2071
|
+
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.");
|
|
2072
|
+
}
|
|
2073
|
+
function validateClaudeSourceUsage(value) {
|
|
2074
|
+
if (!isOperationRecord(value)) invalid("Ceal Claude source usage is invalid.");
|
|
2075
|
+
requireExactOperationKeys(value, ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"], ["cache_creation"]);
|
|
2076
|
+
for (const key of ["input_tokens", "output_tokens"]) if (!safeInteger(value[key])) invalid("Ceal Claude source usage is invalid.");
|
|
2077
|
+
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.");
|
|
2078
|
+
if (value.cache_creation !== void 0 && value.cache_creation !== null) validateClaudeCacheCreationUsage(value.cache_creation);
|
|
2079
|
+
}
|
|
2080
|
+
function validateClaudeCacheCreationUsage(value) {
|
|
2081
|
+
if (!isOperationRecord(value)) invalid("Ceal Claude cache creation usage is invalid.");
|
|
2082
|
+
requireExactOperationKeys(value, ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"]);
|
|
2083
|
+
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.");
|
|
2084
|
+
}
|
|
2085
|
+
function validateClaudeSemantics(value) {
|
|
2086
|
+
if (value.counter_semantics !== "assistant_message" || !validClaudeFinality(value.finality) || value.child_inclusion !== "unknown" || !validCorrectionSemantics(value.correction_semantics)) invalid("Ceal Claude usage semantics are invalid.");
|
|
2087
|
+
}
|
|
2088
|
+
function validClaudeFinality(value) {
|
|
2089
|
+
return value === "terminal" || value === "nonterminal" || value === "unknown";
|
|
2090
|
+
}
|
|
2091
|
+
function validCorrectionSemantics(value) {
|
|
2092
|
+
return value === "not_observed" || value === "unknown";
|
|
2093
|
+
}
|
|
2094
|
+
function validateCodexUsageCounts(value) {
|
|
2095
|
+
if (!isOperationRecord(value)) invalid("Ceal Codex usage fields are invalid.");
|
|
2096
|
+
requireExactOperationKeys(value, CEAL_CODEX_USAGE_COUNT_FIELDS);
|
|
2097
|
+
for (const key of Object.keys(value)) if (!safeInteger(value[key])) invalid("Ceal Codex usage fields are invalid.");
|
|
2098
|
+
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.");
|
|
2099
|
+
}
|
|
2100
|
+
function validateNormalizedUsage(value) {
|
|
2101
|
+
if (!isOperationRecord(value)) invalid("Ceal normalized Host usage is invalid.");
|
|
2102
|
+
requireExactOperationKeys(value, ["input", "output", "total", "cached_input", "cache_write_input", "reasoning_output"]);
|
|
2103
|
+
for (const key of Object.keys(value)) if (value[key] !== null && !safeInteger(value[key])) invalid("Ceal normalized Host usage is invalid.");
|
|
2104
|
+
validateNormalizedTotals(value);
|
|
2105
|
+
}
|
|
2106
|
+
function validateNormalizedTotals(value) {
|
|
2107
|
+
validateNormalizedCountTotal(value);
|
|
2108
|
+
validateNormalizedInputSubsets(value);
|
|
2109
|
+
validateNormalizedOutputSubset(value);
|
|
2110
|
+
}
|
|
2111
|
+
function validateNormalizedCountTotal(value) {
|
|
2112
|
+
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.");
|
|
2113
|
+
}
|
|
2114
|
+
function validateNormalizedInputSubsets(value) {
|
|
2115
|
+
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.");
|
|
2116
|
+
}
|
|
2117
|
+
function validateNormalizedOutputSubset(value) {
|
|
2118
|
+
if (value.output !== null && value.reasoning_output !== null && Number(value.reasoning_output) > Number(value.output)) invalid("Ceal normalized Host output subset is inconsistent.");
|
|
2119
|
+
}
|
|
2120
|
+
function validateSourceRange(value) {
|
|
2121
|
+
if (!isOperationRecord(value)) invalid("Ceal Host usage source range is invalid.");
|
|
2122
|
+
requireExactOperationKeys(value, ["source_file_ref", "start_offset", "end_offset"]);
|
|
2123
|
+
requireSafeRef2(value.source_file_ref, "Ceal Host usage source-file reference is invalid.");
|
|
2124
|
+
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.");
|
|
2125
|
+
}
|
|
2126
|
+
function validateCealHostUsageCoverageGap(value) {
|
|
2127
|
+
if (!isOperationRecord(value)) invalid("Ceal Host usage coverage gap is invalid.");
|
|
2128
|
+
requireExactOperationKeys(value, ["reason", "source_file_ref", "start_offset", "end_offset", "omitted_count"]);
|
|
2129
|
+
if (!isOneOf(HOST_USAGE_COVERAGE_GAP_REASONS, value.reason) || !validUsageGapCount(value.reason, value.omitted_count)) invalid("Ceal Host usage coverage gap is invalid.");
|
|
2130
|
+
if (value.source_file_ref === null) {
|
|
2131
|
+
if (value.start_offset !== null || value.end_offset !== null) invalid("Ceal Host usage coverage gap range is invalid.");
|
|
1723
2132
|
return;
|
|
1724
2133
|
}
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
2134
|
+
requireSafeRef2(value.source_file_ref, "Ceal Host usage coverage file reference is invalid.");
|
|
2135
|
+
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.");
|
|
2136
|
+
}
|
|
2137
|
+
function validateCoverageGap(value) {
|
|
2138
|
+
validateCealHostUsageCoverageGap(value);
|
|
2139
|
+
}
|
|
2140
|
+
function validUsageGapCount(reason, value) {
|
|
2141
|
+
return value === null ? reason !== "outbox_capacity" : safeInteger(value) && Number(value) >= 1;
|
|
2142
|
+
}
|
|
2143
|
+
function isOneOf(values, value) {
|
|
2144
|
+
return typeof value === "string" && values.some((candidate) => candidate === value);
|
|
2145
|
+
}
|
|
2146
|
+
function isCealHostUsageBatchReference(value) {
|
|
2147
|
+
return typeof value === "string" && value.startsWith(CEAL_HOST_USAGE_BATCH_REF_PREFIX) && isCealDigest(value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length));
|
|
2148
|
+
}
|
|
2149
|
+
function cealHostUsageBatchObjectDigestFromFileName(value) {
|
|
2150
|
+
if (!value.endsWith(".json")) return null;
|
|
2151
|
+
const digest2 = value.slice(0, -5);
|
|
2152
|
+
return isCealDigest(digest2) ? digest2 : null;
|
|
2153
|
+
}
|
|
2154
|
+
function cealHostUsageBatchObjectDigestFromReference(value) {
|
|
2155
|
+
return isCealHostUsageBatchReference(value) ? value.slice(CEAL_HOST_USAGE_BATCH_REF_PREFIX.length) : null;
|
|
2156
|
+
}
|
|
2157
|
+
function safeInteger(value) {
|
|
2158
|
+
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
2159
|
+
}
|
|
2160
|
+
function boundedText(value, maximum) {
|
|
2161
|
+
return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maximum && !hasControlCharacters(value);
|
|
2162
|
+
}
|
|
2163
|
+
function hasControlCharacters(value) {
|
|
2164
|
+
for (const character of value) {
|
|
2165
|
+
const code = character.codePointAt(0);
|
|
2166
|
+
if (code !== void 0 && (code < 32 || code === 127)) return true;
|
|
1729
2167
|
}
|
|
2168
|
+
return false;
|
|
2169
|
+
}
|
|
2170
|
+
function sha256(value) {
|
|
2171
|
+
return createHash4("sha256").update(value, "utf8").digest("hex");
|
|
1730
2172
|
}
|
|
1731
2173
|
|
|
1732
2174
|
// packages/ceal-client-protocol/src/host-prompt-ref.ts
|
|
@@ -1833,11 +2275,72 @@ var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_SCHEMA = deriveCealClientWireSch
|
|
|
1833
2275
|
var CEAL_HOST_INVOCATION_AUTHENTICATION_REQUEST_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.request_fields]);
|
|
1834
2276
|
var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.result_schema_name, fields: hostInvocationAuthenticationContract.result_fields });
|
|
1835
2277
|
var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_FIELDS = Object.freeze([...hostInvocationAuthenticationContract.result_fields]);
|
|
2278
|
+
var CEAL_HOST_INVOCATION_AUTHENTICATION_REFUSAL_SCHEMA = deriveCealClientWireSchemaVersion({ schema_name: hostInvocationAuthenticationContract.refusal_schema_name, fields: hostInvocationAuthenticationContract.refusal_fields });
|
|
1836
2279
|
var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE = "^(?:0|[1-9][0-9]{0,8})$";
|
|
1837
2280
|
var CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN = new RegExp(CEAL_HOST_AUTHENTICATION_BUDGET_PATTERN_SOURCE, "u");
|
|
1838
2281
|
var CEAL_HOST_INVOCATION_CONTEXT_REQUEST_MAX_BYTES = 16 * 1024;
|
|
1839
2282
|
var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES = 2 * 1024;
|
|
2283
|
+
var CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES = 32;
|
|
1840
2284
|
var CEAL_HOST_CONTEXT_TOKEN_PREFIX = "ceal_context_";
|
|
2285
|
+
function boundCealHostInvocationHumanMessageWindow(newestFirst, sourceTruncated = false) {
|
|
2286
|
+
const messages = [];
|
|
2287
|
+
let truncated = sourceTruncated || newestFirst.length > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES;
|
|
2288
|
+
for (const candidate of newestFirst.slice(0, CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_MESSAGES)) {
|
|
2289
|
+
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 } : {} };
|
|
2290
|
+
if (encodedMessageWindowBytes([...messages, complete]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) {
|
|
2291
|
+
messages.push(Object.freeze(complete));
|
|
2292
|
+
continue;
|
|
2293
|
+
}
|
|
2294
|
+
const clipped = clipHumanMessageToWindow(messages, candidate);
|
|
2295
|
+
if (clipped === null) {
|
|
2296
|
+
truncated = true;
|
|
2297
|
+
break;
|
|
2298
|
+
}
|
|
2299
|
+
messages.push(Object.freeze(clipped));
|
|
2300
|
+
}
|
|
2301
|
+
return Object.freeze({ messages: Object.freeze(messages), truncated });
|
|
2302
|
+
}
|
|
2303
|
+
function encodedMessageWindowBytes(messages) {
|
|
2304
|
+
return new TextEncoder().encode(JSON.stringify(messages)).byteLength;
|
|
2305
|
+
}
|
|
2306
|
+
function clipHumanMessageToWindow(prefix, candidate) {
|
|
2307
|
+
const clipped = { host_turn_ref: candidate.host_turn_ref, host_input_ref: candidate.host_input_ref, text: "", text_truncated: true };
|
|
2308
|
+
const available = CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES - encodedMessageWindowBytes([...prefix, clipped]);
|
|
2309
|
+
if (available < 0) return null;
|
|
2310
|
+
const text = [];
|
|
2311
|
+
let used = 0;
|
|
2312
|
+
for (const point of candidate.text) {
|
|
2313
|
+
const encodedPoint = JSON.stringify(point);
|
|
2314
|
+
const cost = new TextEncoder().encode(encodedPoint).byteLength - 2;
|
|
2315
|
+
if (used + cost > available) break;
|
|
2316
|
+
text.push(point);
|
|
2317
|
+
used += cost;
|
|
2318
|
+
}
|
|
2319
|
+
const result = { ...clipped, text: text.join("") };
|
|
2320
|
+
return encodedMessageWindowBytes([...prefix, result]) <= CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES ? result : null;
|
|
2321
|
+
}
|
|
2322
|
+
function decodeCealHostInvocationHumanMessageWindow(value) {
|
|
2323
|
+
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();
|
|
2324
|
+
const messages = value.messages.map(decodeHumanMessage);
|
|
2325
|
+
const bytes = new TextEncoder().encode(JSON.stringify(messages)).byteLength;
|
|
2326
|
+
if (bytes > CEAL_HOST_INVOCATION_HUMAN_MESSAGE_WINDOW_MAX_BYTES) throw invalidInvocationContextRequest();
|
|
2327
|
+
return Object.freeze({ messages: Object.freeze(messages), truncated: value.truncated });
|
|
2328
|
+
}
|
|
2329
|
+
function decodeHumanMessage(candidate) {
|
|
2330
|
+
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();
|
|
2331
|
+
if (candidate.text_truncated !== void 0 && candidate.text_truncated !== true) throw invalidInvocationContextRequest();
|
|
2332
|
+
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 } : {} });
|
|
2333
|
+
}
|
|
2334
|
+
function safeReference(value) {
|
|
2335
|
+
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
|
|
2336
|
+
}
|
|
2337
|
+
function exactOptionalKeys(value, required, optional = []) {
|
|
2338
|
+
const keys = Object.keys(value);
|
|
2339
|
+
return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => required.includes(key) || optional.includes(key));
|
|
2340
|
+
}
|
|
2341
|
+
function invalidInvocationContextRequest() {
|
|
2342
|
+
return new TypeError("The Host invocation context request is invalid.");
|
|
2343
|
+
}
|
|
1841
2344
|
function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTRACT) {
|
|
1842
2345
|
const clientNonce = contract.host_invocation_authentication.client_nonce;
|
|
1843
2346
|
return {
|
|
@@ -1847,40 +2350,20 @@ function deriveCealHostInvocationNonceContract(contract = CEAL_CLIENT_WIRE_CONTR
|
|
|
1847
2350
|
};
|
|
1848
2351
|
}
|
|
1849
2352
|
var hostNonceContract = deriveCealHostInvocationNonceContract();
|
|
1850
|
-
var CEAL_HOST_NONCE_ENCODED_CHARACTERS = hostNonceContract.encoded_characters;
|
|
1851
2353
|
var CEAL_HOST_CLIENT_NONCE_PATTERN = new RegExp(hostNonceContract.client_nonce_pattern_source, "u");
|
|
1852
2354
|
var CEAL_HOST_CONTEXT_TOKEN_PATTERN = new RegExp(hostNonceContract.context_token_pattern_source, "u");
|
|
1853
|
-
var CEAL_HOST_INVOCATION_AUTHENTICATION_RESULT_MAX_BYTES = deriveCealHostInvocationAuthenticationResultMaxBytes();
|
|
1854
|
-
function deriveCealHostInvocationAuthenticationResultMaxBytes(contract = CEAL_CLIENT_WIRE_CONTRACT) {
|
|
1855
|
-
const hostAuthentication = contract.host_invocation_authentication;
|
|
1856
|
-
const values = {
|
|
1857
|
-
schema_version: deriveCealClientWireSchemaVersion({ schema_name: hostAuthentication.result_schema_name, fields: hostAuthentication.result_fields }),
|
|
1858
|
-
context_token: `${CEAL_HOST_CONTEXT_TOKEN_PREFIX}${"A".repeat(hostAuthentication.client_nonce.encoded_characters)}`,
|
|
1859
|
-
expires_at: (/* @__PURE__ */ new Date("+010000-01-01T00:00:00.000Z")).toISOString()
|
|
1860
|
-
};
|
|
1861
|
-
const fields = hostAuthentication.result_fields;
|
|
1862
|
-
if (fields.some((field) => !Object.hasOwn(values, field))) throw new TypeError("Host invocation result fields have no bounded sample value.");
|
|
1863
|
-
return new TextEncoder().encode(`${JSON.stringify(Object.fromEntries(fields.map((field) => [field, values[field]])))}
|
|
1864
|
-
`).byteLength;
|
|
1865
|
-
}
|
|
1866
2355
|
var CEAL_HOST_MINT_REQUEST_CONTEXT_REFUSAL_REASONS = vocabulary([
|
|
1867
2356
|
"request_authority_unavailable",
|
|
1868
|
-
"
|
|
1869
|
-
"authority_mismatch",
|
|
1870
|
-
"host_source_mismatch",
|
|
1871
|
-
"host_session_mismatch",
|
|
1872
|
-
"host_turn_mismatch",
|
|
1873
|
-
"host_input_mismatch",
|
|
1874
|
-
"host_prompt_mismatch"
|
|
2357
|
+
"request_creation_refused"
|
|
1875
2358
|
]);
|
|
1876
2359
|
var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
|
|
1877
2360
|
"invalid_arguments",
|
|
1878
2361
|
"options_invalid",
|
|
1879
2362
|
"session_unavailable",
|
|
1880
2363
|
"context_unavailable",
|
|
2364
|
+
"activation_wait_exhausted",
|
|
1881
2365
|
"context_replaced",
|
|
1882
2366
|
"no_binding",
|
|
1883
|
-
"context_stale",
|
|
1884
2367
|
"context_expired",
|
|
1885
2368
|
"host_source_refused",
|
|
1886
2369
|
"host_credential_refused",
|
|
@@ -1897,23 +2380,35 @@ var CEAL_HOST_AUTHENTICATION_CAUSES = vocabulary([
|
|
|
1897
2380
|
"relay_failed",
|
|
1898
2381
|
"host_refusal_invalid"
|
|
1899
2382
|
]);
|
|
2383
|
+
var CEAL_HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
|
|
2384
|
+
"permission_denied",
|
|
2385
|
+
"socket_missing",
|
|
2386
|
+
"connection_refused",
|
|
2387
|
+
"closed_early",
|
|
2388
|
+
"response_invalid",
|
|
2389
|
+
"timed_out",
|
|
2390
|
+
"cancelled",
|
|
2391
|
+
"unavailable"
|
|
2392
|
+
]);
|
|
1900
2393
|
var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
1901
2394
|
invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
|
|
1902
2395
|
options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
|
|
1903
2396
|
session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
|
|
1904
|
-
|
|
1905
|
-
|
|
2397
|
+
// This reason cannot distinguish a Codex side conversation from a missing
|
|
2398
|
+
// context in a regular session, so guidance must leave that choice to the caller.
|
|
2399
|
+
context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
|
|
2400
|
+
activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
|
|
2401
|
+
context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
|
|
1906
2402
|
// `no_binding` now means the producer has no real current Host session. The
|
|
1907
2403
|
// Host Relay never uses it for an uncreated Gateway Request; there is no
|
|
1908
2404
|
// useful retry until the consumer is running inside a Host session.
|
|
1909
2405
|
no_binding: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
|
|
1910
|
-
|
|
1911
|
-
context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "retry" }),
|
|
2406
|
+
context_expired: Object.freeze({ classification: "host_invocation_context_expired", next_action: "answer_with_gap" }),
|
|
1912
2407
|
host_source_refused: Object.freeze({ classification: "host_source_refused", next_action: "answer_with_gap" }),
|
|
1913
2408
|
host_credential_refused: Object.freeze({ classification: "host_registration_credential_refused", next_action: "ask_admin" }),
|
|
1914
2409
|
gateway_unavailable: Object.freeze({ classification: "host_mint_gateway_unavailable", next_action: "ask_admin" }),
|
|
1915
2410
|
gateway_rate_limited: Object.freeze({ classification: "host_mint_gateway_rate_limited", next_action: "answer_with_gap" }),
|
|
1916
|
-
contract_mismatch: Object.freeze({ classification: "
|
|
2411
|
+
contract_mismatch: Object.freeze({ classification: "host_contract_mismatch", next_action: "upgrade_ceal_client" }),
|
|
1917
2412
|
gateway_refused: Object.freeze({ classification: "host_mint_gateway_refused", next_action: "answer_with_gap" }),
|
|
1918
2413
|
gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
|
|
1919
2414
|
producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
|
|
@@ -1921,7 +2416,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
|
1921
2416
|
relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
|
|
1922
2417
|
transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
|
|
1923
2418
|
mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
|
|
1924
|
-
relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "
|
|
2419
|
+
relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
|
|
1925
2420
|
host_refusal_invalid: Object.freeze({ classification: "host_refusal_invalid", next_action: "answer_with_gap" })
|
|
1926
2421
|
});
|
|
1927
2422
|
|
|
@@ -1935,10 +2430,13 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_EVENTS = vocabulary([
|
|
|
1935
2430
|
"activation_recorded",
|
|
1936
2431
|
"activation_failed",
|
|
1937
2432
|
"watcher_scan_failed",
|
|
2433
|
+
"usage_capture_failed",
|
|
2434
|
+
"usage_upload_failed",
|
|
1938
2435
|
"activation_wait_skipped",
|
|
1939
2436
|
"activation_wait_engaged",
|
|
1940
2437
|
"activation_wait_completed",
|
|
1941
|
-
"activation_wait_exhausted"
|
|
2438
|
+
"activation_wait_exhausted",
|
|
2439
|
+
"invocation_authentication_failed"
|
|
1942
2440
|
]);
|
|
1943
2441
|
var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
|
|
1944
2442
|
"malformed_line",
|
|
@@ -1948,11 +2446,22 @@ var CEAL_HOST_SERVICE_DIAGNOSTIC_FAILURE_KINDS = vocabulary([
|
|
|
1948
2446
|
"size_budget",
|
|
1949
2447
|
"symlink"
|
|
1950
2448
|
]);
|
|
2449
|
+
var CEAL_HOST_SERVICE_DIAGNOSTIC_WATCHER_OPTIONAL_FIELDS = vocabulary(["failure_kind", "cause"]);
|
|
2450
|
+
var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_OPTIONAL_FIELDS = vocabulary(["cause"]);
|
|
2451
|
+
var CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE = "^[a-z][a-z0-9_]{0,63}(?::[A-Za-z][A-Za-z0-9_]{0,63})?$";
|
|
2452
|
+
var CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES = Object.freeze([
|
|
2453
|
+
...CEAL_HOST_AUTHENTICATION_CAUSES,
|
|
2454
|
+
...CEAL_HOST_RELAY_EXCHANGE_FAILURES.map((failure) => `relay_exchange:${failure}`)
|
|
2455
|
+
]);
|
|
2456
|
+
var hostServiceDiagnosticCausePattern = new RegExp(CEAL_HOST_SERVICE_DIAGNOSTIC_CAUSE_PATTERN_SOURCE, "u");
|
|
2457
|
+
function isCealHostServiceDiagnosticCause(value, event) {
|
|
2458
|
+
return typeof value === "string" && hostServiceDiagnosticCausePattern.test(value) && (event !== "invocation_authentication_failed" || CEAL_HOST_SERVICE_DIAGNOSTIC_AUTHENTICATION_CAUSES.includes(value));
|
|
2459
|
+
}
|
|
1951
2460
|
|
|
1952
2461
|
// packages/ceal-client-protocol/src/client-result-materialization.ts
|
|
1953
2462
|
var CEAL_UNREAD_REASONS = vocabulary(["blocked", "unavailable", "too_large", "unsupported", "download_failed", "permission_denied"]);
|
|
1954
2463
|
var REQUIRED_FIELDS2 = Object.freeze(["schema_version", "operation_id", "path", "sha256"]);
|
|
1955
|
-
var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "
|
|
2464
|
+
var FIELDS = /* @__PURE__ */ new Set([...REQUIRED_FIELDS2, "local_result_root", "request_context_argv", "how_to_read"]);
|
|
1956
2465
|
|
|
1957
2466
|
// packages/ceal-client-protocol/src/discovery-manifest.ts
|
|
1958
2467
|
var DISCOVERY_MANIFEST_KEYS = CEAL_CLIENT_WIRE_CONTRACT.command_response.discovery_manifest_fields;
|
|
@@ -2034,12 +2543,14 @@ var ADMIN_SOURCE_OWNERS = vocabulary([
|
|
|
2034
2543
|
"resource",
|
|
2035
2544
|
"prompt",
|
|
2036
2545
|
"usage",
|
|
2546
|
+
"provider_request_lifecycle",
|
|
2037
2547
|
"connector",
|
|
2038
2548
|
"session",
|
|
2039
2549
|
"knowledge",
|
|
2040
2550
|
"policy"
|
|
2041
2551
|
]);
|
|
2042
2552
|
var ADMIN_COMPLETENESS_STATES = vocabulary(["complete", "partial", "unknown"]);
|
|
2553
|
+
var ADMIN_PROVIDER_REQUEST_CAPTURE_HEALTH_STATES = vocabulary(["available", "missing", "invalid", "unreadable"]);
|
|
2043
2554
|
var ADMIN_OPERATION_OUTCOMES = vocabulary(["completed", "failed", "denied", "cancelled", "unknown"]);
|
|
2044
2555
|
var ADMIN_APPROVAL_DISPOSITIONS = CEAL_OPERATION_APPROVAL_DISPOSITIONS;
|
|
2045
2556
|
var ADMIN_APPROVAL_POSTURES = vocabulary([...ADMIN_APPROVAL_DISPOSITIONS, "not_applicable"]);
|
|
@@ -2078,7 +2589,7 @@ function waitForAbort(signal, milliseconds) {
|
|
|
2078
2589
|
import { execFile } from "node:child_process";
|
|
2079
2590
|
import { constants } from "node:fs";
|
|
2080
2591
|
import { lstat, open } from "node:fs/promises";
|
|
2081
|
-
import { dirname, win32 as win323 } from "node:path";
|
|
2592
|
+
import { dirname, join as join2, win32 as win323 } from "node:path";
|
|
2082
2593
|
import { fileURLToPath } from "node:url";
|
|
2083
2594
|
var SecureFileCustodyError = class extends Error {
|
|
2084
2595
|
name = "SecureFileCustodyError";
|
|
@@ -2096,6 +2607,7 @@ var SecureFileCustodyError = class extends Error {
|
|
|
2096
2607
|
}
|
|
2097
2608
|
};
|
|
2098
2609
|
var WINDOWS_SECUREFS_REFUSAL_SCHEMA = "ceal.host_securefs_refusal.v1";
|
|
2610
|
+
var WINDOWS_SECUREFS_MAX_WRITE_BYTES = 1048576;
|
|
2099
2611
|
var WINDOWS_SECUREFS_TIMEOUT_MS = 1e4;
|
|
2100
2612
|
var WINDOWS_SECUREFS_DIAGNOSTIC_BYTES = 4096;
|
|
2101
2613
|
function secureOpenFlags(flags, platform) {
|
|
@@ -2138,18 +2650,46 @@ async function assertWindowsIdentityStable(handle, first, path) {
|
|
|
2138
2650
|
}
|
|
2139
2651
|
async function readPrivateFileWithSecurefs(path, maxBytes, custody = {}) {
|
|
2140
2652
|
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new TypeError("The securefs read bound must be a positive safe integer.");
|
|
2141
|
-
const result = await
|
|
2653
|
+
const result = await runSecurefsCommand(["internal", "securefs", "read-private-file", path, String(maxBytes)], maxBytes, custody);
|
|
2142
2654
|
if (result.exit_code === 0 && result.stderr.length === 0 && result.stdout.length <= maxBytes) return result.stdout;
|
|
2143
2655
|
if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned bytes with a refusal.");
|
|
2144
2656
|
if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command exceeded its output contract.");
|
|
2145
2657
|
throw securefsRefusal(result.stderr);
|
|
2146
2658
|
}
|
|
2147
|
-
async function
|
|
2148
|
-
|
|
2149
|
-
|
|
2659
|
+
async function ensurePrivateDirectoryWithSecurefs(path, custody = {}) {
|
|
2660
|
+
const result = await runSecurefsCommand(["internal", "securefs", "ensure-private-dir", path], 0, custody);
|
|
2661
|
+
if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
|
|
2662
|
+
if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid directory result.");
|
|
2663
|
+
throw securefsRefusal(result.stderr);
|
|
2664
|
+
}
|
|
2665
|
+
async function writePrivateFileWithSecurefs(path, bytes, maxBytes, custody = {}) {
|
|
2666
|
+
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.");
|
|
2667
|
+
const result = await runSecurefsCommand(["internal", "securefs", "write-private-file", path, String(maxBytes)], 0, custody, Buffer.from(bytes));
|
|
2668
|
+
if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return;
|
|
2669
|
+
if (result.stdout.length !== 0 || result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host securefs command returned an invalid write result.");
|
|
2670
|
+
throw securefsRefusal(result.stderr);
|
|
2671
|
+
}
|
|
2672
|
+
async function isPrivateWindowsDirectory(path, custody = {}) {
|
|
2673
|
+
await lstat(path);
|
|
2674
|
+
try {
|
|
2675
|
+
const result = await runSecurefsCommand(["internal", "securefs", "verify-private-dir", path], 0, custody);
|
|
2676
|
+
if (result.exit_code === 0 && result.stdout.length === 0 && result.stderr.length === 0) return true;
|
|
2677
|
+
if (result.stdout.length !== 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned unexpected bytes.");
|
|
2678
|
+
if (result.exit_code === 0) throw new SecureFileCustodyError("unavailable", "The Windows Host directory proof returned an invalid result.");
|
|
2679
|
+
const refusal = securefsRefusal(result.stderr);
|
|
2680
|
+
if (refusal.reason === "not_private" || refusal.reason === "reparse_point") return false;
|
|
2681
|
+
throw refusal;
|
|
2682
|
+
} catch (error) {
|
|
2683
|
+
if (error instanceof SecureFileCustodyError) throw error;
|
|
2684
|
+
throw new SecureFileCustodyError("unavailable", "The Windows Host directory custody proof is unavailable.");
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
async function runSecurefsCommand(args, maxBytes, custody, stdin) {
|
|
2688
|
+
if (custody.run_securefs_command !== void 0) return await custody.run_securefs_command(args, stdin);
|
|
2689
|
+
const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
|
|
2150
2690
|
const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
|
|
2151
2691
|
return await new Promise((resolve, reject2) => {
|
|
2152
|
-
execFile(executable, processArgs, { encoding: "buffer", timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
|
|
2692
|
+
const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
|
|
2153
2693
|
const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
|
|
2154
2694
|
if (exitCode === null) {
|
|
2155
2695
|
reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
|
|
@@ -2157,6 +2697,8 @@ async function runWindowsSecurefs(args, maxBytes, custody) {
|
|
|
2157
2697
|
}
|
|
2158
2698
|
resolve({ exit_code: exitCode, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr) });
|
|
2159
2699
|
});
|
|
2700
|
+
child.stdin?.on("error", () => void 0);
|
|
2701
|
+
child.stdin?.end(stdin);
|
|
2160
2702
|
});
|
|
2161
2703
|
}
|
|
2162
2704
|
function securefsRefusal(stderr) {
|
|
@@ -2174,9 +2716,9 @@ function securefsRefusal(stderr) {
|
|
|
2174
2716
|
if (value.code === "not_private") return new SecureFileCustodyError("not_private", "The Windows Host securefs file is not private to the current user.");
|
|
2175
2717
|
return new SecureFileCustodyError("unavailable", "The Windows Host securefs command refused the file read.");
|
|
2176
2718
|
}
|
|
2177
|
-
function resolveInstalledHostExecutable() {
|
|
2719
|
+
function resolveInstalledHostExecutable(platform) {
|
|
2178
2720
|
const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
|
|
2179
|
-
return win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe");
|
|
2721
|
+
return platform === "win32" ? win323.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
|
|
2180
2722
|
}
|
|
2181
2723
|
function isRecord(value) {
|
|
2182
2724
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -2192,6 +2734,11 @@ function isPrivateFileMode(mode, platform = process.platform, _handle) {
|
|
|
2192
2734
|
if (platform === "win32") return false;
|
|
2193
2735
|
return (mode & 63) === 0;
|
|
2194
2736
|
}
|
|
2737
|
+
async function isPrivateDirectory(path, platform = process.platform, custody = {}) {
|
|
2738
|
+
if (platform === "win32") return await isPrivateWindowsDirectory(path, custody);
|
|
2739
|
+
const entry = await lstat(path);
|
|
2740
|
+
return entry.isDirectory() && !entry.isSymbolicLink() && isSelfOwned(entry.uid, platform) && isPrivateFileMode(entry.mode, platform);
|
|
2741
|
+
}
|
|
2195
2742
|
|
|
2196
2743
|
// host/producer-service.ts
|
|
2197
2744
|
var SAFE_REF2 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
|
@@ -2218,7 +2765,8 @@ function parseHostProducerServeArgs(args, platform = process.platform) {
|
|
|
2218
2765
|
async function readHostProducerConfig(descriptor, configPath, platform = process.platform, custody = {}) {
|
|
2219
2766
|
const config = decodeHostProducerConfigText(descriptor, await readProducerConfigText(configPath, platform, hostProducerError, custody), platform);
|
|
2220
2767
|
const path = platform === "win32" ? win324 : posix3;
|
|
2221
|
-
const
|
|
2768
|
+
const registrationStateFile = hostProducerRegistrationStateFile(config.outbox_dir, platform);
|
|
2769
|
+
const root = path.dirname(registrationStateFile);
|
|
2222
2770
|
try {
|
|
2223
2771
|
assertHostProducerSourcePaths(root, config, descriptor.producer_id, platform);
|
|
2224
2772
|
} catch (error) {
|
|
@@ -2232,10 +2780,21 @@ function decodeHostProducerConfigText(descriptor, text, platform = process.platf
|
|
|
2232
2780
|
const { extra_paths: extras, ...core } = decoded;
|
|
2233
2781
|
return Object.freeze(descriptor.config({ schema_version: descriptor.schema, ...core }, extras));
|
|
2234
2782
|
}
|
|
2235
|
-
async function serveHostProducer(descriptor, config, signal, dependencies
|
|
2236
|
-
|
|
2783
|
+
async function serveHostProducer(descriptor, config, signal, dependencies) {
|
|
2784
|
+
const runtimeOptions = descriptor.runtime_options(config);
|
|
2785
|
+
const serving = serveProducer(runtimeOptions, config, signal, dependencies.drain ?? descriptor.drain, dependencies.wait);
|
|
2786
|
+
if (descriptor.background === void 0 || dependencies.drain !== void 0) {
|
|
2787
|
+
await serving;
|
|
2788
|
+
return;
|
|
2789
|
+
}
|
|
2790
|
+
const background = descriptor.background(config, signal, dependencies);
|
|
2791
|
+
await Promise.all([serving, background]);
|
|
2792
|
+
}
|
|
2793
|
+
function hostProducerRegistrationStateFile(outboxDirectory, platform = process.platform) {
|
|
2794
|
+
const path = platform === "win32" ? win324 : posix3;
|
|
2795
|
+
return path.join(path.resolve(outboxDirectory, "../../../../.."), "registration.json");
|
|
2237
2796
|
}
|
|
2238
|
-
async function runHostProducerCli(descriptor, args, signal, dependencies
|
|
2797
|
+
async function runHostProducerCli(descriptor, args, signal, dependencies) {
|
|
2239
2798
|
await serveHostProducer(descriptor, await readHostProducerConfig(descriptor, parseHostProducerServeArgs(args)), signal, dependencies);
|
|
2240
2799
|
}
|
|
2241
2800
|
function hostProducerError(code, message = code) {
|
|
@@ -2394,44 +2953,993 @@ function producerShapeFacts(value, options) {
|
|
|
2394
2953
|
if (Object.hasOwn(value, "schema_version") && value.schema_version !== options.schema) facts.push({ name: "schema_version", value: "wrong_type", expected: options.schema });
|
|
2395
2954
|
return facts;
|
|
2396
2955
|
}
|
|
2397
|
-
function validateIdentity(sourceRef, installationRef, epoch, error) {
|
|
2398
|
-
if (!SAFE_REF2.test(sourceRef) || !SAFE_REF2.test(installationRef) || !positive(epoch, 2147483647)) throw error("invalid_config", refusalFacts(producerIdentityFacts(sourceRef, installationRef, epoch)));
|
|
2399
|
-
return epoch;
|
|
2956
|
+
function validateIdentity(sourceRef, installationRef, epoch, error) {
|
|
2957
|
+
if (!SAFE_REF2.test(sourceRef) || !SAFE_REF2.test(installationRef) || !positive(epoch, 2147483647)) throw error("invalid_config", refusalFacts(producerIdentityFacts(sourceRef, installationRef, epoch)));
|
|
2958
|
+
return epoch;
|
|
2959
|
+
}
|
|
2960
|
+
function producerIdentityFacts(sourceRef, installationRef, epoch) {
|
|
2961
|
+
const facts = [];
|
|
2962
|
+
if (!SAFE_REF2.test(sourceRef)) facts.push({ name: "host_source_ref", value: "wrong_type", expected: "a safe reference" });
|
|
2963
|
+
if (!SAFE_REF2.test(installationRef)) facts.push({ name: "producer_installation_ref", value: "wrong_type", expected: "a safe reference" });
|
|
2964
|
+
if (!positive(epoch, 2147483647)) facts.push({ name: "producer_epoch", value: "wrong_type", expected: "a positive integer" });
|
|
2965
|
+
return facts;
|
|
2966
|
+
}
|
|
2967
|
+
function validateIntervals(reconcile, retry, timeout, error) {
|
|
2968
|
+
if (!boundedMilliseconds(reconcile) || !boundedMilliseconds(retry) || !boundedMilliseconds(timeout)) throw error("invalid_config", refusalFacts(producerIntervalFacts(reconcile, retry, timeout)));
|
|
2969
|
+
return [reconcile, retry, timeout];
|
|
2970
|
+
}
|
|
2971
|
+
function producerIntervalFacts(reconcile, retry, timeout) {
|
|
2972
|
+
const facts = [];
|
|
2973
|
+
if (!boundedMilliseconds(reconcile)) facts.push({ name: "reconcile_interval_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
|
|
2974
|
+
if (!boundedMilliseconds(retry)) facts.push({ name: "retry_backoff_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
|
|
2975
|
+
if (!boundedMilliseconds(timeout)) facts.push({ name: "ipc_timeout_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
|
|
2976
|
+
return facts;
|
|
2977
|
+
}
|
|
2978
|
+
function hasConfigKeys(value, required, tolerated = []) {
|
|
2979
|
+
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));
|
|
2980
|
+
}
|
|
2981
|
+
function isRecord2(value) {
|
|
2982
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2983
|
+
}
|
|
2984
|
+
function positive(value, maximum) {
|
|
2985
|
+
return Number.isSafeInteger(value) && Number(value) > 0 && Number(value) <= maximum;
|
|
2986
|
+
}
|
|
2987
|
+
function boundedMilliseconds(value) {
|
|
2988
|
+
return positive(value, 6e4) && Number(value) >= 25;
|
|
2989
|
+
}
|
|
2990
|
+
|
|
2991
|
+
// host/relay/src/host-registration-state.ts
|
|
2992
|
+
import { constants as constants3 } from "node:fs";
|
|
2993
|
+
import { dirname as dirname2 } from "node:path";
|
|
2994
|
+
var HOST_REGISTRATION_STATE_SCHEMA = "ceal.host_registration_state.v1";
|
|
2995
|
+
var HOST_REGISTRATION_STATE_KEYS = Object.freeze([
|
|
2996
|
+
"credential_generation",
|
|
2997
|
+
"gateway_request_origin",
|
|
2998
|
+
"host_access_token",
|
|
2999
|
+
"host_installation_ref",
|
|
3000
|
+
"host_source_ref",
|
|
3001
|
+
"registration_attempt_ref",
|
|
3002
|
+
"schema_version",
|
|
3003
|
+
"status"
|
|
3004
|
+
]);
|
|
3005
|
+
var HOST_REGISTRATION_STATE_MAX_BYTES = 65536;
|
|
3006
|
+
var HostRegistrationStateError = class extends Error {
|
|
3007
|
+
name = "HostRegistrationStateError";
|
|
3008
|
+
code = "credential";
|
|
3009
|
+
};
|
|
3010
|
+
async function readHostRegistrationAuthority(path, expectedHostSourceRef, platform = process.platform, custody = {}) {
|
|
3011
|
+
let raw;
|
|
3012
|
+
try {
|
|
3013
|
+
await assertPrivateRegistrationDirectory(dirname2(path), platform, custody);
|
|
3014
|
+
raw = platform === "win32" ? await readWindowsRegistration(path, custody) : await readPosixRegistration(path, platform, custody);
|
|
3015
|
+
} catch (error) {
|
|
3016
|
+
throw registrationReadError(error);
|
|
3017
|
+
}
|
|
3018
|
+
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}`)}.`);
|
|
3019
|
+
let value;
|
|
3020
|
+
try {
|
|
3021
|
+
value = JSON.parse(raw);
|
|
3022
|
+
} catch {
|
|
3023
|
+
throw new HostRegistrationStateError("Host registration state is invalid.");
|
|
3024
|
+
}
|
|
3025
|
+
return decodeHostRegistrationAuthority(value, expectedHostSourceRef);
|
|
3026
|
+
}
|
|
3027
|
+
async function readWindowsRegistration(path, custody) {
|
|
3028
|
+
const bytes = await readPrivateFileWithSecurefs(path, HOST_REGISTRATION_STATE_MAX_BYTES, custody);
|
|
3029
|
+
try {
|
|
3030
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
3031
|
+
} catch {
|
|
3032
|
+
throw new HostRegistrationStateError("Host registration state is invalid.");
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
async function readPosixRegistration(path, platform, custody) {
|
|
3036
|
+
const handle = await openNoFollow(path, constants3.O_RDONLY, void 0, platform, custody);
|
|
3037
|
+
try {
|
|
3038
|
+
const stats = await handle.stat();
|
|
3039
|
+
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.");
|
|
3040
|
+
return await handle.readFile("utf8");
|
|
3041
|
+
} finally {
|
|
3042
|
+
await handle.close();
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
function registrationReadError(error) {
|
|
3046
|
+
if (error instanceof HostRegistrationStateError) return error;
|
|
3047
|
+
if (error instanceof SecureFileCustodyError && error.reason === "not_private") return new HostRegistrationStateError("Host registration file is not private to its owner.");
|
|
3048
|
+
return new HostRegistrationStateError("Host registration file is unavailable.");
|
|
3049
|
+
}
|
|
3050
|
+
function decodeHostRegistrationAuthority(value, expectedHostSourceRef) {
|
|
3051
|
+
const keys = HOST_REGISTRATION_STATE_KEYS;
|
|
3052
|
+
const fieldCount = record(value) ? Object.keys(value).length : 0;
|
|
3053
|
+
const missing = record(value) ? keys.filter((key) => !Object.hasOwn(value, key)).length : keys.length;
|
|
3054
|
+
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" }])}.`);
|
|
3055
|
+
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>" }])}.`);
|
|
3056
|
+
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" }])}.`);
|
|
3057
|
+
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")}.`);
|
|
3058
|
+
return { gateway_request_origin: value.gateway_request_origin, host_access_token: value.host_access_token };
|
|
3059
|
+
}
|
|
3060
|
+
function validRegistrationIdentity(value, expectedHostSourceRef) {
|
|
3061
|
+
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;
|
|
3062
|
+
}
|
|
3063
|
+
function validRegistrationCredential(value) {
|
|
3064
|
+
return Number.isSafeInteger(value.credential_generation) && Number(value.credential_generation) > 0 && validHostAccessToken(value.host_access_token);
|
|
3065
|
+
}
|
|
3066
|
+
function validHostAccessToken(value) {
|
|
3067
|
+
return typeof value === "string" && CEAL_HOST_ACCESS_TOKEN_PATTERN.test(value);
|
|
3068
|
+
}
|
|
3069
|
+
function validGatewayOrigin(value) {
|
|
3070
|
+
try {
|
|
3071
|
+
if (typeof value !== "string" || /\s|\0/u.test(value)) return false;
|
|
3072
|
+
const parsed = new URL(value);
|
|
3073
|
+
const hostname = parsed.hostname.toLowerCase().replace(/\.+$/u, "");
|
|
3074
|
+
return hostname !== "" && validGatewayPort(parsed.port) && (loopbackHttpOrigin(parsed, hostname) || parsed.protocol === "https:") && cleanOriginPath(parsed) && bareOriginSuffix(value);
|
|
3075
|
+
} catch {
|
|
3076
|
+
return false;
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3079
|
+
function loopbackHttpOrigin(parsed, hostname) {
|
|
3080
|
+
return parsed.protocol === "http:" && parsed.port !== "" && (hostname === "127.0.0.1" || hostname === "[::1]");
|
|
3081
|
+
}
|
|
3082
|
+
function validGatewayPort(port) {
|
|
3083
|
+
if (port === "") return true;
|
|
3084
|
+
const numeric = Number(port);
|
|
3085
|
+
return Number.isInteger(numeric) && numeric >= 1 && numeric <= 65535;
|
|
3086
|
+
}
|
|
3087
|
+
function cleanOriginPath(parsed) {
|
|
3088
|
+
return parsed.username === "" && parsed.password === "" && parsed.pathname === "/" && parsed.search === "" && parsed.hash === "";
|
|
3089
|
+
}
|
|
3090
|
+
function bareOriginSuffix(value) {
|
|
3091
|
+
const schemeEnd = value.indexOf("://");
|
|
3092
|
+
const authority = schemeEnd < 0 ? "" : value.slice(schemeEnd + 3);
|
|
3093
|
+
const suffixOffset = authority.search(/[\\/?#]/u);
|
|
3094
|
+
const rawSuffix = suffixOffset < 0 ? "" : authority.slice(suffixOffset);
|
|
3095
|
+
return rawSuffix === "" || rawSuffix === "/";
|
|
3096
|
+
}
|
|
3097
|
+
async function assertPrivateRegistrationDirectory(path, platform, custody) {
|
|
3098
|
+
if (!await isPrivateDirectory(path, platform, custody)) throw new HostRegistrationStateError("Host registration directory is not private to its owner.");
|
|
3099
|
+
}
|
|
3100
|
+
function record(value) {
|
|
3101
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3102
|
+
}
|
|
3103
|
+
|
|
3104
|
+
// host/relay/src/host-usage-facts-store.ts
|
|
3105
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
3106
|
+
import { constants as constants4 } from "node:fs";
|
|
3107
|
+
import { mkdir as mkdir2, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
|
|
3108
|
+
import { dirname as dirname4, join as join3 } from "node:path";
|
|
3109
|
+
|
|
3110
|
+
// host/relay/src/durable-atomic-replacement.ts
|
|
3111
|
+
import { lstat as lstat3, mkdir, open as open2, rename, unlink } from "node:fs/promises";
|
|
3112
|
+
import { dirname as dirname3 } from "node:path";
|
|
3113
|
+
|
|
3114
|
+
// host/windows-rename-retry.ts
|
|
3115
|
+
import { setTimeout as setTimeout2 } from "node:timers/promises";
|
|
3116
|
+
var RETRY_WINDOW_MS = 1e4;
|
|
3117
|
+
var RETRY_START_DELAY_MS = 100;
|
|
3118
|
+
var RETRY_MAX_DELAY_MS = 2e3;
|
|
3119
|
+
var RETRYABLE_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]);
|
|
3120
|
+
var WindowsRenameRetryError = class extends Error {
|
|
3121
|
+
code = "rename_unavailable";
|
|
3122
|
+
constructor(target, attempts, options = {}) {
|
|
3123
|
+
super(`Windows did not permit renaming into place within the bounded retry window: ${target} (after ${attempts} attempts). Wait for the process holding the path to release it, then rerun the same install or update command.`, options);
|
|
3124
|
+
this.name = "WindowsRenameRetryError";
|
|
3125
|
+
}
|
|
3126
|
+
};
|
|
3127
|
+
function resolveRetrySchedule(tuning) {
|
|
3128
|
+
return {
|
|
3129
|
+
windowMs: tuning.windowMs ?? RETRY_WINDOW_MS,
|
|
3130
|
+
startDelayMs: tuning.startDelayMs ?? RETRY_START_DELAY_MS,
|
|
3131
|
+
maxDelayMs: tuning.maxDelayMs ?? RETRY_MAX_DELAY_MS,
|
|
3132
|
+
sleep: tuning.sleep ?? ((ms) => setTimeout2(ms)),
|
|
3133
|
+
now: tuning.now ?? (() => Date.now())
|
|
3134
|
+
};
|
|
3135
|
+
}
|
|
3136
|
+
async function renameWithWindowsRetry(operation, tuning) {
|
|
3137
|
+
const schedule = resolveRetrySchedule(tuning);
|
|
3138
|
+
const deadline = schedule.now() + schedule.windowMs;
|
|
3139
|
+
let delayMs = schedule.startDelayMs;
|
|
3140
|
+
let attempts = 0;
|
|
3141
|
+
for (; ; ) {
|
|
3142
|
+
attempts += 1;
|
|
3143
|
+
try {
|
|
3144
|
+
await operation();
|
|
3145
|
+
return;
|
|
3146
|
+
} catch (error) {
|
|
3147
|
+
if (tuning.platform !== "win32" || !isRetryableRenameError(error)) throw error;
|
|
3148
|
+
await sleepWithinWindow(schedule, deadline, delayMs, () => new WindowsRenameRetryError(tuning.target, attempts, { cause: error }));
|
|
3149
|
+
delayMs = Math.min(delayMs * 2, schedule.maxDelayMs);
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
}
|
|
3153
|
+
async function sleepWithinWindow(schedule, deadline, delayMs, exhausted) {
|
|
3154
|
+
if (schedule.now() >= deadline) throw exhausted();
|
|
3155
|
+
await schedule.sleep(Math.min(delayMs, deadline - schedule.now()));
|
|
3156
|
+
if (schedule.now() >= deadline) throw exhausted();
|
|
3157
|
+
}
|
|
3158
|
+
function isRetryableRenameError(error) {
|
|
3159
|
+
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && RETRYABLE_CODES.has(error.code);
|
|
3160
|
+
}
|
|
3161
|
+
|
|
3162
|
+
// host/relay/src/durable-atomic-replacement.ts
|
|
3163
|
+
var DEFAULT_PORT = {
|
|
3164
|
+
platform: process.platform,
|
|
3165
|
+
mkdir: (path, options) => mkdir(path, options),
|
|
3166
|
+
lstat: (path) => lstat3(path),
|
|
3167
|
+
open_file: (path) => open2(path, "wx", 384),
|
|
3168
|
+
rename,
|
|
3169
|
+
unlink,
|
|
3170
|
+
open_directory: (path) => open2(path),
|
|
3171
|
+
unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
|
|
3172
|
+
};
|
|
3173
|
+
async function durableAtomicReplace(target, data, port = DEFAULT_PORT) {
|
|
3174
|
+
const parent = dirname3(target);
|
|
3175
|
+
await port.mkdir(parent, { recursive: true, mode: 448 });
|
|
3176
|
+
const parentStats = await port.lstat(parent);
|
|
3177
|
+
const expectedUid = typeof process.geteuid === "function" ? process.geteuid() : parentStats.uid;
|
|
3178
|
+
const ownerPrivate = port.platform === "win32" || isOwnedBy(parentStats.uid, expectedUid) && isPrivateFileMode(parentStats.mode, port.platform);
|
|
3179
|
+
if (!parentStats.isDirectory() || parentStats.isSymbolicLink() || !ownerPrivate) throw new TypeError(`Host Relay durable-state directory is unsafe: ${refusalFacts([{ name: "parent_stats", value: parentStats, expected: "an owner-private directory" }, { name: "platform", value: port.platform }])}.`);
|
|
3180
|
+
const temporary = `${target}.${port.unique_ref()}.new`;
|
|
3181
|
+
let staged;
|
|
3182
|
+
const failures = [];
|
|
3183
|
+
try {
|
|
3184
|
+
staged = await port.open_file(temporary);
|
|
3185
|
+
await staged.writeFile(data, typeof data === "string" ? { encoding: "utf8" } : void 0);
|
|
3186
|
+
await staged.sync();
|
|
3187
|
+
const closing = staged;
|
|
3188
|
+
staged = void 0;
|
|
3189
|
+
await closing.close();
|
|
3190
|
+
await renameWithWindowsRetry(() => port.rename(temporary, target), { ...port.rename_retry, platform: port.platform, target });
|
|
3191
|
+
await syncParentDirectory(parent, port);
|
|
3192
|
+
} catch (error) {
|
|
3193
|
+
failures.push(error);
|
|
3194
|
+
}
|
|
3195
|
+
await closeStaged(staged, failures);
|
|
3196
|
+
await removeTemporary(temporary, port, failures);
|
|
3197
|
+
throwFailures(failures);
|
|
3198
|
+
}
|
|
3199
|
+
async function syncParentDirectory(path, port) {
|
|
3200
|
+
if (port.platform === "win32") return;
|
|
3201
|
+
const handle = await port.open_directory(path);
|
|
3202
|
+
let failure;
|
|
3203
|
+
try {
|
|
3204
|
+
await handle.sync();
|
|
3205
|
+
} catch (error) {
|
|
3206
|
+
if (!directorySyncUnsupported(error)) failure = error;
|
|
3207
|
+
}
|
|
3208
|
+
try {
|
|
3209
|
+
await handle.close();
|
|
3210
|
+
} catch (error) {
|
|
3211
|
+
if (failure === void 0) failure = error;
|
|
3212
|
+
else failure = new AggregateError([failure, error], "Host Relay directory sync and close failed.");
|
|
3213
|
+
}
|
|
3214
|
+
if (failure !== void 0) throw failure;
|
|
3215
|
+
}
|
|
3216
|
+
async function closeStaged(staged, failures) {
|
|
3217
|
+
if (staged !== void 0) try {
|
|
3218
|
+
await staged.close();
|
|
3219
|
+
} catch (error) {
|
|
3220
|
+
failures.push(error);
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
async function removeTemporary(path, port, failures) {
|
|
3224
|
+
try {
|
|
3225
|
+
await port.unlink(path);
|
|
3226
|
+
} catch (error) {
|
|
3227
|
+
if (errorCode(error) !== "ENOENT") failures.push(error);
|
|
3228
|
+
}
|
|
3229
|
+
}
|
|
3230
|
+
function throwFailures(failures) {
|
|
3231
|
+
if (failures.length === 1) throw failures[0];
|
|
3232
|
+
if (failures.length > 1) throw new AggregateError(failures, "Host Relay durable replacement and cleanup failed.");
|
|
3233
|
+
}
|
|
3234
|
+
function directorySyncUnsupported(error) {
|
|
3235
|
+
return ["EINVAL", "ENOSYS", "ENOTSUP"].includes(errorCode(error) ?? "");
|
|
3236
|
+
}
|
|
3237
|
+
function errorCode(error) {
|
|
3238
|
+
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
3239
|
+
}
|
|
3240
|
+
|
|
3241
|
+
// host/relay/src/host-usage-facts-store.ts
|
|
3242
|
+
var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
|
|
3243
|
+
var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
|
|
3244
|
+
var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
|
|
3245
|
+
var HOST_USAGE_FACTS_REF_MAX_LENGTH = 512;
|
|
3246
|
+
var HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES = 64;
|
|
3247
|
+
var HOST_USAGE_FACTS_OUTBOX_MAX_BYTES = 16 * 1024 * 1024;
|
|
3248
|
+
var HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS = 16;
|
|
3249
|
+
var HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES = 128;
|
|
3250
|
+
var SESSION_TRANSITION_TAILS = /* @__PURE__ */ new Map();
|
|
3251
|
+
var HostUsageFactsStore = class {
|
|
3252
|
+
root;
|
|
3253
|
+
sessions;
|
|
3254
|
+
batches;
|
|
3255
|
+
platform;
|
|
3256
|
+
custody;
|
|
3257
|
+
afterPendingWrite;
|
|
3258
|
+
afterBatchPublish;
|
|
3259
|
+
sessionDirectoryCursor;
|
|
3260
|
+
constructor(options) {
|
|
3261
|
+
this.root = join3(options.outbox_dir, "usage-facts");
|
|
3262
|
+
this.sessions = join3(this.root, "sessions");
|
|
3263
|
+
this.batches = join3(this.root, "batches");
|
|
3264
|
+
this.platform = options.platform ?? process.platform;
|
|
3265
|
+
this.custody = options.secure_file_custody ?? {};
|
|
3266
|
+
this.afterPendingWrite = options.afterPendingWrite;
|
|
3267
|
+
this.afterBatchPublish = options.afterBatchPublish;
|
|
3268
|
+
}
|
|
3269
|
+
async prepare() {
|
|
3270
|
+
for (const directory of [this.root, this.sessions, this.batches]) {
|
|
3271
|
+
await preparePrivateDirectory(directory, this.platform, this.custody);
|
|
3272
|
+
}
|
|
3273
|
+
}
|
|
3274
|
+
async close() {
|
|
3275
|
+
const cursor = this.sessionDirectoryCursor;
|
|
3276
|
+
this.sessionDirectoryCursor = void 0;
|
|
3277
|
+
await cursor?.close();
|
|
3278
|
+
}
|
|
3279
|
+
async readState(producer, hostSourceRef, hostSessionRef) {
|
|
3280
|
+
await this.prepare();
|
|
3281
|
+
const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
3282
|
+
const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
3283
|
+
if (value === null) return null;
|
|
3284
|
+
validateState(value, producer, hostSourceRef, hostSessionRef);
|
|
3285
|
+
return value;
|
|
3286
|
+
}
|
|
3287
|
+
createState(producer, hostSourceRef, hostSessionRef) {
|
|
3288
|
+
return {
|
|
3289
|
+
schema_version: HOST_USAGE_FACTS_STATE_SCHEMA,
|
|
3290
|
+
producer,
|
|
3291
|
+
host_source_ref: hostSourceRef,
|
|
3292
|
+
host_session_ref: hostSessionRef,
|
|
3293
|
+
cursors: {},
|
|
3294
|
+
eligible_batches: [],
|
|
3295
|
+
coverage_gaps: [],
|
|
3296
|
+
coverage_gap_created_at: null
|
|
3297
|
+
};
|
|
3298
|
+
}
|
|
3299
|
+
async prepareSourceCursor(producer, hostSourceRef, hostSessionRef, sourceSlot, initial, createdAt) {
|
|
3300
|
+
let state = await this.readState(producer, hostSourceRef, hostSessionRef);
|
|
3301
|
+
if (state === null) {
|
|
3302
|
+
state = this.createState(producer, hostSourceRef, hostSessionRef);
|
|
3303
|
+
state = await this.writeCursor(state, sourceSlot, initial);
|
|
3304
|
+
}
|
|
3305
|
+
state = await this.recoverPending(state);
|
|
3306
|
+
if (state.quarantined_reason !== void 0) return null;
|
|
3307
|
+
state = await this.commitCoverageGaps(state, createdAt);
|
|
3308
|
+
const cursor = state.cursors[sourceSlot];
|
|
3309
|
+
return cursor === void 0 ? null : { state, cursor };
|
|
3310
|
+
}
|
|
3311
|
+
async writeCursor(state, sourceSlot, cursor) {
|
|
3312
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3313
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3314
|
+
if (latest.pending_transition !== void 0) throw new Error("Host usage facts cursor has an unfinished transition.");
|
|
3315
|
+
const current = latest.cursors[sourceSlot];
|
|
3316
|
+
if (current !== void 0 && !sameCursor(current, cursor)) throw new Error("Host usage facts cursor was already initialized differently.");
|
|
3317
|
+
const updated = { ...latest, cursors: { ...latest.cursors, [sourceSlot]: cursor } };
|
|
3318
|
+
await this.writeState(updated);
|
|
3319
|
+
return updated;
|
|
3320
|
+
});
|
|
3321
|
+
}
|
|
3322
|
+
async commitScanTransition(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta = [], clearCoverageGaps = false) {
|
|
3323
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3324
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3325
|
+
return await this.commitScanTransitionLocked(latest, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps);
|
|
3326
|
+
});
|
|
3327
|
+
}
|
|
3328
|
+
async recoverPending(state) {
|
|
3329
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3330
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3331
|
+
const recovered = await this.finishPendingTransition(latest);
|
|
3332
|
+
await this.sweepOrphanedBatches(recovered);
|
|
3333
|
+
return recovered;
|
|
3334
|
+
});
|
|
3335
|
+
}
|
|
3336
|
+
/** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
|
|
3337
|
+
async sweepOrphanedBatches(state) {
|
|
3338
|
+
await this.prepare();
|
|
3339
|
+
const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
|
|
3340
|
+
await preparePrivateDirectory(directoryPath, this.platform, this.custody);
|
|
3341
|
+
const expected = expectedBatchNames(state);
|
|
3342
|
+
const directory = await opendir(directoryPath);
|
|
3343
|
+
let inspected = 0;
|
|
3344
|
+
let deleted = 0;
|
|
3345
|
+
try {
|
|
3346
|
+
while (inspected < HOST_USAGE_FACTS_ORPHAN_SWEEP_ENTRIES) {
|
|
3347
|
+
const entry = await directory.read();
|
|
3348
|
+
if (entry === null) break;
|
|
3349
|
+
inspected += 1;
|
|
3350
|
+
if (!isOrphanBatchEntry(entry, expected)) continue;
|
|
3351
|
+
await unlink2(join3(directoryPath, entry.name));
|
|
3352
|
+
deleted += 1;
|
|
3353
|
+
}
|
|
3354
|
+
} finally {
|
|
3355
|
+
await directory.close();
|
|
3356
|
+
}
|
|
3357
|
+
if (deleted > 0) await syncDirectory(directoryPath, this.platform);
|
|
3358
|
+
return deleted;
|
|
3359
|
+
}
|
|
3360
|
+
async commitCoverageGaps(state, createdAt) {
|
|
3361
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3362
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3363
|
+
if (latest.coverage_gaps.length === 0 || latest.pending_transition !== void 0 || !hasOutboxCapacity(latest, 0)) return latest;
|
|
3364
|
+
const sourceRanges = coverageRanges(latest.coverage_gaps);
|
|
3365
|
+
const canonical = createCealHostUsageBatch({
|
|
3366
|
+
host_source_ref: latest.host_source_ref,
|
|
3367
|
+
host_session_ref: latest.host_session_ref,
|
|
3368
|
+
created_at: latest.coverage_gap_created_at ?? createdAt,
|
|
3369
|
+
source_ranges: sourceRanges,
|
|
3370
|
+
facts: [],
|
|
3371
|
+
coverage_gaps: latest.coverage_gaps
|
|
3372
|
+
});
|
|
3373
|
+
const cursor = firstCursor(latest);
|
|
3374
|
+
if (cursor === null) return latest;
|
|
3375
|
+
return await this.commitScanTransitionLocked(latest, cursor[0], cursor[1], cursor[1], canonical, [], true);
|
|
3376
|
+
});
|
|
3377
|
+
}
|
|
3378
|
+
async nextUploadCandidate(producer, hostSourceRef) {
|
|
3379
|
+
await this.prepare();
|
|
3380
|
+
const names = await this.readNextSessionNames();
|
|
3381
|
+
for (const name of names) {
|
|
3382
|
+
const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
3383
|
+
if (state === null) continue;
|
|
3384
|
+
validateStateOwner(state, producer, hostSourceRef);
|
|
3385
|
+
let validated = state;
|
|
3386
|
+
if (validated.pending_transition === void 0) await this.sweepOrphanedBatches(validated);
|
|
3387
|
+
else validated = await this.recoverPending(validated);
|
|
3388
|
+
if (validated.pending_transition !== void 0 || validated.quarantined_reason !== void 0) continue;
|
|
3389
|
+
const next = validated.eligible_batches[0];
|
|
3390
|
+
if (next === void 0) continue;
|
|
3391
|
+
const batch = await this.readBatch(validated, next.batch_ref);
|
|
3392
|
+
return { state: validated, batch };
|
|
3393
|
+
}
|
|
3394
|
+
return null;
|
|
3395
|
+
}
|
|
3396
|
+
async readNextSessionNames() {
|
|
3397
|
+
this.sessionDirectoryCursor ??= await opendir(this.sessions);
|
|
3398
|
+
const names = [];
|
|
3399
|
+
let inspected = 0;
|
|
3400
|
+
while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
|
|
3401
|
+
const entry = await this.sessionDirectoryCursor.read();
|
|
3402
|
+
if (entry === null) {
|
|
3403
|
+
await this.sessionDirectoryCursor.close();
|
|
3404
|
+
this.sessionDirectoryCursor = void 0;
|
|
3405
|
+
break;
|
|
3406
|
+
}
|
|
3407
|
+
inspected += 1;
|
|
3408
|
+
if (entry.isFile() && entry.name.endsWith(".json")) names.push(entry.name);
|
|
3409
|
+
}
|
|
3410
|
+
return names;
|
|
3411
|
+
}
|
|
3412
|
+
async acknowledge(state, batchRef) {
|
|
3413
|
+
await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3414
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3415
|
+
if (latest.pending_transition?.batch_ref === batchRef) throw new Error("Host usage facts cannot acknowledge a pending transition batch.");
|
|
3416
|
+
const remaining = latest.eligible_batches.filter((entry) => entry.batch_ref !== batchRef);
|
|
3417
|
+
if (remaining.length === latest.eligible_batches.length) return;
|
|
3418
|
+
await this.writeState({ ...latest, eligible_batches: remaining });
|
|
3419
|
+
await removeFileIfPresent(this.batchPath(state, batchRef));
|
|
3420
|
+
});
|
|
3421
|
+
}
|
|
3422
|
+
async quarantine(state, reason) {
|
|
3423
|
+
return await this.withSessionLock(state.producer, state.host_source_ref, state.host_session_ref, async () => {
|
|
3424
|
+
const latest = await this.readState(state.producer, state.host_source_ref, state.host_session_ref) ?? state;
|
|
3425
|
+
const updated = { ...latest, quarantined_reason: reason ?? "state_malformed" };
|
|
3426
|
+
await this.writeState(updated);
|
|
3427
|
+
return updated;
|
|
3428
|
+
});
|
|
3429
|
+
}
|
|
3430
|
+
async retireCursor(state, sourceSlot, cursor, gap) {
|
|
3431
|
+
return await this.commitScanTransition(state, sourceSlot, cursor, null, null, [gap]);
|
|
3432
|
+
}
|
|
3433
|
+
async commitScanTransitionLocked(state, sourceSlot, beforeCursor, afterCursor, batch, gapDelta, clearCoverageGaps) {
|
|
3434
|
+
if (state.pending_transition !== void 0) throw new Error("Host usage facts transition must recover before another scan.");
|
|
3435
|
+
if (!sameCursor(state.cursors[sourceSlot], beforeCursor)) throw new Error("Host usage facts transition cursor does not match its durable predecessor.");
|
|
3436
|
+
const queued = await this.publishTransitionBatch(state, batch);
|
|
3437
|
+
const pending = {
|
|
3438
|
+
source_slot: sourceSlot,
|
|
3439
|
+
before_cursor: beforeCursor,
|
|
3440
|
+
after_cursor: afterCursor,
|
|
3441
|
+
batch_ref: queued.batch_ref,
|
|
3442
|
+
batch_bytes: queued.batch_bytes,
|
|
3443
|
+
gap_delta: [...gapDelta, ...queued.overflow_gaps],
|
|
3444
|
+
clear_coverage_gaps: clearCoverageGaps && queued.batch_ref !== null
|
|
3445
|
+
};
|
|
3446
|
+
const prepared = { ...state, pending_transition: pending };
|
|
3447
|
+
await this.writeState(prepared);
|
|
3448
|
+
await this.afterPendingWrite?.();
|
|
3449
|
+
return await this.finishPendingTransition(prepared);
|
|
3450
|
+
}
|
|
3451
|
+
async publishTransitionBatch(state, batch) {
|
|
3452
|
+
if (batch === null) return { batch_ref: null, batch_bytes: 0, overflow_gaps: [] };
|
|
3453
|
+
const serialized = serializeBatch(batch);
|
|
3454
|
+
if (!hasOutboxCapacity(state, serialized.byteLength)) return { batch_ref: null, batch_bytes: 0, overflow_gaps: overflowCoverageGaps(batch) };
|
|
3455
|
+
await this.writeImmutableBatch(state, batch, serialized);
|
|
3456
|
+
await this.afterBatchPublish?.();
|
|
3457
|
+
return { batch_ref: batch.batch_ref, batch_bytes: serialized.byteLength, overflow_gaps: [] };
|
|
3458
|
+
}
|
|
3459
|
+
async finishPendingTransition(state) {
|
|
3460
|
+
const pending = state.pending_transition;
|
|
3461
|
+
if (pending === void 0 || state.quarantined_reason !== void 0) return state;
|
|
3462
|
+
const current = state.cursors[pending.source_slot];
|
|
3463
|
+
if (!sameCursor(current, pending.before_cursor) && !cursorMatches(current, pending.after_cursor)) {
|
|
3464
|
+
const quarantined = { ...state, quarantined_reason: "pending_cursor_mismatch" };
|
|
3465
|
+
await this.writeState(quarantined);
|
|
3466
|
+
return quarantined;
|
|
3467
|
+
}
|
|
3468
|
+
let cursors = state.cursors;
|
|
3469
|
+
if (!cursorMatches(current, pending.after_cursor)) {
|
|
3470
|
+
const next = { ...state.cursors };
|
|
3471
|
+
if (pending.after_cursor === null) delete next[pending.source_slot];
|
|
3472
|
+
else next[pending.source_slot] = pending.after_cursor;
|
|
3473
|
+
cursors = next;
|
|
3474
|
+
}
|
|
3475
|
+
const eligible = pending.batch_ref === null ? state.eligible_batches : appendEligible(state.eligible_batches, { batch_ref: pending.batch_ref, bytes: pending.batch_bytes });
|
|
3476
|
+
const gaps = pending.clear_coverage_gaps ? [] : appendCoverageGaps(state.coverage_gaps, pending.gap_delta);
|
|
3477
|
+
const { pending_transition: _pendingTransition, ...settledState } = state;
|
|
3478
|
+
const updated = {
|
|
3479
|
+
...settledState,
|
|
3480
|
+
cursors,
|
|
3481
|
+
eligible_batches: eligible,
|
|
3482
|
+
coverage_gaps: gaps,
|
|
3483
|
+
coverage_gap_created_at: gaps.length === 0 ? null : state.coverage_gap_created_at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
3484
|
+
};
|
|
3485
|
+
await this.writeState(updated);
|
|
3486
|
+
return updated;
|
|
3487
|
+
}
|
|
3488
|
+
async writeImmutableBatch(state, batch, bytes) {
|
|
3489
|
+
const path = this.batchPath(state, batch.batch_ref);
|
|
3490
|
+
await preparePrivateDirectory(dirname4(path), this.platform, this.custody);
|
|
3491
|
+
const existing = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
3492
|
+
if (existing !== null) {
|
|
3493
|
+
if (!existing.equals(bytes)) throw new Error("Host usage facts batch reference conflicts with existing bytes.");
|
|
3494
|
+
await syncExistingFile(path, this.platform);
|
|
3495
|
+
return;
|
|
3496
|
+
}
|
|
3497
|
+
if (this.platform === "win32") {
|
|
3498
|
+
await writePrivateFileWithSecurefs(path, bytes, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.custody);
|
|
3499
|
+
return;
|
|
3500
|
+
}
|
|
3501
|
+
let handle;
|
|
3502
|
+
try {
|
|
3503
|
+
handle = await openNoFollow(path, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384, this.platform);
|
|
3504
|
+
await handle.writeFile(bytes);
|
|
3505
|
+
await handle.sync();
|
|
3506
|
+
await handle.close();
|
|
3507
|
+
handle = void 0;
|
|
3508
|
+
await syncDirectory(dirname4(path), this.platform);
|
|
3509
|
+
} catch (error) {
|
|
3510
|
+
await handle?.close().catch(() => void 0);
|
|
3511
|
+
if (errorCode2(error) === "EEXIST") {
|
|
3512
|
+
const winner = await readOptionalBytes(path, CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
3513
|
+
if (winner !== null && winner.equals(bytes)) {
|
|
3514
|
+
await syncExistingFile(path, this.platform);
|
|
3515
|
+
return;
|
|
3516
|
+
}
|
|
3517
|
+
throw new Error("Host usage facts batch reference conflicts with existing bytes.");
|
|
3518
|
+
}
|
|
3519
|
+
await removeFileIfPresent(path).catch(() => void 0);
|
|
3520
|
+
throw error;
|
|
3521
|
+
}
|
|
3522
|
+
}
|
|
3523
|
+
async readBatch(state, batchRef) {
|
|
3524
|
+
const bytes = await readOptionalBytes(this.batchPath(state, batchRef), CEAL_HOST_USAGE_BATCH_MAX_BYTES, this.platform, this.custody);
|
|
3525
|
+
if (bytes === null) throw new Error("Host usage facts batch object is missing.");
|
|
3526
|
+
let value;
|
|
3527
|
+
try {
|
|
3528
|
+
value = JSON.parse(bytes.toString("utf8"));
|
|
3529
|
+
} catch {
|
|
3530
|
+
throw new Error("Host usage facts batch object is malformed.");
|
|
3531
|
+
}
|
|
3532
|
+
validateCealHostUsageBatch(value);
|
|
3533
|
+
if (value.batch_ref !== batchRef) throw new Error("Host usage facts batch object identity does not match its index.");
|
|
3534
|
+
return value;
|
|
3535
|
+
}
|
|
3536
|
+
async writeState(state) {
|
|
3537
|
+
validateState(state, state.producer, state.host_source_ref, state.host_session_ref);
|
|
3538
|
+
const bytes = Buffer.from(JSON.stringify(state), "utf8");
|
|
3539
|
+
if (bytes.byteLength > HOST_USAGE_FACTS_STATE_MAX_BYTES) throw new Error("Host usage facts state exceeds its byte limit.");
|
|
3540
|
+
await this.prepare();
|
|
3541
|
+
const path = this.sessionPath(state.producer, state.host_source_ref, state.host_session_ref);
|
|
3542
|
+
if (this.platform === "win32") await writePrivateFileWithSecurefs(path, bytes, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.custody);
|
|
3543
|
+
else await durableAtomicReplace(path, bytes);
|
|
3544
|
+
}
|
|
3545
|
+
async withSessionLock(producer, hostSourceRef, hostSessionRef, run) {
|
|
3546
|
+
const key = this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
3547
|
+
const previous = SESSION_TRANSITION_TAILS.get(key) ?? Promise.resolve();
|
|
3548
|
+
let release;
|
|
3549
|
+
const gate = new Promise((resolve) => {
|
|
3550
|
+
release = resolve;
|
|
3551
|
+
});
|
|
3552
|
+
const tail = previous.then(() => gate);
|
|
3553
|
+
SESSION_TRANSITION_TAILS.set(key, tail);
|
|
3554
|
+
await previous;
|
|
3555
|
+
try {
|
|
3556
|
+
return await run();
|
|
3557
|
+
} finally {
|
|
3558
|
+
release?.();
|
|
3559
|
+
if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
|
|
3560
|
+
}
|
|
3561
|
+
}
|
|
3562
|
+
sessionPath(producer, hostSourceRef, hostSessionRef) {
|
|
3563
|
+
return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
|
|
3564
|
+
}
|
|
3565
|
+
batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
|
|
3566
|
+
const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
|
|
3567
|
+
return join3(this.batches, sessionName.slice(0, -5));
|
|
3568
|
+
}
|
|
3569
|
+
batchPath(state, batchRef) {
|
|
3570
|
+
return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
|
|
3571
|
+
}
|
|
3572
|
+
};
|
|
3573
|
+
function serializeBatch(batch) {
|
|
3574
|
+
validateCealHostUsageBatch(batch);
|
|
3575
|
+
return Buffer.from(JSON.stringify(batch), "utf8");
|
|
3576
|
+
}
|
|
3577
|
+
function batchFileName(batchRef) {
|
|
3578
|
+
const digest2 = cealHostUsageBatchObjectDigestFromReference(batchRef);
|
|
3579
|
+
if (digest2 === null) throw new TypeError("Host usage facts batch reference is invalid.");
|
|
3580
|
+
return `${digest2}.json`;
|
|
3581
|
+
}
|
|
3582
|
+
function expectedBatchNames(state) {
|
|
3583
|
+
const expected = new Set(state.eligible_batches.map(({ batch_ref }) => batchFileName(batch_ref)));
|
|
3584
|
+
const pending = state.pending_transition?.batch_ref;
|
|
3585
|
+
if (pending !== null && pending !== void 0) expected.add(batchFileName(pending));
|
|
3586
|
+
return expected;
|
|
3587
|
+
}
|
|
3588
|
+
function isOrphanBatchEntry(entry, expected) {
|
|
3589
|
+
return entry.isFile() && cealHostUsageBatchObjectDigestFromFileName(entry.name) !== null && !expected.has(entry.name);
|
|
3590
|
+
}
|
|
3591
|
+
function hasOutboxCapacity(state, bytes) {
|
|
3592
|
+
const existingBytes = state.eligible_batches.reduce((total, entry) => total + entry.bytes, 0);
|
|
3593
|
+
return state.eligible_batches.length < HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES && existingBytes + bytes <= HOST_USAGE_FACTS_OUTBOX_MAX_BYTES;
|
|
3594
|
+
}
|
|
3595
|
+
function overflowCoverageGaps(batch) {
|
|
3596
|
+
const count = batch.facts.length;
|
|
3597
|
+
const gaps = [...batch.coverage_gaps];
|
|
3598
|
+
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 });
|
|
3599
|
+
return gaps;
|
|
3600
|
+
}
|
|
3601
|
+
function appendEligible(existing, next) {
|
|
3602
|
+
if (existing.some((entry) => entry.batch_ref === next.batch_ref)) return existing;
|
|
3603
|
+
if (existing.length >= HOST_USAGE_FACTS_OUTBOX_MAX_BATCHES) throw new Error("Host usage facts outbox is full during transition recovery.");
|
|
3604
|
+
return [...existing, next];
|
|
3605
|
+
}
|
|
3606
|
+
function appendCoverageGaps(existing, added) {
|
|
3607
|
+
if (added.length === 0) return existing;
|
|
3608
|
+
const byIdentity = new Map(existing.map((gap) => [JSON.stringify(gap), gap]));
|
|
3609
|
+
for (const gap of added) byIdentity.set(JSON.stringify(gap), gap);
|
|
3610
|
+
const combined = [...byIdentity.values()];
|
|
3611
|
+
if (combined.length <= CEAL_HOST_USAGE_BATCH_MAX_GAPS) return combined;
|
|
3612
|
+
const omitted = combined.some((gap) => gap.omitted_count === null) ? null : combined.reduce((total, gap) => total + (gap.omitted_count ?? 0), 0);
|
|
3613
|
+
return [{ reason: "outbox_capacity", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: omitted }];
|
|
3614
|
+
}
|
|
3615
|
+
function coverageRanges(gaps) {
|
|
3616
|
+
const ranges = /* @__PURE__ */ new Map();
|
|
3617
|
+
for (const gap of gaps) {
|
|
3618
|
+
if (gap.source_file_ref === null || gap.start_offset === null || gap.end_offset === null) continue;
|
|
3619
|
+
const current = ranges.get(gap.source_file_ref);
|
|
3620
|
+
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 });
|
|
3621
|
+
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) });
|
|
3622
|
+
}
|
|
3623
|
+
return [...ranges.values()];
|
|
3624
|
+
}
|
|
3625
|
+
function firstCursor(state) {
|
|
3626
|
+
const entry = Object.entries(state.cursors)[0];
|
|
3627
|
+
return entry === void 0 ? null : entry;
|
|
3628
|
+
}
|
|
3629
|
+
function sameCursor(left, right) {
|
|
3630
|
+
return left !== void 0 && JSON.stringify(left) === JSON.stringify(right);
|
|
3631
|
+
}
|
|
3632
|
+
function cursorMatches(left, right) {
|
|
3633
|
+
return right === null ? left === void 0 : sameCursor(left, right);
|
|
3634
|
+
}
|
|
3635
|
+
function validateState(value, producer, hostSourceRef, hostSessionRef) {
|
|
3636
|
+
validateStateIdentity(value, producer, hostSourceRef, hostSessionRef);
|
|
3637
|
+
validateStateShape(value);
|
|
3638
|
+
validateStateLimits(value);
|
|
3639
|
+
validateStateContents(value);
|
|
3640
|
+
}
|
|
3641
|
+
function validateStateIdentity(value, producer, hostSourceRef, hostSessionRef) {
|
|
3642
|
+
if (!isRecord3(value) || value.schema_version !== HOST_USAGE_FACTS_STATE_SCHEMA || value.producer !== producer || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new Error("Host usage facts state identity is invalid.");
|
|
3643
|
+
}
|
|
3644
|
+
function validateStateLimits(value) {
|
|
3645
|
+
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.");
|
|
3646
|
+
}
|
|
3647
|
+
function validateStateContents(value) {
|
|
3648
|
+
for (const [slot, cursor] of Object.entries(value.cursors)) {
|
|
3649
|
+
validateSourceSlot(slot);
|
|
3650
|
+
validateFileCursor(cursor);
|
|
3651
|
+
}
|
|
3652
|
+
for (const item of value.eligible_batches) validateEligibleBatch(item);
|
|
3653
|
+
if (value.pending_transition !== void 0) validatePending(value.pending_transition);
|
|
3654
|
+
for (const gap of value.coverage_gaps) validateGap(gap);
|
|
3655
|
+
validateStateOptionalMetadata(value.coverage_gap_created_at, value.quarantined_reason);
|
|
3656
|
+
}
|
|
3657
|
+
function validateStateOptionalMetadata(coverageGapCreatedAt, quarantine) {
|
|
3658
|
+
if (coverageGapCreatedAt !== null && !validTimestamp(coverageGapCreatedAt)) throw new Error("Host usage facts state coverage time is invalid.");
|
|
3659
|
+
if (quarantine !== void 0 && quarantine !== "pending_cursor_mismatch" && quarantine !== "state_malformed") throw new Error("Host usage facts state quarantine is invalid.");
|
|
3660
|
+
}
|
|
3661
|
+
function validateStateOwner(value, producer, hostSourceRef) {
|
|
3662
|
+
if (!isRecord3(value) || value.host_session_ref === void 0) throw new Error("Host usage facts state owner is invalid.");
|
|
3663
|
+
validateState(value, producer, hostSourceRef, String(value.host_session_ref));
|
|
3664
|
+
}
|
|
3665
|
+
function validateStateShape(value) {
|
|
3666
|
+
const required = ["schema_version", "producer", "host_source_ref", "host_session_ref", "cursors", "eligible_batches", "coverage_gaps", "coverage_gap_created_at"];
|
|
3667
|
+
const optional = ["pending_transition", "quarantined_reason"];
|
|
3668
|
+
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.");
|
|
3669
|
+
if (!isRecord3(value.cursors) || !Array.isArray(value.eligible_batches) || !Array.isArray(value.coverage_gaps) || value.coverage_gap_created_at !== null && typeof value.coverage_gap_created_at !== "string") throw new Error("Host usage facts state collections are invalid.");
|
|
3670
|
+
}
|
|
3671
|
+
function validateFileCursor(value) {
|
|
3672
|
+
if (!isRecord3(value) || !sameKeys(value, ["source_file_ref", "device", "inode", "offset", "anchor_start", "anchor_sha256", "last_ordinal", "host_turn_ref", "native_turn_id", "requested_model", "codex_total_usage", "skipping_oversized_line"])) throw new Error("Host usage facts source cursor is invalid.");
|
|
3673
|
+
validateCursorIdentity(value);
|
|
3674
|
+
validateCursorOffsets(value);
|
|
3675
|
+
validateCursorContext(value);
|
|
3676
|
+
if (value.codex_total_usage !== null) validateCodexCounts(value.codex_total_usage);
|
|
3677
|
+
if (typeof value.skipping_oversized_line !== "boolean") throw new Error("Host usage facts source cursor line state is invalid.");
|
|
3678
|
+
}
|
|
3679
|
+
function validateCursorIdentity(value) {
|
|
3680
|
+
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.");
|
|
3681
|
+
}
|
|
3682
|
+
function validateCursorOffsets(value) {
|
|
3683
|
+
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.");
|
|
3684
|
+
}
|
|
3685
|
+
function validateCursorContext(value) {
|
|
3686
|
+
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.");
|
|
3687
|
+
}
|
|
3688
|
+
function validOptionalText(value, maximum) {
|
|
3689
|
+
return value === null || typeof value === "string" && value.length <= maximum;
|
|
3690
|
+
}
|
|
3691
|
+
function validateCodexCounts(value) {
|
|
3692
|
+
if (!isRecord3(value) || !sameKeys(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) throw new Error("Host usage facts cumulative usage is invalid.");
|
|
3693
|
+
if (!Object.values(value).every(safeInteger2)) throw new Error("Host usage facts cumulative usage is invalid.");
|
|
3694
|
+
}
|
|
3695
|
+
function validatePending(value) {
|
|
3696
|
+
if (!isRecord3(value) || !sameKeys(value, ["source_slot", "before_cursor", "after_cursor", "batch_ref", "batch_bytes", "gap_delta", "clear_coverage_gaps"])) throw new Error("Host usage facts pending transition is invalid.");
|
|
3697
|
+
validatePendingCursors(value);
|
|
3698
|
+
validatePendingBatch(value);
|
|
3699
|
+
validatePendingFields(value);
|
|
3700
|
+
for (const gap of value.gap_delta) validateGap(gap);
|
|
3701
|
+
}
|
|
3702
|
+
function validatePendingCursors(value) {
|
|
3703
|
+
validateSourceSlot(value.source_slot);
|
|
3704
|
+
validateFileCursor(value.before_cursor);
|
|
3705
|
+
if (value.after_cursor !== null) validateFileCursor(value.after_cursor);
|
|
3706
|
+
}
|
|
3707
|
+
function validatePendingBatch(value) {
|
|
3708
|
+
if (value.batch_ref !== null && !isCealHostUsageBatchReference(value.batch_ref)) throw new Error("Host usage facts pending batch reference is invalid.");
|
|
3709
|
+
}
|
|
3710
|
+
function validatePendingFields(value) {
|
|
3711
|
+
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.");
|
|
3712
|
+
}
|
|
3713
|
+
function validateEligibleBatch(value) {
|
|
3714
|
+
if (!isRecord3(value) || !sameKeys(value, ["batch_ref", "bytes"]) || !isCealHostUsageBatchReference(value.batch_ref) || !safeInteger2(value.bytes) || Number(value.bytes) < 1 || Number(value.bytes) > CEAL_HOST_USAGE_BATCH_MAX_BYTES) throw new Error("Host usage facts eligible batch is invalid.");
|
|
3715
|
+
}
|
|
3716
|
+
function validateGap(value) {
|
|
3717
|
+
try {
|
|
3718
|
+
validateCealHostUsageCoverageGap(value);
|
|
3719
|
+
} catch {
|
|
3720
|
+
throw new Error("Host usage facts coverage gap is invalid.");
|
|
3721
|
+
}
|
|
3722
|
+
}
|
|
3723
|
+
function validateSourceSlot(value) {
|
|
3724
|
+
if (value !== "main" && (typeof value !== "string" || !/^subagent:[a-f0-9]{64}$/u.test(value))) throw new Error("Host usage facts source slot is invalid.");
|
|
3725
|
+
}
|
|
3726
|
+
async function readOptionalJson(path, maxBytes, platform, custody) {
|
|
3727
|
+
const bytes = await readOptionalBytes(path, maxBytes, platform, custody);
|
|
3728
|
+
if (bytes === null) return null;
|
|
3729
|
+
try {
|
|
3730
|
+
return JSON.parse(bytes.toString("utf8"));
|
|
3731
|
+
} catch {
|
|
3732
|
+
throw new Error("Host usage facts state JSON is malformed.");
|
|
3733
|
+
}
|
|
3734
|
+
}
|
|
3735
|
+
async function readOptionalBytes(path, maxBytes, platform, custody) {
|
|
3736
|
+
if (platform === "win32") {
|
|
3737
|
+
try {
|
|
3738
|
+
return await readPrivateFileWithSecurefs(path, maxBytes, custody);
|
|
3739
|
+
} catch (error) {
|
|
3740
|
+
if (errorCode2(error) === "ENOENT") return null;
|
|
3741
|
+
throw error;
|
|
3742
|
+
}
|
|
3743
|
+
}
|
|
3744
|
+
let handle;
|
|
3745
|
+
try {
|
|
3746
|
+
handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
|
|
3747
|
+
const stats = await handle.stat();
|
|
3748
|
+
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.");
|
|
3749
|
+
return await handle.readFile();
|
|
3750
|
+
} catch (error) {
|
|
3751
|
+
if (errorCode2(error) === "ENOENT") return null;
|
|
3752
|
+
throw error;
|
|
3753
|
+
} finally {
|
|
3754
|
+
await handle?.close();
|
|
3755
|
+
}
|
|
3756
|
+
}
|
|
3757
|
+
async function preparePrivateDirectory(path, platform, custody) {
|
|
3758
|
+
if (platform === "win32") {
|
|
3759
|
+
await ensurePrivateDirectoryWithSecurefs(path, custody);
|
|
3760
|
+
return;
|
|
3761
|
+
}
|
|
3762
|
+
await mkdir2(path, { recursive: true, mode: 448 });
|
|
3763
|
+
if (!await isPrivateDirectory(path, platform)) throw new Error("Host usage facts directory is not owner private.");
|
|
3764
|
+
}
|
|
3765
|
+
async function syncExistingFile(path, platform) {
|
|
3766
|
+
const handle = await openNoFollow(path, constants4.O_RDONLY, void 0, platform);
|
|
3767
|
+
try {
|
|
3768
|
+
await handle.sync();
|
|
3769
|
+
} finally {
|
|
3770
|
+
await handle.close();
|
|
3771
|
+
}
|
|
3772
|
+
await syncDirectory(dirname4(path), platform);
|
|
3773
|
+
}
|
|
3774
|
+
async function syncDirectory(path, platform) {
|
|
3775
|
+
if (platform === "win32") return;
|
|
3776
|
+
const handle = await open3(path, constants4.O_RDONLY);
|
|
3777
|
+
try {
|
|
3778
|
+
await handle.sync();
|
|
3779
|
+
} finally {
|
|
3780
|
+
await handle.close();
|
|
3781
|
+
}
|
|
3782
|
+
}
|
|
3783
|
+
async function removeFileIfPresent(path) {
|
|
3784
|
+
try {
|
|
3785
|
+
await unlink2(path);
|
|
3786
|
+
} catch (error) {
|
|
3787
|
+
if (errorCode2(error) !== "ENOENT") throw error;
|
|
3788
|
+
}
|
|
2400
3789
|
}
|
|
2401
|
-
function
|
|
2402
|
-
|
|
2403
|
-
if (!SAFE_REF2.test(sourceRef)) facts.push({ name: "host_source_ref", value: "wrong_type", expected: "a safe reference" });
|
|
2404
|
-
if (!SAFE_REF2.test(installationRef)) facts.push({ name: "producer_installation_ref", value: "wrong_type", expected: "a safe reference" });
|
|
2405
|
-
if (!positive(epoch, 2147483647)) facts.push({ name: "producer_epoch", value: "wrong_type", expected: "a positive integer" });
|
|
2406
|
-
return facts;
|
|
3790
|
+
function sameKeys(value, expected) {
|
|
3791
|
+
return Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
|
|
2407
3792
|
}
|
|
2408
|
-
function
|
|
2409
|
-
|
|
2410
|
-
return [reconcile, retry, timeout];
|
|
3793
|
+
function isRecord3(value) {
|
|
3794
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2411
3795
|
}
|
|
2412
|
-
function
|
|
2413
|
-
|
|
2414
|
-
if (!boundedMilliseconds(reconcile)) facts.push({ name: "reconcile_interval_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
|
|
2415
|
-
if (!boundedMilliseconds(retry)) facts.push({ name: "retry_backoff_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
|
|
2416
|
-
if (!boundedMilliseconds(timeout)) facts.push({ name: "ipc_timeout_ms", value: "wrong_type", expected: "25..60000 milliseconds" });
|
|
2417
|
-
return facts;
|
|
3796
|
+
function safeInteger2(value) {
|
|
3797
|
+
return Number.isSafeInteger(value) && Number(value) >= 0;
|
|
2418
3798
|
}
|
|
2419
|
-
function
|
|
2420
|
-
return
|
|
3799
|
+
function validTimestamp(value) {
|
|
3800
|
+
return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
2421
3801
|
}
|
|
2422
|
-
function
|
|
2423
|
-
return
|
|
3802
|
+
function errorCode2(error) {
|
|
3803
|
+
return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
|
|
2424
3804
|
}
|
|
2425
|
-
function
|
|
2426
|
-
return
|
|
3805
|
+
function sha2562(value) {
|
|
3806
|
+
return createHash5("sha256").update(value, "utf8").digest("hex");
|
|
2427
3807
|
}
|
|
2428
|
-
|
|
2429
|
-
|
|
3808
|
+
|
|
3809
|
+
// host/service-log.ts
|
|
3810
|
+
import { copyFile, mkdir as mkdir3, stat, truncate, appendFile } from "node:fs/promises";
|
|
3811
|
+
import { dirname as dirname5, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
|
|
3812
|
+
|
|
3813
|
+
// host/service-log-delivery.ts
|
|
3814
|
+
var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
|
|
3815
|
+
function createHostServiceLogDelivery(stream, schedule = (flush) => {
|
|
3816
|
+
setImmediate(flush);
|
|
3817
|
+
}, onDeliveryGap = () => void 0) {
|
|
3818
|
+
const pending = [];
|
|
3819
|
+
const highWaterMark = stream.writableHighWaterMark;
|
|
3820
|
+
const byteBudget = highWaterMark + highWaterMark;
|
|
3821
|
+
let pendingBytes = 0;
|
|
3822
|
+
let droppedLines = 0;
|
|
3823
|
+
let flushScheduled = false;
|
|
3824
|
+
let waitingForDrain = false;
|
|
3825
|
+
let closed = !stream.writable;
|
|
3826
|
+
function stop() {
|
|
3827
|
+
if (closed) return;
|
|
3828
|
+
closed = true;
|
|
3829
|
+
pending.length = 0;
|
|
3830
|
+
pendingBytes = 0;
|
|
3831
|
+
stream.off("drain", onDrain);
|
|
3832
|
+
stream.off("close", onTerminal);
|
|
3833
|
+
stream.off("finish", onTerminal);
|
|
3834
|
+
stream.off("error", onError);
|
|
3835
|
+
}
|
|
3836
|
+
function onTerminal() {
|
|
3837
|
+
stop();
|
|
3838
|
+
}
|
|
3839
|
+
function onError() {
|
|
3840
|
+
stop();
|
|
3841
|
+
}
|
|
3842
|
+
function onDrain() {
|
|
3843
|
+
waitingForDrain = false;
|
|
3844
|
+
scheduleFlush();
|
|
3845
|
+
}
|
|
3846
|
+
function scheduleFlush() {
|
|
3847
|
+
if (closed || flushScheduled || pending.length === 0 && droppedLines === 0) return;
|
|
3848
|
+
flushScheduled = true;
|
|
3849
|
+
let scheduling = true;
|
|
3850
|
+
let invokedSynchronously = false;
|
|
3851
|
+
try {
|
|
3852
|
+
schedule(() => {
|
|
3853
|
+
if (scheduling) {
|
|
3854
|
+
invokedSynchronously = true;
|
|
3855
|
+
return;
|
|
3856
|
+
}
|
|
3857
|
+
flushScheduled = false;
|
|
3858
|
+
flush();
|
|
3859
|
+
});
|
|
3860
|
+
} catch {
|
|
3861
|
+
flushScheduled = false;
|
|
3862
|
+
stop();
|
|
3863
|
+
return;
|
|
3864
|
+
}
|
|
3865
|
+
scheduling = false;
|
|
3866
|
+
if (invokedSynchronously) {
|
|
3867
|
+
flushScheduled = false;
|
|
3868
|
+
stop();
|
|
3869
|
+
}
|
|
3870
|
+
}
|
|
3871
|
+
function flush() {
|
|
3872
|
+
if (closed) return;
|
|
3873
|
+
if (!stream.writable) {
|
|
3874
|
+
stop();
|
|
3875
|
+
return;
|
|
3876
|
+
}
|
|
3877
|
+
while (pending.length > 0) {
|
|
3878
|
+
if (stream.writableNeedDrain) {
|
|
3879
|
+
if (!waitingForDrain) {
|
|
3880
|
+
waitingForDrain = true;
|
|
3881
|
+
stream.once("drain", onDrain);
|
|
3882
|
+
}
|
|
3883
|
+
return;
|
|
3884
|
+
}
|
|
3885
|
+
const next = pending.shift();
|
|
3886
|
+
if (next === void 0) return;
|
|
3887
|
+
pendingBytes -= next.bytes;
|
|
3888
|
+
let accepted;
|
|
3889
|
+
try {
|
|
3890
|
+
accepted = stream.write(next.line);
|
|
3891
|
+
} catch {
|
|
3892
|
+
stop();
|
|
3893
|
+
return;
|
|
3894
|
+
}
|
|
3895
|
+
if (!accepted) {
|
|
3896
|
+
waitingForDrain = true;
|
|
3897
|
+
stream.once("drain", onDrain);
|
|
3898
|
+
return;
|
|
3899
|
+
}
|
|
3900
|
+
}
|
|
3901
|
+
if (droppedLines > 0) {
|
|
3902
|
+
const line = `${JSON.stringify({ schema_version: HOST_SERVICE_LOG_DELIVERY_SCHEMA, omitted_line_count: droppedLines })}
|
|
3903
|
+
`;
|
|
3904
|
+
droppedLines = 0;
|
|
3905
|
+
try {
|
|
3906
|
+
onDeliveryGap(line);
|
|
3907
|
+
} catch {
|
|
3908
|
+
}
|
|
3909
|
+
pending.push({ line, bytes: Buffer.byteLength(line, "utf8") });
|
|
3910
|
+
pendingBytes += Buffer.byteLength(line, "utf8");
|
|
3911
|
+
flush();
|
|
3912
|
+
}
|
|
3913
|
+
}
|
|
3914
|
+
stream.on("close", onTerminal);
|
|
3915
|
+
stream.on("finish", onTerminal);
|
|
3916
|
+
stream.on("error", onError);
|
|
3917
|
+
return (line) => {
|
|
3918
|
+
if (closed) return;
|
|
3919
|
+
const bytes = Buffer.byteLength(line, "utf8");
|
|
3920
|
+
if (bytes > highWaterMark || stream.writableLength + pendingBytes + bytes > byteBudget) {
|
|
3921
|
+
droppedLines += 1;
|
|
3922
|
+
scheduleFlush();
|
|
3923
|
+
return;
|
|
3924
|
+
}
|
|
3925
|
+
pending.push({ line, bytes });
|
|
3926
|
+
pendingBytes += bytes;
|
|
3927
|
+
scheduleFlush();
|
|
3928
|
+
};
|
|
2430
3929
|
}
|
|
2431
3930
|
|
|
3931
|
+
// host/invocation-authentication-client-command.ts
|
|
3932
|
+
var HOST_OWNED_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+){0,7}$/u;
|
|
3933
|
+
function isHostOwnedFailureCode(value) {
|
|
3934
|
+
return typeof value === "string" && HOST_OWNED_CODE.test(value);
|
|
3935
|
+
}
|
|
3936
|
+
var DOCTOR_FLAGS = Object.freeze({
|
|
3937
|
+
"--expected-sha256": "expected_sha256",
|
|
3938
|
+
"--expected-source-commit": "expected_source_commit",
|
|
3939
|
+
"--expected-instance-ref": "expected_instance_ref"
|
|
3940
|
+
});
|
|
3941
|
+
|
|
2432
3942
|
// host/service-log.ts
|
|
2433
|
-
import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
|
|
2434
|
-
import { dirname as dirname2, isAbsolute, posix as posix4, win32 as win325 } from "node:path";
|
|
2435
3943
|
var HOST_SERVICE_LOG_ENVIRONMENT = "CEAL_HOST_SERVICE_LOG";
|
|
2436
3944
|
var HOST_SERVICE_LOG_ARGUMENT = "--ceal-host-service-log";
|
|
2437
3945
|
var HostServiceLogArgumentError = class extends Error {
|
|
@@ -2450,17 +3958,30 @@ function consumeHostServiceLogArgument(args, platform = process.platform) {
|
|
|
2450
3958
|
if (indexes.length !== 1 || path === void 0 || !pathApi.isAbsolute(path) || pathApi.normalize(path) !== path) throw new HostServiceLogArgumentError();
|
|
2451
3959
|
return { args: [...args.slice(0, index), ...args.slice(index + 2)], path };
|
|
2452
3960
|
}
|
|
3961
|
+
var defaultHostServiceLogDelivery = createHostServiceLogDelivery(process.stderr, void 0, (line) => {
|
|
3962
|
+
void persistHostServiceLogLine(line);
|
|
3963
|
+
});
|
|
2453
3964
|
function writeHostServiceDiagnostic(producer_id, event, failure_kind, cause, sink) {
|
|
2454
|
-
const
|
|
3965
|
+
const details = diagnosticDetails(event, failure_kind, cause);
|
|
3966
|
+
const line = `${JSON.stringify({ schema_version: CEAL_HOST_SERVICE_DIAGNOSTIC_SCHEMA, producer_id, event, ...details })}
|
|
2455
3967
|
`;
|
|
2456
3968
|
try {
|
|
2457
3969
|
(sink ?? defaultHostServiceDiagnosticSink)(line);
|
|
2458
3970
|
} catch {
|
|
2459
3971
|
}
|
|
2460
3972
|
}
|
|
3973
|
+
function diagnosticDetails(event, failureKind, cause) {
|
|
3974
|
+
if (event === "watcher_scan_failed") return {
|
|
3975
|
+
...failureKind === void 0 ? {} : { failure_kind: failureKind },
|
|
3976
|
+
...validDiagnosticCause(cause, event) ? { cause } : {}
|
|
3977
|
+
};
|
|
3978
|
+
return validDiagnosticCause(cause, event) ? { cause } : {};
|
|
3979
|
+
}
|
|
3980
|
+
function validDiagnosticCause(cause, event) {
|
|
3981
|
+
return cause !== void 0 && isCealHostServiceDiagnosticCause(cause, event);
|
|
3982
|
+
}
|
|
2461
3983
|
function defaultHostServiceDiagnosticSink(line) {
|
|
2462
3984
|
writeHostServiceLogLine(line);
|
|
2463
|
-
process.stderr.write(line);
|
|
2464
3985
|
}
|
|
2465
3986
|
var HOST_SERVICE_LOG_MAX_BYTES = 1024 * 1024;
|
|
2466
3987
|
var HOST_SERVICE_LOG_CHECK_INTERVAL_MS = 6e4;
|
|
@@ -2489,7 +4010,7 @@ function boundHostServiceLog(environment = process.env) {
|
|
|
2489
4010
|
ready.then(() => rotateHostServiceLog(path)).catch((error) => {
|
|
2490
4011
|
if (reported) return;
|
|
2491
4012
|
reported = true;
|
|
2492
|
-
|
|
4013
|
+
writeHostServiceLogLine(`[host-service-log] rotation_failed code=${errorCode3(error)}
|
|
2493
4014
|
`);
|
|
2494
4015
|
});
|
|
2495
4016
|
};
|
|
@@ -2499,10 +4020,22 @@ function boundHostServiceLog(environment = process.env) {
|
|
|
2499
4020
|
return () => clearInterval(timer);
|
|
2500
4021
|
}
|
|
2501
4022
|
function writeHostServiceLogLine(line, environment = process.env) {
|
|
4023
|
+
void persistHostServiceLogLine(line, environment);
|
|
4024
|
+
defaultHostServiceLogDelivery(line);
|
|
4025
|
+
}
|
|
4026
|
+
async function writeHostServiceCommandResult(schemaVersion, result, sink) {
|
|
4027
|
+
const line = `${JSON.stringify({ schema_version: schemaVersion, ...result })}
|
|
4028
|
+
`;
|
|
4029
|
+
const serviceLine = `${JSON.stringify({ schema_version: schemaVersion, ok: result.ok, ...!result.ok ? { code: isHostOwnedFailureCode(result.code) ? result.code : "host_failure_unclassified" } : {} })}
|
|
4030
|
+
`;
|
|
4031
|
+
await persistHostServiceLogLine(serviceLine);
|
|
4032
|
+
sink(line);
|
|
4033
|
+
}
|
|
4034
|
+
async function persistHostServiceLogLine(line, environment = process.env) {
|
|
2502
4035
|
if (process.platform !== "win32") return;
|
|
2503
4036
|
const path = environment[HOST_SERVICE_LOG_ENVIRONMENT];
|
|
2504
4037
|
if (path === void 0 || !win325.isAbsolute(path) || win325.normalize(path) !== path) return;
|
|
2505
|
-
|
|
4038
|
+
await appendHostServiceLogLine(path, line).catch(() => void 0);
|
|
2506
4039
|
}
|
|
2507
4040
|
async function appendHostServiceLogLine(path, line) {
|
|
2508
4041
|
if (!isAbsolute(path)) return;
|
|
@@ -2512,10 +4045,10 @@ async function appendHostServiceLogLine(path, line) {
|
|
|
2512
4045
|
var HOST_SERVICE_LOG_TAIL_BYTES = 64 * 1024;
|
|
2513
4046
|
var hostServiceLogDirectories = /* @__PURE__ */ new Map();
|
|
2514
4047
|
function ensureHostServiceLogDirectory(path) {
|
|
2515
|
-
const directory =
|
|
4048
|
+
const directory = dirname5(path);
|
|
2516
4049
|
const existing = hostServiceLogDirectories.get(directory);
|
|
2517
4050
|
if (existing !== void 0) return existing;
|
|
2518
|
-
const pending =
|
|
4051
|
+
const pending = mkdir3(directory, { recursive: true, mode: 448 }).then(() => void 0).catch((error) => {
|
|
2519
4052
|
hostServiceLogDirectories.delete(directory);
|
|
2520
4053
|
throw error;
|
|
2521
4054
|
});
|
|
@@ -2523,21 +4056,97 @@ function ensureHostServiceLogDirectory(path) {
|
|
|
2523
4056
|
return pending;
|
|
2524
4057
|
}
|
|
2525
4058
|
function isNotFound(error) {
|
|
2526
|
-
return
|
|
4059
|
+
return errorCode3(error) === "ENOENT";
|
|
2527
4060
|
}
|
|
2528
|
-
function
|
|
4061
|
+
function errorCode3(error) {
|
|
2529
4062
|
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "unknown";
|
|
2530
4063
|
}
|
|
2531
4064
|
|
|
4065
|
+
// host/relay/src/host-usage-facts-uploader.ts
|
|
4066
|
+
var HostUsageFactsUploader = class {
|
|
4067
|
+
options;
|
|
4068
|
+
store;
|
|
4069
|
+
constructor(options) {
|
|
4070
|
+
if (options.producer !== "codex" && options.producer !== "claude") throw new TypeError("Host usage facts producer is invalid.");
|
|
4071
|
+
this.options = options;
|
|
4072
|
+
this.store = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
|
|
4073
|
+
}
|
|
4074
|
+
async close() {
|
|
4075
|
+
await this.store.close();
|
|
4076
|
+
}
|
|
4077
|
+
async uploadOne(signal) {
|
|
4078
|
+
const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
|
|
4079
|
+
if (candidate === null) return false;
|
|
4080
|
+
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);
|
|
4081
|
+
const timeout = AbortSignal.timeout(this.options.timeout_ms ?? 5e3);
|
|
4082
|
+
const requestSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
|
|
4083
|
+
const response2 = await this.options.fetch(`${registration.gateway_request_origin}${CEAL_HOST_USAGE_INGRESS_PATH}`, {
|
|
4084
|
+
method: "POST",
|
|
4085
|
+
headers: { authorization: `Bearer ${registration.host_access_token}`, "content-type": "application/json" },
|
|
4086
|
+
body: JSON.stringify(candidate.batch),
|
|
4087
|
+
signal: requestSignal
|
|
4088
|
+
});
|
|
4089
|
+
if (response2.status !== CEAL_HOST_USAGE_BATCH_ACK_STATUS) {
|
|
4090
|
+
await response2.body?.cancel().catch(() => void 0);
|
|
4091
|
+
throw new Error("Gateway did not acknowledge the Host usage facts batch.");
|
|
4092
|
+
}
|
|
4093
|
+
await this.store.acknowledge(candidate.state, candidate.batch.batch_ref);
|
|
4094
|
+
return true;
|
|
4095
|
+
}
|
|
4096
|
+
};
|
|
4097
|
+
async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
|
|
4098
|
+
const uploader = new HostUsageFactsUploader(options);
|
|
4099
|
+
let delay = 500;
|
|
4100
|
+
let failures = 0;
|
|
4101
|
+
try {
|
|
4102
|
+
while (!signal.aborted) {
|
|
4103
|
+
try {
|
|
4104
|
+
await options.capture_next?.();
|
|
4105
|
+
} catch {
|
|
4106
|
+
writeHostServiceDiagnostic(options.producer, "usage_capture_failed", void 0, "capture_failed");
|
|
4107
|
+
}
|
|
4108
|
+
if (signal.aborted) return;
|
|
4109
|
+
try {
|
|
4110
|
+
const uploaded = await uploader.uploadOne(signal);
|
|
4111
|
+
failures = 0;
|
|
4112
|
+
delay = uploaded ? 100 : 1e3;
|
|
4113
|
+
} catch {
|
|
4114
|
+
if (signal.aborted) return;
|
|
4115
|
+
failures += 1;
|
|
4116
|
+
delay = Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
|
|
4117
|
+
writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
|
|
4118
|
+
}
|
|
4119
|
+
if (!signal.aborted) await wait(signal, delay);
|
|
4120
|
+
}
|
|
4121
|
+
} finally {
|
|
4122
|
+
await uploader.close().catch(() => void 0);
|
|
4123
|
+
}
|
|
4124
|
+
}
|
|
4125
|
+
|
|
2532
4126
|
// host/relay/src/host-producer-core.ts
|
|
2533
|
-
import { createHash as
|
|
4127
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
2534
4128
|
var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
|
|
2535
4129
|
function isHostTranscriptCursorReason(value) {
|
|
2536
4130
|
return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
|
|
2537
4131
|
}
|
|
2538
4132
|
var TRANSCRIPT_MISSING_REASON = "transcript_missing";
|
|
2539
4133
|
var TRANSCRIPT_SCAN_READ_ERROR_ERRNOS = ["EBADF", "EACCES", "EIO", "EMFILE", "ENFILE", "ENOENT", "ENOTDIR", "EPERM"];
|
|
2540
|
-
var
|
|
4134
|
+
var HOST_INVOCATION_TRANSCRIPT_READ_MAX_BYTES = 1024 * 1024;
|
|
4135
|
+
function mergeHostInvocationHumanMessageWindow(existing, chronological) {
|
|
4136
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4137
|
+
const newestFirst = [];
|
|
4138
|
+
for (const message of [...chronological].reverse()) {
|
|
4139
|
+
if (seen.has(message.host_input_ref)) continue;
|
|
4140
|
+
seen.add(message.host_input_ref);
|
|
4141
|
+
newestFirst.push(message);
|
|
4142
|
+
}
|
|
4143
|
+
for (const message of existing?.messages ?? []) {
|
|
4144
|
+
if (seen.has(message.host_input_ref)) continue;
|
|
4145
|
+
seen.add(message.host_input_ref);
|
|
4146
|
+
newestFirst.push(message);
|
|
4147
|
+
}
|
|
4148
|
+
return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
|
|
4149
|
+
}
|
|
2541
4150
|
function transcriptScanFailureKind(error, adapterFailureKind) {
|
|
2542
4151
|
if (transcriptErrorCode(error) === "ELOOP") return "symlink";
|
|
2543
4152
|
const adapter = adapterFailureKind(error);
|
|
@@ -2594,10 +4203,10 @@ async function transcriptCursorBoundsReason(handle, cursor, size) {
|
|
|
2594
4203
|
return null;
|
|
2595
4204
|
}
|
|
2596
4205
|
function transcriptSha256(value) {
|
|
2597
|
-
return
|
|
4206
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
2598
4207
|
}
|
|
2599
4208
|
function transcriptObjectSha256(value) {
|
|
2600
|
-
return
|
|
4209
|
+
return createHash6("sha256").update(JSON.stringify(value), "utf8").digest("hex");
|
|
2601
4210
|
}
|
|
2602
4211
|
function isTranscriptRecord(value) {
|
|
2603
4212
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -2619,7 +4228,7 @@ function createTranscriptWatcherBase(options, owner) {
|
|
|
2619
4228
|
outboxRetentionMs: options.retention_ms ?? owner.default_retention_ms,
|
|
2620
4229
|
now: options.now ?? (() => /* @__PURE__ */ new Date()),
|
|
2621
4230
|
log: options.log ?? ((line) => {
|
|
2622
|
-
|
|
4231
|
+
writeHostServiceLogLine(`${line}
|
|
2623
4232
|
`);
|
|
2624
4233
|
}),
|
|
2625
4234
|
producerInstallationRef: options.producer_installation_ref
|
|
@@ -2659,7 +4268,13 @@ var HostTranscriptWatcher = class {
|
|
|
2659
4268
|
}
|
|
2660
4269
|
async scanRegistration(registration) {
|
|
2661
4270
|
return this.openTranscript(registration, (handle) => this.scanOpened(handle, registration), {
|
|
2662
|
-
missing: () =>
|
|
4271
|
+
missing: async () => {
|
|
4272
|
+
try {
|
|
4273
|
+
return await this.retireMissing(registration);
|
|
4274
|
+
} catch (error) {
|
|
4275
|
+
return this.scanFailed(void 0, registration, error);
|
|
4276
|
+
}
|
|
4277
|
+
},
|
|
2663
4278
|
failed: (handle, error) => this.scanFailed(handle, registration, error)
|
|
2664
4279
|
});
|
|
2665
4280
|
}
|
|
@@ -2742,8 +4357,8 @@ var HostProducerDrainCore = class {
|
|
|
2742
4357
|
};
|
|
2743
4358
|
|
|
2744
4359
|
// host/codex/src/codex-outbox.ts
|
|
2745
|
-
import { mkdir as
|
|
2746
|
-
import { dirname as
|
|
4360
|
+
import { mkdir as mkdir4, open as open4, readdir, rename as rename2, stat as stat2, unlink as unlink3 } from "node:fs/promises";
|
|
4361
|
+
import { dirname as dirname6, isAbsolute as isAbsolute2, join as join4 } from "node:path";
|
|
2747
4362
|
|
|
2748
4363
|
// host/invocation-context.ts
|
|
2749
4364
|
var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
|
|
@@ -2778,7 +4393,7 @@ function invocationContextFromTurn(identity, promptRef, expiresAt, descriptor) {
|
|
|
2778
4393
|
return Object.freeze(context);
|
|
2779
4394
|
}
|
|
2780
4395
|
function isHostInvocationTurnSelection(value) {
|
|
2781
|
-
return
|
|
4396
|
+
return isRecord4(value) && Object.keys(value).length === 5 && value.schema_version === HOST_INVOCATION_TURN_SELECTION_SCHEMA && ["host_source_ref", "host_session_ref", "prompt_ref", "turn_generation_ref"].every((key) => safeRef(value[key]));
|
|
2782
4397
|
}
|
|
2783
4398
|
function exactKeys(value, keys) {
|
|
2784
4399
|
const actual = Object.keys(value);
|
|
@@ -2789,7 +4404,7 @@ function requiredKeys(value, required, optional) {
|
|
|
2789
4404
|
const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
|
|
2790
4405
|
return actual.length >= required.length && actual.length <= allowed.size && required.every((key) => Object.hasOwn(value, key)) && actual.every((key) => allowed.has(key));
|
|
2791
4406
|
}
|
|
2792
|
-
function
|
|
4407
|
+
function isRecord4(value) {
|
|
2793
4408
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2794
4409
|
}
|
|
2795
4410
|
function safeRef(value) {
|
|
@@ -2810,18 +4425,107 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
|
|
|
2810
4425
|
"frame_too_large"
|
|
2811
4426
|
];
|
|
2812
4427
|
|
|
2813
|
-
// host/relay/src/
|
|
2814
|
-
import {
|
|
2815
|
-
var
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
unique_ref: () => `${process.pid}.${crypto.randomUUID()}`
|
|
4428
|
+
// host/relay/src/host-usage-facts-capture.ts
|
|
4429
|
+
import { constants as constants5 } from "node:fs";
|
|
4430
|
+
var HOST_USAGE_FACTS_SCAN_MAX_BYTES = 1024 * 1024;
|
|
4431
|
+
var HOST_USAGE_FACTS_SCAN_MAX_ROWS = 256;
|
|
4432
|
+
var HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES = 64 * 1024;
|
|
4433
|
+
var HostUsageTranscriptSourceError = class extends Error {
|
|
4434
|
+
constructor(options) {
|
|
4435
|
+
super("Host usage transcript source could not be read.", options);
|
|
4436
|
+
this.name = "HostUsageTranscriptSourceError";
|
|
4437
|
+
}
|
|
2824
4438
|
};
|
|
4439
|
+
async function readHostUsageTranscriptSource(read) {
|
|
4440
|
+
try {
|
|
4441
|
+
return await read();
|
|
4442
|
+
} catch (error) {
|
|
4443
|
+
throw new HostUsageTranscriptSourceError({ cause: error });
|
|
4444
|
+
}
|
|
4445
|
+
}
|
|
4446
|
+
async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
|
|
4447
|
+
if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
|
|
4448
|
+
let failed = false;
|
|
4449
|
+
for (let attempt = 0; attempt < registrations.length; attempt += 1) {
|
|
4450
|
+
const index = (startIndex + attempt) % registrations.length;
|
|
4451
|
+
const registration = registrations[index];
|
|
4452
|
+
if (registration === void 0) continue;
|
|
4453
|
+
try {
|
|
4454
|
+
if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
|
|
4455
|
+
} catch (error) {
|
|
4456
|
+
if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
|
|
4457
|
+
failed = true;
|
|
4458
|
+
}
|
|
4459
|
+
}
|
|
4460
|
+
return { captured: false, nextIndex: startIndex, failed };
|
|
4461
|
+
}
|
|
4462
|
+
async function openHostUsageTranscriptCursor(input) {
|
|
4463
|
+
const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants5.O_RDONLY));
|
|
4464
|
+
let source;
|
|
4465
|
+
try {
|
|
4466
|
+
source = await readHostUsageTranscriptSource(() => input.inspect(handle));
|
|
4467
|
+
} catch (error) {
|
|
4468
|
+
await handle.close().catch(() => void 0);
|
|
4469
|
+
throw error;
|
|
4470
|
+
}
|
|
4471
|
+
const sourceFileRef = hostUsageSourceFileReference(input.source_kind, input.host_source_ref, input.host_session_ref, source.device, source.inode);
|
|
4472
|
+
let prepared;
|
|
4473
|
+
try {
|
|
4474
|
+
prepared = await input.store.prepareSourceCursor(input.producer, input.host_source_ref, input.host_session_ref, input.source_slot, input.initial_cursor(sourceFileRef, source.device, source.inode), input.created_at);
|
|
4475
|
+
} catch (error) {
|
|
4476
|
+
await handle.close().catch(() => void 0);
|
|
4477
|
+
throw error;
|
|
4478
|
+
}
|
|
4479
|
+
if (prepared === null) {
|
|
4480
|
+
await handle.close();
|
|
4481
|
+
return null;
|
|
4482
|
+
}
|
|
4483
|
+
return { handle, source, source_file_ref: sourceFileRef, ...prepared };
|
|
4484
|
+
}
|
|
4485
|
+
async function readHostUsageTranscriptChunk(handle, offset, size, skippingOversizedLine) {
|
|
4486
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(size) || size < offset) throw new TypeError("Host usage transcript range is invalid.");
|
|
4487
|
+
if (size === offset) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
|
|
4488
|
+
if (skippingOversizedLine) return await resumeOversizedLine(handle, offset, size);
|
|
4489
|
+
const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
|
|
4490
|
+
const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
|
|
4491
|
+
if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: skippingOversizedLine, oversized_rows: 0 };
|
|
4492
|
+
const chunk = bytes.subarray(0, bytesRead);
|
|
4493
|
+
return completeChunk(chunk, offset);
|
|
4494
|
+
}
|
|
4495
|
+
async function resumeOversizedLine(handle, offset, size) {
|
|
4496
|
+
const bytes = Buffer.allocUnsafe(Math.min(HOST_USAGE_FACTS_SCAN_MAX_BYTES, size - offset));
|
|
4497
|
+
const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
|
|
4498
|
+
if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
|
|
4499
|
+
const chunk = bytes.subarray(0, bytesRead);
|
|
4500
|
+
const delimiter = chunk.indexOf(10);
|
|
4501
|
+
if (delimiter < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
|
|
4502
|
+
return completeChunk(chunk.subarray(delimiter + 1), offset + delimiter + 1);
|
|
4503
|
+
}
|
|
4504
|
+
function completeChunk(chunk, offset) {
|
|
4505
|
+
const parsed = completeLinePrefix(chunk, offset);
|
|
4506
|
+
const oversizedRows = parsed.oversizedRows + (parsed.incompleteOversized ? 1 : 0);
|
|
4507
|
+
const endOffset = parsed.incompleteOversized ? offset + chunk.length : parsed.endOffset;
|
|
4508
|
+
return { lines: parsed.lines, end_offset: endOffset, skipping_oversized_line: parsed.incompleteOversized, oversized_rows: oversizedRows };
|
|
4509
|
+
}
|
|
4510
|
+
function completeLinePrefix(bytes, baseOffset) {
|
|
4511
|
+
const lines = [];
|
|
4512
|
+
let lineStart = 0;
|
|
4513
|
+
let endOffset = baseOffset;
|
|
4514
|
+
let oversizedRows = 0;
|
|
4515
|
+
let rowCount = 0;
|
|
4516
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
4517
|
+
if (bytes[index] !== 10) continue;
|
|
4518
|
+
const line = bytes.subarray(lineStart, index);
|
|
4519
|
+
if (line.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES) oversizedRows += 1;
|
|
4520
|
+
else lines.push(line);
|
|
4521
|
+
lineStart = index + 1;
|
|
4522
|
+
endOffset = baseOffset + lineStart;
|
|
4523
|
+
rowCount += 1;
|
|
4524
|
+
if (rowCount >= HOST_USAGE_FACTS_SCAN_MAX_ROWS) return { lines, endOffset, oversizedRows, incompleteOversized: false };
|
|
4525
|
+
}
|
|
4526
|
+
const incomplete = bytes.subarray(lineStart);
|
|
4527
|
+
return { lines, endOffset, oversizedRows, incompleteOversized: incomplete.length > HOST_USAGE_FACTS_SOURCE_ROW_MAX_BYTES };
|
|
4528
|
+
}
|
|
2825
4529
|
|
|
2826
4530
|
// host/relay/src/relay-quarantine-store.ts
|
|
2827
4531
|
var RELAY_QUARANTINE_MAX_BYTES = 16 * 1024 * 1024;
|
|
@@ -2838,16 +4542,6 @@ var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
|
|
|
2838
4542
|
|
|
2839
4543
|
// host/relay/src/relay-ipc.ts
|
|
2840
4544
|
var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
|
|
2841
|
-
var HOST_RELAY_EXCHANGE_FAILURES = vocabulary([
|
|
2842
|
-
"permission_denied",
|
|
2843
|
-
"socket_missing",
|
|
2844
|
-
"connection_refused",
|
|
2845
|
-
"closed_early",
|
|
2846
|
-
"response_invalid",
|
|
2847
|
-
"timed_out",
|
|
2848
|
-
"cancelled",
|
|
2849
|
-
"unavailable"
|
|
2850
|
-
]);
|
|
2851
4545
|
|
|
2852
4546
|
// host/codex/src/codex-types.ts
|
|
2853
4547
|
var CODEX_OUTBOX_SCHEMA_VERSION = "ceal.codex_observation_outbox.v1";
|
|
@@ -2878,12 +4572,12 @@ function validateCodexHostInvocationContext(value) {
|
|
|
2878
4572
|
validateContextTimes(value);
|
|
2879
4573
|
}
|
|
2880
4574
|
function validateIdentity2(value) {
|
|
2881
|
-
if (!
|
|
4575
|
+
if (!isRecord5(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every(safeRef2)) {
|
|
2882
4576
|
throw new CodexHostAdapterError("storage", "Codex Host invocation identity is malformed.");
|
|
2883
4577
|
}
|
|
2884
4578
|
}
|
|
2885
4579
|
function isContextShape(value) {
|
|
2886
|
-
return
|
|
4580
|
+
return isRecord5(value) && hasHostInvocationContextKeys(value, ["turn_generation_ref"]) && value.schema_version === CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION;
|
|
2887
4581
|
}
|
|
2888
4582
|
function validateContextReferences(value) {
|
|
2889
4583
|
if (!safeRef2(value.prompt_ref) || !optionalSafeRef(value.turn_generation_ref)) throw new CodexHostAdapterError("storage", "Codex Host invocation context is malformed.");
|
|
@@ -2901,7 +4595,7 @@ function safeRef2(value) {
|
|
|
2901
4595
|
function timestamp(value) {
|
|
2902
4596
|
return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
|
|
2903
4597
|
}
|
|
2904
|
-
function
|
|
4598
|
+
function isRecord5(value) {
|
|
2905
4599
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2906
4600
|
}
|
|
2907
4601
|
|
|
@@ -2919,12 +4613,12 @@ var CodexOutboxStore = class {
|
|
|
2919
4613
|
constructor(directory) {
|
|
2920
4614
|
if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
|
|
2921
4615
|
this.directory = directory;
|
|
2922
|
-
this.entriesDirectory =
|
|
2923
|
-
this.sessionsDirectory =
|
|
2924
|
-
this.activeContextsDirectory =
|
|
2925
|
-
this.turnSelectionsDirectory =
|
|
2926
|
-
this.registrationsDirectory =
|
|
2927
|
-
this.cursorsDirectory =
|
|
4616
|
+
this.entriesDirectory = join4(directory, "entries");
|
|
4617
|
+
this.sessionsDirectory = join4(directory, "sessions");
|
|
4618
|
+
this.activeContextsDirectory = join4(directory, "active-contexts");
|
|
4619
|
+
this.turnSelectionsDirectory = join4(directory, "turn-selections");
|
|
4620
|
+
this.registrationsDirectory = join4(directory, "transcript-registrations");
|
|
4621
|
+
this.cursorsDirectory = join4(directory, "transcript-cursors");
|
|
2928
4622
|
}
|
|
2929
4623
|
async prepare() {
|
|
2930
4624
|
for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
|
|
@@ -2943,7 +4637,7 @@ var CodexOutboxStore = class {
|
|
|
2943
4637
|
for (const name of await readdir(this.entriesDirectory)) {
|
|
2944
4638
|
if (!name.endsWith(".json")) continue;
|
|
2945
4639
|
try {
|
|
2946
|
-
const value = JSON.parse(await readOwnerStateFile(
|
|
4640
|
+
const value = JSON.parse(await readOwnerStateFile(join4(this.entriesDirectory, name)));
|
|
2947
4641
|
validateEnvelope(value);
|
|
2948
4642
|
entries.push(value);
|
|
2949
4643
|
} catch {
|
|
@@ -2956,7 +4650,7 @@ var CodexOutboxStore = class {
|
|
|
2956
4650
|
async remove(entry) {
|
|
2957
4651
|
validateEnvelope(entry);
|
|
2958
4652
|
try {
|
|
2959
|
-
await
|
|
4653
|
+
await unlink3(this.entryPath(entry.submission_ref));
|
|
2960
4654
|
} catch (error) {
|
|
2961
4655
|
if (!isNotFound2(error)) throw storageError("Unable to remove the Codex outbox entry.");
|
|
2962
4656
|
}
|
|
@@ -2974,7 +4668,7 @@ var CodexOutboxStore = class {
|
|
|
2974
4668
|
await writeAtomicJson(path, context);
|
|
2975
4669
|
} catch (error) {
|
|
2976
4670
|
try {
|
|
2977
|
-
await
|
|
4671
|
+
await unlink3(path);
|
|
2978
4672
|
} catch (unlinkError) {
|
|
2979
4673
|
if (!isNotFound2(unlinkError)) throw storageError("Unable to clear a failed Codex Host context replacement.");
|
|
2980
4674
|
}
|
|
@@ -2989,13 +4683,13 @@ var CodexOutboxStore = class {
|
|
|
2989
4683
|
async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
|
|
2990
4684
|
if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
|
|
2991
4685
|
await this.prepare();
|
|
2992
|
-
return
|
|
4686
|
+
return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
|
|
2993
4687
|
}
|
|
2994
4688
|
async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
|
|
2995
4689
|
const selection = await this.readInvocationTurnSelection(identity.host_source_ref, identity.host_session_ref);
|
|
2996
4690
|
if (selection === null || selection.prompt_ref !== promptRef || selection.turn_generation_ref !== turnGenerationRef) return false;
|
|
2997
4691
|
const path = this.activeContextPath(identity);
|
|
2998
|
-
const active = await
|
|
4692
|
+
const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
|
|
2999
4693
|
if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
|
|
3000
4694
|
await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
|
|
3001
4695
|
return true;
|
|
@@ -3014,7 +4708,7 @@ var CodexOutboxStore = class {
|
|
|
3014
4708
|
async readRawInvocationContext(hostSourceRef, hostSessionRef) {
|
|
3015
4709
|
if (!SAFE_REF3.test(hostSourceRef) || !SAFE_REF3.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
|
|
3016
4710
|
await this.prepare();
|
|
3017
|
-
const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) =>
|
|
4711
|
+
const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
|
|
3018
4712
|
return context;
|
|
3019
4713
|
}
|
|
3020
4714
|
/** Clear the projection only if the caller still owns its exact active turn. */
|
|
@@ -3023,7 +4717,7 @@ var CodexOutboxStore = class {
|
|
|
3023
4717
|
const active = await this.readInvocationContext(identity.host_source_ref, identity.host_session_ref, now);
|
|
3024
4718
|
if (active === null || !sameIdentity(active.identity, identity)) return false;
|
|
3025
4719
|
try {
|
|
3026
|
-
await
|
|
4720
|
+
await unlink3(this.activeContextPath(identity));
|
|
3027
4721
|
} catch (error) {
|
|
3028
4722
|
if (!isNotFound2(error)) throw storageError("Unable to clear the Codex Host invocation context.");
|
|
3029
4723
|
}
|
|
@@ -3038,13 +4732,13 @@ var CodexOutboxStore = class {
|
|
|
3038
4732
|
const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
|
|
3039
4733
|
if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
|
|
3040
4734
|
await this.prepare();
|
|
3041
|
-
return
|
|
4735
|
+
return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession);
|
|
3042
4736
|
}
|
|
3043
4737
|
async registerTranscript(registration) {
|
|
3044
4738
|
validateRegistration(registration);
|
|
3045
4739
|
await this.prepare();
|
|
3046
4740
|
const path = this.registrationPath(registration.host_source_ref, registration.host_session_ref);
|
|
3047
|
-
const existing = await
|
|
4741
|
+
const existing = await readOptionalJson2(path, validateRegistration);
|
|
3048
4742
|
if (existing !== null && (existing.codex_session_id !== registration.codex_session_id || existing.transcript_path !== registration.transcript_path)) {
|
|
3049
4743
|
throw storageError("Codex transcript registration conflicts with the source-bound session.");
|
|
3050
4744
|
}
|
|
@@ -3069,7 +4763,7 @@ var CodexOutboxStore = class {
|
|
|
3069
4763
|
for (const name of await readdir(this.registrationsDirectory)) {
|
|
3070
4764
|
if (!name.endsWith(".json")) continue;
|
|
3071
4765
|
try {
|
|
3072
|
-
const value = JSON.parse(await readOwnerStateFile(
|
|
4766
|
+
const value = JSON.parse(await readOwnerStateFile(join4(this.registrationsDirectory, name)));
|
|
3073
4767
|
validateRegistration(value);
|
|
3074
4768
|
registrations.push(value);
|
|
3075
4769
|
} catch {
|
|
@@ -3080,7 +4774,7 @@ var CodexOutboxStore = class {
|
|
|
3080
4774
|
async readTranscriptCursor(registration) {
|
|
3081
4775
|
validateRegistration(registration);
|
|
3082
4776
|
await this.prepare();
|
|
3083
|
-
return
|
|
4777
|
+
return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor);
|
|
3084
4778
|
}
|
|
3085
4779
|
async writeTranscriptCursor(cursor) {
|
|
3086
4780
|
validateCursor(cursor);
|
|
@@ -3103,27 +4797,27 @@ var CodexOutboxStore = class {
|
|
|
3103
4797
|
}
|
|
3104
4798
|
entryPath(submissionRef) {
|
|
3105
4799
|
if (!SAFE_REF3.test(submissionRef)) throw storageError("Codex submission identity is malformed.");
|
|
3106
|
-
return
|
|
4800
|
+
return join4(this.entriesDirectory, `${cealRequestSha256(submissionRef)}.json`);
|
|
3107
4801
|
}
|
|
3108
4802
|
sessionPath(sourceRef, sessionRef) {
|
|
3109
|
-
return
|
|
4803
|
+
return join4(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
|
|
3110
4804
|
}
|
|
3111
4805
|
activeContextPath(identity) {
|
|
3112
|
-
return
|
|
4806
|
+
return join4(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
|
|
3113
4807
|
}
|
|
3114
4808
|
turnSelectionPath(sourceRef, sessionRef) {
|
|
3115
|
-
return
|
|
4809
|
+
return join4(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
|
|
3116
4810
|
}
|
|
3117
4811
|
registrationPath(sourceRef, sessionRef) {
|
|
3118
|
-
return
|
|
4812
|
+
return join4(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
|
|
3119
4813
|
}
|
|
3120
4814
|
cursorPath(sourceRef, sessionRef) {
|
|
3121
|
-
return
|
|
4815
|
+
return join4(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
|
|
3122
4816
|
}
|
|
3123
4817
|
};
|
|
3124
4818
|
async function removeOwnerState(path, what) {
|
|
3125
4819
|
try {
|
|
3126
|
-
await
|
|
4820
|
+
await unlink3(path);
|
|
3127
4821
|
} catch (error) {
|
|
3128
4822
|
if (!isNotFound2(error)) throw storageError(`Unable to retire the Codex transcript ${what}.`);
|
|
3129
4823
|
}
|
|
@@ -3154,7 +4848,7 @@ async function writeAtomicJson(path, value) {
|
|
|
3154
4848
|
if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
|
|
3155
4849
|
const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
|
|
3156
4850
|
try {
|
|
3157
|
-
const handle = await
|
|
4851
|
+
const handle = await open4(temp, "wx");
|
|
3158
4852
|
try {
|
|
3159
4853
|
await handle.writeFile(text, "utf8");
|
|
3160
4854
|
await handle.sync();
|
|
@@ -3162,19 +4856,19 @@ async function writeAtomicJson(path, value) {
|
|
|
3162
4856
|
await handle.close();
|
|
3163
4857
|
}
|
|
3164
4858
|
await rename2(temp, path);
|
|
3165
|
-
await
|
|
4859
|
+
await syncDirectory2(dirname6(path));
|
|
3166
4860
|
} catch (error) {
|
|
3167
4861
|
try {
|
|
3168
|
-
await
|
|
4862
|
+
await unlink3(temp);
|
|
3169
4863
|
} catch {
|
|
3170
4864
|
}
|
|
3171
4865
|
if (error instanceof CodexHostAdapterError) throw error;
|
|
3172
4866
|
throw storageError("Unable to atomically replace Codex owner state.");
|
|
3173
4867
|
}
|
|
3174
4868
|
}
|
|
3175
|
-
async function
|
|
4869
|
+
async function syncDirectory2(path) {
|
|
3176
4870
|
try {
|
|
3177
|
-
const handle = await
|
|
4871
|
+
const handle = await open4(path, "r");
|
|
3178
4872
|
try {
|
|
3179
4873
|
await handle.sync();
|
|
3180
4874
|
} finally {
|
|
@@ -3183,7 +4877,7 @@ async function syncDirectory(path) {
|
|
|
3183
4877
|
} catch {
|
|
3184
4878
|
}
|
|
3185
4879
|
}
|
|
3186
|
-
async function
|
|
4880
|
+
async function readOptionalJson2(path, validate) {
|
|
3187
4881
|
try {
|
|
3188
4882
|
const value = JSON.parse(await readOwnerStateFile(path));
|
|
3189
4883
|
validate(value);
|
|
@@ -3199,7 +4893,7 @@ async function ensureOwnerDirectory(path) {
|
|
|
3199
4893
|
await stat2(path);
|
|
3200
4894
|
} catch (error) {
|
|
3201
4895
|
if (!isNotFound2(error)) throw storageError("Codex owner state directory is unavailable.");
|
|
3202
|
-
await
|
|
4896
|
+
await mkdir4(path, { recursive: true });
|
|
3203
4897
|
}
|
|
3204
4898
|
const stats = await stat2(path);
|
|
3205
4899
|
if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
|
|
@@ -3207,7 +4901,7 @@ async function ensureOwnerDirectory(path) {
|
|
|
3207
4901
|
async function readOwnerStateFile(path) {
|
|
3208
4902
|
let handle;
|
|
3209
4903
|
try {
|
|
3210
|
-
handle = await
|
|
4904
|
+
handle = await open4(path);
|
|
3211
4905
|
const stats = await handle.stat();
|
|
3212
4906
|
if (!stats.isFile()) throw storageError("Codex owner state path is not a regular file.");
|
|
3213
4907
|
return await handle.readFile("utf8");
|
|
@@ -3216,8 +4910,8 @@ async function readOwnerStateFile(path) {
|
|
|
3216
4910
|
}
|
|
3217
4911
|
}
|
|
3218
4912
|
function validateEnvelope(value) {
|
|
3219
|
-
if (!
|
|
3220
|
-
if (!
|
|
4913
|
+
if (!isRecord6(value)) throw storageError("Codex outbox entry is malformed.");
|
|
4914
|
+
if (!sameKeys2(value, ["schema_version", "identity", "host_input_ref", "prompt_ref", "observations", "origin_input", "submission_ref", "created_at", "expires_at"], ["codex_turn_id"])) throw storageError(`Codex outbox entry key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the outbox entry key set")}).`);
|
|
3221
4915
|
if (value.schema_version !== CODEX_OUTBOX_SCHEMA_VERSION) throw storageError(`Codex outbox entry is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CODEX_OUTBOX_SCHEMA_VERSION}`)}).`);
|
|
3222
4916
|
validateIdentity3(value.identity);
|
|
3223
4917
|
validateEnvelopeReferences(value);
|
|
@@ -3232,8 +4926,8 @@ function validateEnvelopeReferences(value) {
|
|
|
3232
4926
|
if (typeof value.origin_input !== "boolean") throw storageError("Codex outbox origin disposition is malformed.");
|
|
3233
4927
|
}
|
|
3234
4928
|
function validateRegistration(value) {
|
|
3235
|
-
if (!
|
|
3236
|
-
if (!
|
|
4929
|
+
if (!isRecord6(value)) throw storageError("Codex transcript registration is malformed.");
|
|
4930
|
+
if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "codex_session_id", "transcript_path", "registered_at", "expires_at"], ["cwd"])) throw storageError(`Codex transcript registration key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the registration key set")}).`);
|
|
3237
4931
|
if (value.schema_version !== CODEX_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION) throw storageError(`Codex transcript registration is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CODEX_TRANSCRIPT_REGISTRATION_SCHEMA_VERSION}`)}).`);
|
|
3238
4932
|
validateRegistrationFields(value);
|
|
3239
4933
|
}
|
|
@@ -3248,13 +4942,28 @@ function validRegistrationCwd(value) {
|
|
|
3248
4942
|
return value === void 0 || typeof value === "string" && isAbsolute2(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
|
|
3249
4943
|
}
|
|
3250
4944
|
function validateCursor(value) {
|
|
3251
|
-
if (!
|
|
3252
|
-
if (!
|
|
4945
|
+
if (!isRecord6(value)) throw storageError("Codex transcript cursor is malformed.");
|
|
4946
|
+
if (!sameKeys2(value, ["schema_version", "host_source_ref", "host_session_ref", "transcript_path", "device", "inode", "offset", "last_ordinal", "anchor_start", "anchor_sha256", "header_validated", "status", "updated_at"], ["active_task", "human_message_window", "reason"])) throw storageError(`Codex transcript cursor key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the cursor key set")}).`);
|
|
4947
|
+
validateCursorIdentityAndPosition(value);
|
|
4948
|
+
validateCursorOptionalFields(value);
|
|
4949
|
+
}
|
|
4950
|
+
function validateCursorIdentityAndPosition(value) {
|
|
3253
4951
|
if (value.schema_version !== CODEX_TRANSCRIPT_CURSOR_SCHEMA_VERSION) throw storageError(`Codex transcript cursor is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CODEX_TRANSCRIPT_CURSOR_SCHEMA_VERSION}`)}).`);
|
|
3254
4952
|
if (!validCursorSource(value) || !validCursorPosition(value) || !validCursorStatus(value)) throw storageError("Codex transcript cursor fields are malformed.");
|
|
4953
|
+
}
|
|
4954
|
+
function validateCursorOptionalFields(value) {
|
|
3255
4955
|
if (value.active_task !== void 0 && !validActiveTask(value.active_task)) throw storageError("Codex transcript task cursor is malformed.");
|
|
4956
|
+
validateHumanMessageProjection(value.human_message_window);
|
|
3256
4957
|
if (value.reason !== void 0 && !isHostTranscriptCursorReason(value.reason)) throw storageError("Codex transcript cursor reason is malformed.");
|
|
3257
4958
|
}
|
|
4959
|
+
function validateHumanMessageProjection(value) {
|
|
4960
|
+
if (value === void 0) return;
|
|
4961
|
+
try {
|
|
4962
|
+
decodeCealHostInvocationHumanMessageWindow(value);
|
|
4963
|
+
} catch {
|
|
4964
|
+
throw storageError("Codex transcript human-message projection is malformed.");
|
|
4965
|
+
}
|
|
4966
|
+
}
|
|
3258
4967
|
function validCursorSource(value) {
|
|
3259
4968
|
return [value.host_source_ref, value.host_session_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate)) && typeof value.transcript_path === "string" && value.transcript_path.length > 0 && typeof value.device === "string" && typeof value.inode === "string";
|
|
3260
4969
|
}
|
|
@@ -3265,7 +4974,7 @@ function validCursorStatus(value) {
|
|
|
3265
4974
|
return (value.status === "active" || value.status === "quarantined") && isTimestamp(value.updated_at);
|
|
3266
4975
|
}
|
|
3267
4976
|
function validActiveTask(value) {
|
|
3268
|
-
if (!
|
|
4977
|
+
if (!isRecord6(value) || !sameKeys2(value, ["codex_turn_id", "host_turn_ref", "started_at"], ["origin_host_input_ref", "prompt_ref", "model", "token_usage", "last_total_usage", "token_usage_gap_reason"])) return false;
|
|
3269
4978
|
return validActiveTaskIdentity(value) && validActiveTaskReferences(value) && validActiveTaskUsage(value);
|
|
3270
4979
|
}
|
|
3271
4980
|
function validActiveTaskIdentity(value) {
|
|
@@ -3281,7 +4990,7 @@ function validActiveTaskUsage(value) {
|
|
|
3281
4990
|
return (value.token_usage === void 0 || validTokenUsage(value.token_usage)) && (value.last_total_usage === void 0 || validTokenUsage(value.last_total_usage)) && (value.token_usage_gap_reason === void 0 || value.token_usage_gap_reason === "token_count_shape_not_attributable");
|
|
3282
4991
|
}
|
|
3283
4992
|
function validTokenUsage(value) {
|
|
3284
|
-
if (!
|
|
4993
|
+
if (!isRecord6(value) || !sameKeys2(value, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"])) return false;
|
|
3285
4994
|
if (![value.input_tokens, value.cached_input_tokens, value.cache_write_input_tokens, value.output_tokens, value.reasoning_output_tokens, value.total_tokens].every(nonNegativeInteger)) return false;
|
|
3286
4995
|
return 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);
|
|
3287
4996
|
}
|
|
@@ -3301,8 +5010,8 @@ function validateEnvelopeTimestamps(value) {
|
|
|
3301
5010
|
if (!isTimestamp(value.expires_at)) throw storageError("Codex outbox timestamps are malformed.");
|
|
3302
5011
|
}
|
|
3303
5012
|
function validateSession(value) {
|
|
3304
|
-
if (!
|
|
3305
|
-
if (!
|
|
5013
|
+
if (!isRecord6(value)) throw storageError("Codex session snapshot is malformed.");
|
|
5014
|
+
if (!sameKeys2(value, ["schema_version", "host_session_ref", "host_source_ref", "observed_at", "value", "expires_at"])) throw storageError(`Codex session snapshot key set is malformed (${refusalFact("keys", Object.keys(value), "exactly the session snapshot key set")}).`);
|
|
3306
5015
|
if (value.schema_version !== CODEX_SESSION_SCHEMA_VERSION) throw storageError(`Codex session snapshot is malformed (${refusalFact("schema_version", value.schema_version, `expected ${CODEX_SESSION_SCHEMA_VERSION}`)}).`);
|
|
3307
5016
|
if (!SAFE_REF3.test(String(value.host_session_ref)) || !SAFE_REF3.test(String(value.host_source_ref)) || !isTimestamp(value.observed_at) || !isTimestamp(value.expires_at) || !isJsonValue(value.value)) throw storageError("Codex session snapshot fields are malformed.");
|
|
3308
5017
|
}
|
|
@@ -3310,27 +5019,27 @@ function validateTurnSelection(value) {
|
|
|
3310
5019
|
if (!isHostInvocationTurnSelection(value)) throw storageError("Codex Host turn selection is malformed.");
|
|
3311
5020
|
}
|
|
3312
5021
|
function validateIdentity3(value) {
|
|
3313
|
-
if (!
|
|
5022
|
+
if (!isRecord6(value) || !hasHostInvocationIdentityKeys(value) || ![value.host_session_ref, value.host_turn_ref, value.host_source_ref].every((candidate) => typeof candidate === "string" && SAFE_REF3.test(candidate))) throw storageError("Codex Host identity is malformed.");
|
|
3314
5023
|
}
|
|
3315
5024
|
function isJsonValue(value) {
|
|
3316
5025
|
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
3317
5026
|
if (typeof value === "number") return Number.isFinite(value);
|
|
3318
5027
|
if (Array.isArray(value)) return value.every(isJsonValue);
|
|
3319
|
-
return
|
|
5028
|
+
return isRecord6(value) && Object.entries(value).every(([key, child]) => key.length > 0 && key.length <= 128 && isJsonValue(child));
|
|
3320
5029
|
}
|
|
3321
5030
|
function isTimestamp(value) {
|
|
3322
5031
|
return typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value));
|
|
3323
5032
|
}
|
|
3324
|
-
function
|
|
5033
|
+
function sameKeys2(value, required, optional = []) {
|
|
3325
5034
|
const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
|
|
3326
5035
|
const keys = Object.keys(value);
|
|
3327
5036
|
return keys.length >= required.length && keys.length <= allowed.size && required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => allowed.has(key));
|
|
3328
5037
|
}
|
|
3329
|
-
function
|
|
5038
|
+
function isRecord6(value) {
|
|
3330
5039
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3331
5040
|
}
|
|
3332
5041
|
function isNotFound2(error) {
|
|
3333
|
-
return
|
|
5042
|
+
return isRecord6(error) && error.code === "ENOENT";
|
|
3334
5043
|
}
|
|
3335
5044
|
function storageError(message) {
|
|
3336
5045
|
return new CodexHostAdapterError("storage", message);
|
|
@@ -3359,7 +5068,7 @@ var CodexProducer = class {
|
|
|
3359
5068
|
};
|
|
3360
5069
|
|
|
3361
5070
|
// host/codex/src/codex-decoder.ts
|
|
3362
|
-
import { createHash as
|
|
5071
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
3363
5072
|
var SAFE_REF4 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
|
3364
5073
|
var MAX_PAYLOAD_BYTES = 512 * 1024;
|
|
3365
5074
|
function observationRef(hostSourceRef, event, identity, value) {
|
|
@@ -3373,23 +5082,23 @@ function hostInputReference(sourceRef, sessionRef, nativeTurnId, messageId, ordi
|
|
|
3373
5082
|
if (![sourceRef, sessionRef, nativeTurnId, messageId].every((value) => SAFE_REF4.test(value)) || !Number.isSafeInteger(ordinal) || ordinal < 0) {
|
|
3374
5083
|
throw new CodexHostAdapterError("invalid_input", "Codex input identity is invalid.");
|
|
3375
5084
|
}
|
|
3376
|
-
return `codex-input:${shortDigest({ source_ref: sourceRef, session_ref: sessionRef, native_turn_id: nativeTurnId, message_id: messageId, ordinal, prompt_sha256:
|
|
5085
|
+
return `codex-input:${shortDigest({ source_ref: sourceRef, session_ref: sessionRef, native_turn_id: nativeTurnId, message_id: messageId, ordinal, prompt_sha256: sha2563(prompt) })}`;
|
|
3377
5086
|
}
|
|
3378
5087
|
function promptObservationValue(prompt) {
|
|
3379
|
-
return { body_sha256:
|
|
5088
|
+
return { body_sha256: sha2563(prompt) };
|
|
3380
5089
|
}
|
|
3381
5090
|
function turnObservationValue(sessionId, turnRef, status) {
|
|
3382
|
-
return { status, host_session_id_sha256:
|
|
5091
|
+
return { status, host_session_id_sha256: sha2563(sessionId), host_turn_ref: turnRef };
|
|
3383
5092
|
}
|
|
3384
|
-
function
|
|
3385
|
-
return
|
|
5093
|
+
function sha2563(value) {
|
|
5094
|
+
return createHash7("sha256").update(value, "utf8").digest("hex");
|
|
3386
5095
|
}
|
|
3387
5096
|
function shortDigest(value) {
|
|
3388
5097
|
return cealRequestSha256(value);
|
|
3389
5098
|
}
|
|
3390
5099
|
|
|
3391
5100
|
// host/codex/src/codex-transcript-baseline.ts
|
|
3392
|
-
import { createHash as
|
|
5101
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
3393
5102
|
|
|
3394
5103
|
// host/codex/src/codex-transcript-decoder.ts
|
|
3395
5104
|
var SAFE_REF5 = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
|
|
@@ -3401,16 +5110,32 @@ function decodeCodexTranscriptLine(line) {
|
|
|
3401
5110
|
} catch {
|
|
3402
5111
|
reject("Codex transcript record is not valid JSON.");
|
|
3403
5112
|
}
|
|
3404
|
-
if (!
|
|
5113
|
+
if (!isRecord7(value)) reject("Codex transcript record envelope is malformed.");
|
|
3405
5114
|
const ordinal = safeOrdinal(value.ordinal);
|
|
3406
5115
|
const timestamp3 = safeTimestamp(value.timestamp);
|
|
3407
|
-
if (!
|
|
5116
|
+
if (!isRecord7(value.payload) || typeof value.type !== "string") reject("Codex transcript record payload is malformed.");
|
|
3408
5117
|
if (value.type === "session_meta") return decodeSessionMeta(value.payload, ordinal, timestamp3);
|
|
3409
5118
|
if (value.type === "turn_context") return decodeTurnContext(value.payload, ordinal, timestamp3);
|
|
3410
5119
|
if (value.type === "event_msg") return decodeEventMessage(value.payload, ordinal, timestamp3);
|
|
3411
5120
|
if (value.type === "response_item") return decodeResponseItem(value.payload, ordinal, timestamp3);
|
|
3412
5121
|
return { kind: "ignored", ordinal, timestamp: timestamp3 };
|
|
3413
5122
|
}
|
|
5123
|
+
function decodeCodexUsageTranscriptLine(line) {
|
|
5124
|
+
let value;
|
|
5125
|
+
try {
|
|
5126
|
+
value = JSON.parse(line);
|
|
5127
|
+
} catch {
|
|
5128
|
+
reject("Codex transcript record is not valid JSON.");
|
|
5129
|
+
}
|
|
5130
|
+
if (!isRecord7(value)) reject("Codex transcript record envelope is malformed.");
|
|
5131
|
+
const ordinal = safeOrdinal(value.ordinal);
|
|
5132
|
+
const timestamp3 = safeTimestamp(value.timestamp);
|
|
5133
|
+
if (!isRecord7(value.payload) || typeof value.type !== "string") reject("Codex transcript record payload is malformed.");
|
|
5134
|
+
if (value.type === "session_meta") return decodeSessionMeta(value.payload, ordinal, timestamp3);
|
|
5135
|
+
if (value.type === "turn_context") return decodeTurnContext(value.payload, ordinal, timestamp3);
|
|
5136
|
+
if (value.type === "event_msg" && ["task_started", "task_complete", "turn_aborted", "token_count"].includes(String(value.payload.type))) return decodeEventMessage(value.payload, ordinal, timestamp3);
|
|
5137
|
+
return { kind: "ignored", ordinal, timestamp: timestamp3 };
|
|
5138
|
+
}
|
|
3414
5139
|
function decodeTurnContext(payload, ordinal, timestamp3) {
|
|
3415
5140
|
return {
|
|
3416
5141
|
kind: "turn_context",
|
|
@@ -3450,7 +5175,7 @@ function decodeEventMessage(payload, ordinal, timestamp3) {
|
|
|
3450
5175
|
started_at: safeNumber(payload.started_at),
|
|
3451
5176
|
completed_at: safeNumber(payload.completed_at),
|
|
3452
5177
|
duration_ms: safeNumber(payload.duration_ms),
|
|
3453
|
-
reason:
|
|
5178
|
+
reason: boundedText2(payload.reason, 256, "Codex task abort reason is invalid.")
|
|
3454
5179
|
};
|
|
3455
5180
|
}
|
|
3456
5181
|
if (payload.type === "token_count") return decodeTokenCount(payload, ordinal, timestamp3);
|
|
@@ -3458,7 +5183,7 @@ function decodeEventMessage(payload, ordinal, timestamp3) {
|
|
|
3458
5183
|
}
|
|
3459
5184
|
function decodeTokenCount(payload, ordinal, timestamp3) {
|
|
3460
5185
|
if (payload.info === null) return { kind: "token_count", ordinal, timestamp: timestamp3 };
|
|
3461
|
-
if (!
|
|
5186
|
+
if (!isRecord7(payload.info)) return { kind: "token_count", ordinal, timestamp: timestamp3, usage_gap_reason: "token_count_shape_not_attributable" };
|
|
3462
5187
|
const lastUsage = optionalTokenUsage(payload.info.last_token_usage);
|
|
3463
5188
|
const totalUsage = optionalTokenUsage(payload.info.total_token_usage);
|
|
3464
5189
|
const gap = lastUsage.status === "invalid" || totalUsage.status === "invalid";
|
|
@@ -3482,7 +5207,7 @@ function optionalTokenUsage(value) {
|
|
|
3482
5207
|
}
|
|
3483
5208
|
}
|
|
3484
5209
|
function decodeTokenUsage(value) {
|
|
3485
|
-
if (!
|
|
5210
|
+
if (!isRecord7(value)) reject("Codex token usage is malformed.");
|
|
3486
5211
|
const usage = {
|
|
3487
5212
|
input_tokens: safeTokenCount(value.input_tokens),
|
|
3488
5213
|
cached_input_tokens: safeTokenCount(value.cached_input_tokens),
|
|
@@ -3514,14 +5239,14 @@ function userTextContentKind(kinds) {
|
|
|
3514
5239
|
return kinds.length === 1 && (kinds[0] === "user.text" || kinds[0] === "goal.internal_context") ? kinds[0] : void 0;
|
|
3515
5240
|
}
|
|
3516
5241
|
function userMessageMetadata(value) {
|
|
3517
|
-
if (!
|
|
5242
|
+
if (!isRecord7(value) || !Array.isArray(value.content_item_kinds)) reject("Codex user message provenance is malformed.");
|
|
3518
5243
|
return { ...value, content_item_kinds: value.content_item_kinds };
|
|
3519
5244
|
}
|
|
3520
5245
|
function userTextContent(value) {
|
|
3521
5246
|
if (!Array.isArray(value)) reject(`Codex user text content is malformed (${refusalFact("kind", typeof value, "array")}).`);
|
|
3522
5247
|
if (value.length !== 1) reject(`Codex user text content is malformed (${refusalFact("items", value.length, "exactly one")}).`);
|
|
3523
|
-
if (!
|
|
3524
|
-
return
|
|
5248
|
+
if (!isRecord7(value[0]) || value[0].type !== "input_text") reject(`Codex user text content is malformed (${refusalFact("item_type", isRecord7(value[0]) ? value[0].type : typeof value[0], "input_text")}).`);
|
|
5249
|
+
return boundedText2(value[0].text, MAX_PROMPT_BYTES, "Codex user text is invalid.");
|
|
3525
5250
|
}
|
|
3526
5251
|
function safeOrdinal(value) {
|
|
3527
5252
|
if (!Number.isSafeInteger(value) || Number(value) < 0) reject("Codex transcript ordinal is invalid.");
|
|
@@ -3545,18 +5270,18 @@ function safeRef3(value, message) {
|
|
|
3545
5270
|
if (typeof value !== "string" || !SAFE_REF5.test(value)) reject(message);
|
|
3546
5271
|
return value;
|
|
3547
5272
|
}
|
|
3548
|
-
function
|
|
5273
|
+
function boundedText2(value, maximum, message) {
|
|
3549
5274
|
if (typeof value !== "string") reject(`${message} ${refusalFact("kind", typeof value, "string")}.`);
|
|
3550
5275
|
const bytes = Buffer.byteLength(value, "utf8");
|
|
3551
5276
|
if (bytes > maximum) reject(`${message} ${refusalFact("bytes", bytes, `at most ${maximum} UTF-8 bytes`)}.`);
|
|
3552
5277
|
return value;
|
|
3553
5278
|
}
|
|
3554
5279
|
function boundedNonEmptyText(value, maximum, message) {
|
|
3555
|
-
const result =
|
|
5280
|
+
const result = boundedText2(value, maximum, message);
|
|
3556
5281
|
if (result.length === 0) reject(message);
|
|
3557
5282
|
return result;
|
|
3558
5283
|
}
|
|
3559
|
-
function
|
|
5284
|
+
function isRecord7(value) {
|
|
3560
5285
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3561
5286
|
}
|
|
3562
5287
|
function reject(message) {
|
|
@@ -3579,6 +5304,7 @@ function codexTranscriptInitialCursor(registration, device, inode, now) {
|
|
|
3579
5304
|
anchor_start: 0,
|
|
3580
5305
|
anchor_sha256: digest(Buffer.alloc(0)),
|
|
3581
5306
|
header_validated: false,
|
|
5307
|
+
human_message_window: { messages: [], truncated: false },
|
|
3582
5308
|
status: "active",
|
|
3583
5309
|
updated_at: timestamp2(now)
|
|
3584
5310
|
};
|
|
@@ -3589,14 +5315,14 @@ async function ownedCodexTranscriptFile(handle, platform = process.platform) {
|
|
|
3589
5315
|
if (platform !== "win32" && !isSelfOwned(stats.uid, platform, handle)) throw new CodexHostAdapterError("storage", "Codex transcript source is owned by another user.");
|
|
3590
5316
|
return { size: stats.size, device: String(stats.dev), inode: String(stats.ino) };
|
|
3591
5317
|
}
|
|
3592
|
-
function assertCodexTranscriptHeader(registration,
|
|
3593
|
-
if (
|
|
3594
|
-
{ name: "kind", value:
|
|
3595
|
-
{ name: "session_id", value:
|
|
5318
|
+
function assertCodexTranscriptHeader(registration, record2) {
|
|
5319
|
+
if (record2.kind !== "session_meta" || record2.session_id !== registration.codex_session_id) throw new CodexHostAdapterError("payload_rejected", `Codex transcript header does not match its SessionStart registration (${refusalFacts([
|
|
5320
|
+
{ name: "kind", value: record2.kind, expected: "session_meta" },
|
|
5321
|
+
{ name: "session_id", value: record2.kind === "session_meta" ? record2.session_id : "unavailable", expected: registration.codex_session_id }
|
|
3596
5322
|
])}).`);
|
|
3597
5323
|
}
|
|
3598
5324
|
function digest(value) {
|
|
3599
|
-
return
|
|
5325
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
3600
5326
|
}
|
|
3601
5327
|
function timestamp2(now) {
|
|
3602
5328
|
const value = now();
|
|
@@ -3634,8 +5360,11 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
3634
5360
|
const { size, device, inode } = await ownedCodexTranscriptFile(handle);
|
|
3635
5361
|
const preflight = await this.preflight(registration, handle, size, device, inode);
|
|
3636
5362
|
if (preflight.cursor === null) return preflight.result;
|
|
5363
|
+
if (preflight.checkpointPending) await this.commitCursor(registration, handle, preflight.cursor, 0, device, inode, preflight.cursor.last_ordinal, preflight.cursor.active_task, preflight.cursor.human_message_window ?? { messages: [], truncated: false });
|
|
3637
5364
|
const complete = await this.readChunk(handle, preflight.cursor.offset, size);
|
|
3638
|
-
if (complete === "empty" || complete === "partial")
|
|
5365
|
+
if (complete === "empty" || complete === "partial") {
|
|
5366
|
+
return { records: 0, enqueued: 0, quarantined: false };
|
|
5367
|
+
}
|
|
3639
5368
|
return await this.consumeCompleteChunk(registration, handle, preflight.cursor, complete, device, inode);
|
|
3640
5369
|
}
|
|
3641
5370
|
async scanFailed(handle, registration, error) {
|
|
@@ -3650,40 +5379,51 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
3650
5379
|
const existing = await this.store.readTranscriptCursor(registration);
|
|
3651
5380
|
let cursor = existing ?? codexTranscriptInitialCursor(registration, device, inode, this.now);
|
|
3652
5381
|
if (cursor.status === "quarantined") {
|
|
3653
|
-
return { cursor: null, result: { records: 0, enqueued: 0, quarantined: true } };
|
|
5382
|
+
return { cursor: null, checkpointPending: false, result: { records: 0, enqueued: 0, quarantined: true } };
|
|
3654
5383
|
}
|
|
3655
5384
|
const reason = this.cursorIdentityReason(cursor, registration.transcript_path, device, inode) ?? await this.cursorBoundsReason(handle, cursor, size);
|
|
3656
|
-
if (reason === null)
|
|
5385
|
+
if (reason === null) {
|
|
5386
|
+
if (cursor.human_message_window !== void 0) return { cursor, checkpointPending: existing === null, result: { records: 0, enqueued: 0, quarantined: false } };
|
|
5387
|
+
const humanWindow = await this.readHumanMessageProjection(handle, registration, cursor);
|
|
5388
|
+
return { cursor: { ...cursor, human_message_window: humanWindow }, checkpointPending: true, result: { records: 0, enqueued: 0, quarantined: false } };
|
|
5389
|
+
}
|
|
3657
5390
|
await this.quarantine(registration, cursor, device, inode, reason);
|
|
3658
|
-
|
|
5391
|
+
this.diagnostic("watcher_scan_failed", "other", `cursor_${reason}`);
|
|
5392
|
+
return { cursor: null, checkpointPending: false, result: { records: 0, enqueued: 0, quarantined: true } };
|
|
5393
|
+
}
|
|
5394
|
+
async readHumanMessageProjection(handle, registration, cursor) {
|
|
5395
|
+
return readCodexHumanMessageProjection(registration, cursor, (offset, size) => this.readChunk(handle, offset, size));
|
|
3659
5396
|
}
|
|
3660
5397
|
async consumeCompleteChunk(registration, handle, cursor, complete, device, inode) {
|
|
3661
5398
|
let activeTask = cursor.active_task;
|
|
3662
5399
|
let lastOrdinal = cursor.last_ordinal;
|
|
5400
|
+
let humanWindow = cursor.human_message_window ?? { messages: [], truncated: false };
|
|
3663
5401
|
let records = 0;
|
|
3664
5402
|
let enqueued = 0;
|
|
3665
5403
|
for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
|
|
3666
|
-
const
|
|
3667
|
-
assertRecordSequence(registration, cursor, records, lastOrdinal,
|
|
3668
|
-
|
|
3669
|
-
|
|
5404
|
+
const record2 = decodeCodexTranscriptLine(line);
|
|
5405
|
+
assertRecordSequence(registration, cursor, records, lastOrdinal, record2);
|
|
5406
|
+
const message = codexHumanMessage(registration, record2);
|
|
5407
|
+
if (message !== null) humanWindow = mergeHostInvocationHumanMessageWindow(humanWindow, [message]);
|
|
5408
|
+
await this.observeSessionMetadata(registration, record2);
|
|
5409
|
+
const outcome = await this.processRecord(registration, activeTask, record2);
|
|
3670
5410
|
activeTask = outcome.activeTask;
|
|
3671
5411
|
enqueued += outcome.enqueued;
|
|
3672
|
-
lastOrdinal =
|
|
5412
|
+
lastOrdinal = record2.ordinal;
|
|
3673
5413
|
records += 1;
|
|
3674
5414
|
}
|
|
3675
|
-
await this.commitCursor(registration, handle, cursor, complete.length, device, inode, lastOrdinal, activeTask);
|
|
5415
|
+
await this.commitCursor(registration, handle, cursor, complete.length, device, inode, lastOrdinal, activeTask, humanWindow);
|
|
3676
5416
|
return { records, enqueued, quarantined: false };
|
|
3677
5417
|
}
|
|
3678
|
-
async observeSessionMetadata(registration,
|
|
3679
|
-
if (
|
|
5418
|
+
async observeSessionMetadata(registration, record2) {
|
|
5419
|
+
if (record2.kind !== "session_meta") return;
|
|
3680
5420
|
const session = await this.store.readSession(registration.host_source_ref, registration.host_session_ref);
|
|
3681
|
-
if (session !== null && this.isRecord(session.value)) await this.store.saveSession({ ...session, value: { ...session.value, host_version:
|
|
5421
|
+
if (session !== null && this.isRecord(session.value)) await this.store.saveSession({ ...session, value: { ...session.value, host_version: record2.cli_version } });
|
|
3682
5422
|
}
|
|
3683
|
-
async commitCursor(registration, handle, cursor, consumedBytes, device, inode, lastOrdinal, activeTask) {
|
|
5423
|
+
async commitCursor(registration, handle, cursor, consumedBytes, device, inode, lastOrdinal, activeTask, humanWindow) {
|
|
3684
5424
|
const offset = cursor.offset + consumedBytes;
|
|
3685
5425
|
const anchor = await this.readAnchor(handle, offset, CODEX_TRANSCRIPT_ANCHOR_BYTES);
|
|
3686
|
-
await this.store.writeTranscriptCursor({
|
|
5426
|
+
await this.store.writeTranscriptCursor({ ...cursor, transcript_path: registration.transcript_path, device, inode, offset, last_ordinal: lastOrdinal, anchor_start: anchor.start, anchor_sha256: anchor.sha256, header_validated: cursor.header_validated || consumedBytes > 0, human_message_window: humanWindow, ...activeTask === void 0 ? { active_task: void 0 } : { active_task: activeTask }, status: "active", updated_at: this.stamp() });
|
|
3687
5427
|
}
|
|
3688
5428
|
async quarantineFailure(registration, handle) {
|
|
3689
5429
|
if (handle === void 0) return;
|
|
@@ -3701,40 +5441,40 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
3701
5441
|
};
|
|
3702
5442
|
await this.store.writeTranscriptCursor(quarantined);
|
|
3703
5443
|
}
|
|
3704
|
-
async processRecord(registration, activeTask,
|
|
3705
|
-
if (
|
|
3706
|
-
if (
|
|
3707
|
-
if (
|
|
3708
|
-
if (
|
|
3709
|
-
if (
|
|
5444
|
+
async processRecord(registration, activeTask, record2) {
|
|
5445
|
+
if (record2.kind === "task_started") return this.processTaskStarted(registration, record2);
|
|
5446
|
+
if (record2.kind === "turn_context") return { ...activeTask === void 0 ? {} : { activeTask: record2.turn_id === activeTask.codex_turn_id ? { ...activeTask, model: record2.model } : activeTask }, enqueued: 0 };
|
|
5447
|
+
if (record2.kind === "token_count") return { ...activeTask === void 0 ? {} : { activeTask: accumulateTokenCount(activeTask, record2) }, enqueued: 0 };
|
|
5448
|
+
if (record2.kind === "user_text") return this.processUserInput(registration, activeTask, record2);
|
|
5449
|
+
if (record2.kind === "task_complete" || record2.kind === "turn_aborted") return this.processTerminal(registration, activeTask, record2);
|
|
3710
5450
|
return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
|
|
3711
5451
|
}
|
|
3712
|
-
async processTaskStarted(registration,
|
|
3713
|
-
return { activeTask: { codex_turn_id:
|
|
5452
|
+
async processTaskStarted(registration, record2) {
|
|
5453
|
+
return { activeTask: { codex_turn_id: record2.turn_id, host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id), started_at: record2.timestamp }, enqueued: 0 };
|
|
3714
5454
|
}
|
|
3715
|
-
async processUserInput(registration, activeTask,
|
|
3716
|
-
if (activeTask === void 0 || activeTask.codex_turn_id !==
|
|
3717
|
-
const adopted = await this.adoptHookCorrelatedTurn(registration,
|
|
5455
|
+
async processUserInput(registration, activeTask, record2) {
|
|
5456
|
+
if (activeTask === void 0 || activeTask.codex_turn_id !== record2.turn_id) {
|
|
5457
|
+
const adopted = await this.adoptHookCorrelatedTurn(registration, record2);
|
|
3718
5458
|
if (adopted === void 0) return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
|
|
3719
5459
|
activeTask = adopted;
|
|
3720
5460
|
}
|
|
3721
|
-
const hostInputRef = hostInputReference(registration.host_source_ref, registration.host_session_ref,
|
|
5461
|
+
const hostInputRef = hostInputReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id, record2.message_id, record2.ordinal, record2.prompt);
|
|
3722
5462
|
const origin = activeTask.origin_host_input_ref === void 0;
|
|
3723
|
-
const promptValue = promptObservationValue(
|
|
5463
|
+
const promptValue = promptObservationValue(record2.prompt);
|
|
3724
5464
|
const currentPromptRef = hostProducerPromptRef(promptValue.body_sha256);
|
|
3725
5465
|
const promptRef = activeTask.prompt_ref ?? currentPromptRef;
|
|
3726
5466
|
const steeredPromptRef = await this.steeredPromptRef(registration, activeTask, origin, currentPromptRef);
|
|
3727
5467
|
const identity = { host_source_ref: registration.host_source_ref, host_session_ref: registration.host_session_ref, host_turn_ref: activeTask.host_turn_ref };
|
|
3728
5468
|
const observations = [{
|
|
3729
|
-
observation_ref: observationRef(registration.host_source_ref, "transcript_user_text", hostInputRef,
|
|
5469
|
+
observation_ref: observationRef(registration.host_source_ref, "transcript_user_text", hostInputRef, record2.prompt),
|
|
3730
5470
|
observation_kind: "prompt",
|
|
3731
|
-
observed_at:
|
|
5471
|
+
observed_at: record2.timestamp,
|
|
3732
5472
|
value: promptValue
|
|
3733
5473
|
}];
|
|
3734
5474
|
if (origin) {
|
|
3735
|
-
observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_task_started", activeTask.host_turn_ref,
|
|
5475
|
+
observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_task_started", activeTask.host_turn_ref, record2.turn_id), observation_kind: "turn", observed_at: record2.timestamp, value: turnObservationValue(registration.codex_session_id, activeTask.host_turn_ref, "started") });
|
|
3736
5476
|
const session = await this.store.readSession(registration.host_source_ref, registration.host_session_ref);
|
|
3737
|
-
if (session !== null) observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_session", registration.host_session_ref, session.value), observation_kind: "session", observed_at:
|
|
5477
|
+
if (session !== null) observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_session", registration.host_session_ref, session.value), observation_kind: "session", observed_at: record2.timestamp, value: session.value });
|
|
3738
5478
|
}
|
|
3739
5479
|
const envelope = {
|
|
3740
5480
|
schema_version: "ceal.codex_observation_outbox.v1",
|
|
@@ -3742,10 +5482,10 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
3742
5482
|
host_input_ref: hostInputRef,
|
|
3743
5483
|
prompt_ref: promptRef,
|
|
3744
5484
|
observations,
|
|
3745
|
-
codex_turn_id:
|
|
5485
|
+
codex_turn_id: record2.turn_id,
|
|
3746
5486
|
origin_input: origin,
|
|
3747
|
-
submission_ref: codexSubmissionReference(hostInputRef, "input",
|
|
3748
|
-
created_at:
|
|
5487
|
+
submission_ref: codexSubmissionReference(hostInputRef, "input", record2.ordinal),
|
|
5488
|
+
created_at: record2.timestamp,
|
|
3749
5489
|
expires_at: this.expire(this.outboxRetentionMs)
|
|
3750
5490
|
};
|
|
3751
5491
|
const persisted = await this.persistUserInputTurn(activeTask, hostInputRef, origin, currentPromptRef, promptRef, identity, envelope);
|
|
@@ -3775,14 +5515,14 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
3775
5515
|
* stay ignored. A stale active task for another turn releases first, the
|
|
3776
5516
|
* same as a task_started supersession.
|
|
3777
5517
|
*/
|
|
3778
|
-
async adoptHookCorrelatedTurn(registration,
|
|
3779
|
-
const currentPromptRef = hostProducerPromptRef(promptObservationValue(
|
|
5518
|
+
async adoptHookCorrelatedTurn(registration, record2) {
|
|
5519
|
+
const currentPromptRef = hostProducerPromptRef(promptObservationValue(record2.prompt).body_sha256);
|
|
3780
5520
|
const selection = await this.store.readInvocationTurnSelection(registration.host_source_ref, registration.host_session_ref);
|
|
3781
5521
|
if (selection?.prompt_ref !== currentPromptRef) return void 0;
|
|
3782
5522
|
return {
|
|
3783
|
-
codex_turn_id:
|
|
3784
|
-
host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref,
|
|
3785
|
-
started_at:
|
|
5523
|
+
codex_turn_id: record2.turn_id,
|
|
5524
|
+
host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id),
|
|
5525
|
+
started_at: record2.timestamp
|
|
3786
5526
|
};
|
|
3787
5527
|
}
|
|
3788
5528
|
async persistUserInputTurn(activeTask, hostInputRef, origin, currentPromptRef, promptRef, identity, envelope) {
|
|
@@ -3801,21 +5541,21 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
3801
5541
|
throw error;
|
|
3802
5542
|
}
|
|
3803
5543
|
}
|
|
3804
|
-
async processTerminal(registration, activeTask,
|
|
3805
|
-
if (activeTask === void 0 || activeTask.codex_turn_id !==
|
|
5544
|
+
async processTerminal(registration, activeTask, record2) {
|
|
5545
|
+
if (activeTask === void 0 || activeTask.codex_turn_id !== record2.turn_id || activeTask.origin_host_input_ref === void 0 || activeTask.prompt_ref === void 0) return { ...activeTask === void 0 ? {} : { activeTask }, enqueued: 0 };
|
|
3806
5546
|
const identity = { host_source_ref: registration.host_source_ref, host_session_ref: registration.host_session_ref, host_turn_ref: activeTask.host_turn_ref };
|
|
3807
|
-
const timing =
|
|
3808
|
-
const observations = terminalObservations(registration, activeTask,
|
|
5547
|
+
const timing = record2.kind === "task_complete" ? { status: "available", unit: "milliseconds", started_at: record2.started_at, completed_at: record2.completed_at, duration_ms: record2.duration_ms, time_to_first_token_ms: record2.time_to_first_token_ms } : { status: "available", unit: "milliseconds", started_at: record2.started_at, completed_at: record2.completed_at, duration_ms: record2.duration_ms, terminal: "aborted", reason: record2.reason };
|
|
5548
|
+
const observations = terminalObservations(registration, activeTask, record2, timing);
|
|
3809
5549
|
await this.store.put({
|
|
3810
5550
|
schema_version: "ceal.codex_observation_outbox.v1",
|
|
3811
5551
|
identity,
|
|
3812
5552
|
host_input_ref: activeTask.origin_host_input_ref,
|
|
3813
5553
|
prompt_ref: activeTask.prompt_ref,
|
|
3814
5554
|
observations,
|
|
3815
|
-
codex_turn_id:
|
|
5555
|
+
codex_turn_id: record2.turn_id,
|
|
3816
5556
|
origin_input: false,
|
|
3817
|
-
submission_ref: codexSubmissionReference(activeTask.origin_host_input_ref, "terminal",
|
|
3818
|
-
created_at:
|
|
5557
|
+
submission_ref: codexSubmissionReference(activeTask.origin_host_input_ref, "terminal", record2.ordinal),
|
|
5558
|
+
created_at: record2.timestamp,
|
|
3819
5559
|
expires_at: this.expire(this.outboxRetentionMs)
|
|
3820
5560
|
});
|
|
3821
5561
|
await this.store.clearInvocationContext(identity, this.now());
|
|
@@ -3826,6 +5566,29 @@ var CodexTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
3826
5566
|
await this.store.writeTranscriptCursor(quarantined);
|
|
3827
5567
|
}
|
|
3828
5568
|
};
|
|
5569
|
+
async function readCodexHumanMessageProjection(registration, cursor, readChunk) {
|
|
5570
|
+
let offset = 0;
|
|
5571
|
+
const state = { records: 0, lastOrdinal: 0, window: { messages: [], truncated: false } };
|
|
5572
|
+
while (offset < cursor.offset) {
|
|
5573
|
+
const complete = await readChunk(offset, cursor.offset);
|
|
5574
|
+
if (complete === "empty" || complete === "partial") throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix is incomplete.");
|
|
5575
|
+
consumeCodexHumanMessageProjectionChunk(registration, complete, state);
|
|
5576
|
+
offset += complete.length;
|
|
5577
|
+
}
|
|
5578
|
+
if (offset !== cursor.offset || cursor.offset > 0 && (state.records === 0 || state.lastOrdinal !== cursor.last_ordinal)) throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix does not match its cursor boundary.");
|
|
5579
|
+
return state.window;
|
|
5580
|
+
}
|
|
5581
|
+
function consumeCodexHumanMessageProjectionChunk(registration, complete, state) {
|
|
5582
|
+
for (const line of complete.toString("utf8").split("\n").filter((value) => value.length > 0)) {
|
|
5583
|
+
const record2 = decodeCodexTranscriptLine(line);
|
|
5584
|
+
if (state.records === 0) assertCodexTranscriptHeader(registration, record2);
|
|
5585
|
+
else if (record2.ordinal <= state.lastOrdinal) throw new CodexHostAdapterError("payload_rejected", "Codex transcript projection prefix has a nonmonotonic ordinal.");
|
|
5586
|
+
const message = codexHumanMessage(registration, record2);
|
|
5587
|
+
if (message !== null) state.window = mergeHostInvocationHumanMessageWindow(state.window, [message]);
|
|
5588
|
+
state.lastOrdinal = record2.ordinal;
|
|
5589
|
+
state.records += 1;
|
|
5590
|
+
}
|
|
5591
|
+
}
|
|
3829
5592
|
function codexTranscriptScanFailureKind(error) {
|
|
3830
5593
|
return transcriptScanFailureKind(error, (candidate) => {
|
|
3831
5594
|
if (!(candidate instanceof CodexHostAdapterError)) return void 0;
|
|
@@ -3834,10 +5597,10 @@ function codexTranscriptScanFailureKind(error) {
|
|
|
3834
5597
|
return void 0;
|
|
3835
5598
|
});
|
|
3836
5599
|
}
|
|
3837
|
-
function accumulateTokenCount(activeTask,
|
|
3838
|
-
if (
|
|
3839
|
-
const last =
|
|
3840
|
-
const total =
|
|
5600
|
+
function accumulateTokenCount(activeTask, record2) {
|
|
5601
|
+
if (record2.usage_gap_reason !== void 0) return { ...activeTask, token_usage_gap_reason: record2.usage_gap_reason };
|
|
5602
|
+
const last = record2.last_usage;
|
|
5603
|
+
const total = record2.total_usage;
|
|
3841
5604
|
if (last === void 0 || ignoreTokenCount(activeTask.last_total_usage, total, last)) return activeTask;
|
|
3842
5605
|
const tokenUsage = addUsage(activeTask.token_usage, last);
|
|
3843
5606
|
return {
|
|
@@ -3851,14 +5614,14 @@ function ignoreTokenCount(previous, total, last) {
|
|
|
3851
5614
|
if (total === void 0 || previous === void 0) return false;
|
|
3852
5615
|
return sameUsage(total, previous) || regressedUsage(total, previous) && looksLikeStaleRegression(total, previous, last);
|
|
3853
5616
|
}
|
|
3854
|
-
function terminalObservations(registration, activeTask,
|
|
5617
|
+
function terminalObservations(registration, activeTask, record2, timing) {
|
|
3855
5618
|
const tokenValue = activeTask.token_usage_gap_reason !== void 0 ? notRecorded(activeTask.token_usage_gap_reason) : activeTask.token_usage === void 0 ? notRecorded("token_count_not_observed_for_active_turn") : tokenObservationValue(activeTask.token_usage);
|
|
3856
5619
|
const observations = [
|
|
3857
|
-
{ observation_ref: observationRef(registration.host_source_ref, "transcript_terminal", activeTask.host_turn_ref,
|
|
3858
|
-
{ observation_ref: observationRef(registration.host_source_ref, "transcript_timing", activeTask.host_turn_ref, timing), observation_kind: "timing", observed_at:
|
|
3859
|
-
{ observation_ref: observationRef(registration.host_source_ref, "transcript_token", activeTask.host_turn_ref, tokenValue), observation_kind: "token", observed_at:
|
|
5620
|
+
{ observation_ref: observationRef(registration.host_source_ref, "transcript_terminal", activeTask.host_turn_ref, record2), observation_kind: "turn", observed_at: record2.timestamp, value: turnObservationValue(registration.codex_session_id, activeTask.host_turn_ref, "stopped") },
|
|
5621
|
+
{ observation_ref: observationRef(registration.host_source_ref, "transcript_timing", activeTask.host_turn_ref, timing), observation_kind: "timing", observed_at: record2.timestamp, value: timing },
|
|
5622
|
+
{ observation_ref: observationRef(registration.host_source_ref, "transcript_token", activeTask.host_turn_ref, tokenValue), observation_kind: "token", observed_at: record2.timestamp, value: tokenValue }
|
|
3860
5623
|
];
|
|
3861
|
-
if (activeTask.model !== void 0) observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_model", activeTask.host_turn_ref, activeTask.model), observation_kind: "model", observed_at:
|
|
5624
|
+
if (activeTask.model !== void 0) observations.push({ observation_ref: observationRef(registration.host_source_ref, "transcript_model", activeTask.host_turn_ref, activeTask.model), observation_kind: "model", observed_at: record2.timestamp, value: { status: "available", value: activeTask.model, source: "turn_context.model" } });
|
|
3862
5625
|
return observations;
|
|
3863
5626
|
}
|
|
3864
5627
|
function notRecorded(reason) {
|
|
@@ -3907,16 +5670,24 @@ function looksLikeStaleRegression(current, previous, last) {
|
|
|
3907
5670
|
if (previous.total_tokens <= 0 || current.total_tokens <= 0 || last.total_tokens <= 0) return false;
|
|
3908
5671
|
return current.total_tokens * 100 >= previous.total_tokens * 98 || current.total_tokens + last.total_tokens * 2 >= previous.total_tokens;
|
|
3909
5672
|
}
|
|
3910
|
-
function
|
|
3911
|
-
if (
|
|
3912
|
-
|
|
5673
|
+
function codexHumanMessage(registration, record2) {
|
|
5674
|
+
if (record2.kind !== "user_text" || record2.content_item_kind !== "user.text") return null;
|
|
5675
|
+
return {
|
|
5676
|
+
host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id),
|
|
5677
|
+
host_input_ref: hostInputReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id, record2.message_id, record2.ordinal, record2.prompt),
|
|
5678
|
+
text: record2.prompt
|
|
5679
|
+
};
|
|
5680
|
+
}
|
|
5681
|
+
function assertRecordSequence(registration, cursor, records, lastOrdinal, record2) {
|
|
5682
|
+
if ((cursor.header_validated || records > 0) && record2.ordinal <= lastOrdinal) throw new CodexHostAdapterError("payload_rejected", `Codex transcript ordinal is not monotonic (${refusalFact("ordinal", record2.ordinal, `greater than ${lastOrdinal}`)}).`);
|
|
5683
|
+
if (!cursor.header_validated && records === 0) assertCodexTranscriptHeader(registration, record2);
|
|
3913
5684
|
}
|
|
3914
5685
|
|
|
3915
5686
|
// host/codex/src/codex-producer-runtime.ts
|
|
3916
5687
|
async function drainCodexProducerOnce(options) {
|
|
3917
5688
|
const scan = await new CodexTranscriptWatcher({
|
|
3918
5689
|
outbox_dir: options.outbox_dir,
|
|
3919
|
-
diagnostic: (event, failure_kind) => writeHostServiceDiagnostic("codex", event, failure_kind)
|
|
5690
|
+
diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("codex", event, failure_kind, cause)
|
|
3920
5691
|
}).scanOnce().catch((error) => {
|
|
3921
5692
|
writeHostServiceDiagnostic("codex", "watcher_scan_failed", codexTranscriptScanFailureKind(error));
|
|
3922
5693
|
throw error;
|
|
@@ -3925,6 +5696,236 @@ async function drainCodexProducerOnce(options) {
|
|
|
3925
5696
|
return { scanned: scan.enqueued, ...await producer.drainOutbox() };
|
|
3926
5697
|
}
|
|
3927
5698
|
|
|
5699
|
+
// host/codex/src/codex-usage-facts-capturer.ts
|
|
5700
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
5701
|
+
var CodexUsageFactsCapturer = class {
|
|
5702
|
+
sources;
|
|
5703
|
+
usage;
|
|
5704
|
+
now;
|
|
5705
|
+
diagnosticSink;
|
|
5706
|
+
nextRegistrationIndex = 0;
|
|
5707
|
+
constructor(options) {
|
|
5708
|
+
this.sources = new CodexOutboxStore(options.outbox_dir);
|
|
5709
|
+
this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
|
|
5710
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
5711
|
+
this.diagnosticSink = options.diagnostic_sink;
|
|
5712
|
+
}
|
|
5713
|
+
async captureNext() {
|
|
5714
|
+
const registrations = await this.sources.listTranscriptRegistrations();
|
|
5715
|
+
const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
|
|
5716
|
+
this.nextRegistrationIndex = result.nextIndex;
|
|
5717
|
+
if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
|
|
5718
|
+
return result.captured;
|
|
5719
|
+
}
|
|
5720
|
+
async captureRegistration(registration) {
|
|
5721
|
+
const prepared = await openHostUsageTranscriptCursor({
|
|
5722
|
+
path: registration.transcript_path,
|
|
5723
|
+
producer: "codex",
|
|
5724
|
+
source_kind: "codex_transcript",
|
|
5725
|
+
host_source_ref: registration.host_source_ref,
|
|
5726
|
+
host_session_ref: registration.host_session_ref,
|
|
5727
|
+
source_slot: "main",
|
|
5728
|
+
created_at: this.stamp(),
|
|
5729
|
+
store: this.usage,
|
|
5730
|
+
inspect: ownedCodexTranscriptFile,
|
|
5731
|
+
initial_cursor: initialCursor
|
|
5732
|
+
});
|
|
5733
|
+
if (prepared === null) return false;
|
|
5734
|
+
const { handle, source, source_file_ref: sourceFileRef, state, cursor: current } = prepared;
|
|
5735
|
+
try {
|
|
5736
|
+
if (await cursorReplaced(handle, source, sourceFileRef, current)) {
|
|
5737
|
+
const after = replacementCursor(sourceFileRef, source.device, source.inode);
|
|
5738
|
+
const gap = coverageGap("source_file_replaced", null, null, null, null);
|
|
5739
|
+
await this.usage.commitScanTransition(state, "main", current, after, null, [gap]);
|
|
5740
|
+
return true;
|
|
5741
|
+
}
|
|
5742
|
+
if (source.size === current.offset && !current.skipping_oversized_line) return false;
|
|
5743
|
+
return await this.captureChunk(handle, registration, current, sourceFileRef, source.size, state);
|
|
5744
|
+
} finally {
|
|
5745
|
+
await handle.close();
|
|
5746
|
+
}
|
|
5747
|
+
}
|
|
5748
|
+
async captureChunk(handle, registration, before, sourceFileRef, size, state) {
|
|
5749
|
+
const chunk = await readHostUsageTranscriptChunk(handle, before.offset, size, before.skipping_oversized_line);
|
|
5750
|
+
if (chunk.end_offset === before.offset && chunk.lines.length === 0) return false;
|
|
5751
|
+
const processed = processCodexLines(chunk.lines, registration, sourceFileRef, before, chunk.oversized_rows);
|
|
5752
|
+
const after = await updateAnchor(handle, { ...processed.cursor, offset: chunk.end_offset, skipping_oversized_line: chunk.skipping_oversized_line });
|
|
5753
|
+
const gaps = buildCoverageGaps(sourceFileRef, before.offset, chunk.end_offset, processed.gapCounts);
|
|
5754
|
+
const batch = processed.facts.length === 0 && gaps.length === 0 ? null : createCealHostUsageBatch({
|
|
5755
|
+
host_source_ref: registration.host_source_ref,
|
|
5756
|
+
host_session_ref: registration.host_session_ref,
|
|
5757
|
+
created_at: processed.createdAt,
|
|
5758
|
+
source_ranges: [{ source_file_ref: sourceFileRef, start_offset: before.offset, end_offset: chunk.end_offset }],
|
|
5759
|
+
facts: processed.facts,
|
|
5760
|
+
coverage_gaps: gaps
|
|
5761
|
+
});
|
|
5762
|
+
await this.usage.commitScanTransition(state, "main", before, after, batch);
|
|
5763
|
+
return true;
|
|
5764
|
+
}
|
|
5765
|
+
stamp() {
|
|
5766
|
+
const value = this.now();
|
|
5767
|
+
if (!Number.isFinite(value.getTime())) throw new Error("Codex usage facts clock is invalid.");
|
|
5768
|
+
return value.toISOString();
|
|
5769
|
+
}
|
|
5770
|
+
};
|
|
5771
|
+
function processCodexLines(lines, registration, sourceFileRef, initial, oversizedRows) {
|
|
5772
|
+
let cursor = initial;
|
|
5773
|
+
let createdAt = registration.registered_at;
|
|
5774
|
+
let records = 0;
|
|
5775
|
+
const facts = [];
|
|
5776
|
+
const gapCounts = /* @__PURE__ */ new Map();
|
|
5777
|
+
if (oversizedRows > 0) gapCounts.set("unsupported_source_shape", oversizedRows);
|
|
5778
|
+
for (const bytes of lines) {
|
|
5779
|
+
const record2 = decodeCodexLine(bytes);
|
|
5780
|
+
if (record2 === null || !validInitialHeader(record2, registration, initial.offset, records) || !hasIncreasingOrdinal(cursor, record2)) {
|
|
5781
|
+
addCodexGap(gapCounts, "unsupported_source_shape");
|
|
5782
|
+
records += 1;
|
|
5783
|
+
continue;
|
|
5784
|
+
}
|
|
5785
|
+
createdAt = record2.timestamp;
|
|
5786
|
+
cursor = applyCodexRecord(cursor, record2, registration, sourceFileRef, facts, gapCounts);
|
|
5787
|
+
cursor = { ...cursor, last_ordinal: record2.ordinal };
|
|
5788
|
+
records += 1;
|
|
5789
|
+
}
|
|
5790
|
+
return { cursor, facts, gapCounts, createdAt };
|
|
5791
|
+
}
|
|
5792
|
+
function decodeCodexLine(bytes) {
|
|
5793
|
+
try {
|
|
5794
|
+
return decodeCodexUsageTranscriptLine(bytes.toString("utf8"));
|
|
5795
|
+
} catch {
|
|
5796
|
+
return null;
|
|
5797
|
+
}
|
|
5798
|
+
}
|
|
5799
|
+
function validInitialHeader(record2, registration, initialOffset, records) {
|
|
5800
|
+
if (initialOffset !== 0 || records !== 0) return true;
|
|
5801
|
+
try {
|
|
5802
|
+
assertCodexTranscriptHeader(registration, record2);
|
|
5803
|
+
return true;
|
|
5804
|
+
} catch {
|
|
5805
|
+
return false;
|
|
5806
|
+
}
|
|
5807
|
+
}
|
|
5808
|
+
function hasIncreasingOrdinal(cursor, record2) {
|
|
5809
|
+
return cursor.last_ordinal === null || record2.ordinal > cursor.last_ordinal;
|
|
5810
|
+
}
|
|
5811
|
+
function applyCodexRecord(cursor, record2, registration, sourceFileRef, facts, gapCounts) {
|
|
5812
|
+
if (record2.kind === "token_count") return applyTokenCount(cursor, registration, sourceFileRef, record2, facts, gapCounts);
|
|
5813
|
+
if (record2.kind === "task_started") return { ...cursor, host_turn_ref: hostTurnReference(registration.host_source_ref, registration.host_session_ref, record2.turn_id), native_turn_id: record2.turn_id, requested_model: null, codex_total_usage: null };
|
|
5814
|
+
if (record2.kind === "turn_context" && cursor.native_turn_id === record2.turn_id) return { ...cursor, requested_model: record2.model };
|
|
5815
|
+
if ((record2.kind === "task_complete" || record2.kind === "turn_aborted") && cursor.native_turn_id === record2.turn_id) return { ...cursor, host_turn_ref: null, native_turn_id: null, requested_model: null, codex_total_usage: null };
|
|
5816
|
+
return cursor;
|
|
5817
|
+
}
|
|
5818
|
+
function applyTokenCount(cursor, registration, sourceFileRef, record2, facts, gapCounts) {
|
|
5819
|
+
if (record2.usage_gap_reason !== void 0 || record2.last_usage === void 0 && record2.total_usage === void 0) addCodexGap(gapCounts, "source_usage_unavailable");
|
|
5820
|
+
else facts.push(codexUsageFact(registration, sourceFileRef, cursor, record2));
|
|
5821
|
+
return { ...cursor, codex_total_usage: record2.total_usage ?? cursor.codex_total_usage };
|
|
5822
|
+
}
|
|
5823
|
+
function addCodexGap(gaps, reason) {
|
|
5824
|
+
gaps.set(reason, (gaps.get(reason) ?? 0) + 1);
|
|
5825
|
+
}
|
|
5826
|
+
function initialCursor(sourceFileRef, device, inode) {
|
|
5827
|
+
return {
|
|
5828
|
+
source_file_ref: sourceFileRef,
|
|
5829
|
+
device,
|
|
5830
|
+
inode,
|
|
5831
|
+
offset: 0,
|
|
5832
|
+
anchor_start: 0,
|
|
5833
|
+
anchor_sha256: sha2564(Buffer.alloc(0)),
|
|
5834
|
+
last_ordinal: null,
|
|
5835
|
+
host_turn_ref: null,
|
|
5836
|
+
native_turn_id: null,
|
|
5837
|
+
requested_model: null,
|
|
5838
|
+
codex_total_usage: null,
|
|
5839
|
+
skipping_oversized_line: false
|
|
5840
|
+
};
|
|
5841
|
+
}
|
|
5842
|
+
function codexUsageFact(registration, sourceFileRef, cursor, record2) {
|
|
5843
|
+
const sourceEventRef = hostUsageSourceEventReference(sourceFileRef, `codex:${record2.ordinal}`);
|
|
5844
|
+
const total = record2.total_usage;
|
|
5845
|
+
const cumulativeTransition = transitionKind(cursor.codex_total_usage, total);
|
|
5846
|
+
const selected = record2.last_usage ?? total;
|
|
5847
|
+
const normalized = normalizedCounts(selected);
|
|
5848
|
+
return {
|
|
5849
|
+
fact_ref: hostUsageFactReference(sourceFileRef, sourceEventRef),
|
|
5850
|
+
host_session_ref: registration.host_session_ref,
|
|
5851
|
+
host_turn_ref: cursor.host_turn_ref,
|
|
5852
|
+
source_file_ref: sourceFileRef,
|
|
5853
|
+
source_event_ref: sourceEventRef,
|
|
5854
|
+
source_event_ordinal: record2.ordinal,
|
|
5855
|
+
observed_at: record2.timestamp,
|
|
5856
|
+
producer: "codex_transcript",
|
|
5857
|
+
requested_model: cursor.requested_model,
|
|
5858
|
+
reported_model: null,
|
|
5859
|
+
source_usage: { last_token_usage: record2.last_usage ?? null, total_token_usage: total ?? null },
|
|
5860
|
+
normalized_usage: normalized,
|
|
5861
|
+
counter_semantics: record2.last_usage !== void 0 && total !== void 0 ? "last_delta_total_cumulative" : total !== void 0 ? "total_cumulative_only" : "unknown",
|
|
5862
|
+
cumulative_transition: cumulativeTransition,
|
|
5863
|
+
finality: "unknown",
|
|
5864
|
+
correction_semantics: "unknown"
|
|
5865
|
+
};
|
|
5866
|
+
}
|
|
5867
|
+
function transitionKind(baseline, total) {
|
|
5868
|
+
if (total === void 0) return "not_observed";
|
|
5869
|
+
if (baseline === null) return "baseline";
|
|
5870
|
+
if (sameCounts(baseline, total)) return "same";
|
|
5871
|
+
return isRegression(total, baseline) ? "reset_or_correction" : "advanced";
|
|
5872
|
+
}
|
|
5873
|
+
function normalizedCounts(selected) {
|
|
5874
|
+
return selected === void 0 ? nullCounts() : {
|
|
5875
|
+
input: selected.input_tokens,
|
|
5876
|
+
output: selected.output_tokens,
|
|
5877
|
+
total: selected.total_tokens,
|
|
5878
|
+
cached_input: selected.cached_input_tokens,
|
|
5879
|
+
cache_write_input: selected.cache_write_input_tokens,
|
|
5880
|
+
reasoning_output: selected.reasoning_output_tokens
|
|
5881
|
+
};
|
|
5882
|
+
}
|
|
5883
|
+
function nullCounts() {
|
|
5884
|
+
return { input: null, output: null, total: null, cached_input: null, cache_write_input: null, reasoning_output: null };
|
|
5885
|
+
}
|
|
5886
|
+
function isRegression(current, previous) {
|
|
5887
|
+
return CEAL_CODEX_USAGE_COUNT_FIELDS.some((key) => current[key] < previous[key]);
|
|
5888
|
+
}
|
|
5889
|
+
function sameCounts(left, right) {
|
|
5890
|
+
return CEAL_CODEX_USAGE_COUNT_FIELDS.every((key) => left[key] === right[key]);
|
|
5891
|
+
}
|
|
5892
|
+
function buildCoverageGaps(sourceFileRef, startOffset, endOffset, counts) {
|
|
5893
|
+
return [...counts].map(([reason, omittedCount]) => coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount));
|
|
5894
|
+
}
|
|
5895
|
+
function coverageGap(reason, sourceFileRef, startOffset, endOffset, omittedCount) {
|
|
5896
|
+
return { reason, source_file_ref: sourceFileRef, start_offset: startOffset, end_offset: endOffset, omitted_count: omittedCount };
|
|
5897
|
+
}
|
|
5898
|
+
function sha2564(value) {
|
|
5899
|
+
return createHash9("sha256").update(value).digest("hex");
|
|
5900
|
+
}
|
|
5901
|
+
async function anchorMatches(handle, cursor) {
|
|
5902
|
+
const bytes = Buffer.alloc(cursor.offset - cursor.anchor_start);
|
|
5903
|
+
if (bytes.length === 0) return sha2564(bytes) === cursor.anchor_sha256;
|
|
5904
|
+
const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, cursor.anchor_start));
|
|
5905
|
+
return bytesRead === bytes.length && sha2564(bytes) === cursor.anchor_sha256;
|
|
5906
|
+
}
|
|
5907
|
+
async function cursorReplaced(handle, source, sourceFileRef, cursor) {
|
|
5908
|
+
return cursor.source_file_ref !== sourceFileRef || cursor.device !== source.device || cursor.inode !== source.inode || source.size < cursor.offset || !await anchorMatches(handle, cursor);
|
|
5909
|
+
}
|
|
5910
|
+
function replacementCursor(sourceFileRef, device, inode) {
|
|
5911
|
+
return {
|
|
5912
|
+
...initialCursor(sourceFileRef, device, inode),
|
|
5913
|
+
source_file_ref: sourceFileRef,
|
|
5914
|
+
device,
|
|
5915
|
+
inode,
|
|
5916
|
+
offset: 0
|
|
5917
|
+
};
|
|
5918
|
+
}
|
|
5919
|
+
async function updateAnchor(handle, cursor) {
|
|
5920
|
+
const anchorStart = Math.max(0, cursor.offset - CODEX_TRANSCRIPT_ANCHOR_BYTES);
|
|
5921
|
+
const anchor = Buffer.alloc(cursor.offset - anchorStart);
|
|
5922
|
+
if (anchor.length > 0) {
|
|
5923
|
+
const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(anchor, 0, anchor.length, anchorStart));
|
|
5924
|
+
if (bytesRead !== anchor.length) throw new Error("Codex usage facts source changed during anchor read.");
|
|
5925
|
+
}
|
|
5926
|
+
return { ...cursor, anchor_start: anchorStart, anchor_sha256: sha2564(anchor) };
|
|
5927
|
+
}
|
|
5928
|
+
|
|
3928
5929
|
// host/codex/src/codex-producer-service.ts
|
|
3929
5930
|
var CODEX_PRODUCER_CONFIG_SCHEMA = "ceal.codex_producer_config.v1";
|
|
3930
5931
|
var CODEX_SESSIONS_ROOT = "codex_sessions_root";
|
|
@@ -3933,12 +5934,14 @@ var CODEX_PRODUCER_DESCRIPTOR = {
|
|
|
3933
5934
|
producer_id: "codex",
|
|
3934
5935
|
extra_paths: [CODEX_SESSIONS_ROOT],
|
|
3935
5936
|
config: (shared, extras) => ({ ...shared, codex_sessions_root: hostProducerExtraPath(extras, CODEX_SESSIONS_ROOT) }),
|
|
3936
|
-
runtime_options: (config) => Object.freeze({
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
5937
|
+
runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
|
|
5938
|
+
drain: drainCodexProducerOnce,
|
|
5939
|
+
background: (config, signal, dependencies) => {
|
|
5940
|
+
const capturer = new CodexUsageFactsCapturer({ outbox_dir: config.outbox_dir });
|
|
5941
|
+
return runHostUsageFactsUploader({ producer: "codex", outbox_dir: config.outbox_dir, host_source_ref: config.host_source_ref, registration_state_file: hostProducerRegistrationStateFile(config.outbox_dir), capture_next: () => capturer.captureNext(), fetch: dependencies.fetch }, signal);
|
|
5942
|
+
}
|
|
3940
5943
|
};
|
|
3941
|
-
function runCodexProducerCli(args, signal, dependencies
|
|
5944
|
+
function runCodexProducerCli(args, signal, dependencies) {
|
|
3942
5945
|
return runHostProducerCli(CODEX_PRODUCER_DESCRIPTOR, args, signal, dependencies);
|
|
3943
5946
|
}
|
|
3944
5947
|
|
|
@@ -3955,8 +5958,7 @@ async function runProducerCommand(schemaVersion, run) {
|
|
|
3955
5958
|
await run(serviceArguments.args, controller.signal);
|
|
3956
5959
|
} catch (error) {
|
|
3957
5960
|
const code = typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "producer_failed";
|
|
3958
|
-
|
|
3959
|
-
`);
|
|
5961
|
+
await writeHostServiceCommandResult(schemaVersion, { ok: false, code }, (line) => process.stderr.write(line));
|
|
3960
5962
|
process.exitCode = 1;
|
|
3961
5963
|
} finally {
|
|
3962
5964
|
stopLogBound();
|
|
@@ -3966,4 +5968,4 @@ async function runProducerCommand(schemaVersion, run) {
|
|
|
3966
5968
|
}
|
|
3967
5969
|
|
|
3968
5970
|
// host/codex/bin/ceal-codex-producer.ts
|
|
3969
|
-
await runProducerCommand("ceal.codex_producer_command.v1", runCodexProducerCli);
|
|
5971
|
+
await runProducerCommand("ceal.codex_producer_command.v1", (args, signal) => runCodexProducerCli(args, signal, { fetch: globalThis.fetch }));
|