@aaac/runtime 0.1.55 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -11
- package/dist/adapters/adk-sdk.d.ts +3 -3
- package/dist/adapters/adk-sdk.js +6 -8
- package/dist/adapters/adk-sdk.js.map +1 -1
- package/dist/adapters/claude-agent-sdk.d.ts +3 -3
- package/dist/adapters/claude-agent-sdk.js +22 -23
- package/dist/adapters/claude-agent-sdk.js.map +1 -1
- package/dist/adapters/mock.d.ts +2 -3
- package/dist/adapters/openai-agents-sdk.d.ts +3 -3
- package/dist/adapters/openai-agents-sdk.js +6 -5
- package/dist/adapters/openai-agents-sdk.js.map +1 -1
- package/dist/chunk-2INQL5TG.js +298 -0
- package/dist/chunk-2INQL5TG.js.map +1 -0
- package/dist/chunk-3CLWG72V.js +47 -0
- package/dist/chunk-3CLWG72V.js.map +1 -0
- package/dist/chunk-3DDB34BU.js +237 -0
- package/dist/chunk-3DDB34BU.js.map +1 -0
- package/dist/chunk-ABXDSTUV.js +685 -0
- package/dist/chunk-ABXDSTUV.js.map +1 -0
- package/dist/{chunk-3H3PVPPF.js → chunk-F5R46S7I.js} +151 -204
- package/dist/chunk-F5R46S7I.js.map +1 -0
- package/dist/chunk-FKAI54OM.js +234 -0
- package/dist/chunk-FKAI54OM.js.map +1 -0
- package/dist/chunk-KTVMMG33.js +1111 -0
- package/dist/chunk-KTVMMG33.js.map +1 -0
- package/dist/chunk-MSVIEEGR.js +269 -0
- package/dist/chunk-MSVIEEGR.js.map +1 -0
- package/dist/chunk-VJXGCWSZ.js +36 -0
- package/dist/chunk-VJXGCWSZ.js.map +1 -0
- package/dist/claude-bundles/full.js +311 -309
- package/dist/claude-bundles/lean.js +6 -6
- package/dist/claude-bundles/prompt.js +17 -0
- package/dist/generator/index.d.ts +2 -2
- package/dist/generator/index.js +8 -7
- package/dist/guardrail-hooks-CB23nhZV.d.ts +202 -0
- package/dist/hook-protocol-CFnNudiV.d.ts +96 -0
- package/dist/hooks-lite-CoWWnCRH.d.ts +428 -0
- package/dist/index-BlSepCSZ.d.ts +296 -0
- package/dist/index.d.ts +785 -105
- package/dist/index.js +2189 -634
- package/dist/index.js.map +1 -1
- package/dist/lib/claude-native/hooks-lite.d.ts +3 -26
- package/dist/lib/claude-native/hooks-lite.js +18 -36
- package/dist/lib/claude-native/hooks-prompt.d.ts +5 -0
- package/dist/lib/claude-native/hooks-prompt.js +33 -0
- package/dist/lib/claude-native/hooks-prompt.js.map +1 -0
- package/dist/lib/claude-native/index.d.ts +56 -214
- package/dist/lib/claude-native/index.js +79 -280
- package/dist/lib/claude-native/index.js.map +1 -1
- package/dist/{navigation-context-D_E1NIUf.d.ts → navigation-context-B-RpUg3_.d.ts} +1 -1
- package/dist/navigation-index-prompt-CbrS5laO.d.ts +43 -0
- package/dist/{task-runner-DfIEorkU.d.ts → task-runner-GWoI7_71.d.ts} +100 -493
- package/dist/workspace-user-prompt-submit-D11Iu0zO.d.ts +269 -0
- package/package.json +15 -6
- package/dist/chunk-3H3PVPPF.js.map +0 -1
- package/dist/chunk-DBM5XN67.js +0 -354
- package/dist/chunk-DBM5XN67.js.map +0 -1
- package/dist/chunk-KXGUWBGK.js +0 -370
- package/dist/chunk-KXGUWBGK.js.map +0 -1
- package/dist/chunk-LDCQZPDG.js +0 -11
- package/dist/chunk-LDCQZPDG.js.map +0 -1
- package/dist/chunk-N4KNGDYY.js +0 -1963
- package/dist/chunk-N4KNGDYY.js.map +0 -1
- package/dist/chunk-NMX4C6LC.js +0 -332
- package/dist/chunk-NMX4C6LC.js.map +0 -1
- package/dist/chunk-QVH5KKBR.js +0 -374
- package/dist/chunk-QVH5KKBR.js.map +0 -1
- package/dist/context-DKkamYX_.d.ts +0 -31
- package/dist/guardrail-hooks-slK-z0Dz.d.ts +0 -83
- package/dist/index-LqEvaRk-.d.ts +0 -299
- package/dist/workspace-pre-tool-use-C6nidc0q.d.ts +0 -333
package/dist/chunk-QVH5KKBR.js
DELETED
|
@@ -1,374 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
guardrailCacheKey
|
|
3
|
-
} from "./chunk-LDCQZPDG.js";
|
|
4
|
-
import {
|
|
5
|
-
createGuardrailHooksFromRules,
|
|
6
|
-
matchGlob
|
|
7
|
-
} from "./chunk-NMX4C6LC.js";
|
|
8
|
-
|
|
9
|
-
// src/lib/claude-native/hook-protocol.ts
|
|
10
|
-
function parseHookInput(raw) {
|
|
11
|
-
const parsed = JSON.parse(raw);
|
|
12
|
-
if (typeof parsed.hook_event_name === "string" && parsed.hookEventName === void 0) {
|
|
13
|
-
parsed.hookEventName = parsed.hook_event_name;
|
|
14
|
-
}
|
|
15
|
-
return parsed;
|
|
16
|
-
}
|
|
17
|
-
async function readHookInput() {
|
|
18
|
-
const chunks = [];
|
|
19
|
-
for await (const chunk of process.stdin) {
|
|
20
|
-
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
21
|
-
}
|
|
22
|
-
const raw = Buffer.concat(chunks).toString("utf-8").trim();
|
|
23
|
-
if (!raw) {
|
|
24
|
-
throw new Error("Empty stdin \u2014 no hook input received");
|
|
25
|
-
}
|
|
26
|
-
return parseHookInput(raw);
|
|
27
|
-
}
|
|
28
|
-
function emitHookOutput(output) {
|
|
29
|
-
process.stdout.write(JSON.stringify(output) + "\n");
|
|
30
|
-
}
|
|
31
|
-
function buildContextResponse(eventName, additionalContext) {
|
|
32
|
-
return {
|
|
33
|
-
hookSpecificOutput: {
|
|
34
|
-
hookEventName: eventName,
|
|
35
|
-
additionalContext
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
function buildDenyResponse(reason) {
|
|
40
|
-
return {
|
|
41
|
-
hookSpecificOutput: {
|
|
42
|
-
hookEventName: "PreToolUse",
|
|
43
|
-
permissionDecision: "deny",
|
|
44
|
-
permissionDecisionReason: reason
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
function buildAllowResponse() {
|
|
49
|
-
return {};
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// src/lib/claude-native/cache-store.ts
|
|
53
|
-
import { readFile, writeFile, rename, stat, mkdir } from "fs/promises";
|
|
54
|
-
import { join } from "path";
|
|
55
|
-
import { randomBytes } from "crypto";
|
|
56
|
-
function createCacheStore(options) {
|
|
57
|
-
const { cacheDir } = options;
|
|
58
|
-
function cacheFilePath(key) {
|
|
59
|
-
return join(cacheDir, `${key}.json`);
|
|
60
|
-
}
|
|
61
|
-
async function ensureDir() {
|
|
62
|
-
await mkdir(cacheDir, { recursive: true });
|
|
63
|
-
}
|
|
64
|
-
const store = {
|
|
65
|
-
async read(key) {
|
|
66
|
-
try {
|
|
67
|
-
const raw = await readFile(cacheFilePath(key), "utf-8");
|
|
68
|
-
return JSON.parse(raw);
|
|
69
|
-
} catch {
|
|
70
|
-
return null;
|
|
71
|
-
}
|
|
72
|
-
},
|
|
73
|
-
async write(key, data, sourceHash) {
|
|
74
|
-
await ensureDir();
|
|
75
|
-
const entry = {
|
|
76
|
-
data,
|
|
77
|
-
writtenAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
78
|
-
sourceHash
|
|
79
|
-
};
|
|
80
|
-
const content = JSON.stringify(entry, null, 2);
|
|
81
|
-
const target = cacheFilePath(key);
|
|
82
|
-
const tmpPath = `${target}.${randomBytes(4).toString("hex")}.tmp`;
|
|
83
|
-
await writeFile(tmpPath, content, "utf-8");
|
|
84
|
-
try {
|
|
85
|
-
await rename(tmpPath, target);
|
|
86
|
-
} catch {
|
|
87
|
-
await writeFile(target, content, "utf-8");
|
|
88
|
-
}
|
|
89
|
-
},
|
|
90
|
-
async readIfFresh(key, currentHash) {
|
|
91
|
-
const entry = await store.read(key);
|
|
92
|
-
if (!entry) return null;
|
|
93
|
-
if (entry.sourceHash !== currentHash) return null;
|
|
94
|
-
return entry.data;
|
|
95
|
-
},
|
|
96
|
-
async getFileMtime(filePath) {
|
|
97
|
-
try {
|
|
98
|
-
const s = await stat(filePath);
|
|
99
|
-
return s.mtimeMs;
|
|
100
|
-
} catch {
|
|
101
|
-
return null;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
};
|
|
105
|
-
return store;
|
|
106
|
-
}
|
|
107
|
-
function computeSourceHash(inputs) {
|
|
108
|
-
return inputs.map(String).join(":");
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// src/lib/claude-native/latency.ts
|
|
112
|
-
var TimeoutError = class extends Error {
|
|
113
|
-
constructor(ms) {
|
|
114
|
-
super(`Operation timed out after ${ms}ms`);
|
|
115
|
-
this.name = "TimeoutError";
|
|
116
|
-
}
|
|
117
|
-
};
|
|
118
|
-
async function withTimeout(promise, timeoutMs) {
|
|
119
|
-
if (timeoutMs <= 0) return promise;
|
|
120
|
-
let timer;
|
|
121
|
-
const timeout = new Promise((_resolve, reject) => {
|
|
122
|
-
timer = setTimeout(() => reject(new TimeoutError(timeoutMs)), timeoutMs);
|
|
123
|
-
});
|
|
124
|
-
try {
|
|
125
|
-
return await Promise.race([promise, timeout]);
|
|
126
|
-
} finally {
|
|
127
|
-
clearTimeout(timer);
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
function createExclusiveLock() {
|
|
131
|
-
let pending = null;
|
|
132
|
-
return {
|
|
133
|
-
async run(fn) {
|
|
134
|
-
if (pending) return pending;
|
|
135
|
-
pending = fn().finally(() => {
|
|
136
|
-
pending = null;
|
|
137
|
-
});
|
|
138
|
-
return pending;
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
}
|
|
142
|
-
async function withDegrade(operation, fallback, timeoutMs) {
|
|
143
|
-
try {
|
|
144
|
-
const value = await withTimeout(operation(), timeoutMs);
|
|
145
|
-
return { value, degraded: false };
|
|
146
|
-
} catch (err) {
|
|
147
|
-
const reason = err instanceof TimeoutError ? err.message : err instanceof Error ? err.message : String(err);
|
|
148
|
-
return { value: fallback, degraded: true, reason };
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// src/lib/claude-native/artifact-resolver.ts
|
|
153
|
-
function resolvePathToArtifacts(filePath, navigationIndex) {
|
|
154
|
-
const artifacts = navigationIndex.artifacts ?? {};
|
|
155
|
-
const matches = [];
|
|
156
|
-
for (const [id, artifact] of Object.entries(artifacts)) {
|
|
157
|
-
const patterns = artifact?.files?.path_patterns;
|
|
158
|
-
if (!Array.isArray(patterns)) continue;
|
|
159
|
-
for (const pattern of patterns) {
|
|
160
|
-
if (typeof pattern !== "string") continue;
|
|
161
|
-
if (matchGlob(pattern, filePath)) {
|
|
162
|
-
matches.push({ artifactId: id, artifact, matchedPattern: pattern });
|
|
163
|
-
break;
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
return matches;
|
|
168
|
-
}
|
|
169
|
-
function isProtectedArtifact(match) {
|
|
170
|
-
const props = match.artifact.properties ?? {};
|
|
171
|
-
if (props.authority === "generated") {
|
|
172
|
-
const regen = match.artifact.routes?.regenerate;
|
|
173
|
-
const hint = regen ? ` Run '${regen}' to regenerate.` : " Edit the source artifact and regenerate instead.";
|
|
174
|
-
return {
|
|
175
|
-
protected: true,
|
|
176
|
-
reason: `File belongs to generated artifact '${match.artifactId}'. Direct editing is not allowed.${hint}`
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
if (props.manual_edit === "forbidden") {
|
|
180
|
-
return {
|
|
181
|
-
protected: true,
|
|
182
|
-
reason: `File belongs to artifact '${match.artifactId}' which has manual_edit: forbidden. This artifact must not be edited directly.`
|
|
183
|
-
};
|
|
184
|
-
}
|
|
185
|
-
return { protected: false, reason: "" };
|
|
186
|
-
}
|
|
187
|
-
function listArtifacts(navigationIndex) {
|
|
188
|
-
const artifacts = navigationIndex.artifacts ?? {};
|
|
189
|
-
return Object.entries(artifacts).map(([id, artifact]) => ({
|
|
190
|
-
id,
|
|
191
|
-
artifact
|
|
192
|
-
}));
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// src/lib/claude-native/pre-tool-use.ts
|
|
196
|
-
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "Write", "MultiEdit", "edit", "write"]);
|
|
197
|
-
var BASH_TOOLS = /* @__PURE__ */ new Set(["Bash", "bash", "Terminal", "terminal"]);
|
|
198
|
-
function createPreToolUseHandler(config) {
|
|
199
|
-
const guardrailHooks = config.guardrailRules ? createGuardrailHooksFromRules(config.guardrailRules) : null;
|
|
200
|
-
return async function handlePreToolUse(input) {
|
|
201
|
-
const toolName = input.tool_name ?? "";
|
|
202
|
-
const toolInput = input.tool_input ?? {};
|
|
203
|
-
if (EDIT_TOOLS.has(toolName)) {
|
|
204
|
-
const filePath = toolInput.file_path ?? toolInput.path ?? "";
|
|
205
|
-
if (filePath) {
|
|
206
|
-
const matches = resolvePathToArtifacts(
|
|
207
|
-
filePath,
|
|
208
|
-
config.navigationIndex
|
|
209
|
-
);
|
|
210
|
-
for (const match of matches) {
|
|
211
|
-
const check = isProtectedArtifact(match);
|
|
212
|
-
if (check.protected) {
|
|
213
|
-
return buildDenyResponse(check.reason);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
if (BASH_TOOLS.has(toolName) && guardrailHooks) {
|
|
219
|
-
const command = toolInput.command ?? "";
|
|
220
|
-
if (command) {
|
|
221
|
-
const hookResult = guardrailHooks.beforeShellExecution({ command });
|
|
222
|
-
if (hookResult.permission === "deny") {
|
|
223
|
-
return buildDenyResponse(
|
|
224
|
-
hookResult.user_message ?? "Command blocked by guardrail"
|
|
225
|
-
);
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
return buildAllowResponse();
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// src/lib/claude-native/workspace-router.ts
|
|
234
|
-
import { resolve } from "path";
|
|
235
|
-
function routePathToMember(filePath, members, workspaceRoot) {
|
|
236
|
-
if (!filePath) return null;
|
|
237
|
-
const absPath = filePath.startsWith("/") ? filePath : resolve(workspaceRoot, filePath);
|
|
238
|
-
let best = null;
|
|
239
|
-
let bestPrefixLen = 0;
|
|
240
|
-
for (const member of members) {
|
|
241
|
-
const memberRoot = member.root;
|
|
242
|
-
const prefix = memberRoot.endsWith("/") ? memberRoot : memberRoot + "/";
|
|
243
|
-
if (absPath.startsWith(prefix) && prefix.length > bestPrefixLen) {
|
|
244
|
-
best = member;
|
|
245
|
-
bestPrefixLen = prefix.length;
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
return best;
|
|
249
|
-
}
|
|
250
|
-
function stripMemberPrefix(filePath, memberRoot, workspaceRoot) {
|
|
251
|
-
const absPath = filePath.startsWith("/") ? filePath : resolve(workspaceRoot, filePath);
|
|
252
|
-
const prefix = memberRoot.endsWith("/") ? memberRoot : memberRoot + "/";
|
|
253
|
-
if (absPath.startsWith(prefix)) {
|
|
254
|
-
return absPath.slice(prefix.length);
|
|
255
|
-
}
|
|
256
|
-
return filePath;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
// src/lib/claude-native/workspace-pre-tool-use.ts
|
|
260
|
-
var EDIT_TOOLS2 = /* @__PURE__ */ new Set(["Edit", "Write", "MultiEdit", "edit", "write"]);
|
|
261
|
-
var BASH_TOOLS2 = /* @__PURE__ */ new Set(["Bash", "bash", "Terminal", "terminal"]);
|
|
262
|
-
function extractCommandPathTokens(command) {
|
|
263
|
-
const tokens = [];
|
|
264
|
-
for (const raw of command.split(/\s+/)) {
|
|
265
|
-
const t = raw.replace(/^['"]+|['"]+$/g, "");
|
|
266
|
-
if (t && (t.includes("/") || t.includes("\\"))) {
|
|
267
|
-
tokens.push(t);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
return tokens;
|
|
271
|
-
}
|
|
272
|
-
function createWorkspacePreToolUseHandler(config) {
|
|
273
|
-
const store = createCacheStore({ cacheDir: config.cacheDir });
|
|
274
|
-
const guardrailHooksByMember = /* @__PURE__ */ new Map();
|
|
275
|
-
async function loadGuardrailHooks(member) {
|
|
276
|
-
const key = member.name;
|
|
277
|
-
if (guardrailHooksByMember.has(key)) {
|
|
278
|
-
return guardrailHooksByMember.get(key) ?? null;
|
|
279
|
-
}
|
|
280
|
-
const cacheKey = member.guardrailCacheKey ?? guardrailCacheKey(member.cacheKey);
|
|
281
|
-
const entry = await store.read(cacheKey);
|
|
282
|
-
const rules = entry?.data;
|
|
283
|
-
const hooks = rules && (rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0) ? createGuardrailHooksFromRules(rules) : null;
|
|
284
|
-
guardrailHooksByMember.set(key, hooks);
|
|
285
|
-
return hooks;
|
|
286
|
-
}
|
|
287
|
-
function membersForCommand(command) {
|
|
288
|
-
for (const token of extractCommandPathTokens(command)) {
|
|
289
|
-
const owner = routePathToMember(
|
|
290
|
-
token,
|
|
291
|
-
config.members,
|
|
292
|
-
config.workspaceRoot
|
|
293
|
-
);
|
|
294
|
-
if (owner) return [owner];
|
|
295
|
-
}
|
|
296
|
-
return config.members;
|
|
297
|
-
}
|
|
298
|
-
return async function handleWorkspacePreToolUse(input) {
|
|
299
|
-
const toolName = input.tool_name ?? "";
|
|
300
|
-
const toolInput = input.tool_input ?? {};
|
|
301
|
-
if (BASH_TOOLS2.has(toolName)) {
|
|
302
|
-
const command = toolInput.command ?? "";
|
|
303
|
-
if (!command) {
|
|
304
|
-
return buildAllowResponse();
|
|
305
|
-
}
|
|
306
|
-
for (const member2 of membersForCommand(command)) {
|
|
307
|
-
const hooks = await loadGuardrailHooks(member2);
|
|
308
|
-
if (!hooks) continue;
|
|
309
|
-
const result = hooks.beforeShellExecution({ command });
|
|
310
|
-
if (result.permission === "deny") {
|
|
311
|
-
return buildDenyResponse(
|
|
312
|
-
result.user_message ?? "Command blocked by guardrail"
|
|
313
|
-
);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
return buildAllowResponse();
|
|
317
|
-
}
|
|
318
|
-
if (!EDIT_TOOLS2.has(toolName)) {
|
|
319
|
-
return buildAllowResponse();
|
|
320
|
-
}
|
|
321
|
-
const filePath = toolInput.file_path ?? toolInput.path ?? "";
|
|
322
|
-
if (!filePath) {
|
|
323
|
-
return buildAllowResponse();
|
|
324
|
-
}
|
|
325
|
-
const member = routePathToMember(
|
|
326
|
-
filePath,
|
|
327
|
-
config.members,
|
|
328
|
-
config.workspaceRoot
|
|
329
|
-
);
|
|
330
|
-
if (!member) {
|
|
331
|
-
return buildAllowResponse();
|
|
332
|
-
}
|
|
333
|
-
const entry = await store.read(member.cacheKey);
|
|
334
|
-
if (!entry) {
|
|
335
|
-
return buildAllowResponse();
|
|
336
|
-
}
|
|
337
|
-
const repoRelPath = stripMemberPrefix(
|
|
338
|
-
filePath,
|
|
339
|
-
member.root,
|
|
340
|
-
config.workspaceRoot
|
|
341
|
-
);
|
|
342
|
-
const matches = resolvePathToArtifacts(repoRelPath, entry.data);
|
|
343
|
-
for (const match of matches) {
|
|
344
|
-
const check = isProtectedArtifact(match);
|
|
345
|
-
if (check.protected) {
|
|
346
|
-
return buildDenyResponse(check.reason);
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
return buildAllowResponse();
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
export {
|
|
354
|
-
parseHookInput,
|
|
355
|
-
readHookInput,
|
|
356
|
-
emitHookOutput,
|
|
357
|
-
buildContextResponse,
|
|
358
|
-
buildDenyResponse,
|
|
359
|
-
buildAllowResponse,
|
|
360
|
-
createCacheStore,
|
|
361
|
-
computeSourceHash,
|
|
362
|
-
TimeoutError,
|
|
363
|
-
withTimeout,
|
|
364
|
-
createExclusiveLock,
|
|
365
|
-
withDegrade,
|
|
366
|
-
resolvePathToArtifacts,
|
|
367
|
-
isProtectedArtifact,
|
|
368
|
-
listArtifacts,
|
|
369
|
-
createPreToolUseHandler,
|
|
370
|
-
routePathToMember,
|
|
371
|
-
stripMemberPrefix,
|
|
372
|
-
createWorkspacePreToolUseHandler
|
|
373
|
-
};
|
|
374
|
-
//# sourceMappingURL=chunk-QVH5KKBR.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/claude-native/hook-protocol.ts","../src/lib/claude-native/cache-store.ts","../src/lib/claude-native/latency.ts","../src/lib/claude-native/artifact-resolver.ts","../src/lib/claude-native/pre-tool-use.ts","../src/lib/claude-native/workspace-router.ts","../src/lib/claude-native/workspace-pre-tool-use.ts"],"sourcesContent":["/**\n * Claude Code Hook Protocol — parse stdin JSON input and emit hook response JSON.\n *\n * Implements the protocol defined at https://code.claude.com/docs/en/hooks\n * for SessionStart, UserPromptSubmit, and PreToolUse hook events.\n */\n\n// ---------------------------------------------------------------------------\n// Hook Event Types\n// ---------------------------------------------------------------------------\n\nexport type HookEventName = \"SessionStart\" | \"UserPromptSubmit\" | \"PreToolUse\";\n\nexport interface SessionStartInput {\n hookEventName: \"SessionStart\";\n session_id?: string;\n type?: \"new\" | \"resume\" | \"clear\" | \"compact\";\n}\n\nexport interface UserPromptSubmitInput {\n hookEventName: \"UserPromptSubmit\";\n session_id?: string;\n prompt?: string;\n}\n\nexport interface PreToolUseInput {\n hookEventName: \"PreToolUse\";\n session_id?: string;\n tool_name?: string;\n tool_input?: {\n file_path?: string;\n path?: string;\n command?: string;\n content?: string;\n [key: string]: unknown;\n };\n}\n\nexport type HookInput = SessionStartInput | UserPromptSubmitInput | PreToolUseInput;\n\n// ---------------------------------------------------------------------------\n// Hook Response Types\n// ---------------------------------------------------------------------------\n\nexport type PermissionDecision = \"allow\" | \"deny\" | \"ask\";\n\nexport interface HookOutput {\n /** Hook-specific output envelope. */\n hookSpecificOutput?: {\n hookEventName: HookEventName;\n /** Additional context injected into the session. */\n additionalContext?: string;\n /** Permission decision for PreToolUse hooks. */\n permissionDecision?: PermissionDecision;\n /** Reason for the permission decision. */\n permissionDecisionReason?: string;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Parse / Emit\n// ---------------------------------------------------------------------------\n\n/**\n * Parse hook input from a raw JSON string (typically from stdin).\n * Throws on invalid JSON but not on missing fields — callers handle defaults.\n */\nexport function parseHookInput(raw: string): HookInput {\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n // Claude Code's hook INPUT wire protocol sends the event name as snake_case\n // `hook_event_name` (sibling fields session_id / tool_name / tool_input are\n // likewise snake_case). The internal HookInput union — and every hook bin's\n // event guard — reads `hookEventName`. Normalize once here, at the single\n // stdin parse boundary, so the guards match real payloads (#252). Output\n // stays camelCase `hookSpecificOutput.hookEventName`, which the wire expects.\n if (typeof parsed.hook_event_name === \"string\" && parsed.hookEventName === undefined) {\n parsed.hookEventName = parsed.hook_event_name;\n }\n // Boundary assertion: stdin JSON is inherently untyped, and HookInput models\n // the event name as required, so the normalized record is asserted here.\n return parsed as unknown as HookInput;\n}\n\n/**\n * Read all of stdin and parse as hook input JSON.\n */\nexport async function readHookInput(): Promise<HookInput> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string));\n }\n const raw = Buffer.concat(chunks).toString(\"utf-8\").trim();\n if (!raw) {\n throw new Error(\"Empty stdin — no hook input received\");\n }\n return parseHookInput(raw);\n}\n\n/**\n * Emit a hook response as JSON to stdout.\n */\nexport function emitHookOutput(output: HookOutput): void {\n process.stdout.write(JSON.stringify(output) + \"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Response Builders\n// ---------------------------------------------------------------------------\n\n/**\n * Build a response that injects additional context into the session.\n */\nexport function buildContextResponse(\n eventName: HookEventName,\n additionalContext: string,\n): HookOutput {\n return {\n hookSpecificOutput: {\n hookEventName: eventName,\n additionalContext,\n },\n };\n}\n\n/**\n * Build a deny response for PreToolUse hooks.\n */\nexport function buildDenyResponse(reason: string): HookOutput {\n return {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: reason,\n },\n };\n}\n\n/**\n * Build an allow response (empty output = allow by default).\n */\nexport function buildAllowResponse(): HookOutput {\n return {};\n}\n","/**\n * Cache Store — read/write `.claude/cache/` directory.\n *\n * Stores navigation-index.json and metadata for graph cache invalidation.\n * Uses atomic write (write-to-temp + rename) for concurrent-access safety.\n */\n\nimport { readFile, writeFile, rename, stat, mkdir } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CacheEntry<T = unknown> {\n data: T;\n /** ISO timestamp of when the cache was written. */\n writtenAt: string;\n /** Hash of source inputs used for invalidation. */\n sourceHash: string;\n}\n\nexport interface CacheStoreOptions {\n /** Absolute path to the `.claude/cache/` directory. */\n cacheDir: string;\n}\n\n// ---------------------------------------------------------------------------\n// Cache Store\n// ---------------------------------------------------------------------------\n\nexport interface CacheStore {\n read<T = unknown>(key: string): Promise<CacheEntry<T> | null>;\n write<T = unknown>(key: string, data: T, sourceHash: string): Promise<void>;\n /**\n * Check if a cache entry is fresh by comparing its sourceHash.\n * Returns the cached data if fresh, null if stale or missing.\n */\n readIfFresh<T = unknown>(key: string, currentHash: string): Promise<T | null>;\n /** Get the mtime of a file (for invalidation checks). */\n getFileMtime(filePath: string): Promise<number | null>;\n}\n\nexport function createCacheStore(options: CacheStoreOptions): CacheStore {\n const { cacheDir } = options;\n\n function cacheFilePath(key: string): string {\n return join(cacheDir, `${key}.json`);\n }\n\n async function ensureDir(): Promise<void> {\n await mkdir(cacheDir, { recursive: true });\n }\n\n const store: CacheStore = {\n async read<T = unknown>(key: string): Promise<CacheEntry<T> | null> {\n try {\n const raw = await readFile(cacheFilePath(key), \"utf-8\");\n return JSON.parse(raw) as CacheEntry<T>;\n } catch {\n return null;\n }\n },\n\n async write<T = unknown>(key: string, data: T, sourceHash: string): Promise<void> {\n await ensureDir();\n const entry: CacheEntry<T> = {\n data,\n writtenAt: new Date().toISOString(),\n sourceHash,\n };\n const content = JSON.stringify(entry, null, 2);\n const target = cacheFilePath(key);\n const tmpPath = `${target}.${randomBytes(4).toString(\"hex\")}.tmp`;\n\n // Atomic write: write to temp file then rename\n await writeFile(tmpPath, content, \"utf-8\");\n try {\n await rename(tmpPath, target);\n } catch {\n // Fallback: direct write if rename fails (cross-device)\n await writeFile(target, content, \"utf-8\");\n }\n },\n\n async readIfFresh<T = unknown>(key: string, currentHash: string): Promise<T | null> {\n const entry = await store.read<T>(key);\n if (!entry) return null;\n if (entry.sourceHash !== currentHash) return null;\n return entry.data;\n },\n\n async getFileMtime(filePath: string): Promise<number | null> {\n try {\n const s = await stat(filePath);\n return s.mtimeMs;\n } catch {\n return null;\n }\n },\n };\n\n return store;\n}\n\n/**\n * Compute a simple hash string from an array of file mtimes and content strings.\n * Not cryptographic — used only for cache invalidation.\n */\nexport function computeSourceHash(inputs: Array<string | number>): string {\n return inputs.map(String).join(\":\");\n}\n","/**\n * Latency utilities — timeout wrapper, graph build exclusion, degrade policy.\n *\n * Mirrors the Promise-sharing pattern from analyzer-bridge.ts for concurrent\n * graph build exclusion.\n */\n\n// ---------------------------------------------------------------------------\n// Timeout wrapper\n// ---------------------------------------------------------------------------\n\nexport class TimeoutError extends Error {\n constructor(ms: number) {\n super(`Operation timed out after ${ms}ms`);\n this.name = \"TimeoutError\";\n }\n}\n\n/**\n * Race a promise against a timeout. Resolves with the promise result or\n * rejects with TimeoutError.\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n): Promise<T> {\n if (timeoutMs <= 0) return promise;\n\n let timer: ReturnType<typeof setTimeout>;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new TimeoutError(timeoutMs)), timeoutMs);\n });\n\n try {\n return await Promise.race([promise, timeout]);\n } finally {\n clearTimeout(timer!);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Exclusive lock (Promise sharing)\n// ---------------------------------------------------------------------------\n\n/**\n * Creates an exclusive async lock that ensures only one invocation runs at a\n * time. Subsequent callers await the same Promise (analyzer-bridge pattern).\n */\nexport function createExclusiveLock<T>(): {\n run: (fn: () => Promise<T>) => Promise<T>;\n} {\n let pending: Promise<T> | null = null;\n\n return {\n async run(fn: () => Promise<T>): Promise<T> {\n if (pending) return pending;\n pending = fn().finally(() => {\n pending = null;\n });\n return pending;\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Degrade policy\n// ---------------------------------------------------------------------------\n\nexport interface DegradeResult<T> {\n value: T;\n degraded: boolean;\n reason?: string;\n}\n\n/**\n * Attempt an operation with timeout; if it fails or times out, return the\n * fallback value with `degraded: true`.\n */\nexport async function withDegrade<T>(\n operation: () => Promise<T>,\n fallback: T,\n timeoutMs: number,\n): Promise<DegradeResult<T>> {\n try {\n const value = await withTimeout(operation(), timeoutMs);\n return { value, degraded: false };\n } catch (err) {\n const reason =\n err instanceof TimeoutError\n ? err.message\n : err instanceof Error\n ? err.message\n : String(err);\n return { value: fallback, degraded: true, reason };\n }\n}\n","/**\n * Artifact Resolver — reverse-lookup path to artifact_id using navigation-index.\n *\n * Uses glob matching from guardrail-hooks.ts to match file paths against\n * artifact path_patterns defined in the navigation index.\n */\n\nimport { matchGlob } from \"../guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Minimal shape of a navigation-index artifact node. */\nexport interface NavigationArtifact {\n properties?: {\n type?: string;\n authority?: string;\n manual_edit?: string;\n [key: string]: unknown;\n };\n files?: {\n path_patterns?: string[];\n [key: string]: unknown;\n };\n agents?: {\n owners?: string[];\n editors?: string[];\n [key: string]: unknown;\n };\n routes?: {\n regenerate?: string;\n [key: string]: unknown;\n };\n relations?: {\n derived_artifacts?: string[];\n [key: string]: unknown;\n };\n}\n\nexport interface ArtifactMatch {\n artifactId: string;\n artifact: NavigationArtifact;\n /** The glob pattern that matched. */\n matchedPattern: string;\n}\n\n// ---------------------------------------------------------------------------\n// Resolver\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a file path to its artifact(s) in the navigation index.\n * Returns all matching artifacts (a file may belong to multiple artifacts).\n */\nexport function resolvePathToArtifacts(\n filePath: string,\n navigationIndex: Record<string, unknown>,\n): ArtifactMatch[] {\n const artifacts =\n (navigationIndex.artifacts as Record<string, NavigationArtifact>) ?? {};\n const matches: ArtifactMatch[] = [];\n\n for (const [id, artifact] of Object.entries(artifacts)) {\n const patterns = artifact?.files?.path_patterns;\n if (!Array.isArray(patterns)) continue;\n\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n if (matchGlob(pattern, filePath)) {\n matches.push({ artifactId: id, artifact, matchedPattern: pattern });\n break; // One match per artifact is sufficient\n }\n }\n }\n\n return matches;\n}\n\n/**\n * Check if a file path targets a protected artifact (generated or manual_edit: forbidden).\n */\nexport function isProtectedArtifact(match: ArtifactMatch): {\n protected: boolean;\n reason: string;\n} {\n const props = match.artifact.properties ?? {};\n\n if (props.authority === \"generated\") {\n const regen = match.artifact.routes?.regenerate;\n const hint = regen\n ? ` Run '${regen}' to regenerate.`\n : \" Edit the source artifact and regenerate instead.\";\n return {\n protected: true,\n reason:\n `File belongs to generated artifact '${match.artifactId}'.` +\n ` Direct editing is not allowed.${hint}`,\n };\n }\n\n if (props.manual_edit === \"forbidden\") {\n return {\n protected: true,\n reason:\n `File belongs to artifact '${match.artifactId}' which has manual_edit: forbidden.` +\n ` This artifact must not be edited directly.`,\n };\n }\n\n return { protected: false, reason: \"\" };\n}\n\n/**\n * Get all artifact entries from a navigation index as a flat list.\n */\nexport function listArtifacts(\n navigationIndex: Record<string, unknown>,\n): Array<{ id: string; artifact: NavigationArtifact }> {\n const artifacts =\n (navigationIndex.artifacts as Record<string, NavigationArtifact>) ?? {};\n return Object.entries(artifacts).map(([id, artifact]) => ({\n id,\n artifact,\n }));\n}\n","/**\n * PreToolUse Hook Handler — artifact guardrail + DSL guardrail enforcement.\n *\n * Executed before tool use (Edit, Write, Bash, etc.). Checks:\n * 1. Edit/Write tools: file path → artifact reverse lookup → deny if protected\n * 2. Bash tool: apply DSL guardrail rules via GuardrailHooks\n */\n\nimport {\n createGuardrailHooksFromRules,\n getBlockingViolations,\n type GuardrailRuleData,\n} from \"../guardrail-hooks.js\";\nimport {\n resolvePathToArtifacts,\n isProtectedArtifact,\n} from \"./artifact-resolver.js\";\nimport {\n buildDenyResponse,\n buildAllowResponse,\n type HookOutput,\n type PreToolUseInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface PreToolUseHandlerConfig {\n /** Navigation index for artifact resolution. */\n navigationIndex: Record<string, unknown>;\n /** DSL guardrail rules for Bash command evaluation. */\n guardrailRules?: GuardrailRuleData;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Tool names that perform file edits. */\nconst EDIT_TOOLS = new Set([\"Edit\", \"Write\", \"MultiEdit\", \"edit\", \"write\"]);\n\n/** Tool names that execute shell commands. */\nconst BASH_TOOLS = new Set([\"Bash\", \"bash\", \"Terminal\", \"terminal\"]);\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a PreToolUse hook handler.\n */\nexport function createPreToolUseHandler(config: PreToolUseHandlerConfig) {\n // Pre-compile guardrail hooks if rules provided\n const guardrailHooks = config.guardrailRules\n ? createGuardrailHooksFromRules(config.guardrailRules)\n : null;\n\n return async function handlePreToolUse(\n input: PreToolUseInput,\n ): Promise<HookOutput> {\n const toolName = input.tool_name ?? \"\";\n const toolInput = input.tool_input ?? {};\n\n // --- Edit/Write tool: artifact protection ---\n if (EDIT_TOOLS.has(toolName)) {\n const filePath = toolInput.file_path ?? toolInput.path ?? \"\";\n if (filePath) {\n const matches = resolvePathToArtifacts(\n filePath,\n config.navigationIndex,\n );\n\n for (const match of matches) {\n const check = isProtectedArtifact(match);\n if (check.protected) {\n return buildDenyResponse(check.reason);\n }\n }\n }\n }\n\n // --- Bash tool: DSL guardrail enforcement ---\n if (BASH_TOOLS.has(toolName) && guardrailHooks) {\n const command = toolInput.command ?? \"\";\n if (command) {\n const hookResult = guardrailHooks.beforeShellExecution({ command });\n if (hookResult.permission === \"deny\") {\n return buildDenyResponse(\n hookResult.user_message ?? \"Command blocked by guardrail\",\n );\n }\n }\n }\n\n // --- Default: allow ---\n return buildAllowResponse();\n };\n}\n","/**\n * Workspace Router — route a file path to the owning workspace member.\n *\n * Pure path-manipulation module. No imports from navigation-context,\n * agent-contracts, or any heavy dependency — safe for the lean hooks-lite\n * entry point.\n *\n * Algorithm: longest-prefix match among member absolute root paths.\n *\n * C4 resolution: stripMemberPrefix converts a workspace-relative path\n * (`aaac/packages/runtime/x.ts`) into a repo-relative path\n * (`packages/runtime/x.ts`) so existing member DSL path_patterns work\n * without modification.\n */\n\nimport { resolve } from \"node:path\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceMember {\n /** Human-readable member name (e.g. `\"aaac\"`). */\n name: string;\n /** Absolute path to the member root directory. */\n root: string;\n}\n\n// ---------------------------------------------------------------------------\n// Router\n// ---------------------------------------------------------------------------\n\n/**\n * Route a file path to the workspace member whose root is the longest\n * matching prefix of that path.\n *\n * Generic over `T extends WorkspaceMember` so callers that pass a richer\n * member type (e.g. `WorkspaceMemberPreToolUseConfig`) get back that type\n * without a cast.\n *\n * @param filePath - Absolute or workspace-root-relative file path (as\n * received from Claude Code's `tool_input.file_path`).\n * @param members - Workspace members with **absolute** root paths.\n * @param workspaceRoot - Absolute path to the workspace root directory.\n * Used to resolve relative `filePath` values.\n * @returns The owning member, or `null` when no member claims this path.\n */\nexport function routePathToMember<T extends WorkspaceMember>(\n filePath: string,\n members: T[],\n workspaceRoot: string,\n): T | null {\n if (!filePath) return null;\n\n // Normalise to absolute path\n const absPath = filePath.startsWith(\"/\")\n ? filePath\n : resolve(workspaceRoot, filePath);\n\n let best: T | null = null;\n let bestPrefixLen = 0;\n\n for (const member of members) {\n const memberRoot = member.root;\n // Ensure the prefix ends with \"/\" so \"aaac-extra\" doesn't match \"aaac\"\n const prefix = memberRoot.endsWith(\"/\") ? memberRoot : memberRoot + \"/\";\n\n if (absPath.startsWith(prefix) && prefix.length > bestPrefixLen) {\n best = member;\n bestPrefixLen = prefix.length;\n }\n }\n\n return best;\n}\n\n/**\n * Strip the member root prefix from `filePath` to obtain a repo-relative\n * path that member DSL `path_patterns` can match against unchanged (C4).\n *\n * Example:\n * filePath = \"aaac/packages/runtime/x.ts\" (workspace-relative)\n * memberRoot = \"/abs/workspace/aaac\"\n * workspaceRoot = \"/abs/workspace\"\n * → returns \"packages/runtime/x.ts\"\n *\n * @param filePath - Absolute or workspace-root-relative path.\n * @param memberRoot - Absolute path to the member root.\n * @param workspaceRoot - Absolute path to the workspace root.\n * @returns Repo-relative path (no leading slash/dot).\n * Falls back to the original `filePath` when stripping is not possible.\n */\nexport function stripMemberPrefix(\n filePath: string,\n memberRoot: string,\n workspaceRoot: string,\n): string {\n const absPath = filePath.startsWith(\"/\")\n ? filePath\n : resolve(workspaceRoot, filePath);\n\n const prefix = memberRoot.endsWith(\"/\") ? memberRoot : memberRoot + \"/\";\n if (absPath.startsWith(prefix)) {\n return absPath.slice(prefix.length);\n }\n\n return filePath;\n}\n","/**\n * Workspace PreToolUse Hook Handler — routes edits to the owning member\n * and enforces that member's artifact guardrails.\n *\n * Hot-path module. Does NOT import navigation-context or agent-contracts —\n * it only reads an already-built navigation index from the cache. Suitable\n * for inclusion in the lean hooks-lite entry point.\n *\n * Flow (per PreToolUse invocation):\n * 1. Extract file path from tool input.\n * 2. Route to owning member via longest-prefix match (workspace-router).\n * 3. Read member's navigation-index from cache (cache-store).\n * 4. Strip member-root prefix → repo-relative path (C4 resolution).\n * 5. Resolve path to artifacts; deny if protected.\n */\n\nimport {\n createGuardrailHooksFromRules,\n type GuardrailHooks,\n type GuardrailRuleData,\n} from \"../guardrail-hooks.js\";\nimport {\n resolvePathToArtifacts,\n isProtectedArtifact,\n} from \"./artifact-resolver.js\";\nimport {\n createCacheStore,\n} from \"./cache-store.js\";\nimport { guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\nimport {\n buildDenyResponse,\n buildAllowResponse,\n type HookOutput,\n type PreToolUseInput,\n} from \"./hook-protocol.js\";\nimport {\n routePathToMember,\n stripMemberPrefix,\n type WorkspaceMember,\n} from \"./workspace-router.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceMemberPreToolUseConfig extends WorkspaceMember {\n /**\n * Cache key for this member's navigation-index JSON.\n * Format: `navigation-index.<name>` (e.g. `navigation-index.aaac`).\n */\n cacheKey: string;\n /**\n * Cache key for this member's DSL guardrail rules (#238 / C5).\n *\n * Defaults to `guardrailCacheKey(cacheKey)` (i.e. `<cacheKey>.guardrails`)\n * when omitted, matching what `ensureNavigationIndex` persists during the\n * SessionStart warm-up. Provided explicitly only for tests / custom layouts.\n */\n guardrailCacheKey?: string;\n}\n\nexport interface WorkspacePreToolUseConfig {\n /** Absolute path to the workspace root directory. */\n workspaceRoot: string;\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members to route edits to. */\n members: WorkspaceMemberPreToolUseConfig[];\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Tool names that perform file edits. */\nconst EDIT_TOOLS = new Set([\"Edit\", \"Write\", \"MultiEdit\", \"edit\", \"write\"]);\n\n/** Tool names that execute shell commands. */\nconst BASH_TOOLS = new Set([\"Bash\", \"bash\", \"Terminal\", \"terminal\"]);\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Extract path-like tokens from a shell command so a Bash invocation can be\n * routed to the owning workspace member (#238 / C5).\n *\n * Whitespace-split, strips common shell quoting; keeps only tokens that look\n * like paths (contain a `/` or `\\`). This is a best-effort heuristic — command\n * guardrails that fail to route to a specific member fall back to evaluating\n * against every member's rules (safety-preserving union).\n */\nfunction extractCommandPathTokens(command: string): string[] {\n const tokens: string[] = [];\n for (const raw of command.split(/\\s+/)) {\n const t = raw.replace(/^['\"]+|['\"]+$/g, \"\");\n if (t && (t.includes(\"/\") || t.includes(\"\\\\\"))) {\n tokens.push(t);\n }\n }\n return tokens;\n}\n\n/**\n * Create a workspace-aware PreToolUse hook handler.\n *\n * On each invocation the handler:\n * - Edit/Write tools:\n * - Routes the target path to the owning member by longest-prefix match.\n * - Reads the member's cached navigation-index (allows if no cache yet).\n * - Strips the member-root prefix so `resolvePathToArtifacts` receives the\n * same repo-relative path the member DSL's `path_patterns` expect (C4).\n * - Denies if any matched artifact is protected (Phase 1).\n * - Bash tools (#238 / C5, Phase 3):\n * - Routes the command to the owning member via a path token in the command\n * (longest-prefix match); when no member path is present, evaluates the\n * command against every member's rules so safety guardrails are never\n * silently skipped.\n * - Loads that member's DSL guardrail rules from the companion cache entry\n * and denies blocking command violations.\n *\n * Artifact protection (Phase 1) and Bash guardrails (Phase 3) are independent\n * and coexist: a member with only artifact rules keeps working unchanged, and\n * a member with only guardrail rules still enforces Bash safety.\n */\nexport function createWorkspacePreToolUseHandler(\n config: WorkspacePreToolUseConfig,\n) {\n const store = createCacheStore({ cacheDir: config.cacheDir });\n\n // Per-member compiled guardrail hooks, memoised across invocations.\n const guardrailHooksByMember = new Map<string, GuardrailHooks | null>();\n\n async function loadGuardrailHooks(\n member: WorkspaceMemberPreToolUseConfig,\n ): Promise<GuardrailHooks | null> {\n const key = member.name;\n if (guardrailHooksByMember.has(key)) {\n return guardrailHooksByMember.get(key) ?? null;\n }\n const cacheKey = member.guardrailCacheKey ?? guardrailCacheKey(member.cacheKey);\n const entry = await store.read<GuardrailRuleData>(cacheKey);\n const rules = entry?.data;\n const hooks =\n rules &&\n (rules.commandRules.length > 0 ||\n rules.fileRules.length > 0 ||\n rules.contentRules.length > 0)\n ? createGuardrailHooksFromRules(rules)\n : null;\n guardrailHooksByMember.set(key, hooks);\n return hooks;\n }\n\n /**\n * Route a Bash command to the member(s) whose guardrail rules apply. Returns\n * a single owning member when a member-prefixed path is present in the\n * command; otherwise returns every member (safety-preserving union).\n */\n function membersForCommand(\n command: string,\n ): WorkspaceMemberPreToolUseConfig[] {\n for (const token of extractCommandPathTokens(command)) {\n const owner = routePathToMember(\n token,\n config.members,\n config.workspaceRoot,\n );\n if (owner) return [owner];\n }\n return config.members;\n }\n\n return async function handleWorkspacePreToolUse(\n input: PreToolUseInput,\n ): Promise<HookOutput> {\n const toolName = input.tool_name ?? \"\";\n const toolInput = input.tool_input ?? {};\n\n // --- Bash tool: member-scoped DSL guardrail enforcement (Phase 3 / C5) ---\n if (BASH_TOOLS.has(toolName)) {\n const command = toolInput.command ?? \"\";\n if (!command) {\n return buildAllowResponse();\n }\n for (const member of membersForCommand(command)) {\n const hooks = await loadGuardrailHooks(member);\n if (!hooks) continue;\n const result = hooks.beforeShellExecution({ command });\n if (result.permission === \"deny\") {\n return buildDenyResponse(\n result.user_message ?? \"Command blocked by guardrail\",\n );\n }\n }\n return buildAllowResponse();\n }\n\n if (!EDIT_TOOLS.has(toolName)) {\n return buildAllowResponse();\n }\n\n const filePath = toolInput.file_path ?? toolInput.path ?? \"\";\n if (!filePath) {\n return buildAllowResponse();\n }\n\n // Step 1: Route to owning member\n const member = routePathToMember(\n filePath,\n config.members,\n config.workspaceRoot,\n );\n if (!member) {\n // Path does not belong to any declared member — allow\n return buildAllowResponse();\n }\n\n // Step 2: Load member's navigation-index from cache\n const entry = await store.read<Record<string, unknown>>(member.cacheKey);\n if (!entry) {\n // No cache yet (session-start hasn't run) — fail-open\n return buildAllowResponse();\n }\n\n // Step 3: Strip member-root prefix → repo-relative path (C4)\n const repoRelPath = stripMemberPrefix(\n filePath,\n member.root,\n config.workspaceRoot,\n );\n\n // Step 4: Resolve path to artifacts and check protection\n const matches = resolvePathToArtifacts(repoRelPath, entry.data);\n\n for (const match of matches) {\n const check = isProtectedArtifact(match);\n if (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|
-
* Build the guardrail context from resolved DSL + binding data.
|
|
3
|
-
*
|
|
4
|
-
* (The DSL→TypeScript codegen context builder, `buildContractContext`, was
|
|
5
|
-
* removed alongside the runtime `generate()` codegen path.)
|
|
6
|
-
*/
|
|
7
|
-
interface GuardrailCheckEntry {
|
|
8
|
-
guardrail_id: string;
|
|
9
|
-
description: string;
|
|
10
|
-
severity: string;
|
|
11
|
-
action: string;
|
|
12
|
-
matcher_type: string;
|
|
13
|
-
pattern: string;
|
|
14
|
-
message: string;
|
|
15
|
-
file_glob?: string;
|
|
16
|
-
exclude_glob?: string;
|
|
17
|
-
}
|
|
18
|
-
interface GuardrailContext {
|
|
19
|
-
commandChecks: GuardrailCheckEntry[];
|
|
20
|
-
fileChecks: GuardrailCheckEntry[];
|
|
21
|
-
contentChecks: GuardrailCheckEntry[];
|
|
22
|
-
allChecks: GuardrailCheckEntry[];
|
|
23
|
-
hasGuardrails: boolean;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Build guardrail context from DSL guardrails, binding guardrail_impl, and active policy.
|
|
27
|
-
* Mirrors the agent-contracts resolveChecks pattern.
|
|
28
|
-
*/
|
|
29
|
-
declare function buildGuardrailContext(dsl: any, binding: any, policyName?: string): GuardrailContext;
|
|
30
|
-
|
|
31
|
-
export { type GuardrailContext as G, buildGuardrailContext as b };
|
|
@@ -1,83 +0,0 @@
|
|
|
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 };
|