osuite 2.14.0 → 2.15.0
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/BUSINESS_EVIDENCE.md +77 -0
- package/GOVERNED_RECOVERY.md +8 -0
- package/GOVERNED_TOOLS.md +6 -0
- package/README.md +4 -0
- package/business-evidence.mjs +139 -0
- package/cli.js +71 -23
- package/codexExec.mjs +120 -0
- package/codexTrust.mjs +107 -0
- package/credentials.js +1 -238
- package/governed-tools/authority.mjs +10 -8
- package/governed-tools/contract.mjs +4 -1
- package/governed-tools/executor.mjs +27 -16
- package/governed-tools/journal.mjs +12 -5
- package/nativeDoctor.mjs +5 -6
- package/package.json +8 -1
- package/projectHooks.js +21 -4
- package/runtime/admission.mjs +27 -15
- package/runtime/coding-agent-facts.mjs +192 -0
- package/runtime/config.mjs +21 -12
- package/runtime/context.mjs +12 -3
- package/runtime/credentials.mjs +314 -0
- package/runtime/hook.mjs +30 -3
- package/runtime/outcome.mjs +17 -6
- package/runtime/protocol.mjs +17 -1
- package/runtime/shell.mjs +16 -2
package/projectHooks.js
CHANGED
|
@@ -6,8 +6,11 @@ import path from 'node:path';
|
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
7
|
import { spawn } from 'node:child_process';
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { inspectCredentialFile, readCredentialFile } from './runtime/credentials.mjs';
|
|
9
10
|
|
|
10
11
|
const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop|session)\.(?:py|mjs)/;
|
|
12
|
+
const CODEX_RUNTIME_TAG = / --osuite-hook-version=[a-f0-9]{16}$/;
|
|
13
|
+
const withoutCodexTag = command => String(command || '').replace(CODEX_RUNTIME_TAG, '');
|
|
11
14
|
|
|
12
15
|
export const RUNTIME_HOOKS = {
|
|
13
16
|
claude: {
|
|
@@ -112,6 +115,12 @@ export function mergeHookSettings(existingText, templateText) {
|
|
|
112
115
|
const requested = (Array.isArray(groups) ? groups : []).flatMap(group => group.hooks || []);
|
|
113
116
|
const next = current.map(group => ({ ...group, hooks: (group.hooks || []).map(existing => {
|
|
114
117
|
const replacement = requested.find(hook => sameHook(existing, hook));
|
|
118
|
+
if (replacement && CODEX_RUNTIME_TAG.test(replacement.command) && existing.command !== replacement.command
|
|
119
|
+
&& withoutCodexTag(existing.command) === withoutCodexTag(replacement.command)
|
|
120
|
+
&& (existing.commandWindows === undefined || withoutCodexTag(existing.commandWindows) === withoutCodexTag(replacement.commandWindows))) {
|
|
121
|
+
migrated.push({ event, matcher: group.matcher, command: replacement.command });
|
|
122
|
+
return { ...existing, command: replacement.command, commandWindows: replacement.commandWindows };
|
|
123
|
+
}
|
|
115
124
|
if (!replacement || !hookScriptName(existing.command).endsWith('.py') || !hookScriptName(replacement.command).endsWith('.mjs')) return existing;
|
|
116
125
|
const script = hookScriptName(existing.command);
|
|
117
126
|
const stock = [`python3 .claude/hooks/${script}`, `python3 .codex/hooks/${script}`,
|
|
@@ -236,12 +245,19 @@ export function buildNodeRuntimeBootstrap(runtime, bootstrap = {}, { projectRoot
|
|
|
236
245
|
const shellQuote = value => `'${String(value).replace(/'/g, "'\\''")}'`;
|
|
237
246
|
const events = { PreToolUse: 'pretool', PostToolUse: 'posttool', SessionStart: 'session', Stop: 'stop' };
|
|
238
247
|
const settings = { hooks: {} };
|
|
248
|
+
const runtimeHash = crypto.createHash('sha256').update(JSON.stringify(Object.entries(files)
|
|
249
|
+
.filter(([name]) => name.startsWith(`${directory}/runtime/`)))).digest('hex');
|
|
239
250
|
for (const [event, script] of Object.entries(events)) {
|
|
240
251
|
files[`${directory}/hooks/osuite_${script}.mjs`] = `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runHookCli } from '../runtime/hook.mjs';\nawait runHookCli({ host: ${literal(host)}, runtimeId: ${literal(runtimeId)}, installDir: fileURLToPath(new URL('..', import.meta.url)), event: ${literal(event)} });\n`;
|
|
241
252
|
const absolute = path.join(path.resolve(projectRoot), directory, `hooks/osuite_${script}.mjs`);
|
|
242
253
|
const handler = { type: 'command', command: `node ${shellQuote(absolute)}`, timeout: 60 };
|
|
243
254
|
if (host === 'claude' && event === 'PreToolUse') handler.onFailure = 'block';
|
|
244
|
-
if (host === 'codex')
|
|
255
|
+
if (host === 'codex') {
|
|
256
|
+
const hash = crypto.createHash('sha256').update(runtimeHash).update(files[`${directory}/hooks/osuite_${script}.mjs`]).digest('hex').slice(0, 16);
|
|
257
|
+
const tag = ` --osuite-hook-version=${hash}`;
|
|
258
|
+
handler.command += tag;
|
|
259
|
+
handler.commandWindows = `node "${absolute.replace(/"/g, '""')}"${tag}`;
|
|
260
|
+
}
|
|
245
261
|
settings.hooks[event] = [{ hooks: [handler] }];
|
|
246
262
|
}
|
|
247
263
|
if (host === 'claude') settings.hooks.PostToolUseFailure = settings.hooks.PostToolUse;
|
|
@@ -632,7 +648,7 @@ function managedFileStatus(projectRoot, relativePath, expected) {
|
|
|
632
648
|
function isManagedHookCommand(command, projectRoot, relativePath) {
|
|
633
649
|
if (typeof command !== 'string') return false;
|
|
634
650
|
const executable = relativePath.endsWith('.py') ? 'python3' : 'node';
|
|
635
|
-
const text = command.trim();
|
|
651
|
+
const text = (relativePath.startsWith('.codex/') ? withoutCodexTag(command) : command).trim();
|
|
636
652
|
// Recognize the former stock Codex template without evaluating its substitution.
|
|
637
653
|
if (relativePath.startsWith('.codex/') && executable === 'python3'
|
|
638
654
|
&& text === `python3 "$(git rev-parse --show-toplevel)/${relativePath}"`) return true;
|
|
@@ -825,7 +841,8 @@ export function parseDotenv(body) {
|
|
|
825
841
|
|
|
826
842
|
/** The credentials the installed hook will use: shell values first, then its own .env. */
|
|
827
843
|
export function hookCredentials(projectRoot, installation, shellEnv = process.env) {
|
|
828
|
-
const
|
|
844
|
+
const relativePath = `${installation.installDir}/.env`;
|
|
845
|
+
const dotenv = parseDotenv(readCredentialFile(projectRoot, relativePath, { maxBytes: 65536 }));
|
|
829
846
|
const env = { ...dotenv };
|
|
830
847
|
Object.entries(shellEnv || {}).forEach(([key, value]) => {
|
|
831
848
|
if (value !== undefined) env[key] = value;
|
|
@@ -833,7 +850,7 @@ export function hookCredentials(projectRoot, installation, shellEnv = process.en
|
|
|
833
850
|
return {
|
|
834
851
|
baseUrl: String(env.OSUITE_BASE_URL || env.DASHCLAW_BASE_URL || '').replace(/\/$/, ''),
|
|
835
852
|
apiKey: String(env.OSUITE_API_KEY || env.DASHCLAW_API_KEY || ''),
|
|
836
|
-
envFile:
|
|
853
|
+
envFile: inspectCredentialFile(projectRoot, relativePath).storagePath,
|
|
837
854
|
hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || (installation.runtime === 'cursor' ? 'observe' : 'enforce')),
|
|
838
855
|
};
|
|
839
856
|
}
|
package/runtime/admission.mjs
CHANGED
|
@@ -139,8 +139,9 @@ function installCheck(payload, context) {
|
|
|
139
139
|
return { authorized: false, decision: payload.decision.decision, installCheck: true, reason: 'approval_not_requested', response: payload };
|
|
140
140
|
}
|
|
141
141
|
|
|
142
|
-
export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(),
|
|
143
|
-
|
|
142
|
+
export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(),
|
|
143
|
+
beforeRelease = async () => true, rememberOperation } = {}) {
|
|
144
|
+
const guard = await api.request('POST', '/api/guard', rememberOperation ? { ...context, hook_dispatch: 'v1' } : context);
|
|
144
145
|
if (!guard.ok) {
|
|
145
146
|
// Rejection, bad evidence and unknown errors are not availability failures.
|
|
146
147
|
if (!isTransientFailure(guard)) return closed('guard_rejected', { rejectedStatus: guard.status });
|
|
@@ -153,27 +154,38 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
|
|
|
153
154
|
if (!DECISIONS.has(requestedDecision)) return closed('unsupported_guard_decision');
|
|
154
155
|
const rollout = rolloutAuthority(guard.body, context, config);
|
|
155
156
|
if (!rollout.valid) return closed('rule_rollout_binding_invalid');
|
|
156
|
-
const
|
|
157
|
+
const operationId = rememberOperation && /^hact_[a-f0-9]{64}$/.test(guard.body.hook_action_id || '') ? guard.body.hook_action_id : null;
|
|
158
|
+
if (operationId && !rememberOperation(operationId)) return closed('hook_operation_binding_changed', { actionId: operationId });
|
|
159
|
+
const binding = operationId ? { action_id: operationId, hook_dispatch: 'v1' } : {};
|
|
160
|
+
const finish = result => ({
|
|
161
|
+
...result,
|
|
162
|
+
...(operationId ? { hookOperationId: operationId } : {}),
|
|
163
|
+
...(rollout.binding ? { observeOnly: false, ruleRolloutBinding: rollout.binding } : {}),
|
|
164
|
+
});
|
|
165
|
+
const create = fields => api.request('POST', '/api/actions', { ...context, ...binding, ...fields });
|
|
157
166
|
if (requestedDecision === 'block') {
|
|
158
167
|
// Observation still persists the would-block result, but never calls it authority.
|
|
159
168
|
const observeOnly = config.mode === 'observe' && !rollout.binding;
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
169
|
+
let actionId = null;
|
|
170
|
+
if (observeOnly || operationId) {
|
|
171
|
+
const recorded = await create(operationId
|
|
172
|
+
? { status: 'cancelled', timestamp_end: new Date().toISOString(), error_message: 'CLIENT_BLOCKED' }
|
|
173
|
+
: { status: 'blocked' });
|
|
174
|
+
if (safeId(recorded.body?.action_id) && (!operationId || recorded.body.action_id === operationId)) actionId = recorded.body.action_id;
|
|
175
|
+
if (!actionId && observeOnly && !recorded.ok && (!isTransientFailure(recorded) || config.guardFailureMode !== 'allow')) {
|
|
176
|
+
return finish(closed('admission_unconfirmed', { rejectedStatus: recorded.status, actionId: operationId }));
|
|
164
177
|
}
|
|
165
178
|
}
|
|
166
|
-
return finish({ ...closed('policy_block'), observeOnly, response: guard.body });
|
|
179
|
+
return finish({ ...closed('policy_block'), observeOnly, response: guard.body, actionId });
|
|
167
180
|
}
|
|
168
|
-
const created = await
|
|
169
|
-
|
|
170
|
-
});
|
|
171
|
-
if (!created.ok) return closed('admission_unconfirmed', { rejectedStatus: created.status });
|
|
181
|
+
const created = await create({ status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running' });
|
|
182
|
+
if (!created.ok) return finish(closed('admission_unconfirmed', { rejectedStatus: created.status, actionId: operationId }));
|
|
183
|
+
if (operationId && created.body?.action_id !== operationId) return finish(closed('hook_operation_binding_changed', { actionId: operationId }));
|
|
172
184
|
if (!rolloutAuthority(created.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid');
|
|
173
185
|
const diagnostic = installCheck(created.body, context);
|
|
174
186
|
if (diagnostic) return finish(diagnostic);
|
|
175
187
|
let result = finish(actionAdmission(created.body, requestedDecision, context));
|
|
176
|
-
if (result.authorized) return await beforeRelease(result.response) ? result : closed('action_evidence_changed');
|
|
188
|
+
if (result.authorized) return await beforeRelease(result.response) ? result : finish(closed('action_evidence_changed', { actionId: result.actionId }));
|
|
177
189
|
if (result.decision !== 'require_approval') return result;
|
|
178
190
|
if (config.mode === 'observe' && !rollout.binding) return { ...result, observeOnly: true };
|
|
179
191
|
|
|
@@ -205,11 +217,11 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
|
|
|
205
217
|
return closed('approval_not_confirmed', { actionId: expected.actionId });
|
|
206
218
|
}
|
|
207
219
|
// GET observes a grant. Only this fresh POST may redeem it. Never retry a lost reply.
|
|
208
|
-
const current = await
|
|
220
|
+
const current = await create({ status: 'running' });
|
|
209
221
|
if (!current.ok) return closed('admission_unconfirmed', { actionId: expected.actionId, rejectedStatus: current.status });
|
|
210
222
|
if (!rolloutAuthority(current.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid', { actionId: expected.actionId });
|
|
211
223
|
result = finish(actionAdmission(current.body, 'allow', context, expected));
|
|
212
|
-
if (result.authorized && !await beforeRelease(result.response)) return closed('action_evidence_changed', { actionId: result.actionId });
|
|
224
|
+
if (result.authorized && !await beforeRelease(result.response)) return finish(closed('action_evidence_changed', { actionId: result.actionId }));
|
|
213
225
|
return result;
|
|
214
226
|
}
|
|
215
227
|
return result;
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { posix as path } from 'node:path';
|
|
2
|
+
import { isObject } from './protocol.mjs';
|
|
3
|
+
import { isStdoutPrintf, parseShell, unwrapShellArgv } from './shell.mjs';
|
|
4
|
+
|
|
5
|
+
const FILE_READERS = new Set(['cat', 'head', 'tail', 'less', 'more', 'sed', 'awk', 'jq', 'rg', 'grep', 'base64', 'xxd', 'od', 'openssl', 'sort', 'diff']);
|
|
6
|
+
const FILE_WRITERS = new Set(['rm', 'mv', 'cp', 'install', 'chmod', 'chown', 'touch', 'mkdir', 'rmdir', 'tee', 'truncate']);
|
|
7
|
+
const FILE_COPIERS = new Set(['cp', 'install']);
|
|
8
|
+
const NETWORK_COMMANDS = new Set(['curl', 'wget', 'http', 'https', 'ftp', 'sftp', 'scp', 'ssh', 'rsync', 'nc', 'ncat']);
|
|
9
|
+
const SHELLS = new Set(['sh', 'bash', 'dash', 'zsh']);
|
|
10
|
+
const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'apply_patch']);
|
|
11
|
+
const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'ViewImage']);
|
|
12
|
+
const OPAQUE_COMMANDS = new Set(['eval', 'xargs', 'source', '.']);
|
|
13
|
+
const SECRET_PATH = /(?:^|\/)(?:\.env(?:\.(?!(?:example|sample|template)(?:\.|$))[\w.-]+)?|\.git-credentials|\.netrc|\.npmrc|\.aws\/(?:credentials|sso\/cache(?:\/.*)?)|\.ssh\/[^/]+(?<!\.pub)|\.codex\/auth\.json|\.claude\/\.credentials\.json|\.osuite-project-credentials\/.*|id_(?:rsa|ed25519|ecdsa)|[^/]+\.(?:key|p12)|etc\/(?:shadow|gshadow))(?:$|\/)/i;
|
|
14
|
+
const PROJECT_MANAGED = /(?:^|\/)(?:CLAUDE\.md|AGENTS\.md|\.claude\.md|\.mcp\.json|\.claude\/(?:CLAUDE\.md|settings(?:\.local)?\.json|hooks\/.*|rules\/.*)|\.codex\/(?:config\.toml|hooks\.json|hooks\/.*|rules\/.*)|\.cursor\/(?:hooks\.json|hooks\/.*|rules\/.*)|\.osuite\/(?:hooks\/.*|rules\/.*|config\.json))$/i;
|
|
15
|
+
const MCP_ID = /^mcp__[a-zA-Z0-9_.-]+__[a-zA-Z0-9_.-]+$/;
|
|
16
|
+
|
|
17
|
+
function strings(values) {
|
|
18
|
+
return values.filter(value => typeof value === 'string' && value.length > 0 && value.length <= 512);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function targets(argv) {
|
|
22
|
+
return strings(argv).filter(arg => !arg.startsWith('-') && !arg.includes('://'));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function copyOperands(args, operands) {
|
|
26
|
+
const flag = args.findIndex(arg => arg === '-t' || arg === '--target-directory' || arg.startsWith('--target-directory='));
|
|
27
|
+
if (flag < 0) {
|
|
28
|
+
const destination = operands.at(-1);
|
|
29
|
+
const destinationIsDirectory = operands.length > 2 || /(?:\/|\.(?:claude|codex|cursor|osuite))$/.test(destination || '');
|
|
30
|
+
return { sources: operands.slice(0, -1), destination, destinationIsDirectory };
|
|
31
|
+
}
|
|
32
|
+
const option = args[flag];
|
|
33
|
+
const inline = option.startsWith('--target-directory=');
|
|
34
|
+
const remaining = args.filter((_, index) => index !== flag && (inline || index !== flag + 1));
|
|
35
|
+
return { sources: targets(remaining), destination: inline ? option.slice('--target-directory='.length) : args[flag + 1],
|
|
36
|
+
destinationIsDirectory: true };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function readHost(value) {
|
|
40
|
+
if (typeof value !== 'string') return null;
|
|
41
|
+
try {
|
|
42
|
+
const url = new URL(value.includes('://') ? value : `https://${value}`);
|
|
43
|
+
if (!['http:', 'https:', 'ftp:', 'ssh:', 'sftp:'].includes(url.protocol) || !url.hostname) return null;
|
|
44
|
+
return { host: url.hostname.toLowerCase().replace(/\.$/, ''), pathname: url.pathname.toLowerCase() };
|
|
45
|
+
} catch { return null; }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function networkFacts(values, facts) {
|
|
49
|
+
const decoded = values.map(readHost).filter(Boolean);
|
|
50
|
+
for (const { host, pathname } of decoded) {
|
|
51
|
+
facts.egress_domains.add(host);
|
|
52
|
+
if (host === 'gist.github.com' || host === 'gist.githubusercontent.com' || host === 'pastebin.com'
|
|
53
|
+
|| (host === 'api.github.com' && /^\/gists?(?:\/|$)/.test(pathname))) facts.public_relay = true;
|
|
54
|
+
}
|
|
55
|
+
if (!decoded.length || decoded.length !== values.length) facts.unresolved_egress = true;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function networkArguments(executable, args, scope, facts) {
|
|
59
|
+
if (args.length === 1 && /^(?:--help|--version|-h|-V)$/.test(args[0])) return;
|
|
60
|
+
const curl = executable === 'curl';
|
|
61
|
+
const switches = curl ? /^-[fsShIiNvq]+$|^--(?:fail|silent|show-error|head|include|verbose|globoff)$/
|
|
62
|
+
: /^-[qSNv]+$|^--(?:quiet|server-response|no-verbose|spider|no-config)$/;
|
|
63
|
+
const withValue = curl ? new Set(['-X', '--request', '-o', '--output', '--max-time', '--connect-timeout', '-d', '--data', '--data-binary', '--data-raw', '--url'])
|
|
64
|
+
: new Set(['-O', '--output-document', '--timeout', '--method', '--body-data', '--max-redirect']);
|
|
65
|
+
const locations = [];
|
|
66
|
+
if (!['curl', 'wget'].includes(executable)) facts.unresolved_egress = true;
|
|
67
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
68
|
+
const arg = args[index];
|
|
69
|
+
if (!arg.startsWith('-')) { locations.push(arg); continue; }
|
|
70
|
+
if (arg === '--') { locations.push(...args.slice(index + 1)); break; }
|
|
71
|
+
if (switches.test(arg)) continue;
|
|
72
|
+
const separator = arg.indexOf('=');
|
|
73
|
+
const option = separator < 0 ? arg : arg.slice(0, separator);
|
|
74
|
+
if (!withValue.has(option)) { facts.unresolved_egress = true; continue; }
|
|
75
|
+
const value = separator < 0 ? args[++index] : arg.slice(separator + 1);
|
|
76
|
+
if (!value) { facts.unresolved_egress = true; continue; }
|
|
77
|
+
if (option === '--url') locations.push(value);
|
|
78
|
+
if (['-d', '--data', '--data-binary'].includes(option) && value.startsWith('@')) trackFile(value.slice(1), scope, facts);
|
|
79
|
+
if (['-o', '-O', '--output', '--output-document'].includes(option) && value !== '-') trackFile(value, scope, facts, true);
|
|
80
|
+
}
|
|
81
|
+
// wget follows redirects by default. Require the explicit zero-redirect posture.
|
|
82
|
+
if (executable === 'wget' && !args.includes('--max-redirect=0')) facts.unresolved_egress = true;
|
|
83
|
+
networkFacts(locations, facts);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function trackFile(raw, scope, facts, write = false) {
|
|
87
|
+
if (typeof raw !== 'string' || !raw || raw.length > 512 || raw.includes('\0') || raw.includes('://')) return;
|
|
88
|
+
const file = raw.replaceAll('\\', '/');
|
|
89
|
+
const relative = scope.root && !file.startsWith('~')
|
|
90
|
+
? path.relative(scope.root, path.resolve(scope.cwd || scope.root, file))
|
|
91
|
+
: path.normalize(file).replace(/^\.\//, '');
|
|
92
|
+
if (!write) {
|
|
93
|
+
if (SECRET_PATH.test(path.normalize(file)) || SECRET_PATH.test(relative)) facts.credential_read = true;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (PROJECT_MANAGED.test(relative) || /^~?\/(?:[^/]+\/)*\.(?:claude|codex|cursor)\/(?:settings(?:\.local)?\.json|config\.toml|hooks\.json|(?:rules|hooks)\/.*)$/i.test(file)) {
|
|
97
|
+
facts.managed_write = true;
|
|
98
|
+
}
|
|
99
|
+
if (relative && relative !== '..' && !relative.startsWith('../') && !path.isAbsolute(relative)) facts.write_paths.add(relative);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function shellFacts(command, scope, facts, depth = 0) {
|
|
103
|
+
if (!command || isStdoutPrintf(command)) return;
|
|
104
|
+
const parsed = parseShell(command);
|
|
105
|
+
for (const segment of parsed.segments) {
|
|
106
|
+
const argv = unwrapShellArgv(segment);
|
|
107
|
+
const executable = path.basename(argv[0] || '').toLowerCase();
|
|
108
|
+
const args = argv.slice(1);
|
|
109
|
+
const operands = targets(args);
|
|
110
|
+
if (!executable || OPAQUE_COMMANDS.has(executable)) facts.opaque_dispatch = true;
|
|
111
|
+
if (SHELLS.has(executable)) {
|
|
112
|
+
const flag = args.findIndex(arg => /^-[a-z]*c$/.test(arg));
|
|
113
|
+
if (flag >= 0 && args[flag + 1] && depth < 4) shellFacts(args[flag + 1], scope, facts, depth + 1);
|
|
114
|
+
else if (args.length || parsed.segments.length > 1) facts.opaque_dispatch = true;
|
|
115
|
+
}
|
|
116
|
+
if ((/^(?:python[23]?|node|ruby|perl|deno)$/.test(executable) && args.some(arg => /^-(?:c|e|p|E)$|^--eval(?:=|$)/.test(arg)))
|
|
117
|
+
|| (executable === 'find' && args.some(arg => /^-exec(?:dir)?$/.test(arg)))) facts.opaque_dispatch = true;
|
|
118
|
+
if ((executable === 'cd' || executable === 'pushd') && parsed.segments.length > 1) facts.opaque_dispatch = true;
|
|
119
|
+
if (NETWORK_COMMANDS.has(executable)) networkArguments(executable, args, scope, facts);
|
|
120
|
+
if (NETWORK_COMMANDS.has(executable) && parsed.errors.length > 0) facts.unresolved_egress = true;
|
|
121
|
+
if (executable === 'gh' && (args[0] === 'gist' || args[0] === 'api' && args.some(arg => /(?:^|\/)gists?(?:\b|\/)/.test(arg)))) {
|
|
122
|
+
facts.public_relay = true;
|
|
123
|
+
}
|
|
124
|
+
if (executable === 'git' && args.some(arg => ['clone', 'fetch', 'pull', 'push'].includes(arg))) {
|
|
125
|
+
const locations = args.filter(arg => /^(?:https?|ssh):\/\//i.test(arg));
|
|
126
|
+
if (locations.length) networkFacts(locations, facts);
|
|
127
|
+
}
|
|
128
|
+
if (FILE_READERS.has(executable)) {
|
|
129
|
+
for (const operand of operands) trackFile(operand.split(/[<>]/)[0], scope, facts);
|
|
130
|
+
if (parsed.errors.includes('unsupported_glob_expansion') && args.some(arg => /(?:^|\/)\.(?:env|aws|ssh)[\w.*?/-]*/.test(arg))) {
|
|
131
|
+
facts.credential_read = true;
|
|
132
|
+
}
|
|
133
|
+
if (args.some(arg => arg.includes('$'))) facts.opaque_dispatch = true;
|
|
134
|
+
}
|
|
135
|
+
const inPlace = executable === 'sed' && args.some(arg => /^-i|^--in-place(?:=|$)/.test(arg));
|
|
136
|
+
if (FILE_COPIERS.has(executable) && !(executable === 'install' && args.some(arg => arg === '-d' || arg === '--directory'))) {
|
|
137
|
+
const { sources, destination, destinationIsDirectory } = copyOperands(args, operands);
|
|
138
|
+
for (const source of sources) trackFile(source, scope, facts);
|
|
139
|
+
trackFile(destination, scope, facts, true);
|
|
140
|
+
if (destination && destinationIsDirectory) {
|
|
141
|
+
for (const source of sources) trackFile(path.join(destination, path.basename(source)), scope, facts, true);
|
|
142
|
+
}
|
|
143
|
+
} else if (FILE_WRITERS.has(executable) || inPlace) {
|
|
144
|
+
for (const operand of operands) trackFile(operand, scope, facts, true);
|
|
145
|
+
}
|
|
146
|
+
// Redirect operands appear as ordinary tokens in the conservative shell parser.
|
|
147
|
+
if (parsed.errors.includes('unsupported_shell_syntax')) {
|
|
148
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
149
|
+
const redirect = /^[0-9]*([<>]+)(.*)$/.exec(args[index]) || /([<>]+)(.*)$/.exec(args[index]);
|
|
150
|
+
if (redirect) trackFile(redirect[2] || args[index + 1], scope, facts, redirect[1].startsWith('>'));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const rmFlags = args.slice(0, args.includes('--') ? args.indexOf('--') : undefined);
|
|
154
|
+
const recursive = rmFlags.some(arg => arg === '--recursive' || /^-[^-]*[rR]/.test(arg));
|
|
155
|
+
const force = rmFlags.some(arg => arg === '--force' || /^-[^-]*f/.test(arg));
|
|
156
|
+
if (executable === 'rm' && recursive && force && operands.some(file => {
|
|
157
|
+
if (!scope.root || file.startsWith('~') || /[\$*`?\[]/.test(file)) return true;
|
|
158
|
+
const target = path.relative(scope.root, path.resolve(scope.cwd || scope.root, file));
|
|
159
|
+
return !target || target === '..' || target.startsWith('../');
|
|
160
|
+
})) facts.destructive = true;
|
|
161
|
+
const globalOptions = new Set(['-n', '--namespace', '--context', '--kubeconfig', '--server', '--cluster', '--user']);
|
|
162
|
+
const op = args.find((arg, index) => !arg.startsWith('-') && !globalOptions.has(args[index - 1]));
|
|
163
|
+
if ((executable === 'kubectl' && op === 'delete') || (executable === 'terraform' && op === 'destroy')) facts.destructive = true;
|
|
164
|
+
}
|
|
165
|
+
if (parsed.errors.includes('unsupported_expansion') && /\$\(|`|<\(|>\(/.test(command)) facts.opaque_dispatch = true;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function extractCodingAgentFacts({ tool_name: tool, tool_input: value, cwd }, workspaceRoot) {
|
|
169
|
+
const input = isObject(value) ? value : {};
|
|
170
|
+
const facts = { schema_version: 'osuite.coding_agent_facts.v1', egress_domains: new Set(), write_paths: new Set() };
|
|
171
|
+
const scope = { root: typeof workspaceRoot === 'string' && path.isAbsolute(workspaceRoot) ? path.normalize(workspaceRoot) : '', cwd };
|
|
172
|
+
if (['Bash', 'Shell', 'exec_command'].includes(tool)) shellFacts(typeof input.command === 'string' ? input.command : '', scope, facts);
|
|
173
|
+
if (typeof tool === 'string' && tool.startsWith('mcp__')) {
|
|
174
|
+
facts.mcp_tool = MCP_ID.test(tool) ? tool : 'unresolved';
|
|
175
|
+
for (const target of strings([input.path, input.file_path, input.notebook_path])) trackFile(target, scope, facts);
|
|
176
|
+
}
|
|
177
|
+
if (['WebFetch', 'WebSearch', 'web.fetch', 'web.post', 'HttpRequest'].includes(tool)) {
|
|
178
|
+
networkFacts(strings([input.url, input.uri, ...(Array.isArray(input.allowed_domains) ? input.allowed_domains : [])]), facts);
|
|
179
|
+
} else if (facts.mcp_tool && (typeof input.url === 'string' || typeof input.uri === 'string')) {
|
|
180
|
+
networkFacts(strings([input.url, input.uri]), facts);
|
|
181
|
+
}
|
|
182
|
+
if (READ_TOOLS.has(tool) || WRITE_TOOLS.has(tool)) {
|
|
183
|
+
for (const target of strings([input.path, input.file_path, input.notebook_path])) trackFile(target, scope, facts, WRITE_TOOLS.has(tool));
|
|
184
|
+
}
|
|
185
|
+
if (tool === 'apply_patch') {
|
|
186
|
+
const patch = [value, input.patch, input.input, input.diff, input.command].find(item => typeof item === 'string') || '';
|
|
187
|
+
for (const match of patch.matchAll(/^\*\*\* (?:Update File|Delete File|Add File|Move to): (.+)$/gm)) trackFile(match[1].trim(), scope, facts, true);
|
|
188
|
+
}
|
|
189
|
+
if (facts.egress_domains.size > 32) facts.unresolved_egress = true;
|
|
190
|
+
if (facts.write_paths.size > 32) facts.opaque_dispatch = true;
|
|
191
|
+
return { ...facts, egress_domains: [...facts.egress_domains].sort().slice(0, 32), write_paths: [...facts.write_paths].sort().slice(0, 32) };
|
|
192
|
+
}
|
package/runtime/config.mjs
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import { constants, closeSync, fstatSync, openSync, readFileSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
|
|
4
|
+
import { readCredentialFile } from './credentials.mjs';
|
|
5
|
+
|
|
6
|
+
function parseDotenv(body) {
|
|
7
|
+
const values = {};
|
|
8
|
+
for (const line of (body || '').split(/\r?\n/)) {
|
|
9
|
+
const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
|
|
10
|
+
if (!match) continue;
|
|
11
|
+
let value = match[2];
|
|
12
|
+
if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
|
|
13
|
+
else value = value.replace(/\s+#.*$/, '');
|
|
14
|
+
values[match[1]] = value;
|
|
15
|
+
}
|
|
16
|
+
return values;
|
|
17
|
+
}
|
|
4
18
|
|
|
5
19
|
function readDotenv(installDir, filename = '.env') {
|
|
6
20
|
let fd;
|
|
@@ -8,16 +22,7 @@ function readDotenv(installDir, filename = '.env') {
|
|
|
8
22
|
fd = openSync(path.join(installDir, filename), constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | constants.O_NONBLOCK);
|
|
9
23
|
const stat = fstatSync(fd);
|
|
10
24
|
if (!stat.isFile() || stat.size > 65536) return {};
|
|
11
|
-
|
|
12
|
-
for (const line of readFileSync(fd, 'utf8').split(/\r?\n/)) {
|
|
13
|
-
const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
|
|
14
|
-
if (!match) continue;
|
|
15
|
-
let value = match[2];
|
|
16
|
-
if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
|
|
17
|
-
else value = value.replace(/\s+#.*$/, '');
|
|
18
|
-
values[match[1]] = value;
|
|
19
|
-
}
|
|
20
|
-
return values;
|
|
25
|
+
return parseDotenv(readFileSync(fd, 'utf8'));
|
|
21
26
|
} catch { return {}; }
|
|
22
27
|
finally { if (fd !== undefined) closeSync(fd); }
|
|
23
28
|
}
|
|
@@ -25,7 +30,11 @@ function readDotenv(installDir, filename = '.env') {
|
|
|
25
30
|
export function loadRuntimeConfig({ installDir, env = process.env, host = 'claude', runtimeId } = {}) {
|
|
26
31
|
const plugin = runtimeId === 'codex_plugin';
|
|
27
32
|
const hardened = plugin || host === 'cursor';
|
|
28
|
-
const
|
|
33
|
+
const directory = installDir && path.basename(path.resolve(installDir));
|
|
34
|
+
const project = !plugin && directory === `.${host}`;
|
|
35
|
+
const dotenv = project ? parseDotenv(readCredentialFile(path.dirname(path.resolve(installDir)), `${directory}/.env`, { maxBytes: 65536, checkGit: false }))
|
|
36
|
+
: installDir ? readDotenv(installDir) : {};
|
|
37
|
+
const source = { ...dotenv, ...(plugin && installDir ? readDotenv(installDir, '.env.osuite') : {}), ...env };
|
|
29
38
|
const get = (name, fallback = '') => source[`OSUITE_${name}`] ?? source[`DASHCLAW_${name}`] ?? fallback;
|
|
30
39
|
const number = (name, fallback, min, max) => {
|
|
31
40
|
const value = Number(get(name, fallback));
|
|
@@ -34,7 +43,7 @@ export function loadRuntimeConfig({ installDir, env = process.env, host = 'claud
|
|
|
34
43
|
const requestedMode = get('HOOK_MODE', host === 'cursor' ? 'observe' : 'enforce');
|
|
35
44
|
const mode = ['observe', 'enforce', 'strict'].includes(requestedMode) ? requestedMode : 'strict';
|
|
36
45
|
return {
|
|
37
|
-
host,
|
|
46
|
+
host, projectRoot: project ? path.dirname(path.resolve(installDir)) : undefined,
|
|
38
47
|
ruleRolloutCapability: get('SCOPED_RULE_ROLLOUT') === '1' ? RULE_ROLLOUT_CAPABILITY : undefined,
|
|
39
48
|
runtimeId: get('RUNTIME_ADAPTER_ID', runtimeId || (host === 'cursor' ? 'cursor_hooks' : host === 'codex' ? 'codex_hooks' : 'claude_code_hooks')),
|
|
40
49
|
agentId: get('AGENT_ID', plugin ? 'codex-plugin-runtime' : host === 'cursor' ? 'cursor' : host === 'codex' ? 'codex' : 'claude-code'),
|
package/runtime/context.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { canonicalJson, isObject, safeId, sha256, toolInputDigest } from './protocol.mjs';
|
|
2
|
-
import { classifyShell } from './shell.mjs';
|
|
2
|
+
import { classifyShell, isStdoutPrintf } from './shell.mjs';
|
|
3
3
|
import { collectGitPublication } from './git.mjs';
|
|
4
|
+
import { extractCodingAgentFacts } from './coding-agent-facts.mjs';
|
|
4
5
|
|
|
5
6
|
const contentKeys = new Set(['content', 'new_string', 'old_string', 'new_source', 'old_source', 'file_text', 'patch', 'diff', 'input']);
|
|
6
7
|
const publicHosts = new Set(['file.io', 'transfer.sh', '0x0.st', 'pastebin.com', 'gofile.io', 'wetransfer.com', 'tmpfiles.org']);
|
|
@@ -91,7 +92,7 @@ export function buildActionContext(data, config) {
|
|
|
91
92
|
if (publication) mapped.summary.git_publication = publication;
|
|
92
93
|
// Keep the reference externality hints in addition to structural shell semantics.
|
|
93
94
|
const external = genericContext(tool, input, config.captureToolInput);
|
|
94
|
-
if (external.summary.destination_type || external.sensitive_data_categories?.length) {
|
|
95
|
+
if (!isStdoutPrintf(objectInput.command) && (external.summary.destination_type || external.sensitive_data_categories?.length)) {
|
|
95
96
|
mapped = { ...external, ...mapped, risk_score: Math.max(mapped.risk_score, external.risk_score), summary: { ...external.summary, ...mapped.summary } };
|
|
96
97
|
}
|
|
97
98
|
} else if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'apply_patch'].includes(tool)) {
|
|
@@ -110,13 +111,21 @@ export function buildActionContext(data, config) {
|
|
|
110
111
|
}
|
|
111
112
|
if (goal.length > 2000) throw new Error('Tool evidence exceeds declared_goal schema; not truncated');
|
|
112
113
|
const { summary, reversible, ...fields } = mapped;
|
|
114
|
+
const facts = extractCodingAgentFacts({ ...data, cwd: objectInput.workdir || objectInput.working_directory || data.cwd }, config.projectRoot || data.cwd);
|
|
113
115
|
const signal = autonomySignal(data, config);
|
|
114
116
|
const context = { ...fields, ...(typeof reversible === 'boolean' ? { reversible } : {}), agent_id: config.agentId, declared_goal: goal,
|
|
115
117
|
runtime_session_id: deriveSessionId(data, config), tool_use_id: deriveToolUseId(data), tool_input_digest: toolInputDigest(tool, input),
|
|
116
118
|
runtime_family: 'tool_hook_runtime', adapter_mode: 'hook', install_channel: config.installChannel, settings_scope: config.settingsScope,
|
|
117
119
|
trusted_project_required: config.trustedProjectRequired === true, ...signal,
|
|
118
|
-
input_summary: JSON.stringify({ ...summary, ...signal,
|
|
120
|
+
input_summary: JSON.stringify({ ...summary, ...signal, coding_agent_facts: facts,
|
|
121
|
+
runtime_adapter_id: config.runtimeId, runtime_family: 'tool_hook_runtime', adapter_mode: 'hook' }) };
|
|
119
122
|
if (context.input_summary.length > 4000 || context.tool_use_id.length > 128 || !safeId(context.tool_use_id)) throw new Error('Tool evidence exceeds action schema; not truncated');
|
|
123
|
+
if (data.business_authority_assertion !== undefined) {
|
|
124
|
+
if (!isObject(data.business_authority_assertion) || Buffer.byteLength(canonicalJson(data.business_authority_assertion)) > 8192) {
|
|
125
|
+
throw new Error('Invalid business authority evidence');
|
|
126
|
+
}
|
|
127
|
+
context.business_authority_assertion = data.business_authority_assertion;
|
|
128
|
+
}
|
|
120
129
|
if (config.installCheck) context.health_check = true;
|
|
121
130
|
return context;
|
|
122
131
|
}
|