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.
package/codexTrust.mjs ADDED
@@ -0,0 +1,107 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { loadRuntimeConfig } from './runtime/config.mjs';
6
+ import { canonicalJson, createApiClient, sha256 } from './runtime/protocol.mjs';
7
+ import { emitRuntimeEvent, openSession } from './runtime/hook.mjs';
8
+ import { createStateStore } from './runtime/state.mjs';
9
+
10
+ const review = 'Open codex in this project, trust the workspace if prompted, then use /hooks to review and trust the OSuite entries.';
11
+ const expected = { PreToolUse: 'preToolUse', PostToolUse: 'postToolUse', SessionStart: 'sessionStart', Stop: 'stop' };
12
+
13
+ function listNativeHooks({ projectRoot, env }) {
14
+ return new Promise(resolve => {
15
+ const child = spawn('codex', ['app-server', '--listen', 'stdio://'], {
16
+ cwd: projectRoot, env, stdio: ['pipe', 'pipe', 'ignore'],
17
+ });
18
+ const lines = createInterface({ input: child.stdout });
19
+ let finished = false;
20
+ let bytes = 0;
21
+ const finish = value => {
22
+ if (finished) return;
23
+ finished = true;
24
+ clearTimeout(timeout);
25
+ lines.close();
26
+ child.stdin.destroy();
27
+ child.kill();
28
+ resolve(value);
29
+ };
30
+ const timeout = setTimeout(() => finish(null), 3000);
31
+ child.on('error', () => finish(null));
32
+ child.on('close', () => finish(null));
33
+ child.stdin.on('error', () => finish(null));
34
+ child.stdout.on('data', chunk => { bytes += chunk.length; if (bytes > 524288) finish(null); });
35
+ lines.on('line', line => {
36
+ if (finished) return;
37
+ try {
38
+ const reply = JSON.parse(line);
39
+ if (reply.id === 2) finish(reply.result?.data?.find(entry => entry.cwd === projectRoot) || null);
40
+ } catch { finish(null); }
41
+ });
42
+ const messages = [
43
+ { id: 1, method: 'initialize', params: { clientInfo: { name: 'osuite', version: '1' }, capabilities: { experimentalApi: true } } },
44
+ { method: 'initialized' },
45
+ { id: 2, method: 'hooks/list', params: { cwds: [projectRoot] } },
46
+ ];
47
+ child.stdin.write(messages.map(message => JSON.stringify(message) + '\n').join(''));
48
+ });
49
+ }
50
+
51
+ export async function inspectCodexTrust({ projectRoot, installation, env = process.env, listHooks = listNativeHooks }) {
52
+ if (!installation?.pretool) return { status: 'missing', guidance: 'Run osuite connect codex in this project.' };
53
+ if (!installation.hostEnabled) return { status: 'disabled', guidance: 'Review the project hook enablement in Codex.' };
54
+ const root = fs.realpathSync(projectRoot);
55
+ const settings = path.join(root, '.codex/hooks.json');
56
+ const registrations = installation.diagnostics?.registrations || [];
57
+ if (installation.diagnostics?.status !== 'current' || !fs.lstatSync(settings, { throwIfNoEntry: false })?.isFile()
58
+ || Object.keys(expected).some(event => registrations.filter(hook => hook.event === event).length !== 1)) {
59
+ return { status: 'modified', guidance: 'Verify the installed OSuite hook files, then review their trust in Codex with /hooks.' };
60
+ }
61
+ const native = await listHooks({ projectRoot: root, env });
62
+ if (!Array.isArray(native?.hooks)) return { status: 'unavailable', guidance: 'Use a Codex CLI that supports hooks/list, then run osuite doctor.' };
63
+ const current = registrations.filter(hook => Object.hasOwn(expected, hook.event)).map(hook => native.hooks.find(entry =>
64
+ entry.sourcePath === settings && entry.eventName === expected[hook.event] && entry.command === hook.command));
65
+ if (current.some(hook => hook?.trustStatus === 'modified')) return { status: 'modified', guidance: review };
66
+ if (current.some(hook => !hook || !hook.enabled || hook.async || hook.matcher || !['trusted', 'managed'].includes(hook.trustStatus))) {
67
+ return { status: 'untrusted', guidance: review };
68
+ }
69
+ return { status: 'trusted', fingerprint: sha256(canonicalJson(current.map(hook => hook.currentHash || hook.command))) };
70
+ }
71
+
72
+ export async function auditCodexTrust(projectRoot, env, trust) {
73
+ try {
74
+ const config = loadRuntimeConfig({ host: 'codex', installDir: path.join(projectRoot, '.codex'), env });
75
+ if (!config.apiKey || !config.baseUrl) return;
76
+ const store = createStateStore(config);
77
+ const sessionId = `codex-trust-${sha256(fs.realpathSync(projectRoot)).slice(0, 32)}`;
78
+ const key = `trust:${sessionId}`;
79
+ const current = { status: trust.status, fingerprint: trust.fingerprint || null };
80
+ const previous = store.read(key);
81
+ if (canonicalJson(previous) === canonicalJson(current)) return;
82
+ const api = createApiClient(config);
83
+ await openSession(api, config, { session_id: sessionId }, store);
84
+ const response = await emitRuntimeEvent(api, config, { runtime_session_id: sessionId }, 'hook_trust_changed', null,
85
+ { previous: previous?.status || null, ...current });
86
+ if (response.ok && response.body?.ok) store.write(key, current);
87
+ } catch { /* The current trust verdict is still printed locally. */ }
88
+ }
89
+
90
+ export function codexExecArguments(args) {
91
+ const flagValues = new Set(['--model', '--sandbox']);
92
+ const flags = new Set(['--json', '--ephemeral', '--skip-git-repo-check']);
93
+ let prompt = false;
94
+ for (let index = 0; index < args.length; index += 1) {
95
+ const value = args[index];
96
+ if (value === '--') return args.length === index + 2 && !prompt;
97
+ if (flags.has(value) && !prompt) continue;
98
+ if (flagValues.has(value) && !prompt && args[index + 1] && !args[index + 1].startsWith('-')) {
99
+ const option = args[++index];
100
+ if (value === '--sandbox' && !['read-only', 'workspace-write'].includes(option)) return false;
101
+ continue;
102
+ }
103
+ if (value.startsWith('-') || prompt || ['resume', 'review'].includes(value)) return false;
104
+ prompt = true;
105
+ }
106
+ return prompt;
107
+ }
package/credentials.js CHANGED
@@ -1,238 +1 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import crypto from 'node:crypto';
4
- import { spawnSync } from 'node:child_process';
5
-
6
- export const CREDENTIAL_PATHS = ['.codex/.env', '.claude/.env', '.cursor/.env', '.osuite/.env'];
7
- const POSIX = process.platform !== 'win32';
8
- const NOFOLLOW = fs.constants.O_NOFOLLOW || 0;
9
-
10
- function metadata(file) {
11
- try { return fs.lstatSync(file); } catch (error) {
12
- if (error.code === 'ENOENT') return null;
13
- throw error;
14
- }
15
- }
16
-
17
- function sameFile(a, b) {
18
- return !a && !b || Boolean(a && b && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs);
19
- }
20
-
21
- function owned(stat) {
22
- return !POSIX || typeof process.getuid !== 'function' || stat.uid === process.getuid();
23
- }
24
-
25
- function safePath(projectRoot, relativePath, { create = false } = {}) {
26
- const root = fs.realpathSync(projectRoot);
27
- const absolute = path.resolve(root, relativePath);
28
- const relative = path.relative(root, absolute);
29
- if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
30
- throw new Error('Credential path must stay inside the project.');
31
- }
32
- let directory = root;
33
- const parts = relative.split(path.sep).slice(0, -1);
34
- for (const part of ['', ...parts]) {
35
- if (part) directory = path.join(directory, part);
36
- let stat = metadata(directory);
37
- if (!stat && create) {
38
- fs.mkdirSync(directory, { mode: 0o700 });
39
- if (POSIX) fs.chmodSync(directory, 0o700);
40
- syncDirectory(path.dirname(directory));
41
- stat = metadata(directory);
42
- }
43
- if (!stat) continue;
44
- if (stat.isSymbolicLink()) throw new Error('Refusing a symlink in the credential path.');
45
- if (!stat.isDirectory()) throw new Error('Credential parent must be a directory.');
46
- if (!owned(stat) || POSIX && (stat.mode & 0o022)) throw new Error('Unsafe credential directory ownership or write permissions.');
47
- }
48
- const stat = metadata(absolute);
49
- if (stat?.isSymbolicLink()) throw new Error('Refusing a symlinked credential file.');
50
- if (stat && (!stat.isFile() || stat.nlink !== 1 || !owned(stat))) {
51
- throw new Error('Unsafe credential file type, links, or ownership.');
52
- }
53
- return { root, absolute, relativePath: relative.split(path.sep).join('/'), stat };
54
- }
55
-
56
- function runGit(cwd, args) {
57
- // Inherited GIT_DIR/INDEX_FILE must not hide a tracked project credential.
58
- const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
59
- // Metadata inspection must not execute repository-configured fsmonitor commands.
60
- return spawnSync('git', ['-c', 'core.fsmonitor=false', '-C', cwd, ...args], {
61
- encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'],
62
- });
63
- }
64
-
65
- function repositoryRoots(root, absolute) {
66
- const roots = new Set();
67
- let current = root;
68
- for (const part of ['', ...path.relative(root, path.dirname(absolute)).split(path.sep).filter(Boolean)]) {
69
- if (part) current = path.join(current, part);
70
- if (!metadata(current)) continue;
71
- const result = runGit(current, ['rev-parse', '--show-toplevel']);
72
- if (result.error) throw new Error('Git is required to check whether the credential path is tracked.');
73
- if (result.status === 0) roots.add(result.stdout.trim());
74
- else if (!result.stderr.includes('not a git repository')) throw new Error('Unable to verify Git credential protection.');
75
- }
76
- return [...roots];
77
- }
78
-
79
- function isTracked(root, absolute) {
80
- return repositoryRoots(root, absolute).some((repository) => {
81
- // A tracked .ENV aliases .env on common macOS/Windows filesystems.
82
- const result = runGit(repository, ['ls-files', '--error-unmatch', '--', `:(icase,literal)${path.relative(repository, absolute)}`]);
83
- if (result.status !== 0 && result.status !== 1) throw new Error('Unable to inspect the Git index for credentials.');
84
- return result.status === 0;
85
- });
86
- }
87
-
88
- function assertUntracked(target) {
89
- 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.');
90
- }
91
-
92
- function syncDirectory(directory) {
93
- if (!POSIX) return;
94
- const fd = fs.openSync(directory, fs.constants.O_RDONLY | (fs.constants.O_DIRECTORY || 0) | NOFOLLOW);
95
- try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
96
- }
97
-
98
- function atomicWrite(target, body, mode, { credential = false } = {}) {
99
- const temporary = `${target.absolute}.osuite-tmp-${crypto.randomBytes(12).toString('hex')}`;
100
- let fd;
101
- try {
102
- fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW, mode);
103
- if (POSIX) fs.fchmodSync(fd, mode);
104
- fs.writeFileSync(fd, body, 'utf8');
105
- fs.fsyncSync(fd);
106
- fs.closeSync(fd);
107
- fd = undefined;
108
- const latest = safePath(target.root, target.relativePath);
109
- if (!sameFile(target.stat, latest.stat)) throw new Error('Credential destination changed during the write; refusing to replace it.');
110
- if (credential) assertUntracked(latest);
111
- fs.renameSync(temporary, target.absolute);
112
- syncDirectory(path.dirname(target.absolute));
113
- } finally {
114
- if (fd !== undefined) fs.closeSync(fd);
115
- try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
116
- }
117
- }
118
-
119
- function protectIgnore(target) {
120
- const directory = path.dirname(target.absolute);
121
- const ignorePath = path.join(path.dirname(target.relativePath), '.gitignore');
122
- const ignore = safePath(target.root, ignorePath);
123
- const body = ignore.stat ? fs.readFileSync(ignore.absolute, 'utf8') : '';
124
- const name = path.basename(target.absolute);
125
- // A rule in the credential's own directory works in monorepos and nested repos.
126
- const rules = [`/${name}`, `/${name}.osuite-tmp-*`];
127
- const missing = rules.filter((rule) => !body.split(/\r?\n/).includes(rule));
128
- if (missing.length) {
129
- atomicWrite(ignore, `${body}${body && !body.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`, ignore.stat ? ignore.stat.mode & 0o777 : 0o644);
130
- }
131
- if (repositoryRoots(target.root, target.absolute).length) {
132
- const result = runGit(directory, ['check-ignore', '--no-index', '--', target.absolute]);
133
- if (result.status !== 0) throw new Error('Credential path is not ignored by Git; check conflicting ignore rules.');
134
- }
135
- }
136
-
137
- export function inspectCredentialFile(projectRoot, relativePath) {
138
- const result = { relativePath, exists: false, safe: false, problems: [], mode: null };
139
- try {
140
- const target = safePath(projectRoot, relativePath);
141
- result.exists = Boolean(target.stat);
142
- if (target.stat) {
143
- result.mode = POSIX ? `0${(target.stat.mode & 0o777).toString(8).padStart(3, '0')}` : null;
144
- if (POSIX && (target.stat.mode & 0o777) !== 0o600) result.problems.push(`unsafe mode ${result.mode}; expected 0600`);
145
- }
146
- if (isTracked(target.root, target.absolute)) result.problems.push('tracked by Git');
147
- if (target.stat) {
148
- const roots = repositoryRoots(target.root, target.absolute);
149
- if (roots.length && runGit(path.dirname(target.absolute), ['check-ignore', '--no-index', '--', target.absolute]).status !== 0) result.problems.push('not ignored by Git');
150
- }
151
- result.safe = result.problems.length === 0;
152
- } catch (error) {
153
- result.exists = true;
154
- result.problems.push(error.message);
155
- }
156
- return result;
157
- }
158
-
159
- export function prepareCredentialFile(projectRoot, relativePath) {
160
- let target = safePath(projectRoot, relativePath);
161
- assertUntracked(target);
162
- target = safePath(projectRoot, relativePath, { create: true });
163
- protectIgnore(target);
164
- return target;
165
- }
166
-
167
- export function writeCredentialFile(projectRoot, relativePath, body, options = {}) {
168
- const target = prepareCredentialFile(projectRoot, relativePath);
169
- // Interactive callers must not adopt a newer operator edit at this handoff.
170
- if (Object.hasOwn(options, 'expectedStat') && !sameFile(options.expectedStat, target.stat)) {
171
- throw new Error('Credential destination changed since it was read; refusing to replace it.');
172
- }
173
- atomicWrite(target, String(body), 0o600, { credential: true });
174
- return { relativePath: target.relativePath, status: 'written' };
175
- }
176
-
177
- export function readCredentialFile(projectRoot, relativePath) {
178
- const inspection = inspectCredentialFile(projectRoot, relativePath);
179
- if (!inspection.exists) return null;
180
- if (!inspection.safe) throw new Error(`Unsafe credential file: ${relativePath} (${inspection.problems.join('; ')}).`);
181
- const target = safePath(projectRoot, relativePath);
182
- const fd = fs.openSync(target.absolute, fs.constants.O_RDONLY | NOFOLLOW);
183
- try {
184
- if (!sameFile(target.stat, fs.fstatSync(fd))) throw new Error('Credential changed before reading.');
185
- return fs.readFileSync(fd, 'utf8');
186
- } finally { fs.closeSync(fd); }
187
- }
188
-
189
- export function removeCredentialFile(projectRoot, relativePath) {
190
- const target = safePath(projectRoot, relativePath);
191
- assertUntracked(target);
192
- if (!target.stat) return;
193
- fs.unlinkSync(target.absolute);
194
- syncDirectory(path.dirname(target.absolute));
195
- }
196
-
197
- export function acquireCredentialLock(projectRoot, relativePath) {
198
- prepareCredentialFile(projectRoot, relativePath);
199
- const lockPath = `${relativePath}.connect.lock`;
200
- let target = prepareCredentialFile(projectRoot, lockPath);
201
- if (target.stat) {
202
- let lock;
203
- try { lock = JSON.parse(readCredentialFile(projectRoot, lockPath)); } catch {
204
- throw new Error('Unsafe or unreadable credential lock; inspect its metadata before reconnecting.');
205
- }
206
- if (!Number.isSafeInteger(lock?.pid) || lock.pid < 1) throw new Error('Invalid credential lock.');
207
- let running = true;
208
- try { process.kill(lock.pid, 0); } catch (error) { if (error.code === 'ESRCH') running = false; }
209
- if (running) throw new Error('Another connect process owns this credential file. Wait for it to finish.');
210
- const latest = safePath(projectRoot, lockPath);
211
- if (!sameFile(target.stat, latest.stat)) throw new Error('Credential lock changed during recovery.');
212
- removeCredentialFile(projectRoot, lockPath);
213
- target = prepareCredentialFile(projectRoot, lockPath);
214
- }
215
- let fd;
216
- let lockStat;
217
- try {
218
- fd = fs.openSync(target.absolute, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW, 0o600);
219
- if (POSIX) fs.fchmodSync(fd, 0o600);
220
- fs.writeFileSync(fd, `${JSON.stringify({ pid: process.pid })}\n`, 'utf8');
221
- fs.fsyncSync(fd);
222
- lockStat = fs.fstatSync(fd);
223
- } catch (error) {
224
- if (error.code === 'EEXIST') throw new Error('Another connect process owns this credential file.');
225
- throw error;
226
- } finally { if (fd !== undefined) fs.closeSync(fd); }
227
- syncDirectory(path.dirname(target.absolute));
228
- let released = false;
229
- const release = () => {
230
- if (released) return;
231
- released = true;
232
- process.removeListener('exit', release);
233
- const latest = safePath(projectRoot, lockPath);
234
- if (sameFile(lockStat, latest.stat)) removeCredentialFile(projectRoot, lockPath);
235
- };
236
- process.once('exit', release);
237
- return release;
238
- }
1
+ export * from './runtime/credentials.mjs';
@@ -0,0 +1,22 @@
1
+ import { isObject } from '../runtime/protocol.mjs';
2
+
3
+ export const NATIVE_AMOUNT_SCHEMA = 'osuite.native_amount.v1';
4
+ const reserved = new Set(['__proto__', 'constructor', 'prototype']);
5
+
6
+ export function validUsdMapping(mapping) {
7
+ return isObject(mapping) && Object.keys(mapping).length === 3
8
+ && mapping.currency === 'USD' && mapping.unit === 'minor'
9
+ && Array.isArray(mapping.path) && mapping.path.length > 0 && mapping.path.length <= 8
10
+ && mapping.path.every(key => typeof key === 'string' && /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(key) && !reserved.has(key));
11
+ }
12
+
13
+ export function usdMinorToMajor(value) {
14
+ // At this bound the major-unit number still distinguishes adjacent cents.
15
+ return Number.isSafeInteger(value) && value > 0 && value <= 10 ** 15 ? value / 100 : null;
16
+ }
17
+
18
+ export function agreesWithUsdAmount(value, minor) {
19
+ if (!isObject(value)) return true;
20
+ return [['currency', 'USD'], ['amount_cents', minor], ['amount_usd', usdMinorToMajor(minor)]]
21
+ .every(([key, expected]) => !Object.hasOwn(value, key) || value[key] === expected);
22
+ }
@@ -1,26 +1,35 @@
1
1
  import path from 'node:path';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
- import { canonicalJson, createApiClient } from '../runtime/protocol.mjs';
4
- import { resolveRemotePosture } from '../runtime/posture.mjs';
3
+ import { canonicalJson, createApiClient, isTransientFailure, sha256 } from '../runtime/protocol.mjs';
4
+ import { rejectionFenceUnchanged, resolveRemotePosture } from '../runtime/posture.mjs';
5
5
  import { createStateStore } from '../runtime/state.mjs';
6
6
  import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
7
7
  import { matchesStoredAction, reject } from './contract.mjs';
8
8
 
9
9
  const receiptWindow = Object.freeze({ headersTimeoutMs: 2500, timeoutMs: 5000 });
10
10
 
11
+ function failureDetails(phase, response, mayHaveRegistered = false) {
12
+ return {
13
+ phase, httpStatus: response?.status || null, cause: response?.error || 'authority_evidence_unconfirmed',
14
+ retryAfterSeconds: response?.retryAfterSeconds ?? null,
15
+ retrySameOperation: !mayHaveRegistered && (isTransientFailure(response) || response?.status === 429),
16
+ };
17
+ }
18
+
11
19
  export function createStudioAuthority(config, journalPath) {
12
20
  const responseLimits = { maxResponseBytes: 1048576 };
13
21
  const baseApi = createApiClient(config, responseLimits);
14
22
  const store = createStateStore({ ...config, stateDir: path.join(path.dirname(journalPath), 'posture') });
23
+ let currentRead;
15
24
 
16
- async function current(aborted) {
17
- let remote;
25
+ async function readCurrent() {
26
+ let remote, lastResponse;
18
27
  const deadline = performance.now() + 2000;
19
28
  for (let attempt = 0; attempt < 6; attempt++) {
20
- if (aborted()) reject('ABORTED');
21
29
  let readStatus = null;
22
30
  remote = await resolveRemotePosture(config, { store, api: { async request(method, endpoint, ...args) {
23
31
  const response = await baseApi.request(method, endpoint, ...args);
32
+ lastResponse = response;
24
33
  if (method === 'GET') readStatus = response.status;
25
34
  return response;
26
35
  } } });
@@ -40,11 +49,22 @@ export function createStudioAuthority(config, journalPath) {
40
49
  || !['enforce', 'strict'].includes(remote.posture.mode)
41
50
  || remote.posture.require_assumption_capture !== false
42
51
  || remote.posture.require_signature !== true || remote.posture.on_guard_unavailable !== 'block') {
43
- reject('CURRENT_AUTHORITY_UNAVAILABLE');
52
+ reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('posture', lastResponse));
44
53
  }
45
54
  const effective = { ...config, mode: remote.posture.mode, guardFailureMode: 'block', signatureMode: 'required',
46
55
  approvalWaitMs: 0, ruleRollout: remote.ruleRollout };
47
- return { api: createApiClient(effective, responseLimits), effective };
56
+ return { api: createApiClient(effective, responseLimits), effective, fence: remote.rejectionFence };
57
+ }
58
+
59
+ async function current(aborted) {
60
+ if (aborted()) reject('ABORTED');
61
+ // A single live read can serve overlapping invocations of this scope.
62
+ // The next invocation after it settles must start another remote read.
63
+ currentRead ??= readCurrent().finally(() => { currentRead = null; });
64
+ const value = await currentRead;
65
+ if (aborted()) reject('ABORTED');
66
+ if (!rejectionFenceUnchanged(config, store, value.fence)) reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('posture'));
67
+ return value;
48
68
  }
49
69
 
50
70
  async function read(record) {
@@ -56,6 +76,9 @@ export function createStudioAuthority(config, journalPath) {
56
76
 
57
77
  async function admit(invocation, journal, owner, aborted) {
58
78
  const record = { ...journal.get(invocation.record.scope, invocation.record.operationId),
79
+ nativeAmount: invocation.context.native_amount,
80
+ nativeResource: invocation.context.native_resource,
81
+ delegationDigest: invocation.context.business_authority_assertion && sha256(canonicalJson(invocation.context.business_authority_assertion.claims)),
59
82
  ...(invocation.recovery ? { recovery: invocation.recovery } : {}) };
60
83
  const phase = record.state === 'held' ? 'redeeming' : 'requesting';
61
84
  const { api, effective } = await current(aborted);
@@ -68,7 +91,7 @@ export function createStudioAuthority(config, journalPath) {
68
91
  const actualSession = session.body?.session || session.body?.runtime_session;
69
92
  if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
70
93
  || actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
71
- || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE');
94
+ || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('runtime_session', session));
72
95
  let claimed = false, requestStartedAt = null;
73
96
  const claim = () => {
74
97
  if (claimed) reject('OUTCOME_UNKNOWN');
@@ -85,11 +108,15 @@ export function createStudioAuthority(config, journalPath) {
85
108
  const registering = method === 'POST' && endpoint === '/api/actions';
86
109
  if (registering) { claim(); requestStartedAt = performance.now(); }
87
110
  const response = await api.request(method, endpoint, body, registering ? receiptWindow : options);
111
+ if (endpoint === '/api/guard' && !response.ok) {
112
+ reject(response.status === 403 && invocation.context.business_authority_assertion ? 'DELEGATION_REJECTED' : 'CURRENT_AUTHORITY_UNAVAILABLE',
113
+ null, failureDetails('guard', response));
114
+ }
88
115
  if (registering) {
89
116
  if (!response.ok || !matchesStoredAction(response.body, record, config)
90
117
  || !cavaFingerprint(response.body)) {
91
118
  settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
92
- reject('OUTCOME_UNKNOWN');
119
+ reject('OUTCOME_UNKNOWN', null, failureDetails('action_registration', response, true));
93
120
  }
94
121
  }
95
122
  return response;
@@ -136,5 +163,11 @@ export function createStudioAuthority(config, journalPath) {
136
163
  && typeof response.body.action?.timestamp_end === 'string';
137
164
  }
138
165
 
139
- return { admit, read, report };
166
+ async function closeOwnerOutcome(record, receipt) {
167
+ const response = await baseApi.request('POST', `/api/actions/${encodeURIComponent(record.actionId)}/resource-confirmation`,
168
+ { agent_id: config.agentId, native_owner_receipt: receipt }, receiptWindow);
169
+ return response.ok && response.body.action_id === record.actionId ? response.body.owner_receipt : null;
170
+ }
171
+
172
+ return { admit, read, report, closeOwnerOutcome };
140
173
  }
@@ -1,5 +1,6 @@
1
1
  import { types } from 'node:util';
2
2
  import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
3
+ import { NATIVE_AMOUNT_SCHEMA, agreesWithUsdAmount, usdMinorToMajor, validUsdMapping } from './amount.mjs';
3
4
 
4
5
  export const CALL_SCHEMA = 'osuite.native_tool_call.v1';
5
6
  export const COVERAGE = 'wrapped-call-only';
@@ -12,18 +13,19 @@ const recoveryMessages = Object.freeze({
12
13
  read_business_result: 'This operation already completed. Read the original result from your application store; OSuite retains its digest, not the full output. Do not send the tool call again.',
13
14
  reconcile_without_resend: 'Keep the operation ID and journal. Read the existing action and resource evidence with an authorized operator; an unknown or mismatched result is not proof that nothing executed. Do not resend.',
14
15
  restore_connection: 'Restore the correct connection and current credentials, then read status for the same operation ID. Do not replace its ID or clear its journal to work around rejection.',
16
+ retry_same_operation: 'Wait for Studio to recover or until the retry delay elapses. Use the same operation ID and unchanged input.',
15
17
  repair_journal: 'Preserve the journal and stop new sends. Ask an operator to inspect storage permissions, capacity and verified backups; never reinitialize a missing journal on the restart path.',
16
18
  check_current_authority: 'Keep the same operation ID and arguments. A call must pass fresh authority checks before execution; this local status is not permission to execute.',
17
19
  stop: 'This operation is denied, expired or cancelled. Stop and consult the policy owner. Changing its ID is not a way to bypass that decision.',
18
20
  inspect_configuration: 'Check the supported runtime, input, mapping and connection configuration. Keep any existing operation ID and journal; do not automatically repeat a possibly sent call.',
19
21
  });
20
22
 
21
- function recoveryGuidance(code, state) {
23
+ function recoveryGuidance(code, state, details) {
22
24
  let nextStep;
23
25
  if (code === 'ALREADY_COMPLETED' || (state === 'completed' && code !== 'BINDING_MISMATCH')) nextStep = 'read_business_result';
24
26
  else if (['OUTCOME_UNKNOWN', 'UNCERTAIN', 'BINDING_MISMATCH', 'CONFLICT'].includes(code)) nextStep = 'reconcile_without_resend';
25
27
  else if (code?.startsWith('JOURNAL_')) nextStep = 'repair_journal';
26
- else if (code === 'CURRENT_AUTHORITY_UNAVAILABLE') nextStep = 'restore_connection';
28
+ else if (code === 'CURRENT_AUTHORITY_UNAVAILABLE') nextStep = details?.retrySameOperation ? 'retry_same_operation' : 'restore_connection';
27
29
  else if (['POLICY_DENIED', 'APPROVAL_EXPIRED', 'CANCELLED'].includes(code)
28
30
  || ['denied', 'expired', 'cancelled'].includes(state)) nextStep = 'stop';
29
31
  else if (code === 'AWAITING_APPROVAL' || (!code && state === 'held')) nextStep = 'review_same_operation';
@@ -37,17 +39,18 @@ function recoveryGuidance(code, state) {
37
39
  }
38
40
 
39
41
  export class GovernedToolError extends Error {
40
- constructor(code, status = null) {
41
- const recovery = recoveryGuidance(code, status?.state);
42
+ constructor(code, status = null, details = null) {
43
+ const recovery = recoveryGuidance(code, status?.state, details);
42
44
  super(`OSuite ${code}: ${recovery.message}`);
43
45
  this.name = 'GovernedToolError';
44
46
  this.code = code;
45
47
  this.status = status === null ? null : Object.freeze({ ...status, recovery });
46
48
  this.retryAutomatically = false;
47
49
  this.recovery = recovery;
50
+ if (details) this.details = Object.freeze({ ...details });
48
51
  }
49
52
  }
50
- export function reject(code, status) { throw new GovernedToolError(code, status); }
53
+ export function reject(code, status, details) { throw new GovernedToolError(code, status, details); }
51
54
 
52
55
  // Validate descriptors before reading values: JSON.stringify alone can invoke
53
56
  // accessors/toJSON or quietly change undefined, non-finite numbers and arrays.
@@ -122,6 +125,24 @@ function describe(binding, args) {
122
125
  return value;
123
126
  }
124
127
 
128
+ function nativeAmount(binding, native, description, inputDigest) {
129
+ if (!binding.amount) return null;
130
+ if (!validUsdMapping(binding.amount)) reject('INVALID_MAPPING');
131
+ let owner = native.arguments;
132
+ for (const key of binding.amount.path.slice(0, -1)) {
133
+ owner = owner && Object.hasOwn(owner, key) ? owner[key] : null;
134
+ }
135
+ const field = binding.amount.path.at(-1);
136
+ const value = owner && Object.hasOwn(owner, field) ? owner[field] : null;
137
+ // A binding may also describe non-financial variants. A monetary policy
138
+ // independently requires evidence before any of those variants can execute.
139
+ if (value == null || value === 0) return null;
140
+ if (usdMinorToMajor(value) === null || !agreesWithUsdAmount(owner, value)
141
+ || !agreesWithUsdAmount(native.arguments, value) || !agreesWithUsdAmount(description.input_summary, value)) reject('INVALID_AMOUNT');
142
+ return { schema_version: NATIVE_AMOUNT_SCHEMA, mapping: binding.amount, value,
143
+ tool_name: native.name, binding_revision: binding.revision, input_digest: inputDigest };
144
+ }
145
+
125
146
  export function makeInvocation({ config, namespace, bindings, operationId, params }) {
126
147
  const scope = scopeFor(config, namespace);
127
148
  if (!id(operationId)) reject('INVALID_OPERATION_ID');
@@ -135,7 +156,11 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
135
156
  // The historical Hook helper normalizes null to {}. Native calls must retain
136
157
  // every JSON value exactly, including that distinction.
137
158
  const inputDigest = sha256(canonicalJson({ tool_name: native.name, tool_input: native.arguments }));
159
+ const amount = nativeAmount(binding, native, description, inputDigest);
138
160
  const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description,
161
+ ...(binding.amount ? { amountMapping: binding.amount } : {}),
162
+ ...(binding.ownerReceipt ? { nativeResource: binding.ownerReceipt.resource } : {}),
163
+ ...(binding.delegation ? { delegationRequired: true } : {}),
139
164
  ...(binding.recovery ? { recovery: { revision: binding.recovery.revision,
140
165
  resourceId: binding.recovery.resourceId, contract: binding.recovery.contract } } : {}) }));
141
166
  const identity = sha256(canonicalJson([scope, operationId]));
@@ -145,6 +170,8 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
145
170
  if (inputSummary.length > 4000) reject('INVALID_MAPPING');
146
171
  const context = jsonSnapshot({ ...description, input_summary: inputSummary, action_id: actionId,
147
172
  agent_id: config.agentId, runtime_session_id: sessionId, tool_use_id: toolUseId,
173
+ ...(amount ? { native_amount: { ...amount, binding_digest: bindingDigest } } : {}),
174
+ ...(binding.ownerReceipt ? { native_resource: { ...binding.ownerReceipt.resource, input_digest: inputDigest } } : {}),
148
175
  tool_input_digest: inputDigest, runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper' });
149
176
  return Object.freeze({ params: native, context, marker, record: Object.freeze({ scope, operationId,
150
177
  inputDigest, bindingDigest, contextDigest: sha256(canonicalJson(context)), actionId, sessionId, toolUseId }) });
@@ -173,6 +200,9 @@ export function matchesStoredAction(payload, record, config) {
173
200
  && envelope.action_id === record.actionId && envelope.org_id === config.orgId && envelope.agent_id === config.agentId
174
201
  && envelope.runtime_session_id === record.sessionId && envelope.tool_use_id === record.toolUseId
175
202
  && (!Object.hasOwn(envelope, 'tool_input_digest') || envelope.tool_input_digest === record.inputDigest)
203
+ && (!record.nativeAmount || canonicalJson(envelope.native_amount) === canonicalJson(record.nativeAmount))
204
+ && (!record.nativeResource || canonicalJson(envelope.native_resource) === canonicalJson(record.nativeResource))
205
+ && (!record.delegationDigest || envelope.business_authority?.assertion_digest === record.delegationDigest)
176
206
  && matchesStoredSummary(action.input_summary, record) && matchesStoredSummary(envelope.input_summary, record);
177
207
  } catch { return false; }
178
208
  }