osuite 2.9.9 → 2.10.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/reviewSurface.js CHANGED
@@ -133,8 +133,16 @@ export function buildReviewSurface(action = {}, options = {}) {
133
133
  ]
134
134
  : [];
135
135
 
136
- const replayUrl = options.baseUrl ? `${String(options.baseUrl).replace(/\/$/, '')}/replay/${actionId}` : null;
137
- const footer = replayUrl ? ['', `${colorize('Replay', BOLD, color)} ${replayUrl}`] : [];
136
+ const baseUrl = options.baseUrl ? String(options.baseUrl).replace(/\/$/, '') : null;
137
+ const replayUrl = baseUrl ? `${baseUrl}/replay/${actionId}` : null;
138
+ // A request still waiting is decided by a person in Studio, so point there.
139
+ const reviewUrl = baseUrl && action.status === 'pending_approval'
140
+ ? `${baseUrl}/approvals?action=${encodeURIComponent(actionId)}`
141
+ : null;
142
+ const footer = [
143
+ ...(reviewUrl ? ['', `${colorize('Review', BOLD, color)} ${reviewUrl}`] : []),
144
+ ...(replayUrl ? [reviewUrl ? null : '', `${colorize('Replay', BOLD, color)} ${replayUrl}`].filter((line) => line !== null) : []),
145
+ ];
138
146
 
139
147
  return [
140
148
  colorize(title, `${BOLD}${CYAN}`, color),
@@ -0,0 +1,150 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { isObject, safeId } from './protocol.mjs';
3
+
4
+ export const REVIEW_DECISIONS = new Set(['require_approval', 'require_dual_approval']);
5
+ const DECISIONS = new Set(['allow', 'warn', 'block', ...REVIEW_DECISIONS]);
6
+ const closed = (reason, extra = {}) => ({ authorized: false, decision: 'block', reason, retryAutomatically: false, ...extra });
7
+
8
+ function approvalReceipts(payload) {
9
+ const action = payload?.action || payload || {};
10
+ return [action.approval_receipts, action.proof_bundle?.approval_receipts,
11
+ payload?.approval_receipts, payload?.contracts?.proof_bundle?.approval_receipts]
12
+ .flatMap(value => Array.isArray(value) ? value.filter(isObject) : []);
13
+ }
14
+
15
+ export function cavaFingerprint(payload) {
16
+ return [payload?.contracts?.action_envelope?.cava?.fingerprint,
17
+ payload?.contracts?.proof_bundle?.action_envelope?.cava?.fingerprint,
18
+ payload?.action?.action_envelope?.cava?.fingerprint,
19
+ payload?.action?.proof_bundle?.action_envelope?.cava?.fingerprint,
20
+ payload?.action_envelope?.cava?.fingerprint, payload?.proof_bundle?.action_envelope?.cava?.fingerprint]
21
+ .find(value => typeof value === 'string' && value.trim()) || null;
22
+ }
23
+
24
+ export function matchesAction(payload, context, { actionId = null, fingerprint = null } = {}) {
25
+ const action = payload?.action || payload;
26
+ if (!isObject(action) || !safeId(action.action_id)) return false;
27
+ if (actionId && action.action_id !== actionId) return false;
28
+ if (payload.action_id && payload.action_id !== action.action_id) return false;
29
+ if (action.tool_input_digest && action.tool_input_digest !== context.tool_input_digest) return false;
30
+ if (action.agent_id && action.agent_id !== context.agent_id) return false;
31
+ if (action.runtime_session_id && action.runtime_session_id !== context.runtime_session_id) return false;
32
+ for (const envelope of [action.action_envelope, payload.contracts?.action_envelope]) {
33
+ if (envelope?.runtime_session_id !== undefined && envelope.runtime_session_id !== context.runtime_session_id) return false;
34
+ }
35
+ if (fingerprint) {
36
+ const receipts = approvalReceipts(payload).filter(receipt => ['allow', 'approved', 'approve'].includes(receipt.decision || receipt.status));
37
+ const fingerprints = receipts.flatMap(receipt => {
38
+ const scope = receipt.approval_scope || {};
39
+ if (scope.reusable === true || (receipt.action_id || scope.action_id) !== action.action_id) return [];
40
+ return [receipt.canonical_fingerprint || scope.canonical_fingerprint].filter(Boolean);
41
+ });
42
+ if (fingerprints.length ? !fingerprints.includes(fingerprint) : cavaFingerprint(payload) !== fingerprint) return false;
43
+ }
44
+ return true;
45
+ }
46
+
47
+ function approvalTime(value) {
48
+ return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value)
49
+ ? Date.parse(value) : NaN;
50
+ }
51
+
52
+ function confirmedRedemption({ action, approval }) {
53
+ if (approval?.state !== 'approved' || approval.reused !== true || action.approval_decision !== 'allow'
54
+ || typeof action.approved_by !== 'string' || !action.approved_by.trim()) return false;
55
+ const approvedAt = approvalTime(action.approved_at);
56
+ const redeemedAt = approvalTime(action.approval_redeemed_at);
57
+ const expiresAt = approvalTime(action.approval_expires_at);
58
+ const now = Date.now();
59
+ // A GET-shaped approval is not a redeemed grant. These are consistency checks,
60
+ // not independent proof of the server's atomic update or exactly-once effects.
61
+ if (![approvedAt, redeemedAt, expiresAt].every(Number.isFinite)
62
+ || approvedAt > redeemedAt || redeemedAt > now || expiresAt <= now) return false;
63
+ if (approval.decided_by !== undefined && approval.decided_by !== action.approved_by) return false;
64
+ if (approval.decided_at !== undefined && approvalTime(approval.decided_at) !== approvedAt) return false;
65
+ if (approval.expires_at !== undefined && approvalTime(approval.expires_at) !== expiresAt) return false;
66
+ return true;
67
+ }
68
+
69
+ export function actionAdmission(payload, requestedDecision, context, expected = {}) {
70
+ if (!isObject(payload) || payload.error || !isObject(payload.action) || !safeId(payload.action_id)
71
+ || payload.action.action_id !== payload.action_id || !matchesAction(payload, context)) return closed('action_creation_not_authorized');
72
+ const actionId = payload.action_id;
73
+ const action = payload.action;
74
+ const decision = payload.decision?.decision;
75
+ const base = { actionId, response: payload };
76
+ if (!DECISIONS.has(decision) || !['running', 'pending_approval'].includes(action.status)
77
+ || (payload.status !== undefined && payload.status !== action.status)
78
+ || action.timestamp_end != null || ['denied', 'expired'].includes(payload.approval?.state)
79
+ || requestedDecision === 'block' || decision === 'block') return closed('action_creation_not_authorized', base);
80
+ if (action.status === 'pending_approval') return { ...base, authorized: false, decision: 'require_approval', reason: 'awaiting_approval' };
81
+ if (REVIEW_DECISIONS.has(decision) || REVIEW_DECISIONS.has(requestedDecision)) {
82
+ if (!confirmedRedemption(payload)
83
+ || !matchesAction(payload, context, expected)) return closed('approval_not_confirmed', base);
84
+ return { ...base, authorized: true, decision: 'approved_by_reviewer' };
85
+ }
86
+ return { ...base, authorized: true, decision: decision === 'warn' || requestedDecision === 'warn' ? 'warn' : 'allow' };
87
+ }
88
+
89
+ function installCheck(payload, context) {
90
+ if (!context.health_check || payload?.approval?.state !== 'not_requested') return null;
91
+ if (payload.error || !safeId(payload.action_id) || payload.action?.action_id !== payload.action_id
92
+ || payload.action?.status !== 'cancelled' || (payload.status !== undefined && payload.status !== 'cancelled')
93
+ || !REVIEW_DECISIONS.has(payload.decision?.decision)) return closed('invalid_install_check');
94
+ return { authorized: false, decision: payload.decision.decision, installCheck: true, reason: 'approval_not_requested', response: payload };
95
+ }
96
+
97
+ export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(), beforeRelease = async () => true } = {}) {
98
+ const guard = await api.request('POST', '/api/guard', context);
99
+ if (!guard.ok) {
100
+ const failOpen = config.guardFailureMode === 'allow' && ![401, 403].includes(guard.status)
101
+ && !['signing_unavailable', 'invalid_response', 'invalid_request'].includes(guard.error);
102
+ return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true };
103
+ }
104
+ const requestedDecision = guard.body?.decision;
105
+ if (!DECISIONS.has(requestedDecision)) return closed('unsupported_guard_decision');
106
+ if (requestedDecision === 'block') {
107
+ // Observation still persists the would-block result, but never calls it authority.
108
+ if (config.mode === 'observe') await api.request('POST', '/api/actions', { ...context, status: 'blocked' });
109
+ return { ...closed('policy_block'), observeOnly: config.mode === 'observe', response: guard.body };
110
+ }
111
+ const created = await api.request('POST', '/api/actions', {
112
+ ...context, status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running',
113
+ });
114
+ if (!created.ok) return closed('admission_unconfirmed');
115
+ const diagnostic = installCheck(created.body, context);
116
+ if (diagnostic) return diagnostic;
117
+ let result = actionAdmission(created.body, requestedDecision, context);
118
+ if (result.authorized) return await beforeRelease(result.response) ? result : closed('action_evidence_changed');
119
+ if (result.decision !== 'require_approval') return result;
120
+ if (config.mode === 'observe') return { ...result, observeOnly: true };
121
+
122
+ const expected = { actionId: result.actionId, fingerprint: cavaFingerprint(created.body) };
123
+ const waitMs = Math.max(0, Math.min(config.approvalWaitMs ?? 30000, 600000));
124
+ const deadline = now() + waitMs;
125
+ while (now() < deadline) {
126
+ await sleep(Math.min(3000, Math.max(0, deadline - now())));
127
+ const polled = await api.request('GET', `/api/actions/${encodeURIComponent(expected.actionId)}`, undefined, {
128
+ timeoutMs: Math.max(1, Math.min(2500, deadline - now())),
129
+ });
130
+ if (!polled.ok) {
131
+ if ([401, 403].includes(polled.status)) return closed('approval_access_rejected', { actionId: expected.actionId });
132
+ continue;
133
+ }
134
+ const action = polled.body?.action || polled.body;
135
+ if (!matchesAction(polled.body, context, expected)) return closed('approval_binding_mismatch', { actionId: expected.actionId });
136
+ if (action.status === 'pending_approval') continue;
137
+ if (action.status !== 'running') return closed('approval_closed', { actionId: expected.actionId });
138
+ if (action.approval_redeemed_at != null || action.timestamp_end != null) return closed('execution_outcome_unknown', { actionId: expected.actionId });
139
+ if (!(action.approved_by || action.approved_at) || polled.body.approval?.state === 'denied') {
140
+ return closed('approval_not_confirmed', { actionId: expected.actionId });
141
+ }
142
+ // GET observes a grant. Only this fresh POST may redeem it. Never retry a lost reply.
143
+ const current = await api.request('POST', '/api/actions', { ...context, status: 'running' });
144
+ if (!current.ok) return closed('admission_unconfirmed', { actionId: expected.actionId });
145
+ result = actionAdmission(current.body, 'allow', context, expected);
146
+ if (result.authorized && !await beforeRelease(result.response)) return closed('action_evidence_changed', { actionId: result.actionId });
147
+ return result;
148
+ }
149
+ return result;
150
+ }
@@ -0,0 +1,56 @@
1
+ import { constants, closeSync, fstatSync, openSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ function readDotenv(installDir, filename = '.env') {
5
+ let fd;
6
+ try {
7
+ fd = openSync(path.join(installDir, filename), constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | constants.O_NONBLOCK);
8
+ const stat = fstatSync(fd);
9
+ if (!stat.isFile() || stat.size > 65536) return {};
10
+ const values = {};
11
+ for (const line of readFileSync(fd, 'utf8').split(/\r?\n/)) {
12
+ const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
13
+ if (!match) continue;
14
+ let value = match[2];
15
+ if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
16
+ else value = value.replace(/\s+#.*$/, '');
17
+ values[match[1]] = value;
18
+ }
19
+ return values;
20
+ } catch { return {}; }
21
+ finally { if (fd !== undefined) closeSync(fd); }
22
+ }
23
+
24
+ export function loadRuntimeConfig({ installDir, env = process.env, host = 'claude', runtimeId } = {}) {
25
+ const plugin = runtimeId === 'codex_plugin';
26
+ const hardened = plugin || host === 'cursor';
27
+ const source = { ...(installDir ? readDotenv(installDir) : {}), ...(plugin && installDir ? readDotenv(installDir, '.env.osuite') : {}), ...env };
28
+ const get = (name, fallback = '') => source[`OSUITE_${name}`] ?? source[`DASHCLAW_${name}`] ?? fallback;
29
+ const number = (name, fallback, min, max) => {
30
+ const value = Number(get(name, fallback));
31
+ return Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
32
+ };
33
+ const requestedMode = get('HOOK_MODE', host === 'cursor' ? 'observe' : 'enforce');
34
+ const mode = ['observe', 'enforce', 'strict'].includes(requestedMode) ? requestedMode : 'strict';
35
+ return {
36
+ host,
37
+ runtimeId: get('RUNTIME_ADAPTER_ID', runtimeId || (host === 'cursor' ? 'cursor_hooks' : host === 'codex' ? 'codex_hooks' : 'claude_code_hooks')),
38
+ agentId: get('AGENT_ID', plugin ? 'codex-plugin-runtime' : host === 'cursor' ? 'cursor' : host === 'codex' ? 'codex' : 'claude-code'),
39
+ orgId: get('ORG_ID'), provider: get('RUNTIME_PROVIDER') || null,
40
+ baseUrl: get('BASE_URL').replace(/\/+$/, ''), apiKey: get('API_KEY'),
41
+ privateKeyBase64: get('PRIVATE_KEY_BASE64').trim(),
42
+ signatureMode: get('SIGNATURE_MODE', hardened ? 'required' : 'workspace_key_optional'),
43
+ mode, guardFailureMode: mode === 'strict' ? 'block' : (get('GUARD_FAILURE_MODE', hardened ? 'block' : 'allow') === 'allow' ? 'allow' : 'block'),
44
+ requireAssumptionCapture: get('REQUIRE_ASSUMPTION_CAPTURE') === 'true',
45
+ approvalTimeoutSeconds: number('APPROVAL_TIMEOUT_SECONDS', 300, 1, 3600),
46
+ approvalWaitMs: number('APPROVAL_WAIT_SECONDS', 30, 0, 40) * 1000,
47
+ stopWaitMs: number('STOP_WAIT_SECONDS', 0, 0, 40) * 1000,
48
+ installCheck: get('HOOK_CHECK') === '1',
49
+ installChannel: get('INSTALL_CHANNEL', plugin ? 'plugin' : 'project_settings'), settingsScope: get('SETTINGS_SCOPE', plugin ? 'managed' : 'project'),
50
+ trustedProjectRequired: get('TRUSTED_PROJECT_REQUIRED', hardened ? 'true' : 'false') === 'true',
51
+ runtimeSessionId: get('RUNTIME_SESSION_ID'), runtimePermissionMode: get('RUNTIME_PERMISSION_MODE'),
52
+ stateDir: get('STATE_DIR') || undefined,
53
+ captureToolInput: get('CAPTURE_TOOL_INPUT', 'summary'),
54
+ allowInsecureHttp: get('ALLOW_INSECURE_HTTP') === '1',
55
+ };
56
+ }
@@ -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
+ }