forked from openclaw/openclaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkspace.ts
More file actions
334 lines (306 loc) · 8.78 KB
/
Copy pathworkspace.ts
File metadata and controls
334 lines (306 loc) · 8.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import fs from "node:fs";
import path from "node:path";
import { MANIFEST_KEY } from "../compat/legacy-names.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { openRootFileSync } from "../infra/boundary-file-read.js";
import { createSubsystemLogger } from "../logging/subsystem.js";
import { isPathInsideWithRealpath } from "../security/scan-paths.js";
import { normalizeTrimmedStringList } from "../shared/string-normalization.js";
import { CONFIG_DIR, resolveUserPath } from "../utils.js";
import { resolveBundledHooksDir } from "./bundled-dir.js";
import {
parseFrontmatter,
resolveHookInvocationPolicy,
resolveOpenClawMetadata,
} from "./frontmatter.js";
import { resolvePluginHookDirs } from "./plugin-hooks.js";
import { resolveHookEntries } from "./policy.js";
import type { Hook, HookEntry, HookSource, ParsedHookFrontmatter } from "./types.js";
type HookPackageManifest = {
name?: string;
} & Partial<Record<typeof MANIFEST_KEY, { hooks?: string[] }>>;
const log = createSubsystemLogger("hooks/workspace");
type LoadedHook = {
hook: Hook;
frontmatter: ParsedHookFrontmatter;
};
function readHookPackageManifest(dir: string): HookPackageManifest | null {
const manifestPath = path.join(dir, "package.json");
const raw = readRootFileUtf8({
absolutePath: manifestPath,
rootPath: dir,
boundaryLabel: "hook package directory",
});
if (raw === null) {
return null;
}
try {
return JSON.parse(raw) as HookPackageManifest;
} catch {
return null;
}
}
function resolvePackageHooks(manifest: HookPackageManifest): string[] {
return normalizeTrimmedStringList(manifest[MANIFEST_KEY]?.hooks);
}
function resolveContainedDir(baseDir: string, targetDir: string): string | null {
const base = path.resolve(baseDir);
const resolved = path.resolve(baseDir, targetDir);
if (
!isPathInsideWithRealpath(base, resolved, {
requireRealpath: true,
})
) {
return null;
}
return resolved;
}
function loadHookFromDir(params: {
hookDir: string;
source: HookSource;
pluginId?: string;
nameHint?: string;
}): LoadedHook | null {
const hookMdPath = path.join(params.hookDir, "HOOK.md");
const content = readRootFileUtf8({
absolutePath: hookMdPath,
rootPath: params.hookDir,
boundaryLabel: "hook directory",
});
if (content === null) {
return null;
}
try {
const frontmatter = parseFrontmatter(content);
const name = frontmatter.name || params.nameHint || path.basename(params.hookDir);
const description = frontmatter.description || "";
const handlerCandidates = ["handler.ts", "handler.js", "index.ts", "index.js"];
let handlerPath: string | undefined;
for (const candidate of handlerCandidates) {
const candidatePath = path.join(params.hookDir, candidate);
const safeCandidatePath = resolveRootFilePath({
absolutePath: candidatePath,
rootPath: params.hookDir,
boundaryLabel: "hook directory",
});
if (safeCandidatePath) {
handlerPath = safeCandidatePath;
break;
}
}
if (!handlerPath) {
log.warn(`Hook "${name}" has HOOK.md but no handler file in ${params.hookDir}`);
return null;
}
let baseDir = params.hookDir;
try {
baseDir = fs.realpathSync.native(params.hookDir);
} catch {
// keep the discovered path when realpath is unavailable
}
return {
hook: {
name,
description,
source: params.source,
pluginId: params.pluginId,
filePath: hookMdPath,
baseDir,
handlerPath,
},
frontmatter,
};
} catch (err) {
const message = err instanceof Error ? (err.stack ?? err.message) : String(err);
log.warn(`Failed to load hook from ${params.hookDir}: ${message}`);
return null;
}
}
/**
* Scan a directory for hooks (subdirectories containing HOOK.md)
*/
function loadHooksFromDir(params: {
dir: string;
source: HookSource;
pluginId?: string;
}): LoadedHook[] {
const { dir, source, pluginId } = params;
if (!fs.existsSync(dir)) {
return [];
}
const stat = fs.statSync(dir);
if (!stat.isDirectory()) {
return [];
}
const hooks: LoadedHook[] = [];
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) {
continue;
}
const hookDir = path.join(dir, entry.name);
const manifest = readHookPackageManifest(hookDir);
const packageHooks = manifest ? resolvePackageHooks(manifest) : [];
if (packageHooks.length > 0) {
for (const hookPath of packageHooks) {
const resolvedHookDir = resolveContainedDir(hookDir, hookPath);
if (!resolvedHookDir) {
log.warn(
`Ignoring out-of-package hook path "${hookPath}" in ${hookDir} (must be within package directory)`,
);
continue;
}
const hook = loadHookFromDir({
hookDir: resolvedHookDir,
source,
pluginId,
nameHint: path.basename(resolvedHookDir),
});
if (hook) {
hooks.push(hook);
}
}
continue;
}
const hook = loadHookFromDir({
hookDir,
source,
pluginId,
nameHint: entry.name,
});
if (hook) {
hooks.push(hook);
}
}
return hooks;
}
export function loadHookEntriesFromDir(params: {
dir: string;
source: HookSource;
pluginId?: string;
}): HookEntry[] {
const hooks = loadHooksFromDir({
dir: params.dir,
source: params.source,
pluginId: params.pluginId,
});
return hooks.map(({ hook, frontmatter }) => {
const entry: HookEntry = {
hook: {
...hook,
source: params.source,
pluginId: params.pluginId,
},
frontmatter,
metadata: resolveOpenClawMetadata(frontmatter),
invocation: resolveHookInvocationPolicy(frontmatter),
};
return entry;
});
}
function discoverWorkspaceHookEntries(
workspaceDir: string,
opts?: {
config?: OpenClawConfig;
managedHooksDir?: string;
bundledHooksDir?: string;
},
): HookEntry[] {
const managedHooksDir = opts?.managedHooksDir ?? path.join(CONFIG_DIR, "hooks");
const workspaceHooksDir = path.join(workspaceDir, "hooks");
const bundledHooksDir = opts?.bundledHooksDir ?? resolveBundledHooksDir();
const extraDirsRaw = opts?.config?.hooks?.internal?.load?.extraDirs ?? [];
const extraDirs = normalizeTrimmedStringList(extraDirsRaw);
const pluginHookDirs = resolvePluginHookDirs({
workspaceDir,
config: opts?.config,
});
const bundledHooks = bundledHooksDir
? loadHookEntriesFromDir({
dir: bundledHooksDir,
source: "openclaw-bundled",
})
: [];
const extraHooks = extraDirs.flatMap((dir) => {
const resolved = resolveUserPath(dir);
return loadHookEntriesFromDir({
dir: resolved,
source: "openclaw-managed",
});
});
const pluginHooks = pluginHookDirs.flatMap(({ dir, pluginId }) =>
loadHookEntriesFromDir({
dir,
source: "openclaw-plugin",
pluginId,
}),
);
const managedHooks = loadHookEntriesFromDir({
dir: managedHooksDir,
source: "openclaw-managed",
});
const workspaceHooks = loadHookEntriesFromDir({
dir: workspaceHooksDir,
source: "openclaw-workspace",
});
return [...extraHooks, ...bundledHooks, ...pluginHooks, ...managedHooks, ...workspaceHooks];
}
export function loadWorkspaceHookEntries(
workspaceDir: string,
opts?: {
config?: OpenClawConfig;
managedHooksDir?: string;
bundledHooksDir?: string;
entries?: HookEntry[];
},
): HookEntry[] {
return resolveHookEntries(opts?.entries ?? discoverWorkspaceHookEntries(workspaceDir, opts), {
onCollisionIgnored: ({ name, kept, ignored }) => {
log.warn(
`Ignoring ${ignored.hook.source} hook "${name}" because it cannot override ${kept.hook.source} hook code`,
);
},
});
}
function readRootFileUtf8(params: {
absolutePath: string;
rootPath: string;
boundaryLabel: string;
}): string | null {
return withOpenedRootFileSync(params, (opened) => {
try {
return fs.readFileSync(opened.fd, "utf-8");
} catch {
return null;
}
});
}
function withOpenedRootFileSync<T>(
params: {
absolutePath: string;
rootPath: string;
boundaryLabel: string;
},
read: (opened: { fd: number; path: string }) => T,
): T | null {
const opened = openRootFileSync({
absolutePath: params.absolutePath,
rootPath: params.rootPath,
boundaryLabel: params.boundaryLabel,
});
if (!opened.ok) {
return null;
}
try {
return read({ fd: opened.fd, path: opened.path });
} finally {
fs.closeSync(opened.fd);
}
}
function resolveRootFilePath(params: {
absolutePath: string;
rootPath: string;
boundaryLabel: string;
}): string | null {
return withOpenedRootFileSync(params, (opened) => opened.path);
}