pi-antigravity-bridge 0.1.1 → 0.1.3
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 +15 -0
- package/package.json +1 -1
- package/src/acp/process-manager.ts +11 -1
- package/src/index.ts +47 -2
- package/src/session/turn-coordinator.ts +442 -145
- package/src/stream/event-mapper.ts +58 -85
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.1.3] - 2026-11-21
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- 修复任务执行途中发送消息会意外中断当前任务并导致后续消息卡在运行态无法输出的问题。
|
|
8
|
+
- 修复中断任务后连续发送新消息时可能因后端会话未完成清理而挂起无响应的问题。
|
|
9
|
+
- 修复新会话首轮多步工具调用期间状态栏缓存命中率始终显示为 0 的问题。
|
|
10
|
+
|
|
11
|
+
## [0.1.2] - 2026-11-21
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- 修复工具调用期间界面出现重复空白参数工具卡片(如 `read ...`)的问题,并改进同轮并行工具调用的聚合展示。
|
|
16
|
+
- 修复按下 `Esc` 时无法立即中断当前模型响应及工具执行流程的问题。
|
|
17
|
+
|
|
3
18
|
## [0.1.1] - 2026-11-21
|
|
4
19
|
|
|
5
20
|
### Changed
|
package/package.json
CHANGED
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
|
|
24
24
|
export const BRIDGE_AGENT_NAME = "pi-bridge";
|
|
25
25
|
export const CLIENT_INFO_NAME = "pi-antigravity-bridge";
|
|
26
|
-
export const CLIENT_INFO_VERSION = "0.1.
|
|
26
|
+
export const CLIENT_INFO_VERSION = "0.1.3";
|
|
27
27
|
|
|
28
28
|
export class AcpRpcError extends Error {
|
|
29
29
|
readonly code: number;
|
|
@@ -758,6 +758,16 @@ export class AcpProcessManager {
|
|
|
758
758
|
}
|
|
759
759
|
}
|
|
760
760
|
|
|
761
|
+
/** 从连接池驱逐并强制销毁已卡死或状态异常的单个子进程连接 */
|
|
762
|
+
async evict(target: AcpClientConnection): Promise<void> {
|
|
763
|
+
for (const [key, conn] of this.pool.entries()) {
|
|
764
|
+
if (conn === target) {
|
|
765
|
+
this.pool.delete(key);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
await target.dispose();
|
|
769
|
+
}
|
|
770
|
+
|
|
761
771
|
async disposeAll(): Promise<void> {
|
|
762
772
|
const connections = Array.from(this.pool.values());
|
|
763
773
|
this.pool.clear();
|
package/src/index.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
|
-
import type {
|
|
4
|
+
import type {
|
|
5
|
+
ImageContent,
|
|
6
|
+
OAuthCredentials,
|
|
7
|
+
OAuthLoginCallbacks,
|
|
8
|
+
TextContent,
|
|
9
|
+
} from "@earendil-works/pi-ai";
|
|
5
10
|
import type {
|
|
6
11
|
ExtensionAPI,
|
|
7
12
|
ExtensionContext,
|
|
@@ -272,10 +277,50 @@ export default function antigravityBridgeExtension(pi: ExtensionAPI): void {
|
|
|
272
277
|
toolActivation.syncForContext(ctx, coordinator.config);
|
|
273
278
|
});
|
|
274
279
|
|
|
280
|
+
// 6. ACP 单会话单活跃轮次协议约束:运行中按 Enter 发送的新消息统一转入 Follow-up 排队队列,
|
|
281
|
+
// 保持原任务完整执行完毕后再自动开启下一轮真实用户请求(同时支持 Alt+Up 编辑队列与 Esc 撤回)。
|
|
282
|
+
pi.on("input", async (event, ctx) => {
|
|
283
|
+
if (
|
|
284
|
+
ctx.model?.provider === ANTIGRAVITY_PROVIDER_ID &&
|
|
285
|
+
event.streamingBehavior === "steer" &&
|
|
286
|
+
!ctx.isIdle()
|
|
287
|
+
) {
|
|
288
|
+
const parts: Array<TextContent | ImageContent> = [];
|
|
289
|
+
if (event.text.length > 0) {
|
|
290
|
+
parts.push({ type: "text", text: event.text });
|
|
291
|
+
}
|
|
292
|
+
if (event.images && event.images.length > 0) {
|
|
293
|
+
parts.push(...event.images);
|
|
294
|
+
}
|
|
295
|
+
await Promise.resolve(
|
|
296
|
+
pi.sendUserMessage(parts.length > 0 ? parts : event.text, {
|
|
297
|
+
deliverAs: "followUp",
|
|
298
|
+
expandPromptTemplates: event.source === "interactive",
|
|
299
|
+
}),
|
|
300
|
+
);
|
|
301
|
+
return { action: "handled" };
|
|
302
|
+
}
|
|
303
|
+
return { action: "continue" };
|
|
304
|
+
});
|
|
305
|
+
|
|
275
306
|
pi.on("turn_end", async (event: TurnEndEvent, ctx) => {
|
|
276
307
|
if (ctx.model?.provider !== ANTIGRAVITY_PROVIDER_ID) return;
|
|
308
|
+
const stopReason = event.message.role === "assistant" ? event.message.stopReason : undefined;
|
|
309
|
+
if (stopReason === "toolUse") {
|
|
310
|
+
updateAntigravityStatusBar(ctx, coordinator.config, coordinator.getTelemetrySnapshot());
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
if (stopReason === "aborted" || event.outcome === "aborted") {
|
|
314
|
+
coordinator.cancelActiveTurnForPiSession(ctx.sessionManager.getSessionId());
|
|
315
|
+
}
|
|
277
316
|
const visible = extractVisibleMessages(event.context.llmMessages);
|
|
278
|
-
await coordinator.persistTurnAnchor(visible);
|
|
317
|
+
await coordinator.persistTurnAnchor(visible, ctx.sessionManager.getSessionId());
|
|
318
|
+
updateAntigravityStatusBar(ctx, coordinator.config, coordinator.getTelemetrySnapshot());
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
pi.on("agent_end", (_event, ctx) => {
|
|
322
|
+
// 若用户在本地工具执行间隙按下 Esc 中断退出,同步结算挂起的后台 MCP 请求并异步发送 session/cancel
|
|
323
|
+
coordinator.cancelActiveTurnForPiSession(ctx.sessionManager.getSessionId());
|
|
279
324
|
updateAntigravityStatusBar(ctx, coordinator.config, coordinator.getTelemetrySnapshot());
|
|
280
325
|
});
|
|
281
326
|
|
|
@@ -65,7 +65,6 @@ import {
|
|
|
65
65
|
|
|
66
66
|
type PumpQueueItem =
|
|
67
67
|
| { kind: "acp_update"; update: AcpSessionUpdatePayload }
|
|
68
|
-
| { kind: "mcp_announced"; placeholderId: string; hintName: string }
|
|
69
68
|
| { kind: "mcp_parked"; call: ParkedToolCall }
|
|
70
69
|
| { kind: "prompt_done"; response: AcpPromptResponse }
|
|
71
70
|
| { kind: "prompt_error"; error: unknown };
|
|
@@ -127,6 +126,12 @@ interface ActiveTurnPump {
|
|
|
127
126
|
cancelledByHoldTimeout: boolean;
|
|
128
127
|
/** 本轮前序中间 `toolUse` 步已经记账的输出 Token 累计数 */
|
|
129
128
|
accountedOutputTokens: number;
|
|
129
|
+
/** 已收到 ACP 前置 `tool_call` 宣告但 HTTP MCP `POST /mcp` 仍在途的并发调用计数 */
|
|
130
|
+
pendingAnnouncedMcpCount: number;
|
|
131
|
+
/** 已向 Pi 推理流发出的宿主 MCP `callId` 集合,防止误结算仍在队列中待消费的后续工具请求 */
|
|
132
|
+
readonly emittedMcpCallIds: Set<string>;
|
|
133
|
+
/** 运行中排队进入的转向用户消息,在工具结果结算或本轮 `prompt_done` 收口时安全串行投递 */
|
|
134
|
+
readonly pendingSteeringUsers: UserMessage[];
|
|
130
135
|
}
|
|
131
136
|
|
|
132
137
|
interface ManagedSessionLedger {
|
|
@@ -158,6 +163,8 @@ interface ManagedSessionLedger {
|
|
|
158
163
|
/** 记录已确认为宿主 MCP 宣告的 ACP `toolCallId`,防止省略 `title` 的 `tool_call_update` 在 hybrid 下串扰 */
|
|
159
164
|
hostMcpAnnouncementIds: Set<string>;
|
|
160
165
|
activePump?: ActiveTurnPump;
|
|
166
|
+
/** 当前会话在后端仍在途的 `session/prompt` RPC Promise(严禁在它结算前重叠发送下一条 `session/prompt`) */
|
|
167
|
+
inFlightPrompt?: Promise<void>;
|
|
161
168
|
}
|
|
162
169
|
|
|
163
170
|
const DEFAULT_SESSION_KEY = "__default_pi_session__";
|
|
@@ -242,9 +249,7 @@ export class TurnCoordinator {
|
|
|
242
249
|
cancelAgySessionById(agySessionId: string): void {
|
|
243
250
|
const ledger = this.ledgersByAgyId.get(agySessionId);
|
|
244
251
|
if (!ledger) return;
|
|
245
|
-
this.
|
|
246
|
-
this.mirrorBroker.abortSessionCalls(agySessionId, "Cancelled by user");
|
|
247
|
-
void ledger.conn.request("session/cancel", { sessionId: agySessionId }).catch(() => {});
|
|
252
|
+
this.abortLedgerTurnNonBlocking(ledger);
|
|
248
253
|
}
|
|
249
254
|
|
|
250
255
|
/** 实时切换当前活跃会话的 AGY 原生执行模式(`default` | `accept-edits` | `plan`) */
|
|
@@ -281,13 +286,20 @@ export class TurnCoordinator {
|
|
|
281
286
|
/** 在每轮对话稳定完结时,将最新会话锚点(含可选 SQLite 检查点)追加进 Pi `.jsonl` 分支 */
|
|
282
287
|
async persistTurnAnchor(
|
|
283
288
|
messagesSnapshot?: readonly (UserMessage | AssistantMessage | ToolResultMessage)[],
|
|
289
|
+
piSessionId?: string,
|
|
284
290
|
): Promise<void> {
|
|
285
|
-
const key = this.resolveCurrentPiSessionKey();
|
|
291
|
+
const key = this.resolveCurrentPiSessionKey(piSessionId);
|
|
286
292
|
const ledger = this.ledgers.get(key);
|
|
287
293
|
if (!ledger || ledger.activePump || ledger.parkedCalls.size > 0) {
|
|
288
294
|
return;
|
|
289
295
|
}
|
|
290
296
|
|
|
297
|
+
// 若前序轮次刚执行过取消,等待后端在途 session/prompt 收敛(正常约数毫秒);若连接卡死则跳过写入污染锚点
|
|
298
|
+
const settled = await this.waitForInFlightPrompt(ledger, 1_500);
|
|
299
|
+
if (!settled || ledger.activePump || ledger.parkedCalls.size > 0) {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
291
303
|
if (messagesSnapshot) {
|
|
292
304
|
ledger.syncedMessageCount = messagesSnapshot.length;
|
|
293
305
|
ledger.syncedTranscriptDigest = computeTranscriptDigest(messagesSnapshot);
|
|
@@ -337,6 +349,96 @@ export class TurnCoordinator {
|
|
|
337
349
|
return anchor;
|
|
338
350
|
}
|
|
339
351
|
|
|
352
|
+
/**
|
|
353
|
+
* 当用户按下 `Esc` 中断流或在工具执行期间中断整个 Agent Run 时,
|
|
354
|
+
* 0 毫秒同步清理挂起中的 MCP 工具调用与活跃队列,并发送 ACP 单向 `session/cancel` 通知。
|
|
355
|
+
*/
|
|
356
|
+
cancelActiveTurnForPiSession(piSessionId?: string): void {
|
|
357
|
+
const key = piSessionId || this.resolveCurrentPiSessionKey();
|
|
358
|
+
const ledger = this.ledgers.get(key);
|
|
359
|
+
if (!ledger) return;
|
|
360
|
+
if (!ledger.activePump && ledger.parkedCalls.size === 0 && !ledger.inFlightPrompt) {
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
this.abortLedgerTurnNonBlocking(ledger);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private abortLedgerTurnNonBlocking(ledger: ManagedSessionLedger): void {
|
|
367
|
+
this.httpMcpBridge.markSessionTurnCancelled(ledger.agySessionId);
|
|
368
|
+
this.mirrorBroker.abortSessionCalls(ledger.agySessionId, "Aborted");
|
|
369
|
+
for (const [, parked] of ledger.parkedCalls) {
|
|
370
|
+
parked.settle({
|
|
371
|
+
isError: true,
|
|
372
|
+
content: [{ type: "text", text: "Cancelled" }],
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
ledger.parkedCalls.clear();
|
|
376
|
+
if (ledger.activePump) {
|
|
377
|
+
ledger.activePump.finished = true;
|
|
378
|
+
}
|
|
379
|
+
ledger.activePump = undefined;
|
|
380
|
+
ledger.conn.notify("session/cancel", { sessionId: ledger.agySessionId });
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* 等待会话在途的 `session/prompt` 请求结算完成。
|
|
385
|
+
* 若超出最大容忍时间仍未结算(例如底层进程死锁),返回 `false` 以便上层驱逐卡死进程并无缝重建。
|
|
386
|
+
*/
|
|
387
|
+
private async waitForInFlightPrompt(
|
|
388
|
+
ledger: ManagedSessionLedger,
|
|
389
|
+
timeoutMs: number,
|
|
390
|
+
signal?: AbortSignal,
|
|
391
|
+
): Promise<boolean> {
|
|
392
|
+
const inflight = ledger.inFlightPrompt;
|
|
393
|
+
if (!inflight) return true;
|
|
394
|
+
if (signal?.aborted) return false;
|
|
395
|
+
|
|
396
|
+
return new Promise<boolean>((resolve) => {
|
|
397
|
+
let done = false;
|
|
398
|
+
const finish = (ok: boolean) => {
|
|
399
|
+
if (done) return;
|
|
400
|
+
done = true;
|
|
401
|
+
clearTimeout(timer);
|
|
402
|
+
signal?.removeEventListener("abort", onAbort);
|
|
403
|
+
resolve(ok);
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
const onAbort = () => finish(false);
|
|
407
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
408
|
+
|
|
409
|
+
const timer = setTimeout(() => {
|
|
410
|
+
finish(false);
|
|
411
|
+
}, timeoutMs);
|
|
412
|
+
|
|
413
|
+
void inflight.finally(() => {
|
|
414
|
+
finish(true);
|
|
415
|
+
});
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** 驱逐已卡死的后端连接与会话绑定,确保下一轮消息能通过健康新进程正常响应 */
|
|
420
|
+
private async discardWedgedLedger(ledger: ManagedSessionLedger): Promise<void> {
|
|
421
|
+
this.ledgers.delete(ledger.piSessionKey);
|
|
422
|
+
this.ledgersByAgyId.delete(ledger.agySessionId);
|
|
423
|
+
|
|
424
|
+
for (const [, parked] of ledger.parkedCalls) {
|
|
425
|
+
parked.settle({
|
|
426
|
+
isError: true,
|
|
427
|
+
content: [{ type: "text", text: "Session reset" }],
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
ledger.parkedCalls.clear();
|
|
431
|
+
ledger.detachedCallIds.clear();
|
|
432
|
+
ledger.activePump = undefined;
|
|
433
|
+
ledger.inFlightPrompt = undefined;
|
|
434
|
+
|
|
435
|
+
if (ledger.mcpToken) {
|
|
436
|
+
this.httpMcpBridge.unregisterSessionBinding(ledger.mcpToken);
|
|
437
|
+
}
|
|
438
|
+
this.mirrorBroker.abortSessionCalls(ledger.agySessionId, "Session reset");
|
|
439
|
+
await this.processManager.evict(ledger.conn);
|
|
440
|
+
}
|
|
441
|
+
|
|
340
442
|
/** Pi `registerProvider` 核心流式入口 */
|
|
341
443
|
streamSimple(
|
|
342
444
|
model: Model<Api>,
|
|
@@ -347,13 +449,32 @@ export class TurnCoordinator {
|
|
|
347
449
|
thinkingLevel: options?.reasoning,
|
|
348
450
|
});
|
|
349
451
|
|
|
350
|
-
|
|
452
|
+
const signal = options?.signal;
|
|
453
|
+
if (signal?.aborted) {
|
|
454
|
+
this.cancelActiveTurnForPiSession(options?.sessionId);
|
|
455
|
+
writer.fail("aborted", "Request aborted by user");
|
|
456
|
+
return writer.stream;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const onImmediateAbort = () => {
|
|
460
|
+
this.cancelActiveTurnForPiSession(options?.sessionId);
|
|
351
461
|
if (!writer.isTerminated) {
|
|
352
|
-
|
|
353
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
354
|
-
writer.fail(isAborted ? "aborted" : "error", msg);
|
|
462
|
+
writer.fail("aborted", "Request aborted by user");
|
|
355
463
|
}
|
|
356
|
-
}
|
|
464
|
+
};
|
|
465
|
+
signal?.addEventListener("abort", onImmediateAbort, { once: true });
|
|
466
|
+
|
|
467
|
+
void this.runStreamStep(writer, model, context, options)
|
|
468
|
+
.catch((error) => {
|
|
469
|
+
if (!writer.isTerminated) {
|
|
470
|
+
const isAborted = Boolean(signal?.aborted);
|
|
471
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
472
|
+
writer.fail(isAborted ? "aborted" : "error", msg);
|
|
473
|
+
}
|
|
474
|
+
})
|
|
475
|
+
.finally(() => {
|
|
476
|
+
signal?.removeEventListener("abort", onImmediateAbort);
|
|
477
|
+
});
|
|
357
478
|
|
|
358
479
|
return writer.stream;
|
|
359
480
|
}
|
|
@@ -465,12 +586,9 @@ export class TurnCoordinator {
|
|
|
465
586
|
if (isHostMcpAnnouncement) {
|
|
466
587
|
ledger.hostMcpAnnouncementIds.add(update.toolCallId);
|
|
467
588
|
this.httpMcpBridge.recordAcpToolAnnouncement(sessionId, update.title || "");
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
placeholderId: update.toolCallId,
|
|
472
|
-
hintName,
|
|
473
|
-
});
|
|
589
|
+
if (ledger.activePump && !ledger.activePump.finished) {
|
|
590
|
+
ledger.activePump.pendingAnnouncedMcpCount++;
|
|
591
|
+
}
|
|
474
592
|
return;
|
|
475
593
|
}
|
|
476
594
|
|
|
@@ -492,21 +610,6 @@ export class TurnCoordinator {
|
|
|
492
610
|
ledger.activePump?.queue.push({ kind: "acp_update", update });
|
|
493
611
|
}
|
|
494
612
|
|
|
495
|
-
private extractHintToolNameFromAnnouncement(
|
|
496
|
-
ledger: ManagedSessionLedger,
|
|
497
|
-
rawTitle: string | undefined,
|
|
498
|
-
): string {
|
|
499
|
-
if (!rawTitle) return ledger.hostMcpTools[0]?.name ?? "tool";
|
|
500
|
-
const lower = rawTitle.toLowerCase();
|
|
501
|
-
for (const tool of ledger.hostMcpTools) {
|
|
502
|
-
if (lower === tool.name.toLowerCase() || lower.endsWith(`_${tool.name.toLowerCase()}`)) {
|
|
503
|
-
return tool.name;
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
const stripped = rawTitle.replace(/^mcp_pi_tools_/i, "").trim();
|
|
507
|
-
return stripped || rawTitle;
|
|
508
|
-
}
|
|
509
|
-
|
|
510
613
|
private isHostMcpToolEvent(
|
|
511
614
|
ledger: ManagedSessionLedger,
|
|
512
615
|
rawTitle: string | undefined,
|
|
@@ -578,7 +681,9 @@ export class TurnCoordinator {
|
|
|
578
681
|
// 2b. 模式 A / Hybrid:镜像工具执行完毕,无缝续接后台同一活跃 ACP Turn 队列(含已缓存的尾部事件与终态)
|
|
579
682
|
if (existing.activePump) {
|
|
580
683
|
const { trailingUsers } = this.collectRecentToolResultsAndSteeringUsers(visibleMessages);
|
|
581
|
-
|
|
684
|
+
if (trailingUsers.length > 0) {
|
|
685
|
+
existing.activePump.pendingSteeringUsers.push(...trailingUsers);
|
|
686
|
+
}
|
|
582
687
|
writer.setResponseMetadata({
|
|
583
688
|
responseId: existing.agySessionId,
|
|
584
689
|
providerThinkingLevel: existing.appliedThoughtLevel,
|
|
@@ -591,24 +696,39 @@ export class TurnCoordinator {
|
|
|
591
696
|
return;
|
|
592
697
|
}
|
|
593
698
|
|
|
594
|
-
// 2c.
|
|
595
|
-
const
|
|
596
|
-
if (
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
)
|
|
605
|
-
|
|
699
|
+
// 2c. 连续正常追问:先确认上一轮在途请求已完全收敛;若底层卡死则自动驱逐重建,否则直接复用会话与缓存
|
|
700
|
+
const idleOk = await this.waitForInFlightPrompt(existing, 2_500, options?.signal);
|
|
701
|
+
if (!idleOk) {
|
|
702
|
+
if (options?.signal?.aborted) {
|
|
703
|
+
writer.fail("aborted", "Request aborted by user");
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
await this.discardWedgedLedger(existing);
|
|
707
|
+
} else {
|
|
708
|
+
const continuationPrompts = this.tryExtractIncrementalUserPrompts(existing, visibleMessages);
|
|
709
|
+
if (continuationPrompts && existing.toolsDigest === toolsDigest) {
|
|
710
|
+
await this.executePromptOnLedger(
|
|
711
|
+
existing,
|
|
712
|
+
continuationPrompts,
|
|
713
|
+
visibleMessages,
|
|
714
|
+
writer,
|
|
715
|
+
model,
|
|
716
|
+
options,
|
|
717
|
+
);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
606
720
|
}
|
|
607
721
|
}
|
|
608
722
|
|
|
609
723
|
// 3. 会话不存在、工具集/模式变更或历史分支偏离:安全拆解旧会话并按三级状态机重建/恢复
|
|
610
|
-
|
|
611
|
-
|
|
724
|
+
const stillExisting = this.ledgers.get(piSessionKey);
|
|
725
|
+
if (stillExisting) {
|
|
726
|
+
const settled = await this.waitForInFlightPrompt(stillExisting, 1_500, options?.signal);
|
|
727
|
+
if (!settled) {
|
|
728
|
+
await this.discardWedgedLedger(stillExisting);
|
|
729
|
+
} else {
|
|
730
|
+
await this.teardownLedger(stillExisting);
|
|
731
|
+
}
|
|
612
732
|
}
|
|
613
733
|
|
|
614
734
|
const { ledger, initialPromptBlocks } = await this.bootstrapOrRestoreLedger({
|
|
@@ -672,21 +792,6 @@ export class TurnCoordinator {
|
|
|
672
792
|
return { recentToolResults, trailingUsers };
|
|
673
793
|
}
|
|
674
794
|
|
|
675
|
-
private forwardSteeringUsersIfPresent(
|
|
676
|
-
ledger: ManagedSessionLedger,
|
|
677
|
-
trailingUsers: readonly UserMessage[],
|
|
678
|
-
): void {
|
|
679
|
-
if (trailingUsers.length === 0) return;
|
|
680
|
-
const steerBlocks = convertUserMessagesToPromptBlocks(trailingUsers);
|
|
681
|
-
if (steerBlocks.length === 0) return;
|
|
682
|
-
void ledger.conn
|
|
683
|
-
.request("session/prompt", {
|
|
684
|
-
sessionId: ledger.agySessionId,
|
|
685
|
-
prompt: steerBlocks,
|
|
686
|
-
})
|
|
687
|
-
.catch(() => {});
|
|
688
|
-
}
|
|
689
|
-
|
|
690
795
|
private async continueFromParkedOrDetachedToolResults(
|
|
691
796
|
ledger: ManagedSessionLedger,
|
|
692
797
|
writer: StepStreamWriter,
|
|
@@ -707,7 +812,7 @@ export class TurnCoordinator {
|
|
|
707
812
|
const { recentToolResults, trailingUsers } =
|
|
708
813
|
this.collectRecentToolResultsAndSteeringUsers(visibleMessages);
|
|
709
814
|
|
|
710
|
-
// 分支 A:若存在因超过 165
|
|
815
|
+
// 分支 A:若存在因超过 165 秒守护阈值已剥离的调用,等待在途取消收敛后通过新 session/prompt 补发迟到结果
|
|
711
816
|
if (ledger.detachedCallIds.size > 0) {
|
|
712
817
|
const detachedResults: ToolResultMessage[] = [];
|
|
713
818
|
for (const callId of ledger.detachedCallIds) {
|
|
@@ -722,6 +827,45 @@ export class TurnCoordinator {
|
|
|
722
827
|
}
|
|
723
828
|
ledger.detachedCallIds.clear();
|
|
724
829
|
ledger.activePump = undefined;
|
|
830
|
+
|
|
831
|
+
const idleOk = await this.waitForInFlightPrompt(ledger, 2_500, options?.signal);
|
|
832
|
+
if (!idleOk) {
|
|
833
|
+
if (options?.signal?.aborted) {
|
|
834
|
+
writer.fail("aborted", "Request aborted by user");
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
await this.discardWedgedLedger(ledger);
|
|
838
|
+
const cwd = this.activeContext?.cwd ?? process.cwd();
|
|
839
|
+
const isProjectTrusted = this.activeContext?.isProjectTrusted?.() ?? false;
|
|
840
|
+
const mountInfo = prepareCustomizationMount(
|
|
841
|
+
visibleMessages,
|
|
842
|
+
this.currentConfig,
|
|
843
|
+
cwd,
|
|
844
|
+
);
|
|
845
|
+
const restored = await this.bootstrapOrRestoreLedger({
|
|
846
|
+
piSessionKey: ledger.piSessionKey,
|
|
847
|
+
cwd,
|
|
848
|
+
isProjectTrusted,
|
|
849
|
+
visibleMessages,
|
|
850
|
+
hostMcpTools,
|
|
851
|
+
toolsDigest,
|
|
852
|
+
mountedPluginPaths: mountInfo.mountedPluginPaths,
|
|
853
|
+
mountDigest: mountInfo.mountDigest,
|
|
854
|
+
additionalDirectories: mountInfo.additionalDirectories,
|
|
855
|
+
workspaceContextBlock: mountInfo.workspaceContextBlock,
|
|
856
|
+
signal: options?.signal,
|
|
857
|
+
});
|
|
858
|
+
await this.executePromptOnLedger(
|
|
859
|
+
restored.ledger,
|
|
860
|
+
restored.initialPromptBlocks,
|
|
861
|
+
visibleMessages,
|
|
862
|
+
writer,
|
|
863
|
+
model,
|
|
864
|
+
options,
|
|
865
|
+
);
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
|
|
725
869
|
this.httpMcpBridge.clearSessionCancelled(ledger.agySessionId);
|
|
726
870
|
|
|
727
871
|
const lateBlocks =
|
|
@@ -740,31 +884,73 @@ export class TurnCoordinator {
|
|
|
740
884
|
return;
|
|
741
885
|
}
|
|
742
886
|
|
|
743
|
-
// 分支 B:165
|
|
887
|
+
// 分支 B:165 秒内正常完成,直接结算已发给 Pi 的挂起 HTTP MCP 请求并继续消费同一活跃 ACP Turn
|
|
744
888
|
const pump = ledger.activePump;
|
|
745
889
|
if (!pump) {
|
|
890
|
+
for (const [, parked] of ledger.parkedCalls) {
|
|
891
|
+
parked.settle({
|
|
892
|
+
isError: true,
|
|
893
|
+
content: [{ type: "text", text: "Turn ended" }],
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
ledger.parkedCalls.clear();
|
|
897
|
+
const idleOk = await this.waitForInFlightPrompt(ledger, 2_000, options?.signal);
|
|
898
|
+
if (!idleOk) {
|
|
899
|
+
if (options?.signal?.aborted) {
|
|
900
|
+
writer.fail("aborted", "Request aborted by user");
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
await this.discardWedgedLedger(ledger);
|
|
904
|
+
const cwd = this.activeContext?.cwd ?? process.cwd();
|
|
905
|
+
const isProjectTrusted = this.activeContext?.isProjectTrusted?.() ?? false;
|
|
906
|
+
const mountInfo = prepareCustomizationMount(visibleMessages, this.currentConfig, cwd);
|
|
907
|
+
const restored = await this.bootstrapOrRestoreLedger({
|
|
908
|
+
piSessionKey: ledger.piSessionKey,
|
|
909
|
+
cwd,
|
|
910
|
+
isProjectTrusted,
|
|
911
|
+
visibleMessages,
|
|
912
|
+
hostMcpTools,
|
|
913
|
+
toolsDigest,
|
|
914
|
+
mountedPluginPaths: mountInfo.mountedPluginPaths,
|
|
915
|
+
mountDigest: mountInfo.mountDigest,
|
|
916
|
+
additionalDirectories: mountInfo.additionalDirectories,
|
|
917
|
+
workspaceContextBlock: mountInfo.workspaceContextBlock,
|
|
918
|
+
signal: options?.signal,
|
|
919
|
+
});
|
|
920
|
+
await this.executePromptOnLedger(
|
|
921
|
+
restored.ledger,
|
|
922
|
+
restored.initialPromptBlocks,
|
|
923
|
+
visibleMessages,
|
|
924
|
+
writer,
|
|
925
|
+
model,
|
|
926
|
+
options,
|
|
927
|
+
);
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
746
930
|
const replay = buildFreshReplayPromptBlocks(visibleMessages);
|
|
747
931
|
await this.executePromptOnLedger(ledger, replay, visibleMessages, writer, model, options);
|
|
748
932
|
return;
|
|
749
933
|
}
|
|
750
934
|
|
|
751
|
-
|
|
752
|
-
|
|
935
|
+
if (trailingUsers.length > 0) {
|
|
936
|
+
pump.pendingSteeringUsers.push(...trailingUsers);
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
// 仅结算已发给 Pi 执行的工具调用,保留仍在队列中等待下一步发出的并发/顺序后续请求;
|
|
940
|
+
// 运行中附带的用户消息保留在 pump.pendingSteeringUsers 中,待当前任务 prompt_done 后以真实用户身份串行发送。
|
|
941
|
+
const entriesToSettle = Array.from(ledger.parkedCalls.entries()).filter(
|
|
942
|
+
([callId]) => pump.emittedMcpCallIds.has(callId) || recentToolResults.has(callId),
|
|
943
|
+
);
|
|
753
944
|
|
|
754
|
-
for (const [callId, parked] of
|
|
945
|
+
for (const [callId, parked] of entriesToSettle) {
|
|
755
946
|
const tr = recentToolResults.get(callId);
|
|
756
947
|
ledger.parkedCalls.delete(callId);
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
}
|
|
763
|
-
parked.settle({
|
|
764
|
-
content: [{ type: "text", text: "(tool call skipped)" }],
|
|
765
|
-
isError: true,
|
|
766
|
-
});
|
|
767
|
-
}
|
|
948
|
+
pump.emittedMcpCallIds.delete(callId);
|
|
949
|
+
|
|
950
|
+
parked.settle({
|
|
951
|
+
content: tr ? [...tr.content] : [{ type: "text", text: "(tool call skipped)" }],
|
|
952
|
+
isError: tr ? tr.isError : true,
|
|
953
|
+
});
|
|
768
954
|
}
|
|
769
955
|
|
|
770
956
|
writer.setResponseMetadata({
|
|
@@ -817,8 +1003,19 @@ export class TurnCoordinator {
|
|
|
817
1003
|
tools: params.hostMcpTools,
|
|
818
1004
|
onParkedCall: (call) => {
|
|
819
1005
|
const fullLedger = ledgerDraft as ManagedSessionLedger;
|
|
1006
|
+
if (!fullLedger.activePump || fullLedger.activePump.finished) {
|
|
1007
|
+
call.settle({
|
|
1008
|
+
isError: true,
|
|
1009
|
+
content: [{ type: "text", text: "Turn cancelled." }],
|
|
1010
|
+
});
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
820
1013
|
fullLedger.parkedCalls.set(call.callId, call);
|
|
821
|
-
fullLedger.activePump
|
|
1014
|
+
fullLedger.activePump.pendingAnnouncedMcpCount = Math.max(
|
|
1015
|
+
0,
|
|
1016
|
+
fullLedger.activePump.pendingAnnouncedMcpCount - 1,
|
|
1017
|
+
);
|
|
1018
|
+
fullLedger.activePump.queue.push({ kind: "mcp_parked", call });
|
|
822
1019
|
},
|
|
823
1020
|
onHoldTimeout: async (call) => {
|
|
824
1021
|
const fullLedger = ledgerDraft as ManagedSessionLedger;
|
|
@@ -828,9 +1025,7 @@ export class TurnCoordinator {
|
|
|
828
1025
|
}
|
|
829
1026
|
if (fullLedger.agySessionId) {
|
|
830
1027
|
this.httpMcpBridge.markSessionTurnCancelled(fullLedger.agySessionId);
|
|
831
|
-
|
|
832
|
-
.request("session/cancel", { sessionId: fullLedger.agySessionId })
|
|
833
|
-
.catch(() => {});
|
|
1028
|
+
fullLedger.conn.notify("session/cancel", { sessionId: fullLedger.agySessionId });
|
|
834
1029
|
}
|
|
835
1030
|
},
|
|
836
1031
|
});
|
|
@@ -1092,6 +1287,40 @@ export class TurnCoordinator {
|
|
|
1092
1287
|
}
|
|
1093
1288
|
}
|
|
1094
1289
|
|
|
1290
|
+
private startTrackedSessionPrompt(
|
|
1291
|
+
ledger: ManagedSessionLedger,
|
|
1292
|
+
pump: ActiveTurnPump,
|
|
1293
|
+
outboundPayload: { sessionId: string; prompt: AcpPromptBlock[] },
|
|
1294
|
+
): void {
|
|
1295
|
+
this.httpMcpBridge.clearSessionCancelled(ledger.agySessionId);
|
|
1296
|
+
pump.finished = false;
|
|
1297
|
+
|
|
1298
|
+
let trackedRef: Promise<void> | undefined;
|
|
1299
|
+
const tracked = ledger.conn
|
|
1300
|
+
.request<AcpPromptResponse>("session/prompt", outboundPayload)
|
|
1301
|
+
.then((response) => {
|
|
1302
|
+
pump.finished = true;
|
|
1303
|
+
if (ledger.activePump === pump) {
|
|
1304
|
+
this.mirrorBroker.completePendingCallsImplicitly(ledger.agySessionId);
|
|
1305
|
+
}
|
|
1306
|
+
pump.queue.push({ kind: "prompt_done", response });
|
|
1307
|
+
})
|
|
1308
|
+
.catch((error) => {
|
|
1309
|
+
pump.finished = true;
|
|
1310
|
+
if (ledger.activePump === pump) {
|
|
1311
|
+
this.mirrorBroker.abortSessionCalls(ledger.agySessionId, "ACP prompt error");
|
|
1312
|
+
}
|
|
1313
|
+
pump.queue.push({ kind: "prompt_error", error });
|
|
1314
|
+
})
|
|
1315
|
+
.finally(() => {
|
|
1316
|
+
if (ledger.inFlightPrompt === trackedRef) {
|
|
1317
|
+
ledger.inFlightPrompt = undefined;
|
|
1318
|
+
}
|
|
1319
|
+
});
|
|
1320
|
+
trackedRef = tracked;
|
|
1321
|
+
ledger.inFlightPrompt = tracked;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1095
1324
|
private async executePromptOnLedger(
|
|
1096
1325
|
ledger: ManagedSessionLedger,
|
|
1097
1326
|
promptBlocks: AcpPromptBlock[],
|
|
@@ -1104,6 +1333,12 @@ export class TurnCoordinator {
|
|
|
1104
1333
|
model: Model<Api>,
|
|
1105
1334
|
options?: SimpleStreamOptions,
|
|
1106
1335
|
): Promise<void> {
|
|
1336
|
+
await this.waitForInFlightPrompt(ledger, 2_500, options?.signal);
|
|
1337
|
+
if (options?.signal?.aborted) {
|
|
1338
|
+
writer.fail("aborted", "Request aborted by user");
|
|
1339
|
+
return;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1107
1342
|
await this.syncSessionModelAndMode(ledger, model, options);
|
|
1108
1343
|
|
|
1109
1344
|
writer.setResponseMetadata({
|
|
@@ -1127,28 +1362,17 @@ export class TurnCoordinator {
|
|
|
1127
1362
|
}
|
|
1128
1363
|
}
|
|
1129
1364
|
|
|
1130
|
-
this.httpMcpBridge.clearSessionCancelled(ledger.agySessionId);
|
|
1131
|
-
|
|
1132
1365
|
const pump: ActiveTurnPump = {
|
|
1133
1366
|
queue: new AsyncEventQueue<PumpQueueItem>(),
|
|
1134
1367
|
finished: false,
|
|
1135
1368
|
cancelledByHoldTimeout: false,
|
|
1136
1369
|
accountedOutputTokens: 0,
|
|
1370
|
+
pendingAnnouncedMcpCount: 0,
|
|
1371
|
+
emittedMcpCallIds: new Set<string>(),
|
|
1372
|
+
pendingSteeringUsers: [],
|
|
1137
1373
|
};
|
|
1138
1374
|
ledger.activePump = pump;
|
|
1139
|
-
|
|
1140
|
-
void ledger.conn
|
|
1141
|
-
.request<AcpPromptResponse>("session/prompt", outboundPayload)
|
|
1142
|
-
.then((response) => {
|
|
1143
|
-
pump.finished = true;
|
|
1144
|
-
this.mirrorBroker.completePendingCallsImplicitly(ledger.agySessionId);
|
|
1145
|
-
pump.queue.push({ kind: "prompt_done", response });
|
|
1146
|
-
})
|
|
1147
|
-
.catch((error) => {
|
|
1148
|
-
pump.finished = true;
|
|
1149
|
-
this.mirrorBroker.abortSessionCalls(ledger.agySessionId, "ACP prompt error");
|
|
1150
|
-
pump.queue.push({ kind: "prompt_error", error });
|
|
1151
|
-
});
|
|
1375
|
+
this.startTrackedSessionPrompt(ledger, pump, outboundPayload);
|
|
1152
1376
|
|
|
1153
1377
|
if (options?.onResponse) {
|
|
1154
1378
|
await options.onResponse(
|
|
@@ -1178,28 +1402,22 @@ export class TurnCoordinator {
|
|
|
1178
1402
|
): Promise<void> {
|
|
1179
1403
|
const signal = options?.signal;
|
|
1180
1404
|
|
|
1181
|
-
const
|
|
1182
|
-
this.
|
|
1183
|
-
this.mirrorBroker.abortSessionCalls(ledger.agySessionId, "Aborted");
|
|
1184
|
-
for (const [, parked] of ledger.parkedCalls) {
|
|
1185
|
-
parked.settle({
|
|
1186
|
-
isError: true,
|
|
1187
|
-
content: [{ type: "text", text: "Cancelled" }],
|
|
1188
|
-
});
|
|
1189
|
-
}
|
|
1190
|
-
ledger.parkedCalls.clear();
|
|
1191
|
-
ledger.activePump = undefined;
|
|
1192
|
-
await ledger.conn
|
|
1193
|
-
.request("session/cancel", { sessionId: ledger.agySessionId })
|
|
1194
|
-
.catch(() => {});
|
|
1405
|
+
const abortCurrentTurnSync = () => {
|
|
1406
|
+
this.abortLedgerTurnNonBlocking(ledger);
|
|
1195
1407
|
};
|
|
1196
1408
|
|
|
1197
1409
|
while (!writer.isTerminated) {
|
|
1410
|
+
if (signal?.aborted) {
|
|
1411
|
+
abortCurrentTurnSync();
|
|
1412
|
+
writer.fail("aborted", "Request aborted by user");
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1198
1416
|
let item: PumpQueueItem;
|
|
1199
1417
|
try {
|
|
1200
1418
|
item = await pump.queue.shift(signal);
|
|
1201
1419
|
} catch {
|
|
1202
|
-
|
|
1420
|
+
abortCurrentTurnSync();
|
|
1203
1421
|
writer.fail("aborted", "Request aborted by user");
|
|
1204
1422
|
return;
|
|
1205
1423
|
}
|
|
@@ -1223,7 +1441,7 @@ export class TurnCoordinator {
|
|
|
1223
1441
|
if (update.content.type === "text") {
|
|
1224
1442
|
const { quotaError } = writer.appendTextDelta(update.content.text);
|
|
1225
1443
|
if (quotaError) {
|
|
1226
|
-
|
|
1444
|
+
abortCurrentTurnSync();
|
|
1227
1445
|
writer.fail("error", `Antigravity quota exhausted (429): ${quotaError}`);
|
|
1228
1446
|
return;
|
|
1229
1447
|
}
|
|
@@ -1236,15 +1454,18 @@ export class TurnCoordinator {
|
|
|
1236
1454
|
ledger.agySessionId,
|
|
1237
1455
|
update,
|
|
1238
1456
|
);
|
|
1239
|
-
writer.
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1457
|
+
await writer.appendToolCallStreaming(
|
|
1458
|
+
{
|
|
1459
|
+
id: update.toolCallId,
|
|
1460
|
+
name: classified.mirrorToolName,
|
|
1461
|
+
arguments: classified.arguments,
|
|
1462
|
+
},
|
|
1463
|
+
writer.hasEmittedAnyDelta ? 0 : 2,
|
|
1464
|
+
);
|
|
1244
1465
|
|
|
1245
1466
|
// 短窗口合并同一帧并发到达的额外原生 tool_call
|
|
1246
1467
|
await new Promise((r) => setTimeout(r, 15));
|
|
1247
|
-
while (
|
|
1468
|
+
while (!signal?.aborted) {
|
|
1248
1469
|
const nextPeek = pump.queue.peek();
|
|
1249
1470
|
if (
|
|
1250
1471
|
nextPeek?.kind === "acp_update" &&
|
|
@@ -1268,6 +1489,12 @@ export class TurnCoordinator {
|
|
|
1268
1489
|
}
|
|
1269
1490
|
}
|
|
1270
1491
|
|
|
1492
|
+
if (signal?.aborted) {
|
|
1493
|
+
abortCurrentTurnSync();
|
|
1494
|
+
writer.fail("aborted", "Request aborted by user");
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1271
1498
|
writer.finishWithToolUse(this.buildIntermediateStepUsage(ledger, pump, writer));
|
|
1272
1499
|
return;
|
|
1273
1500
|
}
|
|
@@ -1275,34 +1502,64 @@ export class TurnCoordinator {
|
|
|
1275
1502
|
continue;
|
|
1276
1503
|
}
|
|
1277
1504
|
|
|
1278
|
-
if (item.kind === "mcp_announced") {
|
|
1279
|
-
writer.beginPendingToolCall(item.placeholderId, item.hintName);
|
|
1280
|
-
continue;
|
|
1281
|
-
}
|
|
1282
|
-
|
|
1283
1505
|
if (item.kind === "mcp_parked") {
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1506
|
+
pump.emittedMcpCallIds.add(item.call.callId);
|
|
1507
|
+
await writer.appendToolCallStreaming(
|
|
1508
|
+
{
|
|
1509
|
+
id: item.call.callId,
|
|
1510
|
+
name: item.call.toolName,
|
|
1511
|
+
arguments: item.call.arguments,
|
|
1512
|
+
},
|
|
1513
|
+
writer.hasEmittedAnyDelta ? 0 : 2,
|
|
1514
|
+
);
|
|
1289
1515
|
|
|
1290
|
-
//
|
|
1291
|
-
|
|
1292
|
-
while (
|
|
1293
|
-
pump.queue.peek()?.kind === "mcp_parked"
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
} else if (nextItem.kind === "mcp_parked") {
|
|
1516
|
+
// 聚合同一推理步并发触发的其余 MCP 工具调用(若已有 ACP 前置宣告仍在 loopback 传输途中则短窗口收齐)
|
|
1517
|
+
const batchDeadline = Date.now() + 180;
|
|
1518
|
+
while (!signal?.aborted) {
|
|
1519
|
+
if (pump.queue.peek()?.kind === "mcp_parked") {
|
|
1520
|
+
const nextItem = (await pump.queue.shift()) as {
|
|
1521
|
+
kind: "mcp_parked";
|
|
1522
|
+
call: ParkedToolCall;
|
|
1523
|
+
};
|
|
1524
|
+
pump.emittedMcpCallIds.add(nextItem.call.callId);
|
|
1300
1525
|
writer.appendToolCall({
|
|
1301
1526
|
id: nextItem.call.callId,
|
|
1302
1527
|
name: nextItem.call.toolName,
|
|
1303
1528
|
arguments: nextItem.call.arguments,
|
|
1304
1529
|
});
|
|
1530
|
+
continue;
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
const waitWindowMs = pump.pendingAnnouncedMcpCount > 0 ? 20 : 20;
|
|
1534
|
+
if (pump.pendingAnnouncedMcpCount <= 0 && Date.now() + 140 > batchDeadline) {
|
|
1535
|
+
// 无额外已宣告在途请求时仅做一次 20ms 微批探测即收口
|
|
1536
|
+
await new Promise((r) => setTimeout(r, waitWindowMs));
|
|
1537
|
+
while (pump.queue.peek()?.kind === "mcp_parked") {
|
|
1538
|
+
const nextItem = (await pump.queue.shift()) as {
|
|
1539
|
+
kind: "mcp_parked";
|
|
1540
|
+
call: ParkedToolCall;
|
|
1541
|
+
};
|
|
1542
|
+
pump.emittedMcpCallIds.add(nextItem.call.callId);
|
|
1543
|
+
writer.appendToolCall({
|
|
1544
|
+
id: nextItem.call.callId,
|
|
1545
|
+
name: nextItem.call.toolName,
|
|
1546
|
+
arguments: nextItem.call.arguments,
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
break;
|
|
1305
1550
|
}
|
|
1551
|
+
|
|
1552
|
+
if (Date.now() >= batchDeadline) {
|
|
1553
|
+
pump.pendingAnnouncedMcpCount = 0;
|
|
1554
|
+
break;
|
|
1555
|
+
}
|
|
1556
|
+
await new Promise((r) => setTimeout(r, waitWindowMs));
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
if (signal?.aborted) {
|
|
1560
|
+
abortCurrentTurnSync();
|
|
1561
|
+
writer.fail("aborted", "Request aborted by user");
|
|
1562
|
+
return;
|
|
1306
1563
|
}
|
|
1307
1564
|
|
|
1308
1565
|
writer.finishWithToolUse(this.buildIntermediateStepUsage(ledger, pump, writer));
|
|
@@ -1311,7 +1568,6 @@ export class TurnCoordinator {
|
|
|
1311
1568
|
|
|
1312
1569
|
if (item.kind === "prompt_done") {
|
|
1313
1570
|
this.mirrorBroker.completePendingCallsImplicitly(ledger.agySessionId);
|
|
1314
|
-
ledger.activePump = undefined;
|
|
1315
1571
|
|
|
1316
1572
|
if (ledger.windowSize) {
|
|
1317
1573
|
recordObservedContextWindow(model.id, ledger.windowSize);
|
|
@@ -1319,14 +1575,48 @@ export class TurnCoordinator {
|
|
|
1319
1575
|
}
|
|
1320
1576
|
|
|
1321
1577
|
if (item.response.stopReason === "cancelled" && signal?.aborted) {
|
|
1578
|
+
ledger.activePump = undefined;
|
|
1322
1579
|
writer.fail("aborted", "Request aborted");
|
|
1323
1580
|
return;
|
|
1324
1581
|
}
|
|
1325
1582
|
if (item.response.stopReason === "refusal") {
|
|
1583
|
+
ledger.activePump = undefined;
|
|
1326
1584
|
writer.fail("error", "Model refused the request");
|
|
1327
1585
|
return;
|
|
1328
1586
|
}
|
|
1329
1587
|
|
|
1588
|
+
// 若运行中存在排队进入的转向用户消息,在当前轮次完全结束后立即以真实用户身份串行续接下一轮 session/prompt
|
|
1589
|
+
if (
|
|
1590
|
+
pump.pendingSteeringUsers.length > 0 &&
|
|
1591
|
+
!signal?.aborted &&
|
|
1592
|
+
item.response.stopReason !== "cancelled"
|
|
1593
|
+
) {
|
|
1594
|
+
const raw = convertAcpUsageToPiUsage(item.response.usage);
|
|
1595
|
+
const rawPromptTotal = raw.input + raw.cacheRead + raw.cacheWrite;
|
|
1596
|
+
if (rawPromptTotal > 0) {
|
|
1597
|
+
ledger.lastObservedCacheRatio = Math.min(
|
|
1598
|
+
1,
|
|
1599
|
+
Math.max(0, raw.cacheRead / rawPromptTotal),
|
|
1600
|
+
);
|
|
1601
|
+
}
|
|
1602
|
+
const steerBlocks = convertUserMessagesToPromptBlocks(
|
|
1603
|
+
pump.pendingSteeringUsers.splice(0),
|
|
1604
|
+
);
|
|
1605
|
+
if (steerBlocks.length > 0) {
|
|
1606
|
+
if (writer.estimatedOutputTokens > 0) {
|
|
1607
|
+
writer.appendTextDelta("\n\n");
|
|
1608
|
+
}
|
|
1609
|
+
pump.accountedOutputTokens = 0;
|
|
1610
|
+
this.startTrackedSessionPrompt(ledger, pump, {
|
|
1611
|
+
sessionId: ledger.agySessionId,
|
|
1612
|
+
prompt: steerBlocks,
|
|
1613
|
+
});
|
|
1614
|
+
continue;
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
ledger.activePump = undefined;
|
|
1619
|
+
|
|
1330
1620
|
const calibratedUsage = this.buildFinalStepUsage(
|
|
1331
1621
|
ledger,
|
|
1332
1622
|
pump,
|
|
@@ -1388,15 +1678,21 @@ export class TurnCoordinator {
|
|
|
1388
1678
|
};
|
|
1389
1679
|
}
|
|
1390
1680
|
|
|
1391
|
-
const
|
|
1681
|
+
const prevCachedPrefix = ledger.cachedPrefixTokens;
|
|
1682
|
+
const stepTotal = Math.max(output + 1, liveWindowUsed || prevCachedPrefix + output);
|
|
1392
1683
|
const promptTokens = Math.max(1, stepTotal - output);
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1684
|
+
let cacheRead = 0;
|
|
1685
|
+
if (ledger.lastObservedCacheRatio !== undefined) {
|
|
1686
|
+
if (ledger.lastObservedCacheRatio > 0) {
|
|
1687
|
+
cacheRead = Math.min(promptTokens, Math.round(promptTokens * ledger.lastObservedCacheRatio));
|
|
1688
|
+
}
|
|
1689
|
+
} else if (prevCachedPrefix > 0) {
|
|
1690
|
+
// 首轮多步执行途中尚无最终 PromptResponse.usage 时,按同会话前序已缓存前缀估算命中量
|
|
1691
|
+
cacheRead = Math.min(promptTokens, prevCachedPrefix);
|
|
1692
|
+
}
|
|
1397
1693
|
const input = Math.max(0, promptTokens - cacheRead);
|
|
1398
1694
|
const totalTokens = input + cacheRead + output;
|
|
1399
|
-
ledger.cachedPrefixTokens = Math.max(
|
|
1695
|
+
ledger.cachedPrefixTokens = Math.max(prevCachedPrefix, totalTokens);
|
|
1400
1696
|
|
|
1401
1697
|
return {
|
|
1402
1698
|
input,
|
|
@@ -1641,6 +1937,7 @@ export class TurnCoordinator {
|
|
|
1641
1937
|
ledger.parkedCalls.clear();
|
|
1642
1938
|
ledger.detachedCallIds.clear();
|
|
1643
1939
|
ledger.activePump = undefined;
|
|
1940
|
+
ledger.inFlightPrompt = undefined;
|
|
1644
1941
|
|
|
1645
1942
|
if (ledger.mcpToken) {
|
|
1646
1943
|
this.httpMcpBridge.unregisterSessionBinding(ledger.mcpToken);
|
|
@@ -183,12 +183,6 @@ export function convertAcpUsageToPiUsage(acpUsage?: AcpPromptUsage): Usage {
|
|
|
183
183
|
};
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
-
interface PendingToolCallSlot {
|
|
187
|
-
contentIndex: number;
|
|
188
|
-
block: ToolCall;
|
|
189
|
-
hintName: string;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
186
|
/**
|
|
193
187
|
* 单个 Pi 推理步(`AssistantMessageEventStream`)状态机写出器。
|
|
194
188
|
* 严格保证 `start` 先于一切增量事件发出、块开启与闭合配对平衡,且最终仅发出一次 `done` 或 `error`。
|
|
@@ -199,10 +193,10 @@ export class StepStreamWriter {
|
|
|
199
193
|
private started = false;
|
|
200
194
|
private terminated = false;
|
|
201
195
|
private openBlock?: { kind: "thinking" | "text"; index: number };
|
|
202
|
-
private readonly pendingToolCallSlots: PendingToolCallSlot[] = [];
|
|
203
196
|
private readonly messageFilter = new QuotaSoftErrorFilter();
|
|
204
197
|
private rawEstimatedOutputTokens = 0;
|
|
205
198
|
private rawEstimatedThoughtTokens = 0;
|
|
199
|
+
private emittedDeltaCount = 0;
|
|
206
200
|
|
|
207
201
|
constructor(
|
|
208
202
|
model: Model<Api>,
|
|
@@ -284,6 +278,7 @@ export class StepStreamWriter {
|
|
|
284
278
|
const est = estimateTextTokens(delta);
|
|
285
279
|
this.rawEstimatedThoughtTokens += est;
|
|
286
280
|
this.rawEstimatedOutputTokens += est;
|
|
281
|
+
this.emittedDeltaCount++;
|
|
287
282
|
|
|
288
283
|
const target = this.message.content[this.openBlock.index] as ThinkingContent;
|
|
289
284
|
target.thinking += delta;
|
|
@@ -306,49 +301,83 @@ export class StepStreamWriter {
|
|
|
306
301
|
return { quotaError };
|
|
307
302
|
}
|
|
308
303
|
|
|
304
|
+
/** 当前消息是否尚未发出过任何流式 delta(用于判断是否需分两帧发送首个工具 JSON 增量以供实时 TPS 采样) */
|
|
305
|
+
get hasEmittedAnyDelta(): boolean {
|
|
306
|
+
return this.emittedDeltaCount > 0;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
309
|
/**
|
|
310
|
-
*
|
|
311
|
-
*
|
|
310
|
+
* 写入完整工具调用块。
|
|
311
|
+
* 严格保持 `toolCall.id` 与 `arguments` 从 `toolcall_start` 起恒定不变,避免 Pi TUI 因 ID 变更或空参数占位产生重复 `...` 卡片;
|
|
312
|
+
* 当 `splitDeltaWithDelayMs > 0` 时,在同一稳定 `id` 与完整 `arguments` 上分两帧发出 JSON 增量以提供跨时间窗口的流式 TPS 采样点。
|
|
312
313
|
*/
|
|
313
|
-
|
|
314
|
+
async appendToolCallStreaming(
|
|
315
|
+
call: { id: string; name: string; arguments: JsonObject },
|
|
316
|
+
splitDeltaWithDelayMs = 0,
|
|
317
|
+
): Promise<void> {
|
|
314
318
|
if (this.terminated) return;
|
|
315
319
|
this.flushHeldText();
|
|
316
320
|
this.ensureStarted();
|
|
317
321
|
this.closeOpenBlock();
|
|
318
322
|
|
|
323
|
+
const serializedArgs = JSON.stringify(call.arguments ?? {});
|
|
319
324
|
const index = this.message.content.length;
|
|
320
|
-
const
|
|
325
|
+
const toolCallBlock: ToolCall = {
|
|
321
326
|
type: "toolCall",
|
|
322
|
-
id:
|
|
323
|
-
name:
|
|
324
|
-
arguments:
|
|
327
|
+
id: call.id,
|
|
328
|
+
name: call.name,
|
|
329
|
+
arguments: call.arguments,
|
|
325
330
|
};
|
|
326
|
-
this.message.content.push(
|
|
327
|
-
this.pendingToolCallSlots.push({
|
|
328
|
-
contentIndex: index,
|
|
329
|
-
block,
|
|
330
|
-
hintName,
|
|
331
|
-
});
|
|
331
|
+
this.message.content.push(toolCallBlock);
|
|
332
332
|
|
|
333
|
-
this.rawEstimatedOutputTokens += Math.max(
|
|
333
|
+
this.rawEstimatedOutputTokens += Math.max(
|
|
334
|
+
1,
|
|
335
|
+
estimateTextTokens(call.name) + estimateTextTokens(serializedArgs),
|
|
336
|
+
);
|
|
334
337
|
|
|
335
338
|
this.stream.push({
|
|
336
339
|
type: "toolcall_start",
|
|
337
340
|
contentIndex: index,
|
|
338
341
|
partial: this.message,
|
|
339
342
|
});
|
|
343
|
+
|
|
344
|
+
if (splitDeltaWithDelayMs > 0 && serializedArgs.length >= 2) {
|
|
345
|
+
const headDelta = serializedArgs.slice(0, 1);
|
|
346
|
+
const tailDelta = serializedArgs.slice(1);
|
|
347
|
+
this.emittedDeltaCount++;
|
|
348
|
+
this.stream.push({
|
|
349
|
+
type: "toolcall_delta",
|
|
350
|
+
contentIndex: index,
|
|
351
|
+
delta: headDelta,
|
|
352
|
+
partial: this.message,
|
|
353
|
+
});
|
|
354
|
+
await new Promise((r) => setTimeout(r, splitDeltaWithDelayMs));
|
|
355
|
+
if (this.terminated) return;
|
|
356
|
+
this.emittedDeltaCount++;
|
|
357
|
+
this.stream.push({
|
|
358
|
+
type: "toolcall_delta",
|
|
359
|
+
contentIndex: index,
|
|
360
|
+
delta: tailDelta,
|
|
361
|
+
partial: this.message,
|
|
362
|
+
});
|
|
363
|
+
} else {
|
|
364
|
+
this.emittedDeltaCount++;
|
|
365
|
+
this.stream.push({
|
|
366
|
+
type: "toolcall_delta",
|
|
367
|
+
contentIndex: index,
|
|
368
|
+
delta: serializedArgs,
|
|
369
|
+
partial: this.message,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
|
|
340
373
|
this.stream.push({
|
|
341
|
-
type: "
|
|
374
|
+
type: "toolcall_end",
|
|
342
375
|
contentIndex: index,
|
|
343
|
-
|
|
376
|
+
toolCall: toolCallBlock,
|
|
344
377
|
partial: this.message,
|
|
345
378
|
});
|
|
346
379
|
}
|
|
347
380
|
|
|
348
|
-
/**
|
|
349
|
-
* 完成先前已开启的挂起工具块(发出剩余 JSON `toolcall_delta` 与 `toolcall_end`),
|
|
350
|
-
* 若无匹配的前置挂起块则直接完整发出 `toolcall_start -> toolcall_delta -> toolcall_end`。
|
|
351
|
-
*/
|
|
352
381
|
appendToolCall(call: { id: string; name: string; arguments: JsonObject }): void {
|
|
353
382
|
if (this.terminated) return;
|
|
354
383
|
this.flushHeldText();
|
|
@@ -356,42 +385,6 @@ export class StepStreamWriter {
|
|
|
356
385
|
this.closeOpenBlock();
|
|
357
386
|
|
|
358
387
|
const serializedArgs = JSON.stringify(call.arguments ?? {});
|
|
359
|
-
const matchIdx = this.pendingToolCallSlots.findIndex(
|
|
360
|
-
(s) =>
|
|
361
|
-
s.hintName === call.name ||
|
|
362
|
-
s.hintName.toLowerCase().includes(call.name.toLowerCase()) ||
|
|
363
|
-
call.name.toLowerCase().includes(s.hintName.toLowerCase()),
|
|
364
|
-
);
|
|
365
|
-
const slot =
|
|
366
|
-
matchIdx !== -1
|
|
367
|
-
? this.pendingToolCallSlots.splice(matchIdx, 1)[0]
|
|
368
|
-
: this.pendingToolCallSlots.shift();
|
|
369
|
-
|
|
370
|
-
if (slot) {
|
|
371
|
-
slot.block.id = call.id;
|
|
372
|
-
slot.block.name = call.name;
|
|
373
|
-
slot.block.arguments = call.arguments;
|
|
374
|
-
const tailDelta = serializedArgs.startsWith("{")
|
|
375
|
-
? serializedArgs.slice(1)
|
|
376
|
-
: serializedArgs;
|
|
377
|
-
if (tailDelta.length > 0) {
|
|
378
|
-
this.rawEstimatedOutputTokens += estimateTextTokens(tailDelta);
|
|
379
|
-
this.stream.push({
|
|
380
|
-
type: "toolcall_delta",
|
|
381
|
-
contentIndex: slot.contentIndex,
|
|
382
|
-
delta: tailDelta,
|
|
383
|
-
partial: this.message,
|
|
384
|
-
});
|
|
385
|
-
}
|
|
386
|
-
this.stream.push({
|
|
387
|
-
type: "toolcall_end",
|
|
388
|
-
contentIndex: slot.contentIndex,
|
|
389
|
-
toolCall: slot.block,
|
|
390
|
-
partial: this.message,
|
|
391
|
-
});
|
|
392
|
-
return;
|
|
393
|
-
}
|
|
394
|
-
|
|
395
388
|
const index = this.message.content.length;
|
|
396
389
|
const toolCallBlock: ToolCall = {
|
|
397
390
|
type: "toolCall",
|
|
@@ -405,6 +398,7 @@ export class StepStreamWriter {
|
|
|
405
398
|
1,
|
|
406
399
|
estimateTextTokens(call.name) + estimateTextTokens(serializedArgs),
|
|
407
400
|
);
|
|
401
|
+
this.emittedDeltaCount++;
|
|
408
402
|
|
|
409
403
|
this.stream.push({
|
|
410
404
|
type: "toolcall_start",
|
|
@@ -425,32 +419,12 @@ export class StepStreamWriter {
|
|
|
425
419
|
});
|
|
426
420
|
}
|
|
427
421
|
|
|
428
|
-
/** 清理尚未收到实际 MCP 调用即被取消的悬空前置工具块 */
|
|
429
|
-
private finalizeUnmatchedPendingToolCalls(): void {
|
|
430
|
-
while (this.pendingToolCallSlots.length > 0) {
|
|
431
|
-
const slot = this.pendingToolCallSlots.shift()!;
|
|
432
|
-
this.stream.push({
|
|
433
|
-
type: "toolcall_delta",
|
|
434
|
-
contentIndex: slot.contentIndex,
|
|
435
|
-
delta: "}",
|
|
436
|
-
partial: this.message,
|
|
437
|
-
});
|
|
438
|
-
this.stream.push({
|
|
439
|
-
type: "toolcall_end",
|
|
440
|
-
contentIndex: slot.contentIndex,
|
|
441
|
-
toolCall: slot.block,
|
|
442
|
-
partial: this.message,
|
|
443
|
-
});
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
|
|
447
422
|
/** 以 `toolUse` 结束当前切片步,并支持写入单步归因 Usage(供窗口进度条、缓存命中率与单步 TPS 实时计算) */
|
|
448
423
|
finishWithToolUse(stepUsage?: Usage): void {
|
|
449
424
|
if (this.terminated) return;
|
|
450
425
|
this.flushHeldText();
|
|
451
426
|
this.ensureStarted();
|
|
452
427
|
this.closeOpenBlock();
|
|
453
|
-
this.finalizeUnmatchedPendingToolCalls();
|
|
454
428
|
|
|
455
429
|
if (stepUsage) {
|
|
456
430
|
this.message.usage = stepUsage;
|
|
@@ -478,7 +452,6 @@ export class StepStreamWriter {
|
|
|
478
452
|
|
|
479
453
|
this.ensureStarted();
|
|
480
454
|
this.closeOpenBlock();
|
|
481
|
-
this.finalizeUnmatchedPendingToolCalls();
|
|
482
455
|
|
|
483
456
|
const reason = acpStopReason === "max_tokens" ? "length" : "stop";
|
|
484
457
|
this.message.stopReason = reason;
|
|
@@ -505,7 +478,6 @@ export class StepStreamWriter {
|
|
|
505
478
|
fail(reason: "aborted" | "error", errorMessage: string): void {
|
|
506
479
|
if (this.terminated) return;
|
|
507
480
|
this.closeOpenBlock();
|
|
508
|
-
this.finalizeUnmatchedPendingToolCalls();
|
|
509
481
|
this.message.stopReason = reason;
|
|
510
482
|
this.message.errorMessage = errorMessage;
|
|
511
483
|
|
|
@@ -543,6 +515,7 @@ export class StepStreamWriter {
|
|
|
543
515
|
});
|
|
544
516
|
}
|
|
545
517
|
this.rawEstimatedOutputTokens += estimateTextTokens(text);
|
|
518
|
+
this.emittedDeltaCount++;
|
|
546
519
|
const target = this.message.content[this.openBlock.index] as TextContent;
|
|
547
520
|
target.text += text;
|
|
548
521
|
this.stream.push({
|