Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): retain convergence receipts through runtime settlement

zqchris7dab5d0467be
diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts
index 430f613cfa..52918a168f 100644
--- a/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts
@@ -29,40 +29,103 @@ function deferred<T>() {
return { promise, resolve };
}
+function live(id: string, closeGate: Promise<void> = Promise.resolve()) {
+ const pending: AgentEvent[] = [];
+ let wake: (() => void) | undefined;
+ let running = false;
+ let ended = false;
+ const emit = (event: AgentEvent) => { pending.push(event); wake?.(); };
+ const close = vi.fn(async () => { await closeGate; ended = true; wake?.(); });
+ const handle = {
+ id, agentKind: 'pi', model: 'm', close,
+ send: vi.fn(async () => { running = true; }),
+ isTurnRunning: () => running,
+ setInteractionResolver() {},
+ async *events() {
+ while (!ended || pending.length) {
+ if (!pending.length) await new Promise<void>((resolve) => { wake = resolve; });
+ const event = pending.shift();
+ if (event) yield event;
+ }
+ },
+ } as unknown as AgentSessionHandle;
+ const logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return this; } };
+ const instance = new Session({ id, agentKind: 'pi', workDir: '/repo', handle,
+ capabilities: {} as never, logger, turnStallMs: 0 });
+ const seen: AgentEvent[] = [];
+ instance.onEvent((event) => seen.push(event));
+ const finish = (result: string) => {
+ running = false;
+ emit({ type: 'text', source: 'pi', data: { text: result } });
+ emit({ type: 'done', source: 'pi', data: { status: 'completed', result } });
+ };
+ return { instance, handle, close, emit, seen, finish };
+}
+
describe('Pi package runtime invalidation', () => {
- it('keeps both busy caller and sibling alive, delivers their results, and retires each independently', async () => {
- function live(id: string) {
- const pending: AgentEvent[] = [];
- let wake: (() => void) | undefined;
- let running = false;
- let ended = false;
- const emit = (event: AgentEvent) => { pending.push(event); wake?.(); };
- const close = vi.fn(async () => { ended = true; wake?.(); });
- const handle = {
- id, agentKind: 'pi', model: 'm', close,
- send: vi.fn(async () => { running = true; }),
- isTurnRunning: () => running,
- setInteractionResolver() {},
- async *events() {
- while (!ended || pending.length) {
- if (!pending.length) await new Promise<void>((resolve) => { wake = resolve; });
- const event = pending.shift();
- if (event) yield event;
- }
- },
- } as unknown as AgentSessionHandle;
- const logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return this; } };
- const instance = new Session({ id, agentKind: 'pi', workDir: '/repo', handle,
- capabilities: {} as never, logger, turnStallMs: 0 });
- const seen: AgentEvent[] = [];
- instance.onEvent((event) => seen.push(event));
- const finish = (result: string) => {
- running = false;
- emit({ type: 'text', source: 'pi', data: { text: result } });
- emit({ type: 'done', source: 'pi', data: { status: 'completed', result } });
- };
- return { instance, handle, close, emit, seen, finish };
+ it.each(['success', 'failure', 'close', 'timeout'] as const)('retains a finished caller through convergence delivery: %s', async (mode) => {
+ const fails = mode !== 'success';
+ const caller = live('caller');
+ const idle = live('idle');
+ const closing = deferred<void>();
+ const maker: InvalidationMaker = {
+ advanceLocalPiPackageRuntimeGeneration: vi.fn(),
+ listActiveSessions: () => [caller.instance, idle.instance],
+ getSessionMeta: vi.fn(async (id: string) => ({ id, agentKind: 'pi' as const, workDir: '/repo',
+ model: 'm', title: id, createdAt: 1, updatedAt: 1 })),
+ closeSessionIfCurrent: async (instance) => {
+ if (instance === idle.instance) {
+ await closing.promise;
+ if (fails) throw new Error('idle process exit unconfirmed');
+ }
+ return instance.closeAfterCurrentTurn();
+ },
+ };
+ await caller.instance.send('update');
+ const snapshot = await captureLocalPiPackageRuntimeInvalidationSnapshot(maker);
+ let receipt: AgentEvent | undefined;
+ const publish = vi.fn((outcome) => {
+ receipt = { type: 'text', source: 'pi', data: { text: JSON.stringify(outcome) } };
+ return receipt;
+ });
+ const settled = settleLocalPiPackageRuntimeSnapshot(maker, snapshot, 'caller', publish);
+ caller.finish('done before sibling close');
+ await vi.waitFor(() => expect(caller.seen.some(event => event.type === 'done')).toBe(true));
+ expect(caller.close).not.toHaveBeenCalled();
+ if (mode === 'timeout') vi.useFakeTimers();
+ closing.resolve();
+ await vi.waitFor(() => expect(publish).toHaveBeenCalledOnce());
+ expect(caller.close).not.toHaveBeenCalled(); // Publishing alone is not delivery.
+ if (mode === 'timeout') {
+ try {
+ const rejected = expect(settled).rejects.toThrow('receipt delivery timed out');
+ await vi.advanceTimersByTimeAsync(10_000);
+ await rejected;
+ expect(caller.close).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ await idle.instance.close();
+ }
+ return;
}
+ if (mode === 'close') {
+ await caller.instance.close(); // Explicit user close wins over the delivery lease.
+ await expect(settled).resolves.toMatchObject({ runtimeConvergence: 'partial' });
+ expect(caller.handle.send).toHaveBeenCalledOnce();
+ await idle.instance.close();
+ return;
+ }
+ caller.emit(receipt!);
+ await expect(settled).resolves.toEqual(fails
+ ? { runtimeConvergence: 'partial', recoveryAction: 'restart-cindy-to-refresh-packages' }
+ : { runtimeConvergence: 'deferred' });
+ await vi.waitFor(() => expect(caller.instance.getStatus()).toBe('closed'));
+ expect(caller.seen).toContain(receipt);
+ expect(caller.handle.send).toHaveBeenCalledOnce();
+ await idle.instance.close();
+ });
+
+ it('keeps both busy caller and sibling alive, delivers their results, and retires each independently', async () => {
const caller = live('caller');
const sibling = live('sibling');
const idle = live('idle');
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 1a6d1f138e..25b8c6ab25 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -2058,7 +2058,7 @@ export function getMaker(): Maker {
}
// The receipt has been sent, not necessarily consumed by Pi. Keep the
// caller and busy siblings alive until their owned turn settles.
- publishOutcome(await settleLocalPiPackageRuntimeSnapshot(maker, snapshot, callerSessionId));
+ await settleLocalPiPackageRuntimeSnapshot(maker, snapshot, callerSessionId, publishOutcome);
},
getGhostRosterPrompt,
// 仅为命中视觉桥目标的 Pi 模型注册 Layer C 工具。
diff --git a/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts b/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts
index f5cd22c803..88d437943b 100644
--- a/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts
+++ b/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts
@@ -1,4 +1,4 @@
-import type { Maker, Session, PiManagedPackageRuntimeConvergence } from '@cindy/maker-core';
+import type { AgentEvent, Maker, Session, PiManagedPackageRuntimeConvergence } from '@cindy/maker-core';
import type { PiPackagesChangeOrigin } from './pi-package-store.js';
@@ -101,13 +101,50 @@ export async function settleLocalPiPackageRuntimeSnapshot(
maker: InvalidationMaker,
snapshot: PiPackageRuntimeInvalidationSnapshot,
callerSessionId?: string,
+ publishOutcome?: (outcome: PiManagedPackageRuntimeConvergence) => AgentEvent,
): Promise<PiManagedPackageRuntimeConvergence> {
- const result = await invalidateLocalPiPackageRuntimeSnapshot(maker, snapshot, { afterCurrentTurn: true });
- if (result.failedSessionIds.length > 0
- || (callerSessionId && !snapshot.entries.some(({ session, eligible }) => eligible && session.id === callerSessionId))) return {
- runtimeConvergence: 'partial', recoveryAction: 'restart-cindy-to-refresh-packages',
- };
- return { runtimeConvergence: result.deferredSessionIds?.length ? 'deferred' : 'complete' };
+ const caller = snapshot.entries.find(({ session }) => session.id === callerSessionId)?.session;
+ const release = publishOutcome ? caller?.acquireTurnLease() : undefined;
+ try {
+ const result = await invalidateLocalPiPackageRuntimeSnapshot(maker, snapshot, { afterCurrentTurn: true });
+ const outcome: PiManagedPackageRuntimeConvergence = result.failedSessionIds.length > 0
+ || (callerSessionId && !snapshot.entries.some(({ session, eligible }) => eligible && session.id === callerSessionId))
+ ? { runtimeConvergence: 'partial', recoveryAction: 'restart-cindy-to-refresh-packages' }
+ : { runtimeConvergence: result.deferredSessionIds?.length ? 'deferred' : 'complete' };
+ if (publishOutcome && caller && caller.getStatus() !== 'closed') {
+ // Queue insertion is not delivery. Keep the exact caller's existing lease
+ // until Session fans out this receipt, even if its done arrived first.
+ await new Promise<void>((resolve, reject) => {
+ let receipt: AgentEvent | undefined;
+ const seen = new Set<AgentEvent>();
+ const unsubscribeEvent = caller.onEvent((event) => {
+ if (event === receipt) finish();
+ else if (!receipt) seen.add(event);
+ });
+ const unsubscribeStatus = caller.onStatusChange((status) => {
+ if (status === 'closed') finish(); // Explicit close must still win.
+ });
+ const timer = setTimeout(() => finish(new Error('Pi package convergence receipt delivery timed out')), 10_000);
+ function finish(error?: Error) {
+ clearTimeout(timer);
+ unsubscribeEvent();
+ unsubscribeStatus();
+ if (error) reject(error); else resolve();
+ }
+ try {
+ receipt = publishOutcome(outcome);
+ if (seen.has(receipt) || caller.getStatus() === 'closed') finish();
+ } catch (error) {
+ finish(error instanceof Error ? error : new Error(String(error)));
+ }
+ });
+ } else {
+ publishOutcome?.(outcome);
+ }
+ return outcome;
+ } finally {
+ release?.();
+ }
}
export async function invalidateLocalPiPackageRuntimes(
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts
index c31a5f36dd..c774b243b0 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts
@@ -3,7 +3,8 @@ import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { Session, type AgentEvent, type AgentSessionHandle } from '@cindy/maker-core';
import type { DbClient } from '../../localDb/client/DbClient.js';
import { tx as runDbTx } from '../../localDb/worker/opHandlers/tx.js';
@@ -296,6 +297,68 @@ describe('shared-process session turn lease', () => {
await expect(readPersistedSessionTurnLeases(first, 'source-1')).resolves.toEqual([]);
});
+ it.each([
+ { stage: 'read', successor: false },
+ { stage: 'write', successor: false },
+ { stage: 'read', successor: true },
+ ] as const)('settles retirement after lease $stage failure, preserving successor=$successor', async ({ stage, successor }) => {
+ const { first } = setup();
+ let fail = false;
+ const client = {
+ ...first,
+ query: async <T>(sql: string, params?: unknown[]) => {
+ if (fail && stage === 'read') throw new Error('injected lease read failure');
+ return first.query<T>(sql, params);
+ },
+ tx: async (name: string, args: unknown) => {
+ if (fail && stage === 'write') throw new Error('injected lease write failure');
+ return first.tx(name, args);
+ },
+ } as typeof first;
+ const tracker = new SessionTurnLeaseTracker({
+ getDbClient: () => client, owner: { instanceId: 'first', processId: 101 },
+ createTurnId: () => 'turn', now: () => 1, ownerProcessEnded: () => false,
+ });
+ await tracker.markTurnStarted('source-1', 'turn');
+ let finish!: () => void;
+ let exit!: () => void;
+ const terminal = new Promise<void>(resolve => { finish = resolve; });
+ const closed = new Promise<void>(resolve => { exit = resolve; });
+ const handle = {
+ id: 'runtime', agentKind: 'pi', model: 'm', send: vi.fn(async () => {}),
+ isTurnRunning: () => false, setInteractionResolver() {},
+ close: vi.fn(async () => { exit(); }),
+ async *events() {
+ await terminal;
+ yield { type: 'done', source: 'pi', data: { status: 'completed', silentStop: true } } as AgentEvent;
+ await closed;
+ },
+ } as unknown as AgentSessionHandle;
+ const logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return this; } };
+ const runtime = new Session({ id: 'source-1', agentKind: 'pi', workDir: '/repo', handle,
+ capabilities: {} as never, logger, turnStallMs: 0 });
+ const seen: AgentEvent[] = [];
+ runtime.onEvent(event => seen.push(event));
+ await runtime.send('work');
+ const generation = runtime.getTurnGeneration();
+ await runtime.closeAfterCurrentTurn();
+ finish();
+ await vi.waitFor(() => expect(seen).toHaveLength(1));
+ expect(handle.close).not.toHaveBeenCalled();
+ if (successor) await runtime.send('already authorized continuation');
+ fail = true;
+ await expect(tracker.markTurnEndedAndCheckIdle('source-1', 'turn',
+ () => runtime.settleHostTurnContinuation(generation))).rejects.toThrow(`injected lease ${stage} failure`);
+ if (successor) {
+ expect(handle.close).not.toHaveBeenCalled();
+ expect(handle.send).toHaveBeenCalledTimes(2);
+ await runtime.close();
+ } else {
+ await vi.waitFor(() => expect(runtime.getStatus()).toBe('closed'));
+ expect(handle.send).toHaveBeenCalledOnce();
+ }
+ });
+
it('refreshes active PID-only leases with exact liveness without overwriting a successor', async () => {
const { first } = setup();
const owner = { instanceId: 'first', processId: 101 } as {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 82a3cb54cb..0b87eac43c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4025,7 +4025,9 @@ async function settleSilentStopDone(
): Promise<void> {
silentStopTurnLeaseGate.settle(sessionId, turnLeaseId);
try {
- if (!(await sessionTurnLeaseTracker.markTurnEndedAndCheckIdle(sessionId, turnLeaseId))) {
+ if (!(await sessionTurnLeaseTracker.markTurnEndedAndCheckIdle(
+ sessionId, turnLeaseId, () => runtime.settleHostTurnContinuation(generation),
+ ))) {
log.debug('ignored stale silent-stop settle after a newer turn started', {
sessionId,
turnLeaseId,
@@ -4043,7 +4045,6 @@ async function settleSilentStopDone(
void finalizeTurnChangeSet(sessionId, null, 'complete');
productTurnWallClockTracker.clear(sessionId);
productTurnUsageTargetTracker.clear(sessionId);
- runtime.settleHostTurnContinuation(generation);
sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(sessionId);
noteClaudeSessionTurnState(sessionId, false);
agentInputCoordinatorHolder?.onTurnEvent(sessionId, 'done');
diff --git a/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts b/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts
index d3b9a887c9..0cb2470240 100644
--- a/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts
@@ -415,9 +415,19 @@ export class SessionTurnLeaseTracker {
}
/** End one exact generation and report whether no local/shared successor remains. */
- async markTurnEndedAndCheckIdle(sessionId: string, expectedTurnId: string): Promise<boolean> {
- await this.markTurnEnded(sessionId, expectedTurnId);
- return !(await this.isTurnActive(sessionId));
+ async markTurnEndedAndCheckIdle(
+ sessionId: string,
+ expectedTurnId: string,
+ onSettled?: () => void,
+ ): Promise<boolean> {
+ try {
+ await this.markTurnEnded(sessionId, expectedTurnId);
+ return !(await this.isTurnActive(sessionId));
+ } finally {
+ // Runtime continuation ownership must not leak when durable bookkeeping
+ // fails. The owner callback fences its exact instance and generation.
+ onSettled?.();
+ }
}
async isTurnActive(sessionId: string): Promise<boolean> {
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index cc2aed8d25..8895c8d5ab 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -230,6 +230,10 @@ Full access 读/搜/bash 与原生对齐的需求正本见 [`pi-full-access-nati
关闭正在消费结果的调用者。包变更仍推进原有 generation 并捕获准确 runtime 实例;
空闲实例退役,忙碌调用者和同一快照里的兄弟实例保留当前执行,产品终态送达后再退役。
`runtimeConvergence=deferred` 表示旧快照暂时服务在途工作,不表示新包已经加载。
+ 调用者的现有 Host lease 必须覆盖兄弟关闭结果汇总及准确收敛回执的 Session 分发;
+ 不能把回执入队当作已分发。交付等待有界,显式关闭仍可结束旧实例。
+ Host 已放弃续跑时,即使 turn lease 记账失败,也应按原实例与 generation 释放退役等待;
+ 记账失败仍不得据此派发后续工作或重放副作用。
- 设置页明确要求停用/移除的即时失效路径仍可关闭运行时;Session 必须在清除监听器和
当前 turn 归属前给未结算工作发明确失败。用户 Stop 则保持取消,不触发重放。
- provider idle、进程退出、事件流结束都不是成功证明。Session 用已有 turn generation/
diff --git a/docs/research/pi-long-tool-lifecycle-3916.md b/docs/research/pi-long-tool-lifecycle-3916.md
index d46b06811b..0021715ac3 100644
--- a/docs/research/pi-long-tool-lifecycle-3916.md
+++ b/docs/research/pi-long-tool-lifecycle-3916.md
@@ -3,6 +3,7 @@
本报告保留独立 transport 提交 `d8bd012f1` 的取证与验证范围。该提交现已纳入统一
Pi 生命周期 P0 交付;组合验证以 PR 正文为准。P0 同时修复下文记录的
`maker.shutdown.test.ts` 泛型 resolver 类型错误,不把它归因于 transport。
+下文的「本单」及独立验证结果均指该 transport 提交,不代表组合 P0 PR 的全部改动。
## 结论与范围
@@ -41,6 +42,11 @@ fixture 不调用模型、不运行真实打包,不读取个人凭证;生成
失败路径:fixture 确认 prompt、发 `agent_start` 和 `tool_execution_start`,随后
启动继承输出管道的轻量后代并 `exit(23)`。测试直接检查 Pi PID 已不存在、后代 PID 仍存活。
+组合 PR 首轮 Windows CI 在后代存活断言处出现 `ESRCH`。fixture 因此显式设置
+`detached: true`,并等后代通过 IPC 报告就绪后才让 Pi 退出,仍保留 stdout/stderr
+继承、后代存活和无新 prompt 的断言。[Node 文档](https://nodejs.org/api/child_process.html#optionsdetached)
+说明 Windows 下 detached 可让子进程在父进程退出后继续运行;这项调整仅建立受控复现
+的前提,不改变生产进程配置,也不证明原 Windows 打包现场的根因。
修复前,最初 4 个用例中 3 个对照通过,继承管道用例在 2 秒内始终没有 terminal error,
断言失败。修复后同一路径约 0.3 秒收到包含退出码 23 的 terminal error,Session 自动
@@ -87,10 +93,13 @@ lizi-mcps、maker-core related 与 orca-workflow 的无模型单测均通过。
单 worker 复查 27/27 通过,第二轮完整门禁也未再出现。未放宽断言或改插件基座,
该偶发失败的根因尚未确定。
-额外 `tsc --noEmit` 发现 `maker.shutdown.test.ts:91` 的 `TS2322`:泛型 resolve 的
-可选参数签名与 Promise resolver 不匹配。以 CompilerHost 从 Git HEAD 读取所有已改文件、
-排除新增 fixture 后,原基线复现同一个错误;本单没有改该文件。包当前没有 `typecheck`
-script,规定的 `run --if-present typecheck` 跳过,不把跳过称作类型检查通过。
+独立 transport 取证时,额外 `tsc --noEmit` 发现 `maker.shutdown.test.ts:91` 的
+`TS2322`:泛型 resolve 的可选参数签名与 Promise resolver 不匹配。以 CompilerHost
+从当时 Git HEAD 读取所有已改文件、排除新增 fixture 后,原基线复现同一个错误;
+独立提交 `d8bd012f1` 未修改该文件。组合 P0 PR #4186 已修改该文件的 resolver 签名,
+并通过 `pnpm --filter @cindy/maker-core run build`(`tsc --noEmit`)。该包没有
+`typecheck` script,规定的 `run --if-present typecheck` 跳过;类型通过的证据来自
+上述实际执行的 build,不来自跳过的命令。
缓存/模型指标:未修改 system 前缀、工具 schema、模型路由或 usage 计算。
正常 fixture 的 10 input / 3 output 在 done 中原样保留;热路径只增加一个 closed
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index eeef14de03..efc1ce29b8 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -659,10 +659,12 @@ export interface AgentDeps {
* Desktop retires idle instances and defers busy captured instances until
* their product turn settles. A sent receipt is not proof Pi consumed it.
* Native package success remains authoritative; deferred is not a failure.
+ * publishOutcome returns the exact queued event so the Host can retain its
+ * caller lease until Session dispatches that receipt (not a persistence ACK).
*/
onPiManagedPackageMutationSettled?: (
callerSessionId: string | undefined,
- publishOutcome: (outcome: PiManagedPackageRuntimeConvergence) => void,
+ publishOutcome: (outcome: PiManagedPackageRuntimeConvergence) => AgentEvent,
) => Promise<void>;
/**
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
index 513e4d47ee..3d3e0e7e72 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
@@ -703,13 +703,14 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
it.each(['success', 'native-failure'] as const)('consumes the %s package tool result and replies before Session retirement', async (outcome) => {
const deps = buildDeps();
let session!: Session;
+ let convergenceReceipt: import('../../../types/events.js').AgentEvent | undefined;
deps.mutatePiManagedPackage = vi.fn(async () => {
if (outcome === 'native-failure') throw new PiManagedPackageMutationFailedError(true, 'native-command-failed');
return { changed: true, affectedPackage: { source: 'self', enabled: true } };
});
deps.onPiManagedPackageMutationSettled = vi.fn(async (_id, publish) => {
const result = await session.closeAfterCurrentTurn();
- publish({ runtimeConvergence: result === 'deferred' ? 'deferred' : 'complete' });
+ convergenceReceipt = publish({ runtimeConvergence: result === 'deferred' ? 'deferred' : 'complete' });
});
const agent = new PiAgent(deps);
const handle = await agent.startSession({ sessionId: 'mutation-caller', workingDir: cwd, model: 'm' });
@@ -725,6 +726,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
const response = await waitForResponse('mutation-result');
expect(JSON.parse(String(response.value)).ok).toBe(outcome === 'success');
await vi.waitFor(() => expect(deps.onPiManagedPackageMutationSettled).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(seen).toContain(convergenceReceipt));
expect(captured.closed).toBe(false);
expect(session.getStatus()).toBe('active');
captured.onEvent?.({ type: 'tool_execution_end', toolCallId: 'mutation-result',
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts
index 6d54d30ced..bfa41e1144 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts
@@ -39,10 +39,14 @@ vi.mock('../transport.js', async (importOriginal) => {
return process.stdout.end();
}
if (cmd.type === 'fixture_exit_with_descendant') {
- const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], {
- stdio: ['ignore', process.stdout, process.stderr], env: process.env
+ const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000); process.send("ready")'], {
+ // Windows needs detached to establish this fixture's orphan
+ // precondition. Keep inheriting both RPC pipes deliberately.
+ detached: true, windowsHide: true,
+ stdio: ['ignore', process.stdout, process.stderr, 'ipc'], env: process.env
});
- child.once('spawn', () => {
+ child.once('message', () => {
+ child.disconnect();
output({ type: 'fixture_descendant', pid: child.pid });
// Drain the fixture metadata before exiting, leaving both pipes
// open in the descendant exactly as a shell/build child can.
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index cba87776bc..5dc0bb5ab7 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -642,12 +642,14 @@ const DEFAULT_PI_EXTENSION_UI_STRINGS: PiExtensionUiStrings = {
async function notifyPiManagedPackageMutationSettled(
deps: AgentDeps,
callerSessionId: string | undefined,
- publishOutcome: (outcome: PiManagedPackageRuntimeConvergence) => void,
+ publishOutcome: (outcome: PiManagedPackageRuntimeConvergence) => AgentEvent,
): Promise<void> {
- const partial = (): void => publishOutcome({
- runtimeConvergence: 'partial',
- recoveryAction: 'restart-cindy-to-refresh-packages',
- });
+ const partial = (): void => {
+ publishOutcome({
+ runtimeConvergence: 'partial',
+ recoveryAction: 'restart-cindy-to-refresh-packages',
+ });
+ };
const callback = deps.onPiManagedPackageMutationSettled;
if (!callback) {
partial();
@@ -4711,11 +4713,13 @@ export class PiAgent extends BaseAgent {
if (activeExtensionCommandNotifications) {
activeExtensionCommandNotifications.push(text);
}
- queue.push({
+ const notification: AgentEvent = {
type: 'text',
data: { text, isFinal: false },
source: 'pi',
- });
+ };
+ queue.push(notification);
+ return notification;
},
notifyUnsupportedExtensionUi: (method, reason) => {
const key = `${method}:${reason}`;
@@ -5058,11 +5062,13 @@ export class PiAgent extends BaseAgent {
this.deps,
opts.sessionId,
(convergence) => {
- queue.push({
+ const receipt: AgentEvent = {
type: 'text',
data: { text: piManagedPackageRuntimeConvergenceReceipt(convergence), isFinal: false },
source: 'pi',
- });
+ };
+ queue.push(receipt);
+ return receipt;
},
);
}
@@ -7055,7 +7061,7 @@ export class PiAgent extends BaseAgent {
action: 'launch' | 'terminate' | 'status',
runId: string,
) => Promise<boolean>;
- emitExtensionNotification: (message: string, event?: PiRpcEvent) => void;
+ emitExtensionNotification: (message: string, event?: PiRpcEvent) => AgentEvent;
notifyUnsupportedExtensionUi: (method: string, reason: 'unsupported-ui' | 'timed-dialog') => void;
/**
* 把一张挂起的权限卡登记进会话级表,返回注销函数。档位切换 / 关闭会话时由