omp-superagent 0.1.5 → 0.1.6
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 +62 -8
- package/README.ko.md +22 -14
- package/README.md +36 -22
- package/config.example.json +1 -0
- package/docs/OPERATIONS.md +180 -42
- package/docs/design/execution.md +20 -7
- package/docs/design/messaging.md +131 -11
- package/docs/releases/0.1.6.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 +1 -1
- package/skills/head/SKILL.md +7 -2
- package/skills/head/references/model-selection.md +4 -4
- package/skills/head/references/routing.md +9 -4
- package/skills/head/references/supervision.md +4 -3
- package/skills/lane/SKILL.md +19 -13
- package/skills/lane/references/workflow.md +19 -11
- package/src/board.ts +7 -2
- package/src/cli.ts +22 -6
- package/src/config.ts +26 -3
- package/src/contracts.ts +20 -2
- package/src/decision-tool.ts +1 -1
- package/src/extension.ts +40 -2
- package/src/gateway-client.ts +22 -1
- package/src/gateway-config.ts +4 -4
- package/src/gateway-restart-env.ts +7 -2
- package/src/gateway-wire.ts +8 -0
- package/src/group-access.ts +222 -0
- package/src/group-policy.ts +117 -0
- package/src/group-runner-extension.ts +153 -0
- package/src/group-runner.ts +284 -0
- package/src/head-rotation.ts +88 -0
- package/src/host-extension.ts +52 -3
- package/src/host-protocol.ts +1 -0
- package/src/host-sdk-helper.ts +7 -0
- package/src/host-superkit.ts +26 -0
- package/src/host.ts +5 -1
- package/src/lane-extension.ts +6 -3
- package/src/managed-memory-helper.ts +22 -0
- package/src/managed-memory.ts +100 -0
- package/src/managed-ulw.ts +16 -20
- package/src/messenger-command-catalog.json +3 -2
- package/src/native-launch-profile.ts +16 -0
- package/src/native-settings.ts +9 -3
- package/src/result-attachment.ts +211 -0
- package/src/runtime.ts +1109 -157
- package/src/setup-memory.ts +15 -33
- package/src/setup.ts +24 -22
- package/src/store.ts +214 -13
- package/src/topic-history.ts +430 -0
- package/src/topic-request.ts +88 -0
package/src/gateway-client.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import type { IncomingMessage } from "node:http";
|
|
2
2
|
import { Readable, Transform } from "node:stream";
|
|
3
3
|
import type { Config } from "./config";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
4
5
|
import type { Approval, Attachment, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "./contracts";
|
|
5
6
|
import { DeliveryError } from "./delivery";
|
|
6
7
|
import { gatewayCall, gatewayPaths, gatewayRequest, MAX_GATEWAY_ATTACHMENT, MAX_GATEWAY_FRAME, readGatewayJson, type GatewayResult } from "./gateway-protocol";
|
|
7
8
|
import type { GatewayReceipt, QueuedEvent } from "./gateway-wire";
|
|
9
|
+
import type { GroupReply } from "./group-policy";
|
|
8
10
|
|
|
9
11
|
export interface GatewayHeadMessenger extends Messenger {
|
|
10
12
|
assertRoute(route: Route): Promise<void>;
|
|
@@ -105,6 +107,10 @@ class GatewayMessenger implements GatewayHeadMessenger {
|
|
|
105
107
|
try {
|
|
106
108
|
const event = frame.event;
|
|
107
109
|
if (event.kind === "message") await this.handlers.message(event.input);
|
|
110
|
+
else if (event.kind === "group") {
|
|
111
|
+
if (!this.handlers.group) throw new DeliveryError("Restricted group ingress is not enabled", "rejected");
|
|
112
|
+
await this.handlers.group(event.request);
|
|
113
|
+
}
|
|
108
114
|
else if (event.kind === "answer") {
|
|
109
115
|
const reconciled = frame.reconciliation
|
|
110
116
|
? await this.handlers.reconcileAnswer?.(event.approvalId, event.route) ?? "unresolved" : "retry";
|
|
@@ -137,8 +143,23 @@ class GatewayMessenger implements GatewayHeadMessenger {
|
|
|
137
143
|
private effect<T>(operation: string, args: unknown[]): Promise<T> {
|
|
138
144
|
return this.call<T>("/effect", { id: crypto.randomUUID(), operation, args });
|
|
139
145
|
}
|
|
146
|
+
sendGroup(reply: GroupReply): Promise<string> {
|
|
147
|
+
const hash = createHash("sha256").update(JSON.stringify(["group-reply", reply.sourceId, reply.outcome])).digest("hex");
|
|
148
|
+
const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
|
|
149
|
+
return this.call<string>("/effect", { id, operation: "sendGroup", args: [reply] });
|
|
150
|
+
}
|
|
140
151
|
requestRestart(request: GatewayRestartRequest): Promise<GatewayRestartRecord> { return this.call("/restart", request); }
|
|
141
|
-
send(output: OutputRecord): Promise<string> {
|
|
152
|
+
send(output: OutputRecord): Promise<string> {
|
|
153
|
+
const { resultAttachment } = output;
|
|
154
|
+
if (!resultAttachment) return this.effect("send", [output]);
|
|
155
|
+
// Stable across client reattachment; the Gateway journals the one attempt.
|
|
156
|
+
const hash = createHash("sha256").update(JSON.stringify(["result-attachment", output.id])).digest("hex");
|
|
157
|
+
const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
|
|
158
|
+
// The adapter needs bytes and filename, not filesystem paths or native IDs.
|
|
159
|
+
return this.call<string>("/effect", { id, operation: "send", args: [{
|
|
160
|
+
id: output.id, route: output.route, text: output.text, replyTo: output.replyTo, resultAttachment: resultAttachment.payload,
|
|
161
|
+
}] });
|
|
162
|
+
}
|
|
142
163
|
assertRoute(route: Route): Promise<void> { return this.call("/route", { route }, AbortSignal.timeout(1000)); }
|
|
143
164
|
setActivity(message: MessageReference, activity: MessageActivity): Promise<void> {
|
|
144
165
|
return this.effect("setActivity", [{ route: message.route, messageId: message.messageId }, activity]);
|
package/src/gateway-config.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// One-shot parser shared with the operator CLI.
|
|
2
|
-
//
|
|
3
|
-
import {
|
|
1
|
+
// One-shot parser shared with the operator CLI. Return normalized config and
|
|
2
|
+
// its source digest; never load credential files, native OMP, or messenger SDKs.
|
|
3
|
+
import { loadConfigSnapshot } from "./config";
|
|
4
4
|
|
|
5
5
|
const [file, ...extra] = process.argv.slice(2);
|
|
6
6
|
if (!file || extra.length) throw new Error("Expected one Gateway config file");
|
|
7
|
-
process.stdout.write(JSON.stringify(await
|
|
7
|
+
process.stdout.write(JSON.stringify(await loadConfigSnapshot(file)));
|
|
@@ -1,17 +1,22 @@
|
|
|
1
1
|
// One shot, under the recorded restart-runner PID. Resolve FILE.env with the
|
|
2
2
|
// same private-file checks as `start`; never serialize tokens to argv or pipes.
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { loadConfigSnapshot, requireMessengerCredentials } from "./config";
|
|
5
5
|
import { loadCredentials } from "./credentials";
|
|
6
6
|
import { requireGateway } from "./gateway-native";
|
|
7
7
|
|
|
8
8
|
const [file, request, originalStateDir, ...extra] = process.argv.slice(2);
|
|
9
9
|
if (!file || !request || !originalStateDir || extra.length) throw new Error("Missing restart identity");
|
|
10
|
+
const expectedHash = process.env.OMP_SUPERAGENT_RUNNER_CONFIG_SHA256;
|
|
11
|
+
delete process.env.OMP_SUPERAGENT_RUNNER_CONFIG_SHA256;
|
|
10
12
|
const binary = await requireGateway();
|
|
11
13
|
let command = "__restart-rejected";
|
|
12
14
|
try {
|
|
13
|
-
const config = await
|
|
15
|
+
const { config, sourceHash } = await loadConfigSnapshot(file);
|
|
14
16
|
if (config.stateDir !== resolve(originalStateDir)) throw new Error("Restart state directory changed");
|
|
17
|
+
// Never load credential names from an intervening config revision into the
|
|
18
|
+
// runner (and therefore the eventual Gateway or native HEAD environment).
|
|
19
|
+
if (sourceHash !== expectedHash) throw new Error("Restart configuration changed");
|
|
15
20
|
loadCredentials(config);
|
|
16
21
|
requireMessengerCredentials(config);
|
|
17
22
|
command = "__restart-validated";
|
package/src/gateway-wire.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { DialogResponse, GatewayRestartNotice, GatewayRestartRecord, Inbound, Route } from "./contracts";
|
|
2
|
+
import type { HeadRotation } from "./head-rotation";
|
|
2
3
|
import type { ManagedUlwStatus } from "./managed-ulw";
|
|
4
|
+
import type { GroupRequest } from "./group-policy";
|
|
3
5
|
|
|
4
6
|
export type HeadInitialization = {
|
|
5
7
|
readonly sessionId: string;
|
|
@@ -23,9 +25,14 @@ export type GatewayStatus = {
|
|
|
23
25
|
readonly pid: number | null;
|
|
24
26
|
readonly ready: boolean;
|
|
25
27
|
readonly connected: boolean;
|
|
28
|
+
/** Verified by this Host's root session at startup, not the next-launch package. */
|
|
29
|
+
readonly loadedSuperkitPath?: string | null;
|
|
26
30
|
readonly socketPath: string;
|
|
27
31
|
readonly error: string | null;
|
|
28
32
|
readonly initialization?: HeadInitialization;
|
|
33
|
+
readonly rotation?: Pick<HeadRotation, "id" | "stage" | "replacementSessionId"> & {
|
|
34
|
+
readonly previousSessionId: string;
|
|
35
|
+
};
|
|
29
36
|
};
|
|
30
37
|
readonly ulw?: ManagedUlwStatus;
|
|
31
38
|
readonly restart?: Omit<GatewayRestartRecord, "sessionFile">;
|
|
@@ -33,6 +40,7 @@ export type GatewayStatus = {
|
|
|
33
40
|
|
|
34
41
|
export type GatewayEvent =
|
|
35
42
|
| { readonly kind: "message"; readonly input: Inbound }
|
|
43
|
+
| { readonly kind: "group"; readonly request: GroupRequest }
|
|
36
44
|
| { readonly kind: "answer"; readonly approvalId: string; readonly response: DialogResponse; readonly route: Route }
|
|
37
45
|
| ({ readonly kind: "restart" } & GatewayRestartNotice)
|
|
38
46
|
| { readonly kind: "reconnect"; readonly barrier?: string };
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
import { isDeepStrictEqual } from "node:util";
|
|
5
|
+
import { isConfiguredRoute, type Config } from "./config";
|
|
6
|
+
import type { Messenger } from "./contracts";
|
|
7
|
+
import { DeliveryError } from "./delivery";
|
|
8
|
+
import { groupRoom, groupRoomKey, type GroupReply, type GroupRequest } from "./group-policy";
|
|
9
|
+
|
|
10
|
+
const schema = `
|
|
11
|
+
CREATE TABLE IF NOT EXISTS group_requests (
|
|
12
|
+
sequence INTEGER PRIMARY KEY, id TEXT NOT NULL UNIQUE, room TEXT NOT NULL, day TEXT NOT NULL,
|
|
13
|
+
data TEXT NOT NULL, state TEXT NOT NULL
|
|
14
|
+
CHECK(state IN ('pending','running','received','finished','failed','interrupted','revoked','receipt_blocked')),
|
|
15
|
+
worktree TEXT
|
|
16
|
+
);
|
|
17
|
+
CREATE INDEX IF NOT EXISTS group_request_day ON group_requests(room,day);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS group_request_pending ON group_requests(sequence) WHERE state='pending';
|
|
19
|
+
CREATE TABLE IF NOT EXISTS group_responses (
|
|
20
|
+
sequence INTEGER PRIMARY KEY, id TEXT NOT NULL, outcome TEXT NOT NULL, text TEXT, remote_id TEXT,
|
|
21
|
+
state TEXT NOT NULL DEFAULT 'ready' CHECK(state IN ('ready','attempted','sent','failed','uncertain')),
|
|
22
|
+
UNIQUE(id,outcome)
|
|
23
|
+
);
|
|
24
|
+
CREATE INDEX IF NOT EXISTS group_response_ready ON group_responses(sequence) WHERE state='ready';
|
|
25
|
+
`;
|
|
26
|
+
|
|
27
|
+
interface SavedGroup {
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly data: string;
|
|
30
|
+
readonly state: "pending" | "running" | "received" | "finished" | "failed" | "interrupted" | "revoked" | "receipt_blocked";
|
|
31
|
+
readonly worktree: string | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface ResponseRow {
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly data: string;
|
|
37
|
+
readonly outcome: GroupReply["outcome"];
|
|
38
|
+
readonly text: string | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
type ResponseSettlement = "sent" | "failed" | "uncertain";
|
|
42
|
+
|
|
43
|
+
const readRequest = (row: SavedGroup | ResponseRow): GroupRequest => JSON.parse(row.data);
|
|
44
|
+
const databasePath = (stateDir: string) => join(stateDir, "coordination.sqlite");
|
|
45
|
+
|
|
46
|
+
/** Local operator only. Never expose request text, worktree paths or runner diagnostics as status in chat. */
|
|
47
|
+
export function groupRequests(stateDir: string, id?: string) {
|
|
48
|
+
const file = databasePath(stateDir);
|
|
49
|
+
if (!existsSync(file)) return [];
|
|
50
|
+
using db = new Database(file, { readonly: true });
|
|
51
|
+
const exists = db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='group_requests'").get();
|
|
52
|
+
if (!exists) return [];
|
|
53
|
+
const rows = id === undefined
|
|
54
|
+
? db.query<SavedGroup, []>("SELECT id,data,state,worktree FROM group_requests ORDER BY sequence DESC LIMIT 100").all()
|
|
55
|
+
: db.query<SavedGroup, [string]>("SELECT id,data,state,worktree FROM group_requests WHERE id=?").all(id);
|
|
56
|
+
return rows.map(row => ({
|
|
57
|
+
...readRequest(row), state: row.state, worktree: row.worktree,
|
|
58
|
+
delivery: db.query<{ outcome: string; state: string; remoteId: string | null }, [string]>(
|
|
59
|
+
"SELECT outcome,state,remote_id AS remoteId FROM group_responses WHERE id=? ORDER BY sequence").all(row.id),
|
|
60
|
+
}));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export class GroupAccess {
|
|
64
|
+
private readonly db: Database;
|
|
65
|
+
private readonly abort = new AbortController();
|
|
66
|
+
private active?: Promise<void>;
|
|
67
|
+
private sending?: Promise<void>;
|
|
68
|
+
|
|
69
|
+
constructor(private readonly config: Config, private readonly messenger: Pick<Messenger, "sendGroup">) {
|
|
70
|
+
const db = new Database(databasePath(config.stateDir));
|
|
71
|
+
try {
|
|
72
|
+
db.exec("PRAGMA busy_timeout = 5000;");
|
|
73
|
+
db.exec(schema);
|
|
74
|
+
db.transaction(() => {
|
|
75
|
+
// A replacement cannot know whether the previous process invoked the provider or edited a file.
|
|
76
|
+
db.exec(`INSERT INTO group_responses(id,outcome)
|
|
77
|
+
SELECT id,'interrupted' FROM group_requests WHERE state='running';
|
|
78
|
+
UPDATE group_requests SET state='interrupted' WHERE state='running';
|
|
79
|
+
UPDATE group_responses SET state='uncertain' WHERE state='attempted';
|
|
80
|
+
UPDATE group_requests SET state='receipt_blocked' WHERE state='pending' AND EXISTS (
|
|
81
|
+
SELECT 1 FROM group_responses WHERE group_responses.id=group_requests.id
|
|
82
|
+
AND outcome='received' AND state IN ('failed','uncertain')
|
|
83
|
+
);`);
|
|
84
|
+
}).immediate();
|
|
85
|
+
} catch (error) {
|
|
86
|
+
db.close();
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
this.db = db;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private room(request: GroupRequest) {
|
|
93
|
+
const route = request.route;
|
|
94
|
+
if (!isConfiguredRoute(this.config, route) || route.guildId === null) return undefined;
|
|
95
|
+
const room = groupRoom(this.config, route);
|
|
96
|
+
return room?.revision === request.revision && room.mode === request.mode
|
|
97
|
+
&& room.userIds.includes(request.userId) ? room : undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
accept(request: GroupRequest): void {
|
|
101
|
+
const room = this.room(request);
|
|
102
|
+
if (!room || !request.id || !request.messageId || !request.text.trim() || Buffer.byteLength(request.text) > 4000) {
|
|
103
|
+
throw new DeliveryError("Group request is not authorized", "rejected");
|
|
104
|
+
}
|
|
105
|
+
const key = groupRoomKey(room);
|
|
106
|
+
const day = new Date().toISOString().slice(0, 10);
|
|
107
|
+
this.db.transaction(() => {
|
|
108
|
+
const prior = this.db.query<SavedGroup, [string]>("SELECT * FROM group_requests WHERE id=?").get(request.id);
|
|
109
|
+
if (prior) {
|
|
110
|
+
if (!isDeepStrictEqual(readRequest(prior), request)) throw new DeliveryError("Group request identity conflict", "rejected");
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const count = this.db.query<{ count: number }, [string, string]>(
|
|
114
|
+
"SELECT COUNT(*) AS count FROM group_requests WHERE room=? AND day=?").get(key, day);
|
|
115
|
+
const pending = this.db.query<{ count: number }, []>(
|
|
116
|
+
"SELECT COUNT(*) AS count FROM group_requests WHERE state IN ('pending','running')").get();
|
|
117
|
+
if (!count || !pending || count.count >= room.dailyLimit || (room.mode !== "request" && pending.count >= 32)) {
|
|
118
|
+
throw new DeliveryError("Group request budget exceeded", "rejected");
|
|
119
|
+
}
|
|
120
|
+
this.db.run("INSERT INTO group_requests(id,room,day,data,state) VALUES(?,?,?,?,?)",
|
|
121
|
+
[request.id, key, day, JSON.stringify(request), room.mode === "request" ? "received" : "pending"]);
|
|
122
|
+
if (room.mode !== "chat") this.db.run("INSERT INTO group_responses(id,outcome) VALUES(?,'received')", [request.id]);
|
|
123
|
+
}).immediate();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Shared head maintenance wakes this controller; never await inference in the owner intake queue. */
|
|
127
|
+
tick(allowRun: boolean, report: (error: unknown) => void): void {
|
|
128
|
+
if (this.abort.signal.aborted) return;
|
|
129
|
+
if (allowRun && !this.active) this.launch(report);
|
|
130
|
+
if (!this.sending) this.sending = this.flush().catch(report).finally(() => { this.sending = undefined; });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
get busy(): boolean { return this.active !== undefined || this.sending !== undefined; }
|
|
134
|
+
get running(): boolean { return this.active !== undefined; }
|
|
135
|
+
|
|
136
|
+
private launch(report: (error: unknown) => void): void {
|
|
137
|
+
try {
|
|
138
|
+
// Work needs a confirmed kickoff to the same room. Chat has no
|
|
139
|
+
// intermediate message and is eligible as soon as it is admitted.
|
|
140
|
+
const row = this.db.query<SavedGroup, []>(`SELECT q.* FROM group_requests q
|
|
141
|
+
LEFT JOIN group_responses r ON r.id=q.id AND r.outcome='received'
|
|
142
|
+
WHERE q.state='pending' AND (r.id IS NULL OR r.state='sent') ORDER BY q.sequence LIMIT 1`).get();
|
|
143
|
+
if (row) this.active = this.run(readRequest(row)).catch(report).finally(() => { this.active = undefined; });
|
|
144
|
+
} catch (error) { report(error); }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private async run(request: GroupRequest): Promise<void> {
|
|
148
|
+
const room = this.room(request);
|
|
149
|
+
if (!room || room.mode === "request") {
|
|
150
|
+
this.db.run("UPDATE group_requests SET state='revoked' WHERE id=? AND state='pending'", [request.id]);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const claimed = this.db.run("UPDATE group_requests SET state='running' WHERE id=? AND state='pending'", [request.id]);
|
|
154
|
+
if (claimed.changes !== 1) return;
|
|
155
|
+
let outcome: "finished" | "failed" | "interrupted" = "failed";
|
|
156
|
+
let text: string | null = null;
|
|
157
|
+
let worktree: string | null = null;
|
|
158
|
+
try {
|
|
159
|
+
const entry = this.config.command[0];
|
|
160
|
+
const executable = entry && (isAbsolute(entry) ? entry : Bun.which(entry));
|
|
161
|
+
if (!executable) throw new Error("Group mode requires an installed stock OMP executable");
|
|
162
|
+
const { runRestrictedGroup } = await import("./group-runner");
|
|
163
|
+
const result = await runRestrictedGroup({
|
|
164
|
+
id: request.id, mode: room.mode, model: room.model, executable, text: request.text,
|
|
165
|
+
stateDir: join(this.config.stateDir, "groups"), signal: this.abort.signal,
|
|
166
|
+
...(room.mode === "work" ? { repository: room.repository } : {}),
|
|
167
|
+
});
|
|
168
|
+
worktree = room.mode === "work" ? result.worktree ?? null : null;
|
|
169
|
+
if (room.mode === "chat" && result.ok && result.text?.trim()) {
|
|
170
|
+
text = result.text.trim().slice(0, 1500).replace(/[\uD800-\uDBFF]$/, "");
|
|
171
|
+
}
|
|
172
|
+
if (result.ok && (room.mode === "work" ? worktree !== null : text !== null)) outcome = "finished";
|
|
173
|
+
} catch {
|
|
174
|
+
// Never put provider failures, process stderr, tool output or local paths on a group route.
|
|
175
|
+
outcome = "failed";
|
|
176
|
+
}
|
|
177
|
+
if (this.abort.signal.aborted) { outcome = "interrupted"; text = null; }
|
|
178
|
+
this.db.transaction(() => {
|
|
179
|
+
this.db.run("UPDATE group_requests SET state=?,worktree=? WHERE id=? AND state='running'", [outcome, worktree, request.id]);
|
|
180
|
+
this.db.run("INSERT INTO group_responses(id,outcome,text) VALUES(?,?,?)", [request.id, outcome, text]);
|
|
181
|
+
}).immediate();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private async flush(): Promise<void> {
|
|
185
|
+
for (let count = 0; count < 8 && !this.abort.signal.aborted; count++) {
|
|
186
|
+
const row = this.db.query<ResponseRow, []>(`SELECT r.id,r.outcome,r.text,q.data FROM group_responses r
|
|
187
|
+
INNER JOIN group_requests q ON q.id=r.id WHERE r.state='ready' ORDER BY r.sequence LIMIT 1`).get();
|
|
188
|
+
if (!row) return;
|
|
189
|
+
if (!this.room(readRequest(row)) || !this.messenger.sendGroup) {
|
|
190
|
+
this.finishResponse(row, "failed", null);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const claimed = this.db.run("UPDATE group_responses SET state='attempted' WHERE id=? AND outcome=? AND state='ready'", [row.id, row.outcome]);
|
|
194
|
+
if (claimed.changes !== 1) continue;
|
|
195
|
+
let state: ResponseSettlement = "sent";
|
|
196
|
+
let remoteId: string | null = null;
|
|
197
|
+
try {
|
|
198
|
+
remoteId = await this.messenger.sendGroup(row.outcome === "finished"
|
|
199
|
+
? { sourceId: row.id, outcome: row.outcome, ...(row.text === null ? {} : { text: row.text }) }
|
|
200
|
+
: { sourceId: row.id, outcome: row.outcome });
|
|
201
|
+
} catch (error) {
|
|
202
|
+
state = error instanceof DeliveryError && error.certainty === "rejected" ? "failed" : "uncertain";
|
|
203
|
+
}
|
|
204
|
+
this.finishResponse(row, state, remoteId);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
private finishResponse(row: ResponseRow, state: ResponseSettlement, remoteId: string | null): void {
|
|
209
|
+
this.db.transaction(() => {
|
|
210
|
+
this.db.run("UPDATE group_responses SET state=?,remote_id=? WHERE id=? AND outcome=?", [state, remoteId, row.id, row.outcome]);
|
|
211
|
+
if (row.outcome === "received" && state !== "sent") {
|
|
212
|
+
this.db.run("UPDATE group_requests SET state='receipt_blocked' WHERE id=? AND state='pending'", [row.id]);
|
|
213
|
+
}
|
|
214
|
+
}).immediate();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async stop(): Promise<void> {
|
|
218
|
+
this.abort.abort();
|
|
219
|
+
await Promise.allSettled([this.active, this.sending]);
|
|
220
|
+
this.db.close();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import type { Config } from "./config";
|
|
5
|
+
import type { Platform, Route } from "./contracts";
|
|
6
|
+
|
|
7
|
+
export const GROUP_MODEL_SELECTOR = /^([a-z][a-z0-9-]{0,62})\/([a-zA-Z0-9][a-zA-Z0-9._/-]{0,158})$/;
|
|
8
|
+
|
|
9
|
+
type GroupRoomScope = {
|
|
10
|
+
readonly platform: Platform;
|
|
11
|
+
readonly guildId: string;
|
|
12
|
+
readonly channelId: string;
|
|
13
|
+
readonly userIds: readonly string[];
|
|
14
|
+
readonly dailyLimit: number;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
type RoomMode = { readonly mode: "request" }
|
|
18
|
+
| { readonly mode: "chat"; readonly model: string }
|
|
19
|
+
| { readonly mode: "work"; readonly model: string; readonly repository: string };
|
|
20
|
+
|
|
21
|
+
export type GroupRoom = GroupRoomScope & RoomMode & { readonly revision: string };
|
|
22
|
+
|
|
23
|
+
export type GroupRequest = {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
readonly route: Route;
|
|
26
|
+
readonly messageId: string;
|
|
27
|
+
readonly userId: string;
|
|
28
|
+
readonly mode: GroupRoom["mode"];
|
|
29
|
+
readonly revision: string;
|
|
30
|
+
readonly text: string;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export type GroupReply = { readonly sourceId: string } & (
|
|
34
|
+
{ readonly outcome: "received" | "failed" | "interrupted" }
|
|
35
|
+
| { readonly outcome: "finished"; readonly text?: string }
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
export function groupRoom(config: Config, route: Route): GroupRoom | undefined {
|
|
39
|
+
return config.groupRooms?.find(room => room.platform === route.platform
|
|
40
|
+
&& room.guildId === route.guildId && room.channelId === route.channelId);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function groupRoomKey(room: GroupRoomScope): string {
|
|
44
|
+
return JSON.stringify([room.platform, room.guildId, room.channelId]);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function parseGroupRooms(raw: unknown, config: Config, base: string): readonly GroupRoom[] {
|
|
48
|
+
if (!Array.isArray(raw)) throw new Error("groupRooms must be an array");
|
|
49
|
+
const seen = new Set<string>();
|
|
50
|
+
return raw.map((value: unknown, index): GroupRoom => {
|
|
51
|
+
const path = `groupRooms[${index}]`;
|
|
52
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${path} must be an object`);
|
|
53
|
+
const { platform, guildId, channelId, userIds, mode, model, repository, dailyLimit, ...extra } =
|
|
54
|
+
value as Record<string, unknown>;
|
|
55
|
+
if (Object.keys(extra).length || typeof guildId !== "string" || typeof channelId !== "string"
|
|
56
|
+
|| typeof dailyLimit !== "number" || !Number.isSafeInteger(dailyLimit) || dailyLimit < 1) {
|
|
57
|
+
throw new Error(`${path} requires exact platform, guildId, channelId and a positive dailyLimit`);
|
|
58
|
+
}
|
|
59
|
+
let userPattern: RegExp;
|
|
60
|
+
switch (platform) {
|
|
61
|
+
case "discord":
|
|
62
|
+
if (!config.discord?.allowedGuildIds.includes(guildId) || !config.discord.allowedChannelIds.includes(channelId)
|
|
63
|
+
|| config.discord.voice?.textChannelId === channelId || config.discord.voice?.channelId === channelId) {
|
|
64
|
+
throw new Error(`${path} must name an allowed Discord server and parent channel outside the voice configuration`);
|
|
65
|
+
}
|
|
66
|
+
userPattern = /^[1-9]\d{0,19}$/;
|
|
67
|
+
break;
|
|
68
|
+
case "telegram":
|
|
69
|
+
if (guildId !== channelId || !config.telegram?.allowedChatIds.includes(channelId)) {
|
|
70
|
+
throw new Error(`${path} must name an allowed Telegram group; guildId and channelId must be its same signed ID`);
|
|
71
|
+
}
|
|
72
|
+
userPattern = /^[1-9]\d{0,15}$/;
|
|
73
|
+
break;
|
|
74
|
+
case "slack":
|
|
75
|
+
if (guildId !== config.slack?.teamId || !config.slack.allowedChannelIds.includes(channelId)) {
|
|
76
|
+
throw new Error(`${path} must name an allowed Slack workspace and channel`);
|
|
77
|
+
}
|
|
78
|
+
userPattern = /^[UW][A-Z0-9]+$/;
|
|
79
|
+
break;
|
|
80
|
+
default:
|
|
81
|
+
throw new Error(`${path}.platform must be discord, telegram, or slack`);
|
|
82
|
+
}
|
|
83
|
+
if (!Array.isArray(userIds) || !userIds.length || !userIds.every((id): id is string =>
|
|
84
|
+
typeof id === "string" && userPattern.test(id) && (platform !== "telegram" || Number.isSafeInteger(Number(id))))) {
|
|
85
|
+
throw new Error(`${path}.userIds must be a non-empty allowlist of stable platform user IDs`);
|
|
86
|
+
}
|
|
87
|
+
const scope = { platform, guildId, channelId, userIds: [...new Set(userIds)].sort(), dailyLimit };
|
|
88
|
+
const key = groupRoomKey(scope);
|
|
89
|
+
if (seen.has(key)) throw new Error(`${path} duplicates a group room`);
|
|
90
|
+
seen.add(key);
|
|
91
|
+
|
|
92
|
+
let policy: RoomMode;
|
|
93
|
+
if (mode === "request") {
|
|
94
|
+
if (model !== undefined || repository !== undefined) {
|
|
95
|
+
throw new Error(`${path} request mode does not accept model or repository`);
|
|
96
|
+
}
|
|
97
|
+
policy = { mode };
|
|
98
|
+
} else if (mode === "chat" || mode === "work") {
|
|
99
|
+
if (typeof model !== "string" || !GROUP_MODEL_SELECTOR.test(model)) {
|
|
100
|
+
throw new Error(`${path} ${mode} mode requires an exact provider/model`);
|
|
101
|
+
}
|
|
102
|
+
if (mode === "work") {
|
|
103
|
+
if (typeof repository !== "string" || !repository.trim()) throw new Error(`${path}.repository is required for work`);
|
|
104
|
+
const directory = realpathSync(resolve(base, repository));
|
|
105
|
+
if (!statSync(directory).isDirectory()) throw new Error(`${path}.repository must point to a directory`);
|
|
106
|
+
policy = { mode, model, repository: directory };
|
|
107
|
+
} else {
|
|
108
|
+
if (repository !== undefined) throw new Error(`${path} chat mode does not accept a repository`);
|
|
109
|
+
policy = { mode, model };
|
|
110
|
+
}
|
|
111
|
+
} else {
|
|
112
|
+
throw new Error(`${path}.mode must be request, chat, or work`);
|
|
113
|
+
}
|
|
114
|
+
const room = { ...scope, ...policy };
|
|
115
|
+
return { ...room, revision: createHash("sha256").update(JSON.stringify(room)).digest("hex") };
|
|
116
|
+
});
|
|
117
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
closeSync, constants, fstatSync, lstatSync, openSync, opendirSync, readSync, realpathSync, renameSync, unlinkSync,
|
|
4
|
+
writeFileSync, type Stats,
|
|
5
|
+
} from "node:fs";
|
|
6
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
7
|
+
import { Type } from "@sinclair/typebox";
|
|
8
|
+
import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
|
|
9
|
+
|
|
10
|
+
const maxBytes = 32 * 1024;
|
|
11
|
+
const maxCalls = 40;
|
|
12
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
13
|
+
const pathParameter = Type.String({ minLength: 1, maxLength: 512 });
|
|
14
|
+
export const restrictedWorkTools = ["group_list", "group_read", "group_edit"] as const;
|
|
15
|
+
|
|
16
|
+
class RestrictedPathError extends Error {}
|
|
17
|
+
|
|
18
|
+
function isVisibleSegment(segment: string): boolean {
|
|
19
|
+
return Buffer.byteLength(segment) <= 255 && /^[^\s.\\/:][^\\/:]*$/u.test(segment) &&
|
|
20
|
+
!/[\p{Cc}\p{Cf}]/u.test(segment) && !/[ .]$/.test(segment);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function sameFile(first: Stats, second: Stats): boolean {
|
|
24
|
+
return first.dev === second.dev && first.ino === second.ino;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function existingText(path: string): { readonly text: string; readonly mode: number } {
|
|
28
|
+
const expected = lstatSync(path);
|
|
29
|
+
if (!expected.isFile() || expected.nlink !== 1 || expected.size > maxBytes || realpathSync.native(path) !== path)
|
|
30
|
+
throw new RestrictedPathError("Not an eligible regular text file");
|
|
31
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
32
|
+
try {
|
|
33
|
+
const actual = fstatSync(fd);
|
|
34
|
+
if (!sameFile(expected, actual) || !actual.isFile() || actual.nlink !== 1 || actual.size > maxBytes)
|
|
35
|
+
throw new RestrictedPathError("File changed or is not an eligible regular file");
|
|
36
|
+
const buffer = Buffer.alloc(maxBytes + 1);
|
|
37
|
+
let size = 0;
|
|
38
|
+
while (size < buffer.length) {
|
|
39
|
+
const count = readSync(fd, buffer, size, buffer.length - size, size);
|
|
40
|
+
if (count === 0) break;
|
|
41
|
+
size += count;
|
|
42
|
+
}
|
|
43
|
+
const bytes = buffer.subarray(0, size);
|
|
44
|
+
if (size > maxBytes || bytes.includes(0)) throw new RestrictedPathError("Only bounded UTF-8 text is supported");
|
|
45
|
+
return { text: utf8.decode(bytes), mode: actual.mode & 0o777 };
|
|
46
|
+
} finally { closeSync(fd); }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function isMissing(error: unknown): boolean {
|
|
50
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function content(text: string) {
|
|
54
|
+
return { content: [{ type: "text" as const, text }], details: undefined };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Public OMP extension factory; never used unless launched with the parent-owned checkout. */
|
|
58
|
+
export default function groupWorktree(pi: ExtensionAPI): void {
|
|
59
|
+
const configured = process.env.OMP_SA_RESTRICTED_WORKTREE;
|
|
60
|
+
if (!configured || !isAbsolute(configured) || realpathSync.native(configured) !== configured || !lstatSync(configured).isDirectory())
|
|
61
|
+
throw new RestrictedPathError("Missing private group worktree");
|
|
62
|
+
const root = configured;
|
|
63
|
+
const rootIdentity = lstatSync(root);
|
|
64
|
+
const permitted = new Set<string>(restrictedWorkTools);
|
|
65
|
+
pi.on("tool_call", event => permitted.has(event.toolName)
|
|
66
|
+
? undefined : { block: true, reason: "Only the restricted group worktree tools may execute." });
|
|
67
|
+
let calls = 0;
|
|
68
|
+
let remainingBytes = 384 * 1024;
|
|
69
|
+
function location(path: string, kind: "file" | "directory"): string {
|
|
70
|
+
if (!sameFile(rootIdentity, lstatSync(root))) throw new RestrictedPathError("Worktree root changed");
|
|
71
|
+
if (path === "." && kind === "directory") return root;
|
|
72
|
+
const segments = path.split("/");
|
|
73
|
+
if (Buffer.byteLength(path) > 512 || segments.length > 20 || !segments.every(isVisibleSegment))
|
|
74
|
+
throw new RestrictedPathError("Use a visible path relative to the group worktree");
|
|
75
|
+
let current = root;
|
|
76
|
+
for (const segment of kind === "directory" ? segments : segments.slice(0, -1)) {
|
|
77
|
+
current = join(current, segment);
|
|
78
|
+
if (!lstatSync(current).isDirectory() || realpathSync.native(current) !== current)
|
|
79
|
+
throw new RestrictedPathError("Not an eligible directory");
|
|
80
|
+
}
|
|
81
|
+
return kind === "directory" ? current : join(current, segments.at(-1) ?? "");
|
|
82
|
+
}
|
|
83
|
+
function useBudget(signal: AbortSignal | undefined, run: () => string) {
|
|
84
|
+
signal?.throwIfAborted();
|
|
85
|
+
if (++calls > maxCalls || remainingBytes < maxBytes) throw new RestrictedPathError("Group tool budget exhausted");
|
|
86
|
+
try {
|
|
87
|
+
const result = run();
|
|
88
|
+
remainingBytes -= Buffer.byteLength(result);
|
|
89
|
+
return content(result);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error instanceof RestrictedPathError) throw error;
|
|
92
|
+
if (!(error instanceof Error)) throw error;
|
|
93
|
+
// OMP can report the operation failure but must not echo a host path or raw filesystem diagnostic.
|
|
94
|
+
throw new RestrictedPathError("File operation refused inside the group worktree");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
pi.registerTool({
|
|
99
|
+
name: restrictedWorkTools[0], label: "Group list", approval: "read", loadMode: "essential",
|
|
100
|
+
description: "List visible entries in one group worktree directory. Use . for the root.",
|
|
101
|
+
parameters: Type.Object({ path: pathParameter }, { additionalProperties: false }),
|
|
102
|
+
async execute(_id, { path }, signal) {
|
|
103
|
+
return useBudget(signal, () => {
|
|
104
|
+
const directory = location(path, "directory");
|
|
105
|
+
const handle = opendirSync(directory);
|
|
106
|
+
const names: string[] = [];
|
|
107
|
+
try {
|
|
108
|
+
for (let count = 0; count < 8192 && names.length < 120; count++) {
|
|
109
|
+
const entry = handle.readSync();
|
|
110
|
+
if (!entry) break;
|
|
111
|
+
if (!isVisibleSegment(entry.name)) continue;
|
|
112
|
+
const info = lstatSync(join(directory, entry.name));
|
|
113
|
+
if (info.isDirectory()) names.push(`${entry.name}/`);
|
|
114
|
+
else if (info.isFile() && info.nlink === 1 && info.size <= maxBytes) names.push(entry.name);
|
|
115
|
+
}
|
|
116
|
+
} finally { handle.closeSync(); }
|
|
117
|
+
return names.sort().join("\n");
|
|
118
|
+
});
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
pi.registerTool({
|
|
122
|
+
name: restrictedWorkTools[1], label: "Group read", approval: "read", loadMode: "essential",
|
|
123
|
+
description: "Read a visible UTF-8 file (at most 32 KiB) in the group worktree.",
|
|
124
|
+
parameters: Type.Object({ path: pathParameter }, { additionalProperties: false }),
|
|
125
|
+
async execute(_id, { path }, signal) {
|
|
126
|
+
return useBudget(signal, () => existingText(location(path, "file")).text);
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
pi.registerTool({
|
|
130
|
+
name: restrictedWorkTools[2], label: "Group edit", approval: "write", loadMode: "essential",
|
|
131
|
+
description: "Write a complete UTF-8 file (at most 32 KiB) at a visible path in an existing group worktree directory.",
|
|
132
|
+
parameters: Type.Object({ path: pathParameter, text: Type.String({ maxLength: maxBytes }) }, { additionalProperties: false }),
|
|
133
|
+
async execute(_id, { path, text }, signal) {
|
|
134
|
+
return useBudget(signal, () => {
|
|
135
|
+
const bytes = Buffer.byteLength(text);
|
|
136
|
+
if (bytes > maxBytes || text.includes("\0")) throw new RestrictedPathError("Only bounded UTF-8 text is supported");
|
|
137
|
+
const target = location(path, "file");
|
|
138
|
+
let mode = 0o644;
|
|
139
|
+
try { mode = existingText(target).mode; }
|
|
140
|
+
catch (error) { if (!isMissing(error)) throw error; }
|
|
141
|
+
const temp = join(dirname(target), `.group-edit-${randomUUID()}`);
|
|
142
|
+
writeFileSync(temp, text, { mode, flag: "wx" });
|
|
143
|
+
try { renameSync(temp, target); }
|
|
144
|
+
catch (error) {
|
|
145
|
+
unlinkSync(temp);
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
remainingBytes -= bytes;
|
|
149
|
+
return "File written inside the group worktree.";
|
|
150
|
+
});
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
}
|