omp-superagent 0.1.11 → 0.1.15
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/DESIGN.md +21 -5
- package/README.ko.md +3 -1
- package/README.md +3 -1
- package/THIRD_PARTY_NOTICES.md +6 -0
- package/assets/architecture-dark.svg +4 -4
- package/assets/architecture.ko-dark.svg +4 -4
- package/assets/architecture.ko.svg +4 -4
- package/assets/architecture.mmd +5 -5
- package/assets/architecture.svg +4 -4
- package/config.example.json +1 -0
- package/docs/OPERATIONS.en.md +242 -31
- package/docs/OPERATIONS.md +225 -25
- package/docs/design/execution.md +161 -43
- package/docs/design/messaging.md +45 -9
- package/docs/releases/0.1.11.md +4 -2
- package/docs/releases/0.1.13.md +13 -0
- package/docs/releases/0.1.15.md +13 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +9 -3
- package/scripts/prepare-worker-memory.ts +37 -0
- package/scripts/upgrade-evidence-files.mjs +100 -0
- package/scripts/upgrade-evidence.mjs +192 -0
- package/scripts/upgrade-host-wire.mjs +162 -0
- package/skills/head/SKILL.md +22 -47
- package/skills/head/references/routing.md +11 -12
- package/skills/head/references/supervision.md +10 -14
- package/skills/lane/SKILL.md +14 -16
- package/skills/lane/references/workflow.md +14 -27
- package/src/cli.ts +59 -79
- package/src/config/config.ts +4 -0
- package/src/contracts.ts +34 -27
- package/src/cron/cron-jobs.ts +4 -3
- package/src/cron/cron-pr-intake.ts +1 -2
- package/src/extension.ts +57 -14
- package/src/gateway/gateway-client.ts +14 -12
- package/src/group/group-runner.ts +3 -2
- package/src/group-runner-extension.ts +7 -3
- package/src/host-extension.ts +109 -2
- package/src/host-sdk-helper.ts +12 -3
- package/src/lane/decision-tool.ts +2 -3
- package/src/lane/lane-report.ts +8 -30
- package/src/lane/lane-rows.ts +1 -1
- package/src/lane/workflow.ts +44 -3
- package/src/lane-extension.ts +5 -46
- package/src/messaging/discord-context.ts +8 -6
- package/src/omp/host-protocol.ts +4 -3
- package/src/omp/host.ts +24 -7
- package/src/omp/managed-super.ts +43 -27
- package/src/omp/native-sessions.ts +12 -0
- package/src/omp/worker-memory-import.ts +410 -0
- package/src/omp/worker-memory-sdk.ts +8 -0
- package/src/operator/setup.ts +8 -13
- package/src/operator/stop-lane.ts +25 -0
- package/src/pr/pr-github-schema.ts +9 -0
- package/src/pr/pr-github.ts +6 -2
- package/src/pr/pr-intake-automation.ts +11 -8
- package/src/pr/pr-intake-fix.ts +2 -5
- package/src/pr/pr-intake-review.ts +7 -7
- package/src/routing/topic-history.ts +2 -2
- package/src/runtime/controller.ts +444 -408
- package/src/runtime/head-recovery.ts +7 -7
- package/src/runtime/worker-memory.ts +156 -0
- package/src/storage/deferred-routing.ts +1 -7
- package/src/storage/store.ts +441 -375
- package/src/worker/worker-host.ts +3 -2
- package/src/worker/worker-ledger.ts +20 -11
- package/src/worker/worker-memory-page.ts +83 -0
- package/src/worker/worker-memory-proofs.ts +260 -0
- package/src/worker/worker-memory-source.ts +305 -0
- package/src/worker/worker-memory-storage.ts +130 -0
- package/src/worker/worker-profile.ts +2 -0
- package/src/worker/worker-repository.ts +92 -7
- package/src/worker/worker-request.ts +1 -0
- package/src/worker/worker-service.ts +25 -8
- package/src/worker/worker-wire.ts +20 -6
|
@@ -106,7 +106,7 @@ export async function attestWorkerHost(paths: WorkerPaths, files: WorkerFiles, r
|
|
|
106
106
|
receipt.phase === "live" && (receipt.identity.pid !== identity.pid || receipt.identity.ownerPid !== identity.ownerPid
|
|
107
107
|
|| !sameFile(receipt.identity, files.socket)))
|
|
108
108
|
throw new WorkerRefusal("Worker native Host identity or launch receipt does not match");
|
|
109
|
-
return identity;
|
|
109
|
+
return { ...identity, ...(receipt.memory?.file && state.memorySyncVersion === 1 && { memorySyncVersion: 1 }) };
|
|
110
110
|
} finally { await connection.close(); }
|
|
111
111
|
}
|
|
112
112
|
|
|
@@ -148,7 +148,8 @@ export async function inspectWorkerHost(ledger: WorkerLedger, paths: WorkerPaths
|
|
|
148
148
|
saved.identity.pid === identity.pid && saved.identity.ownerPid === identity.ownerPid &&
|
|
149
149
|
saved.identity.sessionId === identity.sessionId && sameFile(saved.identity, files.socket)) {
|
|
150
150
|
return { socket: true, sessionFile: true, sessionId: identity.sessionId, pid: identity.pid,
|
|
151
|
-
pidAlive: true, ownerAlive: true, uncertain: false
|
|
151
|
+
pidAlive: true, ownerAlive: true, uncertain: false,
|
|
152
|
+
...(identity.memorySyncVersion === 1 && { memorySyncVersion: 1 }) };
|
|
152
153
|
}
|
|
153
154
|
} catch (error) {
|
|
154
155
|
if (!(error instanceof Error)) throw error;
|
|
@@ -4,6 +4,7 @@ import { join } from "node:path";
|
|
|
4
4
|
import { Type, type Static } from "@sinclair/typebox/type";
|
|
5
5
|
import { Value } from "@sinclair/typebox/value";
|
|
6
6
|
import { releaseCheckout } from "./worker-checkout";
|
|
7
|
+
import { workerMemoryBinding, type WorkerMemoryBinding } from "./worker-memory-storage";
|
|
7
8
|
import { WorkerRefusal } from "./worker-request";
|
|
8
9
|
import type { WorkerLaneRef, WorkerPolicy } from "./worker-wire";
|
|
9
10
|
|
|
@@ -19,6 +20,7 @@ const identity = Type.Object({
|
|
|
19
20
|
...identityFields,
|
|
20
21
|
dev: Type.Number(),
|
|
21
22
|
ino: Type.Number(),
|
|
23
|
+
memorySyncVersion: Type.Optional(Type.Literal(1)),
|
|
22
24
|
});
|
|
23
25
|
export const workerExit = Type.Object({
|
|
24
26
|
...identityFields,
|
|
@@ -40,6 +42,8 @@ const receiptFields = {
|
|
|
40
42
|
attempt: Type.String({ pattern: "^[0-9a-f-]{36}$" }),
|
|
41
43
|
launcherPid: workerPid,
|
|
42
44
|
sessionId: Type.Union([sessionId, Type.Null()]),
|
|
45
|
+
memory: Type.Optional(workerMemoryBinding),
|
|
46
|
+
privateMemoryPrepared: Type.Optional(Type.Literal(true)),
|
|
43
47
|
};
|
|
44
48
|
const receipt = Type.Union([
|
|
45
49
|
Type.Object({ ...receiptFields, phase: Type.Literal("reserved") }),
|
|
@@ -147,7 +151,9 @@ export class WorkerLedger {
|
|
|
147
151
|
return options.reconcile ? confirm.immediate() : confirm();
|
|
148
152
|
}
|
|
149
153
|
|
|
150
|
-
reserve(ref: WorkerLaneRef, binding: {
|
|
154
|
+
reserve(ref: WorkerLaneRef, binding: {
|
|
155
|
+
readonly repoRoot: string; readonly gitDir: string; readonly launchDigest: string; readonly memory?: WorkerMemoryBinding;
|
|
156
|
+
}, previous: WorkerReceipt | null): ReservedReceipt {
|
|
151
157
|
return this.#db.transaction(() => {
|
|
152
158
|
if ((this.#sealedGeneration(ref, binding.repoRoot) ?? 0) >= ref.generation)
|
|
153
159
|
throw new WorkerRefusal("Worker lane generation was sealed and cannot open");
|
|
@@ -164,25 +170,28 @@ export class WorkerLedger {
|
|
|
164
170
|
}).immediate();
|
|
165
171
|
}
|
|
166
172
|
|
|
167
|
-
|
|
173
|
+
#replaceCurrent(current: WorkerReceipt, replacement: () => WorkerReceipt): boolean {
|
|
168
174
|
return this.#db.transaction(() => {
|
|
169
175
|
const actual = this.get(current.laneId);
|
|
170
176
|
if (actual?.attempt !== current.attempt || actual.phase !== current.phase) return false;
|
|
171
|
-
this.#write(
|
|
177
|
+
this.#write(replacement());
|
|
172
178
|
return true;
|
|
173
179
|
}).immediate();
|
|
174
180
|
}
|
|
175
181
|
|
|
182
|
+
transition(current: WorkerReceipt, next: WorkerReceipt): boolean {
|
|
183
|
+
return this.#replaceCurrent(current, () => next);
|
|
184
|
+
}
|
|
185
|
+
|
|
176
186
|
retire(current: WorkerReceipt, exit?: { readonly sessionId: string; readonly clean: boolean; readonly cleanup: () => void }): boolean {
|
|
177
|
-
return this.#
|
|
178
|
-
const actual = this.get(current.laneId);
|
|
179
|
-
if (actual?.attempt !== current.attempt || actual.phase !== current.phase) return false;
|
|
187
|
+
return this.#replaceCurrent(current, () => {
|
|
180
188
|
exit?.cleanup();
|
|
181
189
|
releaseCheckout(current);
|
|
182
|
-
const { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest } = current;
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
190
|
+
const { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest, memory } = current;
|
|
191
|
+
const sessionId = exit?.sessionId ?? current.sessionId;
|
|
192
|
+
return { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest,
|
|
193
|
+
phase: "released", sessionId, ...(sessionId !== null && memory ? { memory } : {}),
|
|
194
|
+
...(exit?.clean && { exitVerified: true }) };
|
|
195
|
+
});
|
|
187
196
|
}
|
|
188
197
|
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { redactMemorySecrets } from "@oh-my-pi/pi-coding-agent/memory-backend/redact";
|
|
2
|
+
import { CREDENTIAL_PATTERNS } from "@oh-my-pi/pi-coding-agent/secrets/patterns";
|
|
3
|
+
import { Type } from "@sinclair/typebox/type";
|
|
4
|
+
import { Value } from "@sinclair/typebox/value";
|
|
5
|
+
|
|
6
|
+
export const WORKER_MEMORY_ROWS = 16;
|
|
7
|
+
export const WORKER_MEMORY_TEXT_BYTES = 2048;
|
|
8
|
+
export const WORKER_MEMORY_PAGE_BYTES = 24 * 1024;
|
|
9
|
+
export const workerMemoryId = /^[0-9a-f]{16}$/u;
|
|
10
|
+
const workerMemoryStamp = /^[0-9a-f]{64}$/u;
|
|
11
|
+
const credentialPatterns = CREDENTIAL_PATTERNS.map(({ source, flags }) => new RegExp(source, flags));
|
|
12
|
+
const telegramToken = /(?:^|[^A-Za-z0-9_])(?:bot)?\d{6,16}(?::|%3a)[A-Za-z0-9_-]{30,}(?![A-Za-z0-9_-])/iu;
|
|
13
|
+
const telegramBotPath = /^\/(?:file\/)?bot\d+:[^/]+(?:\/|$)/iu;
|
|
14
|
+
const webhookPath = /\/(?:webhooks?|download|signed|private)(?:\/|$)/iu;
|
|
15
|
+
const slackCapability = /(?:^|[^A-Za-z0-9_-])xapp-[A-Za-z0-9_-]{12,}|\bhooks\.slack(?:-gov)?\.com\/(?:services|commands|workflows)\//iu;
|
|
16
|
+
const discordToken = /(?:^|[^\w-])(?:Bot\s+[\w-]+\.[\w-]+\.[\w-]+|[MNO][\w-]{21,27}\.[\w-]{6}\.[\w-]{20,}|mfa\.[\w-]{20,})(?![\w-])/iu;
|
|
17
|
+
|
|
18
|
+
const strict = { additionalProperties: false } as const;
|
|
19
|
+
const cursor = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
|
|
20
|
+
const schema = Type.Object({
|
|
21
|
+
after: cursor,
|
|
22
|
+
next: cursor,
|
|
23
|
+
stamp: Type.String({ minLength: 64, maxLength: 64 }),
|
|
24
|
+
records: Type.Array(Type.Object({
|
|
25
|
+
at: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
|
|
26
|
+
id: Type.String({ minLength: 16, maxLength: 16 }),
|
|
27
|
+
content: Type.String({ minLength: 1, maxLength: WORKER_MEMORY_TEXT_BYTES }),
|
|
28
|
+
}, strict), { maxItems: WORKER_MEMORY_ROWS }),
|
|
29
|
+
}, strict);
|
|
30
|
+
|
|
31
|
+
export type WorkerMemoryRecord = { readonly at: number; readonly id: string; readonly content: string };
|
|
32
|
+
export type WorkerMemoryPage = {
|
|
33
|
+
readonly after: number;
|
|
34
|
+
readonly next: number;
|
|
35
|
+
readonly stamp: string;
|
|
36
|
+
readonly records: readonly WorkerMemoryRecord[];
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export const isWorkerMemoryCursor = (value: unknown): value is number =>
|
|
40
|
+
typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
41
|
+
export const isWorkerMemoryStamp = (value: unknown): value is string =>
|
|
42
|
+
typeof value === "string" && value.length === 64 && workerMemoryStamp.test(value);
|
|
43
|
+
|
|
44
|
+
export function safeWorkerMemoryText(text: string): boolean {
|
|
45
|
+
if (text.length > WORKER_MEMORY_TEXT_BYTES || !text.trim() || Buffer.byteLength(text, "utf8") > WORKER_MEMORY_TEXT_BYTES
|
|
46
|
+
|| /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]|data:[^ ]*,|\[redacted\]|<\/?(?:system|developer|assistant|user|memories|tool_call|system-reminder)\b/iu.test(text)
|
|
47
|
+
|| /\b(?:bearer\s+\S|(?:authorization|(?:set-)?cookie)\s*:|(?:password|passphrase|secret|api[_ -]?key|access[_ -]?token|client[_ -]?secret)\s*[:=]|-----begin\s+[\w ]*private key)|(?:^|\s)\w+@[\w.-]+:\S/iu.test(text)
|
|
48
|
+
|| telegramToken.test(text) || slackCapability.test(text) || discordToken.test(text) || /\/api\/(?:v\d+\/)?webhooks\/\d+\/\S/iu.test(text)
|
|
49
|
+
|| credentialPatterns.some(pattern => pattern.test(text)) || redactMemorySecrets(text) !== text)
|
|
50
|
+
return false;
|
|
51
|
+
for (const link of text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\/[^\s<>"'`]+/giu)) {
|
|
52
|
+
try {
|
|
53
|
+
const url = new URL(link[0]);
|
|
54
|
+
const path = decodeURIComponent(url.pathname);
|
|
55
|
+
if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password
|
|
56
|
+
|| url.search || url.hash || webhookPath.test(path) || telegramToken.test(path) || telegramBotPath.test(path)
|
|
57
|
+
|| (/^hooks\.slack(?:-gov)?\.com\.?$/iu.test(url.hostname) && /^\/(?:services|commands|workflows)(?:\/|$)/iu.test(path))
|
|
58
|
+
|| (url.hostname.replace(/\.$/u, "") === "api.telegram.org" && /^\/(?:file\/)?bot[^/]+(?:\/|$)/iu.test(path))) return false;
|
|
59
|
+
} catch { return false; }
|
|
60
|
+
}
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class WorkerMemoryPageError extends Error {}
|
|
65
|
+
|
|
66
|
+
/** Zero is end-of-scan, not an error or a request to skip the final records. */
|
|
67
|
+
export function parseWorkerMemoryPage(value: unknown, after: number): WorkerMemoryPage {
|
|
68
|
+
if (!isWorkerMemoryCursor(after) || !Value.Check(schema, value) || value.after !== after || !isWorkerMemoryStamp(value.stamp)
|
|
69
|
+
|| (value.next !== 0 && value.next <= after))
|
|
70
|
+
throw new WorkerMemoryPageError("Invalid worker memory page");
|
|
71
|
+
let previous = after;
|
|
72
|
+
const ids = new Set<string>();
|
|
73
|
+
for (const record of value.records) {
|
|
74
|
+
if (record.at <= previous || (value.next !== 0 && record.at > value.next)
|
|
75
|
+
|| !workerMemoryId.test(record.id) || ids.has(record.id) || !safeWorkerMemoryText(record.content))
|
|
76
|
+
throw new WorkerMemoryPageError("Invalid worker memory record");
|
|
77
|
+
previous = record.at;
|
|
78
|
+
ids.add(record.id);
|
|
79
|
+
}
|
|
80
|
+
if (Buffer.byteLength(JSON.stringify(value), "utf8") > WORKER_MEMORY_PAGE_BYTES)
|
|
81
|
+
throw new WorkerMemoryPageError("Worker memory page exceeds its byte limit");
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
|
|
4
|
+
import { safeWorkerMemoryText, WORKER_MEMORY_ROWS } from "./worker-memory-page";
|
|
5
|
+
import { WorkerRefusal } from "./worker-request";
|
|
6
|
+
|
|
7
|
+
export type WorkerFactTool = "retain" | "learn";
|
|
8
|
+
export type WorkerFactCarrier = WorkerFactTool | "bash";
|
|
9
|
+
export type WorkerFactOrigin = { readonly sessionId: string; readonly bank: string };
|
|
10
|
+
type FactBatch = readonly (string | null)[];
|
|
11
|
+
export type WorkerFactEntry =
|
|
12
|
+
| { readonly kind: "direct"; readonly tool: WorkerFactTool; readonly batch: FactBatch }
|
|
13
|
+
| { readonly kind: "mounted"; readonly tool: WorkerFactTool; readonly command: string };
|
|
14
|
+
const maxProofs = 65_536;
|
|
15
|
+
const hexDigest = /^[0-9a-f]{64}$/u;
|
|
16
|
+
const proofTable = "CREATE TABLE worker_fact_proofs (position INTEGER PRIMARY KEY, digest TEXT NOT NULL) STRICT";
|
|
17
|
+
const proofIndex = "CREATE UNIQUE INDEX worker_fact_proofs_digest ON worker_fact_proofs(digest)";
|
|
18
|
+
|
|
19
|
+
export function workerFactDigest(origin: WorkerFactOrigin, tool: WorkerFactTool, text: string): string {
|
|
20
|
+
return createHash("sha256").update(JSON.stringify(["worker-native-fact-v1", origin.sessionId, origin.bank, tool, text])).digest("hex");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function record(value: unknown): value is Readonly<Record<string, unknown>> {
|
|
24
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Only recognized direct native project inputs; never examine context or skill bodies. */
|
|
28
|
+
export function workerFactBatch(origin: WorkerFactOrigin, tool: WorkerFactTool, input: unknown): FactBatch | undefined {
|
|
29
|
+
if (!record(input)) return undefined;
|
|
30
|
+
const fact = (text: unknown) => typeof text === "string" && safeWorkerMemoryText(text) ? workerFactDigest(origin, tool, text) : null;
|
|
31
|
+
if (tool === "learn")
|
|
32
|
+
return input.skill === undefined && (input.scope === undefined || input.scope === "project") && typeof input.memory === "string"
|
|
33
|
+
? [fact(input.memory)] : undefined;
|
|
34
|
+
if (!Array.isArray(input.items) || !input.items.length || input.items.length > WORKER_MEMORY_ROWS) return undefined;
|
|
35
|
+
const batch: (string | null)[] = [];
|
|
36
|
+
for (const item of input.items) {
|
|
37
|
+
if (!record(item) || typeof item.content !== "string" || (item.scope !== undefined && item.scope !== "project")) return undefined;
|
|
38
|
+
batch.push(fact(item.content));
|
|
39
|
+
}
|
|
40
|
+
return batch;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function nativeFactSuccess(tool: WorkerFactTool, details: unknown, length: number): boolean {
|
|
44
|
+
return record(details) && Object.keys(details).length === 1
|
|
45
|
+
&& (tool === "retain" ? details.count === length : details.skill === null);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function isWorkerFactRoot(
|
|
49
|
+
context: { readonly agent: { readonly kind: string; readonly id: string }; readonly sessionManager: object },
|
|
50
|
+
rootAgent: string, rootSession: object,
|
|
51
|
+
): boolean {
|
|
52
|
+
return context.agent.kind === "main" && context.agent.id === rootAgent && context.sessionManager === rootSession;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Reject shell programs, interpolation and extra commands. Literal quoted tool
|
|
56
|
+
// arguments (including the stock JSON form) are still interpreted only by OMP.
|
|
57
|
+
function literalWorkerFactCommand(command: string): WorkerFactTool | undefined {
|
|
58
|
+
const match = /^[ \t]*(retain|learn)(?=[ \t]|$)/u.exec(command);
|
|
59
|
+
if (!match || /^[ \t]*(?:retain|learn)[ \t]+(?:--help|-h)(?:[ \t]|$)/u.test(command)) return;
|
|
60
|
+
let quote: "'" | '"' | undefined;
|
|
61
|
+
let word = "";
|
|
62
|
+
// Stock tool-cli expands @file and '-' before building its typed receipt.
|
|
63
|
+
// Check the literal argv spelling as well as the resulting native call.
|
|
64
|
+
const inline = () => !/^(?:--[^=]+=)?(?:@|-$)/u.test(word);
|
|
65
|
+
for (let i = match[0].length; i < command.length; i++) {
|
|
66
|
+
const character = command.charAt(i);
|
|
67
|
+
if (quote === "'") {
|
|
68
|
+
if (character === quote) quote = undefined;
|
|
69
|
+
else word += character;
|
|
70
|
+
} else if (character === "\\") {
|
|
71
|
+
const escaped = command[++i];
|
|
72
|
+
if (!escaped || escaped === "\n" || escaped === "\r" || escaped === "\0") return;
|
|
73
|
+
word += escaped;
|
|
74
|
+
} else if (character === quote) {
|
|
75
|
+
quote = undefined;
|
|
76
|
+
} else if (character === "$" || character === "`" || character === "\0") {
|
|
77
|
+
return;
|
|
78
|
+
} else if (!quote) {
|
|
79
|
+
if (character === "'" || character === '"') quote = character;
|
|
80
|
+
else if (character === " " || character === "\t") {
|
|
81
|
+
if (!inline()) return;
|
|
82
|
+
word = "";
|
|
83
|
+
}
|
|
84
|
+
else if (/[;&|<>()*?[{}~#!\r\n]/u.test(character)) return;
|
|
85
|
+
else word += character;
|
|
86
|
+
} else word += character;
|
|
87
|
+
}
|
|
88
|
+
if (!quote && inline()) return match[1] === "retain" ? "retain" : "learn";
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function mountedWorkerFact(input: unknown): { readonly tool: WorkerFactTool; readonly command: string } | undefined {
|
|
92
|
+
if (!record(input) || typeof input.command !== "string" || input.command.length > 64 * 1024
|
|
93
|
+
|| Buffer.byteLength(input.command) > 64 * 1024
|
|
94
|
+
|| (input.pty !== undefined && input.pty !== false) || (input.async !== undefined && input.async !== false)
|
|
95
|
+
|| input.cwd !== undefined || input.name !== undefined) return;
|
|
96
|
+
const tool = literalWorkerFactCommand(input.command.trimEnd());
|
|
97
|
+
if (tool) return { tool, command: input.command };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Cheap admission only when the private profile exists but the source is not yet bound. */
|
|
101
|
+
export function canBeginWorkerFact(carrier: WorkerFactCarrier, input: unknown): boolean {
|
|
102
|
+
return carrier === "bash" ? mountedWorkerFact(input) !== undefined : record(input);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function workerFactEntry(origin: WorkerFactOrigin, carrier: WorkerFactCarrier, input: unknown): WorkerFactEntry | undefined {
|
|
106
|
+
if (carrier !== "bash") {
|
|
107
|
+
const batch = workerFactBatch(origin, carrier, input);
|
|
108
|
+
if (batch?.some(digest => digest !== null)) return { kind: "direct", tool: carrier, batch };
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const mounted = mountedWorkerFact(input);
|
|
112
|
+
if (mounted) return { kind: "mounted", tool: mounted.tool, command: createHash("sha256").update(mounted.command).digest("hex") };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The parent must be a proven stock Bash execution. Shell output is never a receipt. */
|
|
116
|
+
export function workerFactResult(origin: WorkerFactOrigin, entry: WorkerFactEntry, details: unknown): FactBatch | undefined {
|
|
117
|
+
if (entry.kind === "direct")
|
|
118
|
+
return nativeFactSuccess(entry.tool, details, entry.batch.length) ? entry.batch : undefined;
|
|
119
|
+
if (!record(details) || details.async !== undefined || details.timedOut === true
|
|
120
|
+
|| (details.exitCode !== undefined && details.exitCode !== 0)
|
|
121
|
+
|| !Array.isArray(details.toolCommands) || details.toolCommands.length !== 1) return;
|
|
122
|
+
const dispatch: unknown = details.toolCommands[0];
|
|
123
|
+
if (!record(dispatch) || dispatch.tool !== entry.tool || dispatch.mode !== "execute" || dispatch.exitCode !== 0
|
|
124
|
+
|| dispatch.tier !== "read" || dispatch.readOnlyHint !== undefined) return;
|
|
125
|
+
const batch = workerFactBatch(origin, entry.tool, dispatch.args);
|
|
126
|
+
if (batch && batch.some(digest => digest !== null) && nativeFactSuccess(entry.tool, dispatch.inner, batch.length)) return batch;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function sameBatch(left: FactBatch, right: FactBatch): boolean {
|
|
130
|
+
return left.length === right.length && left.every((digest, i) => digest === right[i]);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function sameWorkerFactEntry(left: WorkerFactEntry, right: WorkerFactEntry): boolean {
|
|
134
|
+
return left.tool === right.tool && (left.kind === "direct"
|
|
135
|
+
? right.kind === "direct" && sameBatch(left.batch, right.batch)
|
|
136
|
+
: right.kind === "mounted" && left.command === right.command);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function sameWorkerFactResult(expected: FactBatch, observed: FactBatch | undefined): boolean {
|
|
140
|
+
return observed !== undefined && sameBatch(expected, observed);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Reserve this once, alongside a fresh worker bank, without adopting existing data. */
|
|
144
|
+
export function reserveWorkerFactProofs(path: string): string {
|
|
145
|
+
const fd = openSync(path, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
146
|
+
try {
|
|
147
|
+
const stat = fstatSync(fd, { bigint: true });
|
|
148
|
+
const identity = `${stat.dev}:${stat.ino}`;
|
|
149
|
+
using store = openWorkerFactProofs(path, identity, true);
|
|
150
|
+
store.db.exec(`PRAGMA synchronous = FULL; PRAGMA journal_mode = DELETE; ${proofTable}; ${proofIndex};`);
|
|
151
|
+
store.check();
|
|
152
|
+
return identity;
|
|
153
|
+
} finally { closeSync(fd); }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function openWorkerFactProofs(path: string, identity: string, write: boolean) {
|
|
157
|
+
for (const suffix of ["-wal", "-shm"])
|
|
158
|
+
if (lstatSync(path + suffix, { throwIfNoEntry: false })) throw new WorkerRefusal("Worker fact proofs are unavailable");
|
|
159
|
+
const journal = `${path}-journal`;
|
|
160
|
+
const rollback = lstatSync(journal, { bigint: true, throwIfNoEntry: false });
|
|
161
|
+
if (rollback && (!write || !rollback.isFile() || rollback.nlink !== 1n
|
|
162
|
+
|| rollback.uid !== BigInt(process.getuid?.() ?? -1) || (rollback.mode & 0o777n) !== 0o600n
|
|
163
|
+
|| rollback.size > 16n * 1024n * 1024n || realpathSync(journal) !== journal))
|
|
164
|
+
throw new WorkerRefusal("Worker fact proof rollback is unavailable");
|
|
165
|
+
const access = write ? constants.O_RDWR : constants.O_RDONLY;
|
|
166
|
+
const fd = openSync(path, access | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
167
|
+
try {
|
|
168
|
+
const expected = fstatSync(fd, { bigint: true });
|
|
169
|
+
const check = () => {
|
|
170
|
+
checkedProofFile(path, identity);
|
|
171
|
+
if (`${expected.dev}:${expected.ino}` !== identity) throw new WorkerRefusal("Worker fact proofs are unavailable");
|
|
172
|
+
};
|
|
173
|
+
check();
|
|
174
|
+
if (expected.size > 0n) {
|
|
175
|
+
const header = Buffer.alloc(20);
|
|
176
|
+
if (readSync(fd, header, 0, header.length, 0) !== header.length
|
|
177
|
+
|| header.toString("ascii", 0, 16) !== "SQLite format 3\u0000" || header[18] !== 1 || header[19] !== 1)
|
|
178
|
+
throw new WorkerRefusal("Worker fact proof journal mode is unavailable");
|
|
179
|
+
}
|
|
180
|
+
const db = new Database(path, { readonly: !write, strict: true });
|
|
181
|
+
try {
|
|
182
|
+
check();
|
|
183
|
+
db.exec("PRAGMA trusted_schema = OFF; PRAGMA busy_timeout = 0;");
|
|
184
|
+
return { db, check, [Symbol.dispose]() { db.close(); } };
|
|
185
|
+
} catch (error) {
|
|
186
|
+
db.close();
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
} finally { closeSync(fd); }
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function checkedProofFile(path: string, identity: string) {
|
|
193
|
+
const actual = lstatSync(path, { bigint: true });
|
|
194
|
+
if (!actual.isFile() || actual.nlink !== 1n || actual.uid !== BigInt(process.getuid?.() ?? -1)
|
|
195
|
+
|| (actual.mode & 0o777n) !== 0o600n || `${actual.dev}:${actual.ino}` !== identity
|
|
196
|
+
|| actual.size > 16n * 1024n * 1024n || realpathSync(path) !== path)
|
|
197
|
+
throw new WorkerRefusal("Worker fact proofs are unavailable");
|
|
198
|
+
return actual;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function validateProofSchema(db: Database) {
|
|
202
|
+
using schema = db.prepare<{ type: string; sql: string }, []>("SELECT type, sql FROM main.sqlite_schema LIMIT 3");
|
|
203
|
+
const objects = schema.all();
|
|
204
|
+
if (objects.length !== 2 || !objects.some(item => item.type === "table" && item.sql === proofTable)
|
|
205
|
+
|| !objects.some(item => item.type === "index" && item.sql === proofIndex))
|
|
206
|
+
throw new WorkerRefusal("Worker fact proof schema is unavailable");
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Private coordination witness. The stock memory bank is never modified. */
|
|
210
|
+
export function workerFactProofs(path: string, identity: string) {
|
|
211
|
+
return {
|
|
212
|
+
recover() {
|
|
213
|
+
if (!lstatSync(`${path}-journal`, { throwIfNoEntry: false })) return;
|
|
214
|
+
using store = openWorkerFactProofs(path, identity, true);
|
|
215
|
+
// Only SQLite can decide whether this private rollback is hot. Never
|
|
216
|
+
// unlink it or interpret another file as the reserved database.
|
|
217
|
+
store.db.transaction(() => validateProofSchema(store.db)).immediate();
|
|
218
|
+
store.check();
|
|
219
|
+
},
|
|
220
|
+
version() {
|
|
221
|
+
for (const suffix of ["-wal", "-shm", "-journal"])
|
|
222
|
+
if (lstatSync(path + suffix, { throwIfNoEntry: false })) throw new WorkerRefusal("Worker fact proofs are unavailable");
|
|
223
|
+
const file = checkedProofFile(path, identity);
|
|
224
|
+
return `${identity}:${file.size}:${file.mtimeNs}:${file.ctimeNs}`;
|
|
225
|
+
},
|
|
226
|
+
seal(batch: FactBatch) {
|
|
227
|
+
if (batch.length > WORKER_MEMORY_ROWS || batch.some(digest => digest !== null && (digest.length !== 64 || !hexDigest.test(digest))))
|
|
228
|
+
throw new WorkerRefusal("Worker fact proof format is invalid");
|
|
229
|
+
if (!batch.some(item => item !== null)) return;
|
|
230
|
+
using store = openWorkerFactProofs(path, identity, true);
|
|
231
|
+
const { db } = store;
|
|
232
|
+
db.exec("PRAGMA synchronous = FULL;");
|
|
233
|
+
db.transaction(() => {
|
|
234
|
+
validateProofSchema(db);
|
|
235
|
+
using write = db.prepare("INSERT OR IGNORE INTO worker_fact_proofs(digest) VALUES (?)");
|
|
236
|
+
using count = db.prepare<{ position: number }, []>("SELECT max(position) AS position FROM worker_fact_proofs");
|
|
237
|
+
const position = count.get()?.position ?? 0;
|
|
238
|
+
for (const digest of batch.slice(0, Math.max(0, maxProofs - position)))
|
|
239
|
+
if (digest !== null) write.run(digest);
|
|
240
|
+
}).immediate();
|
|
241
|
+
store.check();
|
|
242
|
+
},
|
|
243
|
+
lookup() {
|
|
244
|
+
const store = openWorkerFactProofs(path, identity, false);
|
|
245
|
+
try {
|
|
246
|
+
store.db.exec("BEGIN");
|
|
247
|
+
validateProofSchema(store.db);
|
|
248
|
+
const query = store.db.prepare("SELECT 1 FROM main.worker_fact_proofs INDEXED BY worker_fact_proofs_digest WHERE digest = ?");
|
|
249
|
+
return {
|
|
250
|
+
has(digest: string) { return !!query.get(digest); },
|
|
251
|
+
check: store.check,
|
|
252
|
+
[Symbol.dispose]() { try { query.finalize(); } finally { store[Symbol.dispose](); } },
|
|
253
|
+
};
|
|
254
|
+
} catch (error) {
|
|
255
|
+
store[Symbol.dispose]();
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
}
|