@agentcomms/events-daemon 0.24.0 → 0.25.0

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/dist/index.d.mts CHANGED
@@ -11574,6 +11574,141 @@ declare const JUDGE_KIND_LOCAL_ENDPOINT: "local-endpoint";
11574
11574
  declare const JUDGE_KINDS: readonly [typeof JUDGE_KIND_TYPESAFE, typeof JUDGE_KIND_LAYA, typeof JUDGE_KIND_LOCAL_ENDPOINT];
11575
11575
  type JudgeKind = (typeof JUDGE_KINDS)[number];
11576
11576
  //#endregion
11577
+ //#region src/domain/source-options.d.ts
11578
+ interface GmailSourceOptions {
11579
+ readonly channel: "gmail";
11580
+ readonly labels: readonly string[] | "inbox" | "any";
11581
+ readonly includeSpamTrash: boolean;
11582
+ }
11583
+ interface SlackSourceOptions {
11584
+ readonly channel: "slack";
11585
+ readonly conversations: readonly string[];
11586
+ }
11587
+ interface ResendSourceOptions {
11588
+ readonly channel: "resend";
11589
+ readonly kinds: readonly ("received" | "status")[];
11590
+ }
11591
+ interface WhatsAppSourceOptions {
11592
+ readonly channel: "whatsapp";
11593
+ readonly chats: readonly string[] | "all-allowed";
11594
+ }
11595
+ type SourceOptions = GmailSourceOptions | SlackSourceOptions | ResendSourceOptions | WhatsAppSourceOptions;
11596
+ //#endregion
11597
+ //#region src/domain/webhook-target.d.ts
11598
+ interface PlainWebhookUrl {
11599
+ readonly kind: "plain";
11600
+ readonly value: string;
11601
+ }
11602
+ interface SecretWebhookUrl {
11603
+ readonly kind: "secret";
11604
+ readonly scheme: "http" | "https";
11605
+ readonly host: string;
11606
+ readonly port: number;
11607
+ readonly sha256: string;
11608
+ }
11609
+ interface WebhookTargetDocument {
11610
+ readonly targetId: string;
11611
+ readonly version: number;
11612
+ readonly kind: "webhook";
11613
+ readonly url: PlainWebhookUrl | SecretWebhookUrl;
11614
+ readonly approvedAddressSet: readonly string[];
11615
+ readonly signing: "standard-webhooks";
11616
+ readonly ordering: "strict";
11617
+ readonly retryLimit: number;
11618
+ readonly representation: "plain" | "enveloped";
11619
+ }
11620
+ //#endregion
11621
+ //#region src/runtime/laya/contracts.d.ts
11622
+ declare const LAYA_KIND: (typeof JUDGE_KINDS)[1];
11623
+ interface LayaManifestFile {
11624
+ readonly path: string;
11625
+ readonly size: number;
11626
+ readonly sha256: string;
11627
+ }
11628
+ interface CanonicalLayaManifest {
11629
+ readonly manifestVersion: 1;
11630
+ readonly manifestId: string;
11631
+ readonly source: {
11632
+ readonly host: "huggingface.co";
11633
+ readonly repo: string;
11634
+ readonly revision: string;
11635
+ };
11636
+ readonly weights: {
11637
+ readonly publisher: string;
11638
+ readonly origin: string;
11639
+ readonly originSha256: string;
11640
+ readonly licence: string;
11641
+ };
11642
+ readonly files: readonly LayaManifestFile[];
11643
+ readonly runtime: Readonly<Record<string, string>>;
11644
+ readonly context: {
11645
+ readonly maxTokens: 512;
11646
+ readonly language: "en";
11647
+ };
11648
+ readonly promptTemplates: readonly string[];
11649
+ }
11650
+ interface LayaRuntimeFile {
11651
+ readonly path: string;
11652
+ readonly size: number;
11653
+ readonly sha256: string;
11654
+ readonly executable: boolean;
11655
+ }
11656
+ interface CanonicalLayaRuntimeLock {
11657
+ readonly schemaVersion: 1;
11658
+ readonly packages: readonly {
11659
+ readonly name: string;
11660
+ readonly version: string;
11661
+ readonly url: string;
11662
+ readonly integrity: string;
11663
+ }[];
11664
+ readonly platform: {
11665
+ readonly id: string;
11666
+ readonly files: readonly (LayaRuntimeFile & {
11667
+ readonly package: string;
11668
+ })[];
11669
+ readonly digest: string;
11670
+ };
11671
+ readonly digest: string;
11672
+ }
11673
+ interface CanonicalLayaEnablement {
11674
+ readonly id: `judge-kind:${typeof LAYA_KIND}`;
11675
+ readonly kind: typeof LAYA_KIND;
11676
+ readonly version: number;
11677
+ readonly manifest: CanonicalLayaManifest;
11678
+ readonly runtimeLock: CanonicalLayaRuntimeLock;
11679
+ readonly disclosures: CanonicalLayaEnablementDisclosures;
11680
+ }
11681
+ interface CanonicalLayaEnablementDisclosures {
11682
+ readonly modelBytes: number;
11683
+ readonly runtimeBytes: number;
11684
+ readonly runtimeLicences: readonly string[];
11685
+ readonly workerMemory: string;
11686
+ readonly facts: Readonly<{
11687
+ readonly englishCpu: string;
11688
+ readonly macosBoundary: string;
11689
+ readonly linuxUnavailable: string;
11690
+ readonly windowsUnavailable: string;
11691
+ readonly downloadAfterApproval: string;
11692
+ readonly oneAtATime: string;
11693
+ }>;
11694
+ readonly limitations: Readonly<{
11695
+ readonly sandboxDeprecation: string;
11696
+ readonly englishAccuracy: string;
11697
+ }>;
11698
+ }
11699
+ //#endregion
11700
+ //#region src/runtime/laya/templates.d.ts
11701
+ /**
11702
+ * Laya's two immutable prompt templates (E2-2, D11). The reviewed manifest lists which of them a release offers; their
11703
+ * content lives here, in the daemon's worker source, so a semantic change is a new id and a new manifest entry, never
11704
+ * an edit. Each has a stable SHA-256 over its canonical content, which the D11 gate subject binds.
11705
+ *
11706
+ * This module is loaded inside the isolated worker as well as by the daemon: it imports Node built-ins only.
11707
+ */
11708
+ declare const LAYA_NOUL_TEMPLATE_ID: "laya-noul-v1";
11709
+ declare const LAYA_CHOICE2_TEMPLATE_ID: "laya-choice2-v1";
11710
+ type LayaTemplateId = typeof LAYA_NOUL_TEMPLATE_ID | typeof LAYA_CHOICE2_TEMPLATE_ID;
11711
+ //#endregion
11577
11712
  //#region src/domain/judges.d.ts
11578
11713
  declare const TYPESAFE_SYSTEM_ONE_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
11579
11714
  declare const JUDGE_BUDGET_ID = "judge-budget";
@@ -11606,7 +11741,20 @@ type LocalEndpointJudgeDocument = (LocalEndpointJudgeBase & {
11606
11741
  readonly protocol: "json-score";
11607
11742
  readonly scorePointer: string;
11608
11743
  });
11609
- type CanonicalJudgeDocument = TypeSafeJudgeDocument | LocalEndpointJudgeDocument;
11744
+ /**
11745
+ * A Laya judge (D2, D11): the canonical Laya provider, the reviewed manifest entry in the endpoint's place — with one
11746
+ * model per entry it is also the model, so the document names it once, as `model` — and one of the two immutable
11747
+ * prompt templates. Execution refuses it unless that entry is the enabled one and lists the template.
11748
+ */
11749
+ interface LayaJudgeDocument {
11750
+ readonly judgeId: string;
11751
+ readonly version: number;
11752
+ readonly kind: typeof JUDGE_KIND_LAYA;
11753
+ readonly provider: typeof JUDGE_KIND_LAYA;
11754
+ readonly model: string;
11755
+ readonly promptTemplate: LayaTemplateId;
11756
+ }
11757
+ type CanonicalJudgeDocument = TypeSafeJudgeDocument | LocalEndpointJudgeDocument | LayaJudgeDocument;
11610
11758
  interface JudgeBudgetLimits {
11611
11759
  readonly callsPerRollingHour: number;
11612
11760
  readonly inputTokensPerRolling30Days: number;
@@ -11629,27 +11777,7 @@ type CanonicalJudgeKindEnablementDocument = {
11629
11777
  readonly id: "judge-kind:local-endpoint";
11630
11778
  readonly kind: typeof JUDGE_KIND_LOCAL_ENDPOINT;
11631
11779
  readonly version: number;
11632
- };
11633
- //#endregion
11634
- //#region src/domain/source-options.d.ts
11635
- interface GmailSourceOptions {
11636
- readonly channel: "gmail";
11637
- readonly labels: readonly string[] | "inbox" | "any";
11638
- readonly includeSpamTrash: boolean;
11639
- }
11640
- interface SlackSourceOptions {
11641
- readonly channel: "slack";
11642
- readonly conversations: readonly string[];
11643
- }
11644
- interface ResendSourceOptions {
11645
- readonly channel: "resend";
11646
- readonly kinds: readonly ("received" | "status")[];
11647
- }
11648
- interface WhatsAppSourceOptions {
11649
- readonly channel: "whatsapp";
11650
- readonly chats: readonly string[] | "all-allowed";
11651
- }
11652
- type SourceOptions = GmailSourceOptions | SlackSourceOptions | ResendSourceOptions | WhatsAppSourceOptions;
11780
+ } | CanonicalLayaEnablement;
11653
11781
  //#endregion
11654
11782
  //#region src/domain/sse-subscriber.d.ts
11655
11783
  interface SseSubscriberDocument {
@@ -11672,30 +11800,6 @@ interface SseTargetDocument {
11672
11800
  readonly representation: "plain" | "enveloped";
11673
11801
  }
11674
11802
  //#endregion
11675
- //#region src/domain/webhook-target.d.ts
11676
- interface PlainWebhookUrl {
11677
- readonly kind: "plain";
11678
- readonly value: string;
11679
- }
11680
- interface SecretWebhookUrl {
11681
- readonly kind: "secret";
11682
- readonly scheme: "http" | "https";
11683
- readonly host: string;
11684
- readonly port: number;
11685
- readonly sha256: string;
11686
- }
11687
- interface WebhookTargetDocument {
11688
- readonly targetId: string;
11689
- readonly version: number;
11690
- readonly kind: "webhook";
11691
- readonly url: PlainWebhookUrl | SecretWebhookUrl;
11692
- readonly approvedAddressSet: readonly string[];
11693
- readonly signing: "standard-webhooks";
11694
- readonly ordering: "strict";
11695
- readonly retryLimit: number;
11696
- readonly representation: "plain" | "enveloped";
11697
- }
11698
- //#endregion
11699
11803
  //#region src/domain/activation-documents.d.ts
11700
11804
  interface DryRunTargetDocument {
11701
11805
  readonly targetId: string;
@@ -12800,7 +12904,8 @@ interface B3ApprovalPreviewTerminalView {
12800
12904
  }
12801
12905
  /**
12802
12906
  * The terminal and desktop fixture boundary. This formats only daemon-authored identifiers and a canonical, neutralised
12803
- * preview representation; it never consumes a secret operation or claims the approval.
12907
+ * preview representation; it never consumes a secret operation or claims the approval. A B3 v3 rule preview naming a
12908
+ * Laya judge also carries D11's Laya limits, rendered after the preview.
12804
12909
  */
12805
12910
  export declare function renderB3ApprovalPreviewV1(value: unknown): B3ApprovalPreviewTerminalView;
12806
12911
  interface B3ControlContract {
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { R as createEventsMcpServer, X as status, a as B3_CONTROL_V1_OPERATION_SPECS, c as B3_CONTROL_V1_SUCCESSOR_REQUIREMENT, d as B3_SECRET_TERMINAL_ORIGIN, i as B3_CONTROL_ERROR_CODES, l as B3_DESKTOP_CONTROL_OPERATIONS, m as renderB3ApprovalPreviewV1, n as B3_CAPABILITIES, o as B3_CONTROL_V1_RESULT_OPERATIONS, r as B3_CONTROL_CONTRACT, s as B3_CONTROL_V1_SCHEMA_VERSION, t as B3_APPROVAL_VIEW_VARIANTS, u as B3_JUDGE_UNAVAILABLE_VARIANTS } from "./b3-contract-C1q5aekF.mjs";
1
+ import { K as createEventsMcpServer, a as B3_CONTROL_V1_OPERATION_SPECS, c as B3_CONTROL_V1_SUCCESSOR_REQUIREMENT, d as B3_SECRET_TERMINAL_ORIGIN, i as B3_CONTROL_ERROR_CODES, it as status, l as B3_DESKTOP_CONTROL_OPERATIONS, m as renderB3ApprovalPreviewV1, n as B3_CAPABILITIES, o as B3_CONTROL_V1_RESULT_OPERATIONS, r as B3_CONTROL_CONTRACT, s as B3_CONTROL_V1_SCHEMA_VERSION, t as B3_APPROVAL_VIEW_VARIANTS, u as B3_JUDGE_UNAVAILABLE_VARIANTS } from "./b3-contract-ByO1DTgr.mjs";
2
2
  export { B3_APPROVAL_VIEW_VARIANTS, B3_CAPABILITIES, B3_CONTROL_CONTRACT, B3_CONTROL_ERROR_CODES, B3_CONTROL_V1_OPERATION_SPECS, B3_CONTROL_V1_RESULT_OPERATIONS, B3_CONTROL_V1_SCHEMA_VERSION, B3_CONTROL_V1_SUCCESSOR_REQUIREMENT, B3_DESKTOP_CONTROL_OPERATIONS, B3_JUDGE_UNAVAILABLE_VARIANTS, B3_SECRET_TERMINAL_ORIGIN, createEventsMcpServer, renderB3ApprovalPreviewV1, status };
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,356 @@
1
+ import { _ as layaTemplate, f as writeWorkerFrame, g as layaLayout, h as isLayaTemplateId, i as assertWorkerLoadBinding, l as WorkerFrameParser, o as runWorkerBoundaryProbe, r as assertNoProbeSocketsRemain, s as sealWorkerNetworkAfterProbe } from "./worker-boundary-probe-CFN6EsyK.mjs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ //#region src/runtime/laya/worker-runtime.ts
6
+ /** The sequence's own markers: `[CLS]`, the head's `[SEP]`, and the `[SEP]` either side of the state. */
7
+ const LAYA_SEQUENCE_MARKERS = 4;
8
+ /** The one question each request asks; the name is not part of the rendered sequence. */
9
+ const LAYA_QUESTION_NAME = "decision";
10
+ function isRecord(value) {
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ }
13
+ function exactKeys(value, keys) {
14
+ const found = Object.keys(value).sort();
15
+ const expected = [...keys].sort();
16
+ return found.length === expected.length && found.every((key, index) => key === expected[index]);
17
+ }
18
+ function normalAbsolute(value) {
19
+ return typeof value === "string" && value.length > 0 && isAbsolute(value) && resolve(value) === value;
20
+ }
21
+ function layaLoadPayload(value) {
22
+ if (!isRecord(value) || !exactKeys(value, ["runtimeRoot", "modelDir"])) return null;
23
+ if (!normalAbsolute(value.runtimeRoot) || !normalAbsolute(value.modelDir)) return null;
24
+ return {
25
+ runtimeRoot: value.runtimeRoot,
26
+ modelDir: value.modelDir
27
+ };
28
+ }
29
+ function layaWorkerRequest(value) {
30
+ if (!isLayaTemplateId(value.templateId)) return null;
31
+ if (typeof value.instructions !== "string" || value.instructions.length === 0) return null;
32
+ if (typeof value.state !== "string" || value.state.length === 0) return null;
33
+ return {
34
+ templateId: value.templateId,
35
+ instructions: value.instructions,
36
+ state: value.state
37
+ };
38
+ }
39
+ function tokens(runtime, text) {
40
+ const counted = runtime.countTokens(text);
41
+ if (!Number.isSafeInteger(counted) || counted < 0) throw new Error("the Laya tokenizer count is not a token count");
42
+ return counted;
43
+ }
44
+ /**
45
+ * The exact length of the sequence the runtime would build, counted over the complete, uncut layout, or null when it
46
+ * would cut anything: an option over 48 tokens, a head over its 192-token budget, or a sequence over 512. (The
47
+ * runtime's further cut of options that leave the head under a 16-token reserve cannot apply to a two-option
48
+ * template whose options are each within 48; a template with more options is a new id and a new review.) Within these
49
+ * bounds nothing is cut, so the runtime's own `usage.input_tokens` must equal this count (hf-laya-onnx-config).
50
+ */
51
+ function layaSequenceTokens(runtime, request) {
52
+ const layout = layaLayout(request.templateId, request);
53
+ const head = tokens(runtime, layout.head);
54
+ const options = layout.options.map((option) => tokens(runtime, option));
55
+ const state = tokens(runtime, layout.state);
56
+ const optionTokens = options.reduce((sum, count) => sum + count, 0);
57
+ if (options.some((count) => count > 48)) return null;
58
+ if (2 + head + options.length + optionTokens > 192) return null;
59
+ const sequence = head + options.length + optionTokens + state + LAYA_SEQUENCE_MARKERS;
60
+ return sequence > 512 ? null : sequence;
61
+ }
62
+ /**
63
+ * Reads one `noul` answer where System One puts it — `answers.<name>.noul` — exactly as the runtime returns it, after
64
+ * the checks D5 makes: a finite number in [0, 1], never clamped. The usage must be the uncut count with no output
65
+ * tokens (npm-receptron-laya-0.1.2-output), or the runtime cut something and the answer is malformed.
66
+ */
67
+ function noulValue(answer, sequenceTokens) {
68
+ if (!isRecord(answer) || !isRecord(answer.answers) || !isRecord(answer.usage)) return null;
69
+ if (!exactKeys(answer.answers, ["decision"])) return null;
70
+ const decision = answer.answers[LAYA_QUESTION_NAME];
71
+ if (!isRecord(decision) || decision.type !== "noul") return null;
72
+ const value = decision.noul;
73
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return null;
74
+ if (answer.usage.input_tokens !== sequenceTokens || answer.usage.output_tokens !== 0) return null;
75
+ return value;
76
+ }
77
+ /**
78
+ * One request: count, refuse rather than let the runtime cut, ask, check. `laya-choice2-v1` is laid out and counted
79
+ * like any template but refuses before the runtime is asked: System One's `choice` `criteria` shape is "not stated"
80
+ * in the Phase E provider record, and the Task 8 record names neither it nor where the runtime puts a choice's
81
+ * probabilities, so building or reading that wire would be an inference. It stays `template-blocked` until a record
82
+ * names both.
83
+ */
84
+ async function evaluateLayaRequest(runtime, request) {
85
+ let sequenceTokens;
86
+ try {
87
+ sequenceTokens = layaSequenceTokens(runtime, request);
88
+ } catch {
89
+ return {
90
+ kind: "refused",
91
+ code: "malformed"
92
+ };
93
+ }
94
+ if (sequenceTokens === null) return {
95
+ kind: "refused",
96
+ code: "token-limit"
97
+ };
98
+ if (layaTemplate(request.templateId).type !== "noul") return {
99
+ kind: "refused",
100
+ code: "template-blocked"
101
+ };
102
+ const questions = Object.create(null);
103
+ questions[LAYA_QUESTION_NAME] = {
104
+ type: "noul",
105
+ instructions: request.instructions
106
+ };
107
+ let answer;
108
+ try {
109
+ answer = await runtime.systemOne(request.state, questions);
110
+ } catch {
111
+ return {
112
+ kind: "refused",
113
+ code: "malformed"
114
+ };
115
+ }
116
+ const value = noulValue(answer, sequenceTokens);
117
+ return value === null ? {
118
+ kind: "refused",
119
+ code: "malformed"
120
+ } : {
121
+ kind: "answer",
122
+ value,
123
+ inputTokens: sequenceTokens
124
+ };
125
+ }
126
+ /**
127
+ * Exactly the verified model directory and the CPU provider (D11's `Laya.load({ modelDir, executionProviders: ["cpu"] })`).
128
+ * With `modelDir` set the package never calls its downloader, and no repo, revision, token, cache directory, progress
129
+ * callback or session option is passed, so neither a download nor a provider override is reachable
130
+ * (npm-receptron-laya-0.1.2-load, npm-receptron-laya-0.1.2-download).
131
+ */
132
+ function layaLoadOptions(modelDir) {
133
+ return {
134
+ modelDir,
135
+ executionProviders: ["cpu"]
136
+ };
137
+ }
138
+ /** The module that defines `Laya.load` inside the verified runtime tree (npm-receptron-laya-0.1.2-load). */
139
+ const LAYA_RUNTIME_MODULE = "node_modules/@receptron/laya/dist/laya.js";
140
+ /** The tokenizer package `Laya.load` builds its tokenizer from (npm-receptron-laya-0.1.2-load). */
141
+ const LAYA_TOKENIZERS_PACKAGE = "node_modules/@huggingface/tokenizers";
142
+ function within(root, path) {
143
+ const offset = relative(root, path);
144
+ return offset.length > 0 && !offset.startsWith("..") && !isAbsolute(offset) && !offset.split(sep).includes("..");
145
+ }
146
+ /**
147
+ * The worker's one computed import: an absolute file URL inside the tree the daemon verified just before this start.
148
+ * There is no package-name fallback — nothing resolves through the daemon's own `node_modules` — and phase E's
149
+ * static check admits exactly this call, in exactly this file.
150
+ */
151
+ async function importVerified(root, entry) {
152
+ const verifiedEntry = resolve(root, entry);
153
+ if (!within(root, verifiedEntry)) throw new Error("the Laya runtime entry is outside its verified tree");
154
+ return await import(pathToFileURL(verifiedEntry).href);
155
+ }
156
+ async function jsonFile(path) {
157
+ return JSON.parse(await readFile(path, "utf8"));
158
+ }
159
+ function relativeEntry(value) {
160
+ if (typeof value !== "string") return null;
161
+ const entry = value.startsWith("./") ? value.slice(2) : value;
162
+ if (entry.length === 0 || entry.includes("\\") || entry.includes("\0") || entry.startsWith("/")) return null;
163
+ return entry.split("/").some((part) => part === "" || part === "." || part === "..") ? null : entry;
164
+ }
165
+ /** Node's package entry for an ES module import, over a closed subset of `package.json` forms; anything else fails. */
166
+ function moduleEntry(manifest) {
167
+ if (!isRecord(manifest)) return null;
168
+ const exported = manifest.exports;
169
+ if (exported !== void 0) {
170
+ const root = isRecord(exported) && Object.hasOwn(exported, ".") ? exported["."] : exported;
171
+ if (typeof root === "string") return relativeEntry(root);
172
+ if (!isRecord(root)) return null;
173
+ const imported = root.import;
174
+ if (typeof imported === "string") return relativeEntry(imported);
175
+ if (isRecord(imported) && typeof imported.default === "string") return relativeEntry(imported.default);
176
+ return relativeEntry(root.default);
177
+ }
178
+ return relativeEntry(manifest.module ?? manifest.main);
179
+ }
180
+ /**
181
+ * Loads the runtime from the daemon-verified trees: the model's own context limits, the bundle's tokenizer, and
182
+ * `Laya.load` with only `layaLoadOptions`. Any shape it does not recognise refuses the load; it never falls back.
183
+ */
184
+ async function loadVerifiedLayaRuntime(payload) {
185
+ const config = await jsonFile(resolve(payload.modelDir, "laya_config.json"));
186
+ if (!isRecord(config) || config.max_len !== 512 || config.head_max_len !== 192) throw new Error("the verified Laya model does not have its reviewed context limits");
187
+ const tokenizerJson = await jsonFile(resolve(payload.modelDir, "tokenizer", "tokenizer.json"));
188
+ const tokenizerConfig = await jsonFile(resolve(payload.modelDir, "tokenizer", "tokenizer_config.json"));
189
+ const tokenizersEntry = moduleEntry(await jsonFile(resolve(payload.runtimeRoot, LAYA_TOKENIZERS_PACKAGE, "package.json")));
190
+ if (tokenizersEntry === null) throw new Error("the verified tokenizer package has no module entry");
191
+ const tokenizers = await importVerified(payload.runtimeRoot, `${LAYA_TOKENIZERS_PACKAGE}/${tokenizersEntry}`);
192
+ if (typeof tokenizers.Tokenizer !== "function") throw new Error("the verified tokenizer package has no Tokenizer");
193
+ const tokenizer = new tokenizers.Tokenizer(tokenizerJson, tokenizerConfig);
194
+ if (typeof tokenizer.encode !== "function") throw new Error("the verified tokenizer cannot encode");
195
+ const encode = tokenizer.encode.bind(tokenizer);
196
+ const countTokens = (text) => {
197
+ const encoded = encode(text, { add_special_tokens: false });
198
+ const ids = isRecord(encoded) ? encoded.ids : void 0;
199
+ if (!Array.isArray(ids) || !ids.every((id) => Number.isSafeInteger(id))) throw new Error("the verified tokenizer returned no token ids");
200
+ return ids.length;
201
+ };
202
+ countTokens("boundary");
203
+ const runtime = (await importVerified(payload.runtimeRoot, LAYA_RUNTIME_MODULE)).Laya;
204
+ if (runtime === void 0 || runtime === null || typeof runtime.load !== "function") throw new Error("the verified runtime has no Laya.load");
205
+ const loaded = await runtime.load.call(runtime, layaLoadOptions(payload.modelDir));
206
+ if (loaded === null || typeof loaded.systemOne !== "function" || typeof loaded.close !== "function") throw new Error("the verified runtime did not load a System One model");
207
+ const systemOne = loaded.systemOne.bind(loaded);
208
+ const close = loaded.close.bind(loaded);
209
+ return {
210
+ countTokens,
211
+ systemOne: (state, questions) => systemOne(state, questions),
212
+ close: async () => {
213
+ await close();
214
+ }
215
+ };
216
+ }
217
+ //#endregion
218
+ //#region src/runtime/laya/worker-main.ts
219
+ function bindingFromProbe(frame) {
220
+ if (typeof frame.nonce !== "string" || typeof frame.pid !== "number" || !Number.isSafeInteger(frame.pid) || typeof frame.profile !== "string" || typeof frame.entry !== "string" || typeof frame.pipeGeneration !== "string" || typeof frame.tcpPort !== "number" || !Number.isSafeInteger(frame.tcpPort) || typeof frame.udpPort !== "number" || !Number.isSafeInteger(frame.udpPort) || typeof frame.udsPath !== "string") return null;
221
+ return {
222
+ nonce: frame.nonce,
223
+ pid: frame.pid,
224
+ profile: frame.profile,
225
+ entry: frame.entry,
226
+ pipeGeneration: frame.pipeGeneration,
227
+ tcpPort: frame.tcpPort,
228
+ udpPort: frame.udpPort,
229
+ udsPath: frame.udsPath
230
+ };
231
+ }
232
+ /** The probe must name this very process: its PID, the entry Node is running and the reviewed profile. */
233
+ function namesThisWorker(probe) {
234
+ return probe.pid === process.pid && probe.entry === process.argv[1] && probe.profile === "(version 1) (allow default) (deny network*)";
235
+ }
236
+ /** Only the exact binding of the proven child, and these fields, may arrive on a request frame. */
237
+ const REQUEST_FIELDS = [
238
+ "type",
239
+ "nonce",
240
+ "pid",
241
+ "profile",
242
+ "entry",
243
+ "pipeGeneration",
244
+ "requestId",
245
+ "templateId",
246
+ "instructions",
247
+ "state"
248
+ ];
249
+ function requestFrame(binding, frame) {
250
+ const keys = Object.keys(frame).sort();
251
+ const expected = [...REQUEST_FIELDS].sort();
252
+ if (frame.type !== "request" || keys.length !== expected.length || keys.some((key, index) => key !== expected[index]) || frame.nonce !== binding.nonce || frame.pid !== binding.pid || frame.profile !== binding.profile || frame.entry !== binding.entry || frame.pipeGeneration !== binding.pipeGeneration || typeof frame.requestId !== "string" || frame.requestId.length === 0) return null;
253
+ const request = layaWorkerRequest(frame);
254
+ return request === null ? null : {
255
+ requestId: frame.requestId,
256
+ request
257
+ };
258
+ }
259
+ async function rejectAndExit() {
260
+ process.exitCode = 70;
261
+ process.stdin.destroy();
262
+ throw new Error("worker protocol");
263
+ }
264
+ const parser = new WorkerFrameParser();
265
+ let binding;
266
+ /** The load frame is answered exactly once: `loaded`, or `load-refused` after which every frame ends the worker. */
267
+ let loadAnswered = false;
268
+ let runtime;
269
+ let work = Promise.resolve();
270
+ process.stdin.on("data", (chunk) => {
271
+ work = work.then(async () => {
272
+ for (const frame of parser.push(chunk)) {
273
+ if (binding === void 0) {
274
+ const probe = frame.type === "probe" ? bindingFromProbe(frame) : null;
275
+ if (probe === null || !namesThisWorker(probe)) return rejectAndExit();
276
+ const result = await runWorkerBoundaryProbe(probe, async (attempt, outcome) => {
277
+ await writeWorkerFrame(process.stdout, {
278
+ type: "probe-attempt",
279
+ ...probe,
280
+ attempt,
281
+ outcome
282
+ });
283
+ });
284
+ sealWorkerNetworkAfterProbe();
285
+ await assertNoProbeSocketsRemain();
286
+ binding = {
287
+ nonce: probe.nonce,
288
+ pid: probe.pid,
289
+ profile: probe.profile,
290
+ entry: probe.entry,
291
+ pipeGeneration: probe.pipeGeneration
292
+ };
293
+ await writeWorkerFrame(process.stdout, {
294
+ type: "probe-result",
295
+ ...probe,
296
+ ...result
297
+ });
298
+ continue;
299
+ }
300
+ if (!loadAnswered) {
301
+ try {
302
+ assertWorkerLoadBinding(binding, frame);
303
+ } catch {
304
+ await rejectAndExit();
305
+ }
306
+ loadAnswered = true;
307
+ const payload = layaLoadPayload(frame.payload);
308
+ try {
309
+ if (payload === null) throw new Error("load payload");
310
+ runtime = await loadVerifiedLayaRuntime(payload);
311
+ } catch {
312
+ await writeWorkerFrame(process.stdout, {
313
+ type: "load-refused",
314
+ ...binding,
315
+ code: "runtime-failed"
316
+ });
317
+ continue;
318
+ }
319
+ await writeWorkerFrame(process.stdout, {
320
+ type: "loaded",
321
+ ...binding
322
+ });
323
+ continue;
324
+ }
325
+ const request = runtime === void 0 ? null : requestFrame(binding, frame);
326
+ if (runtime === void 0 || request === null) return rejectAndExit();
327
+ const outcome = await evaluateLayaRequest(runtime, request.request);
328
+ await writeWorkerFrame(process.stdout, outcome.kind === "answer" ? {
329
+ type: "answer",
330
+ ...binding,
331
+ requestId: request.requestId,
332
+ value: outcome.value,
333
+ inputTokens: outcome.inputTokens
334
+ } : {
335
+ type: "refused",
336
+ ...binding,
337
+ requestId: request.requestId,
338
+ code: outcome.code
339
+ });
340
+ }
341
+ });
342
+ work.catch(() => {
343
+ process.exitCode = 70;
344
+ process.stdin.destroy();
345
+ });
346
+ });
347
+ process.stdin.on("end", () => {
348
+ try {
349
+ parser.finish();
350
+ } catch {
351
+ process.exitCode = 70;
352
+ }
353
+ if (runtime !== void 0) runtime.close().catch(() => void 0).finally(() => process.exit());
354
+ });
355
+ //#endregion
356
+ export {};