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.
@@ -0,0 +1,314 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import { spawnSync } from 'node:child_process';
6
+
7
+ export const CREDENTIAL_PATHS = ['.codex/.env', '.claude/.env', '.cursor/.env', '.osuite/.env'];
8
+ const POSIX = process.platform !== 'win32';
9
+ const NOFOLLOW = fs.constants.O_NOFOLLOW || 0;
10
+
11
+ function metadata(file) {
12
+ try { return fs.lstatSync(file); } catch (error) {
13
+ if (error.code === 'ENOENT') return null;
14
+ throw error;
15
+ }
16
+ }
17
+
18
+ function sameFile(a, b) {
19
+ return !a && !b || Boolean(a && b && a.dev === b.dev && a.ino === b.ino && a.size === b.size
20
+ && a.mode === b.mode && a.uid === b.uid && a.nlink === b.nlink
21
+ && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs);
22
+ }
23
+
24
+ function owned(stat) {
25
+ return !POSIX || typeof process.getuid !== 'function' || stat.uid === process.getuid();
26
+ }
27
+
28
+ function credentialPathError(code, message) {
29
+ return Object.assign(new Error(message), { code });
30
+ }
31
+
32
+ function projectPath(root, relativePath) {
33
+ const absolute = path.resolve(root, relativePath);
34
+ const relative = path.relative(root, absolute);
35
+ if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
36
+ throw credentialPathError('CREDENTIAL_PATH_UNSAFE', 'Credential path must stay inside the project.');
37
+ }
38
+ return relative;
39
+ }
40
+
41
+ function checkDirectory(directory, { create = false, privateMode = false, allowGroupWrite = false } = {}) {
42
+ let stat = metadata(directory);
43
+ if (!stat && create) {
44
+ try {
45
+ fs.mkdirSync(directory, { mode: 0o700 });
46
+ syncDirectory(path.dirname(directory));
47
+ } catch (error) {
48
+ if (error.code !== 'EEXIST') throw error;
49
+ }
50
+ stat = metadata(directory);
51
+ }
52
+ if (!stat) return null;
53
+ if (!stat.isDirectory()) throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Expected a real directory (no symlinks): ${directory}`);
54
+ if (!owned(stat) || POSIX && (stat.mode & (allowGroupWrite ? 0o002 : 0o022))) {
55
+ throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Unsafe credential directory ownership or write permissions: ${directory}. Use a user-owned workspace and remove write access for others from credential storage.`);
56
+ }
57
+ if (POSIX && privateMode && (stat.mode & 0o777) !== 0o700) {
58
+ throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Private credential directory must have mode 0700: ${directory}`);
59
+ }
60
+ return stat;
61
+ }
62
+
63
+ function sharedProjectRoot(root, stat, relative, create) {
64
+ // A group-writable parent can rename even a 0700 child. Keep the secrets in
65
+ // a different, user-controlled tree and bind that slot to this project inode.
66
+ let current = root;
67
+ for (const part of relative.split(path.sep).slice(0, -1)) {
68
+ current = path.join(current, part);
69
+ if (!checkDirectory(current, { allowGroupWrite: true })) break;
70
+ }
71
+ if (metadata(path.join(root, relative))) {
72
+ throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Existing credential path in a group-writable project: ${relative}. Secure the project directory before inspecting the file, or remove it and reconnect to rotate the credentials.`);
73
+ }
74
+ if (!/^\.(?:codex|claude|cursor|osuite)\//.test(relative.split(path.sep).join('/'))) {
75
+ if (create) throw credentialPathError('CREDENTIAL_PATH_UNSAFE', 'Use osuite connect to save credentials in private storage for this team project.');
76
+ return null;
77
+ }
78
+ const home = fs.realpathSync(os.homedir());
79
+ checkDirectory(home);
80
+ for (let parent = path.dirname(home); parent !== home; parent = path.dirname(parent)) {
81
+ const ancestor = metadata(parent);
82
+ const trustedSticky = ancestor?.uid === 0 && (ancestor.mode & 0o1000);
83
+ if (!ancestor?.isDirectory() || (!owned(ancestor) && ancestor.uid !== 0) || (ancestor.mode & 0o022) && !trustedSticky) {
84
+ throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Private credential storage requires a protected home directory: ${home}`);
85
+ }
86
+ if (parent === path.dirname(parent)) break;
87
+ }
88
+ const storage = path.join(home, '.osuite-project-credentials');
89
+ const identity = crypto.createHash('sha256').update(JSON.stringify([root, stat.dev, stat.ino])).digest('hex');
90
+ const privateRoot = path.join(storage, identity);
91
+ if (!checkDirectory(storage, { create, privateMode: true }) || !checkDirectory(privateRoot, { create, privateMode: true })) return null;
92
+ return privateRoot;
93
+ }
94
+
95
+ function safePath(projectRoot, relativePath, { create = false } = {}) {
96
+ const project = fs.realpathSync(projectRoot);
97
+ const relative = projectPath(project, relativePath);
98
+ const projectStat = checkDirectory(project, { allowGroupWrite: true });
99
+ const shared = POSIX && (projectStat.mode & 0o020) !== 0;
100
+ const root = shared ? sharedProjectRoot(project, projectStat, relative, create) : project;
101
+ const logicalPath = relative.split(path.sep).join('/');
102
+ if (!root) return { project, relativePath: logicalPath, stat: null };
103
+ const absolute = path.join(root, relative);
104
+ let directory = root;
105
+ for (const part of relative.split(path.sep).slice(0, -1)) {
106
+ directory = path.join(directory, part);
107
+ if (!checkDirectory(directory, { create, privateMode: shared })) break;
108
+ }
109
+ const stat = metadata(absolute);
110
+ if (stat?.isSymbolicLink()) throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Refusing a symlinked credential file: ${logicalPath}`);
111
+ if (stat && (!stat.isFile() || stat.nlink !== 1 || !owned(stat))) {
112
+ throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Unsafe credential file type, links, or ownership: ${logicalPath}`);
113
+ }
114
+ return { root, project, absolute, relativePath: logicalPath, stat };
115
+ }
116
+
117
+ function runGit(cwd, args) {
118
+ // Inherited GIT_DIR/INDEX_FILE must not hide a tracked project credential.
119
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
120
+ // Metadata inspection must not execute repository-configured fsmonitor commands.
121
+ return spawnSync('git', ['-c', 'core.fsmonitor=false', '-C', cwd, ...args], {
122
+ encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'],
123
+ });
124
+ }
125
+
126
+ function repositoryRoots(root, absolute) {
127
+ const roots = new Set();
128
+ let current = root;
129
+ for (const part of ['', ...path.relative(root, path.dirname(absolute)).split(path.sep).filter(Boolean)]) {
130
+ if (part) current = path.join(current, part);
131
+ if (!metadata(current)) continue;
132
+ const result = runGit(current, ['rev-parse', '--show-toplevel']);
133
+ if (result.error) throw new Error('Git is required to check whether the credential path is tracked.');
134
+ if (result.status === 0) roots.add(result.stdout.trim());
135
+ else if (!result.stderr.includes('not a git repository')) throw new Error('Unable to verify Git credential protection.');
136
+ }
137
+ return [...roots];
138
+ }
139
+
140
+ function isTracked(root, absolute) {
141
+ return repositoryRoots(root, absolute).some((repository) => {
142
+ // A tracked .ENV aliases .env on common macOS/Windows filesystems.
143
+ const result = runGit(repository, ['ls-files', '--error-unmatch', '--', `:(icase,literal)${path.relative(repository, absolute)}`]);
144
+ if (result.status !== 0 && result.status !== 1) throw new Error('Unable to inspect the Git index for credentials.');
145
+ return result.status === 0;
146
+ });
147
+ }
148
+
149
+ function assertUntracked(target) {
150
+ if (isTracked(target.root, target.absolute)) throw new Error('Refusing to write credentials to a tracked path. Remove it from Git and rotate any exposed credentials first.');
151
+ }
152
+
153
+ function syncDirectory(directory) {
154
+ if (!POSIX) return;
155
+ const fd = fs.openSync(directory, fs.constants.O_RDONLY | (fs.constants.O_DIRECTORY || 0) | NOFOLLOW);
156
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
157
+ }
158
+
159
+ function atomicWrite(target, body, mode, { credential = false } = {}) {
160
+ const temporary = `${target.absolute}.osuite-tmp-${crypto.randomBytes(12).toString('hex')}`;
161
+ let fd;
162
+ try {
163
+ fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW, mode);
164
+ if (POSIX) fs.fchmodSync(fd, mode);
165
+ fs.writeFileSync(fd, body, 'utf8');
166
+ fs.fsyncSync(fd);
167
+ fs.closeSync(fd);
168
+ fd = undefined;
169
+ const latest = safePath(target.project, target.relativePath);
170
+ if (latest.absolute !== target.absolute || !sameFile(target.stat, latest.stat)) throw new Error('Credential destination changed during the write; refusing to replace it.');
171
+ if (credential) assertUntracked(latest);
172
+ fs.renameSync(temporary, target.absolute);
173
+ syncDirectory(path.dirname(target.absolute));
174
+ } finally {
175
+ if (fd !== undefined) fs.closeSync(fd);
176
+ try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
177
+ }
178
+ }
179
+
180
+ function protectIgnore(target) {
181
+ const directory = path.dirname(target.absolute);
182
+ const ignorePath = path.join(path.dirname(target.relativePath), '.gitignore');
183
+ const ignore = safePath(target.root, ignorePath);
184
+ const body = ignore.stat ? fs.readFileSync(ignore.absolute, 'utf8') : '';
185
+ const name = path.basename(target.absolute);
186
+ // A rule in the credential's own directory works in monorepos and nested repos.
187
+ const rules = [`/${name}`, `/${name}.osuite-tmp-*`];
188
+ const missing = rules.filter((rule) => !body.split(/\r?\n/).includes(rule));
189
+ if (missing.length) {
190
+ atomicWrite(ignore, `${body}${body && !body.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`, ignore.stat ? ignore.stat.mode & 0o777 : 0o644);
191
+ }
192
+ if (repositoryRoots(target.root, target.absolute).length) {
193
+ const result = runGit(directory, ['check-ignore', '--no-index', '--', target.absolute]);
194
+ if (result.status !== 0) throw new Error('Credential path is not ignored by Git; check conflicting ignore rules.');
195
+ }
196
+ }
197
+
198
+ export function inspectCredentialFile(projectRoot, relativePath) {
199
+ const result = { relativePath, exists: false, safe: false, problems: [], mode: null, storagePath: relativePath };
200
+ try {
201
+ const target = safePath(projectRoot, relativePath);
202
+ result.storagePath = target.root && target.root !== target.project ? target.absolute : relativePath;
203
+ result.exists = Boolean(target.stat);
204
+ if (target.stat) {
205
+ result.mode = POSIX ? (target.stat.mode & 0o7777).toString(8).padStart(4, '0') : null;
206
+ if (POSIX && (target.stat.mode & 0o7777) !== 0o600) result.problems.push(`unsafe mode ${result.mode}; expected 0600. Set mode 0600 and rotate if the credential was exposed`);
207
+ }
208
+ if (target.absolute && isTracked(target.root, target.absolute)) result.problems.push('tracked by Git');
209
+ if (target.stat) {
210
+ const roots = repositoryRoots(target.root, target.absolute);
211
+ if (roots.length && runGit(path.dirname(target.absolute), ['check-ignore', '--no-index', '--', target.absolute]).status !== 0) result.problems.push('not ignored by Git');
212
+ }
213
+ result.safe = result.problems.length === 0;
214
+ } catch (error) {
215
+ result.problems.push(error.message);
216
+ }
217
+ return result;
218
+ }
219
+
220
+ export function prepareCredentialFile(projectRoot, relativePath) {
221
+ let target = safePath(projectRoot, relativePath);
222
+ if (target.absolute) assertUntracked(target);
223
+ target = safePath(projectRoot, relativePath, { create: true });
224
+ assertUntracked(target);
225
+ if (target.stat && POSIX && (target.stat.mode & 0o022)) {
226
+ throw credentialPathError('CREDENTIAL_FILE_PERMISSIONS', 'Credential file is writable by others: set mode 0600 and rotate the credential.');
227
+ }
228
+ protectIgnore(target);
229
+ return target;
230
+ }
231
+
232
+ export function writeCredentialFile(projectRoot, relativePath, body, options = {}) {
233
+ const target = prepareCredentialFile(projectRoot, relativePath);
234
+ // Interactive callers must not adopt a newer operator edit at this handoff.
235
+ if (Object.hasOwn(options, 'expectedStat') && !sameFile(options.expectedStat, target.stat)) {
236
+ throw new Error('Credential destination changed since it was read; refusing to replace it.');
237
+ }
238
+ atomicWrite(target, String(body), 0o600, { credential: true });
239
+ return { relativePath: target.root === target.project ? target.relativePath : target.absolute, status: 'written' };
240
+ }
241
+
242
+ function assertPrivateFile(stat) {
243
+ if (stat && POSIX && (stat.mode & 0o7777) !== 0o600) {
244
+ throw credentialPathError('CREDENTIAL_FILE_PERMISSIONS', 'Unsafe credential file mode: set mode 0600 and rotate if the credential was exposed.');
245
+ }
246
+ }
247
+
248
+ export function readCredentialFile(projectRoot, relativePath, { maxBytes = Infinity, checkGit = true } = {}) {
249
+ const target = safePath(projectRoot, relativePath);
250
+ if (!target.stat) return null;
251
+ assertPrivateFile(target.stat);
252
+ if (checkGit) {
253
+ const inspection = inspectCredentialFile(projectRoot, relativePath);
254
+ if (!inspection.safe) throw credentialPathError('CREDENTIAL_FILE_UNSAFE', `Unsafe credential file: ${relativePath} (${inspection.problems.join('; ')}).`);
255
+ }
256
+ const fd = fs.openSync(target.absolute, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | NOFOLLOW);
257
+ try {
258
+ const stat = fs.fstatSync(fd);
259
+ if (!sameFile(target.stat, stat)) throw credentialPathError('CREDENTIAL_FILE_CHANGED', 'Credential changed before reading.');
260
+ if (stat.size > maxBytes) throw credentialPathError('INVALID_CREDENTIAL_FILE', 'Credential exceeds the maximum file size.');
261
+ return fs.readFileSync(fd, 'utf8');
262
+ } finally { fs.closeSync(fd); }
263
+ }
264
+
265
+ export function removeCredentialFile(projectRoot, relativePath) {
266
+ const target = safePath(projectRoot, relativePath);
267
+ if (!target.stat) return;
268
+ assertUntracked(target);
269
+ fs.unlinkSync(target.absolute);
270
+ syncDirectory(path.dirname(target.absolute));
271
+ }
272
+
273
+ export function acquireCredentialLock(projectRoot, relativePath) {
274
+ prepareCredentialFile(projectRoot, relativePath);
275
+ const lockPath = `${relativePath}.connect.lock`;
276
+ let target = prepareCredentialFile(projectRoot, lockPath);
277
+ if (target.stat) {
278
+ let lock;
279
+ try { lock = JSON.parse(readCredentialFile(projectRoot, lockPath)); } catch {
280
+ throw new Error('Unsafe or unreadable credential lock; inspect its metadata before reconnecting.');
281
+ }
282
+ if (!Number.isSafeInteger(lock?.pid) || lock.pid < 1) throw new Error('Invalid credential lock.');
283
+ let running = true;
284
+ try { process.kill(lock.pid, 0); } catch (error) { if (error.code === 'ESRCH') running = false; }
285
+ if (running) throw new Error('Another connect process owns this credential file. Wait for it to finish.');
286
+ const latest = safePath(projectRoot, lockPath);
287
+ if (!sameFile(target.stat, latest.stat)) throw new Error('Credential lock changed during recovery.');
288
+ removeCredentialFile(projectRoot, lockPath);
289
+ target = prepareCredentialFile(projectRoot, lockPath);
290
+ }
291
+ let fd;
292
+ let lockStat;
293
+ try {
294
+ fd = fs.openSync(target.absolute, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW, 0o600);
295
+ if (POSIX) fs.fchmodSync(fd, 0o600);
296
+ fs.writeFileSync(fd, `${JSON.stringify({ pid: process.pid })}\n`, 'utf8');
297
+ fs.fsyncSync(fd);
298
+ lockStat = fs.fstatSync(fd);
299
+ } catch (error) {
300
+ if (error.code === 'EEXIST') throw new Error('Another connect process owns this credential file.');
301
+ throw error;
302
+ } finally { if (fd !== undefined) fs.closeSync(fd); }
303
+ syncDirectory(path.dirname(target.absolute));
304
+ let released = false;
305
+ const release = () => {
306
+ if (released) return;
307
+ released = true;
308
+ process.removeListener('exit', release);
309
+ const latest = safePath(projectRoot, lockPath);
310
+ if (sameFile(lockStat, latest.stat)) removeCredentialFile(projectRoot, lockPath);
311
+ };
312
+ process.once('exit', release);
313
+ return release;
314
+ }
package/runtime/hook.mjs CHANGED
@@ -158,7 +158,22 @@ export async function runHook(data, localConfig, dependencies = {}) {
158
158
  }
159
159
  await emitRuntimeEvent(api, config, context, 'tool_preflight', null, { tool_input_digest: context.tool_input_digest, install_check: config.installCheck === true });
160
160
  if (!fenceUnchanged()) return deny(accessChanged);
161
- const result = await admitAction(context, { api, config, ...dependencies.admission, beforeRelease: response => validateGitPublication(context, response) });
161
+ const operationKey = `operation:${session}:${context.tool_use_id}`;
162
+ const rememberOperation = ['claude', 'codex'].includes(config.host) && config.privateKeyBase64 && !config.installCheck
163
+ ? actionId => {
164
+ const current = store.update(operationKey, prior => prior || { action_id: actionId, input_digest: context.tool_input_digest });
165
+ return current.action_id === actionId && current.input_digest === context.tool_input_digest;
166
+ } : undefined;
167
+ const result = await admitAction(context, { api, config, ...dependencies.admission, rememberOperation,
168
+ beforeRelease: response => validateGitPublication(context, response) });
169
+ const dispatchBody = result.hookOperationId ? { hook_action_id: result.hookOperationId, tool_input_digest: context.tool_input_digest } : null;
170
+ const cancelUnreleased = async () => {
171
+ if (!dispatchBody || !fenceUnchanged()) return;
172
+ await api.request('PATCH', `/api/actions/${result.hookOperationId}`, {
173
+ ...dispatchBody, status: 'cancelled', error_message: 'CLIENT_BLOCKED', timestamp_end: new Date(now()).toISOString(),
174
+ output_summary: 'The hook stopped the tool before releasing it to the host.',
175
+ }, { timeoutMs: 1500 });
176
+ };
162
177
  if (result.degraded) {
163
178
  rememberGap(store, result.reason, now());
164
179
  await emitRuntimeEvent(api, config, context, 'governance_unavailable', null, { decision: result.decision === 'allow' ? 'guard_unavailable' : 'guard_unavailable_blocked' });
@@ -174,12 +189,24 @@ export async function runHook(data, localConfig, dependencies = {}) {
174
189
  try {
175
190
  store.write(`action:${context.tool_use_id}`, { schema: 'osuite.node_action.v1', action_id: result.actionId,
176
191
  runtime_session_id: session, tool_name: data.tool_name, tool_use_id: context.tool_use_id,
177
- tool_input_digest: context.tool_input_digest, require_signature: config.signatureMode === 'required', install_check: config.installCheck === true });
178
- } catch { return deny('Cannot persist the exact-action receipt state. The admitted tool was not released; reconcile its action in Studio before retrying.'); }
192
+ tool_input_digest: context.tool_input_digest, require_signature: config.signatureMode === 'required', install_check: config.installCheck === true,
193
+ ...(dispatchBody ? { hook_dispatch: true } : {}) });
194
+ } catch {
195
+ await cancelUnreleased();
196
+ return deny('Cannot persist the exact-action receipt state. The admitted tool was not released; reconcile its action in Studio before retrying.');
197
+ }
198
+ if (dispatchBody) {
199
+ const claim = await api.request('POST', `/api/actions/${result.hookOperationId}/dispatch`, dispatchBody, { timeoutMs: 2000 });
200
+ if (!claim.ok || claim.status !== 201 || claim.body?.action_id !== result.hookOperationId
201
+ || !Number.isFinite(Date.parse(claim.body.hook_dispatch_at))) {
202
+ return deny(`Dispatch was not confirmed for ${result.hookOperationId}. No tool was released by this hook. Reconcile in Studio.`);
203
+ }
204
+ }
179
205
  updatePending(store, context);
180
206
  await emitRuntimeEvent(api, config, context, 'tool_allowed', result.actionId, { decision: result.decision, install_check: config.installCheck === true });
181
207
  return checkedNote(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.' : '');
182
208
  }
209
+ if (result.reason === 'action_evidence_changed') await cancelUnreleased();
183
210
  if (result.decision === 'require_approval') {
184
211
  if (result.observeOnly !== true) updatePending(store, context, { action_id: result.actionId, agent_id: config.agentId,
185
212
  runtime_session_id: session, tool_input_digest: context.tool_input_digest, fingerprint: cavaFingerprint(result.response) });
@@ -14,7 +14,13 @@ export function terminalOutcome(config, data, now = Date.now()) {
14
14
  const structured = isObject(response.structuredContent) ? response.structuredContent : response;
15
15
  const error = [response, structured].some(value => value.error || value.isError === true || value.is_error === true || value.interrupted === true);
16
16
  const exitCode = Object.hasOwn(response, 'exit_code') ? response.exit_code : structured.exit_code;
17
- if (error) {
17
+ if (response.interrupted === true || structured.interrupted === true) {
18
+ status = 'cancelled';
19
+ summary = 'Runtime reported that the tool was interrupted.';
20
+ } else if (config.host === 'codex' && structured.error_kind === 'sandbox_launch_failed') {
21
+ status = 'failed';
22
+ summary = 'Codex reported a sandbox launch failure.';
23
+ } else if (error) {
18
24
  status = 'failed';
19
25
  summary = 'Runtime reported a tool error; details omitted.';
20
26
  } else if (Number.isSafeInteger(exitCode)) {
@@ -33,14 +39,14 @@ export function terminalOutcome(config, data, now = Date.now()) {
33
39
 
34
40
  function validReport(report, provenance) {
35
41
  const outcome = report?.outcome;
36
- return isObject(outcome) && (provenance.schema === 'osuite.diagnostic_terminal_report.v1' ? outcome.status === 'cancelled' : ['completed', 'failed'].includes(outcome.status))
42
+ return isObject(outcome) && (provenance.schema === 'osuite.diagnostic_terminal_report.v1' ? outcome.status === 'cancelled' : ['completed', 'failed', 'cancelled'].includes(outcome.status))
37
43
  && Object.keys(outcome).sort().join(',') === 'output_summary,status,timestamp_end'
38
44
  && typeof outcome.output_summary === 'string' && Number.isFinite(Date.parse(outcome.timestamp_end))
39
45
  && typeof report.action_reported === 'boolean'
40
46
  && canonicalJson(report.provenance) === canonicalJson(provenance);
41
47
  }
42
48
 
43
- export async function recordOutcome(config, data, { api, store, now = Date.now } = {}) {
49
+ export async function recordOutcome(config, data, { api, store, now = Date.now, nativeOutcome = null } = {}) {
44
50
  if (!isObject(data)) return pending('invalid_hook_input');
45
51
  const toolId = deriveToolUseId(data);
46
52
  if (!safeId(toolId)) return pending('invalid_tool_id');
@@ -61,7 +67,9 @@ export async function recordOutcome(config, data, { api, store, now = Date.now }
61
67
  if (report !== undefined && !validReport(report, provenance)) return pending('untrusted_outcome_state');
62
68
  if (report === undefined) {
63
69
  const outcome = state.install_check ? { status: 'cancelled', timestamp_end: new Date(now()).toISOString(),
64
- output_summary: 'Inert diagnostic hook probe; the tool was not executed.' } : terminalOutcome(config, data, now());
70
+ output_summary: 'Inert diagnostic hook probe; the tool was not executed.' } : nativeOutcome
71
+ ? { status: nativeOutcome.status, output_summary: nativeOutcome.summary, timestamp_end: new Date(now()).toISOString() }
72
+ : terminalOutcome(config, data, now());
65
73
  if (!outcome) return pending('terminal_evidence_missing');
66
74
  report = { outcome, action_reported: false, provenance };
67
75
  state.outcome_report = report;
@@ -69,7 +77,10 @@ export async function recordOutcome(config, data, { api, store, now = Date.now }
69
77
  }
70
78
  const outcome = report.outcome;
71
79
  if (!report.action_reported) {
72
- const response = await api.request('PATCH', `/api/actions/${encodeURIComponent(state.action_id)}`, outcome, { timeoutMs: 2000 });
80
+ const response = await api.request('PATCH', `/api/actions/${encodeURIComponent(state.action_id)}`, {
81
+ ...outcome,
82
+ ...(state.hook_dispatch ? { hook_action_id: state.action_id, tool_input_digest: state.tool_input_digest } : {}),
83
+ }, { timeoutMs: 2000 });
73
84
  const action = response.body?.action;
74
85
  if (!response.ok || response.status !== 200 || !isObject(action)
75
86
  || action.action_id !== state.action_id || action.status !== outcome.status || action.timestamp_end !== outcome.timestamp_end) {
@@ -82,7 +93,7 @@ export async function recordOutcome(config, data, { api, store, now = Date.now }
82
93
  const event = {
83
94
  event_id: `evt_outcome_${sha256(`${state.runtime_session_id}|${state.action_id}|${toolId}|${outcome.timestamp_end}`).slice(0, 24)}`,
84
95
  runtime_session_id: state.runtime_session_id,
85
- event_type: state.install_check ? 'turn_stopped' : outcome.status === 'completed' ? 'tool_completed' : 'tool_failed',
96
+ event_type: outcome.status === 'cancelled' ? 'turn_stopped' : outcome.status === 'completed' ? 'tool_completed' : 'tool_failed',
86
97
  tool_name: state.tool_name, tool_use_id: toolId, action_id: state.action_id,
87
98
  timestamp: outcome.timestamp_end,
88
99
  payload: { status: outcome.status, output_summary: outcome.output_summary, ...(state.install_check ? { install_check: true } : {}) },
@@ -77,7 +77,10 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
77
77
  }
78
78
  }
79
79
  const controller = new AbortController();
80
- const timer = setTimeout(() => controller.abort(), Math.max(1, Math.min(options.timeoutMs ?? timeoutMs, 30000)));
80
+ const totalMs = Math.max(1, Math.min(options.timeoutMs ?? timeoutMs, 30000));
81
+ const headMs = Math.max(1, Math.min(options.headersTimeoutMs ?? totalMs, totalMs));
82
+ const started = performance.now();
83
+ let timer = setTimeout(() => controller.abort(), headMs);
81
84
  let status = 0;
82
85
  try {
83
86
  const response = await fetchImpl(baseUrl + endpoint, {
@@ -88,6 +91,16 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
88
91
  ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
89
92
  });
90
93
  status = response.status;
94
+ if (headMs < totalMs) {
95
+ const elapsed = performance.now() - started;
96
+ if (controller.signal.aborted || elapsed >= headMs) {
97
+ controller.abort();
98
+ return { ok: false, status, error: 'timeout' };
99
+ }
100
+ // A timely header buys only the remainder of the original total, never a fresh timeout per chunk.
101
+ clearTimeout(timer);
102
+ timer = setTimeout(() => controller.abort(), Math.max(1, totalMs - elapsed));
103
+ }
91
104
  if (status < 200 || status >= 300) {
92
105
  await response.body?.cancel();
93
106
  return { ok: false, status, error: 'http_error' };
@@ -110,6 +123,9 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
110
123
  try { parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); } catch {
111
124
  return { ok: false, status, error: 'invalid_response' };
112
125
  }
126
+ if (headMs < totalMs && (controller.signal.aborted || performance.now() - started >= totalMs)) {
127
+ return { ok: false, status, error: 'timeout' };
128
+ }
113
129
  if (!isObject(parsed)) return { ok: false, status, error: 'invalid_response' };
114
130
  return { ok: true, status, body: parsed };
115
131
  } catch (error) {
package/runtime/shell.mjs CHANGED
@@ -48,7 +48,20 @@ export function parseShell(command) {
48
48
  return { segments, errors: [...new Set(errors)] };
49
49
  }
50
50
 
51
- function unwrap(tokens) {
51
+ function stdoutPrintfArgv(argv) {
52
+ if (argv[0] !== 'printf') return false;
53
+ const format = argv[1] === '--' ? argv[2] : argv[1];
54
+ // Bash printf -v assigns a variable. %n can assign through a format operand.
55
+ return typeof format === 'string' && (argv[1] === '--' || !format.startsWith('-'))
56
+ && !/%[-+#0 '.0-9*$]*n/.test(format.replace(/%%/g, ''));
57
+ }
58
+
59
+ export function isStdoutPrintf(command) {
60
+ const { segments, errors } = parseShell(command);
61
+ return errors.length === 0 && segments.length === 1 && stdoutPrintfArgv(segments[0]);
62
+ }
63
+
64
+ export function unwrapShellArgv(tokens) {
52
65
  let argv = [...tokens];
53
66
  for (let depth = 0; depth < 8 && argv.length; depth += 1) {
54
67
  while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0] || '')) argv.shift();
@@ -112,7 +125,7 @@ function boundedObservation(exe, args) {
112
125
  }
113
126
 
114
127
  function classifyArgv(tokens, cwd, depth) {
115
- const argv = unwrap(tokens), exe = basename(argv[0]), args = argv.slice(1);
128
+ const argv = unwrapShellArgv(tokens), exe = basename(argv[0]), args = argv.slice(1);
116
129
  if (!exe) return incomplete(tokens, cwd, ['unsupported_wrapper']);
117
130
  if (shells.has(exe)) {
118
131
  const index = args.findIndex(arg => /^-[a-z]*c$/.test(arg));
@@ -121,6 +134,7 @@ function classifyArgv(tokens, cwd, depth) {
121
134
  }
122
135
  const canonical = { runtime: 'bash', executable: exe, operation: args[0] || '', tool_category: 'other', cwd, systems_touched: [exe] };
123
136
  const classified = (type, risk, reversible, category = 'deployment') => result(type, risk, reversible, { ...canonical, tool_category: category });
137
+ if (stdoutPrintfArgv(tokens)) return classified('other', 10, true, 'observation');
124
138
  if (exe === 'git') {
125
139
  let index = 0;
126
140
  while (index < args.length && args[index].startsWith('-')) { const flag = args[index++]; if (gitValueFlags.has(flag)) index += 1; }