Files
Agent-Workbench/scripts/m4-live/payload.mjs
T
2026-11-11 22:58:21 +08:00

67 lines
7.2 KiB
JavaScript

// A one-shot compatibility observation in a new owned session. This function
// calls the existing Provider; it never reads or returns any 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 fresh 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.__workbenchM4Preflights ??= new Set();
ensure(!globalThis.__workbenchM4Preflights.has(session.id), 'A preflight cannot be replayed.'); globalThis.__workbenchM4Preflights.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.');
// A single physical request is this experiment's design, not a saved quota.
config.modelRouting.maxAttempts = 1;
config.modelRouting.members = config.modelRouting.members.map(value => ({ ...value, modelIdentityPolicy: 'require-match',
...(input.scope === 'streaming' ? { streaming: true } : {}) }));
const tools = input.scope === 'tools' ? [{ type: 'function', function: { name: 'workbench_m4_echo_nonce', description: 'Echo the supplied compatibility nonce. No file or command operation.',
parameters: { type: 'object', properties: { nonce: { type: 'string' } }, required: ['nonce'], additionalProperties: false } } }] : [];
const prompt = input.scope === 'tools' ? 'Call workbench_m4_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 M4 observation ended; do not replay.')), input.observationMs);
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, 'A frozen preflight must have one route.');
for (const body of variants) {
const actual = Object.fromEntries(['max_tokens', 'max_output_tokens', 'max_completion_tokens'].filter(key => Object.hasOwn(body, key)).map(key => [key, body[key]]));
ensure(JSON.stringify(actual) === JSON.stringify(input.expectedOutput.fields), 'Output fields must equal explicit settings or the Messages protocol requirement.');
}
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: 'M4 单次兼容预检', 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 });
// An observed tool call is not executed or inserted as an unpaired 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 : 'm4_compatibility_preflight');
}
const ledger = hub.ledger.page({ filters: { sessionId: session.id }, limit: 2 }); ensure(ledger.total <= 1 && ledger.items.length === ledger.total, 'Single-request contract violated.');
const calls = response?.message?.tool_calls ?? []; let contentPassed = false;
try { contentPassed = input.scope === 'tools' ? calls.length === 1 && calls[0].function.name === 'workbench_m4_echo_nonce'
&& JSON.parse(calls[0].function.arguments).nonce === input.nonce : !calls.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: ledger.total, wireStarts: wireIds.size, receipts, actualToolsExecuted: run.toolCalls, contentPassed,
outputFieldsSource: input.expectedOutput.source, savedConfigurationChanged: false, message: response?.message ?? null, usage: run.usage };
}