cataly-linux-x64 0.0.0-stage → 0.2.1
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/LICENSE +661 -0
- package/THIRD-PARTY-NOTICES.txt +47981 -0
- package/cataly +0 -0
- package/cataly.ts +599 -0
- package/package.json +21 -4
- package/README.md +0 -3
package/cataly
ADDED
|
Binary file
|
package/cataly.ts
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
// Cataly bridge for OMP (DESIGN 3.5, 4.3, 10.6; EXT-01 to EXT-37 kept parts), loaded by every OMP process from the
|
|
2
|
+
// global extension folder. Inert unless the session carries a Cataly launch token or the session marker and the
|
|
3
|
+
// hub accepts it: until then only the session start and switch handlers, no timer, connection or prompt text. An
|
|
4
|
+
// accepted session forwards events, offers the hub's tools, appends its guidance, asks it at stop and keeps
|
|
5
|
+
// tool-result fingerprints; a Tern session also takes commands, fences switches and offers forms. The hub decides.
|
|
6
|
+
|
|
7
|
+
import { lstatSync } from "node:fs";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
import type {
|
|
10
|
+
AgentToolResult, BeforeAgentStartEvent, BeforeAgentStartEventResult, ExtensionAPI, ExtensionAskDialogQuestion, ExtensionContext,
|
|
11
|
+
MessageEndEvent, SessionStopEventResult, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionStartEvent,
|
|
12
|
+
} from "@oh-my-pi/pi-coding-agent";
|
|
13
|
+
|
|
14
|
+
const PROTOCOL = 1;
|
|
15
|
+
const VERSION = "0.2.1"; // `cataly extension` writes the release file with it filled in (IR req. 5-6)
|
|
16
|
+
const MARKER = "cataly";
|
|
17
|
+
const DELIVERY = "cataly-delivery";
|
|
18
|
+
const [CONNECT_MS, HEARTBEAT_MS, SILENT_MS, CHANGE_MS] = [1_000, 15_000, 45_000, 10_000];
|
|
19
|
+
const [TOOL_MS, SHELL_MS, STOP_MS, SHUTDOWN_MS] = [5_000, 2_000, 1_000, 500];
|
|
20
|
+
const [BUFFER_EVENTS, BUFFER_BYTES, LINE_MAX, TEXT_CUT, CALLS_KEPT, IDS_KEPT] = [1_000, 1 << 20, 1 << 20, 2_048, 4_096, 1_024];
|
|
21
|
+
const BACKOFF_S = [1, 2, 4, 8, 16, 30];
|
|
22
|
+
const UNSURE = "nothing was recorded or started unless the hub reports otherwise. Retrying is safe.";
|
|
23
|
+
|
|
24
|
+
type Json = Record<string, unknown>;
|
|
25
|
+
type Ctx = ExtensionContext;
|
|
26
|
+
type Pi = ExtensionAPI;
|
|
27
|
+
|
|
28
|
+
/** One stream connection, as returned by `Deps.connect`. */
|
|
29
|
+
export interface Wire { write(line: string): void; close(): void }
|
|
30
|
+
|
|
31
|
+
export interface Deps {
|
|
32
|
+
env: Record<string, string | undefined>;
|
|
33
|
+
connect(path: string, onLine: (line: string) => void, onClose: () => void): Promise<Wire>;
|
|
34
|
+
uid(): number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Bun's Unix socket client, line-framed; only in the user's own private socket directory (DESIGN 8). */
|
|
38
|
+
export async function unixConnect(path: string, onLine: (line: string) => void, onClose: () => void): Promise<Wire> {
|
|
39
|
+
if (!privateDir(dirname(path), process.getuid?.() ?? -1)) throw new Error("the hub socket's directory is not private");
|
|
40
|
+
let buf = "";
|
|
41
|
+
let closed = false;
|
|
42
|
+
const end = () => void (closed || ((closed = true), onClose()));
|
|
43
|
+
const data = (s: { end(): void }, chunk: Uint8Array) => {
|
|
44
|
+
buf += chunk.toString();
|
|
45
|
+
if (buf.length > LINE_MAX * 2) return void ((buf = ""), s.end());
|
|
46
|
+
for (let at = buf.indexOf("\n"); at >= 0; at = buf.indexOf("\n")) {
|
|
47
|
+
const line = buf.slice(0, at);
|
|
48
|
+
buf = buf.slice(at + 1);
|
|
49
|
+
if (line.trim()) onLine(line);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const sock = await withTimeout(Bun.connect({ unix: path, socket: { data, close: end, error: end } }), CONNECT_MS);
|
|
53
|
+
if (!sock) throw new Error("the hub did not accept a connection within 1 s");
|
|
54
|
+
return { write: line => void (closed || sock.write(line)), close: () => (sock.end(), end()) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function withTimeout<T>(p: Promise<T>, ms: number): Promise<T | undefined> {
|
|
58
|
+
const { promise, resolve } = Promise.withResolvers<T | undefined>();
|
|
59
|
+
const timer = setTimeout(() => resolve(undefined), ms);
|
|
60
|
+
p.then(resolve, () => resolve(undefined)).finally(() => clearTimeout(timer));
|
|
61
|
+
return promise;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The user's own directory, mode 0700 or stricter, not a symlink: no other user can stand in for the hub. */
|
|
65
|
+
export function privateDir(dir: string, uid: number): boolean {
|
|
66
|
+
const s = safe(() => lstatSync(dir));
|
|
67
|
+
return Boolean(s && !s.isSymbolicLink() && s.isDirectory() && s.uid === uid && (s.mode & 0o077) === 0);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The hub socket: the launch's `CATALY_SOCKET`, else the per-user default (EXT-33). */
|
|
71
|
+
export function socketPath(deps: Deps): string {
|
|
72
|
+
const { CATALY_SOCKET: given, XDG_RUNTIME_DIR: run } = deps.env;
|
|
73
|
+
if (given) return given;
|
|
74
|
+
const candidate = run ? `${run}/cataly/hub.sock` : "";
|
|
75
|
+
if (candidate && candidate.length < (process.platform === "darwin" ? 104 : 108)) return candidate;
|
|
76
|
+
return `/tmp/cataly-${deps.uid()}/hub.sock`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Runs `fn`; a throw from OMP's side never escapes into the session. */
|
|
80
|
+
function safe<T>(fn: () => T): T | undefined {
|
|
81
|
+
try { return fn(); } catch { return undefined; }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function marked(ctx: Ctx): boolean {
|
|
85
|
+
const branch = safe(() => ctx.sessionManager.getBranch()) ?? [];
|
|
86
|
+
return branch.some(e => e.type === "custom" && e.customType === MARKER);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function textOf(content: unknown): string {
|
|
90
|
+
if (typeof content === "string") return content;
|
|
91
|
+
const blocks = Array.isArray(content) ? (content as Json[]) : [];
|
|
92
|
+
return blocks.flatMap(b => (b?.type === "text" && typeof b.text === "string" ? [b.text] : [])).join("\n");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Drops run timing, job bookkeeping and file locations from result details (EVR req. 13). */
|
|
96
|
+
function stable(value: unknown): unknown {
|
|
97
|
+
if (Array.isArray(value)) return value.map(stable);
|
|
98
|
+
if (!value || typeof value !== "object") return value;
|
|
99
|
+
const out: Json = {};
|
|
100
|
+
for (const key of Object.keys(value as Json).sort())
|
|
101
|
+
if (!/^(duration|elapsed|startedAt|endedAt|timestamp|time|jobId|outputPath|artifactPath|path)/i.test(key))
|
|
102
|
+
out[key] = stable((value as Json)[key]);
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** SHA-256 over the tool name, visible content and structured details (EVR req. 13). */
|
|
107
|
+
export function fingerprint(tool: string, result: Json | undefined): string {
|
|
108
|
+
const hasher = new Bun.CryptoHasher("sha256");
|
|
109
|
+
hasher.update(JSON.stringify([tool, stable(result?.content ?? null), stable(result?.details ?? null)]));
|
|
110
|
+
return hasher.digest("hex");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface Call { tool: string; cwd: string; starts: number; command?: string; fingerprint?: string; error?: boolean }
|
|
114
|
+
|
|
115
|
+
/** The model OMP runs for this context, `provider/id`, or "" when unknown. */
|
|
116
|
+
function modelOf(ctx: Ctx): string {
|
|
117
|
+
const m = safe(() => ctx?.models?.current?.() ?? ctx?.model);
|
|
118
|
+
return m ? `${m.provider}/${m.id}` : "";
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Agent registry IDs of this realm's accepted sessions and subagents, with the session the hub knows. */
|
|
122
|
+
const owners = new Map<string, string>();
|
|
123
|
+
|
|
124
|
+
/** The bridge state of one OMP process. */
|
|
125
|
+
export class Bridge {
|
|
126
|
+
wired = false; role = "none"; key: string | undefined;
|
|
127
|
+
guidance = ""; session = ""; ctx!: Ctx;
|
|
128
|
+
// The connection, its numbering, its offline buffer and its reconnect state (EXT req. 13-15).
|
|
129
|
+
wire: Wire | undefined;
|
|
130
|
+
connecting = false; shutting = false;
|
|
131
|
+
next = 1; seq = 0;
|
|
132
|
+
pending = new Map<number, (v: Json | undefined) => void>();
|
|
133
|
+
queue: string[] = [];
|
|
134
|
+
queued = 0; dropped = 0;
|
|
135
|
+
lastRx = 0; attempt = 0;
|
|
136
|
+
warned = false; lastAnswer = false; shell = false; fallbackTo = "";
|
|
137
|
+
calls = new Map<string, Call>(); pin: string | undefined;
|
|
138
|
+
// Terminal sessions (DESIGN 4.3): change mark, commands applying, order, delivery outcomes, open forms.
|
|
139
|
+
tern = false;
|
|
140
|
+
changing = 0; applying = 0;
|
|
141
|
+
chain = Promise.resolve();
|
|
142
|
+
delivered = new Map<string, { key: string; out: Json }>();
|
|
143
|
+
forms = new Map<string, (answer: unknown) => void>();
|
|
144
|
+
token: string | undefined; parent = "";
|
|
145
|
+
|
|
146
|
+
constructor(readonly pi: Pi, readonly deps: Deps) {
|
|
147
|
+
this.token = deps.env.CATALY_LAUNCH || undefined;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Session start or switch: a candidate connects; anything else stays inert (EXT req. 1-3). A subagent of an
|
|
151
|
+
* accepted session connects as `sub` with its parent: its spawner's session in this realm, else (inside a hub
|
|
152
|
+
* launch) its header's parent file, which the hub resolves. Its veto stands first, so no verdict blocks (EXT req. 9). */
|
|
153
|
+
async consider(ctx: Ctx, transition?: Json): Promise<void> {
|
|
154
|
+
const sub = ctx?.agent?.kind === "sub";
|
|
155
|
+
if (sub && (this.wired || this.parent)) return;
|
|
156
|
+
const id = String(ctx.sessionManager?.getSessionId?.() ?? "");
|
|
157
|
+
if (this.wired) {
|
|
158
|
+
this.ctx = ctx;
|
|
159
|
+
this.changing = 0;
|
|
160
|
+
if (id !== this.session) {
|
|
161
|
+
this.calls.clear();
|
|
162
|
+
this.session = id;
|
|
163
|
+
owners.set(String(ctx.agent?.id), id);
|
|
164
|
+
const answer = await this.request("bridge.switch", { session: id, file: this.file(), ...transition }, TOOL_MS);
|
|
165
|
+
this.apply(answer);
|
|
166
|
+
}
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (sub) {
|
|
170
|
+
const header = this.token ? safe(() => ctx.sessionManager.getHeader()?.parentSession) : undefined;
|
|
171
|
+
[this.parent, this.token] = [owners.get(String(ctx.agent.parentId)) ?? header ?? "", undefined];
|
|
172
|
+
if (!this.parent) return;
|
|
173
|
+
this.pi.on("tool_call", (e, c) => this.veto(e, c));
|
|
174
|
+
} else if (!this.token && !marked(ctx)) return;
|
|
175
|
+
this.ctx = ctx;
|
|
176
|
+
this.session = id;
|
|
177
|
+
await this.connect();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
file(): string {
|
|
181
|
+
return String(this.ctx?.sessionManager?.getSessionFile?.() ?? "");
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Idle, model, thinking and goal as OMP reports them now (HOST req. 94-95). */
|
|
185
|
+
facts(ctx: Ctx): Json {
|
|
186
|
+
const modes = safe(() => ctx.sessionModes?.getState());
|
|
187
|
+
const goal = modes && { status: modes.goal.status, objective: modes.goal.objective };
|
|
188
|
+
const thinking = safe(() => this.pi.getThinkingLevel?.());
|
|
189
|
+
return { idle: Boolean(safe(() => ctx?.isIdle?.())), model: modelOf(ctx) || undefined, thinking, goal };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
hello(): Json {
|
|
193
|
+
const ctx = this.ctx;
|
|
194
|
+
const [cwd, agent, mode] = [ctx?.cwd ?? "", ctx?.agent?.kind ?? "main", ctx?.mode ?? ""].map(String);
|
|
195
|
+
const ids = { version: VERSION, token: this.token, key: this.key, session: this.session, file: this.file(), parent: this.parent };
|
|
196
|
+
return { ext: PROTOCOL, ...ids, pid: process.pid, cwd, agent, mode, marker: marked(ctx), ...this.facts(ctx) };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async connect(): Promise<void> {
|
|
200
|
+
if (this.connecting || this.shutting) return;
|
|
201
|
+
this.connecting = true;
|
|
202
|
+
this.wire = await this.deps.connect(socketPath(this.deps), line => this.receive(line), () => this.closed()).catch(() => undefined);
|
|
203
|
+
this.connecting = false;
|
|
204
|
+
if (!this.wire) return this.retry();
|
|
205
|
+
this.lastRx = Date.now();
|
|
206
|
+
const answer = await this.request("bridge.hello", this.hello(), TOOL_MS, true);
|
|
207
|
+
this.token = undefined;
|
|
208
|
+
if (!answer) return this.wire?.close();
|
|
209
|
+
if (answer.role !== "lead" && answer.role !== "lane") {
|
|
210
|
+
// Role none: inert for this session (EXT req. 4).
|
|
211
|
+
[this.role, this.key] = ["none", undefined];
|
|
212
|
+
return void (this.wire?.close(), (this.wire = undefined));
|
|
213
|
+
}
|
|
214
|
+
[this.attempt, this.key] = [0, String(answer.key ?? "")];
|
|
215
|
+
owners.set(String(this.ctx.agent?.id), this.parent || this.session);
|
|
216
|
+
this.tern ||= answer.tern === true;
|
|
217
|
+
this.apply(answer);
|
|
218
|
+
if (!this.wired) this.wire_up(answer);
|
|
219
|
+
else this.resend();
|
|
220
|
+
if (this.warned) this.status(answer.status as string | undefined);
|
|
221
|
+
this.warned = false;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
apply(answer: Json | undefined): void {
|
|
225
|
+
if (!answer) return;
|
|
226
|
+
this.role = String(answer.role ?? this.role);
|
|
227
|
+
if (typeof answer.guidance === "string") this.guidance = answer.guidance;
|
|
228
|
+
if (typeof answer.pin === "string") this.pin = answer.pin;
|
|
229
|
+
if (answer.shell !== undefined) this.shell = Boolean(answer.shell);
|
|
230
|
+
if (this.role !== "none" && !this.parent) this.mark();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Reconnect: snapshot first, then what was buffered, then how much was lost (EXT req. 13-14). */
|
|
234
|
+
resend(): void {
|
|
235
|
+
this.send("bridge.event", { kind: "snapshot", session: this.session, role: this.role, ...this.facts(this.ctx), last_seq: this.seq });
|
|
236
|
+
for (const line of this.queue.splice(0)) this.wire?.write(line);
|
|
237
|
+
this.queued = 0;
|
|
238
|
+
if (this.dropped > 0) this.event("dropped", { count: this.dropped });
|
|
239
|
+
this.dropped = 0;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
retry(): void {
|
|
243
|
+
if (this.shutting) return;
|
|
244
|
+
if (!this.warned) {
|
|
245
|
+
this.warned = true;
|
|
246
|
+
safe(() => this.ctx?.ui?.notify?.("Cataly hub not reachable; retrying.", "warning"));
|
|
247
|
+
this.status("Cataly offline");
|
|
248
|
+
}
|
|
249
|
+
const wait = BACKOFF_S[Math.min(this.attempt, BACKOFF_S.length - 1)] * 1000;
|
|
250
|
+
this.attempt += 1;
|
|
251
|
+
this.timer(() => void this.connect(), wait, false);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
closed(): void {
|
|
255
|
+
this.wire = undefined;
|
|
256
|
+
for (const resolve of this.pending.values()) resolve(undefined);
|
|
257
|
+
this.pending.clear();
|
|
258
|
+
if (this.wired && !this.shutting) this.retry();
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
receive(line: string): void {
|
|
262
|
+
this.lastRx = Date.now();
|
|
263
|
+
const msg = safe(() => JSON.parse(line) as Json);
|
|
264
|
+
if (!msg) return;
|
|
265
|
+
const resolve = this.pending.get(Number(msg.id ?? 0));
|
|
266
|
+
if (resolve) return resolve(msg.err ? undefined : ((msg.ok as Json) ?? {}));
|
|
267
|
+
const item = msg.item as Json | undefined;
|
|
268
|
+
const cmd = item?.cmd as Json | undefined;
|
|
269
|
+
if (cmd && this.tern && cmd.op === "form") {
|
|
270
|
+
// A form answer does not wait behind a command; the rest run one at a time, after a hello answer read with them (EXT req. 29).
|
|
271
|
+
const resolve = this.forms.get(String(cmd.call));
|
|
272
|
+
resolve?.(cmd.answer);
|
|
273
|
+
return this.send("bridge.reply", { n: cmd.n, ...(resolve ? {} : { refused: "the form was already answered" }) });
|
|
274
|
+
}
|
|
275
|
+
if (cmd) return void (this.chain = this.chain.then(() => (this.tern ? this.command(cmd) : undefined)));
|
|
276
|
+
if (item && typeof item.status === "string") this.status(item.status);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
line(method: string, params: Json, id = 0): string {
|
|
280
|
+
return `${JSON.stringify({ v: 1, id, method, params })}\n`;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
send(method: string, params: Json): void {
|
|
284
|
+
this.wire?.write(this.line(method, params));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** One event, numbered; buffered while disconnected, oldest dropped first (EXT req. 13). */
|
|
288
|
+
event(kind: string, fields: Json = {}): void {
|
|
289
|
+
this.seq += 1;
|
|
290
|
+
const line = this.line("bridge.event", { seq: this.seq, session: this.session, kind, ...fields });
|
|
291
|
+
if (this.wire) return this.wire.write(line);
|
|
292
|
+
this.queue.push(line);
|
|
293
|
+
this.queued += line.length;
|
|
294
|
+
while (this.queue.length > BUFFER_EVENTS || this.queued > BUFFER_BYTES) {
|
|
295
|
+
this.queued -= this.queue.shift()?.length ?? 0;
|
|
296
|
+
this.dropped += 1;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** A request answered by the hub, or `undefined` on timeout or disconnect. */
|
|
301
|
+
request(method: string, params: Json, ms: number, early = false): Promise<Json | undefined> {
|
|
302
|
+
if (!this.wire || (!early && !this.key)) return Promise.resolve(undefined);
|
|
303
|
+
const id = this.next++;
|
|
304
|
+
const { promise, resolve } = Promise.withResolvers<Json | undefined>();
|
|
305
|
+
const timer = setTimeout(() => this.pending.get(id)?.(undefined), ms);
|
|
306
|
+
this.pending.set(id, v => (this.pending.delete(id), clearTimeout(timer), resolve(v)));
|
|
307
|
+
this.wire.write(this.line(method, params, id));
|
|
308
|
+
return promise;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
timer(fn: () => void, ms: number, repeat: boolean): void {
|
|
312
|
+
const guarded = () => void safe(fn);
|
|
313
|
+
const ctx = this.ctx;
|
|
314
|
+
if (repeat) ctx?.setInterval?.(guarded, ms) ?? setInterval(guarded, ms);
|
|
315
|
+
else ctx?.setTimeout?.(guarded, ms) ?? setTimeout(guarded, ms);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
status(text: string | undefined): void {
|
|
319
|
+
safe(() => this.ctx?.ui?.setStatus?.("cataly", text || undefined));
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** The session marker, once per branch, so a resume by hand is recognised (EXT req. 6). */
|
|
323
|
+
mark(): void {
|
|
324
|
+
if (this.ctx && !marked(this.ctx)) safe(() => this.pi.appendEntry(MARKER, { v: PROTOCOL }));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** After the first acceptance: handlers, tools and the heartbeat (EXT req. 4, 15, 17). */
|
|
328
|
+
wire_up(answer: Json): void {
|
|
329
|
+
this.wired = true;
|
|
330
|
+
const pi = this.pi;
|
|
331
|
+
const tools = Array.isArray(answer.tools) ? (answer.tools as Json[]) : [];
|
|
332
|
+
const names = tools.map(def => String(def.name ?? "")).filter(Boolean);
|
|
333
|
+
for (const def of tools.filter(def => def.name)) {
|
|
334
|
+
const name = String(def.name);
|
|
335
|
+
// The hub sets each tool's answer deadline (a lane report reads evidence files).
|
|
336
|
+
const ms = Number(def.timeout_ms) || TOOL_MS;
|
|
337
|
+
const parameters = (def.parameters ?? { type: "object" }) as ToolDefinition["parameters"];
|
|
338
|
+
const [label, description] = [String(def.label ?? name), String(def.description ?? "")];
|
|
339
|
+
// The hub checks every operation, so OMP need not ask (extension API `approval`; a user deny still wins). An
|
|
340
|
+
// `essential` tool stays a direct call, never a bash command, where the outer bash approval would ask.
|
|
341
|
+
const approval = { tier: "write", policy: "allow" } as const;
|
|
342
|
+
const execute: ToolDefinition["execute"] = (callId, params, _s, _u, ctx) => this.tool(name, ms, callId, params as Json, ctx);
|
|
343
|
+
pi.registerTool({ name, label, description, parameters, approval, loadMode: "essential", execute });
|
|
344
|
+
}
|
|
345
|
+
safe(() => pi.setActiveTools?.([...(pi.getActiveTools?.() ?? []).filter((n: string) => !names.includes(n)), ...names]));
|
|
346
|
+
this.status(answer.status as string | undefined);
|
|
347
|
+
this.timer(() => this.beat(), HEARTBEAT_MS, true);
|
|
348
|
+
pi.on("before_agent_start", async (e, ctx) => (await this.barrier(ctx), this.guide(e, ctx)));
|
|
349
|
+
// Lane and terminal hooks, added only once the hub said they apply (EXT req. 1, 32, 34, 38, 42).
|
|
350
|
+
if ((this.shell || this.tern) && !this.parent)
|
|
351
|
+
pi.on("tool_call", (e, ctx) => (this.tern && e.toolName === "ask" ? this.form(e, ctx) : this.shell ? this.veto(e, ctx) : undefined));
|
|
352
|
+
const guard = (_e: unknown, ctx: Ctx) => this.guard(ctx);
|
|
353
|
+
if (this.tern) [pi.on("session_before_switch", guard), pi.on("session_before_branch", guard), pi.on("session_before_tree", guard)];
|
|
354
|
+
if (this.pin) pi.on("retry_fallback_applied", e => void (this.fallbackTo = e.to));
|
|
355
|
+
pi.on("session_stop", (_e, ctx) => this.stop(ctx));
|
|
356
|
+
pi.on("session_shutdown", (_e, ctx) => this.shutdown(ctx));
|
|
357
|
+
pi.on("session_branch", (e, ctx) => this.transition("session_branch", e.reason, ctx));
|
|
358
|
+
pi.on("session_tree", (_e, ctx) => this.transition("session_tree", undefined, ctx));
|
|
359
|
+
pi.on("turn_start", async (_e, ctx) => void (await this.barrier(ctx), this.main(ctx) && this.event("turn_start")));
|
|
360
|
+
pi.on("message_end", (e, ctx) => this.message(e, ctx));
|
|
361
|
+
pi.on("tool_execution_start", (e, ctx) => this.toolStart(e, ctx));
|
|
362
|
+
pi.on("tool_execution_end", (e, ctx) => this.toolEnd(e, ctx));
|
|
363
|
+
// The main agent's events the hub follows, each with the fields it reads; payloads differ across OMP versions.
|
|
364
|
+
const dialog = (e: Json) => ({ call: e.toolCallId ?? e.reviewId, tool: e.toolName, choice: e.choice });
|
|
365
|
+
const goal = (e: Json) => ({ status: (e.goal as Json)?.status ?? e.status, objective: (e.goal as Json)?.objective ?? e.objective });
|
|
366
|
+
const forwards: [string, (e: Json) => Json][] = [
|
|
367
|
+
...["agent_start", "turn_end", "session_compact", ...(this.tern ? ["session_clear"] : [])].map((k): [string, (e: Json) => Json] => [k, () => ({})]),
|
|
368
|
+
["agent_end", e => ({ will_continue: e.willContinue ?? e.yielded, awaiting: e.awaitingAsyncWork })],
|
|
369
|
+
["goal_updated", goal],
|
|
370
|
+
...["tool_approval_requested", "tool_approval_resolved", "plan_review_requested", "plan_review_resolved"].map((k): [string, (e: Json) => Json] => [k, dialog]),
|
|
371
|
+
];
|
|
372
|
+
const on = pi.on as unknown as (event: string, handler: (e: Json, ctx: Ctx) => unknown) => void;
|
|
373
|
+
for (const [kind, fields] of forwards) on(kind, (e, ctx) => this.main(ctx) && this.event(kind, fields(e)));
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
main(ctx: Ctx): boolean {
|
|
377
|
+
return this.role !== "none" && ctx?.agent?.kind !== "sub";
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
beat(): void {
|
|
381
|
+
if (!this.wire) return;
|
|
382
|
+
if (Date.now() - this.lastRx > SILENT_MS) return this.wire.close();
|
|
383
|
+
this.send("bridge.ping", {});
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
transition(kind: string, reason: string | undefined, ctx: Ctx): void {
|
|
387
|
+
if (!this.main(ctx)) return;
|
|
388
|
+
this.changing = 0;
|
|
389
|
+
this.calls.clear();
|
|
390
|
+
this.session = String(ctx.sessionManager?.getSessionId?.() ?? this.session);
|
|
391
|
+
this.event(kind, { file: this.file(), reason });
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** A user's switch, branch or tree move (EXT req. 31; PATCH-01 rules 6-7): cancelled while a hub command is
|
|
395
|
+
* applied, else marked changing until its after-event or 10 s, when the current session is reported. */
|
|
396
|
+
guard(ctx: Ctx): Json | undefined {
|
|
397
|
+
if (!this.main(ctx)) return;
|
|
398
|
+
if (this.applying > 0) {
|
|
399
|
+
safe(() => ctx?.ui?.notify?.("Cataly is applying a remote command; switch again in a moment.", "warning"));
|
|
400
|
+
return { cancel: true };
|
|
401
|
+
}
|
|
402
|
+
const mark = (this.changing = Date.now());
|
|
403
|
+
this.timer(() => {
|
|
404
|
+
if (this.changing !== mark) return;
|
|
405
|
+
this.changing = 0;
|
|
406
|
+
this.session = String(ctx?.sessionManager?.getSessionId?.() ?? this.session);
|
|
407
|
+
this.event("session_current", { file: this.file() });
|
|
408
|
+
}, CHANGE_MS, false);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** One hub command (EXT req. 25-31), answered with `bridge.reply`. A command for another
|
|
412
|
+
* session, or during a user's session change, is refused "not current" without calling OMP. */
|
|
413
|
+
async command(c: Json): Promise<void> {
|
|
414
|
+
const current = c.session === this.session && !this.changing;
|
|
415
|
+
this.applying += Number(current);
|
|
416
|
+
const out = current ? await this.run(c, this.ctx).catch(e => ({ refused: String(e?.message ?? e) })) : { refused: "not current" };
|
|
417
|
+
this.applying -= Number(current);
|
|
418
|
+
this.send("bridge.reply", { n: c.n, ...out });
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
async run(c: Json, ctx: Ctx): Promise<Json> {
|
|
422
|
+
const idle = Boolean(ctx?.isIdle?.());
|
|
423
|
+
if (c.op === "state") return { ...this.facts(ctx), session: this.session, file: this.file() };
|
|
424
|
+
if (c.op === "deliver") return this.deliver(c, idle);
|
|
425
|
+
if (c.op === "interrupt") return idle ? { idle: true } : (ctx.abort(), {});
|
|
426
|
+
if (c.op === "shutdown") return !idle && !c.force ? { refused: "busy: a turn is running" } : (ctx.shutdown(), {});
|
|
427
|
+
if (c.op === "model") {
|
|
428
|
+
if (!idle) return { refused: "a turn is running" };
|
|
429
|
+
const model = ctx.models.resolve(String(c.model));
|
|
430
|
+
if (!model) return { refused: `OMP does not know the model ${c.model}` };
|
|
431
|
+
if ((await this.pi.setModel(model)) === false) return { refused: "OMP did not set the model" };
|
|
432
|
+
return { model: modelOf(ctx) };
|
|
433
|
+
}
|
|
434
|
+
if (c.op === "goal") {
|
|
435
|
+
if (!ctx?.sessionModes) return { refused: "goal control needs OMP's TUI session modes" };
|
|
436
|
+
const done = await ctx.sessionModes.set({ mode: "goal", action: c.action, objective: c.objective } as Parameters<typeof ctx.sessionModes.set>[0]);
|
|
437
|
+
return done?.ok === false ? { refused: `${done.code}: ${done.message}` } : this.facts(ctx);
|
|
438
|
+
}
|
|
439
|
+
return { refused: `unknown command ${c.op}` };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Deliver (EXT req. 25, 29): a custom message carrying the delivery ID (wake), or a steer of
|
|
443
|
+
* the running turn; a repeated ID returns the first outcome without calling OMP again. */
|
|
444
|
+
async deliver(c: Json, idle: boolean): Promise<Json> {
|
|
445
|
+
const [id, text] = [String(c.id ?? ""), String(c.text ?? "")];
|
|
446
|
+
const key = `${c.mode}\n${text}`;
|
|
447
|
+
const seen = this.delivered.get(id);
|
|
448
|
+
if (seen) return seen.key === key ? seen.out : { refused: "this delivery ID came with other text" };
|
|
449
|
+
let out: Json = { sent: true };
|
|
450
|
+
if (c.mode !== "steer") {
|
|
451
|
+
const message = { customType: DELIVERY, content: text, display: true, details: { delivery: id } };
|
|
452
|
+
await this.pi.sendMessage(message, { triggerTurn: true, deliverAs: "followUp" });
|
|
453
|
+
} else if (idle) out = { refused: "no running turn to steer" };
|
|
454
|
+
else await this.pi.sendUserMessage(text, { deliverAs: "steer" });
|
|
455
|
+
this.delivered.set(id, { key, out });
|
|
456
|
+
if (this.delivered.size > IDS_KEPT) this.delivered.delete(this.delivered.keys().next().value ?? "");
|
|
457
|
+
return out;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Form interception (EXT req. 42): the hub may mirror the ask tool's questions; the local dialog
|
|
461
|
+
* stays usable, the first answer wins and the other is withdrawn. */
|
|
462
|
+
async form(e: ToolCallEvent, ctx: Ctx): Promise<ToolCallEventResult | undefined> {
|
|
463
|
+
const ask = ctx?.ui?.askDialog;
|
|
464
|
+
if (!this.main(ctx) || typeof ask !== "function") return;
|
|
465
|
+
const call = String(e.toolCallId ?? "");
|
|
466
|
+
const offer = await this.request("bridge.form", { session: this.session, call, input: e.input }, TOOL_MS);
|
|
467
|
+
if (!offer?.mirrored) return;
|
|
468
|
+
const local = new AbortController();
|
|
469
|
+
const forms = Promise.withResolvers<unknown>();
|
|
470
|
+
this.forms.set(call, forms.resolve);
|
|
471
|
+
const remote = forms.promise.then(answer => ({ by: "Discord", answer }));
|
|
472
|
+
const questions = (e.input as Json)?.questions as ExtensionAskDialogQuestion[];
|
|
473
|
+
const here = Promise.resolve(safe(() => ask.call(ctx.ui, questions, { signal: local.signal })))
|
|
474
|
+
.catch(() => undefined)
|
|
475
|
+
.then(answer => ({ by: "the terminal", answer }));
|
|
476
|
+
const won = await Promise.race([here, remote]);
|
|
477
|
+
this.forms.delete(call);
|
|
478
|
+
local.abort();
|
|
479
|
+
this.event("form_closed", { call, by: won.by });
|
|
480
|
+
if (won.answer === undefined) return { block: true, reason: "The user dismissed the question." };
|
|
481
|
+
return { block: true, reason: `The user answered (at ${won.by}): ${JSON.stringify(won.answer)}` };
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** Shell and spawn calls (EXT req. 32-35): the hub judges their facts; no answer blocks. */
|
|
485
|
+
async veto(e: ToolCallEvent, ctx: Ctx): Promise<ToolCallEventResult | undefined> {
|
|
486
|
+
const tool = String(e.toolName ?? "");
|
|
487
|
+
if (tool !== "bash" && tool !== "task") return undefined;
|
|
488
|
+
const file = this.file();
|
|
489
|
+
const saved = tool === "task" && file !== "" && (await Bun.file(file).exists());
|
|
490
|
+
const command = (e.input as Json | undefined)?.command;
|
|
491
|
+
const params = { session: this.session, agent: ctx?.agent?.id, call: e.toolCallId, tool, command, saved };
|
|
492
|
+
const answer = await this.request("bridge.shell", params, SHELL_MS);
|
|
493
|
+
if (answer?.allow) return undefined;
|
|
494
|
+
return { block: true, reason: String(answer?.reason || "No command ran: Cataly did not answer within 2 s. Report a blocker (kind waiting).") };
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** Model barrier (EXT req. 38-39): the hub judges what OMP runs; a hold or no answer aborts. */
|
|
498
|
+
async barrier(ctx: Ctx): Promise<void> {
|
|
499
|
+
if (!this.pin || ctx?.agent?.kind === "sub") return;
|
|
500
|
+
const thinking = safe(() => this.pi.getThinkingLevel?.());
|
|
501
|
+
const facts = { session: this.session, model: modelOf(ctx), thinking, fallback: this.fallbackTo };
|
|
502
|
+
const answer = await this.request("bridge.model", facts, SHELL_MS);
|
|
503
|
+
if (!answer?.allow) safe(() => ctx?.abort?.());
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** Appends the hub's guidance once to the prompt list OMP passes in (EXT req. 36). */
|
|
507
|
+
guide(e: BeforeAgentStartEvent, ctx: Ctx): BeforeAgentStartEventResult | undefined {
|
|
508
|
+
const prompt: unknown = e.systemPrompt;
|
|
509
|
+
if (!this.main(ctx) || !this.guidance || !Array.isArray(prompt) || prompt.includes(this.guidance)) return;
|
|
510
|
+
return prompt.every(b => typeof b === "string") ? { systemPrompt: [...prompt, this.guidance] } : undefined;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** Messages, with the delivery ID of a delivered custom message as its receipt (EXT req. 27). */
|
|
514
|
+
message(e: MessageEndEvent, ctx: Ctx): void {
|
|
515
|
+
if (!this.main(ctx)) return;
|
|
516
|
+
const ev = e as unknown as Json;
|
|
517
|
+
const m = (ev.message ?? ev) as Json;
|
|
518
|
+
const role = String(m.role ?? "");
|
|
519
|
+
if (role !== "user" && role !== "assistant" && !(role === "custom" && m.display)) return;
|
|
520
|
+
const all = textOf(m.content);
|
|
521
|
+
const visible = { text: all.slice(0, TEXT_CUT), truncated: all.length > TEXT_CUT };
|
|
522
|
+
const stop = m.stopReason as string | undefined;
|
|
523
|
+
if (role === "assistant") this.lastAnswer = visible.text.trim() !== "" && stop === "stop";
|
|
524
|
+
const delivery = (m.details as Json | undefined)?.delivery;
|
|
525
|
+
const receipt = delivery ? { delivery, file: this.file() } : {};
|
|
526
|
+
this.event("message_end", { role, ...visible, stop, entry: ev.entryId ?? m.id, at: m.timestamp, ...receipt });
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
toolStart(e: ToolExecutionStartEvent, ctx: Ctx): void {
|
|
530
|
+
if (!this.main(ctx)) return;
|
|
531
|
+
const id = String(e.toolCallId ?? "");
|
|
532
|
+
const tool = String(e.toolName ?? "");
|
|
533
|
+
const seen = this.calls.get(id);
|
|
534
|
+
const command = tool === "bash" ? String((e.args as Json | undefined)?.command ?? "").slice(0, TEXT_CUT) : undefined;
|
|
535
|
+
if (seen) seen.starts += 1;
|
|
536
|
+
else this.calls.set(id, { tool, cwd: String(ctx.cwd ?? ""), starts: 1, command });
|
|
537
|
+
if (this.calls.size > CALLS_KEPT) this.calls.delete(this.calls.keys().next().value ?? "");
|
|
538
|
+
this.event("tool_execution_start", { call: id, tool, cwd: ctx.cwd });
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
toolEnd(e: ToolExecutionEndEvent, ctx: Ctx): void {
|
|
542
|
+
if (!this.main(ctx)) return;
|
|
543
|
+
const id = String(e.toolCallId ?? "");
|
|
544
|
+
const call = this.calls.get(id);
|
|
545
|
+
const result = e.result as Json | undefined;
|
|
546
|
+
if (call) [call.error, call.fingerprint] = [Boolean(e.isError), fingerprint(call.tool, result)];
|
|
547
|
+
const job = (result?.details as Json | undefined)?.jobId;
|
|
548
|
+
this.event("tool_execution_end", { call: id, tool: e.toolName, error: Boolean(e.isError), job });
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** Facts for the calls a tool names in `calls` (EXT req. 21-22); the hub judges them. */
|
|
552
|
+
evidence(params: Json): Json[] | undefined {
|
|
553
|
+
if (!Array.isArray(params?.calls)) return undefined;
|
|
554
|
+
return params.calls.slice(0, 64).map(raw => {
|
|
555
|
+
const call = this.calls.get(String(raw));
|
|
556
|
+
return call ? { call: String(raw), seen: true, ...call, ambiguous: call.starts > 1 } : { call: String(raw), seen: false };
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/** Forwards one tool call and returns the hub's text unchanged (EXT req. 18). */
|
|
561
|
+
async tool(name: string, ms: number, callId: string, params: Json, ctx: Ctx): Promise<AgentToolResult> {
|
|
562
|
+
if (!this.main(ctx)) throw new Error(`${name} is not available in this session.`);
|
|
563
|
+
const call = { session: this.session, agent: ctx?.agent?.id, call: callId, tool: name, input: params };
|
|
564
|
+
const answer = await this.request("bridge.tool", { ...call, evidence: this.evidence(params) }, ms);
|
|
565
|
+
if (!answer) throw new Error(`Cataly did not answer in time: ${UNSURE}`);
|
|
566
|
+
const text = String(answer.text ?? "");
|
|
567
|
+
if (answer.error) throw new Error(text);
|
|
568
|
+
return { content: [{ type: "text", text }] };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** Stop gate (EXT req. 41): continue once with the hub's reminder; otherwise stop. */
|
|
572
|
+
async stop(ctx: Ctx): Promise<SessionStopEventResult | undefined> {
|
|
573
|
+
if (!this.main(ctx) || this.role !== "lead") return undefined;
|
|
574
|
+
const answer = await this.request("bridge.stop", { session: this.session, answered: this.lastAnswer }, STOP_MS);
|
|
575
|
+
this.lastAnswer = false;
|
|
576
|
+
const context = answer?.context;
|
|
577
|
+
return typeof context === "string" && context ? { continue: true, additionalContext: context } : undefined;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async shutdown(ctx: Ctx): Promise<void> {
|
|
581
|
+
if (ctx?.agent?.kind === "sub" && !this.parent) return; // a subagent's own bridge closes for it
|
|
582
|
+
if (!this.parent) this.event("session_shutdown");
|
|
583
|
+
this.shutting = true;
|
|
584
|
+
if (this.wire) await Bun.sleep(SHUTDOWN_MS / 10);
|
|
585
|
+
void (this.wire?.close(), (this.wire = undefined));
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** The factory: two handlers, nothing else, until the hub accepts the session (EXT req. 1). */
|
|
590
|
+
export function bridge(pi: Pi, deps: Deps): Bridge {
|
|
591
|
+
const b = new Bridge(pi, deps);
|
|
592
|
+
pi.on("session_start", (_e, ctx) => b.consider(ctx));
|
|
593
|
+
pi.on("session_switch", (e, ctx) => b.consider(ctx, { reason: e.reason }));
|
|
594
|
+
return b;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
export default function cataly(pi: Pi): void {
|
|
598
|
+
bridge(pi, { env: process.env, connect: unixConnect, uid: () => process.getuid?.() ?? 0 });
|
|
599
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cataly-linux-x64",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "The Cataly binary and OMP extension for Linux x64; install the cataly package",
|
|
5
|
+
"license": "AGPL-3.0-only",
|
|
6
|
+
"homepage": "https://github.com/vntrevx/Cataly",
|
|
7
|
+
"os": [
|
|
8
|
+
"linux"
|
|
9
|
+
],
|
|
10
|
+
"cpu": [
|
|
11
|
+
"x64"
|
|
12
|
+
],
|
|
13
|
+
"libc": [
|
|
14
|
+
"glibc"
|
|
15
|
+
],
|
|
16
|
+
"files": [
|
|
17
|
+
"cataly",
|
|
18
|
+
"cataly.ts",
|
|
19
|
+
"LICENSE",
|
|
20
|
+
"THIRD-PARTY-NOTICES.txt"
|
|
21
|
+
],
|
|
22
|
+
"preferUnplugged": true
|
|
23
|
+
}
|
package/README.md
DELETED