合入小壹 Node 侧防御过度清理(R5-V)

This commit is contained in:
WuYongJie 2026-11-28 20:10:58 +08:00
commit 6fd9203ec2
14 changed files with 21 additions and 126 deletions

View File

@ -20,7 +20,7 @@ export function canvasReadQuery(args) {
export async function previewTarget(host, layer, signal) {
signal?.throwIfAborted();
const state=typeof host.canvas.readCanvas==='function'?await host.canvas.readCanvas({layer}):await host.canvas.read();
const state=await host.canvas.readCanvas({layer});
signal?.throwIfAborted();
if(state?.conversationActive===false||state?.context?.id!==host.canvas.documentId)throw Error('当前项目已切换,未生成其他项目的预览');
if(state.writeBlocked||host.canvasOperations?.writesBlocked||host.canvasNotificationsDetached)throw Error('用户已接手或画布已改变,请在新回合重新确认修改');

View File

@ -1,6 +1,5 @@
import { Type } from '@sinclair/typebox';
import path from 'node:path';
import { Value } from '@sinclair/typebox/value';
import { validateToolArguments } from '@earendil-works/pi-ai';
import fs from 'node:fs/promises';
import { createReadStream } from 'node:fs';
@ -138,7 +137,6 @@ export class EnterpriseKnowledge {
async page(name, args = {}, options = {}) {
options.signal?.throwIfAborted();
if (!['search_files','list_directory'].includes(name)) throw Error('该操作不是目录或搜索分页');
if (!Value.Check(schemas[name],args)) throw Error('企业知识库查询参数无效');
const connection=await this.connect(options);
connection.pages ??= new Map();
const {revision:_revision,offset=0,...query}=args;
@ -247,7 +245,6 @@ export class EnterpriseKnowledge {
async call(name,args={},options={}) {
options.signal?.throwIfAborted();
if (!names.includes(name)) throw Error('企业知识库操作未开放');
if (!Value.Check(schemas[name], args)) throw Error('企业知识库查询参数无效');
if (name==='read_text' && (args.offset??0)>0 && !args.revision) throw Error('文档续页必须携带原revision');
if (name==='list_directory' && (args.offset??0)>0 && !args.revision) throw Error('目录续页必须携带原revision');
if (name==='search_files' && (args.offset??0)>0 && !args.revision) throw Error('搜索续页必须携带原revision');
@ -260,7 +257,7 @@ export class EnterpriseKnowledge {
if(connection.retryAt>Date.now())throw failure(429,{retryAfterSeconds:Math.ceil((connection.retryAt-Date.now())/1000),usage:connection.usage});
const tool=connection.tools.get(name);
if(!tool)throw Error(`企业知识库尚未开放工具 ${name}`);
try { args=validateToolArguments({name,parameters:tool.inputSchema},{name,arguments:args}); } catch { throw Error('企业知识库参数不符合当前服务契约'); }
args=validateToolArguments({name,parameters:tool.inputSchema},{name,arguments:args});
let reply;
try {
reply=await rpc('tools/call',{name,arguments:args},false,options);

View File

@ -208,6 +208,3 @@ export class Native98kBroker {
}
knowledge(brandId) { return this.start('knowledge', { brandId: brandId ?? null }); }
}
// Compatibility entry point for external desktop drivers.
export {NativeControlClient as NativeCanvas} from './native-control-client.mjs';

View File

@ -38,7 +38,6 @@ export const nativeCallParameters = Type.Object({
/** One registry adapter covers native commands. It does not implement them. */
export function nativeTools(host, make) {
if (typeof host.canvas?.nativeCatalog !== 'function' || typeof host.canvas?.nativeCall !== 'function') return [];
const available = (write = true) => {
if (host.canvasNotificationsDetached || write && canvasOperations(host).writesBlocked) throw Error('原项目已切换或原操作结果需核查,本轮不再派发原生操作');
};
@ -127,7 +126,7 @@ export function nativeTools(host, make) {
let settled = result;
if (result?.pending === true) {
pendingJob = result.job;
if (!Number.isSafeInteger(pendingJob) || pendingJob < 1 || typeof host.canvas.nativePoll !== 'function') throw Error('原生操作尚未确认,禁止重复执行');
if (!Number.isSafeInteger(pendingJob) || pendingJob < 1) throw Error('原生操作尚未确认,禁止重复执行');
await host.store.appendEvent({ type: 'native_job_started', run: host.canvas.run, job: pendingJob, method: args.method, revision: args.revision });
const interrupt = args.method === 'engine.execute' && host.qaNativeTimeout?.(args.params.command);
if (interrupt) {
@ -169,17 +168,12 @@ export function nativeTools(host, make) {
throw error;
} finally { if (scope.active === owner) scope.active=null; }
}), ...nativeToolMetadata('native_call')},
...(typeof host.canvas.nativeReconcile === 'function' ? [{...make('native_reconcile', '只读核查本会话保留的原生或工作流未知任务。使用原始run、文档及job或operationId,不重发也不申请写入许可;仅权威终态才解除阻断。缺少任务身份时必须人工核查。', Type.Object({}, {additionalProperties:false}), async () => {
{...make('native_reconcile', '只读核查本会话保留的原生或工作流未知任务。使用原始run、文档及job或operationId,不重发也不申请写入许可;仅权威终态才解除阻断。缺少任务身份时必须人工核查。', Type.Object({}, {additionalProperties:false}), async () => {
if (host.canvasNotificationsDetached) throw Error('当前项目已切换,不能核查其他项目任务');
const scope=canvasOperations(host);
const original = scope.original;
if (!original) return {status:'none',message:'没有待核查的原生任务'};
if (original.identity && (original.identity.scope !== host.store.identity?.scope || original.identity.project !== host.store.identity?.project
|| original.identity.accountId !== host.canvas.identity?.accountId || original.identity.origin !== host.canvas.identity?.origin)) throw Error('账号、来源或项目已切换,原任务仍待核查');
if (original.kind === 'canvas-edit' && typeof host.canvas.editReconcile === 'function'
&& Number.isSafeInteger(original.documentId) && typeof original.run === 'string' && original.run
&& Number.isSafeInteger(original.beforeRevision) && typeof original.command === 'string' && original.command
&& Number.isSafeInteger(original.targetLayerId) && original.targetLayerId > 0) {
if (original.kind === 'canvas-edit' && Number.isSafeInteger(original.targetLayerId)) {
const input = {run:original.run,documentId:original.documentId,beforeRevision:original.beforeRevision,
command:original.command,targetLayerId:original.targetLayerId};
const receipt = await host.canvas.editReconcile(input);
@ -190,9 +184,7 @@ export function nativeTools(host, make) {
if (applied) scope.settle(original);
return {status:applied ? 'applied' : 'unknown',receipt};
}
if (original.kind === 'workflow' && typeof host.canvas.workflowReconcile === 'function'
&& Number.isSafeInteger(original.documentId) && typeof original.run === 'string' && original.run
&& typeof original.operationId === 'string' && original.operationId) {
if (original.kind === 'workflow') {
const receipt = await host.canvas.workflowReconcile({run:original.run,documentId:original.documentId,operationId:original.operationId});
if (receipt?.run !== original.run || receipt?.documentId !== original.documentId || receipt?.operationId !== original.operationId) throw Error('核查回执身份不一致,原操作仍待核查');
const complete = receipt.phase === 'complete';
@ -200,7 +192,7 @@ export function nativeTools(host, make) {
if (terminal) scope.settle(original);
return {status:complete ? 'completed' : terminal ? receipt.phase : 'unknown',receipt};
}
if (original.kind !== 'native' || !Number.isSafeInteger(original.job) || original.job < 1 || !Number.isSafeInteger(original.documentId) || typeof original.run !== 'string' || !original.run) {
if (original.kind !== 'native' || !Number.isSafeInteger(original.job) || original.job < 1) {
return {status:'unknown',message:'原操作缺少可核查的原生任务编号;保留阻断,请在原项目人工核查',kind:original.kind};
}
const receipt = await host.canvas.nativeReconcile({run:original.run,documentId:original.documentId,job:original.job});
@ -212,6 +204,6 @@ export function nativeTools(host, make) {
&& receipt.completed === true && receipt.executed === false && receipt.applied === false;
if ((applied || notApplied)) scope.settle(original);
return {status:applied ? 'applied' : notApplied ? 'not_applied' : 'unknown',receipt};
}), ...nativeToolMetadata('native_reconcile')}] : []),
}), ...nativeToolMetadata('native_reconcile')},
];
}

View File

@ -1,52 +0,0 @@
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, normalizeContext } from '@earendil-works/pi-ai/compat';
import { decodeToolReply } from './json-tool-codec.mjs';
import { auditResponse } from './response-audit.mjs';
/** Reuse Pi's parser with an IN-MEMORY fetch. No inference POST is possible. */
export async function parseReceipt(record, piModel, protocolMode, tools) {
if (!['received', 'complete'].includes(record.phase) || record.terminal !== true || typeof record.raw !== 'string') throw Error('没有完整原响应,继续保留未知状态');
if (typeof record.model?.id !== 'string' || !['anthropic-messages','openai-chat','openai-responses'].includes(record.model.protocol)) {
throw Error('原响应缺少可识别的模型协议');
}
let raw = Buffer.from(record.raw, 'base64').toString('utf8');
const anthropic = record.model.protocol === 'anthropic-messages';
const responses = record.model.protocol === 'openai-responses';
if (responses && !/^data:|^event:/m.test(raw)) {
const original = JSON.parse(raw);
const response = original.output ? original : original.data;
if (!Array.isArray(response?.output) || !['completed', 'incomplete'].includes(response.status)) {
throw Error('原响应仍不完整,未重新生成');
}
const frame = (type, fields) => 'event: ' + type + '\ndata: ' + JSON.stringify({ type, ...fields }) + '\n\n';
raw = response.output.map((item, output_index) => frame('response.output_item.done', { item, output_index })).join('') +
frame('response.' + response.status, { response });
} else if (!/^data:|^event:/m.test(raw)) {
const original = JSON.parse(raw);
const value = original.choices ? original : original.data;
if (anthropic || !value?.choices?.[0]?.message || typeof value.choices[0].finish_reason !== 'string') throw Error('原响应已保留,但此格式尚未完成只读解析,未执行任何操作');
const choice = value.choices[0];
const delta = { ...choice.message, ...(choice.message.tool_calls ? { tool_calls: choice.message.tool_calls.map((t, index) => ({ ...t, index })) } : {}) };
raw = `data: ${JSON.stringify({ id: value.id, model: value.model, choices: [{ index: 0, delta, finish_reason: null }] })}\n\ndata: ${JSON.stringify({ id: value.id, model: value.model, choices: [{ index: 0, delta: {}, finish_reason: choice.finish_reason }], usage: value.usage })}\n\ndata: [DONE]\n\n`;
}
let fetches = 0;
const api = responses ? openAIResponsesApi() : anthropic ? anthropicMessagesApi() : openAICompletionsApi();
const originalModel = {...piModel, id:record.model.id,
api: responses ? 'openai-responses' : anthropic ? 'anthropic-messages' : 'openai-completions',
baseUrl: anthropic ? 'https://api.vip98k.com' : 'https://api.vip98k.com/v1'};
const stream = api.streamSimple(originalModel, normalizeContext({ messages: [{ role: 'user', content: '仅在内存中解析留存响应', timestamp: 0 }] }), {
apiKey: 'native-broker-only',
fetch: async () => {
if (++fetches !== 1) throw Error('禁止重试原请求');
return new Response(raw, { headers: { 'content-type': 'text/event-stream' } });
},
});
for await (const _event of stream) { /* consume only; no tools or UI updates */ }
const message = await stream.result();
if (!['stop', 'toolUse', 'length'].includes(message.stopReason)) throw Error('原响应仍不完整,未重新生成');
if (message.stopReason !== 'length') auditResponse(raw, record.model.protocol);
if (protocolMode === 'structured-json' && message.stopReason !== 'length') {
message.content = decodeToolReply(message.content.filter(c => c.type === 'text').map(c => c.text).join(''), normalizeContext({ tools, messages: [] }), record.id);
message.stopReason = message.content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop';
}
return message;
}

View File

@ -60,10 +60,6 @@ const pendingOriginal = (requestKey, remoteTaskId) => ({ status: 'pending', pend
async function generateClip({ requestKey, ...input }, { generator, ledgerDir, media }, signal) {
const spec = videoRequestSpec(input);
if (!spec.prompt) throw invalid('请提供镜头描述');
if (!ledgerDir) {
if (!generator?.generate) throw new BridgeError('当前未配置视频生成服务', 'missing_video_generator_adapter');
throw new BridgeError('当前未配置视频请求账本', 'missing_video_request_ledger');
}
const requestDigest = digest(spec);
const file = path.join(ledgerDir, `${digest(requestKey)}.json`);
await fs.mkdir(ledgerDir, { recursive: true });

View File

@ -61,7 +61,6 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d
const saveDeadline = Date.now() + (timeoutMs ?? LOCAL_OPERATION_WAIT_MS);
const adoption=args.intent==='adopt_candidate';
const requestWrite=async()=>{
if(typeof host.canvas.read!=='function'||typeof host.canvas.requestWrite!=='function')throw Error('画布写入许可不可用,未派发采纳');
while(!await acquireWrite(host,scope,signal,checkTurn,detailBatch,onWriteWaiting)){
signal?.throwIfAborted();
if(Date.now()>=saveDeadline)throw Error('当前编辑尚未落定,已保留候选');
@ -71,8 +70,6 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d
};
if(adoption)await requestWrite();
let observedOriginal=false;
const canReconcile = typeof host.canvas.workflowReconcile === 'function'
&& Number.isSafeInteger(documentId) && typeof run === 'string' && run;
const reconcileOriginal=async()=>{
signal?.throwIfAborted();
checkTurn();
@ -80,10 +77,10 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d
return reconcileWorkflowReceipt(host.canvas,{run,documentId,operationId});
};
const pollReceipt=async()=>{
if(observedOriginal && canReconcile)return reconcileOriginal();
if(observedOriginal)return reconcileOriginal();
try { return await host.canvas.workflowPoll(operationId); }
catch(error) {
if(!canvasReplyTimedOut(error)||!canReconcile)throw error;
if(!canvasReplyTimedOut(error))throw error;
return reconcileOriginal();
}
};
@ -91,12 +88,7 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d
try { return await host.canvas.workflowExecute({...args,operationId}); }
catch(error) {
if(!canvasReplyTimedOut(error))throw error;
if(canReconcile)return reconcileOriginal();
if(!detailBatch)throw error;
signal?.throwIfAborted();
checkTurn();
observedOriginal=true;
return pollReceipt();
return reconcileOriginal();
}
};
if(adoption&&onAdoptionPrepared){
@ -127,14 +119,7 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d
dispatched = true;
result = await submit();
}
const notDispatched = result?.phase === 'not_dispatched' && result.accepted === false && result.dispatched === false
&& result.operationId === operationId && typeof run === 'string' && run && result.run === run
&& Number.isSafeInteger(documentId) && documentId > 0 && result.documentId === documentId
&& Number.isSafeInteger(result.baseRevision) && result.baseRevision >= 0
&& ['accountId','origin','project'].every(key => typeof identity[key] === 'string' && identity[key])
&& result.accountId === identity.accountId && result.origin === identity.origin
&& result.projectLocalId === `${identity.origin}|${identity.accountId}|${identity.project}`
&& result.error?.code === 'local_precondition_failed' && typeof result.error.message === 'string' && result.error.message.trim();
const notDispatched = result?.phase === 'not_dispatched' && result.operationId === operationId;
if (notDispatched) { dispatched = false; terminal = true; }
checkTurn();
if (notDispatched) {

View File

@ -5,7 +5,7 @@ import path from 'node:path';
import os from 'node:os';
import net from 'node:net';
import {createInterface} from 'node:readline';
import {NativeCanvas} from '../src/native-bridge.mjs';
import {NativeControlClient as NativeCanvas} from '../src/native-control-client.mjs';
const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
async function wait(check){for(let i=0;i<100;i++){if(check())return;await pause(5);}throw Error('Loopback transport state not settled');}

View File

@ -21,7 +21,6 @@ import { atomic } from '../src/store.mjs';
import { Native98kBroker } from '../src/native-bridge.mjs';
import { StdioCanvas } from '../src/stdio-canvas.mjs';
import { projectTools } from '../src/project-tools.mjs';
import { parseReceipt } from '../src/receipt.mjs';
import { createPhotoCraftExtensions } from '../src/photocraft-extension.mjs';
import { callProductionTool } from '../src/production-goal.mjs';
import { productionStore, stubProductionOperations } from './production-store-fixture.mjs';
@ -270,19 +269,6 @@ test('Pi sends an inline image and decodes a streamed function on both OpenAI AP
}
});
test('a retained Responses function call is audited and decoded without a network fetch', async () => {
const model = {id:'route-model',api:'openai-responses',provider:'jiansun-native-98k',input:['text','image'],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}};
const response = {model:model.id,status:'completed',output:[
{id:'fc_route',type:'function_call',status:'completed',call_id:'call_route',name:'record_color',arguments:'{"color":"green"}'},
]};
const record = {phase:'received',terminal:true,model:{id:model.id,protocol:'openai-responses'},raw:Buffer.from(JSON.stringify(response)).toString('base64')};
const message = await parseReceipt(record,model,'native-tools',[]);
assert.equal(message.stopReason,'toolUse');
assert.deepEqual(message.content[0].arguments,{color:'green'});
response.output[0].arguments = '{"color":';
await assert.rejects(parseReceipt({...record,raw:Buffer.from(JSON.stringify(response)).toString('base64')},model,'native-tools',[]));
});
const sse = (delta, finish) => `data: ${JSON.stringify({ id: 'wire', model: 'qa', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\ndata: [DONE]\n\n`;
const outcomeUnknownMessage = 'The request was sent, but its final outcome could not be confirmed. Do not retry with a new idempotency key.';
const outcomeUnknownError = `503 request_outcome_unknown: ${outcomeUnknownMessage}`;

View File

@ -494,7 +494,7 @@ test('actual Pi SDK executes memory tools, persists full transcript and reads pr
} };
let host = await DetailPiAgent.open({ store, transport });
assert.deepEqual(host.session.getActiveToolNames().sort(),
['bash','codemode','context_read','edit','find','grep','ls','memory_search','memory_set','read','tool_search','write']);
['bash','codemode','context_read','edit','find','grep','ls','memory_search','memory_set','native_call','native_catalog','native_reconcile','read','tool_search','write']);
await host.prompt('这个测试产品颜色是胡桃色,请记住。');
const messages = host.session.messages.length, entries = host.manager.getEntryCount();
await host.dispose();

View File

@ -128,7 +128,6 @@ test('媒体命令或适配器缺失提供结构化错误,解码失败不给
await assert.rejects(createVideoMedia({ ...f.config, ffmpegPath: missing }).inspect(f.source), { category: 'missing_ffmpeg_binary' });
const request = { requestKey: 'shot-1', prompt: '商品慢推镜头' };
await assert.rejects(f.tools.video_generate_clip(request), { category: 'missing_video_generator_adapter' });
await assert.rejects(createVideoToolExecutors().video_generate_clip(request), { category: 'missing_video_generator_adapter' });
assert.deepEqual(await fs.readdir(f.ledgerDir), []);
const broken = path.join(f.root, 'broken.mp4');
await fs.writeFile(broken, 'corrupt');

View File

@ -130,7 +130,6 @@ test('failed or stale adoption permission never dispatches',async()=>{
await assert.rejects(executeWorkflow(x.host,{...args,intent:'adopt_candidate',candidateId:'chosen'}));
assert.equal(x.calls.length,0); assert.equal(x.host.canvasOperations.writesBlocked,true);
}
const x=setup([]);await assert.rejects(executeWorkflow(x.host,{...args,intent:'adopt_candidate',candidateId:'chosen'}));assert.equal(x.calls.length,0);
});
test('generation never requests a write lease',async()=>{
const x=setup(['complete']);x.host.canvas.read=async()=>{throw Error('unexpected canvas read')};x.host.canvas.requestWrite=async()=>{throw Error('unexpected permission')};

View File

@ -42,16 +42,12 @@ test('preserves a new layer lock as the reason a write was not dispatched',async
assert.equal(x.events[0].reason,'layer_newly_locked');
});
test('a malformed or foreign rejection cannot clear a possibly dispatched operation',async()=>{
for (const [key,value] of Object.entries({operationId:'other',run:'other',documentId:8,baseRevision:-1,
accountId:'other',origin:'https://other.test',projectLocalId:'other',accepted:true,dispatched:true,
error:{code:'other',message:'not sent'}})) {
const x = fixture(receipt=>({...receipt,[key]:value}));
await assert.rejects(executeWorkflow(x.host,args));
assert.equal(x.host.canvasOperations.original.operationId,x.calls[0],key);
assert.equal(x.host.canvasOperations.writesBlocked,true,key);
assert.equal(x.events.length,0,key);
}
test('a rejection for another operation cannot clear a possibly dispatched operation',async()=>{
const x = fixture(receipt=>({...receipt,operationId:'other'}));
await assert.rejects(executeWorkflow(x.host,args));
assert.equal(x.host.canvasOperations.original.operationId,x.calls[0]);
assert.equal(x.host.canvasOperations.writesBlocked,true);
assert.equal(x.events.length,0);
});
test('a user edit after the workflow read leaves an authoritative rejection known not dispatched',async()=>{

View File

@ -10,7 +10,7 @@ import { SessionManager } from '@earendil-works/pi-coding-agent';
import { DetailPiAgent } from '../src/agent.mjs';
import { ProjectStore, atomic } from '../src/store.mjs';
import { StdioCanvas } from '../src/stdio-canvas.mjs';
import { NativeCanvas } from '../src/native-bridge.mjs';
import { NativeControlClient as NativeCanvas } from '../src/native-control-client.mjs';
import { workflowContext, workflowResult } from '../src/workflow-context.mjs';
import { executeWorkflow } from '../src/workflow-execute.mjs';
import { cleanup } from './cleanup.mjs';