// One-shot QA adapter. Runs inside the existing formal host via the inspector; // never reads a credential value. Mirrors the sealed R preflight payload. export async function boundedGptPreflight(input) { const ensure = (value, message) => { if (!value) throw new Error(message); }; ensure(process.pid === input.pid, 'Unexpected host PID.'); 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 owned loopback server.'); const context = servers[0].workbenchHostAuthority?.context; ensure(context?.provider && context?.store && context?.runtime, 'Original context missing.'); const { store, provider, runtime } = context; ensure(runtime.appDirectory === input.runtimeRoot, 'Loaded runtime changed.'); ensure(![...store.sessions.values()].some(s => ['running', 'stopping', 'awaiting_approval'].includes(s.status)), 'Host is busy.'); const session = store.session(input.sessionId), project = store.project(session.projectId); ensure(session.projectId === input.projectId && session.messages.length === 0 && !session.runId, 'Probe session must be new and owned.'); const hub = provider.modelHub(store); const connection = hub.view().connections.find(c => c.id === input.connectionId); ensure(connection?.hasKey && connection.credentialRevision === input.credentialRevision, 'Original saved credential revision changed.'); ensure(connection.enabled && connection.protocol === 'chat-completions' && (connection.modelIdentityPolicy ?? 'record') === 'record', 'Probe protocol/auth/identity mismatch.'); ensure(connection.baseUrl === input.baseUrl && connection.model === input.model && connection.revision === input.connectionRevision, 'Connection changed.'); const config = hub.prepare({ ...store.config, mode: 'compatible', maxSteps: 1, maxOutputTokens: 256, contextLimit: 16000, maxRunTokens: 16000, maxTaskTokens: 16000, maxRunDurationMs: 320000, modelResponseTimeoutMs: 300000, modelStreamIdleTimeoutMs: 120000 }, { type: 'connection', id: input.connectionId }); config.modelRouting.members = config.modelRouting.members.map(member => ({ ...member, modelIdentityPolicy: 'require-match', modelIdentityAliases: [], modelIdentityAliasSource: '' })); ensure(config.modelRouting.members.length === 1 && config.modelRouting.maxAttempts === 1 && config.maxOutputTokens === 256, 'One-request hard limits missing.'); globalThis.__gptWProbeOnce ??= new Set(); ensure(!globalThis.__gptWProbeOnce.has(input.sessionId), 'This sample cannot be replayed.'); globalThis.__gptWProbeOnce.add(input.sessionId); session.title = input.title; const run = store.beginRun(session, input.prompt, false, config, { forceNewTask: true }); store.message(session, 'user', input.prompt); session.providerMessages.push({ role: 'user', content: input.prompt }); const step = store.beginStep(session, run), planner = runtime.requestPlanner(); let plan, response, diagnostic = null, requestEvent, receipts = 0, wireStarts = 0; const wireIds = new Set(); const signal = AbortSignal.timeout(320000); let stopReason = 'identity_probe_complete'; try { plan = planner.prepare(session, run, config, { system: 'This is a connection identity preflight. Reply to the user exactly. No tools are available. Do not perform any project work.', tools: [], stepId: step.id }); const variants = plan.body.kind === 'model-route-plan' ? plan.body.variants.map(v => v.body) : [plan.body]; ensure(variants.length === 1 && variants.every(b => !(b.tools?.length) && b.max_tokens === 256 && b.model === input.model), 'Wire request violates no-tool contract.'); ensure(plan.record.tokenReservation.reservedTokens <= 16000, 'Reservation exceeds sealed budget.'); const progress = event => { if (event.consumption) { receipts += Number(store.recordConsumption(session, run, { ...event.consumption, requestId: plan.record.id }, plan.record.tokenReservation.reservedTokens)); return; } if (event.phase === 'running' && event.wireAttemptId) { wireIds.add(event.wireAttemptId); wireStarts = wireIds.size; ensure(wireStarts === 1, 'No retries permitted.'); } requestEvent ??= store.event(session, { kind: 'model', source: 'model_connection', label: 'W · GPT单次身份预检(无工具)', phase: 'running', runId: run.id, contextPlanId: plan.record.id, startedAt: new Date().toISOString() }); if (event.modelAttemptId) requestEvent.modelAttemptId = event.modelAttemptId; if (event.connectionId) requestEvent.connectionId = event.connectionId; if (event.model) requestEvent.actualModel = event.model; if (event.modelIdentity) requestEvent.modelIdentity = event.modelIdentity; if (event.requestUrl) requestEvent.requestUrl = event.requestUrl; if (event.diagnostic) requestEvent.diagnostic = event.diagnostic; if (event.stream) requestEvent.stream = event.stream; if (event.phase) requestEvent.phase = event.phase; plan.record.requestAttempts = wireStarts; step.modelAttempts = wireStarts; store.save(session); }; response = await provider.complete(config, plan.messages, project, signal, progress, plan.record, [], { attempts: 1, maxBudgetAttempts: 1 }); ensure(!response.message.tool_calls?.length, 'Unsolicited tools are never executed.'); ensure(receipts === 1, 'Expected one original consumption receipt.'); planner.finish(session, plan.record, { response, attempts: wireStarts }); session.providerMessages.push(response.message); store.message(session, 'assistant', response.message.content); const total = (run.usage?.reportedTokens ?? run.usage?.totalTokens ?? 0); session.status = total > 16000 ? 'paused' : 'completed'; if (total > 16000) stopReason = 'task_token_limit'; } catch (cause) { diagnostic = cause.diagnostic ?? { source: 'workbench', origin: 'local', stage: 'identity_preflight', kind: signal.aborted ? 'cancelled' : 'runtime', title: '身份预检需要核对', message: provider.redact(cause.message), occurredAt: new Date().toISOString() }; session.status = diagnostic.kind === 'model_identity' || signal.aborted ? 'paused' : 'failed'; stopReason = diagnostic.kind; session.lastFailure = { ...diagnostic, runId: run.id }; const message = store.message(session, 'system', diagnostic.message); session.failure = { ...session.lastFailure, messageId: message.id }; if (plan) planner.finish(session, plan.record, { error: new Error(diagnostic.message), attempts: wireStarts }); } finally { if (requestEvent) { requestEvent.phase = diagnostic ? 'failed' : 'completed'; requestEvent.finishedAt = new Date().toISOString(); if (diagnostic) requestEvent.diagnostic = diagnostic; } store.finishStep(session, step, diagnostic ? 'failed' : 'completed'); store.finishRun(session, run, stopReason); } const attempts = hub.attempts.filter(a => a.sessionId === session.id); ensure(attempts.length <= 1 && wireStarts <= 1, 'Single-request limit exceeded.'); return { sessionId: session.id, projectId: project.id, taskId: run.taskId, runId: run.id, status: session.status, stopReason, attempts: attempts.length, receipts, wireStarts, actualTools: run.toolCalls, usage: run.usage, contextPlanId: plan?.record.id ?? null, diagnostic, message: response?.message ?? null }; }