@armadra/agent 0.12.0 → 0.14.0
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/CHANGELOG.md +16 -0
- package/CHANGELOG.zh-CN.md +16 -0
- package/dist/ai/fake/fake-provider.d.ts +6 -0
- package/dist/ai/fake/fake-provider.js +46 -0
- package/dist/ai/fake/fake-script.d.ts +8 -1
- package/dist/ai/fake/fake-script.js +5 -1
- package/dist/bridge/pi/args.d.ts +19 -0
- package/dist/bridge/pi/args.js +96 -0
- package/dist/bridge/pi/capabilities.d.ts +57 -0
- package/dist/bridge/pi/capabilities.js +65 -0
- package/dist/bridge/pi/config.d.ts +28 -0
- package/dist/bridge/pi/config.js +67 -0
- package/dist/bridge/pi/elicit.d.ts +23 -0
- package/dist/bridge/pi/elicit.js +86 -0
- package/dist/bridge/pi/entry.d.ts +14 -0
- package/dist/bridge/pi/entry.js +59 -0
- package/dist/bridge/pi/events.d.ts +62 -0
- package/dist/bridge/pi/events.js +223 -0
- package/dist/bridge/pi/gate.d.ts +42 -0
- package/dist/bridge/pi/gate.js +69 -0
- package/dist/bridge/pi/mcp.d.ts +17 -0
- package/dist/bridge/pi/mcp.js +49 -0
- package/dist/bridge/pi/prompt.d.ts +8 -0
- package/dist/bridge/pi/prompt.js +26 -0
- package/dist/bridge/pi/replay.d.ts +10 -0
- package/dist/bridge/pi/replay.js +87 -0
- package/dist/bridge/pi/server.d.ts +61 -0
- package/dist/bridge/pi/server.js +240 -0
- package/dist/bridge/pi/session.d.ts +112 -0
- package/dist/bridge/pi/session.js +497 -0
- package/dist/bridge/pi/tools.d.ts +36 -0
- package/dist/bridge/pi/tools.js +129 -0
- package/dist/bundle/ama.cjs +2426 -559
- package/dist/cli/main.d.ts +1 -0
- package/dist/cli/main.js +7 -0
- package/dist/codemode/host-side.d.ts +7 -0
- package/dist/codemode/host-side.js +7 -2
- package/dist/drivers/catalog.js +1 -1
- package/dist/drivers/native/pi-extension.d.ts +39 -0
- package/dist/drivers/native/pi-extension.js +100 -0
- package/dist/drivers/native/pi-rpc-core.d.ts +49 -0
- package/dist/drivers/native/pi-rpc-core.js +108 -0
- package/dist/drivers/native/pi-rpc.d.ts +4 -1
- package/dist/drivers/native/pi-rpc.js +40 -76
- package/dist/i18n/catalog.d.ts +56 -0
- package/dist/i18n/catalog.js +3 -0
- package/dist/i18n/messages/bridge.d.ts +123 -0
- package/dist/i18n/messages/bridge.js +123 -0
- package/dist/i18n/messages/cli-help.js +4 -0
- package/docs/README.md +6 -6
- package/docs/en/README.md +1 -1
- package/docs/en/reference/acp.md +87 -9
- package/docs/guides/agents.md +2 -0
- package/docs/reference/acp.md +87 -9
- package/package.json +1 -1
- package/dist/drivers/native/pi-gate.d.ts +0 -19
- package/dist/drivers/native/pi-gate.js +0 -39
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `ama --mode acp --bridge pi` 的进程入口(#254)。
|
|
3
|
+
*
|
|
4
|
+
* bootstrap 之前分流:不解析供应商与模型,不需要 ama 的 key 或会话;stdin / stdout 是 ACP(NDJSON),
|
|
5
|
+
* 诊断写 stderr。退出语义同 `--mode acp`:stdin 关闭 → 收掉全部 Pi 子进程 → 退出 0;SIGINT / SIGTERM → 130 / 143。
|
|
6
|
+
*/
|
|
7
|
+
import { reportError } from "../../cli/bootstrap.js";
|
|
8
|
+
import { ExitCode } from "../../cli/exit-codes.js";
|
|
9
|
+
import { createAcpConnection } from "../../modes/acp/acp-connection.js";
|
|
10
|
+
import { onTerminationSignals } from "../../modes/shared.js";
|
|
11
|
+
import { RpcError } from "../../drivers/jsonrpc.js";
|
|
12
|
+
import { RPC_ERRORS } from "../../drivers/acp/types.js";
|
|
13
|
+
import { parseBridgeArgs } from "./args.js";
|
|
14
|
+
import { PiBridgeServer } from "./server.js";
|
|
15
|
+
export async function runBridge(argv, io, options = {}) {
|
|
16
|
+
let passthrough;
|
|
17
|
+
try {
|
|
18
|
+
passthrough = parseBridgeArgs(argv).passthrough;
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
return reportError(error, io);
|
|
22
|
+
}
|
|
23
|
+
const stdin = options.stdin ?? process.stdin;
|
|
24
|
+
const stdout = options.stdout ?? process.stdout;
|
|
25
|
+
const log = (message) => io.stderr(`ama: ${message}\n`);
|
|
26
|
+
const target = {};
|
|
27
|
+
const connection = createAcpConnection({ input: stdin, output: stdout }, log, {
|
|
28
|
+
onRequest: async (method, params, ctx) => {
|
|
29
|
+
if (target.server === undefined)
|
|
30
|
+
throw new RpcError(RPC_ERRORS.internalError, method);
|
|
31
|
+
return target.server.handle(method, (params ?? {}), ctx);
|
|
32
|
+
},
|
|
33
|
+
onNotification: (method, params) => target.server?.handleNotification(method, params),
|
|
34
|
+
});
|
|
35
|
+
const server = new PiBridgeServer({
|
|
36
|
+
connection,
|
|
37
|
+
passthrough,
|
|
38
|
+
env: io.env,
|
|
39
|
+
log,
|
|
40
|
+
...(options.deps !== undefined ? { deps: options.deps } : {}),
|
|
41
|
+
});
|
|
42
|
+
target.server = server;
|
|
43
|
+
return new Promise((resolve) => {
|
|
44
|
+
let finished = false;
|
|
45
|
+
const finish = async (code) => {
|
|
46
|
+
if (finished)
|
|
47
|
+
return;
|
|
48
|
+
finished = true;
|
|
49
|
+
offSignals();
|
|
50
|
+
stdin.pause?.();
|
|
51
|
+
await server.dispose();
|
|
52
|
+
await connection.peer.flush();
|
|
53
|
+
connection.peer.close();
|
|
54
|
+
resolve(code);
|
|
55
|
+
};
|
|
56
|
+
void connection.peer.closed.then(() => finish(ExitCode.Ok));
|
|
57
|
+
const offSignals = onTerminationSignals((code) => void finish(code));
|
|
58
|
+
});
|
|
59
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi 事件 → ACP `session/update`(#254)。
|
|
3
|
+
*
|
|
4
|
+
* - `message_update` 的 text / thinking delta → `agent_message_chunk` / `agent_thought_chunk`;
|
|
5
|
+
* - `tool_execution_start|update|end` → `tool_call` / `tool_call_update`(标题、类别、位置沿用驱动的规则;
|
|
6
|
+
* `partialResult` 与 `result` 转成内容;`rawInput` 带参数)。审批闸在 `tool_execution_start` 之后才问,
|
|
7
|
+
* 所以要过闸的调用先以 `pending` 公布(权限请求关联到它),放行后 `markRunning` 转 `in_progress`;只读内置工具直接 `in_progress`;
|
|
8
|
+
* - MCP 工具(`mcp__<server>__<tool>`,只认桥注册过的服务器)写 `_meta.is_mcp_tool_call` 与
|
|
9
|
+
* `rawInput {server, tool, arguments}`,客户端据此识别自家工具;codemode 里发起的内层调用带
|
|
10
|
+
* `_meta.ama.parentToolCallId`;
|
|
11
|
+
* - 结果的 `details.todos` → `plan`(整表);子 Agent 工具(`subagent`)写 `_meta["armadra.subagent"]`;
|
|
12
|
+
* - assistant 的 `message_end` 累加本回合用量(input 不含缓存命中)与费用来源。
|
|
13
|
+
*/
|
|
14
|
+
import { type AcpPromptUsage, type AcpSessionUpdate, type AcpToolCall } from "../../drivers/acp/types.js";
|
|
15
|
+
import { type Json } from "./tools.js";
|
|
16
|
+
export interface EventsOptions {
|
|
17
|
+
cwd: string;
|
|
18
|
+
emit(update: AcpSessionUpdate): void;
|
|
19
|
+
/** 桥注册给 Pi 的 MCP 服务器名(客户端给的原样)。 */
|
|
20
|
+
mcpServers(): readonly string[];
|
|
21
|
+
}
|
|
22
|
+
export declare class PiEventMapper {
|
|
23
|
+
private readonly options;
|
|
24
|
+
/** 已公布的工具调用(id → 展示字段),供审批关联与结束时补全。 */
|
|
25
|
+
private readonly published;
|
|
26
|
+
private usage;
|
|
27
|
+
/** 本会话里 assistant 消息的费用是否都是账单值(`cost.totalFromProvider`)。 */
|
|
28
|
+
private costMessages;
|
|
29
|
+
private costFromProvider;
|
|
30
|
+
private last;
|
|
31
|
+
constructor(options: EventsOptions);
|
|
32
|
+
/** 回合开始:清空本回合用量。 */
|
|
33
|
+
resetTurn(): void;
|
|
34
|
+
/** 本回合最后一条 assistant 消息(判停止原因、取最终文本)。 */
|
|
35
|
+
lastAssistant(): Json | undefined;
|
|
36
|
+
/** 本回合累加的用量(没收到任何 assistant 消息返回 undefined)。 */
|
|
37
|
+
turnUsage(): AcpPromptUsage | undefined;
|
|
38
|
+
/** 费用是否全是账单值:没见过任何带费用的 assistant 消息时 undefined。 */
|
|
39
|
+
costIsFromProvider(): boolean | undefined;
|
|
40
|
+
/** 已公布调用的标题与类别。 */
|
|
41
|
+
toolInfo(id: string): {
|
|
42
|
+
title: string;
|
|
43
|
+
kind: AcpToolCall["kind"];
|
|
44
|
+
} | undefined;
|
|
45
|
+
/** 审批闸放行:调用从 `pending` 转为 `in_progress`。 */
|
|
46
|
+
markRunning(id: string): void;
|
|
47
|
+
onEvent(record: Json): void;
|
|
48
|
+
private onMessageUpdate;
|
|
49
|
+
private onMessageEnd;
|
|
50
|
+
private mcpRef;
|
|
51
|
+
/** 一次调用的展示字段(`tool_call` 与权限请求的 `toolCall` 共用)。 */
|
|
52
|
+
describe(tool: string, input: Json, record?: Json): Omit<AcpToolCall, "toolCallId" | "status"> & {
|
|
53
|
+
title: string;
|
|
54
|
+
};
|
|
55
|
+
/** 公布一个新调用(`tool_call`)。 */
|
|
56
|
+
private publish;
|
|
57
|
+
/** `_meta`:自家工具标记(顶层,客户端约定)与 ama 命名空间下的父调用。 */
|
|
58
|
+
private metaOf;
|
|
59
|
+
private onToolStart;
|
|
60
|
+
private onToolUpdate;
|
|
61
|
+
private onToolEnd;
|
|
62
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi 事件 → ACP `session/update`(#254)。
|
|
3
|
+
*
|
|
4
|
+
* - `message_update` 的 text / thinking delta → `agent_message_chunk` / `agent_thought_chunk`;
|
|
5
|
+
* - `tool_execution_start|update|end` → `tool_call` / `tool_call_update`(标题、类别、位置沿用驱动的规则;
|
|
6
|
+
* `partialResult` 与 `result` 转成内容;`rawInput` 带参数)。审批闸在 `tool_execution_start` 之后才问,
|
|
7
|
+
* 所以要过闸的调用先以 `pending` 公布(权限请求关联到它),放行后 `markRunning` 转 `in_progress`;只读内置工具直接 `in_progress`;
|
|
8
|
+
* - MCP 工具(`mcp__<server>__<tool>`,只认桥注册过的服务器)写 `_meta.is_mcp_tool_call` 与
|
|
9
|
+
* `rawInput {server, tool, arguments}`,客户端据此识别自家工具;codemode 里发起的内层调用带
|
|
10
|
+
* `_meta.ama.parentToolCallId`;
|
|
11
|
+
* - 结果的 `details.todos` → `plan`(整表);子 Agent 工具(`subagent`)写 `_meta["armadra.subagent"]`;
|
|
12
|
+
* - assistant 的 `message_end` 累加本回合用量(input 不含缓存命中)与费用来源。
|
|
13
|
+
*/
|
|
14
|
+
import { ACP_META_KEY, } from "../../drivers/acp/types.js";
|
|
15
|
+
import { PI_READ_ONLY_TOOLS } from "../../drivers/native/pi-extension.js";
|
|
16
|
+
import { bridgeToolTitle, mcpToolOf, piResultContent, piToolKind, piToolLocations, planEntriesOf, SUBAGENT_TOOL, subagentMeta, } from "./tools.js";
|
|
17
|
+
const emptyUsage = () => ({
|
|
18
|
+
input: 0,
|
|
19
|
+
output: 0,
|
|
20
|
+
cacheRead: 0,
|
|
21
|
+
cacheWrite: 0,
|
|
22
|
+
total: 0,
|
|
23
|
+
seen: false,
|
|
24
|
+
});
|
|
25
|
+
export class PiEventMapper {
|
|
26
|
+
options;
|
|
27
|
+
/** 已公布的工具调用(id → 展示字段),供审批关联与结束时补全。 */
|
|
28
|
+
published = new Map();
|
|
29
|
+
usage = emptyUsage();
|
|
30
|
+
/** 本会话里 assistant 消息的费用是否都是账单值(`cost.totalFromProvider`)。 */
|
|
31
|
+
costMessages = 0;
|
|
32
|
+
costFromProvider = 0;
|
|
33
|
+
last;
|
|
34
|
+
constructor(options) {
|
|
35
|
+
this.options = options;
|
|
36
|
+
}
|
|
37
|
+
/** 回合开始:清空本回合用量。 */
|
|
38
|
+
resetTurn() {
|
|
39
|
+
this.usage = emptyUsage();
|
|
40
|
+
this.last = undefined;
|
|
41
|
+
}
|
|
42
|
+
/** 本回合最后一条 assistant 消息(判停止原因、取最终文本)。 */
|
|
43
|
+
lastAssistant() {
|
|
44
|
+
return this.last;
|
|
45
|
+
}
|
|
46
|
+
/** 本回合累加的用量(没收到任何 assistant 消息返回 undefined)。 */
|
|
47
|
+
turnUsage() {
|
|
48
|
+
const u = this.usage;
|
|
49
|
+
if (!u.seen)
|
|
50
|
+
return undefined;
|
|
51
|
+
return {
|
|
52
|
+
inputTokens: u.input,
|
|
53
|
+
outputTokens: u.output,
|
|
54
|
+
cachedReadTokens: u.cacheRead,
|
|
55
|
+
cachedWriteTokens: u.cacheWrite,
|
|
56
|
+
totalTokens: u.total > 0 ? u.total : u.input + u.output + u.cacheRead + u.cacheWrite,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** 费用是否全是账单值:没见过任何带费用的 assistant 消息时 undefined。 */
|
|
60
|
+
costIsFromProvider() {
|
|
61
|
+
return this.costMessages === 0 ? undefined : this.costFromProvider === this.costMessages;
|
|
62
|
+
}
|
|
63
|
+
/** 已公布调用的标题与类别。 */
|
|
64
|
+
toolInfo(id) {
|
|
65
|
+
return this.published.get(id);
|
|
66
|
+
}
|
|
67
|
+
/** 审批闸放行:调用从 `pending` 转为 `in_progress`。 */
|
|
68
|
+
markRunning(id) {
|
|
69
|
+
if (this.published.has(id))
|
|
70
|
+
this.options.emit({
|
|
71
|
+
sessionUpdate: "tool_call_update",
|
|
72
|
+
toolCallId: id,
|
|
73
|
+
status: "in_progress",
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
onEvent(record) {
|
|
77
|
+
switch (record["type"]) {
|
|
78
|
+
case "message_update":
|
|
79
|
+
this.onMessageUpdate(record);
|
|
80
|
+
return;
|
|
81
|
+
case "message_end":
|
|
82
|
+
this.onMessageEnd(record);
|
|
83
|
+
return;
|
|
84
|
+
case "tool_execution_start":
|
|
85
|
+
this.onToolStart(record);
|
|
86
|
+
return;
|
|
87
|
+
case "tool_execution_update":
|
|
88
|
+
this.onToolUpdate(record);
|
|
89
|
+
return;
|
|
90
|
+
case "tool_execution_end":
|
|
91
|
+
this.onToolEnd(record);
|
|
92
|
+
return;
|
|
93
|
+
default:
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
onMessageUpdate(record) {
|
|
97
|
+
const event = (record["assistantMessageEvent"] ?? {});
|
|
98
|
+
const delta = event["delta"];
|
|
99
|
+
if (typeof delta !== "string" || delta === "")
|
|
100
|
+
return;
|
|
101
|
+
if (event["type"] === "text_delta")
|
|
102
|
+
this.options.emit({
|
|
103
|
+
sessionUpdate: "agent_message_chunk",
|
|
104
|
+
content: { type: "text", text: delta },
|
|
105
|
+
});
|
|
106
|
+
else if (event["type"] === "thinking_delta")
|
|
107
|
+
this.options.emit({
|
|
108
|
+
sessionUpdate: "agent_thought_chunk",
|
|
109
|
+
content: { type: "text", text: delta },
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
onMessageEnd(record) {
|
|
113
|
+
const message = (record["message"] ?? {});
|
|
114
|
+
if (message["role"] !== "assistant")
|
|
115
|
+
return;
|
|
116
|
+
this.last = message;
|
|
117
|
+
const usage = (message["usage"] ?? {});
|
|
118
|
+
const num = (key) => typeof usage[key] === "number" ? usage[key] : 0;
|
|
119
|
+
const u = this.usage;
|
|
120
|
+
this.usage = {
|
|
121
|
+
input: u.input + num("input"),
|
|
122
|
+
output: u.output + num("output"),
|
|
123
|
+
cacheRead: u.cacheRead + num("cacheRead"),
|
|
124
|
+
cacheWrite: u.cacheWrite + num("cacheWrite"),
|
|
125
|
+
total: u.total + num("totalTokens"),
|
|
126
|
+
seen: true,
|
|
127
|
+
};
|
|
128
|
+
const cost = (usage["cost"] ?? {});
|
|
129
|
+
if (typeof cost["total"] === "number") {
|
|
130
|
+
this.costMessages++;
|
|
131
|
+
const billed = cost["totalFromProvider"];
|
|
132
|
+
if (billed === true || typeof billed === "number")
|
|
133
|
+
this.costFromProvider++;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
mcpRef(tool) {
|
|
137
|
+
return mcpToolOf(tool, this.options.mcpServers());
|
|
138
|
+
}
|
|
139
|
+
/** 一次调用的展示字段(`tool_call` 与权限请求的 `toolCall` 共用)。 */
|
|
140
|
+
describe(tool, input, record) {
|
|
141
|
+
const mcp = this.mcpRef(tool);
|
|
142
|
+
const locations = piToolLocations(input, this.options.cwd);
|
|
143
|
+
const meta = this.metaOf(record, mcp, tool, input);
|
|
144
|
+
return {
|
|
145
|
+
title: bridgeToolTitle(tool, input, mcp),
|
|
146
|
+
kind: piToolKind(tool),
|
|
147
|
+
name: tool,
|
|
148
|
+
rawInput: mcp !== undefined ? { server: mcp.server, tool: mcp.tool, arguments: input } : input,
|
|
149
|
+
...(locations !== undefined ? { locations } : {}),
|
|
150
|
+
...(meta !== undefined ? { _meta: meta } : {}),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/** 公布一个新调用(`tool_call`)。 */
|
|
154
|
+
publish(id, tool, input, status, record, extra = {}) {
|
|
155
|
+
const fields = this.describe(tool, input, record);
|
|
156
|
+
this.published.set(id, { title: fields.title, kind: fields.kind });
|
|
157
|
+
this.options.emit({ sessionUpdate: "tool_call", toolCallId: id, status, ...fields, ...extra });
|
|
158
|
+
}
|
|
159
|
+
/** `_meta`:自家工具标记(顶层,客户端约定)与 ama 命名空间下的父调用。 */
|
|
160
|
+
metaOf(record, mcp, tool, input) {
|
|
161
|
+
const meta = {};
|
|
162
|
+
if (mcp !== undefined)
|
|
163
|
+
meta["is_mcp_tool_call"] = true;
|
|
164
|
+
if (tool === SUBAGENT_TOOL) {
|
|
165
|
+
const sub = subagentMeta(input);
|
|
166
|
+
if (sub !== undefined)
|
|
167
|
+
meta["armadra.subagent"] = sub;
|
|
168
|
+
}
|
|
169
|
+
const parent = record?.["parentToolCallId"];
|
|
170
|
+
if (typeof parent === "string" && parent !== "")
|
|
171
|
+
meta[ACP_META_KEY] = { parentToolCallId: parent };
|
|
172
|
+
return Object.keys(meta).length > 0 ? meta : undefined;
|
|
173
|
+
}
|
|
174
|
+
onToolStart(record) {
|
|
175
|
+
const id = String(record["toolCallId"] ?? "");
|
|
176
|
+
const tool = String(record["toolName"] ?? "tool");
|
|
177
|
+
const input = (record["args"] ?? {});
|
|
178
|
+
// 审批闸在 `tool_execution_start` 之后才问:要过闸的调用先标 `pending`,放行后再转 `in_progress`
|
|
179
|
+
if (!this.published.has(id)) {
|
|
180
|
+
const gated = !PI_READ_ONLY_TOOLS.includes(tool);
|
|
181
|
+
this.publish(id, tool, input, gated ? "pending" : "in_progress", record);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
onToolUpdate(record) {
|
|
185
|
+
const id = String(record["toolCallId"] ?? "");
|
|
186
|
+
if (!this.published.has(id))
|
|
187
|
+
this.publish(id, String(record["toolName"] ?? "tool"), (record["args"] ?? {}), "in_progress", record);
|
|
188
|
+
const content = piResultContent(record["partialResult"]);
|
|
189
|
+
if (content !== undefined)
|
|
190
|
+
this.options.emit({
|
|
191
|
+
sessionUpdate: "tool_call_update",
|
|
192
|
+
toolCallId: id,
|
|
193
|
+
status: "in_progress",
|
|
194
|
+
content,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
onToolEnd(record) {
|
|
198
|
+
const id = String(record["toolCallId"] ?? "");
|
|
199
|
+
const status = record["isError"] === true ? "failed" : "completed";
|
|
200
|
+
// todo 类工具把整表放在结果的 details.todos:每来一次结果就整表发一次 plan
|
|
201
|
+
const entries = record["isError"] === true
|
|
202
|
+
? undefined
|
|
203
|
+
: planEntriesOf((record["result"] ?? {})["details"]);
|
|
204
|
+
if (entries !== undefined)
|
|
205
|
+
this.options.emit({ sessionUpdate: "plan", entries });
|
|
206
|
+
const content = piResultContent(record["result"]);
|
|
207
|
+
if (!this.published.has(id)) {
|
|
208
|
+
// 没执行就结束的调用(被阻止、参数不合):直接公布成终态
|
|
209
|
+
this.publish(id, String(record["toolName"] ?? "tool"), (record["args"] ?? {}), status, record, {
|
|
210
|
+
...(content !== undefined ? { content } : {}),
|
|
211
|
+
});
|
|
212
|
+
this.published.delete(id);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
this.published.delete(id);
|
|
216
|
+
this.options.emit({
|
|
217
|
+
sessionUpdate: "tool_call_update",
|
|
218
|
+
toolCallId: id,
|
|
219
|
+
status,
|
|
220
|
+
...(content !== undefined ? { content } : {}),
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 桥的四个权限模式与审批判定(#254)。
|
|
3
|
+
*
|
|
4
|
+
* Pi 没有权限模式,所以由 ama 加载的扩展(`drivers/native/pi-extension.ts`)在每次工具调用前把请求交给桥,
|
|
5
|
+
* 桥按当前模式判定:**每次调用都问桥**,`session/set_mode` 立即生效(不靠 `--tools`)。
|
|
6
|
+
*
|
|
7
|
+
* - `default`:只读以外都交给人;
|
|
8
|
+
* - `auto-edit`:放行 `edit` / `write`,其余只读以外交给人;
|
|
9
|
+
* - `plan`:放行只读内置工具与带 `readOnlyHint` 的 MCP 工具,其余拒绝并告诉模型现在在 plan 模式;
|
|
10
|
+
* - `full-auto`:都放行,但命中 ama 危险命令规则的 bash 仍交给人。
|
|
11
|
+
*
|
|
12
|
+
* 判定只产生「放行 / 拒绝 / 交给人」;交给人时请求只发给客户端,桥从不代答。
|
|
13
|
+
*/
|
|
14
|
+
import type { Json } from "./tools.js";
|
|
15
|
+
/** 桥的模式 id(与 ama 的权限模式同名)。 */
|
|
16
|
+
export type BridgeMode = "default" | "auto-edit" | "plan" | "full-auto";
|
|
17
|
+
/** `availableModes` 的顺序(严格的在前,与 ama 的选择器一致)。 */
|
|
18
|
+
export declare const BRIDGE_MODES: readonly BridgeMode[];
|
|
19
|
+
export declare function isBridgeMode(value: string): value is BridgeMode;
|
|
20
|
+
/** 审批闸发来的一次调用(扩展按固定形状序列化)。 */
|
|
21
|
+
export interface GateCall {
|
|
22
|
+
id: string;
|
|
23
|
+
tool: string;
|
|
24
|
+
input: Json;
|
|
25
|
+
/** 工具声明了 `readOnlyHint`。 */
|
|
26
|
+
readOnly: boolean;
|
|
27
|
+
/** codemode 等父调用的 id。 */
|
|
28
|
+
parent?: string;
|
|
29
|
+
}
|
|
30
|
+
export type Verdict = {
|
|
31
|
+
kind: "allow";
|
|
32
|
+
} | {
|
|
33
|
+
kind: "ask";
|
|
34
|
+
}
|
|
35
|
+
/** `reason` 回给模型(固定英文)。 */
|
|
36
|
+
| {
|
|
37
|
+
kind: "deny";
|
|
38
|
+
reason: string;
|
|
39
|
+
};
|
|
40
|
+
/** 解析扩展发来的正文;形状不对返回 undefined(调用方按拒绝处理)。 */
|
|
41
|
+
export declare function parseGateCall(message: unknown): GateCall | undefined;
|
|
42
|
+
export declare function verdictFor(mode: BridgeMode, call: GateCall): Verdict;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 桥的四个权限模式与审批判定(#254)。
|
|
3
|
+
*
|
|
4
|
+
* Pi 没有权限模式,所以由 ama 加载的扩展(`drivers/native/pi-extension.ts`)在每次工具调用前把请求交给桥,
|
|
5
|
+
* 桥按当前模式判定:**每次调用都问桥**,`session/set_mode` 立即生效(不靠 `--tools`)。
|
|
6
|
+
*
|
|
7
|
+
* - `default`:只读以外都交给人;
|
|
8
|
+
* - `auto-edit`:放行 `edit` / `write`,其余只读以外交给人;
|
|
9
|
+
* - `plan`:放行只读内置工具与带 `readOnlyHint` 的 MCP 工具,其余拒绝并告诉模型现在在 plan 模式;
|
|
10
|
+
* - `full-auto`:都放行,但命中 ama 危险命令规则的 bash 仍交给人。
|
|
11
|
+
*
|
|
12
|
+
* 判定只产生「放行 / 拒绝 / 交给人」;交给人时请求只发给客户端,桥从不代答。
|
|
13
|
+
*/
|
|
14
|
+
import { matchDangerous } from "../../permissions/dangerous.js";
|
|
15
|
+
import { PI_READ_ONLY_TOOLS } from "../../drivers/native/pi-extension.js";
|
|
16
|
+
/** `availableModes` 的顺序(严格的在前,与 ama 的选择器一致)。 */
|
|
17
|
+
export const BRIDGE_MODES = ["default", "auto-edit", "plan", "full-auto"];
|
|
18
|
+
export function isBridgeMode(value) {
|
|
19
|
+
return BRIDGE_MODES.includes(value);
|
|
20
|
+
}
|
|
21
|
+
/** 解析扩展发来的正文;形状不对返回 undefined(调用方按拒绝处理)。 */
|
|
22
|
+
export function parseGateCall(message) {
|
|
23
|
+
if (typeof message !== "string")
|
|
24
|
+
return undefined;
|
|
25
|
+
let raw;
|
|
26
|
+
try {
|
|
27
|
+
raw = JSON.parse(message);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
if (typeof raw["id"] !== "string" || typeof raw["tool"] !== "string")
|
|
33
|
+
return undefined;
|
|
34
|
+
const input = raw["input"] !== null && typeof raw["input"] === "object" ? raw["input"] : {};
|
|
35
|
+
return {
|
|
36
|
+
id: raw["id"],
|
|
37
|
+
tool: raw["tool"],
|
|
38
|
+
input,
|
|
39
|
+
readOnly: raw["readOnly"] === true,
|
|
40
|
+
...(typeof raw["parent"] === "string" ? { parent: raw["parent"] } : {}),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const EDIT_TOOLS = new Set(["edit", "write"]);
|
|
44
|
+
const SHELL_TOOLS = new Set(["bash", "powershell"]);
|
|
45
|
+
/** 命中 ama 危险命令规则的 shell 调用。 */
|
|
46
|
+
function isDangerousShell(call) {
|
|
47
|
+
const command = call.input["command"];
|
|
48
|
+
return (SHELL_TOOLS.has(call.tool) &&
|
|
49
|
+
typeof command === "string" &&
|
|
50
|
+
matchDangerous(command) !== undefined);
|
|
51
|
+
}
|
|
52
|
+
export function verdictFor(mode, call) {
|
|
53
|
+
const readOnly = call.readOnly || PI_READ_ONLY_TOOLS.includes(call.tool);
|
|
54
|
+
switch (mode) {
|
|
55
|
+
case "plan":
|
|
56
|
+
return readOnly
|
|
57
|
+
? { kind: "allow" }
|
|
58
|
+
: {
|
|
59
|
+
kind: "deny",
|
|
60
|
+
reason: `${call.tool} was blocked: this session is in plan mode, which only allows read-only tools. Describe the change in your reply instead of making it.`,
|
|
61
|
+
};
|
|
62
|
+
case "full-auto":
|
|
63
|
+
return isDangerousShell(call) ? { kind: "ask" } : { kind: "allow" };
|
|
64
|
+
case "auto-edit":
|
|
65
|
+
return readOnly || EDIT_TOOLS.has(call.tool) ? { kind: "allow" } : { kind: "ask" };
|
|
66
|
+
default:
|
|
67
|
+
return readOnly ? { kind: "allow" } : { kind: "ask" };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 客户端 `mcpServers`(ACP 形状)→ Pi 的 `registerMcpServer` 配置(#254)。
|
|
3
|
+
*
|
|
4
|
+
* ama 自己不说 MCP:这里只做形状转换,连接由 Pi 内置的 MCP 完成(扩展加载时对每一项调用
|
|
5
|
+
* `pi.registerMcpServer(name, { …, exposure: "direct" })`)。stdio 与 http 支持;sse 桥没有声明
|
|
6
|
+
* (`mcpCapabilities.sse: false`),收到也跳过。Pi 的服务器名只允许字母、数字、`_`、`-`,其余换成 `_`。
|
|
7
|
+
*/
|
|
8
|
+
import type { Json } from "./tools.js";
|
|
9
|
+
export interface PiMcpPlan {
|
|
10
|
+
/** 写进 `bridge.json` 的 `mcpServers`(Pi 的服务器名 → 配置)。 */
|
|
11
|
+
servers: Record<string, Json>;
|
|
12
|
+
/** 客户端给的原名(桥用它认 `mcp__<server>__<tool>`)。 */
|
|
13
|
+
names: string[];
|
|
14
|
+
/** 被跳过的条目(名字或 `#序号`),调用方写一行 stderr。 */
|
|
15
|
+
skipped: string[];
|
|
16
|
+
}
|
|
17
|
+
export declare function piMcpPlan(list: unknown): PiMcpPlan;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 客户端 `mcpServers`(ACP 形状)→ Pi 的 `registerMcpServer` 配置(#254)。
|
|
3
|
+
*
|
|
4
|
+
* ama 自己不说 MCP:这里只做形状转换,连接由 Pi 内置的 MCP 完成(扩展加载时对每一项调用
|
|
5
|
+
* `pi.registerMcpServer(name, { …, exposure: "direct" })`)。stdio 与 http 支持;sse 桥没有声明
|
|
6
|
+
* (`mcpCapabilities.sse: false`),收到也跳过。Pi 的服务器名只允许字母、数字、`_`、`-`,其余换成 `_`。
|
|
7
|
+
*/
|
|
8
|
+
function pairs(value) {
|
|
9
|
+
const out = {};
|
|
10
|
+
if (!Array.isArray(value))
|
|
11
|
+
return out;
|
|
12
|
+
for (const item of value) {
|
|
13
|
+
const name = item["name"];
|
|
14
|
+
const val = item["value"];
|
|
15
|
+
if (typeof name === "string" && name !== "" && typeof val === "string")
|
|
16
|
+
out[name] = val;
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
export function piMcpPlan(list) {
|
|
21
|
+
const plan = { servers: {}, names: [], skipped: [] };
|
|
22
|
+
if (!Array.isArray(list))
|
|
23
|
+
return plan;
|
|
24
|
+
list.forEach((entry, index) => {
|
|
25
|
+
const server = (entry ?? {});
|
|
26
|
+
const name = server["name"];
|
|
27
|
+
if (typeof name !== "string" || name === "") {
|
|
28
|
+
plan.skipped.push(`#${index + 1}`);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const piName = name.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
32
|
+
const type = server["type"];
|
|
33
|
+
if (typeof server["command"] === "string" && (type === undefined || type === "stdio")) {
|
|
34
|
+
const args = Array.isArray(server["args"])
|
|
35
|
+
? server["args"].filter((a) => typeof a === "string")
|
|
36
|
+
: [];
|
|
37
|
+
plan.servers[piName] = { command: server["command"], args, env: pairs(server["env"]) };
|
|
38
|
+
}
|
|
39
|
+
else if (type === "http" && typeof server["url"] === "string") {
|
|
40
|
+
plan.servers[piName] = { url: server["url"], headers: pairs(server["headers"]) };
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
plan.skipped.push(name);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
plan.names.push(name);
|
|
47
|
+
});
|
|
48
|
+
return plan;
|
|
49
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACP 提示内容块 → Pi `prompt` 命令的 `message` 与 `images`(#254)。
|
|
3
|
+
*
|
|
4
|
+
* 文本与嵌入资源拼成一条 message(资源包在 `<resource uri>` 里,链接写成 `@uri`),图片走 `images`;
|
|
5
|
+
* 音频块 Pi 没有对应入口,忽略。
|
|
6
|
+
*/
|
|
7
|
+
import type { Json } from "./tools.js";
|
|
8
|
+
export declare function promptCommand(blocks: unknown): Json;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACP 提示内容块 → Pi `prompt` 命令的 `message` 与 `images`(#254)。
|
|
3
|
+
*
|
|
4
|
+
* 文本与嵌入资源拼成一条 message(资源包在 `<resource uri>` 里,链接写成 `@uri`),图片走 `images`;
|
|
5
|
+
* 音频块 Pi 没有对应入口,忽略。
|
|
6
|
+
*/
|
|
7
|
+
import { RPC_ERRORS } from "../../drivers/acp/types.js";
|
|
8
|
+
import { RpcError } from "../../drivers/jsonrpc.js";
|
|
9
|
+
import { msg } from "../../i18n/index.js";
|
|
10
|
+
export function promptCommand(blocks) {
|
|
11
|
+
if (!Array.isArray(blocks))
|
|
12
|
+
throw new RpcError(RPC_ERRORS.invalidParams, msg().bridge.session.promptNotArray);
|
|
13
|
+
const parts = [];
|
|
14
|
+
const images = [];
|
|
15
|
+
for (const block of blocks) {
|
|
16
|
+
if (block.type === "text")
|
|
17
|
+
parts.push(block.text);
|
|
18
|
+
else if (block.type === "image")
|
|
19
|
+
images.push({ type: "image", data: block.data, mimeType: block.mimeType });
|
|
20
|
+
else if (block.type === "resource_link")
|
|
21
|
+
parts.push(`@${block.uri}`);
|
|
22
|
+
else if (block.type === "resource" && typeof block.resource.text === "string")
|
|
23
|
+
parts.push(`<resource uri="${block.resource.uri}">\n${block.resource.text}\n</resource>`);
|
|
24
|
+
}
|
|
25
|
+
return { type: "prompt", message: parts.join("\n"), ...(images.length > 0 ? { images } : {}) };
|
|
26
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `session/load` 的回放(#254):Pi 的 `get_messages` → ACP 更新。
|
|
3
|
+
*
|
|
4
|
+
* user → `user_message_chunk`;assistant 的 text / thinking → `agent_message_chunk` / `agent_thought_chunk`,
|
|
5
|
+
* toolCall → 终态的 `tool_call`(结果来自随后的 `toolResult` 消息);最后一次带 `details.todos` 的结果补一份 `plan`。
|
|
6
|
+
* system 与未知角色跳过。
|
|
7
|
+
*/
|
|
8
|
+
import type { AcpSessionUpdate } from "../../drivers/acp/types.js";
|
|
9
|
+
import { type Json } from "./tools.js";
|
|
10
|
+
export declare function replayUpdates(messages: readonly Json[], cwd: string, mcpServers: readonly string[]): AcpSessionUpdate[];
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `session/load` 的回放(#254):Pi 的 `get_messages` → ACP 更新。
|
|
3
|
+
*
|
|
4
|
+
* user → `user_message_chunk`;assistant 的 text / thinking → `agent_message_chunk` / `agent_thought_chunk`,
|
|
5
|
+
* toolCall → 终态的 `tool_call`(结果来自随后的 `toolResult` 消息);最后一次带 `details.todos` 的结果补一份 `plan`。
|
|
6
|
+
* system 与未知角色跳过。
|
|
7
|
+
*/
|
|
8
|
+
import { bridgeToolTitle, mcpToolOf, piResultContent, piToolKind, piToolLocations, planEntriesOf, } from "./tools.js";
|
|
9
|
+
export function replayUpdates(messages, cwd, mcpServers) {
|
|
10
|
+
const results = new Map();
|
|
11
|
+
for (const message of messages)
|
|
12
|
+
if (message["role"] === "toolResult" && typeof message["toolCallId"] === "string")
|
|
13
|
+
results.set(message["toolCallId"], message);
|
|
14
|
+
const out = [];
|
|
15
|
+
let plan;
|
|
16
|
+
for (const message of messages) {
|
|
17
|
+
if (message["role"] === "toolResult")
|
|
18
|
+
plan = planEntriesOf(message["details"]) ?? plan;
|
|
19
|
+
const content = message["content"];
|
|
20
|
+
const blocks = typeof content === "string"
|
|
21
|
+
? [{ type: "text", text: content }]
|
|
22
|
+
: Array.isArray(content)
|
|
23
|
+
? content
|
|
24
|
+
: [];
|
|
25
|
+
if (message["role"] === "user") {
|
|
26
|
+
for (const block of blocks) {
|
|
27
|
+
if (block["type"] === "text" && typeof block["text"] === "string" && block["text"] !== "")
|
|
28
|
+
out.push({
|
|
29
|
+
sessionUpdate: "user_message_chunk",
|
|
30
|
+
content: { type: "text", text: block["text"] },
|
|
31
|
+
});
|
|
32
|
+
else if (block["type"] === "image" &&
|
|
33
|
+
typeof block["data"] === "string" &&
|
|
34
|
+
typeof block["mimeType"] === "string")
|
|
35
|
+
out.push({
|
|
36
|
+
sessionUpdate: "user_message_chunk",
|
|
37
|
+
content: { type: "image", data: block["data"], mimeType: block["mimeType"] },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
else if (message["role"] === "assistant") {
|
|
42
|
+
for (const block of blocks) {
|
|
43
|
+
if (block["type"] === "text" && typeof block["text"] === "string" && block["text"] !== "")
|
|
44
|
+
out.push({
|
|
45
|
+
sessionUpdate: "agent_message_chunk",
|
|
46
|
+
content: { type: "text", text: block["text"] },
|
|
47
|
+
});
|
|
48
|
+
else if (block["type"] === "thinking" &&
|
|
49
|
+
typeof block["thinking"] === "string" &&
|
|
50
|
+
block["thinking"] !== "")
|
|
51
|
+
out.push({
|
|
52
|
+
sessionUpdate: "agent_thought_chunk",
|
|
53
|
+
content: { type: "text", text: block["thinking"] },
|
|
54
|
+
});
|
|
55
|
+
else if (block["type"] === "toolCall" && typeof block["id"] === "string") {
|
|
56
|
+
const tool = String(block["name"] ?? "tool");
|
|
57
|
+
const input = (block["arguments"] ?? {});
|
|
58
|
+
const mcp = mcpToolOf(tool, mcpServers);
|
|
59
|
+
const result = results.get(block["id"]);
|
|
60
|
+
const status = result === undefined
|
|
61
|
+
? "completed"
|
|
62
|
+
: result["isError"] === true
|
|
63
|
+
? "failed"
|
|
64
|
+
: "completed";
|
|
65
|
+
const resultContent = result !== undefined ? piResultContent(result) : undefined;
|
|
66
|
+
const locations = piToolLocations(input, cwd);
|
|
67
|
+
out.push({
|
|
68
|
+
sessionUpdate: "tool_call",
|
|
69
|
+
toolCallId: block["id"],
|
|
70
|
+
title: bridgeToolTitle(tool, input, mcp),
|
|
71
|
+
kind: piToolKind(tool),
|
|
72
|
+
status,
|
|
73
|
+
name: tool,
|
|
74
|
+
rawInput: mcp !== undefined ? { server: mcp.server, tool: mcp.tool, arguments: input } : input,
|
|
75
|
+
...(locations !== undefined ? { locations } : {}),
|
|
76
|
+
...(resultContent !== undefined ? { content: resultContent } : {}),
|
|
77
|
+
...(mcp !== undefined ? { _meta: { is_mcp_tool_call: true } } : {}),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// 回放末尾补一份当前计划(最后一次带 todos 的结果)
|
|
84
|
+
if (plan !== undefined)
|
|
85
|
+
out.push({ sessionUpdate: "plan", entries: plan });
|
|
86
|
+
return out;
|
|
87
|
+
}
|