@covibes/zeroshot 5.4.0 → 5.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +8 -465
- package/cli/index.js +101 -5231
- package/package.json +16 -130
- package/CHANGELOG.md +0 -537
- package/cli/commands/providers.js +0 -149
- package/cli/lib/first-run.js +0 -211
- package/cli/lib/update-checker.js +0 -281
- package/cli/message-formatter-utils.js +0 -75
- package/cli/message-formatters-normal.js +0 -275
- package/cli/message-formatters-watch.js +0 -181
- package/cluster-templates/base-templates/debug-workflow.json +0 -375
- package/cluster-templates/base-templates/full-workflow.json +0 -581
- package/cluster-templates/base-templates/single-worker.json +0 -63
- package/cluster-templates/base-templates/worker-validator.json +0 -208
- package/cluster-templates/conductor-bootstrap.json +0 -124
- package/docker/zeroshot-cluster/Dockerfile +0 -152
- package/docker/zeroshot-cluster/pre-baked-deps.json +0 -28
- package/lib/completion.js +0 -174
- package/lib/docker-config.js +0 -220
- package/lib/git-remote-utils.js +0 -165
- package/lib/id-detector.js +0 -56
- package/lib/provider-defaults.js +0 -62
- package/lib/provider-detection.js +0 -59
- package/lib/provider-names.js +0 -57
- package/lib/settings/claude-auth.js +0 -78
- package/lib/settings.js +0 -503
- package/lib/stream-json-parser.js +0 -10
- package/scripts/fix-node-pty-permissions.js +0 -75
- package/scripts/record-demo.sh +0 -279
- package/scripts/setup-merge-queue.sh +0 -170
- package/scripts/test-install.sh +0 -40
- package/scripts/validate-templates.js +0 -100
- package/src/agent/agent-config.js +0 -246
- package/src/agent/agent-context-builder.js +0 -444
- package/src/agent/agent-hook-executor.js +0 -599
- package/src/agent/agent-lifecycle.js +0 -743
- package/src/agent/agent-stuck-detector.js +0 -256
- package/src/agent/agent-task-executor.js +0 -1690
- package/src/agent/agent-trigger-evaluator.js +0 -67
- package/src/agent/output-extraction.js +0 -217
- package/src/agent/output-reformatter.js +0 -175
- package/src/agent/schema-utils.js +0 -146
- package/src/agent-wrapper.js +0 -579
- package/src/agents/git-pusher-template.js +0 -285
- package/src/attach/attach-client.js +0 -438
- package/src/attach/attach-server.js +0 -543
- package/src/attach/index.js +0 -35
- package/src/attach/protocol.js +0 -220
- package/src/attach/ring-buffer.js +0 -121
- package/src/attach/socket-discovery.js +0 -267
- package/src/claude-task-runner.js +0 -574
- package/src/config-router.js +0 -80
- package/src/config-validator.js +0 -1925
- package/src/copy-worker.js +0 -43
- package/src/input-helpers.js +0 -65
- package/src/isolation-manager.js +0 -1471
- package/src/issue-providers/README.md +0 -305
- package/src/issue-providers/azure-devops-provider.js +0 -273
- package/src/issue-providers/base-provider.js +0 -232
- package/src/issue-providers/github-provider.js +0 -179
- package/src/issue-providers/gitlab-provider.js +0 -241
- package/src/issue-providers/index.js +0 -196
- package/src/issue-providers/jira-provider.js +0 -239
- package/src/ledger.js +0 -631
- package/src/lib/safe-exec.js +0 -88
- package/src/logic-engine.js +0 -223
- package/src/message-bus-bridge.js +0 -139
- package/src/message-bus.js +0 -249
- package/src/name-generator.js +0 -232
- package/src/orchestrator.js +0 -2815
- package/src/preflight.js +0 -639
- package/src/process-metrics.js +0 -608
- package/src/providers/anthropic/cli-builder.js +0 -73
- package/src/providers/anthropic/index.js +0 -204
- package/src/providers/anthropic/models.js +0 -23
- package/src/providers/anthropic/output-parser.js +0 -177
- package/src/providers/base-provider.js +0 -251
- package/src/providers/capabilities.js +0 -60
- package/src/providers/google/cli-builder.js +0 -55
- package/src/providers/google/index.js +0 -116
- package/src/providers/google/models.js +0 -24
- package/src/providers/google/output-parser.js +0 -101
- package/src/providers/index.js +0 -91
- package/src/providers/openai/cli-builder.js +0 -133
- package/src/providers/openai/index.js +0 -136
- package/src/providers/openai/models.js +0 -21
- package/src/providers/openai/output-parser.js +0 -143
- package/src/providers/opencode/cli-builder.js +0 -42
- package/src/providers/opencode/index.js +0 -103
- package/src/providers/opencode/models.js +0 -55
- package/src/providers/opencode/output-parser.js +0 -122
- package/src/schemas/sub-cluster.js +0 -185
- package/src/status-footer.js +0 -1026
- package/src/sub-cluster-wrapper.js +0 -601
- package/src/task-runner.js +0 -30
- package/src/template-resolver.js +0 -372
- package/src/tui/CHANGES.txt +0 -133
- package/src/tui/LAYOUT.md +0 -261
- package/src/tui/README.txt +0 -192
- package/src/tui/TWO-LEVEL-NAVIGATION.md +0 -186
- package/src/tui/data-poller.js +0 -349
- package/src/tui/demo.js +0 -208
- package/src/tui/formatters.js +0 -129
- package/src/tui/index.js +0 -193
- package/src/tui/keybindings.js +0 -324
- package/src/tui/layout.js +0 -334
- package/src/tui/renderer.js +0 -184
- package/task-lib/attachable-watcher.js +0 -309
- package/task-lib/claude-recovery.js +0 -156
- package/task-lib/commands/clean.js +0 -50
- package/task-lib/commands/episodes.js +0 -105
- package/task-lib/commands/get-log-path.js +0 -23
- package/task-lib/commands/kill.js +0 -32
- package/task-lib/commands/list.js +0 -105
- package/task-lib/commands/logs.js +0 -453
- package/task-lib/commands/resume.js +0 -42
- package/task-lib/commands/run.js +0 -57
- package/task-lib/commands/schedule.js +0 -105
- package/task-lib/commands/scheduler-cmd.js +0 -96
- package/task-lib/commands/schedules.js +0 -148
- package/task-lib/commands/status.js +0 -44
- package/task-lib/commands/unschedule.js +0 -16
- package/task-lib/completion.js +0 -9
- package/task-lib/config.js +0 -8
- package/task-lib/name-generator.js +0 -230
- package/task-lib/package.json +0 -3
- package/task-lib/runner.js +0 -201
- package/task-lib/scheduler.js +0 -252
- package/task-lib/store.js +0 -529
- package/task-lib/tui/formatters.js +0 -215
- package/task-lib/tui/index.js +0 -197
- package/task-lib/tui/layout.js +0 -111
- package/task-lib/tui/renderer.js +0 -129
- package/task-lib/tui.js +0 -425
- package/task-lib/watcher.js +0 -226
|
@@ -1,599 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AgentHookExecutor - Hook transformation and execution
|
|
3
|
-
*
|
|
4
|
-
* Provides:
|
|
5
|
-
* - Hook execution (publish_message, stop_cluster, etc.)
|
|
6
|
-
* - Template variable substitution
|
|
7
|
-
* - Transform script execution in VM sandbox
|
|
8
|
-
* - Logic scripts for conditional config (like triggers)
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
const vm = require('vm');
|
|
12
|
-
const { execSync } = require('../lib/safe-exec'); // Enforces timeouts
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Deep merge two objects, with source taking precedence
|
|
16
|
-
* @param {Object} target - Base object
|
|
17
|
-
* @param {Object} source - Override object
|
|
18
|
-
* @returns {Object} Merged object
|
|
19
|
-
*/
|
|
20
|
-
function deepMerge(target, source) {
|
|
21
|
-
if (!source || typeof source !== 'object') return target;
|
|
22
|
-
if (!target || typeof target !== 'object') return source;
|
|
23
|
-
|
|
24
|
-
const result = { ...target };
|
|
25
|
-
for (const key of Object.keys(source)) {
|
|
26
|
-
if (
|
|
27
|
-
source[key] &&
|
|
28
|
-
typeof source[key] === 'object' &&
|
|
29
|
-
!Array.isArray(source[key]) &&
|
|
30
|
-
target[key] &&
|
|
31
|
-
typeof target[key] === 'object' &&
|
|
32
|
-
!Array.isArray(target[key])
|
|
33
|
-
) {
|
|
34
|
-
result[key] = deepMerge(target[key], source[key]);
|
|
35
|
-
} else {
|
|
36
|
-
result[key] = source[key];
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return result;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
async function parseResultDataForHookLogic({ agent, result }) {
|
|
43
|
-
if (!result?.output) return null;
|
|
44
|
-
try {
|
|
45
|
-
return await agent._parseResultOutput(result.output);
|
|
46
|
-
} catch (parseError) {
|
|
47
|
-
agent._log(
|
|
48
|
-
`⚠️ Hook logic: result parsing failed, continuing with null: ${parseError.message}`
|
|
49
|
-
);
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
async function resolveHookConfigWithLogic({ hook, agent, context, result }) {
|
|
55
|
-
if (!hook.logic) return hook.config;
|
|
56
|
-
|
|
57
|
-
const resultData = await parseResultDataForHookLogic({ agent, result });
|
|
58
|
-
const overrides = evaluateHookLogic({
|
|
59
|
-
logic: hook.logic,
|
|
60
|
-
resultData,
|
|
61
|
-
agent,
|
|
62
|
-
context,
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
if (!overrides) {
|
|
66
|
-
return hook.config;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
agent._log(`Hook logic returned overrides: ${JSON.stringify(overrides)}`);
|
|
70
|
-
return deepMerge(hook.config, overrides);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
async function resolvePublishMessage({ hook, agent, context, cluster, result }) {
|
|
74
|
-
if (hook.transform) {
|
|
75
|
-
return executeTransform({
|
|
76
|
-
transform: hook.transform,
|
|
77
|
-
context,
|
|
78
|
-
agent,
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
const effectiveConfig = await resolveHookConfigWithLogic({
|
|
83
|
-
hook,
|
|
84
|
-
agent,
|
|
85
|
-
context,
|
|
86
|
-
result,
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
return substituteTemplate({
|
|
90
|
-
config: effectiveConfig,
|
|
91
|
-
context,
|
|
92
|
-
agent,
|
|
93
|
-
cluster,
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Execute a hook
|
|
99
|
-
* THROWS on failure - no silent errors
|
|
100
|
-
* @param {Object} params - Hook execution parameters
|
|
101
|
-
* @param {Object} params.hook - Hook configuration
|
|
102
|
-
* @param {Object} params.agent - Agent instance
|
|
103
|
-
* @param {Object} params.message - Triggering message
|
|
104
|
-
* @param {Object} params.result - Agent execution result
|
|
105
|
-
* @param {Object} params.messageBus - Message bus instance
|
|
106
|
-
* @param {Object} params.cluster - Cluster object
|
|
107
|
-
* @param {Object} params.orchestrator - Orchestrator instance
|
|
108
|
-
* @returns {Promise<void>}
|
|
109
|
-
*/
|
|
110
|
-
async function executeHook(params) {
|
|
111
|
-
const { hook, agent, message, result, cluster } = params;
|
|
112
|
-
|
|
113
|
-
if (!hook) {
|
|
114
|
-
return;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// Build context for hook execution
|
|
118
|
-
const context = {
|
|
119
|
-
result,
|
|
120
|
-
triggeringMessage: message,
|
|
121
|
-
agent,
|
|
122
|
-
cluster,
|
|
123
|
-
};
|
|
124
|
-
|
|
125
|
-
// NO try/catch - errors must propagate
|
|
126
|
-
if (hook.action === 'publish_message') {
|
|
127
|
-
const messageToPublish = await resolvePublishMessage({
|
|
128
|
-
hook,
|
|
129
|
-
agent,
|
|
130
|
-
context,
|
|
131
|
-
cluster,
|
|
132
|
-
result,
|
|
133
|
-
});
|
|
134
|
-
agent._publish(messageToPublish);
|
|
135
|
-
return;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
if (hook.action === 'execute_system_command') {
|
|
139
|
-
throw new Error('execute_system_command not implemented');
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
throw new Error(`Unknown hook action: ${hook.action}`);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
function getAccessedFields(script) {
|
|
146
|
-
return [...script.matchAll(/result\.([a-zA-Z_]+)/g)].map((m) => m[1]);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
function logTransformParseFailure({ agent, context, parseError }) {
|
|
150
|
-
const taskId = context.result?.taskId || agent.currentTaskId || 'UNKNOWN';
|
|
151
|
-
console.error(`\n${'='.repeat(80)}`);
|
|
152
|
-
console.error(`🔴 TRANSFORM SCRIPT BLOCKED - RESULT PARSING FAILED`);
|
|
153
|
-
console.error(`${'='.repeat(80)}`);
|
|
154
|
-
console.error(`Agent: ${agent.id}, Role: ${agent.role}`);
|
|
155
|
-
console.error(`TaskID: ${taskId}`);
|
|
156
|
-
console.error(`Parse error: ${parseError.message}`);
|
|
157
|
-
console.error(`Output (last 500 chars): ${(context.result.output || '').slice(-500)}`);
|
|
158
|
-
console.error(`${'='.repeat(80)}\n`);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
function logMissingResultFields({ agent, context, accessedFields, missingFields, resultData }) {
|
|
162
|
-
const taskId = context.result?.taskId || agent.currentTaskId || 'UNKNOWN';
|
|
163
|
-
console.error(`\n${'='.repeat(80)}`);
|
|
164
|
-
console.error(`🔴 TRANSFORM SCRIPT BLOCKED - MISSING REQUIRED FIELDS`);
|
|
165
|
-
console.error(`${'='.repeat(80)}`);
|
|
166
|
-
console.error(`Agent: ${agent.id}, Role: ${agent.role}, TaskID: ${taskId}`);
|
|
167
|
-
console.error(`Script accesses: ${accessedFields.join(', ')}`);
|
|
168
|
-
console.error(`Missing from result: ${missingFields.join(', ')}`);
|
|
169
|
-
console.error(`Result keys: ${Object.keys(resultData).join(', ')}`);
|
|
170
|
-
console.error(`Result data: ${JSON.stringify(resultData, null, 2)}`);
|
|
171
|
-
console.error(`${'='.repeat(80)}\n`);
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
async function parseTransformResultData({ context, agent, script, scriptUsesResult }) {
|
|
175
|
-
if (context.result?.output) {
|
|
176
|
-
let resultData = null;
|
|
177
|
-
try {
|
|
178
|
-
resultData = await agent._parseResultOutput(context.result.output);
|
|
179
|
-
} catch (parseError) {
|
|
180
|
-
logTransformParseFailure({ agent, context, parseError });
|
|
181
|
-
throw new Error(
|
|
182
|
-
`Transform script cannot run: result parsing failed. ` +
|
|
183
|
-
`Agent: ${agent.id}, Error: ${parseError.message}`
|
|
184
|
-
);
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
const accessedFields = getAccessedFields(script);
|
|
188
|
-
const missingFields = accessedFields.filter((f) => resultData[f] === undefined);
|
|
189
|
-
if (missingFields.length > 0) {
|
|
190
|
-
logMissingResultFields({ agent, context, accessedFields, missingFields, resultData });
|
|
191
|
-
const taskId = context.result?.taskId || agent.currentTaskId || 'UNKNOWN';
|
|
192
|
-
throw new Error(
|
|
193
|
-
`Transform script accesses undefined fields: ${missingFields.join(', ')}. ` +
|
|
194
|
-
`Agent ${agent.id} (task ${taskId}) output missing required fields. ` +
|
|
195
|
-
`Check agent's jsonSchema and output format.`
|
|
196
|
-
);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
return resultData;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
if (scriptUsesResult) {
|
|
203
|
-
const taskId = context.result?.taskId || agent.currentTaskId || 'UNKNOWN';
|
|
204
|
-
const outputLength = (context.result?.output || '').length;
|
|
205
|
-
throw new Error(
|
|
206
|
-
`Transform script uses result.* variables but no output was captured. ` +
|
|
207
|
-
`Agent: ${agent.id}, TaskID: ${taskId}, Iteration: ${agent.iteration}, ` +
|
|
208
|
-
`Output length: ${outputLength}. ` +
|
|
209
|
-
`Check that the task completed successfully and the get-log-path command exists.`
|
|
210
|
-
);
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
return null;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
function buildTransformSandbox({ resultData, context, agent }) {
|
|
217
|
-
const helpers = {
|
|
218
|
-
getConfig: require('../config-router').getConfig,
|
|
219
|
-
};
|
|
220
|
-
|
|
221
|
-
return {
|
|
222
|
-
result: resultData,
|
|
223
|
-
triggeringMessage: context.triggeringMessage,
|
|
224
|
-
helpers,
|
|
225
|
-
JSON,
|
|
226
|
-
console: {
|
|
227
|
-
log: (...args) => agent._log('[transform]', ...args),
|
|
228
|
-
error: (...args) => console.error('[transform]', ...args),
|
|
229
|
-
warn: (...args) => console.warn('[transform]', ...args),
|
|
230
|
-
},
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
function runTransformScript(script, sandbox) {
|
|
235
|
-
const vmContext = vm.createContext(sandbox);
|
|
236
|
-
const wrappedScript = `(function() { ${script} })()`;
|
|
237
|
-
|
|
238
|
-
try {
|
|
239
|
-
return vm.runInContext(wrappedScript, vmContext, { timeout: 5000 });
|
|
240
|
-
} catch (err) {
|
|
241
|
-
throw new Error(`Transform script error: ${err.message}`);
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
function validateTransformResult(result) {
|
|
246
|
-
if (!result || typeof result !== 'object') {
|
|
247
|
-
throw new Error(
|
|
248
|
-
`Transform script must return an object with topic and content, got: ${typeof result}`
|
|
249
|
-
);
|
|
250
|
-
}
|
|
251
|
-
if (!result.topic) {
|
|
252
|
-
throw new Error(`Transform script result must have a 'topic' property`);
|
|
253
|
-
}
|
|
254
|
-
if (!result.content) {
|
|
255
|
-
throw new Error(`Transform script result must have a 'content' property`);
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
function validateClusterOperationsResult(result, agent) {
|
|
260
|
-
if (result.topic !== 'CLUSTER_OPERATIONS') return;
|
|
261
|
-
|
|
262
|
-
const operations = result.content?.data?.operations;
|
|
263
|
-
if (!operations) {
|
|
264
|
-
console.error(`\n${'='.repeat(80)}`);
|
|
265
|
-
console.error(`🔴 CLUSTER_OPERATIONS MALFORMED - MISSING OPERATIONS ARRAY`);
|
|
266
|
-
console.error(`${'='.repeat(80)}`);
|
|
267
|
-
console.error(`Agent: ${agent.id}`);
|
|
268
|
-
console.error(`Result: ${JSON.stringify(result, null, 2)}`);
|
|
269
|
-
console.error(`${'='.repeat(80)}\n`);
|
|
270
|
-
throw new Error(
|
|
271
|
-
`CLUSTER_OPERATIONS message missing operations array. ` +
|
|
272
|
-
`Agent ${agent.id} transform script returned invalid structure.`
|
|
273
|
-
);
|
|
274
|
-
}
|
|
275
|
-
if (!Array.isArray(operations)) {
|
|
276
|
-
throw new Error(`CLUSTER_OPERATIONS.operations must be an array, got: ${typeof operations}`);
|
|
277
|
-
}
|
|
278
|
-
if (operations.length === 0) {
|
|
279
|
-
throw new Error(`CLUSTER_OPERATIONS.operations is empty - no operations to execute`);
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
for (let i = 0; i < operations.length; i++) {
|
|
283
|
-
const op = operations[i];
|
|
284
|
-
if (!op || !op.action) {
|
|
285
|
-
throw new Error(`CLUSTER_OPERATIONS.operations[${i}] missing required 'action' field`);
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
agent._log(`✅ CLUSTER_OPERATIONS validated: ${operations.length} operations`);
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Execute a hook transform script
|
|
294
|
-
* Transform scripts return the message to publish, with access to:
|
|
295
|
-
* - result: parsed agent output
|
|
296
|
-
* - triggeringMessage: the message that triggered the agent
|
|
297
|
-
* - helpers: { getConfig(complexity, taskType) }
|
|
298
|
-
* @param {Object} params - Transform parameters
|
|
299
|
-
* @param {Object} params.transform - Transform configuration
|
|
300
|
-
* @param {Object} params.context - Execution context
|
|
301
|
-
* @param {Object} params.agent - Agent instance
|
|
302
|
-
* @returns {Promise<Object>} Message to publish
|
|
303
|
-
*/
|
|
304
|
-
async function executeTransform(params) {
|
|
305
|
-
const { transform, context, agent } = params;
|
|
306
|
-
const { engine, script } = transform;
|
|
307
|
-
|
|
308
|
-
if (engine !== 'javascript') {
|
|
309
|
-
throw new Error(`Unsupported transform engine: ${engine}`);
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
// Parse result output if we have a result
|
|
313
|
-
// VALIDATION: Check if script uses result.* variables and fail early if no output
|
|
314
|
-
const scriptUsesResult = /\bresult\.[a-zA-Z]/.test(script);
|
|
315
|
-
const resultData = await parseTransformResultData({
|
|
316
|
-
context,
|
|
317
|
-
agent,
|
|
318
|
-
script,
|
|
319
|
-
scriptUsesResult,
|
|
320
|
-
});
|
|
321
|
-
|
|
322
|
-
const sandbox = buildTransformSandbox({ resultData, context, agent });
|
|
323
|
-
const result = runTransformScript(script, sandbox);
|
|
324
|
-
|
|
325
|
-
validateTransformResult(result);
|
|
326
|
-
validateClusterOperationsResult(result, agent);
|
|
327
|
-
|
|
328
|
-
return result;
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
/**
|
|
332
|
-
* Substitute template variables in hook config
|
|
333
|
-
* ONLY parses result output if result.* variables are used
|
|
334
|
-
* THROWS on any error - no silent failures
|
|
335
|
-
* @param {Object} params - Substitution parameters
|
|
336
|
-
* @param {Object} params.config - Hook configuration
|
|
337
|
-
* @param {Object} params.context - Execution context
|
|
338
|
-
* @param {Object} params.agent - Agent instance
|
|
339
|
-
* @param {Object} params.cluster - Cluster object
|
|
340
|
-
* @returns {Promise<Object>} Substituted configuration
|
|
341
|
-
*/
|
|
342
|
-
async function substituteTemplate(params) {
|
|
343
|
-
const { config, context, agent, cluster } = params;
|
|
344
|
-
|
|
345
|
-
if (!config) {
|
|
346
|
-
throw new Error('_substituteTemplate: config is required');
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
const json = JSON.stringify(config);
|
|
350
|
-
|
|
351
|
-
// Check if ANY result.* variables are used BEFORE parsing
|
|
352
|
-
// Generic pattern - no hardcoded field names, works with any agent config
|
|
353
|
-
const usesResultVars = /\{\{result\.[^}]+\}\}/.test(json);
|
|
354
|
-
|
|
355
|
-
let resultData = null;
|
|
356
|
-
if (usesResultVars) {
|
|
357
|
-
if (!context.result) {
|
|
358
|
-
throw new Error(
|
|
359
|
-
`Hook uses result.* variables but no result in context. ` +
|
|
360
|
-
`Agent: ${agent.id}, TaskID: ${agent.currentTaskId}, Iteration: ${agent.iteration}`
|
|
361
|
-
);
|
|
362
|
-
}
|
|
363
|
-
if (!context.result.output) {
|
|
364
|
-
// Log detailed context for debugging
|
|
365
|
-
const taskId = context.result.taskId || agent.currentTaskId || 'UNKNOWN';
|
|
366
|
-
console.error(`\n${'='.repeat(80)}`);
|
|
367
|
-
console.error(`🔴 HOOK FAILURE - EMPTY OUTPUT`);
|
|
368
|
-
console.error(`${'='.repeat(80)}`);
|
|
369
|
-
console.error(`Agent: ${agent.id}`);
|
|
370
|
-
console.error(`Task ID: ${taskId}`);
|
|
371
|
-
console.error(`Iteration: ${context.result.iteration || agent.iteration}`);
|
|
372
|
-
console.error(`Result success: ${context.result.success}`);
|
|
373
|
-
console.error(`Result error: ${context.result.error || 'none'}`);
|
|
374
|
-
console.error(`Output length: ${(context.result.output || '').length}`);
|
|
375
|
-
console.error(`Hook config: ${JSON.stringify(config, null, 2)}`);
|
|
376
|
-
|
|
377
|
-
// Auto-fetch and publish task logs for debugging
|
|
378
|
-
let taskLogs = 'Task logs unavailable';
|
|
379
|
-
if (taskId !== 'UNKNOWN') {
|
|
380
|
-
console.error(`\nFetching task logs for ${taskId}...`);
|
|
381
|
-
try {
|
|
382
|
-
const ctPath = agent._getClaudeTasksPath();
|
|
383
|
-
taskLogs = execSync(`${ctPath} logs ${taskId} --lines 100`, {
|
|
384
|
-
encoding: 'utf-8',
|
|
385
|
-
timeout: 5000,
|
|
386
|
-
maxBuffer: 1024 * 1024, // 1MB
|
|
387
|
-
}).trim();
|
|
388
|
-
console.error(`✓ Retrieved ${taskLogs.split('\n').length} lines of logs`);
|
|
389
|
-
} catch (err) {
|
|
390
|
-
taskLogs = `Failed to retrieve logs: ${err.message}`;
|
|
391
|
-
console.error(`✗ Failed to retrieve logs: ${err.message}`);
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
console.error(`${'='.repeat(80)}\n`);
|
|
395
|
-
|
|
396
|
-
// Publish task logs to message bus for visibility in zeroshot logs
|
|
397
|
-
agent._publish({
|
|
398
|
-
topic: 'AGENT_ERROR',
|
|
399
|
-
receiver: 'broadcast',
|
|
400
|
-
content: {
|
|
401
|
-
text: `Task logs for ${taskId} (last 100 lines)`,
|
|
402
|
-
data: {
|
|
403
|
-
taskId,
|
|
404
|
-
logs: taskLogs,
|
|
405
|
-
logsPreview: taskLogs.split('\n').slice(-20).join('\n'), // Last 20 lines as preview
|
|
406
|
-
},
|
|
407
|
-
},
|
|
408
|
-
});
|
|
409
|
-
|
|
410
|
-
throw new Error(
|
|
411
|
-
`Hook uses result.* variables but result.output is empty. ` +
|
|
412
|
-
`Agent: ${agent.id}, TaskID: ${taskId}, ` +
|
|
413
|
-
`Iteration: ${context.result.iteration || agent.iteration}, ` +
|
|
414
|
-
`Success: ${context.result.success}. ` +
|
|
415
|
-
`Task logs posted to message bus.`
|
|
416
|
-
);
|
|
417
|
-
}
|
|
418
|
-
// Parse result output - WILL THROW if no JSON block
|
|
419
|
-
resultData = await agent._parseResultOutput(context.result.output);
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
// Helper to escape a value for JSON string substitution
|
|
423
|
-
// Uses JSON.stringify for ALL escaping - no manual replace() calls
|
|
424
|
-
const escapeForJsonString = (value) => {
|
|
425
|
-
if (value === null || value === undefined) {
|
|
426
|
-
throw new Error(`Cannot escape null/undefined value for JSON`);
|
|
427
|
-
}
|
|
428
|
-
// JSON.stringify handles ALL escaping (newlines, quotes, backslashes, control chars)
|
|
429
|
-
// .slice(1, -1) strips the outer quotes it adds
|
|
430
|
-
// For arrays/objects: stringify twice - once for JSON, once to escape for string embedding
|
|
431
|
-
const stringified =
|
|
432
|
-
typeof value === 'string' ? JSON.stringify(value) : JSON.stringify(JSON.stringify(value));
|
|
433
|
-
return stringified.slice(1, -1);
|
|
434
|
-
};
|
|
435
|
-
|
|
436
|
-
// Helper to escape template-like patterns in substituted values
|
|
437
|
-
// This prevents content containing "{{result.foo}}" from being flagged as unsubstituted variables
|
|
438
|
-
// Uses Unicode escape for first brace: {{ -> \u007B{ (invisible to humans, breaks pattern match)
|
|
439
|
-
const escapeTemplatePatterns = (str) => {
|
|
440
|
-
return str.replace(/\{\{/g, '\\u007B{');
|
|
441
|
-
};
|
|
442
|
-
|
|
443
|
-
let substituted = json
|
|
444
|
-
.replace(/\{\{cluster\.id\}\}/g, escapeTemplatePatterns(cluster.id))
|
|
445
|
-
.replace(/\{\{cluster\.createdAt\}\}/g, String(cluster.createdAt))
|
|
446
|
-
.replace(/\{\{iteration\}\}/g, String(agent.iteration))
|
|
447
|
-
.replace(
|
|
448
|
-
/\{\{error\.message\}\}/g,
|
|
449
|
-
escapeTemplatePatterns(escapeForJsonString(context.error?.message ?? ''))
|
|
450
|
-
)
|
|
451
|
-
.replace(
|
|
452
|
-
/\{\{result\.output\}\}/g,
|
|
453
|
-
escapeTemplatePatterns(escapeForJsonString(context.result?.output ?? ''))
|
|
454
|
-
);
|
|
455
|
-
|
|
456
|
-
// Substitute ALL result.* variables dynamically from parsed resultData
|
|
457
|
-
if (resultData) {
|
|
458
|
-
// Generic substitution - replace {{result.fieldName}} with resultData[fieldName]
|
|
459
|
-
// No hardcoded field names - works with any agent output schema
|
|
460
|
-
// CRITICAL: For booleans/nulls/numbers, we need to match and remove surrounding quotes
|
|
461
|
-
// to produce valid JSON (e.g., "{{result.approved}}" -> true, not "true")
|
|
462
|
-
substituted = substituted.replace(/"?\{\{result\.([^}]+)\}\}"?/g, (match, fieldName) => {
|
|
463
|
-
const value = resultData[fieldName];
|
|
464
|
-
if (value === undefined) {
|
|
465
|
-
// Missing fields should gracefully default to null or empty values
|
|
466
|
-
// This allows optional schema fields without hardcoding field names
|
|
467
|
-
// If a field is truly required, the schema validation will catch it
|
|
468
|
-
console.warn(
|
|
469
|
-
`⚠️ Agent ${agent.id}: Template variable {{result.${fieldName}}} not found in output. ` +
|
|
470
|
-
`If this field is required by the schema, the agent violated its own schema. ` +
|
|
471
|
-
`Defaulting to null. Agent output keys: ${Object.keys(resultData).join(', ')}`
|
|
472
|
-
);
|
|
473
|
-
return 'null';
|
|
474
|
-
}
|
|
475
|
-
// Booleans, numbers, and null should be unquoted JSON primitives
|
|
476
|
-
if (typeof value === 'boolean' || typeof value === 'number' || value === null) {
|
|
477
|
-
return String(value);
|
|
478
|
-
}
|
|
479
|
-
// Strings need to be quoted and escaped for JSON
|
|
480
|
-
// Also escape any template-like patterns in the content to prevent false positives
|
|
481
|
-
return escapeTemplatePatterns(JSON.stringify(value));
|
|
482
|
-
});
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
// Check for unsubstituted KNOWN template variables only
|
|
486
|
-
// KNOWN patterns: {{cluster.X}}, {{iteration}}, {{error.X}}, {{result.X}}
|
|
487
|
-
// Content may contain arbitrary {{...}} patterns (React dangerouslySetInnerHTML, Mustache, etc.)
|
|
488
|
-
// Those are NOT template variables - they're just content that happens to contain braces
|
|
489
|
-
const KNOWN_TEMPLATE_PREFIXES = ['cluster', 'iteration', 'error', 'result'];
|
|
490
|
-
const knownVariablePattern = new RegExp(
|
|
491
|
-
`\\{\\{(${KNOWN_TEMPLATE_PREFIXES.join('|')})(\\.[a-zA-Z_][a-zA-Z0-9_]*)?\\}\\}`,
|
|
492
|
-
'g'
|
|
493
|
-
);
|
|
494
|
-
const remaining = substituted.match(knownVariablePattern);
|
|
495
|
-
if (remaining) {
|
|
496
|
-
throw new Error(`Unsubstituted template variables: ${remaining.join(', ')}`);
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
// Parse and validate result
|
|
500
|
-
let result;
|
|
501
|
-
try {
|
|
502
|
-
result = JSON.parse(substituted);
|
|
503
|
-
} catch (e) {
|
|
504
|
-
console.error('JSON parse failed. Substituted string:');
|
|
505
|
-
console.error(substituted);
|
|
506
|
-
throw new Error(`Template substitution produced invalid JSON: ${e.message}`);
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
return result;
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
/**
|
|
513
|
-
* Evaluate hook logic script to get config overrides
|
|
514
|
-
* Similar to trigger logic, but returns an object to merge into config
|
|
515
|
-
* @param {Object} params - Evaluation parameters
|
|
516
|
-
* @param {Object} params.logic - Logic configuration { engine, script }
|
|
517
|
-
* @param {Object} params.resultData - Parsed agent result data
|
|
518
|
-
* @param {Object} params.agent - Agent instance
|
|
519
|
-
* @param {Object} params.context - Execution context
|
|
520
|
-
* @returns {Object|null} Config overrides to merge, or null if none
|
|
521
|
-
*/
|
|
522
|
-
function evaluateHookLogic(params) {
|
|
523
|
-
const { logic, resultData, agent, context } = params;
|
|
524
|
-
|
|
525
|
-
if (!logic || !logic.script) {
|
|
526
|
-
return null;
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
if (logic.engine !== 'javascript') {
|
|
530
|
-
throw new Error(`Unsupported hook logic engine: ${logic.engine}`);
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
// Build sandbox context - similar to LogicEngine but focused on result data
|
|
534
|
-
const sandbox = {
|
|
535
|
-
// The parsed result from agent output - this is the main input
|
|
536
|
-
result: resultData || {},
|
|
537
|
-
|
|
538
|
-
// Agent context
|
|
539
|
-
agent: {
|
|
540
|
-
id: agent.id,
|
|
541
|
-
role: agent.role,
|
|
542
|
-
iteration: agent.iteration || 0,
|
|
543
|
-
},
|
|
544
|
-
|
|
545
|
-
// Triggering message (if available)
|
|
546
|
-
message: context.triggeringMessage || null,
|
|
547
|
-
|
|
548
|
-
// Safe built-ins
|
|
549
|
-
Set,
|
|
550
|
-
Map,
|
|
551
|
-
Array,
|
|
552
|
-
Object,
|
|
553
|
-
String,
|
|
554
|
-
Number,
|
|
555
|
-
Boolean,
|
|
556
|
-
Math,
|
|
557
|
-
Date,
|
|
558
|
-
JSON,
|
|
559
|
-
|
|
560
|
-
// Console for debugging (logs to agent log)
|
|
561
|
-
console: {
|
|
562
|
-
log: (...args) => agent._log('[hook-logic]', ...args),
|
|
563
|
-
error: (...args) => console.error('[hook-logic]', ...args),
|
|
564
|
-
warn: (...args) => console.warn('[hook-logic]', ...args),
|
|
565
|
-
},
|
|
566
|
-
};
|
|
567
|
-
|
|
568
|
-
// Execute in VM sandbox with timeout
|
|
569
|
-
const vmContext = vm.createContext(sandbox);
|
|
570
|
-
const wrappedScript = `(function() { 'use strict'; ${logic.script} })()`;
|
|
571
|
-
|
|
572
|
-
let result;
|
|
573
|
-
try {
|
|
574
|
-
result = vm.runInContext(wrappedScript, vmContext, { timeout: 1000 });
|
|
575
|
-
} catch (err) {
|
|
576
|
-
throw new Error(`Hook logic script error: ${err.message}`);
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
// Logic scripts can return:
|
|
580
|
-
// - undefined/null: no overrides
|
|
581
|
-
// - object: merge into config
|
|
582
|
-
if (result === undefined || result === null) {
|
|
583
|
-
return null;
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
if (typeof result !== 'object') {
|
|
587
|
-
throw new Error(`Hook logic script must return an object or undefined, got: ${typeof result}`);
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
return result;
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
module.exports = {
|
|
594
|
-
executeHook,
|
|
595
|
-
executeTransform,
|
|
596
|
-
substituteTemplate,
|
|
597
|
-
evaluateHookLogic,
|
|
598
|
-
deepMerge,
|
|
599
|
-
};
|