sentinelayer-cli 0.6.2 → 0.8.0

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.
Files changed (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -1,309 +1,311 @@
1
- import { randomUUID } from "node:crypto";
2
- import { createAgentContext, dispatchTool, isReadOnlyTool, BudgetExhaustedError } from "../tools/dispatch.js";
3
- import { createMultiProviderApiClient } from "../../../ai/client.js";
4
-
5
- /**
6
- * JulesSubAgent — lightweight isolated agent for parallel audit work.
7
- *
8
- * Each sub-agent gets:
9
- * - Own conversation context (no parent history)
10
- * - Own tool access (subset of Jules' tools)
11
- * - Own budget slice (clamped to parent allocation)
12
- * - Shared blackboard (append-only)
13
- * - Own telemetry session
14
- * - AbortController linked to parent (kill propagation)
15
- *
16
- * Sub-agents are NOT full Jules instances. They are focused workers:
17
- * - FileScanner: reads file batches, extracts structured summaries
18
- * - PatternHunter: searches for specific issue classes
19
- */
20
-
21
- const DEFAULT_MAX_TURNS = 10;
22
- const DEFAULT_TEMPERATURE = 0;
23
-
24
- export class JulesSubAgent {
25
- /**
26
- * @param {object} config
27
- * @param {string} config.id - Unique identifier (e.g., "file-scanner-dashboard")
28
- * @param {string} config.role - "FileScanner" | "PatternHunter" | "custom"
29
- * @param {string} config.systemPrompt - System instruction for this sub-agent
30
- * @param {string[]} config.allowedTools - Tool names this agent can use
31
- * @param {object} config.scope - { files: string[], patterns: string[] }
32
- * @param {object} config.budget - Budget slice { maxCostUsd, maxOutputTokens, maxRuntimeMs, maxToolCalls }
33
- * @param {object} config.blackboard - Shared blackboard instance (appendEntry, query)
34
- * @param {object} [config.provider] - { provider, model, apiKey } overrides
35
- * @param {number} [config.maxTurns] - Max agentic loop iterations
36
- * @param {AbortController} [config.parentAbort] - Linked to parent for kill propagation
37
- * @param {function} [config.onEvent] - Streaming event callback
38
- */
39
- constructor(config) {
40
- this.id = config.id || `subagent-${randomUUID().slice(0, 8)}`;
41
- this.role = config.role;
42
- this.systemPrompt = config.systemPrompt;
43
- this.allowedTools = new Set(config.allowedTools || ["FileRead", "Grep", "Glob", "FrontendAnalyze"]);
44
- this.scope = config.scope || {};
45
- this.maxTurns = config.maxTurns ?? DEFAULT_MAX_TURNS;
46
- this.blackboard = config.blackboard;
47
- this.onEvent = config.onEvent;
48
-
49
- // Isolated context
50
- this.conversation = [];
51
- this.findings = [];
52
- this.turnCount = 0;
53
-
54
- // Budget-gated agent context
55
- this.ctx = createAgentContext({
56
- agentIdentity: {
57
- id: this.id,
58
- persona: `Jules Sub-Agent (${this.role})`,
59
- parentId: "frontend",
60
- },
61
- budget: config.budget || {
62
- maxCostUsd: 1.0,
63
- maxOutputTokens: 4000,
64
- maxRuntimeMs: 120000,
65
- maxToolCalls: 50,
66
- },
67
- sessionId: randomUUID(),
68
- runId: `sub-${this.id}-${Date.now()}`,
69
- onEvent: config.onEvent,
70
- });
71
-
72
- // LLM client
73
- this.client = createMultiProviderApiClient(config.provider || {});
74
-
75
- // Abort linkage
76
- this.abortController = new AbortController();
77
- if (config.parentAbort) {
78
- config.parentAbort.signal.addEventListener("abort", () => {
79
- this.abortController.abort();
80
- }, { once: true });
81
- }
82
- }
83
-
84
- /**
85
- * Execute the sub-agent's task.
86
- * Runs an agentic loop: LLM → tool_use → execute → feed back → repeat.
87
- * Returns structured results.
88
- */
89
- async execute() {
90
- this.emitEvent("agent_start", { role: this.role, scope: this.scope });
91
-
92
- // Build initial messages
93
- const messages = [
94
- { role: "user", content: this.buildTaskPrompt() },
95
- ];
96
-
97
- try {
98
- while (this.turnCount < this.maxTurns) {
99
- if (this.abortController.signal.aborted) {
100
- this.emitEvent("agent_abort", { reason: "parent_killed" });
101
- break;
102
- }
103
-
104
- this.turnCount++;
105
-
106
- // Call LLM
107
- const response = await this.client.invoke({
108
- systemPrompt: this.systemPrompt,
109
- messages,
110
- temperature: DEFAULT_TEMPERATURE,
111
- });
112
-
113
- // Track cost
114
- this.ctx.usage.outputTokens += estimateTokens(response.text);
115
- this.ctx.usage.costUsd += estimateCost(response.text);
116
-
117
- // Parse tool_use blocks from response
118
- const toolCalls = parseToolCalls(response.text);
119
-
120
- if (toolCalls.length === 0) {
121
- // No more tool calls — sub-agent is done
122
- const structured = parseStructuredOutput(response.text);
123
- if (structured.findings) {
124
- for (const finding of structured.findings) {
125
- this.findings.push(finding);
126
- if (this.blackboard) {
127
- await this.blackboard.appendEntry({
128
- agentId: this.id,
129
- source: this.role,
130
- ...finding,
131
- });
132
- }
133
- }
134
- }
135
- messages.push({ role: "assistant", content: response.text });
136
- break;
137
- }
138
-
139
- // Execute tool calls
140
- const toolResults = [];
141
- for (const call of toolCalls) {
142
- if (!this.allowedTools.has(call.tool)) {
143
- toolResults.push({ tool: call.tool, error: `Tool ${call.tool} not allowed for this sub-agent` });
144
- continue;
145
- }
146
- try {
147
- const result = await dispatchTool(call.tool, call.input, this.ctx);
148
- toolResults.push({ tool: call.tool, result });
149
- } catch (err) {
150
- if (err instanceof BudgetExhaustedError) {
151
- this.emitEvent("budget_stop", { reason: err.message });
152
- return this.buildResult("budget_exhausted");
153
- }
154
- toolResults.push({ tool: call.tool, error: err.message });
155
- }
156
- }
157
-
158
- // Feed results back to conversation
159
- messages.push({ role: "assistant", content: response.text });
160
- messages.push({
161
- role: "user",
162
- content: formatToolResults(toolResults),
163
- });
164
- }
165
- } catch (err) {
166
- this.emitEvent("agent_error", { error: err.message });
167
- return this.buildResult("error", err.message);
168
- }
169
-
170
- this.emitEvent("agent_complete", {
171
- findings: this.findings.length,
172
- turns: this.turnCount,
173
- toolCalls: this.ctx.usage.toolCalls,
174
- });
175
-
176
- return this.buildResult("completed");
177
- }
178
-
179
- buildTaskPrompt() {
180
- const parts = [];
181
- if (this.scope.files && this.scope.files.length > 0) {
182
- parts.push(`Files in your scope:\n${this.scope.files.join("\n")}`);
183
- }
184
- if (this.scope.patterns && this.scope.patterns.length > 0) {
185
- parts.push(`Patterns to search for:\n${this.scope.patterns.join("\n")}`);
186
- }
187
- parts.push("Return your findings as a JSON array in a ```json code block.");
188
- return parts.join("\n\n");
189
- }
190
-
191
- buildResult(status, error) {
192
- return {
193
- agentId: this.id,
194
- role: this.role,
195
- status,
196
- error: error || null,
197
- findings: this.findings,
198
- usage: {
199
- turns: this.turnCount,
200
- toolCalls: this.ctx.usage.toolCalls,
201
- costUsd: this.ctx.usage.costUsd,
202
- outputTokens: this.ctx.usage.outputTokens,
203
- durationMs: Date.now() - this.ctx.startedAt,
204
- filesRead: [...(this.ctx.usage.filesRead || [])],
205
- },
206
- };
207
- }
208
-
209
- emitEvent(event, payload) {
210
- if (this.onEvent) {
211
- this.onEvent({
212
- stream: "sl_event",
213
- event,
214
- agent: { id: this.id, persona: `Jules Sub-Agent (${this.role})`, parentId: "frontend" },
215
- payload,
216
- usage: {
217
- costUsd: this.ctx.usage.costUsd,
218
- toolCalls: this.ctx.usage.toolCalls,
219
- durationMs: Date.now() - this.ctx.startedAt,
220
- },
221
- });
222
- }
223
- }
224
- }
225
-
226
- /**
227
- * Run a batch of sub-agents with concurrency control.
228
- */
229
- export async function runSubAgentBatch(agents, { maxConcurrent = 4 } = {}) {
230
- const results = [];
231
- const queue = [...agents];
232
-
233
- async function runNext() {
234
- while (queue.length > 0) {
235
- const agent = queue.shift();
236
- const result = await agent.execute();
237
- results.push(result);
238
- }
239
- }
240
-
241
- const workers = Array.from(
242
- { length: Math.min(maxConcurrent, agents.length) },
243
- () => runNext(),
244
- );
245
- await Promise.all(workers);
246
- return results;
247
- }
248
-
249
- // ── Helpers ──────────────────────────────────────────────────────────
250
-
251
- function parseToolCalls(text) {
252
- // Parse tool_use blocks from LLM response
253
- // Format: ```tool_use\n{"tool":"FileRead","input":{...}}\n```
254
- const calls = [];
255
- const regex = /```tool_use\s*\n([\s\S]*?)```/g;
256
- let match;
257
- while ((match = regex.exec(text)) !== null) {
258
- try {
259
- const parsed = JSON.parse(match[1].trim());
260
- if (parsed.tool && parsed.input) {
261
- calls.push(parsed);
262
- }
263
- } catch { /* skip malformed */ }
264
- }
265
- return calls;
266
- }
267
-
268
- function parseStructuredOutput(text) {
269
- // Parse JSON findings from LLM response
270
- const jsonMatch = text.match(/```json\s*\n([\s\S]*?)```/);
271
- if (jsonMatch) {
272
- try {
273
- const parsed = JSON.parse(jsonMatch[1].trim());
274
- if (Array.isArray(parsed)) {
275
- return { findings: parsed };
276
- }
277
- if (parsed.findings && Array.isArray(parsed.findings)) {
278
- return parsed;
279
- }
280
- } catch { /* skip malformed */ }
281
- }
282
- return { findings: [] };
283
- }
284
-
285
- function formatToolResults(results) {
286
- return results.map(r => {
287
- if (r.error) return `Tool ${r.tool} failed: ${r.error}`;
288
- const summary = typeof r.result === "string" ? r.result :
289
- JSON.stringify(r.result).slice(0, 2000);
290
- return `Tool ${r.tool} result:\n${summary}`;
291
- }).join("\n\n");
292
- }
293
-
294
- function estimateTokens(text) {
295
- return Math.ceil((text || "").length / 4);
296
- }
297
-
298
- function estimateCost(text) {
299
- // Rough: $15/M output tokens for Claude Sonnet
300
- const tokens = estimateTokens(text);
301
- return (tokens / 1_000_000) * 15;
302
- }
303
-
304
- export class SubAgentError extends Error {
305
- constructor(message) {
306
- super(message);
307
- this.name = "SubAgentError";
308
- }
309
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import { createAgentContext, dispatchTool, isReadOnlyTool, BudgetExhaustedError } from "../tools/dispatch.js";
3
+ import { createMultiProviderApiClient } from "../../../ai/client.js";
4
+ import { createAgentEvent } from "../../../events/schema.js";
5
+
6
+ /**
7
+ * JulesSubAgent — lightweight isolated agent for parallel audit work.
8
+ *
9
+ * Each sub-agent gets:
10
+ * - Own conversation context (no parent history)
11
+ * - Own tool access (subset of Jules' tools)
12
+ * - Own budget slice (clamped to parent allocation)
13
+ * - Shared blackboard (append-only)
14
+ * - Own telemetry session
15
+ * - AbortController linked to parent (kill propagation)
16
+ *
17
+ * Sub-agents are NOT full Jules instances. They are focused workers:
18
+ * - FileScanner: reads file batches, extracts structured summaries
19
+ * - PatternHunter: searches for specific issue classes
20
+ */
21
+
22
+ const DEFAULT_MAX_TURNS = 10;
23
+ const DEFAULT_TEMPERATURE = 0;
24
+
25
+ export class JulesSubAgent {
26
+ /**
27
+ * @param {object} config
28
+ * @param {string} config.id - Unique identifier (e.g., "file-scanner-dashboard")
29
+ * @param {string} config.role - "FileScanner" | "PatternHunter" | "custom"
30
+ * @param {string} config.systemPrompt - System instruction for this sub-agent
31
+ * @param {string[]} config.allowedTools - Tool names this agent can use
32
+ * @param {object} config.scope - { files: string[], patterns: string[] }
33
+ * @param {object} config.budget - Budget slice { maxCostUsd, maxOutputTokens, maxRuntimeMs, maxToolCalls }
34
+ * @param {object} config.blackboard - Shared blackboard instance (appendEntry, query)
35
+ * @param {object} [config.provider] - { provider, model, apiKey } overrides
36
+ * @param {number} [config.maxTurns] - Max agentic loop iterations
37
+ * @param {AbortController} [config.parentAbort] - Linked to parent for kill propagation
38
+ * @param {function} [config.onEvent] - Streaming event callback
39
+ */
40
+ constructor(config) {
41
+ this.id = config.id || `subagent-${randomUUID().slice(0, 8)}`;
42
+ this.role = config.role;
43
+ this.systemPrompt = config.systemPrompt;
44
+ this.allowedTools = new Set(config.allowedTools || ["FileRead", "Grep", "Glob", "FrontendAnalyze"]);
45
+ this.scope = config.scope || {};
46
+ this.maxTurns = config.maxTurns ?? DEFAULT_MAX_TURNS;
47
+ this.blackboard = config.blackboard;
48
+ this.onEvent = config.onEvent;
49
+
50
+ // Isolated context
51
+ this.conversation = [];
52
+ this.findings = [];
53
+ this.turnCount = 0;
54
+
55
+ // Budget-gated agent context
56
+ this.ctx = createAgentContext({
57
+ agentIdentity: {
58
+ id: this.id,
59
+ persona: `Jules Sub-Agent (${this.role})`,
60
+ parentId: "frontend",
61
+ },
62
+ budget: config.budget || {
63
+ maxCostUsd: 1.0,
64
+ maxOutputTokens: 4000,
65
+ maxRuntimeMs: 120000,
66
+ maxToolCalls: 50,
67
+ },
68
+ sessionId: randomUUID(),
69
+ runId: `sub-${this.id}-${Date.now()}`,
70
+ onEvent: config.onEvent,
71
+ });
72
+
73
+ // LLM client
74
+ this.client = createMultiProviderApiClient(config.provider || {});
75
+
76
+ // Abort linkage
77
+ this.abortController = new AbortController();
78
+ if (config.parentAbort) {
79
+ config.parentAbort.signal.addEventListener("abort", () => {
80
+ this.abortController.abort();
81
+ }, { once: true });
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Execute the sub-agent's task.
87
+ * Runs an agentic loop: LLM → tool_use → execute → feed back → repeat.
88
+ * Returns structured results.
89
+ */
90
+ async execute() {
91
+ this.emitEvent("agent_start", { role: this.role, scope: this.scope });
92
+
93
+ // Build initial messages
94
+ const messages = [
95
+ { role: "user", content: this.buildTaskPrompt() },
96
+ ];
97
+
98
+ try {
99
+ while (this.turnCount < this.maxTurns) {
100
+ if (this.abortController.signal.aborted) {
101
+ this.emitEvent("agent_abort", { reason: "parent_killed" });
102
+ break;
103
+ }
104
+
105
+ this.turnCount++;
106
+
107
+ // Call LLM
108
+ const response = await this.client.invoke({
109
+ systemPrompt: this.systemPrompt,
110
+ messages,
111
+ temperature: DEFAULT_TEMPERATURE,
112
+ });
113
+
114
+ // Track cost
115
+ this.ctx.usage.outputTokens += estimateTokens(response.text);
116
+ this.ctx.usage.costUsd += estimateCost(response.text);
117
+
118
+ // Parse tool_use blocks from response
119
+ const toolCalls = parseToolCalls(response.text);
120
+
121
+ if (toolCalls.length === 0) {
122
+ // No more tool calls — sub-agent is done
123
+ const structured = parseStructuredOutput(response.text);
124
+ if (structured.findings) {
125
+ for (const finding of structured.findings) {
126
+ this.findings.push(finding);
127
+ if (this.blackboard) {
128
+ await this.blackboard.appendEntry({
129
+ agentId: this.id,
130
+ source: this.role,
131
+ ...finding,
132
+ });
133
+ }
134
+ }
135
+ }
136
+ messages.push({ role: "assistant", content: response.text });
137
+ break;
138
+ }
139
+
140
+ // Execute tool calls
141
+ const toolResults = [];
142
+ for (const call of toolCalls) {
143
+ if (!this.allowedTools.has(call.tool)) {
144
+ toolResults.push({ tool: call.tool, error: `Tool ${call.tool} not allowed for this sub-agent` });
145
+ continue;
146
+ }
147
+ try {
148
+ const result = await dispatchTool(call.tool, call.input, this.ctx);
149
+ toolResults.push({ tool: call.tool, result });
150
+ } catch (err) {
151
+ if (err instanceof BudgetExhaustedError) {
152
+ this.emitEvent("budget_stop", { reason: err.message });
153
+ return this.buildResult("budget_exhausted");
154
+ }
155
+ toolResults.push({ tool: call.tool, error: err.message });
156
+ }
157
+ }
158
+
159
+ // Feed results back to conversation
160
+ messages.push({ role: "assistant", content: response.text });
161
+ messages.push({
162
+ role: "user",
163
+ content: formatToolResults(toolResults),
164
+ });
165
+ }
166
+ } catch (err) {
167
+ this.emitEvent("agent_error", { error: err.message });
168
+ return this.buildResult("error", err.message);
169
+ }
170
+
171
+ this.emitEvent("agent_complete", {
172
+ findings: this.findings.length,
173
+ turns: this.turnCount,
174
+ toolCalls: this.ctx.usage.toolCalls,
175
+ });
176
+
177
+ return this.buildResult("completed");
178
+ }
179
+
180
+ buildTaskPrompt() {
181
+ const parts = [];
182
+ if (this.scope.files && this.scope.files.length > 0) {
183
+ parts.push(`Files in your scope:\n${this.scope.files.join("\n")}`);
184
+ }
185
+ if (this.scope.patterns && this.scope.patterns.length > 0) {
186
+ parts.push(`Patterns to search for:\n${this.scope.patterns.join("\n")}`);
187
+ }
188
+ parts.push("Return your findings as a JSON array in a ```json code block.");
189
+ return parts.join("\n\n");
190
+ }
191
+
192
+ buildResult(status, error) {
193
+ return {
194
+ agentId: this.id,
195
+ role: this.role,
196
+ status,
197
+ error: error || null,
198
+ findings: this.findings,
199
+ usage: {
200
+ turns: this.turnCount,
201
+ toolCalls: this.ctx.usage.toolCalls,
202
+ costUsd: this.ctx.usage.costUsd,
203
+ outputTokens: this.ctx.usage.outputTokens,
204
+ durationMs: Date.now() - this.ctx.startedAt,
205
+ filesRead: [...(this.ctx.usage.filesRead || [])],
206
+ },
207
+ };
208
+ }
209
+
210
+ emitEvent(event, payload) {
211
+ if (this.onEvent) {
212
+ this.onEvent(createAgentEvent({
213
+ event,
214
+ agent: { id: this.id, persona: `Jules Sub-Agent (${this.role})`, parentId: "frontend" },
215
+ payload,
216
+ usage: {
217
+ costUsd: this.ctx.usage.costUsd,
218
+ toolCalls: this.ctx.usage.toolCalls,
219
+ durationMs: Date.now() - this.ctx.startedAt,
220
+ },
221
+ sessionId: this.ctx.sessionId,
222
+ runId: this.ctx.runId,
223
+ }));
224
+ }
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Run a batch of sub-agents with concurrency control.
230
+ */
231
+ export async function runSubAgentBatch(agents, { maxConcurrent = 4 } = {}) {
232
+ const results = [];
233
+ const queue = [...agents];
234
+
235
+ async function runNext() {
236
+ while (queue.length > 0) {
237
+ const agent = queue.shift();
238
+ const result = await agent.execute();
239
+ results.push(result);
240
+ }
241
+ }
242
+
243
+ const workers = Array.from(
244
+ { length: Math.min(maxConcurrent, agents.length) },
245
+ () => runNext(),
246
+ );
247
+ await Promise.all(workers);
248
+ return results;
249
+ }
250
+
251
+ // ── Helpers ──────────────────────────────────────────────────────────
252
+
253
+ function parseToolCalls(text) {
254
+ // Parse tool_use blocks from LLM response
255
+ // Format: ```tool_use\n{"tool":"FileRead","input":{...}}\n```
256
+ const calls = [];
257
+ const regex = /```tool_use\s*\n([\s\S]*?)```/g;
258
+ let match;
259
+ while ((match = regex.exec(text)) !== null) {
260
+ try {
261
+ const parsed = JSON.parse(match[1].trim());
262
+ if (parsed.tool && parsed.input) {
263
+ calls.push(parsed);
264
+ }
265
+ } catch { /* skip malformed */ }
266
+ }
267
+ return calls;
268
+ }
269
+
270
+ function parseStructuredOutput(text) {
271
+ // Parse JSON findings from LLM response
272
+ const jsonMatch = text.match(/```json\s*\n([\s\S]*?)```/);
273
+ if (jsonMatch) {
274
+ try {
275
+ const parsed = JSON.parse(jsonMatch[1].trim());
276
+ if (Array.isArray(parsed)) {
277
+ return { findings: parsed };
278
+ }
279
+ if (parsed.findings && Array.isArray(parsed.findings)) {
280
+ return parsed;
281
+ }
282
+ } catch { /* skip malformed */ }
283
+ }
284
+ return { findings: [] };
285
+ }
286
+
287
+ function formatToolResults(results) {
288
+ return results.map(r => {
289
+ if (r.error) return `Tool ${r.tool} failed: ${r.error}`;
290
+ const summary = typeof r.result === "string" ? r.result :
291
+ JSON.stringify(r.result).slice(0, 2000);
292
+ return `Tool ${r.tool} result:\n${summary}`;
293
+ }).join("\n\n");
294
+ }
295
+
296
+ function estimateTokens(text) {
297
+ return Math.ceil((text || "").length / 4);
298
+ }
299
+
300
+ function estimateCost(text) {
301
+ // Rough: $15/M output tokens for Claude Sonnet
302
+ const tokens = estimateTokens(text);
303
+ return (tokens / 1_000_000) * 15;
304
+ }
305
+
306
+ export class SubAgentError extends Error {
307
+ constructor(message) {
308
+ super(message);
309
+ this.name = "SubAgentError";
310
+ }
311
+ }