osuite 2.9.9 → 2.10.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) OSuite contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # OSuite SDK (v2.9.9)
1
+ # OSuite SDK (v2.10.0)
2
2
 
3
3
  **Governed action SDK for AI agents.**
4
4
 
@@ -18,6 +18,8 @@ curl -fsSL https://studio.osuite.ai/install.sh | bash
18
18
 
19
19
  The installer detects Codex, Claude Code, SDK, or MCP-style projects, opens a browser handoff, and writes the approved runtime environment into the project (`.codex/.env`, `.claude/.env`, or `.osuite/.env`). API keys remain available as a fallback, but the normal path is terminal start -> Studio approval -> terminal auto-finish.
20
20
 
21
+ It needs Node.js 18 or newer, and Python 3.8 or newer for the Codex and Claude Code hooks (the SDK and MCP lanes do not need Python). It checks both first and says how to install what is missing. When the global npm folder is not writable, it installs the CLI into `~/.osuite/npm` instead of asking for `sudo`.
22
+
21
23
  ### Python
22
24
  ```bash
23
25
  pip install requests
@@ -381,72 +383,70 @@ await osuite.syncState({
381
383
 
382
384
  ## Agent Identity
383
385
 
384
- Enroll agents via public-key pairing and manage approved identities for signature verification. Pairing is available in the v1 legacy SDK; the REST endpoints are callable directly from any HTTP client.
385
-
386
- ### Create Pairing
386
+ Enroll agents via public-key pairing and manage approved identities for signature verification. The current Node client, including `osuite/legacy`, does not expose pairing or identity-management helpers. Use the REST endpoints below with a workspace owner/admin credential; this does not grant an agent permission to approve its own actions.
387
387
 
388
388
  ```javascript
389
- // Node SDK (v1 legacy)
390
- import { OSuite } from 'osuite/legacy';
391
- const osuite = new OSuite({ baseUrl, apiKey, agentId });
392
-
393
- const { pairing } = await osuite.createPairing(publicKeyPem, 'RSASSA-PKCS1-v1_5', 'my-agent');
394
- console.log(pairing.id); // pair_...
389
+ async function identityRequest(route, { method = 'GET', body } = {}) {
390
+ const response = await fetch(`${baseUrl}${route}`, {
391
+ method,
392
+ headers: { 'content-type': 'application/json', 'x-api-key': adminApiKey },
393
+ ...(body === undefined ? {} : { body: JSON.stringify(body) })
394
+ });
395
+ if (!response.ok) throw new Error(`Identity request failed: ${response.status}`);
396
+ return response.json();
397
+ }
395
398
  ```
396
399
 
397
- ### Wait for Pairing Approval
400
+ ### Create Pairing
398
401
 
399
402
  ```javascript
400
- const approved = await osuite.waitForPairing(pairing.id, { timeout: 300 });
403
+ const { pairing } = await identityRequest('/api/pairings', {
404
+ method: 'POST',
405
+ body: { agent_id: agentId, agent_name: 'my-agent', public_key: publicKeyPem, algorithm: 'RSASSA-PKCS1-v1_5' }
406
+ });
407
+ console.log(pairing.id); // pair_...
401
408
  ```
402
409
 
403
410
  ### Get Pairing
404
411
 
405
412
  ```javascript
406
- const status = await osuite.getPairing(pairingId);
413
+ const status = await identityRequest(`/api/pairings/${encodeURIComponent(pairing.id)}`);
407
414
  console.log(status.pairing.status); // pending | approved | expired
408
415
  ```
409
416
 
417
+ Poll this GET with a bounded timeout while an administrator reviews the pairing. Do not create another pairing just because its status is still pending or a response was lost.
418
+
410
419
  ### Approve Pairing (Admin)
411
420
 
412
421
  ```javascript
413
- // Direct HTTP — admin API key required
414
- const res = await fetch(`${baseUrl}/api/pairings/${pairingId}/approve`, {
415
- method: 'POST',
416
- headers: { 'x-api-key': adminApiKey }
417
- });
422
+ await identityRequest(`/api/pairings/${encodeURIComponent(pairing.id)}/approve`, { method: 'POST' });
418
423
  ```
419
424
 
420
425
  ### List Pairings (Admin)
421
426
 
422
427
  ```javascript
423
- const res = await fetch(`${baseUrl}/api/pairings`, {
424
- headers: { 'x-api-key': adminApiKey }
425
- });
426
- const { pairings } = await res.json();
428
+ const { pairings } = await identityRequest('/api/pairings');
427
429
  ```
428
430
 
429
431
  ### Register Identity (Admin)
430
432
 
431
433
  ```javascript
432
- // Node SDK (v1 legacy)
433
- await osuite.registerIdentity('agent-007', publicKeyPem, 'RSASSA-PKCS1-v1_5');
434
+ await identityRequest('/api/identities', {
435
+ method: 'POST',
436
+ body: { agent_id: 'agent-007', public_key: publicKeyPem, algorithm: 'RSASSA-PKCS1-v1_5' }
437
+ });
434
438
  ```
435
439
 
436
440
  ### List Identities (Admin)
437
441
 
438
442
  ```javascript
439
- const { identities } = await osuite.getIdentities();
443
+ const { identities } = await identityRequest('/api/identities');
440
444
  ```
441
445
 
442
446
  ### Revoke Identity (Admin)
443
447
 
444
448
  ```javascript
445
- // Direct HTTP — admin API key required
446
- const res = await fetch(`${baseUrl}/api/identities/${agentId}`, {
447
- method: 'DELETE',
448
- headers: { 'x-api-key': adminApiKey }
449
- });
449
+ await identityRequest(`/api/identities/${encodeURIComponent(agentId)}`, { method: 'DELETE' });
450
450
  ```
451
451
 
452
452
  ---
@@ -518,11 +518,11 @@ osuite adapter init acme-erp # scaffold an enterprise custom adapter mapping
518
518
  osuite adapter test .osuite/adapters/acme-erp.json
519
519
  osuite approvals # approval inbox
520
520
  osuite review <actionId> # Decision V2 review surface
521
- osuite approve <actionId> # approve a specific action
521
+ osuite approve <actionId> # approve from the CLI where the workspace allows it; otherwise prints the Studio link
522
522
  osuite deny <actionId> # deny a specific action
523
523
  ```
524
524
 
525
- For local CLI agents, `osuite connect auto` prints a browser handoff URL and installs the project hook lane when it can detect Codex or Claude Code. If browser handoff is unavailable, copy `.codex/.env.example` or `.claude/.env.example` to `.env`, fill `OSUITE_API_KEY`, and run the agent from the same project root. The CLI is intentionally more than an API wrapper:
525
+ For local CLI agents, `osuite connect auto` opens the browser handoff in your browser (or prints the link with `--no-browser`, in CI, over SSH, or without a terminal), waits as long as the one-time code is valid (about 10 minutes), and installs the project hook lane when it can detect Codex or Claude Code. If browser handoff is unavailable, copy `.codex/.env.example` or `.claude/.env.example` to `.env`, fill `OSUITE_API_KEY`, and run the agent from the same project root. The CLI is intentionally more than an API wrapper:
526
526
  - `doctor` tells a developer what is missing before they connect an agent.
527
527
  - `explain` gives a local CAVA preview before a command reaches OSuite.
528
528
  - `adapters` explains the three Runtime Coverage tiers: reference adapters, managed OSuite adapters, and enterprise custom adapters.
@@ -530,6 +530,10 @@ For local CLI agents, `osuite connect auto` prints a browser handoff URL and ins
530
530
  - `approvals` provides a readable approval inbox instead of raw JSON.
531
531
  - `review` renders a PCAA/CAVA/Decision V2 review card with action understanding, evidence confidence, control posture, and score dimensions when present.
532
532
 
533
+ Project installation refuses settings, credentials, or hook paths whose symlinks resolve outside the project's real root, including linked parent directories. Existing settings are merged; `disableAllHooks: true` and explicit Codex hook-disable flags stay disabled even with `--force`. Disabled setup is reported as not ready, not as a successful connection.
534
+
535
+ `doctor` separates hook configuration, project enablement, credentials, connectivity, telemetry, and an enforced policy outcome. Observation-only mode, an unavailable guard (whether fail-open or fail-closed), or telemetry without a matching policy outcome does not pass the governance check. Hook warnings are printed even when the probe otherwise succeeds. The probe never executes its sample tool command and does not prove the host loaded the hooks: start or restart the runtime and verify its actual hook invocation separately.
536
+
533
537
  When an agent calls `waitForApproval()`, it prints the action ID and replay link to stdout. Approve from any terminal or the dashboard, and the agent unblocks instantly.
534
538
 
535
539
  ### Runtime Coverage tiers
@@ -564,16 +568,16 @@ It detects `.claude`, creates `.claude/hooks/*`, `.claude/settings.json`, `.clau
564
568
 
565
569
  ---
566
570
 
567
- ## Classic SDK (v1)
571
+ ## Legacy Import Compatibility
568
572
 
569
- The v2 SDK covers the 45 methods most critical to agent governance. If you require the full platform surface (188+ methods including Calendar, Workflows, Routing, Pairing, etc.), the v1 SDK is available via the `osuite/legacy` sub-path in Node.js or via the full client in Python.
573
+ `osuite/legacy` currently aliases the v2 client. It preserves the import path, not the full historical v1 method surface. ESM and CommonJS expose the same current client capabilities.
570
574
 
571
575
  ```javascript
572
- // v1 legacy import
576
+ // Compatibility import for the current client
573
577
  import { OSuite } from 'osuite/legacy';
574
578
  ```
575
579
 
576
- Methods moved to v1 only: `createWebhook`, `getActivityLogs`, `mapCompliance`, `getProofReport`.
580
+ If older code depends on methods not listed in this SDK, migrate those calls to documented REST endpoints or review its existing pinned version before upgrading. Importing `osuite/legacy` does not restore removed methods. Python client releases are separate from this npm package.
577
581
 
578
582
  ---
579
583
 
package/cli.js CHANGED
@@ -1,10 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { spawn } from 'node:child_process';
3
4
  import fs from 'node:fs';
4
5
  import path from 'node:path';
5
6
  import crypto from 'node:crypto';
6
7
  import { fileURLToPath } from 'node:url';
7
8
  import { OSuite, buildReviewSurface } from './osuite.js';
9
+ import {
10
+ describeInstallResult,
11
+ findHookInstallations,
12
+ installBlockers,
13
+ installProjectFile,
14
+ resolveProjectPath,
15
+ runHookCheck,
16
+ } from './projectHooks.js';
8
17
 
9
18
  const __filename = fileURLToPath(import.meta.url);
10
19
  const __dirname = path.dirname(__filename);
@@ -130,6 +139,8 @@ function parseArgs(argv) {
130
139
  return { command, args };
131
140
  }
132
141
 
142
+ // Hooks run with the agent's environment, not the values this CLI loads from project .env files.
143
+ const SHELL_ENV = { ...process.env };
133
144
  loadProjectEnvironment();
134
145
 
135
146
  function envValue(name, fallback) {
@@ -309,6 +320,33 @@ async function startDeviceConnect({ baseUrl, runtime, agentId }) {
309
320
  return payload;
310
321
  }
311
322
 
323
+ // Opens the handoff in the browser, as `gh auth login` does. Not with
324
+ // --no-browser or OSUITE_NO_BROWSER=1, in CI, over SSH, without a terminal or
325
+ // a Linux display: there the printed link is opened by hand.
326
+ function shouldOpenBrowser(args = {}, env = process.env) {
327
+ if (args['no-browser']) return false;
328
+ if (['1', 'true', 'yes'].includes(String(env.OSUITE_NO_BROWSER || '').trim().toLowerCase())) return false;
329
+ if (env.CI || env.SSH_CONNECTION || env.SSH_TTY) return false;
330
+ if (process.platform === 'linux' && !env.DISPLAY && !env.WAYLAND_DISPLAY) return false;
331
+ return Boolean(process.stdout.isTTY);
332
+ }
333
+
334
+ function openInBrowser(url) {
335
+ const [command, commandArgs] = process.platform === 'darwin'
336
+ ? ['open', [url]]
337
+ : process.platform === 'win32'
338
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
339
+ : ['xdg-open', [url]];
340
+ try {
341
+ const child = spawn(command, commandArgs, { stdio: 'ignore', detached: true });
342
+ child.on('error', () => {});
343
+ child.unref();
344
+ return true;
345
+ } catch {
346
+ return false;
347
+ }
348
+ }
349
+
312
350
  async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs }) {
313
351
  const deadline = Date.now() + timeoutMs;
314
352
  while (Date.now() <= deadline) {
@@ -326,7 +364,7 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
326
364
  continue;
327
365
  }
328
366
  if (response.status === 410 || payload.status === 'expired') {
329
- throw new Error('Browser handoff expired. Run osuite connect again.');
367
+ throw new Error('The connect code expired before it was approved. Run osuite connect again for a new code.');
330
368
  }
331
369
  if (response.status === 409 || payload.status === 'consumed') {
332
370
  throw new Error(payload.error || 'Browser handoff was already consumed.');
@@ -340,13 +378,7 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
340
378
  }
341
379
 
342
380
  function projectFilePath(relativePath) {
343
- const clean = String(relativePath || '').replace(/^\/+/, '');
344
- const root = path.resolve(process.cwd());
345
- const absolute = path.resolve(root, clean);
346
- if (absolute !== root && !absolute.startsWith(`${root}${path.sep}`)) {
347
- throw new Error(`Refusing to write outside the project root: ${relativePath}`);
348
- }
349
- return absolute;
381
+ return resolveProjectPath(process.cwd(), relativePath);
350
382
  }
351
383
 
352
384
  function writeProjectFile(relativePath, body, { force = false } = {}) {
@@ -445,7 +477,7 @@ async function loadRuntimeBootstrap(spec, args, config) {
445
477
  return response.json();
446
478
  }
447
479
 
448
- async function installRuntimeProjectBootstrap(target, args = {}) {
480
+ async function installRuntimeProjectBootstrap(target, args = {}, { nextSteps = true } = {}) {
449
481
  const spec = PROJECT_BOOTSTRAPS[target];
450
482
  const config = readConfig();
451
483
  const bootstrap = await loadRuntimeBootstrap(spec, args, config);
@@ -453,29 +485,64 @@ async function installRuntimeProjectBootstrap(target, args = {}) {
453
485
  const results = [];
454
486
 
455
487
  Object.entries(bootstrap.files || {}).forEach(([relativePath, body]) => {
456
- results.push(writeProjectFile(remapBootstrapPath(spec, relativePath), body, { force }));
488
+ results.push(installProjectFile(process.cwd(), remapBootstrapPath(spec, relativePath), body, { force }));
457
489
  });
458
490
 
459
491
  if (bootstrap.recommended_env) {
460
- results.push(writeProjectFile(spec.envPath, `${bootstrap.recommended_env.trim()}\n`, { force }));
492
+ results.push(installProjectFile(process.cwd(), spec.envPath, `${bootstrap.recommended_env.trim()}\n`, { force }));
461
493
  }
462
494
 
463
- const written = results.filter((item) => item.status === 'written');
464
- const skipped = results.filter((item) => item.status === 'skipped');
495
+ const blockers = installBlockers(results);
496
+ const colors = { created: ANSI.green, merged: ANSI.green, replaced: ANSI.green, failed: ANSI.red, kept: ANSI.yellow };
465
497
 
466
498
  write(c(spec.label, ANSI.bold));
467
499
  write(`Installing project files into ${process.cwd()}`);
468
500
  write('');
469
- written.forEach((item) => write(` ${c('created', ANSI.green)} ${item.relativePath}`));
470
- skipped.forEach((item) => write(` ${c('kept ', ANSI.yellow)} ${item.relativePath} (use --force to replace)`));
471
- write('');
472
- write(c('Next steps', ANSI.bold));
473
- write(` 1. Copy ${spec.envPath} to ${spec.envPath.replace(/\.example$/, '')} and fill OSUITE_API_KEY.`);
474
- write(' 2. Run osuite doctor.');
475
- write(` 3. ${spec.runLine}`);
476
- write(` 4. ${spec.smokeLine}`);
477
- write('');
478
- write(c('OSuite CLI is the control surface; the project hook files are what intercept agent actions.', ANSI.dim));
501
+ results.forEach((result) => {
502
+ describeInstallResult(result).forEach((line) => {
503
+ const status = line.split(/\s+/)[0];
504
+ write(` ${colors[status] ? `${c(status, colors[status])}${line.slice(status.length)}` : line}`);
505
+ });
506
+ });
507
+ if (blockers.length) {
508
+ write('');
509
+ write(c('OSuite hook setup is not ready, so this agent is not governed:', ANSI.red));
510
+ blockers.forEach((blocker) => write(` ${blocker}`));
511
+ }
512
+ if (nextSteps) {
513
+ write('');
514
+ write(c('Next steps', ANSI.bold));
515
+ write(` 1. Copy ${spec.envPath} to ${spec.envPath.replace(/\.example$/, '')} and fill OSUITE_API_KEY.`);
516
+ write(' 2. Run osuite doctor. It checks project enablement, connection, telemetry, and governance with a direct hook probe.');
517
+ write(` 3. ${spec.runLine}`);
518
+ write(` 4. ${spec.smokeLine}`);
519
+ write('');
520
+ write(c('OSuite CLI is the control surface; the project hook files are what intercept agent actions.', ANSI.dim));
521
+ }
522
+ return { ok: blockers.length === 0, results, blockers };
523
+ }
524
+
525
+ function writeCheckLine(status, label, detail) {
526
+ const tags = {
527
+ ok: c('OK ', ANSI.green),
528
+ miss: c('MISS', ANSI.yellow),
529
+ warn: c('WARN', ANSI.yellow),
530
+ fail: c('FAIL', ANSI.red),
531
+ };
532
+ write(`${tags[status]} ${label.padEnd(18)} ${detail}`);
533
+ }
534
+
535
+ // A telemetry-only result must never count as successful governance.
536
+ async function verifyProjectHooks(runtimes) {
537
+ const installations = findHookInstallations(process.cwd(), runtimes);
538
+ const checks = [];
539
+ for (const installation of installations) {
540
+ const check = await runHookCheck({ projectRoot: process.cwd(), installation, shellEnv: SHELL_ENV });
541
+ check.steps.forEach((step) => writeCheckLine(step.ok ? 'ok' : 'fail', step.label, `${installation.label}: ${step.detail}`));
542
+ (check.warnings || []).forEach((warning) => writeCheckLine('warn', 'Hook warning', `${installation.label}: ${warning}`));
543
+ checks.push({ installation, ...check });
544
+ }
545
+ return checks;
479
546
  }
480
547
 
481
548
  function banner() {
@@ -492,12 +559,13 @@ function printHelp() {
492
559
  write(c(`OSuite CLI v${pkg.version}`, ANSI.dim));
493
560
  write('');
494
561
  write(c('Useful commands', ANSI.bold));
495
- write(' osuite doctor Check connection, runtime, signatures, package health');
562
+ write(' osuite doctor Check connection, then run the project hook with a sample call');
496
563
  write(' osuite status Ping Studio and show current workspace connection');
497
564
  write(' osuite explain "git push origin main" Explain how CAVA/Decision V2 will read a command');
498
565
  write(' osuite approvals --limit 20 Show pending approval inbox');
499
566
  write(' osuite review <actionId> Render the decision review card');
500
- write(' osuite approve <actionId> --reason "Looks safe"');
567
+ write(' osuite approve <actionId> Approve from the CLI where the workspace allows it;');
568
+ write(' otherwise prints the Studio link to approve it');
501
569
  write(' osuite deny <actionId> --reason "Outside change window"');
502
570
  write(' osuite adapters [status|coverage] Explain Runtime Coverage tiers and next steps');
503
571
  write(' osuite adapter init <name> Scaffold an enterprise custom adapter mapping');
@@ -505,6 +573,7 @@ function printHelp() {
505
573
  write(' osuite external status Show external verifier network setup and usage');
506
574
  write(' osuite external configure --provider babyblue_invinoveritas --mode shadow --api-key <key> --expected-source-class independent_mediator');
507
575
  write(' osuite connect [auto|codex|claude|sdk|mcp] Detect runtime and start browser handoff');
576
+ write(' --no-browser prints the link instead of opening it');
508
577
  write(' osuite init [sdk|codex|claude|mcp] Print setup steps for a runtime lane');
509
578
  write('');
510
579
  write(c('Environment', ANSI.bold));
@@ -977,16 +1046,28 @@ async function doctor() {
977
1046
  }
978
1047
  }
979
1048
 
1049
+ const hookChecks = await verifyProjectHooks();
1050
+ if (!hookChecks.length) writeCheckLine('miss', 'Agent hooks', 'none in this project (fine for SDK and MCP runtimes)');
1051
+ const hooksOk = hookChecks.every((check) => check.ok);
1052
+
980
1053
  write('');
981
- if (!ok) {
1054
+ if (!ok || !hooksOk) {
982
1055
  write(c('Next step', ANSI.bold));
983
- write(' osuite init');
984
- write(' export OSUITE_BASE_URL=https://studio.osuite.ai');
985
- write(' export OSUITE_API_KEY=<workspace-api-key>');
1056
+ if (!ok) {
1057
+ write(' osuite init');
1058
+ write(' export OSUITE_BASE_URL=https://studio.osuite.ai');
1059
+ write(' export OSUITE_API_KEY=<workspace-api-key>');
1060
+ }
1061
+ hookChecks.filter((check) => !check.ok).forEach((check) => {
1062
+ write(` ${check.installation.label} is not governed yet. Fix the FAIL line above, or run osuite connect ${check.installation.runtime} to reinstall, then run osuite doctor again.`);
1063
+ });
986
1064
  process.exit(1);
987
1065
  }
988
1066
 
989
1067
  write(c('Your OSuite CLI is ready.', ANSI.green));
1068
+ hookChecks.forEach((check) => {
1069
+ write(` ${check.installation.label} direct hook probe was governed and reached OSuite; verify host invocation after starting the runtime.`);
1070
+ });
990
1071
  }
991
1072
 
992
1073
  async function status() {
@@ -1028,6 +1109,9 @@ async function approvals(args) {
1028
1109
 
1029
1110
  write(`${'Action ID'.padEnd(18)} ${'Risk'.padStart(3)} ${'Type'.padEnd(24)} ${'Agent'.padEnd(18)} Goal`);
1030
1111
  actions.forEach((action) => write(renderActionRow(action)));
1112
+ write('');
1113
+ write(c('Review and decide in Studio:', ANSI.dim));
1114
+ actions.forEach((action) => write(` ${client.baseUrl}/approvals?action=${encodeURIComponent(action.action_id)}`));
1031
1115
  }
1032
1116
 
1033
1117
  async function review(actionId) {
@@ -1047,7 +1131,19 @@ async function decide(actionId, decision, args) {
1047
1131
  process.exit(1);
1048
1132
  }
1049
1133
  const client = requireClient();
1050
- const result = await client.approveAction(actionId, decision, args.reason || args.reasoning);
1134
+ let result;
1135
+ try {
1136
+ result = await client.approveAction(actionId, decision, args.reason || args.reasoning);
1137
+ } catch (error) {
1138
+ // Agents share this machine's API key, so the workspace only accepts
1139
+ // decisions from a person signed in to Studio.
1140
+ if (error?.response?.code === 'HUMAN_APPROVER_REQUIRED') {
1141
+ write(c('Approvals are made by a person signed in to OSuite Studio.', ANSI.yellow));
1142
+ write(`Open this request to ${decision === 'allow' ? 'approve' : 'deny'} it: ${error.response.review_url || `${client.baseUrl}/approvals?action=${encodeURIComponent(actionId)}`}`);
1143
+ process.exit(1);
1144
+ }
1145
+ throw error;
1146
+ }
1051
1147
  const label = decision === 'allow' ? 'Approved' : 'Denied';
1052
1148
  write(c(`${label} ${actionId}`, decision === 'allow' ? ANSI.green : ANSI.red));
1053
1149
  if (result?.action?.status) write(`New status ${result.action.status}`);
@@ -1159,7 +1255,8 @@ async function external(args = {}) {
1159
1255
  async function init(target = 'generic', args = {}) {
1160
1256
  write(c('OSuite init', `${ANSI.bold}${ANSI.cyan}`));
1161
1257
  if (PROJECT_BOOTSTRAPS[target]) {
1162
- await installRuntimeProjectBootstrap(target, args);
1258
+ const install = await installRuntimeProjectBootstrap(target, args);
1259
+ if (!install.ok) process.exitCode = 1;
1163
1260
  return;
1164
1261
  }
1165
1262
 
@@ -1213,17 +1310,21 @@ async function connect(target = 'auto', args = {}) {
1213
1310
  write(`Browser handoff ${handoffUrl}`);
1214
1311
  write(`One-time code ${code}`);
1215
1312
  write('');
1313
+ const opened = !args['dry-run'] && shouldOpenBrowser(args) && openInBrowser(handoffUrl);
1216
1314
  write(c('What happens next', ANSI.bold));
1217
- write(' 1. Open the browser handoff URL and approve this terminal connection in Studio.');
1315
+ write(opened
1316
+ ? ' 1. Studio opened in your browser. Check the code matches, then approve this terminal.'
1317
+ : ' 1. Open the browser handoff URL, check the code matches, then approve this terminal in Studio.');
1218
1318
  write(' 2. OSuite prepares the runtime identity, project hook lane, and signed env for this project.');
1219
1319
  write(' 3. Return here; the CLI will finish automatically and then you can run osuite doctor.');
1220
1320
  write('');
1221
1321
 
1322
+ let install = null;
1222
1323
  if (PROJECT_BOOTSTRAPS[runtime]) {
1223
1324
  if (args['dry-run']) {
1224
1325
  write(`Dry run: would install project hook files for ${runtime}.`);
1225
1326
  } else {
1226
- await installRuntimeProjectBootstrap(runtime, args);
1327
+ install = await installRuntimeProjectBootstrap(runtime, args, { nextSteps: false });
1227
1328
  }
1228
1329
  } else {
1229
1330
  write(c('Runtime setup', ANSI.bold));
@@ -1233,7 +1334,9 @@ async function connect(target = 'auto', args = {}) {
1233
1334
  }
1234
1335
 
1235
1336
  if (!args['dry-run'] && connectPayload) {
1236
- const timeoutMs = parsePositiveInt(args['poll-timeout-ms'], 180000);
1337
+ // Wait as long as the code is valid, so approving late still connects.
1338
+ const expiresInSeconds = Math.max(30, Number(connectPayload.expires_in || 600));
1339
+ const timeoutMs = parsePositiveInt(args['poll-timeout-ms'], expiresInSeconds * 1000);
1237
1340
  const intervalMs = parsePositiveInt(
1238
1341
  args['poll-interval-ms'],
1239
1342
  Math.max(1000, Number(connectPayload.interval_seconds || 2) * 1000),
@@ -1241,7 +1344,7 @@ async function connect(target = 'auto', args = {}) {
1241
1344
 
1242
1345
  write('');
1243
1346
  write(c('Waiting for browser approval', ANSI.bold));
1244
- write(` Code ${code} expires in about ${Math.round(Number(connectPayload.expires_in || 600) / 60)} minutes.`);
1347
+ write(` Code ${code} expires in about ${Math.round(expiresInSeconds / 60)} minutes. Press Ctrl+C to stop waiting.`);
1245
1348
 
1246
1349
  const credential = await pollDeviceConnect({
1247
1350
  baseUrl,
@@ -1255,13 +1358,36 @@ async function connect(target = 'auto', args = {}) {
1255
1358
  const envPath = envPathForRuntime(runtime);
1256
1359
  const result = writeProjectFile(envPath, formatEnvBody(credential.env), { force: true });
1257
1360
  write('');
1258
- write(c('Connected to OSuite', ANSI.green));
1259
- write(` ${result.status === 'written' ? 'wrote' : 'kept'} ${result.relativePath}`);
1260
- write(' Run osuite doctor, then start the agent from this project root.');
1361
+ write(`Saved credentials to ${result.relativePath}`);
1362
+ if (!PROJECT_BOOTSTRAPS[runtime]) {
1363
+ write(c('Connected to OSuite', ANSI.green));
1364
+ write(' Run osuite doctor, then start the agent from this project root.');
1365
+ } else if (!install?.ok) {
1366
+ write(c('Not connected: OSuite hook setup is not ready, so this agent is not governed.', ANSI.red));
1367
+ (install?.blockers || []).forEach((blocker) => write(` ${blocker}`));
1368
+ write(` Fix the file above, then run osuite connect ${runtime} again.`);
1369
+ process.exitCode = 1;
1370
+ } else {
1371
+ write('');
1372
+ write(c('Checking the installed hook', ANSI.bold));
1373
+ const checks = await verifyProjectHooks([runtime]);
1374
+ write('');
1375
+ if (checks.length && checks.every((check) => check.ok)) {
1376
+ write(c('Connected to OSuite', ANSI.green));
1377
+ write(` The direct ${PROJECT_BOOTSTRAPS[runtime].label.replace(/ hook runtime$/, '')} hook probe was governed and reached Studio; host invocation still needs runtime verification.`);
1378
+ write(` ${PROJECT_BOOTSTRAPS[runtime].runLine}`);
1379
+ } else {
1380
+ write(c('Not connected: credentials are saved, but the hook check failed, so this agent is not governed yet.', ANSI.red));
1381
+ write(' Fix the FAIL line above, then run osuite doctor.');
1382
+ process.exitCode = 1;
1383
+ }
1384
+ }
1261
1385
  } else {
1262
1386
  write('');
1263
- write(c('Browser approval not completed before the timeout.', ANSI.yellow));
1264
- write(' Keep the browser handoff open or run osuite connect again.');
1387
+ write(c('Not connected: nobody approved this terminal in the browser in time.', ANSI.yellow));
1388
+ write(` Run osuite connect ${runtime} again for a new code${install?.ok ? '; the hook files are already installed, only the credentials are missing' : ''}.`);
1389
+ write(' If the browser did not open, copy the handoff link above into it.');
1390
+ process.exitCode = 1;
1265
1391
  }
1266
1392
  }
1267
1393
 
package/osuite.js CHANGED
@@ -142,10 +142,17 @@ class OSuite {
142
142
  }
143
143
 
144
144
  if (action.status === 'pending_approval') wasPending = true;
145
- if (action.approved_by || action.approved_at) return action;
146
- if (action.status === 'failed' || action.status === 'cancelled') {
145
+ if (action.status === 'expired') {
146
+ throw new ApprovalDeniedError(
147
+ action.error_message || 'The approval request expired before anyone reviewed it. Ask again.',
148
+ 'expired',
149
+ );
150
+ }
151
+ if (['failed', 'cancelled', 'blocked'].includes(action.status)) {
147
152
  throw new ApprovalDeniedError(action.error_message || 'Operator denied the action.', action.status);
148
153
  }
154
+ // Denials also carry reviewer metadata; it is not permission on its own.
155
+ if (action.status === 'running' && (action.approved_by || action.approved_at)) return action;
149
156
  if (wasPending && action.status !== 'pending_approval') {
150
157
  throw new Error(`Action ${actionId} left pending_approval without explicit approval metadata.`);
151
158
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.9.9",
3
+ "version": "2.10.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,7 @@
23
23
  },
24
24
  "files": [
25
25
  "cli.js",
26
+ "projectHooks.js",
26
27
  "reviewSurface.js",
27
28
  "osuite.js",
28
29
  "index.cjs",
@@ -0,0 +1,741 @@
1
+ // Project hook install and verification for `osuite connect`, `osuite init` and `osuite doctor`.
2
+ // Settings files are merged, never replaced: most projects already have them.
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { spawn } from 'node:child_process';
8
+
9
+ const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop)\.py/;
10
+
11
+ export const RUNTIME_HOOKS = {
12
+ claude: {
13
+ label: 'Claude Code',
14
+ dir: '.claude',
15
+ settings: ['.claude/settings.json', '.claude/settings.local.json'],
16
+ },
17
+ codex: {
18
+ label: 'Codex',
19
+ dir: '.codex',
20
+ settings: ['.codex/hooks.json'],
21
+ config: '.codex/config.toml',
22
+ },
23
+ };
24
+
25
+ const MERGED_FILES = {
26
+ '.claude/settings.json': 'json',
27
+ '.claude/settings.local.json': 'json',
28
+ '.codex/hooks.json': 'json',
29
+ '.codex/config.toml': 'toml',
30
+ };
31
+
32
+ export const DOCTOR_COMMAND = 'echo "OSuite doctor hook check"';
33
+
34
+ function isPlainObject(value) {
35
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
36
+ }
37
+
38
+ function hookScriptName(command) {
39
+ const match = String(command || '').match(HOOK_SCRIPT_RE);
40
+ return match ? match[0] : '';
41
+ }
42
+
43
+ // An OSuite hook already in the file counts as present even when its path differs,
44
+ // so a re-run never registers a second copy that would govern each call twice.
45
+ function sameHook(existing, wanted) {
46
+ const existingScript = hookScriptName(existing?.command);
47
+ const wantedScript = hookScriptName(wanted?.command);
48
+ if (existingScript && wantedScript) return existingScript === wantedScript;
49
+ return String(existing?.command || '').trim() === String(wanted?.command || '').trim();
50
+ }
51
+
52
+ function countHooks(hooks) {
53
+ if (!isPlainObject(hooks)) return 0;
54
+ return Object.values(hooks).reduce((total, groups) => total + (Array.isArray(groups)
55
+ ? groups.reduce((sum, group) => sum + (Array.isArray(group?.hooks) ? group.hooks.length : 0), 0)
56
+ : 0), 0);
57
+ }
58
+
59
+ function templateHooks(template) {
60
+ const hooks = isPlainObject(template?.hooks) ? template.hooks : {};
61
+ return Object.entries(hooks).flatMap(([event, groups]) => (Array.isArray(groups) ? groups : [])
62
+ .flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : [])
63
+ .map((hook) => ({ event, matcher: group.matcher, command: hook.command }))));
64
+ }
65
+
66
+ function disabledHookSettings(settings) {
67
+ return settings?.disableAllHooks === true
68
+ ? ['disableAllHooks = true keeps hooks disabled; intentional disablement was preserved']
69
+ : [];
70
+ }
71
+
72
+ /**
73
+ * Add the OSuite PreToolUse/PostToolUse entries to a JSON settings file.
74
+ * The user's own hooks and every other key stay as they are.
75
+ */
76
+ export function mergeHookSettings(existingText, templateText) {
77
+ const template = JSON.parse(templateText);
78
+ if (existingText === null || existingText === undefined) {
79
+ return { status: 'created', body: templateText, added: templateHooks(template), keptHooks: 0, keptKeys: [], conflicts: disabledHookSettings(template) };
80
+ }
81
+
82
+ let settings = {};
83
+ if (existingText.trim()) {
84
+ try {
85
+ settings = JSON.parse(existingText);
86
+ } catch (error) {
87
+ return { status: 'error', error: `not valid JSON (${error.message})` };
88
+ }
89
+ }
90
+ if (!isPlainObject(settings)) return { status: 'error', error: 'expected a JSON object at the top level' };
91
+
92
+ let hooks = settings.hooks;
93
+ if (hooks === undefined || hooks === null || (Array.isArray(hooks) && hooks.length === 0)) hooks = {};
94
+ if (!isPlainObject(hooks)) return { status: 'error', error: '"hooks" must be an object keyed by event name' };
95
+
96
+ const wanted = isPlainObject(template.hooks) ? template.hooks : {};
97
+ const merged = { ...hooks };
98
+ const added = [];
99
+ for (const [event, groups] of Object.entries(wanted)) {
100
+ const current = merged[event] === undefined ? [] : merged[event];
101
+ if (!Array.isArray(current)) return { status: 'error', error: `"hooks.${event}" must be a list` };
102
+ const present = current.flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []));
103
+ const next = [...current];
104
+ for (const group of Array.isArray(groups) ? groups : []) {
105
+ const missing = (group.hooks || []).filter((hook) => !present.some((existing) => sameHook(existing, hook)));
106
+ if (!missing.length) continue;
107
+ next.push({ ...group, hooks: missing });
108
+ missing.forEach((hook) => added.push({ event, matcher: group.matcher, command: hook.command }));
109
+ }
110
+ if (next.length !== current.length) merged[event] = next;
111
+ }
112
+
113
+ const result = {
114
+ added,
115
+ keptHooks: countHooks(hooks),
116
+ keptKeys: Object.keys(settings).filter((key) => key !== 'hooks'),
117
+ conflicts: disabledHookSettings(settings),
118
+ };
119
+ if (!added.length) return { ...result, status: 'unchanged', body: existingText };
120
+ return { ...result, status: 'merged', body: `${JSON.stringify({ ...settings, hooks: merged }, null, 2)}\n` };
121
+ }
122
+
123
+ // --- TOML ------------------------------------------------------------------
124
+ // Line-based on purpose: the CLI has no dependencies, and the partial only sets
125
+ // plain keys. Lines inside multi-line strings and arrays are skipped.
126
+
127
+ function normalizeTomlKey(raw) {
128
+ return String(raw || '')
129
+ .split('.')
130
+ .map((part) => part.trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1'))
131
+ .join('.');
132
+ }
133
+
134
+ function stripTomlValue(raw) {
135
+ const value = String(raw || '').trim();
136
+ const quote = value[0];
137
+ if (quote === '"' || quote === "'") {
138
+ const end = value.indexOf(quote, 1);
139
+ return end > 0 ? value.slice(0, end + 1) : value;
140
+ }
141
+ const hash = value.indexOf('#');
142
+ return (hash >= 0 ? value.slice(0, hash) : value).trim();
143
+ }
144
+
145
+ function withoutStrings(text) {
146
+ return String(text || '').replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, '');
147
+ }
148
+
149
+ function bracketDelta(text) {
150
+ const bare = withoutStrings(text).replace(/#.*$/, '');
151
+ return (bare.match(/[[{]/g) || []).length - (bare.match(/[\]}]/g) || []).length;
152
+ }
153
+
154
+ function parseInlineTable(raw) {
155
+ const inner = withoutStrings(raw).includes('{') ? String(raw).trim().replace(/^\{|\}\s*(#.*)?$/g, '') : '';
156
+ return inner.split(',').map((part) => part.split('=')).filter((pair) => pair.length >= 2)
157
+ .map(([key, ...rest]) => [normalizeTomlKey(key), stripTomlValue(rest.join('='))]);
158
+ }
159
+
160
+ function scanToml(text) {
161
+ const lines = String(text || '').split(/\r?\n/);
162
+ const values = new Map();
163
+ const tables = new Map();
164
+ const inlineTables = new Set();
165
+ const root = { lastIndex: -1 };
166
+ let current = root;
167
+ let tableName = '';
168
+ let firstHeaderIndex = -1;
169
+ let multiline = null;
170
+ let depth = 0;
171
+
172
+ lines.forEach((line, index) => {
173
+ if (multiline) {
174
+ if (line.includes(multiline)) multiline = null;
175
+ current.lastIndex = index;
176
+ return;
177
+ }
178
+ if (depth > 0) {
179
+ depth += bracketDelta(line);
180
+ current.lastIndex = index;
181
+ return;
182
+ }
183
+ const trimmed = line.trim();
184
+ if (!trimmed || trimmed.startsWith('#')) return;
185
+
186
+ const header = trimmed.match(/^\[(\[)?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/);
187
+ if (header) {
188
+ if (firstHeaderIndex < 0) firstHeaderIndex = index;
189
+ tableName = normalizeTomlKey(header[2]);
190
+ const isArrayTable = Boolean(header[1]);
191
+ current = { headerIndex: index, lastIndex: index, arrayTable: isArrayTable };
192
+ if (!isArrayTable && !tables.has(tableName)) tables.set(tableName, current);
193
+ return;
194
+ }
195
+
196
+ const pair = trimmed.match(/^([^=]+?)\s*=\s*(.*)$/);
197
+ if (!pair) return;
198
+ current.lastIndex = index;
199
+ const value = pair[2];
200
+ if (!current.arrayTable) {
201
+ const key = tableName ? `${tableName}.${normalizeTomlKey(pair[1])}` : normalizeTomlKey(pair[1]);
202
+ values.set(key, stripTomlValue(value));
203
+ if (value.trim().startsWith('{')) {
204
+ inlineTables.add(key);
205
+ parseInlineTable(value).forEach(([innerKey, innerValue]) => values.set(`${key}.${innerKey}`, innerValue));
206
+ }
207
+ }
208
+ const tripleDouble = (value.match(/"""/g) || []).length;
209
+ const tripleSingle = (value.match(/'''/g) || []).length;
210
+ if (tripleDouble % 2 === 1) multiline = '"""';
211
+ else if (tripleSingle % 2 === 1) multiline = "'''";
212
+ else depth = Math.max(0, bracketDelta(value));
213
+ });
214
+
215
+ return { lines, values, tables, inlineTables, root, firstHeaderIndex };
216
+ }
217
+
218
+ function tomlEntries(text) {
219
+ const entries = [];
220
+ let table = '';
221
+ String(text || '').split(/\r?\n/).forEach((line) => {
222
+ const trimmed = line.trim();
223
+ if (!trimmed || trimmed.startsWith('#')) return;
224
+ const header = trimmed.match(/^\[\s*([^\]]+?)\s*\]$/);
225
+ if (header) {
226
+ table = normalizeTomlKey(header[1]);
227
+ return;
228
+ }
229
+ const pair = trimmed.match(/^([^=]+?)\s*=\s*(.*)$/);
230
+ if (pair) entries.push({ table, key: normalizeTomlKey(pair[1]), value: stripTomlValue(pair[2]) });
231
+ });
232
+ return entries;
233
+ }
234
+
235
+ function describeTomlEntry(entry) {
236
+ return `${entry.table ? `[${entry.table}] ` : ''}${entry.key} = ${entry.value}`;
237
+ }
238
+
239
+ const HOOK_FLAGS = ['features.hooks', 'features.codex_hooks'];
240
+
241
+ /**
242
+ * Add the keys of the OSuite config.toml partial that the file does not set yet.
243
+ * Values the user already chose are kept and reported; running it again changes nothing.
244
+ */
245
+ export function mergeTomlPartial(existingText, partialText) {
246
+ const entries = tomlEntries(partialText);
247
+ if (existingText === null || existingText === undefined) {
248
+ return { status: 'created', body: partialText, added: entries.map(describeTomlEntry), kept: [], conflicts: [] };
249
+ }
250
+
251
+ const scan = scanToml(existingText);
252
+ const added = [];
253
+ const kept = [];
254
+ const conflicts = [];
255
+ const rootLines = [];
256
+ const tableLines = new Map();
257
+ const newTables = new Map();
258
+
259
+ HOOK_FLAGS.forEach((flag) => {
260
+ if (scan.values.get(flag) === 'false') {
261
+ conflicts.push(`${flag.replace('features.', '[features] ')} = false turns Codex hooks off; set it to true`);
262
+ }
263
+ });
264
+
265
+ for (const entry of entries) {
266
+ const fullKey = entry.table ? `${entry.table}.${entry.key}` : entry.key;
267
+ if (HOOK_FLAGS.includes(fullKey) && conflicts.length && !scan.values.has(fullKey)) continue;
268
+ if (scan.values.has(fullKey)) {
269
+ const current = scan.values.get(fullKey);
270
+ if (current !== entry.value && !HOOK_FLAGS.includes(fullKey)) {
271
+ kept.push({ key: describeTomlEntry({ ...entry, value: current }), suggested: entry.value });
272
+ }
273
+ continue;
274
+ }
275
+ const line = `${entry.key} = ${entry.value}`;
276
+ if (!entry.table) {
277
+ rootLines.push(line);
278
+ } else if (scan.inlineTables.has(entry.table) || (scan.values.has(entry.table) && !scan.tables.has(entry.table))) {
279
+ kept.push({ key: `${entry.table} (inline)`, suggested: `add ${line}` });
280
+ continue;
281
+ } else if (scan.tables.has(entry.table)) {
282
+ if (!tableLines.has(entry.table)) tableLines.set(entry.table, []);
283
+ tableLines.get(entry.table).push(line);
284
+ } else if ([...scan.values.keys()].some((key) => key.startsWith(`${entry.table}.`))) {
285
+ // The table only exists through dotted keys; a [table] header would redefine it.
286
+ rootLines.push(`${entry.table}.${line}`);
287
+ } else {
288
+ if (!newTables.has(entry.table)) newTables.set(entry.table, []);
289
+ newTables.get(entry.table).push(line);
290
+ }
291
+ added.push(describeTomlEntry(entry));
292
+ }
293
+
294
+ if (!added.length) return { status: 'unchanged', body: existingText, added, kept, conflicts };
295
+
296
+ const eol = existingText.includes('\r\n') ? '\r\n' : '\n';
297
+ const lines = [...scan.lines];
298
+ const inserts = [];
299
+ tableLines.forEach((items, table) => {
300
+ inserts.push({ index: scan.tables.get(table).lastIndex + 1, lines: items });
301
+ });
302
+ if (rootLines.length) {
303
+ const index = scan.root.lastIndex >= 0 ? scan.root.lastIndex + 1 : (scan.firstHeaderIndex >= 0 ? 0 : lines.length);
304
+ const spacer = scan.firstHeaderIndex >= index && String(lines[index] || '').trim() ? [''] : [];
305
+ inserts.push({ index, lines: ['# Added by OSuite', ...rootLines, ...spacer] });
306
+ }
307
+ inserts.sort((a, b) => b.index - a.index).forEach(({ index, lines: items }) => lines.splice(index, 0, ...items));
308
+
309
+ let body = lines.join(eol);
310
+ if (newTables.size) {
311
+ body = body.replace(/\s*$/, '');
312
+ newTables.forEach((items, table) => {
313
+ body += `${eol}${eol}# Added by OSuite${eol}[${table}]${eol}${items.join(eol)}`;
314
+ });
315
+ }
316
+ if (!body.endsWith(eol)) body += eol;
317
+ return { status: 'merged', body, added, kept, conflicts };
318
+ }
319
+
320
+ // --- Install ---------------------------------------------------------------
321
+
322
+ function isInside(root, target) {
323
+ const relative = path.relative(root, target);
324
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
325
+ }
326
+
327
+ export function resolveProjectPath(projectRoot, relativePath) {
328
+ const root = path.resolve(projectRoot);
329
+ const absolute = path.resolve(root, String(relativePath || '').replace(/^\/+/, ''));
330
+ if (!isInside(root, absolute)) {
331
+ throw new Error(`Refusing to write outside the project root: ${relativePath}`);
332
+ }
333
+
334
+ const realRoot = fs.realpathSync(root);
335
+ const parts = path.relative(root, absolute).split(path.sep).filter(Boolean);
336
+ let resolved = realRoot;
337
+ for (let index = 0; index < parts.length; index += 1) {
338
+ const next = path.join(resolved, parts[index]);
339
+ let stat;
340
+ try {
341
+ stat = fs.lstatSync(next);
342
+ } catch (error) {
343
+ if (error.code === 'ENOENT') return path.join(next, ...parts.slice(index + 1));
344
+ throw error;
345
+ }
346
+ // Check each existing parent, not just the leaf. lstat also catches dangling
347
+ // links, which existsSync would mistake for safe new files.
348
+ try {
349
+ resolved = fs.realpathSync(next);
350
+ } catch (error) {
351
+ if (stat.isSymbolicLink()) throw new Error(`Cannot resolve project symlink safely: ${relativePath}`);
352
+ throw error;
353
+ }
354
+ if (!isInside(realRoot, resolved)) {
355
+ throw new Error(`Refusing to write outside the project root through a symlink: ${relativePath}`);
356
+ }
357
+ }
358
+ return resolved;
359
+ }
360
+
361
+ function readIfExists(absolute) {
362
+ return fs.existsSync(absolute) ? fs.readFileSync(absolute, 'utf8') : null;
363
+ }
364
+
365
+ function writeFile(absolute, body) {
366
+ fs.mkdirSync(path.dirname(absolute), { recursive: true });
367
+ fs.writeFileSync(absolute, String(body ?? ''));
368
+ }
369
+
370
+ /**
371
+ * Install one bootstrap file. Settings files are merged; OSuite's own files
372
+ * are created, left alone when identical, and replaced only with --force.
373
+ */
374
+ export function installProjectFile(projectRoot, relativePath, body, { force = false } = {}) {
375
+ const absolute = resolveProjectPath(projectRoot, relativePath);
376
+ const existing = readIfExists(absolute);
377
+ const kind = MERGED_FILES[relativePath];
378
+
379
+ if (kind) {
380
+ let merge;
381
+ try {
382
+ merge = kind === 'json' ? mergeHookSettings(existing, String(body ?? '')) : mergeTomlPartial(existing, String(body ?? ''));
383
+ } catch (error) {
384
+ merge = { status: 'error', error: `OSuite template could not be read (${error.message})` };
385
+ }
386
+ if (merge.status === 'created' || merge.status === 'merged') writeFile(absolute, merge.body);
387
+ const { body: _body, ...report } = merge;
388
+ return { relativePath, kind, ...report };
389
+ }
390
+
391
+ if (existing === null) {
392
+ writeFile(absolute, body);
393
+ return { relativePath, status: 'created' };
394
+ }
395
+ if (existing === String(body ?? '')) return { relativePath, status: 'unchanged' };
396
+ if (force) {
397
+ writeFile(absolute, body);
398
+ return { relativePath, status: 'replaced' };
399
+ }
400
+ return { relativePath, status: 'kept' };
401
+ }
402
+
403
+ export function installBlockers(results = []) {
404
+ return results.flatMap((result) => [
405
+ ...(result.status === 'error' ? [`${result.relativePath}: ${result.error}`] : []),
406
+ ...(result.conflicts || []).map((conflict) => `${result.relativePath}: ${conflict}`),
407
+ ]);
408
+ }
409
+
410
+ /** Lines that say exactly what an install changed, for the terminal. */
411
+ export function describeInstallResult(result) {
412
+ const lines = [];
413
+ const name = result.relativePath;
414
+ if (result.status === 'error') {
415
+ lines.push(`failed ${name}: ${result.error}. Nothing was changed; fix the file and run this again.`);
416
+ return lines;
417
+ }
418
+ if (result.kind === 'json') {
419
+ if (result.status === 'unchanged') lines.push(`unchanged ${name} (OSuite hooks already there)`);
420
+ else lines.push(`${result.status === 'created' ? 'created' : 'merged '} ${name}`);
421
+ if (result.status !== 'unchanged') {
422
+ result.added.forEach((hook) => lines.push(` + ${hook.event} ${hook.matcher || '*'} → ${hook.command}`));
423
+ }
424
+ if (result.status === 'merged') {
425
+ const others = result.keptKeys.length ? ` and your other settings (${result.keptKeys.join(', ')})` : '';
426
+ lines.push(` kept ${result.keptHooks} existing hook${result.keptHooks === 1 ? '' : 's'}${others}`);
427
+ }
428
+ (result.conflicts || []).forEach((conflict) => lines.push(` ! ${conflict}`));
429
+ return lines;
430
+ }
431
+ if (result.kind === 'toml') {
432
+ if (result.status === 'unchanged') lines.push(`unchanged ${name} (OSuite settings already there)`);
433
+ else lines.push(`${result.status === 'created' ? 'created' : 'merged '} ${name}`);
434
+ if (result.status !== 'unchanged') result.added.forEach((entry) => lines.push(` + ${entry}`));
435
+ result.kept.forEach((entry) => lines.push(` kept your ${entry.key} (OSuite suggests ${entry.suggested})`));
436
+ result.conflicts.forEach((conflict) => lines.push(` ! ${conflict}`));
437
+ return lines;
438
+ }
439
+ const labels = {
440
+ created: `created ${name}`,
441
+ unchanged: `unchanged ${name}`,
442
+ replaced: `replaced ${name}`,
443
+ kept: `kept ${name} (differs from this OSuite version; use --force to replace)`,
444
+ };
445
+ lines.push(labels[result.status] || `${result.status} ${name}`);
446
+ return lines;
447
+ }
448
+
449
+ // --- Verify ----------------------------------------------------------------
450
+
451
+ function readJson(absolute) {
452
+ return JSON.parse(fs.readFileSync(absolute, 'utf8'));
453
+ }
454
+
455
+ function findCommand(settings, event, script) {
456
+ const groups = Array.isArray(settings?.hooks?.[event]) ? settings.hooks[event] : [];
457
+ return groups
458
+ .flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []))
459
+ .find((hook) => typeof hook?.command === 'string' && hookScriptName(hook.command) === script) || null;
460
+ }
461
+
462
+ /** OSuite hooks registered in this project, with anything that stops them from running. */
463
+ export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIME_HOOKS)) {
464
+ return runtimes.flatMap((runtime) => {
465
+ const spec = RUNTIME_HOOKS[runtime];
466
+ if (!spec) return [];
467
+ const problems = [];
468
+ const disabledReasons = [];
469
+ let pretool = null;
470
+ let posttool = null;
471
+ spec.settings.forEach((settingsPath) => {
472
+ const absolute = path.join(projectRoot, settingsPath);
473
+ if (!fs.existsSync(absolute)) return;
474
+ let settings;
475
+ try {
476
+ settings = readJson(absolute);
477
+ } catch {
478
+ problems.push(`${settingsPath} is not valid JSON, so ${spec.label} cannot load its hooks`);
479
+ return;
480
+ }
481
+ disabledHookSettings(settings).forEach((reason) => disabledReasons.push(`${settingsPath}: ${reason}`));
482
+ const pre = findCommand(settings, 'PreToolUse', 'osuite_pretool.py');
483
+ const post = findCommand(settings, 'PostToolUse', 'osuite_posttool.py');
484
+ if (pre && !pretool) pretool = { settingsPath, command: pre.command };
485
+ if (post && !posttool) posttool = { settingsPath, command: post.command };
486
+ });
487
+
488
+ const scriptPath = `${spec.dir}/hooks/osuite_pretool.py`;
489
+ const scriptPresent = fs.existsSync(path.join(projectRoot, scriptPath));
490
+ if (!pretool && !scriptPresent && !problems.length) return [];
491
+ if (!pretool) {
492
+ problems.push(`no PreToolUse hook in ${spec.settings.join(' or ')} runs osuite_pretool.py`);
493
+ }
494
+ if (spec.config) {
495
+ const config = readIfExists(path.join(projectRoot, spec.config));
496
+ if (config !== null) {
497
+ const values = scanToml(config).values;
498
+ HOOK_FLAGS.forEach((flag) => {
499
+ if (values.get(flag) === 'false') disabledReasons.push(`${spec.config} turns hooks off (${flag} = false)`);
500
+ });
501
+ }
502
+ }
503
+ return [{ runtime, label: spec.label, installDir: spec.dir, pretool, posttool,
504
+ hostEnabled: disabledReasons.length === 0, disabledReasons, problems: [...problems, ...disabledReasons] }];
505
+ });
506
+ }
507
+
508
+ export function parseDotenv(body) {
509
+ const values = {};
510
+ String(body || '').split(/\r?\n/).forEach((line) => {
511
+ const trimmed = line.trim();
512
+ if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) return;
513
+ const [rawKey, ...rawValue] = trimmed.split('=');
514
+ const key = rawKey.trim();
515
+ let value = rawValue.join('=').trim().replace(/^['"]|['"]$/g, '');
516
+ if (value.includes(' #')) value = value.slice(0, value.indexOf(' #')).trim();
517
+ if (key) values[key] = value;
518
+ });
519
+ return values;
520
+ }
521
+
522
+ /** The credentials the installed hook will use: shell values first, then its own .env. */
523
+ export function hookCredentials(projectRoot, installation, shellEnv = process.env) {
524
+ const dotenv = parseDotenv(readIfExists(path.join(projectRoot, installation.installDir, '.env')));
525
+ const env = { ...dotenv };
526
+ Object.entries(shellEnv || {}).forEach(([key, value]) => {
527
+ if (value !== undefined) env[key] = value;
528
+ });
529
+ return {
530
+ baseUrl: String(env.OSUITE_BASE_URL || env.DASHCLAW_BASE_URL || '').replace(/\/$/, ''),
531
+ apiKey: String(env.OSUITE_API_KEY || env.DASHCLAW_API_KEY || ''),
532
+ envFile: `${installation.installDir}/.env`,
533
+ hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || 'enforce'),
534
+ };
535
+ }
536
+
537
+ function runShell(command, { cwd, env, input, timeoutMs }) {
538
+ return new Promise((resolve) => {
539
+ let stdout = '';
540
+ let stderr = '';
541
+ let settled = false;
542
+ const child = spawn(command, { cwd, env, shell: true, stdio: ['pipe', 'pipe', 'pipe'] });
543
+ const finish = (result) => {
544
+ if (settled) return;
545
+ settled = true;
546
+ clearTimeout(timer);
547
+ resolve({ stdout, stderr, ...result });
548
+ };
549
+ const timer = setTimeout(() => {
550
+ child.kill('SIGKILL');
551
+ finish({ code: null, timedOut: true });
552
+ }, timeoutMs);
553
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
554
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
555
+ child.on('error', (error) => finish({ code: null, error }));
556
+ child.on('close', (code) => finish({ code }));
557
+ child.stdin.on('error', () => {});
558
+ child.stdin.end(input);
559
+ });
560
+ }
561
+
562
+ function hookMessages(stdout) {
563
+ return String(stdout || '').split(/\r?\n/).flatMap((line) => {
564
+ try {
565
+ const parsed = JSON.parse(line);
566
+ return typeof parsed?.systemMessage === 'string' ? [parsed.systemMessage] : [];
567
+ } catch {
568
+ return [];
569
+ }
570
+ });
571
+ }
572
+
573
+ function hookWarnings(stdout, stderr) {
574
+ return [...new Set([
575
+ ...hookMessages(stdout),
576
+ ...String(stderr || '').split(/\r?\n/).map((line) => line.trim())
577
+ .filter((line) => /\bWarning:|Not governed|\[observe\]|Guard unavailable/i.test(line)),
578
+ ])];
579
+ }
580
+
581
+ function lastLine(text) {
582
+ return String(text || '').trim().split(/\r?\n/).filter(Boolean).pop() || '';
583
+ }
584
+
585
+ async function fetchSessionEvents(fetchImpl, { baseUrl, apiKey, sessionId }) {
586
+ try {
587
+ const response = await fetchImpl(`${baseUrl}/api/runtime-sessions/${encodeURIComponent(sessionId)}/events?limit=50`, {
588
+ headers: { 'x-api-key': apiKey },
589
+ });
590
+ const payload = await response.json().catch(() => ({}));
591
+ return { status: response.status, items: Array.isArray(payload?.items) ? payload.items : [] };
592
+ } catch (error) {
593
+ return { status: 0, items: [], error: error.message };
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Directly probe the registered hook with an inert Bash call. Configuration,
599
+ * telemetry, and policy outcomes are separate checks; this is not a host launch.
600
+ */
601
+ export async function runHookCheck({
602
+ projectRoot,
603
+ installation,
604
+ shellEnv = process.env,
605
+ fetchImpl = globalThis.fetch,
606
+ timeoutMs = 30000,
607
+ } = {}) {
608
+ const steps = [];
609
+ const warnings = [];
610
+ const state = { configured: false, hostEnabled: false, connected: false, telemetry: false, governed: false };
611
+ let sessionId;
612
+ const result = (ok) => ({ ok, ...state, steps, runtime: installation?.runtime, sessionId, warnings });
613
+ const fail = (label, detail) => {
614
+ steps.push({ label, ok: false, detail });
615
+ return result(false);
616
+ };
617
+
618
+ if (!installation?.pretool) return fail('Hook installed', installation?.problems?.join('; ') || 'no OSuite hook found');
619
+ const disabledReasons = installation.disabledReasons || [];
620
+ const problems = (installation.problems || []).filter((problem) => !disabledReasons.includes(problem));
621
+ if (problems.length) return fail('Hook installed', problems.join('; '));
622
+ state.configured = true;
623
+ steps.push({ label: 'Hook installed', ok: true, detail: `${installation.pretool.settingsPath} runs ${installation.pretool.command}` });
624
+ if (installation.hostEnabled === false || disabledReasons.length) {
625
+ return fail('Host hooks enabled', disabledReasons.join('; ') || 'hooks are disabled in project settings');
626
+ }
627
+ state.hostEnabled = true;
628
+ steps.push({ label: 'Host hooks enabled', ok: true, detail: 'project settings permit hooks; actual host invocation is not verified by this direct probe' });
629
+
630
+ const credentials = hookCredentials(projectRoot, installation, shellEnv);
631
+ if (!credentials.baseUrl || !credentials.apiKey) {
632
+ return fail('Hook credentials', `OSUITE_BASE_URL and OSUITE_API_KEY are not set in ${credentials.envFile} or the shell; governance cannot be verified`);
633
+ }
634
+ steps.push({ label: 'Hook credentials', ok: true, detail: `base URL and API key configured for ${credentials.baseUrl}` });
635
+
636
+ const id = crypto.randomBytes(4).toString('hex');
637
+ sessionId = `osuite-doctor-${id}`;
638
+ const toolUseId = `osuite_doctor_${id}`;
639
+ const sample = {
640
+ session_id: sessionId,
641
+ cwd: projectRoot,
642
+ hook_event_name: 'PreToolUse',
643
+ tool_name: 'Bash',
644
+ tool_input: { command: DOCTOR_COMMAND, description: 'OSuite doctor hook check' },
645
+ tool_use_id: toolUseId,
646
+ };
647
+ // OSUITE_HOOK_CHECK tells the hook and OSuite this is a probe: a call that
648
+ // would need approval is reported, not sent to reviewers.
649
+ const env = { ...shellEnv, OSUITE_APPROVAL_WAIT_SECONDS: '3', OSUITE_HOOK_CHECK: '1' };
650
+ const run = await runShell(installation.pretool.command, {
651
+ cwd: projectRoot, env, input: JSON.stringify(sample), timeoutMs,
652
+ });
653
+ const messages = hookMessages(run.stdout);
654
+ warnings.push(...hookWarnings(run.stdout, run.stderr));
655
+ const said = messages[0] || lastLine(run.stderr);
656
+
657
+ if (run.timedOut) return fail('Hook test', `the hook did not finish within ${Math.round(timeoutMs / 1000)}s`);
658
+ if (run.code === 127 && /^python3?\b/.test(installation.pretool.command)) {
659
+ return fail('Hook test', 'python3 was not found. The hook runs with Python 3.8 or newer: install it (macOS: xcode-select --install), then run osuite doctor');
660
+ }
661
+ if (run.error || (run.code !== 0 && run.code !== 2)) {
662
+ return fail('Hook test', `the hook command failed (${run.error ? run.error.message : `exit ${run.code}`})${said ? `: ${said}` : ''}`);
663
+ }
664
+ steps.push({
665
+ ok: true,
666
+ label: 'Hook test',
667
+ detail: `sample Bash call (${DOCTOR_COMMAND}) ${run.code === 0 ? 'allowed' : 'stopped'} by the hook${run.code === 2 && said ? `: ${said}` : ''}`,
668
+ });
669
+
670
+ let lookup = await fetchSessionEvents(fetchImpl, { ...credentials, sessionId });
671
+ if (!lookup.items.some((event) => event?.tool_use_id === toolUseId) && lookup.status !== 401 && lookup.status !== 403) {
672
+ await new Promise((resolve) => setTimeout(resolve, 500));
673
+ lookup = await fetchSessionEvents(fetchImpl, { ...credentials, sessionId });
674
+ }
675
+ const seen = lookup.items.filter((event) => event?.tool_use_id === toolUseId && event?.runtime_session_id === sessionId);
676
+
677
+ if (installation.posttool && run.code === 0) {
678
+ // Closes the sample action in the ledger; not part of the verdict.
679
+ await runShell(installation.posttool.command, {
680
+ cwd: projectRoot,
681
+ env,
682
+ timeoutMs,
683
+ input: JSON.stringify({
684
+ ...sample,
685
+ hook_event_name: 'PostToolUse',
686
+ tool_response: { stdout: 'OSuite doctor hook check', stderr: '', interrupted: false, exit_code: 0 },
687
+ }),
688
+ });
689
+ }
690
+
691
+ state.connected = lookup.status >= 200 && lookup.status < 300;
692
+ if (state.connected) steps.push({ ok: true, label: 'Studio connection', detail: `runtime event endpoint answered HTTP ${lookup.status}` });
693
+ if (!state.connected || !seen.length) {
694
+ const reason = lookup.status === 401 || lookup.status === 403
695
+ ? `OSuite rejected the API key in ${credentials.envFile} (HTTP ${lookup.status})`
696
+ : said || (lookup.error ? `could not reach ${credentials.baseUrl} (${lookup.error})` : `no runtime event for session ${sessionId}`);
697
+ return fail(state.connected ? 'Studio event' : 'Studio connection', `the sample call did not reach OSuite: ${reason}`);
698
+ }
699
+ state.telemetry = true;
700
+ steps.push({
701
+ ok: true,
702
+ label: 'Studio event',
703
+ detail: `${[...new Set(seen.map((event) => event.event_type))].join(', ')} reached OSuite (session ${sessionId})`,
704
+ });
705
+
706
+ const observing = credentials.hookMode === 'observe' || seen.some((event) => (
707
+ event.payload?.hook_mode === 'observe' || event.payload?.observe_only === true
708
+ || String(event.payload?.decision || '').startsWith('observe_')
709
+ ));
710
+ if (observing) return fail('Governance', 'Not governed: observation-only mode records telemetry but does not enforce policy; the mode was not changed');
711
+ const unavailable = seen.some((event) => ['guard_unavailable', 'guard_unavailable_blocked'].includes(event.payload?.decision));
712
+ if (unavailable) return fail('Governance', `Not governed: guard unavailable; the hook ${run.code === 0 ? 'failed open' : 'failed closed'}, and telemetry alone does not verify governance`);
713
+ const ungoverned = warnings.find((warning) => /Not governed/i.test(warning));
714
+ if (ungoverned) return fail('Governance', ungoverned);
715
+
716
+ const outcome = seen.find((event) => {
717
+ const decision = event.payload?.decision;
718
+ if (run.code === 0) {
719
+ return event.event_type === 'tool_allowed' && typeof event.action_id === 'string' && event.action_id.trim()
720
+ && ['allow', 'warn', 'approved_by_reviewer'].includes(decision);
721
+ }
722
+ if (event.event_type === 'install_check_policy_result') {
723
+ return run.code === 2 && event.payload?.install_check === true
724
+ && event.payload?.approval_state === 'not_requested'
725
+ && ['require_approval', 'require_dual_approval'].includes(decision);
726
+ }
727
+ if (event.event_type === 'tool_blocked' && decision === 'block') {
728
+ return event.payload?.reason !== 'action_creation_not_authorized'
729
+ && !String(event.payload?.reason || '').startsWith('Unsupported guard decision:');
730
+ }
731
+ return event.event_type === 'tool_requires_approval' && typeof event.action_id === 'string' && event.action_id.trim()
732
+ && ['require_approval', 'require_dual_approval'].includes(decision);
733
+ });
734
+ if (!outcome) return fail('Governance', 'Not verified: telemetry arrived, but no matching enforced policy outcome was recorded for the sample call');
735
+ state.governed = true;
736
+ const detail = outcome.event_type === 'install_check_policy_result'
737
+ ? `verified policy would require ${outcome.payload.decision === 'require_dual_approval' ? 'two-person approval' : 'approval'}; the probe was not executed and no request was sent to reviewers`
738
+ : `verified ${outcome.payload.decision} policy outcome for the direct hook probe; the sample command was not executed`;
739
+ steps.push({ ok: true, label: 'Governance', detail });
740
+ return result(true);
741
+ }
package/reviewSurface.js CHANGED
@@ -133,8 +133,16 @@ export function buildReviewSurface(action = {}, options = {}) {
133
133
  ]
134
134
  : [];
135
135
 
136
- const replayUrl = options.baseUrl ? `${String(options.baseUrl).replace(/\/$/, '')}/replay/${actionId}` : null;
137
- const footer = replayUrl ? ['', `${colorize('Replay', BOLD, color)} ${replayUrl}`] : [];
136
+ const baseUrl = options.baseUrl ? String(options.baseUrl).replace(/\/$/, '') : null;
137
+ const replayUrl = baseUrl ? `${baseUrl}/replay/${actionId}` : null;
138
+ // A request still waiting is decided by a person in Studio, so point there.
139
+ const reviewUrl = baseUrl && action.status === 'pending_approval'
140
+ ? `${baseUrl}/approvals?action=${encodeURIComponent(actionId)}`
141
+ : null;
142
+ const footer = [
143
+ ...(reviewUrl ? ['', `${colorize('Review', BOLD, color)} ${reviewUrl}`] : []),
144
+ ...(replayUrl ? [reviewUrl ? null : '', `${colorize('Replay', BOLD, color)} ${replayUrl}`].filter((line) => line !== null) : []),
145
+ ];
138
146
 
139
147
  return [
140
148
  colorize(title, `${BOLD}${CYAN}`, color),