gongxiangp2/apps/detail-agent-pi/src/desktop-host.mjs

235 lines
14 KiB
JavaScript

import { CanvasOperations } from './canvas-operations.mjs';
import { BridgeError, authorityFailure, authorityLost } from './bridge-error.mjs';
import { redact } from './credentials.mjs';
import { createInterface } from 'node:readline';
import path from 'node:path';
import { assertPiNodeVersion } from './runtime-policy.mjs';
import { pathToFileURL } from 'node:url';
import { randomUUID } from 'node:crypto';
import { executionCategory } from './activity-event.mjs';
assertPiNodeVersion(process.versions.node);
const canvasTelemetry = new Set(['pi-state', 'pi-context-usage', 'pi-ui-request', 'pi-ui-poll', 'pi-ui-cancel']);
export function observeCanvasCalls(store, call) {
return async (action, input, execution) => {
if (action === 'pi-delta' || action === 'pi-activity') return call(action,input);
const identity={...store.executionScope,operationId:input.operationId ?? execution?.operationId ?? randomUUID(),
attempt:execution?.attempt ?? 1,requestId:execution?.requestId ?? input.request?.requestId,
revision:input.revision ?? store.executionScope.revision};
const category=executionCategory(action);
const startedAt = performance.now();
const record = (status, extra) => store.appendEvent({
type:'canvas_receipt', action, ...(action === 'pi-image-request' ? {imageAction:input.action} : null),
...(action === 'pi-native-call' ? {nativeMethod:input.method,command:input.params?.command} : null),
...identity, phase:'receipt', status,
durationMs:Math.round(performance.now() - startedAt), ...extra,
}).catch(error=>console.warn('小壹画布事件写入失败',error.code ?? error.name));
store.executionHealth.agentHeartbeat=Date.now();
let accepted = false;
try {
const reply=call(action,action==='pi-production-finish'?{...input,execution:{...identity,...store.executionHealth}}:input,()=>{
store.executionHealth.uiHeartbeat=Date.now();
accepted = true;
});
execution?.onEnqueued?.();
const value=await reply;
if (value?.conversationActive === true) store.executionHealth.uiHeartbeat=Date.now();
const binding=value?.productionCanvas;
if (binding?.documentKey) Object.assign(store.executionScope,{
outputId:binding.outputId,variantId:binding.variantId,documentKey:binding.documentKey,writeEpoch:binding.writeEpoch,
});
if (Number.isSafeInteger(value?.revision) &&
(binding?.documentKey || value.revision >= (store.executionScope.revision ?? 0))) {
store.executionScope.revision=value.revision;
}
const status=value?.executed===false && value?.error ? 'failed' :
[value?.status,value?.phase].find(v=>typeof v==='string') ?? 'completed';
const failure = status === 'failed' ? BridgeError.from(value.failure ?? value.error ?? value) : undefined;
if (!canvasTelemetry.has(action) || failure) await record(status,{category,revision:value?.revision ?? identity.revision,
...(failure ? {failureCategory:failure.category,message:failure.message} : null),
...(value?.requestId ? {requestId:value.requestId} : null)});
return value;
} catch(error) {
const failure=BridgeError.from(error);
const status=failure.category==='cancelled'?'cancelled':failure.category==='transport_interrupted'?'unknown':'failed';
await record(status,{category:accepted?category:'ui_ack',failureCategory:failure.category,message:failure.message});
throw error;
}
};
}
// Explicit local QA only. Matching a pending real job consumes the switch;
// model arguments can neither configure nor re-arm it.
export function qaNativeTimeout(raw) {
if (!raw) return () => false;
let value; try { value = JSON.parse(raw); } catch { throw Error('本地原生超时验收配置无效'); }
const keys = ['scope','project','documentId','accountId','origin','command'];
if (!value || Object.keys(value).sort().join() !== [...keys].sort().join()
|| keys.filter(key => key !== 'documentId').some(key => typeof value[key] !== 'string' || !value[key] || value[key].length > 256)
|| !Number.isSafeInteger(value.documentId) || value.documentId < 1) throw Error('本地原生超时验收配置无效');
let consumed = false;
return (identity, command) => {
if (consumed || command !== value.command || keys.filter(key => key !== 'command').some(key => identity[key] !== value[key])) return false;
consumed = true; return true;
};
}
const consumeQaNativeTimeout = qaNativeTimeout(process.env.PHOTOCRAFT_QA_NATIVE_TIMEOUT);
async function cli() {
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
let initial, serial = 0, closed = false;
const waiting = new Map();
const send = value => { if (!closed) process.stdout.write(JSON.stringify(redact(value)) + '\n'); };
const call = (action, input) => new Promise((resolve, reject) => {
const id = ++serial;
waiting.set(id, { resolve, reject }); send({ type: 'canvas', id, action, input });
});
lines.on('line', line => {
try {
if (line.length > 2 * 1024 * 1024) throw Error('本地消息超限');
const value = JSON.parse(line);
if (!initial) { initial = value; void runSession(value, call).then(result => send({type:'complete',value:result})).finally(() => { lines.close(); process.stdin.destroy(); }); return; }
const pending = waiting.get(value.id);
if (pending) {
waiting.delete(value.id);
if (value.error) pending.reject(typeof value.error === 'string' ? Error(value.error) : BridgeError.from(value.error));
else pending.resolve(value.value);
}
} catch { send({ type: 'fatal', error: '本地连接消息无效;不会重发模型请求' }); }
});
lines.on('close', () => {
closed = true;
for (const pending of waiting.values()) { pending.reject(new BridgeError('客户端已关闭,原请求需只读核查','transport_interrupted',{retryable:true,dispatched:true})); }
waiting.clear();
});
}
if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) {
if (process.argv[2] === '--daemon') {
const { startDaemon } = await import('./desktop-daemon.mjs');
const { templateRequest } = await import('./enterprise-templates.mjs');
startDaemon({ runSession, readKnowledge:templateRequest });
} else await cli();
}
export function bindRecovery(host, recovery, identity) {
if (!recovery) return;
const {scope, project, documentId, accountId, origin} = identity;
if (typeof scope !== 'string' || !scope || typeof project !== 'string' || !project || !Number.isSafeInteger(documentId) || documentId < 1
|| typeof accountId !== 'string' || !accountId || typeof origin !== 'string' || !origin) throw Error('原操作核查身份不完整,未派发');
const key = JSON.stringify([scope, project, documentId, accountId, origin]);
let slot = recovery.get(key);
if (!slot) {
slot = { pending: [], active: 0 }; recovery.set(key, slot);
}
slot.active++;
host.canvasOperations = new CanvasOperations(slot.pending, {documentId,scope,project,accountId,origin});
let released = false;
return () => {
if (released) return;
released = true;
const current = recovery.get(key);
if (current === slot) {
current.active--;
if (!current.active && !current.pending.length) recovery.delete(key);
}
};
}
export async function runSession(config, call, sharedBroker, recovery, signal, onAuthorizationLost) {
if (config.mode === 'record-production-export') {
try {
const {recordProductionExport} = await import('./production-goal.mjs');
return await recordProductionExport(config.sessionDir, config.goalId);
} catch(error) { return {error:BridgeError.from(error).message}; }
}
let host, broker, store, output, atomic, heartbeat;
let releaseRecovery;
const productionGoal=config.mode==='prompt'&&config.productProduction===true
? {outputId:config.outputId,variantId:config.variantId,requestedOutputs:config.requestedOutputs,
pendingOutputs:config.pendingOutputs,drafts:config.productionDrafts,workspaceId:config.workspaceId,template:config.productionTemplate} : undefined;
const startedAt = performance.now();
const abort = () => { if (host) void host.session.abort().catch(()=>{}); };
try {
if (!authorityLost(signal?.reason)) signal?.throwIfAborted();
signal?.addEventListener('abort',abort,{once:true});
const [{DetailPiAgent},{Native98kBroker},storage,{StdioCanvas},{resolveRules},{productionGoalPreflight}] =
await Promise.all([import('./agent.mjs'),import('./native-bridge.mjs'),import('./store.mjs'),
import('./stdio-canvas.mjs'),import('./rules.mjs'),import('./production-goal.mjs')]);
atomic = storage.atomic;
if (productionGoal) {
const blocked = productionGoalPreflight(productionGoal);
if (blocked) return blocked;
}
const modelRole=productionGoal?'detail':'chat';
const bindingConfig={binary:config.binary,profile:config.profile,project:config.project,scope:config.scope,modelRole,
dispatchLease:config.dispatchLease,onAuthorizationLost};
broker=sharedBroker??new Native98kBroker(bindingConfig);
const brokerStartedAt = performance.now();
let binding;
if(config.ruleCatalog==null&&config.ruleId==null){
binding={brandId:'unconfigured',shopId:'unconfigured',categoryId:'unconfigured',brandName:'未配置',shopName:'未配置',categoryName:'未配置',platform:'native-project',version:'unconfigured-v1',source:'explicit-unconfigured-project-discussion',rules:['当前项目未配置品牌/店铺/品类规则。可以讨论通用思路;不得编造或借用其他品牌规则,产品事实以本项目只读资料为准。']};
}else{
const combo = config.ruleCatalog?.bindings?.find(b => b.id === config.ruleId);
if (!combo) throw Error('项目规则快照不完整,未发送模型');
const shop = config.ruleCatalog.shops.find(s => s.id === combo.shopId);
binding = resolveRules({ brandId: shop.brandId, shopId: shop.id, categoryId: combo.categoryId }, config.ruleCatalog);
}
store = await storage.ProjectStore.open(config.root, { scope: config.scope, project: config.project }, binding, { continuous:true });
store.projectExportRoot = config.projectExportRoot;
store.xiaoyiCache = config.xiaoyiCache;
signal?.throwIfAborted();
broker.bind(bindingConfig);
const info = await broker.info(productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined);
const brokerReadyAt = performance.now();
if (info.accountScope !== config.scope) throw authorityFailure('scope_changed');
store.executionScope={runId:config.runId ?? randomUUID(),outputId:config.outputId,variantId:config.variantId,
revision:config.revision,documentKey:config.documentKey};
store.executionHealth={agentHeartbeat:Date.now()};
heartbeat=setInterval(()=>{
store.executionHealth.agentHeartbeat=Date.now();
},15_000);
heartbeat.unref();
const canvas = new StdioCanvas(observeCanvasCalls(store,call), config.documentId);
const usage = [];
host = await DetailPiAgent.open({ store, broker, productionGoal, productionSignal:signal, brokerInfo:info, canvas, projectEvidence:config.projectEvidence, documentId:config.documentId, onEvent: event => {
if (event.type === 'usage') usage.push(event);
} });
if (productionGoal) await store.appendEvent({type:'production_startup',
importsMs:Math.round(brokerStartedAt-startedAt),brokerMs:Math.round(brokerReadyAt-brokerStartedAt),
sessionMs:Math.round(performance.now()-brokerReadyAt),checks:info.selectionTimings});
releaseRecovery = bindRecovery(host, recovery, {scope:info.accountScope, project:config.project, documentId:config.documentId,
accountId:host.canvas.identity?.accountId, origin:host.canvas.identity?.origin});
host.qaNativeTimeout = command => consumeQaNativeTimeout({scope:info.accountScope, project:config.project, documentId:config.documentId,
accountId:host.canvas.identity?.accountId, origin:host.canvas.identity?.origin}, command);
signal?.throwIfAborted();
const result = await host.prompt(config.text, {referenceContent:config.referenceContent,goalContinuation:!!productionGoal&&!config.goalUserEntry});
signal?.throwIfAborted();
if (broker.authority?.error) throw broker.authority.error;
output = {...result,unknown:false,usage,contextUsage:host.contextUsage,
pending:[],bindingHash:store.hash,sessionFile:host.manager.getSessionFile()};
} catch (error) {
const authority = [signal?.reason, broker?.authority?.error, error].find(authorityLost);
if (authority) {
onAuthorizationLost?.(authority);
let draftSaved = false;
if (store) {
const draft = {state:'paused', reason:authority.category, documentId:config.documentId,
scope:config.scope, project:config.project, text:config.text, sessionFile:host?.manager.getSessionFile()};
try {
await atomic(path.join(store.dir, 'authorization-pause.json'), draft);
draftSaved = true;
} catch { /* The paused receipt reports the actual draft write outcome. */ }
}
return {phase:'paused', draftSaved, error:authority.message, failure:authority.wire(),
unknown:false,reposted:false};
}
const failure = BridgeError.from(error).wire();
output = {error:failure.message,failure,unknown:false,pending:[],reposted:false,contextUsage:host?.contextUsage};
} finally {
clearInterval(heartbeat);
signal?.removeEventListener('abort',abort);
try { if (host) await host.dispose(); } finally { releaseRecovery?.(); if (broker && !sharedBroker) await broker.close(); }
}
return output;
}