@armadra/agent 0.13.0 → 0.15.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/CHANGELOG.zh-CN.md +16 -0
  3. package/README.md +1 -0
  4. package/README.zh-CN.md +1 -0
  5. package/dist/bridge/pi/args.d.ts +19 -0
  6. package/dist/bridge/pi/args.js +96 -0
  7. package/dist/bridge/pi/capabilities.d.ts +57 -0
  8. package/dist/bridge/pi/capabilities.js +65 -0
  9. package/dist/bridge/pi/config.d.ts +28 -0
  10. package/dist/bridge/pi/config.js +67 -0
  11. package/dist/bridge/pi/elicit.d.ts +23 -0
  12. package/dist/bridge/pi/elicit.js +86 -0
  13. package/dist/bridge/pi/entry.d.ts +14 -0
  14. package/dist/bridge/pi/entry.js +59 -0
  15. package/dist/bridge/pi/events.d.ts +62 -0
  16. package/dist/bridge/pi/events.js +223 -0
  17. package/dist/bridge/pi/gate.d.ts +42 -0
  18. package/dist/bridge/pi/gate.js +69 -0
  19. package/dist/bridge/pi/mcp.d.ts +17 -0
  20. package/dist/bridge/pi/mcp.js +49 -0
  21. package/dist/bridge/pi/prompt.d.ts +8 -0
  22. package/dist/bridge/pi/prompt.js +26 -0
  23. package/dist/bridge/pi/replay.d.ts +10 -0
  24. package/dist/bridge/pi/replay.js +87 -0
  25. package/dist/bridge/pi/server.d.ts +61 -0
  26. package/dist/bridge/pi/server.js +240 -0
  27. package/dist/bridge/pi/session.d.ts +112 -0
  28. package/dist/bridge/pi/session.js +497 -0
  29. package/dist/bridge/pi/tools.d.ts +36 -0
  30. package/dist/bridge/pi/tools.js +129 -0
  31. package/dist/bundle/ama.cjs +2398 -562
  32. package/dist/cli/main.d.ts +1 -0
  33. package/dist/cli/main.js +7 -0
  34. package/dist/drivers/catalog.js +23 -1
  35. package/dist/drivers/native/pi-extension.d.ts +39 -0
  36. package/dist/drivers/native/pi-extension.js +100 -0
  37. package/dist/drivers/native/pi-rpc-core.d.ts +49 -0
  38. package/dist/drivers/native/pi-rpc-core.js +108 -0
  39. package/dist/drivers/native/pi-rpc.d.ts +4 -1
  40. package/dist/drivers/native/pi-rpc.js +40 -76
  41. package/dist/i18n/catalog.d.ts +56 -0
  42. package/dist/i18n/catalog.js +3 -0
  43. package/dist/i18n/messages/bridge.d.ts +123 -0
  44. package/dist/i18n/messages/bridge.js +123 -0
  45. package/dist/i18n/messages/cli-help.js +4 -0
  46. package/docs/README.md +6 -6
  47. package/docs/en/README.md +1 -1
  48. package/docs/en/reference/acp.md +87 -9
  49. package/docs/guides/agents.md +3 -0
  50. package/docs/reference/acp.md +87 -9
  51. package/package.json +1 -1
  52. package/dist/drivers/native/pi-gate.d.ts +0 -19
  53. package/dist/drivers/native/pi-gate.js +0 -39
@@ -0,0 +1,497 @@
1
+ /**
2
+ * 一个 ACP 会话 = 一个 `pi --mode rpc --session-id <id>` 子进程(#254)。
3
+ *
4
+ * - 握手:`get_state`(当前模型、推理强度、消息数)、`get_available_models`、`get_available_thinking_levels`;
5
+ * 没有可用模型 → `pi_no_model`;
6
+ * - 回合:`prompt` → 应答 `disposition`(`handled` 不等回合)→ 事件流 → `agent_settled` 结束;
7
+ * `aborted` 为真或本端已取消 → `cancelled`;assistant 的 `stopReason` 为 `length` → `max_tokens`,`error` → JSON-RPC 错误;
8
+ * 运行中再来的 prompt 答 busy;答复的 `usage` 是本回合累加;
9
+ * - 取消:撤回挂起的审批与征询,发 `abort`,15 秒看门狗(过了关 stdin 再杀进程树);
10
+ * - 用量:开会话、回合结束与换模型之后发 `usage_update`(`get_session_stats` 的上下文占用与窗口、费用)。
11
+ */
12
+ import { AmaError } from "../../errors.js";
13
+ import { armCancelWatchdog } from "../../drivers/base.js";
14
+ import { RPC_ERRORS, } from "../../drivers/acp/types.js";
15
+ import { RpcError } from "../../drivers/jsonrpc.js";
16
+ import { PiRpcCore } from "../../drivers/native/pi-rpc-core.js";
17
+ import { PI_GATE_TITLE, PI_REASON_TITLE, PI_STATUS_KEY, } from "../../drivers/native/pi-extension.js";
18
+ import { stderrHint } from "../../drivers/process.js";
19
+ import { oneLine } from "../../drivers/turn.js";
20
+ import { msg } from "../../i18n/index.js";
21
+ import { permissionModeLabel } from "../../permissions/modes.js";
22
+ import { CONFIG_IDS, buildConfigOptions, modelRefOf, modelValue, } from "./config.js";
23
+ import { CANCELLED_RESPONSE, planElicitation } from "./elicit.js";
24
+ import { PiEventMapper } from "./events.js";
25
+ import { BRIDGE_MODES, isBridgeMode, parseGateCall, verdictFor, } from "./gate.js";
26
+ import { promptCommand } from "./prompt.js";
27
+ import { replayUpdates } from "./replay.js";
28
+ function asRpcError(error) {
29
+ if (error instanceof RpcError)
30
+ return error;
31
+ if (error instanceof AmaError)
32
+ return new RpcError(RPC_ERRORS.internalError, error.message, { code: error.code });
33
+ return new RpcError(RPC_ERRORS.internalError, error.message);
34
+ }
35
+ const dataOf = (response) => (response["data"] ?? {});
36
+ export class PiBridgeSession {
37
+ init;
38
+ core;
39
+ mapper;
40
+ id;
41
+ configState = { models: [], levels: [] };
42
+ messageCount = 0;
43
+ running;
44
+ settle;
45
+ exitWaiters = new Set();
46
+ interrupted = false;
47
+ closed = false;
48
+ lastUsage;
49
+ mode = "default";
50
+ /** 挂起的 `session/request_permission`(取消与关闭时撤回)。 */
51
+ asks = new Set();
52
+ /** 桥自己拒绝的调用 → 回给模型的理由(扩展随后用 editor 对话框来取)。 */
53
+ denials = new Map();
54
+ /** 扩展报告的工具名(`setStatus`);没收到为 undefined。 */
55
+ tools;
56
+ resolveStatus;
57
+ statusSeen = new Promise((resolve) => (this.resolveStatus = resolve));
58
+ constructor(init) {
59
+ this.init = init;
60
+ this.id = init.id;
61
+ this.mapper = new PiEventMapper({
62
+ cwd: init.cwd,
63
+ emit: (update) => init.emit(update),
64
+ mcpServers: () => init.mcpServers,
65
+ });
66
+ this.core = new PiRpcCore({
67
+ transport: init.transport,
68
+ commands: init.info.commands,
69
+ onEvent: (record) => this.onRecord(record),
70
+ onUiRequest: (record) => this.onUiRequest(record),
71
+ onExit: (error) => this.onExit(error),
72
+ exitMessage: (hint) => msg().bridge.pi.exited(hint),
73
+ timeoutMessage: (command) => msg().bridge.pi.commandTimedOut(command),
74
+ });
75
+ }
76
+ get sessionId() {
77
+ return this.id;
78
+ }
79
+ get isRunning() {
80
+ return this.running !== undefined;
81
+ }
82
+ get existingMessages() {
83
+ return this.messageCount;
84
+ }
85
+ /** 握手:取状态、模型与推理强度;没有可用模型抛 `pi_no_model`。 */
86
+ async start(signal) {
87
+ const aborted = new Promise((_, reject) => {
88
+ if (signal?.aborted === true)
89
+ reject(new Error("aborted"));
90
+ signal?.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
91
+ });
92
+ void aborted.catch(() => undefined);
93
+ const run = async () => {
94
+ const state = dataOf(await this.request({ type: "get_state" }));
95
+ if (typeof state["sessionId"] === "string" && state["sessionId"] !== "")
96
+ this.id = state["sessionId"];
97
+ this.messageCount = typeof state["messageCount"] === "number" ? state["messageCount"] : 0;
98
+ const models = dataOf(await this.request({ type: "get_available_models" }))["models"];
99
+ const list = (Array.isArray(models) ? models : []).flatMap((m) => modelRefOf(m) ?? []);
100
+ const current = modelRefOf(state["model"]);
101
+ if (list.length === 0 && current === undefined)
102
+ throw new RpcError(RPC_ERRORS.internalError, msg().bridge.pi.noModel, {
103
+ code: "pi_no_model",
104
+ });
105
+ this.configState = {
106
+ models: list,
107
+ ...(current !== undefined ? { current } : {}),
108
+ levels: [],
109
+ ...(typeof state["thinkingLevel"] === "string" ? { level: state["thinkingLevel"] } : {}),
110
+ };
111
+ await this.refreshLevels();
112
+ // 扩展的能力报告通常早于 get_state 的应答到达;没到就最多再等一小会儿
113
+ await Promise.race([
114
+ this.statusSeen,
115
+ new Promise((resolve) => setTimeout(resolve, this.init.deps?.statusWaitMs ?? 300).unref()),
116
+ ]);
117
+ };
118
+ try {
119
+ await Promise.race([run(), aborted]);
120
+ }
121
+ catch (error) {
122
+ throw asRpcError(error);
123
+ }
124
+ }
125
+ async request(command) {
126
+ const response = await this.core.request(command);
127
+ if (response["success"] !== true)
128
+ throw new AmaError("agent_failed", oneLine(String(response["error"] ?? `${String(command["type"])} failed`), 300));
129
+ return response;
130
+ }
131
+ async refreshLevels() {
132
+ if (!this.init.info.capabilities.thinkingLevels)
133
+ return;
134
+ try {
135
+ const levels = dataOf(await this.request({ type: "get_available_thinking_levels" }))["levels"];
136
+ this.configState = {
137
+ ...this.configState,
138
+ levels: Array.isArray(levels)
139
+ ? levels.filter((l) => typeof l === "string")
140
+ : [],
141
+ };
142
+ }
143
+ catch {
144
+ // 读不到就不给 thought_level 项
145
+ }
146
+ }
147
+ configOptions() {
148
+ return buildConfigOptions(this.configState);
149
+ }
150
+ /** `session/set_config_option`:返回全部配置项的新状态;换模型之后重取推理强度并发 `config_option_update`。 */
151
+ async setConfigOption(id, value) {
152
+ const m = msg().bridge.config;
153
+ const state = this.configState;
154
+ if (id === CONFIG_IDS.model) {
155
+ const model = state.models.find((x) => modelValue(x) === value);
156
+ if (model === undefined)
157
+ throw new RpcError(RPC_ERRORS.invalidParams, m.invalidValue(id, value));
158
+ await this.change(id, { type: "set_model", provider: model.provider, modelId: model.id });
159
+ await this.syncState();
160
+ await this.refreshLevels();
161
+ const options = this.configOptions();
162
+ this.init.emit({ sessionUpdate: "config_option_update", configOptions: options });
163
+ void this.reportUsage();
164
+ return options;
165
+ }
166
+ if (id === CONFIG_IDS.thoughtLevel) {
167
+ if (!state.levels.includes(value))
168
+ throw new RpcError(RPC_ERRORS.invalidParams, m.invalidValue(id, value));
169
+ await this.change(id, { type: "set_thinking_level", level: value });
170
+ await this.syncState();
171
+ return this.configOptions();
172
+ }
173
+ throw new RpcError(RPC_ERRORS.invalidParams, m.unknownOption(id));
174
+ }
175
+ async change(id, command) {
176
+ try {
177
+ await this.request(command);
178
+ }
179
+ catch (error) {
180
+ throw new RpcError(RPC_ERRORS.invalidParams, msg().bridge.config.setFailed(id, error.message));
181
+ }
182
+ }
183
+ /** 改动之后以 `get_state` 为准(Pi 可能把推理强度夹到模型支持的范围)。 */
184
+ async syncState() {
185
+ try {
186
+ const state = dataOf(await this.request({ type: "get_state" }));
187
+ const current = modelRefOf(state["model"]);
188
+ this.configState = {
189
+ ...this.configState,
190
+ ...(current !== undefined ? { current } : {}),
191
+ ...(typeof state["thinkingLevel"] === "string" ? { level: state["thinkingLevel"] } : {}),
192
+ };
193
+ }
194
+ catch {
195
+ // 以本地记录为准
196
+ }
197
+ }
198
+ /** `session/load`:把已有消息回放成更新。 */
199
+ async replay() {
200
+ const data = dataOf(await this.request({ type: "get_messages" }));
201
+ const messages = Array.isArray(data["messages"]) ? data["messages"] : [];
202
+ for (const update of replayUpdates(messages, this.init.cwd, this.init.mcpServers))
203
+ this.init.emit(update);
204
+ }
205
+ /** `usage_update`:上下文占用与窗口、累计费用(USD);同值不重发,拿不到不发。 */
206
+ async reportUsage() {
207
+ if (this.core.exited || this.closed || !this.init.info.capabilities.sessionStats)
208
+ return;
209
+ try {
210
+ const stats = await Promise.race([
211
+ this.request({ type: "get_session_stats" }),
212
+ new Promise((resolve) => setTimeout(() => resolve({}), 5_000).unref()),
213
+ ]);
214
+ const data = dataOf(stats);
215
+ const context = (data["contextUsage"] ?? {});
216
+ const size = context["contextWindow"];
217
+ if (typeof size !== "number")
218
+ return;
219
+ const tokens = typeof context["tokens"] === "number" ? context["tokens"] : 0;
220
+ const cost = data["cost"];
221
+ const fromProvider = this.init.info.capabilities.costFromProvider
222
+ ? this.mapper.costIsFromProvider()
223
+ : undefined;
224
+ const update = {
225
+ sessionUpdate: "usage_update",
226
+ used: Math.max(0, Math.round(tokens)),
227
+ size: Math.max(0, Math.round(size)),
228
+ ...(typeof cost === "number" ? { cost: { amount: cost, currency: "USD" } } : {}),
229
+ ...(fromProvider !== undefined ? { _meta: { "armadra.pi": { fromProvider } } } : {}),
230
+ };
231
+ const key = JSON.stringify(update);
232
+ if (key === this.lastUsage)
233
+ return;
234
+ this.lastUsage = key;
235
+ this.init.emit(update);
236
+ }
237
+ catch {
238
+ // 统计拿不到不影响会话
239
+ }
240
+ }
241
+ async prompt(blocks) {
242
+ if (this.closed || this.core.exited)
243
+ throw this.exitedError();
244
+ if (this.running !== undefined)
245
+ throw new RpcError(RPC_ERRORS.invalidRequest, msg().bridge.session.busy);
246
+ const command = promptCommand(blocks);
247
+ this.mapper.resetTurn();
248
+ this.interrupted = false;
249
+ this.running = this.run(command);
250
+ try {
251
+ return await this.running;
252
+ }
253
+ catch (error) {
254
+ throw asRpcError(error);
255
+ }
256
+ finally {
257
+ this.running = undefined;
258
+ this.settle = undefined;
259
+ this.exitWaiters.clear();
260
+ }
261
+ }
262
+ async run(command) {
263
+ // 先让出一拍:`this.running` 赋值之后再写命令(同步回显的对端里事件可能立刻到达并触发 cancel)
264
+ await Promise.resolve();
265
+ const settled = new Promise((resolve) => (this.settle = resolve));
266
+ const response = await this.core.request(command);
267
+ if (response["success"] !== true)
268
+ throw new RpcError(RPC_ERRORS.internalError, msg().bridge.pi.promptRejected(oneLine(String(response["error"] ?? "unknown"), 300)));
269
+ const handled = this.init.info.capabilities.disposition && dataOf(response)["disposition"] === "handled";
270
+ let aborted = false;
271
+ if (!handled)
272
+ aborted = await Promise.race([settled, this.exitPromise()]);
273
+ await this.reportUsage();
274
+ return this.complete(aborted);
275
+ }
276
+ complete(aborted) {
277
+ const usage = this.mapper.turnUsage();
278
+ const result = (stopReason) => ({
279
+ stopReason,
280
+ ...(usage !== undefined ? { usage } : {}),
281
+ });
282
+ if (aborted || this.interrupted)
283
+ return result("cancelled");
284
+ const last = this.mapper.lastAssistant();
285
+ switch (last?.["stopReason"]) {
286
+ case "error":
287
+ throw new RpcError(RPC_ERRORS.internalError, msg().bridge.pi.turnFailed(oneLine(String(last["errorMessage"] ?? "unknown error"), 300)));
288
+ case "aborted":
289
+ return result("cancelled");
290
+ case "length":
291
+ return result("max_tokens");
292
+ default:
293
+ return result("end_turn");
294
+ }
295
+ }
296
+ /** `session/cancel`:撤回挂起的审批、发 `abort`,看门狗兜底。 */
297
+ cancel() {
298
+ const running = this.running;
299
+ if (running === undefined || this.closed)
300
+ return;
301
+ this.interrupted = true;
302
+ this.cancelPending();
303
+ void this.core.request({ type: "abort" }).catch(() => undefined);
304
+ armCancelWatchdog(this.init.transport, running.catch(() => undefined), {
305
+ ...this.init.deps,
306
+ log: (_level, message) => this.init.log(message),
307
+ });
308
+ }
309
+ /** 撤回挂起的审批与征询(客户端收到 `$/cancel_request`);Pi 一侧按拒绝 / 取消应答。 */
310
+ cancelPending() {
311
+ for (const controller of this.asks)
312
+ controller.abort();
313
+ }
314
+ async close() {
315
+ if (this.closed)
316
+ return;
317
+ this.closed = true;
318
+ this.cancelPending();
319
+ if (this.running !== undefined) {
320
+ this.interrupted = true;
321
+ this.core.write({ type: "abort" });
322
+ }
323
+ try {
324
+ await this.init.transport.terminate();
325
+ }
326
+ finally {
327
+ this.init.dispose();
328
+ }
329
+ }
330
+ exitedError() {
331
+ return new RpcError(RPC_ERRORS.internalError, msg().bridge.pi.exited(stderrHint(this.init.transport)), { code: "agent_exited" });
332
+ }
333
+ exitPromise() {
334
+ return new Promise((_, reject) => {
335
+ if (this.core.exited)
336
+ reject(this.core.exitError());
337
+ else
338
+ this.exitWaiters.add(reject);
339
+ });
340
+ }
341
+ onExit(error) {
342
+ for (const reject of this.exitWaiters)
343
+ reject(error);
344
+ this.exitWaiters.clear();
345
+ this.cancelPending();
346
+ }
347
+ onRecord(record) {
348
+ if (record["type"] === "agent_settled")
349
+ this.settle?.(record["aborted"] === true);
350
+ else
351
+ this.mapper.onEvent(record);
352
+ }
353
+ /** 当前模式与可选模式(`session/new|load|resume` 的 `modes`)。 */
354
+ modes() {
355
+ const desc = msg().bridge.modes;
356
+ return {
357
+ currentModeId: this.mode,
358
+ availableModes: BRIDGE_MODES.map((id) => ({
359
+ id,
360
+ name: permissionModeLabel(id),
361
+ description: desc[id],
362
+ })),
363
+ };
364
+ }
365
+ /** `session/set_mode`:立即生效(闸每次调用都问桥)。 */
366
+ setMode(id) {
367
+ if (!isBridgeMode(id))
368
+ throw new RpcError(RPC_ERRORS.invalidParams, msg().bridge.session.unknownMode(id));
369
+ this.mode = id;
370
+ this.init.emit({ sessionUpdate: "current_mode_update", currentModeId: id });
371
+ }
372
+ /** 扩展报告的能力:Pi 里有没有 `todo` / `subagent` / `questionnaire` 工具;没收到报告为 undefined。 */
373
+ capabilities() {
374
+ const tools = this.tools;
375
+ if (tools === undefined)
376
+ return undefined;
377
+ return {
378
+ todo: tools.includes("todo"),
379
+ subagent: tools.includes("subagent"),
380
+ questionnaire: tools.includes("questionnaire"),
381
+ };
382
+ }
383
+ /** 扩展 UI 请求:审批闸与拒绝理由、能力报告;其它对话框本批取消(后续批次接上征询)。 */
384
+ onUiRequest(record) {
385
+ const id = String(record["id"] ?? "");
386
+ const method = String(record["method"] ?? "");
387
+ const respond = (body) => this.core.write({ type: "extension_ui_response", id, ...body });
388
+ if (method === "confirm" && record["title"] === PI_GATE_TITLE) {
389
+ void this.onGate(record).then((confirmed) => respond({ confirmed }), () => respond({ confirmed: false }));
390
+ }
391
+ else if (method === "editor" && record["title"] === PI_REASON_TITLE) {
392
+ const key = String(record["prefill"] ?? "");
393
+ const reason = this.denials.get(key);
394
+ this.denials.delete(key);
395
+ respond(reason !== undefined ? { value: reason } : { cancelled: true });
396
+ }
397
+ else if (method === "setStatus" && record["statusKey"] === PI_STATUS_KEY) {
398
+ this.onStatus(record["statusText"]);
399
+ }
400
+ else if (method === "notify") {
401
+ if (record["notifyType"] === "warning" || record["notifyType"] === "error")
402
+ this.init.log(oneLine(String(record["message"] ?? ""), 200));
403
+ }
404
+ else if (method === "select" ||
405
+ method === "confirm" ||
406
+ method === "input" ||
407
+ method === "editor") {
408
+ void this.onDialog(record).then(respond, () => respond(CANCELLED_RESPONSE));
409
+ }
410
+ }
411
+ /** 其它扩展的对话框 → 征询(客户端声明了 `elicitation` 才转,否则取消并在 stderr 说一行)。 */
412
+ async onDialog(record) {
413
+ const plan = planElicitation(record);
414
+ const title = oneLine(String(record["title"] ?? record["method"] ?? ""), 80);
415
+ if (plan === undefined || !this.init.canElicit() || this.closed) {
416
+ this.init.log(msg().bridge.pi.dialogUnsupported(title));
417
+ return CANCELLED_RESPONSE;
418
+ }
419
+ const controller = new AbortController();
420
+ this.asks.add(controller);
421
+ // Pi 的 timeout 到点它自己按取消处理;这里同时撤回给客户端的请求($/cancel_request)
422
+ const timeout = record["timeout"];
423
+ const timer = typeof timeout === "number" && timeout > 0
424
+ ? setTimeout(() => controller.abort(), timeout)
425
+ : undefined;
426
+ timer?.unref();
427
+ try {
428
+ const answer = await this.init.askElicitation({ sessionId: this.id, mode: "form", message: plan.message, requestedSchema: plan.schema }, controller.signal);
429
+ if (controller.signal.aborted || answer.action !== "accept")
430
+ return CANCELLED_RESPONSE;
431
+ return plan.toResponse(answer.content);
432
+ }
433
+ finally {
434
+ clearTimeout(timer);
435
+ this.asks.delete(controller);
436
+ }
437
+ }
438
+ onStatus(text) {
439
+ try {
440
+ const status = JSON.parse(String(text ?? ""));
441
+ if (Array.isArray(status["tools"]))
442
+ this.tools = status["tools"].filter((t) => typeof t === "string");
443
+ if (Array.isArray(status["mcpFailures"]))
444
+ for (const failure of status["mcpFailures"])
445
+ this.init.log(msg().bridge.pi.mcpFailed(oneLine(String(failure), 200)));
446
+ }
447
+ catch {
448
+ // 不是我们的报告
449
+ }
450
+ this.resolveStatus?.();
451
+ }
452
+ /** 审批闸:按模式放行、拒绝,或把请求交给客户端(人)。返回是否放行。 */
453
+ async onGate(record) {
454
+ const call = parseGateCall(record["message"]);
455
+ if (call === undefined || this.closed)
456
+ return false;
457
+ const verdict = verdictFor(this.mode, call);
458
+ if (verdict.kind === "deny") {
459
+ this.denials.set(call.id, verdict.reason);
460
+ return false;
461
+ }
462
+ if (verdict.kind === "ask" && !(await this.askHuman(call)))
463
+ return false;
464
+ this.mapper.markRunning(call.id);
465
+ return true;
466
+ }
467
+ /** `session/request_permission`(allow_once / reject_once);客户端取消、出错或会话取消都按拒绝。 */
468
+ async askHuman(call) {
469
+ if (this.interrupted)
470
+ return false;
471
+ const controller = new AbortController();
472
+ this.asks.add(controller);
473
+ const core = msg().acp.core;
474
+ try {
475
+ const fields = this.mapper.describe(call.tool, call.input, {
476
+ ...(call.parent !== undefined ? { parentToolCallId: call.parent } : {}),
477
+ });
478
+ const answer = await this.init.askPermission({
479
+ sessionId: this.id,
480
+ toolCall: { toolCallId: call.id, status: "pending", ...fields },
481
+ options: [
482
+ { optionId: "allow_once", name: core.allowOnce, kind: "allow_once" },
483
+ { optionId: "reject_once", name: core.rejectOnce, kind: "reject_once" },
484
+ ],
485
+ }, controller.signal);
486
+ return (!controller.signal.aborted &&
487
+ answer.outcome.outcome === "selected" &&
488
+ answer.outcome.optionId === "allow_once");
489
+ }
490
+ catch {
491
+ return false;
492
+ }
493
+ finally {
494
+ this.asks.delete(controller);
495
+ }
496
+ }
497
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Pi 工具调用 → ACP 工具调用的展示字段(#254):标题、类别、位置、结果内容,以及 MCP 工具名的拆解。
3
+ *
4
+ * Pi 把 MCP 工具注册成 `mcp__<server>__<tool>`,名字里除字母、数字、`_` 以外的字符都换成 `_`;拆回原服务器名时
5
+ * 只对桥自己注册过的服务器匹配(取最长的),认不出的当普通工具。
6
+ */
7
+ import type { AcpPlanEntry, AcpToolCallContent, AcpToolCallLocation } from "../../drivers/acp/types.js";
8
+ import type { AcpToolKind } from "../../drivers/types.js";
9
+ import type { Json } from "../../drivers/native/pi-rpc-core.js";
10
+ export type { Json };
11
+ /** Pi 对 MCP 工具名的规整:字母、数字、`_` 以外的字符换成 `_`。 */
12
+ export declare function piToolSegment(name: string): string;
13
+ export interface McpToolRef {
14
+ /** 客户端给的服务器名(原样)。 */
15
+ server: string;
16
+ /** Pi 名字里 `mcp__<server>__` 之后的部分。 */
17
+ tool: string;
18
+ }
19
+ /** 认出桥注册过的 MCP 工具;`servers` 是客户端给的服务器名。 */
20
+ export declare function mcpToolOf(name: string, servers: readonly string[]): McpToolRef | undefined;
21
+ /** 标题:MCP 工具写成 `<服务器>: <工具>`,其余沿用驱动的规则。 */
22
+ export declare function bridgeToolTitle(tool: string, input: Json, mcp?: McpToolRef): string;
23
+ export declare function piToolLocations(input: Json, cwd: string): AcpToolCallLocation[] | undefined;
24
+ /** Pi 的 `{content: [...]}` 结果 → ACP 内容(文本前 4 KB,图片原样;没有内容返回 undefined)。 */
25
+ export declare function piResultContent(result: unknown): AcpToolCallContent[] | undefined;
26
+ /** 工具类别:驱动的规则之上,`todo` 是 `think`。 */
27
+ export declare function piToolKind(tool: string): AcpToolKind;
28
+ /** Pi 的 subagent 扩展的工具名。 */
29
+ export declare const SUBAGENT_TOOL = "subagent";
30
+ /** 子 Agent 调用的 `_meta["armadra.subagent"]`:单个 `{agent, task}`;并行 / 链式带 `tasks`。 */
31
+ export declare function subagentMeta(input: Json): Json | undefined;
32
+ /**
33
+ * 工具结果里的 `details.todos` → ACP 计划条目(每次整表)。条目形如 `{text, done}` 或 `{content, status}`
34
+ * (`id`、`priority` 可有可无);没有 `todos` 数组返回 undefined。
35
+ */
36
+ export declare function planEntriesOf(details: unknown): AcpPlanEntry[] | undefined;
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Pi 工具调用 → ACP 工具调用的展示字段(#254):标题、类别、位置、结果内容,以及 MCP 工具名的拆解。
3
+ *
4
+ * Pi 把 MCP 工具注册成 `mcp__<server>__<tool>`,名字里除字母、数字、`_` 以外的字符都换成 `_`;拆回原服务器名时
5
+ * 只对桥自己注册过的服务器匹配(取最长的),认不出的当普通工具。
6
+ */
7
+ import { isAbsolute, resolve } from "node:path";
8
+ import { piToolTitle } from "../../drivers/native/pi-rpc.js";
9
+ import { msg } from "../../i18n/index.js";
10
+ import { TOOL_OUTPUT_LIMIT } from "../../modes/acp/acp-tool-text.js";
11
+ import { piToolKind as driverToolKind } from "../../drivers/native/pi-rpc.js";
12
+ /** Pi 对 MCP 工具名的规整:字母、数字、`_` 以外的字符换成 `_`。 */
13
+ export function piToolSegment(name) {
14
+ return name.replace(/[^A-Za-z0-9_]/g, "_");
15
+ }
16
+ /** 认出桥注册过的 MCP 工具;`servers` 是客户端给的服务器名。 */
17
+ export function mcpToolOf(name, servers) {
18
+ if (!name.startsWith("mcp__"))
19
+ return undefined;
20
+ let best;
21
+ let bestLength = -1;
22
+ for (const server of servers) {
23
+ const prefix = `mcp__${piToolSegment(server)}__`;
24
+ if (name.startsWith(prefix) && prefix.length > bestLength) {
25
+ best = { server, tool: name.slice(prefix.length) };
26
+ bestLength = prefix.length;
27
+ }
28
+ }
29
+ return best;
30
+ }
31
+ function argOf(args, ...keys) {
32
+ for (const key of keys) {
33
+ const value = args[key];
34
+ if (typeof value === "string" && value !== "")
35
+ return value;
36
+ }
37
+ return undefined;
38
+ }
39
+ /** 标题:MCP 工具写成 `<服务器>: <工具>`,其余沿用驱动的规则。 */
40
+ export function bridgeToolTitle(tool, input, mcp) {
41
+ return mcp !== undefined ? `${mcp.server}: ${mcp.tool}` : piToolTitle(tool, input);
42
+ }
43
+ export function piToolLocations(input, cwd) {
44
+ const path = argOf(input, "path");
45
+ if (path === undefined)
46
+ return undefined;
47
+ return [{ path: isAbsolute(path) ? path : resolve(cwd, path) }];
48
+ }
49
+ /** Pi 的 `{content: [...]}` 结果 → ACP 内容(文本前 4 KB,图片原样;没有内容返回 undefined)。 */
50
+ export function piResultContent(result) {
51
+ if (result === null || typeof result !== "object")
52
+ return undefined;
53
+ const blocks = result["content"];
54
+ if (!Array.isArray(blocks))
55
+ return undefined;
56
+ const out = [];
57
+ let text = "";
58
+ for (const block of blocks) {
59
+ if (block["type"] === "text" && typeof block["text"] === "string")
60
+ text += block["text"];
61
+ else if (block["type"] === "image" &&
62
+ typeof block["data"] === "string" &&
63
+ typeof block["mimeType"] === "string")
64
+ out.push({
65
+ type: "content",
66
+ content: { type: "image", data: block["data"], mimeType: block["mimeType"] },
67
+ });
68
+ }
69
+ if (text !== "")
70
+ out.unshift({
71
+ type: "content",
72
+ content: {
73
+ type: "text",
74
+ text: text.length > TOOL_OUTPUT_LIMIT
75
+ ? `${text.slice(0, TOOL_OUTPUT_LIMIT)}\n${msg().acp.tools.truncated(text.length)}`
76
+ : text,
77
+ },
78
+ });
79
+ return out.length > 0 ? out : undefined;
80
+ }
81
+ /** 工具类别:驱动的规则之上,`todo` 是 `think`。 */
82
+ export function piToolKind(tool) {
83
+ return tool === "todo" ? "think" : driverToolKind(tool);
84
+ }
85
+ /** Pi 的 subagent 扩展的工具名。 */
86
+ export const SUBAGENT_TOOL = "subagent";
87
+ /** 子 Agent 调用的 `_meta["armadra.subagent"]`:单个 `{agent, task}`;并行 / 链式带 `tasks`。 */
88
+ export function subagentMeta(input) {
89
+ const pair = (v) => {
90
+ const item = (v ?? {});
91
+ return typeof item["agent"] === "string" && typeof item["task"] === "string"
92
+ ? { agent: item["agent"], task: item["task"] }
93
+ : undefined;
94
+ };
95
+ const single = pair(input);
96
+ if (single !== undefined)
97
+ return single;
98
+ for (const key of ["tasks", "chain"]) {
99
+ const list = input[key];
100
+ if (Array.isArray(list)) {
101
+ const tasks = list.flatMap((v) => pair(v) ?? []);
102
+ if (tasks.length > 0)
103
+ return { mode: key === "chain" ? "chain" : "parallel", tasks };
104
+ }
105
+ }
106
+ return undefined;
107
+ }
108
+ /**
109
+ * 工具结果里的 `details.todos` → ACP 计划条目(每次整表)。条目形如 `{text, done}` 或 `{content, status}`
110
+ * (`id`、`priority` 可有可无);没有 `todos` 数组返回 undefined。
111
+ */
112
+ export function planEntriesOf(details) {
113
+ const todos = details?.["todos"];
114
+ if (!Array.isArray(todos))
115
+ return undefined;
116
+ return todos.flatMap((todo) => {
117
+ const content = [todo["text"], todo["content"], todo["title"]].find((v) => typeof v === "string" && v !== "");
118
+ if (content === undefined)
119
+ return [];
120
+ const raw = typeof todo["status"] === "string" ? todo["status"].toLowerCase() : "";
121
+ const status = todo["done"] === true || raw === "completed" || raw === "done"
122
+ ? "completed"
123
+ : raw === "in_progress" || raw === "in-progress" || raw === "active"
124
+ ? "in_progress"
125
+ : "pending";
126
+ const priority = todo["priority"] === "high" || todo["priority"] === "low" ? todo["priority"] : "medium";
127
+ return [{ content, priority, status }];
128
+ });
129
+ }