Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(pi): expose runtime capability manifest from get_commands (#2053)
nanaco9d41cb292e92
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 01ad962864..c481c1b24c 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -69,6 +69,7 @@ import type {ListCustomizationsOptions,ListCustomizationsResult,} from '../types/customizations.js';+import type { PiRuntimeCapabilityManifest } from '../types/pi-runtime-capabilities.js';import { scanWorkspaceFileResources } from './shared/palette-scanner.js';import type { AutoReviewDelegate } from './shared/auto-review-decision.js';@@ -1160,6 +1161,12 @@ export interface AgentSessionHandle {readonly id: string;readonly agentKind: AgentKind;readonly model: string;+ /** Pi-only, per-session runtime command catalog. Undefined for other agents. */+ getRuntimeCapabilities?(): PiRuntimeCapabilityManifest | undefined;+ /** Subscribe to Pi runtime catalog replacement; returns an idempotent disposer. */+ onRuntimeCapabilitiesChange?(+ listener: (manifest: PiRuntimeCapabilityManifest | undefined) => void,+ ): () => void;/** Codex-only: 当前会话绑定的 app-server host 是否经 loopback proxy 出口。 */readonly codexProxyActive?: boolean;/**diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.tsindex 766fabf279..d463bf3cb0 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts@@ -25,6 +25,8 @@ import { StringDecoder } from 'node:string_decoder';import { fileURLToPath } from 'node:url';import { afterEach, describe, expect, it } from 'vitest';+import { capturePiRuntimeCapabilityManifest } from '../runtime-capabilities.js';+const __dirname = path.dirname(fileURLToPath(import.meta.url));const REPO_ROOT = path.resolve(__dirname, '../../../../../..');const PLATFORM_KEY = `${process.platform}-${process.arch}`;@@ -635,6 +637,26 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts});const skills = normalizeSkills(result.commands, fixture);+ const manifest = await capturePiRuntimeCapabilityManifest(+ { request: async () => ({ type: 'response', command: 'get_commands', success: true, data: { commands: result.commands } }) },+ {},+ 1,+ 'ready',+ );+ expect(manifest.status).toBe('loaded');+ expect(manifest.commands).toEqual(expect.arrayContaining([+ expect.objectContaining({+ name: 'skill:global-skill',+ description: 'fixture global-skill',+ source: 'skill',+ sourceInfo: expect.objectContaining({+ source: 'auto',+ scope: 'user',+ baseDir: fixture.configHome,+ }),+ }),+ ]));+expect(skills).toEqual([{name: 'skill:global-skill',description: 'fixture global-skill',diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-runtime-capabilities.lifecycle.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-runtime-capabilities.lifecycle.test.tsnew file mode 100644index 0000000000..9c5723d8b0--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/pi-runtime-capabilities.lifecycle.test.ts@@ -0,0 +1,274 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const captured = vi.hoisted(() => ({+ instances: [] as Array<{+ sessionId: string;+ sdkSessionId: string;+ requests: Array<Record<string, unknown>>;+ closed: boolean;+ onExit?: (info: { code: number | null; signal: string | null }) => void;+ }>,+ catalogs: {} as Record<string, unknown>,+ runtimeFailures: new Set<string>(),+ runtimeDeferred: false,+ runtimeRelease: undefined as (() => void) | undefined,+ rewindStateFailure: false,+}));++vi.mock('../rpc-client.js', () => ({+ PiRpcProcess: class {+ private readonly state: (typeof captured.instances)[number];+ isClosed = false;+ constructor(opts: {+ env: Record<string, string | undefined>;+ onEvent: (event: unknown) => void;+ onExit?: (info: { code: number | null; signal: string | null }) => void;+ }) {+ this.state = {+ sessionId: opts.env.CINDY_PI_SESSION_ID ?? '',+ sdkSessionId: `/mock/${opts.env.CINDY_PI_SESSION_ID || 'fork'}.jsonl`,+ requests: [],+ closed: false,+ onExit: opts.onExit,+ };+ captured.instances.push(this.state);+ void opts.onEvent;+ }+ async request(command: Record<string, unknown>): Promise<{ type?: string; command?: string; success: boolean; data?: unknown; error?: string }> {+ this.state.requests.push(command);+ if (command.type === 'get_state') {+ if (captured.rewindStateFailure && this.state.requests.some((request) => request.type === 'fork')) {+ return { success: false, error: 'rewind state unavailable' };+ }+ return { success: true, data: { sessionFile: this.state.sdkSessionId, model: { contextWindow: 200_000 } } };+ }+ if (command.type === 'get_commands') {+ if (captured.runtimeFailures.has(this.state.sessionId)) {+ return { type: 'response', command: 'get_commands', success: false, error: 'provider=/secret/path rejected' };+ }+ if (captured.runtimeDeferred) {+ await new Promise<void>((resolve) => { captured.runtimeRelease = resolve; });+ }+ const data = captured.catalogs[this.state.sessionId] ?? { commands: [] };+ return { type: 'response', command: 'get_commands', success: true, data };+ }+ if (command.type === 'get_fork_messages') {+ return { success: true, data: { messages: [{ entryId: 'rewind-entry' }] } };+ }+ if (command.type === 'fork') {+ this.state.sdkSessionId = `/mock/${this.state.sessionId || 'fork'}-rewind.jsonl`;+ return { success: true, data: {} };+ }+ if (command.type === 'switch_session') return { success: true, data: {} };+ if (command.type === 'clone') return { success: true, data: {} };+ return { success: true, data: { entries: [] } };+ }+ send(): void {}+ async close(): Promise<void> {+ this.isClosed = true;+ this.state.closed = true;+ }+ },+}));++import { PiAgent } from '../index.js';+import type { AgentDeps } from '../../base-agent.js';+import type { Logger } from '../../../interfaces/logger.js';++const noopLogger: Logger = {+ trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {}, child: () => noopLogger,+};++describe('Pi runtime capability lifecycle', () => {+ let home = '';+ let cwd = '';++ beforeEach(() => {+ captured.instances = [];+ captured.catalogs = {};+ captured.runtimeFailures = new Set();+ captured.runtimeDeferred = false;+ captured.runtimeRelease = undefined;+ captured.rewindStateFailure = false;+ home = mkdtempSync(path.join(tmpdir(), 'pi-runtime-home-'));+ cwd = mkdtempSync(path.join(tmpdir(), 'pi-runtime-cwd-'));+ });+ afterEach(() => {+ rmSync(home, { recursive: true, force: true });+ rmSync(cwd, { recursive: true, force: true });+ });++ function deps(): AgentDeps {+ return {+ auth: {+ getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),+ triggerLogin: async () => ({ authenticated: true }), logout: async () => {}, getAuthEnv: async () => ({}),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' }, binaryPath: '/mock/pi', logger: noopLogger,+ capabilityAdditions: { availableModels: [{ id: 'm', displayName: 'M', contextWindow: 200_000, efforts: [], defaultEffort: null }] },+ resolvePiAgentHome: () => home,+ };+ }++ const catalog = (name: string) => ({ commands: [{ name, source: 'skill', sourceInfo: { source: 'auto', scope: 'user', baseDir: '/tmp' } }] });++ it('captures once after ready, exposes a stable per-session query/event contract, and clears on close', async () => {+ captured.catalogs.s1 = catalog('skill:s1');+ const handle = await new PiAgent(deps()).startSession({ sessionId: 's1', workingDir: cwd, model: 'm' });+ await vi.waitFor(() => {+ expect(handle.getRuntimeCapabilities?.()).toMatchObject({ status: 'loaded', sessionId: 's1', commands: [{ name: 'skill:s1' }] });+ });+ const changes: unknown[] = [];+ const dispose = handle.onRuntimeCapabilitiesChange?.((manifest) => changes.push(manifest));+ expect(changes).toHaveLength(1);+ expect(changes[0]).toMatchObject({ status: 'loaded', commands: [{ name: 'skill:s1' }] });+ expect(captured.instances[0]?.requests.filter((request) => request.type === 'get_commands')).toHaveLength(1);+ await handle.close();+ expect(handle.getRuntimeCapabilities?.()).toBeUndefined();+ expect(changes).toHaveLength(2);+ expect(changes[0]).toMatchObject({ status: 'loaded', commands: [{ name: 'skill:s1' }] });+ expect(changes[1]).toBeUndefined();+ dispose?.();+ });++ it('clears the catalog when the Pi process exits unexpectedly', async () => {+ captured.catalogs.s1 = catalog('skill:s1');+ const handle = await new PiAgent(deps()).startSession({ sessionId: 's1', workingDir: cwd, model: 'm' });+ const instance = captured.instances[0]!;+ const changes: unknown[] = [];+ handle.onRuntimeCapabilitiesChange?.((manifest) => changes.push(manifest));+ instance.onExit?.({ code: 1, signal: null });+ expect(handle.getRuntimeCapabilities?.()).toBeUndefined();+ expect(changes.at(-1)).toBeUndefined();+ expect(changes.length).toBeGreaterThanOrEqual(1);+ await handle.close();+ expect(instance.closed).toBe(true);+ });++ it('does not block normal prompt dispatch when get_commands fails', async () => {+ captured.runtimeFailures.add('s1');+ const handle = await new PiAgent(deps()).startSession({ sessionId: 's1', workingDir: cwd, model: 'm' });+ await vi.waitFor(() => {+ expect(handle.getRuntimeCapabilities?.()).toMatchObject({+ status: 'failed',+ error: { code: 'rpc_failed', message: 'Pi runtime command discovery was rejected' },+ });+ });+ await expect(handle.send({ type: 'user', content: 'hello' })).resolves.toBeUndefined();+ await handle.close();+ });++ it('does not block ready while capability discovery is pending', async () => {+ captured.catalogs.s1 = catalog('skill:s1');+ captured.runtimeDeferred = true;+ const start = new PiAgent(deps()).startSession({ sessionId: 's1', workingDir: cwd, model: 'm' });+ const handle = await start;+ expect(handle.getRuntimeCapabilities?.()).toBeUndefined();+ captured.runtimeRelease?.();+ await vi.waitFor(() => {+ expect(handle.getRuntimeCapabilities?.()).toMatchObject({ status: 'loaded', commands: [{ name: 'skill:s1' }] });+ });+ await handle.close();+ });++ it('keeps concurrent session catalogs isolated and does not let list calls trigger RPC', async () => {+ captured.catalogs.s1 = catalog('skill:s1');+ captured.catalogs.s2 = catalog('skill:s2');+ const agent = new PiAgent(deps());+ const [first, second] = await Promise.all([+ agent.startSession({ sessionId: 's1', workingDir: cwd, model: 'm' }),+ agent.startSession({ sessionId: 's2', workingDir: cwd, model: 'm' }),+ ]);+ await vi.waitFor(() => {+ expect(first.getRuntimeCapabilities?.()?.commands[0]?.name).toBe('skill:s1');+ expect(second.getRuntimeCapabilities?.()?.commands[0]?.name).toBe('skill:s2');+ });+ const before = captured.instances.map((instance) => instance.requests.length);+ await agent.listAgentSkills({ workingDir: cwd });+ expect(captured.instances.map((instance) => instance.requests.length)).toEqual(before);+ await Promise.all([first.close(), second.close()]);+ });++ it('clears the old catalog immediately when rewind changes runtime identity', async () => {+ captured.catalogs.s1 = catalog('skill:before-failed-rewind');+ const failedHandle = await new PiAgent(deps()).startSession({ sessionId: 's1', workingDir: cwd, model: 'm' });+ await vi.waitFor(() => {+ expect(failedHandle.getRuntimeCapabilities?.()).toMatchObject({ status: 'loaded' });+ });+ const failedChanges: unknown[] = [];+ failedHandle.onRuntimeCapabilitiesChange?.((manifest) => failedChanges.push(manifest));+ captured.rewindStateFailure = true;+ await expect(failedHandle.commitRewindFiles?.('', '', { tailTurnsToDrop: 1 }))+ .rejects.toThrow('pi rewind get_state failed');+ expect(failedHandle.getRuntimeCapabilities?.()).toBeUndefined();+ expect(failedChanges.at(-1)).toBeUndefined();+ await failedHandle.close();++ captured.rewindStateFailure = false;+ captured.catalogs.s1 = catalog('skill:before-rewind');+ const handle = await new PiAgent(deps()).startSession({ sessionId: 's1', workingDir: cwd, model: 'm' });+ await vi.waitFor(() => {+ expect(handle.getRuntimeCapabilities?.()).toMatchObject({+ status: 'loaded',+ sdkSessionId: '/mock/s1.jsonl',+ commands: [{ name: 'skill:before-rewind' }],+ });+ });++ const changes: unknown[] = [];+ handle.onRuntimeCapabilitiesChange?.((manifest) => changes.push(manifest));+ captured.runtimeDeferred = true;+ captured.catalogs.s1 = catalog('skill:after-rewind');++ const result = await handle.commitRewindFiles?.('', '', { tailTurnsToDrop: 1 });+ expect(result?.sdkSessionId).toBe('/mock/s1-rewind.jsonl');+ expect(handle.getRuntimeCapabilities?.()).toBeUndefined();+ expect(changes).toHaveLength(2);+ expect(changes[0]).toMatchObject({ sdkSessionId: '/mock/s1.jsonl', status: 'loaded' });+ expect(changes[1]).toBeUndefined();++ captured.runtimeRelease?.();+ await vi.waitFor(() => {+ expect(handle.getRuntimeCapabilities?.()).toMatchObject({+ status: 'loaded',+ sdkSessionId: '/mock/s1-rewind.jsonl',+ commands: [{ name: 'skill:after-rewind' }],+ });+ });+ expect(captured.instances.at(-1)?.requests.filter((request) => request.type === 'get_commands')).toHaveLength(2);+ await handle.close();+ });++ it('refreshes the catalog after switch_session resume and returns a separate fork catalog', async () => {+ captured.catalogs.s1 = catalog('skill:resumed');+ const resumeFile = path.join(cwd, 'resume.jsonl');+ writeFileSync(resumeFile, '{}');+ const handle = await new PiAgent(deps()).startSession({ sessionId: 's1', workingDir: cwd, model: 'm', resumeSessionId: resumeFile });+ const instance = captured.instances[0]!;+ expect(instance.requests.filter((request) => request.type === 'switch_session')).toHaveLength(1);+ expect(instance.requests.filter((request) => request.type === 'get_commands')).toHaveLength(1);+ await vi.waitFor(() => {+ expect(handle.getRuntimeCapabilities?.()).toMatchObject({ status: 'loaded', commands: [{ name: 'skill:resumed' }] });+ });+ await handle.close();++ captured.catalogs[''] = catalog('skill:fork');+ captured.catalogs.forked = catalog('skill:fork');+ const fork = await new PiAgent(deps()).forkSdkSession({+ sourceSdkSessionId: '/mock/source.jsonl', upToMessageId: undefined, workingDir: cwd,+ });+ expect(fork.runtimeCapabilities).toBeUndefined();+ expect(captured.instances.at(-1)?.requests.filter((request) => request.type === 'get_commands')).toHaveLength(0);++ const forkedHandle = await new PiAgent(deps()).startSession({+ sessionId: 'forked', workingDir: cwd, model: 'm', resumeSessionId: fork.newSdkSessionId,+ });+ await vi.waitFor(() => {+ expect(forkedHandle.getRuntimeCapabilities?.()).toMatchObject({ status: 'loaded', commands: [{ name: 'skill:fork' }] });+ });+ await forkedHandle.close();+ });+});diff --git a/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts b/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.tsnew file mode 100644index 0000000000..4571a39313--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts@@ -0,0 +1,176 @@+import { describe, expect, it } from 'vitest';++import {+ capturePiRuntimeCapabilityManifest,+ parsePiRuntimeCommands,+} from '../runtime-capabilities.js';++describe('Pi runtime capability parsing', () => {+ const command = {+ name: 'skill:fixture',+ description: 'fixture skill',+ source: 'skill',+ sourceInfo: {+ source: 'auto',+ scope: 'user',+ baseDir: '/private/user/pi-home',+ path: '/private/user/pi-home/skills/fixture',+ },+ };++ it('keeps stable command and provenance fields from a real-shaped response', () => {+ expect(parsePiRuntimeCommands({ commands: [command] })).toEqual({+ ok: true,+ commands: [command],+ });+ });++ it('accepts an authoritative empty catalog without treating it as scanner discovery', () => {+ expect(parsePiRuntimeCommands({ commands: [] })).toEqual({ ok: true, commands: [] });+ });++ it.each([+ ['missing commands', {}],+ ['duplicate names', { commands: [command, command] }],+ ['missing sourceInfo', { commands: [{ ...command, sourceInfo: undefined }] }],+ ['invalid known sourceInfo field', { commands: [{ ...command, sourceInfo: { source: 'auto', scope: 1 } }] }],+ ['unknown command field', { commands: [{ ...command, extra: 'secret' }] }],+ ['unknown sourceInfo field', { commands: [{ ...command, sourceInfo: { ...command.sourceInfo, extra: 'secret' } }] }],+ ['unknown response field', { commands: [command], extra: 'secret' }],+ ['oversized payload', { commands: [{ ...command, description: 'x'.repeat(4_097) }] }],+ ])('rejects conservative malformed case: %s', (_name, data) => {+ expect(parsePiRuntimeCommands(data)).toEqual({ ok: false });+ });++ it('rejects a catalog whose total serialized payload is oversized', () => {+ const commands = Array.from({ length: 100 }, (_, index) => ({+ ...command,+ name: `skill:fixture-${index}`,+ description: 'x'.repeat(3_000),+ }));+ expect(parsePiRuntimeCommands({ commands })).toEqual({ ok: false });+ });++ it('redacts rpc failures and classifies unsupported/timeout as unknown', async () => {+ const unsupported = await capturePiRuntimeCapabilityManifest(+ { request: async () => ({ type: 'response', command: 'get_commands', success: false, error: '/secret/provider/path unsupported' }) },+ { sessionId: 's1', sdkSessionId: '/private/session.jsonl' },+ 1,+ 'ready',+ );+ expect(unsupported).toMatchObject({+ sessionId: 's1',+ sdkSessionId: '/private/session.jsonl',+ status: 'unknown',+ error: { stage: 'ready', code: 'unsupported', message: 'Pi does not support runtime command discovery' },+ });+ expect(JSON.stringify(unsupported)).not.toContain('secret/provider/path');++ const timedOut = await capturePiRuntimeCapabilityManifest(+ { request: async () => { throw new Error('pi rpc timeout after 30000ms: get_commands /token=secret'); } },+ { sessionId: 's2' },+ 2,+ 'ready',+ );+ expect(timedOut).toMatchObject({ status: 'unknown', error: { code: 'timeout' } });+ expect(JSON.stringify(timedOut)).not.toContain('token=secret');+ });++ it('marks malformed and explicit rpc failures without throwing', async () => {+ const malformed = await capturePiRuntimeCapabilityManifest(+ { request: async () => ({ type: 'response', command: 'get_commands', success: true, data: { commands: [{ ...command, sourceInfo: {} }] } }) },+ { sessionId: 's1' },+ 1,+ 'ready',+ );+ expect(malformed).toMatchObject({ status: 'failed', error: { code: 'malformed_response' } });++ const failed = await capturePiRuntimeCapabilityManifest(+ { request: async () => ({ type: 'response', command: 'get_commands', success: false, error: 'gateway failed' }) },+ { sessionId: 's1' },+ 2,+ 'switch_session',+ );+ expect(failed).toMatchObject({ status: 'failed', error: { stage: 'switch_session', code: 'rpc_failed' } });++ const rejectedTimeout = await capturePiRuntimeCapabilityManifest(+ { request: async () => ({ type: 'response', command: 'get_commands', success: false, error: 'timeout waiting for get_commands' }) },+ { sessionId: 's1' },+ 3,+ 'ready',+ );+ expect(rejectedTimeout).toMatchObject({ status: 'failed', error: { code: 'rpc_failed' } });++ const rejectedProcessText = await capturePiRuntimeCapabilityManifest(+ { request: async () => ({ type: 'response', command: 'get_commands', success: false, error: 'process already exited' }) },+ { sessionId: 's1' },+ 4,+ 'ready',+ );+ expect(rejectedProcessText).toMatchObject({ status: 'failed', error: { code: 'rpc_failed' } });++ const rejectedClosed = await capturePiRuntimeCapabilityManifest(+ { request: async () => ({ type: 'response', command: 'get_commands', success: false, error: 'account closed' }) },+ { sessionId: 's1' },+ 5,+ 'ready',+ );+ expect(rejectedClosed).toMatchObject({ status: 'failed', error: { code: 'rpc_failed' } });++ const rejectedSpawn = await capturePiRuntimeCapabilityManifest(+ { request: async () => ({ type: 'response', command: 'get_commands', success: false, error: 'extension spawn policy rejected' }) },+ { sessionId: 's1' },+ 6,+ 'ready',+ );+ expect(rejectedSpawn).toMatchObject({ status: 'failed', error: { code: 'rpc_failed' } });++ const writeFailure = await capturePiRuntimeCapabilityManifest(+ { request: async () => { throw new Error('pi rpc write failed: EPIPE'); } },+ { sessionId: 's1' },+ 7,+ 'ready',+ );+ expect(writeFailure).toMatchObject({ status: 'unknown', error: { code: 'process_unavailable' } });++ const processError = await capturePiRuntimeCapabilityManifest(+ { request: async () => { throw new Error('pi process error: spawn ENOENT'); } },+ { sessionId: 's1' },+ 8,+ 'ready',+ );+ expect(processError).toMatchObject({ status: 'unknown', error: { code: 'process_unavailable' } });++ const processExit = await capturePiRuntimeCapabilityManifest(+ { request: async () => { throw new Error('pi process exited (code=1, signal=null)'); } },+ { sessionId: 's1' },+ 9,+ 'ready',+ );+ expect(processExit).toMatchObject({ status: 'unknown', error: { code: 'process_unavailable' } });++ const alreadyExited = await capturePiRuntimeCapabilityManifest(+ { request: async () => { throw new Error('pi process already exited'); } },+ { sessionId: 's1' },+ 10,+ 'ready',+ );+ expect(alreadyExited).toMatchObject({ status: 'unknown', error: { code: 'process_unavailable' } });+ });++ it.each([+ ['non-object', null],+ ['missing type', { command: 'get_commands', success: true, data: { commands: [command] } }],+ ['missing success', { type: 'response', command: 'get_commands', data: { commands: [command] } }],+ ['wrong command', { type: 'response', command: 'get_state', success: true, data: { commands: [command] } }],+ ['unknown envelope field', { type: 'response', command: 'get_commands', success: true, data: { commands: [command] }, extra: 'secret' }],+ ])('rejects malformed RPC response envelope: %s', async (_name, response) => {+ const manifest = await capturePiRuntimeCapabilityManifest(+ { request: async () => response as never },+ { sessionId: 's1' },+ 1,+ 'ready',+ );+ expect(manifest).toMatchObject({ status: 'failed', error: { code: 'malformed_response' } });+ });+});diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 100a594450..147e457f2d 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -80,6 +80,7 @@ import { createAsyncQueue, type AsyncQueue } from '../shared/async-queue.js';import { resolveMcpToolTarget } from '../shared/mcp-tool-target.js';import { resolveAgentCredentialMode } from '../credential-mode.js';import { PiRpcProcess, type PiRpcEvent } from './rpc-client.js';+import { capturePiRuntimeCapabilityManifest } from './runtime-capabilities.js';import {createPiTranslateContext,translatePiEvent,@@ -93,6 +94,7 @@ import {piContextTokensFromTree,userDraftTextFromPiEntry,} from './session-tree.js';+import type { PiRuntimeCapabilityManifest } from '../../types/pi-runtime-capabilities.js';const PI_PROVIDER_ID = 'cindy';// 既非 Cindy 网关(cindy/xd)也非订阅直连(openai/anthropic/xai)的 providerId = 显式 BYOM@@ -424,6 +426,9 @@ export class PiAgent extends BaseAgent {// pi 原生 compact RPC:手动压缩(可带聚焦指令,调 LLM 生成摘要)。// 斜杠转义后用户无法手输 /compact,此能力是 pi 会话手动压缩的唯一入口。manualCompact: { supported: true },+ // Pi 的 get_commands runtime catalog 通过 per-session handle 查询;+ // manifest 本身在 ready/fork 后异步采集,暂不可用不代表能力不支持。+ runtimeCapabilities: { supported: true },};}@@ -1146,6 +1151,29 @@ export class PiAgent extends BaseAgent {// preparePiExtraSpawnConfig 注册、但 handle 尚未交出,close() 不会跑 → 单独// 兜底注销 ctx 再抛(构造失败没有 proc 可关)。catch 必抛,故其后 proc 恒已赋值。let proc: PiRpcProcess;+ let runtimeCapabilityManifest: PiRuntimeCapabilityManifest | undefined;+ let runtimeCapabilityGeneration = 0;+ const runtimeCapabilityListeners = new Set<(+ manifest: PiRuntimeCapabilityManifest | undefined,+ ) => void>();+ const notifyRuntimeCapabilityListener = (+ listener: (manifest: PiRuntimeCapabilityManifest | undefined) => void,+ manifest: PiRuntimeCapabilityManifest | undefined,+ ): void => {+ try {+ listener(manifest);+ } catch (error) {+ this.deps.logger.warn('pi runtime capability listener failed (non-fatal)', {+ message: error instanceof Error ? error.message : String(error),+ });+ }+ };+ const publishRuntimeCapabilities = (manifest: PiRuntimeCapabilityManifest | undefined): void => {+ runtimeCapabilityManifest = manifest;+ for (const listener of runtimeCapabilityListeners) {+ notifyRuntimeCapabilityListener(listener, manifest);+ }+ };const proxySessionToken = randomBytes(32).toString('base64url');let disposeProxySession: (() => void) | undefined;// 幂等:onExit(进程异常退出)与 close()(用户结束)可能都调用它;首次注销后置位,@@ -1281,6 +1309,9 @@ export class PiAgent extends BaseAgent {},onExit: ({ code, signal }) => {clearActiveTurnPermissionPolicy('process_exit', { dismissPending: true });+ runtimeCapabilityGeneration++;+ publishRuntimeCapabilities(undefined);+ runtimeCapabilityListeners.clear();if (!closed) {// 非用户 close 的进程死亡:terminal error + 收尾,避免 UI 永久 running。queue.push({@@ -1411,6 +1442,22 @@ export class PiAgent extends BaseAgent {// 身份注册(否则 ?session= ctx 泄漏)+ 关掉可能已 spawn 的子进程(否则僵尸 pi// 仍持有本会话的 MCP 路由),再把原始错误抛给调用方。let sdkSessionId = '';+ const refreshRuntimeCapabilities = async (+ stage: 'ready' | 'switch_session' | 'fork',+ ): Promise<void> => {+ const generation = ++runtimeCapabilityGeneration;+ const manifest = await capturePiRuntimeCapabilityManifest(+ proc,+ {+ ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),+ ...(sdkSessionId ? { sdkSessionId } : {}),+ },+ generation,+ stage,+ );+ if (!closed && generation === runtimeCapabilityGeneration) publishRuntimeCapabilities(manifest);+ };+ let runtimeCaptureStage: 'ready' | 'switch_session' = 'ready';try {// Resume:pi 的会话钥匙是 session JSONL 绝对路径(get_state.sessionFile),// 落库 sdk_session_id 存的就是它;切换失败走 invalid-resume CAS 协定。@@ -1443,6 +1490,8 @@ export class PiAgent extends BaseAgent {resumeSessionId: opts.resumeSessionId,error: switched.error,});+ } else {+ runtimeCaptureStage = 'switch_session';}}}@@ -1478,6 +1527,14 @@ export class PiAgent extends BaseAgent {sdkSessionId = stateData.sessionFile || stateData.sessionId || `pi-${Date.now()}`;queue.push({ type: 'session_id', data: sdkSessionId, source: 'pi' });+ // get_state is the ready boundary. Capture exactly once after the final+ // fresh/resumed runtime has been selected; list/customization calls never+ // trigger this RPC.+ // Capability discovery is optional and must not delay session creation.+ // The ready boundary has selected the final Pi session identity; publish+ // the result later through the per-session query/listener contract.+ void refreshRuntimeCapabilities(runtimeCaptureStage);+// plan 镜像与 pi 持久态对齐(resume 关键):pi 的 plan-mode 扩展在 session_start 会从// session entry 自恢复 planModeEnabled,但不发 notify。若镜像固定为 false 而 pi 实为 true,// 由于 /plan 是 toggle + setPlanMode 幂等短路,会导致方向反转或关不掉。故从 get_entries@@ -1689,6 +1746,18 @@ export class PiAgent extends BaseAgent {get id() { return sdkSessionId; },agentKind,get model() { return mutableModel; },+ getRuntimeCapabilities() { return runtimeCapabilityManifest; },+ onRuntimeCapabilitiesChange(listener) {+ if (closed) {+ notifyRuntimeCapabilityListener(listener, undefined);+ return () => undefined;+ }+ runtimeCapabilityListeners.add(listener);+ // Replay the current snapshot synchronously so late subscribers cannot+ // miss an async ready/rewind capture that completed before registration.+ notifyRuntimeCapabilityListener(listener, runtimeCapabilityManifest);+ return () => runtimeCapabilityListeners.delete(listener);+ },// 每轮权限策略(IM 群 / 个人微信等)是 host 侧的 forceConfirmToolCall 回调,必须在// 工具执行前的审批边界强制执行。ask/auto 下 cindy-bridge 会把非只读内置工具与桥接@@ -1780,6 +1849,9 @@ export class PiAgent extends BaseAgent {async close(): Promise<void> {closed = true;+ runtimeCapabilityGeneration++;+ publishRuntimeCapabilities(undefined);+ runtimeCapabilityListeners.clear();// 会话结束时挂起的卡已经不可能有人回答:清 policy 并强制 deny,别让等它的调用// 悬着(同 CC / Codex)。clearActiveTurnPermissionPolicy('session_closed', { dismissPending: true });@@ -1989,12 +2061,20 @@ export class PiAgent extends BaseAgent {}const forked = await proc.request({ type: 'fork', entryId });if (!forked.success) throw new Error(`pi rewind fork failed: ${forked.error ?? 'unknown'}`);+ // Pi has switched runtime identity at the successful fork response. Clear+ // the old catalog before any follow-up get_state can fail or time out.+ runtimeCapabilityGeneration++;+ publishRuntimeCapabilities(undefined);const state = await proc.request({ type: 'get_state' });if (!state.success) throw new Error(`pi rewind get_state failed: ${state.error ?? 'unknown'}`);const replacement = (state.data as { sessionFile?: string } | undefined)?.sessionFile;if (!replacement) throw new Error('pi rewind replacement session path unavailable');sdkSessionId = replacement;queue.push({ type: 'session_id', data: replacement, source: 'pi' });+ // The Pi session has already switched to the replacement file. Do not+ // make rewind wait for optional discovery; the generation fence keeps+ // this asynchronous refresh from publishing stale data.+ void refreshRuntimeCapabilities('fork');return { sdkSessionId: replacement };},@@ -2254,6 +2334,9 @@ export class PiAgent extends BaseAgent {tailTurnsToDrop: tailDrop,});// uuidMap 空:与 Codex 一致,pi agentMeta 不存 SDK message uuid。+ // This short-lived control-plane process is closed immediately. The+ // newly created live session will capture its own authoritative catalog+ // at ready; do not hold this fork path for an optional 5s RPC timeout.return { newSdkSessionId: newPath, uuidMap: new Map() };} finally {await proc.close();diff --git a/packages/maker-core/src/agents/pi/runtime-capabilities.ts b/packages/maker-core/src/agents/pi/runtime-capabilities.tsnew file mode 100644index 0000000000..36db19e263--- /dev/null+++ b/packages/maker-core/src/agents/pi/runtime-capabilities.ts@@ -0,0 +1,215 @@+import type { PiRpcResponse } from './rpc-client.js';+import type {+ PiRuntimeCapabilityError,+ PiRuntimeCapabilityErrorStage,+ PiRuntimeCapabilityManifest,+ PiRuntimeCommand,+ PiRuntimeCommandSourceInfo,+} from '../../types/pi-runtime-capabilities.js';++const MAX_RESPONSE_BYTES = 256_000;+const MAX_COMMANDS = 4_096;+const MAX_NAME_LENGTH = 256;+const MAX_DESCRIPTION_LENGTH = 4_096;+const MAX_SOURCE_LENGTH = 128;+const MAX_SOURCE_INFO_VALUE_LENGTH = 4_096;+const MAX_ERROR_MESSAGE_LENGTH = 160;+export const PI_RUNTIME_CAPABILITY_TIMEOUT_MS = 5_000;+const PI_RPC_RESPONSE_KEYS = new Set(['type', 'id', 'command', 'success', 'data', 'error']);++type RuntimeCommandParseResult =+ | { ok: true; commands: PiRuntimeCommand[] }+ | { ok: false };++function boundedString(value: unknown, maxLength: number): string | undefined {+ if (typeof value !== 'string' || value.trim().length === 0 || value.length > maxLength) return undefined;+ return value;+}++function parseSourceInfo(value: unknown): PiRuntimeCommandSourceInfo | undefined {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;+ const raw = value as Record<string, unknown>;+ if (Object.keys(raw).some((key) => !['path', 'scope', 'baseDir', 'source', 'origin'].includes(key))) return undefined;+ for (const key of ['path', 'scope', 'baseDir', 'source', 'origin'] as const) {+ if (Object.hasOwn(raw, key) && !boundedString(raw[key], MAX_SOURCE_INFO_VALUE_LENGTH)) {+ return undefined;+ }+ }+ const path = boundedString(raw.path, MAX_SOURCE_INFO_VALUE_LENGTH);+ const scope = boundedString(raw.scope, MAX_SOURCE_INFO_VALUE_LENGTH);+ const baseDir = boundedString(raw.baseDir, MAX_SOURCE_INFO_VALUE_LENGTH);+ const source = boundedString(raw.source, MAX_SOURCE_INFO_VALUE_LENGTH);+ const origin = boundedString(raw.origin, MAX_SOURCE_INFO_VALUE_LENGTH);+ // A sourceInfo object with no recognized provenance is not trustworthy enough+ // to mark the command catalog loaded.+ if (!path && !scope && !baseDir && !source) return undefined;+ return {+ ...(path ? { path } : {}),+ ...(scope ? { scope } : {}),+ ...(baseDir ? { baseDir } : {}),+ ...(source ? { source } : {}),+ ...(origin ? { origin } : {}),+ };+}++/** Conservative parser for Pi's get_commands `data.commands` payload. */+export function parsePiRuntimeCommands(data: unknown): RuntimeCommandParseResult {+ if (data === null || typeof data !== 'object' || Array.isArray(data)) return { ok: false };+ const rawData = data as Record<string, unknown>;+ if (Object.keys(rawData).some((key) => key !== 'commands')) return { ok: false };+ const commands = rawData.commands;+ if (!Array.isArray(commands) || commands.length > MAX_COMMANDS) return { ok: false };++ let serializedLength = 0;+ try {+ const serialized = JSON.stringify(data);+ if (typeof serialized !== 'string') return { ok: false };+ serializedLength = Buffer.byteLength(serialized, 'utf8');+ } catch {+ return { ok: false };+ }+ if (serializedLength > MAX_RESPONSE_BYTES) return { ok: false };++ const seen = new Set<string>();+ const parsed: PiRuntimeCommand[] = [];+ for (const value of commands) {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return { ok: false };+ const raw = value as Record<string, unknown>;+ if (Object.keys(raw).some((key) => !['name', 'description', 'source', 'sourceInfo'].includes(key))) {+ return { ok: false };+ }+ const name = boundedString(raw.name, MAX_NAME_LENGTH);+ const source = boundedString(raw.source, MAX_SOURCE_LENGTH);+ const sourceInfo = parseSourceInfo(raw.sourceInfo);+ if (!name || !source || !sourceInfo || seen.has(name)) return { ok: false };+ const description = raw.description === undefined+ ? undefined+ : boundedString(raw.description, MAX_DESCRIPTION_LENGTH);+ if (raw.description !== undefined && !description) return { ok: false };+ seen.add(name);+ parsed.push({+ name,+ ...(description ? { description } : {}),+ source,+ sourceInfo,+ });+ }+ return { ok: true, commands: parsed };+}++function classifyExplicitRpcFailure(raw: string): Pick<PiRuntimeCapabilityError, 'code' | 'message'> {+ const text = raw.toLowerCase();+ if (text.includes('unknown command') || text.includes('unsupported') || text.includes('not supported')) {+ return { code: 'unsupported', message: 'Pi does not support runtime command discovery' };+ }+ return { code: 'rpc_failed', message: 'Pi runtime command discovery was rejected' };+}++function classifyTransportFailure(raw: string): Pick<PiRuntimeCapabilityError, 'code' | 'message'> {+ const text = raw.toLowerCase();+ if (text.startsWith('pi rpc timeout after ')) {+ return { code: 'timeout', message: 'Pi runtime command discovery timed out' };+ }+ if (+ text.startsWith('pi process already exited')+ || text.startsWith('pi process exited (')+ || text.startsWith('pi process error:')+ || text.startsWith('pi rpc write failed:')+ ) {+ return { code: 'process_unavailable', message: 'Pi process was unavailable for runtime command discovery' };+ }+ return { code: 'rpc_failed', message: 'Pi runtime command discovery was rejected' };+}++function statusForFailureCode(code: PiRuntimeCapabilityError['code']): 'unknown' | 'failed' {+ return code === 'unsupported' || code === 'timeout' || code === 'process_unavailable'+ ? 'unknown'+ : 'failed';+}++function errorManifest(+ identity: { sessionId?: string; sdkSessionId?: string },+ generation: number,+ stage: PiRuntimeCapabilityErrorStage,+ failure: Pick<PiRuntimeCapabilityError, 'code' | 'message'>,+ status: 'unknown' | 'failed',+): PiRuntimeCapabilityManifest {+ return {+ ...(identity.sessionId ? { sessionId: identity.sessionId } : {}),+ ...(identity.sdkSessionId ? { sdkSessionId: identity.sdkSessionId } : {}),+ capturedAt: new Date().toISOString(),+ generation,+ status,+ source: 'pi:get_commands',+ commands: [],+ error: { stage, ...failure, message: failure.message.slice(0, MAX_ERROR_MESSAGE_LENGTH) },+ };+}++export async function capturePiRuntimeCapabilityManifest(+ requester: {+ request(+ command: Record<string, unknown>,+ options?: { timeoutMs?: number },+ ): Promise<PiRpcResponse>;+ },+ identity: { sessionId?: string; sdkSessionId?: string },+ generation: number,+ stage: PiRuntimeCapabilityErrorStage,+): Promise<PiRuntimeCapabilityManifest> {+ try {+ const response = await requester.request(+ { type: 'get_commands' },+ { timeoutMs: PI_RUNTIME_CAPABILITY_TIMEOUT_MS },+ );+ const rawResponse = response as unknown;+ if (+ typeof rawResponse !== 'object'+ || rawResponse === null+ || Array.isArray(rawResponse)+ ) {+ return errorManifest(identity, generation, stage, {+ code: 'malformed_response',+ message: 'Pi returned an invalid runtime command response',+ }, 'failed');+ }+ const responseRecord = rawResponse as Record<string, unknown>;+ if (+ Object.keys(responseRecord).some((key) => !PI_RPC_RESPONSE_KEYS.has(key))+ || responseRecord.type !== 'response'+ || responseRecord.command !== 'get_commands'+ || typeof responseRecord.success !== 'boolean'+ || (responseRecord.id !== undefined && typeof responseRecord.id !== 'string')+ || (responseRecord.error !== undefined && typeof responseRecord.error !== 'string')+ ) {+ return errorManifest(identity, generation, stage, {+ code: 'malformed_response',+ message: 'Pi returned an invalid runtime command response',+ }, 'failed');+ }+ const typedResponse = responseRecord as unknown as PiRpcResponse;+ if (!typedResponse.success) {+ const failure = classifyExplicitRpcFailure(typeof typedResponse.error === 'string' ? typedResponse.error : 'rpc rejected');+ return errorManifest(identity, generation, stage, failure, statusForFailureCode(failure.code));+ }+ const parsed = parsePiRuntimeCommands(typedResponse.data);+ if (!parsed.ok) {+ return errorManifest(identity, generation, stage, {+ code: 'malformed_response',+ message: 'Pi returned an invalid runtime command catalog',+ }, 'failed');+ }+ return {+ ...(identity.sessionId ? { sessionId: identity.sessionId } : {}),+ ...(identity.sdkSessionId ? { sdkSessionId: identity.sdkSessionId } : {}),+ capturedAt: new Date().toISOString(),+ generation,+ status: 'loaded',+ source: 'pi:get_commands',+ commands: parsed.commands,+ };+ } catch (error) {+ const failure = classifyTransportFailure(error instanceof Error ? error.message : 'rpc failed');+ return errorManifest(identity, generation, stage, failure, statusForFailureCode(failure.code));+ }+}diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex 6e415cee55..199e537e14 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -31,6 +31,7 @@ import type {ListCustomizationsOptions,ListCustomizationsResult,} from './types/customizations.js';+import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilities.js';import { Session, generateSessionId } from './session.js';import type {AgentSessionHandle,@@ -642,6 +643,19 @@ export class Maker {return this.activeSessions.get(id);}+ /** Read a live session's per-runtime Pi capability snapshot without creating or resuming it. */+ getSessionRuntimeCapabilities(id: string): PiRuntimeCapabilityManifest | undefined {+ return this.activeSessions.get(id)?.getRuntimeCapabilities();+ }++ /** Subscribe to a live session's per-runtime Pi catalog without sharing state across sessions. */+ onSessionRuntimeCapabilitiesChange(+ id: string,+ listener: (manifest: PiRuntimeCapabilityManifest | undefined) => void,+ ): () => void {+ return this.activeSessions.get(id)?.onRuntimeCapabilitiesChange(listener) ?? (() => undefined);+ }+/*** 读 session 持久化元数据 (title / agentKind / sdkSessionId / ...).* 主要给 IPC 层在 send 前查最新 title 作为日志诊断字段透传用 ——diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 6c87151862..71096b6b8e 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -42,6 +42,7 @@ import type {} from './types/events.js';import { isTerminalAgentErrorEvent } from './types/events.js';import type { ContextUsageData } from './types/context-usage.js';+import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilities.js';import type {AgentSessionHandle,BackgroundTaskSnapshot,@@ -719,6 +720,18 @@ export class Session {return this.handle.getUsageSnapshot();}+ /** Return the current per-session Pi runtime capability snapshot, if exposed. */+ getRuntimeCapabilities(): PiRuntimeCapabilityManifest | undefined {+ return this.handle.getRuntimeCapabilities?.();+ }++ /** Subscribe to replacement of the current per-session Pi runtime catalog. */+ onRuntimeCapabilitiesChange(+ listener: (manifest: PiRuntimeCapabilityManifest | undefined) => void,+ ): () => void {+ return this.handle.onRuntimeCapabilitiesChange?.(listener) ?? (() => undefined);+ }+async getContextUsage(): Promise<ContextUsageData> {this.ensureActive();if (!this.handle.getContextUsage) {diff --git a/packages/maker-core/src/types/capabilities.ts b/packages/maker-core/src/types/capabilities.tsindex 24c52e87e5..ed53c104d3 100644--- a/packages/maker-core/src/types/capabilities.ts+++ b/packages/maker-core/src/types/capabilities.ts@@ -74,6 +74,12 @@ export interface Capabilities {multimodal: MultimodalCapability;/** Session 操作 */+ /**+ * Pi runtime command catalog queried from the live session. This is a+ * capability of the session contract; the manifest itself may still be+ * undefined while discovery is pending or unavailable.+ */+ runtimeCapabilities?: CapabilityStatus;fork: CapabilityStatus;rewind: CapabilityStatus;/** 同一 SDK session 内的原生分支树;与创建独立 Cindy 会话的 fork 正交。 */diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex eee42e113c..ad7ef02281 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -10,6 +10,7 @@*/import type { WorkflowProgressEntry } from '@cindy/maker-shared/agent-task';+import type { PiRuntimeCapabilityManifest } from './pi-runtime-capabilities.js';export type AgentEventType =| 'text' // 流式文本输出(增量或完整)@@ -394,4 +395,6 @@ export interface ForkSdkSessionResult {* upToMessageId 锚点能在新 jsonl 里查到。*/uuidMap: Map<string, string>;+ /** Pi-only runtime command catalog captured from the forked runtime, if available. */+ runtimeCapabilities?: PiRuntimeCapabilityManifest;}diff --git a/packages/maker-core/src/types/index.ts b/packages/maker-core/src/types/index.tsindex b8cac8839d..3b8ce2ff06 100644--- a/packages/maker-core/src/types/index.ts+++ b/packages/maker-core/src/types/index.ts@@ -5,5 +5,6 @@ export * from './events.js';export * from './permissions.js';export * from './palette.js';export * from './customizations.js';+export * from './pi-runtime-capabilities.js';export * from './memory.js';export * from './account-rate-limits.js';diff --git a/packages/maker-core/src/types/pi-runtime-capabilities.ts b/packages/maker-core/src/types/pi-runtime-capabilities.tsnew file mode 100644index 0000000000..61f0c72740--- /dev/null+++ b/packages/maker-core/src/types/pi-runtime-capabilities.ts@@ -0,0 +1,63 @@+/**+ * Pi runtime capability facts.+ *+ * This is deliberately separate from customization discovery: a filesystem+ * scanner can report `discovered`, while only Pi's `get_commands` response can+ * report `loaded`.+ */++export type PiRuntimeCapabilityStatus =+ | 'discovered'+ | 'approved'+ | 'loaded'+ | 'failed'+ | 'unknown';++export type PiRuntimeCapabilitySource = 'pi:get_commands';++export type PiRuntimeCapabilityErrorStage = 'ready' | 'switch_session' | 'fork';++export interface PiRuntimeCapabilityError {+ stage: PiRuntimeCapabilityErrorStage;+ code:+ | 'unsupported'+ | 'timeout'+ | 'process_unavailable'+ | 'rpc_failed'+ | 'malformed_response';+ /** Bounded, provider/auth/path-redacted diagnostic text. */+ message: string;+}++/** Stable provenance fields exposed by Pi's command catalog. */+export interface PiRuntimeCommandSourceInfo {+ path?: string;+ scope?: string;+ baseDir?: string;+ source?: string;+ origin?: string;+}++export interface PiRuntimeCommand {+ name: string;+ description?: string;+ source: string;+ sourceInfo: PiRuntimeCommandSourceInfo;+}++/**+ * Per-session runtime catalog snapshot. All fields are optional at call sites+ * through the AgentSessionHandle contract, so old consumers remain compatible.+ */+export interface PiRuntimeCapabilityManifest {+ /** Existing Cindy business session key, when the caller supplied one. */+ sessionId?: string;+ /** Existing Pi SDK/session file key; no new cross-layer identity is created. */+ sdkSessionId?: string;+ capturedAt: string;+ generation: number;+ status: PiRuntimeCapabilityStatus;+ source: PiRuntimeCapabilitySource;+ commands: readonly PiRuntimeCommand[];+ error?: PiRuntimeCapabilityError;+}