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.
package/GOVERNED_TOOLS.md CHANGED
@@ -85,6 +85,103 @@ the mapping, not that the mapping is semantically complete. Studio still owns
85
85
  the allow/hold/deny decision. Do not put secrets in `input_summary`: that bounded
86
86
  description is sent to Studio even though full native arguments stay local.
87
87
 
88
+ For a USD tool that takes integer cents, configure the binding with
89
+ `amount: { currency: 'USD', unit: 'minor', path: ['amount_cents'] }`. `path`
90
+ selects a field in the original JSON arguments and can include nested keys.
91
+ The wrapper signs the integer cents, field path, mapping revision and native
92
+ input digest in both governance requests. Studio uses this evidence for
93
+ `amount_usd` threshold policies. `input_summary` can display the amount. If it
94
+ also specifies `amount_cents`, `amount_usd` or `currency`, the values must agree
95
+ with the mapping. Tool variants without a positive amount can run only when
96
+ their policies permit an action without amount evidence. Whole-CAD refunds
97
+ continue to use the exact `refund.create` mapping.
98
+
99
+ Missing, conflicting, unsupported, and unsigned amount evidence has a dedicated
100
+ `NATIVE_AMOUNT_*` code and a configuration hint. Studio shows these refusals in
101
+ **Policies → Rules → Amount rule errors**. The wrapper refuses a call with an
102
+ invalid binding before it can start the native tool. A JavaScript binding that
103
+ cannot be safely copied as JSON produces its configuration error locally.
104
+
105
+ ### Limit The Cumulative Amount Per Request
106
+
107
+ Add `businessKey: { path: ['request_id'] }` to each related USD tool binding.
108
+ Use the same stable identifier in the native arguments across agents and
109
+ tools for a single business request. Nested paths work when they end in the
110
+ same field name. The signed evidence contains the field path and a digest of
111
+ the value. Supply both bindings before recording the first related action.
112
+
113
+ Create an `amount_threshold` policy through `POST /api/policies` with the
114
+ following JSON encoded as the `rules` string.
115
+
116
+ ```json
117
+ {
118
+ "action_types": ["api"],
119
+ "max_amount_usd": 500,
120
+ "action": "require_approval",
121
+ "on_missing": "block",
122
+ "aggregate": { "key": "request_id", "on_denied": "block" }
123
+ }
124
+ ```
125
+
126
+ Studio reserves an action once and includes completed, in-flight, uncertain
127
+ and pending amounts for the same workspace and business key. A confirmed
128
+ denial or expiry releases the amount. A reservation whose action record has
129
+ been deleted still counts conservatively. Set `on_denied` to `require_approval`
130
+ to route later actions for that key through a new review, or omit it to apply
131
+ only the cumulative cap. Set `action` to `block` for a hard cap. This policy
132
+ requires the direct PostgreSQL connection (`DASHCLAW_DB_DRIVER=postgres`) and
133
+ the current Studio schema. Calls from before the business key was configured
134
+ have no key to associate with a reservation.
135
+
136
+ ### Reconcile With The Resource Owner
137
+
138
+ Bind `ownerReceipt: { resourceId, publicKey, query }` to the tool. `publicKey`
139
+ is the resource owner's Ed25519 SPKI DER encoded as base64. A workspace admin
140
+ pins the same key for `resourceId` in the `NATIVE_RESOURCE_OWNERS` setting,
141
+ an array of `{ resource_id, public_key }` entries. The owner should keep its
142
+ signing key separate from OSuite and the executing agent.
143
+
144
+ After a dropped reply or restart, call `tools.reconcile(operationId, params)`
145
+ with the same operation and arguments. `query` receives `operationId`, a
146
+ timeout signal and the signed receipt scope (`org_id`, `action_id`,
147
+ `input_digest`, `resource_id`, `key_id`). It performs the resource owner's
148
+ authenticated lookup and returns `{ claims, signature }`. The claims contain
149
+ that scope, `schema_version: 'osuite.native_owner_receipt.v1'`, `receipt_id`,
150
+ UTC `observed_at`, `complete: true`, `final: true` and `outcome` (`committed`
151
+ or `absent`). The signature is base64 Ed25519 over the schema version, a newline
152
+ and the canonical JSON claims. An `absent` receipt requires a complete scoped
153
+ read and a fence against a later submission for that action. The SDK returns
154
+ `unknown` while the receipt is incomplete, untrusted or unavailable. The
155
+ journal continues to prevent a second execution.
156
+
157
+ Studio's `GET /api/proof/export?format=native&action_id=…` returns a signed
158
+ native proof. Use `from` and `to` in UTC in place of `action_id` for a cohort
159
+ and `format=native-checkpoint` for its independently obtained checkpoint.
160
+ The window includes registered, verified native actions by creation time.
161
+ Studio reads `OSUITE_NATIVE_PROOF_SIGNING_KEY` and
162
+ `OSUITE_NATIVE_CHECKPOINT_SIGNING_KEY` as separately provisioned base64
163
+ Ed25519 PKCS8 DER keys. Give the reviewer the public keys through a trusted
164
+ channel along with the pinned owner keys. `verifyNativeProofCohort` from
165
+ `osuite/native-proof` verifies the signed records and checkpoint offline and
166
+ counts committed, absent and unknown outcomes.
167
+
168
+ ### Delegated Calls
169
+
170
+ Set `delegation: async intent => issuer.authorize(intent)` on a native tool
171
+ binding. The callback receives the frozen tool parameters, action and input
172
+ commitments and runtime scope. An authenticated workspace issuer supplies an
173
+ `osuite.business_authority.v2` assertion bound to the initiating user, tenant,
174
+ planner, executing agent, executor credential, resource principal and grant.
175
+ Reuse that assertion when resuming the same held operation.
176
+
177
+ Studio checks the issuer and current grant on both admission requests. Each
178
+ issuer in `BUSINESS_AUTHORITY_ISSUERS` can list `grants` with its active grant
179
+ IDs, expiry, authorized principals, action scope and eligible reviewer roles.
180
+ List the native agent IDs that require v2 assertions in
181
+ `NATIVE_DELEGATION_REQUIRED_FOR`. For offline verification of delegated proofs,
182
+ include the trusted issuer public keys in `roots.issuers` as entries with
183
+ `id`, `org_id` and `public_key`.
184
+
88
185
  Use a separately enrolled SDK/MCP identity with a current signing key. A Hook
89
186
  credential is not interchangeable with an SDK credential. The new `sdk`/`mcp`
90
187
  posture endpoint must be deployed server-side. Older servers fail explicitly;
package/README.md CHANGED
@@ -23,6 +23,29 @@ npm install osuite
23
23
 
24
24
  ### Connect And Verify
25
25
 
26
+ With Studio's acknowledged terminal enrollment enabled, start from your project directory.
27
+
28
+ ```bash
29
+ osuite login
30
+ osuite test
31
+ ```
32
+
33
+ Use `osuite login --no-browser` to enter the displayed code in Studio from another device.
34
+ Run the same command after a timeout or interruption to resume. Project markers
35
+ preselect Claude Code and Codex. Use `--runtimes claude,codex` to specify the
36
+ hosts directly, or `--runtimes sdk` for an SDK-only project. For piped runs,
37
+ `--yes` applies the previewed changes and `--test` records the initial test.
38
+ Codex still requires you to review project Hook trust in `/hooks`.
39
+
40
+ The project SDK can load its signed credentials from `.osuite/terminal/.env`.
41
+ Follow [Native Tool Compatibility](GOVERNED_TOOLS.md) to wrap your tool callback
42
+ and verify the application path. `osuite test` records a policy evaluation for
43
+ a fixed test action without running the callback.
44
+
45
+ For an isolated sample, start `npm run demo -- --serve` in a Studio checkout
46
+ and run `osuite demo` from your terminal. Demo data belongs to that loopback
47
+ Studio process.
48
+
26
49
  For a checked-out SDK source tree, run from the project you want to connect:
27
50
 
28
51
  ```bash
package/cli.js CHANGED
@@ -10,10 +10,11 @@ import { runTryFlow } from './tryFlow.js';
10
10
  import { runDoctorWithMeasurement } from './activationMetrics.js';
11
11
  import { auditCodexTrust, codexExecArguments, inspectCodexTrust } from './codexTrust.mjs';
12
12
  import { runCodexExec } from './codexExec.mjs';
13
+ import { onboardingWelcome, runOnboardingLogin, runOnboardingTest, showOnboardingError } from './onboardingCli.js';
13
14
  import {
14
15
  credentialDigest, getInstallationIdentity, migrateMcpInstallation, parseInstallationIdentity,
15
16
  readInstallationBundle, readInstallationIdentity, readMcpMigration,
16
- MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH,
17
+ MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, TERMINAL_ENV_PATH,
17
18
  } from './installationIdentity.js';
18
19
  import {
19
20
  CREDENTIAL_PATHS, acquireCredentialLock, inspectCredentialFile,
@@ -59,7 +60,7 @@ const GIT_OBSERVATION_RISKS = {
59
60
  const PUBLIC_FILE_HOST_HINTS = ['transfer.sh', 'file.io', 'tmpfiles.org', '0x0.st', 'ufile.io', 'gofile.io', 'wetransfer.com'];
60
61
  const SECURITY_CONTROL_WEAKENING_RE = /(\bspctl\b[\s\S]*(--master-disable|--global-disable|--disable)|\bcsrutil\b[\s\S]*\bdisable\b|Set-MpPreference[\s\S]*Disable(?:RealtimeMonitoring|BehaviorMonitoring|IOAVProtection)[\s\S]*(true|\$true|1)|netsh\s+advfirewall\s+set\s+allprofiles\s+state\s+off|\bsystemctl\b[\s\S]*\b(stop|disable|mask)\b[\s\S]*(auditd|falcon|crowdstrike|osquery|defender|mdatp|sentinel|carbonblack|firewalld|ufw)|\bufw\b[\s\S]*\bdisable\b)/i;
61
62
  const DEFAULT_BASE_URL = 'https://studio.osuite.ai';
62
- const CLI_CREDENTIAL_PATHS = [...CREDENTIAL_PATHS, MCP_ENV_PATH];
63
+ const CLI_CREDENTIAL_PATHS = [...CREDENTIAL_PATHS, MCP_ENV_PATH, TERMINAL_ENV_PATH];
63
64
  const PROJECT_BOOTSTRAPS = {
64
65
  codex: {
65
66
  label: 'Codex hook runtime',
@@ -112,7 +113,7 @@ const RUNTIME_COVERAGE_TIERS = [
112
113
  ];
113
114
 
114
115
  function useColor() {
115
- return !process.env.NO_COLOR && process.stdout.isTTY !== false;
116
+ return !Object.hasOwn(process.env, 'NO_COLOR') && process.stdout.isTTY === true;
116
117
  }
117
118
 
118
119
  function c(value, color) {
@@ -139,7 +140,7 @@ function parseEnvBody(body = '') {
139
140
 
140
141
  function loadProjectEnvironment() {
141
142
  // Enrollment selects one whole runtime bundle, never a merged global env.
142
- if (['connect', 'codex'].includes(process.argv[2]) || CONTROLLED_TRANSFER_CLI || NATIVE_RUNTIME_DOCTOR) return;
143
+ if (!process.argv[2] || ['connect', 'codex', 'login', 'test', 'demo'].includes(process.argv[2]) || CONTROLLED_TRANSFER_CLI || NATIVE_RUNTIME_DOCTOR) return;
143
144
  for (const relativePath of [...CLI_CREDENTIAL_PATHS, '.env']) {
144
145
  let body;
145
146
  try { body = readCredentialFile(process.cwd(), relativePath, { maxBytes: 65536 }); }
@@ -151,7 +152,7 @@ function loadProjectEnvironment() {
151
152
  }
152
153
 
153
154
  function parseArgs(argv) {
154
- const [command = 'help', ...rest] = argv;
155
+ const [command = '', ...rest] = argv;
155
156
  const args = { _: [] };
156
157
  for (let index = 0; index < rest.length; index += 1) {
157
158
  const token = rest[index];
@@ -375,12 +376,12 @@ function sleep(ms) {
375
376
  return new Promise((resolve) => setTimeout(resolve, ms));
376
377
  }
377
378
 
378
- async function postJson(url, body) {
379
+ async function postJson(url, body, timeoutMs = 15000) {
379
380
  const response = await fetch(url, {
380
381
  method: 'POST',
381
382
  headers: { 'content-type': 'application/json' },
382
383
  body: JSON.stringify(body || {}),
383
- signal: AbortSignal.timeout(15000),
384
+ signal: AbortSignal.timeout(timeoutMs),
384
385
  redirect: 'error',
385
386
  });
386
387
  const text = await response.text();
@@ -395,7 +396,7 @@ async function postJson(url, body) {
395
396
  return { response, payload };
396
397
  }
397
398
 
398
- async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId }) {
399
+ async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey, installationId, onboarding, sample, requests, expectedOrgId }) {
399
400
  const { response, payload } = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/start`, {
400
401
  runtime,
401
402
  agent_id: agentId,
@@ -404,8 +405,17 @@ async function startDeviceConnect({ baseUrl, runtime, agentId, previousKey, inst
404
405
  protocol_version: 2,
405
406
  client_version: pkg.version,
406
407
  ...(previousKey ? { previous_key: previousKey } : {}),
408
+ ...(onboarding ? { onboarding: true, sample_only: Boolean(sample), runtime_requests: requests || [] } : {}),
409
+ ...(expectedOrgId ? { expected_org_id: expectedOrgId } : {}),
407
410
  });
408
411
  if (!response.ok) {
412
+ if (onboarding) {
413
+ const reasons = {
414
+ DEVICE_CONNECT_V2_DISABLED: 'Studio has not enabled terminal enrollment. Check Setup Status or ask your workspace administrator.',
415
+ LOCAL_DEMO_REQUIRED: 'Use osuite demo with a loopback Studio running in local Demo mode.',
416
+ };
417
+ throw Object.assign(new Error(reasons[payload.code] || `Could not start terminal enrollment (HTTP ${response.status}).`), { publicOnboardingError: true });
418
+ }
409
419
  throw new Error(payload.error || `Unable to start browser handoff: HTTP ${response.status}`);
410
420
  }
411
421
  if (!payload.device_code || !payload.poll_token || !payload.user_code) {
@@ -441,7 +451,7 @@ function openInBrowser(url) {
441
451
  }
442
452
  }
443
453
 
444
- async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs, protocolVersion = 1 }) {
454
+ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, intervalMs, protocolVersion = 1, onboarding = false }) {
445
455
  const deadline = Date.now() + timeoutMs;
446
456
  while (Date.now() <= deadline) {
447
457
  let result;
@@ -449,7 +459,7 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
449
459
  result = await postJson(`${normalizedBaseUrl(baseUrl)}/api/onboarding/device-connect/poll`, {
450
460
  device_code: deviceCode,
451
461
  poll_token: pollToken,
452
- });
462
+ }, onboarding ? Math.max(1, Math.min(15000, deadline - Date.now())) : 15000);
453
463
  } catch (error) {
454
464
  if (protocolVersion !== 2) throw error;
455
465
  await sleep(Math.max(10, intervalMs));
@@ -473,14 +483,19 @@ async function pollDeviceConnect({ baseUrl, deviceCode, pollToken, timeoutMs, in
473
483
  continue;
474
484
  }
475
485
  if (response.status === 410 || payload.status === 'expired') {
476
- const error = new Error('The connect code expired before it was approved. Run osuite connect again for a new code.');
486
+ const error = new Error(onboarding ? 'The device code expired. Run the same command to get a new code.' : 'The connect code expired before it was approved. Run osuite connect again for a new code.');
477
487
  error.code = 'DEVICE_CONNECT_EXPIRED';
488
+ error.publicOnboardingError = onboarding;
478
489
  throw error;
479
490
  }
491
+ if (onboarding && payload.status === 'declined') {
492
+ throw Object.assign(new Error('Studio could not reserve credentials for this runtime. Check the workspace API key limit.'), { code: 'RUNTIME_APPROVAL_FAILED', publicOnboardingError: true });
493
+ }
480
494
  if (response.status === 409 || payload.status === 'consumed') {
481
495
  throw new Error(payload.error || 'Browser handoff was already consumed.');
482
496
  }
483
497
  if (response.status === 404) {
498
+ if (onboarding) throw Object.assign(new Error('Studio could not find the saved handoff. Rerun to request a new device code.'), { code: 'DEVICE_CONNECT_NOT_FOUND', publicOnboardingError: true });
484
499
  throw new Error('Browser handoff was not found. Run osuite connect again.');
485
500
  }
486
501
  throw new Error(payload.error || `Unable to finish browser handoff: HTTP ${response.status}`);
@@ -507,15 +522,16 @@ async function finalizeDeviceConnect(journal, journalPath, validateLive) {
507
522
  throw new Error('Studio did not confirm this saved connection. The recovery journal was left unchanged; retry the same osuite connect command.');
508
523
  }
509
524
  if (!result.payload.active) {
510
- removeCredentialFile(process.cwd(), journalPath);
525
+ if (journalPath) removeCredentialFile(process.cwd(), journalPath);
511
526
  throw new Error('Saved connection was superseded or revoked. It was not installed over the current credentials. Run osuite connect again for a fresh connection.');
512
527
  }
513
528
  return;
514
529
  }
515
530
  if (result && result.response.status < 500) {
516
531
  if (result.response.status === 410) {
517
- removeCredentialFile(process.cwd(), journalPath);
518
- throw new Error('Saved connection expired before finalization. Existing credentials were not changed; run osuite connect again.');
532
+ if (journalPath) removeCredentialFile(process.cwd(), journalPath);
533
+ throw Object.assign(new Error(journalPath ? 'Saved connection expired before finalization. Existing credentials were not changed; run osuite connect again.'
534
+ : 'The saved approval expired before confirmation. Rerun to obtain a new device code.'), { code: 'DEVICE_CONNECT_EXPIRED', publicOnboardingError: !journalPath });
519
535
  }
520
536
  throw new Error(`Connection was not finalized (HTTP ${result.response.status}). The recovery journal is saved; rerun the same osuite connect command to resume.`);
521
537
  }
@@ -765,6 +781,9 @@ function printHelp() {
765
781
  write(c(`OSuite CLI v${pkg.version}`, ANSI.dim));
766
782
  write('');
767
783
  write(c('Useful commands', ANSI.bold));
784
+ write(' osuite login [--no-browser] Connect this project and configure detected runtimes');
785
+ write(' osuite test Record a test decision in the connected workspace');
786
+ write(' osuite demo [--base-url URL] Record a labeled sample in a loopback Demo Studio');
768
787
  write(' osuite doctor Check connection, then run the project hook with a sample call');
769
788
  write(' osuite doctor --runtime sdk|mcp Check only that native connection; never run project hooks');
770
789
  write(' osuite doctor --controlled-transfers Read strict profile capabilities only (Node 24; --runtime sdk|mcp)');
@@ -1868,6 +1887,7 @@ async function main() {
1868
1887
  const { command, args } = parseArgs(process.argv.slice(2));
1869
1888
 
1870
1889
  if (command === 'codex') return managedCodexExec(process.argv.slice(3));
1890
+ if (!command) return onboardingWelcome();
1871
1891
  if (['help', '--help', '-h'].includes(command)) return printHelp();
1872
1892
  if (['version', '--version', '-v'].includes(command)) return write(pkg.version);
1873
1893
  if (CONTROLLED_TRANSFER_CLI) return controlledTransferCommand(command, args);
@@ -1913,6 +1933,25 @@ async function main() {
1913
1933
  if (command === 'external') return external(args);
1914
1934
  if (command === 'connect') return connect(args._[0] || 'auto', args);
1915
1935
  if (command === 'init') return init(args._[0] || 'generic', args);
1936
+ if (['login', 'test', 'demo'].includes(command)) {
1937
+ if (args.help || args._.includes('-h')) return printHelp();
1938
+ const sample = command === 'demo';
1939
+ const deps = { startDeviceConnect, pollDeviceConnect, finalizeDeviceConnect, assertConnectionCredentialScope,
1940
+ parseEnvBody, formatEnvBody, shouldOpenBrowser, openInBrowser, baseUrl: readConfig(SHELL_ENV).baseUrl || DEFAULT_BASE_URL };
1941
+ const onInterrupt = () => {
1942
+ write(`\nSetup paused. Run osuite ${command} again to resume.`);
1943
+ process.exit(130);
1944
+ };
1945
+ process.once('SIGINT', onInterrupt);
1946
+ try {
1947
+ if (command === 'test') await runOnboardingTest(args, deps);
1948
+ else await runOnboardingLogin(args, deps, { sample });
1949
+ } catch (error) {
1950
+ showOnboardingError(error, command);
1951
+ process.exitCode = 1;
1952
+ } finally { process.removeListener('SIGINT', onInterrupt); }
1953
+ return;
1954
+ }
1916
1955
 
1917
1956
  write(`Unknown command: ${command}`);
1918
1957
  write('');
@@ -0,0 +1,44 @@
1
+ export const NATIVE_AMOUNT_SCHEMA = 'osuite.native_amount.v1';
2
+ const reserved = new Set(['__proto__', 'constructor', 'prototype']);
3
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+
5
+ export function validNativePath(path) {
6
+ return Array.isArray(path) && path.length > 0 && path.length <= 8
7
+ && path.every(key => typeof key === 'string' && /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(key) && !reserved.has(key));
8
+ }
9
+
10
+ export function validUsdMapping(mapping) {
11
+ return isObject(mapping) && Object.keys(mapping).length === 3
12
+ && mapping.currency === 'USD' && mapping.unit === 'minor'
13
+ && validNativePath(mapping.path);
14
+ }
15
+
16
+ export function usdMinorToMajor(value) {
17
+ // At this bound the major-unit number still distinguishes adjacent cents.
18
+ return Number.isSafeInteger(value) && value > 0 && value <= 10 ** 15 ? value / 100 : null;
19
+ }
20
+
21
+ export function agreesWithUsdAmount(value, minor) {
22
+ if (!isObject(value)) return true;
23
+ return [['currency', 'USD'], ['amount_cents', minor], ['amount_usd', minor === 0 ? 0 : usdMinorToMajor(minor)]]
24
+ .every(([key, expected]) => !Object.hasOwn(value, key) || value[key] === expected);
25
+ }
26
+
27
+ const mappingHint = "Configure the SDK tool binding with amount: { currency: 'USD', unit: 'minor', path: ['amount_cents'] }, using the path in your native arguments.";
28
+ const keyHint = "Set businessKey: { path: ['request_id'] } in the SDK binding. Use the same stable business identifier for every related payment and match the final path segment to the policy's aggregate.key.";
29
+ const issues = Object.freeze({
30
+ NATIVE_AMOUNT_REQUIRED: ['The applicable amount rule requires a signed USD amount.', mappingHint],
31
+ NATIVE_AMOUNT_UNSUPPORTED: ['The native amount mapping is unsupported.', mappingHint],
32
+ NATIVE_AMOUNT_UNSIGNED: ['The native amount evidence has no verified agent signature.', 'Connect the SDK with signatureMode set to required and register its signing public key for this agent in Studio.'],
33
+ NATIVE_AMOUNT_INVALID: ['The native amount evidence is invalid.', 'Use a positive integer in USD cents at the configured native argument path. Check the tool binding and signing SDK version.'],
34
+ NATIVE_AMOUNT_CONFLICT: ['Native amount representations disagree.', 'Use one source of USD cents. If supplied, currency, amount_cents, and amount_usd must agree with the mapped amount.'],
35
+ NATIVE_AMOUNT_KEY_REQUIRED: ['The cumulative amount rule requires a matching signed business key.', keyHint],
36
+ NATIVE_AMOUNT_KEY_INVALID: ['The native business key mapping or value is invalid.', keyHint],
37
+ NATIVE_AMOUNT_LEDGER_UNAVAILABLE: ['The cumulative amount ledger is unavailable.', 'Use the direct PostgreSQL driver (DASHCLAW_DB_DRIVER=postgres) and run the current Studio schema migration. Retry the same operation after Studio is healthy.'],
38
+ });
39
+
40
+ export function nativeAmountIssue(code) {
41
+ if (typeof code !== 'string' || !Object.hasOwn(issues, code)) return null;
42
+ const [reason, configuration_hint] = issues[code];
43
+ return { code, reason, configuration_hint };
44
+ }
@@ -1,26 +1,36 @@
1
1
  import path from 'node:path';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
- import { canonicalJson, createApiClient } from '../runtime/protocol.mjs';
4
- import { resolveRemotePosture } from '../runtime/posture.mjs';
3
+ import { canonicalJson, createApiClient, isTransientFailure, sha256 } from '../runtime/protocol.mjs';
4
+ import { rejectionFenceUnchanged, resolveRemotePosture } from '../runtime/posture.mjs';
5
5
  import { createStateStore } from '../runtime/state.mjs';
6
6
  import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
7
7
  import { matchesStoredAction, reject } from './contract.mjs';
8
+ import { nativeAmountIssue } from './amount.mjs';
8
9
 
9
10
  const receiptWindow = Object.freeze({ headersTimeoutMs: 2500, timeoutMs: 5000 });
10
11
 
12
+ function failureDetails(phase, response, mayHaveRegistered = false) {
13
+ return {
14
+ phase, httpStatus: response?.status || null, cause: response?.error || 'authority_evidence_unconfirmed',
15
+ retryAfterSeconds: response?.retryAfterSeconds ?? null,
16
+ retrySameOperation: !mayHaveRegistered && (isTransientFailure(response) || response?.status === 429),
17
+ };
18
+ }
19
+
11
20
  export function createStudioAuthority(config, journalPath) {
12
21
  const responseLimits = { maxResponseBytes: 1048576 };
13
22
  const baseApi = createApiClient(config, responseLimits);
14
23
  const store = createStateStore({ ...config, stateDir: path.join(path.dirname(journalPath), 'posture') });
24
+ let currentRead;
15
25
 
16
- async function current(aborted) {
17
- let remote;
26
+ async function readCurrent() {
27
+ let remote, lastResponse;
18
28
  const deadline = performance.now() + 2000;
19
29
  for (let attempt = 0; attempt < 6; attempt++) {
20
- if (aborted()) reject('ABORTED');
21
30
  let readStatus = null;
22
31
  remote = await resolveRemotePosture(config, { store, api: { async request(method, endpoint, ...args) {
23
32
  const response = await baseApi.request(method, endpoint, ...args);
33
+ lastResponse = response;
24
34
  if (method === 'GET') readStatus = response.status;
25
35
  return response;
26
36
  } } });
@@ -40,11 +50,22 @@ export function createStudioAuthority(config, journalPath) {
40
50
  || !['enforce', 'strict'].includes(remote.posture.mode)
41
51
  || remote.posture.require_assumption_capture !== false
42
52
  || remote.posture.require_signature !== true || remote.posture.on_guard_unavailable !== 'block') {
43
- reject('CURRENT_AUTHORITY_UNAVAILABLE');
53
+ reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('posture', lastResponse));
44
54
  }
45
55
  const effective = { ...config, mode: remote.posture.mode, guardFailureMode: 'block', signatureMode: 'required',
46
56
  approvalWaitMs: 0, ruleRollout: remote.ruleRollout };
47
- return { api: createApiClient(effective, responseLimits), effective };
57
+ return { api: createApiClient(effective, responseLimits), effective, fence: remote.rejectionFence };
58
+ }
59
+
60
+ async function current(aborted) {
61
+ if (aborted()) reject('ABORTED');
62
+ // A single live read can serve overlapping invocations of this scope.
63
+ // The next invocation after it settles must start another remote read.
64
+ currentRead ??= readCurrent().finally(() => { currentRead = null; });
65
+ const value = await currentRead;
66
+ if (aborted()) reject('ABORTED');
67
+ if (!rejectionFenceUnchanged(config, store, value.fence)) reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('posture'));
68
+ return value;
48
69
  }
49
70
 
50
71
  async function read(record) {
@@ -56,6 +77,9 @@ export function createStudioAuthority(config, journalPath) {
56
77
 
57
78
  async function admit(invocation, journal, owner, aborted) {
58
79
  const record = { ...journal.get(invocation.record.scope, invocation.record.operationId),
80
+ nativeAmount: invocation.context.native_amount,
81
+ nativeResource: invocation.context.native_resource,
82
+ delegationDigest: invocation.context.business_authority_assertion && sha256(canonicalJson(invocation.context.business_authority_assertion.claims)),
59
83
  ...(invocation.recovery ? { recovery: invocation.recovery } : {}) };
60
84
  const phase = record.state === 'held' ? 'redeeming' : 'requesting';
61
85
  const { api, effective } = await current(aborted);
@@ -68,7 +92,7 @@ export function createStudioAuthority(config, journalPath) {
68
92
  const actualSession = session.body?.session || session.body?.runtime_session;
69
93
  if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
70
94
  || actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
71
- || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE');
95
+ || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('runtime_session', session));
72
96
  let claimed = false, requestStartedAt = null;
73
97
  const claim = () => {
74
98
  if (claimed) reject('OUTCOME_UNKNOWN');
@@ -84,12 +108,31 @@ export function createStudioAuthority(config, journalPath) {
84
108
  if (aborted()) reject('ABORTED');
85
109
  const registering = method === 'POST' && endpoint === '/api/actions';
86
110
  if (registering) { claim(); requestStartedAt = performance.now(); }
87
- const response = await api.request(method, endpoint, body, registering ? receiptWindow : options);
111
+ const guardRequest = endpoint === '/api/guard';
112
+ const response = await api.request(method, endpoint, body, {
113
+ ...(registering ? receiptWindow : options), readForbiddenBody: registering || guardRequest,
114
+ });
115
+ if (guardRequest) {
116
+ const issue = nativeAmountIssue(response.body?.code) || nativeAmountIssue(invocation.context.native_amount_issue);
117
+ if (issue && (!response.ok || invocation.context.native_amount_issue)) {
118
+ reject(issue.code, null, { ...failureDetails('guard', response), cause: issue.code,
119
+ ...(issue.code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE' ? { retrySameOperation: true } : {}) });
120
+ }
121
+ if (!response.ok) {
122
+ reject(response.status === 403 && invocation.context.business_authority_assertion ? 'DELEGATION_REJECTED' : 'CURRENT_AUTHORITY_UNAVAILABLE',
123
+ null, failureDetails('guard', response));
124
+ }
125
+ }
88
126
  if (registering) {
127
+ if (response.status === 403 && response.body?.decision?.decision === 'block'
128
+ && response.body.action?.status === 'blocked' && matchesStoredAction(response.body, record, config)) {
129
+ const code = nativeAmountIssue(response.body.decision.code)?.code || 'POLICY_DENIED';
130
+ if (settle('denied')) reject(code, null, { ...failureDetails('action_registration', response), cause: code });
131
+ }
89
132
  if (!response.ok || !matchesStoredAction(response.body, record, config)
90
133
  || !cavaFingerprint(response.body)) {
91
134
  settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
92
- reject('OUTCOME_UNKNOWN');
135
+ reject('OUTCOME_UNKNOWN', null, failureDetails('action_registration', response, true));
93
136
  }
94
137
  }
95
138
  return response;
@@ -105,8 +148,10 @@ export function createStudioAuthority(config, journalPath) {
105
148
  if (result.authorized) return { phase, dispatchDeadline: requestStartedAt + receiptWindow.timeoutMs, response: result.response,
106
149
  ruleExpiresAt: result.ruleRolloutBinding?.expires_at ?? null };
107
150
  if (result.reason === 'policy_block') {
151
+ const issue = nativeAmountIssue(result.response?.code);
152
+ if (issue?.code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE') reject(issue.code, null, { phase: 'guard', retrySameOperation: true });
108
153
  if (!claimed) claim();
109
- settle('denied'); reject('POLICY_DENIED');
154
+ settle('denied'); reject(issue?.code || 'POLICY_DENIED');
110
155
  }
111
156
  if (result.decision === 'require_approval' && result.response?.action?.status === 'pending_approval') {
112
157
  if (!settle('held', { fingerprint: cavaFingerprint(result.response) })) reject('OUTCOME_UNKNOWN');
@@ -136,5 +181,11 @@ export function createStudioAuthority(config, journalPath) {
136
181
  && typeof response.body.action?.timestamp_end === 'string';
137
182
  }
138
183
 
139
- return { admit, read, report };
184
+ async function closeOwnerOutcome(record, receipt) {
185
+ const response = await baseApi.request('POST', `/api/actions/${encodeURIComponent(record.actionId)}/resource-confirmation`,
186
+ { agent_id: config.agentId, native_owner_receipt: receipt }, receiptWindow);
187
+ return response.ok && response.body.action_id === record.actionId ? response.body.owner_receipt : null;
188
+ }
189
+
190
+ return { admit, read, report, closeOwnerOutcome };
140
191
  }
@@ -1,5 +1,6 @@
1
1
  import { types } from 'node:util';
2
2
  import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
3
+ import { NATIVE_AMOUNT_SCHEMA, agreesWithUsdAmount, nativeAmountIssue, usdMinorToMajor, validNativePath, validUsdMapping } from './amount.mjs';
3
4
 
4
5
  export const CALL_SCHEMA = 'osuite.native_tool_call.v1';
5
6
  export const COVERAGE = 'wrapped-call-only';
@@ -12,18 +13,24 @@ const recoveryMessages = Object.freeze({
12
13
  read_business_result: 'This operation already completed. Read the original result from your application store; OSuite retains its digest, not the full output. Do not send the tool call again.',
13
14
  reconcile_without_resend: 'Keep the operation ID and journal. Read the existing action and resource evidence with an authorized operator; an unknown or mismatched result is not proof that nothing executed. Do not resend.',
14
15
  restore_connection: 'Restore the correct connection and current credentials, then read status for the same operation ID. Do not replace its ID or clear its journal to work around rejection.',
16
+ retry_same_operation: 'Wait for Studio to recover or until the retry delay elapses. Use the same operation ID and unchanged input.',
15
17
  repair_journal: 'Preserve the journal and stop new sends. Ask an operator to inspect storage permissions, capacity and verified backups; never reinitialize a missing journal on the restart path.',
16
18
  check_current_authority: 'Keep the same operation ID and arguments. A call must pass fresh authority checks before execution; this local status is not permission to execute.',
17
19
  stop: 'This operation is denied, expired or cancelled. Stop and consult the policy owner. Changing its ID is not a way to bypass that decision.',
18
20
  inspect_configuration: 'Check the supported runtime, input, mapping and connection configuration. Keep any existing operation ID and journal; do not automatically repeat a possibly sent call.',
19
21
  });
20
22
 
21
- function recoveryGuidance(code, state) {
23
+ function recoveryGuidance(code, state, details) {
24
+ const amountIssue = nativeAmountIssue(code);
25
+ if (amountIssue) {
26
+ return Object.freeze({ nextStep: code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE' ? 'retry_same_operation' : 'inspect_configuration',
27
+ preserveOperationId: true, message: `${amountIssue.reason} ${amountIssue.configuration_hint}` });
28
+ }
22
29
  let nextStep;
23
30
  if (code === 'ALREADY_COMPLETED' || (state === 'completed' && code !== 'BINDING_MISMATCH')) nextStep = 'read_business_result';
24
31
  else if (['OUTCOME_UNKNOWN', 'UNCERTAIN', 'BINDING_MISMATCH', 'CONFLICT'].includes(code)) nextStep = 'reconcile_without_resend';
25
32
  else if (code?.startsWith('JOURNAL_')) nextStep = 'repair_journal';
26
- else if (code === 'CURRENT_AUTHORITY_UNAVAILABLE') nextStep = 'restore_connection';
33
+ else if (code === 'CURRENT_AUTHORITY_UNAVAILABLE') nextStep = details?.retrySameOperation ? 'retry_same_operation' : 'restore_connection';
27
34
  else if (['POLICY_DENIED', 'APPROVAL_EXPIRED', 'CANCELLED'].includes(code)
28
35
  || ['denied', 'expired', 'cancelled'].includes(state)) nextStep = 'stop';
29
36
  else if (code === 'AWAITING_APPROVAL' || (!code && state === 'held')) nextStep = 'review_same_operation';
@@ -37,17 +44,19 @@ function recoveryGuidance(code, state) {
37
44
  }
38
45
 
39
46
  export class GovernedToolError extends Error {
40
- constructor(code, status = null) {
41
- const recovery = recoveryGuidance(code, status?.state);
47
+ constructor(code, status = null, details = null) {
48
+ const recovery = recoveryGuidance(code, status?.state, details);
42
49
  super(`OSuite ${code}: ${recovery.message}`);
43
50
  this.name = 'GovernedToolError';
44
51
  this.code = code;
45
52
  this.status = status === null ? null : Object.freeze({ ...status, recovery });
46
53
  this.retryAutomatically = false;
47
54
  this.recovery = recovery;
55
+ const hint = nativeAmountIssue(code)?.configuration_hint;
56
+ if (details || hint) this.details = Object.freeze({ ...details, ...(hint ? { configurationHint: hint } : {}) });
48
57
  }
49
58
  }
50
- export function reject(code, status) { throw new GovernedToolError(code, status); }
59
+ export function reject(code, status, details) { throw new GovernedToolError(code, status, details); }
51
60
 
52
61
  // Validate descriptors before reading values: JSON.stringify alone can invoke
53
62
  // accessors/toJSON or quietly change undefined, non-finite numbers and arrays.
@@ -122,6 +131,36 @@ function describe(binding, args) {
122
131
  return value;
123
132
  }
124
133
 
134
+ function readOwnPath(input, path) {
135
+ return path.reduce((object, key) => object && Object.hasOwn(object, key) ? object[key] : undefined, input);
136
+ }
137
+
138
+ function nativeAmount(binding, native, description, inputDigest) {
139
+ if (binding.amount === undefined) return {};
140
+ if (!validUsdMapping(binding.amount)) return { issue: 'NATIVE_AMOUNT_UNSUPPORTED' };
141
+ const { path } = binding.amount;
142
+ const owner = readOwnPath(native.arguments, path.slice(0, -1));
143
+ const value = readOwnPath(owner, path.slice(-1));
144
+ // A binding may also describe non-financial variants. A monetary policy
145
+ // independently requires evidence before any of those variants can execute.
146
+ if (value == null) return {};
147
+ if (value !== 0 && usdMinorToMajor(value) === null) return { issue: 'NATIVE_AMOUNT_INVALID' };
148
+ if (!agreesWithUsdAmount(owner, value) || !agreesWithUsdAmount(native.arguments, value)
149
+ || !agreesWithUsdAmount(description.input_summary, value)) return { issue: 'NATIVE_AMOUNT_CONFLICT' };
150
+ if (value === 0) return {};
151
+ const amount = { schema_version: NATIVE_AMOUNT_SCHEMA, mapping: binding.amount, value,
152
+ tool_name: native.name, binding_revision: binding.revision, input_digest: inputDigest };
153
+ if (binding.businessKey === undefined) return { amount };
154
+ const keyPath = binding.businessKey?.path;
155
+ if (!validNativePath(keyPath) || Object.keys(binding.businessKey).length !== 1) return { issue: 'NATIVE_AMOUNT_KEY_INVALID' };
156
+ const key = readOwnPath(native.arguments, keyPath);
157
+ const name = keyPath.at(-1);
158
+ if (!id(key) || [native.arguments, description.input_summary].some(source => source && Object.hasOwn(source, name) && source[name] !== key)) {
159
+ return { issue: 'NATIVE_AMOUNT_KEY_INVALID' };
160
+ }
161
+ return { amount: { ...amount, business_key: { path: keyPath, value_digest: sha256(canonicalJson(key)) } } };
162
+ }
163
+
125
164
  export function makeInvocation({ config, namespace, bindings, operationId, params }) {
126
165
  const scope = scopeFor(config, namespace);
127
166
  if (!id(operationId)) reject('INVALID_OPERATION_ID');
@@ -135,7 +174,12 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
135
174
  // The historical Hook helper normalizes null to {}. Native calls must retain
136
175
  // every JSON value exactly, including that distinction.
137
176
  const inputDigest = sha256(canonicalJson({ tool_name: native.name, tool_input: native.arguments }));
177
+ const { amount, issue } = nativeAmount(binding, native, description, inputDigest);
138
178
  const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description,
179
+ ...(binding.amount === undefined ? {} : { amountMapping: binding.amount }),
180
+ ...(binding.businessKey === undefined ? {} : { businessKey: binding.businessKey }),
181
+ ...(binding.ownerReceipt ? { nativeResource: binding.ownerReceipt.resource } : {}),
182
+ ...(binding.delegation ? { delegationRequired: true } : {}),
139
183
  ...(binding.recovery ? { recovery: { revision: binding.recovery.revision,
140
184
  resourceId: binding.recovery.resourceId, contract: binding.recovery.contract } } : {}) }));
141
185
  const identity = sha256(canonicalJson([scope, operationId]));
@@ -145,6 +189,9 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
145
189
  if (inputSummary.length > 4000) reject('INVALID_MAPPING');
146
190
  const context = jsonSnapshot({ ...description, input_summary: inputSummary, action_id: actionId,
147
191
  agent_id: config.agentId, runtime_session_id: sessionId, tool_use_id: toolUseId,
192
+ ...(amount ? { native_amount: { ...amount, binding_digest: bindingDigest } } : {}),
193
+ ...(issue ? { native_amount_issue: issue } : {}),
194
+ ...(binding.ownerReceipt ? { native_resource: { ...binding.ownerReceipt.resource, input_digest: inputDigest } } : {}),
148
195
  tool_input_digest: inputDigest, runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper' });
149
196
  return Object.freeze({ params: native, context, marker, record: Object.freeze({ scope, operationId,
150
197
  inputDigest, bindingDigest, contextDigest: sha256(canonicalJson(context)), actionId, sessionId, toolUseId }) });
@@ -173,6 +220,9 @@ export function matchesStoredAction(payload, record, config) {
173
220
  && envelope.action_id === record.actionId && envelope.org_id === config.orgId && envelope.agent_id === config.agentId
174
221
  && envelope.runtime_session_id === record.sessionId && envelope.tool_use_id === record.toolUseId
175
222
  && (!Object.hasOwn(envelope, 'tool_input_digest') || envelope.tool_input_digest === record.inputDigest)
223
+ && (!record.nativeAmount || canonicalJson(envelope.native_amount) === canonicalJson(record.nativeAmount))
224
+ && (!record.nativeResource || canonicalJson(envelope.native_resource) === canonicalJson(record.nativeResource))
225
+ && (!record.delegationDigest || envelope.business_authority?.assertion_digest === record.delegationDigest)
176
226
  && matchesStoredSummary(action.input_summary, record) && matchesStoredSummary(envelope.input_summary, record);
177
227
  } catch { return false; }
178
228
  }