import {extensionAvailable} from '../extensions/availability.ts'; import {updateMaintenance} from '../../updates/maintenance.ts'; import {TeamMessages} from '../studio/messages.ts'; import {StrategicPlanning,STRATEGY_TOOLS,type StrategyRound} from '../strategic/service.ts'; import {specialistRoles,type SpecialistRole} from '../strategic/settings.ts'; import {finishStrategyDispatch} from '../strategic/scheduling.ts'; import {AdaptiveOrchestration,ADAPTIVE_TOOLS,ADAPTIVE_WORKER_GUIDANCE,ADAPTIVE_PLANNER_GUIDANCE} from './adaptive.ts'; import {ExperienceService,EXPERIENCE_TOOLS,EXPERIENCE_WORKER_GUIDANCE,EXPERIENCE_PLANNER_GUIDANCE} from './experience.ts'; import {executionConstraints,readTaskPolicy,taskPolicyFromRow} from './freescope.ts'; import {readEfficiencyOptions} from './efficiency-settings.ts'; import {taskActions} from './action-pause.ts'; import {workerCompletion,markWorkerBudgetBlocked} from './worker-completion.ts'; import {loginPlannerContext,loginPlannerDelivered,loginPausedTaskSQL} from '../android/login-state.ts'; import {controlPool,backgroundPool} from '../../db/pool.ts'; import {capabilityCompletionReady} from './completion-wait.ts'; import {recoverControl,recoverLoop,transientDatabaseError} from '../../db/recovery.ts'; import {KnowledgeInbox} from './knowledge-inbox.ts'; import {IDENTITY_TOOLS} from './identity.ts'; import {BROWSER_GUIDANCE} from '../browser/tools.ts'; import path from 'node:path'; import {ReverseRuntime} from '../reverse/runtime.ts'; import {TrafficFlow,TRAFFIC_GUIDANCE} from '../traffic/flow.ts'; import {CHECK_TOOLS,registerCheckTools} from '../traffic/check-tools.ts'; import {taskProgress} from './progress.ts'; import {runPlannerRound,compactPlannerContext,plannerRecoveryContext,plannerRecoveryPrompt,plannerRevisions,plannerMessages,plannerModelRevisionSQL,type PlannerOutcome,type PlannerPlan} from './planner-recovery.ts'; import {withPlannerRecovery} from '../llm/profile-wire.ts'; import {registerFindingReadTools} from '../findings/tools.ts'; import {checkpointTaskReport,withTaskReport,reportLeadSeconds} from './report.ts'; import {TaskSlots,DEFAULT_TASK_CONCURRENCY,taskConcurrencyLimit} from './slots.ts'; import {continuousGuidance,finishDiscoveryIfReady} from './continuous.ts'; import {reopenExploration,completeAchievedTask} from './completion.ts'; import {taskWorkDir,artifactSpec} from '../workspace/layout.ts'; import {augmentSession,bindAugmentation} from '../mcp/session.ts'; import type {McpService} from '../mcp/service.ts'; import type {SkillsService} from '../skills/service.ts'; /** Task host: Pi owns a single session; this host owns scheduling and cancellation. * Behavior: task supervision, planning, execution, pause and recovery. * Planner's temporary JSON protocol is tracked separately under G01/G02/G07. */ import type { Pool } from "pg"; import type { PihostConfig } from "../../config.ts"; import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; import { createHostedSession, getPiRuntime, type HostedSession } from "../../pi/session-host.ts"; import { claimNextIntent, retryIntent,releaseModelingIntent,recoverModelingIntents } from "./host.ts"; import {runTool,type ToolContext,type GateOptions} from "../tools/gate.ts"; import { registerBusinessTools } from "../tools/business.ts"; import { runJudge } from "../tools/judge.ts"; import {promptDefaults} from '../agents/service.ts'; import {goTrim} from '../assets/asset-match.ts'; import type { AgentsService } from "../agents/service.ts"; import type { AssetsService } from "../assets/service.ts"; import type { FindingsService } from "../findings/service.ts"; import type { InterceptService } from "../intercept/service.ts"; import { plannerInterval } from "./scheduler.ts"; import {ExplorationService} from '../exploration/service.ts'; import {registerGraphTools,GRAPH_TOOLS} from '../exploration/tools.ts'; import {assembleTools} from '../tools/assembly.ts'; import {registerAssetTools,ASSET_TOOLS} from '../assets/tools.ts'; import {POC_TOOLS,registerPocTools} from '../pocs/tools.ts'; import {POC_GUIDANCE} from '../pocs/service.ts'; import {pocNeedsReview,pocMayComplete,pocReviewed,pocDelivery} from '../pocs/lifecycle.ts'; import {FINGERPRINT_TOOLS} from '../fingerprints/tools.ts'; import {FINGERPRINT_GUIDANCE,type FingerprintChange} from '../fingerprints/service.ts'; import {bootstrapFingerprints} from '../fingerprints/orchestration.ts'; import {fingerprintMayComplete,fingerprintNeedsReview,recordFingerprintDelivery,acknowledgeFingerprintReview,relatedFingerprintURL} from '../fingerprints/lifecycle.ts'; import {registerWorkControls,WORK_CONTROLS} from './work-tools.ts'; import {registerTraceTools,TRACE_TOOLS} from '../activity/tools.ts'; import {TaskModelResolver} from '../llm/profile-runtime.ts'; import {EfficiencySupervisor,efficiencyDecision,type ProgressSample} from './efficiency.ts'; import {observeStallReview} from './stall-review.ts'; import {goalEfficiencyGuidance,plannerEfficiencyGuidance,plannerReverseGuidance} from './execution-guidance.ts'; import {WorkerHandoffs,HANDOFF_TOOLS} from './handoff.ts'; import {ReverseProxies} from '../reverse/proxy.ts'; import {registerReverseTools,REVERSE_PROXY_TOOLS,reverseWorkerGuidance} from '../reverse/tools.ts'; import {CodeIntelService} from '../codeintel/service.ts'; import {registerCodeIntelTools,CODE_INTEL_TOOLS} from '../codeintel/tools.ts'; import {HUNT_TOOLS} from '../hunting/tools.ts'; import {INTEL_TOOLS} from '../intel/tools.ts'; import {WINDOWS_TOOLS,WINDOWS_GUIDANCE,WINDOWS_PLANNER_GUIDANCE} from '../windows/tools.ts'; import {ANDROID_TOOLS,ANDROID_GUIDANCE,ANDROID_PLANNER_GUIDANCE} from '../android/tools.ts'; import {ModelingService} from '../modeling/service.ts'; import {MODELER_TOOLS,MODELING_REQUEST_TOOLS,MODELING_GUIDANCE,registerModelingTools} from '../modeling/tools.ts'; import {probeModelingEntrance,MODELING_EXECUTION_GUIDANCE,type ModelingEntrance} from '../modeling/execution.ts'; export interface EngineDeps { trafficFlow?:TrafficFlow; pocs?:import('../pocs/service.ts').PocService; hunting?:import('../hunting/service.ts').HuntingService; intel?:import('../intel/client.ts').IntelClient; windows?:import('../windows/service.ts').WindowsService; android?:import('../android/service.ts').AndroidService; fingerprints?:import('../fingerprints/service.ts').FingerprintService; /** Injectable target transport probe; production uses the ordinary tool gate. */ modelingProbe?:(target:string,signal:AbortSignal)=>Promise; agents: AgentsService; mcp?: McpService | null; skills?: SkillsService; assets: AssetsService; findings: FindingsService; intercept: InterceptService; settingsConsumers: { get(): { workers: number; taskConcurrencyEnabled: boolean; taskConcurrencyLimit: number; trafficCapture: boolean }; getRebuildCount(): number } | null; } interface RunContext { taskId: number; policyRevision:number; abort: AbortController; execution: AbortController; sessions: Set; generation: number; paused: boolean; pending: boolean; hintTriggers: string[][]; done: Promise; releaseSlot?:()=>void; lastDiscoveryReview?:number; } interface TaskSnapshot { network_mode?:'standard'|'jump'; execution_mode?:string; worker_limit?:number; queue_mode?:string; description?:string; id:number; kind?:string; goal: string; agent_key: string; deadline_at: Date | null; plan_heartbeat_seconds: number; active_llm_profile_id?: number | null; llm_profile_id?: number | null; } export class TaskEngine { private readonly runs = new Map(); private readonly modelingLeases=new Map(); private readonly backgroundInitializers=new Map>(); private readonly deleting = new Set(); private readonly workspaceCleaning=new Set(); private readonly operations=new Map>>(); private queuePump: Promise | null = null; private closing = false; /** 代码索引循环自成一体:只往探索图写事实,绝不参与任务收尾的等待。 */ private readonly intelLoops = new Set>(); private readonly intelDone = new Map>(); /** 每个任务一个取消源:暂停/停止/删除只影响它自己,不会连带别的任务。 */ private readonly intelTasks = new Map(); private readonly intelRevisions=new Map(); private readonly settling=new Map>(); private readonly finalRuns=new Map(); private readonly slotAbort=new AbortController(); private readonly settlementControllers=new Map(); readonly slots:TaskSlots; private admissionTail:Promise=Promise.resolve(); private readonly work=new Map(); readonly graph: ExplorationService; readonly adaptive:AdaptiveOrchestration; readonly experience:ExperienceService; readonly strategy:StrategicPlanning; readonly team:TeamMessages; readonly modeling: ModelingService; readonly efficiency:EfficiencySupervisor; readonly handoffs:WorkerHandoffs; readonly proxies:ReverseProxies; readonly codeIntel:CodeIntelService; readonly reverseRuntime:ReverseRuntime; browsers?: import("../browser/task-browser.ts").TaskBrowsers; constructor(private readonly pool: Pool, private readonly config: PihostConfig, private readonly deps: EngineDeps) { this.slots=new TaskSlots(()=>this.taskLimit(),()=>{setImmediate(()=>{void this.pumpQueue().catch(e=>console.error('[slots] queue',e));});}); if(deps.trafficFlow)registerCheckTools(deps.trafficFlow); this.efficiency=new EfficiencySupervisor(pool,config.efficiency); this.handoffs=new WorkerHandoffs(pool,config.dataDir,deps.fingerprints,deps.pocs);this.handoffs.register(); if(deps.pocs){registerPocTools(deps.pocs);deps.pocs.bindNotify(id=>this.notifyPocs(id));} this.modeling=new ModelingService(pool); this.modeling.bind(id=>{void this.launch(id).catch(e=>console.error('[modeling] launch',e));},id=>{void this.wakeModelConsumer(id);}); registerModelingTools(this.modeling); this.proxies=new ReverseProxies(pool,config.dataDir); registerBusinessTools({ trafficFlow:deps.trafficFlow, reverseProxies:this.proxies, assets: deps.assets, findings: deps.findings,modeling:this.modeling,fingerprints:deps.fingerprints }); registerAssetTools(pool); registerWorkControls(pool,this); registerTraceTools(pool); registerFindingReadTools(pool); deps.findings.setOnRecord((id)=>this.notify(id)); this.graph=new ExplorationService(pool,id=>this.notify(id),(id,texts)=>this.notifyHints(id,texts)); this.experience=new ExperienceService(pool); this.team=new TeamMessages(pool,(task,recipient,intent)=>{this.notify(task);if(recipient==='worker'&&intent&&this.work.has(intent))void this.team.inbox(task,'worker',intent).then(messages=>this.steerWork(task,intent,'团队新交接:'+JSON.stringify(messages))).catch(()=>{});}); this.strategy=new StrategicPlanning(pool); this.adaptive=new AdaptiveOrchestration(pool,id=>{this.notify(id);void this.stopInvalidatedWork(id).catch(error=>console.warn('[adaptive] stale worker cancellation',error));},async ctx=>{const work=this.work.get(ctx.intentId??0);if(!work||work.taskId!==ctx.taskId)throw Error('只能收口当前Worker意图');work.finishing=true;}); registerReverseTools(this.proxies,this.pool); this.codeIntel=new CodeIntelService(pool,config.dataDir,config.codeIntel); this.reverseRuntime=new ReverseRuntime(pool,this.codeIntel,config.codeIntel,path.join(config.dataDir,'reverse-events.jsonl')); // 取消回收不依赖任务是否还活着:结束/重启后仍要能把外部审计停掉 this.codeIntel.startCancelSweeper(); registerCodeIntelTools(this.codeIntel); registerGraphTools(pool,this.graph,id=>this.notify(id),async(id)=>{ if(this.isDeleting(id))throw new Error('任务正在删除'); await pool.query("UPDATE tasks SET status='running',paused=FALSE,completed_at=NULL WHERE id=$1 AND deleted_at IS NULL",[id]); await pool.query("UPDATE explorations SET status='open',updated_at=now() WHERE id=(SELECT exploration_id FROM tasks WHERE id=$1)",[id]); this.resume(id); },id=>{setImmediate(()=>this.abort(id));}); } private async stopInvalidatedWork(taskId:number):Promise{ const ids=[...this.work].filter(([,w])=>w.taskId===taskId).map(([id])=>id);if(!ids.length)return; const stale=await this.pool.query("SELECT n.id FROM exploration_nodes n WHERE n.id=ANY($1::bigint[]) AND (n.assessment_state<>'active' OR EXISTS(SELECT 1 FROM intent_dependencies d JOIN task_capabilities c ON c.id=d.capability_id WHERE d.intent_id=n.id AND (c.state<>'active' OR (d.capability_revision IS NOT NULL AND c.revision<>d.capability_revision))))",[ids]); for(const row of stale.rows)this.work.get(Number(row.id))?.abort.abort(); } isRunning(id: number): boolean { return this.runs.has(id); } private initializeBackgroundModeling(id:number){ if(this.backgroundInitializers.has(id))return; const release=this.beginTaskOperation(id);if(!release)return; const work=this.modeling.initializeTask(id).catch(async error=>{ await this.emit(id,'background_modeling_error',{error:String(error).slice(0,500)}); await this.pool.query(`INSERT INTO activity(exploration_id,worker,kind,summary) SELECT exploration_id,'system','text','业务建模暂不可用,测试继续执行' FROM tasks WHERE id=$1 AND deleted_at IS NULL`,[id]); }).finally(()=>{release();this.backgroundInitializers.delete(id);setImmediate(()=>void this.pumpQueue().catch(console.error));}); this.backgroundInitializers.set(id,work); } private async wakeModelConsumer(id:number):Promise{ try{ const task=(await controlPool(this.pool).query("SELECT status,paused,queued FROM tasks WHERE id=$1 AND deleted_at IS NULL",[id])).rows[0]; if(!task||task.paused||task.queued||!['created','running'].includes(task.status))return; if(this.runs.has(id)){ this.notify(id); const catalog=await this.modeling.catalog(id),revision=JSON.stringify(catalog); for(const work of this.work.values())if(work.taskId===id&&!work.abort.signal.aborted&&work.modelingRevision!==revision){ const update='[业务模型后台更新,补充线索;测试继续执行]\n'+revision; if(work.session)await work.session.session.steer(update);else work.steering.push(update);work.modelingRevision=revision; } }else await this.launch(id); }catch(e){console.error('[modeling] consumer wake',e);} } isDeleting(id: number): boolean { return this.deleting.has(id)||this.workspaceCleaning.has(id); } workspaceBusy(id:number):boolean {return this.codeIntel.busy(id)||this.closing||this.isDeleting(id)||this.runs.has(id)||this.settling.has(id)||this.finalRuns.has(id)||this.operations.has(id)||this.slots.ids.includes(id)||this.modelingLeases.has(id);} beginWorkspaceCleanup(id:number):(()=>void)|null { if(this.workspaceBusy(id))return null;this.workspaceCleaning.add(id); return ()=>this.workspaceCleaning.delete(id); } /** 批次 1b:旁路运行时注入(删除 drain、意图停止取消)。 */ attachSideRuntime(rt: { drainTask(taskId: number): Promise; cancelWorker(taskId: number, explorationId: number, intentId: number): void }): void { this.sideRuntime = rt; } private sideRuntime: { drainTask(taskId: number): Promise; cancelWorker(taskId: number, explorationId: number, intentId: number): void } | null = null; /** 意图停止/删除时取消其旁路运行(对照 cancelWorkerSide)。 */ cancelWorkerSide(taskId: number, explorationId: number, intentId: number): void { void this.deps.windows?.cancelTask(taskId,intentId,'intent_cancelled').catch(e=>console.error('[windows] intent cleanup',String(e))); void this.deps.android?.broker.cancelTask(taskId,intentId,'intent_cancelled').catch(e=>console.error('[android] intent cleanup',String(e))); this.sideRuntime?.cancelWorker(taskId, explorationId, intentId); } /** Admission is synchronous with deletion; release only after file writes end. */ beginTaskOperation(id:number):(()=>void)|null { if(this.closing||this.isDeleting(id))return null; let resolve!:()=>void;const done=new Promise(r=>resolve=r),set=this.operations.get(id)??new Set>();set.add(done);this.operations.set(id,set); let released=false;return ()=>{if(released)return;released=true;set.delete(done);if(!set.size)this.operations.delete(id);resolve();}; } private invalidate(run: RunContext): void { run.generation++; run.execution.abort(); for (const h of run.sessions) void h.session.abort().catch(() => {}); } /** 用户明确停止/删除:本任务的后台分析与已提交的外部审计一起停,并等它停稳。 */ /** 停掉本任务后台并等它交还文件。返回 false 表示时间到了还没退干净,调用方不能当作已退出。 */ private async stopBackground(id: number): Promise { this.intelRevisions.set(id,(this.intelRevisions.get(id)??0)+1); this.intelTasks.get(id)?.abort(); const loop = this.intelDone.get(id); let settled = !loop; if (loop) { settled = await Promise.race([ loop.then(() => true, () => true), new Promise(resolve => setTimeout(() => resolve(false), 15_000)), ]); } // 还挂着文件操作就再等一会儿(扫描/解包/打包) for (let i = 0; i < 40 && this.codeIntel.busy(id); i++) await new Promise(resolve => setTimeout(resolve, 250)); await this.codeIntel.stopTask(id).catch(() => {}); return settled && !this.codeIntel.busy(id); } /** 用户明确停止(运行控制里的 stop);正常完成走 abort,不会走到这里。 */ stop(id: number): void { void this.stopBackground(id); this.abort(id); } abort(id: number): void { taskActions(this.pool).release(id); void this.deps.windows?.cancelTask(id,undefined,this.closing?'host_shutdown':'task_aborted').catch(e=>console.error('[windows] cleanup',String(e))); void this.deps.android?.broker.cancelTask(id,undefined,this.closing?'host_shutdown':'task_aborted').catch(e=>console.error('[android] abort cleanup',String(e))); void this.browsers?.stopTask(id); void this.proxies.stopTask(id).catch(error=>console.error('[reverse-proxy] stop',error)); this.settlementControllers.get(id)?.abort(); this.finalRuns.get(id)?.abort(); const run = this.runs.get(id); if (!run) return; run.abort.abort(); this.invalidate(run); } async resetPolicySessions(id:number):Promise{ const run=this.runs.get(id);if(!run||run.policyRevision===(await readTaskPolicy(this.pool,id)).revision)return; run.abort.abort();this.invalidate(run);await run.done; // A concurrent resume may have committed while the old sessions drained. // Relaunch it with the new policy instead of leaving a running task orphaned. const task=(await this.pool.query("SELECT id FROM tasks WHERE id=$1 AND status='running' AND NOT paused AND NOT queued AND deleted_at IS NULL AND NOT archived",[id])).rows[0]; if(task&&!this.runs.has(id))await this.launch(id); } pause(id: number,preserveAndroid=false): void { if(!preserveAndroid)void this.deps.windows?.cancelTask(id,undefined,'task_paused').catch(e=>console.error('[windows] retain',String(e))); if(!preserveAndroid)void this.deps.android?.broker.cancelTask(id,undefined,'task_paused').catch(e=>console.error('[android] pause cleanup',String(e))); void this.codeIntel.stopTask(id).catch(()=>{}); // 暂停时把本任务正在进行的导入/打包打断,恢复后循环会重新拉起来 this.intelTasks.get(id)?.abort(); this.browsers?.pauseTask(id); void this.proxies.stopTask(id).catch(error=>console.error('[reverse-proxy] pause',error)); const run = this.runs.get(id); if (!run) return; if(!run.paused){run.paused = true;this.invalidate(run);} this.releaseIdleSlot(run); } async pauseForLogin(id:number):Promise{ const gate=taskActions(this.pool);gate.hold([id]); if(!await gate.drained([id]))return false; // Sessions remain parked at their next model/tool boundary, without abort/retry. await Promise.all([...(this.runs.get(id)?.sessions??[])].map(h=>h.flushEvents())); return await gate.drained([id]); } resume(id: number): void { this.startDeadlineCoordinator(id); // 暂停时把后台循环 aborted 掉了,这里要重新拉起来 this.startCodeIntel(id); const run = this.runs.get(id); if (!run) { void this.launch(id); return; } if(!run.paused){this.notify(id);return;} void (async()=>{await this.deps.android?.broker.resumeTask(id);await this.deps.windows?.resumeTask(id);await this.efficiency.resetIfSuspended(id);})().then(async()=>{ if(this.runs.get(id)!==run||run.abort.signal.aborted)return; const current=(await this.pool.query("SELECT * FROM tasks WHERE id=$1 AND deleted_at IS NULL AND status IN('created','running') AND NOT paused",[id])).rows[0]; if(!current||await this.batchBlocked(current)){this.releaseIdleSlot(run);return;} if(this.runs.get(id)!==run||run.abort.signal.aborted||this.settling.has(id))return; if(!run.releaseSlot){const release=this.tryAcquireRunSlot(current);if(!release){void this.pool.query("UPDATE tasks SET queued=true,queued_at=COALESCE(queued_at,now()) WHERE id=$1",[id]);return;}run.releaseSlot=release;} run.execution = new AbortController();run.paused = false;this.notify(id); }).catch(async error=>{console.error('[engine] resume failed',error);await this.pool.query("UPDATE tasks SET paused=true,queued=false WHERE id=$1 AND deleted_at IS NULL AND status IN('created','running','paused')",[id]);await this.emit(id,'android_resume_blocked',{message:String(error)});}); } notify(id: number): void { const run = this.runs.get(id); if (!run) return; run.pending = true; } async notifyFingerprints(taskId:number,change?:FingerprintChange):Promise{ await this.deps.pocs?.refresh(taskId); this.notify(taskId);if(!change||!this.deps.fingerprints)return; for(const [intentId,work] of this.work){if(work.taskId!==taskId||work.finishing||work.abort.signal.aborted||(work.fingerprintRevision??-1)>=change.revision)continue; const summary=await this.deps.fingerprints.summary(taskId,intentId); const relevant=change.intentId===intentId||summary.focus?.asset_ids?.includes(change.assetId??0)||summary.focus?.urls?.some(url=>relatedFingerprintURL(url,change.url))||summary.observations.some(o=>relatedFingerprintURL(o.url,change.url)); if(!relevant)continue; const text='[宿主指纹更新,按当前意图筛选;这是识别线索,不是漏洞结论]\n'+JSON.stringify(summary); work.knowledge.offer('fingerprints',summary,text,()=>recordFingerprintDelivery(this.pool,taskId,'worker_update',summary.revision,summary.observations.flatMap(o=>o.observation_ids),intentId)); work.fingerprintRevision=summary.revision; } } async notifyPocs(taskId:number):Promise{ this.notify(taskId);if(!this.deps.pocs)return; for(const [intentId,work] of this.work){if(work.taskId!==taskId||work.finishing||work.abort.signal.aborted)continue; const summary=await this.deps.pocs.summary(taskId,intentId); if(!summary.enabled||(work.pocRevision??-1)>=summary.revision)continue; if(summary.candidates.length){const text='[宿主 PoC 知识更新:仅供当前意图判断,非漏洞结论或执行授权]\n'+JSON.stringify(summary);work.knowledge.offer('pocs',summary,text,()=>pocDelivery(this.pool,taskId,'worker_update',summary.revision,summary.candidates.map(c=>Number(c.id)),intentId));} work.pocRevision=summary.revision; } } notifyHints(id:number,texts:string[]):void{const run=this.runs.get(id);if(!run||!texts.length)return;run.hintTriggers.push([...texts]);this.notify(id);} async platformState(id:number):Promise<{started:boolean;paused:boolean;ready:boolean}>{const run=this.runs.get(id),task=(await this.pool.query('SELECT * FROM tasks WHERE id=$1',[id])).rows[0];return {started:!!run,paused:!!run?.paused,ready:!!task&&await this.ready(task)};} async killWork(taskId:number,intentId:number):Promise{ const work=this.work.get(intentId);if(!work||work.taskId!==taskId)throw new Error(`意图 ${intentId} 当前没有运行中的 work(可能已结束或未被领取)`); work.abort.abort(); await this.pool.query("UPDATE exploration_nodes SET state='stopped',completed_at=now(),updated_at=now() WHERE id=$1 AND task_id=$2 AND state='running'",[intentId,taskId]); await work.session?.session.abort();this.notify(taskId); } async steerWork(taskId:number,intentId:number,message:string):Promise{ if(!message.trim())throw new Error('纠偏消息不能为空');const work=this.work.get(intentId); if(!work||work.taskId!==taskId||work.finishing||work.abort.signal.aborted)throw new Error(`意图 ${intentId} 当前没有运行中的 work(可能已结束或未被领取)`); work.skipTools++;try{const text=`[规划者纠偏]\n${message}`;if(work.session)await work.session.session.steer(text);else work.steering.push(text);}catch(error){work.skipTools--;throw error;} } /** 彻底删除成功后才调用:清掉本任务的索引文件,归档路径不会走到这里。 */ async purgeTaskData(id: number): Promise { await this.codeIntel.purgeTask(id).catch(error => console.error('[codeintel] purge:', String(error))); await this.deps.hunting?.purgeTask(id).catch(error => console.error('[hunting] purge:', String(error))); await this.deps.windows?.cancelTask(id).catch(error=>console.error('[windows] cleanup',String(error))); await this.deps.android?.broker.cancelTask(id).catch(error => console.error('[android] purge:', String(error))); } async stopExecution(id: number): Promise { this.abort(id); await this.deps.windows?.cancelTask(id).catch(error=>console.error('[windows] cleanup',String(error))); await this.deps.android?.broker.cancelTask(id).catch(error => console.error('[android] stop:', String(error))); // 白盒后台(索引循环、已提交的审计)也必须随停止入口一起取消并等它退干净 const background = this.stopBackground(id).catch(() => false); await Promise.all([ this.drain(id), this.browsers?.stopTask(id), this.proxies.stopTask(id), background, ]); } async drain(id: number): Promise { await this.runs.get(id)?.done; await this.settling.get(id); } async shutdown(): Promise { this.closing = true;this.slotAbort.abort();this.codeIntel.stopCancelSweeper(); const intelIds=[...this.intelTasks.keys()]; for (const ctl of this.intelTasks.values()) ctl.abort(); await Promise.allSettled(intelIds.map(id=>this.codeIntel.stopTask(id))); for(const ctl of this.settlementControllers.values())ctl.abort(); const runs = [...this.runs.values()]; for (const run of runs) this.abort(run.taskId); for(const ctl of this.finalRuns.values())ctl.abort(); await Promise.all(runs.map((run) => run.done)); await Promise.allSettled([...this.settling.values()]); await Promise.all([...this.operations.values()].flatMap(set=>[...set])); await this.proxies.stopAll().catch(() => {}); await Promise.allSettled([...this.intelLoops]); } async beginDelete(id: number): Promise { if(this.workspaceCleaning.has(id))throw new Error('工作空间正在清理,请稍后重试'); this.deleting.add(id); // 这一步只负责“停下来”,不销毁任何文件:归档路径也会走这里 if (!await this.stopBackground(id)) { this.deleting.delete(id); throw new Error('后台仍在释放文件,请稍后再试删除或归档'); } this.abort(id); await this.drain(id); await this.proxies.stopTask(id); await this.browsers?.stopTask(id); await Promise.all([...(this.operations.get(id)??[])]); // 对照 drainTaskSideQuestions:等待旁路终写+快照 flush;未保存的检查点不得静默丢失 if (this.sideRuntime) await this.sideRuntime.drainTask(id); } endDelete(id: number): void { this.deleting.delete(id); } private async serializeAdmission(action:()=>Promise):Promise{ const previous=this.admissionTail;let release!:()=>void;this.admissionTail=new Promise(r=>release=r); await previous;try{return await action();}finally{release();} } private taskLimit():number{const s=this.deps.settingsConsumers?.get();return s?.taskConcurrencyEnabled?taskConcurrencyLimit(s.taskConcurrencyLimit):DEFAULT_TASK_CONCURRENCY;} refreshTaskConcurrency():void{this.slots.refresh();} private async batchBlocked(task:{id:number;batch_id?:string;kind?:string}):Promise{ if(task.batch_id&&(await this.pool.query('SELECT paused FROM task_batches WHERE id=$1',[task.batch_id])).rows[0]?.paused)return true; if(task.kind!=='modeling')return false; return !!(await this.pool.query(`SELECT 1 WHERE EXISTS(SELECT 1 FROM task_business_models m JOIN tasks p ON p.id=m.task_id WHERE m.modeling_task_id=$1 AND p.batch_id IS NOT NULL) AND NOT EXISTS(SELECT 1 FROM task_business_models m JOIN tasks p ON p.id=m.task_id LEFT JOIN task_batches b ON b.id=p.batch_id WHERE m.modeling_task_id=$1 AND p.status IN('created','running','paused') AND NOT p.paused AND p.deleted_at IS NULL AND NOT COALESCE(b.paused,false))`,[task.id])).rowCount; } private activeRuns():number{return this.slots.size;} /** Modeling is task-owned auxiliary work, without a global task-count cap. * Keep re-entrant leases for cleanup protection; only primary runs use slots. */ private tryAcquireRunSlot(task:{id:number|string;kind?:string}):(()=>void)|null{ const id=Number(task.id); if(task.kind!=='modeling')return this.slots.tryAcquire(id); this.modelingLeases.set(id,(this.modelingLeases.get(id)??0)+1); let released=false; return ()=>{if(released)return;released=true;const n=(this.modelingLeases.get(id)??1)-1; if(n)this.modelingLeases.set(id,n);else this.modelingLeases.delete(id); setImmediate(()=>void this.pumpQueue().catch(console.error));}; } async acquireTaskSession(id:number,signal:AbortSignal):Promise<()=>void>{ if(this.closing||this.isDeleting(id))throw new Error('任务正在关闭或删除'); const combined=AbortSignal.any([signal,this.slotAbort.signal]); const task=(await this.pool.query('SELECT id,kind FROM tasks WHERE id=$1 AND deleted_at IS NULL',[id])).rows[0]; combined.throwIfAborted();if(this.closing||this.isDeleting(id))throw new Error('任务正在关闭或删除'); if(task?.kind==='modeling')return this.tryAcquireRunSlot(task)!; return this.slots.acquire(id,combined); } private releaseIdleSlot(run:RunContext){if((run.paused||run.abort.signal.aborted)&&!run.sessions.size&&run.releaseSlot){run.releaseSlot();run.releaseSlot=undefined;}} async acquireConversationTask(id:number,signal:AbortSignal):Promise<()=>void>{ await this.pool.query("UPDATE tasks SET queued=true,queued_at=now(),first_run_at=NULL WHERE id=$1 AND queue_mode='pentest_chat'",[id]); let release:(()=>void)|undefined; try{release=await this.slots.acquire(id,AbortSignal.any([signal,this.slotAbort.signal]));const changed=await this.pool.query("UPDATE tasks SET queued=false,queued_at=NULL,first_run_at=now() WHERE id=$1 AND status='running' AND NOT paused AND deleted_at IS NULL",[id]);if(!changed.rowCount)throw new Error('任务已暂停或结束');return release;} catch(e){release?.();await this.pool.query("UPDATE tasks SET queued=false,queued_at=NULL WHERE id=$1 AND queue_mode='pentest_chat'",[id]);throw e;} } private async ready(task:TaskSnapshot):Promise{ const runtime=await getPiRuntime(this.config); try{for(const role of task.kind==='modeling'?['modeler']:['goals',task.agent_key||'planner','worker'])await new TaskModelResolver(this.pool,this.config,runtime,Number(task.id),role).current();return true;}catch{return false;} } /** Original follow-up admission: persistent FIFO, terminal revival and CAS. * Caller holds beginTaskOperation until the response/compensation finishes. */ async admitFollowUp(id:number):Promise{return this.serializeAdmission(async()=>{ if(this.closing||this.isDeleting(id))throw new Error('task is being deleted'); const task=(await this.pool.query('SELECT * FROM tasks WHERE id=$1 AND deleted_at IS NULL',[id])).rows[0];if(!task)throw new Error('task is being deleted'); if((await this.pool.query(`SELECT 1 WHERE ${loginPausedTaskSQL('$1::bigint')}`,[id])).rowCount)throw new Error('正在协助登录,请使用“登录完成,继续任务”恢复'); if(task.queue_mode==='pentest_chat')throw new Error('请在原 pentest 会话中继续该任务'); const old=this.runs.get(id),engineWasPaused=old?.paused,settings=this.deps.settingsConsumers?.get(),enabled=true; const ready=!enabled||await this.ready(task); const active=old&&!old.abort.signal.aborted&&!old.paused&&task.status==='running'&&!task.paused&&!task.queued&&ready; const backlog=task.kind!=='modeling'&&enabled&&!!(await this.pool.query("SELECT 1 FROM tasks WHERE id<>$1 AND kind<>'modeling' AND queued=TRUE AND paused=FALSE AND deleted_at IS NULL AND archived=FALSE ORDER BY queued_at,id LIMIT 1",[id])).rowCount; const atCapacity=task.kind!=='modeling'&&this.activeRuns()-(old?.releaseSlot?1:0)>=this.taskLimit(); const queued=!active&&enabled&&(!ready||backlog||atCapacity); if(old&&!active){if(!['running','created','paused'].includes(task.status))this.abort(id);else this.pause(id);if(old.abort.signal.aborted)await old.done;} const committed=await this.pool.query(`UPDATE tasks SET status='running',completed_at=NULL,paused=FALSE,queued=$3, queued_at=CASE WHEN NOT $3 THEN NULL WHEN queued THEN COALESCE(queued_at,now()) ELSE now() END, queue_mode=CASE WHEN NOT $3 THEN '' WHEN queued AND queue_mode='bootstrap' THEN 'bootstrap' ELSE 'resume' END, first_run_at=CASE WHEN $2='timeout' THEN NULL ELSE first_run_at END, deadline_at=CASE WHEN $2='timeout' THEN NULL ELSE deadline_at END,updated_at=now() WHERE id=$1 AND status=$2 AND deleted_at IS NULL RETURNING id`,[id,task.status,queued]); if(!committed.rowCount){if(old&&!engineWasPaused&&!task.paused&&!old.abort.signal.aborted)this.resume(id);throw new Error(`task ${id} lifecycle changed before admission (expected status "${task.status}")`);} await reopenExploration(this.pool,id); if(queued){if(!task.queued){const summary=!ready?'已排队:当前没有可运行的 LLM 配置,配置恢复后自动开始':backlog?'已排队:已有更早的任务等待运行,将按 FIFO 顺序自动开始':`已排队:达到并发上限 ${this.taskLimit()},等待空位后自动开始`; await this.pool.query("INSERT INTO activity(exploration_id,worker,kind,summary) VALUES($1,'system','text',$2)",[task.exploration_id,summary]).catch(e=>console.error('[admission] queue audit failed',e));}return true;} if(this.runs.has(id)){this.resume(id);this.notify(id);}else await this.startRun(id); return false; });} async bootstrap(id:number):Promise{await this.pool.query("UPDATE tasks SET queue_mode='bootstrap' WHERE id=$1 AND first_run_at IS NULL AND deleted_at IS NULL",[id]);await this.launch(id);} async launch(id: number): Promise {await this.serializeAdmission(()=>this.startRun(id));} private async startRun(id: number,fromQueue=false): Promise { if(updateMaintenance.blocked())return; const release=updateMaintenance.acquire('request'); try{await this.startRunWithLease(id,fromQueue);}finally{release();} } private async startRunWithLease(id:number,fromQueue:boolean):Promise{ // Reserve synchronously before any await; concurrent launch callers share one slot. if (this.closing || this.runs.has(id) || this.settling.has(id) || this.isDeleting(id)) return; if((await this.pool.query("SELECT 1 FROM tasks WHERE id=$1 AND queue_mode='pentest_chat'",[id])).rowCount)return; const candidate=(await this.pool.query("SELECT * FROM tasks WHERE id=$1 AND status IN ('created','running') AND paused=FALSE AND deleted_at IS NULL AND archived=FALSE",[id])).rows[0]; if(!candidate||taskActions(this.pool).held(id))return; try{await this.deps.android?.broker.resumeTask(id);await this.deps.windows?.resumeTask(id);}catch(error){await this.pool.query("UPDATE tasks SET paused=true,queued=false,stopped_reason=$2 WHERE id=$1 AND deleted_at IS NULL AND status IN('created','running')",[id,'设备现场恢复未完成:'+String(error).slice(0,200)]);await this.emit(id,'android_resume_blocked',{message:String(error)});return;} if(candidate.deadline_at&&new Date(candidate.deadline_at).getTime()<=Date.now()){ void this.settleTask(id).catch(error=>console.error('[engine] deadline settlement',error));return; } if(!await this.ready(candidate)){await this.pool.query("UPDATE tasks SET queued=true,queued_at=COALESCE(queued_at,now()) WHERE id=$1 AND status IN ('created','running') AND NOT paused AND deleted_at IS NULL",[id]);return;} const batchPaused=await this.batchBlocked(candidate); const older=candidate.kind!=='modeling'&&!fromQueue&&(await this.pool.query("SELECT 1 FROM tasks WHERE id<>$1 AND kind<>'modeling' AND queued AND NOT paused AND status IN('created','running') AND queue_mode<>'pentest_chat' AND deleted_at IS NULL AND NOT archived AND (queued_at,id)<(COALESCE($2::timestamptz,now()),$1) LIMIT 1",[id,candidate.queued_at])).rowCount; if(batchPaused||older){await this.pool.query("UPDATE tasks SET queued=true,queued_at=COALESCE(queued_at,now()) WHERE id=$1 AND status IN ('created','running') AND NOT paused AND deleted_at IS NULL",[id]);if(!fromQueue)setImmediate(()=>void this.pumpQueue().catch(console.error));return;} if(candidate.deadline_at&&new Date(candidate.deadline_at).getTime()<=Date.now()){ void this.settleTask(id).catch(error=>console.error('[engine] deadline settlement',error));return; } const settings = this.deps.settingsConsumers?.get(); const releaseSlot=this.tryAcquireRunSlot(candidate); if (!releaseSlot) { await this.pool.query("UPDATE tasks SET queued=TRUE, queued_at=COALESCE(queued_at,now()) WHERE id=$1 AND status IN ('created','running','paused') AND deleted_at IS NULL", [id]); return; } const loginPending=!!(await this.pool.query("SELECT 1 FROM android_login_assistance WHERE task_id=$1 AND state='resumed'",[id])).rowCount; const run: RunContext = { taskId: id, policyRevision:Number(candidate.policy_revision)||0, abort: new AbortController(), execution: new AbortController(), sessions: new Set(), generation: 0, paused: false, pending: loginPending, hintTriggers:[], done: Promise.resolve(),releaseSlot }; this.runs.set(id, run); this.startDeadlineCoordinator(id); run.done = this.supervise(run, Math.max(1, candidate.freescope?taskPolicyFromRow(candidate).options.workers:candidate.worker_limit??settings?.workers ?? 6)).finally(() => { run.releaseSlot?.();run.releaseSlot=undefined; if (this.runs.get(id) === run) this.runs.delete(id); void this.pumpQueue().catch((e) => console.error("[engine] queue:", e)); }); } async pumpQueue(): Promise { if(updateMaintenance.blocked())return; if (this.closing) return; if (this.queuePump) return this.queuePump; const work = async () => { const orphaned=await this.pool.query(`UPDATE tasks child SET status='failed',queued=false,paused=false,queued_at=NULL,completed_at=now(),stopped_reason='来源测试任务均已结束,后台建模已停止;已提交草稿保留' WHERE child.kind='modeling' AND child.status IN('created','running','paused') AND EXISTS(SELECT 1 FROM business_model_runs r WHERE r.task_id=child.id AND r.trigger_kind IN('initial','discovery')) AND EXISTS(SELECT 1 FROM task_business_models m WHERE m.modeling_task_id=child.id) AND NOT EXISTS(SELECT 1 FROM task_business_models m JOIN tasks p ON p.id=m.task_id WHERE m.modeling_task_id=child.id AND p.status IN('created','running','paused') AND p.deleted_at IS NULL) RETURNING child.id`); for(const child of orphaned.rows)this.abort(Number(child.id)); for(const row of (await this.pool.query("SELECT id FROM tasks WHERE execution_mode='continuous' AND status IN('created','running','paused') AND deadline_at<=now() AND deleted_at IS NULL AND NOT archived")).rows)void this.settleTask(Number(row.id)).catch(e=>console.error('[batch] cutoff',e)); const expired=await this.pool.query("SELECT id,kind FROM tasks WHERE status IN ('created','running') AND paused=FALSE AND deadline_at<=now() AND (kind='modeling' OR EXISTS(SELECT 1 FROM task_business_models m WHERE m.task_id=tasks.id AND m.version_id IS NULL))"); for(const row of expired.rows){const id=Number(row.id);if(row.kind==='modeling'){await this.modeling.fail(id,'timeout','业务建模执行超过时间上限;已提交草稿保留,主测试继续');this.abort(id);await this.emit(id,'modeling_timeout',{draft_preserved:true});continue;}await withTaskReport(this.pool,id,'达到任务截止时间',c=>c.query("UPDATE tasks SET status='timeout',stopped_reason=CASE WHEN kind='modeling' THEN '业务建模执行超过时间上限;草稿已保留,请检查网络、覆盖缺口或提交错误后重试' ELSE stopped_reason END,completed_at=now(),updated_at=now() WHERE id=$1 AND status IN('created','running') AND NOT paused AND deadline_at<=now()",[id]));this.abort(id);if(row.kind==='modeling')await this.emit(id,'modeling_timeout',{draft_preserved:true});} const settings = this.deps.settingsConsumers?.get(); const limit = this.taskLimit(); const rows = await this.pool.query("SELECT t.id,t.kind FROM tasks t LEFT JOIN task_batches b ON b.id=t.batch_id WHERE t.queued=TRUE AND t.paused=FALSE AND t.status IN ('created','running') AND t.queue_mode<>'pentest_chat' AND t.deleted_at IS NULL AND t.archived=FALSE AND NOT COALESCE(b.paused,false) ORDER BY t.queued_at NULLS FIRST,t.id"); for (const row of rows.rows) { if(row.kind!=='modeling'&&this.activeRuns()>=limit)continue; const task=(await this.pool.query('SELECT * FROM tasks WHERE id=$1',[row.id])).rows[0]; if(!task)continue; if(task.kind!=='modeling'&&this.activeRuns()>=limit)continue; if(!await this.ready(task)||await this.batchBlocked(task))continue; if(this.settling.has(Number(row.id)))continue; const run=this.runs.get(Number(row.id));if(run?.abort.signal.aborted)continue; if(run){const release=run.releaseSlot??this.tryAcquireRunSlot(task);if(!release)continue;run.releaseSlot=release;await this.pool.query("UPDATE tasks SET queued=FALSE,queued_at=NULL WHERE id=$1",[row.id]);this.resume(Number(row.id));} else await this.startRun(Number(row.id),true); } }; this.queuePump = this.serializeAdmission(work).finally(() => { this.queuePump = null; }); return this.queuePump; } async recover(): Promise { // Called once on boot; a fresh process owns no surviving worker lease. if (this.runs.size) throw new Error("recover requires a quiescent engine"); if(this.deps.android){ const retained=(await this.pool.query("SELECT DISTINCT s.task_id FROM android_sessions s JOIN tasks t ON t.id=s.task_id WHERE s.state IN('starting','running','paused','recovering') AND t.deleted_at IS NULL AND t.status IN('created','running','paused') AND NOT EXISTS(SELECT 1 FROM android_login_assistance a WHERE a.session_id=s.id AND a.state IN('pausing','active','resuming','resumed'))")).rows; for(const row of retained)await this.deps.android.broker.cancelTask(Number(row.task_id),undefined,'host_shutdown'); } await recoverModelingIntents(this.pool); await this.pool.query(`UPDATE exploration_nodes n SET state='open', claimed_by=NULL, claimed_at=NULL FROM tasks t WHERE n.task_id=t.id AND n.kind='intent' AND n.state='running' AND t.status IN ('running','paused') AND t.deleted_at IS NULL AND t.archived=FALSE AND t.queue_mode<>'pentest_chat'`); const rows = await this.pool.query("SELECT id FROM tasks WHERE status='running' AND paused=FALSE AND queued=FALSE AND deleted_at IS NULL AND archived=FALSE AND queue_mode<>'pentest_chat' ORDER BY id"); for (const row of rows.rows) await this.launch(Number(row.id)); await this.pumpQueue(); // 对照 restoreTaskRuntimes/startDeadlineCoordinator:非活跃(含暂停/排队)未终态任务 // 重启后也有到点收尾——独立于 planner/worker 循环的每任务绝对时钟。 await this.startDeadlineCoordinators(); // 重启前结束的任务,白盒可能还在跑:窗口内恢复剩余时间,过期的明确标记 const GRACE_MS = 10 * 60_000; const pending = await this.pool.query( `SELECT DISTINCT n.task_id, COALESCE(t.completed_at, t.updated_at) AS finished_at FROM exploration_nodes n JOIN tasks t ON t.id=n.task_id WHERE n.kind='fact' AND n.payload->>'kind'='code_ready' AND n.payload->>'audit_state'='running' AND t.deleted_at IS NULL AND t.status IN ('done','failed','timeout')`).catch(() => null); for (const row of pending?.rows ?? []) { const taskId = Number(row.task_id); const finishedAt = Date.parse(String(row.finished_at ?? '')) || 0; const deadline = finishedAt ? finishedAt + GRACE_MS : 0; if (!deadline || Date.now() >= deadline) { await this.codeIntel.markUnfinished(taskId).catch(() => {}); continue; } this.startCodeIntel(taskId, deadline); } } /** 每任务 deadline 协调器(幂等;绝对墙钟,暂停也计数;到点跑收尾时序)。 */ private coordStarted = new Set(); private reportPrepared=new Map(); private async startDeadlineCoordinators(): Promise { const rows = await this.pool.query( "SELECT id FROM tasks WHERE status IN ('running','paused') AND deleted_at IS NULL AND archived=FALSE AND queued=FALSE AND queue_mode<>'pentest_chat'", ); for (const row of rows.rows as { id: number }[]) { this.startDeadlineCoordinator(Number(row.id)); } } startDeadlineCoordinator(taskId: number): void { if (this.coordStarted.has(taskId) || this.isDeleting(taskId)) return; this.coordStarted.add(taskId); void (async () => { try { for (;;) { if (this.closing) return; const t = (await controlPool(this.pool).query("SELECT status, deadline_at, timeout_seconds FROM tasks WHERE id=$1", [taskId]).catch(() => null))?.rows[0] as { status: string; deadline_at: Date | string | null; timeout_seconds: number } | undefined; if (t === undefined && !this.closing) { await new Promise((r) => setTimeout(r, 5_000)); continue; } if (!t || ["done", "failed", "timeout"].includes(t.status)) return; const dl = t.deadline_at ? new Date(t.deadline_at).getTime() : 0; const sleepUnref = (ms: number) => new Promise((r) => { const t = setTimeout(r, ms); t.unref?.(); }); if (dl <= 0) { await sleepUnref(t.timeout_seconds>0?500:30000); continue; } const remaining = dl - Date.now(); if(remaining>0&&remaining<=reportLeadSeconds(t.timeout_seconds)*1000&&this.reportPrepared.get(taskId)!==dl){await checkpointTaskReport(this.pool,taskId);this.reportPrepared.set(taskId,dl);} if (remaining > 0) { const untilReport=remaining-reportLeadSeconds(t.timeout_seconds)*1000;await sleepUnref(Math.min(remaining,untilReport>0?untilReport:60000,60000));continue; } if(this.closing)return; await this.settleTask(taskId);return; } } finally { this.coordStarted.delete(taskId); } })().catch(error=>console.error('[deadline] coordinator failed',error)); } /** Source engine_timeout.go: single coordinator, 90s drain, terminal planner, guarded state. */ private settleTask(taskId:number):Promise{ const existing=this.settling.get(taskId);if(existing)return existing; const settlement=new AbortController();this.settlementControllers.set(taskId,settlement); let releaseSlot:(()=>void)|undefined; const work=Promise.resolve().then(async()=>{ if(this.closing||this.isDeleting(taskId))return; const initial=(await this.pool.query("SELECT * FROM tasks WHERE id=$1 AND deleted_at IS NULL AND status IN ('created','running','paused')",[taskId])).rows[0] as TaskSnapshot|undefined; if(!initial)return; if((initial.deadline_at&&new Date(initial.deadline_at).getTime()>Date.now())||(await this.pool.query(`SELECT 1 WHERE ${loginPausedTaskSQL('$1::bigint')}`,[taskId])).rowCount)return; if(initial.kind==='modeling'){ await this.modeling.fail(taskId,'timeout','业务建模执行超过时间上限;已提交草稿保留,主测试继续'); this.abort(taskId);await this.emit(taskId,'modeling_timeout',{draft_preserved:true});return; } releaseSlot=await this.slots.acquire(taskId,AbortSignal.any([settlement.signal,this.slotAbort.signal])); if(settlement.signal.aborted)return; await this.emit(taskId,'task_settling',{}); const run=this.runs.get(taskId);let timer:ReturnType|undefined; if(run){ if(initial.execution_mode==='continuous'){run.abort.abort();this.invalidate(run);} const graceful=await Promise.race([run.done.then(()=>true),new Promise(r=>{timer=setTimeout(()=>r(false),initial.execution_mode==='continuous'?10000:90000);})]); if(timer)clearTimeout(timer); if(!graceful){this.invalidate(run);await Promise.race([run.done,new Promise(r=>setTimeout(r,3000))]);} } if(this.closing||this.isDeleting(taskId)||settlement.signal.aborted)return; await fingerprintMayComplete(this.pool,taskId,true);await pocMayComplete(this.pool,taskId,true); let met=false; try{met=await this.finalPlannerRound(taskId);}catch(error){await this.emit(taskId,'final_planner_error',{error:String(error)}).catch(console.error);} if(this.closing||this.isDeleting(taskId)||settlement.signal.aborted)return; const release=this.beginTaskOperation(taskId);if(!release)return; try{ const status=initial.execution_mode==='continuous'?'timeout':met?'done':'timeout',won=await withTaskReport(this.pool,taskId,'达到任务截止时间',c=>c.query("WITH terminal AS (UPDATE tasks SET status=$2,paused=false,queued=false,queued_at=NULL,stopped_reason=CASE WHEN $2='timeout' THEN '任务已到截止时间,发现及未完成方向已保留' ELSE stopped_reason END,completed_at=now(),updated_at=now() WHERE id=$1 AND deleted_at IS NULL AND status IN ('created','running','paused') RETURNING id), stopped AS (UPDATE exploration_nodes SET state='stopped',completed_at=now(),updated_at=now() WHERE task_id IN (SELECT id FROM terminal) AND kind='intent' AND state IN ('open','running','paused','blocked') RETURNING id) SELECT id FROM terminal",[taskId,status])); if(won.rowCount)await this.emit(taskId,met?'task_done':'task_timeout',{}); }finally{release();} }).finally(()=>{releaseSlot?.();this.settlementControllers.delete(taskId);if(this.settling.get(taskId)===work)this.settling.delete(taskId); // 终态写入之后再清一次:运行循环退出时代理清理会因为任务还是 running 而跳过 void this.proxies.stopTaskIfTerminal(taskId).catch(() => {}); void this.pumpQueue().catch(console.error);}); this.settling.set(taskId,work);return work; } private async finalPlannerRound(taskId:number):Promise{ const release=this.beginTaskOperation(taskId);if(!release)return false; const ctl=new AbortController();this.finalRuns.set(taskId,ctl);let host:HostedSession|undefined; const finalTimer=setTimeout(()=>ctl.abort(),30000); try{ let task:TaskSnapshot|undefined,spec:Awaited>|undefined,profile:{provider?:string;modelId?:string}|undefined; // Finalization cannot wait forever for an unavailable model profile. const readyDeadline=Date.now()+30000; while(!ctl.signal.aborted&&!this.closing&&!this.isDeleting(taskId)&&Date.now()(r=>{const timer=setTimeout(done,2000);function done(){clearTimeout(timer);ctl.signal.removeEventListener('abort',done);r();}ctl.signal.addEventListener('abort',done,{once:true});}); } } if(!task||!spec||!profile||ctl.signal.aborted||this.closing)return false; const canExecute=async()=>!ctl.signal.aborted&&!this.closing&&!this.isDeleting(taskId)&&!!(await this.pool.query("SELECT 1 FROM tasks WHERE id=$1 AND deleted_at IS NULL AND status IN ('created','running','paused')",[taskId])).rowCount; const ctx={businessKind:'planner',businessId:'task-'+taskId+'-final',agentKey:'planner',taskId,signal:ctl.signal,canExecute}; const tools=await assembleTools(this.pool,['graph_overview','list_facts','node_detail','list_goals','prove_goal','resolve_goal','expand_digest',...TRACE_TOOLS.planner,'list_findings','report_finding'],ctx,await this.gateOptions()); const row=(await this.pool.query("SELECT task_timeout_wrapup_prompt,task_timeout_wrapup_max_turns FROM agents WHERE key='planner'")).rows[0]; const finalPrompt=goTrim(String(row?.task_timeout_wrapup_prompt??''))?row.task_timeout_wrapup_prompt:promptDefaults.wrapup.planner!.task_timeout; await this.graph.ensure(taskId); await this.pool.query("UPDATE explorations SET round_no=round_no+1 WHERE id=(SELECT exploration_id FROM tasks WHERE id=$1)",[taskId]); await this.emit(taskId,'final_planner_start',{}); host=await createHostedSession(this.pool,this.config,{kind:'planner',businessId:ctx.businessId,cwd:taskWorkDir(this.config,taskId),systemPrompt:spec.systemPrompt+artifactSpec(taskWorkDir(this.config,taskId))+'\n截止收尾:仅整理已有证据与报告,不得新建方向、请求目标或执行命令。',...profile,customTools:tools,customToolsOnly:true,freshContext:true,runBudget:{maxTurns:Math.max(1,Number(row?.task_timeout_wrapup_max_turns)||3),runSeconds:30},activity:{taskId,worker:'planner'}}); const cancel=()=>void host?.session.abort();ctl.signal.addEventListener('abort',cancel,{once:true}); try{if(!await canExecute())return false;await host.session.prompt('任务探索图概览:\n'+JSON.stringify({...await this.graph.overview(taskId),fingerprints:await this.deps.fingerprints?.summary(taskId),poc_knowledge:await this.deps.pocs?.summary(taskId)})+'\n【任务终局收尾(本轮特殊指令,覆盖上面的常规规划流程)】:'+finalPrompt);await host.flushEvents();if(host.modelFailure)throw new Error(host.modelFailure);} finally{ctl.signal.removeEventListener('abort',cancel);} const achieved=await this.pool.query("SELECT 1 FROM explorations e JOIN tasks t ON t.exploration_id=e.id WHERE t.id=$1 AND e.status='achieved'",[taskId]); await this.emit(taskId,'final_planner_done',{met:!!achieved.rowCount});return !!achieved.rowCount; }catch(error){await this.emit(taskId,'final_planner_error',{error:String(error)});return false;} finally{clearTimeout(finalTimer);await host?.dispose();if(this.finalRuns.get(taskId)===ctl)this.finalRuns.delete(taskId);release();} } private async admitted(run: RunContext, generation: number): Promise { const gate=taskActions(this.pool);if(gate.held(run.taskId)&&!gate.inAction(run.taskId))return false; if (this.settling.has(run.taskId) || !run.releaseSlot || run.abort.signal.aborted || run.paused || run.generation !== generation || this.isDeleting(run.taskId)) return false; const r = await recoverControl(()=>controlPool(this.pool).query("SELECT 1 FROM tasks WHERE id=$1 AND status='running' AND paused=FALSE AND queued=FALSE AND deleted_at IS NULL AND archived=FALSE AND (deadline_at IS NULL OR deadline_at>now()) AND (execution_mode='continuous' OR NOT EXISTS(SELECT 1 FROM explorations WHERE id=tasks.exploration_id AND status='achieved'))", [run.taskId]),run.abort.signal); return (r.rowCount ?? 0) > 0 && !run.abort.signal.aborted && !run.paused && run.generation === generation&&(!gate.held(run.taskId)||!!gate.inAction(run.taskId)); } private async wait(run: RunContext, ms: number): Promise { if (run.abort.signal.aborted) return; await new Promise((resolve) => { const done = () => { clearTimeout(timer); run.abort.signal.removeEventListener("abort", done); resolve(); }; const timer = setTimeout(done, ms); run.abort.signal.addEventListener("abort", done, { once: true }); if (run.abort.signal.aborted) done(); }); } private async supervise(run: RunContext, workers: number): Promise { let deadlineTimer: NodeJS.Timeout | undefined; const control=(operation:()=>Promise)=>recoverControl(operation,run.abort.signal); try { const r = await control(()=>controlPool(this.pool).query(`UPDATE tasks SET status='running',queued=FALSE,updated_at=now() WHERE id=$1 AND status IN ('created','running') AND paused=FALSE AND deleted_at IS NULL AND archived=FALSE RETURNING *`, [run.taskId])); const task = r.rows[0] as TaskSnapshot | undefined; if (!task || run.abort.signal.aborted) return; if(task.execution_mode==='continuous'&&!task.deadline_at){const clock=(await control(()=>controlPool(this.pool).query("UPDATE tasks SET first_run_at=COALESCE(first_run_at,now()),deadline_at=now()+make_interval(secs=>timeout_seconds) WHERE id=$1 RETURNING deadline_at",[run.taskId]))).rows[0];task.deadline_at=clock.deadline_at;} await control(()=>this.graph.ensure(run.taskId)); const timeout=()=>this.settleTask(run.taskId); if (task.deadline_at) { const left = new Date(task.deadline_at).getTime() - Date.now(); if(left<=0){void timeout().catch(console.error);return;} deadlineTimer = setTimeout(() => void timeout().catch(console.error), left); } if(task.kind==='pentest'){await taskProgress(this.pool,run.taskId,'starting','任务已启动,正在准备测试环境');this.initializeBackgroundModeling(run.taskId);} if(task.kind==='modeling'){ const stamped=(await control(()=>controlPool(this.pool).query("UPDATE tasks SET first_run_at=COALESCE(first_run_at,now()),deadline_at=COALESCE(deadline_at,now()+make_interval(secs=>timeout_seconds)),queue_mode='' WHERE id=$1 AND status='running' AND NOT paused RETURNING deadline_at",[run.taskId]))).rows[0]; if(!stamped)return; task.deadline_at=stamped.deadline_at; if(!deadlineTimer)deadlineTimer=setTimeout(()=>void timeout().catch(console.error),Math.max(0,new Date(stamped.deadline_at).getTime()-Date.now())); await this.runModeling(run,task); return; } const stamped=(await control(()=>controlPool(this.pool).query("UPDATE tasks SET first_run_at=COALESCE(first_run_at,now()),deadline_at=CASE WHEN first_run_at IS NOT NULL OR deadline_at IS NOT NULL THEN deadline_at WHEN timeout_seconds>0 THEN now()+make_interval(secs=>timeout_seconds) ELSE NULL END,queue_mode='' WHERE id=$1 AND status='running' AND NOT paused AND deleted_at IS NULL RETURNING deadline_at",[run.taskId]))).rows[0]; if(!stamped)return; if(!task.deadline_at&&stamped.deadline_at){task.deadline_at=stamped.deadline_at;deadlineTimer=setTimeout(()=>void timeout().catch(console.error),Math.max(0,new Date(stamped.deadline_at).getTime()-Date.now()));} const existing = await control(()=>controlPool(this.pool).query("SELECT 1 FROM exploration_nodes WHERE task_id=$1 AND kind='intent' AND state IN ('open','running') LIMIT 1", [run.taskId])); const goals=await control(()=>controlPool(this.pool).query("SELECT 1 FROM exploration_nodes WHERE task_id=$1 AND kind='goal' LIMIT 1",[run.taskId])); if(!goals.rowCount&&(task.queue_mode==='bootstrap'||!existing.rowCount)&&String(task.goal).trim())await this.decomposeGoals(run,task,run.generation); if(!await this.admitted(run,run.generation))return; if (!existing.rowCount) run.pending = true; if(this.deps.pocs&&await this.deps.pocs.available(run.taskId))await this.deps.pocs.pin(run.taskId); if(this.deps.fingerprints&&await this.deps.fingerprints.available(run.taskId)){ await taskProgress(this.pool,run.taskId,'fingerprinting','正在识别目标指纹并匹配 PoC 线索'); try{await bootstrapFingerprints(this.pool,this.deps.fingerprints,run.taskId,run.execution.signal,async(url,signal)=>runTool(this.pool,'http_request',{url,method:'GET'},{businessKind:'worker',businessId:`task-${run.taskId}-fingerprint-bootstrap`,agentKey:'worker',workerName:'fingerprint-bootstrap',taskId:run.taskId,signal,canExecute:()=>this.admitted(run,run.generation)},{...await this.gateOptions(),enforceInterceptScope:true}));} catch(e){console.warn('[fingerprints] task initialization:',String(e));await this.emit(run.taskId,'fingerprint_bootstrap_error',{error:String(e).slice(0,400)});} } if(!await this.admitted(run,run.generation))return; await control(()=>Promise.resolve(this.deps.pocs?.refresh(run.taskId))); await this.strategy.initialize(run.taskId); await taskProgress(this.pool,run.taskId,'testing','正在调度和执行测试检查'); // 索引/审计可能比任务活得久,所以它不进入这组等待,收尾不会被它拖住 this.startCodeIntel(run.taskId); const recovering=(operation:()=>Promise,label:string)=>recoverLoop(operation,()=>this.pool.query('SELECT 1'),run.abort.signal,async(waiting,error)=>{ console.warn('[task-db]',run.taskId,label,waiting?'waiting':'recovered',waiting?String(error):''); await taskProgress(controlPool(this.pool),run.taskId,waiting?'database_wait':'database_recovered',waiting?'数据库暂时不可用,任务保留,正在等待恢复':'数据库已恢复,正在重新核对任务状态').catch(()=>{}); await this.emit(run.taskId,waiting?'task_database_wait':'task_database_recovered',{loop:label,message:waiting?'数据库暂时不可用,保留任务并等待恢复':'数据库已恢复,重新核对任务状态'}).catch(()=>{}); }); const loops = [...specialistRoles.map(role=>this.strategicLoop(run,task,role)),this.valueLoop(run),recovering(()=>this.efficiencyLoop(run),'efficiency'),recovering(()=>this.plannerLoop(run, task),'planner'), ...Array.from({ length: workers }, (_, i) => recovering(()=>this.workerLoop(run, i + 1),'worker-'+(i+1)))]; // First loop failure cancels siblings; always drain them before releasing the slot. try { await Promise.all(loops); } catch (err) { console.error('[task-loop]',run.taskId,String(err));this.abort(run.taskId); await Promise.allSettled(loops); throw err; } } catch (err) { if(run.abort.signal.aborted)return; await withTaskReport(this.pool,run.taskId,'执行异常,保存已有结果',c=>c.query("UPDATE tasks SET status='failed',stopped_reason=$2,completed_at=now(),updated_at=now() WHERE id=$1 AND status='running'", [run.taskId, String(err).slice(0,200)])).catch(() => {}); await this.emit(run.taskId, "task_error", { error: String(err) }).catch(() => {}); } finally { if (deadlineTimer) clearTimeout(deadlineTimer); await this.deps.windows?.cancelTask(run.taskId,undefined,'task_finished').catch(e=>console.error('[windows] final cleanup',String(e))); await this.deps.android?.broker.cancelTask(run.taskId,undefined,'task_finished').catch(e=>console.error('[android] final cleanup',String(e))); run.abort.abort(); this.invalidate(run); await Promise.allSettled([...run.sessions].map((h) => h.dispose())); run.sessions.clear(); await this.browsers?.stopTask(run.taskId); // A reverse proxy must never outlive the task it was built for. await this.proxies.stopTaskIfTerminal(run.taskId).catch((error) => console.error('[reverse-proxy] 任务结束清理失败', String(error))); } } private async valueLoop(run:RunContext):Promise{ while(!run.abort.signal.aborted&&!this.settling.has(run.taskId)){ if(!run.paused)await this.strategy.values.refresh(run.taskId).catch(e=>console.warn('[strategy] scoring deferred',String(e))); await this.wait(run,5000); } } private async strategicLoop(run:RunContext,task:TaskSnapshot,role:SpecialistRole):Promise{ while(!run.abort.signal.aborted&&!this.settling.has(run.taskId)){ try{if(!run.paused&&await this.admitted(run,run.generation)){const round=await this.strategy.reserve(run.taskId,role);if(round)await this.strategicRound(run,task,round);}} catch(error){console.warn('[strategy] independent loop',role,String(error));} await this.wait(run,2000); } } private async strategicRound(run:RunContext,task:TaskSnapshot,round:StrategyRound){ let h:HostedSession|undefined,error='';const generation=run.generation; const ctl=new AbortController();const signal=AbortSignal.any([run.abort.signal,run.execution.signal,ctl.signal]); const timer=setTimeout(()=>ctl.abort(new Error('专项规划本轮时间已用完')),round.seconds*1000); try{ const spec=await this.deps.agents.resolveSessionSpec(round.role,{Goal:String(task.goal??''),DataDir:this.config.dataDir}); const ctx:ToolContext={businessKind:'planner',businessId:'task-'+run.taskId+'-'+round.role,agentKey:round.role,workerName:round.role,taskId:run.taskId,planningToken:round.token,signal,canExecute:()=>this.admitted(run,generation)}; const tools=await assembleTools(this.pool,STRATEGY_TOOLS.filter(k=>k!=='save_logic_scenario'||round.role==='business_logic'),ctx,await this.gateOptions()); h=await createHostedSession(this.pool,this.config,{kind:'planner',businessId:ctx.businessId,cwd:taskWorkDir(this.config,run.taskId),systemPrompt:spec.systemPrompt,...await this.profile(task,spec),customTools:tools,customToolsOnly:true,employeeCapabilities:true,freshContext:true,activity:{taskId:run.taskId,worker:round.role}}); run.sessions.add(h);const abort=()=>{void h?.session.abort();};signal.addEventListener('abort',abort,{once:true}); try{ if(signal.aborted||!await this.admitted(run,generation))return; const experience=await this.experience.deliver(run.taskId,0,'strategy_'+round.role).catch(()=>({items:[],unavailable:true})); await h.session.prompt('依据当前任务开展一轮独立专项规划。先调用 strategy_context,不依赖口头交接替代图谱派单。经验候选:'+JSON.stringify(experience)+'。本轮最多派发少量当前可执行方向;用 record_strategy_review(phase=final) 保存结论和回访条件;反向岗位还须先提交 phase=independent 的独立假设。'); await h.flushEvents();if(h.modelFailure)throw Error(h.modelFailure); if(ctl.signal.aborted)throw Error('专项规划本轮超时'); }finally{signal.removeEventListener('abort',abort);} }catch(e){error=String(e).slice(0,600);} finally{clearTimeout(timer);if(h){await h.dispose().catch(()=>{});run.sessions.delete(h);this.releaseIdleSlot(run);}await this.strategy.finish(run.taskId,round,error,run.abort.signal.aborted||run.execution.signal.aborted||generation!==run.generation);this.notify(run.taskId);} } private async efficiencyLoop(run:RunContext):Promise{ let nextCheck=0; while(!run.abort.signal.aborted&&!this.settling.has(run.taskId)){ if(Date.now()>=nextCheck&&!run.paused){ const options=await readEfficiencyOptions(this.pool,this.config.efficiency,run.taskId); nextCheck=Date.now()+30000; if(!await this.admitted(run,run.generation)){await this.wait(run,1000);continue;} const sample=await this.efficiency.sample(run.taskId),state=await this.efficiency.observe(run.taskId,sample); if(await this.efficiency.review(run.taskId,sample))await this.adaptive.checkpoint(run.taskId,sample.revision); const continuous=(await this.pool.query('SELECT execution_mode FROM tasks WHERE id=$1 AND NOT freescope',[run.taskId])).rows[0]?.execution_mode==='continuous'; let reason=efficiencyDecision(state,sample,continuous?{...options,maxActiveSeconds:0}:options,Date.now()); // A scheduled planner remains alive during evidence droughts. Explicit // model/time/token budgets and task deadlines still take precedence. if(reason==='no_new_evidence'&&(await this.pool.query("SELECT 1 FROM task_planner_recovery r WHERE r.task_id=$1 AND EXISTS(SELECT 1 FROM exploration_nodes n WHERE n.task_id=$1 AND n.kind='goal' AND n.state<>'met' AND NOT n.payload ? 'resolution')",[run.taskId])).rowCount)reason=null; if(reason&&await this.efficiency.pause(run.taskId,reason,sample))this.pause(run.taskId); if (!reason) await observeStallReview(this.pool,run.taskId,sample).catch(() => { console.warn('[stall-review] sample failed',run.taskId); }); } await this.wait(run,1000); } } private async plannerLoop(run: RunContext, task: TaskSnapshot): Promise { const interval = task.execution_mode==='continuous'?Math.min(60000,plannerInterval(Number(task.plan_heartbeat_seconds)||600)):plannerInterval(Number(task.plan_heartbeat_seconds) || 600); let nextHeartbeat = Date.now() + interval; while (!run.abort.signal.aborted&&!this.settling.has(run.taskId)) { const state = await controlPool(this.pool).query("SELECT status,paused FROM tasks WHERE id=$1 AND deleted_at IS NULL", [run.taskId]); const row = state.rows[0]; if (!row || !['running','paused'].includes(row.status)) { this.abort(run.taskId); return; } if(row.paused&&!run.paused)this.pause(run.taskId); const review=(await this.pool.query(`SELECT next_attempt_at,model_revision,${plannerModelRevisionSQL} AS current_model_revision FROM task_planner_recovery WHERE task_id=$1`,[run.taskId])).rows[0]; const reviewDue=!!review&&(Date.now()>=new Date(review.next_attempt_at).getTime()||review.model_revision!==review.current_model_revision); const loginReview=!!(await this.pool.query("SELECT 1 FROM android_login_assistance WHERE task_id=$1 AND state='resumed' AND revision IS DISTINCT FROM planner_delivered_revision",[run.taskId])).rowCount; const pocRetry=await this.deps.pocs?.retryDue?.(run.taskId)??false; if (!run.paused && !row.paused && (run.pending || reviewDue || loginReview || pocRetry || Date.now() >= nextHeartbeat)) { // A single planner consumes all edges; workers never run a planner session. await this.wait(run, 3000); if(this.settling.has(run.taskId))return; run.pending = false; const generation = run.generation; if (await this.admitted(run, generation)) { if(loginReview){ await this.plan(run,task,generation,await this.efficiency.sample(run.taskId)); await this.wait(run,1000); continue; } const achieved=await this.pool.query("SELECT 1 FROM explorations e JOIN tasks t ON t.exploration_id=e.id WHERE t.id=$1 AND e.status='achieved'",[run.taskId]); await this.deps.pocs?.refresh(run.taskId); const fingerprintReview=await fingerprintNeedsReview(this.pool,run.taskId)||await pocNeedsReview(this.pool,run.taskId); if(!fingerprintReview&&await this.efficiency.finishCovered(run.taskId)){this.abort(run.taskId);return;} const goals = await this.pool.query("SELECT 1 FROM exploration_nodes WHERE task_id=$1 AND kind='goal' AND state='open' LIMIT 1", [run.taskId]); const active = await this.pool.query("SELECT 1 FROM exploration_nodes WHERE task_id=$1 AND kind='intent' AND state IN ('open','running') LIMIT 1", [run.taskId]); const anyIntent = await this.pool.query("SELECT 1 FROM exploration_nodes WHERE task_id=$1 AND kind='intent' LIMIT 1", [run.taskId]); // Original goalless branch: no active intents -> done; open goals never finish on idle. const completionRequested=!!(await this.pool.query('SELECT 1 FROM task_fingerprint_state WHERE task_id=$1 AND completion_requested UNION ALL SELECT 1 FROM task_poc_state WHERE task_id=$1 AND completion_requested UNION ALL SELECT 1 FROM android_task_state WHERE task_id=$1 AND completion_requested',[run.taskId])).rowCount; const closing=task.execution_mode!=='continuous'&&!!(completionRequested||achieved.rowCount||(!goals.rowCount&&anyIntent.rowCount&&!active.rowCount)); const fingerprintReady=!closing||(await fingerprintMayComplete(this.pool,run.taskId)&&await pocMayComplete(this.pool,run.taskId)); if(closing&&!fingerprintReady){run.pending=true;if(!fingerprintReview){await this.wait(run,100);continue;}} if (closing && fingerprintReady && !fingerprintReview) { if(completionRequested){if(await completeAchievedTask(this.pool,run.taskId)){this.abort(run.taskId);return;}run.pending=true;await this.wait(run,1000);continue;} const won = await withTaskReport(this.pool,run.taskId,'当前探索方向已完成',async c=>(await capabilityCompletionReady(c,run.taskId))?c.query("UPDATE tasks SET status='done',completed_at=now(),updated_at=now() WHERE id=$1 AND status='running' AND paused=FALSE RETURNING id", [run.taskId]):{rowCount:0}); if(!won.rowCount){run.pending=true;await this.wait(run,1000);continue;} if (won.rowCount) await this.emit(run.taskId, "task_done", {}); if(won.rowCount)await this.pool.query("UPDATE exploration_nodes SET state='stopped',completed_at=now(),claimed_by=NULL,claimed_at=NULL,updated_at=now() WHERE task_id=$1 AND kind='intent' AND state IN('open','running','paused','blocked')",[run.taskId]); this.abort(run.taskId); return; } if(task.execution_mode==='continuous'&&!fingerprintReview&&await finishDiscoveryIfReady(this.pool,run.taskId)){this.abort(run.taskId);return;} if (goals.rowCount || !anyIntent.rowCount || fingerprintReview || task.execution_mode==='continuous'){ const sample=await this.efficiency.sample(run.taskId); const prior=(await this.pool.query('SELECT plan_signature FROM task_efficiency_state WHERE task_id=$1',[run.taskId])).rows[0]; if(!reviewDue&&(await readEfficiencyOptions(this.pool,this.config.efficiency,run.taskId)).enabled&&prior?.plan_signature===sample.revision&&!(task.execution_mode==='continuous'&&Date.now()-(run.lastDiscoveryReview??0)>=60000)){ // No graph/hint changes: a heartbeat is a cheap supervision tick. await this.efficiency.recordRound(run.taskId,sample); }else{run.lastDiscoveryReview=Date.now();await this.plan(run, task, generation,sample);} } } nextHeartbeat = Date.now() + interval; } await this.wait(run, 1000); } } /** 代码索引流水线:导入 → 下发审计 → 收线索。模型不参与,也不阻塞任何人。 */ private startCodeIntel(taskId: number, graceDeadline = 0): void { if(this.closing||this.isDeleting(taskId))return; const revision=this.intelRevisions.get(taskId)??0; const existing = this.intelTasks.get(taskId); if (existing && !existing.signal.aborted) return; // 已经在跑 const running = this.intelDone.get(taskId); if (running) { // 旧循环还在退出:等它结束再起新的,避免两个循环同时动同一个任务 const restart=()=>{if((this.intelRevisions.get(taskId)??0)===revision)this.startCodeIntel(taskId,graceDeadline);};void running.then(restart,restart); return; } const ctl = new AbortController(); this.intelTasks.set(taskId, ctl); const loop: Promise = this.codeIntelLoop(taskId, ctl.signal, graceDeadline) .catch(error => console.error('[codeintel] loop:', String(error))) .finally(() => { if (this.intelTasks.get(taskId) === ctl) this.intelTasks.delete(taskId); if (this.intelDone.get(taskId) === loop) this.intelDone.delete(taskId); this.intelLoops.delete(loop); }); this.intelDone.set(taskId, loop); this.intelLoops.add(loop); } private async codeIntelLoop(taskId: number, signal: AbortSignal, graceDeadline = 0): Promise { const interval = Math.max(5000, this.codeIntel.options.pollSeconds * 1000); // 任务收尾后仍留一段窗口把已有分析的结果收回来;收不到就留可见状态,不影响任务结论 const grace = 10 * 60 * 1000; // 重启恢复时按持久化的完成时间算剩余窗口,不从当前时间重新计时 let graceUntil = graceDeadline; const sleep = (ms: number) => new Promise(resolve => { const done=()=>{clearTimeout(timer);signal.removeEventListener('abort',done);resolve();}; const timer=setTimeout(done,ms);signal.addEventListener('abort',done,{once:true});if(signal.aborted)done(); }); while (!signal.aborted && !this.isDeleting(taskId)) { await taskActions(this.pool).wait(taskId,signal).catch(()=>{});if(signal.aborted)return; const row = (await this.pool.query('SELECT status,paused FROM tasks WHERE id=$1 AND deleted_at IS NULL', [taskId]).catch(() => null))?.rows[0]; if (!row) return; const terminal = ['done', 'failed', 'timeout'].includes(String(row.status)); if (row.status==='failed'||row.status==='timeout') {await this.codeIntel.stopTask(taskId).catch(()=>{});return;} if (terminal) { graceUntil = graceUntil || Date.now() + grace; if (Date.now() > graceUntil) { await this.codeIntel.markUnfinished(taskId).catch(() => {}); return; } } if (!row.paused) { // 终态之后只回收已有工作:不再扫描、导入或派发新的分析 await this.codeIntel.tick(taskId, signal, terminal ? 'collect' : 'full') .catch(error => console.error('[codeintel] tick:', String(error))); } await sleep(interval); } } private async workerLoop(run: RunContext, number: number): Promise { let idleMs=250; while (!run.abort.signal.aborted&&!this.settling.has(run.taskId)) { const generation = run.generation; if (!(await this.admitted(run, generation))) { await this.wait(run, 1000); continue; } const login=(await this.pool.query("SELECT a.revision,a.planner_delivered_revision,s.intent_id FROM android_login_assistance a JOIN android_sessions s ON s.id=a.session_id WHERE a.task_id=$1 AND a.state='resumed'",[run.taskId])).rows[0]; if(login&&login.revision!==login.planner_delivered_revision){await this.wait(run,500);continue;} if(!login&&(await this.pool.query('SELECT 1 FROM android_task_state WHERE task_id=$1 AND completion_requested',[run.taskId])).rowCount){await this.wait(run,1000);continue;} const claim = await claimNextIntent(controlPool(this.pool), run.taskId, `worker-task${run.taskId}-${number}`,login?Number(login.intent_id):undefined); if (!claim.claimed || !claim.intentId) { await this.wait(run, idleMs);idleMs=Math.min(2000,idleMs*2);continue; } idleMs=250; if(this.settling.has(run.taskId)){await this.pool.query("UPDATE exploration_nodes SET state='open',claimed_by=NULL,claimed_at=NULL WHERE id=$1 AND state='running'",[claim.intentId]);return;} try{await this.runIntent(run, claim.intentId, generation,`work#${number}`,`worker-task${run.taskId}-${number}`);}catch(error){ if(run.abort.signal.aborted||run.paused||generation!==run.generation)continue; if(!transientDatabaseError(error))throw error; await recoverControl(()=>this.pool.query("UPDATE exploration_nodes SET state='blocked',blocked_reason='database_interrupted_result_review_required',completed_at=now(),updated_at=now() WHERE id=$1 AND state IN ('running','open')",[claim.intentId]),run.abort.signal); }finally{await finishStrategyDispatch(this.pool,claim.intentId);} this.notify(run.taskId); } } private async plan(run: RunContext, task: TaskSnapshot, generation: number,plannedSample:ProgressSample): Promise { await runPlannerRound(this.pool,run.taskId,recovery=>this.planAttempt(run,task,generation,plannedSample,recovery),()=>this.admitted(run,generation)); } private async planAttempt(run: RunContext, task: TaskSnapshot, generation: number,plannedSample:ProgressSample,plan:PlannerPlan): Promise { const recovery=plan.strategy!=='normal'; let outcome:PlannerOutcome; let h: HostedSession | null = null; try { const spec = await this.deps.agents.resolveSessionSpec(task.agent_key || "planner",{Goal:String(task.goal??""),DataDir:this.config.dataDir}); const profile = await this.profile(task, spec); const ctx={businessKind:'planner',businessId:`task-${run.taskId}`,agentKey:'planner',taskId:run.taskId,signal:run.execution.signal,canExecute:()=>this.admitted(run,generation)}; const tools=await this.augmentedTools(['orchestration_state','search_experience','identity_status',...GRAPH_TOOLS.planner,...ASSET_TOOLS.planner,...FINGERPRINT_TOOLS,...POC_TOOLS,'android_capabilities','windows_capabilities',...WORK_CONTROLS,...TRACE_TOOLS.planner,...MODELING_REQUEST_TOOLS,'list_findings','report_finding','reverse_proxies',...(this.deps.trafficFlow?['traffic_candidates']:[])],ctx,await this.gateOptions()); h = await createHostedSession(this.pool, this.config, { kind: "planner", businessId: `task-${run.taskId}`, cwd:taskWorkDir(this.config,run.taskId),systemPrompt: spec.systemPrompt+'\n新增方向尽量填写 validation_contract(surface/action/invariant/identity_context)供各规划岗位共同去重。可参考探索价值调整投入,低分仍需留回访;不得将探索分当作严重程度或证据。专项岗位共享当前 Worker,不增加并发。'+WINDOWS_PLANNER_GUIDANCE+ANDROID_PLANNER_GUIDANCE+ADAPTIVE_PLANNER_GUIDANCE+EXPERIENCE_PLANNER_GUIDANCE+(await extensionAvailable('fingerprints',run.taskId)?FINGERPRINT_GUIDANCE:'')+(await extensionAvailable('pocs',run.taskId)?POC_GUIDANCE:'')+MODELING_GUIDANCE+artifactSpec(taskWorkDir(this.config,run.taskId))+TRAFFIC_GUIDANCE+plannerEfficiencyGuidance+plannerReverseGuidance+continuousGuidance(task), ...profile, customTools:tools, freshContext:true,activity:{taskId:run.taskId,worker:"planner"} }); run.sessions.add(h); if (!(await this.admitted(run, generation))) return; const beforePlanning=(await plannerRevisions(this.pool,run.taskId)).progress; const hints=run.hintTriggers.splice(0),triggerText=hints.map(texts=>`人新增了 ${texts.length} 条战略提示:${texts.join(";")}`).join("\n"); const overview=await this.graph.overview(run.taskId); Object.assign(overview,{team_messages:await this.team.inbox(run.taskId,'planner')}); const fingerprints=await this.deps.fingerprints?.summary(run.taskId); const pocKnowledge=await this.deps.pocs?.deliver(run.taskId,'planner'); Object.assign(overview,{adaptive:await this.adaptive.state(run.taskId),browser_environments:this.browsers?.list(run.taskId)??[],business_models:await this.modeling.catalog(run.taskId),fingerprints,poc_knowledge:pocKnowledge}); Object.assign(overview,{experience:await this.experience.deliver(run.taskId,0,'planning').catch(error=>{console.warn('[experience] planner retrieval deferred',String(error));return {enabled:true,items:[],unavailable:true};})}); if(fingerprints)await recordFingerprintDelivery(this.pool,run.taskId,'planner',fingerprints.revision,fingerprints.observations.flatMap(o=>o.observation_ids)); const flow=await this.deps.trafficFlow?.list(run.taskId); const constraints={rows:await executionConstraints(this.pool,run.taskId)}; await this.pool.query('UPDATE explorations SET round_no=round_no+1 WHERE id=(SELECT exploration_id FROM tasks WHERE id=$1)',[run.taskId]); await taskProgress(this.pool,run.taskId,recovery?'planning_recovery':'planning',plannerMessages[plan.strategy]); const summary=plannerRecoveryContext(overview,plan); const login=await loginPlannerContext(this.pool,run.taskId); await withPlannerRecovery(recovery,()=>h!.session.prompt(`${plannerRecoveryPrompt(plan)}\n任务探索图概览:\n${JSON.stringify(summary)}\n操作约束:${JSON.stringify(constraints.rows)}\n已观察流量与共享检查:${JSON.stringify(recovery?compactPlannerContext(flow??[],plan.failures):flow??[])}\n本轮触发:${triggerText}${login?'\n【用户协助登录完成】'+login.message+'\n设备会话:'+login.session_id:''}\n使用 add_intent 提交新方向;用 prove_goal 标记已被事实/发现证实的目标。没有新方向可以直接结束本轮,不能把本轮结束当成目标达成。`)); await h.flushEvents(); if (!(await this.admitted(run, generation))) return; if(h.modelFailure)throw new Error(h.modelFailure); const messages = h.session.messages as { role: string; content?: {type: string; text?: string}[]; stopReason?: string; errorMessage?: string }[]; const last = messages.filter((m) => m.role === 'assistant').at(-1); if (last?.stopReason === 'error') throw new Error(last.errorMessage || 'planner model error'); if(login)await loginPlannerDelivered(this.pool,run.taskId,login.revision); if(fingerprints)await acknowledgeFingerprintReview(this.pool,run.taskId,fingerprints.revision); if(pocKnowledge?.enabled)await pocReviewed(this.pool,run.taskId,pocKnowledge.revision); if((await this.pool.query('SELECT 1 FROM task_fingerprint_state WHERE task_id=$1 AND completion_requested UNION ALL SELECT 1 FROM task_poc_state WHERE task_id=$1 AND completion_requested UNION ALL SELECT 1 FROM android_task_state WHERE task_id=$1 AND completion_requested',[run.taskId])).rowCount)run.pending=true; const intents=await this.graph.nodes(run.taskId,'intent'); const activeIntents=intents.filter(n=>['open','running'].includes(n.state)); await taskProgress(this.pool,run.taskId,activeIntents.length?'testing':'monitoring',activeIntents.length?'本轮规划已完成,正在推进已派发的检查':'本轮检查已结束,等待新线索或下一轮规划'); await this.emit(run.taskId, 'planner_done', { intents: intents.length }); // A worker can publish new evidence while the model is thinking. Only // acknowledge the revision supplied to this planning round, never newer work. const roundSample=await this.efficiency.sample(run.taskId); await this.efficiency.recordRound(run.taskId,roundSample,plannedSample.revision); if (h.modelStopReason === 'stop') { await observeStallReview(this.pool,run.taskId,{approvals:roundSample.approvals,completedRound:true}).catch(() => { console.warn('[stall-review] round sample failed',run.taskId); }); } if(task.execution_mode!=='continuous'&&!(await this.pool.query("SELECT 1 FROM exploration_nodes WHERE task_id=$1 AND kind='goal' AND state<>'met' AND NOT payload ? 'resolution' LIMIT 1",[run.taskId])).rowCount)run.pending=true; if(task.execution_mode==='continuous'&&await finishDiscoveryIfReady(this.pool,run.taskId))this.abort(run.taskId); outcome=(await plannerRevisions(this.pool,run.taskId)).progress!==beforePlanning?'progress':activeIntents.length?'waiting':'idle'; } catch (err) { outcome=h?.modelStopReason==='length'?'length':'error'; if(task.execution_mode==='continuous')await this.pool.query('UPDATE tasks SET discovery_finish_request=NULL WHERE id=$1',[run.taskId]); if (await this.admitted(run, generation)) {await this.emit(run.taskId, 'planner_error', {error: String(err)});await this.efficiency.recordFailure(run.taskId);} } finally { if (h) { await h.dispose(); run.sessions.delete(h);this.releaseIdleSlot(run); } } return outcome; } private async decomposeGoals(run:RunContext,task:TaskSnapshot,generation:number):Promise{ let h:HostedSession|null=null; try{ await taskProgress(this.pool,run.taskId,'planning','正在分解测试目标,等待规划模型响应'); const spec=await this.deps.agents.resolveSessionSpec('goals',{EngagementDescription:String(task.description??task.goal??''),DataDir:this.config.dataDir}); const ctx={businessKind:'planner',businessId:`task-${run.taskId}-goals`,agentKey:'goals',taskId:run.taskId,signal:run.execution.signal,canExecute:()=>this.admitted(run,generation)}; h=await createHostedSession(this.pool,this.config,{kind:'planner',businessId:ctx.businessId,cwd:taskWorkDir(this.config,run.taskId),systemPrompt:spec.systemPrompt+WINDOWS_PLANNER_GUIDANCE+ANDROID_PLANNER_GUIDANCE+artifactSpec(taskWorkDir(this.config,run.taskId))+goalEfficiencyGuidance+continuousGuidance(task),...await this.profile(task,spec),customTools:await this.augmentedTools([...GRAPH_TOOLS.goals,'android_capabilities','windows_capabilities'],ctx,await this.gateOptions()),freshContext:true,activity:{taskId:run.taskId,worker:"planner"}}); run.sessions.add(h);if(!(await this.admitted(run,generation)))return; await h.session.prompt(`任务目标:\n${task.goal}\n${(await readTaskPolicy(this.pool,run.taskId)).freescope?'Freescope:不提取操作约束,直接用 set_goals 提交可核验的高影响目标。':'使用 set_constraints 抽取明确的操作约束,再用 set_goals 提交最终可核验目标。'}`);await h.flushEvents();if(h.modelFailure)throw new Error(h.modelFailure); }catch(e){if(await this.admitted(run,generation))await this.emit(run.taskId,'goals_error',{error:String(e)});} finally{if(h){await h.dispose();run.sessions.delete(h);this.releaseIdleSlot(run);}} if(!(await this.admitted(run,generation)))return; const existing=await this.graph.nodes(run.taskId,'goal'); if(!existing.length){await this.graph.addGoal(run.taskId,{text:task.goal},'system');await this.emit(run.taskId,'goals_fallback',{reason:'LLM 未提交目标,原始任务目标作为单目标'});} } private async gateOptions(){ return {rules:await this.deps.intercept.gateRules(),getRules:()=>this.deps.intercept.gateRules(),requestApproval:(id:number,reason?:string,ms?:number,action?:'deny'|'allow',signal?:AbortSignal)=>this.deps.intercept.requestApproval(id,reason,ms,action,signal), judge:(tool:string,params:Record,context:ToolContext)=>runJudge({pool:this.pool,config:this.config,tool,params,context})}; } private async profile(task: TaskSnapshot, spec: {agentKey?:string;provider?: string; modelId?: string}): Promise<{provider?: string; modelId?: string}> { const selected=await new TaskModelResolver(this.pool,this.config,await getPiRuntime(this.config),Number(task.id),spec.agentKey??'planner').current(); return {provider:selected.model.provider,modelId:selected.model.id}; } private async augmentedTools(keys:string[],ctx:ToolContext,gate:GateOptions):Promise{ const tools=await assembleTools(this.pool,keys,ctx,gate); if(!this.deps.mcp)return tools; const augmentation=await augmentSession(this.pool,this.deps.mcp,this.deps.skills,ctx,gate); return bindAugmentation([...tools,...augmentation.tools],augmentation); } private async refreshExperienceContext(taskId:number,intentId:number):Promise{ const work=this.work.get(intentId);if(!work||Date.now()-(work.experienceCheckedAt??0)<15000)return; work.experienceCheckedAt=Date.now(); let revoked:number[]=[]; try{ revoked=await this.experience.revoked(taskId,intentId); const packet=await this.experience.deliver(taskId,intentId,'evidence_update'); work.knowledge.offer('experience',packet,'[历史经验候选更新,先核对当前适用条件]\n'+JSON.stringify(packet),async()=>{}); }catch(error){console.warn('[experience] context refresh deferred',String(error));return;} const revision=JSON.stringify(revoked); if(revoked.length&&work.revokedExperience!==revision){ work.revokedExperience=revision; const text='[历史经验来源已撤回] 经验 '+revoked.map(id=>'#'+id).join('、')+' 的来源证据或版本已失效。停止依赖历史结论,重新核对当前任务的前提和证据;保留已取得的真实观察。'; if(work.session)await work.session.session.steer(text);else work.steering.push(text); throw Error('历史经验来源已失效,本次工具动作未执行;请先重新核对当前证据。'); } } private async workerTools(run: RunContext, intentId: number, generation: number, signal: AbortSignal,workerName:string): Promise { const taskId = run.taskId; // G04:ctx 携带 taskId/intentId,业务 handler 从 ctx 解析归属(见 tools/business.ts) const canExecute=async(toolKey?:string)=>{ if(signal.aborted)return false; const admitted=await this.admitted(run,generation); // At the deadline, the bounded wrap-up may persist existing observations. // It must not admit another network request, shell command or worker. if(!admitted){ if(!['record_fact','report_finding','save_worker_checkpoint'].includes(toolKey??'')||!run.releaseSlot||run.abort.signal.aborted||run.paused||run.generation!==generation||this.isDeleting(taskId))return false; if(!(await this.pool.query("SELECT 1 FROM tasks WHERE id=$1 AND status='running' AND paused=FALSE AND queued=FALSE AND deleted_at IS NULL AND archived=FALSE AND deadline_at<=now()",[taskId])).rowCount)return false; } return !!(await this.pool.query("SELECT 1 FROM exploration_nodes WHERE id=$1 AND task_id=$2 AND state='running' AND assessment_state='active'",[intentId,taskId])).rowCount; }; const ctx = { businessKind: "worker", businessId: `task-${taskId}-intent-${intentId}`, agentKey: "worker", runId: `task-${taskId}`, deviceHostGeneration: `task-${taskId}-generation-${generation}`, taskId, intentId, workerName, signal, cwd:path.join(this.config.dataDir,'workspace','tasks',String(taskId)), canExecute,beforeExecute:async()=>{const work=this.work.get(intentId);if(work?.finishing)throw new Error('当前意图已收口,请输出最后摘要,不再执行工具');await this.refreshExperienceContext(taskId,intentId);if(work?.session)await work.knowledge.flush(async text=>{await work.session!.session.steer(text);});if(work?.skipTools){work.skipTools--;throw new Error('规划者已注入纠偏指令,本次动作未执行;请根据新指令重新规划下一步。');}} }; // G06:统一门选项——拦截规则(含超时)+ 审批 + judge 兜底(tools/judge.ts 真实模型裁决) const gateOpts = { rules: await this.deps.intercept.gateRules(),getRules:()=>this.deps.intercept.gateRules(), requestApproval: (tcid: number, reason?: string, timeoutMs?: number, timeoutAction?: "deny" | "allow", signal?: AbortSignal) => this.deps.intercept.requestApproval(tcid, reason, timeoutMs, timeoutAction, signal), judge: (toolKey: string, params: Record,context:ToolContext) => runJudge({ pool: this.pool, config: this.config, tool: toolKey, params,context }), }; const reviewing=!!(await this.pool.query("SELECT 1 FROM finding_verifications WHERE review_intent_id=$1 AND state IN('pending','running')",[intentId])).rowCount; return this.augmentedTools([...ADAPTIVE_TOOLS,...EXPERIENCE_TOOLS,...IDENTITY_TOOLS,...GRAPH_TOOLS.worker,...ASSET_TOOLS.worker,...FINGERPRINT_TOOLS,...POC_TOOLS,...TRACE_TOOLS.worker,...HANDOFF_TOOLS,...MODELING_REQUEST_TOOLS,...CODE_INTEL_TOOLS,...HUNT_TOOLS,...INTEL_TOOLS,...ANDROID_TOOLS,...WINDOWS_TOOLS,'analysis_capabilities','list_findings','http_request','insert_assets',...(reviewing?[]:['report_finding']),...REVERSE_PROXY_TOOLS,...(this.browsers?['task_browser']:[]),...(this.deps.trafficFlow?CHECK_TOOLS:[])],ctx,gateOpts); } private async runIntent(run: RunContext, intentId: number, generation: number,workerName:string,leaseOwner:string): Promise { let h: HostedSession | null = null; let ok = false,dbInterrupted=false; let budgetLimited:import('../../pi/budget.ts').BudgetExit|undefined; let routedFailure:import('../llm/task-stream.ts').RouterFailure|undefined; const work={taskId:run.taskId,abort:new AbortController(),session:undefined as HostedSession|undefined,steering:[] as string[],skipTools:0,finishing:false,knowledge:new KnowledgeInbox(),fingerprintRevision:-1,pocRevision:-1,modelingRevision:''};this.work.set(intentId,work); const signal = AbortSignal.any([run.execution.signal,work.abort.signal]); const control=(operation:()=>Promise)=>recoverControl(operation,signal); const cancel=()=>{void h?.session.abort().catch(console.error);};signal.addEventListener('abort',cancel,{once:true}); try { if (!(await this.admitted(run, generation))) return; const spec = await control(()=>this.deps.agents.resolveSessionSpec('worker',{WorkerName:workerName,DataDir:this.config.dataDir})); const task = (await control(()=>this.pool.query('SELECT * FROM tasks WHERE id=$1',[run.taskId]))).rows[0]; const intent = (await control(()=>this.pool.query('SELECT title,payload FROM exploration_nodes WHERE id=$1',[intentId]))).rows[0]; // Display-only progress never invalidates a claimed intent or repeats a // model/tool effect when the projection connection is temporarily busy. await taskProgress(backgroundPool(this.pool),run.taskId,'testing',`${workerName.replace(/^work#/, 'Worker #')}:${String(intent?.title??intent?.payload?.summary??'执行检查').slice(0,140)}`).catch(error=>console.warn('[task-progress]',String(error))); const constraints=await control(()=>executionConstraints(this.pool,run.taskId)); h = await createHostedSession(this.pool, this.config, {kind:'worker', businessId:`task-${run.taskId}-intent-${intentId}`,cwd:taskWorkDir(this.config,run.taskId,intentId),systemPrompt:spec.systemPrompt+ADAPTIVE_WORKER_GUIDANCE+EXPERIENCE_WORKER_GUIDANCE+WINDOWS_GUIDANCE+ANDROID_GUIDANCE+BROWSER_GUIDANCE+(await extensionAvailable('fingerprints',run.taskId)?FINGERPRINT_GUIDANCE:'')+(await extensionAvailable('pocs',run.taskId)?POC_GUIDANCE:'')+MODELING_GUIDANCE+continuousGuidance(task)+artifactSpec(taskWorkDir(this.config,run.taskId,intentId),true)+TRAFFIC_GUIDANCE+reverseWorkerGuidance+'\n用提供的工具完成任务,真实观察用 record_fact 写回探索图;漏洞用 report_finding 登记。\n业务模型目录:'+JSON.stringify(await this.modeling.catalog(run.taskId))+'\n操作约束:'+JSON.stringify(constraints),...await this.profile(task,spec),customTools:await this.workerTools(run,intentId,generation,signal,workerName),activity:{taskId:run.taskId,nodeId:intentId,worker:workerName}}); run.sessions.add(h); work.session=h; if (signal.aborted||!(await this.admitted(run, generation))) return; for(const message of work.steering)await h.session.steer(message);work.steering=[]; const packet={...await this.handoffs.packet(run.taskId,intentId),experience:await this.experience.deliver(run.taskId,intentId,'worker_start').catch(error=>{console.warn('[experience] worker retrieval deferred',String(error));return {enabled:true,items:[],unavailable:true};}),browser_environments:this.browsers?.list(run.taskId)??[],business_logic_scenario:(await this.pool.query("SELECT s.* FROM business_logic_scenarios s JOIN exploration_nodes n ON n.task_id=s.task_id AND (n.payload->>'scenario_id')=s.id::text WHERE n.id=$1 AND s.task_id=$2",[intentId,run.taskId])).rows[0]??null}; work.knowledge.seed('experience',packet.experience); if(packet.fingerprints){work.knowledge.seed('fingerprints',packet.fingerprints);work.fingerprintRevision=packet.fingerprints.revision;await recordFingerprintDelivery(this.pool,run.taskId,'worker',packet.fingerprints.revision,packet.fingerprints.observations.flatMap(o=>o.observation_ids),intentId);} if(packet.poc_knowledge?.enabled){work.knowledge.seed('pocs',packet.poc_knowledge);work.pocRevision=packet.poc_knowledge.revision;await pocDelivery(this.pool,run.taskId,'worker',packet.poc_knowledge.revision,packet.poc_knowledge.candidates.map(c=>Number(c.id)),intentId);} if (signal.aborted || !await this.admitted(run, generation)) return; await h.session.prompt(`执行意图 #${intentId}。当前结构化交接包:\n${JSON.stringify(packet)}`); await h.flushEvents(); const last = h.session.messages.filter((m) => m.role === 'assistant').at(-1) as {stopReason?:string;errorMessage?:string;content?:{type:string}[]}|undefined; if(h.modelFailure)throw new Error(h.modelFailure); if(workerCompletion(last,h.budgetExit)==='budget_limited'){budgetLimited=h.budgetExit;return;} if(workerCompletion(last)!=='complete')throw new Error(last?.errorMessage || 'worker did not complete'); await this.pool.query("UPDATE finding_verifications SET state='needs_evidence',summary='独立复核会话结束但未提交完整验证结论;原始发现保留',finished_at=now() WHERE review_intent_id=$1 AND state IN('pending','running')",[intentId]); await this.pool.query("UPDATE findings f SET verification_status='needs_evidence' FROM finding_verifications v WHERE v.finding_id=f.id AND v.review_intent_id=$1 AND v.state='needs_evidence' AND f.evidence_version=v.evidence_version",[intentId]); ok = true; } catch (err) { dbInterrupted=transientDatabaseError(err); routedFailure=h?.llmFailure; if(!routedFailure&&String(err).includes('LLM profile chain exhausted'))routedFailure={routerHandled:true,chainExhausted:true}; if (await this.admitted(run,generation)) await recoverControl(()=>this.pool.query("UPDATE exploration_nodes SET last_error=$2 WHERE id=$1 AND state='running'",[intentId,String(err).slice(0,300)]),run.abort.signal); } finally { if (h) { const last=h.session.messages.filter(message=>message.role==='assistant').at(-1) as {content?:{type:string;text?:string}[]}|undefined; await this.handoffs.observe(run.taskId,intentId,{outcome:ok?'completed':budgetLimited?'budget_limited':signal.aborted?'interrupted':'error',summary:(last?.content??[]).filter(block=>block.type==='text').map(block=>block.text??'').join('\n')}).catch(()=>console.warn('[handoff] runtime observation deferred; graph and native checkpoint retained')); try { await h.dispose(); } catch (error) { console.error("[worker] session cleanup failed", error); } finally { run.sessions.delete(h); this.releaseIdleSlot(run); } } this.browsers?.releaseWorker(run.taskId,'task-'+run.taskId+'-intent-'+intentId); signal.removeEventListener('abort',cancel);if(this.work.get(intentId)===work)this.work.delete(intentId); // Final claim cleanup must run after cancellation; an aborted control retry // would skip the CAS below and leave a dead worker marked running. if(await releaseModelingIntent(this.pool,run.taskId,intentId,leaseOwner))return; if(work.abort.signal.aborted){await this.pool.query("UPDATE exploration_nodes SET state='stopped',completed_at=now(),updated_at=now() WHERE id=$1 AND state='running'",[intentId]);await this.emit(run.taskId,'intent_stopped',{intentId});return;} if (!(await this.admitted(run,generation))) { // CAS does not resurrect nodes already stopped by task control. await this.pool.query(`UPDATE exploration_nodes n SET state=CASE WHEN t.status IN ('done','failed','timeout') OR t.deleted_at IS NOT NULL THEN 'stopped' ELSE 'open' END, claimed_by=NULL,claimed_at=NULL,attempts=CASE WHEN t.paused THEN GREATEST(n.attempts-1,0) ELSE n.attempts END,updated_at=now() FROM tasks t WHERE t.id=n.task_id AND n.id=$1 AND n.state='running'`,[intentId]); } else if(dbInterrupted){ await recoverControl(()=>this.pool.query("UPDATE exploration_nodes SET state='blocked',blocked_reason='database_interrupted_result_review_required',completed_at=now(),updated_at=now() WHERE id=$1 AND state='running'",[intentId]),run.abort.signal); await this.emit(run.taskId,'intent_blocked',{intentId,reason:'database_interrupted_result_review_required'}); } else if (budgetLimited) { const blocked=await markWorkerBudgetBlocked(this.pool,run.taskId,intentId,budgetLimited); if(blocked.changed)await this.emit(run.taskId,'intent_blocked',{intentId,reason:blocked.reason,message:blocked.message}); } else if (ok) { const done = await recoverControl(()=>this.pool.query(`UPDATE exploration_nodes n SET state='done',updated_at=now() FROM tasks t WHERE n.id=$1 AND n.task_id=t.id AND n.state='running' AND t.status='running' AND t.paused=FALSE RETURNING n.id`,[intentId]),run.abort.signal); if (done.rowCount) await this.emit(run.taskId,'intent_done',{intentId}); } else { if(routedFailure?.routerHandled){await this.pool.query("UPDATE exploration_nodes SET state='blocked',blocked_reason=$2,completed_at=now(),updated_at=now() WHERE id=$1 AND state='running'",[intentId,routedFailure.chainExhausted?'llm_quota_exhausted':null]);await this.emit(run.taskId,'intent_blocked',{intentId,reason:routedFailure.chainExhausted?'llm_quota_exhausted':'model_router_error'});return;} const result = await retryIntent(this.pool,intentId,3); if(result!=='unchanged')await this.emit(run.taskId,result==='requeued'?'intent_retry':'intent_exhausted',{intentId}); } } } private async runModeling(run:RunContext,task:TaskSnapshot):Promise{ while(!run.abort.signal.aborted){ if(run.paused){await this.wait(run,100);continue;} const generation=run.generation; let h:HostedSession|undefined; try{ if(!await this.admitted(run,generation))return; const record=await this.modeling.get(run.taskId); const competing=(await this.pool.query(`SELECT 1 FROM business_model_runs r JOIN tasks t ON t.id=r.task_id WHERE r.system_id=$1 AND r.task_id<>$2 AND r.execution_key=$3 AND t.status IN ('created','running','paused') AND t.deleted_at IS NULL LIMIT 1`,[record.system_id,run.taskId,record.execution_key])).rowCount; if(competing)throw new Error('该系统已有另一建模任务,请使用现有任务或发起新的增量建模'); const agent=await this.deps.agents.get('modeler'); if(!agent||agent.enabled===false)throw new Error('业务建模 Agent 已禁用'); const spec=await this.deps.agents.resolveSessionSpec('modeler'); const ctx:ToolContext={businessKind:'worker',businessId:`task-${run.taskId}-modeling`,agentKey:'modeler',taskId:run.taskId,signal:run.execution.signal,canExecute:()=>this.admitted(run,generation)}; const gates={...await this.gateOptions(),enforceInterceptScope:true}; const tools=await this.augmentedTools([...MODELER_TOOLS,'api_model_read','http_request'],ctx,gates); if(!tools.some(t=>t.name==='http_request'))throw new Error('业务建模的 HTTP 请求工具已禁用,无法检查目标入口'); const entrance=await (this.deps.modelingProbe?this.deps.modelingProbe(record.target,run.execution.signal):probeModelingEntrance(record.target,async()=>{ const result=await runTool(this.pool,'http_request',{url:record.target,method:'GET'},ctx,gates); // GateResult uses "blocked" for both policy denial and handler errors. // Only an audited execution failure is eligible for a transport retry. const audit=result.status==='blocked'&&result.toolCallId?(await this.pool.query('SELECT execution_ms FROM tool_calls WHERE id=$1',[result.toolCallId])).rows[0]:undefined; return {...result,executionFailed:audit?.execution_ms!==undefined&&audit.execution_ms!==null}; },run.execution.signal)); if(!await this.admitted(run,generation))continue; await this.emit(run.taskId,'modeling_entrance_checked',{status:entrance.status}); const constraints=await executionConstraints(this.pool,run.taskId); const sourceContext=record.source_task_id&&task.network_mode==='jump'?'\n来源任务资料受跳板工作区隔离限制,不要尝试读取其他任务目录。本次只使用宿主入口响应、可用工具及本建模工作目录内的证据。':record.source_task_id?`\n来源资料目录(只读参考):${taskWorkDir(this.config,Number(record.source_task_id),Number(record.source_intent_id)||0)}。可读取其中已有的 JS、抓包与分析产物,写入仍使用本次建模工作目录。只对本次指定目标建模;原任务说明用于限定范围。`:''; await this.pool.query('UPDATE business_model_runs SET finish_requested=FALSE WHERE task_id=$1',[run.taskId]); h=await createHostedSession(this.pool,this.config,{kind:'worker',businessId:ctx.businessId,cwd:taskWorkDir(this.config,run.taskId),systemPrompt:spec.systemPrompt+MODELING_EXECUTION_GUIDANCE+artifactSpec(taskWorkDir(this.config,run.taskId))+sourceContext+'\n操作约束:'+JSON.stringify(constraints),...await this.profile(task,spec),customTools:tools,freshContext:true,activity:{taskId:run.taskId,worker:'modeler'}}); run.sessions.add(h); const executionSignal=run.execution.signal; const cancel=()=>{void h?.session.abort();};executionSignal.addEventListener('abort',cancel,{once:true}); try{ if(!await this.admitted(run,generation))continue; await h.session.prompt(`执行业务建模任务。目标:${record.target}\n宿主已检查入口,HTTP ${entrance.status};复用以下响应,不必重复检查连通性:\n${entrance.body}\n系统 id:${record.system_id},环境:${record.environment},身份标签:${record.auth_context||'未指定'}。这些标签不包含登录凭据。\n说明:${task.goal}\n${task.description??''}\n已有草稿接口目录:${JSON.stringify(record.endpoints.slice(0,300))}\n已有实体:${JSON.stringify(record.entities).slice(0,12000)}\n历史基准版本:${record.base_version_id??'无'}。按 api_model_read(system_id, path) 读取需要核验的历史接口。\n先核验已有结果,再分批 api_model_submit。响应必须包含 responses;增量按路径及 HTTP 方法合并。以实际响应、页面、JS 或工作目录中的证据为依据,区分真实验证、静态推断和 mock 观察;未能验证的内容必须标注。\n完成后调用 api_model_done,明确覆盖范围与缺口。缺少凭据时说明缺口,不要编造结果。`); await h.flushEvents(); }finally{executionSignal.removeEventListener('abort',cancel);} if(!await this.admitted(run,generation))continue; const staged=await this.modeling.get(run.taskId); if(h.budgetExit&&!staged.finish_requested){ const timed=h.budgetExit.reason==='timeout'; await this.modeling.fail(run.taskId,timed?'timeout':'failed',timed?'业务建模达到执行或收尾时间上限;已提交草稿保留,主测试继续':'业务建模达到轮次上限;已提交草稿保留,主测试继续'); await this.emit(run.taskId,timed?'modeling_timeout':'modeling_failed',{reason:h.budgetExit.reason,draft_preserved:true});return; } if(h.modelFailure)throw new Error(h.modelFailure); await this.modeling.publish(run.taskId); await this.emit(run.taskId,'task_done',{kind:'modeling'}); return; }catch(e){ if(await this.admitted(run,generation)){ await this.modeling.fail(run.taskId,'failed',String(e).slice(0,500)); await this.emit(run.taskId,'modeling_failed',{error:String(e),draft_preserved:true}); return; } }finally{if(h){await h.dispose();run.sessions.delete(h);this.releaseIdleSlot(run);}} } } private async emit(taskId: number, event: string, payload: Record): Promise { const {appendEvent} = await import('../../events/ledger.ts'); await appendEvent(this.pool,this.config.dataDir+'/events-dlq.jsonl',{business_kind:'task',business_id:String(taskId),event_type:event,payload}); } }