Download src/workflow/node-dispatch.js from VanyaJ/bada-terminal: direct link, hf CLI and curl.
- Browser
- Download file 24.1 kB
-
https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/workflow/node-dispatch.js
- Command line
-
hf download hf://VanyaJ/bada-terminal/src/workflow/node-dispatch.js
-
curl -L -o node-dispatch.js https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/workflow/node-dispatch.js
24.1 kB
| // ๋ธ๋ผ์ฐ์ ์์ฐ ์ ์ง drain: docs/specs/bong-browser-use.md (v1.4.0) | |
| // ์ค๋ช ๋ฌธ์: docs/specs/bada-code-quality.md (v1.0.0) | |
| // ์คํ ์ํ ๋งต์ ์์ง์ด ์์ ํ๊ณ ์ด ๋ชจ๋์ ์ง์ ๋ ์ฑ ์๋ง ์ฒ๋ฆฌํ๋ค. | |
| const db = require('../../knowledge-db'); | |
| const { isUncertainCliFailure } = require('../utils/cli-storage-error'); | |
| const agentRunner = require('../agent-runner'); | |
| function createNodeDispatch(dependencies) { | |
| const { activeRuns, log, syncAgentsMd } = dependencies; | |
| return { | |
| async onNodeTrigger(runId) { | |
| const run = activeRuns.get(runId); | |
| if (!run || run.status !== 'running') return; | |
| if (run.isExecuting) { | |
| if (run.logStream && run.logStream.writable) { | |
| run.logStream.write(`[Engine] Warning: Concurrency guard blocked re-entry trigger for run ${runId}\n`); | |
| } | |
| return; | |
| } | |
| run.isExecuting = true; | |
| let nodeId = ''; | |
| let nodeName = 'Unknown Node'; | |
| let taskId = null; | |
| let node = null; | |
| try { | |
| if (run.currentNodeIndex >= run.sortedNodeIds.length) { | |
| this.completeWorkflow(runId); | |
| return; | |
| } | |
| nodeId = run.sortedNodeIds[run.currentNodeIndex]; | |
| // Skip sequential execution of child nodes that ran in parallel | |
| if (run.parallelExecutedNodeIds && run.parallelExecutedNodeIds.has(nodeId)) { | |
| run.logStream.write(`[Engine] Skipping Node "${nodeId}" because it was already executed in parallel.\n`); | |
| run.parallelExecutedNodeIds.delete(nodeId); | |
| run.currentNodeIndex++; | |
| setImmediate(() => this.emit('node:trigger', runId)); | |
| return; | |
| } | |
| node = run.nodes.find(n => n.id === nodeId); | |
| if (!node) { | |
| this.handleWorkflowFailure(runId, new Error(`๋ ธ๋ '${nodeId}'๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค.`)); | |
| return; | |
| } | |
| nodeName = node.name; | |
| require("../services/runtime-usage-ledger").refresh(run); | |
| require("../services/runtime-usage-ledger").checkAncestors(run); | |
| // Budget Guard | |
| const isAgentType = ['agent', 'pty_agent', 'orchestrator', 'reviewer'].includes(node.type); | |
| if (isAgentType) { | |
| run.agentRunCount = (run.agentRunCount || 0) + 1; | |
| let graph = {}; | |
| try { | |
| const runRecord = db.getWorkflowRun ? db.getWorkflowRun(runId) : null; | |
| const workflow = runRecord ? db.getWorkflow(runRecord.workflow_id) : null; | |
| graph = workflow && typeof workflow.graph_json === 'string' ? JSON.parse(workflow.graph_json) : (workflow?.graph || {}); | |
| } catch (e) { | |
| graph = {}; | |
| } | |
| const maxAgentRuns = node.config?.maxAgentRuns || graph.maxAgentRuns || 5; | |
| if (run.agentRunCount > maxAgentRuns) { | |
| run.status = 'pausing'; | |
| run.logStream.write(`[Engine] Agent run budget exceeded (${run.agentRunCount} > ${maxAgentRuns}). Pausing workflow run.\n`); | |
| try { | |
| db.saveTriageItem(run.projectId, { | |
| run_id: run.runId, | |
| source_type: 'workflow', | |
| error_message: `Budget Exceeded: Agent run limit reached (${maxAgentRuns} runs)`, | |
| ai_analysis: `### ๐จ Budget Exceeded (์์ฐ ์ด๊ณผ)\n- **์ฌ์ **: ์์ด์ ํธ ์คํ ํ๋(${maxAgentRuns}ํ)๋ฅผ ์ด๊ณผํ์ฌ ์๋ ์ผ์์ ์ง ๋์์ต๋๋ค.\n- **ํด๊ฒฐ ๋ฐฉ์**: ์ํฌํ๋ก์ฐ ๋ฃจํ ์ค๊ณ๋ฅผ ๊ฒํ ํ๊ฑฐ๋ ํ๋ ๊ฐ์ ์ํฅ ์กฐ์ ํ์ญ์์ค.\n\n**์ต๊ทผ ์ํ**: ๋ฃจํ๋ฐฑ ํ์๊ฐ ์ด๊ณผ๋์์ต๋๋ค.`, | |
| status: 'pending' | |
| }); | |
| } catch (dbErr) { | |
| log.error('[Engine] Failed to save budget exceeded triage item:', dbErr); | |
| } | |
| this.emit('node:progress', { runId, nodeId, status: 'pausing', error: 'Agent run budget exceeded' }); | |
| run.journal.appendStep(runId, `[Engine] Agent ์คํ ํ๋(${maxAgentRuns}ํ) ์ด๊ณผ๋ก ์์ ์ด ์ผ์์ ์ง๋์์ต๋๋ค.`); | |
| await this.suspendWorkflowRun(runId, Object.assign(new Error('Agent run budget exceeded'), { code: 'WORKFLOW_PAUSED' })); | |
| return; | |
| } | |
| // Token Cost Budget Guard | |
| const maxBudget = node.config?.maxBudget || graph.maxBudget || 1.0; | |
| if ((run.cumulativeCost || 0) > maxBudget) { | |
| run.status = 'pausing'; | |
| run.logStream.write(`[Engine] Token budget exceeded ($${(run.cumulativeCost || 0).toFixed(4)} > $${maxBudget.toFixed(2)}). Pausing workflow run.\n`); | |
| try { | |
| db.saveTriageItem(run.projectId, { | |
| run_id: run.runId, | |
| source_type: 'workflow', | |
| error_message: `Budget Exceeded: Token budget limit reached ($${maxBudget.toFixed(2)})`, | |
| ai_analysis: `### ๐จ Budget Exceeded (ํ ํฐ ์์ฐ ์ด๊ณผ)\n- **์ฌ์ **: ๋์ ํ ํฐ ๋น์ฉ($${(run.cumulativeCost || 0).toFixed(4)})์ด ์ค์ ๋ ํ๋($${maxBudget.toFixed(2)})๋ฅผ ์ด๊ณผํ์ฌ ์๋ ์ผ์์ ์ง ๋์์ต๋๋ค.\n- **ํด๊ฒฐ ๋ฐฉ์**: API ์ฌ์ฉ๋์ ๊ฒํ ํ๊ฑฐ๋ ์์ฐ ํ๋(maxBudget) ๊ฐ์ ๋๋ฆฌ์ญ์์ค.\n\n**์ต๊ทผ ์ํ**: ๋์ ์คํ ๋น์ฉ์ด ์ด๊ณผ๋์์ต๋๋ค.`, | |
| status: 'pending' | |
| }); | |
| } catch (dbErr) { | |
| log.error('[Engine] Failed to save budget exceeded triage item:', dbErr); | |
| } | |
| this.emit('node:progress', { runId, nodeId, status: 'pausing', error: 'Token budget exceeded' }); | |
| run.journal.appendStep(runId, `[Engine] ํ ํฐ ์์ฐ ํ๋($${maxBudget.toFixed(2)}) ์ด๊ณผ๋ก ์์ ์ด ์ผ์์ ์ง๋์์ต๋๋ค.`); | |
| await this.suspendWorkflowRun(runId, Object.assign(new Error('Token budget exceeded'), { code: 'WORKFLOW_PAUSED' })); | |
| return; | |
| } | |
| } | |
| // Workflow Run Budget Guard (B1) | |
| if (run.runBudgetUsd && run.usage && (run.usage.costUsd || 0) >= run.runBudgetUsd) { | |
| if (run.logStream && run.logStream.writable) { | |
| run.logStream.write(`[Engine] Workflow run budget exceeded ($${(run.usage.costUsd || 0).toFixed(4)} >= $${run.runBudgetUsd.toFixed(2)}). Terminating workflow run.\n`); | |
| } | |
| try { | |
| db.saveTriageItem(run.projectId, { | |
| run_id: run.runId, | |
| source_type: 'workflow', | |
| error_message: `BUDGET_EXCEEDED: run budget limit reached ($${run.runBudgetUsd.toFixed(2)})`, | |
| ai_analysis: `### ๐จ Budget Exceeded (๋ฐ ์์ฐ ์ด๊ณผ)\n- **์ฌ์ **: ๋์ ์คํ ๋น์ฉ($${(run.usage.costUsd || 0).toFixed(4)})์ด ์ค์ ๋ ๋ฐ ์์ฐ ํ๋($${run.runBudgetUsd.toFixed(2)})๋ฅผ ๋ฌ์ฑ/์ด๊ณผํ์ฌ ์คํจ ์ฒ๋ฆฌ ๋์์ต๋๋ค.\n- **ํด๊ฒฐ ๋ฐฉ์**: ์์ฐ ์ค์ ์ ๊ฒํ ํ๊ฑฐ๋ ๋น์ฉ์ ์ํฅ ์กฐ์ ํ์ญ์์ค.`, | |
| status: 'pending' | |
| }); | |
| } catch (dbErr) { | |
| log.error('[Engine] Failed to save workflow run budget exceeded triage item:', dbErr); | |
| } | |
| this.emit('node:progress', { runId, nodeId, status: 'failed', error: 'BUDGET_EXCEEDED' }); | |
| run.journal.appendStep(runId, `[Engine] ๋ฐ ์์ฐ ํ๋($${run.runBudgetUsd.toFixed(2)}) ์ด๊ณผ๋ก ์์ ์ด ์คํจ ์ค๋จ๋์์ต๋๋ค.`); | |
| this.handleWorkflowFailure(runId, Object.assign(new Error(`BUDGET_EXCEEDED: run budget limit reached ($${run.runBudgetUsd.toFixed(2)})`), { code: 'BUDGET_EXCEEDED' })); | |
| return; | |
| } | |
| run.currentNodeId = nodeId; | |
| syncAgentsMd(run); | |
| try { | |
| db.checkpointWorkflowRun(runId, 'running', nodeId, run.runData); | |
| } catch (dbErr) { | |
| run.logStream.write(`[Engine] Checkpoint database write failed: ${dbErr.message}\n`); | |
| dbErr.code = 'WORKFLOW_CHECKPOINT'; | |
| throw dbErr; | |
| } | |
| run.logStream.write(`\n[Node ${run.currentNodeIndex + 1}/${run.sortedNodeIds.length}] Executing: ${node.name} (${node.type})\n`); | |
| this.emit('node:progress', { runId, nodeId, status: 'running', name: node.name }); | |
| run.journal.appendStep(runId, `๋ ธ๋ [${node.name}] (${node.type}) ์คํ์ ์์ํฉ๋๋ค.`); | |
| const taskQuestion = node.config ? (node.config.prompt || `Run step ${node.name} (${node.type})`) : `Run step ${node.name}`; | |
| const incomingEdges = run.edges.filter(e => e.target === nodeId); | |
| run.nodeTasks = run.nodeTasks || {}; | |
| const parentTaskIds = incomingEdges.map(e => run.nodeTasks[e.source]).filter(Boolean); | |
| const agentId = (node.config && (node.config.agentProfileId || node.config.agentId)) || node.type; | |
| taskId = 'task_' + runId + '_' + nodeId + '_' + Date.now(); | |
| run.nodeTasks[nodeId] = taskId; | |
| // NATS ๋์ ๊ตฌ๋ ํ์ฑํ | |
| try { | |
| const natsManager = require("../services/bada-nats-manager"); | |
| natsManager.subscribeAgentMessages(runId, agentId); | |
| } catch (natsErr) { | |
| log.warn('Failed to register dynamic NATS subscriber', null, natsErr); | |
| } | |
| run.journal.createTaskNote(runId, taskId, agentId, taskQuestion, parentTaskIds); | |
| try { | |
| db.enqueueWorkflowTask(taskId, runId, nodeId, agentId, node.config || {}); | |
| db.completeWorkflowTask(taskId, 'running', null, null); | |
| } catch (dbErr) { | |
| log.error('[Engine] Failed to write task to DB:', dbErr.message); | |
| } | |
| const interpolatedConfig = this.interpolate(node.config || {}, run.runData); | |
| let evolutionContext = ''; | |
| for (const [key, val] of Object.entries(run.runData)) { | |
| if (key.startsWith('harness_') && val && val.parentAgentNodeId === nodeId && val.errorLog) { | |
| evolutionContext += `\n\nโ ๏ธ [์ด์ ๊ฒ์ฆ ์คํจ ํผ๋๋ฐฑ ๋ฐ ์งํ ๋ก๊ทธ] โ ๏ธ\n์ด์ ์คํ์ ๊ฒ์ฆ ๊ฒฐ๊ณผ ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค. ์๋ ์๋ฌ ๋ก๊ทธ๋ฅผ ๋ถ์ํ์ฌ ์์ธ์ ์์ ํ์ญ์์ค:\n- ์๋ฌ ๋ก๊ทธ:\n${val.errorLog}\n`; | |
| } | |
| } | |
| if (evolutionContext) { | |
| interpolatedConfig.prompt = (interpolatedConfig.prompt || '') + evolutionContext; | |
| run.logStream.write(`[Engine] Evolved failure context injected for node "${nodeId}"\n`); | |
| } | |
| let reviewerContext = ''; | |
| for (const [key, val] of Object.entries(run.runData)) { | |
| if (key.startsWith('reviewer_') && key.endsWith('_feedback') && val) { | |
| const reviewerId = key.substring('reviewer_'.length, key.length - '_feedback'.length); | |
| const hasEdge = run.edges.some(e => e.source === nodeId && e.target === reviewerId); | |
| if (hasEdge) { | |
| reviewerContext += `\n\nโ ๏ธ [๋ฆฌ๋ทฐ์ด ๋ฐ๋ ค ํผ๋๋ฐฑ] โ ๏ธ\n์ด์ ๊ตฌํ์ ๋ํด ๋ฆฌ๋ทฐ์ด ์์ด์ ํธ(${reviewerId})๊ฐ ๋ฐ๋ คํ์ต๋๋ค. ์๋ ํผ๋๋ฐฑ์ ์ฐธ๊ณ ํ์ฌ ์ฝ๋๋ฅผ ์์ ํ์ญ์์ค:\n- ํผ๋๋ฐฑ:\n${val}\n`; | |
| } | |
| } | |
| } | |
| if (reviewerContext) { | |
| interpolatedConfig.prompt = (interpolatedConfig.prompt || '') + reviewerContext; | |
| run.logStream.write(`[Engine] Reviewer feedback context injected for node "${nodeId}"\n`); | |
| } | |
| if (node.type === 'orchestrator' || node.type === 'agent' || node.type === 'pty_agent') { | |
| const history = await agentRunner.runHistorySearchAgent(run.workflowId, run.runId, run.logStream, run.projectId, run.journal); | |
| if (history.successfulRuns.length > 0 || history.failedRuns.length > 0) { | |
| const header = `\n\n=== [๊ณผ๊ฑฐ ์ ๋ณด ํ์ ์์ด์ ํธ ์ ๊ณต] ์ด์ ์คํ ์ด๋ ฅ ๋ฐ ์์ฌ๊ฒฐ์ ์ธ๊ณผ๊ด๊ณ ===\n`; | |
| const footer = `\n==========================================================\n`; | |
| let body; | |
| if (history.historyContext && history.historyContext.trim()) { | |
| // 1์ฐจ ๊ฒฝ๋ก: MemoryFacade๊ฐ ํฉ์ฑํ ์ปจํ ์คํธ(๋ฆฌํฌํธ ์ค๋ํซ + ์คํจ triage ์ง๋จ ํฌํจ) | |
| body = history.historyContext; | |
| } else { | |
| // ํด๋ฐฑ: record ๋ฐฐ์ด์์ ๋ณ์ ์ํ + ๋ฆฌํฌํธ ๋ณธ๋ฌธ์ ์ง์ ์กฐ๋ฆฝ | |
| body = ''; | |
| history.successfulRuns.forEach(r => { | |
| body += `- [์ฑ๊ณต ๋ฐ: ${r.runId}] ๋ณ์ ์ํ: ${JSON.stringify(r.variables)}\n`; | |
| if (r.reportContext) body += ` ์ด์ ์คํ ์ธ๊ณผ ๋ถ์:\n${r.reportContext}\n`; | |
| }); | |
| history.failedRuns.forEach(r => { | |
| body += `- [์คํจ ๋ฐ: ${r.runId}] ๋ณ์ ์ํ: ${JSON.stringify(r.variables)}\n`; | |
| if (r.reportContext) body += ` ์ด์ ์คํ ์ธ๊ณผ ๋ถ์:\n${r.reportContext}\n`; | |
| }); | |
| } | |
| interpolatedConfig.prompt = (interpolatedConfig.prompt || '') + header + body + footer; | |
| } | |
| } | |
| const provId = 'prov_' + runId + '_' + nodeId + '_' + Date.now(); | |
| const parentNodeIds = incomingEdges.map(e => e.source); | |
| // [NiFi Provenance] ๋ ธ๋ ์คํ ์ ์ ๋ ฅ ๋ฐ์ดํฐ ์ค๋ ์ท ๊ธฐ๋ก | |
| try { | |
| db.saveWorkflowProvenance({ | |
| id: provId, | |
| run_id: runId, | |
| node_id: nodeId, | |
| parent_node_ids: parentNodeIds, | |
| input_flow_file: run.runData, | |
| status: 'running', | |
| started_at: new Date().toISOString() | |
| }); | |
| } catch (provErr) { | |
| run.logStream.write(`[Provenance Engine] Failed to save initial provenance: ${provErr.message}\n`); | |
| } | |
| run.runData[`node_timeline_${nodeId}`] = { | |
| startedAt: new Date().toISOString(), | |
| endedAt: null, | |
| agentProfile: node.config?.agentProfileId || node.config?.agent_profile_id || null | |
| }; | |
| let output = null; | |
| let attempt = 0; | |
| const maxAttempts = (node.config && typeof node.config.retry_count === 'number') ? node.config.retry_count + 1 : 1; | |
| const retryDelay = (node.config && typeof node.config.retry_delay === 'number') ? node.config.retry_delay : 5; | |
| while (attempt < maxAttempts) { | |
| try { | |
| run.abortController?.signal.throwIfAborted(); | |
| attempt++; | |
| if (attempt > 1) { | |
| run.logStream.write(`[Engine] Retrying node "${nodeId}" (Attempt ${attempt}/${maxAttempts}) in ${retryDelay}s...\n`); | |
| await require('timers/promises').setTimeout(retryDelay * 1000, undefined, { signal: run.abortController?.signal }); | |
| try { | |
| db.saveWorkflowProvenance({ | |
| id: provId, | |
| run_id: runId, | |
| node_id: nodeId, | |
| status: 'running', | |
| retry_count: attempt - 1 | |
| }); | |
| } catch (e) { /* intentional: ํ์ผ ์กฐํ ์คํจ ์ ๋ฌด์ */ } | |
| } | |
| output = await require('./node-operation').execute(run, node, () => this.executeNode(run, node, interpolatedConfig)); | |
| run.abortController?.signal.throwIfAborted(); | |
| break; | |
| } catch (execErr) { | |
| if (run.abortController?.signal.aborted || isUncertainCliFailure(execErr) || ['WORKFLOW_PAUSED', 'DECISION_GATE_DENIED', 'HARNESS_CONFIGURATION'].includes(execErr.code) || node.type === 'decision_gate') throw execErr; | |
| run.logStream.write(`[Engine] Node "${nodeId}" execution attempt ${attempt} failed: ${execErr.message}\n`); | |
| if (attempt >= maxAttempts) { | |
| // [NiFi Provenance] ์ต์ข ์๋ ์คํจ ์ ์ํ ์ ๋ฐ์ดํธ | |
| try { | |
| db.saveWorkflowProvenance({ | |
| id: provId, | |
| run_id: runId, | |
| node_id: nodeId, | |
| status: 'failed', | |
| output_flow_file: { error: execErr.message }, | |
| ended_at: new Date().toISOString(), | |
| retry_count: attempt - 1 | |
| }); | |
| } catch (provErr) { /* intentional: ํ์ผ ์กฐํ ์คํจ ์ ๋ฌด์ */ } | |
| throw execErr; | |
| } | |
| } | |
| } | |
| // [NiFi Provenance] ๋ ธ๋ ์คํ ์ฑ๊ณต ์ ์ถ๋ ฅ ์ค๋ ์ท ๊ธฐ๋ก | |
| try { | |
| db.saveWorkflowProvenance({ | |
| id: provId, | |
| run_id: runId, | |
| node_id: nodeId, | |
| status: 'success', | |
| output_flow_file: output, | |
| ended_at: new Date().toISOString() | |
| }); | |
| } catch (provErr) { /* intentional: ํ์ผ ์กฐํ ์คํจ ์ ๋ฌด์ */ } | |
| if (run.runData[`node_timeline_${nodeId}`]) { | |
| run.runData[`node_timeline_${nodeId}`].endedAt = new Date().toISOString(); | |
| } | |
| run.runData[nodeId] = { status: 'success', output }; | |
| run.logStream.write(`[Node ${nodeId}] Completed successfully.\n`); | |
| this.emit('node:progress', { runId, nodeId, status: 'completed', output }); | |
| if (taskId) { | |
| try { | |
| db.completeWorkflowTask(taskId, 'completed', output, null); | |
| } catch (dbErr) { | |
| log.error('[Engine] Failed to write task completion to DB:', dbErr.message); | |
| } | |
| } | |
| run.journal.appendStep(runId, `๋ ธ๋ [${node.name}] ์คํ ์๋ฃ. ๊ฒฐ๊ณผ ๋ฐ์ดํฐ: ${JSON.stringify(output)}`); | |
| const taskDecision = output ? (output.strategy || output.decision || JSON.stringify(output)) : 'Success'; | |
| run.journal.updateTaskNoteDecision(taskId, taskDecision, JSON.stringify(output, null, 2)); | |
| if (node.type === 'reviewer' && output && (output.approved === false || output.approved === 'false')) { | |
| run.runData[`reviewer_${nodeId}_feedback`] = output.feedback || '๋ฐ๋ ค ํผ๋๋ฐฑ์ด ์ง์ ๋์ง ์์์ต๋๋ค.'; | |
| const incomingEdges = run.edges.filter(e => e.target === nodeId); | |
| const predecessorId = incomingEdges.length > 0 ? incomingEdges[0].source : null; | |
| const predecessorIndex = predecessorId ? run.sortedNodeIds.indexOf(predecessorId) : -1; | |
| if (predecessorIndex !== -1) { | |
| const backRouteKey = `reviewer_backroute_${nodeId}_${predecessorId}`; | |
| run.runData[backRouteKey] = (run.runData[backRouteKey] || 0) + 1; | |
| const maxBackRoutes = (node.config && node.config.maxReviewerRetries) || 3; | |
| if (run.runData[backRouteKey] > maxBackRoutes) { | |
| // [P15 A3] ๋ฐ๋ ค ์ํ ์์ง ์ ์ฒ๋ฆฌ โ ๊ณผ๊ฑฐ์๋ ๋ฐ๋ ค๋ ์ฐ์ถ๋ฌผ์ด "๋ฌด์ธ ํต๊ณผ" | |
| // (์น์ธ๋ ๊ฒ์ฒ๋ผ ๋ค์ ๋ ธ๋๋ก ์งํ)๋์ด ํ์ง ๊ฒ์ดํธ๊ฐ ์ฐํ๋๋ ๊ฒฐํจ์ด ์์๋ค. | |
| // config.onExhaust๋ก ๋์์ ์ ํํ๋ค: 'fail'(์ค๋จ) | 'hitl'(์ฌ๋ ํ๋จ ์ด๊ด) | | |
| // 'proceed'(๋ช ์์ ์ ํ ์์๋ง โ ํ์ง ๋ฏธ๋ฌ ์ฐ์ถ๋ฌผ ๋ฌด์ธ ํต๊ณผ ์ํ ์ธ์ง ํ์). | |
| // โ v2 ์ ํ ์๋ฃ: ๊ธฐ๋ณธ๊ฐ์ 'fail'๋ก ์ ํํ์ฌ ํ์ง ๊ฒ์ดํธ ์ฐํ๋ฅผ ์์ฒ ์ฐจ๋จ. | |
| // ๊ธฐ์กด 'proceed' ๋์์ด ํ์ํ๋ฉด ๋ ธ๋ config์ onExhaust:'proceed' ๋ช ์. | |
| // ์ค๊ณ ๊ทผ๊ฑฐ: docs/DESIGN_P15_MULTIAGENT_LOOP_IMPROVEMENTS.md ยง3 A3 | |
| const onExhaust = (node.config && node.config.onExhaust) || 'fail'; | |
| const exhaustMsg = `[Reviewer] ์ต๋ ๋ฐ๋ ค ํ์(${maxBackRoutes}ํ) ์ด๊ณผ (onExhaust=${onExhaust}). ๋ง์ง๋ง ํผ๋๋ฐฑ: ${output.feedback || '์์'}`; | |
| run.logStream.write(exhaustMsg + '\n'); | |
| run.journal.appendStep(runId, exhaustMsg); | |
| // ์์ค์ปฌ๋ ์ด์ ์ฌ์ ๋ฅผ ํ์ค ์์น์ ๊ธฐ๋ก โ HITL ๋ ธ๋/๋ฆฌ์ํธ๊ฐ ๊ณตํต ์ฐธ์กฐ(A4 ์ฐ๊ณ) | |
| run.runData._escalation = { | |
| reason: 'REVIEWER_EXHAUSTED', | |
| nodeId, | |
| rejections: run.runData[backRouteKey] - 1, | |
| lastFeedback: output.feedback || null | |
| }; | |
| if (onExhaust === 'fail') { | |
| // ๋ ธ๋ ์คํจ ๊ฒฝ๋ก(catch โ on_failure ์ ๋ต)๋ก ์ ํฉํ๊ฒ ํ๋ ค๋ณด๋ธ๋ค | |
| throw new Error(`REVIEWER_EXHAUSTED: ๋ฆฌ๋ทฐ์ด ๋ฐ๋ ค ${maxBackRoutes}ํ ์ด๊ณผ โ ํ์ง ๊ธฐ์ค ๋ฏธ๋ฌ๋ก ์ค๋จ`); | |
| } | |
| if (onExhaust === 'hitl') { | |
| // ๊ทธ๋ํ์ hitl ๋ ธ๋๊ฐ ์์ผ๋ฉด ๊ทธ ๋ ธ๋๋ก ์ ํํด ์ฌ๋ ํ๋จ์ผ๋ก ์ด๊ดํ๋ค | |
| const hitlIndex = run.sortedNodeIds.findIndex((nid) => { | |
| const n = run.nodes.find((x) => x.id === nid); | |
| return n && n.type === 'hitl'; | |
| }); | |
| if (hitlIndex !== -1) { | |
| run.logStream.write(`[Reviewer] HITL ๋ ธ๋(${run.sortedNodeIds[hitlIndex]})๋ก ์์ค์ปฌ๋ ์ด์ ํฉ๋๋ค.\n`); | |
| run.currentNodeIndex = hitlIndex; | |
| setImmediate(() => this.emit('node:trigger', runId)); | |
| return; | |
| } | |
| // hitl ๋ ธ๋๊ฐ ์์ผ๋ฉด fail ํด๋ฐฑ(๋ฌด์ธ ํต๊ณผ๋ณด๋ค ์์ ํ ์ชฝ์ผ๋ก) | |
| throw new Error(`REVIEWER_EXHAUSTED: ๋ฐ๋ ค ${maxBackRoutes}ํ ์ด๊ณผ + HITL ๋ ธ๋ ๋ถ์ฌ โ ์ค๋จ(fail ํด๋ฐฑ)`); | |
| } | |
| // 'proceed'(๊ธฐ์กด ๋์): ์งํํ๋ ๋ค์ด์คํธ๋ฆผ์ด ์๋ณํ ์ ์๊ฒ ํ๋๊ทธ๋ฅผ ๋จ๊ธด๋ค | |
| run.runData._reviewerExhausted = true; | |
| run.logStream.write(`[Reviewer] โ ๊ฒฝ๊ณ : ๋ฐ๋ ค๋ ์ฐ์ถ๋ฌผ์ด ๊ทธ๋๋ก ์งํ๋ฉ๋๋ค(_reviewerExhausted=true). onExhaust:'fail' ์ค์ ์ ๊ถ์ฅํฉ๋๋ค.\n`); | |
| // Fall through to next node instead of back-routing | |
| } else { | |
| run.logStream.write(`[Reviewer] ๋ฐ๋ ค๋จ (${run.runData[backRouteKey]}/${maxBackRoutes}): ${output.feedback || '์ด์ ๋ฏธ์ง์ '}. ${predecessorId} ๋ ธ๋๋ก ๋ฐฑ-๋ผ์ฐํ ํฉ๋๋ค.\n`); | |
| run.journal.appendStep(runId, `[Reviewer] ๋ฐ๋ ค๋จ (${run.runData[backRouteKey]}/${maxBackRoutes}): ${predecessorId} ๋ ธ๋๋ก ๋ฐฑ-๋ผ์ฐํ ํฉ๋๋ค.`); | |
| run.currentNodeIndex = predecessorIndex; | |
| setImmediate(() => this.emit('node:trigger', runId)); | |
| return; | |
| } | |
| } else { | |
| run.logStream.write(`[Reviewer] ๋ฐ๋ ค๋์์ผ๋ ์ด์ ๋ฉ์ปค ๋ ธ๋๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค. ๋ค์ ๋จ๊ณ๋ก ์งํํฉ๋๋ค.\n`); | |
| } | |
| } | |
| run.currentNodeIndex++; | |
| setImmediate(() => this.emit('node:trigger', runId)); | |
| } catch (err) { | |
| const checkRun = activeRuns.get(runId); | |
| if (!checkRun || checkRun.status !== 'running') { | |
| return; | |
| } | |
| if (run.runData[`node_timeline_${nodeId}`]) { | |
| run.runData[`node_timeline_${nodeId}`].endedAt = new Date().toISOString(); | |
| } | |
| const onFailureStrategy = (node && node.config && node.config.on_failure) || 'abort'; | |
| if (nodeId) { | |
| run.logStream.write(`[Node ${nodeId}] Failed: ${err.message}. (Strategy: ${onFailureStrategy})\n`); | |
| this.emit('node:progress', { runId, nodeId, status: 'failed', error: err.message }); | |
| run.journal.appendStep(runId, `๋ ธ๋ [${nodeName}] ์คํ ์คํจ. ์๋ฌ: ${err.message}`); | |
| if (taskId) run.journal.updateTaskNoteDecision(taskId, `Failed: ${err.message}`, `Error: ${err.message}`); | |
| if (taskId) { | |
| try { | |
| db.completeWorkflowTask(taskId, 'failed', null, err.message); | |
| } catch (dbErr) { | |
| log.error('[Engine] Failed to write task failure to DB:', dbErr.message); | |
| } | |
| } | |
| } | |
| if (onFailureStrategy === 'continue' && !isUncertainCliFailure(err) && node?.type !== 'decision_gate' && !['WORKFLOW_PAUSED', 'DECISION_GATE_DENIED', 'HARNESS_CONFIGURATION', 'WORKFLOW_CHECKPOINT'].includes(err.code)) { | |
| run.logStream.write(`[Engine] Strategy 'continue' triggered. Moving to next node.\n`); | |
| run.currentNodeIndex++; | |
| setImmediate(() => this.emit('node:trigger', runId)); | |
| } else { | |
| this.handleWorkflowFailure(runId, err); | |
| } | |
| } finally { | |
| const activeRun = activeRuns.get(runId); | |
| if (activeRun) { | |
| activeRun.isExecuting = false; | |
| } | |
| } | |
| } | |
| }; | |
| } | |
| module.exports = { createNodeDispatch }; | |