@aisac/cli 0.4.0-beta.2 → 0.4.0-beta.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +115 -10
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +243 -5
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +6 -0
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +584 -35
  11. package/dist/codex-compatibility.mjs +48 -2
  12. package/dist/codex-engineering.mjs +165 -0
  13. package/dist/codex-hooks.mjs +411 -0
  14. package/dist/codex-permissions.mjs +67 -34
  15. package/dist/codex-protocol-fingerprint.json +11 -11
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +259 -23
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/extensions-catalog.mjs +373 -0
  23. package/dist/extensions-cli.mjs +492 -0
  24. package/dist/extensions-preferences.mjs +151 -0
  25. package/dist/guardrails/continuity.mjs +239 -0
  26. package/dist/guardrails/format.mjs +111 -0
  27. package/dist/guardrails/guards.mjs +449 -0
  28. package/dist/guardrails/patch.mjs +33 -0
  29. package/dist/guardrails/run.mjs +286 -0
  30. package/dist/guardrails/shell-words.mjs +206 -0
  31. package/dist/guardrails-plugin.mjs +207 -0
  32. package/dist/launch.mjs +278 -34
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/mcp-servers.mjs +192 -0
  35. package/dist/mcp.mjs +10 -2
  36. package/dist/monitor.mjs +76 -1
  37. package/dist/package.json +1 -1
  38. package/dist/platform.mjs +78 -29
  39. package/dist/release-manifest-public-keys.json +10 -0
  40. package/dist/release-manifest.json +328 -0
  41. package/dist/release-manifest.mjs +817 -0
  42. package/dist/release-settings.mjs +210 -0
  43. package/dist/self-update.mjs +1036 -0
  44. package/dist/state.mjs +25 -1
  45. package/dist/token-guide.mjs +132 -0
  46. package/dist/update-actions.mjs +442 -0
  47. package/package.json +1 -1
@@ -0,0 +1,286 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ /**
4
+ * Guardrail dispatcher (spec aisac-engineering-extensions FR2, FR5, FR6): the
5
+ * command the hosts run for each hook event.
6
+ * - Claude Code: the session plugin `aisac-guardrails` registers one command per
7
+ * event, and that one process runs every enabled hook bound to it, so a tool
8
+ * call pays for one Node start. The launcher passes the state folder, the
9
+ * preferences file and the locale as arguments.
10
+ * - Codex (`--client codex`, E6b): one command per hook and event, byte-stable so
11
+ * the user's review in `/hooks` holds. The enabled set, the locale, the state
12
+ * folder and the preferences file come from GUARDRAILS_SESSION_ENV, which the
13
+ * monitor put in the app-server's environment; without it the hook does
14
+ * nothing. The project is the payload's `cwd`, never an inherited
15
+ * CLAUDE_PROJECT_DIR, and a patch (`apply_patch`) is an edit of every file its
16
+ * headers name.
17
+ * The event payload comes from the host on stdin and is untrusted.
18
+ *
19
+ * Exit 0 always, except exit 2 for a PreToolUse refusal (reason on stderr).
20
+ * Any error lets the tool call run: a broken guard must not stop all work.
21
+ */
22
+ import { homedir } from 'node:os';
23
+ import { isAbsolute, join, resolve } from 'node:path';
24
+ import { pathToFileURL } from 'node:url';
25
+ import { GUARDRAILS_SESSION_ENV, parseGuardrailsSession } from '../codex-hooks.mjs';
26
+ import { hookById } from '../extensions-catalog.mjs';
27
+ import { GUARDS } from './guards.mjs';
28
+ import { PATCH_TOOL, patchPaths } from './patch.mjs';
29
+ import {
30
+ continuityReminder,
31
+ docsReminder,
32
+ recordEdit,
33
+ resetTurn,
34
+ restoreCompactSnapshot,
35
+ saveCompactSnapshot,
36
+ sessionContext,
37
+ } from './continuity.mjs';
38
+ import { formatEdited } from './format.mjs';
39
+
40
+ const MAX_INPUT_BYTES = 1024 * 1024;
41
+ const EVENTS = new Set([
42
+ 'PreToolUse',
43
+ 'PostToolUse',
44
+ 'UserPromptSubmit',
45
+ 'SessionStart',
46
+ 'PreCompact',
47
+ 'Stop',
48
+ ]);
49
+ const REFUSAL_EXIT_CODE = 2;
50
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/u;
51
+ const ARGUMENT_NAMES = ['--client', '--event', '--hooks', '--state', '--prefs', '--locale'];
52
+ // Codex matches a patch with the edit tool names too (`Edit|Write` fires for
53
+ // `apply_patch`, measured on 0.166.0), so the catalog's Claude matchers bind it.
54
+ /** @type {Readonly<Record<string, readonly string[]>>} */
55
+ const TOOL_ALIASES = Object.freeze({
56
+ [PATCH_TOOL]: Object.freeze([PATCH_TOOL, 'Edit', 'Write']),
57
+ });
58
+
59
+ /**
60
+ * @typedef {object} RunOptions
61
+ * @property {'claude' | 'codex'} client
62
+ * @property {import('../extensions-catalog.mjs').HookEvent} event
63
+ * @property {string[]} hooks
64
+ * @property {string} stateDir
65
+ * @property {string} prefsPath
66
+ * @property {'pt-BR' | 'en'} locale
67
+ */
68
+
69
+ /** Catalog ids bound to the event. @param {string[]} ids @param {string} event */
70
+ function boundIds(ids, event) {
71
+ return ids.filter((id) => {
72
+ const entry = hookById(id);
73
+ return entry !== undefined && entry.bindings.some((binding) => binding.event === event);
74
+ });
75
+ }
76
+
77
+ /**
78
+ * Strict launcher arguments; null when anything is off. In Codex the enabled
79
+ * set and the paths come from the session value in the environment, and a hook
80
+ * the session did not enable is dropped.
81
+ * @param {string[]} argv
82
+ * @param {NodeJS.ProcessEnv} [env]
83
+ * @returns {RunOptions | null}
84
+ */
85
+ export function parseArguments(argv, env = process.env) {
86
+ /** @type {Record<string, string>} */
87
+ const values = {};
88
+ for (let index = 0; index < argv.length; index += 2) {
89
+ const name = argv[index] ?? '';
90
+ const value = argv[index + 1];
91
+ if (!ARGUMENT_NAMES.includes(name) || value === undefined || Object.hasOwn(values, name))
92
+ return null;
93
+ values[name] = value;
94
+ }
95
+ const event = values['--event'] ?? '';
96
+ if (!EVENTS.has(event)) return null;
97
+ const typedEvent = /** @type {import('../extensions-catalog.mjs').HookEvent} */ (event);
98
+ const requested = (values['--hooks'] ?? '').split(',');
99
+ if (values['--client'] === 'codex') {
100
+ if (['--state', '--prefs', '--locale'].some((name) => Object.hasOwn(values, name))) return null;
101
+ const session = parseGuardrailsSession(env[GUARDRAILS_SESSION_ENV]);
102
+ if (session === null) return null;
103
+ return {
104
+ client: 'codex',
105
+ event: typedEvent,
106
+ hooks: boundIds(requested, event).filter((id) => session.hooks.includes(id)),
107
+ stateDir: session.stateDir,
108
+ prefsPath: session.prefsPath,
109
+ locale: session.locale,
110
+ };
111
+ }
112
+ if (values['--client'] !== undefined && values['--client'] !== 'claude') return null;
113
+ const stateDir = values['--state'] ?? '';
114
+ const prefsPath = values['--prefs'] ?? '';
115
+ if (!isAbsolute(stateDir) || !isAbsolute(prefsPath)) return null;
116
+ return {
117
+ client: 'claude',
118
+ event: typedEvent,
119
+ hooks: boundIds(requested, event),
120
+ stateDir,
121
+ prefsPath,
122
+ locale: values['--locale'] === 'pt-BR' ? 'pt-BR' : 'en',
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Codex's user config files: `~/.codex/config.toml`, and `$CODEX_HOME/config.toml`
128
+ * when CODEX_HOME is set. They hold the off switch of every Codex hook, so
129
+ * `secrets-guard` keeps the agent out of them (FR2.2, E6b).
130
+ * @param {NodeJS.ProcessEnv} env @param {string} home
131
+ */
132
+ export function codexConfigPaths(env, home) {
133
+ const paths = [join(home, '.codex', 'config.toml')];
134
+ const codexHome = env.CODEX_HOME;
135
+ if (typeof codexHome === 'string' && isAbsolute(codexHome) && !CONTROL_CHARACTERS.test(codexHome))
136
+ paths.push(join(resolve(codexHome), 'config.toml'));
137
+ return [...new Set(paths)];
138
+ }
139
+
140
+ /** @returns {Promise<string | null>} */
141
+ async function readInput() {
142
+ /** @type {Buffer[]} */
143
+ const chunks = [];
144
+ let size = 0;
145
+ for await (const chunk of process.stdin) {
146
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
147
+ size += buffer.length;
148
+ if (size > MAX_INPUT_BYTES) return null;
149
+ chunks.push(buffer);
150
+ }
151
+ return Buffer.concat(chunks).toString('utf8');
152
+ }
153
+
154
+ /** Does a hook's binding for this event accept the tool or source? @param {string} id @param {string} event @param {string} subject */
155
+ function bound(id, event, subject) {
156
+ const names = TOOL_ALIASES[subject] ?? [subject];
157
+ return (hookById(id)?.bindings ?? []).some(
158
+ (binding) =>
159
+ binding.event === event &&
160
+ (binding.matcher === undefined ||
161
+ binding.matcher.split('|').some((name) => names.includes(name))),
162
+ );
163
+ }
164
+
165
+ /**
166
+ * The files a tool call edits: `file_path`, or every path a Codex patch names.
167
+ * @param {string} tool @param {Record<string, unknown>} toolInput
168
+ * @returns {unknown[]}
169
+ */
170
+ function editedFiles(tool, toolInput) {
171
+ return tool === PATCH_TOOL ? patchPaths(toolInput.command) : [toolInput.file_path];
172
+ }
173
+
174
+ /**
175
+ * Run the enabled hooks for one event.
176
+ * @param {RunOptions} options
177
+ * @param {Record<string, unknown>} input
178
+ * @returns {Promise<{ exitCode: number, stdout: string, stderr: string }>}
179
+ */
180
+ export async function dispatch(options, input) {
181
+ // Codex adds no project variable: one in its environment was inherited from the
182
+ // user's shell (for example a Claude Code terminal), so Codex uses the payload cwd.
183
+ const envProject = options.client === 'codex' ? undefined : process.env.CLAUDE_PROJECT_DIR;
184
+ const projectDir =
185
+ typeof envProject === 'string' && isAbsolute(envProject)
186
+ ? envProject
187
+ : typeof input.cwd === 'string' && isAbsolute(input.cwd)
188
+ ? input.cwd
189
+ : process.cwd();
190
+ const home = homedir();
191
+ const context = {
192
+ projectDir,
193
+ stateDir: options.stateDir,
194
+ prefsPath: options.prefsPath,
195
+ codexConfigs: codexConfigPaths(process.env, home),
196
+ home,
197
+ locale: options.locale,
198
+ };
199
+ const enabled = new Set(options.hooks);
200
+ const tool = typeof input.tool_name === 'string' ? input.tool_name : '';
201
+ const toolInput =
202
+ typeof input.tool_input === 'object' && input.tool_input !== null
203
+ ? /** @type {Record<string, unknown>} */ (input.tool_input)
204
+ : {};
205
+ const quiet = { exitCode: 0, stdout: '', stderr: '' };
206
+
207
+ if (options.event === 'PreToolUse') {
208
+ for (const [id, guard] of Object.entries(GUARDS)) {
209
+ if (!enabled.has(id) || !bound(id, 'PreToolUse', tool)) continue;
210
+ const reason = guard(input, context);
211
+ if (reason !== null)
212
+ return { exitCode: REFUSAL_EXIT_CODE, stdout: '', stderr: `[aisac ${id}] ${reason}\n` };
213
+ }
214
+ return quiet;
215
+ }
216
+ if (options.event === 'PostToolUse') {
217
+ let reminder = '';
218
+ for (const filePath of editedFiles(tool, toolInput)) {
219
+ if (enabled.has('format-on-edit') && bound('format-on-edit', 'PostToolUse', tool))
220
+ await formatEdited(projectDir, filePath);
221
+ if (enabled.has('continuity-reminder') && bound('continuity-reminder', 'PostToolUse', tool))
222
+ await recordEdit(context, input.session_id, filePath);
223
+ if (
224
+ reminder.length === 0 &&
225
+ enabled.has('docs-reminder') &&
226
+ bound('docs-reminder', 'PostToolUse', tool)
227
+ )
228
+ reminder = await docsReminder(context, input.session_id, filePath);
229
+ }
230
+ return reminder.length === 0
231
+ ? quiet
232
+ : {
233
+ exitCode: 0,
234
+ stdout: JSON.stringify({
235
+ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: reminder },
236
+ }),
237
+ stderr: '',
238
+ };
239
+ }
240
+ if (options.event === 'UserPromptSubmit') {
241
+ if (enabled.has('docs-reminder') || enabled.has('continuity-reminder'))
242
+ await resetTurn(context, input.session_id);
243
+ return quiet;
244
+ }
245
+ if (options.event === 'Stop') {
246
+ const reason = enabled.has('continuity-reminder')
247
+ ? await continuityReminder(context, input.session_id, input.stop_hook_active)
248
+ : '';
249
+ return reason.length === 0
250
+ ? quiet
251
+ : { exitCode: 0, stdout: JSON.stringify({ decision: 'block', reason }), stderr: '' };
252
+ }
253
+ if (options.event === 'PreCompact') {
254
+ if (enabled.has('compact-continuity')) await saveCompactSnapshot(context, input.session_id);
255
+ return quiet;
256
+ }
257
+ const source = typeof input.source === 'string' ? input.source : 'startup';
258
+ const text =
259
+ source === 'compact'
260
+ ? enabled.has('compact-continuity')
261
+ ? await restoreCompactSnapshot(context, input.session_id)
262
+ : ''
263
+ : enabled.has('session-context') && bound('session-context', 'SessionStart', source)
264
+ ? await sessionContext(context)
265
+ : '';
266
+ return { exitCode: 0, stdout: text, stderr: '' };
267
+ }
268
+
269
+ async function main() {
270
+ const options = parseArguments(process.argv.slice(2));
271
+ if (options === null || options.hooks.length === 0) return;
272
+ const raw = await readInput();
273
+ if (raw === null) return;
274
+ /** @type {unknown} */
275
+ const parsed = JSON.parse(raw);
276
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return;
277
+ const result = await dispatch(options, /** @type {Record<string, unknown>} */ (parsed));
278
+ if (result.stdout.length > 0) process.stdout.write(result.stdout);
279
+ if (result.stderr.length > 0) process.stderr.write(result.stderr);
280
+ process.exitCode = result.exitCode;
281
+ }
282
+
283
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href)
284
+ main().catch(() => {
285
+ process.exitCode = 0;
286
+ });
@@ -0,0 +1,206 @@
1
+ // @ts-check
2
+ /**
3
+ * A small POSIX-style shell word splitter for guardrail decisions. It never
4
+ * runs anything. It keeps quotes, escapes and command substitutions inside
5
+ * their word, splits commands on control operators, and marks redirection
6
+ * targets. When the text cannot be split (an unterminated quote), `ok` is
7
+ * false and callers fall back to a word-boundary scan of the raw text.
8
+ */
9
+
10
+ /**
11
+ * @typedef {object} ShellCommand
12
+ * @property {string[]} words Words of one simple command, without redirections.
13
+ * @property {string[]} targets File targets of its redirections (`>`, `>>`, `<`, `&>`, ...).
14
+ */
15
+
16
+ const CONTROL_OPERATORS = ['&&', '||', ';;', '|&', ';', '|', '&', '(', ')'];
17
+ const REDIRECTIONS = ['&>>', '&>', '>>', '>|', '<>', '<<<', '<<', '>', '<'];
18
+ const HEREDOC_OPERATORS = new Set(['<<', '<<<']);
19
+ const MAX_COMMAND_LENGTH = 64 * 1024;
20
+
21
+ /** @param {string} text @param {number} index @param {string[]} candidates */
22
+ function operatorAt(text, index, candidates) {
23
+ return candidates.find((candidate) => text.startsWith(candidate, index));
24
+ }
25
+
26
+ /**
27
+ * Read a `$(...)` or backtick substitution verbatim, so its text stays in the word.
28
+ * @param {string} text @param {number} start index of `$(` or the backtick
29
+ * @returns {number} index after the substitution, or -1 when it never closes
30
+ */
31
+ function substitutionEnd(text, start) {
32
+ if (text[start] === '`') {
33
+ const close = text.indexOf('`', start + 1);
34
+ return close === -1 ? -1 : close + 1;
35
+ }
36
+ let depth = 0;
37
+ for (let index = start; index < text.length; index += 1) {
38
+ if (text[index] === '(') depth += 1;
39
+ else if (text[index] === ')') {
40
+ depth -= 1;
41
+ if (depth === 0) return index + 1;
42
+ }
43
+ }
44
+ return -1;
45
+ }
46
+
47
+ /**
48
+ * Split a shell command line into simple commands.
49
+ * @param {string} text
50
+ * @returns {{ ok: boolean, commands: ShellCommand[] }}
51
+ */
52
+ export function splitShell(text) {
53
+ if (typeof text !== 'string' || text.length > MAX_COMMAND_LENGTH)
54
+ return { ok: false, commands: [] };
55
+ /** @type {ShellCommand[]} */
56
+ const commands = [];
57
+ /** @type {ShellCommand} */
58
+ let current = { words: [], targets: [] };
59
+ let word = '';
60
+ let inWord = false;
61
+ /** @type {string | null} */
62
+ let pendingRedirection = null;
63
+
64
+ const endWord = () => {
65
+ if (!inWord) return;
66
+ if (pendingRedirection !== null) {
67
+ if (!HEREDOC_OPERATORS.has(pendingRedirection)) current.targets.push(word);
68
+ pendingRedirection = null;
69
+ } else current.words.push(word);
70
+ word = '';
71
+ inWord = false;
72
+ };
73
+ const endCommand = () => {
74
+ endWord();
75
+ if (current.words.length > 0 || current.targets.length > 0) commands.push(current);
76
+ current = { words: [], targets: [] };
77
+ };
78
+
79
+ let index = 0;
80
+ while (index < text.length) {
81
+ const char = text[index];
82
+ if (char === ' ' || char === '\t') {
83
+ endWord();
84
+ index += 1;
85
+ } else if (char === '\n') {
86
+ endCommand();
87
+ index += 1;
88
+ } else if (char === '#' && !inWord) {
89
+ const newline = text.indexOf('\n', index);
90
+ index = newline === -1 ? text.length : newline;
91
+ } else if (char === "'") {
92
+ const close = text.indexOf("'", index + 1);
93
+ if (close === -1) return { ok: false, commands: [] };
94
+ word += text.slice(index + 1, close);
95
+ inWord = true;
96
+ index = close + 1;
97
+ } else if (char === '"') {
98
+ let cursor = index + 1;
99
+ let closed = false;
100
+ while (cursor < text.length) {
101
+ const inner = text[cursor];
102
+ if (
103
+ inner === '\\' &&
104
+ cursor + 1 < text.length &&
105
+ '"\\$`\n'.includes(text[cursor + 1] ?? '')
106
+ ) {
107
+ if (text[cursor + 1] !== '\n') word += text[cursor + 1];
108
+ cursor += 2;
109
+ } else if (inner === '"') {
110
+ closed = true;
111
+ cursor += 1;
112
+ break;
113
+ } else if (inner === '$' && text[cursor + 1] === '(') {
114
+ const end = substitutionEnd(text, cursor + 1);
115
+ if (end === -1) return { ok: false, commands: [] };
116
+ word += text.slice(cursor, end);
117
+ cursor = end;
118
+ } else {
119
+ word += inner;
120
+ cursor += 1;
121
+ }
122
+ }
123
+ if (!closed) return { ok: false, commands: [] };
124
+ inWord = true;
125
+ index = cursor;
126
+ } else if (char === '\\') {
127
+ if (text[index + 1] === '\n') index += 2;
128
+ else {
129
+ word += text[index + 1] ?? '';
130
+ inWord = true;
131
+ index += 2;
132
+ }
133
+ } else if ((char === '$' && text[index + 1] === '(') || char === '`') {
134
+ const end = substitutionEnd(text, char === '`' ? index : index + 1);
135
+ if (end === -1) return { ok: false, commands: [] };
136
+ word += text.slice(index, end);
137
+ inWord = true;
138
+ index = end;
139
+ } else {
140
+ const redirection = operatorAt(text, index, REDIRECTIONS);
141
+ const descriptorWord = inWord && /^\d+$/u.test(word);
142
+ if (redirection !== undefined && (!inWord || descriptorWord)) {
143
+ if (descriptorWord) {
144
+ word = '';
145
+ inWord = false;
146
+ } else endWord();
147
+ index += redirection.length;
148
+ // `2>&1` and `>&2` duplicate a descriptor; they name no file.
149
+ if (text[index] === '&' && /\d|-/u.test(text[index + 1] ?? '')) {
150
+ index += 2;
151
+ continue;
152
+ }
153
+ pendingRedirection = redirection;
154
+ continue;
155
+ }
156
+ const operator = operatorAt(text, index, CONTROL_OPERATORS);
157
+ if (operator !== undefined) {
158
+ endCommand();
159
+ index += operator.length;
160
+ continue;
161
+ }
162
+ word += char;
163
+ inWord = true;
164
+ index += 1;
165
+ }
166
+ }
167
+ endCommand();
168
+ return { ok: true, commands };
169
+ }
170
+
171
+ /** Basename of a program word (`/usr/bin/git` -> `git`). @param {string} word */
172
+ export function programName(word) {
173
+ const slash = word.lastIndexOf('/');
174
+ return slash === -1 ? word : word.slice(slash + 1);
175
+ }
176
+
177
+ const WRAPPERS = new Set([
178
+ 'sudo',
179
+ 'doas',
180
+ 'env',
181
+ 'command',
182
+ 'nice',
183
+ 'nohup',
184
+ 'time',
185
+ 'exec',
186
+ 'npx',
187
+ 'bunx',
188
+ ]);
189
+
190
+ /**
191
+ * The words of a command with leading `VAR=value` assignments and wrappers
192
+ * such as `sudo` or `env` removed, so `sudo rm -rf /` is seen as `rm -rf /`.
193
+ * @param {string[]} words
194
+ */
195
+ export function effectiveWords(words) {
196
+ let index = 0;
197
+ while (index < words.length) {
198
+ const word = words[index] ?? '';
199
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(word)) index += 1;
200
+ else if (WRAPPERS.has(programName(word))) {
201
+ index += 1;
202
+ while ((words[index] ?? '').startsWith('-')) index += 1;
203
+ } else break;
204
+ }
205
+ return words.slice(index);
206
+ }
@@ -0,0 +1,207 @@
1
+ // @ts-check
2
+ /**
3
+ * The session plugin `aisac-guardrails` (spec aisac-engineering-extensions
4
+ * FR5): written into the launch's private folder with only the enabled
5
+ * hooks, and deleted with that folder on exit. Every command is the absolute
6
+ * Node executable plus the dispatcher inside the installed package; nothing
7
+ * comes from the server (ADR-0048).
8
+ */
9
+ import { access, mkdir, realpath, writeFile } from 'node:fs/promises';
10
+ import { isAbsolute, join } from 'node:path';
11
+ import { hookById } from './extensions-catalog.mjs';
12
+ import { enabledHookIds, preferencesPath, readPreferences } from './extensions-preferences.mjs';
13
+ import { readStoredLocale, resolvePackLocale } from './engineering-pack.mjs';
14
+ import {
15
+ codexHookConfigArgs,
16
+ codexHooksLine,
17
+ codexHooksValue,
18
+ summarizeCodexHooks,
19
+ } from './codex-hooks.mjs';
20
+ import { readCodexHookList } from './codex-permissions.mjs';
21
+
22
+ export const GUARDRAILS_PLUGIN_NAME = 'aisac-guardrails';
23
+ const PLUGIN_VERSION = '1.0.0';
24
+ const PLUGIN_DIRECTORY = 'guardrails';
25
+ const STATE_DIRECTORY = 'guardrails-state';
26
+ const DISPATCHER = join('guardrails', 'run.mjs');
27
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/u;
28
+ /** @type {Readonly<Record<string, number>>} */
29
+ const TIMEOUT_SECONDS = Object.freeze({
30
+ PreToolUse: 5,
31
+ PostToolUse: 5,
32
+ UserPromptSubmit: 5,
33
+ Stop: 5,
34
+ SessionStart: 10,
35
+ PreCompact: 10,
36
+ });
37
+
38
+ /** POSIX single-quote quoting for the host's shell. @param {string} value */
39
+ export function shellQuote(value) {
40
+ return `'${value.replaceAll("'", "'\\''")}'`;
41
+ }
42
+
43
+ /** @param {string} path */
44
+ function safeAbsolute(path) {
45
+ return isAbsolute(path) && !CONTROL_CHARACTERS.test(path);
46
+ }
47
+
48
+ /**
49
+ * The plugin's hooks.json for the enabled ids: one entry per event, whose
50
+ * matcher is the union of the enabled hooks' matchers for that event.
51
+ * @param {string[]} enabled
52
+ * @param {{ node: string, dispatcher: string, stateDir: string, prefsPath: string, locale: 'pt-BR' | 'en' }} paths
53
+ */
54
+ export function guardrailsHooks(enabled, paths) {
55
+ /** @type {Map<string, { ids: string[], matchers: Set<string>, unmatched: boolean }>} */
56
+ const events = new Map();
57
+ for (const id of enabled) {
58
+ for (const binding of hookById(id)?.bindings ?? []) {
59
+ const current = events.get(binding.event) ?? {
60
+ ids: [],
61
+ matchers: new Set(),
62
+ unmatched: false,
63
+ };
64
+ if (!current.ids.includes(id)) current.ids.push(id);
65
+ if (binding.matcher === undefined) current.unmatched = true;
66
+ else for (const name of binding.matcher.split('|')) current.matchers.add(name);
67
+ events.set(binding.event, current);
68
+ }
69
+ }
70
+ /** @type {Record<string, unknown[]>} */
71
+ const hooks = {};
72
+ for (const [event, group] of events) {
73
+ const command = [
74
+ shellQuote(paths.node),
75
+ shellQuote(paths.dispatcher),
76
+ '--event',
77
+ event,
78
+ '--hooks',
79
+ group.ids.join(','),
80
+ '--state',
81
+ shellQuote(paths.stateDir),
82
+ '--prefs',
83
+ shellQuote(paths.prefsPath),
84
+ '--locale',
85
+ paths.locale,
86
+ ].join(' ');
87
+ hooks[event] = [
88
+ {
89
+ ...(group.unmatched || group.matchers.size === 0
90
+ ? {}
91
+ : { matcher: [...group.matchers].join('|') }),
92
+ hooks: [{ type: 'command', command, timeout: TIMEOUT_SECONDS[event] ?? 5 }],
93
+ },
94
+ ];
95
+ }
96
+ return {
97
+ description: 'AISAC Engineering guardrails for this session (aisac hooks to change them).',
98
+ hooks,
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Write the plugin for a licensed launch. Null when no hook is enabled or the
104
+ * package lacks the dispatcher; the launch then goes on without it.
105
+ * @param {{ directory: string, root: string, packageRoot: string }} input
106
+ * @returns {Promise<{ pluginRoot: string, count: number, line: string } | null>}
107
+ */
108
+ export async function prepareGuardrails(input) {
109
+ const enabled = enabledHookIds(await readPreferences(input.root));
110
+ if (enabled.length === 0) return null;
111
+ const dispatcher = join(input.packageRoot, DISPATCHER);
112
+ const prefsPath = preferencesPath(input.root);
113
+ const pluginRoot = join(input.directory, PLUGIN_DIRECTORY);
114
+ const stateDir = join(input.directory, STATE_DIRECTORY);
115
+ if (![process.execPath, dispatcher, prefsPath, pluginRoot, stateDir].every(safeAbsolute))
116
+ return null;
117
+ if (
118
+ !(await access(dispatcher).then(
119
+ () => true,
120
+ () => false,
121
+ ))
122
+ )
123
+ return null;
124
+ const locale = resolvePackLocale(await readStoredLocale(input.root));
125
+ await mkdir(join(pluginRoot, '.claude-plugin'), { recursive: true, mode: 0o700 });
126
+ await mkdir(join(pluginRoot, 'hooks'), { mode: 0o700 });
127
+ await mkdir(stateDir, { mode: 0o700 });
128
+ const manifest = {
129
+ name: GUARDRAILS_PLUGIN_NAME,
130
+ version: PLUGIN_VERSION,
131
+ description: 'AISAC Engineering guardrail hooks, loaded for this session only.',
132
+ author: { name: 'AISAC' },
133
+ hooks: './hooks/hooks.json',
134
+ };
135
+ const hooks = guardrailsHooks(enabled, {
136
+ node: process.execPath,
137
+ dispatcher,
138
+ stateDir,
139
+ prefsPath,
140
+ locale,
141
+ });
142
+ await writeFile(
143
+ join(pluginRoot, '.claude-plugin', 'plugin.json'),
144
+ `${JSON.stringify(manifest, null, 2)}\n`,
145
+ { mode: 0o600, flag: 'wx' },
146
+ );
147
+ await writeFile(join(pluginRoot, 'hooks', 'hooks.json'), `${JSON.stringify(hooks, null, 2)}\n`, {
148
+ mode: 0o600,
149
+ flag: 'wx',
150
+ });
151
+ return {
152
+ pluginRoot,
153
+ count: enabled.length,
154
+ line: `AISAC Engineering: ${enabled.length} guardrail${enabled.length === 1 ? '' : 's'} on (aisac hooks to change them).`,
155
+ };
156
+ }
157
+
158
+ /**
159
+ * What Codex reports for the AISAC hooks the user has on, read with Codex's own
160
+ * `hooks/list` for the exact flags the monitor passes (spec FR6, E6b). Null when
161
+ * no Codex hook is enabled or the package lacks the dispatcher; `summary` is null
162
+ * when the listing failed.
163
+ * @param {{ root: string, packageRoot: string, executable: string, cwd: string, profile: string | undefined, environment: NodeJS.ProcessEnv }} input
164
+ * @param {{ listHooks?: typeof readCodexHookList }} [dependencies]
165
+ * @returns {Promise<{ enabled: string[], summary: import('./codex-hooks.mjs').CodexHooksSummary | null } | null>}
166
+ */
167
+ export async function readCodexGuardrails(input, dependencies = {}) {
168
+ const listHooks = dependencies.listHooks ?? readCodexHookList;
169
+ const enabled = enabledHookIds(await readPreferences(input.root)).filter(
170
+ (id) => hookById(id)?.clients.includes('codex') === true,
171
+ );
172
+ if (enabled.length === 0) return null;
173
+ // The monitor resolves the same file from its own folder; both use the real path.
174
+ const dispatcher = await realpath(join(input.packageRoot, DISPATCHER)).catch(() => null);
175
+ if (dispatcher === null || !safeAbsolute(dispatcher) || !safeAbsolute(process.execPath))
176
+ return null;
177
+ const paths = { node: process.execPath, dispatcher };
178
+ const summary = await listHooks({
179
+ executable: input.executable,
180
+ cwd: input.cwd,
181
+ profile: input.profile,
182
+ environment: input.environment,
183
+ configArgs: codexHookConfigArgs(paths),
184
+ }).then(
185
+ (listed) => summarizeCodexHooks(listed, paths, enabled),
186
+ () => null,
187
+ );
188
+ return { enabled, summary };
189
+ }
190
+
191
+ /**
192
+ * The guardrails for a licensed Codex launch: the value the launcher hands the
193
+ * monitor, and the launch line. The line comes from `hooks/list`, so a guardrail
194
+ * that waits for the user's review in `/hooks` is never called on.
195
+ * @param {{ root: string, packageRoot: string, executable: string, cwd: string, profile: string | undefined, environment: NodeJS.ProcessEnv }} input
196
+ * @param {{ listHooks?: typeof readCodexHookList }} [dependencies]
197
+ * @returns {Promise<{ value: string, line: string } | null>}
198
+ */
199
+ export async function prepareCodexGuardrails(input, dependencies = {}) {
200
+ const read = await readCodexGuardrails(input, dependencies);
201
+ if (read === null) return null;
202
+ const locale = resolvePackLocale(await readStoredLocale(input.root));
203
+ return {
204
+ value: codexHooksValue(read.enabled, locale),
205
+ line: codexHooksLine(read.enabled.length, read.summary),
206
+ };
207
+ }