osuite 2.10.0 → 2.10.2

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.
@@ -0,0 +1,58 @@
1
+ import { constants, closeSync, fstatSync, openSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
4
+
5
+ function readDotenv(installDir, filename = '.env') {
6
+ let fd;
7
+ try {
8
+ fd = openSync(path.join(installDir, filename), constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | constants.O_NONBLOCK);
9
+ const stat = fstatSync(fd);
10
+ if (!stat.isFile() || stat.size > 65536) return {};
11
+ const values = {};
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;
21
+ } catch { return {}; }
22
+ finally { if (fd !== undefined) closeSync(fd); }
23
+ }
24
+
25
+ export function loadRuntimeConfig({ installDir, env = process.env, host = 'claude', runtimeId } = {}) {
26
+ const plugin = runtimeId === 'codex_plugin';
27
+ const hardened = plugin || host === 'cursor';
28
+ const source = { ...(installDir ? readDotenv(installDir) : {}), ...(plugin && installDir ? readDotenv(installDir, '.env.osuite') : {}), ...env };
29
+ const get = (name, fallback = '') => source[`OSUITE_${name}`] ?? source[`DASHCLAW_${name}`] ?? fallback;
30
+ const number = (name, fallback, min, max) => {
31
+ const value = Number(get(name, fallback));
32
+ return Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
33
+ };
34
+ const requestedMode = get('HOOK_MODE', host === 'cursor' ? 'observe' : 'enforce');
35
+ const mode = ['observe', 'enforce', 'strict'].includes(requestedMode) ? requestedMode : 'strict';
36
+ return {
37
+ host,
38
+ ruleRolloutCapability: get('SCOPED_RULE_ROLLOUT') === '1' ? RULE_ROLLOUT_CAPABILITY : undefined,
39
+ runtimeId: get('RUNTIME_ADAPTER_ID', runtimeId || (host === 'cursor' ? 'cursor_hooks' : host === 'codex' ? 'codex_hooks' : 'claude_code_hooks')),
40
+ agentId: get('AGENT_ID', plugin ? 'codex-plugin-runtime' : host === 'cursor' ? 'cursor' : host === 'codex' ? 'codex' : 'claude-code'),
41
+ orgId: get('ORG_ID'), provider: get('RUNTIME_PROVIDER') || null,
42
+ baseUrl: get('BASE_URL').replace(/\/+$/, ''), apiKey: get('API_KEY'),
43
+ privateKeyBase64: get('PRIVATE_KEY_BASE64').trim(),
44
+ signatureMode: get('SIGNATURE_MODE', hardened ? 'required' : 'workspace_key_optional'),
45
+ mode, guardFailureMode: mode === 'strict' ? 'block' : (get('GUARD_FAILURE_MODE', hardened ? 'block' : 'allow') === 'allow' ? 'allow' : 'block'),
46
+ requireAssumptionCapture: get('REQUIRE_ASSUMPTION_CAPTURE') === 'true',
47
+ approvalTimeoutSeconds: number('APPROVAL_TIMEOUT_SECONDS', 300, 1, 3600),
48
+ approvalWaitMs: number('APPROVAL_WAIT_SECONDS', 30, 0, 40) * 1000,
49
+ stopWaitMs: number('STOP_WAIT_SECONDS', 0, 0, 40) * 1000,
50
+ installCheck: get('HOOK_CHECK') === '1',
51
+ installChannel: get('INSTALL_CHANNEL', plugin ? 'plugin' : 'project_settings'), settingsScope: get('SETTINGS_SCOPE', plugin ? 'managed' : 'project'),
52
+ trustedProjectRequired: get('TRUSTED_PROJECT_REQUIRED', hardened ? 'true' : 'false') === 'true',
53
+ runtimeSessionId: get('RUNTIME_SESSION_ID'), runtimePermissionMode: get('RUNTIME_PERMISSION_MODE'),
54
+ stateDir: get('STATE_DIR') || undefined,
55
+ captureToolInput: get('CAPTURE_TOOL_INPUT', 'summary'),
56
+ allowInsecureHttp: get('ALLOW_INSECURE_HTTP') === '1',
57
+ };
58
+ }
@@ -0,0 +1,122 @@
1
+ import { canonicalJson, isObject, safeId, sha256, toolInputDigest } from './protocol.mjs';
2
+ import { classifyShell } from './shell.mjs';
3
+ import { collectGitPublication } from './git.mjs';
4
+
5
+ const contentKeys = new Set(['content', 'new_string', 'old_string', 'new_source', 'old_source', 'file_text', 'patch', 'diff', 'input']);
6
+ const publicHosts = new Set(['file.io', 'transfer.sh', '0x0.st', 'pastebin.com', 'gofile.io', 'wetransfer.com', 'tmpfiles.org']);
7
+ const contentSummary = value => { const raw = typeof value === 'string' ? value : canonicalJson(value); return { length: [...raw].length, sha256: sha256(raw) }; };
8
+
9
+ export function summarizeToolInput(input, capture = 'summary') {
10
+ if (capture === 'full') return input;
11
+ if (!isObject(input)) return contentSummary(input);
12
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => [key,
13
+ contentKeys.has(key) ? contentSummary(value) : key === 'edits' && Array.isArray(value) ? { count: value.length, ...contentSummary(value) }
14
+ : typeof value === 'string' ? value.length <= 500 ? value : { ...contentSummary(value) }
15
+ : value !== null && typeof value === 'object' ? contentSummary(value) : value]));
16
+ }
17
+
18
+ export function deriveToolUseId(data) {
19
+ const explicit = data.tool_use_id ?? data.event_id ?? data.id;
20
+ if ((typeof explicit === 'string' || typeof explicit === 'number') && String(explicit)) return String(explicit);
21
+ return `tool_${sha256(canonicalJson({ session_id: data.session_id || '', tool_name: data.tool_name || '', tool_input: data.tool_input ?? {} })).slice(0, 32)}`;
22
+ }
23
+
24
+ export function deriveSessionId(data, config) {
25
+ const explicit = data.session_id || config.runtimeSessionId;
26
+ if (explicit) {
27
+ if (!safeId(String(explicit)) || String(explicit).length > 128) throw new Error('Invalid runtime session evidence');
28
+ return String(explicit);
29
+ }
30
+ return `sess_${sha256(canonicalJson([config.agentId, config.runtimeId, data.cwd || process.cwd()])).slice(0, 32)}`;
31
+ }
32
+
33
+ export function autonomySignal(data, config) {
34
+ const raw = String(data.runtime_permission_mode || data.runtimePermissionMode || data.permission_mode || data.permissionMode || config.runtimePermissionMode || '').replace(/[- _]/g, '').toLowerCase();
35
+ const mode = ({ default: 'manual', manual: 'manual', ask: 'manual', askfirst: 'manual', prompt: 'manual', confirm: 'manual',
36
+ acceptedits: 'accept_edits', accepteditsmode: 'accept_edits', bypass: 'bypass', bypasspermissions: 'bypass', dangerouslyskippermissions: 'bypass',
37
+ auto: 'auto', automode: 'auto', automatic: 'auto', autonomous: 'auto', plan: 'plan', planning: 'plan', readonly: 'plan' })[raw] || 'unknown';
38
+ return { runtime_permission_mode: mode,
39
+ runtime_permission_decision: ({ manual: 'manual_prompt_required', accept_edits: 'edit_acceptance_mode', bypass: 'permissions_bypassed', auto: 'auto_mode_observed', plan: 'plan_only' })[mode] || 'unknown',
40
+ runtime_permission_source: config.host === 'claude' ? 'claude_code' : config.host,
41
+ runtime_autonomy_level: ({ manual: 'human_prompted', accept_edits: 'bounded_edit_autonomy', bypass: 'runtime_permission_bypass', auto: 'runtime_classifier', plan: 'no_side_effects_expected' })[mode] || 'unknown' };
42
+ }
43
+
44
+ function genericContext(tool, input, capture = 'summary') {
45
+ const serialized = canonicalJson(input), lower = `${tool} ${serialized}`.toLowerCase();
46
+ let host = '';
47
+ try { host = new URL(serialized.match(/https?:\/\/[^\s"\\<>]+/)?.[0]).hostname.toLowerCase(); } catch { /* No literal destination. */ }
48
+ const sensitive = [];
49
+ if (/customer|client.data|user.data|personal.data|\bpii\b/.test(lower)) sensitive.push('customer_data');
50
+ if (/credential|secret|api[_ -]?key|private[_ -]?key|password/.test(lower)) sensitive.push('credentials');
51
+ if (/source.code|proprietary|internal.document/.test(lower)) sensitive.push('internal_data');
52
+ let risk = /upload|share|publish|export|send|attach|link/.test(lower) ? 35 : 10;
53
+ const summary = { tool_name: tool, tool_category: 'tool_observation', tool_input_summary: summarizeToolInput(input, capture) };
54
+ if (host) {
55
+ summary.endpoint_host = host; summary.tool_category = 'network_egress'; summary.persists_remote = true;
56
+ summary.destination_type = publicHosts.has(host) ? 'public_file_host' : /notion|drive|dropbox|slack|confluence|jira|mcp/.test(lower) ? 'external_workspace' : 'public_api';
57
+ summary.destination_visibility = publicHosts.has(host) ? 'external_public' : 'external_private';
58
+ risk = Math.max(risk, publicHosts.has(host) ? 70 : summary.destination_type === 'external_workspace' ? 45 : 40);
59
+ }
60
+ if (/public link|publicly accessible|anyone with the link|public upload/.test(lower)) {
61
+ summary.destination_type ||= 'public_share_link'; summary.destination_visibility = 'external_public'; summary.persists_remote = true; risk = Math.max(risk, 75);
62
+ }
63
+ if (/notion|google drive|dropbox|slack|confluence|jira/.test(lower)) {
64
+ summary.destination_type ||= 'external_workspace'; summary.destination_visibility ||= 'external_private'; summary.persists_remote = true;
65
+ }
66
+ const extra = {};
67
+ if (/okta|cloudtrail|mfa|sign.in|access log|security log|audit log/.test(lower)) {
68
+ summary.payload_class = 'identity_security_logs'; risk = Math.max(risk, 65);
69
+ Object.assign(extra, { personal_data_likelihood: 75, privacy_review_required: true, data_minimization_declared: false, authorization_scope: 'identity.logs.export external.processor.share' });
70
+ if (summary.destination_type || /vendor|forensic|third.party/.test(lower)) extra.external_data_processors = ['approved_external_vendor'];
71
+ } else if (sensitive.length) {
72
+ extra.personal_data_likelihood = sensitive.includes('customer_data') ? 55 : 35;
73
+ if (summary.destination_type) { risk = Math.max(risk, 50); Object.assign(extra, { privacy_review_required: true, data_minimization_declared: false, authorization_scope: 'external.share review_required' }); }
74
+ }
75
+ if (sensitive.length) { summary.sensitive_categories = sensitive; extra.sensitive_data_categories = sensitive; }
76
+ return { action_type: risk >= 35 ? 'api' : 'other', risk_score: risk, reversible: true, systems_touched: ['tool_runtime', tool, ...(host ? [host] : [])], summary, ...extra };
77
+ }
78
+
79
+ export function buildActionContext(data, config) {
80
+ if (!isObject(data) || typeof data.tool_name !== 'string' || !data.tool_name || data.tool_name.length > 128 || !safeId(config.agentId) || config.agentId.length > 128) throw new Error('Invalid tool invocation evidence');
81
+ const tool = data.tool_name, input = data.tool_input ?? {}, objectInput = isObject(input) ? input : {};
82
+ let mapped, goal;
83
+ if (tool === 'Bash' || (config.host === 'cursor' && tool === 'Shell')) {
84
+ if (typeof objectInput.command !== 'string' || !objectInput.command) throw new Error('Missing Bash command evidence');
85
+ if (config.host === 'cursor' && objectInput.working_directory !== undefined
86
+ && (typeof objectInput.working_directory !== 'string' || !objectInput.working_directory || objectInput.working_directory.includes('\0'))) throw new Error('Invalid Shell working directory');
87
+ const cwd = config.host === 'cursor' ? objectInput.working_directory || data.cwd || process.cwd() : data.cwd || process.cwd();
88
+ goal = `${tool}: ${objectInput.command}`;
89
+ mapped = classifyShell(objectInput.command, cwd);
90
+ const publication = collectGitPublication(objectInput.command, cwd);
91
+ if (publication) mapped.summary.git_publication = publication;
92
+ // Keep the reference externality hints in addition to structural shell semantics.
93
+ const external = genericContext(tool, input, config.captureToolInput);
94
+ if (external.summary.destination_type || external.sensitive_data_categories?.length) {
95
+ mapped = { ...external, ...mapped, risk_score: Math.max(mapped.risk_score, external.risk_score), summary: { ...external.summary, ...mapped.summary } };
96
+ }
97
+ } else if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'apply_patch'].includes(tool)) {
98
+ const file = objectInput.path || objectInput.file_path || objectInput.notebook_path || 'unknown';
99
+ goal = `${tool}: ${file}`;
100
+ const lower = String(file).toLowerCase();
101
+ const type = /\.env|secret|credential|private_key|id_rsa/.test(lower) ? ['security', 85, true]
102
+ : /migration|schema|seed/.test(lower) ? ['migrate', 70, false]
103
+ : /deploy|infra|terraform|kubernetes|k8s/.test(lower) ? ['deploy', 75, true]
104
+ : /auth|login|oauth|jwt|token|password/.test(lower) ? ['security', 75, true] : ['other', 15, true];
105
+ mapped = { action_type: type[0], risk_score: type[1], reversible: type[2], systems_touched: ['filesystem'], summary: { tool_input_summary: summarizeToolInput(input, config.captureToolInput) } };
106
+ if (tool === 'apply_patch') { mapped.action_type = 'review'; mapped.risk_score = 40; mapped.summary.classification_status = 'incomplete'; }
107
+ } else {
108
+ mapped = genericContext(tool, input, config.captureToolInput);
109
+ goal = `${tool}: ${canonicalJson(summarizeToolInput(input)).slice(0, 120)}`;
110
+ }
111
+ if (goal.length > 2000) throw new Error('Tool evidence exceeds declared_goal schema; not truncated');
112
+ const { summary, reversible, ...fields } = mapped;
113
+ const signal = autonomySignal(data, config);
114
+ const context = { ...fields, ...(typeof reversible === 'boolean' ? { reversible } : {}), agent_id: config.agentId, declared_goal: goal,
115
+ runtime_session_id: deriveSessionId(data, config), tool_use_id: deriveToolUseId(data), tool_input_digest: toolInputDigest(tool, input),
116
+ runtime_family: 'tool_hook_runtime', adapter_mode: 'hook', install_channel: config.installChannel, settings_scope: config.settingsScope,
117
+ trusted_project_required: config.trustedProjectRequired === true, ...signal,
118
+ input_summary: JSON.stringify({ ...summary, ...signal, runtime_adapter_id: config.runtimeId, runtime_family: 'tool_hook_runtime', adapter_mode: 'hook' }) };
119
+ 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');
120
+ if (config.installCheck) context.health_check = true;
121
+ return context;
122
+ }
@@ -0,0 +1,83 @@
1
+ import { loadRuntimeConfig } from './config.mjs';
2
+ import { deny, readHookInput, runHook } from './hook.mjs';
3
+ import { isObject, safeId } from './protocol.mjs';
4
+
5
+ const EVENTS = {
6
+ preToolUse: 'PreToolUse', postToolUse: 'PostToolUse', postToolUseFailure: 'PostToolUseFailure',
7
+ sessionStart: 'SessionStart', sessionEnd: 'SessionEnd', stop: 'Stop',
8
+ };
9
+ const toolEvents = new Set(['preToolUse', 'postToolUse', 'postToolUseFailure']);
10
+
11
+ export function normalizeCursorInput(data) {
12
+ if (!isObject(data) || !Object.hasOwn(EVENTS, data.hook_event_name)) throw new Error('Unsupported Cursor hook event');
13
+ const session = data.conversation_id;
14
+ if (!safeId(session) || session.length > 128 || (data.session_id !== undefined && data.session_id !== session)) {
15
+ throw new Error('Invalid Cursor conversation identity');
16
+ }
17
+ const normalized = { hook_event_name: EVENTS[data.hook_event_name], session_id: session };
18
+ if (!toolEvents.has(data.hook_event_name)) return normalized;
19
+ if (!safeId(data.tool_use_id) || data.tool_use_id.length > 128 || typeof data.tool_name !== 'string'
20
+ || !data.tool_name || data.tool_name.length > 128 || !isObject(data.tool_input)
21
+ || typeof data.cwd !== 'string' || !data.cwd || data.cwd.includes('\0')) throw new Error('Invalid Cursor tool evidence');
22
+ Object.assign(normalized, { cwd: data.cwd, tool_name: data.tool_name, tool_use_id: data.tool_use_id, tool_input: data.tool_input });
23
+ if (data.hook_event_name === 'postToolUseFailure') {
24
+ if (!['timeout', 'error', 'permission_denied'].includes(data.failure_type) || typeof data.error_message !== 'string') {
25
+ throw new Error('Invalid Cursor failure evidence');
26
+ }
27
+ normalized.tool_response = { isError: true };
28
+ } else if (data.hook_event_name === 'postToolUse' && typeof data.tool_output === 'string') {
29
+ // Cursor documents a JSON-serialized result here, unlike Codex's arbitrary
30
+ // text response. Never inspect stdout or another nested output as metadata.
31
+ let result;
32
+ try { result = JSON.parse(data.tool_output); } catch { return normalized; }
33
+ if (data.tool_name === 'Shell' && isObject(result) && Number.isSafeInteger(result.exitCode)
34
+ && !result.backgroundTaskId && !result.background_task_id && !result.session_id
35
+ && data.tool_input.run_in_background !== true) {
36
+ const error = result.error || result.isError === true || result.is_error === true || result.interrupted === true;
37
+ normalized.tool_response = { exit_code: result.exitCode, ...(error ? { isError: true } : {}) };
38
+ }
39
+ }
40
+ return normalized;
41
+ }
42
+
43
+ function cursorReply(event, result) {
44
+ const message = result.stdout?.systemMessage || result.stdout?.reason || result.stderr || '';
45
+ if (event === 'preToolUse') {
46
+ const blocked = result.exitCode !== 0;
47
+ // Cursor's user/agent messages are deny-only. Keep allowed-mode notices in
48
+ // hook logs too, without claiming that the host displays them to the user.
49
+ return { exitCode: blocked ? 2 : 0, stdout: { permission: blocked ? 'deny' : 'allow',
50
+ ...(message ? { user_message: message, agent_message: message } : {}) }, stderr: result.stderr || (!blocked ? message : '') };
51
+ }
52
+ // A stop follow-up is an automatic new user turn in Cursor, not a notice.
53
+ if (event === 'stop' || event === 'sessionEnd') return { exitCode: 0, stdout: {}, stderr: message };
54
+ return { exitCode: 0, stdout: message ? { additional_context: message } : {}, stderr: result.stderr || '' };
55
+ }
56
+
57
+ export async function runCursorHook(data, config, dependencies = {}) {
58
+ const event = Object.hasOwn(EVENTS, data?.hook_event_name) ? data.hook_event_name : 'preToolUse';
59
+ try {
60
+ return cursorReply(event, await runHook(normalizeCursorInput(data), { ...config, host: 'cursor' }, dependencies));
61
+ } catch {
62
+ return cursorReply(event, event === 'preToolUse' ? deny('Invalid Cursor hook evidence. No execution was authorized.')
63
+ : { exitCode: 0, stdout: {}, stderr: '[OSuite] Cursor evidence was not recorded; no completion is claimed.' });
64
+ }
65
+ }
66
+
67
+ export async function runCursorHookCli({ installDir, event = 'preToolUse' } = {}) {
68
+ let result;
69
+ try {
70
+ const data = await readHookInput();
71
+ const allowed = event === 'postToolUse' ? ['postToolUse', 'postToolUseFailure']
72
+ : event === 'sessionStart' ? ['sessionStart', 'sessionEnd'] : [event];
73
+ if (data.hook_event_name && !allowed.includes(data.hook_event_name)) throw new Error('Unexpected Cursor hook event');
74
+ data.hook_event_name ||= event;
75
+ result = await runCursorHook(data, loadRuntimeConfig({ host: 'cursor', runtimeId: 'cursor_hooks', installDir }));
76
+ } catch {
77
+ result = cursorReply(event, event === 'preToolUse' ? deny('Invalid Cursor hook input. No execution was authorized.')
78
+ : { exitCode: 0, stdout: {}, stderr: '[OSuite] Cursor event was not processed; no completion is claimed.' });
79
+ }
80
+ process.stdout.write(`${JSON.stringify(result.stdout)}\n`);
81
+ if (result.stderr) process.stderr.write(`${result.stderr}\n`);
82
+ process.exitCode = result.exitCode;
83
+ }
@@ -0,0 +1,46 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { realpathSync } from 'node:fs';
3
+ import { canonicalJson } from './protocol.mjs';
4
+
5
+ export function collectGitPublication(command, cwd = process.cwd(), env = process.env) {
6
+ const match = /^git push ([A-Za-z0-9][A-Za-z0-9_-]*) ([A-Za-z0-9][A-Za-z0-9_-]*)$/.exec(command);
7
+ if (!match || match[0] !== command || ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_NAMESPACE', 'GIT_CONFIG_COUNT', 'GIT_CONFIG_PARAMETERS'].some(key => env[key])) return null;
8
+ const [, remote, branch] = match;
9
+ // All subprocesses are local metadata reads. Bound the whole collection, not
10
+ // just each read, so evidence gathering cannot consume the host hook timeout.
11
+ const deadline = performance.now() + 1500;
12
+ function git(args, optional = false) {
13
+ const remaining = Math.floor(deadline - performance.now());
14
+ if (remaining <= 0) throw new Error('Git evidence deadline');
15
+ const result = spawnSync('git', args, { cwd, env, encoding: 'utf8', timeout: Math.min(500, remaining), maxBuffer: 65536, windowsHide: true });
16
+ if (result.error) throw new Error('Git evidence unavailable');
17
+ if (optional && result.status === 1) return '';
18
+ if (result.status !== 0) throw new Error('Git evidence unavailable');
19
+ return result.stdout.trim();
20
+ }
21
+ try {
22
+ for (const [key, allowed] of [[`remote.${remote}.mirror`, ['', 'false']], ['push.followTags', ['', 'false']],
23
+ ['push.recurseSubmodules', ['', 'no']], [`remote.${remote}.receivepack`, ['']], ['push.pushOption', ['']]]) {
24
+ if (!allowed.includes(git(['config', '--get-all', key], true))) return null;
25
+ }
26
+ const urls = git(['remote', 'get-url', '--push', '--all', remote]).split(/\r?\n/);
27
+ if (urls.length !== 1) return null;
28
+ const repository = /^(?:git@github\.com:|https:\/\/github\.com\/|ssh:\/\/git@github\.com\/)([A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*?)(?:\.git)?$/.exec(urls[0]);
29
+ if (!repository) return null;
30
+ const commit = git(['rev-parse', '--verify', `refs/heads/${branch}^{commit}`]);
31
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit)) return null;
32
+ return { schema_version: 'osuite.git_publication.v1', repository: `github.com/${repository[1]}`, remote, branch,
33
+ working_directory: realpathSync(cwd), push_url: urls[0], source_commit: commit, command };
34
+ } catch { return null; }
35
+ }
36
+
37
+ export function validateGitPublication(context, payload) {
38
+ try {
39
+ const expected = JSON.parse(context.input_summary || '{}').git_publication;
40
+ if (!expected) return true;
41
+ const current = collectGitPublication(expected.command, expected.working_directory);
42
+ const returned = payload?.action || payload;
43
+ const actual = JSON.parse(returned?.input_summary || '{}').git_publication;
44
+ return canonicalJson(expected) === canonicalJson(current) && canonicalJson(expected) === canonicalJson(actual);
45
+ } catch { return false; }
46
+ }
@@ -0,0 +1,202 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createApiClient, isObject, safeId } from './protocol.mjs';
3
+ import { createStateStore } from './state.mjs';
4
+ import { loadRuntimeConfig } from './config.mjs';
5
+ import { resolveRemotePosture } from './posture.mjs';
6
+ import { buildActionContext, deriveSessionId } from './context.mjs';
7
+ import { admitAction, cavaFingerprint, matchesAction } from './admission.mjs';
8
+ import { recordOutcome } from './outcome.mjs';
9
+ import { validateGitPublication } from './git.mjs';
10
+
11
+ const note = message => ({ exitCode: 0, stdout: message ? { systemMessage: `[OSuite] ${message}` } : {}, stderr: '' });
12
+ export function deny(message) {
13
+ const reason = `[OSuite] ${message}`;
14
+ return { exitCode: 2, stderr: reason, stdout: { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } } };
15
+ }
16
+
17
+ export function applyPosture(config, posture) {
18
+ return { ...config, mode: posture.mode, guardFailureMode: posture.mode === 'strict' ? 'block' : posture.on_guard_unavailable,
19
+ signatureMode: posture.require_signature ? 'required' : 'workspace_key_optional',
20
+ requireAssumptionCapture: posture.require_assumption_capture, approvalTimeoutSeconds: posture.approval_timeout_seconds };
21
+ }
22
+
23
+ export async function emitRuntimeEvent(api, config, context, eventType, actionId = null, payload = {}) {
24
+ return api.request('POST', `/api/runtime-sessions/${encodeURIComponent(context.runtime_session_id)}/events`, {
25
+ event_id: `evt_${randomUUID()}`, runtime_session_id: context.runtime_session_id, event_type: eventType,
26
+ tool_name: context.tool_name || null, tool_use_id: context.tool_use_id || null, action_id: actionId,
27
+ payload: { hook_mode: config.mode, guard_failure_mode: config.guardFailureMode, ...payload },
28
+ }, { timeoutMs: 1500 });
29
+ }
30
+
31
+ export async function openSession(api, config, data, store, now = Date.now()) {
32
+ const sessionId = deriveSessionId(data, config);
33
+ const marker = `session:${sessionId}`;
34
+ const cached = store.read(marker);
35
+ if (cached?.mode === config.mode && cached?.signature_mode === config.signatureMode && now - cached.at >= 0 && now - cached.at < 1800000) return sessionId;
36
+ const response = await api.request('POST', '/api/runtime-sessions', {
37
+ runtime_session_id: sessionId, agent_id: config.agentId, runtime_adapter_id: config.runtimeId,
38
+ runtime_family: 'tool_hook_runtime', adapter_mode: 'hook', client_name: config.host,
39
+ governance_posture: config.mode, signature_mode: config.signatureMode,
40
+ install_channel: config.installChannel, settings_scope: config.settingsScope,
41
+ trusted_project_required: config.trustedProjectRequired === true, status: 'active',
42
+ metadata: { implementation: 'node', runtime_adapter_id: config.runtimeId },
43
+ }, { timeoutMs: 1500 });
44
+ if (response.ok && response.body?.runtime_session?.runtime_session_id === sessionId) {
45
+ store.write(marker, { at: now, mode: config.mode, signature_mode: config.signatureMode });
46
+ }
47
+ return sessionId;
48
+ }
49
+
50
+ function rememberGap(store, reason, now) {
51
+ try {
52
+ const previous = store.read('governance-gap');
53
+ store.write('governance-gap', { since: previous?.since || new Date(now).toISOString(), last_seen: new Date(now).toISOString(),
54
+ calls: Math.min(Number(previous?.calls || 0) + 1, Number.MAX_SAFE_INTEGER), reason });
55
+ } catch { /* The user still receives the explicit ungoverned notice. */ }
56
+ }
57
+
58
+ async function flushGap(api, config, context, store) {
59
+ const gap = store.read('governance-gap');
60
+ if (!gap) return;
61
+ const response = await emitRuntimeEvent(api, config, context, 'governance_unavailable', null, {
62
+ since: gap.since, last_seen: gap.last_seen, ungoverned_tool_calls: gap.calls, reason: gap.reason,
63
+ });
64
+ if (response.ok && response.body?.ok === true) store.remove('governance-gap');
65
+ }
66
+
67
+ function updatePending(store, context, entry = null) {
68
+ const key = `pending:${context.runtime_session_id}`;
69
+ const saved = store.read(key);
70
+ const entries = (Array.isArray(saved) ? saved : []).filter(value => value.tool_input_digest !== context.tool_input_digest);
71
+ if (entry) entries.push(entry);
72
+ if (entries.length) store.write(key, entries.slice(-64));
73
+ else store.remove(key);
74
+ }
75
+
76
+ async function stopHook(data, config, api, store) {
77
+ const session = deriveSessionId(data, config), key = `pending:${session}`;
78
+ const saved = store.read(key);
79
+ if (!Array.isArray(saved) || !saved.length) return note();
80
+ const retained = [], decided = [];
81
+ const deadline = performance.now() + 3000;
82
+ for (const entry of saved) {
83
+ if (!safeId(entry.action_id)) continue;
84
+ if (performance.now() >= deadline) { retained.push(entry); continue; }
85
+ const response = await api.request('GET', `/api/actions/${encodeURIComponent(entry.action_id)}`, undefined, { timeoutMs: Math.max(1, deadline - performance.now()) });
86
+ if (!response.ok) { retained.push(entry); continue; }
87
+ const action = response.body?.action || response.body;
88
+ if (!matchesAction(response.body, entry, { actionId: entry.action_id, fingerprint: entry.fingerprint })) {
89
+ decided.push('Held action evidence no longer matches. Do not retry automatically; reconcile in Studio.'); continue;
90
+ }
91
+ if (action.status === 'pending_approval') { retained.push(entry); continue; }
92
+ if (action.status === 'running' && (action.approved_by || action.approved_at) && action.approval_redeemed_at == null && action.timestamp_end == null) {
93
+ decided.push('A held action was approved. Submit exactly the same tool call through OSuite again; current policy and one-use POST admission must still authorize it.');
94
+ } else if (action.status === 'running') {
95
+ decided.push('A held action has an uncertain execution outcome. Do not retry automatically; reconcile its action/replay in Studio.');
96
+ } else decided.push('A held action was denied, expired, or closed. Do not retry automatically; tell the user.');
97
+ }
98
+ if (retained.length) store.write(key, retained); else store.remove(key);
99
+ if (decided.length && !data.stop_hook_active) return { exitCode: 0, stderr: '', stdout: { decision: 'block', reason: `[OSuite] ${decided.join(' ')}` } };
100
+ return note(decided.join(' ') || 'An action is still held for human review. No tool was executed by this hook.');
101
+ }
102
+
103
+ export async function runHook(data, localConfig, dependencies = {}) {
104
+ const event = data?.hook_event_name || 'PreToolUse';
105
+ const pre = event === 'PreToolUse';
106
+ try {
107
+ if (!isObject(data)) return deny('Invalid hook input. No execution was authorized.');
108
+ // Validate before networking, including exact digest and schema bounds.
109
+ const initialContext = pre ? buildActionContext(data, localConfig) : null;
110
+ const store = dependencies.store || createStateStore(localConfig);
111
+ const now = dependencies.now || Date.now;
112
+ const apiFactory = dependencies.apiFactory || createApiClient;
113
+ let api = dependencies.api || apiFactory(localConfig);
114
+ if (event === 'PostToolUse' || event === 'PostToolUseFailure') {
115
+ const result = await recordOutcome(localConfig, data, { api, store, now });
116
+ return note(result.reason ? 'Tool outcome is not yet acknowledged. Evidence was retained; do not repeat the side effect.' : '');
117
+ }
118
+ const remote = await resolveRemotePosture(localConfig, { api, store, now: now() });
119
+ const config = { ...applyPosture(localConfig, remote.posture), ruleRollout: remote.ruleRollout,
120
+ orgId: remote.orgId || localConfig.orgId };
121
+ api = dependencies.api || apiFactory(config);
122
+ if (event === 'Stop') return stopHook(data, config, api, store);
123
+ if (remote.blocked) return pre ? deny('Verified runtime posture is unavailable or expired. Execution is blocked; reconnect or restore access.')
124
+ : note('Verified runtime posture is unavailable. Enforce hooks will block execution until it can be verified.');
125
+ if (!pre && event !== 'SessionStart' && event !== 'SessionEnd') return note('Unsupported hook event; no execution decision was made.');
126
+ const session = await openSession(api, config, data, store, now());
127
+ if (!pre) {
128
+ await emitRuntimeEvent(api, config, { runtime_session_id: session }, event === 'SessionStart' ? 'session_started' : 'session_ended');
129
+ return note(remote.available ? '' : 'Observe mode is active without verified remote posture. This is not governance authorization.');
130
+ }
131
+ const context = { ...initialContext, tool_name: data.tool_name };
132
+ if (!remote.available) {
133
+ rememberGap(store, 'posture_unavailable', now());
134
+ return note('Not governed: remote posture is unavailable; explicit observe mode does not enforce OSuite policy.');
135
+ }
136
+ await emitRuntimeEvent(api, config, context, 'tool_preflight', null, { tool_input_digest: context.tool_input_digest, install_check: config.installCheck === true });
137
+ const result = await admitAction(context, { api, config, ...dependencies.admission, beforeRelease: response => validateGitPublication(context, response) });
138
+ if (result.degraded) {
139
+ rememberGap(store, result.reason, now());
140
+ await emitRuntimeEvent(api, config, context, 'governance_unavailable', null, { decision: result.decision === 'allow' ? 'guard_unavailable' : 'guard_unavailable_blocked' });
141
+ return result.decision === 'allow' ? note('Not governed: the guard is unavailable and this verified posture explicitly allows availability fallback. No authorization or completion is claimed.')
142
+ : deny('Guard unavailable. Verified policy requires blocking this call.');
143
+ }
144
+ await flushGap(api, config, context, store);
145
+ if (result.installCheck) {
146
+ await emitRuntimeEvent(api, config, context, 'install_check_policy_result', null, { decision: result.decision, approval_state: 'not_requested', install_check: true });
147
+ return deny('Install check: policy would require human approval. No request was sent to reviewers and no tool was executed.');
148
+ }
149
+ if (result.authorized) {
150
+ try {
151
+ store.write(`action:${context.tool_use_id}`, { schema: 'osuite.node_action.v1', action_id: result.actionId,
152
+ runtime_session_id: session, tool_name: data.tool_name, tool_use_id: context.tool_use_id,
153
+ tool_input_digest: context.tool_input_digest, require_signature: config.signatureMode === 'required', install_check: config.installCheck === true });
154
+ } catch { return deny('Cannot persist the exact-action receipt state. The admitted tool was not released; reconcile its action in Studio before retrying.'); }
155
+ updatePending(store, context);
156
+ await emitRuntimeEvent(api, config, context, 'tool_allowed', result.actionId, { decision: result.decision, install_check: config.installCheck === true });
157
+ return note(config.mode === 'observe' && !result.ruleRolloutBinding ? 'Observe mode recorded a policy result; it does not enforce OSuite policy.' : result.decision === 'warn' ? 'OSuite authorized this call with a policy warning.' : '');
158
+ }
159
+ if (result.decision === 'require_approval') {
160
+ if (result.observeOnly !== true) updatePending(store, context, { action_id: result.actionId, agent_id: config.agentId,
161
+ runtime_session_id: session, tool_input_digest: context.tool_input_digest, fingerprint: cavaFingerprint(result.response) });
162
+ await emitRuntimeEvent(api, config, context, 'tool_requires_approval', result.actionId, { decision: result.observeOnly === true ? 'observe_would_require_approval' : result.response?.decision?.decision || 'require_approval' });
163
+ return result.observeOnly === true ? note('Observe mode: this call would require human approval; it is not authorized by a reviewer.')
164
+ : deny(`Human approval is still required for action ${result.actionId}. Do not run or automatically retry it. Review it in OSuite Studio.`);
165
+ }
166
+ await emitRuntimeEvent(api, config, context, 'tool_blocked', result.actionId, { decision: result.observeOnly === true ? 'observe_would_block' : 'block', reason: result.reason });
167
+ return result.observeOnly === true ? note('Observe mode: OSuite policy would block this call. It is not authorized by OSuite.')
168
+ : deny(`OSuite policy did not authorize this exact action (${result.reason}). Do not retry automatically.`);
169
+ } catch {
170
+ return pre ? deny('Hook evidence or state is invalid. Execution is blocked; no successful admission is claimed.')
171
+ : note('Runtime evidence could not be recorded. No completion or authorization is claimed.');
172
+ }
173
+ }
174
+
175
+ export async function readHookInput(input = process.stdin) {
176
+ const chunks = []; let size = 0;
177
+ for await (const chunk of input) {
178
+ size += Buffer.byteLength(chunk);
179
+ if (size > 1048576) throw new Error('Hook input exceeds limit');
180
+ chunks.push(Buffer.from(chunk));
181
+ }
182
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)).replace(/^\uFEFF/, '');
183
+ const value = JSON.parse(text);
184
+ if (!isObject(value)) throw new Error('Invalid hook input');
185
+ return value;
186
+ }
187
+
188
+ export async function runHookCli({ host, installDir, event = 'PreToolUse', runtimeId } = {}) {
189
+ let result;
190
+ try {
191
+ const data = await readHookInput();
192
+ const allowedEvents = event === 'PostToolUse' ? ['PostToolUse', 'PostToolUseFailure'] : [event];
193
+ if (data.hook_event_name && !allowedEvents.includes(data.hook_event_name)) throw new Error('Unexpected hook event');
194
+ data.hook_event_name ||= event;
195
+ result = await runHook(data, loadRuntimeConfig({ host, installDir, runtimeId }));
196
+ } catch {
197
+ result = event === 'PreToolUse' ? deny('Invalid hook input. No execution was authorized.') : note('Runtime event could not be processed; no completion is claimed.');
198
+ }
199
+ process.stdout.write(`${JSON.stringify(result.stdout)}\n`);
200
+ if (result.stderr) process.stderr.write(`${result.stderr}\n`);
201
+ process.exitCode = result.exitCode;
202
+ }