omp-superagent 0.1.6 → 0.1.8
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 +36 -20
- package/README.ko.md +140 -33
- package/README.md +165 -41
- package/THIRD_PARTY_NOTICES.md +9 -7
- package/config.example.json +3 -1
- package/docs/OPERATIONS.md +395 -157
- package/docs/design/execution.md +156 -22
- package/docs/design/messaging.md +258 -52
- package/docs/discord-voice.md +8 -4
- package/docs/releases/0.1.7.md +25 -0
- package/docs/releases/0.1.8.md +21 -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 -9
- package/scripts/ci.ts +4 -4
- package/scripts/test-omp.sh +2 -1
- package/skills/head/SKILL.md +26 -5
- package/skills/head/references/routing.md +68 -33
- package/skills/head/references/supervision.md +20 -4
- package/skills/lane/references/workflow.md +16 -7
- package/src/board.ts +5 -3
- package/src/cli.ts +161 -19
- package/src/config.ts +21 -1
- package/src/contracts.ts +63 -8
- package/src/cron-jobs.ts +443 -19
- package/src/cron-pr-intake.ts +257 -0
- package/src/discord-markdown.ts +350 -123
- package/src/extension.ts +78 -13
- package/src/gateway-client.ts +8 -2
- package/src/head-quota.ts +80 -0
- package/src/head-recovery.ts +40 -1
- package/src/host-extension.ts +122 -4
- package/src/host-inventory-manifest.ts +2 -2
- package/src/host-protocol.ts +11 -0
- package/src/host-sdk-helper.ts +121 -12
- package/src/host.ts +175 -57
- package/src/installed-omp.ts +116 -4
- package/src/lane-rows.ts +44 -4
- package/src/lane-watch.ts +339 -0
- package/src/managed-memory-helper.ts +13 -10
- package/src/managed-memory.ts +62 -27
- package/src/managed-ulw-probe.ts +75 -20
- package/src/managed-ulw.ts +174 -21
- package/src/messenger-command-catalog.json +2 -2
- package/src/native-launch-profile.ts +4 -2
- package/src/native-presets.ts +32 -5
- package/src/native-sessions.ts +3 -1
- package/src/native-settings.ts +47 -9
- package/src/observation-request.ts +23 -0
- package/src/omp-usage.ts +254 -36
- package/src/pr-github-schema.ts +5 -1
- package/src/pr-github.ts +68 -19
- package/src/pr-intake-automation.ts +316 -0
- package/src/pr-intake-comment.ts +226 -0
- package/src/pr-intake-fix.ts +233 -0
- package/src/pr-intake-github.ts +480 -0
- package/src/pr-intake-material.ts +230 -0
- package/src/pr-intake-mode.ts +59 -0
- package/src/pr-intake-review.ts +397 -0
- package/src/pr-intake-tree.ts +69 -0
- package/src/pr-intake-work.ts +29 -0
- package/src/pr-watch.ts +91 -32
- package/src/runtime.ts +2702 -391
- package/src/setup-judge.ts +1 -1
- package/src/setup.ts +12 -16
- package/src/store.ts +429 -86
- package/src/topic-history.ts +243 -47
- package/src/worker-checkout.ts +106 -0
- package/src/worker-destination.ts +10 -0
- package/src/worker-doctor.ts +66 -0
- package/src/worker-enrollment.ts +165 -0
- package/src/worker-host.ts +180 -0
- package/src/worker-ledger.ts +188 -0
- package/src/worker-placement.ts +78 -0
- package/src/worker-profile.ts +274 -0
- package/src/worker-registration.ts +288 -0
- package/src/worker-repository.ts +233 -0
- package/src/worker-request.ts +74 -0
- package/src/worker-service.ts +230 -0
- package/src/worker-stdio.ts +61 -0
- package/src/worker-trust.ts +36 -0
- package/src/worker-wire.ts +204 -0
- package/src/workflow.ts +81 -32
- package/src/setup-memory.ts +0 -21
package/src/installed-omp.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { realpathSync } from "node:fs";
|
|
2
|
-
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
1
|
+
import { closeSync, constants, fstatSync, openSync, readSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
|
|
5
5
|
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
@@ -27,14 +27,126 @@ export function resolveOmpCommand(command: string[], path = process.env.PATH ??
|
|
|
27
27
|
return [executable, ...args];
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
type InstalledOmp = Awaited<ReturnType<typeof probeInstalledOmp>>;
|
|
31
|
+
const inspected = new Map<string, { identity: string; result: Promise<InstalledOmp> }>();
|
|
32
|
+
const EXECUTION_ENV_KEYS = [
|
|
33
|
+
"PATH",
|
|
34
|
+
"LD_LIBRARY_PATH",
|
|
35
|
+
"LD_PRELOAD",
|
|
36
|
+
"DYLD_LIBRARY_PATH",
|
|
37
|
+
"DYLD_FALLBACK_LIBRARY_PATH",
|
|
38
|
+
"DYLD_INSERT_LIBRARIES",
|
|
39
|
+
] as const;
|
|
40
|
+
|
|
41
|
+
function fileIdentity(filePath: string): [string, ...string[]] {
|
|
42
|
+
const target = realpathSync(filePath);
|
|
43
|
+
const { dev, ino, size, mtimeNs, ctimeNs } = statSync(target, { bigint: true });
|
|
44
|
+
return [target, dev.toString(), ino.toString(), size.toString(), mtimeNs.toString(), ctimeNs.toString()];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function readShebangTokens(filePath: string): string[] | null {
|
|
48
|
+
const fd = openSync(filePath, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
49
|
+
try {
|
|
50
|
+
if (!fstatSync(fd).isFile()) throw new Error("OMP executable must be a regular file");
|
|
51
|
+
const buffer = Buffer.allocUnsafe(256);
|
|
52
|
+
const bytes = readSync(fd, buffer, 0, buffer.length, 0);
|
|
53
|
+
if (bytes < 2 || buffer[0] !== 0x23 || buffer[1] !== 0x21) return null;
|
|
54
|
+
const line = buffer.subarray(2, bytes).toString("utf8");
|
|
55
|
+
const newline = line.indexOf("\n");
|
|
56
|
+
if (newline < 0 && bytes === buffer.length) return [];
|
|
57
|
+
const trimmed = (newline >= 0 ? line.slice(0, newline) : line).replace(/\r$/, "").trim();
|
|
58
|
+
return trimmed ? trimmed.split(/[ \t]+/) : [];
|
|
59
|
+
} finally {
|
|
60
|
+
closeSync(fd);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function resolveEnvCommand(tokens: readonly string[], path: string): string | null {
|
|
65
|
+
// Only cache forms whose interpreter search uses the provided PATH
|
|
66
|
+
// unchanged. env options, assignments, quoting and substitutions can
|
|
67
|
+
// change the interpreter; use the uncached real probe for those forms.
|
|
68
|
+
const target = tokens[1] === "-S" ? tokens[2] : tokens.length === 2 ? tokens[1] : undefined;
|
|
69
|
+
if (!target || target.startsWith("-") || !/^[\w./+-]+$/.test(target)) return null;
|
|
70
|
+
if (isAbsolute(target) || target.includes("/")) return resolve(target);
|
|
71
|
+
return Bun.which(target, { PATH: path });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The kernel-executed file plus its shebang interpreter and loader environment:
|
|
76
|
+
* replacing, rewriting or retargeting the binary/script, or changing PATH/LD_*
|
|
77
|
+
* changes this identity. Returns null when a required shebang target is missing.
|
|
78
|
+
*/
|
|
79
|
+
function executionIdentity(
|
|
80
|
+
executable: string, path: string, credentials: readonly string[], environment: NodeJS.ProcessEnv,
|
|
81
|
+
): string | null {
|
|
82
|
+
const files: [string, ...string[]][] = [];
|
|
83
|
+
const seen = new Set<string>();
|
|
84
|
+
let current: string | null = executable;
|
|
85
|
+
for (let depth = 0; current; depth++) {
|
|
86
|
+
if (depth === 4) return null;
|
|
87
|
+
const id = fileIdentity(current);
|
|
88
|
+
if (seen.has(id[0])) return null;
|
|
89
|
+
seen.add(id[0]);
|
|
90
|
+
files.push(id);
|
|
91
|
+
const tokens = readShebangTokens(id[0]);
|
|
92
|
+
if (!tokens) break;
|
|
93
|
+
const interpreter = tokens[0];
|
|
94
|
+
if (!interpreter) return null;
|
|
95
|
+
const resolvedInterp = isAbsolute(interpreter) || interpreter.includes("/")
|
|
96
|
+
? resolve(interpreter)
|
|
97
|
+
: Bun.which(interpreter, { PATH: path });
|
|
98
|
+
if (!resolvedInterp) return null;
|
|
99
|
+
if (basename(interpreter) === "env") {
|
|
100
|
+
files.push(fileIdentity(resolvedInterp));
|
|
101
|
+
const target = resolveEnvCommand(tokens, path);
|
|
102
|
+
if (!target) return null;
|
|
103
|
+
current = target;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
current = resolvedInterp;
|
|
107
|
+
}
|
|
108
|
+
const env = EXECUTION_ENV_KEYS.map(name => credentials.includes(name) ? null : environment[name] ?? null);
|
|
109
|
+
return JSON.stringify({ files, env });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Inspect CLI metadata only; never open an agent or provider session.
|
|
114
|
+
* Results are reused in this process while the configured executable's file
|
|
115
|
+
* identity, shebang interpreter, and execution environment are unchanged, so
|
|
116
|
+
* repeated Host starts do not respawn the probes.
|
|
117
|
+
*/
|
|
31
118
|
export async function inspectInstalledOmp(
|
|
32
119
|
command: string[], credentials: string[] = [], environment: NodeJS.ProcessEnv = process.env,
|
|
33
|
-
) {
|
|
120
|
+
): Promise<InstalledOmp> {
|
|
34
121
|
const path = environment.PATH ?? "";
|
|
35
122
|
const [entry] = resolveOmpCommand(command, path);
|
|
36
123
|
const executable = entry && (isAbsolute(entry) ? entry : Bun.which(entry, { PATH: path }));
|
|
37
124
|
if (!executable) throw new Error(`Cannot find the configured OMP executable ${entry ?? ""} on PATH`);
|
|
125
|
+
let identity: string | null;
|
|
126
|
+
try { identity = executionIdentity(executable, path, credentials, environment); }
|
|
127
|
+
catch { return probeInstalledOmp(executable, credentials, environment); }
|
|
128
|
+
if (identity === null) return probeInstalledOmp(executable, credentials, environment);
|
|
129
|
+
const cached = inspected.get(executable);
|
|
130
|
+
if (cached?.identity === identity) return cached.result;
|
|
131
|
+
const result = probeInstalledOmp(executable, credentials, environment);
|
|
132
|
+
inspected.set(executable, { identity, result });
|
|
133
|
+
const forget = () => { if (inspected.get(executable)?.result === result) inspected.delete(executable); };
|
|
134
|
+
try {
|
|
135
|
+
const value = await result;
|
|
136
|
+
// A file replaced while it was probed may not be the one that answered.
|
|
137
|
+
let unchanged = false;
|
|
138
|
+
try { unchanged = executionIdentity(executable, path, credentials, environment) === identity; } catch {}
|
|
139
|
+
if (!unchanged) forget();
|
|
140
|
+
return value;
|
|
141
|
+
} catch (error) {
|
|
142
|
+
forget();
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function probeInstalledOmp(
|
|
148
|
+
executable: string, credentials: string[], environment: NodeJS.ProcessEnv,
|
|
149
|
+
) {
|
|
38
150
|
const env = { ...environment };
|
|
39
151
|
for (const name of credentials) delete env[name];
|
|
40
152
|
const probe = async (...args: string[]) => {
|
package/src/lane-rows.ts
CHANGED
|
@@ -1,12 +1,52 @@
|
|
|
1
1
|
import type { Database } from "bun:sqlite";
|
|
2
|
+
import { isAbsolute, normalize } from "node:path";
|
|
3
|
+
import { Type } from "@sinclair/typebox";
|
|
4
|
+
import { Value } from "@sinclair/typebox/value";
|
|
2
5
|
import type { Lane } from "./contracts";
|
|
6
|
+
import type { RemotePlacement } from "./worker-wire";
|
|
3
7
|
|
|
4
|
-
export
|
|
5
|
-
|
|
6
|
-
|
|
8
|
+
export interface LaneRow {
|
|
9
|
+
readonly data: string;
|
|
10
|
+
/** Missing only when opening a pre-migration ledger read-only. */
|
|
11
|
+
readonly remote?: string | null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const remoteSchema = Type.Object({
|
|
15
|
+
workerId: Type.String({ pattern: "^[A-Za-z0-9_-]{1,128}$" }),
|
|
16
|
+
repoId: Type.String({ pattern: "^[a-f0-9]{64}$" }),
|
|
17
|
+
revision: Type.String({ pattern: "^(?:[a-f0-9]{40}|[a-f0-9]{64})$" }),
|
|
18
|
+
subdir: Type.String({ maxLength: 2048 }),
|
|
19
|
+
stateDir: Type.String(),
|
|
20
|
+
}, { additionalProperties: false });
|
|
21
|
+
|
|
22
|
+
function parseRemote(json: string): RemotePlacement {
|
|
23
|
+
const parsed: unknown = JSON.parse(json);
|
|
24
|
+
if (!Value.Check(remoteSchema, parsed)
|
|
25
|
+
|| !isAbsolute(parsed.stateDir) || normalize(parsed.stateDir) !== parsed.stateDir || /[\r\n\0]/.test(parsed.stateDir)
|
|
26
|
+
|| /[\\\u0000-\u001f\u007f]/.test(parsed.subdir)
|
|
27
|
+
|| (parsed.subdir && parsed.subdir.split("/").some(part => !part || part === "." || part === ".." || part.toLowerCase() === ".git"))) {
|
|
28
|
+
throw new Error("Invalid durable remote lane placement");
|
|
29
|
+
}
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Placement is a separate immutable SQLite field; state-only updates do not rewrite it. */
|
|
34
|
+
export function laneData({ remote: _placement, ...lane }: Lane): string {
|
|
35
|
+
return JSON.stringify(lane);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function toLane(row: LaneRow): Lane {
|
|
39
|
+
const { remote: _placement, ...lane } = JSON.parse(row.data) as Lane;
|
|
40
|
+
return { ...lane, ...(row.remote == null ? {} : { remote: parseRemote(row.remote) }),
|
|
41
|
+
model: lane.model ?? null, modelReason: lane.modelReason ?? null,
|
|
7
42
|
modelPreset: lane.modelPreset ?? null, modelPresetSnapshot: lane.modelPresetSnapshot ?? null };
|
|
8
43
|
}
|
|
9
44
|
|
|
10
45
|
export function readLaneRows(db: Database): Lane[] {
|
|
11
|
-
|
|
46
|
+
// Status can read a legacy ledger before any process opens the writer.
|
|
47
|
+
return db.query<LaneRow, []>("SELECT * FROM lanes ORDER BY rowid").all().map(toLane);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function lanePlacement(lane: Lane) {
|
|
51
|
+
return lane.remote ? { target: "remote" as const, ...lane.remote } : { target: "local" as const };
|
|
12
52
|
}
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
// allow: SIZE_OK — the cursor, notice, and redacted readback use one versioned watch ledger.
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { Type, type Static } from "@sinclair/typebox/type";
|
|
4
|
+
import { Value } from "@sinclair/typebox/value";
|
|
5
|
+
import { authorizeRoute, type Config } from "./config";
|
|
6
|
+
import { routeKey, type InputRecord, type Lane, type OutputRecord, type Route, type StorePort } from "./contracts";
|
|
7
|
+
|
|
8
|
+
const stateKey = "lane-watch:v1";
|
|
9
|
+
const noticePrefix = "lane-watch-notice:";
|
|
10
|
+
const outputSuffix = ":notice";
|
|
11
|
+
const stopKey = "head:stop-boundary";
|
|
12
|
+
const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
13
|
+
const laneIdSchema = Type.String({ pattern: "^[a-zA-Z0-9_-]{1,128}$" });
|
|
14
|
+
const commandSchema = Type.Object({
|
|
15
|
+
action: Type.Union([Type.Literal("track"), Type.Literal("status"), Type.Literal("untrack")]),
|
|
16
|
+
sourceId: Type.String({ minLength: 1 }),
|
|
17
|
+
laneId: Type.Optional(laneIdSchema),
|
|
18
|
+
}, { additionalProperties: false });
|
|
19
|
+
export type LaneWatchCommand = Static<typeof commandSchema>;
|
|
20
|
+
|
|
21
|
+
const nullableString = Type.Union([Type.String(), Type.Null()]);
|
|
22
|
+
const blocked = Type.Union([Type.Literal("execution-uncertain"), Type.Literal("runtime-interrupted"), Type.Literal("kickoff-held")]);
|
|
23
|
+
const eventText = {
|
|
24
|
+
progress: "New structured progress evidence was recorded. This is not verified acceptance.",
|
|
25
|
+
waiting: "A matching native admission reported a wait. The underlying dependency's state is not independently verified.",
|
|
26
|
+
completed: "The lane was recorded as completed by explicit closure.",
|
|
27
|
+
failed: "A matching native execution reported an error. The lane was not marked complete; external effects may still be uncertain.",
|
|
28
|
+
paused: "The lane is recorded as paused. This does not confirm its processes or services stopped.",
|
|
29
|
+
reopened: "The lane was reopened. No execution or successful resume is implied.",
|
|
30
|
+
cancelled: "The lane was recorded as cancelled.",
|
|
31
|
+
"execution-uncertain": "Work is stalled by a submitted request with an uncertain outcome. No work was replayed.",
|
|
32
|
+
"runtime-interrupted": "Work is stalled because the runtime is recorded as interrupted. Native ownership or execution may be unresolved.",
|
|
33
|
+
"kickoff-held": "Work is stalled because kickoff delivery is missing, failed or uncertain.",
|
|
34
|
+
} as const;
|
|
35
|
+
const eventKind = Type.Union([
|
|
36
|
+
Type.Literal("progress"), Type.Literal("waiting"), Type.Literal("completed"), Type.Literal("failed"),
|
|
37
|
+
Type.Literal("paused"), Type.Literal("reopened"), Type.Literal("cancelled"), blocked,
|
|
38
|
+
]);
|
|
39
|
+
const snapshot = Type.Object({
|
|
40
|
+
workState: Type.Union([Type.Literal("open"), Type.Literal("paused"), Type.Literal("completed"), Type.Literal("cancelled")]),
|
|
41
|
+
runtimeState: Type.Union([Type.Literal("unloaded"), Type.Literal("starting"), Type.Literal("running"), Type.Literal("idle"), Type.Literal("interrupted")]),
|
|
42
|
+
evidence: nullableString, waiting: nullableString, failure: nullableString,
|
|
43
|
+
block: Type.Union([Type.Object({ kind: blocked, key: Type.String() }), Type.Null()]),
|
|
44
|
+
});
|
|
45
|
+
const held = Type.Union([Type.Literal("untracked"), Type.Literal("head-stopped"), Type.Literal("source-unavailable"), Type.Literal("target-unavailable"), Type.Null()]);
|
|
46
|
+
const view = Type.Object({
|
|
47
|
+
laneId: laneIdSchema, sourceId: Type.String(), tracking: Type.Boolean(), held,
|
|
48
|
+
workState: Type.Union([snapshot.properties.workState, Type.Null()]),
|
|
49
|
+
runtimeState: Type.Union([snapshot.properties.runtimeState, Type.Null()]),
|
|
50
|
+
blocked: Type.Union([blocked, Type.Null()]), events: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
|
|
51
|
+
lastEvents: Type.Union([Type.Array(eventKind), Type.Null()]),
|
|
52
|
+
});
|
|
53
|
+
const watchSchema = Type.Object({
|
|
54
|
+
laneId: laneIdSchema, sourceId: Type.String(), routeKey: Type.String(), targetRouteKey: Type.String(),
|
|
55
|
+
epoch: Type.String(), enabled: Type.Boolean(), stopBoundary: nullableString, snapshot,
|
|
56
|
+
targetRejected: Type.Optional(Type.Literal(true)),
|
|
57
|
+
events: Type.Integer({ minimum: 0 }), lastEvents: Type.Array(eventKind),
|
|
58
|
+
});
|
|
59
|
+
const stateSchema = Type.Object({ watches: Type.Array(watchSchema), receipts: Type.Record(Type.String(), Type.Union([view, Type.Null()])) });
|
|
60
|
+
const noticeSchema = Type.Object({ epoch: Type.String(), sourceId: Type.String(), events: Type.Array(eventKind, { minItems: 1 }) });
|
|
61
|
+
const failureSchema = Type.Object({ id: Type.String(), requestId: Type.String(), generation: Type.Integer({ minimum: 0 }) });
|
|
62
|
+
type Snapshot = Static<typeof snapshot>;
|
|
63
|
+
type EventKind = Static<typeof eventKind>;
|
|
64
|
+
type Watch = Static<typeof watchSchema>;
|
|
65
|
+
type State = Static<typeof stateSchema>;
|
|
66
|
+
type View = Static<typeof view>;
|
|
67
|
+
type ObservationScope = { readonly source: InputRecord; readonly lane: Lane };
|
|
68
|
+
type CrossPlatformProof = {
|
|
69
|
+
readonly open: () => boolean;
|
|
70
|
+
readonly check: (source: Route, target: Route) => Promise<boolean>;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
class LaneWatchError extends Error {}
|
|
74
|
+
|
|
75
|
+
export function isLaneWatchNotice(id: string): boolean {
|
|
76
|
+
return id.startsWith(noticePrefix);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function readNotice(store: Pick<StorePort, "getMeta">, id: string) {
|
|
80
|
+
const raw = store.getMeta(id);
|
|
81
|
+
if (raw === null) return null;
|
|
82
|
+
const value: unknown = JSON.parse(raw);
|
|
83
|
+
if (!Value.Check(noticeSchema, value)) throw new LaneWatchError("Damaged lane watch notice");
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Reply provenance only. Never use this as input ownership or action authority. */
|
|
88
|
+
export function laneWatchReplySource(store: Pick<StorePort, "input" | "getMeta">,
|
|
89
|
+
input: InputRecord | null, outputId: string): InputRecord | null {
|
|
90
|
+
if (!input || !isLaneWatchNotice(input.id) || input.target !== "main" || outputId !== `${input.id}${outputSuffix}`
|
|
91
|
+
|| store.getMeta(`user-source:${input.id}`) === "true") return null;
|
|
92
|
+
const notice = readNotice(store, input.id);
|
|
93
|
+
const original = notice && store.input(notice.sourceId);
|
|
94
|
+
if (!original || isLaneWatchNotice(original.id) || store.getMeta(`user-source:${original.id}`) !== "true"
|
|
95
|
+
|| original.state === "cancelled" || original.state === "uncertain" || routeKey(original.route) !== routeKey(input.route)
|
|
96
|
+
|| original.messageId !== input.messageId || original.interactionId !== input.interactionId
|
|
97
|
+
|| original.invocationId !== input.invocationId) return null;
|
|
98
|
+
return original;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function changes(before: Snapshot, after: Snapshot): EventKind[] {
|
|
102
|
+
const events: EventKind[] = [];
|
|
103
|
+
if (before.workState !== after.workState) {
|
|
104
|
+
events.push(after.workState === "open" ? "reopened" : after.workState);
|
|
105
|
+
}
|
|
106
|
+
if (after.failure && before.failure !== after.failure) events.push("failed");
|
|
107
|
+
if (after.workState === "open") {
|
|
108
|
+
if (after.evidence && before.evidence !== after.evidence) events.push("progress");
|
|
109
|
+
if (after.waiting && before.waiting !== after.waiting) events.push("waiting");
|
|
110
|
+
if (after.block && before.block?.key !== after.block.key) events.push(after.block.kind);
|
|
111
|
+
}
|
|
112
|
+
return events;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Observe the coordination ledger without connecting to Hosts, changing lane queues, or reading transcripts. */
|
|
116
|
+
export class LaneWatcher {
|
|
117
|
+
constructor(private readonly store: StorePort, private readonly config: Config) {}
|
|
118
|
+
|
|
119
|
+
change(command: LaneWatchCommand): View | readonly View[] | null {
|
|
120
|
+
if (!Value.Check(commandSchema, command)) throw new LaneWatchError("Invalid lane watch command");
|
|
121
|
+
const source = this.source(command.sourceId);
|
|
122
|
+
if (!source) throw new LaneWatchError("Lane watch requires an original authorized owner source");
|
|
123
|
+
const scope = routeKey(source.route);
|
|
124
|
+
const state = this.state();
|
|
125
|
+
const visible = state.watches.filter(watch => watch.routeKey === scope
|
|
126
|
+
&& (command.laneId === undefined || watch.laneId === command.laneId));
|
|
127
|
+
if (command.action === "status") {
|
|
128
|
+
return command.laneId ? (visible[0] ? this.view(visible[0]) : null) : visible.map(watch => this.view(watch));
|
|
129
|
+
}
|
|
130
|
+
if (!command.laneId) throw new LaneWatchError("Track and untrack require a managed laneId");
|
|
131
|
+
const receipt = JSON.stringify([source.id, command.action, command.laneId]);
|
|
132
|
+
const previous = visible[0];
|
|
133
|
+
const previousHold = previous && this.held(previous);
|
|
134
|
+
if (Object.hasOwn(state.receipts, receipt)) {
|
|
135
|
+
const saved = state.receipts[receipt];
|
|
136
|
+
if (previous && previousHold === "target-unavailable") return this.view(previous);
|
|
137
|
+
return saved && command.action === "untrack" ? this.redact(saved) : saved ?? null;
|
|
138
|
+
}
|
|
139
|
+
let watch: Watch | undefined;
|
|
140
|
+
if (command.action === "track") {
|
|
141
|
+
const lane = this.store.lane(command.laneId);
|
|
142
|
+
if (!lane || !this.targetAllowed(source.route, lane.route)) throw new LaneWatchError("Lane watch requires an authorized managed lane");
|
|
143
|
+
watch = previous && previousHold === null ? previous : {
|
|
144
|
+
laneId: lane.id, sourceId: source.id, routeKey: scope, targetRouteKey: routeKey(lane.route),
|
|
145
|
+
epoch: randomUUID(), enabled: true, stopBoundary: this.store.getMeta(stopKey), snapshot: this.snapshot(lane),
|
|
146
|
+
events: previousHold === "target-unavailable" ? 0 : previous?.events ?? 0,
|
|
147
|
+
lastEvents: previousHold === "target-unavailable" ? [] : previous?.lastEvents ?? [],
|
|
148
|
+
};
|
|
149
|
+
} else if (previous) {
|
|
150
|
+
watch = { ...previous, enabled: false };
|
|
151
|
+
}
|
|
152
|
+
const result = watch ? this.view(watch) : null;
|
|
153
|
+
this.save({
|
|
154
|
+
watches: [...state.watches.filter(item => item !== previous), ...(watch ? [watch] : [])],
|
|
155
|
+
receipts: { ...state.receipts, [receipt]: result },
|
|
156
|
+
});
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
recordFailure(input: InputRecord): void {
|
|
161
|
+
if (!input.target || input.target === "main" || input.state !== "submitted" || !input.requestId || input.generation === null) return;
|
|
162
|
+
this.store.setMeta(`lane-watch-failure:${input.target}`, JSON.stringify({
|
|
163
|
+
id: input.id, requestId: input.requestId, generation: input.generation,
|
|
164
|
+
}));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
poll(now: number): void {
|
|
168
|
+
for (const watch of this.state().watches) {
|
|
169
|
+
const scope = this.scope(watch);
|
|
170
|
+
if (scope && scope.source.route.platform === scope.lane.route.platform) this.advance(watch.epoch, now);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Cross-platform accounts must be authenticated before the durable cursor advances. */
|
|
175
|
+
async pollCrossPlatform(now: number, proof: CrossPlatformProof): Promise<boolean> {
|
|
176
|
+
let notified = false;
|
|
177
|
+
for (const watch of this.state().watches) {
|
|
178
|
+
if (!proof.open()) break;
|
|
179
|
+
const scope = this.scope(watch);
|
|
180
|
+
if (!scope || scope.source.route.platform === scope.lane.route.platform
|
|
181
|
+
|| JSON.stringify(this.snapshot(scope.lane)) === JSON.stringify(watch.snapshot)) continue;
|
|
182
|
+
let allowed: boolean;
|
|
183
|
+
try { allowed = await proof.check(scope.source.route, scope.lane.route); }
|
|
184
|
+
catch (error) {
|
|
185
|
+
if (error instanceof Error) continue; // No trustworthy proof: leave the cursor untouched.
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
if (!proof.open()) break;
|
|
189
|
+
if (!allowed) this.holdRejectedTarget(watch.sourceId, watch.laneId);
|
|
190
|
+
else notified = this.advance(watch.epoch, now) || notified;
|
|
191
|
+
}
|
|
192
|
+
return notified;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private advance(epoch: string, now: number): boolean {
|
|
196
|
+
const state = this.state();
|
|
197
|
+
const watch = state.watches.find(item => item.epoch === epoch);
|
|
198
|
+
const scope = watch && this.scope(watch);
|
|
199
|
+
if (!watch || !scope) return false;
|
|
200
|
+
const { source, lane } = scope;
|
|
201
|
+
const snapshot = this.snapshot(lane);
|
|
202
|
+
if (JSON.stringify(snapshot) === JSON.stringify(watch.snapshot)) return false;
|
|
203
|
+
const events = changes(watch.snapshot, snapshot);
|
|
204
|
+
const next = { ...watch, snapshot, events: watch.events + Number(events.length > 0),
|
|
205
|
+
lastEvents: events.length ? events : watch.lastEvents };
|
|
206
|
+
const updated = { ...state, watches: state.watches.map(item => item.epoch === epoch ? next : item) };
|
|
207
|
+
if (!events.length) { this.save(updated); return false; }
|
|
208
|
+
const id = `${noticePrefix}${watch.epoch}:${next.events}`;
|
|
209
|
+
// Advance the baseline in the same transaction as durable HEAD intake.
|
|
210
|
+
return this.store.receive({ id, route: source.route, messageId: source.messageId, attachments: [], receivedAt: now,
|
|
211
|
+
...(source.interactionId !== undefined ? { interactionId: source.interactionId } : {}),
|
|
212
|
+
...(source.invocationId !== undefined ? { invocationId: source.invocationId } : {}),
|
|
213
|
+
text: this.noticeText(watch, events) }, "main", {
|
|
214
|
+
[id]: JSON.stringify({ epoch, sourceId: source.id, events }), [stateKey]: JSON.stringify(updated),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Settle only HEAD's informational receipt; no prompt, tool, or lane command is submitted. */
|
|
219
|
+
consume(input: InputRecord): void {
|
|
220
|
+
if (this.store.input(input.id)?.state !== "pending") return;
|
|
221
|
+
const notice = this.notice(input);
|
|
222
|
+
if (!notice) { this.store.settle(input.id, "cancelled"); return; }
|
|
223
|
+
this.store.settle(input.id, "done", { id: `${input.id}${outputSuffix}`, text: this.noticeText(notice.watch, notice.events) });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
deliveryScope(output: OutputRecord) {
|
|
227
|
+
if (!isLaneWatchNotice(output.sourceId) || output.id !== `${output.sourceId}${outputSuffix}`) return null;
|
|
228
|
+
const input = this.store.input(output.sourceId);
|
|
229
|
+
const notice = input?.state === "done" ? this.notice(input) : null;
|
|
230
|
+
const target = notice && this.store.lane(notice.watch.laneId);
|
|
231
|
+
return notice && target && routeKey(notice.source.route) === routeKey(output.route)
|
|
232
|
+
? { source: notice.source, target } : null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
holdRejectedTarget(sourceId: string, laneId: string): void {
|
|
236
|
+
const state = this.state();
|
|
237
|
+
const watch = state.watches.find(item => item.sourceId === sourceId && item.laneId === laneId);
|
|
238
|
+
if (watch && !watch.targetRejected) {
|
|
239
|
+
this.save({ ...state, watches: state.watches.map(item => item === watch ? { ...item, targetRejected: true } : item) });
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
private notice(input: InputRecord) {
|
|
244
|
+
if (!isLaneWatchNotice(input.id) || input.target !== "main" || this.store.getMeta(`user-source:${input.id}`) === "true") return null;
|
|
245
|
+
const notice = readNotice(this.store, input.id);
|
|
246
|
+
if (!notice) return null;
|
|
247
|
+
const watch = this.state().watches.find(item => item.epoch === notice.epoch);
|
|
248
|
+
const source = watch && this.source(watch.sourceId);
|
|
249
|
+
return watch && source && source.id === notice.sourceId && watch.routeKey === routeKey(input.route) && this.held(watch) === null
|
|
250
|
+
? { watch, source, events: notice.events } : null;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private noticeText(watch: Watch, events: readonly EventKind[]): string {
|
|
254
|
+
return [`Lane ${watch.laneId} observation:`, ...events.map(event => eventText[event])].join("\n");
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private snapshot(lane: Lane): Snapshot {
|
|
258
|
+
const observation = lane.observation;
|
|
259
|
+
const owner = observation && this.store.input(observation.inputId);
|
|
260
|
+
const observed = owner?.target === lane.id && owner.requestId === observation?.requestId
|
|
261
|
+
&& owner.generation === lane.generation && observation?.generation === lane.generation
|
|
262
|
+
&& observation.sessionId === lane.sessionId ? observation : null;
|
|
263
|
+
const evidence = observed?.lastEvidence;
|
|
264
|
+
const waiting = owner?.state === "submitted" ? observed?.waiting : null;
|
|
265
|
+
const rawFailure = this.store.getMeta(`lane-watch-failure:${lane.id}`);
|
|
266
|
+
const failure: unknown = rawFailure === null ? null : JSON.parse(rawFailure);
|
|
267
|
+
let failureKey: string | null = null;
|
|
268
|
+
if (Value.Check(failureSchema, failure)) {
|
|
269
|
+
const failed = this.store.input(failure.id);
|
|
270
|
+
if (failed?.target === lane.id && failed.requestId === failure.requestId && failed.generation === failure.generation
|
|
271
|
+
&& (failed.state === "uncertain" || failed.state === "cancelled")) failureKey = digest(failure);
|
|
272
|
+
}
|
|
273
|
+
const uncertain = lane.workState === "open" ? this.store.inputs(lane.id, "uncertain")[0] : undefined;
|
|
274
|
+
const kickoff = lane.workState === "open" ? this.store.kickoffHold(lane.id) : null;
|
|
275
|
+
let block: Snapshot["block"] = null;
|
|
276
|
+
if (uncertain) block = { kind: "execution-uncertain", key: digest(["execution-uncertain", uncertain.id]) };
|
|
277
|
+
else if (lane.workState === "open" && lane.runtimeState === "interrupted")
|
|
278
|
+
block = { kind: "runtime-interrupted", key: digest(["runtime-interrupted", lane.generation]) };
|
|
279
|
+
else if (kickoff && (kickoff.state === "failed" || kickoff.state === "uncertain" || kickoff.state === "missing"))
|
|
280
|
+
block = { kind: "kickoff-held", key: digest(["kickoff-held", kickoff.outputId, kickoff.state]) };
|
|
281
|
+
return {
|
|
282
|
+
workState: lane.workState, runtimeState: lane.runtimeState, block,
|
|
283
|
+
evidence: evidence ? digest([observed?.requestId, evidence.at, evidence.kind, evidence.fingerprint]) : null,
|
|
284
|
+
waiting: waiting ? digest([observed?.requestId, waiting.since, waiting.target]) : null,
|
|
285
|
+
failure: failureKey,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private source(id: string): InputRecord | null {
|
|
290
|
+
const source = this.store.input(id);
|
|
291
|
+
return source && !isLaneWatchNotice(id) && source.state !== "cancelled" && source.state !== "uncertain"
|
|
292
|
+
&& this.store.getMeta(`user-source:${id}`) === "true" && authorizeRoute(this.config, source.route) ? source : null;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
private targetAllowed(source: Route, target: Route): boolean {
|
|
296
|
+
return authorizeRoute(this.config, target) && (source.platform !== target.platform || source.accountId === target.accountId);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private scope(watch: Watch): ObservationScope | null {
|
|
300
|
+
if (this.held(watch) !== null) return null;
|
|
301
|
+
const source = this.source(watch.sourceId);
|
|
302
|
+
const lane = this.store.lane(watch.laneId);
|
|
303
|
+
return source && lane ? { source, lane } : null;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private held(watch: Watch): View["held"] {
|
|
307
|
+
if (watch.targetRejected) return "target-unavailable";
|
|
308
|
+
const lane = this.store.lane(watch.laneId);
|
|
309
|
+
if (!lane || routeKey(lane.route) !== watch.targetRouteKey || !authorizeRoute(this.config, lane.route)) return "target-unavailable";
|
|
310
|
+
if (!watch.enabled) return "untracked";
|
|
311
|
+
if (watch.stopBoundary !== this.store.getMeta(stopKey)) return "head-stopped";
|
|
312
|
+
const source = this.source(watch.sourceId);
|
|
313
|
+
if (!source || routeKey(source.route) !== watch.routeKey) return "source-unavailable";
|
|
314
|
+
if (!this.targetAllowed(source.route, lane.route)) return "target-unavailable";
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
private view(watch: Watch): View {
|
|
319
|
+
const held = this.held(watch);
|
|
320
|
+
const view = { laneId: watch.laneId, sourceId: watch.sourceId, tracking: held === null, held,
|
|
321
|
+
workState: watch.snapshot.workState, runtimeState: watch.snapshot.runtimeState, blocked: watch.snapshot.block?.kind ?? null,
|
|
322
|
+
events: watch.events, lastEvents: watch.lastEvents };
|
|
323
|
+
return held === "untracked" || held === "source-unavailable" || held === "target-unavailable" ? this.redact(view) : view;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
private redact(view: View): View {
|
|
327
|
+
return { ...view, workState: null, runtimeState: null, blocked: null, events: null, lastEvents: null };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private state(): State {
|
|
331
|
+
const raw = this.store.getMeta(stateKey);
|
|
332
|
+
if (raw === null) return { watches: [], receipts: {} };
|
|
333
|
+
const value: unknown = JSON.parse(raw);
|
|
334
|
+
if (!Value.Check(stateSchema, value)) throw new LaneWatchError("Damaged lane watch state");
|
|
335
|
+
return value;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
private save(state: State): void { this.store.setMeta(stateKey, JSON.stringify(state)); }
|
|
339
|
+
}
|
|
@@ -1,22 +1,25 @@
|
|
|
1
1
|
// Configuration only. Never import the SDK entry point, account storage, or a backend.
|
|
2
|
-
import {
|
|
2
|
+
import { canEnableGlobalMemory, effectiveManagedMemory, ensureManagedMemory, parseMemoryConsent, type ManagedMemoryReport } from "./managed-memory";
|
|
3
3
|
import { parseNativeLaunch } from "./native-launch-profile";
|
|
4
4
|
|
|
5
|
-
const unavailable:
|
|
6
|
-
|
|
5
|
+
const unavailable: ManagedMemoryReport = { memory: { status: "unknown" }, updated: false };
|
|
6
|
+
const [operation, ...args] = process.argv.slice(2);
|
|
7
|
+
async function check(): Promise<ManagedMemoryReport> {
|
|
7
8
|
const cwd = process.cwd();
|
|
8
|
-
|
|
9
|
-
if (operation !== "inspect" && operation !== "apply-consented") return unavailable;
|
|
9
|
+
if (operation !== "inspect" && operation !== "preflight" && operation !== "enabled" && operation !== "apply-consented") return unavailable;
|
|
10
10
|
const parsed = await parseNativeLaunch([...args, "--mode", "rpc-ui", "--cwd", cwd]);
|
|
11
11
|
if (parsed.mode !== "rpc-ui" || parsed.cwd !== cwd) return unavailable;
|
|
12
12
|
const { Settings } = await import("@oh-my-pi/pi-coding-agent/config/settings");
|
|
13
13
|
const settings = await Settings.loadReadOnly({ cwd, configFiles: parsed.config });
|
|
14
|
-
if (operation === "
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
return
|
|
14
|
+
if (operation === "apply-consented") {
|
|
15
|
+
return ensureManagedMemory(settings, parsed.launchAgentDir, parseMemoryConsent(await Bun.stdin.text()));
|
|
16
|
+
}
|
|
17
|
+
return { memory: await effectiveManagedMemory(settings, parsed.launchAgentDir), updated: false };
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
// Native parse/read diagnostics may include private settings. Emit only known fields.
|
|
21
21
|
const report = await check().catch(() => unavailable);
|
|
22
|
-
|
|
22
|
+
const output = operation === "preflight" || operation === "enabled"
|
|
23
|
+
? report.memory.status === "enabled" || (operation === "preflight" && canEnableGlobalMemory(report.memory))
|
|
24
|
+
: report;
|
|
25
|
+
process.stdout.write(`MANAGED_MEMORY ${JSON.stringify(output)}\n`);
|