feat(runtime): default to passthrough and persist execution permissions
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { isPassthrough } from './model-capacity.mjs';
|
||||
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
||||
const fail = message => { throw new Error('Messages 请求未发送:' + message); };
|
||||
|
||||
@@ -13,7 +14,7 @@ function contentBlocks(content) {
|
||||
}
|
||||
|
||||
export function messagesBody(config, messages, tools, native) {
|
||||
if (native.nativeParameters.thinking?.type === 'enabled' && native.nativeParameters.thinking.budget_tokens >= config.maxOutputTokens) fail('thinking.budget_tokens 必须小于本次 max_tokens 输出预算。');
|
||||
if (!isPassthrough(config) && native.nativeParameters.thinking?.type === 'enabled' && native.nativeParameters.thinking.budget_tokens >= config.maxOutputTokens) fail('thinking.budget_tokens 必须小于本次 max_tokens 输出预算。');
|
||||
const system = [], wire = [];
|
||||
const append = (role, content) => {
|
||||
if (!content.length) return;
|
||||
@@ -49,7 +50,7 @@ export function messagesBody(config, messages, tools, native) {
|
||||
});
|
||||
return { model: config.model, ...(system.length ? { system } : {}), messages: wire,
|
||||
...(definitions.length ? { tools: definitions, tool_choice: { type: 'auto' } } : {}),
|
||||
max_tokens: config.maxOutputTokens, stream: config.streaming === true, ...native.nativeParameters };
|
||||
...(!isPassthrough(config) ? { max_tokens: config.maxOutputTokens } : {}), stream: config.streaming === true, ...native.nativeParameters };
|
||||
}
|
||||
|
||||
export function messagesHistory(body) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { unrestricted, ceiling } from './execution-policy.mjs';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
export const BROWSER_ACTIVE = new Set(['queued', 'snapshotting', 'launching', 'running', 'closing']);
|
||||
@@ -7,27 +8,27 @@ export const BROWSER_LIMITS = Object.freeze({ files: 512, bytes: 32 * 1024 * 102
|
||||
export const browserError = (message, status = 409) => Object.assign(new Error(message), { status });
|
||||
export const browserHash = value => createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(value)).digest('hex');
|
||||
|
||||
export function browserPlanInput(input = {}) {
|
||||
export function browserPlanInput(input = {}, config = {}) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)
|
||||
|| Object.keys(input).some(key => !['build_directory', 'path', 'viewport', 'steps'].includes(key))) throw browserError('浏览器计划只接受构建目录、页面路径、视口和交互步骤。', 400);
|
||||
const buildDirectory = input.build_directory ?? 'dist';
|
||||
if (typeof buildDirectory !== 'string' || !buildDirectory.trim() || buildDirectory.length > 160 || /[\\:\0]/.test(buildDirectory)
|
||||
if (typeof buildDirectory !== 'string' || !buildDirectory.trim() || buildDirectory.length > ceiling(config, 160) || /[\\:\0]/.test(buildDirectory)
|
||||
|| buildDirectory.startsWith('/') || buildDirectory.split('/').some(part => !part || part.startsWith('.') || ['node_modules', 'runtime'].includes(part.toLowerCase()))) throw browserError('构建目录需要项目内的常规相对目录,例如dist或build。', 400);
|
||||
const pathname = input.path ?? '/';
|
||||
if (typeof pathname !== 'string' || pathname.length > 300 || !pathname.startsWith('/') || pathname.startsWith('//') || /[\\\0\r\n]/.test(pathname)
|
||||
if (typeof pathname !== 'string' || pathname.length > ceiling(config, 300) || !pathname.startsWith('/') || pathname.startsWith('//') || /[\\\0\r\n]/.test(pathname)
|
||||
|| pathname.split(/[/?#]/).includes('..') || new URL(pathname, 'http://127.0.0.1').origin !== 'http://127.0.0.1') throw browserError('页面路径必须位于所属本地预览,例如/。', 400);
|
||||
const viewport = input.viewport ?? { width: 1280, height: 900 };
|
||||
if (!viewport || Object.keys(viewport).some(key => !['width', 'height'].includes(key)) || !Number.isSafeInteger(viewport.width) || !Number.isSafeInteger(viewport.height)
|
||||
|| viewport.width < 320 || viewport.width > 1440 || viewport.height < 400 || viewport.height > 1200) throw browserError('浏览器视口范围为宽320–1440、高400–1200像素。', 400);
|
||||
|| viewport.width < (unrestricted(config) ? 1 : 320) || viewport.width > ceiling(config, 1440) || viewport.height < (unrestricted(config) ? 1 : 400) || viewport.height > ceiling(config, 1200)) throw browserError('浏览器视口范围为宽320–1440、高400–1200像素。', 400);
|
||||
const steps = input.steps ?? [];
|
||||
if (!Array.isArray(steps) || steps.length > BROWSER_LIMITS.steps) throw browserError('浏览器计划最多20个交互或断言。', 400);
|
||||
if (!Array.isArray(steps) || steps.length > ceiling(config, BROWSER_LIMITS.steps)) throw browserError('浏览器计划最多20个交互或断言。', 400);
|
||||
for (const step of steps) {
|
||||
if (!step || typeof step !== 'object' || Array.isArray(step) || !BROWSER_ACTIONS.includes(step.action)
|
||||
|| Object.keys(step).some(key => !['action', 'selector', 'value', 'text', 'count', 'visible', 'contains'].includes(key))) throw browserError('浏览器步骤只支持填写、选择、点击和文本/数量/可见性断言。', 400);
|
||||
if (typeof step.selector !== 'string' || !step.selector.trim() || step.selector.length > 300 || /[\0\r\n]|>>|^[a-z_-]+=/i.test(step.selector)) throw browserError('步骤需要最多300字的CSS选择器,不能使用脚本或跨页面选择器。', 400);
|
||||
if (['fill', 'select'].includes(step.action) && (typeof step.value !== 'string' || step.value.length > 2000)) throw browserError('填写或选择需要最多2000字的value。', 400);
|
||||
if (step.action === 'assert_text' && (typeof step.text !== 'string' || step.text.length > 4000)) throw browserError('文本断言需要最多4000字的text。', 400);
|
||||
if (step.action === 'assert_count' && (!Number.isSafeInteger(step.count) || step.count < 0 || step.count > 1000)) throw browserError('数量断言需要0–1000的整数count。', 400);
|
||||
if (typeof step.selector !== 'string' || !step.selector.trim() || step.selector.length > ceiling(config, 300) || /[\0\r\n]|>>|^[a-z_-]+=/i.test(step.selector)) throw browserError('步骤需要最多300字的CSS选择器,不能使用脚本或跨页面选择器。', 400);
|
||||
if (['fill', 'select'].includes(step.action) && (typeof step.value !== 'string' || step.value.length > ceiling(config, 2000))) throw browserError('填写或选择需要最多2000字的value。', 400);
|
||||
if (step.action === 'assert_text' && (typeof step.text !== 'string' || step.text.length > ceiling(config, 4000))) throw browserError('文本断言需要最多4000字的text。', 400);
|
||||
if (step.action === 'assert_count' && (!Number.isSafeInteger(step.count) || step.count < 0 || step.count > ceiling(config, 1000))) throw browserError('数量断言需要0–1000的整数count。', 400);
|
||||
if (step.visible !== undefined && typeof step.visible !== 'boolean' || step.contains !== undefined && typeof step.contains !== 'boolean') throw browserError('可见性和包含选项需要布尔值。', 400);
|
||||
}
|
||||
return { buildDirectory, path: pathname, viewport: { ...viewport }, steps: structuredClone(steps) };
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
import { ceiling } from './execution-policy.mjs';
|
||||
export const browsingError = message => Object.assign(new Error(message), { status: 409, code: 'BROWSING_SCOPE_REJECTED' });
|
||||
export const BROWSING_ACTIONS = ['click','fill','scroll','wait','navigate','back','forward','reload','download'];
|
||||
export function browsingUrl(value, { origins = null, previewOrigin = null, allowHttpLoopback = false, workbenchOrigin = null } = {}) {
|
||||
export function browsingUrl(value, { origins = null, previewOrigin = null, allowHttpLoopback = false, workbenchOrigin = null, fullAccess = false } = {}) {
|
||||
let url; try { url = new URL(value); } catch { throw browsingError('请填写明确的网站地址。'); }
|
||||
if (fullAccess && ['http:', 'https:'].includes(url.protocol)) return url;
|
||||
const local = url.hostname === '127.0.0.1' && (url.origin === previewOrigin || allowHttpLoopback);
|
||||
if (url.username || url.password || url.href.length > 2000 || (url.protocol !== 'https:' && !(local && url.protocol === 'http:'))
|
||||
|| url.origin === workbenchOrigin || !local && (/^(localhost|.*\.localhost|.*\.local|\[.*\]|\d+(?:\.\d+){0,3})$/i.test(url.hostname))) throw browsingError('只接受HTTPS网站或明确所属预览;不能访问工作台、凭据地址或其它本地服务。');
|
||||
if (origins && !origins.includes(url.origin)) throw browsingError('网站来源超出原授权范围,请重新明确授权。');
|
||||
return url;
|
||||
}
|
||||
export function browsingAction(input) {
|
||||
export function browsingAction(input, config = {}) {
|
||||
const fields = ['action','observationId','revision','ref','value','url','amount','milliseconds'];
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !fields.includes(key)) || !BROWSING_ACTIONS.includes(input.action)) throw browsingError('浏览器只接受固定的所属页面动作。');
|
||||
if (typeof input.observationId !== 'string' || typeof input.revision !== 'string') throw browsingError('动作需要原页面观察及修订身份。');
|
||||
if (['click','fill'].includes(input.action) && (typeof input.ref !== 'string' || !/^e\d{1,4}$/.test(input.ref))) throw browsingError('请使用原观察提供的可见控件编号。');
|
||||
if (input.action === 'fill' && (typeof input.value !== 'string' || input.value.length > 4000)) throw browsingError('输入值需要4000字以内的文本;密码和文件选择不通过代理填写。');
|
||||
if (['click','fill'].includes(input.action) && (typeof input.ref !== 'string' || !/^e\d+$/.test(input.ref))) throw browsingError('请使用原观察提供的可见控件编号。');
|
||||
if (input.action === 'fill' && (typeof input.value !== 'string' || input.value.length > ceiling(config, 4000))) throw browsingError('输入值需要文本。');
|
||||
if (['navigate','download'].includes(input.action) && typeof input.url !== 'string') throw browsingError('页面导航或下载需要明确地址。');
|
||||
if (input.action === 'scroll' && (!Number.isInteger(input.amount) || Math.abs(input.amount) > 1200)) throw browsingError('每次滚动范围为正负1200像素。');
|
||||
if (input.action === 'wait' && (!Number.isInteger(input.milliseconds) || input.milliseconds < 0 || input.milliseconds > 2000)) throw browsingError('每次页面等待最多2秒。');
|
||||
if (input.action === 'scroll' && (!Number.isSafeInteger(input.amount) || Math.abs(input.amount) > ceiling(config, 1200))) throw browsingError('滚动范围需要有效像素整数。');
|
||||
if (input.action === 'wait' && (!Number.isSafeInteger(input.milliseconds) || input.milliseconds < 0 || input.milliseconds > ceiling(config, 2000))) throw browsingError('页面等待需要有效毫秒数。');
|
||||
return input;
|
||||
}
|
||||
export const browsingToolDefinitions = [
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { unrestricted, ceiling } from './execution-policy.mjs';
|
||||
import { engineError, engineDigest, engineCanonicalDigest } from './engines.mjs';
|
||||
import { completionBody, requestMetrics } from './model-request.mjs';
|
||||
import { compactToolFeedback } from '../../core/context/tool-feedback.mjs';
|
||||
@@ -102,9 +103,9 @@ export function engineContextEvidence(store,session,job,messages) {
|
||||
export function engineContextView(messages,tools,config,index,reference) {
|
||||
const original=completionBody(config,messages,tools),before=requestMetrics(original);
|
||||
const safetyTokens=Math.max(512,Math.ceil(Math.min(config.contextLimit,24000)*0.1));
|
||||
const inputBudget=config.contextLimit-config.maxOutputTokens-safetyTokens;
|
||||
const inputBudget=config.capacityMode === 'passthrough' ? null : config.contextLimit-config.maxOutputTokens-safetyTokens;
|
||||
const groups=engineHistoryGroups(messages),fixed=groups.filter(x=>['system','developer','user'].includes(x.messages[0].role));
|
||||
if(before.estimatedInputTokens<=inputBudget)return {schemaVersion:1,mode:'full',messages,body:original,before,metrics:before,
|
||||
if(inputBudget === null || before.estimatedInputTokens<=inputBudget)return {schemaVersion:1,mode:'full',messages,body:original,before,metrics:before,
|
||||
inputBudget,safetyTokens,indexArtifactId:null,indexSha256:null,retainedGroups:groups.map(x=>x.index),archivedGroups:[]};
|
||||
if(!index||!reference?.id||!reference.sha256)throw engineError('超限原生历史缺少可核对的归档索引。');
|
||||
const selected=new Set(fixed.map(x=>x.index)),latest=index.groups.filter(x=>x.results.length).at(-1);
|
||||
|
||||
@@ -73,8 +73,8 @@ export function verifyEngineModelInput(store, session, job, request) {
|
||||
if (input.owner.sessionId !== job.sessionId || input.owner.taskId !== job.taskId || input.owner.runId !== job.runId || input.owner.projectId !== job.projectId
|
||||
|| controlledDigest(input.native) !== request.sourceSha256 || metrics.sha256 !== request.requestSha256 || metrics.bytes !== request.requestBytes
|
||||
|| !Number.isSafeInteger(request.maxAttempts) || request.maxAttempts < 1 || request.maxAttempts > 8
|
||||
|| !Number.isSafeInteger(input.native.maxTokens) || input.native.maxTokens < 1
|
||||
|| !requestVariants(input.body).every(body => outputReservation(body) === input.native.maxTokens)
|
||||
|| (job.model.capacityMode !== 'passthrough' && (!Number.isSafeInteger(input.native.maxTokens) || input.native.maxTokens < 1))
|
||||
|| !requestVariants(input.body).every(body => outputReservation(body) === (job.model.capacityMode === 'passthrough' ? null : input.native.maxTokens))
|
||||
|| request.reservedPerAttempt !== (request.reservationVersion===1?request.tokenReservation.reservedTokens:metrics.estimatedInputTokens + 128 + input.native.maxTokens)) throw engineError('原引擎模型输入、归属或预算核对失败。');
|
||||
if(input.view){
|
||||
const view=input.view,source=store.owned('artifact',view.sourceArtifactId,session.id),sourceValue=JSON.parse(store.artifactStore.read(source));
|
||||
@@ -97,7 +97,7 @@ export function verifyEngineModelInput(store, session, job, request) {
|
||||
indexArtifactId:projected.indexArtifactId,indexSha256:projected.indexSha256,beforeInputTokens:projected.before.estimatedInputTokens,
|
||||
inputBudget:projected.inputBudget,safetyTokens:projected.safetyTokens,retainedGroups:projected.retainedGroups,archivedGroups:projected.archivedGroups};
|
||||
if(controlledDigest(view)!==controlledDigest(expectedView)||controlledDigest(projected.body)!==controlledDigest(input.body)
|
||||
||projected.metrics.estimatedInputTokens>projected.inputBudget)throw engineError('原生上下文发送视图或预算不匹配。');
|
||||
||projected.inputBudget!==null&&projected.metrics.estimatedInputTokens>projected.inputBudget)throw engineError('原生上下文发送视图或预算不匹配。');
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { unrestricted, ceiling } from './execution-policy.mjs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { workerPath, workerPathKey } from './workers.mjs';
|
||||
|
||||
@@ -25,7 +26,7 @@ export function evaluationSourcePath(value) {
|
||||
}
|
||||
export function evaluationInput(input, config) {
|
||||
object(input, ['title', 'samples', 'budget', 'evidenceMode'], '评测');
|
||||
if (!Array.isArray(input.samples) || !input.samples.length || input.samples.length > 3) throw evaluationConflict('每批评测需要1到3个固定样本。');
|
||||
if (!Array.isArray(input.samples) || !input.samples.length || !unrestricted(config) && input.samples.length > 3) throw evaluationConflict('每批评测需要1到3个固定样本。');
|
||||
const count = input.samples.length;
|
||||
const samples = input.samples.map(item => {
|
||||
object(item, ['label', 'goal', 'criteria', 'paths', 'checks'], '样本');
|
||||
@@ -39,7 +40,7 @@ export function evaluationInput(input, config) {
|
||||
if (new Set(samples.map(item => item.label)).size !== count) throw evaluationConflict('样本名称不能重复。');
|
||||
const raw = input.budget ?? {}; object(raw, ['maxTokens', 'maxSteps', 'maxToolCalls', 'maxDurationMs'], '总预算');
|
||||
const maximumTokens = Math.min(config.maxTaskTokens ?? 1000000, (config.maxRunTokens ?? 200000) * count);
|
||||
const budget = {
|
||||
const budget = unrestricted(config) ? { maxTokens: 0, maxSteps: 0, maxToolCalls: 0, maxDurationMs: 0 } : {
|
||||
maxTokens: integer(raw.maxTokens, maximumTokens, count * 2000, maximumTokens, '总token预算'),
|
||||
maxSteps: integer(raw.maxSteps, Math.min(200, (config.maxSteps ?? 12) * count), count * 2, 200, '总请求步数'),
|
||||
maxToolCalls: integer(raw.maxToolCalls, Math.min(512, count * 64), count * 2, 512, '总工具次数'),
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// This is product behavior, never an authorization mechanism for the host OS.
|
||||
// Old Run snapshots without this field keep their original execution contract.
|
||||
export const unrestricted = value => (value?.config ?? value)?.executionMode === 'unrestricted';
|
||||
export const ceiling = (value, restrictedMaximum) => unrestricted(value) ? Infinity : restrictedMaximum;
|
||||
|
||||
export const approvalModes = ['ask', 'auto', 'full'];
|
||||
export const approvalLabels = { ask: '请求批准', auto: '帮我批准', full: '完全访问权限' };
|
||||
export function automaticApproval(config, action = {}) {
|
||||
const mode = config.approvalMode ?? 'ask';
|
||||
if (mode === 'full') return { approve: true, mode, source: 'full-access-policy' };
|
||||
if (mode !== 'auto') return { approve: false, mode, source: 'user-approval' };
|
||||
const command = String(action.command ?? '').trim();
|
||||
const highImpact = /(?:\b(?:rm|rmdir|del|erase|format|diskpart|shutdown|reboot|reg|runas|curl|wget|ssh|scp|sudo)\b|Remove-Item|Remove-\w+|Stop-Process|Start-Process|Invoke-WebRequest|Invoke-RestMethod|Invoke-Expression|Set-ExecutionPolicy|git\s+(?:push|reset|clean)|(?:npm|pnpm|yarn|pip)\s+(?:install|add|ci)|[;&|<>`]|\$\()/i.test(command);
|
||||
const routine = action.checkPlanId || action.browserPlanId || action.browsingInput?.action === 'observe'
|
||||
|| /^(?:(?:npm|pnpm|yarn)\s+(?:test|run\s+(?:test|check|lint|typecheck|build))\b|(?:node|python|python3)\s+(?:--test|-m\s+(?:pytest|unittest|compileall))\b|git\s+(?:status|diff|log|show)\b|Get-(?:ChildItem|Content|Item|Location)\b|(?:ls|pwd|cat|rg)\b)/i.test(command);
|
||||
return { approve: !highImpact && !!routine, mode, source: !highImpact && routine ? 'automatic-policy' : 'user-approval' };
|
||||
}
|
||||
|
||||
export function openToolDefinitions(tools, config) {
|
||||
if (!unrestricted(config)) return tools.filter(tool => !['rollback_change', 'open_browser_tab'].includes(tool.function.name));
|
||||
const open = value => Array.isArray(value) ? value.map(open) : value && typeof value === 'object'
|
||||
? Object.fromEntries(Object.entries(value).filter(([key]) => !['maxLength', 'maxItems', 'maximum'].includes(key)).map(([key, item]) => [key, open(item)])) : value;
|
||||
return tools.map(tool => ({ ...tool, function: { ...tool.function, parameters: open(tool.function.parameters),
|
||||
description: ({ run_command: '执行用户任务需要的终端命令。当前操作权限:' + approvalLabels[config.approvalMode ?? 'ask'] + ';完全访问直接执行,其他模式由工作台按权限处理批准。不设本地时长或输出额度,保存实际退出码与完整日志。',
|
||||
propose_file: '写入完整UTF-8文本文件。开放模式自动应用并保存原字节、SHA及改动记录;有原SHA时核对当前文件。',
|
||||
propose_patch: '按原文件SHA和唯一文本锚点替换。开放模式自动应用并保存实际差异。',
|
||||
read_file: '读取项目UTF-8文件及SHA。不设默认行数或字符上限,可主动用行范围或offset/limit分页。',
|
||||
read_artifact: '读取本次会话实际工件及SHA。不设默认字符上限,可主动用offset/limit分页。',
|
||||
prepare_change_set: '将待应用提案封存并自动应用,返回真实逐文件状态;已经应用的提案返回原状态。',
|
||||
plan_delivery: '为当前任务创建本地Git交付计划;开放模式自动执行所创建的提交计划并保存实际结果。',
|
||||
plan_checks: '为当前任务准备实际工程检查计划,保留检查目标、解释器和源码身份;准备计划不代表已经通过。',
|
||||
run_checks: '执行所属检查计划,按当前操作权限处理批准,保存真实退出码、测试数量和完整日志。',
|
||||
prepare_environment: '执行所属依赖准备计划,按当前操作权限处理批准,保留原始结果;安装不代表测试通过。',
|
||||
run_browser: '执行所属浏览器检查计划,按当前操作权限处理批准,保留真实DOM、断言结果及截图。',
|
||||
act_browser_tab: '使用原页面观察的修订和控件编号交互;按当前操作权限处理批准,保留实际页面和操作回执。',
|
||||
observe_browser_tab: '观察当前任务所属桌面浏览标签页,返回原DOM、控件编号和截图;不设本地文本与控件数量额度。',
|
||||
propose_file_chunk: '分段组装文本文件,按draft_id、next_offset和draft_sha256续写,complete=true时完整提案自动应用。',
|
||||
list_files: '列出项目中请求范围的实际文件路径;不设默认数量上限,可用path和depth选择范围。',
|
||||
search_files: '在项目文本文件中按字面内容搜索,不设默认文件或匹配数量上限。',
|
||||
})[tool.function.name] ?? tool.function.description } }));
|
||||
}
|
||||
|
||||
export function executionMode(value = 'unrestricted') {
|
||||
if (!['unrestricted', 'restricted'].includes(value)) throw Object.assign(new Error('执行方式需要选择完全开放或手动限制。'), { status: 400 });
|
||||
return value;
|
||||
}
|
||||
|
||||
export const openDefaults = Object.freeze({ executionMode: 'unrestricted', capacityMode: 'passthrough', historyPolicy: 'preserve',
|
||||
maxSteps: 0, maxRunDurationMs: 0, maxRunTokens: 0, maxTaskTokens: 0, modelResponseTimeoutMs: 0, modelStreamIdleTimeoutMs: 0 });
|
||||
@@ -1,3 +1,4 @@
|
||||
import { unrestricted, ceiling } from './execution-policy.mjs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { taskContract } from './task-control.mjs';
|
||||
import { modelWaitSettings } from '../../core/models/request-deadline.mjs';
|
||||
@@ -19,6 +20,8 @@ export function modelSnapshot(config) {
|
||||
return {
|
||||
mode: config.mode, baseUrl: config.baseUrl, model: config.model,
|
||||
contextLimit: config.contextLimit, maxOutputTokens: config.maxOutputTokens,
|
||||
...(config.executionMode ? { executionMode: config.executionMode } : {}),
|
||||
...(config.approvalMode ? { approvalMode: config.approvalMode } : {}),
|
||||
...(config.capacityMode ? { capacityMode: config.capacityMode } : {}),
|
||||
...(config.historyPolicy ? { historyPolicy: config.historyPolicy } : {}),
|
||||
configRevision: config.configRevision ?? 1,
|
||||
@@ -35,10 +38,10 @@ export function modelSnapshot(config) {
|
||||
|
||||
export function executionBudget(config) {
|
||||
return {
|
||||
maxSteps: config.maxSteps ?? 12,
|
||||
maxDurationMs: config.maxRunDurationMs ?? 600000,
|
||||
maxTokens: config.maxRunTokens ?? 200000,
|
||||
maxTaskTokens: config.maxTaskTokens ?? 1000000,
|
||||
maxSteps: config.maxSteps ?? 0,
|
||||
maxDurationMs: config.maxRunDurationMs ?? 0,
|
||||
maxTokens: config.maxRunTokens ?? 0,
|
||||
maxTaskTokens: config.maxTaskTokens ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
import { isId } from './execution.mjs';
|
||||
import { ceiling } from './execution-policy.mjs';
|
||||
import { isContinuation, taskContract } from './task-control.mjs';
|
||||
import { planHash, planError, taskRequirements } from './task-plans.mjs';
|
||||
export { requestedFilePaths, changeRequirement } from './file-intent.mjs';
|
||||
|
||||
export function fileResultInput(input, { source = 'agent' } = {}) {
|
||||
export function fileResultInput(input, { source = 'agent', config = {} } = {}) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['files', 'reason'].includes(key))
|
||||
|| typeof input.reason !== 'string' || !input.reason.trim() || input.reason.length > 600 || input.reason.includes('\0')
|
||||
|| !Array.isArray(input.files) || !input.files.length || input.files.length > 8) throw planError('成果核对需要1–8个文件和采用原因(最多600字)。', 'input', 400);
|
||||
|| typeof input.reason !== 'string' || !input.reason.trim() || input.reason.length > ceiling(config, 600) || input.reason.includes('\0')
|
||||
|| !Array.isArray(input.files) || !input.files.length || input.files.length > ceiling(config, 8)) throw planError('成果核对需要文件和采用原因。', 'input', 400);
|
||||
const files = input.files.map(file => {
|
||||
if (!file || typeof file !== 'object' || Object.keys(file).some(key => !['path', 'sha256', 'read_call_ids', 'source_result_id'].includes(key))
|
||||
|| typeof file.path !== 'string' || !file.path || file.path.length > 240 || /[\\:\0]/.test(file.path) || file.path.startsWith('/')
|
||||
|| typeof file.path !== 'string' || !file.path || file.path.length > ceiling(config, 240) || /[\\:\0]/.test(file.path) || file.path.startsWith('/')
|
||||
|| file.path.split('/').some(part => !part || part === '.' || part === '..') || !/^[a-f0-9]{64}$/.test(file.sha256)
|
||||
|| file.source_result_id !== undefined && !isId(file.source_result_id)) throw planError('需要项目内文件路径、当前SHA256和有效来源ID。', 'input', 400);
|
||||
const calls = file.read_call_ids ?? [];
|
||||
if (!Array.isArray(calls) || calls.length > 128 || calls.some(id => typeof id !== 'string' || !id || id.length > 160) || new Set(calls).size !== calls.length
|
||||
if (!Array.isArray(calls) || calls.length > ceiling(config, 128) || calls.some(id => typeof id !== 'string' || !id || id.length > ceiling(config, 160)) || new Set(calls).size !== calls.length
|
||||
|| source === 'agent' && !calls.length || source === 'user' && calls.length) throw planError('模型需引用本Task实际read_file调用;用户核对由宿主直接读取。', 'input', 400);
|
||||
return { path: file.path, sha256: file.sha256, read_call_ids: calls, ...(file.source_result_id ? { source_result_id: file.source_result_id } : {}) };
|
||||
});
|
||||
|
||||
@@ -11,13 +11,17 @@ export function capacitySettings(input = {}, previous = DEFAULT_MODEL_CAPACITY)
|
||||
}));
|
||||
}
|
||||
|
||||
export const isPassthrough = config => config.capacityMode === 'passthrough';
|
||||
|
||||
export function capacityMode(value = 'manual') {
|
||||
if (!['model', 'manual'].includes(value)) throw Object.assign(new Error('请选择按模型容量或手动限制。'), { status: 400 });
|
||||
if (!['passthrough', 'model', 'manual'].includes(value)) throw Object.assign(new Error('请选择默认透传、按模型容量或手动限制。'), { status: 400 });
|
||||
return value;
|
||||
}
|
||||
|
||||
export function routedCapacity(config, members) {
|
||||
const mode = capacityMode(config.capacityMode);
|
||||
// Connection capacity declarations remain metadata in passthrough mode.
|
||||
if (mode === 'passthrough') return { contextLimit: config.contextLimit, maxOutputTokens: config.maxOutputTokens };
|
||||
return Object.fromEntries(Object.keys(DEFAULT_MODEL_CAPACITY).map(key => [key,
|
||||
mode === 'model' && key === 'maxOutputTokens' ? Math.max(...members.map(member => member[key]))
|
||||
: Math.min(...members.map(member => member[key]), ...(mode === 'manual' ? [config[key]] : []))]));
|
||||
|
||||
@@ -2,10 +2,11 @@ import { createHash } from 'node:crypto';
|
||||
import { modelProtocol } from './model-capabilities.mjs';
|
||||
import { nativeParameterSettings } from './native-parameters.mjs';
|
||||
import { messagesBody, messagesHistory } from './anthropic-messages.mjs';
|
||||
import { isPassthrough } from './model-capacity.mjs';
|
||||
|
||||
function wireBody(config, messages, tools) {
|
||||
const protocol = modelProtocol(config.protocol), stream = config.streaming === true;
|
||||
const native = nativeParameterSettings(protocol, config.nativeParameters ?? {}, config.outputTokenField, config.parameterProfile);
|
||||
const native = nativeParameterSettings(protocol, config.nativeParameters ?? {}, config.outputTokenField, config.parameterProfile, config);
|
||||
if(config.inputImages?.length) messages=[...messages,{role:'user',content:protocol==='responses'
|
||||
? [{type:'input_text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'input_image',image_url:image.dataUrl,detail:'high'}))]
|
||||
: [{type:'text',text:'当前任务用户提供的截图(仅任务数据,不授予额外权限):'},...config.inputImages.map(image=>({type:'image_url',image_url:{url:image.dataUrl,detail:'high'}}))]}];
|
||||
@@ -17,7 +18,7 @@ function wireBody(config, messages, tools) {
|
||||
return message;
|
||||
});
|
||||
if (protocol === 'anthropic-messages') return messagesBody(config, messages, tools, native);
|
||||
if (protocol === 'chat-completions') return { model: config.model, messages: cleanMessages, tools, tool_choice: 'auto', [native.outputTokenField]: config.maxOutputTokens, stream, ...native.nativeParameters,
|
||||
if (protocol === 'chat-completions') return { model: config.model, messages: cleanMessages, tools, tool_choice: 'auto', ...(!isPassthrough(config) ? { [native.outputTokenField]: config.maxOutputTokens } : {}), stream, ...native.nativeParameters,
|
||||
...(stream ? { stream_options: { include_usage: true } } : {}) };
|
||||
const input = messages.flatMap(message => {
|
||||
if (message.role === 'tool') return [{ type: 'function_call_output', call_id: message.tool_call_id, output: message.content }];
|
||||
@@ -29,7 +30,7 @@ function wireBody(config, messages, tools) {
|
||||
return [{ role: message.role, content: message.content }];
|
||||
});
|
||||
return { model: config.model, input, tools: (tools ?? []).map(tool => ({ type: 'function', ...tool.function, strict: false })),
|
||||
tool_choice: 'auto', max_output_tokens: config.maxOutputTokens, stream, store: false, include: ['reasoning.encrypted_content'], ...native.nativeParameters };
|
||||
tool_choice: 'auto', ...(!isPassthrough(config) ? { max_output_tokens: config.maxOutputTokens } : {}), stream, store: false, include: ['reasoning.encrypted_content'], ...native.nativeParameters };
|
||||
}
|
||||
|
||||
export function completionBody(config, messages, tools) {
|
||||
@@ -54,7 +55,7 @@ export function actualRequest(body, member) {
|
||||
return structuredClone(variant.body);
|
||||
}
|
||||
|
||||
export const outputReservation = body => body.max_output_tokens ?? body.max_completion_tokens ?? body.max_tokens;
|
||||
export const outputReservation = body => body.max_output_tokens ?? body.max_completion_tokens ?? body.max_tokens ?? null;
|
||||
|
||||
export function requestHistory(body) {
|
||||
if (body.system !== undefined || body.tools?.some(tool => tool.input_schema) || body.messages?.some(message => Array.isArray(message.content) && message.content.some(part => ['tool_use', 'tool_result', 'thinking', 'image'].includes(part.type)))) return messagesHistory(body);
|
||||
@@ -96,7 +97,7 @@ export function imageTokenReserve(body){
|
||||
const bytes=Buffer.from(url.slice(22,70),'base64');
|
||||
if(bytes.length<24||!bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))||bytes.readUInt32BE(8)!==13||bytes.toString('ascii',12,16)!=='IHDR')throw new Error('视觉请求图像头不完整或类型不符。');
|
||||
const width=bytes.readUInt32BE(16),height=bytes.readUInt32BE(20);
|
||||
if(!width||!height||Math.max(width,height)>1024)throw new Error('视觉请求超过已校验副本范围。');
|
||||
if(!width||!height)throw new Error('视觉请求超过已校验副本范围。');
|
||||
return total+Math.max(4096,Math.ceil(width/32)*Math.ceil(height/32)*4);
|
||||
},0)));
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@ const bounded=value=>Math.min(Number.MAX_SAFE_INTEGER,Math.max(0,Math.ceil(value
|
||||
const endpoint=value=>String(value??'').replace(/\/+$/,'');
|
||||
export function localModelEstimate(body){
|
||||
const metrics=requestMetrics(body);
|
||||
return {schemaVersion:1,inputTokens:metrics.estimatedInputTokens,outputTokens:outputReservation(body),
|
||||
const output = outputReservation(body);
|
||||
return {schemaVersion:1,inputTokens:metrics.estimatedInputTokens,outputTokens:output ?? 0,...(output === null ? { outputLimitKnown: false } : {}),
|
||||
requestSha256:metrics.sha256,requestBytes:metrics.bytes,estimateMethod:metrics.estimateMethod};
|
||||
}
|
||||
export function taskConsumption(store,taskId){
|
||||
@@ -82,7 +83,7 @@ function reservationRoutes(config,body,receipts,overheadTokens,method){
|
||||
const all=routeSources(member,receipts),outlier=method!=='observed-route-max-v1'?isolatedOutlier(all):null;
|
||||
const sources=outlier?all.filter((_,index)=>index!==outlier.index):all;
|
||||
const route={connectionId:member.id??null,model:member.model,protocol:member.protocol??'chat-completions',endpoint:member.baseUrl,
|
||||
localInputTokens:local.inputTokens,outputReservation:local.outputTokens,...calibrate(local,sources,overheadTokens,method===RESERVATION_METHOD?all:sources),sources};
|
||||
localInputTokens:local.inputTokens,outputReservation:local.outputTokens,...(local.outputLimitKnown === false ? { outputLimitKnown: false } : {}),...calibrate(local,sources,overheadTokens,method===RESERVATION_METHOD?all:sources),sources};
|
||||
if(method!=='observed-route-max-v1')route.excludedSources=outlier?[{...all[outlier.index],sourceIndex:outlier.index,reason:'isolated_input_ratio_outlier',
|
||||
inputRatio:outlier.ratio,nextHighestRatio:outlier.nextRatio,factor:ISOLATED_OUTLIER_FACTOR}]:[];
|
||||
return route;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export function nativeParameterSettings(protocol?: string, parameters?: Record<string, unknown>, outputTokenField?: string, parameterProfile?: string): {
|
||||
export function nativeParameterSettings(protocol?: string, parameters?: Record<string, unknown>, outputTokenField?: string, parameterProfile?: string, config?: { executionMode?: string }): {
|
||||
nativeParameters: Record<string, unknown>;
|
||||
outputTokenField: string;
|
||||
parameterProfile?: string;
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import { unrestricted } from './execution-policy.mjs';
|
||||
const fail = message => { throw Object.assign(new Error(message), { status: 400 }); };
|
||||
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
||||
import { reasoningEfforts as efforts, messagesEfforts, parameterProfileSettings } from './model-parameter-profiles.mjs';
|
||||
const verbosity = ['low', 'medium', 'high'];
|
||||
|
||||
export function nativeParameterSettings(protocol = 'chat-completions', parameters = {}, outputTokenField, parameterProfile) {
|
||||
if (!object(parameters) || JSON.stringify(parameters).length > 8192) fail('原生参数必须是8KB以内的JSON对象。');
|
||||
export function nativeParameterSettings(protocol = 'chat-completions', parameters = {}, outputTokenField, parameterProfile, config = {}) {
|
||||
if (!object(parameters) || !unrestricted(config) && JSON.stringify(parameters).length > 8192) fail('原生参数必须是8KB以内的JSON对象。');
|
||||
if (unrestricted(config)) {
|
||||
const managed = ['model', 'messages', 'input', 'system', 'tools', 'tool_choice', 'stream', 'apiKey', 'api_key', 'baseUrl', 'authorization', 'headers'];
|
||||
if (Object.keys(parameters).some(key => managed.includes(key))) fail('原生参数不能替换实际模型、消息、工具、传输或凭据字段。');
|
||||
return { nativeParameters: structuredClone(parameters), outputTokenField: outputTokenField ?? (protocol === 'responses' ? 'max_output_tokens' : 'max_tokens'),
|
||||
...(parameterProfile !== undefined ? { parameterProfile: parameterProfileSettings(protocol, parameterProfile) } : {}) };
|
||||
}
|
||||
const allowed = protocol === 'anthropic-messages' ? ['temperature', 'top_p', 'top_k', 'stop_sequences', 'thinking', 'output_config'] : protocol === 'responses' ? ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning', 'text']
|
||||
: ['temperature', 'top_p', 'parallel_tool_calls', 'reasoning_effort', 'verbosity', 'seed', 'thinking'];
|
||||
for (const [key, value] of Object.entries(parameters)) {
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { ceiling } from './execution-policy.mjs';
|
||||
|
||||
export const MAXIMUM_RESEARCH_BYTES = 512 * 1024 * 1024;
|
||||
export const RESEARCH_ACTIVE = new Set(['queued', 'connecting', 'analyzing', 'stopping']);
|
||||
export const researchError = (message, status = 409) => Object.assign(new Error(message), { status });
|
||||
export async function researchFileIdentity(filename, { signal } = {}) {
|
||||
if (typeof filename !== 'string' || !filename.trim() || filename.length > 3000 || filename.includes('\0')) throw researchError('需要一个本地工件的完整路径。', 400);
|
||||
export async function researchFileIdentity(filename, { signal, config = {} } = {}) {
|
||||
if (typeof filename !== 'string' || !filename.trim() || filename.length > ceiling(config, 3000) || filename.includes('\0')) throw researchError('需要一个本地工件的完整路径。', 400);
|
||||
const input = filename.trim().replace(/^"(.*)"$/, '$1');
|
||||
if (!path.isAbsolute(input)) throw researchError('研究工件路径需要是绝对路径。', 400);
|
||||
const initial = await fs.promises.lstat(input);
|
||||
if (!initial.isFile() || initial.isSymbolicLink()) throw researchError('首批研究入口支持常规ASAR、EXE和DLL文件。', 400);
|
||||
const resolved = await fs.promises.realpath(input), before = await fs.promises.stat(resolved);
|
||||
if (!['.asar', '.exe', '.dll'].includes(path.extname(resolved).toLowerCase())) throw researchError('当前入口支持ASAR、EXE和DLL工件。', 400);
|
||||
if (before.size > MAXIMUM_RESEARCH_BYTES) throw researchError('工件超过当前512MiB登记上限。', 400);
|
||||
if (before.size > ceiling(config, MAXIMUM_RESEARCH_BYTES)) throw researchError('工件超过当前512MiB登记上限。', 400);
|
||||
const hash = createHash('sha256'); let bytes = 0;
|
||||
for await (const chunk of fs.createReadStream(resolved, { signal })) { bytes += chunk.length; if (bytes > MAXIMUM_RESEARCH_BYTES) throw researchError('工件读取期间超过登记上限。'); hash.update(chunk); }
|
||||
for await (const chunk of fs.createReadStream(resolved, { signal })) { bytes += chunk.length; if (bytes > ceiling(config, MAXIMUM_RESEARCH_BYTES)) throw researchError('工件读取期间超过登记上限。'); hash.update(chunk); }
|
||||
const after = await fs.promises.stat(resolved);
|
||||
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino || bytes !== before.size) throw researchError('工件在登记期间变化,需要按新版本重新登记。');
|
||||
return { path: resolved, sha256: hash.digest('hex'), bytes, modifiedAt: after.mtime.toISOString(), extension: path.extname(resolved).toLowerCase() };
|
||||
@@ -40,8 +41,8 @@ export const researchTargetContract = target => ({ schemaVersion: 1, id: target.
|
||||
projectId: target.projectId, taskId: target.taskId, runId: target.runId, path: target.path, sha256: target.sha256,
|
||||
bytes: target.bytes, extension: target.extension, label: target.label, source: target.source, registeredAt: target.registeredAt });
|
||||
|
||||
export function researchPointer(value, pointer = '/normalized_result') {
|
||||
if (typeof pointer !== 'string' || pointer.length > 400 || !pointer.startsWith('/') || pointer.split('/').length > 12) throw researchError('Evidence字段需要有效JSON Pointer,最多10层。', 400);
|
||||
export function researchPointer(value, pointer = '/normalized_result', config = {}) {
|
||||
if (typeof pointer !== 'string' || pointer.length > ceiling(config, 400) || !pointer.startsWith('/') || pointer.split('/').length > ceiling(config, 12)) throw researchError('Evidence字段需要有效JSON Pointer。', 400);
|
||||
for (const raw of pointer.slice(1).split('/')) {
|
||||
if (/~(?:[^01]|$)/.test(raw)) throw researchError('Evidence字段转义无效。', 400);
|
||||
const key = raw.replace(/~1/g, '/').replace(/~0/g, '~');
|
||||
@@ -53,7 +54,7 @@ export function researchPointer(value, pointer = '/normalized_result') {
|
||||
|
||||
export function sealResearchDocument(store, session, run, text, kind) {
|
||||
const bytes = Buffer.byteLength(text, 'utf8');
|
||||
if (bytes > 64 * 1024 * 1024) throw researchError('完整研究证据超过当前64MiB接收范围。');
|
||||
if (bytes > ceiling(store, 64 * 1024 * 1024)) throw researchError('完整研究证据超过当前64MiB接收范围。');
|
||||
const parts = [];
|
||||
for (let start = 0; start < text.length;) {
|
||||
let end = Math.min(text.length, start + 500000);
|
||||
@@ -71,8 +72,8 @@ export function readResearchDocument(store, session, reference) {
|
||||
const artifact = store.owned('artifact', reference.id, session.id);
|
||||
if (artifact.sha256 !== reference.sha256) throw researchError('研究证据清单与封存引用不匹配。');
|
||||
const manifest = JSON.parse(store.artifactStore.read(artifact));
|
||||
if (manifest.kind !== 'research-document' || manifest.schemaVersion !== 1 || !Array.isArray(manifest.parts) || manifest.parts.length > 160
|
||||
|| manifest.bytes > 64 * 1024 * 1024 || manifest.bytes !== reference.bytes || manifest.sha256 !== reference.documentSha256) throw researchError('研究证据清单无效。');
|
||||
if (manifest.kind !== 'research-document' || manifest.schemaVersion !== 1 || !Array.isArray(manifest.parts) || manifest.parts.length > ceiling(store, 160)
|
||||
|| manifest.bytes > ceiling(store, 64 * 1024 * 1024) || manifest.bytes !== reference.bytes || manifest.sha256 !== reference.documentSha256) throw researchError('研究证据清单无效。');
|
||||
const parts = manifest.parts.map(part => {
|
||||
const source = store.owned('artifact', part.id, session.id);
|
||||
if (source.taskId !== artifact.taskId || source.runId !== artifact.runId || source.sha256 !== part.sha256 || source.bytes !== part.bytes) throw researchError('研究证据分片的来源不匹配。');
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { unrestricted, ceiling } from './execution-policy.mjs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { isId } from './execution.mjs';
|
||||
|
||||
@@ -11,34 +12,34 @@ const text = (value, max, label) => {
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > max || /\0/.test(value)) throw planError(label + '需要1–' + max + '字文本。', 'input', 400);
|
||||
return value.trim();
|
||||
};
|
||||
const unique = (values, label, max = 32) => {
|
||||
if (!Array.isArray(values) || values.length > max || values.some(value => typeof value !== 'string' || !value || value.length > 160)
|
||||
const unique = (values, label, max = 32, config = {}) => {
|
||||
if (!Array.isArray(values) || values.length > max || values.some(value => typeof value !== 'string' || !value || value.length > ceiling(config, 160))
|
||||
|| new Set(values).size !== values.length) throw planError(label + '需要不重复的文本列表。', 'input', 400);
|
||||
return [...values];
|
||||
};
|
||||
|
||||
export function taskPlanInput(input) {
|
||||
export function taskPlanInput(input, config = {}) {
|
||||
if (!object(input) || Object.keys(input).some(key => !['expected_revision', 'steps'].includes(key))
|
||||
|| !Number.isSafeInteger(input.expected_revision) || input.expected_revision < 0) throw planError('任务计划需要expected_revision和steps,不能添加执行命令或完成状态。', 'input', 400);
|
||||
if (!Array.isArray(input.steps) || !input.steps.length || input.steps.length > TASK_PLAN_LIMITS.steps) throw planError('任务计划需要1–12个步骤。', 'input', 400);
|
||||
if (!Array.isArray(input.steps) || !input.steps.length || input.steps.length > ceiling(config, TASK_PLAN_LIMITS.steps)) throw planError('任务计划需要1–12个步骤。', 'input', 400);
|
||||
const steps = input.steps.map(value => {
|
||||
if (!object(value) || Object.keys(value).some(key => !['key', 'title', 'criterion', 'kind', 'depends_on', 'tools', 'paths', 'checks', 'viewport_width', 'actions'].includes(key))
|
||||
|| typeof value.key !== 'string' || !keyPattern.test(value.key) || !['analysis', 'changes', 'results', 'checks', 'browser'].includes(value.kind)) throw planError('步骤需要key、title、criterion和有效证据类别。', 'input', 400);
|
||||
const step = { key: value.key, title: text(value.title, 100, '步骤标题'), criterion: text(value.criterion, 300, '通过条件'), kind: value.kind,
|
||||
depends_on: unique(value.depends_on ?? [], '前置依赖', TASK_PLAN_LIMITS.steps).sort() };
|
||||
const step = { key: value.key, title: text(value.title, ceiling(config, 100), '步骤标题'), criterion: text(value.criterion, ceiling(config, 300), '通过条件'), kind: value.kind,
|
||||
depends_on: unique(value.depends_on ?? [], '前置依赖', ceiling(config, TASK_PLAN_LIMITS.steps), config).sort() };
|
||||
const allowed = value.kind === 'analysis' ? ['tools'] : ['changes', 'results'].includes(value.kind) ? ['paths'] : value.kind === 'checks' ? ['checks'] : ['viewport_width', 'actions'];
|
||||
if (['tools', 'paths', 'checks', 'viewport_width', 'actions'].some(key => value[key] !== undefined && !allowed.includes(key))) throw planError('步骤证据字段与类别不一致。', 'input', 400);
|
||||
if (value.kind === 'analysis') {
|
||||
step.tools = unique(value.tools, '读取工具', PLAN_READ_TOOLS.length).sort();
|
||||
if (!step.tools.length || step.tools.some(tool => !PLAN_READ_TOOLS.includes(tool))) throw planError('工程读取只能引用已声明的实际只读工具。', 'input', 400);
|
||||
} else if (['changes', 'results'].includes(value.kind)) {
|
||||
step.paths = unique(value.paths, '文件范围').sort();
|
||||
step.paths = unique(value.paths, '文件范围', ceiling(config, 32), config).sort();
|
||||
if (!step.paths.length || step.paths.some(file => /[\\:\0]/.test(file) || file.startsWith('/') || file.split('/').some(part => !part || part === '..' || ['.git', '.hg', '.svn'].includes(part)))) throw planError('源码步骤需要项目内常规相对文件路径。', 'input', 400);
|
||||
} else if (value.kind === 'checks') {
|
||||
step.checks = unique(value.checks, '检查名称', 6).sort();
|
||||
step.checks = unique(value.checks, '检查名称', ceiling(config, 6), config).sort();
|
||||
if (!step.checks.length) throw planError('检查步骤必须固定至少一个实际检查名称。', 'input', 400);
|
||||
} else {
|
||||
if (!Number.isSafeInteger(value.viewport_width) || value.viewport_width < 320 || value.viewport_width > 1440) throw planError('页面步骤需要320–1440像素的固定视口宽度。', 'input', 400);
|
||||
if (!Number.isSafeInteger(value.viewport_width) || value.viewport_width < (unrestricted(config) ? 1 : 320) || value.viewport_width > ceiling(config, 1440)) throw planError('页面步骤需要320–1440像素的固定视口宽度。', 'input', 400);
|
||||
step.viewport_width = value.viewport_width; step.actions = unique(value.actions ?? [], '页面必要操作', 6).sort();
|
||||
if (step.actions.some(action => !['fill', 'select', 'click', 'assert_text', 'assert_count', 'assert_visible'].includes(action))) throw planError('页面必要操作无效。', 'input', 400);
|
||||
}
|
||||
@@ -51,7 +52,7 @@ export function taskPlanInput(input) {
|
||||
const walk = key => { if (visiting.has(key)) throw planError('任务步骤依赖不能形成循环。', 'input', 400);
|
||||
if (done.has(key)) return; visiting.add(key); for (const dependency of steps.find(step => step.key === key).depends_on) walk(dependency); visiting.delete(key); done.add(key); };
|
||||
for (const step of steps) walk(step.key);
|
||||
if (steps.reduce((sum, step) => sum + step.title.length + step.criterion.length, 0) > TASK_PLAN_LIMITS.text) throw planError('计划文本超过保留预算,请缩小单个任务范围。', 'input', 400);
|
||||
if (steps.reduce((sum, step) => sum + step.title.length + step.criterion.length, 0) > ceiling(config, TASK_PLAN_LIMITS.text)) throw planError('计划文本超过保留预算,请缩小单个任务范围。', 'input', 400);
|
||||
return { expected_revision: input.expected_revision, steps };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { unrestricted, ceiling } from './execution-policy.mjs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { isId, accountedTokens, emptyUsage } from './execution.mjs';
|
||||
import { selectedEngineInput } from './engine-execution.mjs';
|
||||
@@ -32,11 +33,11 @@ const text = (value, maximum, label) => {
|
||||
export function collaborationInput(input, config) {
|
||||
if (!input || Array.isArray(input) || Object.keys(input).some(key => !['goal', 'budget', 'children', 'engine'].includes(key))) throw workerConflict('协作只接受父目标、预算、子任务和已检测的引擎。');
|
||||
const engine = input.engine === undefined ? null : selectedEngineInput(input.engine);
|
||||
if (!Array.isArray(input.children) || input.children.length !== (engine ? 1 : 2)) throw workerConflict(engine ? '受控引擎计划需要一个所属子工程。' : '本阶段需要两个受限子任务。');
|
||||
if (!Array.isArray(input.children) || (unrestricted(config) ? input.children.length < 1 : input.children.length !== (engine ? 1 : 2))) throw workerConflict(engine ? '受控引擎计划需要一个所属子工程。' : '本阶段需要两个受限子任务。');
|
||||
const raw = input.budget ?? {};
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).some(key => !['maxTokens', 'maxSteps', 'maxToolCalls', 'maxDurationMs'].includes(key))) throw workerConflict('协作预算字段无效。');
|
||||
const tokenMaximum = Math.min(config.maxTaskTokens ?? 1000000, config.maxRunTokens ?? 200000);
|
||||
const budget = {
|
||||
const budget = unrestricted(config) ? { maxTokens: 0, maxSteps: 0, maxToolCalls: 0, maxDurationMs: 0 } : {
|
||||
maxTokens: bounded(raw.maxTokens, tokenMaximum, 1000, tokenMaximum, '总token预算'),
|
||||
maxSteps: bounded(raw.maxSteps, Math.min(200, (config.maxSteps ?? 12) * 2), 2, 200, '总请求步数'),
|
||||
maxToolCalls: bounded(raw.maxToolCalls, 96, 2, 512, '总工具次数'),
|
||||
@@ -44,17 +45,17 @@ export function collaborationInput(input, config) {
|
||||
};
|
||||
const children = input.children.map((item, index) => {
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item) || Object.keys(item).some(key => !['label', 'goal', 'paths', 'budget'].includes(key))) throw workerConflict('子任务字段无效。');
|
||||
if (!Array.isArray(item.paths) || !item.paths.length || item.paths.length > 16) throw workerConflict('每个子任务需要1到16个修改范围。');
|
||||
if (!Array.isArray(item.paths) || !item.paths.length || !unrestricted(config) && item.paths.length > 16) throw workerConflict('每个子任务需要1到16个修改范围。');
|
||||
const paths = item.paths.map(workerPath).sort();
|
||||
if (new Set(paths.map(workerPathKey)).size !== paths.length) throw workerConflict('子任务范围不能重复。');
|
||||
const part = item.budget ?? {};
|
||||
if (!part || Array.isArray(part) || Object.keys(part).some(key => !['maxTokens', 'maxSteps', 'maxToolCalls'].includes(key))) throw workerConflict('子预算字段无效。');
|
||||
const allocate = key => engine ? budget[key] : index === 0 ? Math.floor(budget[key] / 2) : budget[key] - Math.floor(budget[key] / 2);
|
||||
return { label: text(item.label, 64, '子任务名称'), goal: text(item.goal, 8000, '子目标'), paths,
|
||||
budget: Object.fromEntries(['maxTokens', 'maxSteps', 'maxToolCalls'].map(key => [key, bounded(part[key], allocate(key), key === 'maxTokens' ? 500 : 1, budget[key], key)])) };
|
||||
return { label: text(item.label, ceiling(config, 64), '子任务名称'), goal: text(item.goal, ceiling(config, 8000), '子目标'), paths,
|
||||
budget: Object.fromEntries(['maxTokens', 'maxSteps', 'maxToolCalls'].map(key => [key, unrestricted(config) ? 0 : bounded(part[key], allocate(key), key === 'maxTokens' ? 500 : 1, budget[key], key)])) };
|
||||
});
|
||||
for (const key of ['maxTokens', 'maxSteps', 'maxToolCalls']) if (children.reduce((sum, child) => sum + child.budget[key], 0) > budget[key]) throw workerConflict('子任务预算之和不能超过父预算:' + key);
|
||||
return { goal: text(input.goal, 20000, '父目标'), budget, children, ...(engine ? { engine } : {}) };
|
||||
return { goal: text(input.goal, ceiling(config, 20000), '父目标'), budget, children, ...(engine ? { engine } : {}) };
|
||||
}
|
||||
|
||||
export function collaborationSeal(group) {
|
||||
@@ -108,7 +109,7 @@ export function assertWorkerWriteScope(store, session, value, { readOnly = false
|
||||
export function assertWorkerTool(store, session, tool, args) {
|
||||
const worker = workerForSession(store, session);
|
||||
if (!worker) return;
|
||||
if (!WORKER_TOOLS.has(tool)) throw workerConflict('受限子任务不开放这个工具:' + tool);
|
||||
if (!unrestricted(store) && !WORKER_TOOLS.has(tool)) throw workerConflict('受限子任务不开放这个工具:' + tool);
|
||||
if (tool === 'propose_file' || tool === 'propose_patch' || tool === 'propose_file_chunk') assertWorkerWriteScope(store, session, args.path);
|
||||
}
|
||||
export function assertWorkersResolved(store, projectId, { recoveryTaskId = null } = {}) {
|
||||
|
||||
Reference in New Issue
Block a user