osuite 2.14.2 → 2.16.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
@@ -137,12 +137,15 @@ export async function runHook(data, localConfig, dependencies = {}) {
137
137
  const checkedNote = message => fenceUnchanged() ? note(message) : pre ? deny(accessChanged) : note(accessChanged);
138
138
  const config = { ...applyPosture(localConfig, remote.posture), ruleRollout: remote.ruleRollout,
139
139
  orgId: remote.orgId || localConfig.orgId };
140
+ const postureEvidence = { local_mode: localConfig.mode, effective_mode: config.mode,
141
+ source: remote.source, scope: remote.scope || null, valid_until: remote.validUntil || null,
142
+ revision: remote.revision, fallback: remote.source === 'unavailable' ? config.guardFailureMode : null };
140
143
  api = trackPostureRejections(dependencies.api || apiFactory(config), localConfig, store, now);
141
144
  if (event === 'Stop') {
142
145
  const stopped = await stopHook(data, config, api, store, fenceUnchanged);
143
146
  return fenceUnchanged() ? stopped : note(accessChanged);
144
147
  }
145
- if (remote.blocked) return pre ? deny('Verified runtime posture is unavailable or expired. Execution is blocked; reconnect or restore access.')
148
+ if (remote.blocked) return pre ? deny('POSTURE_UNAVAILABLE. Verified runtime posture is unavailable or expired. Execution is blocked. Reconnect or restore access.')
146
149
  : note('Verified runtime posture is unavailable. Enforce hooks will block execution until it can be verified.');
147
150
  if (!pre && event !== 'SessionStart' && event !== 'SessionEnd') return note('Unsupported hook event; no execution decision was made.');
148
151
  const session = await openSession(api, config, data, store, now());
@@ -156,12 +159,34 @@ export async function runHook(data, localConfig, dependencies = {}) {
156
159
  rememberGap(store, 'posture_unavailable', now());
157
160
  return checkedNote('Not governed: remote posture is unavailable; explicit observe mode does not enforce OSuite policy.');
158
161
  }
159
- await emitRuntimeEvent(api, config, context, 'tool_preflight', null, { tool_input_digest: context.tool_input_digest, install_check: config.installCheck === true });
162
+ await emitRuntimeEvent(api, config, context, 'tool_preflight', null, { tool_input_digest: context.tool_input_digest,
163
+ install_check: config.installCheck === true, runtime_posture: postureEvidence });
160
164
  if (!fenceUnchanged()) return deny(accessChanged);
161
- const result = await admitAction(context, { api, config, ...dependencies.admission, beforeRelease: response => validateGitPublication(context, response) });
165
+ const operationKey = `operation:${session}:${context.tool_use_id}`;
166
+ const rememberOperation = ['claude', 'codex'].includes(config.host) && config.privateKeyBase64 && !config.installCheck
167
+ ? actionId => {
168
+ const current = store.update(operationKey, prior => prior || { action_id: actionId, input_digest: context.tool_input_digest });
169
+ return current.action_id === actionId && current.input_digest === context.tool_input_digest;
170
+ } : undefined;
171
+ if (rememberOperation && config.mode === 'observe' && remote.source === 'remote' && !remote.ruleRollout?.enabled) {
172
+ context.hook_observation = { runtime_id: config.runtimeId, provider: config.provider ?? null,
173
+ local_mode: localConfig.mode, valid_until: remote.validUntil, revision: remote.revision };
174
+ }
175
+ const result = await admitAction(context, { api, config, ...dependencies.admission, rememberOperation,
176
+ beforeRelease: response => validateGitPublication(context, response) });
177
+ const dispatchBody = result.hookOperationId ? { hook_action_id: result.hookOperationId, tool_input_digest: context.tool_input_digest } : null;
178
+ const cancelUnreleased = async () => {
179
+ if (!dispatchBody || !fenceUnchanged()) return;
180
+ await api.request('PATCH', `/api/actions/${result.hookOperationId}`, {
181
+ ...dispatchBody, status: 'cancelled', error_message: 'CLIENT_BLOCKED', timestamp_end: new Date(now()).toISOString(),
182
+ output_summary: 'The hook stopped the tool before releasing it to the host.',
183
+ }, { timeoutMs: 1500 });
184
+ };
162
185
  if (result.degraded) {
163
186
  rememberGap(store, result.reason, now());
164
- await emitRuntimeEvent(api, config, context, 'governance_unavailable', null, { decision: result.decision === 'allow' ? 'guard_unavailable' : 'guard_unavailable_blocked' });
187
+ await emitRuntimeEvent(api, config, context, 'governance_unavailable', null, { decision: result.decision === 'allow' ? 'guard_unavailable' : 'guard_unavailable_blocked',
188
+ phase: result.phase || 'guard', retry_same_operation: result.retrySameOperation === true,
189
+ retry_after_seconds: result.retryAfterSeconds ?? null });
165
190
  return result.decision === 'allow' ? checkedNote('Not governed: the guard is unavailable and this verified posture explicitly allows availability fallback. No authorization or completion is claimed.')
166
191
  : deny('Guard unavailable. Verified policy requires blocking this call.');
167
192
  }
@@ -170,16 +195,30 @@ export async function runHook(data, localConfig, dependencies = {}) {
170
195
  await emitRuntimeEvent(api, config, context, 'install_check_policy_result', null, { decision: result.decision, approval_state: 'not_requested', install_check: true });
171
196
  return deny('Install check: policy would require human approval. No request was sent to reviewers and no tool was executed.');
172
197
  }
173
- if (result.authorized) {
198
+ if (result.authorized || result.observeRecorded) {
174
199
  try {
175
200
  store.write(`action:${context.tool_use_id}`, { schema: 'osuite.node_action.v1', action_id: result.actionId,
176
201
  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.'); }
202
+ tool_input_digest: context.tool_input_digest, require_signature: config.signatureMode === 'required', install_check: config.installCheck === true,
203
+ ...(dispatchBody ? { hook_dispatch: true } : {}) });
204
+ } catch {
205
+ await cancelUnreleased();
206
+ return deny('Cannot persist the exact-action receipt state. The admitted tool was not released; reconcile its action in Studio before retrying.');
207
+ }
208
+ if (dispatchBody) {
209
+ const claim = await api.request('POST', `/api/actions/${result.hookOperationId}/dispatch`, dispatchBody, { timeoutMs: 2000 });
210
+ if (!claim.ok || claim.status !== 201 || claim.body?.action_id !== result.hookOperationId
211
+ || !Number.isFinite(Date.parse(claim.body.hook_dispatch_at))) {
212
+ return deny(`Dispatch was not confirmed for ${result.hookOperationId}. No tool was released by this hook. Reconcile in Studio.`);
213
+ }
214
+ }
179
215
  updatePending(store, context);
180
- await emitRuntimeEvent(api, config, context, 'tool_allowed', result.actionId, { decision: result.decision, install_check: config.installCheck === true });
216
+ await emitRuntimeEvent(api, config, context, 'tool_allowed', result.actionId, { decision: result.observeRecorded ? 'observed_dispatch' : result.decision,
217
+ ...(result.observeRecorded ? { observe_only: true, policy_recommendation: result.decision } : {}),
218
+ approval_required: false, install_check: config.installCheck === true });
181
219
  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
220
  }
221
+ if (result.reason === 'action_evidence_changed') await cancelUnreleased();
183
222
  if (result.decision === 'require_approval') {
184
223
  if (result.observeOnly !== true) updatePending(store, context, { action_id: result.actionId, agent_id: config.agentId,
185
224
  runtime_session_id: session, tool_input_digest: context.tool_input_digest, fingerprint: cavaFingerprint(result.response) });
@@ -187,7 +226,8 @@ export async function runHook(data, localConfig, dependencies = {}) {
187
226
  return result.observeOnly === true ? checkedNote('Observe mode: this call would require human approval; it is not authorized by a reviewer.')
188
227
  : deny(`Human approval is still required for action ${result.actionId}. Do not run or automatically retry it. Review it in OSuite Studio.`);
189
228
  }
190
- await emitRuntimeEvent(api, config, context, 'tool_blocked', result.actionId, { decision: result.observeOnly === true ? 'observe_would_block' : 'block', reason: result.reason });
229
+ await emitRuntimeEvent(api, config, context, 'tool_blocked', result.actionId, { decision: result.observeOnly === true ? 'observe_would_block' : 'block', reason: result.reason,
230
+ phase: result.phase || null, retry_same_operation: result.retrySameOperation === true, retry_after_seconds: result.retryAfterSeconds ?? null });
191
231
  return result.observeOnly === true ? checkedNote('Observe mode: OSuite policy would block this call. It is not authorized by OSuite.')
192
232
  : deny(`OSuite policy did not authorize this exact action (${result.reason}). Do not retry automatically.`);
193
233
  } catch {
@@ -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 } : {}) },
@@ -232,7 +232,7 @@ export async function resolveRemotePosture(config, { api, store, now = Date.now(
232
232
  entry = cacheEntry(saved, config, now); cached = entry?.document;
233
233
  if (rejectionFenceUnchanged(config, store, rejectionFence) && cached && canonicalJson(cached) === canonicalJson(document)) {
234
234
  return { available: true, blocked: false, source: 'remote', posture: document.posture, revision: document.revision,
235
- ruleRollout: document.rule_rollout, orgId: document.org_id, rejectionFence };
235
+ validUntil: document.valid_until, scope: response.body.scope, ruleRollout: document.rule_rollout, orgId: document.org_id, rejectionFence };
236
236
  }
237
237
  } catch {
238
238
  const posture = offlinePosture(offlinePosture(localPosture(config), readEntry(store, config, now)?.document?.posture), document.posture);
@@ -246,7 +246,7 @@ export async function resolveRemotePosture(config, { api, store, now = Date.now(
246
246
  && validNegotiation(cached, config, now)) {
247
247
  if (capable && !matchesAcknowledgement(cached, acknowledged)) return { available: false, blocked: true, source: 'unavailable', posture, revision: cached.revision };
248
248
  return { available: true, blocked: false, source: 'cache', posture, revision: cached.revision,
249
- ruleRollout: cached.rule_rollout, orgId: cached.org_id, rejectionFence };
249
+ validUntil: cached.valid_until, ruleRollout: cached.rule_rollout, orgId: cached.org_id, rejectionFence };
250
250
  }
251
251
  return { available: false, blocked: rejected || fenced || entry?.rejected === true || capable || posture.mode !== 'observe',
252
252
  source: 'unavailable', posture, revision: cached?.revision || null, rejectionFence };
@@ -102,8 +102,10 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
102
102
  timer = setTimeout(() => controller.abort(), Math.max(1, totalMs - elapsed));
103
103
  }
104
104
  if (status < 200 || status >= 300) {
105
+ const retryAfter = response.headers?.get('retry-after');
106
+ const retryAfterSeconds = /^\d{1,4}$/.test(retryAfter || '') && Number(retryAfter) <= 3600 ? Number(retryAfter) : null;
105
107
  await response.body?.cancel();
106
- return { ok: false, status, error: 'http_error' };
108
+ return { ok: false, status, error: 'http_error', ...(retryAfterSeconds !== null ? { retryAfterSeconds } : {}) };
107
109
  }
108
110
  const reader = response.body?.getReader();
109
111
  if (!reader) return { ok: false, status, error: 'invalid_response' };
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; }