64 lines
6.8 KiB
JavaScript
64 lines
6.8 KiB
JavaScript
// One-shot preflight in the existing host. Uses the existing Provider credential
|
|
// reference; never reads, exports, decrypts or replaces a credential value.
|
|
export async function providerPreflight(input) {
|
|
const ensure = (value, message) => { if (!value) throw Error(message); };
|
|
ensure(process.pid === input.pid, 'Host PID changed.');
|
|
const servers = process._getActiveHandles().filter(h => h?.listening && h.address?.()?.address === '127.0.0.1' && h.address?.()?.port === input.port);
|
|
ensure(servers.length === 1, 'Expected one loopback host.');
|
|
const { store, provider, runtime } = servers[0].workbenchHostAuthority.context;
|
|
ensure(runtime.appDirectory === input.runtimeRoot, 'Runtime changed.');
|
|
ensure(!runtime.active.size, 'Host is busy.');
|
|
const session = store.session(input.sessionId), project = store.project(session.projectId), hub = provider.modelHub(store);
|
|
ensure(session.projectId === input.projectId && !session.runId && !session.messages.length, 'Only a new owned session may run.');
|
|
const connection = hub.view().connections.find(value => value.id === input.connection.id);
|
|
ensure(connection?.enabled && connection.hasKey && connection.revision === input.connection.revision
|
|
&& connection.credentialRevision === input.connection.credentialRevision && connection.model === input.connection.model
|
|
&& connection.protocol === input.connection.protocol && connection.baseUrl === input.connection.baseUrl, 'Frozen connection changed.');
|
|
globalThis.__workbenchADPreflights ??= new Set();
|
|
ensure(!globalThis.__workbenchADPreflights.has(session.id), 'This preflight cannot be replayed.'); globalThis.__workbenchADPreflights.add(session.id);
|
|
const config = hub.prepare({ ...store.config, mode: 'compatible' }, { type: 'connection', id: connection.id });
|
|
ensure(config.capacityMode === 'passthrough' && config.executionMode === 'unrestricted', 'Keep default passthrough.');
|
|
config.modelRouting.maxAttempts = 1;
|
|
config.modelRouting.members = config.modelRouting.members.map(value => ({ ...value, modelIdentityPolicy: 'require-match' }));
|
|
const tools = input.scope === 'tools' ? [{ type: 'function', function: { name: 'workbench_echo_nonce', description: 'Return this preflight nonce. This tool performs no external operation.',
|
|
parameters: { type: 'object', properties: { nonce: { type: 'string' } }, required: ['nonce'], additionalProperties: false } } }] : [];
|
|
const prompt = input.scope === 'tools' ? 'Call workbench_echo_nonce exactly once with nonce ' + input.nonce + '. No other task.' : 'Reply exactly: OK ' + input.nonce;
|
|
const run = store.beginRun(session, prompt, false, config, { forceNewTask: true }), user = store.message(session, 'user', prompt);
|
|
run.inputMessage = { id: user.id, providerIndex: 0, origin: 'user' }; session.providerMessages.push({ role: 'user', content: prompt });
|
|
session.status = 'running'; const step = store.beginStep(session, run), planner = runtime.requestPlanner();
|
|
const controller = new AbortController(), timer = setTimeout(() => controller.abort(Error('Predeclared preflight observation ended; do not replay.')), 180000);
|
|
let plan, response, diagnostic = null, event, receipts = 0; const wireIds = new Set();
|
|
try {
|
|
plan = planner.prepare(session, run, config, { system: 'Connection compatibility preflight only. Follow the user exactly. Do not perform project work.', tools, stepId: step.id });
|
|
const variants = plan.body.kind === 'model-route-plan' ? plan.body.variants.map(value => value.body) : [plan.body];
|
|
ensure(variants.length === 1 && variants.every(value => !Object.hasOwn(value, 'max_tokens') && !Object.hasOwn(value, 'max_output_tokens') && !Object.hasOwn(value, 'max_completion_tokens')), 'No local output cap may be added.');
|
|
response = await provider.complete(config, plan.messages, project, controller.signal, progress => {
|
|
if (progress.consumption) { receipts += Number(store.recordConsumption(session, run, { ...progress.consumption, requestId: plan.record.id }, plan.record.tokenReservation?.reservedTokens ?? plan.record.estimatedInputTokens)); return; }
|
|
if (progress.phase === 'running' && progress.wireAttemptId) { wireIds.add(progress.wireAttemptId); ensure(wireIds.size === 1, 'No retry permitted.'); }
|
|
event ??= store.event(session, { kind: 'model', source: 'model_connection', label: 'AD 单次兼容预检', phase: 'running', runId: run.id, contextPlanId: plan.record.id, startedAt: new Date().toISOString() });
|
|
for (const key of ['modelAttemptId', 'connectionId', 'modelIdentity', 'requestUrl', 'diagnostic', 'stream', 'phase']) if (progress[key] !== undefined) event[key] = progress[key];
|
|
plan.record.requestAttempts = wireIds.size; step.modelAttempts = wireIds.size; store.save(session);
|
|
}, plan.record, tools, { attempts: 1, maxBudgetAttempts: 1 });
|
|
planner.finish(session, plan.record, { response, attempts: wireIds.size });
|
|
// Tool-call output is retained in the original response artifact and result;
|
|
// it is not inserted as an unpaired, apparently executable history call.
|
|
if (!response.message.tool_calls?.length) session.providerMessages.push(response.message);
|
|
store.message(session, 'assistant', response.message.content || '已收到原工具调用,预检不执行工具。'); session.status = 'completed';
|
|
} catch (cause) {
|
|
diagnostic = cause.diagnostic ?? { source: 'workbench', origin: 'local', stage: 'preflight', kind: controller.signal.aborted ? 'observation_stop' : 'runtime', message: provider.redact(cause.message) };
|
|
session.status = 'failed'; session.lastFailure = { ...diagnostic, runId: run.id }; store.message(session, 'system', diagnostic.message);
|
|
if (plan) planner.finish(session, plan.record, { error: new Error(diagnostic.message), attempts: wireIds.size });
|
|
} finally {
|
|
clearTimeout(timer); if (event) { event.phase = diagnostic ? 'failed' : 'completed'; event.finishedAt = new Date().toISOString(); }
|
|
store.finishStep(session, step, diagnostic ? 'failed' : 'completed'); store.finishRun(session, run, diagnostic ? diagnostic.kind : 'compatibility_preflight');
|
|
}
|
|
const rows = hub.attempts.filter(value => value.sessionId === session.id); ensure(rows.length <= 1, 'Single-request contract violated.');
|
|
const toolCalls = response?.message?.tool_calls ?? [];
|
|
let contentPassed = false;
|
|
try { contentPassed = input.scope === 'tools' ? toolCalls.length === 1 && toolCalls[0].function.name === 'workbench_echo_nonce'
|
|
&& JSON.parse(toolCalls[0].function.arguments).nonce === input.nonce : !toolCalls.length && response?.message?.content?.trim() === 'OK ' + input.nonce; } catch {}
|
|
return { sessionId: session.id, taskId: run.taskId, runId: run.id, scope: input.scope, status: session.status, diagnostic,
|
|
attempts: rows.length, wireStarts: wireIds.size, receipts, actualToolsExecuted: run.toolCalls, contentPassed,
|
|
noLocalTokenCaps: true, message: response?.message ?? null, usage: run.usage };
|
|
}
|