@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
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import {
|
|
2
|
+
emitToolExecClose
|
|
3
|
+
} from "./chunk-GNMSH3VC.js";
|
|
4
|
+
|
|
5
|
+
// src/lib/context-pack-adoption.ts
|
|
6
|
+
import { generateId } from "@aaac/observability";
|
|
7
|
+
var PATH_PROBE_TOOLS = /* @__PURE__ */ new Set(["Read", "Grep", "Glob"]);
|
|
8
|
+
var CONTEXT_PACK_TOOLS = /* @__PURE__ */ new Set([
|
|
9
|
+
"analyzer.generateContextPack",
|
|
10
|
+
"generateContextPack"
|
|
11
|
+
]);
|
|
12
|
+
var IMPACT_TOOLS = /* @__PURE__ */ new Set([
|
|
13
|
+
"analyzer.analyzeImpact",
|
|
14
|
+
"analyzeImpact"
|
|
15
|
+
]);
|
|
16
|
+
var MAX_ENTRIES_PATHS = 20;
|
|
17
|
+
var MAX_TOP_PATHS = 20;
|
|
18
|
+
function normalizeToolPath(path) {
|
|
19
|
+
let p = path.trim().replace(/\\/g, "/");
|
|
20
|
+
if (p.startsWith("./")) p = p.slice(2);
|
|
21
|
+
while (p.startsWith("/")) p = p.slice(1);
|
|
22
|
+
return p.toLowerCase();
|
|
23
|
+
}
|
|
24
|
+
function extractProbePaths(toolName, input) {
|
|
25
|
+
if (input == null || typeof input !== "object") return [];
|
|
26
|
+
const obj = input;
|
|
27
|
+
const paths = [];
|
|
28
|
+
if (toolName === "Read") {
|
|
29
|
+
const fp = obj.file_path ?? obj.path;
|
|
30
|
+
if (typeof fp === "string" && fp.length > 0) paths.push(fp);
|
|
31
|
+
return paths;
|
|
32
|
+
}
|
|
33
|
+
if (toolName === "Grep") {
|
|
34
|
+
const fp = obj.path ?? obj.file_path;
|
|
35
|
+
if (typeof fp === "string" && fp.length > 0) paths.push(fp);
|
|
36
|
+
return paths;
|
|
37
|
+
}
|
|
38
|
+
if (toolName === "Glob") {
|
|
39
|
+
const fp = obj.path ?? obj.cwd;
|
|
40
|
+
if (typeof fp === "string" && fp.length > 0) paths.push(fp);
|
|
41
|
+
return paths;
|
|
42
|
+
}
|
|
43
|
+
return paths;
|
|
44
|
+
}
|
|
45
|
+
function isPathProbeTool(toolName) {
|
|
46
|
+
return PATH_PROBE_TOOLS.has(toolName);
|
|
47
|
+
}
|
|
48
|
+
function isContextPackTool(toolName) {
|
|
49
|
+
return CONTEXT_PACK_TOOLS.has(toolName);
|
|
50
|
+
}
|
|
51
|
+
function isImpactTool(toolName) {
|
|
52
|
+
return IMPACT_TOOLS.has(toolName);
|
|
53
|
+
}
|
|
54
|
+
function isAnalyzerObservabilityTool(toolName) {
|
|
55
|
+
return isContextPackTool(toolName) || isImpactTool(toolName);
|
|
56
|
+
}
|
|
57
|
+
function buildContextPackOutputSummary(pack) {
|
|
58
|
+
const entriesPaths = pack.entries.map((e) => e.path).slice(0, MAX_ENTRIES_PATHS);
|
|
59
|
+
return JSON.stringify({
|
|
60
|
+
files_included: pack.metadata.filesIncluded,
|
|
61
|
+
files_referenced: pack.metadata.filesReferenced,
|
|
62
|
+
artifacts_covered: pack.metadata.artifactsCovered,
|
|
63
|
+
total_tokens: pack.metadata.totalTokens,
|
|
64
|
+
budget_tokens: pack.metadata.budgetTokens,
|
|
65
|
+
entries_paths: entriesPaths
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function buildAnalyzeImpactOutputSummary(report) {
|
|
69
|
+
const directly = Array.isArray(report.directlyAffected) ? report.directlyAffected : [];
|
|
70
|
+
const transitive = Array.isArray(report.transitivelyAffected) ? report.transitivelyAffected : [];
|
|
71
|
+
const allPaths = [...directly, ...transitive].map((e) => e.path).filter((p) => typeof p === "string").slice(0, MAX_TOP_PATHS);
|
|
72
|
+
const maxDepth = Math.max(
|
|
73
|
+
...directly.map((e) => e.depth ?? 0),
|
|
74
|
+
...transitive.map((e) => e.depth ?? 0),
|
|
75
|
+
0
|
|
76
|
+
);
|
|
77
|
+
return JSON.stringify({
|
|
78
|
+
affected_count: directly.length + transitive.length,
|
|
79
|
+
max_depth_reached: maxDepth,
|
|
80
|
+
top_paths: allPaths
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
function buildAnalyzerCloseAttributes(toolName, resultText) {
|
|
84
|
+
let parsed;
|
|
85
|
+
try {
|
|
86
|
+
parsed = JSON.parse(resultText);
|
|
87
|
+
} catch {
|
|
88
|
+
return { extraAttributes: {}, paths: [] };
|
|
89
|
+
}
|
|
90
|
+
if (isContextPackTool(toolName)) {
|
|
91
|
+
const pack = parsed;
|
|
92
|
+
const contextPackId = generateId();
|
|
93
|
+
const outputSummary = buildContextPackOutputSummary(pack);
|
|
94
|
+
const paths = (pack.entries ?? []).map((e) => e.path);
|
|
95
|
+
return {
|
|
96
|
+
extraAttributes: {
|
|
97
|
+
"tool.output_summary": outputSummary,
|
|
98
|
+
"tool.context_pack_id": contextPackId
|
|
99
|
+
},
|
|
100
|
+
paths,
|
|
101
|
+
contextPackId
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
if (isImpactTool(toolName)) {
|
|
105
|
+
const outputSummary = buildAnalyzeImpactOutputSummary(parsed);
|
|
106
|
+
const contextPackId = generateId();
|
|
107
|
+
const directly = Array.isArray(parsed.directlyAffected) ? parsed.directlyAffected : [];
|
|
108
|
+
const transitive = Array.isArray(parsed.transitivelyAffected) ? parsed.transitivelyAffected : [];
|
|
109
|
+
const paths = [...directly, ...transitive].map((e) => e.path).filter((p) => typeof p === "string");
|
|
110
|
+
return {
|
|
111
|
+
extraAttributes: {
|
|
112
|
+
"tool.output_summary": outputSummary,
|
|
113
|
+
"tool.context_pack_id": contextPackId
|
|
114
|
+
},
|
|
115
|
+
paths,
|
|
116
|
+
contextPackId
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
return { extraAttributes: {}, paths: [] };
|
|
120
|
+
}
|
|
121
|
+
var ContextPackAdoptionTracker = class {
|
|
122
|
+
packsBySession = /* @__PURE__ */ new Map();
|
|
123
|
+
registerPack(sessionId, spanId, contextPackId, paths) {
|
|
124
|
+
if (!sessionId) return;
|
|
125
|
+
const normalized = new Set(
|
|
126
|
+
paths.map(normalizeToolPath).filter((p) => p.length > 0)
|
|
127
|
+
);
|
|
128
|
+
const records = this.packsBySession.get(sessionId) ?? [];
|
|
129
|
+
records.push({
|
|
130
|
+
contextPackId,
|
|
131
|
+
spanId,
|
|
132
|
+
paths: normalized,
|
|
133
|
+
readPaths: /* @__PURE__ */ new Set()
|
|
134
|
+
});
|
|
135
|
+
this.packsBySession.set(sessionId, records);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Evaluate adoption for a path-probe tool at emit time.
|
|
139
|
+
* Returns undefined when no pack was registered before this call.
|
|
140
|
+
*/
|
|
141
|
+
evaluate(sessionId, toolName, input) {
|
|
142
|
+
if (!sessionId || !isPathProbeTool(toolName)) return void 0;
|
|
143
|
+
const packs = this.packsBySession.get(sessionId);
|
|
144
|
+
if (!packs || packs.length === 0) return void 0;
|
|
145
|
+
const probePaths = extractProbePaths(toolName, input).map(normalizeToolPath);
|
|
146
|
+
if (probePaths.length === 0) return void 0;
|
|
147
|
+
const latestPack = packs[packs.length - 1];
|
|
148
|
+
const probePath = probePaths[0];
|
|
149
|
+
const inPack = latestPack.paths.has(probePath);
|
|
150
|
+
let kind;
|
|
151
|
+
if (inPack) {
|
|
152
|
+
kind = latestPack.readPaths.has(probePath) ? "pack_redundant" : "pack_hit";
|
|
153
|
+
latestPack.readPaths.add(probePath);
|
|
154
|
+
} else {
|
|
155
|
+
kind = "pack_miss";
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
kind,
|
|
159
|
+
contextPackId: latestPack.contextPackId,
|
|
160
|
+
links: [
|
|
161
|
+
{
|
|
162
|
+
linkType: "uses_context_from",
|
|
163
|
+
targetSpanId: latestPack.spanId
|
|
164
|
+
}
|
|
165
|
+
]
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
// src/lib/tool-exec-span-registry.ts
|
|
171
|
+
var ToolExecSpanRegistry = class {
|
|
172
|
+
pending = [];
|
|
173
|
+
register(span) {
|
|
174
|
+
this.pending.push({ ...span, closed: false });
|
|
175
|
+
}
|
|
176
|
+
/** Close the oldest still-open span for {@link toolName} (FIFO). */
|
|
177
|
+
closeFirst(toolName) {
|
|
178
|
+
const idx = this.pending.findIndex((s) => !s.closed && s.toolName === toolName);
|
|
179
|
+
if (idx === -1) return void 0;
|
|
180
|
+
this.pending[idx].closed = true;
|
|
181
|
+
return this.pending[idx];
|
|
182
|
+
}
|
|
183
|
+
isClosed(spanId) {
|
|
184
|
+
const span = this.pending.find((s) => s.spanId === spanId);
|
|
185
|
+
return span?.closed ?? false;
|
|
186
|
+
}
|
|
187
|
+
/** Return spans that are still open (for turn-boundary close). */
|
|
188
|
+
getStillOpen() {
|
|
189
|
+
return this.pending.filter((s) => !s.closed);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// src/lib/library-tool-sdk.ts
|
|
194
|
+
function buildSdkFunctionTools(registry) {
|
|
195
|
+
return registry.getAll().map((def) => ({
|
|
196
|
+
name: def.toolId,
|
|
197
|
+
description: def.description,
|
|
198
|
+
inputSchema: def.inputSchema ?? { type: "object", properties: {} },
|
|
199
|
+
handler: async (args) => {
|
|
200
|
+
const result = await registry.execute(def.toolId, args);
|
|
201
|
+
return typeof result === "string" ? result : JSON.stringify(result);
|
|
202
|
+
}
|
|
203
|
+
}));
|
|
204
|
+
}
|
|
205
|
+
async function buildClaudeMcpServer(registry, observability) {
|
|
206
|
+
const tools = buildSdkFunctionTools(registry);
|
|
207
|
+
if (tools.length === 0) return void 0;
|
|
208
|
+
const sdk = await import("@anthropic-ai/claude-agent-sdk");
|
|
209
|
+
const toolFn = sdk.tool;
|
|
210
|
+
const createServer = sdk.createSdkMcpServer;
|
|
211
|
+
if (!toolFn || !createServer) return void 0;
|
|
212
|
+
const { z } = await import("zod");
|
|
213
|
+
const { jsonSchemaToZod } = await import("./schema-converter-LACA7P4O.js");
|
|
214
|
+
const sdkTools = tools.map((t) => {
|
|
215
|
+
const zodType = jsonSchemaToZod(t.inputSchema);
|
|
216
|
+
const shape = zodType instanceof z.ZodObject ? zodType.shape : {};
|
|
217
|
+
return toolFn(
|
|
218
|
+
t.name,
|
|
219
|
+
t.description,
|
|
220
|
+
shape,
|
|
221
|
+
async (args) => {
|
|
222
|
+
const startMs = Date.now();
|
|
223
|
+
const text = await t.handler(
|
|
224
|
+
args ?? {}
|
|
225
|
+
);
|
|
226
|
+
if (observability?.observer && observability.spanRegistry) {
|
|
227
|
+
const pending = observability.spanRegistry.closeFirst(t.name);
|
|
228
|
+
if (pending) {
|
|
229
|
+
const closeAttrs = isAnalyzerObservabilityTool(t.name) ? buildAnalyzerCloseAttributes(t.name, text) : { extraAttributes: {}, paths: [], contextPackId: void 0 };
|
|
230
|
+
emitToolExecClose(
|
|
231
|
+
observability.observer,
|
|
232
|
+
pending.spanId,
|
|
233
|
+
t.name,
|
|
234
|
+
Date.now() - startMs,
|
|
235
|
+
{
|
|
236
|
+
sessionId: observability.sessionId,
|
|
237
|
+
extraAttributes: closeAttrs.extraAttributes,
|
|
238
|
+
outputSummary: closeAttrs.extraAttributes["tool.output_summary"]
|
|
239
|
+
}
|
|
240
|
+
);
|
|
241
|
+
if (observability.adoptionTracker && closeAttrs.contextPackId && closeAttrs.paths.length > 0) {
|
|
242
|
+
observability.adoptionTracker.registerPack(
|
|
243
|
+
observability.sessionId,
|
|
244
|
+
pending.spanId,
|
|
245
|
+
closeAttrs.contextPackId,
|
|
246
|
+
closeAttrs.paths
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return { content: [{ type: "text", text }] };
|
|
252
|
+
}
|
|
253
|
+
);
|
|
254
|
+
});
|
|
255
|
+
return createServer({
|
|
256
|
+
name: "aaac-library-tools",
|
|
257
|
+
version: "1.0.0",
|
|
258
|
+
tools: sdkTools
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
async function buildOpenAIFunctionTools(registry) {
|
|
262
|
+
const tools = buildSdkFunctionTools(registry);
|
|
263
|
+
if (tools.length === 0) return [];
|
|
264
|
+
try {
|
|
265
|
+
const sdk = await import("@openai/agents");
|
|
266
|
+
const toolFn = sdk.tool;
|
|
267
|
+
if (toolFn) {
|
|
268
|
+
const { jsonSchemaToZod } = await import("./schema-converter-LACA7P4O.js");
|
|
269
|
+
return tools.map(
|
|
270
|
+
(t) => toolFn({
|
|
271
|
+
name: t.name,
|
|
272
|
+
description: t.description,
|
|
273
|
+
parameters: jsonSchemaToZod(t.inputSchema),
|
|
274
|
+
execute: async (_ctx, args) => {
|
|
275
|
+
return t.handler(
|
|
276
|
+
args ?? {}
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
})
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
} catch {
|
|
283
|
+
}
|
|
284
|
+
return tools.map((t) => ({
|
|
285
|
+
type: "function",
|
|
286
|
+
function: {
|
|
287
|
+
name: t.name,
|
|
288
|
+
description: t.description,
|
|
289
|
+
parameters: t.inputSchema
|
|
290
|
+
},
|
|
291
|
+
execute: async (args) => {
|
|
292
|
+
return t.handler(
|
|
293
|
+
args ?? {}
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
}));
|
|
297
|
+
}
|
|
298
|
+
async function buildAdkFunctionTools(registry) {
|
|
299
|
+
const tools = buildSdkFunctionTools(registry);
|
|
300
|
+
if (tools.length === 0) return [];
|
|
301
|
+
return tools.map((t) => ({
|
|
302
|
+
name: t.name,
|
|
303
|
+
description: t.description,
|
|
304
|
+
inputSchema: t.inputSchema,
|
|
305
|
+
execute: async (args) => {
|
|
306
|
+
return t.handler(
|
|
307
|
+
args ?? {}
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
}));
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export {
|
|
314
|
+
ContextPackAdoptionTracker,
|
|
315
|
+
ToolExecSpanRegistry,
|
|
316
|
+
buildSdkFunctionTools,
|
|
317
|
+
buildClaudeMcpServer,
|
|
318
|
+
buildOpenAIFunctionTools,
|
|
319
|
+
buildAdkFunctionTools
|
|
320
|
+
};
|
|
321
|
+
//# sourceMappingURL=chunk-IQGCUM7E.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/context-pack-adoption.ts","../src/lib/tool-exec-span-registry.ts","../src/lib/library-tool-sdk.ts"],"sourcesContent":["/**\n * ContextPack adoption observability (#151).\n *\n * Session-scoped cache of ContextPack / analyzeImpact metadata for emit-time\n * adoption marking on subsequent Read/Glob/Grep tool_exec spans.\n */\n\nimport { generateId } from \"@aaac/observability\";\nimport type { CanonicalLink } from \"@aaac/observability\";\nimport type { ContextPack } from \"./analyzer-bridge.js\";\n\nexport type AdoptionKind = \"pack_hit\" | \"pack_redundant\" | \"pack_miss\";\n\nexport interface AdoptionMarking {\n kind: AdoptionKind;\n contextPackId: string;\n links: CanonicalLink[];\n}\n\ninterface PackRecord {\n contextPackId: string;\n spanId: string;\n paths: Set<string>;\n readPaths: Set<string>;\n}\n\nconst PATH_PROBE_TOOLS = new Set([\"Read\", \"Grep\", \"Glob\"]);\nconst CONTEXT_PACK_TOOLS = new Set([\n \"analyzer.generateContextPack\",\n \"generateContextPack\",\n]);\nconst IMPACT_TOOLS = new Set([\n \"analyzer.analyzeImpact\",\n \"analyzeImpact\",\n]);\n\nconst MAX_ENTRIES_PATHS = 20;\nconst MAX_TOP_PATHS = 20;\n\n/** Normalise file paths for set membership checks. */\nexport function normalizeToolPath(path: string): string {\n let p = path.trim().replace(/\\\\/g, \"/\");\n if (p.startsWith(\"./\")) p = p.slice(2);\n while (p.startsWith(\"/\")) p = p.slice(1);\n return p.toLowerCase();\n}\n\n/** Extract probe paths from Read/Glob/Grep tool input. */\nexport function extractProbePaths(toolName: string, input: unknown): string[] {\n if (input == null || typeof input !== \"object\") return [];\n const obj = input as Record<string, unknown>;\n const paths: string[] = [];\n\n if (toolName === \"Read\") {\n const fp = obj.file_path ?? obj.path;\n if (typeof fp === \"string\" && fp.length > 0) paths.push(fp);\n return paths;\n }\n\n if (toolName === \"Grep\") {\n const fp = obj.path ?? obj.file_path;\n if (typeof fp === \"string\" && fp.length > 0) paths.push(fp);\n return paths;\n }\n\n if (toolName === \"Glob\") {\n const fp = obj.path ?? obj.cwd;\n if (typeof fp === \"string\" && fp.length > 0) paths.push(fp);\n return paths;\n }\n\n return paths;\n}\n\nexport function isPathProbeTool(toolName: string): boolean {\n return PATH_PROBE_TOOLS.has(toolName);\n}\n\nexport function isContextPackTool(toolName: string): boolean {\n return CONTEXT_PACK_TOOLS.has(toolName);\n}\n\nexport function isImpactTool(toolName: string): boolean {\n return IMPACT_TOOLS.has(toolName);\n}\n\nexport function isAnalyzerObservabilityTool(toolName: string): boolean {\n return isContextPackTool(toolName) || isImpactTool(toolName);\n}\n\nexport function buildContextPackOutputSummary(pack: ContextPack): string {\n const entriesPaths = pack.entries\n .map((e) => e.path)\n .slice(0, MAX_ENTRIES_PATHS);\n return JSON.stringify({\n files_included: pack.metadata.filesIncluded,\n files_referenced: pack.metadata.filesReferenced,\n artifacts_covered: pack.metadata.artifactsCovered,\n total_tokens: pack.metadata.totalTokens,\n budget_tokens: pack.metadata.budgetTokens,\n entries_paths: entriesPaths,\n });\n}\n\nexport function buildAnalyzeImpactOutputSummary(report: Record<string, unknown>): string {\n const directly = Array.isArray(report.directlyAffected)\n ? (report.directlyAffected as Array<{ path?: string }>)\n : [];\n const transitive = Array.isArray(report.transitivelyAffected)\n ? (report.transitivelyAffected as Array<{ path?: string }>)\n : [];\n const allPaths = [...directly, ...transitive]\n .map((e) => e.path)\n .filter((p): p is string => typeof p === \"string\")\n .slice(0, MAX_TOP_PATHS);\n const maxDepth = Math.max(\n ...directly.map((e) => (e as { depth?: number }).depth ?? 0),\n ...transitive.map((e) => (e as { depth?: number }).depth ?? 0),\n 0,\n );\n return JSON.stringify({\n affected_count: directly.length + transitive.length,\n max_depth_reached: maxDepth,\n top_paths: allPaths,\n });\n}\n\n/** Build close attributes + register paths from an analyzer MCP handler result. */\nexport function buildAnalyzerCloseAttributes(\n toolName: string,\n resultText: string,\n): { extraAttributes: Record<string, string>; paths: string[]; contextPackId?: string } {\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(resultText) as Record<string, unknown>;\n } catch {\n return { extraAttributes: {}, paths: [] };\n }\n\n if (isContextPackTool(toolName)) {\n const pack = parsed as unknown as ContextPack;\n const contextPackId = generateId();\n const outputSummary = buildContextPackOutputSummary(pack);\n const paths = (pack.entries ?? []).map((e) => e.path);\n return {\n extraAttributes: {\n \"tool.output_summary\": outputSummary,\n \"tool.context_pack_id\": contextPackId,\n },\n paths,\n contextPackId,\n };\n }\n\n if (isImpactTool(toolName)) {\n const outputSummary = buildAnalyzeImpactOutputSummary(parsed);\n const contextPackId = generateId();\n const directly = Array.isArray(parsed.directlyAffected)\n ? (parsed.directlyAffected as Array<{ path?: string }>)\n : [];\n const transitive = Array.isArray(parsed.transitivelyAffected)\n ? (parsed.transitivelyAffected as Array<{ path?: string }>)\n : [];\n const paths = [...directly, ...transitive]\n .map((e) => e.path)\n .filter((p): p is string => typeof p === \"string\");\n return {\n extraAttributes: {\n \"tool.output_summary\": outputSummary,\n \"tool.context_pack_id\": contextPackId,\n },\n paths,\n contextPackId,\n };\n }\n\n return { extraAttributes: {}, paths: [] };\n}\n\nexport class ContextPackAdoptionTracker {\n private readonly packsBySession = new Map<string, PackRecord[]>();\n\n registerPack(\n sessionId: string | undefined,\n spanId: string,\n contextPackId: string,\n paths: string[],\n ): void {\n if (!sessionId) return;\n const normalized = new Set(\n paths.map(normalizeToolPath).filter((p) => p.length > 0),\n );\n const records = this.packsBySession.get(sessionId) ?? [];\n records.push({\n contextPackId,\n spanId,\n paths: normalized,\n readPaths: new Set(),\n });\n this.packsBySession.set(sessionId, records);\n }\n\n /**\n * Evaluate adoption for a path-probe tool at emit time.\n * Returns undefined when no pack was registered before this call.\n */\n evaluate(\n sessionId: string | undefined,\n toolName: string,\n input: unknown,\n ): AdoptionMarking | undefined {\n if (!sessionId || !isPathProbeTool(toolName)) return undefined;\n\n const packs = this.packsBySession.get(sessionId);\n if (!packs || packs.length === 0) return undefined;\n\n const probePaths = extractProbePaths(toolName, input).map(normalizeToolPath);\n if (probePaths.length === 0) return undefined;\n\n const latestPack = packs[packs.length - 1];\n const probePath = probePaths[0];\n\n const inPack = latestPack.paths.has(probePath);\n let kind: AdoptionKind;\n if (inPack) {\n kind = latestPack.readPaths.has(probePath) ? \"pack_redundant\" : \"pack_hit\";\n latestPack.readPaths.add(probePath);\n } else {\n kind = \"pack_miss\";\n }\n\n return {\n kind,\n contextPackId: latestPack.contextPackId,\n links: [\n {\n linkType: \"uses_context_from\",\n targetSpanId: latestPack.spanId,\n },\n ],\n };\n }\n}\n","/**\n * Tracks pending agent.tool_exec open spans so MCP handlers can close them\n * immediately on completion (#151) without waiting for the next assistant turn.\n */\n\nexport interface PendingToolSpan {\n spanId: string;\n toolName: string;\n startMs: number;\n closed: boolean;\n}\n\nexport class ToolExecSpanRegistry {\n private readonly pending: PendingToolSpan[] = [];\n\n register(span: Omit<PendingToolSpan, \"closed\">): void {\n this.pending.push({ ...span, closed: false });\n }\n\n /** Close the oldest still-open span for {@link toolName} (FIFO). */\n closeFirst(toolName: string): PendingToolSpan | undefined {\n const idx = this.pending.findIndex((s) => !s.closed && s.toolName === toolName);\n if (idx === -1) return undefined;\n this.pending[idx].closed = true;\n return this.pending[idx];\n }\n\n isClosed(spanId: string): boolean {\n const span = this.pending.find((s) => s.spanId === spanId);\n return span?.closed ?? false;\n }\n\n /** Return spans that are still open (for turn-boundary close). */\n getStillOpen(): PendingToolSpan[] {\n return this.pending.filter((s) => !s.closed);\n }\n}\n","/**\n * Library Tool → SDK Function Tool conversion.\n *\n * Converts LibraryToolDefinition entries into SDK-native function tools\n * that each adapter can register with its respective LLM SDK.\n *\n * Each adapter receives tools in its native format:\n * - Claude Agent SDK: MCP tool via createSdkMcpServer + tool()\n * - OpenAI Agents SDK: function tool object\n * - Google ADK: FunctionDeclaration tool\n */\n\nimport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nimport type { ObserverEmitFn } from \"./observability-bridge.js\";\nimport { emitToolExecClose } from \"./observability-bridge.js\";\nimport {\n buildAnalyzerCloseAttributes,\n ContextPackAdoptionTracker,\n isAnalyzerObservabilityTool,\n} from \"./context-pack-adoption.js\";\nimport { ToolExecSpanRegistry } from \"./tool-exec-span-registry.js\";\n\n/** Observability context for MCP handler completion-time tool_exec close (#151). */\nexport interface McpObservabilityContext {\n observer?: ObserverEmitFn;\n sessionId?: string;\n spanRegistry?: ToolExecSpanRegistry;\n adoptionTracker?: ContextPackAdoptionTracker;\n}\n\n/**\n * Adapter-agnostic function tool descriptor. Adapters convert this\n * into their SDK-specific tool format.\n */\nexport interface SdkFunctionTool {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n handler: (args: Record<string, unknown>) => Promise<string>;\n}\n\n/**\n * Build adapter-agnostic function tool descriptors from a LibraryToolRegistry.\n * Each tool's handler calls registry.execute() and serialises the result.\n */\nexport function buildSdkFunctionTools(\n registry: LibraryToolRegistry,\n): SdkFunctionTool[] {\n return registry.getAll().map((def) => ({\n name: def.toolId,\n description: def.description,\n inputSchema: def.inputSchema ?? { type: \"object\", properties: {} },\n handler: async (args: Record<string, unknown>): Promise<string> => {\n const result = await registry.execute(def.toolId, args);\n return typeof result === \"string\" ? result : JSON.stringify(result);\n },\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Claude Agent SDK — MCP server wrapping\n// ---------------------------------------------------------------------------\n\n/**\n * Build Claude MCP server tools from a LibraryToolRegistry.\n *\n * Dynamically imports `tool` and `createSdkMcpServer` from the\n * Claude Agent SDK. Returns an MCP server instance to be passed\n * to query() via options.mcpServers.\n *\n * Returns undefined if no tools or if SDK functions are unavailable.\n */\nexport async function buildClaudeMcpServer(\n registry: LibraryToolRegistry,\n observability?: McpObservabilityContext,\n): Promise<unknown | undefined> {\n const tools = buildSdkFunctionTools(registry);\n if (tools.length === 0) return undefined;\n\n const sdk = (await import(\"@anthropic-ai/claude-agent-sdk\")) as Record<\n string,\n unknown\n >;\n type McpToolFn = (\n name: string,\n description: string,\n inputSchema: Record<string, unknown>,\n handler: (\n args: Record<string, unknown>,\n extra: unknown,\n ) => Promise<{ content: Array<{ type: string; text: string }> }>,\n ) => unknown;\n\n const toolFn = sdk.tool as McpToolFn | undefined;\n const createServer = sdk.createSdkMcpServer as\n | ((options: {\n name: string;\n version?: string;\n tools?: unknown[];\n }) => unknown)\n | undefined;\n\n if (!toolFn || !createServer) return undefined;\n\n const { z } = await import(\"zod\");\n const { jsonSchemaToZod } = await import(\"./schema-converter.js\");\n\n const sdkTools = tools.map((t) => {\n const zodType = jsonSchemaToZod(t.inputSchema);\n const shape =\n zodType instanceof z.ZodObject\n ? (zodType.shape as Record<string, unknown>)\n : {};\n\n return toolFn(\n t.name,\n t.description,\n shape,\n async (args) => {\n const startMs = Date.now();\n const text = await t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n if (observability?.observer && observability.spanRegistry) {\n const pending = observability.spanRegistry.closeFirst(t.name);\n if (pending) {\n const closeAttrs = isAnalyzerObservabilityTool(t.name)\n ? buildAnalyzerCloseAttributes(t.name, text)\n : { extraAttributes: {}, paths: [] as string[], contextPackId: undefined };\n emitToolExecClose(\n observability.observer,\n pending.spanId,\n t.name,\n Date.now() - startMs,\n {\n sessionId: observability.sessionId,\n extraAttributes: closeAttrs.extraAttributes,\n outputSummary: closeAttrs.extraAttributes[\"tool.output_summary\"] as string | undefined,\n },\n );\n if (\n observability.adoptionTracker &&\n closeAttrs.contextPackId &&\n closeAttrs.paths.length > 0\n ) {\n observability.adoptionTracker.registerPack(\n observability.sessionId,\n pending.spanId,\n closeAttrs.contextPackId,\n closeAttrs.paths,\n );\n }\n }\n }\n return { content: [{ type: \"text\", text }] };\n },\n );\n });\n\n return createServer({\n name: \"aaac-library-tools\",\n version: \"1.0.0\",\n tools: sdkTools,\n });\n}\n\n// ---------------------------------------------------------------------------\n// OpenAI Agents SDK — function tool objects\n// ---------------------------------------------------------------------------\n\n/**\n * Build OpenAI Agents SDK function tool objects from a LibraryToolRegistry.\n *\n * Dynamically imports `tool` from @openai/agents if available.\n * Falls back to a raw function-tool shape that the SDK also accepts.\n */\nexport async function buildOpenAIFunctionTools(\n registry: LibraryToolRegistry,\n): Promise<unknown[]> {\n const tools = buildSdkFunctionTools(registry);\n if (tools.length === 0) return [];\n\n try {\n const sdk = (await import(\"@openai/agents\")) as Record<string, unknown>;\n const toolFn = sdk.tool as\n | ((def: Record<string, unknown>) => unknown)\n | undefined;\n\n if (toolFn) {\n const { jsonSchemaToZod } = await import(\"./schema-converter.js\");\n return tools.map((t) =>\n toolFn({\n name: t.name,\n description: t.description,\n parameters: jsonSchemaToZod(t.inputSchema),\n execute: async (_ctx: unknown, args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }),\n );\n }\n } catch {\n // SDK not available; fall through to raw format\n }\n\n return tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n },\n execute: async (args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Google ADK — function tool objects\n// ---------------------------------------------------------------------------\n\n/**\n * Build Google ADK function tool objects from a LibraryToolRegistry.\n *\n * ADK's LlmAgent accepts tools as objects with a FunctionDeclaration shape\n * or as callable tool instances. We produce lightweight callable wrappers.\n */\nexport async function buildAdkFunctionTools(\n registry: LibraryToolRegistry,\n): Promise<unknown[]> {\n const tools = buildSdkFunctionTools(registry);\n if (tools.length === 0) return [];\n\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n execute: async (args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }));\n}\n"],"mappings":";;;;;AAOA,SAAS,kBAAkB;AAmB3B,IAAM,mBAAmB,oBAAI,IAAI,CAAC,QAAQ,QAAQ,MAAM,CAAC;AACzD,IAAM,qBAAqB,oB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AAQ,CAAC;AAAA,YACZ;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO,MAAM,IAAI,CAAC,OAAO;AAAA,IACvB,MAAM;AAAA,IACN,UAAU;AAAA,MACR,MAAM,EAAE;AAAA,MACR,aAAa,EAAE;AAAA,MACf,YAAY,EAAE;AAAA,IAChB;AAAA,IACA,SAAS,OAAO,SAAkB;AAChC,aAAO,EAAE;AAAA,QACN,QAAQ,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,EACF,EAAE;AACJ;AAYA,eAAsB,sBACpB,UACoB;AACpB,QAAM,QAAQ,sBAAsB,QAAQ;AAC5C,MAAI,MAAM,WAAW,EAAG,QAAO,CAAC;AAEhC,SAAO,MAAM,IAAI,CAAC,OAAO;AAAA,IACvB,MAAM,EAAE;AAAA,IACR,aAAa,EAAE;AAAA,IACf,aAAa,EAAE;AAAA,IACf,SAAS,OAAO,SAAkB;AAChC,aAAO,EAAE;AAAA,QACN,QAAQ,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,EACF,EAAE;AACJ;","names":[]}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SDK Guardrail Hook Bridge — generic adapter from guardrail check functions
|
|
3
|
+
* + plugin guardrails to SDK-compatible hook responses.
|
|
4
|
+
*
|
|
5
|
+
* Embedded guardrail rules are converted via createGuardrailHooksFromRules(),
|
|
6
|
+
* which delegates to createGuardrailHooks(). All hook logic lives here.
|
|
7
|
+
*/
|
|
8
|
+
interface GuardrailCheckResult {
|
|
9
|
+
guardrail_id: string;
|
|
10
|
+
passed: boolean;
|
|
11
|
+
action: "block" | "warn" | "shadow" | "info";
|
|
12
|
+
message: string;
|
|
13
|
+
}
|
|
14
|
+
interface HookResponse {
|
|
15
|
+
permission?: "deny";
|
|
16
|
+
user_message?: string;
|
|
17
|
+
agent_message?: string;
|
|
18
|
+
additionalContext?: string;
|
|
19
|
+
}
|
|
20
|
+
interface GuardrailRule {
|
|
21
|
+
guardrail_id: string;
|
|
22
|
+
pattern: string;
|
|
23
|
+
action: "block" | "warn" | "shadow" | "info";
|
|
24
|
+
message: string;
|
|
25
|
+
file_glob?: string;
|
|
26
|
+
exclude_glob?: string;
|
|
27
|
+
}
|
|
28
|
+
interface GuardrailRuleData {
|
|
29
|
+
commandRules: GuardrailRule[];
|
|
30
|
+
fileRules: GuardrailRule[];
|
|
31
|
+
contentRules: GuardrailRule[];
|
|
32
|
+
}
|
|
33
|
+
interface GuardrailCheckFunctions {
|
|
34
|
+
checkCommand: (command: string) => GuardrailCheckResult[];
|
|
35
|
+
checkFilePath: (filePath: string) => GuardrailCheckResult[];
|
|
36
|
+
checkContent: (filePath: string, content: string) => GuardrailCheckResult[];
|
|
37
|
+
}
|
|
38
|
+
interface HookContext {
|
|
39
|
+
/** Agent id for per-agent guardrail filtering. */
|
|
40
|
+
agentId?: string;
|
|
41
|
+
command?: string;
|
|
42
|
+
filePath?: string;
|
|
43
|
+
content?: string;
|
|
44
|
+
}
|
|
45
|
+
interface GuardrailHooks {
|
|
46
|
+
beforeShellExecution: (input: {
|
|
47
|
+
command?: string;
|
|
48
|
+
}) => HookResponse;
|
|
49
|
+
preToolUse: (input: {
|
|
50
|
+
tool_name?: string;
|
|
51
|
+
tool_input?: {
|
|
52
|
+
file_path?: string;
|
|
53
|
+
path?: string;
|
|
54
|
+
};
|
|
55
|
+
}) => HookResponse;
|
|
56
|
+
afterFileEdit: (input: {
|
|
57
|
+
file_path?: string;
|
|
58
|
+
content?: string;
|
|
59
|
+
}) => HookResponse;
|
|
60
|
+
runChecks: (ctx: HookContext) => GuardrailCheckResult[];
|
|
61
|
+
}
|
|
62
|
+
declare function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[];
|
|
63
|
+
declare function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[];
|
|
64
|
+
declare function hasBlockingViolation(results: GuardrailCheckResult[]): boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Create SDK hook functions from generated guardrail check functions.
|
|
67
|
+
*
|
|
68
|
+
* Merges DSL-generated checks with plugin-registered guardrails and
|
|
69
|
+
* returns hook functions in the format expected by the Claude SDK,
|
|
70
|
+
* plus a generic runChecks() for programmatic use.
|
|
71
|
+
*/
|
|
72
|
+
declare function createGuardrailHooks(checks: GuardrailCheckFunctions): GuardrailHooks;
|
|
73
|
+
/**
|
|
74
|
+
* Create SDK hook functions from embedded guardrail rule data.
|
|
75
|
+
*/
|
|
76
|
+
/**
|
|
77
|
+
* Create SDK hooks scoped to a single agent from a per-agent guardrail map.
|
|
78
|
+
* Returns empty-passing hooks when the agent has no rules in the map.
|
|
79
|
+
*/
|
|
80
|
+
declare function createGuardrailHooksForAgent(agentId: string, perAgent: Map<string, GuardrailRuleData>): GuardrailHooks;
|
|
81
|
+
declare function createGuardrailHooksFromRules(rules: GuardrailRuleData): GuardrailHooks;
|
|
82
|
+
|
|
83
|
+
export { type GuardrailHooks as G, type HookResponse as H, type GuardrailRuleData as a, type GuardrailCheckResult as b, type GuardrailCheckFunctions as c, type GuardrailRule as d, type HookContext as e, createGuardrailHooks as f, createGuardrailHooksForAgent as g, createGuardrailHooksFromRules as h, getBlockingViolations as i, getWarnings as j, hasBlockingViolation as k };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import { b as SdkFunctionTool, O as ObserverEmitFn, c as TaskContext, d as TaskOutcome, e as AgentContractLike, f as TaskContractLike, P as PromptBuilderOptions, W as WorkflowResult, S as SdkAdapter, g as WorkflowRegistries, H as HandoffInput, h as StepCompleteEvent, i as StepResult, D as DelegateStep, j as
|
|
2
|
-
export {
|
|
1
|
+
import { b as SdkFunctionTool, O as ObserverEmitFn, c as TaskContext, d as TaskOutcome, e as AgentContractLike, f as TaskContractLike, P as PromptBuilderOptions, W as WorkflowResult, S as SdkAdapter, g as WorkflowRegistries, H as HandoffInput, h as StepCompleteEvent, i as StepResult, D as DelegateStep, j as MemoryStore, M as MemoryRef, R as ResolvedComponent, k as ArtifactBindingConfig, l as RunToolchainChecksOptions, m as ModelMappingConfig, n as TaskRunResult, L as LibraryToolRegistry, o as ResolvedToolchain, p as LibraryToolDefinition } from './task-runner-CWb9fVlc.js';
|
|
2
|
+
export { q as AdapterOrFactory, A as AdapterSendOptions, a as AgentExecutionRequest, r as AgentProgressEvent, B as BoundResolveOptions, s as BoundResolver, C as CacheConfig, t as CandidateAgent, u as ConvergenceEnvelope, v as ConvergenceEnvelopePayload, E as EnvelopeParams, w as EvaluateStep, G as GateStep, I as InMemoryStore, x as InnerSpanOptions, y as ModelAwareSdkAdapterFactory, z as ModelClass, F as ModelResolver, J as ModelResolverOptions, K as OBSERVABILITY_ENV_VARS, N as ObservabilityIds, Q as ReceiveSpec, U as ResolvedModel, V as RetryDecision, X as SdkAdapterFactory, Y as SplitPrompt, Z as TaskRunOptions, T as TokenUsage, _ as ToolchainCheckResult, $ as ToolchainManifest, a0 as ToolchainManifestSchema, a1 as WorkflowContractLike, a2 as WorkflowInvocation, a3 as WorkflowRunOptions, a4 as WorkflowStep, a5 as buildCandidateAgents, a6 as buildGateEvaluationPrompt, a7 as buildObservabilityEnv, a8 as buildPerAgentGuardrails, a9 as buildRetryFollowUp, aa as buildSdkFunctionTools, ab as buildSplitTaskPrompt, ac as buildTaskPrompt, ad as collectAnalyzerToolIds, ae as createExecutionEnvelope, af as createLibraryToolRegistry, ag as createModelResolver, ah as createRegistryFromSdkTools, ai as deriveToolchainsForAgents, aj as emitIterationClose, ak as emitIterationMetric, al as emitIterationOpen, am as emitLlmTurnClose, an as emitLlmTurnOpen, ao as emitSessionClose, ap as emitSessionOpen, aq as emitSubagentClose, ar as emitSubagentOpen, as as emitToolExecClose, at as emitToolExecOpen, au as emitToolchainClose, av as emitToolchainOpen, aw as extractStructuredResult, ax as getEffectiveGuardrailIds, ay as getGuardrailRulesForAgent, az as guardrailContextToRuleData, aA as isNavigationIndex, aB as parseGateEvaluationResponse, aC as renderAgentSystemPrompt, aD as renderAnalyzerExplorationMandatePrompt, aE as renderNavigationIndexPrompt, aF as runTask, aG as runToolchainChecks, aH as runWorkflow, aI as serializeObserverEmit, aJ as shouldInjectAnalyzerExplorationMandate, aK as zodSchemaToPromptDescription, aL as zodSchemaToYamlExample } from './task-runner-CWb9fVlc.js';
|
|
3
|
+
import { a as GuardrailRuleData, G as GuardrailHooks, H as HookResponse, b as GuardrailCheckResult } from './guardrail-hooks-slK-z0Dz.js';
|
|
4
|
+
export { c as GuardrailCheckFunctions, d as GuardrailRule, e as HookContext, f as createGuardrailHooks, g as createGuardrailHooksForAgent, h as createGuardrailHooksFromRules, i as getBlockingViolations, j as getWarnings, k as hasBlockingViolation } from './guardrail-hooks-slK-z0Dz.js';
|
|
3
5
|
import { z } from 'zod';
|
|
4
6
|
import { OperationIR, ComponentIR } from '@aaac/contracts';
|
|
5
7
|
import { OtelEmitter } from '@aaac/observability';
|
|
6
8
|
export { ExecutionEnvelope } from '@aaac/observability';
|
|
7
9
|
import { ResolvedConfig } from './generator/index.js';
|
|
10
|
+
export { a as NavigationContext, N as NavigationContextOptions, b as buildNavigationContext } from './navigation-context-BE1KHJ_8.js';
|
|
8
11
|
import './context-DKkamYX_.js';
|
|
9
12
|
|
|
10
13
|
/**
|
|
@@ -115,6 +118,12 @@ interface ProcessEditOptions {
|
|
|
115
118
|
/** Optional observer — no-op when undefined. */
|
|
116
119
|
observer?: ObserverEmitFn;
|
|
117
120
|
}
|
|
121
|
+
/**
|
|
122
|
+
* True when a tool name denotes a file-mutating edit, so a process.edit event
|
|
123
|
+
* should be emitted for it. Used by the task runner to instrument the Process
|
|
124
|
+
* axis from live tool-use progress events (#167).
|
|
125
|
+
*/
|
|
126
|
+
declare function isFileEditTool(toolName: string | undefined): boolean;
|
|
118
127
|
/**
|
|
119
128
|
* Emit process.workflow open span.
|
|
120
129
|
*/
|
|
@@ -690,27 +699,6 @@ interface CreateComponentScopeOptions {
|
|
|
690
699
|
}
|
|
691
700
|
declare function createComponentScope(componentIR: ComponentIR, binding: RuntimeBinding, options?: CreateComponentScopeOptions): ComponentScope;
|
|
692
701
|
|
|
693
|
-
interface NavigationContextOptions {
|
|
694
|
-
configPath?: string;
|
|
695
|
-
embeddedDsl?: Record<string, unknown>;
|
|
696
|
-
projectDslPath?: string;
|
|
697
|
-
artifactBinding?: {
|
|
698
|
-
source: string;
|
|
699
|
-
mappings?: Record<string, string>;
|
|
700
|
-
};
|
|
701
|
-
paths?: Record<string, string>;
|
|
702
|
-
}
|
|
703
|
-
interface NavigationContext {
|
|
704
|
-
dsl: Record<string, unknown>;
|
|
705
|
-
navigationIndex: Record<string, unknown>;
|
|
706
|
-
diagnostics: Array<{
|
|
707
|
-
path: string;
|
|
708
|
-
message: string;
|
|
709
|
-
severity: string;
|
|
710
|
-
}>;
|
|
711
|
-
}
|
|
712
|
-
declare function buildNavigationContext(options: NavigationContextOptions): Promise<NavigationContext>;
|
|
713
|
-
|
|
714
702
|
interface ArtifactResolveOptions {
|
|
715
703
|
dsl: Record<string, unknown>;
|
|
716
704
|
artifactBinding?: {
|
|
@@ -823,6 +811,53 @@ interface GuardStatusResult {
|
|
|
823
811
|
*/
|
|
824
812
|
declare function guardStatus(opts?: GuardStatusOptions): Promise<GuardStatusResult>;
|
|
825
813
|
|
|
814
|
+
declare const ClaudeConfigSchema: z.ZodObject<{
|
|
815
|
+
output_dir: z.ZodDefault<z.ZodString>;
|
|
816
|
+
config_path: z.ZodDefault<z.ZodString>;
|
|
817
|
+
guard_command: z.ZodOptional<z.ZodString>;
|
|
818
|
+
component_id: z.ZodOptional<z.ZodString>;
|
|
819
|
+
}, z.core.$strip>;
|
|
820
|
+
type ClaudeConfig = z.infer<typeof ClaudeConfigSchema>;
|
|
821
|
+
/** Parse and default-fill an opaque config payload from component.yaml. */
|
|
822
|
+
declare function parseClaudeConfig(raw: unknown): ClaudeConfig;
|
|
823
|
+
|
|
824
|
+
type FileAction = "created" | "updated" | "unchanged";
|
|
825
|
+
interface SyncOptions {
|
|
826
|
+
projectRoot: string;
|
|
827
|
+
/** Opaque config payload from component.yaml (validated here). */
|
|
828
|
+
config: unknown;
|
|
829
|
+
/** Resolved agent DSL (plain object; the value the runtime embeds). */
|
|
830
|
+
dsl: Record<string, unknown>;
|
|
831
|
+
/** When true, compute changes without writing. */
|
|
832
|
+
dryRun?: boolean;
|
|
833
|
+
}
|
|
834
|
+
interface SyncResult {
|
|
835
|
+
files: Array<{
|
|
836
|
+
path: string;
|
|
837
|
+
action: FileAction;
|
|
838
|
+
}>;
|
|
839
|
+
}
|
|
840
|
+
interface CheckResult {
|
|
841
|
+
inSync: boolean;
|
|
842
|
+
drift: Array<{
|
|
843
|
+
path: string;
|
|
844
|
+
reason: "missing" | "changed";
|
|
845
|
+
}>;
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Materialize `.claude/*` and the CLAUDE.md integration block from the embedded DSL.
|
|
849
|
+
*
|
|
850
|
+
* Idempotent: re-running with no changes writes nothing. CLAUDE.md uses a
|
|
851
|
+
* marker-delimited block merge so user content outside the block is preserved.
|
|
852
|
+
*/
|
|
853
|
+
declare function syncClaude(opts: SyncOptions): Promise<SyncResult>;
|
|
854
|
+
/**
|
|
855
|
+
* Read-only drift gate. Reports files whose on-disk content differs from a
|
|
856
|
+
* fresh render. For CLAUDE.md, drift means the aaac:claude-native block is
|
|
857
|
+
* missing or stale (content outside the block is ignored).
|
|
858
|
+
*/
|
|
859
|
+
declare function checkClaude(opts: SyncOptions): Promise<CheckResult>;
|
|
860
|
+
|
|
826
861
|
/**
|
|
827
862
|
* Prompt Executor — natural language routing via LLM tool selection.
|
|
828
863
|
*
|
|
@@ -873,4 +908,4 @@ declare function executePrompt(message: string, ir: ComponentIR, binding: Runtim
|
|
|
873
908
|
/** Package version string. */
|
|
874
909
|
declare const version: string;
|
|
875
910
|
|
|
876
|
-
export { type AaacInvocationContext, type AaacObserver, type AaacPolicy, type AaacRuntime, AgentContractLike, AgentLogWriter, type AgentLogWriterOptions, type AgentPlugin, type AnalyzeImpactInput, type AnalyzerBridge, type AnalyzerBridgeOptions, ArtifactBindingConfig, type ArtifactResolveOptions, type ArtifactResolveResult, type BuildCallGraphInput, type ComponentScope, type CreateAdapterOptions, type CreateComponentScopeOptions, type CreateProjectRuntimeOptions, DelegateStep, type DslContext, DslValidationError, type EvaluateGuardrailOptions, type EvaluateGuardrailResult, type ExecuteOptions, type ExecuteTaskOptions, type ExecuteWorkflowOptions, FileMemoryStore, type GenerateContextPackInput, type GuardStatusOptions, type GuardStatusResult, GuardrailCheckResult, GuardrailHooks, type GuardrailListEntry, type GuardrailResult, GuardrailRuleData, HandoffInput, HookResponse, LibraryToolDefinition, LibraryToolRegistry, type ListGuardrailsOptions, type ListGuardrailsResult, type LoadDslOptions, MemoryRef, MemoryStore, type MemoryStoreEntry, ModelMappingConfig,
|
|
911
|
+
export { type AaacInvocationContext, type AaacObserver, type AaacPolicy, type AaacRuntime, AgentContractLike, AgentLogWriter, type AgentLogWriterOptions, type AgentPlugin, type AnalyzeImpactInput, type AnalyzerBridge, type AnalyzerBridgeOptions, ArtifactBindingConfig, type ArtifactResolveOptions, type ArtifactResolveResult, type BuildCallGraphInput, type CheckResult as ClaudeCheckResult, type ClaudeConfig, type FileAction as ClaudeFileAction, type SyncOptions as ClaudeSyncOptions, type SyncResult as ClaudeSyncResult, type ComponentScope, type CreateAdapterOptions, type CreateComponentScopeOptions, type CreateProjectRuntimeOptions, DelegateStep, type DslContext, DslValidationError, type EvaluateGuardrailOptions, type EvaluateGuardrailResult, type ExecuteOptions, type ExecuteTaskOptions, type ExecuteWorkflowOptions, FileMemoryStore, type GenerateContextPackInput, type GuardStatusOptions, type GuardStatusResult, GuardrailCheckResult, GuardrailHooks, type GuardrailListEntry, type GuardrailResult, GuardrailRuleData, HandoffInput, HookResponse, LibraryToolDefinition, LibraryToolRegistry, type ListGuardrailsOptions, type ListGuardrailsResult, type LoadDslOptions, MemoryRef, MemoryStore, type MemoryStoreEntry, ModelMappingConfig, ObserverEmitFn, type OperationHandler, type OperationMemoryRefConfig, type OperationToolDef, PROJECT_CONFIG_FILENAME, type PermissionMode, type PluginLoadResult, PluginRegistry, type ProcessEditOptions, type ProcessTaskOptions, type ProcessWorkflowOptions, type ProgressSink, type ProgressSinkOptions, type ProjectRuntime, type PromptBuilderArgs, PromptBuilderOptions, type PromptExecuteOptions, type PromptResult, type RequiredEntities, type ResolvedAdapterSelection, ResolvedComponent, ResolvedToolchain, type RunLogEvent, RunToolchainChecksOptions, type Runtime, type RuntimeBinding, type RuntimeConfig, SdkAdapter, SdkFunctionTool, StepCompleteEvent, StepResult, TaskContext, TaskContractLike, type TaskHookContext, TaskOutcome, TaskRunResult, WorkflowBuilder, type WorkflowHookContext, WorkflowRegistries, WorkflowResult, buildGuardrailRulesFromDsl, buildRegistriesFromDsl, checkClaude, createAdapter, createAnalyzerBridge, createComponentScope, createProgressSink, createProjectRuntime, createRuntime, createRuntimeBinding, emitProcessEdit, emitProcessTaskClose, emitProcessTaskOpen, emitProcessWorkflowClose, emitProcessWorkflowOpen, evaluateGuardrail, executePrompt, executeTask, executeWorkflow, findProjectConfig, guardStatus, isContextPack, isFileEditTool, jsonSchemaToZod, listGuardrails, loadDslContext, loadPlugins, loadPluginsFromDirectory, loadPluginsFromPaths, operationsToTools, parseClaudeConfig, parseRouterResponse, pluginRegistry, renderContextPackPrompt, resolveArtifacts, syncClaude, version };
|