@aaac/runtime 0.1.35 → 0.1.37
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/dist/adapters/adk-sdk.d.ts +2 -1
- package/dist/adapters/adk-sdk.js +5 -3
- package/dist/adapters/adk-sdk.js.map +1 -1
- package/dist/adapters/claude-agent-sdk.d.ts +2 -1
- package/dist/adapters/claude-agent-sdk.js +4 -2
- package/dist/adapters/claude-agent-sdk.js.map +1 -1
- package/dist/adapters/mock.d.ts +2 -1
- package/dist/adapters/openai-agents-sdk.d.ts +2 -1
- package/dist/adapters/openai-agents-sdk.js +4 -2
- package/dist/adapters/openai-agents-sdk.js.map +1 -1
- package/dist/chunk-63RFYS7F.js +1503 -0
- package/dist/chunk-63RFYS7F.js.map +1 -0
- package/dist/{chunk-GZCEEIXQ.js → chunk-EH5VFZYJ.js} +2 -1
- package/dist/{chunk-Y4CI7UQO.js → chunk-GNMSH3VC.js} +2 -316
- package/dist/chunk-GNMSH3VC.js.map +1 -0
- package/dist/chunk-IQGCUM7E.js +321 -0
- package/dist/chunk-IQGCUM7E.js.map +1 -0
- package/dist/guardrail-hooks-slK-z0Dz.d.ts +83 -0
- package/dist/index.d.ts +59 -24
- package/dist/index.js +234 -1471
- package/dist/index.js.map +1 -1
- package/dist/lib/claude-native/index.d.ts +337 -0
- package/dist/lib/claude-native/index.js +474 -0
- package/dist/lib/claude-native/index.js.map +1 -0
- package/dist/navigation-context-BE1KHJ_8.d.ts +22 -0
- package/dist/{task-runner-CJLeSuUH.d.ts → task-runner-CWb9fVlc.d.ts} +2 -83
- package/package.json +7 -3
- package/dist/chunk-Y4CI7UQO.js.map +0 -1
- /package/dist/{chunk-GZCEEIXQ.js.map → chunk-EH5VFZYJ.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,3 +1,40 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildSdkFunctionTools
|
|
3
|
+
} from "./chunk-IQGCUM7E.js";
|
|
4
|
+
import {
|
|
5
|
+
buildGuardrailContext,
|
|
6
|
+
loadProjectConfig
|
|
7
|
+
} from "./chunk-735UA5HV.js";
|
|
8
|
+
import {
|
|
9
|
+
DslValidationError,
|
|
10
|
+
buildCandidateAgents,
|
|
11
|
+
buildGuardrailRulesFromDsl,
|
|
12
|
+
buildNavigationContext,
|
|
13
|
+
buildRegistriesFromDsl,
|
|
14
|
+
buildRetryFollowUp,
|
|
15
|
+
buildSplitTaskPrompt,
|
|
16
|
+
buildTaskPrompt,
|
|
17
|
+
collectAnalyzerToolIds,
|
|
18
|
+
createAnalyzerBridge,
|
|
19
|
+
emitProcessEdit,
|
|
20
|
+
emitProcessTaskClose,
|
|
21
|
+
emitProcessTaskOpen,
|
|
22
|
+
emitProcessWorkflowClose,
|
|
23
|
+
emitProcessWorkflowOpen,
|
|
24
|
+
extractStructuredResult,
|
|
25
|
+
isContextPack,
|
|
26
|
+
isFileEditTool,
|
|
27
|
+
isNavigationIndex,
|
|
28
|
+
loadDslContext,
|
|
29
|
+
renderAgentSystemPrompt,
|
|
30
|
+
renderAnalyzerExplorationMandatePrompt,
|
|
31
|
+
renderContextPackPrompt,
|
|
32
|
+
renderNavigationIndexPrompt,
|
|
33
|
+
runTask,
|
|
34
|
+
shouldInjectAnalyzerExplorationMandate,
|
|
35
|
+
zodSchemaToPromptDescription,
|
|
36
|
+
zodSchemaToYamlExample
|
|
37
|
+
} from "./chunk-63RFYS7F.js";
|
|
1
38
|
import {
|
|
2
39
|
PluginRegistry,
|
|
3
40
|
createGuardrailHooks,
|
|
@@ -7,11 +44,10 @@ import {
|
|
|
7
44
|
getWarnings,
|
|
8
45
|
hasBlockingViolation,
|
|
9
46
|
pluginRegistry
|
|
10
|
-
} from "./chunk-
|
|
47
|
+
} from "./chunk-EH5VFZYJ.js";
|
|
11
48
|
import {
|
|
12
49
|
OBSERVABILITY_ENV_VARS,
|
|
13
50
|
buildObservabilityEnv,
|
|
14
|
-
buildSdkFunctionTools,
|
|
15
51
|
createExecutionEnvelope,
|
|
16
52
|
emitIterationClose,
|
|
17
53
|
emitIterationMetric,
|
|
@@ -27,11 +63,7 @@ import {
|
|
|
27
63
|
emitToolchainClose,
|
|
28
64
|
emitToolchainOpen,
|
|
29
65
|
serializeObserverEmit
|
|
30
|
-
} from "./chunk-
|
|
31
|
-
import {
|
|
32
|
-
buildGuardrailContext,
|
|
33
|
-
loadProjectConfig
|
|
34
|
-
} from "./chunk-735UA5HV.js";
|
|
66
|
+
} from "./chunk-GNMSH3VC.js";
|
|
35
67
|
import {
|
|
36
68
|
jsonSchemaToZod
|
|
37
69
|
} from "./chunk-ET6TGQRT.js";
|
|
@@ -39,1107 +71,29 @@ import {
|
|
|
39
71
|
// src/index.ts
|
|
40
72
|
import { createRequire } from "module";
|
|
41
73
|
|
|
42
|
-
// src/lib/task-runner.ts
|
|
43
|
-
import { z } from "zod";
|
|
44
|
-
import * as yaml from "yaml";
|
|
45
|
-
|
|
46
|
-
// src/lib/candidate-agents.ts
|
|
47
|
-
function renderAgentSystemPrompt(agent) {
|
|
48
|
-
const sections = [];
|
|
49
|
-
sections.push(`# Role: ${agent.role_name}
|
|
50
|
-
|
|
51
|
-
${agent.purpose}`);
|
|
52
|
-
if (agent.responsibilities.length > 0) {
|
|
53
|
-
sections.push(
|
|
54
|
-
`## Responsibilities
|
|
55
|
-
|
|
56
|
-
${agent.responsibilities.map((r) => `- ${r}`).join("\n")}`
|
|
57
|
-
);
|
|
58
|
-
}
|
|
59
|
-
if (agent.constraints.length > 0) {
|
|
60
|
-
sections.push(
|
|
61
|
-
`## Constraints
|
|
62
|
-
|
|
63
|
-
${agent.constraints.map((c) => `- ${c}`).join("\n")}`
|
|
64
|
-
);
|
|
65
|
-
}
|
|
66
|
-
if (agent.rules && agent.rules.length > 0) {
|
|
67
|
-
const ruleLines = agent.rules.map(
|
|
68
|
-
(r) => `- **${r.id}** [${r.severity}]: ${r.description}`
|
|
69
|
-
);
|
|
70
|
-
sections.push(`## Rules
|
|
71
|
-
|
|
72
|
-
${ruleLines.join("\n")}`);
|
|
73
|
-
}
|
|
74
|
-
return sections.join("\n\n");
|
|
75
|
-
}
|
|
76
|
-
function deriveDescription(purpose) {
|
|
77
|
-
const firstLine = purpose.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
|
|
78
|
-
const sentenceEnd = firstLine.search(/[.!?](\s|$)/);
|
|
79
|
-
if (sentenceEnd !== -1) {
|
|
80
|
-
return firstLine.slice(0, sentenceEnd + 1).trim();
|
|
81
|
-
}
|
|
82
|
-
return firstLine;
|
|
83
|
-
}
|
|
84
|
-
function buildCandidateAgents(agentRegistry, opts) {
|
|
85
|
-
const entryId = opts?.entryAgentId;
|
|
86
|
-
const allowed = opts?.allowedAgentIds;
|
|
87
|
-
const allowSet = allowed ? new Set(allowed) : void 0;
|
|
88
|
-
const candidates = [];
|
|
89
|
-
for (const [id, agent] of Object.entries(agentRegistry)) {
|
|
90
|
-
if (id === entryId) continue;
|
|
91
|
-
if (allowSet && !allowSet.has(id)) continue;
|
|
92
|
-
const agentTools = agent.can_execute_tools ? [...agent.can_execute_tools] : [];
|
|
93
|
-
const derivedToolchains = opts?.toolchainsByAgent?.get(id);
|
|
94
|
-
if (derivedToolchains) {
|
|
95
|
-
for (const tc of derivedToolchains) {
|
|
96
|
-
if (!agentTools.includes(tc.id)) {
|
|
97
|
-
agentTools.push(tc.id);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
candidates.push({
|
|
102
|
-
name: id,
|
|
103
|
-
description: deriveDescription(agent.purpose),
|
|
104
|
-
prompt: renderAgentSystemPrompt(agent),
|
|
105
|
-
...agentTools.length > 0 ? { tools: agentTools } : {}
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
return candidates;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// src/lib/analyzer-bridge.ts
|
|
112
|
-
var ANALYZER_PKG = "artifact-contracts-analyzer";
|
|
113
|
-
async function loadAnalyzerModule() {
|
|
114
|
-
const mod = await import(
|
|
115
|
-
/* webpackIgnore: true */
|
|
116
|
-
ANALYZER_PKG
|
|
117
|
-
);
|
|
118
|
-
return mod;
|
|
119
|
-
}
|
|
120
|
-
function createAnalyzerBridge(options) {
|
|
121
|
-
const { projectRoot, navigationIndex, artifactPatterns, manifests } = options;
|
|
122
|
-
let cachedGraph = null;
|
|
123
|
-
let cachedFileContents = null;
|
|
124
|
-
let graphBuildPromise = null;
|
|
125
|
-
async function ensureGraph() {
|
|
126
|
-
if (cachedGraph) return cachedGraph;
|
|
127
|
-
if (graphBuildPromise) {
|
|
128
|
-
await graphBuildPromise;
|
|
129
|
-
return cachedGraph;
|
|
130
|
-
}
|
|
131
|
-
graphBuildPromise = doBuildGraph();
|
|
132
|
-
await graphBuildPromise;
|
|
133
|
-
return cachedGraph;
|
|
134
|
-
}
|
|
135
|
-
async function doBuildGraph() {
|
|
136
|
-
let mod;
|
|
137
|
-
try {
|
|
138
|
-
mod = await loadAnalyzerModule();
|
|
139
|
-
} catch (error) {
|
|
140
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
141
|
-
throw new Error(
|
|
142
|
-
`artifact-contracts-analyzer is not available. Install it to use analyzer features: ${msg}`
|
|
143
|
-
);
|
|
144
|
-
}
|
|
145
|
-
const patterns = artifactPatterns ?? /* @__PURE__ */ new Map();
|
|
146
|
-
const registry = mod.createDefaultRegistry();
|
|
147
|
-
const astResult = await mod.buildAstGraph({
|
|
148
|
-
projectRoot,
|
|
149
|
-
artifactPatterns: patterns,
|
|
150
|
-
registry
|
|
151
|
-
});
|
|
152
|
-
cachedFileContents = astResult.fileContents;
|
|
153
|
-
cachedGraph = await mod.buildDependencyGraph({
|
|
154
|
-
ast: astResult.graph,
|
|
155
|
-
projectRoot,
|
|
156
|
-
artifactPatterns: patterns,
|
|
157
|
-
manifests: manifests ?? []
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
const bridge = {
|
|
161
|
-
async buildGraph() {
|
|
162
|
-
await ensureGraph();
|
|
163
|
-
},
|
|
164
|
-
async getGraph() {
|
|
165
|
-
return ensureGraph();
|
|
166
|
-
},
|
|
167
|
-
async analyzeImpact(changed, opts) {
|
|
168
|
-
let mod;
|
|
169
|
-
try {
|
|
170
|
-
mod = await loadAnalyzerModule();
|
|
171
|
-
} catch {
|
|
172
|
-
return {
|
|
173
|
-
error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use impact analysis.",
|
|
174
|
-
changed
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
const graph = await ensureGraph();
|
|
178
|
-
return mod.analyzeImpact({
|
|
179
|
-
graph,
|
|
180
|
-
changed,
|
|
181
|
-
direction: opts?.direction ?? "downstream",
|
|
182
|
-
...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
|
|
183
|
-
...opts?.limit !== void 0 ? { limit: opts.limit } : {},
|
|
184
|
-
...navigationIndex ? { navigationIndex } : {}
|
|
185
|
-
});
|
|
186
|
-
},
|
|
187
|
-
async generateContextPack(changed, opts) {
|
|
188
|
-
let mod;
|
|
189
|
-
try {
|
|
190
|
-
mod = await loadAnalyzerModule();
|
|
191
|
-
} catch {
|
|
192
|
-
return {
|
|
193
|
-
entries: [],
|
|
194
|
-
metadata: {
|
|
195
|
-
totalTokens: 0,
|
|
196
|
-
budgetTokens: opts?.budgetTokens ?? 5e4,
|
|
197
|
-
filesIncluded: 0,
|
|
198
|
-
filesExcluded: 0,
|
|
199
|
-
filesReferenced: 0,
|
|
200
|
-
artifactsCovered: [],
|
|
201
|
-
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
202
|
-
}
|
|
203
|
-
};
|
|
204
|
-
}
|
|
205
|
-
const graph = await ensureGraph();
|
|
206
|
-
return mod.generateContextPack({
|
|
207
|
-
graph,
|
|
208
|
-
changed,
|
|
209
|
-
projectRoot,
|
|
210
|
-
...opts?.budgetTokens !== void 0 ? { budgetTokens: opts.budgetTokens } : {},
|
|
211
|
-
...opts?.granularity ? { granularity: opts.granularity } : {},
|
|
212
|
-
...navigationIndex ? { navigationIndex } : {},
|
|
213
|
-
...cachedFileContents ? { fileContents: cachedFileContents } : {}
|
|
214
|
-
});
|
|
215
|
-
},
|
|
216
|
-
async buildCallGraph(entry, opts) {
|
|
217
|
-
let mod;
|
|
218
|
-
try {
|
|
219
|
-
mod = await loadAnalyzerModule();
|
|
220
|
-
} catch {
|
|
221
|
-
return {
|
|
222
|
-
error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use call graph analysis.",
|
|
223
|
-
entry
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
const graph = await ensureGraph();
|
|
227
|
-
return mod.buildCallGraph({
|
|
228
|
-
graph,
|
|
229
|
-
entry,
|
|
230
|
-
...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
|
|
231
|
-
...opts?.direction ? { direction: opts.direction } : {}
|
|
232
|
-
});
|
|
233
|
-
},
|
|
234
|
-
invalidateCache() {
|
|
235
|
-
cachedGraph = null;
|
|
236
|
-
cachedFileContents = null;
|
|
237
|
-
graphBuildPromise = null;
|
|
238
|
-
},
|
|
239
|
-
buildAnalyzerTools() {
|
|
240
|
-
return [
|
|
241
|
-
{
|
|
242
|
-
name: "analyzer.analyzeImpact",
|
|
243
|
-
description: "Analyze the impact of changed files across the dependency graph",
|
|
244
|
-
inputSchema: {
|
|
245
|
-
type: "object",
|
|
246
|
-
properties: {
|
|
247
|
-
changed: {
|
|
248
|
-
type: "array",
|
|
249
|
-
items: { type: "string" },
|
|
250
|
-
description: "File paths that changed"
|
|
251
|
-
},
|
|
252
|
-
direction: {
|
|
253
|
-
type: "string",
|
|
254
|
-
enum: ["downstream", "upstream"],
|
|
255
|
-
description: "Traversal direction. downstream = what breaks if this changes"
|
|
256
|
-
},
|
|
257
|
-
maxDepth: {
|
|
258
|
-
type: "number",
|
|
259
|
-
description: "Maximum BFS depth to explore"
|
|
260
|
-
},
|
|
261
|
-
limit: {
|
|
262
|
-
type: "number",
|
|
263
|
-
description: "Cap the number of affected entries returned"
|
|
264
|
-
}
|
|
265
|
-
},
|
|
266
|
-
required: ["changed"]
|
|
267
|
-
},
|
|
268
|
-
handler: async (args) => {
|
|
269
|
-
const changed = args.changed;
|
|
270
|
-
const result = await bridge.analyzeImpact(changed, {
|
|
271
|
-
direction: args.direction,
|
|
272
|
-
maxDepth: args.maxDepth,
|
|
273
|
-
limit: args.limit
|
|
274
|
-
});
|
|
275
|
-
return JSON.stringify(result);
|
|
276
|
-
}
|
|
277
|
-
},
|
|
278
|
-
{
|
|
279
|
-
name: "analyzer.generateContextPack",
|
|
280
|
-
description: "Generate a token-budget-constrained context pack for changed files",
|
|
281
|
-
inputSchema: {
|
|
282
|
-
type: "object",
|
|
283
|
-
properties: {
|
|
284
|
-
changed: {
|
|
285
|
-
type: "array",
|
|
286
|
-
items: { type: "string" },
|
|
287
|
-
description: "File paths that changed"
|
|
288
|
-
},
|
|
289
|
-
budgetTokens: {
|
|
290
|
-
type: "number",
|
|
291
|
-
description: "Token budget for the context pack"
|
|
292
|
-
},
|
|
293
|
-
granularity: {
|
|
294
|
-
type: "string",
|
|
295
|
-
enum: ["file", "symbol"],
|
|
296
|
-
description: "Context granularity level"
|
|
297
|
-
}
|
|
298
|
-
},
|
|
299
|
-
required: ["changed"]
|
|
300
|
-
},
|
|
301
|
-
handler: async (args) => {
|
|
302
|
-
const changed = args.changed;
|
|
303
|
-
const result = await bridge.generateContextPack(changed, {
|
|
304
|
-
budgetTokens: args.budgetTokens,
|
|
305
|
-
granularity: args.granularity
|
|
306
|
-
});
|
|
307
|
-
return JSON.stringify(result);
|
|
308
|
-
}
|
|
309
|
-
},
|
|
310
|
-
{
|
|
311
|
-
name: "analyzer.buildCallGraph",
|
|
312
|
-
description: "Build a call graph rooted at a symbol",
|
|
313
|
-
inputSchema: {
|
|
314
|
-
type: "object",
|
|
315
|
-
properties: {
|
|
316
|
-
entry: {
|
|
317
|
-
type: "string",
|
|
318
|
-
description: "Entry symbolId (filePath#name) to root the call graph at"
|
|
319
|
-
},
|
|
320
|
-
maxDepth: {
|
|
321
|
-
type: "number",
|
|
322
|
-
description: "Maximum traversal depth"
|
|
323
|
-
},
|
|
324
|
-
direction: {
|
|
325
|
-
type: "string",
|
|
326
|
-
enum: ["forward", "reverse"],
|
|
327
|
-
description: "Traversal direction: forward (callees) or reverse (callers)"
|
|
328
|
-
}
|
|
329
|
-
},
|
|
330
|
-
required: ["entry"]
|
|
331
|
-
},
|
|
332
|
-
handler: async (args) => {
|
|
333
|
-
const entry = args.entry;
|
|
334
|
-
const result = await bridge.buildCallGraph(entry, {
|
|
335
|
-
maxDepth: args.maxDepth,
|
|
336
|
-
direction: args.direction
|
|
337
|
-
});
|
|
338
|
-
return JSON.stringify(result);
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
];
|
|
342
|
-
}
|
|
343
|
-
};
|
|
344
|
-
return bridge;
|
|
345
|
-
}
|
|
346
|
-
function isContextPack(value) {
|
|
347
|
-
if (typeof value !== "object" || value === null) return false;
|
|
348
|
-
const obj = value;
|
|
349
|
-
if (!Array.isArray(obj.entries)) return false;
|
|
350
|
-
if (typeof obj.metadata !== "object" || obj.metadata === null) return false;
|
|
351
|
-
const meta = obj.metadata;
|
|
352
|
-
return typeof meta.totalTokens === "number" && typeof meta.budgetTokens === "number";
|
|
353
|
-
}
|
|
354
|
-
function renderContextPackPrompt(pack) {
|
|
355
|
-
const m = pack.metadata;
|
|
356
|
-
const sections = [];
|
|
357
|
-
sections.push("## Source Code Context");
|
|
358
|
-
sections.push(
|
|
359
|
-
`### Budget
|
|
360
|
-
- Tokens used: ${m.totalTokens} / ${m.budgetTokens}
|
|
361
|
-
- Files included: ${m.filesIncluded}, excluded: ${m.filesExcluded}, referenced: ${m.filesReferenced}`
|
|
362
|
-
);
|
|
363
|
-
if (m.artifactsCovered.length > 0) {
|
|
364
|
-
sections.push(
|
|
365
|
-
`### Affected Artifacts
|
|
366
|
-
${m.artifactsCovered.map((a) => `- ${a}`).join("\n")}`
|
|
367
|
-
);
|
|
368
|
-
}
|
|
369
|
-
if (pack.entries.length > 0) {
|
|
370
|
-
const fileBlocks = [];
|
|
371
|
-
for (const entry of pack.entries) {
|
|
372
|
-
const ext = entry.path.split(".").pop() ?? "";
|
|
373
|
-
const header = `#### ${entry.path} (relevance: ${entry.relevanceScore}, mode: ${entry.contentMode})`;
|
|
374
|
-
const reason = `> ${entry.reason}`;
|
|
375
|
-
if (entry.content) {
|
|
376
|
-
fileBlocks.push(
|
|
377
|
-
`${header}
|
|
378
|
-
${reason}
|
|
379
|
-
|
|
380
|
-
\`\`\`${ext}
|
|
381
|
-
${entry.content}
|
|
382
|
-
\`\`\``
|
|
383
|
-
);
|
|
384
|
-
} else {
|
|
385
|
-
fileBlocks.push(`${header}
|
|
386
|
-
${reason}`);
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
sections.push(`### Files
|
|
390
|
-
${fileBlocks.join("\n\n")}`);
|
|
391
|
-
}
|
|
392
|
-
return sections.join("\n\n");
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
// src/lib/task-runner.ts
|
|
396
|
-
function getZodChecks(schema) {
|
|
397
|
-
const def = schema._def;
|
|
398
|
-
return def?.checks ?? [];
|
|
399
|
-
}
|
|
400
|
-
function extractZodConstraints(schema) {
|
|
401
|
-
const inner = unwrapOptional(schema);
|
|
402
|
-
const parts = [];
|
|
403
|
-
if (inner instanceof z.ZodString) {
|
|
404
|
-
const str = inner;
|
|
405
|
-
if (str.minLength != null) parts.push(`min: ${str.minLength}`);
|
|
406
|
-
if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);
|
|
407
|
-
for (const check of getZodChecks(inner)) {
|
|
408
|
-
if (check.kind === "min") parts.push(`min: ${check.value}`);
|
|
409
|
-
if (check.kind === "max") parts.push(`max: ${check.value}`);
|
|
410
|
-
if (check.kind === "regex" && check.regex) parts.push(`regex: ${check.regex}`);
|
|
411
|
-
const def = check._zod?.def;
|
|
412
|
-
if (def?.format === "regex" && def.pattern instanceof RegExp) {
|
|
413
|
-
parts.push(`regex: ${def.pattern}`);
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
} else if (inner instanceof z.ZodNumber) {
|
|
417
|
-
let hasInt = false;
|
|
418
|
-
for (const check of getZodChecks(inner)) {
|
|
419
|
-
if (check.kind === "int") hasInt = true;
|
|
420
|
-
if (check.kind === "min") parts.push(`min: ${check.value}`);
|
|
421
|
-
if (check.kind === "max") parts.push(`max: ${check.value}`);
|
|
422
|
-
if (check.isInt) hasInt = true;
|
|
423
|
-
const def = check._zod?.def;
|
|
424
|
-
if (def?.check === "number_format" && def.format === "safeint") hasInt = true;
|
|
425
|
-
if (def?.check === "greater_than") parts.push(`min: ${def.value}`);
|
|
426
|
-
if (def?.check === "less_than") parts.push(`max: ${def.value}`);
|
|
427
|
-
}
|
|
428
|
-
if (hasInt) parts.unshift("int");
|
|
429
|
-
} else if (inner instanceof z.ZodArray) {
|
|
430
|
-
for (const check of getZodChecks(inner)) {
|
|
431
|
-
if (check.kind === "min") parts.push(`min: ${check.value}`);
|
|
432
|
-
if (check.kind === "max") parts.push(`max: ${check.value}`);
|
|
433
|
-
const def = check._zod?.def;
|
|
434
|
-
if (def?.check === "min_length") parts.push(`min: ${def.minimum}`);
|
|
435
|
-
if (def?.check === "max_length") parts.push(`max: ${def.maximum}`);
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
return parts.length > 0 ? parts.join(", ") : void 0;
|
|
439
|
-
}
|
|
440
|
-
function zodTypeToString(schema) {
|
|
441
|
-
if (schema instanceof z.ZodString) return "string";
|
|
442
|
-
if (schema instanceof z.ZodNumber) return "number";
|
|
443
|
-
if (schema instanceof z.ZodBoolean) return "boolean";
|
|
444
|
-
if (schema instanceof z.ZodEnum) return `enum(${schema.options.join(", ")})`;
|
|
445
|
-
if (schema instanceof z.ZodLiteral) return `"${String(schema._def.values[0])}"`;
|
|
446
|
-
if (schema instanceof z.ZodArray) {
|
|
447
|
-
const element = schema._def.element;
|
|
448
|
-
const inner = zodTypeToString(element);
|
|
449
|
-
return `${inner}[]`;
|
|
450
|
-
}
|
|
451
|
-
if (schema instanceof z.ZodObject) return "object";
|
|
452
|
-
if (schema instanceof z.ZodOptional) {
|
|
453
|
-
return zodTypeToString(schema._def.innerType);
|
|
454
|
-
}
|
|
455
|
-
if (schema instanceof z.ZodRecord) return "Record<string, unknown>";
|
|
456
|
-
return "unknown";
|
|
457
|
-
}
|
|
458
|
-
function unwrapOptional(schema) {
|
|
459
|
-
if (schema instanceof z.ZodOptional) {
|
|
460
|
-
return schema._def.innerType;
|
|
461
|
-
}
|
|
462
|
-
return schema;
|
|
463
|
-
}
|
|
464
|
-
function getArrayElement(schema) {
|
|
465
|
-
const inner = unwrapOptional(schema);
|
|
466
|
-
if (inner instanceof z.ZodArray) {
|
|
467
|
-
return inner._def.element;
|
|
468
|
-
}
|
|
469
|
-
return null;
|
|
470
|
-
}
|
|
471
|
-
function extractFieldDescriptors(schema) {
|
|
472
|
-
let shape = null;
|
|
473
|
-
if (schema instanceof z.ZodObject) {
|
|
474
|
-
shape = schema.shape;
|
|
475
|
-
}
|
|
476
|
-
if (!shape) return null;
|
|
477
|
-
return Object.entries(shape).map(([name, field]) => {
|
|
478
|
-
const isOptional = field instanceof z.ZodOptional;
|
|
479
|
-
const innerField = isOptional ? field._def.innerType : field;
|
|
480
|
-
const description = innerField.description ?? field.description;
|
|
481
|
-
return {
|
|
482
|
-
name,
|
|
483
|
-
type: zodTypeToString(field),
|
|
484
|
-
required: !isOptional,
|
|
485
|
-
description,
|
|
486
|
-
constraints: extractZodConstraints(innerField)
|
|
487
|
-
};
|
|
488
|
-
});
|
|
489
|
-
}
|
|
490
|
-
function zodSchemaToPromptDescription(schema) {
|
|
491
|
-
const tables = [];
|
|
492
|
-
collectFieldTables(schema, "", tables);
|
|
493
|
-
return tables.join("\n\n");
|
|
494
|
-
}
|
|
495
|
-
function collectFieldTables(schema, pathPrefix, tables) {
|
|
496
|
-
const fields = extractFieldDescriptors(schema);
|
|
497
|
-
if (!fields || fields.length === 0) return;
|
|
498
|
-
const title = pathPrefix ? `**${pathPrefix}**
|
|
499
|
-
|
|
500
|
-
` : "";
|
|
501
|
-
const header = "| Field | Type | Required | Constraints | Description |";
|
|
502
|
-
const sep = "|-------|------|----------|-------------|-------------|";
|
|
503
|
-
const rows = fields.map(
|
|
504
|
-
(f) => `| ${f.name} | ${f.type} | ${f.required ? "Yes" : "No"} | ${f.constraints ?? ""} | ${f.description ?? ""} |`
|
|
505
|
-
);
|
|
506
|
-
tables.push(`${title}${[header, sep, ...rows].join("\n")}`);
|
|
507
|
-
const shape = schema instanceof z.ZodObject ? schema.shape : null;
|
|
508
|
-
if (!shape) return;
|
|
509
|
-
for (const f of fields) {
|
|
510
|
-
const rawField = shape[f.name];
|
|
511
|
-
const inner = unwrapOptional(rawField);
|
|
512
|
-
if (inner instanceof z.ZodObject) {
|
|
513
|
-
collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);
|
|
514
|
-
} else if (inner instanceof z.ZodArray) {
|
|
515
|
-
const element = inner._def.element;
|
|
516
|
-
if (element instanceof z.ZodObject) {
|
|
517
|
-
collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
function zodSchemaToYamlExample(schema, maxDepth = 3) {
|
|
523
|
-
return renderYamlObject(schema, 0, maxDepth);
|
|
524
|
-
}
|
|
525
|
-
function renderYamlObject(schema, indent, maxDepth) {
|
|
526
|
-
const fields = extractFieldDescriptors(schema);
|
|
527
|
-
if (!fields || fields.length === 0) return "";
|
|
528
|
-
const prefix = " ".repeat(indent);
|
|
529
|
-
const lines = [];
|
|
530
|
-
for (const f of fields) {
|
|
531
|
-
const shape = schema instanceof z.ZodObject ? schema.shape : null;
|
|
532
|
-
const rawField = shape?.[f.name];
|
|
533
|
-
if (f.type.endsWith("[]")) {
|
|
534
|
-
lines.push(`${prefix}${f.name}:`);
|
|
535
|
-
const element = rawField ? getArrayElement(rawField) : null;
|
|
536
|
-
if (element && element instanceof z.ZodObject && indent < maxDepth) {
|
|
537
|
-
const nested = renderYamlObject(element, indent + 2, maxDepth);
|
|
538
|
-
if (nested) {
|
|
539
|
-
const basePrefix = " ".repeat(indent + 2);
|
|
540
|
-
const nestedLines = nested.split("\n");
|
|
541
|
-
lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);
|
|
542
|
-
for (let i = 1; i < nestedLines.length; i++) {
|
|
543
|
-
lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);
|
|
544
|
-
}
|
|
545
|
-
} else {
|
|
546
|
-
lines.push(`${prefix} - key: "value"`);
|
|
547
|
-
}
|
|
548
|
-
} else if (f.type === "string[]") {
|
|
549
|
-
lines.push(`${prefix} - "example"`);
|
|
550
|
-
} else {
|
|
551
|
-
lines.push(`${prefix} - key: "value"`);
|
|
552
|
-
}
|
|
553
|
-
} else if (f.type === "object" && indent < maxDepth) {
|
|
554
|
-
const inner = rawField ? unwrapOptional(rawField) : null;
|
|
555
|
-
if (inner && inner instanceof z.ZodObject) {
|
|
556
|
-
lines.push(`${prefix}${f.name}:`);
|
|
557
|
-
const nested = renderYamlObject(inner, indent + 1, maxDepth);
|
|
558
|
-
if (nested) {
|
|
559
|
-
lines.push(nested);
|
|
560
|
-
} else {
|
|
561
|
-
lines.push(`${prefix} key: "value"`);
|
|
562
|
-
}
|
|
563
|
-
} else {
|
|
564
|
-
lines.push(`${prefix}${f.name}:`);
|
|
565
|
-
lines.push(`${prefix} key: "value"`);
|
|
566
|
-
}
|
|
567
|
-
} else if (f.type === "string") {
|
|
568
|
-
lines.push(`${prefix}${f.name}: "..."`);
|
|
569
|
-
} else if (f.type === "number") {
|
|
570
|
-
lines.push(`${prefix}${f.name}: 0`);
|
|
571
|
-
} else if (f.type === "boolean") {
|
|
572
|
-
lines.push(`${prefix}${f.name}: false`);
|
|
573
|
-
} else if (f.type.startsWith("enum(")) {
|
|
574
|
-
const enumVals = f.type.slice(5, -1).split(", ");
|
|
575
|
-
lines.push(`${prefix}${f.name}: "${enumVals[0]}"`);
|
|
576
|
-
} else {
|
|
577
|
-
lines.push(`${prefix}${f.name}: "..."`);
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
return lines.join("\n");
|
|
581
|
-
}
|
|
582
|
-
function isNavigationIndex(value) {
|
|
583
|
-
if (typeof value !== "object" || value === null) return false;
|
|
584
|
-
const obj = value;
|
|
585
|
-
return typeof obj.system === "object" && obj.system !== null && typeof obj.artifacts === "object" && obj.artifacts !== null;
|
|
586
|
-
}
|
|
587
|
-
function renderNavigationIndexPrompt(navigationIndex) {
|
|
588
|
-
const system = navigationIndex.system;
|
|
589
|
-
const artifacts = navigationIndex.artifacts ?? {};
|
|
590
|
-
const ids = Object.keys(artifacts);
|
|
591
|
-
const sections = ["## Project Navigation Index"];
|
|
592
|
-
const systemLabel = system?.name ? `${system.name}${system.id ? ` (${system.id})` : ""}` : system?.id ?? "unknown";
|
|
593
|
-
sections.push(
|
|
594
|
-
`System: ${systemLabel}
|
|
595
|
-
Artifacts: ${ids.length}`
|
|
596
|
-
);
|
|
597
|
-
if (ids.length > 0) {
|
|
598
|
-
const lines = [];
|
|
599
|
-
for (const id of ids) {
|
|
600
|
-
const node = artifacts[id] ?? {};
|
|
601
|
-
const props = node.properties ?? {};
|
|
602
|
-
const tags = [props.type, props.authority].filter((v) => typeof v === "string" && v.length > 0).join(", ");
|
|
603
|
-
const editPolicy = typeof props.manual_edit === "string" ? `, edit:${props.manual_edit}` : "";
|
|
604
|
-
lines.push(`- ${id}${tags || editPolicy ? ` [${tags}${editPolicy}]` : ""}`);
|
|
605
|
-
const patterns = node.files?.path_patterns;
|
|
606
|
-
if (Array.isArray(patterns) && patterns.length > 0) {
|
|
607
|
-
lines.push(` files: ${patterns.join(", ")}`);
|
|
608
|
-
}
|
|
609
|
-
const derived = node.relations?.derived_artifacts;
|
|
610
|
-
if (Array.isArray(derived) && derived.length > 0) {
|
|
611
|
-
lines.push(` derived \u2192 ${derived.join(", ")}`);
|
|
612
|
-
}
|
|
613
|
-
const owners = node.agents?.owners;
|
|
614
|
-
if (Array.isArray(owners) && owners.length > 0) {
|
|
615
|
-
lines.push(` owners: ${owners.join(", ")}`);
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
sections.push(lines.join("\n"));
|
|
619
|
-
}
|
|
620
|
-
return sections.join("\n\n");
|
|
621
|
-
}
|
|
622
|
-
function collectAnalyzerToolIds(registry) {
|
|
623
|
-
if (!registry) return [];
|
|
624
|
-
return registry.getAll().map((def) => def.toolId).filter((id) => id.startsWith("analyzer."));
|
|
625
|
-
}
|
|
626
|
-
function shouldInjectAnalyzerExplorationMandate(context) {
|
|
627
|
-
return isNavigationIndex(context.variables?.navigationIndex);
|
|
628
|
-
}
|
|
629
|
-
function renderAnalyzerExplorationMandatePrompt(toolIds) {
|
|
630
|
-
const tools = toolIds.length > 0 ? toolIds.map((id) => `- \`${id}\``).join("\n") : "- `analyzer.generateContextPack`\n- `analyzer.analyzeImpact`\n- `analyzer.buildCallGraph`";
|
|
631
|
-
return [
|
|
632
|
-
"## Codebase Exploration Protocol (Level 1)",
|
|
633
|
-
"",
|
|
634
|
-
"A Project Navigation Index is provided in the user prompt. When you need to",
|
|
635
|
-
"investigate the codebase (locate affected files, trace dependencies, or scope",
|
|
636
|
-
"changes), you MUST use the analyzer MCP tools **before** ad-hoc Read/Grep/Glob:",
|
|
637
|
-
"",
|
|
638
|
-
"1. Use the navigation index to pick candidate artifacts and path patterns.",
|
|
639
|
-
"2. Call `analyzer.generateContextPack` with your `changed[]` paths and a token budget.",
|
|
640
|
-
"3. Call `analyzer.analyzeImpact` with the same `changed[]` paths.",
|
|
641
|
-
"4. Use Read/Grep/Glob only for gaps the analyzer output did not cover.",
|
|
642
|
-
"",
|
|
643
|
-
"Available analyzer tools:",
|
|
644
|
-
tools
|
|
645
|
-
].join("\n");
|
|
646
|
-
}
|
|
647
|
-
function buildSplitTaskPrompt(agent, task, context, options) {
|
|
648
|
-
const system = [];
|
|
649
|
-
system.push(renderAgentSystemPrompt(agent));
|
|
650
|
-
if (options?.analyzerExploration?.toolIds.length && shouldInjectAnalyzerExplorationMandate(context)) {
|
|
651
|
-
system.push(
|
|
652
|
-
renderAnalyzerExplorationMandatePrompt(options.analyzerExploration.toolIds)
|
|
653
|
-
);
|
|
654
|
-
}
|
|
655
|
-
system.push(`## Task: ${task.id}
|
|
656
|
-
|
|
657
|
-
${task.description}`);
|
|
658
|
-
if (task.completion_criteria.length > 0) {
|
|
659
|
-
system.push(
|
|
660
|
-
`## Completion Criteria
|
|
661
|
-
|
|
662
|
-
${task.completion_criteria.map((c) => `- ${c}`).join("\n")}`
|
|
663
|
-
);
|
|
664
|
-
}
|
|
665
|
-
const handoffId = task.result_handoff;
|
|
666
|
-
const schema = options?.handoffSchemas?.[handoffId];
|
|
667
|
-
let outputSection = `## Required Output Format
|
|
668
|
-
|
|
669
|
-
Return your result as a YAML block matching the "${handoffId}" schema.`;
|
|
670
|
-
if (schema) {
|
|
671
|
-
const fieldTable = zodSchemaToPromptDescription(schema);
|
|
672
|
-
if (fieldTable) {
|
|
673
|
-
outputSection += `
|
|
674
|
-
|
|
675
|
-
${fieldTable}`;
|
|
676
|
-
}
|
|
677
|
-
const yamlExample = zodSchemaToYamlExample(schema);
|
|
678
|
-
if (yamlExample) {
|
|
679
|
-
outputSection += `
|
|
680
|
-
|
|
681
|
-
Example:
|
|
682
|
-
|
|
683
|
-
\`\`\`yaml
|
|
684
|
-
${yamlExample}
|
|
685
|
-
\`\`\``;
|
|
686
|
-
}
|
|
687
|
-
} else {
|
|
688
|
-
outputSection += ` Include all required fields.`;
|
|
689
|
-
}
|
|
690
|
-
system.push(outputSection);
|
|
691
|
-
if (options?.retry) {
|
|
692
|
-
const r = options.retry;
|
|
693
|
-
let recoverySection = `## Recovery Instructions
|
|
694
|
-
|
|
695
|
-
If the task fails due to: "${r.condition}"
|
|
696
|
-
\u2192 Apply the recovery approach from task "${r.fix_task}"`;
|
|
697
|
-
if (r.revalidate_task) {
|
|
698
|
-
recoverySection += `
|
|
699
|
-
\u2192 Then revalidate using task "${r.revalidate_task}"`;
|
|
700
|
-
}
|
|
701
|
-
system.push(recoverySection);
|
|
702
|
-
}
|
|
703
|
-
const userSections = [];
|
|
704
|
-
if (context.handoff_input) {
|
|
705
|
-
const hi = context.handoff_input;
|
|
706
|
-
const payloadStr = typeof hi.payload === "string" ? hi.payload : yaml.stringify(hi.payload);
|
|
707
|
-
userSections.push(`## User Request
|
|
708
|
-
|
|
709
|
-
${context.user_request}`);
|
|
710
|
-
userSections.push(`## Handoff Input (${hi.type})
|
|
711
|
-
|
|
712
|
-
\`\`\`yaml
|
|
713
|
-
${payloadStr}\`\`\``);
|
|
714
|
-
} else {
|
|
715
|
-
userSections.push(`## User Request
|
|
716
|
-
|
|
717
|
-
${context.user_request}`);
|
|
718
|
-
}
|
|
719
|
-
if (context.prior_context) {
|
|
720
|
-
userSections.push(`## Prior Context
|
|
721
|
-
|
|
722
|
-
${context.prior_context}`);
|
|
723
|
-
}
|
|
724
|
-
if (context.relevant_paths && context.relevant_paths.length > 0) {
|
|
725
|
-
userSections.push(
|
|
726
|
-
`## Relevant Files
|
|
727
|
-
|
|
728
|
-
${context.relevant_paths.map((p) => `- ${p}`).join("\n")}`
|
|
729
|
-
);
|
|
730
|
-
}
|
|
731
|
-
if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {
|
|
732
|
-
userSections.push(
|
|
733
|
-
`## Acceptance Criteria
|
|
734
|
-
|
|
735
|
-
${context.acceptance_criteria.map((c) => `- ${c}`).join("\n")}`
|
|
736
|
-
);
|
|
737
|
-
}
|
|
738
|
-
if (context.variables && Object.keys(context.variables).length > 0) {
|
|
739
|
-
const contextPack = context.variables.analyzerContextPack;
|
|
740
|
-
if (isContextPack(contextPack)) {
|
|
741
|
-
userSections.push(renderContextPackPrompt(contextPack));
|
|
742
|
-
}
|
|
743
|
-
const navigationIndex = context.variables.navigationIndex;
|
|
744
|
-
if (isNavigationIndex(navigationIndex)) {
|
|
745
|
-
userSections.push(renderNavigationIndexPrompt(navigationIndex));
|
|
746
|
-
}
|
|
747
|
-
const otherVars = Object.entries(context.variables).filter(
|
|
748
|
-
([k]) => k !== "analyzerContextPack" && k !== "navigationIndex"
|
|
749
|
-
);
|
|
750
|
-
if (otherVars.length > 0) {
|
|
751
|
-
const varLines = otherVars.map(([k, v]) => `- ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join("\n");
|
|
752
|
-
userSections.push(`## Context Variables
|
|
753
|
-
|
|
754
|
-
${varLines}`);
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
return {
|
|
758
|
-
system,
|
|
759
|
-
user: userSections.join("\n\n---\n\n")
|
|
760
|
-
};
|
|
761
|
-
}
|
|
762
|
-
function joinSplitPrompt(split) {
|
|
763
|
-
return [...split.system, split.user].join("\n\n---\n\n");
|
|
764
|
-
}
|
|
765
|
-
function buildTaskPrompt(agent, task, context, options) {
|
|
766
|
-
return joinSplitPrompt(buildSplitTaskPrompt(agent, task, context, options));
|
|
767
|
-
}
|
|
768
|
-
function extractStructuredResult(raw) {
|
|
769
|
-
const yamlMatch = raw.match(/```ya?ml\n([\s\S]*?)```/);
|
|
770
|
-
if (yamlMatch) {
|
|
771
|
-
try {
|
|
772
|
-
return yaml.parse(yamlMatch[1]);
|
|
773
|
-
} catch {
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
const jsonMatch = raw.match(/```json\n([\s\S]*?)```/);
|
|
777
|
-
if (jsonMatch) {
|
|
778
|
-
try {
|
|
779
|
-
return JSON.parse(jsonMatch[1]);
|
|
780
|
-
} catch {
|
|
781
|
-
}
|
|
782
|
-
}
|
|
783
|
-
try {
|
|
784
|
-
return JSON.parse(raw);
|
|
785
|
-
} catch {
|
|
786
|
-
}
|
|
787
|
-
return null;
|
|
788
|
-
}
|
|
789
|
-
function validateOutput(fullOutput, task, schemas) {
|
|
790
|
-
if (!fullOutput.trim()) {
|
|
791
|
-
return { status: "error", message: "Agent returned empty output" };
|
|
792
|
-
}
|
|
793
|
-
const parsed = extractStructuredResult(fullOutput);
|
|
794
|
-
if (!parsed) {
|
|
795
|
-
return {
|
|
796
|
-
status: "validation_error",
|
|
797
|
-
errors: new z.ZodError([{ code: "custom", message: "Could not extract structured result from agent output", path: [] }]),
|
|
798
|
-
raw: fullOutput
|
|
799
|
-
};
|
|
800
|
-
}
|
|
801
|
-
const schema = schemas[task.result_handoff];
|
|
802
|
-
if (!schema) {
|
|
803
|
-
return { status: "success", data: parsed, raw: fullOutput };
|
|
804
|
-
}
|
|
805
|
-
const validation = schema.safeParse(parsed);
|
|
806
|
-
if (!validation.success) {
|
|
807
|
-
return { status: "validation_error", errors: validation.error, raw: fullOutput };
|
|
808
|
-
}
|
|
809
|
-
const data = validation.data;
|
|
810
|
-
if (data.escalation_needed === true) {
|
|
811
|
-
return {
|
|
812
|
-
status: "escalation",
|
|
813
|
-
reason: data.escalation_reasons ?? "Agent requested escalation",
|
|
814
|
-
raw: fullOutput
|
|
815
|
-
};
|
|
816
|
-
}
|
|
817
|
-
return { status: "success", data: validation.data, raw: fullOutput };
|
|
818
|
-
}
|
|
819
|
-
function attachMemoryRef(outcome, adapter) {
|
|
820
|
-
if (outcome.status !== "success") return outcome;
|
|
821
|
-
const ref = adapter.getLastMemoryRef?.();
|
|
822
|
-
if (!ref) return outcome;
|
|
823
|
-
return { ...outcome, memoryRef: ref };
|
|
824
|
-
}
|
|
825
|
-
function buildRetryFollowUp(task, lastOutcome, options) {
|
|
826
|
-
const sections = [];
|
|
827
|
-
sections.push(
|
|
828
|
-
"Your previous response could not be validated. The task work itself is fine \u2014 please re-output only the structured result block in the correct format."
|
|
829
|
-
);
|
|
830
|
-
if (lastOutcome.status === "validation_error") {
|
|
831
|
-
sections.push(`Validation errors:
|
|
832
|
-
${lastOutcome.errors.message}`);
|
|
833
|
-
} else if (lastOutcome.status === "error") {
|
|
834
|
-
sections.push(`Error: ${lastOutcome.message}`);
|
|
835
|
-
}
|
|
836
|
-
const handoffId = task.result_handoff;
|
|
837
|
-
const schema = options?.handoffSchemas?.[handoffId];
|
|
838
|
-
let formatSection = `Required format: Return your result as a YAML block matching the "${handoffId}" schema.`;
|
|
839
|
-
if (schema) {
|
|
840
|
-
const fieldTable = zodSchemaToPromptDescription(schema);
|
|
841
|
-
if (fieldTable) {
|
|
842
|
-
formatSection += `
|
|
843
|
-
|
|
844
|
-
${fieldTable}`;
|
|
845
|
-
}
|
|
846
|
-
const yamlExample = zodSchemaToYamlExample(schema);
|
|
847
|
-
if (yamlExample) {
|
|
848
|
-
formatSection += `
|
|
849
|
-
|
|
850
|
-
Example:
|
|
851
|
-
|
|
852
|
-
\`\`\`yaml
|
|
853
|
-
${yamlExample}
|
|
854
|
-
\`\`\``;
|
|
855
|
-
}
|
|
856
|
-
} else {
|
|
857
|
-
formatSection += ` Include all required fields.`;
|
|
858
|
-
}
|
|
859
|
-
sections.push(formatSection);
|
|
860
|
-
return sections.join("\n\n");
|
|
861
|
-
}
|
|
862
|
-
function defaultDecideRetryStrategy(outcome, _counts) {
|
|
863
|
-
if (outcome.status === "validation_error") {
|
|
864
|
-
return "follow_up";
|
|
865
|
-
}
|
|
866
|
-
if (outcome.status === "error") {
|
|
867
|
-
if (outcome.message === "Agent returned empty output") return "retry";
|
|
868
|
-
return "abort";
|
|
869
|
-
}
|
|
870
|
-
return "abort";
|
|
871
|
-
}
|
|
872
|
-
function summarizeToolInput(input) {
|
|
873
|
-
if (!input) return "";
|
|
874
|
-
const path = input.file_path ?? input.path ?? input.filename ?? input.file;
|
|
875
|
-
if (typeof path === "string") return ` \u2014 ${path}`;
|
|
876
|
-
const cmd = input.command ?? input.cmd;
|
|
877
|
-
if (typeof cmd === "string") return ` \u2014 ${cmd.length > 80 ? cmd.slice(0, 77) + "..." : cmd}`;
|
|
878
|
-
const query = input.query ?? input.search ?? input.pattern;
|
|
879
|
-
if (typeof query === "string") return ` \u2014 "${query}"`;
|
|
880
|
-
return "";
|
|
881
|
-
}
|
|
882
|
-
function timestamp() {
|
|
883
|
-
return (/* @__PURE__ */ new Date()).toISOString();
|
|
884
|
-
}
|
|
885
|
-
function formatProgressPrefix(event, taskId, agentId) {
|
|
886
|
-
const ts = timestamp();
|
|
887
|
-
const sid = event.session_id ? event.session_id.slice(0, 8) : "-";
|
|
888
|
-
const agent = agentId ?? "-";
|
|
889
|
-
return `[${ts},${sid},${agent},${taskId}]`;
|
|
890
|
-
}
|
|
891
|
-
function formatProgressEvent(event, taskId, agentId) {
|
|
892
|
-
const prefix = formatProgressPrefix(event, taskId, agentId);
|
|
893
|
-
switch (event.type) {
|
|
894
|
-
case "tool_use":
|
|
895
|
-
return `${prefix} \u2699 ${event.tool_name ?? "tool"}${summarizeToolInput(event.input)}
|
|
896
|
-
`;
|
|
897
|
-
case "tool_result":
|
|
898
|
-
return "";
|
|
899
|
-
case "text": {
|
|
900
|
-
if (!event.message) return "";
|
|
901
|
-
const trimmed = event.message.trim();
|
|
902
|
-
if (!trimmed) return "";
|
|
903
|
-
const firstLine = trimmed.split("\n")[0];
|
|
904
|
-
const preview = firstLine.length > 120 ? firstLine.slice(0, 117) + "..." : firstLine;
|
|
905
|
-
return `${prefix} \u{1F4AD} ${preview}
|
|
906
|
-
`;
|
|
907
|
-
}
|
|
908
|
-
case "status":
|
|
909
|
-
return event.message ? `${prefix} \u25CF ${event.message}
|
|
910
|
-
` : "";
|
|
911
|
-
default:
|
|
912
|
-
return "";
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
async function runTask(adapter, taskId, context, options) {
|
|
916
|
-
const taskReg = options?.taskRegistry ?? {};
|
|
917
|
-
const agentReg = options?.agentRegistry ?? {};
|
|
918
|
-
const schemas = options?.handoffSchemas ?? {};
|
|
919
|
-
const task = taskReg[taskId];
|
|
920
|
-
if (!task) return { outcome: { status: "error", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };
|
|
921
|
-
const agentContract = agentReg[task.target_agent];
|
|
922
|
-
if (!agentContract) return { outcome: { status: "error", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };
|
|
923
|
-
const taskEnvelope = createExecutionEnvelope({
|
|
924
|
-
taskInstanceId: taskId,
|
|
925
|
-
componentId: agentContract.id,
|
|
926
|
-
fromAgent: agentContract.id,
|
|
927
|
-
parentRunId: options?.parentSpanId,
|
|
928
|
-
// correlates to agent.session run_id
|
|
929
|
-
adapter: options?.envelopeAdapter,
|
|
930
|
-
model: options?.envelopeModel
|
|
931
|
-
});
|
|
932
|
-
const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);
|
|
933
|
-
if (modifiedContext === null) {
|
|
934
|
-
return { outcome: { status: "error", message: `Task "${taskId}" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };
|
|
935
|
-
}
|
|
936
|
-
const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);
|
|
937
|
-
const analyzerToolIds = collectAnalyzerToolIds(options?.libraryTools);
|
|
938
|
-
const promptOpts = {
|
|
939
|
-
handoffSchemas: schemas,
|
|
940
|
-
retry: options?.retry,
|
|
941
|
-
...analyzerToolIds.length > 0 && shouldInjectAnalyzerExplorationMandate(enrichedContext) ? { analyzerExploration: { toolIds: analyzerToolIds } } : {}
|
|
942
|
-
};
|
|
943
|
-
const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };
|
|
944
|
-
let prompt;
|
|
945
|
-
let splitPrompt;
|
|
946
|
-
const pluginPrompt = pluginRegistry.applyPromptBuilder(builderArgs);
|
|
947
|
-
if (pluginPrompt) {
|
|
948
|
-
prompt = pluginPrompt;
|
|
949
|
-
} else {
|
|
950
|
-
const split = buildSplitTaskPrompt(agentContract, task, enrichedContext, promptOpts);
|
|
951
|
-
splitPrompt = split;
|
|
952
|
-
prompt = joinSplitPrompt(split);
|
|
953
|
-
}
|
|
954
|
-
const enhancedPrompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);
|
|
955
|
-
if (enhancedPrompt !== prompt) {
|
|
956
|
-
splitPrompt = void 0;
|
|
957
|
-
prompt = enhancedPrompt;
|
|
958
|
-
}
|
|
959
|
-
const isReadonly = agentContract.mode === "read-only";
|
|
960
|
-
const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;
|
|
961
|
-
const candidateAgents = Object.keys(agentReg).length > 0 ? buildCandidateAgents(agentReg, {
|
|
962
|
-
entryAgentId: agentContract.id,
|
|
963
|
-
allowedAgentIds: agentContract.can_invoke_agents
|
|
964
|
-
}) : [];
|
|
965
|
-
const agents = candidateAgents.length > 0 ? candidateAgents : void 0;
|
|
966
|
-
const maxFollowUps = options?.maxFollowUps ?? 2;
|
|
967
|
-
const maxRetries = options?.maxRetries ?? 0;
|
|
968
|
-
const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;
|
|
969
|
-
const onProgress = options?.progressOutput ? (event) => {
|
|
970
|
-
const line = formatProgressEvent(event, taskId, agentContract.id);
|
|
971
|
-
if (line) options.progressOutput.write(line);
|
|
972
|
-
} : void 0;
|
|
973
|
-
let followUpsUsed = 0;
|
|
974
|
-
let retriesUsed = 0;
|
|
975
|
-
let memoryRef = enrichedContext.memoryRef;
|
|
976
|
-
if (memoryRef && adapter.isCompatible && !adapter.isCompatible(memoryRef.compat)) {
|
|
977
|
-
console.warn(
|
|
978
|
-
`Memory ref compat mismatch: ${memoryRef.compat} is not compatible with this adapter`
|
|
979
|
-
);
|
|
980
|
-
memoryRef = void 0;
|
|
981
|
-
}
|
|
982
|
-
const taskExecStart = Date.now();
|
|
983
|
-
const effectiveSessionId = options?.sessionId ?? options?.parentSpanId ?? taskEnvelope.run_id;
|
|
984
|
-
const subagentSpanId = emitSubagentOpen(
|
|
985
|
-
options?.observer,
|
|
986
|
-
taskEnvelope,
|
|
987
|
-
options?.parentSpanId,
|
|
988
|
-
taskId,
|
|
989
|
-
agentContract.role_name,
|
|
990
|
-
effectiveSessionId
|
|
991
|
-
);
|
|
992
|
-
let closeStatus = "error";
|
|
993
|
-
let closeCause;
|
|
994
|
-
let spanClosed = false;
|
|
995
|
-
const closeSubagentSpan = () => {
|
|
996
|
-
if (spanClosed) return;
|
|
997
|
-
spanClosed = true;
|
|
998
|
-
const durationMs = Date.now() - taskExecStart;
|
|
999
|
-
const lastTokenUsage = adapter.getLastTokenUsage?.();
|
|
1000
|
-
taskEnvelope.execution_metadata = {
|
|
1001
|
-
...taskEnvelope.execution_metadata ?? {},
|
|
1002
|
-
duration_ms: durationMs,
|
|
1003
|
-
...lastTokenUsage ? {
|
|
1004
|
-
token_usage: {
|
|
1005
|
-
input_tokens: lastTokenUsage.inputTokens,
|
|
1006
|
-
output_tokens: lastTokenUsage.outputTokens,
|
|
1007
|
-
...lastTokenUsage.totalTokens !== void 0 ? { total_tokens: lastTokenUsage.totalTokens } : {},
|
|
1008
|
-
...lastTokenUsage.cacheReadTokens !== void 0 ? { cache_read_input_tokens: lastTokenUsage.cacheReadTokens } : {},
|
|
1009
|
-
...lastTokenUsage.cacheCreationTokens !== void 0 ? { cache_creation_input_tokens: lastTokenUsage.cacheCreationTokens } : {}
|
|
1010
|
-
}
|
|
1011
|
-
} : {}
|
|
1012
|
-
};
|
|
1013
|
-
emitSubagentClose(
|
|
1014
|
-
options?.observer,
|
|
1015
|
-
subagentSpanId ?? taskEnvelope.run_id,
|
|
1016
|
-
taskEnvelope,
|
|
1017
|
-
durationMs,
|
|
1018
|
-
closeStatus,
|
|
1019
|
-
agentContract.role_name,
|
|
1020
|
-
closeCause,
|
|
1021
|
-
effectiveSessionId
|
|
1022
|
-
);
|
|
1023
|
-
};
|
|
1024
|
-
try {
|
|
1025
|
-
let fullOutput;
|
|
1026
|
-
try {
|
|
1027
|
-
if (adapter.sendExecution) {
|
|
1028
|
-
fullOutput = await adapter.sendExecution({
|
|
1029
|
-
agentId: agentContract.id,
|
|
1030
|
-
taskId,
|
|
1031
|
-
prompt,
|
|
1032
|
-
handoff: schemas[task.result_handoff] ? { type: task.result_handoff, payload: void 0 } : void 0,
|
|
1033
|
-
schema: schemas[task.result_handoff] ? {
|
|
1034
|
-
handoffType: task.result_handoff,
|
|
1035
|
-
zodSchema: schemas[task.result_handoff],
|
|
1036
|
-
promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff])
|
|
1037
|
-
} : void 0,
|
|
1038
|
-
context: enrichedContext,
|
|
1039
|
-
memoryRef,
|
|
1040
|
-
splitPrompt,
|
|
1041
|
-
agents,
|
|
1042
|
-
options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId, maxFollowUps, attempt: 0 }
|
|
1043
|
-
});
|
|
1044
|
-
} else {
|
|
1045
|
-
fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId });
|
|
1046
|
-
}
|
|
1047
|
-
} catch (err) {
|
|
1048
|
-
closeStatus = "error";
|
|
1049
|
-
closeCause = `SDK error: ${err.message}`;
|
|
1050
|
-
return { outcome: { status: "error", message: closeCause }, follow_ups_used: 0, retries_used: 0 };
|
|
1051
|
-
}
|
|
1052
|
-
let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
|
|
1053
|
-
outcome = await pluginRegistry.runAfterTask(taskId, outcome);
|
|
1054
|
-
while (outcome.status === "validation_error" || outcome.status === "error") {
|
|
1055
|
-
const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
|
|
1056
|
-
if (decision === "abort") break;
|
|
1057
|
-
let effectiveDecision = decision;
|
|
1058
|
-
if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
|
|
1059
|
-
effectiveDecision = "retry";
|
|
1060
|
-
}
|
|
1061
|
-
if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
|
|
1062
|
-
break;
|
|
1063
|
-
}
|
|
1064
|
-
if (effectiveDecision === "follow_up") {
|
|
1065
|
-
followUpsUsed++;
|
|
1066
|
-
const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
|
|
1067
|
-
try {
|
|
1068
|
-
if (adapter.followUp) {
|
|
1069
|
-
fullOutput = await adapter.followUp(followUpPrompt);
|
|
1070
|
-
} else {
|
|
1071
|
-
const retryContext = {
|
|
1072
|
-
...modifiedContext,
|
|
1073
|
-
prior_context: (modifiedContext.prior_context ?? "") + `
|
|
1074
|
-
|
|
1075
|
-
--- FollowUp ${followUpsUsed} ---
|
|
1076
|
-
${followUpPrompt}`
|
|
1077
|
-
};
|
|
1078
|
-
let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
|
|
1079
|
-
retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
|
|
1080
|
-
fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
|
|
1081
|
-
}
|
|
1082
|
-
} catch (err) {
|
|
1083
|
-
outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
|
|
1084
|
-
continue;
|
|
1085
|
-
}
|
|
1086
|
-
} else {
|
|
1087
|
-
retriesUsed++;
|
|
1088
|
-
const retryContext = {
|
|
1089
|
-
...modifiedContext,
|
|
1090
|
-
prior_context: (modifiedContext.prior_context ?? "") + `
|
|
1091
|
-
|
|
1092
|
-
--- Full Retry ${retriesUsed} ---
|
|
1093
|
-
Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
|
|
1094
|
-
Please re-execute the entire task.`
|
|
1095
|
-
};
|
|
1096
|
-
let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
|
|
1097
|
-
retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
|
|
1098
|
-
try {
|
|
1099
|
-
fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
|
|
1100
|
-
} catch (err) {
|
|
1101
|
-
outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
|
|
1102
|
-
continue;
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
|
|
1106
|
-
outcome = await pluginRegistry.runAfterTask(taskId, outcome);
|
|
1107
|
-
}
|
|
1108
|
-
closeStatus = outcome.status;
|
|
1109
|
-
const finalTokenUsage = adapter.getLastTokenUsage?.() ?? void 0;
|
|
1110
|
-
return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed, tokenUsage: finalTokenUsage };
|
|
1111
|
-
} catch (err) {
|
|
1112
|
-
closeStatus = "error";
|
|
1113
|
-
closeCause = err.message;
|
|
1114
|
-
throw err;
|
|
1115
|
-
} finally {
|
|
1116
|
-
closeSubagentSpan();
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
|
-
|
|
1120
74
|
// src/lib/toolchain-checker.ts
|
|
1121
75
|
import { execFile } from "child_process";
|
|
1122
76
|
import { readFile } from "fs/promises";
|
|
1123
77
|
import { existsSync } from "fs";
|
|
1124
78
|
import { resolve } from "path";
|
|
1125
79
|
import { promisify } from "util";
|
|
1126
|
-
import { z
|
|
80
|
+
import { z } from "zod";
|
|
1127
81
|
import { parseToolchainFile } from "@aaac/toolchain";
|
|
1128
82
|
var execFileAsync = promisify(execFile);
|
|
1129
83
|
var SUBPROCESS_TIMEOUT_MS = 3e4;
|
|
1130
84
|
var MANIFEST_FILENAME = ".toolchain-manifest.json";
|
|
1131
|
-
var ToolchainManifestSchema =
|
|
1132
|
-
schema:
|
|
1133
|
-
toolchain_id:
|
|
1134
|
-
generated_at:
|
|
1135
|
-
source_hash:
|
|
1136
|
-
output_hash:
|
|
1137
|
-
source_globs:
|
|
1138
|
-
output_globs:
|
|
1139
|
-
files:
|
|
1140
|
-
|
|
1141
|
-
path:
|
|
1142
|
-
hash:
|
|
85
|
+
var ToolchainManifestSchema = z.object({
|
|
86
|
+
schema: z.string(),
|
|
87
|
+
toolchain_id: z.string(),
|
|
88
|
+
generated_at: z.string(),
|
|
89
|
+
source_hash: z.string(),
|
|
90
|
+
output_hash: z.string(),
|
|
91
|
+
source_globs: z.array(z.string()).optional(),
|
|
92
|
+
output_globs: z.array(z.string()).optional(),
|
|
93
|
+
files: z.array(
|
|
94
|
+
z.object({
|
|
95
|
+
path: z.string(),
|
|
96
|
+
hash: z.string()
|
|
1143
97
|
})
|
|
1144
98
|
).optional()
|
|
1145
99
|
});
|
|
@@ -1353,7 +307,7 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
|
|
|
1353
307
|
};
|
|
1354
308
|
}
|
|
1355
309
|
await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);
|
|
1356
|
-
const sessionMeta = options.resolveModelMeta?.(
|
|
310
|
+
const sessionMeta = options.resolveModelMeta?.("standard");
|
|
1357
311
|
const sessionEnvelope = createExecutionEnvelope({
|
|
1358
312
|
componentId: workflowId,
|
|
1359
313
|
adapter: sessionMeta?.adapter,
|
|
@@ -1884,302 +838,9 @@ function emitStepEvent(options, workflowId, stepIndex, step, result) {
|
|
|
1884
838
|
});
|
|
1885
839
|
}
|
|
1886
840
|
|
|
1887
|
-
// src/lib/process-axis-bridge.ts
|
|
1888
|
-
import { generateId } from "@aaac/observability";
|
|
1889
|
-
function attrs(base) {
|
|
1890
|
-
const out = {};
|
|
1891
|
-
for (const [k, v] of Object.entries(base)) {
|
|
1892
|
-
if (v !== void 0 && v !== "") out[k] = v;
|
|
1893
|
-
}
|
|
1894
|
-
return out;
|
|
1895
|
-
}
|
|
1896
|
-
function emitProcessWorkflowOpen(options) {
|
|
1897
|
-
if (!options.observer) return void 0;
|
|
1898
|
-
const spanId = generateId();
|
|
1899
|
-
options.observer({
|
|
1900
|
-
source: "aaac-runtime",
|
|
1901
|
-
eventType: "process.workflow",
|
|
1902
|
-
lifecycle: "open",
|
|
1903
|
-
spanId,
|
|
1904
|
-
parentSpanId: options.parentSpanId,
|
|
1905
|
-
attributes: attrs({
|
|
1906
|
-
axis: "process",
|
|
1907
|
-
"agent.session_id": options.sessionId,
|
|
1908
|
-
"workflow.id": options.workflowId
|
|
1909
|
-
})
|
|
1910
|
-
});
|
|
1911
|
-
return spanId;
|
|
1912
|
-
}
|
|
1913
|
-
function emitProcessWorkflowClose(spanId, options) {
|
|
1914
|
-
if (!options.observer) return;
|
|
1915
|
-
options.observer({
|
|
1916
|
-
source: "aaac-runtime",
|
|
1917
|
-
eventType: "process.workflow",
|
|
1918
|
-
lifecycle: "close",
|
|
1919
|
-
spanId,
|
|
1920
|
-
attributes: attrs({
|
|
1921
|
-
axis: "process",
|
|
1922
|
-
"workflow.status": options.status,
|
|
1923
|
-
...options.durationMs !== void 0 ? { "workflow.duration_ms": options.durationMs } : {}
|
|
1924
|
-
})
|
|
1925
|
-
});
|
|
1926
|
-
}
|
|
1927
|
-
function emitProcessTaskOpen(options) {
|
|
1928
|
-
if (!options.observer) return void 0;
|
|
1929
|
-
const spanId = generateId();
|
|
1930
|
-
options.observer({
|
|
1931
|
-
source: "aaac-runtime",
|
|
1932
|
-
eventType: "process.task",
|
|
1933
|
-
lifecycle: "open",
|
|
1934
|
-
spanId,
|
|
1935
|
-
parentSpanId: options.parentSpanId,
|
|
1936
|
-
attributes: attrs({
|
|
1937
|
-
axis: "process",
|
|
1938
|
-
"agent.session_id": options.sessionId,
|
|
1939
|
-
"task.id": options.taskId,
|
|
1940
|
-
"task.type": "implement",
|
|
1941
|
-
"task.target_agent": options.targetAgent
|
|
1942
|
-
})
|
|
1943
|
-
});
|
|
1944
|
-
return spanId;
|
|
1945
|
-
}
|
|
1946
|
-
function emitProcessTaskClose(spanId, options) {
|
|
1947
|
-
if (!options.observer) return;
|
|
1948
|
-
options.observer({
|
|
1949
|
-
source: "aaac-runtime",
|
|
1950
|
-
eventType: "process.task",
|
|
1951
|
-
lifecycle: "close",
|
|
1952
|
-
spanId,
|
|
1953
|
-
attributes: attrs({
|
|
1954
|
-
axis: "process",
|
|
1955
|
-
"task.status": options.status,
|
|
1956
|
-
...options.durationMs !== void 0 ? { "task.duration_ms": options.durationMs } : {}
|
|
1957
|
-
})
|
|
1958
|
-
});
|
|
1959
|
-
}
|
|
1960
|
-
function emitProcessEdit(options) {
|
|
1961
|
-
if (!options.observer) return void 0;
|
|
1962
|
-
const spanId = generateId();
|
|
1963
|
-
options.observer({
|
|
1964
|
-
source: "aaac-runtime",
|
|
1965
|
-
eventType: "process.edit",
|
|
1966
|
-
lifecycle: "instant",
|
|
1967
|
-
spanId,
|
|
1968
|
-
parentSpanId: options.parentSpanId,
|
|
1969
|
-
attributes: attrs({
|
|
1970
|
-
axis: "process",
|
|
1971
|
-
"agent.session_id": options.sessionId,
|
|
1972
|
-
"edit.path": options.filePath,
|
|
1973
|
-
"edit.artifact_id": options.artifactId
|
|
1974
|
-
})
|
|
1975
|
-
});
|
|
1976
|
-
return spanId;
|
|
1977
|
-
}
|
|
1978
|
-
|
|
1979
841
|
// src/lib/bound-resolver.ts
|
|
1980
|
-
import { readFile as readFile3 } from "fs/promises";
|
|
1981
|
-
import YAML2 from "yaml";
|
|
1982
|
-
|
|
1983
|
-
// src/lib/dsl-context.ts
|
|
1984
842
|
import { readFile as readFile2 } from "fs/promises";
|
|
1985
843
|
import YAML from "yaml";
|
|
1986
|
-
var DslValidationError = class extends Error {
|
|
1987
|
-
missing;
|
|
1988
|
-
constructor(missing) {
|
|
1989
|
-
super(
|
|
1990
|
-
"Required entities missing after DSL merge:\n" + missing.map((m) => ` - ${m}`).join("\n")
|
|
1991
|
-
);
|
|
1992
|
-
this.name = "DslValidationError";
|
|
1993
|
-
this.missing = missing;
|
|
1994
|
-
}
|
|
1995
|
-
};
|
|
1996
|
-
function buildAgentRegistry(agents) {
|
|
1997
|
-
const registry = {};
|
|
1998
|
-
for (const [id, agent] of Object.entries(agents)) {
|
|
1999
|
-
const rawMode = agent.mode ?? "read-only";
|
|
2000
|
-
const mode = rawMode === "read-write" ? "read-write" : "read-only";
|
|
2001
|
-
registry[id] = {
|
|
2002
|
-
id,
|
|
2003
|
-
role_name: agent.role_name ?? id,
|
|
2004
|
-
purpose: agent.purpose ?? "",
|
|
2005
|
-
mode,
|
|
2006
|
-
responsibilities: agent.responsibilities ?? [],
|
|
2007
|
-
constraints: agent.constraints ?? [],
|
|
2008
|
-
rules: agent.rules ?? [],
|
|
2009
|
-
can_invoke_agents: agent.can_invoke_agents ?? void 0,
|
|
2010
|
-
can_execute_tools: agent.can_execute_tools ?? void 0
|
|
2011
|
-
};
|
|
2012
|
-
}
|
|
2013
|
-
return registry;
|
|
2014
|
-
}
|
|
2015
|
-
function buildTaskRegistry(tasks) {
|
|
2016
|
-
const registry = {};
|
|
2017
|
-
for (const [id, task] of Object.entries(tasks)) {
|
|
2018
|
-
registry[id] = {
|
|
2019
|
-
id,
|
|
2020
|
-
description: task.description ?? "",
|
|
2021
|
-
target_agent: task.target_agent ?? "",
|
|
2022
|
-
result_handoff: task.result_handoff ?? "",
|
|
2023
|
-
completion_criteria: task.completion_criteria ?? [],
|
|
2024
|
-
model_class: task.model_class
|
|
2025
|
-
};
|
|
2026
|
-
}
|
|
2027
|
-
return registry;
|
|
2028
|
-
}
|
|
2029
|
-
function buildWorkflowStep(step) {
|
|
2030
|
-
if (step.type === "gate") {
|
|
2031
|
-
return {
|
|
2032
|
-
type: "gate",
|
|
2033
|
-
gate_kind: step.gate_kind ?? "",
|
|
2034
|
-
description: step.description ?? "",
|
|
2035
|
-
depends_on: step.depends_on
|
|
2036
|
-
};
|
|
2037
|
-
}
|
|
2038
|
-
if (step.type === "evaluate") {
|
|
2039
|
-
return {
|
|
2040
|
-
type: "evaluate",
|
|
2041
|
-
task: step.task ?? "",
|
|
2042
|
-
from_agent: step.from_agent ?? "",
|
|
2043
|
-
evaluator_agent: step.evaluator_agent,
|
|
2044
|
-
description: step.description,
|
|
2045
|
-
loop_to: step.loop_to ?? "",
|
|
2046
|
-
max_iterations: step.max_iterations ?? 1,
|
|
2047
|
-
inject_as: step.inject_as,
|
|
2048
|
-
on_exhausted: step.on_exhausted,
|
|
2049
|
-
depends_on: step.depends_on
|
|
2050
|
-
};
|
|
2051
|
-
}
|
|
2052
|
-
return {
|
|
2053
|
-
type: "delegate",
|
|
2054
|
-
task: step.task ?? "",
|
|
2055
|
-
from_agent: step.from_agent ?? "",
|
|
2056
|
-
description: step.description ?? "",
|
|
2057
|
-
optional: step.optional ?? false,
|
|
2058
|
-
max_retries: step.max_retries ?? 0,
|
|
2059
|
-
max_follow_ups: step.max_follow_ups,
|
|
2060
|
-
depends_on: step.depends_on,
|
|
2061
|
-
instruction: step.instruction,
|
|
2062
|
-
receives: step.receives,
|
|
2063
|
-
retry: step.retry
|
|
2064
|
-
};
|
|
2065
|
-
}
|
|
2066
|
-
function buildWorkflowRegistry(workflows) {
|
|
2067
|
-
const registry = {};
|
|
2068
|
-
for (const [id, wf] of Object.entries(workflows)) {
|
|
2069
|
-
const steps = (wf.steps ?? []).map(buildWorkflowStep);
|
|
2070
|
-
registry[id] = { id, description: wf.description ?? "", steps };
|
|
2071
|
-
}
|
|
2072
|
-
return registry;
|
|
2073
|
-
}
|
|
2074
|
-
function buildHandoffSchemas(handoffTypes) {
|
|
2075
|
-
const schemas = {};
|
|
2076
|
-
for (const [id, ht] of Object.entries(handoffTypes)) {
|
|
2077
|
-
const schema = ht.schema;
|
|
2078
|
-
if (schema) {
|
|
2079
|
-
schemas[id] = jsonSchemaToZod(schema);
|
|
2080
|
-
}
|
|
2081
|
-
}
|
|
2082
|
-
return schemas;
|
|
2083
|
-
}
|
|
2084
|
-
function buildGuardrailRulesFromDsl(dsl) {
|
|
2085
|
-
const raw = dsl._guardrailRules;
|
|
2086
|
-
if (!raw) return void 0;
|
|
2087
|
-
return {
|
|
2088
|
-
commandRules: raw.commandRules ?? [],
|
|
2089
|
-
fileRules: raw.fileRules ?? [],
|
|
2090
|
-
contentRules: raw.contentRules ?? []
|
|
2091
|
-
};
|
|
2092
|
-
}
|
|
2093
|
-
function buildRegistriesFromDsl(dsl) {
|
|
2094
|
-
const agents = dsl.agents ?? {};
|
|
2095
|
-
const tasks = dsl.tasks ?? {};
|
|
2096
|
-
const workflows = dsl.workflow ?? {};
|
|
2097
|
-
const handoffTypes = dsl.handoff_types ?? {};
|
|
2098
|
-
return {
|
|
2099
|
-
agentRegistry: buildAgentRegistry(agents),
|
|
2100
|
-
taskRegistry: buildTaskRegistry(tasks),
|
|
2101
|
-
workflowRegistry: buildWorkflowRegistry(workflows),
|
|
2102
|
-
handoffSchemas: buildHandoffSchemas(handoffTypes)
|
|
2103
|
-
};
|
|
2104
|
-
}
|
|
2105
|
-
function validateRequiredEntities(dsl, required) {
|
|
2106
|
-
const missing = [];
|
|
2107
|
-
const workflows = dsl.workflow ?? {};
|
|
2108
|
-
const tasks = dsl.tasks ?? {};
|
|
2109
|
-
const handoffTypes = dsl.handoff_types ?? {};
|
|
2110
|
-
if (required.workflows) {
|
|
2111
|
-
for (const wfId of required.workflows) {
|
|
2112
|
-
if (!(wfId in workflows)) {
|
|
2113
|
-
missing.push(`workflow "${wfId}" is required by the CLI but not found in the resolved DSL`);
|
|
2114
|
-
}
|
|
2115
|
-
}
|
|
2116
|
-
}
|
|
2117
|
-
if (required.tasks) {
|
|
2118
|
-
for (const taskId of required.tasks) {
|
|
2119
|
-
if (!(taskId in tasks)) {
|
|
2120
|
-
missing.push(`task "${taskId}" is required by the CLI but not found in the resolved DSL`);
|
|
2121
|
-
continue;
|
|
2122
|
-
}
|
|
2123
|
-
const task = tasks[taskId];
|
|
2124
|
-
const invHandoff = task.invocation_handoff;
|
|
2125
|
-
const resHandoff = task.result_handoff;
|
|
2126
|
-
if (invHandoff && !(invHandoff in handoffTypes)) {
|
|
2127
|
-
missing.push(`handoff_type "${invHandoff}" (invocation_handoff of task "${taskId}") not found`);
|
|
2128
|
-
}
|
|
2129
|
-
if (resHandoff && !(resHandoff in handoffTypes)) {
|
|
2130
|
-
missing.push(`handoff_type "${resHandoff}" (result_handoff of task "${taskId}") not found`);
|
|
2131
|
-
}
|
|
2132
|
-
}
|
|
2133
|
-
}
|
|
2134
|
-
if (required.workflows) {
|
|
2135
|
-
for (const wfId of required.workflows) {
|
|
2136
|
-
if (!(wfId in workflows)) continue;
|
|
2137
|
-
const wf = workflows[wfId];
|
|
2138
|
-
const steps = wf.steps ?? [];
|
|
2139
|
-
for (const step of steps) {
|
|
2140
|
-
if (step.type !== "delegate") continue;
|
|
2141
|
-
const taskId = step.task;
|
|
2142
|
-
if (taskId && taskId in tasks) {
|
|
2143
|
-
const task = tasks[taskId];
|
|
2144
|
-
const resHandoff = task.result_handoff;
|
|
2145
|
-
if (resHandoff && !(resHandoff in handoffTypes)) {
|
|
2146
|
-
missing.push(`handoff_type "${resHandoff}" (result of task "${taskId}" in workflow "${wfId}") not found`);
|
|
2147
|
-
}
|
|
2148
|
-
}
|
|
2149
|
-
}
|
|
2150
|
-
}
|
|
2151
|
-
}
|
|
2152
|
-
if (missing.length > 0) {
|
|
2153
|
-
throw new DslValidationError(missing);
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
async function loadDslContext(options) {
|
|
2157
|
-
let dsl;
|
|
2158
|
-
if (options.projectDslPath) {
|
|
2159
|
-
const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import("agent-contracts");
|
|
2160
|
-
const raw = await readFile2(options.projectDslPath, "utf8");
|
|
2161
|
-
const projectData = YAML.parse(raw);
|
|
2162
|
-
if (projectData.extends === "/$embedded/") {
|
|
2163
|
-
const { extends: _extends, ...projectOverrides } = projectData;
|
|
2164
|
-
const merged = mergeDsl(options.embeddedDsl, projectOverrides);
|
|
2165
|
-
dsl = expandDefaults(merged);
|
|
2166
|
-
} else {
|
|
2167
|
-
const projectResult = await resolveDsl(options.projectDslPath);
|
|
2168
|
-
const merged = mergeDsl(options.embeddedDsl, projectResult.data);
|
|
2169
|
-
dsl = expandDefaults(merged);
|
|
2170
|
-
}
|
|
2171
|
-
} else {
|
|
2172
|
-
dsl = options.embeddedDsl;
|
|
2173
|
-
}
|
|
2174
|
-
if (options.requiredEntities) {
|
|
2175
|
-
validateRequiredEntities(dsl, options.requiredEntities);
|
|
2176
|
-
}
|
|
2177
|
-
const registries = buildRegistriesFromDsl(dsl);
|
|
2178
|
-
const guardrailRules = buildGuardrailRulesFromDsl(dsl);
|
|
2179
|
-
return { registries, dsl, guardrailRules };
|
|
2180
|
-
}
|
|
2181
|
-
|
|
2182
|
-
// src/lib/bound-resolver.ts
|
|
2183
844
|
function getEffectiveGuardrailIds(dsl, agentId) {
|
|
2184
845
|
const ids = /* @__PURE__ */ new Set();
|
|
2185
846
|
const agents = dsl.agents ?? {};
|
|
@@ -2355,8 +1016,8 @@ var BoundResolver = class {
|
|
|
2355
1016
|
};
|
|
2356
1017
|
if (opts.bindingPaths && opts.bindingPaths.length > 0) {
|
|
2357
1018
|
for (const bindingPath of opts.bindingPaths) {
|
|
2358
|
-
const raw = await
|
|
2359
|
-
const binding =
|
|
1019
|
+
const raw = await readFile2(bindingPath, "utf8");
|
|
1020
|
+
const binding = YAML.parse(raw);
|
|
2360
1021
|
guardrailCtx = buildGuardrailContext(
|
|
2361
1022
|
dsl,
|
|
2362
1023
|
binding,
|
|
@@ -2533,15 +1194,15 @@ async function loadPluginModule(modulePath) {
|
|
|
2533
1194
|
async function loadPluginsFromPaths(paths, baseDir) {
|
|
2534
1195
|
const result = { loaded: 0, files: [], errors: [] };
|
|
2535
1196
|
for (const p of paths) {
|
|
2536
|
-
const
|
|
2537
|
-
if (!existsSync2(
|
|
2538
|
-
result.errors.push({ file: p, error: `File not found: ${
|
|
1197
|
+
const absPath2 = resolve2(baseDir, p);
|
|
1198
|
+
if (!existsSync2(absPath2)) {
|
|
1199
|
+
result.errors.push({ file: p, error: `File not found: ${absPath2}` });
|
|
2539
1200
|
continue;
|
|
2540
1201
|
}
|
|
2541
1202
|
try {
|
|
2542
|
-
const count = await loadPluginModule(
|
|
1203
|
+
const count = await loadPluginModule(absPath2);
|
|
2543
1204
|
result.loaded += count;
|
|
2544
|
-
result.files.push(
|
|
1205
|
+
result.files.push(absPath2);
|
|
2545
1206
|
} catch (err) {
|
|
2546
1207
|
result.errors.push({
|
|
2547
1208
|
file: p,
|
|
@@ -2683,7 +1344,7 @@ var InMemoryStore = class {
|
|
|
2683
1344
|
};
|
|
2684
1345
|
|
|
2685
1346
|
// src/lib/file-memory-store.ts
|
|
2686
|
-
import { mkdir, readFile as
|
|
1347
|
+
import { mkdir, readFile as readFile3, unlink, writeFile } from "fs/promises";
|
|
2687
1348
|
import { join as join3 } from "path";
|
|
2688
1349
|
function resolveFilePath2(baseDir, ref) {
|
|
2689
1350
|
const runId = ref.parent_run_id ?? "unknown";
|
|
@@ -2702,7 +1363,7 @@ var FileMemoryStore = class {
|
|
|
2702
1363
|
async load(ref) {
|
|
2703
1364
|
const filePath = resolveFilePath2(this.baseDir, ref);
|
|
2704
1365
|
try {
|
|
2705
|
-
const raw = await
|
|
1366
|
+
const raw = await readFile3(filePath, "utf-8");
|
|
2706
1367
|
return JSON.parse(raw);
|
|
2707
1368
|
} catch (error) {
|
|
2708
1369
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
@@ -2725,7 +1386,7 @@ var FileMemoryStore = class {
|
|
|
2725
1386
|
};
|
|
2726
1387
|
|
|
2727
1388
|
// src/lib/agent-log-writer.ts
|
|
2728
|
-
import { mkdir as mkdir2, readFile as
|
|
1389
|
+
import { mkdir as mkdir2, readFile as readFile4, readdir as readdir2, stat, unlink as unlink2, writeFile as writeFile2, appendFile } from "fs/promises";
|
|
2729
1390
|
import { join as join4 } from "path";
|
|
2730
1391
|
var AgentLogWriter = class {
|
|
2731
1392
|
baseDir;
|
|
@@ -2749,7 +1410,7 @@ var AgentLogWriter = class {
|
|
|
2749
1410
|
async readRunLog(runId) {
|
|
2750
1411
|
const filePath = join4(this.baseDir, "runs", `${runId}.jsonl`);
|
|
2751
1412
|
try {
|
|
2752
|
-
const raw = await
|
|
1413
|
+
const raw = await readFile4(filePath, "utf-8");
|
|
2753
1414
|
return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
|
|
2754
1415
|
} catch (error) {
|
|
2755
1416
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
@@ -2767,7 +1428,7 @@ var AgentLogWriter = class {
|
|
|
2767
1428
|
async readHandoff(runId, step) {
|
|
2768
1429
|
const filePath = join4(this.baseDir, "handoffs", `${runId}_${step}.json`);
|
|
2769
1430
|
try {
|
|
2770
|
-
const raw = await
|
|
1431
|
+
const raw = await readFile4(filePath, "utf-8");
|
|
2771
1432
|
return JSON.parse(raw);
|
|
2772
1433
|
} catch (error) {
|
|
2773
1434
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
@@ -2967,59 +1628,6 @@ Install it with: npm install ${pkg2}`
|
|
|
2967
1628
|
|
|
2968
1629
|
// src/lib/execute.ts
|
|
2969
1630
|
import { resolve as resolve3 } from "path";
|
|
2970
|
-
|
|
2971
|
-
// src/lib/navigation-context.ts
|
|
2972
|
-
async function buildNavigationContext(options) {
|
|
2973
|
-
const diagnostics = [];
|
|
2974
|
-
let dsl;
|
|
2975
|
-
if (options.embeddedDsl != null) {
|
|
2976
|
-
if (options.projectDslPath) {
|
|
2977
|
-
const ctx = await loadDslContext({
|
|
2978
|
-
embeddedDsl: options.embeddedDsl,
|
|
2979
|
-
projectDslPath: options.projectDslPath
|
|
2980
|
-
});
|
|
2981
|
-
dsl = ctx.dsl;
|
|
2982
|
-
} else {
|
|
2983
|
-
dsl = options.embeddedDsl;
|
|
2984
|
-
}
|
|
2985
|
-
} else if (options.projectDslPath) {
|
|
2986
|
-
const { resolve: resolve5 } = await import("agent-contracts");
|
|
2987
|
-
const result = await resolve5(options.projectDslPath);
|
|
2988
|
-
dsl = result.data;
|
|
2989
|
-
} else {
|
|
2990
|
-
throw new Error("buildNavigationContext requires embeddedDsl or projectDslPath");
|
|
2991
|
-
}
|
|
2992
|
-
if (options.artifactBinding) {
|
|
2993
|
-
const { resolveBound } = await import("agent-contracts");
|
|
2994
|
-
const boundResult = await resolveBound(dsl, {
|
|
2995
|
-
artifactBinding: options.artifactBinding,
|
|
2996
|
-
paths: options.paths
|
|
2997
|
-
});
|
|
2998
|
-
dsl = boundResult.data;
|
|
2999
|
-
for (const d of boundResult.diagnostics) {
|
|
3000
|
-
diagnostics.push({
|
|
3001
|
-
path: d.rule,
|
|
3002
|
-
message: d.message,
|
|
3003
|
-
severity: d.severity
|
|
3004
|
-
});
|
|
3005
|
-
}
|
|
3006
|
-
}
|
|
3007
|
-
const { validateSchema, buildNavigationIndex } = await import("agent-contracts");
|
|
3008
|
-
const validation = validateSchema(dsl);
|
|
3009
|
-
for (const d of validation.diagnostics) {
|
|
3010
|
-
diagnostics.push({
|
|
3011
|
-
path: d.path,
|
|
3012
|
-
message: d.message,
|
|
3013
|
-
severity: d.severity ?? "error"
|
|
3014
|
-
});
|
|
3015
|
-
}
|
|
3016
|
-
const navigationIndex = buildNavigationIndex(
|
|
3017
|
-
validation.data ?? dsl
|
|
3018
|
-
);
|
|
3019
|
-
return { dsl, navigationIndex, diagnostics };
|
|
3020
|
-
}
|
|
3021
|
-
|
|
3022
|
-
// src/lib/execute.ts
|
|
3023
1631
|
async function resolveExecutionContext(options, requiredEntities) {
|
|
3024
1632
|
const useBoundResolver = options.resolvedComponent || options.bindingPaths && options.bindingPaths.length > 0 || options.artifactBinding;
|
|
3025
1633
|
if (useBoundResolver) {
|
|
@@ -3218,7 +1826,7 @@ var DEFAULT_MEMORY_COMPAT = "aaac/0.1";
|
|
|
3218
1826
|
function getMemoryRefConfig(op) {
|
|
3219
1827
|
return op.memoryRef;
|
|
3220
1828
|
}
|
|
3221
|
-
function
|
|
1829
|
+
function attachMemoryRef(result, memoryRef) {
|
|
3222
1830
|
if (result !== null && typeof result === "object" && !Array.isArray(result)) {
|
|
3223
1831
|
return { ...result, _memoryRef: memoryRef };
|
|
3224
1832
|
}
|
|
@@ -3284,7 +1892,7 @@ function createRuntimeBinding(component, handlers) {
|
|
|
3284
1892
|
memoryRef: newMemoryRef
|
|
3285
1893
|
};
|
|
3286
1894
|
await ctx.memoryStore.save(newMemoryRef, entry);
|
|
3287
|
-
finalResult =
|
|
1895
|
+
finalResult = attachMemoryRef(result, newMemoryRef);
|
|
3288
1896
|
}
|
|
3289
1897
|
ctx.observer?.onOperationEnd?.(operationName, finalResult);
|
|
3290
1898
|
if (ctx.logWriter) {
|
|
@@ -3337,9 +1945,9 @@ async function dispatchOperation(operationName, op, options, input, ctx, handler
|
|
|
3337
1945
|
|
|
3338
1946
|
// src/lib/project-runtime.ts
|
|
3339
1947
|
import { existsSync as existsSync3 } from "fs";
|
|
3340
|
-
import { readFile as
|
|
1948
|
+
import { readFile as readFile5 } from "fs/promises";
|
|
3341
1949
|
import { resolve as resolve4, dirname as dirname2 } from "path";
|
|
3342
|
-
import
|
|
1950
|
+
import YAML2 from "yaml";
|
|
3343
1951
|
import { createPipeline } from "@aaac/observability";
|
|
3344
1952
|
var PROJECT_CONFIG_FILENAME = "project.yaml";
|
|
3345
1953
|
var DEFAULT_ADAPTER = "claude";
|
|
@@ -3368,7 +1976,7 @@ async function createProjectRuntime(options) {
|
|
|
3368
1976
|
}
|
|
3369
1977
|
const config = await loadProjectConfig(configPath);
|
|
3370
1978
|
const env = options.env ?? process.env;
|
|
3371
|
-
const rawManifest =
|
|
1979
|
+
const rawManifest = YAML2.parse(await readFile5(configPath, "utf8"));
|
|
3372
1980
|
const overlayExplicit = typeof rawManifest?.agents === "string" || typeof rawManifest?.dsl === "string";
|
|
3373
1981
|
if (overlayExplicit && !existsSync3(config.dslPath)) {
|
|
3374
1982
|
throw new Error(
|
|
@@ -3573,8 +2181,8 @@ async function resolveArtifacts(options) {
|
|
|
3573
2181
|
}
|
|
3574
2182
|
|
|
3575
2183
|
// src/lib/guard-commands.ts
|
|
3576
|
-
import { readFile as
|
|
3577
|
-
import
|
|
2184
|
+
import { readFile as readFile6, readdir as readdir3 } from "fs/promises";
|
|
2185
|
+
import YAML3 from "yaml";
|
|
3578
2186
|
async function evaluateGuardrail(opts) {
|
|
3579
2187
|
let hookInput;
|
|
3580
2188
|
try {
|
|
@@ -3594,13 +2202,13 @@ async function evaluateGuardrail(opts) {
|
|
|
3594
2202
|
for (const bindingPath of opts.bindingPaths) {
|
|
3595
2203
|
let raw;
|
|
3596
2204
|
try {
|
|
3597
|
-
raw = await
|
|
2205
|
+
raw = await readFile6(bindingPath, "utf8");
|
|
3598
2206
|
} catch (err) {
|
|
3599
2207
|
const code = err.code;
|
|
3600
2208
|
if (code === "ENOENT") continue;
|
|
3601
2209
|
throw err;
|
|
3602
2210
|
}
|
|
3603
|
-
const binding =
|
|
2211
|
+
const binding = YAML3.parse(raw);
|
|
3604
2212
|
guardrailCtx = buildGuardrailContext(
|
|
3605
2213
|
opts.dsl,
|
|
3606
2214
|
binding,
|
|
@@ -3643,13 +2251,13 @@ async function listGuardrails(opts) {
|
|
|
3643
2251
|
for (const bindingPath of opts.bindingPaths) {
|
|
3644
2252
|
let raw;
|
|
3645
2253
|
try {
|
|
3646
|
-
raw = await
|
|
2254
|
+
raw = await readFile6(bindingPath, "utf8");
|
|
3647
2255
|
} catch (err) {
|
|
3648
2256
|
const code = err.code;
|
|
3649
2257
|
if (code === "ENOENT") continue;
|
|
3650
2258
|
throw err;
|
|
3651
2259
|
}
|
|
3652
|
-
const binding =
|
|
2260
|
+
const binding = YAML3.parse(raw);
|
|
3653
2261
|
guardrailCtx = buildGuardrailContext(
|
|
3654
2262
|
opts.dsl,
|
|
3655
2263
|
binding,
|
|
@@ -3702,7 +2310,7 @@ async function guardStatus(opts = {}) {
|
|
|
3702
2310
|
const filePath = `${runsDir}/${file}`;
|
|
3703
2311
|
let raw;
|
|
3704
2312
|
try {
|
|
3705
|
-
raw = await
|
|
2313
|
+
raw = await readFile6(filePath, "utf8");
|
|
3706
2314
|
} catch {
|
|
3707
2315
|
continue;
|
|
3708
2316
|
}
|
|
@@ -3724,8 +2332,159 @@ async function guardStatus(opts = {}) {
|
|
|
3724
2332
|
};
|
|
3725
2333
|
}
|
|
3726
2334
|
|
|
2335
|
+
// src/lib/claude-materialize/config.ts
|
|
2336
|
+
import { z as z2 } from "zod";
|
|
2337
|
+
var ClaudeConfigSchema = z2.object({
|
|
2338
|
+
/** Root directory for Claude artifacts (relative to the project root). */
|
|
2339
|
+
output_dir: z2.string().default(".claude"),
|
|
2340
|
+
/** Path to agent-contracts.yaml (relative to the project root). */
|
|
2341
|
+
config_path: z2.string().default("./agent-contracts.yaml"),
|
|
2342
|
+
/**
|
|
2343
|
+
* Command wired into guardrail hooks (e.g. "dev-team guard evaluate").
|
|
2344
|
+
* Reserved for future hook integration; validated for config parity.
|
|
2345
|
+
*/
|
|
2346
|
+
guard_command: z2.string().optional(),
|
|
2347
|
+
/** Override component id; defaults to `dsl.system.id`. */
|
|
2348
|
+
component_id: z2.string().optional()
|
|
2349
|
+
}).strip();
|
|
2350
|
+
function parseClaudeConfig(raw) {
|
|
2351
|
+
return ClaudeConfigSchema.parse(raw ?? {});
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
// src/lib/claude-materialize/materialize.ts
|
|
2355
|
+
import { existsSync as existsSync4 } from "fs";
|
|
2356
|
+
import { mkdir as mkdir3, readFile as readFile7, writeFile as writeFile3 } from "fs/promises";
|
|
2357
|
+
import { dirname as dirname3, join as join5, resolve as resolve5 } from "path";
|
|
2358
|
+
import {
|
|
2359
|
+
claudeGenerator
|
|
2360
|
+
} from "@aaac/contracts";
|
|
2361
|
+
var CLAUDE_BLOCK_BEGIN = "<!-- aaac:claude-native:begin -->";
|
|
2362
|
+
var CLAUDE_BLOCK_END = "<!-- aaac:claude-native:end -->";
|
|
2363
|
+
function buildComponentIR(dsl, config) {
|
|
2364
|
+
const system = dsl.system;
|
|
2365
|
+
const componentId = config.component_id ?? system?.id ?? "component";
|
|
2366
|
+
return {
|
|
2367
|
+
schema: "aaac/0.1",
|
|
2368
|
+
info: {
|
|
2369
|
+
id: componentId,
|
|
2370
|
+
version: system?.version ?? "1.0.0"
|
|
2371
|
+
},
|
|
2372
|
+
implementation: config.config_path,
|
|
2373
|
+
projections: ["claude"],
|
|
2374
|
+
operations: {}
|
|
2375
|
+
};
|
|
2376
|
+
}
|
|
2377
|
+
function relPath(file) {
|
|
2378
|
+
if (file.targetDir && file.targetDir !== ".") {
|
|
2379
|
+
return join5(file.targetDir, file.path);
|
|
2380
|
+
}
|
|
2381
|
+
return file.path;
|
|
2382
|
+
}
|
|
2383
|
+
function absPath(root, file) {
|
|
2384
|
+
return join5(root, relPath(file));
|
|
2385
|
+
}
|
|
2386
|
+
async function readIfExists(path) {
|
|
2387
|
+
if (!existsSync4(path)) return void 0;
|
|
2388
|
+
return readFile7(path, "utf8");
|
|
2389
|
+
}
|
|
2390
|
+
function renderFiles(dsl, config) {
|
|
2391
|
+
const ir = buildComponentIR(dsl, config);
|
|
2392
|
+
return claudeGenerator.generate(ir, { outputDir: "", componentPath: "" });
|
|
2393
|
+
}
|
|
2394
|
+
function mergeClaudeMdBlock(existing, block) {
|
|
2395
|
+
const normalizedBlock = block.trimStart();
|
|
2396
|
+
if (existing === void 0) {
|
|
2397
|
+
return { content: normalizedBlock, action: "created" };
|
|
2398
|
+
}
|
|
2399
|
+
const beginIdx = existing.indexOf(CLAUDE_BLOCK_BEGIN);
|
|
2400
|
+
const endIdx = existing.indexOf(CLAUDE_BLOCK_END);
|
|
2401
|
+
if (beginIdx === -1 || endIdx === -1) {
|
|
2402
|
+
const needsSeparator = existing.length > 0 && !existing.endsWith("\n");
|
|
2403
|
+
const content2 = existing + (needsSeparator ? "\n" : "") + normalizedBlock;
|
|
2404
|
+
return { content: content2, action: "updated" };
|
|
2405
|
+
}
|
|
2406
|
+
const before = existing.slice(0, beginIdx);
|
|
2407
|
+
let after = existing.slice(endIdx + CLAUDE_BLOCK_END.length);
|
|
2408
|
+
if (after === "\n") {
|
|
2409
|
+
after = "";
|
|
2410
|
+
}
|
|
2411
|
+
const content = before + normalizedBlock + after;
|
|
2412
|
+
if (content === existing) {
|
|
2413
|
+
return { content: existing, action: "unchanged" };
|
|
2414
|
+
}
|
|
2415
|
+
return { content, action: "updated" };
|
|
2416
|
+
}
|
|
2417
|
+
function expectedClaudeMdContent(existing, block) {
|
|
2418
|
+
return mergeClaudeMdBlock(existing, block).content;
|
|
2419
|
+
}
|
|
2420
|
+
function actionForOverwriteTrue(existing, next) {
|
|
2421
|
+
if (existing === void 0) return "created";
|
|
2422
|
+
return existing === next ? "unchanged" : "updated";
|
|
2423
|
+
}
|
|
2424
|
+
function resolveContent(file, existing) {
|
|
2425
|
+
if (file.path === "CLAUDE.md" && file.targetDir === "." && !file.overwrite) {
|
|
2426
|
+
return mergeClaudeMdBlock(existing, file.content);
|
|
2427
|
+
}
|
|
2428
|
+
if (!file.overwrite) {
|
|
2429
|
+
if (existing !== void 0) {
|
|
2430
|
+
return { content: existing, action: "unchanged" };
|
|
2431
|
+
}
|
|
2432
|
+
if (!file.content) {
|
|
2433
|
+
return { content: "", action: "unchanged" };
|
|
2434
|
+
}
|
|
2435
|
+
return { content: file.content, action: "created" };
|
|
2436
|
+
}
|
|
2437
|
+
const action = actionForOverwriteTrue(existing, file.content);
|
|
2438
|
+
return { content: file.content, action };
|
|
2439
|
+
}
|
|
2440
|
+
function checkContent(file, existing) {
|
|
2441
|
+
if (file.path === "CLAUDE.md" && file.targetDir === "." && !file.overwrite) {
|
|
2442
|
+
if (existing === void 0) return "missing";
|
|
2443
|
+
const expected = expectedClaudeMdContent(existing, file.content);
|
|
2444
|
+
return existing === expected ? null : "changed";
|
|
2445
|
+
}
|
|
2446
|
+
if (!file.overwrite) {
|
|
2447
|
+
if (existing === void 0 && file.content) return "missing";
|
|
2448
|
+
return null;
|
|
2449
|
+
}
|
|
2450
|
+
if (existing === void 0) return "missing";
|
|
2451
|
+
if (existing !== file.content) return "changed";
|
|
2452
|
+
return null;
|
|
2453
|
+
}
|
|
2454
|
+
async function syncClaude(opts) {
|
|
2455
|
+
const config = parseClaudeConfig(opts.config);
|
|
2456
|
+
const root = resolve5(opts.projectRoot);
|
|
2457
|
+
const result = { files: [] };
|
|
2458
|
+
for (const file of renderFiles(opts.dsl, config)) {
|
|
2459
|
+
const rel = relPath(file);
|
|
2460
|
+
const abs = absPath(root, file);
|
|
2461
|
+
const existing = await readIfExists(abs);
|
|
2462
|
+
const { content, action } = resolveContent(file, existing);
|
|
2463
|
+
if (action !== "unchanged" && !opts.dryRun) {
|
|
2464
|
+
await mkdir3(dirname3(abs), { recursive: true });
|
|
2465
|
+
await writeFile3(abs, content, "utf8");
|
|
2466
|
+
}
|
|
2467
|
+
result.files.push({ path: rel, action });
|
|
2468
|
+
}
|
|
2469
|
+
return result;
|
|
2470
|
+
}
|
|
2471
|
+
async function checkClaude(opts) {
|
|
2472
|
+
const config = parseClaudeConfig(opts.config);
|
|
2473
|
+
const root = resolve5(opts.projectRoot);
|
|
2474
|
+
const drift = [];
|
|
2475
|
+
for (const file of renderFiles(opts.dsl, config)) {
|
|
2476
|
+
const rel = relPath(file);
|
|
2477
|
+
const existing = await readIfExists(absPath(root, file));
|
|
2478
|
+
const reason = checkContent(file, existing);
|
|
2479
|
+
if (reason) {
|
|
2480
|
+
drift.push({ path: rel, reason });
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
return { inSync: drift.length === 0, drift };
|
|
2484
|
+
}
|
|
2485
|
+
|
|
3727
2486
|
// src/lib/prompt-executor.ts
|
|
3728
|
-
import * as
|
|
2487
|
+
import * as YAML4 from "yaml";
|
|
3729
2488
|
function unwrapInputSchema(input) {
|
|
3730
2489
|
if (!input) {
|
|
3731
2490
|
return { type: "object", properties: {} };
|
|
@@ -3784,7 +2543,7 @@ function parseRouterResponse(response, validNames) {
|
|
|
3784
2543
|
const content = yamlMatch ? yamlMatch[1].trim() : response.trim();
|
|
3785
2544
|
let parsed;
|
|
3786
2545
|
try {
|
|
3787
|
-
parsed =
|
|
2546
|
+
parsed = YAML4.parse(content);
|
|
3788
2547
|
} catch {
|
|
3789
2548
|
const jsonMatch = response.match(/\{[\s\S]*"operation"[\s\S]*\}/);
|
|
3790
2549
|
if (jsonMatch) {
|
|
@@ -3863,6 +2622,7 @@ export {
|
|
|
3863
2622
|
buildSdkFunctionTools,
|
|
3864
2623
|
buildSplitTaskPrompt,
|
|
3865
2624
|
buildTaskPrompt,
|
|
2625
|
+
checkClaude,
|
|
3866
2626
|
collectAnalyzerToolIds,
|
|
3867
2627
|
createAdapter,
|
|
3868
2628
|
createAnalyzerBridge,
|
|
@@ -3911,6 +2671,7 @@ export {
|
|
|
3911
2671
|
guardrailContextToRuleData,
|
|
3912
2672
|
hasBlockingViolation,
|
|
3913
2673
|
isContextPack,
|
|
2674
|
+
isFileEditTool,
|
|
3914
2675
|
isNavigationIndex,
|
|
3915
2676
|
jsonSchemaToZod,
|
|
3916
2677
|
listGuardrails,
|
|
@@ -3919,6 +2680,7 @@ export {
|
|
|
3919
2680
|
loadPluginsFromDirectory,
|
|
3920
2681
|
loadPluginsFromPaths,
|
|
3921
2682
|
operationsToTools,
|
|
2683
|
+
parseClaudeConfig,
|
|
3922
2684
|
parseGateEvaluationResponse,
|
|
3923
2685
|
parseRouterResponse,
|
|
3924
2686
|
pluginRegistry,
|
|
@@ -3932,6 +2694,7 @@ export {
|
|
|
3932
2694
|
runWorkflow,
|
|
3933
2695
|
serializeObserverEmit,
|
|
3934
2696
|
shouldInjectAnalyzerExplorationMandate,
|
|
2697
|
+
syncClaude,
|
|
3935
2698
|
version,
|
|
3936
2699
|
zodSchemaToPromptDescription,
|
|
3937
2700
|
zodSchemaToYamlExample
|