@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.
- package/README.md +115 -10
- package/dist/assets/claude/hooks/context-compaction.ts +17 -5
- package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
- package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
- package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
- package/dist/assets/codex-context-compaction.mjs +243 -5
- package/dist/assets/jev-paid-pilot-terminal.mjs +6 -0
- package/dist/claude-compatibility.mjs +26 -25
- package/dist/claude-observation.mjs +2 -1
- package/dist/cli.mjs +584 -35
- package/dist/codex-compatibility.mjs +48 -2
- package/dist/codex-engineering.mjs +165 -0
- package/dist/codex-hooks.mjs +411 -0
- package/dist/codex-permissions.mjs +67 -34
- package/dist/codex-protocol-fingerprint.json +11 -11
- package/dist/engineering-init.mjs +615 -0
- package/dist/engineering-pack.mjs +259 -23
- package/dist/engineering-scan-pins.json +42 -0
- package/dist/engineering-scan-report.mjs +1274 -0
- package/dist/engineering-scan-tools.mjs +1418 -0
- package/dist/engineering-scan.mjs +1265 -0
- package/dist/extensions-catalog.mjs +373 -0
- package/dist/extensions-cli.mjs +492 -0
- package/dist/extensions-preferences.mjs +151 -0
- package/dist/guardrails/continuity.mjs +239 -0
- package/dist/guardrails/format.mjs +111 -0
- package/dist/guardrails/guards.mjs +449 -0
- package/dist/guardrails/patch.mjs +33 -0
- package/dist/guardrails/run.mjs +286 -0
- package/dist/guardrails/shell-words.mjs +206 -0
- package/dist/guardrails-plugin.mjs +207 -0
- package/dist/launch.mjs +278 -34
- package/dist/managed-host.mjs +977 -0
- package/dist/mcp-servers.mjs +192 -0
- package/dist/mcp.mjs +10 -2
- package/dist/monitor.mjs +76 -1
- package/dist/package.json +1 -1
- package/dist/platform.mjs +78 -29
- package/dist/release-manifest-public-keys.json +10 -0
- package/dist/release-manifest.json +328 -0
- package/dist/release-manifest.mjs +817 -0
- package/dist/release-settings.mjs +210 -0
- package/dist/self-update.mjs +1036 -0
- package/dist/state.mjs +25 -1
- package/dist/token-guide.mjs +132 -0
- package/dist/update-actions.mjs +442 -0
- package/package.json +1 -1
|
@@ -7,6 +7,7 @@ import { spawn } from 'node:child_process';
|
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
import { tmpdir } from 'node:os';
|
|
9
9
|
import fingerprint from './codex-protocol-fingerprint.json' with { type: 'json' };
|
|
10
|
+
import releaseManifest from './release-manifest.json' with { type: 'json' };
|
|
10
11
|
|
|
11
12
|
const MAX_OUTPUT_BYTES = 64 * 1024;
|
|
12
13
|
const MAX_SCHEMA_BYTES = 8 * 1024 * 1024;
|
|
@@ -26,7 +27,9 @@ const PAGINATION_CONTRACT_VALID =
|
|
|
26
27
|
fingerprint.roots[PAGINATION_CONTRACT.response_schema]?.sha256 &&
|
|
27
28
|
typeof PAGINATION_CONTRACT.graph_sha256 === 'string' &&
|
|
28
29
|
PAGINATION_CONTRACT.graph_sha256.length === 64);
|
|
29
|
-
|
|
30
|
+
// One source for the qualified releases: the manifest bundled with this client
|
|
31
|
+
// (ADR-0056 R2; spec aisac-release-manifest FR4).
|
|
32
|
+
const QUALIFIED_VERSIONS = new Set(releaseManifest.hosts.codex.qualified);
|
|
30
33
|
const ANNOTATIONS = new Set([
|
|
31
34
|
'$comment',
|
|
32
35
|
'title',
|
|
@@ -475,7 +478,50 @@ export async function resolveCodexCompatibility(executable, baseEnvironment = pr
|
|
|
475
478
|
}
|
|
476
479
|
}
|
|
477
480
|
|
|
481
|
+
/** @param {string} left @param {string} right */
|
|
482
|
+
function compareStableVersions(left, right) {
|
|
483
|
+
const a = left.split('.').map(Number);
|
|
484
|
+
const b = right.split('.').map(Number);
|
|
485
|
+
for (let index = 0; index < 3; index += 1) {
|
|
486
|
+
const difference = (a[index] ?? 0) - (b[index] ?? 0);
|
|
487
|
+
if (difference !== 0) return difference;
|
|
488
|
+
}
|
|
489
|
+
return 0;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** The newest Codex release this client was qualified against. */
|
|
493
|
+
export const LATEST_QUALIFIED_CODEX = /** @type {string} */ (
|
|
494
|
+
[...QUALIFIED_VERSIONS].sort(compareStableVersions).at(-1)
|
|
495
|
+
);
|
|
496
|
+
|
|
497
|
+
// Rejections a user fixes by installing a qualified Codex (or a newer aisac):
|
|
498
|
+
// the installed release's contract or transport differs from the bundled one.
|
|
499
|
+
const CONTRACT_REJECTIONS = new Set([
|
|
500
|
+
'protocol_schema_mismatch',
|
|
501
|
+
'protocol_method_missing',
|
|
502
|
+
'schema_root_missing_or_invalid',
|
|
503
|
+
'schema_set_too_large',
|
|
504
|
+
'schema_generation_failed',
|
|
505
|
+
'transport_flags_missing',
|
|
506
|
+
'protocol_probe_failed',
|
|
507
|
+
]);
|
|
508
|
+
|
|
509
|
+
/** @param {{reason:string, version:string|null}} decision @returns {string|null} */
|
|
510
|
+
export function codexCompatibilityRemedy(decision) {
|
|
511
|
+
const detected = decision.version === null ? 'The installed Codex' : `Codex ${decision.version}`;
|
|
512
|
+
const reinstall = `npm install -g @openai/codex@${LATEST_QUALIFIED_CODEX}`;
|
|
513
|
+
if (CONTRACT_REJECTIONS.has(decision.reason))
|
|
514
|
+
return `${detected} is not qualified by this aisac (newest qualified: ${LATEST_QUALIFIED_CODEX}). Install the qualified Codex with \`${reinstall}\`, or check for an aisac release that qualifies it with \`npm install -g @aisac/cli@beta\`.`;
|
|
515
|
+
if (decision.reason === 'version_unqualified')
|
|
516
|
+
return `${detected} is older than this aisac supports. Update it with \`${reinstall}\`.`;
|
|
517
|
+
if (decision.reason === 'version_not_stable_0x')
|
|
518
|
+
return `${detected} is not a stable 0.x release. Install a qualified one with \`${reinstall}\`.`;
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
|
|
478
522
|
/** @param {{reason:string, version:string|null}} decision @returns {string} */
|
|
479
523
|
export function codexCompatibilityError(decision) {
|
|
480
|
-
|
|
524
|
+
const coded = `codex_protocol_incompatible:${decision.reason}:detected=${decision.version ?? 'unavailable'};run aisac doctor --json`;
|
|
525
|
+
const remedy = codexCompatibilityRemedy(decision);
|
|
526
|
+
return remedy === null ? coded : `${coded}\n${remedy}`;
|
|
481
527
|
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* AISAC Engineering for Codex (ADR-0047 wave E4c, spec FR4).
|
|
5
|
+
*
|
|
6
|
+
* Codex has no session plugin directory, so the method reaches only the
|
|
7
|
+
* app-server this launch owns, and nothing is written to `~/.codex`,
|
|
8
|
+
* `~/.agents` or the project:
|
|
9
|
+
* - skills: the adapter sends `skills/extraRoots/set` with the pack's
|
|
10
|
+
* `skills/` directory right after the client's initialize (in-memory in that
|
|
11
|
+
* process);
|
|
12
|
+
* - agents: one role file per pack agent, declared with `-c agents.<name>.*`
|
|
13
|
+
* overrides on the owned app-server (the session-flags config layer).
|
|
14
|
+
* The launcher hands the monitor one JSON value; the monitor validates it
|
|
15
|
+
* again before turning it into arguments.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
19
|
+
|
|
20
|
+
export const CODEX_ENGINEERING_ENV = 'AISAC_ENGINEERING_CODEX';
|
|
21
|
+
export const CODEX_ENGINEERING_SKILLS_ROOT_ENV = 'AISAC_ENGINEERING_SKILLS_ROOT';
|
|
22
|
+
export const CODEX_AGENTS_DIRECTORY = 'codex-agents';
|
|
23
|
+
const SKILLS_DIRECTORY = 'skills';
|
|
24
|
+
const PACK_DIRECTORY = 'engineering';
|
|
25
|
+
const RUNTIME_DIRECTORY = 'runtime';
|
|
26
|
+
const CODEX_LAUNCH_DIRECTORY = /^codex-[A-Za-z0-9]{6}$/u;
|
|
27
|
+
const SCHEMA_VERSION = 1;
|
|
28
|
+
const MAX_SPEC_BYTES = 16 * 1024;
|
|
29
|
+
const MAX_AGENTS = 16;
|
|
30
|
+
const MAX_PATH_LENGTH = 4096;
|
|
31
|
+
export const MAX_AGENT_DESCRIPTION_LENGTH = 1024;
|
|
32
|
+
export const AGENT_NAME = /^[a-z][a-z0-9-]{0,63}$/u;
|
|
33
|
+
const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/u;
|
|
34
|
+
/** First Codex release whose session mechanism was verified (spike Q4, 2026-11-03). */
|
|
35
|
+
const MIN_CODEX_VERSION = /** @type {const} */ ([0, 164, 0]);
|
|
36
|
+
|
|
37
|
+
/** @typedef {{ name: string, description: string, configFile: string }} CodexAgentRole */
|
|
38
|
+
/** @typedef {{ schemaVersion: 1, skillsRoot: string, agents: CodexAgentRole[] }} CodexEngineering */
|
|
39
|
+
|
|
40
|
+
/** @param {string} code @returns {never} */
|
|
41
|
+
function fail(code) {
|
|
42
|
+
throw new Error(`codex_engineering_${code}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
46
|
+
function isRecord(value) {
|
|
47
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Whether this Codex version receives the pack. A null or malformed version
|
|
52
|
+
* never does.
|
|
53
|
+
* @param {string | null | undefined} version
|
|
54
|
+
*/
|
|
55
|
+
export function supportsCodexEngineering(version) {
|
|
56
|
+
const match = /^(\d+)\.(\d+)\.(\d+)$/u.exec(version ?? '');
|
|
57
|
+
if (match === null) return false;
|
|
58
|
+
const parts = match.slice(1).map(Number);
|
|
59
|
+
for (let index = 0; index < MIN_CODEX_VERSION.length; index += 1) {
|
|
60
|
+
const part = /** @type {number} */ (parts[index]);
|
|
61
|
+
const minimum = MIN_CODEX_VERSION[index] ?? 0;
|
|
62
|
+
if (part !== minimum) return part > minimum;
|
|
63
|
+
}
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @param {unknown} value */
|
|
68
|
+
function isCleanAbsolutePath(value) {
|
|
69
|
+
return (
|
|
70
|
+
typeof value === 'string' &&
|
|
71
|
+
value.length > 0 &&
|
|
72
|
+
value.length <= MAX_PATH_LENGTH &&
|
|
73
|
+
!CONTROL_CHARACTERS.test(value) &&
|
|
74
|
+
value.startsWith('/') &&
|
|
75
|
+
resolve(value) === value
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @param {unknown} value
|
|
81
|
+
* @param {{ stateDir?: string }} [options] when given, the pack must sit in a
|
|
82
|
+
* Codex launch directory of that state directory
|
|
83
|
+
* @returns {CodexEngineering}
|
|
84
|
+
*/
|
|
85
|
+
export function validateCodexEngineering(value, options = {}) {
|
|
86
|
+
if (!isRecord(value)) fail('invalid');
|
|
87
|
+
const keys = Object.keys(value).sort().join(',');
|
|
88
|
+
if (keys !== 'agents,schemaVersion,skillsRoot') fail('invalid');
|
|
89
|
+
if (value.schemaVersion !== SCHEMA_VERSION) fail('schema');
|
|
90
|
+
const skillsRoot = value.skillsRoot;
|
|
91
|
+
if (!isCleanAbsolutePath(skillsRoot)) fail('path');
|
|
92
|
+
const skills = /** @type {string} */ (skillsRoot);
|
|
93
|
+
if (basename(skills) !== SKILLS_DIRECTORY) fail('path');
|
|
94
|
+
const base = dirname(skills);
|
|
95
|
+
if (basename(base) !== PACK_DIRECTORY) fail('path');
|
|
96
|
+
if (options.stateDir !== undefined) {
|
|
97
|
+
const launch = dirname(base);
|
|
98
|
+
if (
|
|
99
|
+
!CODEX_LAUNCH_DIRECTORY.test(basename(launch)) ||
|
|
100
|
+
dirname(launch) !== join(resolve(options.stateDir), RUNTIME_DIRECTORY)
|
|
101
|
+
)
|
|
102
|
+
fail('path');
|
|
103
|
+
}
|
|
104
|
+
if (!Array.isArray(value.agents) || value.agents.length > MAX_AGENTS) fail('agents');
|
|
105
|
+
const seen = new Set();
|
|
106
|
+
/** @type {CodexAgentRole[]} */
|
|
107
|
+
const agents = [];
|
|
108
|
+
for (const agent of value.agents) {
|
|
109
|
+
if (!isRecord(agent) || Object.keys(agent).sort().join(',') !== 'configFile,description,name')
|
|
110
|
+
fail('agents');
|
|
111
|
+
const { name, description, configFile } = agent;
|
|
112
|
+
if (typeof name !== 'string' || !AGENT_NAME.test(name) || seen.has(name)) fail('agents');
|
|
113
|
+
if (
|
|
114
|
+
typeof description !== 'string' ||
|
|
115
|
+
description.trim().length === 0 ||
|
|
116
|
+
description.length > MAX_AGENT_DESCRIPTION_LENGTH ||
|
|
117
|
+
CONTROL_CHARACTERS.test(description)
|
|
118
|
+
)
|
|
119
|
+
fail('agents');
|
|
120
|
+
if (configFile !== join(base, CODEX_AGENTS_DIRECTORY, `${name}.toml`)) fail('agents');
|
|
121
|
+
seen.add(name);
|
|
122
|
+
agents.push({ name, description, configFile });
|
|
123
|
+
}
|
|
124
|
+
return { schemaVersion: SCHEMA_VERSION, skillsRoot: skills, agents };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Parse the monitor's environment value; null when absent.
|
|
129
|
+
* @param {string | undefined} raw
|
|
130
|
+
* @param {{ stateDir?: string }} [options]
|
|
131
|
+
* @returns {CodexEngineering | null}
|
|
132
|
+
*/
|
|
133
|
+
export function parseCodexEngineering(raw, options = {}) {
|
|
134
|
+
if (raw === undefined || raw === '') return null;
|
|
135
|
+
if (Buffer.byteLength(raw, 'utf8') > MAX_SPEC_BYTES) fail('too_large');
|
|
136
|
+
let value;
|
|
137
|
+
try {
|
|
138
|
+
value = JSON.parse(raw);
|
|
139
|
+
} catch {
|
|
140
|
+
fail('invalid');
|
|
141
|
+
}
|
|
142
|
+
return validateCodexEngineering(value, options);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* A TOML basic string. JSON escapes are TOML escapes; DEL is escaped too.
|
|
147
|
+
* @param {string} value
|
|
148
|
+
*/
|
|
149
|
+
export function tomlBasicString(value) {
|
|
150
|
+
return JSON.stringify(value).replace(/\u007f/gu, '\\u007F');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Session-only `-c` overrides for the owned app-server, one role per agent.
|
|
155
|
+
* @param {CodexEngineering} engineering
|
|
156
|
+
* @returns {string[]}
|
|
157
|
+
*/
|
|
158
|
+
export function codexEngineeringConfigArgs(engineering) {
|
|
159
|
+
return engineering.agents.flatMap((agent) => [
|
|
160
|
+
'-c',
|
|
161
|
+
`agents.${agent.name}.description=${tomlBasicString(agent.description)}`,
|
|
162
|
+
'-c',
|
|
163
|
+
`agents.${agent.name}.config_file=${tomlBasicString(agent.configFile)}`,
|
|
164
|
+
]);
|
|
165
|
+
}
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* AISAC guardrails in Codex (spec aisac-engineering-extensions FR6, E6b).
|
|
4
|
+
*
|
|
5
|
+
* Codex loads session-flag hooks as `untrusted`. The user approves them once in
|
|
6
|
+
* `/hooks`, and Codex keys that approval, and the off switch, by position
|
|
7
|
+
* (`<event>:<group>:<handler>`) and command line (measured on 0.166.0). So:
|
|
8
|
+
* - the launch emits every catalog hook, in CODEX_HOOK_POSITIONS order, each with
|
|
9
|
+
* a byte-stable command: the Node executable, the dispatcher, the event and the
|
|
10
|
+
* hook id. No launch directory, version, locale or random value goes in it;
|
|
11
|
+
* - what changes per launch (the enabled hooks, the locale, the launch's state
|
|
12
|
+
* folder, the preferences file) reaches the hook process through the
|
|
13
|
+
* app-server's environment, which Codex hook processes inherit (measured on
|
|
14
|
+
* 0.166.0), as one JSON value in GUARDRAILS_SESSION_ENV.
|
|
15
|
+
* The launcher hands the monitor CODEX_HOOKS_ENV (enabled ids and locale). The
|
|
16
|
+
* monitor validates it against its own catalog and builds the flags and the
|
|
17
|
+
* session value itself, so the variable can never inject a command or a path.
|
|
18
|
+
* This module imports only the catalog and the TOML helper, so the monitor stays
|
|
19
|
+
* small.
|
|
20
|
+
*/
|
|
21
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
22
|
+
import { CODEX_HOOK_POSITIONS, HOOK_CATALOG, hookById } from './extensions-catalog.mjs';
|
|
23
|
+
import { tomlBasicString } from './codex-engineering.mjs';
|
|
24
|
+
|
|
25
|
+
/** Launcher to monitor: the enabled hook ids and the locale. */
|
|
26
|
+
export const CODEX_HOOKS_ENV = 'AISAC_EXTENSIONS_CODEX_HOOKS';
|
|
27
|
+
/** Monitor to hook processes, through the app-server's environment. */
|
|
28
|
+
export const GUARDRAILS_SESSION_ENV = 'AISAC_GUARDRAILS_SESSION';
|
|
29
|
+
const SCHEMA_VERSION = 1;
|
|
30
|
+
// Same names as the Claude session plugin (guardrails-plugin.mjs) and the
|
|
31
|
+
// preferences module (EXTENSIONS_FILE); a test keeps them equal.
|
|
32
|
+
const STATE_DIRECTORY = 'guardrails-state';
|
|
33
|
+
const PREFERENCES_FILE = 'extensions.json';
|
|
34
|
+
const MAX_VALUE_BYTES = 8 * 1024;
|
|
35
|
+
const MAX_PATH_LENGTH = 4096;
|
|
36
|
+
const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/u;
|
|
37
|
+
const LOCALES = /** @type {const} */ (['pt-BR', 'en']);
|
|
38
|
+
/** First Codex release whose hooks were measured with real turns (spike part 2). */
|
|
39
|
+
const MIN_CODEX_HOOKS_VERSION = /** @type {const} */ ([0, 166, 0]);
|
|
40
|
+
/** @type {Readonly<Record<string, number>>} */
|
|
41
|
+
const TIMEOUT_SECONDS = Object.freeze({
|
|
42
|
+
PreToolUse: 5,
|
|
43
|
+
PostToolUse: 5,
|
|
44
|
+
UserPromptSubmit: 5,
|
|
45
|
+
Stop: 5,
|
|
46
|
+
SessionStart: 10,
|
|
47
|
+
PreCompact: 10,
|
|
48
|
+
});
|
|
49
|
+
// Codex reports camelCase event names in hooks/list.
|
|
50
|
+
/** @type {Readonly<Record<string, string>>} */
|
|
51
|
+
const LISTED_EVENT = Object.freeze({
|
|
52
|
+
PreToolUse: 'preToolUse',
|
|
53
|
+
PostToolUse: 'postToolUse',
|
|
54
|
+
UserPromptSubmit: 'userPromptSubmit',
|
|
55
|
+
SessionStart: 'sessionStart',
|
|
56
|
+
PreCompact: 'preCompact',
|
|
57
|
+
Stop: 'stop',
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
/** @typedef {import('./extensions-catalog.mjs').HookEvent} HookEvent */
|
|
61
|
+
/** @typedef {'pt-BR' | 'en'} HookLocale */
|
|
62
|
+
/** @typedef {{ node: string, dispatcher: string }} HookCommandPaths */
|
|
63
|
+
/** @typedef {{ schemaVersion: 1, hooks: string[], locale: HookLocale }} CodexHooksValue */
|
|
64
|
+
/**
|
|
65
|
+
* @typedef {object} GuardrailsSession
|
|
66
|
+
* @property {1} schemaVersion
|
|
67
|
+
* @property {string[]} hooks The hooks the user had on when the session started.
|
|
68
|
+
* @property {HookLocale} locale
|
|
69
|
+
* @property {string} stateDir The launch's guardrail state folder, deleted on exit.
|
|
70
|
+
* @property {string} prefsPath The preferences file (FR2.2).
|
|
71
|
+
*/
|
|
72
|
+
/**
|
|
73
|
+
* @typedef {object} CodexHookHandler
|
|
74
|
+
* @property {HookEvent} event
|
|
75
|
+
* @property {string} id
|
|
76
|
+
* @property {string | undefined} matcher
|
|
77
|
+
* @property {string} command
|
|
78
|
+
* @property {number} timeout
|
|
79
|
+
*/
|
|
80
|
+
|
|
81
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
82
|
+
function isRecord(value) {
|
|
83
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** @param {unknown} value @returns {value is string} */
|
|
87
|
+
function isCleanAbsolutePath(value) {
|
|
88
|
+
return (
|
|
89
|
+
typeof value === 'string' &&
|
|
90
|
+
value.length > 0 &&
|
|
91
|
+
value.length <= MAX_PATH_LENGTH &&
|
|
92
|
+
!CONTROL_CHARACTERS.test(value) &&
|
|
93
|
+
isAbsolute(value) &&
|
|
94
|
+
resolve(value) === value
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** @param {unknown} value @returns {value is HookLocale} */
|
|
99
|
+
function isLocale(value) {
|
|
100
|
+
return typeof value === 'string' && LOCALES.includes(/** @type {HookLocale} */ (value));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** POSIX single-quote quoting for the shell that runs the hook command. @param {string} value */
|
|
104
|
+
function shellQuote(value) {
|
|
105
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Ids that are Codex catalog hooks, in catalog order, without repeats. @param {unknown} ids */
|
|
109
|
+
function codexHookIds(ids) {
|
|
110
|
+
if (!Array.isArray(ids)) return null;
|
|
111
|
+
const wanted = new Set(ids);
|
|
112
|
+
if (ids.length !== wanted.size) return null;
|
|
113
|
+
for (const id of wanted)
|
|
114
|
+
if (typeof id !== 'string' || hookById(id)?.clients.includes('codex') !== true) return null;
|
|
115
|
+
return HOOK_CATALOG.map((entry) => entry.id).filter((id) => wanted.has(id));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Whether this Codex version gets the guardrails. A null or malformed version
|
|
120
|
+
* never does.
|
|
121
|
+
* @param {string | null | undefined} version
|
|
122
|
+
*/
|
|
123
|
+
export function supportsCodexHooks(version) {
|
|
124
|
+
const match = /^(\d+)\.(\d+)\.(\d+)$/u.exec(version ?? '');
|
|
125
|
+
if (match === null) return false;
|
|
126
|
+
const parts = match.slice(1).map(Number);
|
|
127
|
+
for (let index = 0; index < MIN_CODEX_HOOKS_VERSION.length; index += 1) {
|
|
128
|
+
const part = /** @type {number} */ (parts[index]);
|
|
129
|
+
const minimum = MIN_CODEX_HOOKS_VERSION[index] ?? 0;
|
|
130
|
+
if (part !== minimum) return part > minimum;
|
|
131
|
+
}
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The catalog matcher of a hook's binding for one event. @param {string} id @param {string} event */
|
|
136
|
+
function bindingMatcher(id, event) {
|
|
137
|
+
return hookById(id)?.bindings.find((binding) => binding.event === event)?.matcher;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The byte-stable command of one Codex hook.
|
|
142
|
+
* @param {HookCommandPaths} paths @param {string} event @param {string} id
|
|
143
|
+
*/
|
|
144
|
+
export function codexHookCommand(paths, event, id) {
|
|
145
|
+
if (!isCleanAbsolutePath(paths.node) || !isCleanAbsolutePath(paths.dispatcher))
|
|
146
|
+
throw new Error('codex_hooks_path');
|
|
147
|
+
return [
|
|
148
|
+
shellQuote(paths.node),
|
|
149
|
+
shellQuote(paths.dispatcher),
|
|
150
|
+
'--client',
|
|
151
|
+
'codex',
|
|
152
|
+
'--event',
|
|
153
|
+
event,
|
|
154
|
+
'--hooks',
|
|
155
|
+
id,
|
|
156
|
+
].join(' ');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Every Codex hook handler, in position order: one matcher group per hook, so
|
|
161
|
+
* the user can switch each one off in `/hooks`.
|
|
162
|
+
* @param {HookCommandPaths} paths
|
|
163
|
+
* @returns {CodexHookHandler[]}
|
|
164
|
+
*/
|
|
165
|
+
export function codexHookHandlers(paths) {
|
|
166
|
+
return Object.entries(CODEX_HOOK_POSITIONS).flatMap(([event, ids]) =>
|
|
167
|
+
ids.map((id) => ({
|
|
168
|
+
event: /** @type {HookEvent} */ (event),
|
|
169
|
+
id,
|
|
170
|
+
matcher: bindingMatcher(id, event),
|
|
171
|
+
command: codexHookCommand(paths, event, id),
|
|
172
|
+
timeout: TIMEOUT_SECONDS[event] ?? 5,
|
|
173
|
+
})),
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Session-only `-c` flags for the owned app-server, one per event.
|
|
179
|
+
* @param {HookCommandPaths} paths
|
|
180
|
+
* @returns {string[]}
|
|
181
|
+
*/
|
|
182
|
+
export function codexHookConfigArgs(paths) {
|
|
183
|
+
/** @type {Map<string, string[]>} */
|
|
184
|
+
const groups = new Map();
|
|
185
|
+
for (const handler of codexHookHandlers(paths)) {
|
|
186
|
+
const matcher =
|
|
187
|
+
handler.matcher === undefined ? '' : `matcher=${tomlBasicString(handler.matcher)},`;
|
|
188
|
+
const group = `{${matcher}hooks=[{type="command",command=${tomlBasicString(handler.command)},timeout=${handler.timeout}}]}`;
|
|
189
|
+
groups.set(handler.event, [...(groups.get(handler.event) ?? []), group]);
|
|
190
|
+
}
|
|
191
|
+
return [...groups].flatMap(([event, list]) => ['-c', `hooks.${event}=[${list.join(',')}]`]);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* The launcher's value for the monitor. Ids that are not Codex catalog hooks
|
|
196
|
+
* are dropped.
|
|
197
|
+
* @param {string[]} hooks @param {HookLocale} locale
|
|
198
|
+
*/
|
|
199
|
+
export function codexHooksValue(hooks, locale) {
|
|
200
|
+
const ids = codexHookIds([
|
|
201
|
+
...new Set(hooks.filter((id) => hookById(id)?.clients.includes('codex') === true)),
|
|
202
|
+
]);
|
|
203
|
+
return JSON.stringify({
|
|
204
|
+
schemaVersion: SCHEMA_VERSION,
|
|
205
|
+
hooks: ids ?? [],
|
|
206
|
+
locale: isLocale(locale) ? locale : 'en',
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Parse the monitor's value; null when absent or when no hook is on.
|
|
212
|
+
* @param {string | undefined} raw
|
|
213
|
+
* @returns {CodexHooksValue | null}
|
|
214
|
+
*/
|
|
215
|
+
export function parseCodexHooks(raw) {
|
|
216
|
+
if (raw === undefined || raw === '') return null;
|
|
217
|
+
if (Buffer.byteLength(raw, 'utf8') > MAX_VALUE_BYTES) throw new Error('codex_hooks_too_large');
|
|
218
|
+
/** @type {unknown} */
|
|
219
|
+
let value;
|
|
220
|
+
try {
|
|
221
|
+
value = JSON.parse(raw);
|
|
222
|
+
} catch {
|
|
223
|
+
throw new Error('codex_hooks_invalid');
|
|
224
|
+
}
|
|
225
|
+
if (
|
|
226
|
+
!isRecord(value) ||
|
|
227
|
+
Object.keys(value).sort().join(',') !== 'hooks,locale,schemaVersion' ||
|
|
228
|
+
value.schemaVersion !== SCHEMA_VERSION ||
|
|
229
|
+
!isLocale(value.locale)
|
|
230
|
+
)
|
|
231
|
+
throw new Error('codex_hooks_invalid');
|
|
232
|
+
const hooks = codexHookIds(value.hooks);
|
|
233
|
+
if (hooks === null) throw new Error('codex_hooks_invalid');
|
|
234
|
+
return hooks.length === 0 ? null : { schemaVersion: SCHEMA_VERSION, hooks, locale: value.locale };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* The value the hook processes read, built by the monitor: the launcher's
|
|
239
|
+
* choices plus the launch's own state folder (deleted with the launch on exit)
|
|
240
|
+
* and the preferences file of the state root the pack was checked against.
|
|
241
|
+
* @param {CodexHooksValue} value
|
|
242
|
+
* @param {{ launchDirectory: string, stateRoot: string }} paths
|
|
243
|
+
*/
|
|
244
|
+
export function guardrailsSessionValue(value, paths) {
|
|
245
|
+
const parsed = parseGuardrailsSession(
|
|
246
|
+
JSON.stringify({
|
|
247
|
+
schemaVersion: SCHEMA_VERSION,
|
|
248
|
+
hooks: value.hooks,
|
|
249
|
+
locale: value.locale,
|
|
250
|
+
stateDir: join(paths.launchDirectory, STATE_DIRECTORY),
|
|
251
|
+
prefsPath: join(resolve(paths.stateRoot), PREFERENCES_FILE),
|
|
252
|
+
}),
|
|
253
|
+
);
|
|
254
|
+
if (parsed === null) throw new Error('codex_hooks_session_invalid');
|
|
255
|
+
return JSON.stringify(parsed);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Parse the session value inside a hook process; null when absent or invalid,
|
|
260
|
+
* so the hook does nothing.
|
|
261
|
+
* @param {string | undefined} raw
|
|
262
|
+
* @returns {GuardrailsSession | null}
|
|
263
|
+
*/
|
|
264
|
+
export function parseGuardrailsSession(raw) {
|
|
265
|
+
if (raw === undefined || raw === '' || Buffer.byteLength(raw, 'utf8') > MAX_VALUE_BYTES)
|
|
266
|
+
return null;
|
|
267
|
+
/** @type {unknown} */
|
|
268
|
+
let value;
|
|
269
|
+
try {
|
|
270
|
+
value = JSON.parse(raw);
|
|
271
|
+
} catch {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
if (
|
|
275
|
+
!isRecord(value) ||
|
|
276
|
+
Object.keys(value).sort().join(',') !== 'hooks,locale,prefsPath,schemaVersion,stateDir' ||
|
|
277
|
+
value.schemaVersion !== SCHEMA_VERSION ||
|
|
278
|
+
!isLocale(value.locale) ||
|
|
279
|
+
!isCleanAbsolutePath(value.stateDir) ||
|
|
280
|
+
!isCleanAbsolutePath(value.prefsPath)
|
|
281
|
+
)
|
|
282
|
+
return null;
|
|
283
|
+
const hooks = codexHookIds(value.hooks);
|
|
284
|
+
if (hooks === null) return null;
|
|
285
|
+
return {
|
|
286
|
+
schemaVersion: SCHEMA_VERSION,
|
|
287
|
+
hooks,
|
|
288
|
+
locale: value.locale,
|
|
289
|
+
stateDir: value.stateDir,
|
|
290
|
+
prefsPath: value.prefsPath,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* @typedef {object} CodexHooksSummary
|
|
296
|
+
* @property {{ total: number, trusted: number, untrusted: number, modified: number, disabled: number, missing: number }} handlers
|
|
297
|
+
* Every AISAC hook Codex was given, by what `hooks/list` reports.
|
|
298
|
+
* @property {string[]} on Enabled guardrails whose hooks are all trusted and on.
|
|
299
|
+
* @property {string[]} review Enabled guardrails with a hook that waits for review in `/hooks`.
|
|
300
|
+
* @property {string[]} off Enabled guardrails switched off in Codex (`/hooks` or config.toml).
|
|
301
|
+
* @property {string[]} missing Enabled guardrails Codex did not load.
|
|
302
|
+
*/
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* What `hooks/list` says about the AISAC hooks. A guardrail counts as on only
|
|
306
|
+
* when every one of its hooks is trusted and enabled (spec FR6: an untrusted
|
|
307
|
+
* guardrail is never reported as on).
|
|
308
|
+
* @param {unknown} listed The `hooks/list` result.
|
|
309
|
+
* @param {HookCommandPaths} paths
|
|
310
|
+
* @param {string[]} enabled The guardrails the user has on.
|
|
311
|
+
* @returns {CodexHooksSummary}
|
|
312
|
+
*/
|
|
313
|
+
export function summarizeCodexHooks(listed, paths, enabled) {
|
|
314
|
+
const rows = (isRecord(listed) && Array.isArray(listed.data) ? listed.data : []).flatMap(
|
|
315
|
+
(entry) => (isRecord(entry) && Array.isArray(entry.hooks) ? entry.hooks : []),
|
|
316
|
+
);
|
|
317
|
+
/** @type {Map<string, Record<string, unknown>>} */
|
|
318
|
+
const byCommand = new Map();
|
|
319
|
+
for (const row of rows)
|
|
320
|
+
if (isRecord(row) && row.source === 'sessionFlags' && typeof row.command === 'string')
|
|
321
|
+
byCommand.set(`${String(row.eventName)}\u0000${row.command}`, row);
|
|
322
|
+
const handlers = codexHookHandlers(paths);
|
|
323
|
+
const counts = {
|
|
324
|
+
total: handlers.length,
|
|
325
|
+
trusted: 0,
|
|
326
|
+
untrusted: 0,
|
|
327
|
+
modified: 0,
|
|
328
|
+
disabled: 0,
|
|
329
|
+
missing: 0,
|
|
330
|
+
};
|
|
331
|
+
/** @type {Map<string, 'on' | 'review' | 'off' | 'missing'>} */
|
|
332
|
+
const states = new Map();
|
|
333
|
+
const rank = { on: 0, off: 1, review: 2, missing: 3 };
|
|
334
|
+
for (const handler of handlers) {
|
|
335
|
+
const row = byCommand.get(`${LISTED_EVENT[handler.event]}\u0000${handler.command}`);
|
|
336
|
+
/** @type {'on' | 'review' | 'off' | 'missing'} */
|
|
337
|
+
let state;
|
|
338
|
+
if (row === undefined) {
|
|
339
|
+
counts.missing += 1;
|
|
340
|
+
state = 'missing';
|
|
341
|
+
} else if (row.trustStatus === 'untrusted' || row.trustStatus === 'modified') {
|
|
342
|
+
counts[row.trustStatus] += 1;
|
|
343
|
+
state = 'review';
|
|
344
|
+
} else if (row.trustStatus !== 'trusted' && row.trustStatus !== 'managed') {
|
|
345
|
+
counts.untrusted += 1;
|
|
346
|
+
state = 'review';
|
|
347
|
+
} else if (row.enabled === false) {
|
|
348
|
+
counts.trusted += 1;
|
|
349
|
+
counts.disabled += 1;
|
|
350
|
+
state = 'off';
|
|
351
|
+
} else {
|
|
352
|
+
counts.trusted += 1;
|
|
353
|
+
state = 'on';
|
|
354
|
+
}
|
|
355
|
+
const previous = states.get(handler.id);
|
|
356
|
+
if (previous === undefined || rank[state] > rank[previous]) states.set(handler.id, state);
|
|
357
|
+
}
|
|
358
|
+
const ids =
|
|
359
|
+
codexHookIds([
|
|
360
|
+
...new Set(enabled.filter((id) => hookById(id)?.clients.includes('codex') === true)),
|
|
361
|
+
]) ?? [];
|
|
362
|
+
return {
|
|
363
|
+
handlers: counts,
|
|
364
|
+
on: ids.filter((id) => states.get(id) === 'on'),
|
|
365
|
+
review: ids.filter((id) => states.get(id) === 'review'),
|
|
366
|
+
off: ids.filter((id) => states.get(id) === 'off'),
|
|
367
|
+
missing: ids.filter((id) => states.get(id) === 'missing'),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* The doctor's one-word state for the AISAC hooks in Codex, worst first: a
|
|
373
|
+
* guardrail waiting for review outranks one Codex did not load, which outranks
|
|
374
|
+
* one switched off in Codex.
|
|
375
|
+
* @param {CodexHooksSummary} summary
|
|
376
|
+
* @returns {'needs_review' | 'not_loaded' | 'off_in_codex' | 'on'}
|
|
377
|
+
*/
|
|
378
|
+
export function codexHooksStatus(summary) {
|
|
379
|
+
if (summary.review.length > 0) return 'needs_review';
|
|
380
|
+
if (summary.missing.length > 0) return 'not_loaded';
|
|
381
|
+
if (summary.off.length > 0) return 'off_in_codex';
|
|
382
|
+
return 'on';
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** @param {number} count */
|
|
386
|
+
function guardrails(count) {
|
|
387
|
+
return `${count} guardrail${count === 1 ? '' : 's'}`;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* The launch line for Codex. With no summary (the listing failed), it says the
|
|
392
|
+
* guardrails were handed to Codex and names the review, never "on".
|
|
393
|
+
* @param {number} enabledCount
|
|
394
|
+
* @param {CodexHooksSummary | null} summary
|
|
395
|
+
*/
|
|
396
|
+
export function codexHooksLine(enabledCount, summary) {
|
|
397
|
+
const change = '(aisac hooks to change them)';
|
|
398
|
+
if (summary === null)
|
|
399
|
+
return `AISAC Engineering: ${guardrails(enabledCount)} loaded for Codex; Codex runs them only after you approve the AISAC hooks once in /hooks ${change}.`;
|
|
400
|
+
const total =
|
|
401
|
+
summary.on.length + summary.review.length + summary.off.length + summary.missing.length;
|
|
402
|
+
if (summary.on.length === total) return `AISAC Engineering: ${guardrails(total)} on ${change}.`;
|
|
403
|
+
const parts = [`AISAC Engineering: ${summary.on.length} of ${guardrails(total)} on`];
|
|
404
|
+
if (summary.review.length > 0)
|
|
405
|
+
parts.push(
|
|
406
|
+
`${summary.review.length} wait for your review: open /hooks in Codex and approve the AISAC hooks`,
|
|
407
|
+
);
|
|
408
|
+
if (summary.off.length > 0) parts.push(`${summary.off.length} switched off in Codex (/hooks)`);
|
|
409
|
+
if (summary.missing.length > 0) parts.push(`${summary.missing.length} not loaded by Codex`);
|
|
410
|
+
return `${parts.join('; ')} ${change}.`;
|
|
411
|
+
}
|