@aisac/cli 0.0.0-stage → 0.4.0-beta.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 +159 -2
- package/dist/assets/claude/.claude-plugin/plugin.json +147 -0
- package/dist/assets/claude/hooks/context-compaction.ts +6930 -0
- package/dist/assets/claude/hooks/hooks.json +3 -0
- package/dist/assets/claude/hooks/native-host-contract-runtime.ts +18 -0
- package/dist/assets/claude/hooks/native-host-contract.test.ts +51 -0
- package/dist/assets/claude/hooks/provider-window.js +263 -0
- package/dist/assets/claude/hooks/state-fitting.d.mts +47 -0
- package/dist/assets/claude/hooks/state-fitting.mjs +324 -0
- package/dist/assets/codex-context-compaction.mjs +4689 -0
- package/dist/assets/context-selection-fitting.mjs +194 -0
- package/dist/assets/context-state-fitting.mjs +324 -0
- package/dist/assets/context-telemetry-reporter.mjs +305 -0
- package/dist/assets/jev-paid-pilot-terminal.mjs +1066 -0
- package/dist/claude-checkpoint.mjs +1338 -0
- package/dist/claude-compatibility.mjs +506 -0
- package/dist/claude-observation.mjs +1338 -0
- package/dist/cli.mjs +736 -0
- package/dist/codex-compatibility.mjs +481 -0
- package/dist/codex-diagnostics.mjs +447 -0
- package/dist/codex-permissions.mjs +590 -0
- package/dist/codex-protocol-fingerprint.json +131 -0
- package/dist/context-telemetry.mjs +257 -0
- package/dist/engineering.mjs +190 -0
- package/dist/launch.mjs +646 -0
- package/dist/mcp.mjs +962 -0
- package/dist/monitor.mjs +133 -0
- package/dist/package.json +5 -0
- package/dist/platform.mjs +126 -0
- package/dist/policy.mjs +218 -0
- package/dist/state.mjs +408 -0
- package/dist/telemetry-report.mjs +133 -0
- package/package.json +24 -4
package/dist/monitor.mjs
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @ts-check
|
|
3
|
+
|
|
4
|
+
import { access } from 'node:fs/promises';
|
|
5
|
+
import { constants } from 'node:fs';
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import {
|
|
10
|
+
CODEX_APP_SERVER_PROFILE,
|
|
11
|
+
CODEX_LAUNCH_ENVELOPE,
|
|
12
|
+
ownedAppServerConfigArgs,
|
|
13
|
+
parseCodexLaunchEnvelope,
|
|
14
|
+
} from './codex-permissions.mjs';
|
|
15
|
+
|
|
16
|
+
const root = dirname(fileURLToPath(import.meta.url));
|
|
17
|
+
const endpoint = process.env.AIBRAIN_MCP_URL?.trim();
|
|
18
|
+
const token = process.env.AIBRAIN_MCP_TOKEN?.trim();
|
|
19
|
+
if (!endpoint || !token) throw new Error('aibrain_monitor_auth_config_missing');
|
|
20
|
+
const parsed = new URL(endpoint);
|
|
21
|
+
if (
|
|
22
|
+
parsed.protocol !== 'https:' &&
|
|
23
|
+
!(
|
|
24
|
+
parsed.protocol === 'http:' &&
|
|
25
|
+
['127.0.0.1', 'localhost', '::1', '[::1]'].includes(parsed.hostname)
|
|
26
|
+
)
|
|
27
|
+
)
|
|
28
|
+
throw new Error('aibrain_monitor_endpoint_invalid');
|
|
29
|
+
if (parsed.username || parsed.password || parsed.hash)
|
|
30
|
+
throw new Error('aibrain_monitor_endpoint_credentials');
|
|
31
|
+
if (parsed.search) throw new Error('aibrain_monitor_endpoint_query');
|
|
32
|
+
const canonical = join(root, 'assets', 'codex-context-compaction.mjs');
|
|
33
|
+
await access(canonical, constants.R_OK);
|
|
34
|
+
const launchEnvelope = parseCodexLaunchEnvelope(process.env[CODEX_LAUNCH_ENVELOPE]);
|
|
35
|
+
const policyText = process.env.CODEX_CONTEXT_POLICY_JSON;
|
|
36
|
+
let policy;
|
|
37
|
+
if (policyText === undefined) {
|
|
38
|
+
policy = null;
|
|
39
|
+
} else {
|
|
40
|
+
if (Buffer.byteLength(policyText, 'utf8') > 8 * 1024)
|
|
41
|
+
throw new Error('aibrain_monitor_policy_too_large');
|
|
42
|
+
try {
|
|
43
|
+
policy = JSON.parse(policyText);
|
|
44
|
+
} catch {
|
|
45
|
+
throw new Error('aibrain_monitor_policy_invalid');
|
|
46
|
+
}
|
|
47
|
+
const allowed = new Set([
|
|
48
|
+
'schemaVersion',
|
|
49
|
+
'compactAtPercent',
|
|
50
|
+
'keepThreshold',
|
|
51
|
+
'preserveRecentMessages',
|
|
52
|
+
'maxStateTokens',
|
|
53
|
+
'maxRequestTokens',
|
|
54
|
+
'goal',
|
|
55
|
+
]);
|
|
56
|
+
if (
|
|
57
|
+
policy === null ||
|
|
58
|
+
typeof policy !== 'object' ||
|
|
59
|
+
Array.isArray(policy) ||
|
|
60
|
+
Object.keys(policy).some((key) => !allowed.has(key)) ||
|
|
61
|
+
policy.schemaVersion !== 2 ||
|
|
62
|
+
!Number.isFinite(policy.compactAtPercent) ||
|
|
63
|
+
policy.compactAtPercent < 1 ||
|
|
64
|
+
policy.compactAtPercent > 95 ||
|
|
65
|
+
!Number.isFinite(policy.keepThreshold) ||
|
|
66
|
+
policy.keepThreshold < 0 ||
|
|
67
|
+
policy.keepThreshold > 1 ||
|
|
68
|
+
!Number.isSafeInteger(policy.preserveRecentMessages) ||
|
|
69
|
+
policy.preserveRecentMessages < 1 ||
|
|
70
|
+
policy.preserveRecentMessages > 100 ||
|
|
71
|
+
!Number.isSafeInteger(policy.maxStateTokens) ||
|
|
72
|
+
policy.maxStateTokens < 1000 ||
|
|
73
|
+
policy.maxStateTokens > 25000 ||
|
|
74
|
+
!Number.isSafeInteger(policy.maxRequestTokens) ||
|
|
75
|
+
policy.maxRequestTokens < 1000 ||
|
|
76
|
+
policy.maxRequestTokens > 30000 ||
|
|
77
|
+
policy.maxRequestTokens <= policy.maxStateTokens + 256 ||
|
|
78
|
+
(policy.goal !== undefined && typeof policy.goal !== 'string')
|
|
79
|
+
)
|
|
80
|
+
throw new Error('aibrain_monitor_policy_invalid');
|
|
81
|
+
}
|
|
82
|
+
/** @type {NodeJS.ProcessEnv} */
|
|
83
|
+
const env = {
|
|
84
|
+
...process.env,
|
|
85
|
+
AI_BRAIN_MCP_SERVER: 'aibrain_context',
|
|
86
|
+
CODEX_RECOVERY_MCP_URL: parsed.toString(),
|
|
87
|
+
CODEX_RECOVERY_MCP_TOKEN: token,
|
|
88
|
+
CODEX_CONTEXT_COMPACT_AT: String(policy?.compactAtPercent ?? 85),
|
|
89
|
+
};
|
|
90
|
+
delete env[CODEX_LAUNCH_ENVELOPE];
|
|
91
|
+
delete env[CODEX_APP_SERVER_PROFILE];
|
|
92
|
+
if (launchEnvelope?.profile !== undefined) env[CODEX_APP_SERVER_PROFILE] = launchEnvelope.profile;
|
|
93
|
+
if (policy !== null) env.CODEX_CONTEXT_POLICY_JSON = JSON.stringify(policy);
|
|
94
|
+
else delete env.CODEX_CONTEXT_POLICY_JSON;
|
|
95
|
+
delete env.JEV_API_KEY;
|
|
96
|
+
delete env.TYPESAFE_API_KEY;
|
|
97
|
+
const child = spawn(
|
|
98
|
+
process.execPath,
|
|
99
|
+
[
|
|
100
|
+
canonical,
|
|
101
|
+
'--listen',
|
|
102
|
+
'stdio://',
|
|
103
|
+
'-c',
|
|
104
|
+
'mcp_servers.aibrain_context.enabled=true',
|
|
105
|
+
'-c',
|
|
106
|
+
'mcp_servers.aibrain_context.required=true',
|
|
107
|
+
'-c',
|
|
108
|
+
`mcp_servers.aibrain_context.url=${parsed.toString()}`,
|
|
109
|
+
'-c',
|
|
110
|
+
'mcp_servers.aibrain_context.bearer_token_env_var="CODEX_RECOVERY_MCP_TOKEN"',
|
|
111
|
+
...(launchEnvelope === null ? [] : ownedAppServerConfigArgs(launchEnvelope)),
|
|
112
|
+
],
|
|
113
|
+
{ cwd: process.cwd(), env, stdio: 'inherit' },
|
|
114
|
+
);
|
|
115
|
+
child.on('error', () => process.exit(1));
|
|
116
|
+
/** @param {NodeJS.Signals} signal */
|
|
117
|
+
const forwardSignal = (signal) => {
|
|
118
|
+
if (child.exitCode === null) child.kill(signal);
|
|
119
|
+
};
|
|
120
|
+
const signalHandlers = {
|
|
121
|
+
SIGINT: () => forwardSignal('SIGINT'),
|
|
122
|
+
SIGTERM: () => forwardSignal('SIGTERM'),
|
|
123
|
+
SIGHUP: () => forwardSignal('SIGHUP'),
|
|
124
|
+
};
|
|
125
|
+
process.once('SIGINT', signalHandlers.SIGINT);
|
|
126
|
+
process.once('SIGTERM', signalHandlers.SIGTERM);
|
|
127
|
+
process.once('SIGHUP', signalHandlers.SIGHUP);
|
|
128
|
+
child.on('exit', (code, signal) => {
|
|
129
|
+
process.removeListener('SIGINT', signalHandlers.SIGINT);
|
|
130
|
+
process.removeListener('SIGTERM', signalHandlers.SIGTERM);
|
|
131
|
+
process.removeListener('SIGHUP', signalHandlers.SIGHUP);
|
|
132
|
+
process.exit(signal === null ? (code ?? 1) : 1);
|
|
133
|
+
});
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import { accessSync, constants, existsSync, statSync } from 'node:fs';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { delimiter, isAbsolute, join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
export function platformCheck() {
|
|
8
|
+
if (process.platform === 'win32')
|
|
9
|
+
return {
|
|
10
|
+
ok: false,
|
|
11
|
+
code: 'WINDOWS_NATIVE_UNSUPPORTED',
|
|
12
|
+
message: 'Run this beta inside WSL; native Windows launch is unsupported.',
|
|
13
|
+
};
|
|
14
|
+
if (process.platform !== 'linux')
|
|
15
|
+
return {
|
|
16
|
+
ok: false,
|
|
17
|
+
code: 'PLATFORM_UNSUPPORTED',
|
|
18
|
+
message: 'This beta supports Linux/WSL only.',
|
|
19
|
+
};
|
|
20
|
+
const major = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10);
|
|
21
|
+
if (!Number.isInteger(major) || major < 22)
|
|
22
|
+
return { ok: false, code: 'NODE_UNSUPPORTED', message: 'Node.js 22 or newer is required.' };
|
|
23
|
+
return { ok: true };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {NodeJS.ProcessEnv} [environment] */
|
|
27
|
+
export function captureLockPlatformCheck(environment = process.env) {
|
|
28
|
+
const platform = platformCheck();
|
|
29
|
+
if (!platform.ok) return platform;
|
|
30
|
+
if (resolveNative('flock', environment) === null)
|
|
31
|
+
return {
|
|
32
|
+
ok: false,
|
|
33
|
+
code: 'CODEX_CAPTURE_LOCK_BACKEND_UNAVAILABLE',
|
|
34
|
+
message: 'Codex capture requires util-linux flock on Linux/WSL.',
|
|
35
|
+
};
|
|
36
|
+
return { ok: true };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** @param {string} name @param {NodeJS.ProcessEnv} [environment] */
|
|
40
|
+
export function resolveNative(name, environment = process.env) {
|
|
41
|
+
if (!/^[A-Za-z0-9._+-]+$/u.test(name)) return null;
|
|
42
|
+
const pathValue = environment.PATH ?? '';
|
|
43
|
+
const candidates = isAbsolute(name)
|
|
44
|
+
? [name]
|
|
45
|
+
: pathValue
|
|
46
|
+
.split(delimiter)
|
|
47
|
+
.filter((directory) => directory.length > 0)
|
|
48
|
+
.map((directory) => join(directory, name));
|
|
49
|
+
for (const candidate of candidates) {
|
|
50
|
+
try {
|
|
51
|
+
if (!existsSync(candidate) || !statSync(candidate).isFile()) continue;
|
|
52
|
+
accessSync(candidate, constants.X_OK);
|
|
53
|
+
return candidate;
|
|
54
|
+
} catch {
|
|
55
|
+
// Continue through PATH without invoking a shell or trusting aliases.
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {string} executable @param {NodeJS.ProcessEnv} [environment] */
|
|
62
|
+
export function nativeVersion(executable, environment = process.env) {
|
|
63
|
+
/** @type {NodeJS.ProcessEnv} */
|
|
64
|
+
const safeEnvironment = { ...environment };
|
|
65
|
+
delete safeEnvironment.JEV_API_KEY;
|
|
66
|
+
delete safeEnvironment.TYPESAFE_API_KEY;
|
|
67
|
+
const result = spawnSync(executable, ['--version'], {
|
|
68
|
+
cwd: process.cwd(),
|
|
69
|
+
env: safeEnvironment,
|
|
70
|
+
encoding: 'utf8',
|
|
71
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
72
|
+
timeout: 10_000,
|
|
73
|
+
});
|
|
74
|
+
if (result.error || result.status !== 0) return '';
|
|
75
|
+
return (
|
|
76
|
+
String(result.stdout ?? '')
|
|
77
|
+
.split(/\r?\n/u, 1)[0]
|
|
78
|
+
?.trim() ?? ''
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** @param {'claude'|'codex'} client @param {string} version */
|
|
83
|
+
export function isTestedNativeVersion(client, version) {
|
|
84
|
+
const value = version.trim();
|
|
85
|
+
if (client === 'claude')
|
|
86
|
+
return /^(?:(?:claude(?:\s+code)?)\s+)?2\.1\.(?:294|295|296|299|300|301|302|303)(?:\s+\(Claude\s+Code\))?$/iu.test(
|
|
87
|
+
value,
|
|
88
|
+
);
|
|
89
|
+
return /^(?:codex(?:-cli)?\s+)?0\.16(?:1\.0|2\.0|2\.1|3\.0|4\.0)$/iu.test(value);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const TESTED_NATIVE_VERSIONS = Object.freeze({
|
|
93
|
+
claude: Object.freeze([
|
|
94
|
+
'2.1.294',
|
|
95
|
+
'2.1.295',
|
|
96
|
+
'2.1.296',
|
|
97
|
+
'2.1.299',
|
|
98
|
+
'2.1.300',
|
|
99
|
+
'2.1.301',
|
|
100
|
+
'2.1.302',
|
|
101
|
+
'2.1.303',
|
|
102
|
+
]),
|
|
103
|
+
codex: Object.freeze(['0.161.0', '0.162.0', '0.162.1', '0.163.0', '0.164.0']),
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
/** @param {'claude'|'codex'} client @param {string} version */
|
|
107
|
+
export function nativeVersionDiagnostic(client, version) {
|
|
108
|
+
const detected = version.trim();
|
|
109
|
+
const versionPattern =
|
|
110
|
+
client === 'claude'
|
|
111
|
+
? /^(?:(?:claude(?:\s+code)?)\s+)?(\d{1,3})\.(\d{1,3})\.(\d{1,3})(-[A-Za-z0-9.-]+)?(?:\s+\(Claude\s+Code\))?$/iu
|
|
112
|
+
: /^(?:codex(?:-cli)?\s+)?(\d{1,3})\.(\d{1,3})\.(\d{1,3})(-[A-Za-z0-9.-]+)?$/iu;
|
|
113
|
+
const versionMatch = detected.match(versionPattern);
|
|
114
|
+
const safeDetected = versionMatch
|
|
115
|
+
? `${versionMatch[1]}.${versionMatch[2]}.${versionMatch[3]}${versionMatch[4] ? '-prerelease' : ''}`
|
|
116
|
+
: 'unavailable';
|
|
117
|
+
const label = client === 'claude' ? 'Claude Code' : 'Codex CLI';
|
|
118
|
+
const tested = TESTED_NATIVE_VERSIONS[client].join(', ');
|
|
119
|
+
return `${client}_version_unverified: ${label} detected version ${safeDetected}; tested stable versions: ${tested}. Update AI Brain to a compatible version, then run aisac doctor --json or install a qualified stable native version.`;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** @param {'claude'|'codex'} client @param {string} version */
|
|
123
|
+
export function assertTestedNativeVersion(client, version) {
|
|
124
|
+
if (!isTestedNativeVersion(client, version))
|
|
125
|
+
throw new Error(nativeVersionDiagnostic(client, version));
|
|
126
|
+
}
|
package/dist/policy.mjs
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/** @typedef {'upstream' | 'conservative'} ContextProfile */
|
|
4
|
+
/** @typedef {'compatible' | 'read_only'} ToolPolicy */
|
|
5
|
+
|
|
6
|
+
/** @typedef {{
|
|
7
|
+
* profile: ContextProfile,
|
|
8
|
+
* compactAtPercent: number,
|
|
9
|
+
* keepThreshold: number,
|
|
10
|
+
* preserveRecentMessages: number,
|
|
11
|
+
* minReductionRatio: number,
|
|
12
|
+
* truncateHeadChars: number,
|
|
13
|
+
* maxStateTokens: number,
|
|
14
|
+
* maxRequestTokens: number,
|
|
15
|
+
* toolPolicy: ToolPolicy,
|
|
16
|
+
* goal?: string
|
|
17
|
+
* }} ContextPolicy */
|
|
18
|
+
|
|
19
|
+
export const POLICY_VERSION = 2;
|
|
20
|
+
export const MAX_GOAL_CHARS = 4000;
|
|
21
|
+
|
|
22
|
+
/** @type {Readonly<Record<ContextProfile, Omit<ContextPolicy, 'profile' | 'goal'>>>} */
|
|
23
|
+
export const PROFILE_DEFAULTS = Object.freeze({
|
|
24
|
+
upstream: Object.freeze({
|
|
25
|
+
compactAtPercent: 60,
|
|
26
|
+
keepThreshold: 0.5,
|
|
27
|
+
preserveRecentMessages: 6,
|
|
28
|
+
minReductionRatio: 0.25,
|
|
29
|
+
truncateHeadChars: 300,
|
|
30
|
+
maxStateTokens: 25_000,
|
|
31
|
+
maxRequestTokens: 30_000,
|
|
32
|
+
toolPolicy: 'compatible',
|
|
33
|
+
}),
|
|
34
|
+
conservative: Object.freeze({
|
|
35
|
+
compactAtPercent: 85,
|
|
36
|
+
keepThreshold: 0.2,
|
|
37
|
+
preserveRecentMessages: 6,
|
|
38
|
+
minReductionRatio: 0.25,
|
|
39
|
+
truncateHeadChars: 300,
|
|
40
|
+
maxStateTokens: 25_000,
|
|
41
|
+
maxRequestTokens: 30_000,
|
|
42
|
+
toolPolicy: 'read_only',
|
|
43
|
+
}),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
47
|
+
function record(value) {
|
|
48
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** @param {unknown} value @returns {value is ContextProfile} */
|
|
52
|
+
export function isProfile(value) {
|
|
53
|
+
return value === 'upstream' || value === 'conservative';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** @param {unknown} value @returns {value is ToolPolicy} */
|
|
57
|
+
export function isToolPolicy(value) {
|
|
58
|
+
return value === 'compatible' || value === 'read_only';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {number} value @param {number} min @param {number} max @param {string} name */
|
|
62
|
+
function finiteRange(value, min, max, name) {
|
|
63
|
+
if (!Number.isFinite(value) || value < min || value > max) throw new Error(`invalid_${name}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** @param {number} value @param {number} min @param {number} max @param {string} name */
|
|
67
|
+
function integerRange(value, min, max, name) {
|
|
68
|
+
if (!Number.isSafeInteger(value) || value < min || value > max)
|
|
69
|
+
throw new Error(`invalid_${name}`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @param {unknown} value @param {string} name */
|
|
73
|
+
function boundedGoal(value, name) {
|
|
74
|
+
if (value === undefined) return undefined;
|
|
75
|
+
if (
|
|
76
|
+
typeof value !== 'string' ||
|
|
77
|
+
value.length > MAX_GOAL_CHARS ||
|
|
78
|
+
/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(value)
|
|
79
|
+
)
|
|
80
|
+
throw new Error(`invalid_${name}`);
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** @param {ContextProfile} profile @param {Partial<Omit<ContextPolicy, 'profile'>>} overrides @param {string | undefined} goal */
|
|
85
|
+
export function makePolicy(profile, overrides = {}, goal = overrides.goal) {
|
|
86
|
+
if (!isProfile(profile)) throw new Error('invalid_context_profile');
|
|
87
|
+
const base = PROFILE_DEFAULTS[profile];
|
|
88
|
+
const policy = {
|
|
89
|
+
profile,
|
|
90
|
+
compactAtPercent: overrides.compactAtPercent ?? base.compactAtPercent,
|
|
91
|
+
keepThreshold: overrides.keepThreshold ?? base.keepThreshold,
|
|
92
|
+
preserveRecentMessages: overrides.preserveRecentMessages ?? base.preserveRecentMessages,
|
|
93
|
+
minReductionRatio: overrides.minReductionRatio ?? base.minReductionRatio,
|
|
94
|
+
truncateHeadChars: overrides.truncateHeadChars ?? base.truncateHeadChars,
|
|
95
|
+
maxStateTokens: overrides.maxStateTokens ?? base.maxStateTokens,
|
|
96
|
+
maxRequestTokens: overrides.maxRequestTokens ?? base.maxRequestTokens,
|
|
97
|
+
toolPolicy: overrides.toolPolicy ?? base.toolPolicy,
|
|
98
|
+
...(goal === undefined ? {} : { goal }),
|
|
99
|
+
};
|
|
100
|
+
finiteRange(policy.compactAtPercent, 1, 95, 'compact_at');
|
|
101
|
+
finiteRange(policy.keepThreshold, 0, 1, 'keep_threshold');
|
|
102
|
+
integerRange(policy.preserveRecentMessages, 1, 100, 'preserve_recent');
|
|
103
|
+
finiteRange(policy.minReductionRatio, 0, 1, 'min_reduction');
|
|
104
|
+
integerRange(policy.truncateHeadChars, 0, 4096, 'truncate_head_chars');
|
|
105
|
+
integerRange(policy.maxStateTokens, 1000, 25_000, 'max_state_tokens');
|
|
106
|
+
integerRange(policy.maxRequestTokens, 1000, 30_000, 'max_request_tokens');
|
|
107
|
+
if (policy.maxRequestTokens <= policy.maxStateTokens + 256)
|
|
108
|
+
throw new Error('max_request_tokens_must_exceed_state_plus_256');
|
|
109
|
+
if (!isToolPolicy(policy.toolPolicy)) throw new Error('invalid_tool_policy');
|
|
110
|
+
boundedGoal(policy.goal, 'goal');
|
|
111
|
+
return /** @type {ContextPolicy} */ (policy);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** @param {unknown} value @returns {value is ContextPolicy} */
|
|
115
|
+
export function isValidPolicy(value) {
|
|
116
|
+
if (!record(value) || !isProfile(value.profile)) return false;
|
|
117
|
+
const required = [
|
|
118
|
+
'profile',
|
|
119
|
+
'compactAtPercent',
|
|
120
|
+
'keepThreshold',
|
|
121
|
+
'preserveRecentMessages',
|
|
122
|
+
'minReductionRatio',
|
|
123
|
+
'truncateHeadChars',
|
|
124
|
+
'maxStateTokens',
|
|
125
|
+
'maxRequestTokens',
|
|
126
|
+
'toolPolicy',
|
|
127
|
+
];
|
|
128
|
+
if (required.some((key) => !Object.hasOwn(value, key))) return false;
|
|
129
|
+
if (
|
|
130
|
+
typeof value.compactAtPercent !== 'number' ||
|
|
131
|
+
typeof value.keepThreshold !== 'number' ||
|
|
132
|
+
typeof value.preserveRecentMessages !== 'number' ||
|
|
133
|
+
typeof value.minReductionRatio !== 'number' ||
|
|
134
|
+
typeof value.truncateHeadChars !== 'number' ||
|
|
135
|
+
typeof value.maxStateTokens !== 'number' ||
|
|
136
|
+
typeof value.maxRequestTokens !== 'number' ||
|
|
137
|
+
!isToolPolicy(value.toolPolicy)
|
|
138
|
+
)
|
|
139
|
+
return false;
|
|
140
|
+
if (Object.hasOwn(value, 'goal') && typeof value.goal !== 'string') return false;
|
|
141
|
+
try {
|
|
142
|
+
makePolicy(
|
|
143
|
+
value.profile,
|
|
144
|
+
/** @type {Partial<Omit<ContextPolicy, 'profile'>>} */ (value),
|
|
145
|
+
typeof value.goal === 'string' ? value.goal : undefined,
|
|
146
|
+
);
|
|
147
|
+
const keys = new Set([
|
|
148
|
+
'profile',
|
|
149
|
+
'compactAtPercent',
|
|
150
|
+
'keepThreshold',
|
|
151
|
+
'preserveRecentMessages',
|
|
152
|
+
'minReductionRatio',
|
|
153
|
+
'truncateHeadChars',
|
|
154
|
+
'maxStateTokens',
|
|
155
|
+
'maxRequestTokens',
|
|
156
|
+
'toolPolicy',
|
|
157
|
+
'goal',
|
|
158
|
+
]);
|
|
159
|
+
return Object.keys(value).every((key) => keys.has(key));
|
|
160
|
+
} catch {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** @param {ContextPolicy} policy */
|
|
166
|
+
export function compactWireOptions(policy) {
|
|
167
|
+
return {
|
|
168
|
+
keep_threshold: policy.keepThreshold,
|
|
169
|
+
preserve_recent_messages: policy.preserveRecentMessages,
|
|
170
|
+
min_reduction_ratio: policy.minReductionRatio,
|
|
171
|
+
truncate_head_chars: policy.truncateHeadChars,
|
|
172
|
+
max_state_tokens: policy.maxStateTokens,
|
|
173
|
+
max_request_tokens: policy.maxRequestTokens,
|
|
174
|
+
tool_policy: policy.toolPolicy,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** @param {ContextPolicy} policy */
|
|
179
|
+
export function selectionWireOptions(policy) {
|
|
180
|
+
return {
|
|
181
|
+
keep_threshold: policy.keepThreshold,
|
|
182
|
+
preserve_recent_items: policy.preserveRecentMessages,
|
|
183
|
+
max_state_tokens: policy.maxStateTokens,
|
|
184
|
+
max_request_tokens: policy.maxRequestTokens,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** @param {ContextPolicy} policy */
|
|
189
|
+
export function codexPolicyJson(policy) {
|
|
190
|
+
const serialized = JSON.stringify({
|
|
191
|
+
schemaVersion: POLICY_VERSION,
|
|
192
|
+
compactAtPercent: policy.compactAtPercent,
|
|
193
|
+
keepThreshold: policy.keepThreshold,
|
|
194
|
+
preserveRecentMessages: policy.preserveRecentMessages,
|
|
195
|
+
maxStateTokens: policy.maxStateTokens,
|
|
196
|
+
maxRequestTokens: policy.maxRequestTokens,
|
|
197
|
+
...(policy.goal === undefined ? {} : { goal: policy.goal }),
|
|
198
|
+
});
|
|
199
|
+
if (Buffer.byteLength(serialized, 'utf8') > 8 * 1024)
|
|
200
|
+
throw new Error('context_policy_too_large_for_codex_monitor');
|
|
201
|
+
return serialized;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** @param {ContextPolicy} policy */
|
|
205
|
+
export function publicPolicy(policy) {
|
|
206
|
+
return {
|
|
207
|
+
profile: policy.profile,
|
|
208
|
+
compactAtPercent: policy.compactAtPercent,
|
|
209
|
+
keepThreshold: policy.keepThreshold,
|
|
210
|
+
preserveRecentMessages: policy.preserveRecentMessages,
|
|
211
|
+
minReductionRatio: policy.minReductionRatio,
|
|
212
|
+
truncateHeadChars: policy.truncateHeadChars,
|
|
213
|
+
maxStateTokens: policy.maxStateTokens,
|
|
214
|
+
maxRequestTokens: policy.maxRequestTokens,
|
|
215
|
+
toolPolicy: policy.toolPolicy,
|
|
216
|
+
goalPresent: policy.goal !== undefined,
|
|
217
|
+
};
|
|
218
|
+
}
|