pi-antigravity-bridge 0.1.2 → 0.1.4
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 +14 -0
- package/package.json +1 -1
- package/src/acp/process-manager.ts +11 -1
- package/src/index.ts +41 -2
- package/src/session/turn-coordinator.ts +327 -86
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.1.4] - 2026-11-21
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- 修复会话模型或思考档位切换握手阶段按下 `Esc` 时仍可能发出后台请求的问题。
|
|
8
|
+
|
|
9
|
+
## [0.1.3] - 2026-11-21
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- 修复任务执行途中发送消息会意外中断当前任务并导致后续消息卡在运行态无法输出的问题。
|
|
14
|
+
- 修复中断任务后连续发送新消息时可能因后端会话未完成清理而挂起无响应的问题。
|
|
15
|
+
- 修复新会话首轮多步工具调用期间状态栏缓存命中率始终显示为 0 的问题。
|
|
16
|
+
|
|
3
17
|
## [0.1.2] - 2026-11-21
|
|
4
18
|
|
|
5
19
|
### Fixed
|
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.4";
|
|
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,44 @@ 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());
|
|
279
318
|
updateAntigravityStatusBar(ctx, coordinator.config, coordinator.getTelemetrySnapshot());
|
|
280
319
|
});
|
|
281
320
|
|
|
@@ -128,6 +128,10 @@ interface ActiveTurnPump {
|
|
|
128
128
|
accountedOutputTokens: number;
|
|
129
129
|
/** 已收到 ACP 前置 `tool_call` 宣告但 HTTP MCP `POST /mcp` 仍在途的并发调用计数 */
|
|
130
130
|
pendingAnnouncedMcpCount: number;
|
|
131
|
+
/** 已向 Pi 推理流发出的宿主 MCP `callId` 集合,防止误结算仍在队列中待消费的后续工具请求 */
|
|
132
|
+
readonly emittedMcpCallIds: Set<string>;
|
|
133
|
+
/** 运行中排队进入的转向用户消息,在工具结果结算或本轮 `prompt_done` 收口时安全串行投递 */
|
|
134
|
+
readonly pendingSteeringUsers: UserMessage[];
|
|
131
135
|
}
|
|
132
136
|
|
|
133
137
|
interface ManagedSessionLedger {
|
|
@@ -159,6 +163,8 @@ interface ManagedSessionLedger {
|
|
|
159
163
|
/** 记录已确认为宿主 MCP 宣告的 ACP `toolCallId`,防止省略 `title` 的 `tool_call_update` 在 hybrid 下串扰 */
|
|
160
164
|
hostMcpAnnouncementIds: Set<string>;
|
|
161
165
|
activePump?: ActiveTurnPump;
|
|
166
|
+
/** 当前会话在后端仍在途的 `session/prompt` RPC Promise(严禁在它结算前重叠发送下一条 `session/prompt`) */
|
|
167
|
+
inFlightPrompt?: Promise<void>;
|
|
162
168
|
}
|
|
163
169
|
|
|
164
170
|
const DEFAULT_SESSION_KEY = "__default_pi_session__";
|
|
@@ -243,9 +249,7 @@ export class TurnCoordinator {
|
|
|
243
249
|
cancelAgySessionById(agySessionId: string): void {
|
|
244
250
|
const ledger = this.ledgersByAgyId.get(agySessionId);
|
|
245
251
|
if (!ledger) return;
|
|
246
|
-
this.
|
|
247
|
-
this.mirrorBroker.abortSessionCalls(agySessionId, "Cancelled by user");
|
|
248
|
-
void ledger.conn.request("session/cancel", { sessionId: agySessionId }).catch(() => {});
|
|
252
|
+
this.abortLedgerTurnNonBlocking(ledger);
|
|
249
253
|
}
|
|
250
254
|
|
|
251
255
|
/** 实时切换当前活跃会话的 AGY 原生执行模式(`default` | `accept-edits` | `plan`) */
|
|
@@ -282,13 +286,20 @@ export class TurnCoordinator {
|
|
|
282
286
|
/** 在每轮对话稳定完结时,将最新会话锚点(含可选 SQLite 检查点)追加进 Pi `.jsonl` 分支 */
|
|
283
287
|
async persistTurnAnchor(
|
|
284
288
|
messagesSnapshot?: readonly (UserMessage | AssistantMessage | ToolResultMessage)[],
|
|
289
|
+
piSessionId?: string,
|
|
285
290
|
): Promise<void> {
|
|
286
|
-
const key = this.resolveCurrentPiSessionKey();
|
|
291
|
+
const key = this.resolveCurrentPiSessionKey(piSessionId);
|
|
287
292
|
const ledger = this.ledgers.get(key);
|
|
288
293
|
if (!ledger || ledger.activePump || ledger.parkedCalls.size > 0) {
|
|
289
294
|
return;
|
|
290
295
|
}
|
|
291
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
|
+
|
|
292
303
|
if (messagesSnapshot) {
|
|
293
304
|
ledger.syncedMessageCount = messagesSnapshot.length;
|
|
294
305
|
ledger.syncedTranscriptDigest = computeTranscriptDigest(messagesSnapshot);
|
|
@@ -340,13 +351,13 @@ export class TurnCoordinator {
|
|
|
340
351
|
|
|
341
352
|
/**
|
|
342
353
|
* 当用户按下 `Esc` 中断流或在工具执行期间中断整个 Agent Run 时,
|
|
343
|
-
* 0 毫秒同步清理挂起中的 MCP
|
|
354
|
+
* 0 毫秒同步清理挂起中的 MCP 工具调用与活跃队列,并发送 ACP 单向 `session/cancel` 通知。
|
|
344
355
|
*/
|
|
345
356
|
cancelActiveTurnForPiSession(piSessionId?: string): void {
|
|
346
357
|
const key = piSessionId || this.resolveCurrentPiSessionKey();
|
|
347
358
|
const ledger = this.ledgers.get(key);
|
|
348
359
|
if (!ledger) return;
|
|
349
|
-
if (!ledger.activePump && ledger.parkedCalls.size === 0) {
|
|
360
|
+
if (!ledger.activePump && ledger.parkedCalls.size === 0 && !ledger.inFlightPrompt) {
|
|
350
361
|
return;
|
|
351
362
|
}
|
|
352
363
|
this.abortLedgerTurnNonBlocking(ledger);
|
|
@@ -362,10 +373,70 @@ export class TurnCoordinator {
|
|
|
362
373
|
});
|
|
363
374
|
}
|
|
364
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();
|
|
365
432
|
ledger.activePump = undefined;
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
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);
|
|
369
440
|
}
|
|
370
441
|
|
|
371
442
|
/** Pi `registerProvider` 核心流式入口 */
|
|
@@ -610,7 +681,9 @@ export class TurnCoordinator {
|
|
|
610
681
|
// 2b. 模式 A / Hybrid:镜像工具执行完毕,无缝续接后台同一活跃 ACP Turn 队列(含已缓存的尾部事件与终态)
|
|
611
682
|
if (existing.activePump) {
|
|
612
683
|
const { trailingUsers } = this.collectRecentToolResultsAndSteeringUsers(visibleMessages);
|
|
613
|
-
|
|
684
|
+
if (trailingUsers.length > 0) {
|
|
685
|
+
existing.activePump.pendingSteeringUsers.push(...trailingUsers);
|
|
686
|
+
}
|
|
614
687
|
writer.setResponseMetadata({
|
|
615
688
|
responseId: existing.agySessionId,
|
|
616
689
|
providerThinkingLevel: existing.appliedThoughtLevel,
|
|
@@ -623,24 +696,39 @@ export class TurnCoordinator {
|
|
|
623
696
|
return;
|
|
624
697
|
}
|
|
625
698
|
|
|
626
|
-
// 2c.
|
|
627
|
-
const
|
|
628
|
-
if (
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
)
|
|
637
|
-
|
|
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
|
+
}
|
|
638
720
|
}
|
|
639
721
|
}
|
|
640
722
|
|
|
641
723
|
// 3. 会话不存在、工具集/模式变更或历史分支偏离:安全拆解旧会话并按三级状态机重建/恢复
|
|
642
|
-
|
|
643
|
-
|
|
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
|
+
}
|
|
644
732
|
}
|
|
645
733
|
|
|
646
734
|
const { ledger, initialPromptBlocks } = await this.bootstrapOrRestoreLedger({
|
|
@@ -704,21 +792,6 @@ export class TurnCoordinator {
|
|
|
704
792
|
return { recentToolResults, trailingUsers };
|
|
705
793
|
}
|
|
706
794
|
|
|
707
|
-
private forwardSteeringUsersIfPresent(
|
|
708
|
-
ledger: ManagedSessionLedger,
|
|
709
|
-
trailingUsers: readonly UserMessage[],
|
|
710
|
-
): void {
|
|
711
|
-
if (trailingUsers.length === 0) return;
|
|
712
|
-
const steerBlocks = convertUserMessagesToPromptBlocks(trailingUsers);
|
|
713
|
-
if (steerBlocks.length === 0) return;
|
|
714
|
-
void ledger.conn
|
|
715
|
-
.request("session/prompt", {
|
|
716
|
-
sessionId: ledger.agySessionId,
|
|
717
|
-
prompt: steerBlocks,
|
|
718
|
-
})
|
|
719
|
-
.catch(() => {});
|
|
720
|
-
}
|
|
721
|
-
|
|
722
795
|
private async continueFromParkedOrDetachedToolResults(
|
|
723
796
|
ledger: ManagedSessionLedger,
|
|
724
797
|
writer: StepStreamWriter,
|
|
@@ -739,7 +812,7 @@ export class TurnCoordinator {
|
|
|
739
812
|
const { recentToolResults, trailingUsers } =
|
|
740
813
|
this.collectRecentToolResultsAndSteeringUsers(visibleMessages);
|
|
741
814
|
|
|
742
|
-
// 分支 A:若存在因超过 165
|
|
815
|
+
// 分支 A:若存在因超过 165 秒守护阈值已剥离的调用,等待在途取消收敛后通过新 session/prompt 补发迟到结果
|
|
743
816
|
if (ledger.detachedCallIds.size > 0) {
|
|
744
817
|
const detachedResults: ToolResultMessage[] = [];
|
|
745
818
|
for (const callId of ledger.detachedCallIds) {
|
|
@@ -754,6 +827,45 @@ export class TurnCoordinator {
|
|
|
754
827
|
}
|
|
755
828
|
ledger.detachedCallIds.clear();
|
|
756
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
|
+
|
|
757
869
|
this.httpMcpBridge.clearSessionCancelled(ledger.agySessionId);
|
|
758
870
|
|
|
759
871
|
const lateBlocks =
|
|
@@ -772,31 +884,73 @@ export class TurnCoordinator {
|
|
|
772
884
|
return;
|
|
773
885
|
}
|
|
774
886
|
|
|
775
|
-
// 分支 B:165
|
|
887
|
+
// 分支 B:165 秒内正常完成,直接结算已发给 Pi 的挂起 HTTP MCP 请求并继续消费同一活跃 ACP Turn
|
|
776
888
|
const pump = ledger.activePump;
|
|
777
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
|
+
}
|
|
778
930
|
const replay = buildFreshReplayPromptBlocks(visibleMessages);
|
|
779
931
|
await this.executePromptOnLedger(ledger, replay, visibleMessages, writer, model, options);
|
|
780
932
|
return;
|
|
781
933
|
}
|
|
782
934
|
|
|
783
|
-
|
|
784
|
-
|
|
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
|
+
);
|
|
785
944
|
|
|
786
|
-
for (const [callId, parked] of
|
|
945
|
+
for (const [callId, parked] of entriesToSettle) {
|
|
787
946
|
const tr = recentToolResults.get(callId);
|
|
788
947
|
ledger.parkedCalls.delete(callId);
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
}
|
|
795
|
-
parked.settle({
|
|
796
|
-
content: [{ type: "text", text: "(tool call skipped)" }],
|
|
797
|
-
isError: true,
|
|
798
|
-
});
|
|
799
|
-
}
|
|
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
|
+
});
|
|
800
954
|
}
|
|
801
955
|
|
|
802
956
|
writer.setResponseMetadata({
|
|
@@ -849,14 +1003,19 @@ export class TurnCoordinator {
|
|
|
849
1003
|
tools: params.hostMcpTools,
|
|
850
1004
|
onParkedCall: (call) => {
|
|
851
1005
|
const fullLedger = ledgerDraft as ManagedSessionLedger;
|
|
852
|
-
fullLedger.
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
fullLedger.activePump.queue.push({ kind: "mcp_parked", call });
|
|
1006
|
+
if (!fullLedger.activePump || fullLedger.activePump.finished) {
|
|
1007
|
+
call.settle({
|
|
1008
|
+
isError: true,
|
|
1009
|
+
content: [{ type: "text", text: "Turn cancelled." }],
|
|
1010
|
+
});
|
|
1011
|
+
return;
|
|
859
1012
|
}
|
|
1013
|
+
fullLedger.parkedCalls.set(call.callId, call);
|
|
1014
|
+
fullLedger.activePump.pendingAnnouncedMcpCount = Math.max(
|
|
1015
|
+
0,
|
|
1016
|
+
fullLedger.activePump.pendingAnnouncedMcpCount - 1,
|
|
1017
|
+
);
|
|
1018
|
+
fullLedger.activePump.queue.push({ kind: "mcp_parked", call });
|
|
860
1019
|
},
|
|
861
1020
|
onHoldTimeout: async (call) => {
|
|
862
1021
|
const fullLedger = ledgerDraft as ManagedSessionLedger;
|
|
@@ -866,9 +1025,7 @@ export class TurnCoordinator {
|
|
|
866
1025
|
}
|
|
867
1026
|
if (fullLedger.agySessionId) {
|
|
868
1027
|
this.httpMcpBridge.markSessionTurnCancelled(fullLedger.agySessionId);
|
|
869
|
-
|
|
870
|
-
.request("session/cancel", { sessionId: fullLedger.agySessionId }, { timeoutMs: 3_000 })
|
|
871
|
-
.catch(() => {});
|
|
1028
|
+
fullLedger.conn.notify("session/cancel", { sessionId: fullLedger.agySessionId });
|
|
872
1029
|
}
|
|
873
1030
|
},
|
|
874
1031
|
});
|
|
@@ -1130,6 +1287,40 @@ export class TurnCoordinator {
|
|
|
1130
1287
|
}
|
|
1131
1288
|
}
|
|
1132
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
|
+
|
|
1133
1324
|
private async executePromptOnLedger(
|
|
1134
1325
|
ledger: ManagedSessionLedger,
|
|
1135
1326
|
promptBlocks: AcpPromptBlock[],
|
|
@@ -1142,7 +1333,19 @@ export class TurnCoordinator {
|
|
|
1142
1333
|
model: Model<Api>,
|
|
1143
1334
|
options?: SimpleStreamOptions,
|
|
1144
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
|
+
|
|
1145
1342
|
await this.syncSessionModelAndMode(ledger, model, options);
|
|
1343
|
+
if (options?.signal?.aborted || writer.isTerminated) {
|
|
1344
|
+
if (!writer.isTerminated) {
|
|
1345
|
+
writer.fail("aborted", "Request aborted by user");
|
|
1346
|
+
}
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1146
1349
|
|
|
1147
1350
|
writer.setResponseMetadata({
|
|
1148
1351
|
responseId: ledger.agySessionId,
|
|
@@ -1165,7 +1368,12 @@ export class TurnCoordinator {
|
|
|
1165
1368
|
}
|
|
1166
1369
|
}
|
|
1167
1370
|
|
|
1168
|
-
|
|
1371
|
+
if (options?.signal?.aborted || writer.isTerminated) {
|
|
1372
|
+
if (!writer.isTerminated) {
|
|
1373
|
+
writer.fail("aborted", "Request aborted by user");
|
|
1374
|
+
}
|
|
1375
|
+
return;
|
|
1376
|
+
}
|
|
1169
1377
|
|
|
1170
1378
|
const pump: ActiveTurnPump = {
|
|
1171
1379
|
queue: new AsyncEventQueue<PumpQueueItem>(),
|
|
@@ -1173,21 +1381,11 @@ export class TurnCoordinator {
|
|
|
1173
1381
|
cancelledByHoldTimeout: false,
|
|
1174
1382
|
accountedOutputTokens: 0,
|
|
1175
1383
|
pendingAnnouncedMcpCount: 0,
|
|
1384
|
+
emittedMcpCallIds: new Set<string>(),
|
|
1385
|
+
pendingSteeringUsers: [],
|
|
1176
1386
|
};
|
|
1177
1387
|
ledger.activePump = pump;
|
|
1178
|
-
|
|
1179
|
-
void ledger.conn
|
|
1180
|
-
.request<AcpPromptResponse>("session/prompt", outboundPayload)
|
|
1181
|
-
.then((response) => {
|
|
1182
|
-
pump.finished = true;
|
|
1183
|
-
this.mirrorBroker.completePendingCallsImplicitly(ledger.agySessionId);
|
|
1184
|
-
pump.queue.push({ kind: "prompt_done", response });
|
|
1185
|
-
})
|
|
1186
|
-
.catch((error) => {
|
|
1187
|
-
pump.finished = true;
|
|
1188
|
-
this.mirrorBroker.abortSessionCalls(ledger.agySessionId, "ACP prompt error");
|
|
1189
|
-
pump.queue.push({ kind: "prompt_error", error });
|
|
1190
|
-
});
|
|
1388
|
+
this.startTrackedSessionPrompt(ledger, pump, outboundPayload);
|
|
1191
1389
|
|
|
1192
1390
|
if (options?.onResponse) {
|
|
1193
1391
|
await options.onResponse(
|
|
@@ -1318,6 +1516,7 @@ export class TurnCoordinator {
|
|
|
1318
1516
|
}
|
|
1319
1517
|
|
|
1320
1518
|
if (item.kind === "mcp_parked") {
|
|
1519
|
+
pump.emittedMcpCallIds.add(item.call.callId);
|
|
1321
1520
|
await writer.appendToolCallStreaming(
|
|
1322
1521
|
{
|
|
1323
1522
|
id: item.call.callId,
|
|
@@ -1335,6 +1534,7 @@ export class TurnCoordinator {
|
|
|
1335
1534
|
kind: "mcp_parked";
|
|
1336
1535
|
call: ParkedToolCall;
|
|
1337
1536
|
};
|
|
1537
|
+
pump.emittedMcpCallIds.add(nextItem.call.callId);
|
|
1338
1538
|
writer.appendToolCall({
|
|
1339
1539
|
id: nextItem.call.callId,
|
|
1340
1540
|
name: nextItem.call.toolName,
|
|
@@ -1352,6 +1552,7 @@ export class TurnCoordinator {
|
|
|
1352
1552
|
kind: "mcp_parked";
|
|
1353
1553
|
call: ParkedToolCall;
|
|
1354
1554
|
};
|
|
1555
|
+
pump.emittedMcpCallIds.add(nextItem.call.callId);
|
|
1355
1556
|
writer.appendToolCall({
|
|
1356
1557
|
id: nextItem.call.callId,
|
|
1357
1558
|
name: nextItem.call.toolName,
|
|
@@ -1380,7 +1581,6 @@ export class TurnCoordinator {
|
|
|
1380
1581
|
|
|
1381
1582
|
if (item.kind === "prompt_done") {
|
|
1382
1583
|
this.mirrorBroker.completePendingCallsImplicitly(ledger.agySessionId);
|
|
1383
|
-
ledger.activePump = undefined;
|
|
1384
1584
|
|
|
1385
1585
|
if (ledger.windowSize) {
|
|
1386
1586
|
recordObservedContextWindow(model.id, ledger.windowSize);
|
|
@@ -1388,14 +1588,48 @@ export class TurnCoordinator {
|
|
|
1388
1588
|
}
|
|
1389
1589
|
|
|
1390
1590
|
if (item.response.stopReason === "cancelled" && signal?.aborted) {
|
|
1591
|
+
ledger.activePump = undefined;
|
|
1391
1592
|
writer.fail("aborted", "Request aborted");
|
|
1392
1593
|
return;
|
|
1393
1594
|
}
|
|
1394
1595
|
if (item.response.stopReason === "refusal") {
|
|
1596
|
+
ledger.activePump = undefined;
|
|
1395
1597
|
writer.fail("error", "Model refused the request");
|
|
1396
1598
|
return;
|
|
1397
1599
|
}
|
|
1398
1600
|
|
|
1601
|
+
// 若运行中存在排队进入的转向用户消息,在当前轮次完全结束后立即以真实用户身份串行续接下一轮 session/prompt
|
|
1602
|
+
if (
|
|
1603
|
+
pump.pendingSteeringUsers.length > 0 &&
|
|
1604
|
+
!signal?.aborted &&
|
|
1605
|
+
item.response.stopReason !== "cancelled"
|
|
1606
|
+
) {
|
|
1607
|
+
const raw = convertAcpUsageToPiUsage(item.response.usage);
|
|
1608
|
+
const rawPromptTotal = raw.input + raw.cacheRead + raw.cacheWrite;
|
|
1609
|
+
if (rawPromptTotal > 0) {
|
|
1610
|
+
ledger.lastObservedCacheRatio = Math.min(
|
|
1611
|
+
1,
|
|
1612
|
+
Math.max(0, raw.cacheRead / rawPromptTotal),
|
|
1613
|
+
);
|
|
1614
|
+
}
|
|
1615
|
+
const steerBlocks = convertUserMessagesToPromptBlocks(
|
|
1616
|
+
pump.pendingSteeringUsers.splice(0),
|
|
1617
|
+
);
|
|
1618
|
+
if (steerBlocks.length > 0) {
|
|
1619
|
+
if (writer.estimatedOutputTokens > 0) {
|
|
1620
|
+
writer.appendTextDelta("\n\n");
|
|
1621
|
+
}
|
|
1622
|
+
pump.accountedOutputTokens = 0;
|
|
1623
|
+
this.startTrackedSessionPrompt(ledger, pump, {
|
|
1624
|
+
sessionId: ledger.agySessionId,
|
|
1625
|
+
prompt: steerBlocks,
|
|
1626
|
+
});
|
|
1627
|
+
continue;
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
ledger.activePump = undefined;
|
|
1632
|
+
|
|
1399
1633
|
const calibratedUsage = this.buildFinalStepUsage(
|
|
1400
1634
|
ledger,
|
|
1401
1635
|
pump,
|
|
@@ -1457,15 +1691,21 @@ export class TurnCoordinator {
|
|
|
1457
1691
|
};
|
|
1458
1692
|
}
|
|
1459
1693
|
|
|
1460
|
-
const
|
|
1694
|
+
const prevCachedPrefix = ledger.cachedPrefixTokens;
|
|
1695
|
+
const stepTotal = Math.max(output + 1, liveWindowUsed || prevCachedPrefix + output);
|
|
1461
1696
|
const promptTokens = Math.max(1, stepTotal - output);
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1697
|
+
let cacheRead = 0;
|
|
1698
|
+
if (ledger.lastObservedCacheRatio !== undefined) {
|
|
1699
|
+
if (ledger.lastObservedCacheRatio > 0) {
|
|
1700
|
+
cacheRead = Math.min(promptTokens, Math.round(promptTokens * ledger.lastObservedCacheRatio));
|
|
1701
|
+
}
|
|
1702
|
+
} else if (prevCachedPrefix > 0) {
|
|
1703
|
+
// 首轮多步执行途中尚无最终 PromptResponse.usage 时,按同会话前序已缓存前缀估算命中量
|
|
1704
|
+
cacheRead = Math.min(promptTokens, prevCachedPrefix);
|
|
1705
|
+
}
|
|
1466
1706
|
const input = Math.max(0, promptTokens - cacheRead);
|
|
1467
1707
|
const totalTokens = input + cacheRead + output;
|
|
1468
|
-
ledger.cachedPrefixTokens = Math.max(
|
|
1708
|
+
ledger.cachedPrefixTokens = Math.max(prevCachedPrefix, totalTokens);
|
|
1469
1709
|
|
|
1470
1710
|
return {
|
|
1471
1711
|
input,
|
|
@@ -1710,6 +1950,7 @@ export class TurnCoordinator {
|
|
|
1710
1950
|
ledger.parkedCalls.clear();
|
|
1711
1951
|
ledger.detachedCallIds.clear();
|
|
1712
1952
|
ledger.activePump = undefined;
|
|
1953
|
+
ledger.inFlightPrompt = undefined;
|
|
1713
1954
|
|
|
1714
1955
|
if (ledger.mcpToken) {
|
|
1715
1956
|
this.httpMcpBridge.unregisterSessionBinding(ledger.mcpToken);
|