osuite 2.15.0 → 2.17.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,469 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { acquireCredentialLock, readCredentialFile, removeCredentialFile, writeCredentialFile } from './credentials.js';
6
+ import { credentialDigest, getInstallationIdentity, SDK_ENV_PATH, TERMINAL_ENV_PATH } from './installationIdentity.js';
7
+ import { buildNodeRuntimeBootstrap, findHookInstallations, installProjectFile, planProjectFile, resolveProjectPath } from './projectHooks.js';
8
+ import { createApiClient, validatedBaseUrl } from './runtime/protocol.mjs';
9
+
10
+ const hosts = ['claude', 'codex'];
11
+ const labels = { claude: 'Claude Code', codex: 'Codex', sdk: 'SDK' };
12
+ const demoEnv = '.osuite/demo/.env';
13
+ const endpoint = '/api/onboarding/first-decision';
14
+ const colors = { active: '\x1b[36m', done: '\x1b[32m', attention: '\x1b[33m', failed: '\x1b[31m' };
15
+ const marks = { done: '✓ Done', attention: '! Needs attention', failed: '× Failed' };
16
+ const safeText = value => String(value ?? '').replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').slice(0, 600);
17
+ const plain = () => !process.stdout.isTTY || Object.hasOwn(process.env, 'NO_COLOR');
18
+
19
+ function status(kind, message) {
20
+ const label = marks[kind];
21
+ console.log(`${plain() ? label : `${colors[kind]}${label}\x1b[0m`} ${safeText(message)}`);
22
+ }
23
+
24
+ function current(message) {
25
+ const line = safeText(message);
26
+ const width = line.length + 4;
27
+ if (plain() || (process.stdout.columns || 80) < width) { console.log(line); return; }
28
+ console.log(`${colors.active}┌${'─'.repeat(width - 2)}┐\n│ ${line} │\n└${'─'.repeat(width - 2)}┘\x1b[0m`);
29
+ }
30
+
31
+ function failure(code, message) {
32
+ return Object.assign(new Error(message), { code, publicOnboardingError: true });
33
+ }
34
+
35
+ export function showOnboardingError(error, command) {
36
+ const reason = error.publicOnboardingError ? error.message : 'Could not finish this step. Check the Studio address and local project files.';
37
+ status('failed', reason);
38
+ console.log(`Next osuite ${error.code === 'NOT_CONNECTED' ? 'login' : command}${command === 'demo' ? ' (resume the local sample)' : ''}`);
39
+ }
40
+
41
+ function statePath(envPath) { return `${envPath}.onboarding.json`; }
42
+
43
+ function readState(root, envPath) {
44
+ const raw = readCredentialFile(root, statePath(envPath), { maxBytes: 65536 });
45
+ if (!raw) return null;
46
+ try {
47
+ const state = JSON.parse(raw);
48
+ if (state?.version === 1 && state.lanes?.sdk && validatedBaseUrl(state.baseUrl) === state.baseUrl) return state;
49
+ } catch { /* Protected state is never printed. */ }
50
+ throw failure('STATE', 'The saved setup could not be read. Inspect the protected onboarding state in this project.');
51
+ }
52
+
53
+ function projectFile(root, relativePath) {
54
+ const filename = resolveProjectPath(root, relativePath);
55
+ const stat = fs.statSync(filename, { throwIfNoEntry: false });
56
+ return stat?.isFile() && stat.size <= 1048576 ? filename : null;
57
+ }
58
+
59
+ export function detectProjectRuntimes(root) {
60
+ const has = relative => Boolean(projectFile(root, relative));
61
+ let pkg;
62
+ const manifest = projectFile(root, 'package.json');
63
+ try { if (manifest) pkg = JSON.parse(fs.readFileSync(manifest, 'utf8')); } catch { /* Invalid manifest is not SDK evidence. */ }
64
+ return {
65
+ claude: ['CLAUDE.md', '.claude/CLAUDE.md', '.claude/settings.json', '.claude/settings.local.json'].some(has),
66
+ codex: ['.codex/config.toml', '.codex/hooks.json', '.codex/AGENTS.md'].some(has),
67
+ sdk: ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'].some(key => Object.hasOwn(pkg?.[key] || {}, 'osuite')),
68
+ };
69
+ }
70
+
71
+ function requestedHosts(args, detected, sample) {
72
+ if (sample || args['skip-config']) return [];
73
+ if (!args.runtimes) return hosts.filter(runtime => detected[runtime]);
74
+ if (typeof args.runtimes !== 'string') throw failure('OPTIONS', 'Use --runtimes claude,codex or --runtimes sdk.');
75
+ const wanted = args.runtimes.split(',');
76
+ if (wanted.some(runtime => !Object.hasOwn(labels, runtime))) throw failure('OPTIONS', 'Use --runtimes claude,codex or --runtimes sdk.');
77
+ return hosts.filter(runtime => wanted.includes(runtime));
78
+ }
79
+
80
+ const scopeEnv = { claude: '.claude/.env', codex: '.codex/.env' };
81
+
82
+ function previewRuntime(root, runtime, lane, sharedDigest) {
83
+ try {
84
+ const { files } = buildNodeRuntimeBootstrap(runtime, {}, { projectRoot: root });
85
+ const entries = Object.entries(files).map(([file, contents]) => ({ contents, ...planProjectFile(root, file, contents) }));
86
+ const installation = findHookInstallations(root, [runtime], { diagnose: true })[0];
87
+ const blocked = entries.some(entry => ['error', 'kept'].includes(entry.status) || entry.conflicts?.length)
88
+ || (installation?.hostEnabled === false && installation?.disabledReasons?.length > 0);
89
+ const existingEnv = readCredentialFile(root, scopeEnv[runtime], { maxBytes: 65536 });
90
+ const digest = credentialDigest(existingEnv);
91
+ const credentialsConflict = digest !== null && digest !== lane?.envDigest && digest !== sharedDigest && !lane?.credential;
92
+ return { entries, blocked: blocked || credentialsConflict, credentialsConflict };
93
+ } catch { return { entries: [], blocked: true, unreadable: true }; }
94
+ }
95
+
96
+ function syncSharedCredential(root, runtime, lane, envPath) {
97
+ const body = readCredentialFile(root, envPath);
98
+ const live = readCredentialFile(root, scopeEnv[runtime]);
99
+ if (live !== null && live !== body && credentialDigest(live) !== lane.envDigest) {
100
+ throw failure('CREDENTIAL_CONFLICT', 'The project credential changed after review.');
101
+ }
102
+ if (body !== live) writeCredentialFile(root, scopeEnv[runtime], body);
103
+ lane.envDigest = credentialDigest(body);
104
+ }
105
+
106
+ function writePreview(runtime, preview) {
107
+ if (!preview) return;
108
+ if (preview.credentialsConflict) console.log(` ! ${scopeEnv[runtime]} has existing credentials. Review this runtime's connection before retrying.`);
109
+ if (preview.unreadable) console.log(` ! Could not safely read the ${labels[runtime]} project files.`);
110
+ const entries = preview.entries.filter(entry => ['created', 'merged', 'kept', 'error'].includes(entry.status));
111
+ const configs = entries.filter(entry => entry.kind || ['kept', 'error'].includes(entry.status));
112
+ for (const entry of configs) {
113
+ console.log(` ${entry.status === 'created' ? '+' : entry.status === 'merged' ? '~' : '!'} ${entry.relativePath}`);
114
+ for (const hook of entry.added || []) console.log(` + ${typeof hook === 'string' ? safeText(hook) : hook.event + ' OSuite Hook'}`);
115
+ for (const hook of entry.migrated || []) console.log(` ~ ${hook.event} OSuite Hook`);
116
+ if (entry.conflicts?.length || ['kept', 'error'].includes(entry.status)) console.log(' ! Resolve the existing configuration before applying this runtime.');
117
+ }
118
+ const scripts = entries.length - configs.length;
119
+ if (scripts) console.log(` + ${scripts} packaged files in .${runtime}/`);
120
+ }
121
+
122
+ function sdkSteps() {
123
+ console.log(' SDK wrapper for Node.js');
124
+ console.log(' 1. Install the project dependency with npm install osuite.');
125
+ console.log(` 2. On Node 24 start with node --env-file=${TERMINAL_ENV_PATH} your-agent.mjs.`);
126
+ console.log(' 3. Import createGovernedTools from osuite/governed-tools. Bind your tool name and arguments to a private journal,');
127
+ console.log(' then call tools.run(operationId, { name, arguments: args }, ({ arguments: input }) => originalTool(input)).');
128
+ console.log(' Keep the operation ID across retries. See node_modules/osuite/GOVERNED_TOOLS.md for the config and journal setup.');
129
+ }
130
+
131
+ async function confirm(prompt, args) {
132
+ if (args.yes) return true;
133
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
134
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
135
+ try { return ['', 'y', 'yes'].includes((await terminal.question(`${prompt} [Y/n] `)).trim().toLowerCase()); }
136
+ finally { terminal.close(); }
137
+ }
138
+
139
+ async function selectRuntimeChanges(ready, args) {
140
+ if (args.yes) return ready;
141
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
142
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
143
+ try {
144
+ const answer = (await terminal.question(`Apply Hook changes? Enter for all, choose ${ready.join(',')} or n to pause: `)).trim().toLowerCase();
145
+ if (!answer || answer === 'y' || answer === 'yes') return ready;
146
+ const selected = answer.split(',').map(value => value.trim());
147
+ return selected.every(runtime => ready.includes(runtime)) ? [...new Set(selected)] : null;
148
+ } finally { terminal.close(); }
149
+ }
150
+
151
+ async function waitForApproval(run) {
152
+ if (plain()) return run();
153
+ let tick = 0;
154
+ const frames = ['⠋', '⠙', '⠹', '⠸'];
155
+ const timer = setInterval(() => process.stdout.write(`\r${colors.active}${frames[tick++ % frames.length]}\x1b[0m Waiting for Studio…`), 140);
156
+ try { return await run(); }
157
+ finally { clearInterval(timer); if (tick) process.stdout.write('\r\x1b[2K'); }
158
+ }
159
+
160
+ function apiFromEnv(root, envPath, deps) {
161
+ const env = deps.parseEnvBody(readCredentialFile(root, envPath, { maxBytes: 65536 }) || '');
162
+ if (!validatedBaseUrl(env.OSUITE_BASE_URL) || !env.OSUITE_API_KEY || !env.OSUITE_PRIVATE_KEY_BASE64 || !env.OSUITE_ORG_ID) {
163
+ throw failure('NOT_CONNECTED', 'Connect this project before recording a test.');
164
+ }
165
+ return { baseUrl: env.OSUITE_BASE_URL, orgId: env.OSUITE_ORG_ID, api: createApiClient({
166
+ baseUrl: env.OSUITE_BASE_URL, apiKey: env.OSUITE_API_KEY,
167
+ privateKeyBase64: env.OSUITE_PRIVATE_KEY_BASE64, signatureMode: 'required',
168
+ }, { timeoutMs: 15000 }) };
169
+ }
170
+
171
+ function testResponse(result, { orgId, actionId, sample }) {
172
+ const receipt = result.body?.receipt;
173
+ if (!result.ok || receipt?.action_id !== actionId || receipt.workspace?.id !== orgId || receipt.sample !== sample
174
+ || typeof receipt.reason !== 'string' || typeof receipt.decision !== 'string') {
175
+ throw failure('TEST', `Test receipt could not be confirmed${result.status ? ` (HTTP ${result.status})` : ''}. Retry to recover the same action.`);
176
+ }
177
+ return receipt;
178
+ }
179
+
180
+ export async function runOnboardingTest(args, deps, { sample = false } = {}) {
181
+ const root = process.cwd();
182
+ const envPath = sample ? demoEnv : TERMINAL_ENV_PATH;
183
+ const { api, orgId, baseUrl } = apiFromEnv(root, envPath, deps);
184
+ const pendingPath = `${envPath}.test.json`;
185
+ const release = acquireCredentialLock(root, pendingPath);
186
+ try {
187
+ const saved = readCredentialFile(root, pendingPath, { maxBytes: 4096 });
188
+ const run = saved ? JSON.parse(saved) : { orgId, baseUrl, actionId: `act_test_${randomUUID()}` };
189
+ if (run.orgId !== orgId || run.baseUrl !== baseUrl || !/^act_test_[a-f0-9-]{36}$/.test(run.actionId)) {
190
+ throw failure('TEST_STATE', 'The pending test belongs to a different connection. Inspect the original workspace before retrying.');
191
+ }
192
+ if (!saved) writeCredentialFile(root, pendingPath, `${JSON.stringify(run)}\n`);
193
+ current('3/3 Record test decision');
194
+ const response = await api.request('POST', endpoint, { operation: 'test', action_id: run.actionId });
195
+ const receipt = testResponse(response, { orgId, actionId: run.actionId, sample });
196
+ removeCredentialFile(root, pendingPath);
197
+ const decision = { allow: 'Allowed', warn: 'Allowed with warnings', block: 'Blocked', require_approval: 'Review required',
198
+ require_dual_approval: 'Dual review required', simulate_first: 'Simulation required' }[receipt.decision] || 'Recorded';
199
+ status('done', `Test decision recorded · ${decision}`);
200
+ console.log(` Action ID ${receipt.action_id}`);
201
+ console.log(` Workspace ${safeText(receipt.workspace.name)} (${safeText(orgId)})`);
202
+ console.log(` Source ${sample ? 'Local demo sample' : 'CLI test'}`);
203
+ console.log(` Reason ${safeText(receipt.reason)}`);
204
+ const query = sample ? '' : `?${new URLSearchParams({ orgId })}`;
205
+ console.log(` Studio ${baseUrl}/decisions/${receipt.action_id}${query}`);
206
+ console.log(` Replay ${baseUrl}/replay/${receipt.action_id}${query}`);
207
+ return receipt;
208
+ } finally { release(); }
209
+ }
210
+
211
+ export function onboardingWelcome() {
212
+ const root = process.cwd();
213
+ console.log('OSuite');
214
+ try {
215
+ const state = readState(root, TERMINAL_ENV_PATH);
216
+ if (state?.lanes.sdk.envDigest && state.lanes.sdk.envDigest === credentialDigest(readCredentialFile(root, TERMINAL_ENV_PATH))) {
217
+ status('done', `Connected to ${state.workspace.name}`);
218
+ console.log(state.configured ? 'Next osuite test' : 'Next osuite login Resume runtime setup');
219
+ } else if (state) {
220
+ status('attention', 'Setup in progress');
221
+ console.log('Next osuite login Resume this project');
222
+ } else if ([SDK_ENV_PATH, ...Object.values(scopeEnv)].some(file => readCredentialFile(root, file) !== null)) {
223
+ status('attention', 'Existing runtime credentials found');
224
+ console.log('Next osuite login Set up terminal access for this project');
225
+ } else {
226
+ console.log('Connect this project and record your first decision.');
227
+ console.log('Next osuite login');
228
+ }
229
+ } catch {
230
+ status('attention', 'Check the saved project connection');
231
+ console.log('Next osuite login');
232
+ }
233
+ console.log('Help osuite --help');
234
+ }
235
+
236
+ async function deliver({ lane, state, envPath, root, args, deps, save, terminal }) {
237
+ if (lane.envDigest) return;
238
+ const scope = { baseUrl: state.baseUrl, runtime: lane.runtime, agentId: lane.agentId };
239
+ const currentBody = () => readCredentialFile(root, envPath, { maxBytes: 65536 });
240
+ const validateLive = () => {
241
+ const body = currentBody();
242
+ if (credentialDigest(body) !== lane.before && !(lane.credential && body === deps.formatEnvBody(lane.credential.env))) {
243
+ throw failure('CREDENTIAL_CONFLICT', `Existing credentials changed in ${envPath}. Review the file before resuming.`);
244
+ }
245
+ };
246
+ if (!lane.credential) {
247
+ validateLive();
248
+ const request = lane.request;
249
+ const poll = () => deps.pollDeviceConnect({
250
+ ...scope, deviceCode: request.device_code, pollToken: request.poll_token,
251
+ intervalMs: 750, timeoutMs: Math.min(600000, Number(args['poll-timeout-ms']) || (terminal ? 600000 : 12000)),
252
+ protocolVersion: 2, onboarding: true,
253
+ });
254
+ const credential = terminal ? await waitForApproval(poll) : await poll();
255
+ if (!credential) throw failure('WAIT_TIMEOUT', terminal ? 'Timed out at browser approval. The handoff is saved.' : 'Runtime approval is still pending. Resume in the original approval tab.');
256
+ deps.assertConnectionCredentialScope(credential, scope);
257
+ if (typeof credential.org_id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(credential.org_id)
258
+ || (state.workspace?.id && credential.org_id !== state.workspace.id)) throw failure('WORKSPACE', 'Studio approved a different workspace. Check the original authorization.');
259
+ credential.env.OSUITE_ORG_ID = credential.org_id;
260
+ lane.credential = credential;
261
+ save();
262
+ }
263
+ deps.assertConnectionCredentialScope(lane.credential, scope);
264
+ validateLive();
265
+ if (terminal) console.log(' Browser approved. Confirming the saved connection with Studio…');
266
+ await deps.finalizeDeviceConnect({ credential: lane.credential, session: lane.request, base_url: state.baseUrl }, null, validateLive);
267
+ validateLive();
268
+ const body = deps.formatEnvBody(lane.credential.env);
269
+ writeCredentialFile(root, envPath, body);
270
+ lane.envDigest = credentialDigest(body);
271
+ delete lane.request;
272
+ delete lane.credential;
273
+ save();
274
+ }
275
+
276
+ function handoffLink(session, baseUrl) {
277
+ const link = new URL(session.verification_uri_complete);
278
+ if (link.origin !== baseUrl || link.pathname !== '/connect' || link.search !== '?source=login'
279
+ || link.hash !== `#code=${session.user_code}` || !/^OS-[A-Z0-9]{6}$/.test(session.user_code)) {
280
+ throw failure('HANDOFF', 'Studio returned an invalid authorization link.');
281
+ }
282
+ return link.href;
283
+ }
284
+
285
+ export async function runOnboardingLogin(args, deps, { sample = false } = {}) {
286
+ const root = process.cwd();
287
+ const envPath = sample ? demoEnv : TERMINAL_ENV_PATH;
288
+ const command = sample ? 'demo' : 'login';
289
+ const releases = [];
290
+ try {
291
+ releases.push(acquireCredentialLock(root, envPath));
292
+ let state = readState(root, envPath);
293
+ const baseUrl = validatedBaseUrl(args['base-url'] || state?.baseUrl || (sample ? 'http://127.0.0.1:3000' : deps.baseUrl));
294
+ if (!baseUrl || new URL(baseUrl).origin !== baseUrl || (sample && !['127.0.0.1', 'localhost', '[::1]'].includes(new URL(baseUrl).hostname))) {
295
+ throw failure('STUDIO_URL', sample ? 'Demo needs a loopback Studio URL.' : 'Use a Studio HTTPS origin or a loopback HTTP origin.');
296
+ }
297
+ if (state && state.baseUrl !== baseUrl) throw failure('STUDIO_CHANGED', 'This project has a saved setup for a different Studio. Resume with its original URL.');
298
+ const save = () => writeCredentialFile(root, statePath(envPath), `${JSON.stringify(state)}\n`);
299
+ const detected = sample ? {} : detectProjectRuntimes(root);
300
+ const wanted = state?.wanted || requestedHosts(args, detected, sample);
301
+ for (const runtime of wanted) releases.push(acquireCredentialLock(root, scopeEnv[runtime]));
302
+ if (!state || state.renew) {
303
+ const primaryEnv = readCredentialFile(root, envPath);
304
+ const old = state?.lanes.sdk;
305
+ const before = credentialDigest(primaryEnv);
306
+ if (primaryEnv !== null && before !== (old?.envDigest || old?.before)) {
307
+ throw failure('CREDENTIAL_CONFLICT', `A credential already exists in ${envPath}. Restore the setup state or use a clean project.`);
308
+ }
309
+ // A coding-only project can use one of its Hook identities for CLI receipts.
310
+ // This leaves two key slots sufficient for a dual-host starter workspace.
311
+ const primary = old?.runtime || (!sample && !detected.sdk && !String(args.runtimes || '').split(',').includes('sdk')
312
+ ? wanted.find(runtime => readCredentialFile(root, scopeEnv[runtime]) === null) : null) || 'sdk';
313
+ const identity = getInstallationIdentity(root, envPath, primary);
314
+ const lanes = { sdk: { runtime: primary, agentId: identity.agent_id, before } };
315
+ const requests = [];
316
+ for (const runtime of wanted) {
317
+ if (state?.lanes[runtime]?.envDigest) {
318
+ lanes[runtime] = state.lanes[runtime];
319
+ continue;
320
+ }
321
+ if (state?.skipped?.includes(runtime)) continue;
322
+ if (runtime === primary) {
323
+ lanes[runtime] = { runtime, agentId: identity.agent_id, shared: true };
324
+ continue;
325
+ }
326
+ if (readCredentialFile(root, scopeEnv[runtime]) !== null) continue;
327
+ const host = getInstallationIdentity(root, scopeEnv[runtime], runtime);
328
+ requests.push({ runtime, agent_id: host.agent_id, installation_id: host.installation_id });
329
+ lanes[runtime] = { runtime, agentId: host.agent_id, before: null };
330
+ }
331
+ current('1/3 Connect terminal');
332
+ console.log(` Project ${safeText(path.basename(root))}`);
333
+ console.log(` Studio ${baseUrl}`);
334
+ const session = await deps.startDeviceConnect({ baseUrl, runtime: primary, agentId: identity.agent_id, installationId: identity.installation_id,
335
+ onboarding: true, sample, requests, expectedOrgId: state?.workspace?.id,
336
+ previousKey: primaryEnv ? deps.parseEnvBody(primaryEnv).OSUITE_API_KEY : undefined });
337
+ handoffLink(session, baseUrl);
338
+ if (session.protocol_version !== 2 || session.sample !== sample || !Array.isArray(session.runtime_requests)) {
339
+ throw failure('PROTOCOL', 'This Studio does not support the terminal setup protocol.');
340
+ }
341
+ for (const request of session.runtime_requests) {
342
+ if (!hosts.includes(request.runtime) || lanes[request.runtime]?.agentId !== request.agent_id || lanes[request.runtime].request
343
+ || !request.device_code || !request.poll_token) throw failure('PROTOCOL', 'Studio returned an unexpected runtime binding.');
344
+ lanes[request.runtime].request = request;
345
+ }
346
+ if (requests.some(({ runtime }) => !lanes[runtime].request)) throw failure('PROTOCOL', 'Studio omitted a requested runtime binding.');
347
+ const { device_code, poll_token } = session;
348
+ lanes.sdk.request = { device_code, poll_token };
349
+ state = { version: 1, baseUrl, wanted, sample, lanes, link: handoffLink(session, baseUrl), code: session.user_code,
350
+ connectionId: session.connection_id, workspace: state?.workspace, skipped: state?.skipped || [] };
351
+ save();
352
+ } else if (!state.lanes.sdk.envDigest) current('1/3 Resume terminal connection');
353
+
354
+ if (!state.lanes.sdk.envDigest) {
355
+ console.log(` Open ${baseUrl}/connect?source=login`);
356
+ console.log(` Device code ${state.code}`);
357
+ if (deps.shouldOpenBrowser(args)) deps.openInBrowser(state.link);
358
+ console.log(' Approve this terminal in Studio. Press Ctrl+C to pause.');
359
+ try { await deliver({ lane: state.lanes.sdk, state, envPath, root, args, deps, save, terminal: true }); }
360
+ catch (error) {
361
+ if (['DEVICE_CONNECT_EXPIRED', 'DEVICE_CONNECT_NOT_FOUND'].includes(error.code)
362
+ && (!state.lanes.sdk.credential || error.code === 'DEVICE_CONNECT_EXPIRED')) {
363
+ state.renew = true;
364
+ save();
365
+ }
366
+ throw error;
367
+ }
368
+ }
369
+
370
+ if (state.lanes.sdk.envDigest !== credentialDigest(readCredentialFile(root, envPath))) {
371
+ throw failure('CREDENTIAL_CONFLICT', `Saved credentials changed in ${envPath}. Review them before resuming.`);
372
+ }
373
+ const { api, orgId } = apiFromEnv(root, envPath, deps);
374
+ const connection = await api.request('GET', `${endpoint}?runtimes=1`);
375
+ if (!connection.ok || connection.body.workspace?.id !== orgId || connection.body.connection_id !== state.connectionId) {
376
+ if (sample && [401, 403].includes(connection.status)) {
377
+ removeCredentialFile(root, envPath);
378
+ removeCredentialFile(root, statePath(envPath));
379
+ throw failure('DEMO_RESET', 'The local Demo session was reset. Run osuite demo again for a new sample.');
380
+ }
381
+ throw failure('CONNECTION_NOT_CONFIRMED', 'Studio could not confirm this saved connection.');
382
+ }
383
+ state.workspace = connection.body.workspace;
384
+ delete state.code;
385
+ delete state.link;
386
+ save();
387
+ status('done', `1/3 Connected to ${state.workspace.name}${sample ? ' · Sample' : ''}`);
388
+
389
+ if (!sample) {
390
+ current('2/3 Configure this project');
391
+ const primaryHost = state.lanes[state.lanes.sdk.runtime];
392
+ if (primaryHost?.shared && primaryHost.installed) {
393
+ syncSharedCredential(root, primaryHost.runtime, primaryHost, envPath);
394
+ save();
395
+ }
396
+ const previews = Object.fromEntries(wanted.filter(runtime => !state.lanes[runtime]?.installed && !state.skipped?.includes(runtime))
397
+ .map(runtime => [runtime, previewRuntime(root, runtime, state.lanes[runtime], state.lanes[runtime]?.shared ? state.lanes.sdk.envDigest : undefined)]));
398
+ for (const runtime of [...hosts, 'sdk']) {
399
+ const selected = runtime === 'sdk' ? detected.sdk || args.runtimes?.includes('sdk') : wanted.includes(runtime);
400
+ console.log(` [${selected ? 'x' : ' '}] ${labels[runtime]}${selected && runtime !== 'sdk' ? ' · Add project Hook' : ''}`);
401
+ writePreview(runtime, previews[runtime]);
402
+ }
403
+ const ready = wanted.filter(runtime => previews[runtime] && !previews[runtime].blocked
404
+ && (state.lanes[runtime]?.request || state.lanes[runtime]?.envDigest || state.lanes[runtime]?.shared));
405
+ const approvedFor = (runtime, entry) => state.lanes[runtime].approvedPlan?.[entry.relativePath];
406
+ const alreadyReviewed = ready.filter(runtime => previews[runtime].entries.every(entry => {
407
+ const previous = approvedFor(runtime, entry);
408
+ return previous && (previous.before === entry.before || previous.after === entry.before)
409
+ && (entry.status === 'unchanged' || previous.after === credentialDigest(String(entry.body)));
410
+ }));
411
+ const toReview = ready.filter(runtime => !alreadyReviewed.includes(runtime));
412
+ const selected = toReview.length ? await selectRuntimeChanges(toReview, args) : [];
413
+ if (selected === null) status('attention', 'Runtime changes are pending. Resume with osuite login or pass --yes after review.');
414
+ if (selected) {
415
+ state.skipped = [...new Set([...(state.skipped || []), ...toReview.filter(runtime => !selected.includes(runtime))])];
416
+ for (const runtime of selected) {
417
+ state.lanes[runtime].approvedPlan = Object.fromEntries(previews[runtime].entries.map(entry => [entry.relativePath,
418
+ { before: entry.before, after: entry.status === 'unchanged' ? entry.before : credentialDigest(String(entry.body)) }]));
419
+ }
420
+ save();
421
+ }
422
+ if (wanted.some(runtime => previews[runtime] && !previews[runtime].blocked && !state.lanes[runtime])) {
423
+ state.renew = true;
424
+ save();
425
+ status('attention', 'Runtime conflict resolved. Run osuite login again to authorize the remaining runtime.');
426
+ }
427
+ for (const runtime of [...alreadyReviewed, ...(selected || [])]) {
428
+ const lane = state.lanes[runtime];
429
+ try {
430
+ if (lane.shared) {
431
+ syncSharedCredential(root, runtime, lane, envPath);
432
+ save();
433
+ } else await deliver({ lane, state, envPath: scopeEnv[runtime], root, args, deps, save, terminal: false });
434
+ for (const entry of previews[runtime].entries) installProjectFile(root, entry.relativePath, entry.contents, { expectedDigest: entry.before });
435
+ lane.installed = true;
436
+ save();
437
+ } catch (error) {
438
+ if (['DEVICE_CONNECT_EXPIRED', 'DEVICE_CONNECT_NOT_FOUND', 'RUNTIME_APPROVAL_FAILED'].includes(error.code)) {
439
+ state.renew = true;
440
+ save();
441
+ }
442
+ status('attention', `${labels[runtime]} setup paused. ${error.publicOnboardingError ? error.message : 'Review the project files and resume with osuite login.'}`);
443
+ }
444
+ }
445
+ for (const runtime of hosts.filter(runtime => wanted.includes(runtime))) {
446
+ const lane = state.lanes[runtime];
447
+ const evidence = connection.body.runtimes?.[runtime];
448
+ console.log(` ${labels[runtime]} Files written: ${lane?.installed ? 'yes' : state.skipped?.includes(runtime) ? 'skipped' : 'pending'} · Host loaded: ${evidence?.host_loaded ? 'yes' : 'unconfirmed'} · Test action: ${evidence?.action_recorded ? 'recorded' : 'pending'}`);
449
+ if (lane?.installed && runtime === 'codex') console.log(' Open Codex in this project and review the OSuite entries in /hooks to confirm host trust.');
450
+ if (lane?.installed && !evidence?.action_recorded) console.log(` After opening ${labels[runtime]} here, ask it to run a read-only project command such as git status.`);
451
+ }
452
+ if (detected.sdk || wanted.length === 0 || args.runtimes?.includes('sdk')) sdkSteps();
453
+ if (state.lanes.sdk.runtime === 'sdk') console.log(` SDK Files written: credential saved · Wrapper: ${connection.body.runtimes?.sdk?.action_recorded ? 'verified by a recorded action' : 'awaiting an application action'}`);
454
+ }
455
+
456
+ if (sample || wanted.every(runtime => state.lanes[runtime]?.installed || state.skipped?.includes(runtime))) {
457
+ if (!connection.body.configured) {
458
+ const progress = await api.request('POST', endpoint, { operation: 'configured' });
459
+ if (!progress.ok || !progress.body.configured) throw failure('CONFIGURED', 'Studio could not confirm runtime setup. Resume this project to retry.');
460
+ }
461
+ state.configured = true;
462
+ save();
463
+ status('done', '2/3 Runtime setup recorded');
464
+ } else status('attention', '2/3 Some project runtime changes still need attention. Resume with osuite login.');
465
+
466
+ if (sample || args.test || (!args['no-test'] && await confirm('Run test now?', { yes: false }))) await runOnboardingTest(args, deps, { sample });
467
+ else console.log(`Next osuite ${command === 'demo' ? 'demo' : 'test'}`);
468
+ } finally { releases.reverse().forEach(release => release()); }
469
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.15.0",
3
+ "version": "2.17.0",
4
4
  "description": "OSuite governed action SDK for AI agents. Approve, replay, prove, and verify runtime decisions.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -23,6 +23,9 @@
23
23
  "./governed-tools": {
24
24
  "import": "./governed-tools.mjs"
25
25
  },
26
+ "./native-proof": {
27
+ "import": "./native-proof.mjs"
28
+ },
26
29
  "./experimental/business-evidence": {
27
30
  "import": "./business-evidence.mjs"
28
31
  },
@@ -32,6 +35,7 @@
32
35
  },
33
36
  "files": [
34
37
  "cli.js",
38
+ "onboardingCli.js",
35
39
  "credentials.js",
36
40
  "installationIdentity.js",
37
41
  "activationMetrics.js",
@@ -39,6 +43,7 @@
39
43
  "tryContract.js",
40
44
  "runtime/",
41
45
  "governed-tools.mjs",
46
+ "native-proof.mjs",
42
47
  "governed-tools/*.mjs",
43
48
  "governed-tools/examples/*.mjs",
44
49
  "GOVERNED_TOOLS.md",
package/projectHooks.js CHANGED
@@ -535,9 +535,10 @@ function writeFile(absolute, body) {
535
535
  * Install one bootstrap file. Settings files are merged; OSuite's own files
536
536
  * are created, left alone when identical, and replaced only with --force.
537
537
  */
538
- export function installProjectFile(projectRoot, relativePath, body, { force = false } = {}) {
538
+ export function planProjectFile(projectRoot, relativePath, body, { force = false } = {}) {
539
539
  const absolute = resolveProjectPath(projectRoot, relativePath);
540
540
  const existing = readIfExists(absolute);
541
+ const before = existing === null ? null : crypto.createHash('sha256').update(existing).digest('hex');
541
542
  const kind = MERGED_FILES[relativePath];
542
543
 
543
544
  if (kind) {
@@ -548,21 +549,40 @@ export function installProjectFile(projectRoot, relativePath, body, { force = fa
548
549
  } catch (error) {
549
550
  merge = { status: 'error', error: `OSuite template could not be read (${error.message})` };
550
551
  }
551
- if (merge.status === 'created' || merge.status === 'merged') writeFile(absolute, merge.body);
552
- const { body: _body, ...report } = merge;
553
- return { relativePath, kind, ...report };
552
+ return { relativePath, kind, before, ...merge };
554
553
  }
555
554
 
556
555
  if (existing === null) {
557
- writeFile(absolute, body);
558
- return { relativePath, status: 'created' };
556
+ return { relativePath, before, body, status: 'created' };
559
557
  }
560
- if (existing === String(body ?? '')) return { relativePath, status: 'unchanged' };
558
+ if (existing === String(body ?? '')) return { relativePath, before, status: 'unchanged' };
561
559
  if (force) {
562
- writeFile(absolute, body);
563
- return { relativePath, status: 'replaced' };
560
+ return { relativePath, before, body, status: 'replaced' };
564
561
  }
565
- return { relativePath, status: 'kept' };
562
+ return { relativePath, before, status: 'kept' };
563
+ }
564
+
565
+ export function installProjectFile(projectRoot, relativePath, body, options = {}) {
566
+ const { before, body: proposed, ...report } = planProjectFile(projectRoot, relativePath, body, options);
567
+ const reviewed = Object.hasOwn(options, 'expectedDigest');
568
+ if (reviewed && before !== options.expectedDigest) {
569
+ throw new Error(`Project file changed after the preview: ${relativePath}`);
570
+ }
571
+ if (!['created', 'merged', 'replaced'].includes(report.status)) return report;
572
+ const absolute = resolveProjectPath(projectRoot, relativePath);
573
+ if (!reviewed) { writeFile(absolute, proposed); return report; }
574
+
575
+ // Interruptions during a reviewed install must leave complete files.
576
+ const temporary = path.join(path.dirname(absolute), `.osuite-hook-${crypto.randomUUID()}.tmp`);
577
+ fs.mkdirSync(path.dirname(absolute), { recursive: true });
578
+ try {
579
+ const mode = fs.statSync(absolute, { throwIfNoEntry: false })?.mode ?? 0o644;
580
+ fs.writeFileSync(temporary, proposed, { flag: 'wx', mode });
581
+ if (resolveProjectPath(projectRoot, relativePath) !== absolute
582
+ || planProjectFile(projectRoot, relativePath, body, options).before !== before) throw new Error(`Project file changed during installation: ${relativePath}`);
583
+ fs.renameSync(temporary, absolute);
584
+ } finally { fs.rmSync(temporary, { force: true }); }
585
+ return report;
566
586
  }
567
587
 
568
588
  export function installBlockers(results = []) {
@@ -1036,6 +1056,13 @@ export async function runHookCheck({
1036
1056
  const nodeHook = /\bosuite_pretool\.mjs\b/.test(installation.pretool.command);
1037
1057
  const preflightModes = seen.filter((event) => event.event_type === 'tool_preflight')
1038
1058
  .map((event) => event.payload?.hook_mode).filter((mode) => ['observe', 'enforce', 'strict'].includes(mode));
1059
+ const postureEvent = seen.find(event => event.event_type === 'tool_preflight' && event.payload?.runtime_posture);
1060
+ if (postureEvent) {
1061
+ const observed = postureEvent.payload.runtime_posture;
1062
+ const approval = seen.find(event => ['tool_requires_approval', 'install_check_policy_result'].includes(event.event_type));
1063
+ state.posture = { ...observed, approval_required: Boolean(approval && observed.effective_mode !== 'observe') };
1064
+ steps.push({ ok: true, label: 'Runtime posture', detail: JSON.stringify(state.posture) });
1065
+ }
1039
1066
  const observing = (!preflightModes.length && credentials.hookMode === 'observe') || seen.some((event) => (
1040
1067
  event.payload?.hook_mode === 'observe' || event.payload?.observe_only === true
1041
1068
  || String(event.payload?.decision || '').startsWith('observe_')
@@ -144,11 +144,13 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
144
144
  const guard = await api.request('POST', '/api/guard', rememberOperation ? { ...context, hook_dispatch: 'v1' } : context);
145
145
  if (!guard.ok) {
146
146
  // Rejection, bad evidence and unknown errors are not availability failures.
147
- if (!isTransientFailure(guard)) return closed('guard_rejected', { rejectedStatus: guard.status });
147
+ if (!isTransientFailure(guard)) return closed('guard_rejected', { rejectedStatus: guard.status,
148
+ phase: 'guard', retrySameOperation: guard.status === 429, retryAfterSeconds: guard.retryAfterSeconds });
148
149
  const failOpen = ['observe', 'enforce'].includes(config.mode)
149
150
  && config.ruleRolloutCapability !== RULE_ROLLOUT_CAPABILITY && !config.ruleRollout?.enabled
150
151
  && config.guardFailureMode === 'allow';
151
- return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true };
152
+ return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true,
153
+ phase: 'guard', retrySameOperation: !failOpen, retryAfterSeconds: guard.retryAfterSeconds };
152
154
  }
153
155
  const requestedDecision = guard.body?.decision;
154
156
  if (!DECISIONS.has(requestedDecision)) return closed('unsupported_guard_decision');
@@ -163,6 +165,18 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
163
165
  ...(rollout.binding ? { observeOnly: false, ruleRolloutBinding: rollout.binding } : {}),
164
166
  });
165
167
  const create = fields => api.request('POST', '/api/actions', { ...context, ...binding, ...fields });
168
+ if (context.hook_observation) {
169
+ if (!operationId || config.mode !== 'observe' || rollout.binding) return finish(closed('observation_posture_unconfirmed'));
170
+ const observed = await create({ status: 'running' });
171
+ const action = observed.body?.action;
172
+ if (!observed.ok || action?.status !== 'running' || action.timestamp_end != null
173
+ || action.action_envelope?.hook_observation?.revision !== context.hook_observation.revision
174
+ || !matchesAction(observed.body, context, { actionId: operationId })) {
175
+ return finish(closed('observation_registration_unconfirmed', { actionId: operationId, rejectedStatus: observed.status }));
176
+ }
177
+ return finish({ authorized: false, observeOnly: true, observeRecorded: true, actionId: operationId,
178
+ decision: observed.body.decision?.decision, response: observed.body });
179
+ }
166
180
  if (requestedDecision === 'block') {
167
181
  // Observation still persists the would-block result, but never calls it authority.
168
182
  const observeOnly = config.mode === 'observe' && !rollout.binding;
@@ -179,7 +193,8 @@ export async function admitAction(context, { api, config, sleep = delay, now = (
179
193
  return finish({ ...closed('policy_block'), observeOnly, response: guard.body, actionId });
180
194
  }
181
195
  const created = await create({ status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running' });
182
- if (!created.ok) return finish(closed('admission_unconfirmed', { rejectedStatus: created.status, actionId: operationId }));
196
+ if (!created.ok) return finish(closed('admission_unconfirmed', { rejectedStatus: created.status, actionId: operationId,
197
+ phase: 'action_registration', retrySameOperation: false, retryAfterSeconds: created.retryAfterSeconds }));
183
198
  if (operationId && created.body?.action_id !== operationId) return finish(closed('hook_operation_binding_changed', { actionId: operationId }));
184
199
  if (!rolloutAuthority(created.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid');
185
200
  const diagnostic = installCheck(created.body, context);