@aiti-ai/aiti-omp-agent 0.0.0-stage → 0.1.7

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.

Potentially problematic release.


This version of @aiti-ai/aiti-omp-agent might be problematic. Click here for more details.

@@ -0,0 +1,367 @@
1
+ /**
2
+ * wire.ts — JSONL RPC 线协议宿主(载体无关)。
3
+ *
4
+ * 拆自 aiti-pi-agent 的 pi-rpc-spawn.ts:子进程管理 / request-response id 关联 /
5
+ * 事件扇出 / 死亡上报 + extension_ui_request ⇄ interaction_request 帧桥接。
6
+ * 本层**不含任何 fork 语义**(命令映射 / 能力面 / 生命周期收口由各扩展 handle 负责)。
7
+ */
8
+
9
+ import type { ChildProcess } from "node:child_process";
10
+ import { StringDecoder } from "node:string_decoder";
11
+
12
+ /** 缺省单行字节上限(MCP stdio transport 同款 10MB):无换行的超长行视为子进程失控。 */
13
+ export const DEFAULT_MAX_LINE_BYTES = 10 * 1024 * 1024;
14
+
15
+ /** 控制面命令缺省超时(get_state/set_model/… 等快命令;prompt/compact/bash 等长轮次命令不设)。 */
16
+ export const RPC_CTRL_TIMEOUT_MS = 30_000;
17
+
18
+ export interface LineReaderOptions {
19
+ /** 单行字节上限(换行前累积量),超出触发 onOverflow 并停止处理后续数据。缺省 10MB。 */
20
+ maxLineBytes?: number;
21
+ /** 行超限回调(宿主侧应 markDead——协议流已不可信)。 */
22
+ onOverflow?: (size: number) => void;
23
+ }
24
+
25
+ /**
26
+ * 逐行读取 stdout 流(JSONL);返回取消函数。
27
+ * 字节累积、按 `\n` 切 Buffer 后整行 utf8 解码(MCP ReadBuffer 同款)——
28
+ * 逐 chunk `Buffer.toString` 会把跨 chunk 的多字节字符解码成 U+FFFD(中文必踩)。
29
+ */
30
+ export function lineReader(
31
+ stream: NodeJS.ReadableStream,
32
+ onLine: (line: string) => void,
33
+ opts?: LineReaderOptions,
34
+ ): () => void {
35
+ const maxLineBytes = opts?.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;
36
+ const onOverflow = opts?.onOverflow;
37
+ let buf: Buffer = Buffer.alloc(0);
38
+ let overflowed = false;
39
+ const onData = (c: Buffer | string) => {
40
+ if (overflowed) return;
41
+ const chunk = typeof c === "string" ? Buffer.from(c, "utf8") : c;
42
+ buf = buf.length === 0 ? chunk : Buffer.concat([buf, chunk]);
43
+ let idx: number;
44
+ while ((idx = buf.indexOf(0x0a)) >= 0) {
45
+ const line = buf.subarray(0, idx).toString("utf8").trim();
46
+ buf = buf.subarray(idx + 1);
47
+ if (line) onLine(line);
48
+ }
49
+ if (buf.length > maxLineBytes) {
50
+ overflowed = true;
51
+ onOverflow?.(buf.length);
52
+ }
53
+ };
54
+ stream.on("data", onData);
55
+ return () => {
56
+ stream.off("data", onData);
57
+ };
58
+ }
59
+
60
+ export type HostEventListener = (event: Record<string, unknown>) => void;
61
+
62
+ interface PendingRequest {
63
+ resolve(v: unknown): void;
64
+ reject(e: Error): void;
65
+ timer?: NodeJS.Timeout;
66
+ }
67
+
68
+ /**
69
+ * 载体无关的 RPC 子进程宿主:
70
+ * - 进程管理(stdin 写帧 / stdout 逐行读 / stderr 日志 / exit·error 杀尾)
71
+ * - request id 关联(command 附带 `id`,`response` 帧按 id 回拨;控制面命令可带超时)
72
+ * - 事件扇出(非 response 帧 → onFrame 分发给子类 → emit 给监听者;逐监听器异常隔离)
73
+ * - 死亡上报(session_backend_dead)
74
+ *
75
+ * 子类通过覆写 onFrame 注入语义(extension_ui / host_tool / ready 握手 / 状态帧…),
76
+ * 通过 protected request / writeRaw 发命令。
77
+ */
78
+ export class RpcChildHost {
79
+ protected child: ChildProcess;
80
+ protected pending = new Map<string, PendingRequest>();
81
+ protected seq = 0;
82
+ protected aliveFlag = true;
83
+ private listeners = new Set<HostEventListener>();
84
+ private detachReader: (() => void) | null = null;
85
+
86
+ constructor(child: ChildProcess, opts?: { maxLineBytes?: number }) {
87
+ this.child = child;
88
+ this.detachReader = lineReader(child.stdout!, (line) => this.dispatchLine(line), {
89
+ ...(opts?.maxLineBytes ? { maxLineBytes: opts.maxLineBytes } : {}),
90
+ onOverflow: (size) => this.markDead(`stdout line overflow (${size} bytes > ${opts?.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES})`),
91
+ });
92
+ const stderrDecoder = new StringDecoder("utf8");
93
+ child.stderr?.on("data", (c: Buffer | string) => {
94
+ const text = (typeof c === "string" ? c : stderrDecoder.write(c)).trim();
95
+ if (text) console.log(`[rpc-child] ${text.slice(0, 500)}`);
96
+ });
97
+ // 三个流都必须挂 error 监听:子进程被杀/管道断裂时流上抛 ECONNRESET/EPIPE,
98
+ // 没有监听器 = unhandled 'error' event = 宿主进程崩溃(MCP stdio transport 同款防御)。
99
+ child.stdout?.on("error", (err: Error) => this.markDead(`stdout error: ${err.message}`));
100
+ child.stderr?.on("error", (err: Error) => console.log(`[rpc-child] stderr error: ${err.message}`));
101
+ child.stdin?.on("error", (err: Error) => console.log(`[rpc-child] stdin error: ${err.message}`));
102
+ child.once("exit", (code) => this.markDead(`process exited (${code ?? "signal"})`));
103
+ child.once("error", (err) => this.markDead(`process error: ${err.message}`));
104
+ }
105
+
106
+ emit(event: Record<string, unknown>): void {
107
+ for (const l of this.listeners) {
108
+ try {
109
+ l(event);
110
+ } catch (e) {
111
+ // 逐监听器隔离:一个订阅者抛错不得漏帧给其余订阅者,更不得沿流 data 回调裸抛崩进程
112
+ console.error(`[rpc-child] listener error: ${e instanceof Error ? e.message : String(e)}`);
113
+ }
114
+ }
115
+ }
116
+
117
+ subscribe(listener: HostEventListener): () => void {
118
+ this.listeners.add(listener);
119
+ return () => {
120
+ this.listeners.delete(listener);
121
+ };
122
+ }
123
+
124
+ /** 发命令并挂 id 关联(写 stdin;帧的 id 由本方法追加,勿重复传)。
125
+ * opts.timeoutMs:可选超时(控制面快命令用;prompt/compact/bash 等长轮次命令不设——
126
+ * 超时仅解除 pending 并 reject,不影响子进程继续跑)。 */
127
+ protected request<T = unknown>(command: Record<string, unknown>, opts?: { timeoutMs?: number }): Promise<T> {
128
+ if (!this.aliveFlag || !this.child.stdin?.writable) {
129
+ return Promise.reject(new Error("[rpc-child] not running"));
130
+ }
131
+ const id = `r${++this.seq}`;
132
+ return new Promise<T>((resolve, reject) => {
133
+ const pending: PendingRequest = { resolve: resolve as (v: unknown) => void, reject };
134
+ const timeoutMs = opts?.timeoutMs;
135
+ if (timeoutMs && timeoutMs > 0) {
136
+ const timer = setTimeout(() => {
137
+ this.pending.delete(id);
138
+ reject(new Error(`[rpc-child] timeout: ${String(command.type ?? "?")} after ${timeoutMs}ms`));
139
+ }, timeoutMs);
140
+ timer.unref?.();
141
+ pending.timer = timer;
142
+ }
143
+ this.pending.set(id, pending);
144
+ try {
145
+ this.child.stdin!.write(JSON.stringify({ ...command, id }) + "\n");
146
+ } catch (e) {
147
+ this.pending.delete(id);
148
+ if (pending.timer) clearTimeout(pending.timer);
149
+ reject(new Error(`[rpc-child] write failed: ${e instanceof Error ? e.message : String(e)}`));
150
+ }
151
+ });
152
+ }
153
+
154
+ /** 原样写帧(不回显追加 request id)——host_tool_result 等须回显请求帧的 id。 */
155
+ protected writeRaw(frame: Record<string, unknown>): void {
156
+ if (!this.aliveFlag || !this.child.stdin?.writable) return;
157
+ try {
158
+ this.child.stdin.write(JSON.stringify(frame) + "\n");
159
+ } catch {
160
+ // 写失败(子进程刚死):exit 事件会收尸 markDead
161
+ }
162
+ }
163
+
164
+ /** 行分发:response 按 id 回拨;其余交给子类 onFrame。 */
165
+ protected dispatchLine(line: string): void {
166
+ let msg: Record<string, unknown>;
167
+ try {
168
+ msg = JSON.parse(line) as Record<string, unknown>;
169
+ } catch {
170
+ return;
171
+ }
172
+ if (msg.type === "response" && typeof msg.id === "string") {
173
+ const p = this.pending.get(msg.id);
174
+ if (!p) return;
175
+ this.pending.delete(msg.id);
176
+ if (p.timer) clearTimeout(p.timer);
177
+ if (msg.success === true) p.resolve(msg.data);
178
+ else p.reject(new Error(String(msg.error ?? "request failed")));
179
+ return;
180
+ }
181
+ try {
182
+ this.onFrame(msg);
183
+ } catch (e) {
184
+ // 子类 onFrame 异常同样不得沿流 data 回调裸抛(emit 已隔离,此处兜子类自身逻辑)
185
+ console.error(`[rpc-child] onFrame error: ${e instanceof Error ? e.message : String(e)}`);
186
+ }
187
+ }
188
+
189
+ /** 子类覆写:非 response 帧的语义分发(默认原样透传 emit)。 */
190
+ protected onFrame(_msg: Record<string, unknown>): void {
191
+ this.emit(_msg);
192
+ }
193
+
194
+ protected markDead(reason: string): void {
195
+ if (!this.aliveFlag) return;
196
+ this.aliveFlag = false;
197
+ this.detachReader?.();
198
+ this.detachReader = null;
199
+ for (const p of this.pending.values()) {
200
+ if (p.timer) clearTimeout(p.timer);
201
+ p.reject(new Error(`[rpc-child] dead: ${reason}`));
202
+ }
203
+ this.pending.clear();
204
+ this.emit({ type: "session_backend_dead", reason });
205
+ }
206
+ }
207
+
208
+ // ============================================================================
209
+ // 子进程收尾(dispose 共用)
210
+ // ============================================================================
211
+
212
+ /** 子进程收尾:SIGTERM → graceMs(缺省 1s)→ SIGKILL → destroy 三流(释放句柄/事件循环;
213
+ * MCP stdio transport 同款阶梯 + 清理)。已死进程直接跳过信号、仅清流。幂等可重入。 */
214
+ export async function shutdownChild(child: ChildProcess, graceMs = 1_000): Promise<void> {
215
+ if (child.exitCode === null && child.signalCode === null) {
216
+ try { child.kill("SIGTERM"); } catch { /* 已死容错 */ }
217
+ await new Promise<void>((resolve) => {
218
+ const t = setTimeout(() => {
219
+ try { child.kill("SIGKILL"); } catch { /* 已死容错 */ }
220
+ resolve();
221
+ }, graceMs);
222
+ child.once("exit", () => {
223
+ clearTimeout(t);
224
+ resolve();
225
+ });
226
+ });
227
+ }
228
+ child.stdout?.destroy();
229
+ child.stderr?.destroy();
230
+ child.stdin?.destroy();
231
+ }
232
+
233
+ // ============================================================================
234
+ // extension_ui_request ⇄ interaction_request 桥接(通用帧转换,无 fork 语义)
235
+ // ============================================================================
236
+
237
+ /** fork 子进程 extension_ui_request 帧(select/confirm/input/editor/notify/...)。 */
238
+ export interface ExtensionUIRequest extends Record<string, unknown> {
239
+ type: "extension_ui_request";
240
+ id: string;
241
+ method: string;
242
+ }
243
+
244
+ /** 需要用户作答、要挂 pending 等响应的 UI 方法(其余为单向通知,透传即可)。 */
245
+ export const UI_METHODS_NEEDING_ANSWER = new Set(["select", "confirm", "input", "editor"]);
246
+
247
+ /**
248
+ * 把 extension_ui_request 投影为 pi-web 统一 interaction_request 事件
249
+ * (lib/session/types.ts InteractionRequestEvent)。
250
+ * select/confirm/input → kind "ask_user"(标准问题卡渲染);
251
+ * open_url → kind "open_url"(OAuth 登录专用卡:url/launchUrl 字段,单向无需作答);
252
+ * 其余(editor/notify/setStatus/...)→ kind "generic"(原始帧进 input)。
253
+ */
254
+ export function toInteractionRequest(req: ExtensionUIRequest): Record<string, unknown> {
255
+ const method = req.method;
256
+ if (method === "open_url") {
257
+ // fork 真实帧:{url, launchUrl, instructions}(instructions = 给用户的操作说明)
258
+ const promptText = [req.title, req.instructions].find((s) => typeof s === "string");
259
+ return {
260
+ type: "interaction_request",
261
+ requestId: req.id,
262
+ kind: "open_url",
263
+ toolName: "extension_ui.open_url",
264
+ ...(promptText ? { prompt: promptText } : {}),
265
+ ...(typeof req.url === "string" ? { url: req.url } : {}),
266
+ ...(typeof req.launchUrl === "string" ? { launchUrl: req.launchUrl } : {}),
267
+ input: req,
268
+ };
269
+ }
270
+ if (method === "select") {
271
+ const options = Array.isArray(req.options) ? req.options : [];
272
+ const details = Array.isArray(req.optionDetails) ? req.optionDetails : [];
273
+ return {
274
+ type: "interaction_request",
275
+ requestId: req.id,
276
+ kind: "ask_user",
277
+ toolName: "extension_ui.select",
278
+ prompt: typeof req.title === "string" ? req.title : undefined,
279
+ questions: [
280
+ {
281
+ question: typeof req.title === "string" ? req.title : "Select an option",
282
+ options: options.map((o, i) => ({
283
+ label: String(o),
284
+ ...(typeof (details[i] as { description?: unknown })?.description === "string"
285
+ ? { description: (details[i] as { description: string }).description }
286
+ : {}),
287
+ })),
288
+ },
289
+ ],
290
+ input: req,
291
+ };
292
+ }
293
+ if (method === "confirm") {
294
+ return {
295
+ type: "interaction_request",
296
+ requestId: req.id,
297
+ kind: "ask_user",
298
+ toolName: "extension_ui.confirm",
299
+ prompt: typeof req.title === "string" ? req.title : undefined,
300
+ questions: [
301
+ {
302
+ question: [req.title, req.message].filter((s) => typeof s === "string").join("\n") || "Confirm?",
303
+ options: [{ label: "确认" }, { label: "取消" }],
304
+ },
305
+ ],
306
+ input: req,
307
+ };
308
+ }
309
+ if (method === "input") {
310
+ return {
311
+ type: "interaction_request",
312
+ requestId: req.id,
313
+ kind: "ask_user",
314
+ toolName: "extension_ui.input",
315
+ prompt: typeof req.title === "string" ? req.title : undefined,
316
+ questions: [{ question: typeof req.title === "string" ? req.title : "Input" }],
317
+ input: req,
318
+ };
319
+ }
320
+ return {
321
+ type: "interaction_request",
322
+ requestId: req.id,
323
+ kind: "generic",
324
+ toolName: `extension_ui.${method}`,
325
+ input: req,
326
+ };
327
+ }
328
+
329
+ /**
330
+ * 把用户作答(InteractionAnswer)编回 extension_ui_response 帧
331
+ * (omp RpcExtensionUIResponse:{value} | {confirmed} | {cancelled:true})。
332
+ * 返回 null 表示该请求无需作答(单向通知类)。
333
+ */
334
+ export function toExtensionUIResponse(
335
+ req: ExtensionUIRequest,
336
+ answer: { action: "accept" | "decline"; answers?: Record<string, string | string[]>; message?: string },
337
+ ): Record<string, unknown> | null {
338
+ const method = req.method;
339
+ if (method === "select") {
340
+ if (answer.action === "decline") return { type: "extension_ui_response", id: req.id, cancelled: true };
341
+ const q = typeof req.title === "string" ? req.title : "Select an option";
342
+ const v = answer.answers?.[q];
343
+ return v === undefined
344
+ ? { type: "extension_ui_response", id: req.id, cancelled: true }
345
+ : { type: "extension_ui_response", id: req.id, value: Array.isArray(v) ? v[0] : v };
346
+ }
347
+ if (method === "input" || method === "editor") {
348
+ if (answer.action === "decline") return { type: "extension_ui_response", id: req.id, cancelled: true };
349
+ const q = typeof req.title === "string" ? req.title : method === "input" ? "Input" : "";
350
+ const v = answer.answers?.[q];
351
+ const value = (Array.isArray(v) ? v[0] : v) ?? answer.message ?? "";
352
+ return { type: "extension_ui_response", id: req.id, value };
353
+ }
354
+ if (method === "confirm") {
355
+ if (answer.action === "decline") return { type: "extension_ui_response", id: req.id, cancelled: true };
356
+ // select 卡渲染的确认/取消:按所选 label 判断;accept + 未选「取消」= confirmed
357
+ const q = [req.title, req.message].filter((s) => typeof s === "string").join("\n") || "Confirm?";
358
+ const v = answer.answers?.[q];
359
+ const picked = Array.isArray(v) ? v[0] : v;
360
+ // 防御(fail-closed):answers 非空但未命中问题 key(title 渲染漂移等)→ 视为未确认;
361
+ // 完全无 answers(前端批准按钮路径)保持 confirmed:true,不破坏既有契约。
362
+ const hasAnswers = !!answer.answers && Object.keys(answer.answers).length > 0;
363
+ const confirmed = picked !== undefined ? picked !== "取消" : !hasAnswers;
364
+ return { type: "extension_ui_response", id: req.id, confirmed };
365
+ }
366
+ return null; // notify/setStatus/setWidget/setTitle/open_url/... 单向,无需响应
367
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * P2 host tools 桥接线:把本实例桥(aiti-devtools MCP)的 `aiti_*` 工具注册为
3
+ * omp 宿主工具(set_host_tools)。agent 调用 → host_tool_call 帧 → 本模块经
4
+ * HTTP tools/call 透传给桥 → 结果文本回 host_tool_result。
5
+ *
6
+ * 失败策略:桥不可达 / 无工具 / 注册失败一律静默降级——omp 会话照常可用,
7
+ * 只是少一批 aiti_* 工具(console 记一行)。
8
+ *
9
+ * 拆分自 aiti-pi-agent 的 host-tools-bridge.ts(omp 独有能力)。
10
+ */
11
+
12
+ import { bridgeEnv } from "@aiti-ai/ext-shared/agent-spawn-env";
13
+ import { filterHostToolsByAllow, parseHostToolsAllow, readHostToolsAllow } from "@aiti-ai/ext-shared/host-tools-allow";
14
+ import type { HostToolDefinition } from "./fork-rpc/spec.ts";
15
+
16
+ interface McpTool {
17
+ name: string;
18
+ description?: string;
19
+ inputSchema?: Record<string, unknown>;
20
+ }
21
+
22
+ function mcpEndpoint(): string {
23
+ // 显式 AITI_BRIDGE_URL 优先(测试/特殊部署);缺省按 pi-web 自身实例推导(与 spawn 注入同源)。
24
+ const explicit = process.env.AITI_BRIDGE_URL;
25
+ if (explicit) return `${explicit.replace(/\/+$/, "")}/mcp/mcp`;
26
+ return `${bridgeEnv().AITI_BRIDGE_URL}/mcp/mcp`;
27
+ }
28
+
29
+ async function mcpRpc(method: string, params?: Record<string, unknown>, id: number | string = 1, signal?: AbortSignal): Promise<Record<string, unknown> | undefined> {
30
+ const response = await fetch(mcpEndpoint(), {
31
+ method: "POST",
32
+ headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
33
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, ...(params ? { params } : {}) }),
34
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(15_000),
35
+ });
36
+ if (!response.ok) throw new Error(`bridge MCP ${method} -> HTTP ${response.status}`);
37
+ const contentType = response.headers.get("content-type") ?? "";
38
+ const raw = await response.text();
39
+ let payload: string = raw;
40
+ if (contentType.includes("text/event-stream")) {
41
+ // streamable HTTP 可能回 SSE 帧——取最后一条 data: JSON 行
42
+ const lines = raw.split("\n").filter((line) => line.startsWith("data:"));
43
+ payload = lines.length ? lines[lines.length - 1].slice(5).trim() : "";
44
+ }
45
+ if (!payload) return undefined;
46
+ const parsed = JSON.parse(payload) as { result?: Record<string, unknown>; error?: { message?: string } };
47
+ if (parsed.error) throw new Error(parsed.error.message ?? `bridge MCP ${method} error`);
48
+ return parsed.result;
49
+ }
50
+
51
+ /** 拉取桥 MCP 工具清单并注册为宿主工具;返回注册成功的工具名(失败返回空数组)。 */
52
+ export async function wireBridgeHostTools(handle: {
53
+ setHostTools(tools: HostToolDefinition[]): Promise<string[]>;
54
+ }): Promise<string[]> {
55
+ let seq = 10;
56
+ try {
57
+ const result = await mcpRpc("tools/list");
58
+ const all = Array.isArray(result?.tools) ? (result!.tools as McpTool[]) : [];
59
+ // G1 白名单(docs/pi-web-ext-host-tools-gate-plan.md §G1):缺省只读子集;feature `hostToolsAllow`=* 恢复全量
60
+ const allow = parseHostToolsAllow(readHostToolsAllow("aiti-omp-agent"));
61
+ const tools = filterHostToolsByAllow(all, allow);
62
+ if (!tools.length) return [];
63
+ if (tools.length !== all.length) {
64
+ console.log(`[aiti-omp-agent] G1 host tools allow=${allow === "all" ? "*" : allow === "readonly" ? "readonly" : "custom"}: ${tools.length}/${all.length} wired`);
65
+ }
66
+ const definitions: HostToolDefinition[] = tools.map((tool) => ({
67
+ name: tool.name,
68
+ description: tool.description ?? tool.name,
69
+ parameters: tool.inputSchema && typeof tool.inputSchema === "object" ? tool.inputSchema : { type: "object", properties: {} },
70
+ async execute(args, signal) {
71
+ const callResult = await mcpRpc("tools/call", { name: tool.name, arguments: args }, ++seq, signal);
72
+ const content = Array.isArray(callResult?.content) ? callResult!.content as Array<{ type?: string; text?: string }> : [];
73
+ const text = content
74
+ .filter((item) => !item.type || item.type === "text")
75
+ .map((item) => item.text ?? "")
76
+ .join("\n")
77
+ .trim();
78
+ if (!text) throw new Error(`Host tool ${tool.name} returned no text output.`);
79
+ return text;
80
+ },
81
+ }));
82
+ const accepted = await handle.setHostTools(definitions);
83
+ if (accepted.length) console.log(`[aiti-omp-agent] omp host tools wired: ${accepted.length} aiti tools`);
84
+ return accepted;
85
+ } catch (caught) {
86
+ console.log(`[aiti-omp-agent] omp host tools unavailable: ${caught instanceof Error ? caught.message : caught}`);
87
+ return [];
88
+ }
89
+ }
package/index.ts ADDED
@@ -0,0 +1,128 @@
1
+ /**
2
+ * aiti-omp-agent — omp(oh-my-pi)fork RPC spawn 后端(拆分自 aiti-pi-agent,专一 omp)。
3
+ *
4
+ * 每个会话 = 一个独立 `omp --mode rpc` 子进程(bun 解释)。omp 是 pi 的超集 fork:
5
+ * ready 握手 / get_state(contextUsage·dumpTools·sessionId·sessionFile)/ get_messages /
6
+ * branch / host tools(set_host_tools·host_tool_call)/ login(get_login_providers·login)。
7
+ * 引擎(线协议宿主 / spec / CLI 解析)来自共享层 fork-rpc/;omp 语义在 omp-handle.ts。
8
+ *
9
+ * omp-spawn order=30 "Oh My Pi (omp.sh)" (bun 解释 omp,未装时注册照常、
10
+ * createSession 报清晰安装指引)
11
+ */
12
+
13
+ import { join } from "node:path";
14
+ import { OmpSpawnHandle, OMP_SPEC } from "./omp-handle.ts";
15
+ import { capabilitiesFor } from "./fork-rpc/spec.ts";
16
+ import { resolveForkCli } from "./fork-rpc/cli-resolve.ts";
17
+ import { spawnEnvFeature, spawnCommandFeature, spawnArgsPrefixFeature, captureSpawnEnvFeatures } from "@aiti-ai/ext-shared/agent-spawn-env";
18
+ import { hostToolsAllowFeature } from "@aiti-ai/ext-shared/host-tools-allow";
19
+ import type { LaunchOverride } from "@aiti-ai/ext-shared/agent-spawn-env";
20
+ import { createSessionRecycleApi } from "@aiti-ai/ext-shared/session-recycle";
21
+ import { wireBridgeHostTools } from "./host-tools-bridge.ts";
22
+
23
+ interface SessionCapabilitiesLike extends Record<string, boolean> {}
24
+
25
+ /** 会话 recycle(D8):存量 OmpSpawnHandle 升级到当前扩展代码。
26
+ * ⚠ omp 无 --session-id,重建即新会话(记档 id 保留;仅 dispose 语义)。 */
27
+ let recycleApi: ReturnType<typeof createSessionRecycleApi> | null = null;
28
+
29
+ export default {
30
+ id: "aiti-omp-agent",
31
+ name: "Oh My Pi (omp 子进程后端)",
32
+ version: "0.1.0",
33
+ icon: "🦉",
34
+
35
+ features: [spawnEnvFeature("Omp"), spawnCommandFeature("Omp"), spawnArgsPrefixFeature("Omp"), hostToolsAllowFeature("Omp")],
36
+
37
+ server: {
38
+ startup(ctx: {
39
+ /** 跨扩展服务 slot(P2 协议委托;缺省=旧宿主降级)。 */
40
+ services?: { provide<T>(key: string, impl: T): () => void };
41
+ /** A03/B4:宿主 core(rebindSessionBackend 换绑通道;旧宿主缺席降级)。 */
42
+ core?: { rebindSessionBackend?: (oldId: string, newId: string) => boolean };
43
+ sessionProviders: {
44
+ register(provider: {
45
+ type: string;
46
+ label: string;
47
+ order?: number;
48
+ agentKey?: string;
49
+ maxCapabilities: SessionCapabilitiesLike;
50
+ createSession(options: {
51
+ sessionId?: string;
52
+ cwd?: string;
53
+ model?: { provider: string; id: string };
54
+ env?: Record<string, string>;
55
+ }): Promise<OmpSpawnHandle>;
56
+ }): string;
57
+ };
58
+ }) {
59
+ captureSpawnEnvFeatures((ctx as any)?.features ?? null); // D1:spawn.env feature 捕获
60
+ const spec = OMP_SPEC;
61
+ // P2 host tools:omp 会话 ready 后把桥的 aiti_* 工具注册为宿主工具(失败静默降级)。
62
+ const withHostTools = (h: OmpSpawnHandle): OmpSpawnHandle => {
63
+ if (h.spec.commands.hasHostTools) {
64
+ void h.whenReady.then(() => wireBridgeHostTools(h)).catch(() => {});
65
+ }
66
+ return h;
67
+ };
68
+ // B4 换绑(docs/aiti-omp-agent-id-rebind-design.md):omp 进程生成真实落盘 id,
69
+ // get_state 读回(rpcSessionId)后为 handle 增挂别名键——recycle/resume 用真 id。
70
+ // 时序约束:prompt 受理前的就绪窗口内完成;未读回/宿主不支持 → 维持占位语义(现状)。
71
+ const wireB4Rebind = (
72
+ hPromise: Promise<OmpSpawnHandle>,
73
+ options: { sessionId?: string },
74
+ ): Promise<OmpSpawnHandle> => {
75
+ void (async () => {
76
+ try {
77
+ const handle = await hPromise;
78
+ if (!ctx.core?.rebindSessionBackend) {
79
+ console.log("[aiti-omp-agent] B4 rebind skipped:宿主 core 无 rebindSessionBackend(旧宿主)");
80
+ return;
81
+ }
82
+ for (let i = 0; i < 40 && !handle.rpcSessionId; i++) {
83
+ await new Promise((r) => setTimeout(r, 500));
84
+ }
85
+ const recordId = (options.sessionId ?? "").trim() || handle.id; // 宿主未下传时 = 适配器自生成的记档 id
86
+ const realId = handle.rpcSessionId;
87
+ if (!recordId || !realId || realId === recordId) {
88
+ console.log(`[aiti-omp-agent] B4 rebind skip:record=${recordId ? "有" : "无"} real=${realId ? "有" : "无"}`);
89
+ return;
90
+ }
91
+ const ok = ctx.core.rebindSessionBackend(recordId, realId);
92
+ console.log(`[aiti-omp-agent] B4 rebind ${recordId.slice(0, 8)}… → ${realId.slice(0, 8)}…: ${ok}`);
93
+ if (ok) {
94
+ try { (globalThis as any).__piPageEvents?.publish("aiti-omp-agent:rebind", { from: recordId, to: realId }); } catch { /* 总线缺席:draft 行自然过期 */ }
95
+ }
96
+ } catch (e: any) {
97
+ console.log("[aiti-omp-agent] B4 rebind error:", String(e?.message ?? e).slice(0, 120));
98
+ }
99
+ })();
100
+ return hPromise;
101
+ };
102
+ ctx.sessionProviders.register({
103
+ type: `${spec.id}-spawn`,
104
+ label: spec.label,
105
+ order: spec.order,
106
+ agentKey: spec.agentKey,
107
+ maxCapabilities: capabilitiesFor(spec),
108
+ createSession: (options) => wireB4Rebind(OmpSpawnHandle.start(options, spec).then(withHostTools), options),
109
+ });
110
+ // P2 协议委托:launch 服务(omp 单 fork)。
111
+ ctx.services?.provide?.("aiti-omp-agent.launch", {
112
+ agentKey: "omp",
113
+ capabilities: capabilitiesFor(spec),
114
+ members: [{ name: spec.id, label: spec.label }],
115
+ createSessionFromLaunch: (launch: LaunchOverride, options: { sessionId?: string; cwd?: string; env?: Record<string, string> }) => {
116
+ return wireB4Rebind(OmpSpawnHandle.start({ ...options, launchOverride: launch }, spec).then(withHostTools), options);
117
+ },
118
+ });
119
+ const cli = resolveForkCli(spec);
120
+ console.log(`[omp-spawn] registered: ${spec.id}-spawn (${spec.id}: ${cli ? cli.origin : "未找到(createSession 时报安装指引)"})`);
121
+ },
122
+
123
+ /** 会话 recycle(/session/recycle):存量 handle 升级到当前扩展代码(D8)。 */
124
+ async api(req: Request, ctx: { path: string[]; method: string }) {
125
+ return recycleApi ? await recycleApi(req, ctx) : null;
126
+ },
127
+ },
128
+ };