osuite 2.16.0 → 2.18.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_RECOVERY.md +6 -0
- package/GOVERNED_TOOLS.md +130 -25
- package/README.md +23 -0
- package/RELEASE_NOTES.md +11 -0
- package/cli.js +53 -14
- package/governed-tools/amount.mjs +27 -5
- package/governed-tools/authority.mjs +53 -10
- package/governed-tools/contract.mjs +39 -17
- package/governed-tools/executor.mjs +79 -31
- package/governed-tools/owner-receipt.mjs +75 -7
- package/governed-tools/proof-digest.mjs +16 -0
- package/installationIdentity.js +1 -0
- package/native-proof.mjs +56 -5
- package/nativeDoctor.mjs +4 -2
- package/onboardingCli.js +469 -0
- package/package.json +3 -1
- package/projectHooks.js +30 -10
- package/runtime/guard-timeout.mjs +3 -0
- package/runtime/protocol.mjs +6 -3
package/GOVERNED_RECOVERY.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Evidence-bound native recovery
|
|
2
2
|
|
|
3
|
+
For read-only closure after a restart, see
|
|
4
|
+
[Reconcile With The Resource Owner](GOVERNED_TOOLS.md#reconcile-with-the-resource-owner).
|
|
5
|
+
Call `reconcile` after reopening the same journal. A v2 owner receipt binding
|
|
6
|
+
allows a read-only lookup and keeps the original dispatch fence. The
|
|
7
|
+
write-capable recovery API below applies to other bindings.
|
|
8
|
+
|
|
3
9
|
Version 2.14.0 adds the opt-in
|
|
4
10
|
`tools.recover(operationId, unchangedParams, options)` API to
|
|
5
11
|
`createGovernedTools` on Node 24/POSIX. Confirm registry availability with
|
package/GOVERNED_TOOLS.md
CHANGED
|
@@ -96,30 +96,114 @@ with the mapping. Tool variants without a positive amount can run only when
|
|
|
96
96
|
their policies permit an action without amount evidence. Whole-CAD refunds
|
|
97
97
|
continue to use the exact `refund.create` mapping.
|
|
98
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
|
+
|
|
99
136
|
### Reconcile With The Resource Owner
|
|
100
137
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
`
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
138
|
+
Configure the binding before the first run.
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
import { OWNER_CLOSURE_RECEIPT_SCHEMA } from 'osuite/native-proof';
|
|
142
|
+
|
|
143
|
+
const ownerReceipt = {
|
|
144
|
+
resourceId: 'billing-ledger',
|
|
145
|
+
publicKey: ownerPublicKey,
|
|
146
|
+
schemaVersion: OWNER_CLOSURE_RECEIPT_SCHEMA,
|
|
147
|
+
query: ({ operationId, signal, ...scope }) => owner.lookup(scope, { signal }),
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const result = await tools.reconcile(operationId, unchangedParams);
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Add `ownerReceipt` to the tool binding when creating `tools`. Use base64 Ed25519
|
|
154
|
+
SPKI DER for `publicKey`. A workspace admin pins the same key in the workspace
|
|
155
|
+
setting `NATIVE_RESOURCE_OWNERS`. Set its value to a JSON array of
|
|
156
|
+
`{ resource_id, public_key }` entries. Keep the private key on the owner side.
|
|
157
|
+
Use a read credential scoped to the owner ledger. Give offline verifiers the
|
|
158
|
+
public key through a trusted channel.
|
|
159
|
+
|
|
160
|
+
With this binding, the `run` callback receives `(params, scope)`. Forward the
|
|
161
|
+
frozen scope to the resource and store it with the effect. The scope is
|
|
162
|
+
`org_id`, `action_id`, `input_digest`, `resource_id` and `key_id`. The key ID
|
|
163
|
+
is the SHA-256 digest of the public key's SPKI DER bytes.
|
|
164
|
+
|
|
165
|
+
Reopen the same journal after a dropped reply or restart. Call `reconcile`
|
|
166
|
+
with the original operation ID and arguments. The SDK checks for a recorded
|
|
167
|
+
owner receipt first. Otherwise it calls `query` once. The query also receives
|
|
168
|
+
`schema_version`, `previous_proof_digest` and `observation_digest` from Studio.
|
|
169
|
+
Pass these through to the owner's lookup along with the scope. The owner may
|
|
170
|
+
look up a receipt or read its ledger within that scope.
|
|
171
|
+
|
|
172
|
+
The owner returns `{ claims, signature }`. Copy the scope and the three
|
|
173
|
+
additional fields into `claims`. Add `receipt_id`, `observed_at` in UTC ISO
|
|
174
|
+
format with milliseconds, `complete: true`, `final: true`, and `outcome`.
|
|
175
|
+
Set `outcome` to `committed` and include the owner's `resource_reference`.
|
|
176
|
+
Use 1 to 240 letters, digits or characters from `_:/.-` in the reference.
|
|
177
|
+
For `absent`, set `resource_reference` to null. Issue absence only after a
|
|
178
|
+
complete authoritative read and a resource-side fence against delayed writes.
|
|
179
|
+
Use the time of the owner's read for `observed_at`.
|
|
180
|
+
|
|
181
|
+
Sign the schema version, a newline and canonical JSON of the claims with the
|
|
182
|
+
owner's Ed25519 key. `ownerReceiptPayload(claims)` from `osuite/native-proof`
|
|
183
|
+
builds these bytes. Encode the signature in base64. The owner signs the two
|
|
184
|
+
Studio digests as context for its own resource finding.
|
|
185
|
+
|
|
186
|
+
Incomplete, invalid and unavailable answers return `outcome: 'unknown'`.
|
|
187
|
+
The lookup has a five-second limit and accepts an optional `signal`.
|
|
188
|
+
Studio also verifies a receipt before accepting it. An acknowledged closure
|
|
189
|
+
returns `outcome`, `ownerReceipt` and `ownerClosure`. The journal retains its
|
|
190
|
+
dispatch fence. Reconcile again to read the persisted closure. A new call to
|
|
191
|
+
`run` with that ID cannot execute the callback. The write-capable `recover`
|
|
192
|
+
API is unavailable for this binding.
|
|
193
|
+
|
|
194
|
+
Omitting `schemaVersion` keeps the earlier v1 receipt contract. V1 receipts
|
|
195
|
+
remain readable. The v2 contract applies to actions created with the v2 binding.
|
|
196
|
+
|
|
197
|
+
Download the ordinary proof export with
|
|
198
|
+
`GET /api/proof/export?action_id=…`. Call
|
|
199
|
+
`verifyNativeOwnerClosure(bundle, ownerPublicKey)` from `osuite/native-proof`
|
|
200
|
+
offline. It accepts the export or its `proof_bundle` member. The Studio
|
|
201
|
+
record is tamper-evident. The owner's signature authenticates the scoped
|
|
202
|
+
resource finding and binds it to the earlier proof and the runtime observation.
|
|
203
|
+
|
|
204
|
+
For the native cohort export, use `GET /api/proof/export?format=native`
|
|
205
|
+
with `from` and `to` in UTC. Use `format=native-checkpoint` to obtain its
|
|
206
|
+
checkpoint separately.
|
|
123
207
|
The window includes registered, verified native actions by creation time.
|
|
124
208
|
Studio reads `OSUITE_NATIVE_PROOF_SIGNING_KEY` and
|
|
125
209
|
`OSUITE_NATIVE_CHECKPOINT_SIGNING_KEY` as separately provisioned base64
|
|
@@ -187,6 +271,27 @@ content; do not treat POST/GET hash inequality alone as a failed write. A requir
|
|
|
187
271
|
capability that this wrapper cannot satisfy must still stop execution; reducing
|
|
188
272
|
that requirement is an administrator's policy decision, not an SDK recovery step.
|
|
189
273
|
|
|
274
|
+
## Guard and approval options
|
|
275
|
+
|
|
276
|
+
`run` accepts `waitMs` and `signal`. `waitMs` is the approval wait in
|
|
277
|
+
milliseconds. It defaults to 0 and accepts integers through 600,000. `signal`
|
|
278
|
+
is an optional `AbortSignal`. It can cancel the Guard request or stop an
|
|
279
|
+
approval wait.
|
|
280
|
+
|
|
281
|
+
The SDK waits up to 15,000 ms for `POST /api/guard`. This covers Studio's
|
|
282
|
+
10,000 ms maximum callback timeout plus 5,000 ms for Studio and the network.
|
|
283
|
+
A callback timeout that blocks returns `POLICY_DENIED` with the reason in
|
|
284
|
+
`error.details.reason`. If Guard is unavailable, the SDK fails closed.
|
|
285
|
+
|
|
286
|
+
Action registration and approval redemption check policy again. When Guard
|
|
287
|
+
reports a callback, the SDK adds its budget to the registration limits of
|
|
288
|
+
2,500 ms for headers and 5,000 ms for the whole response.
|
|
289
|
+
|
|
290
|
+
If Guard is cancelled or its response is lost, retry with the same operation
|
|
291
|
+
ID, journal, and input. Studio can return the recorded initial Guard decision.
|
|
292
|
+
The SDK still needs fresh action registration before dispatch. The journal
|
|
293
|
+
prevents a second dispatch for the operation.
|
|
294
|
+
|
|
190
295
|
## Connected MCP Client
|
|
191
296
|
|
|
192
297
|
```js
|
|
@@ -324,9 +429,9 @@ database. Explicit initialization is a provisioning action, not recovery.
|
|
|
324
429
|
Version 2.11.2 changes the default `journalOptions.busyTimeoutMs`
|
|
325
430
|
from 100 to 1,000 ms; the supported range remains 0-5,000 ms. This is a bounded
|
|
326
431
|
local write-lock budget, not extra approval time or an operation retry policy.
|
|
327
|
-
After the dispatch fence commits, the
|
|
328
|
-
|
|
329
|
-
|
|
432
|
+
After the dispatch fence commits, the SDK checks the registration deadline
|
|
433
|
+
again immediately before calling the tool. An expired response leaves an
|
|
434
|
+
uncertain fence. The SDK never renews it or retries automatically.
|
|
330
435
|
Do not delete completed or unknown rows
|
|
331
436
|
to make room: they are replay tombstones. Plan scoped lifecycle/retention with
|
|
332
437
|
the operator, retain the WAL correctly, and never share this database over an
|
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/RELEASE_NOTES.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# SDK 2.18.0 release notes
|
|
2
|
+
|
|
3
|
+
- Reopen the same governed tools journal and call `reconcile` to read an authenticated owner closure.
|
|
4
|
+
- Opt in with `ownerReceipt.schemaVersion` set to `osuite.native_owner_receipt.v2`. A committed closure includes the owner's reference. An absent closure requires a complete scoped read and a resource-side write fence.
|
|
5
|
+
- Verify the tamper-evident Studio export offline with `verifyNativeOwnerClosure` and the owner's public key.
|
|
6
|
+
- The SDK keeps the original dispatch fence and returns `unknown` for incomplete, invalid or timed-out reads. Existing v1 receipts remain readable.
|
|
7
|
+
- Governed tools wait through Studio's callback timeout. A block returns `POLICY_DENIED` with the reason. An allow still needs current action registration before dispatch.
|
|
8
|
+
- If a Guard response is lost, retry with the same operation ID and input. The updated Studio can return its recorded decision. See [Guard and approval options](GOVERNED_TOOLS.md#guard-and-approval-options).
|
|
9
|
+
|
|
10
|
+
Use Node 24 on POSIX for the governed tools runtime. Use a Studio version
|
|
11
|
+
that supports v2 owner closure. See [native tool configuration](GOVERNED_TOOLS.md#reconcile-with-the-resource-owner).
|
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
|
|
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 = '
|
|
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(
|
|
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('');
|
|
@@ -1,13 +1,16 @@
|
|
|
1
|
-
import { isObject } from '../runtime/protocol.mjs';
|
|
2
|
-
|
|
3
1
|
export const NATIVE_AMOUNT_SCHEMA = 'osuite.native_amount.v1';
|
|
4
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
|
+
}
|
|
5
9
|
|
|
6
10
|
export function validUsdMapping(mapping) {
|
|
7
11
|
return isObject(mapping) && Object.keys(mapping).length === 3
|
|
8
12
|
&& mapping.currency === 'USD' && mapping.unit === 'minor'
|
|
9
|
-
&&
|
|
10
|
-
&& mapping.path.every(key => typeof key === 'string' && /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(key) && !reserved.has(key));
|
|
13
|
+
&& validNativePath(mapping.path);
|
|
11
14
|
}
|
|
12
15
|
|
|
13
16
|
export function usdMinorToMajor(value) {
|
|
@@ -17,6 +20,25 @@ export function usdMinorToMajor(value) {
|
|
|
17
20
|
|
|
18
21
|
export function agreesWithUsdAmount(value, minor) {
|
|
19
22
|
if (!isObject(value)) return true;
|
|
20
|
-
return [['currency', 'USD'], ['amount_cents', minor], ['amount_usd', usdMinorToMajor(minor)]]
|
|
23
|
+
return [['currency', 'USD'], ['amount_cents', minor], ['amount_usd', minor === 0 ? 0 : usdMinorToMajor(minor)]]
|
|
21
24
|
.every(([key, expected]) => !Object.hasOwn(value, key) || value[key] === expected);
|
|
22
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,12 +1,28 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
3
|
import { canonicalJson, createApiClient, isTransientFailure, sha256 } from '../runtime/protocol.mjs';
|
|
4
|
+
import { MAX_GUARD_WEBHOOK_TIMEOUT_MS } from '../runtime/guard-timeout.mjs';
|
|
4
5
|
import { rejectionFenceUnchanged, resolveRemotePosture } from '../runtime/posture.mjs';
|
|
5
6
|
import { createStateStore } from '../runtime/state.mjs';
|
|
6
7
|
import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
|
|
7
8
|
import { matchesStoredAction, reject } from './contract.mjs';
|
|
9
|
+
import { nativeAmountIssue } from './amount.mjs';
|
|
8
10
|
|
|
9
11
|
const receiptWindow = Object.freeze({ headersTimeoutMs: 2500, timeoutMs: 5000 });
|
|
12
|
+
const guardTimeoutMs = MAX_GUARD_WEBHOOK_TIMEOUT_MS + 5000;
|
|
13
|
+
|
|
14
|
+
function registrationWindow(guard) {
|
|
15
|
+
let budget = guard.webhook_timeout_ms;
|
|
16
|
+
if (!Number.isFinite(budget) || budget <= 0 || budget > MAX_GUARD_WEBHOOK_TIMEOUT_MS) {
|
|
17
|
+
// Older Studio versions report callback decisions without a budget.
|
|
18
|
+
if (!guard.policy_snapshot?.webhook_decisions?.length) return receiptWindow;
|
|
19
|
+
budget = MAX_GUARD_WEBHOOK_TIMEOUT_MS;
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
headersTimeoutMs: receiptWindow.headersTimeoutMs + budget,
|
|
23
|
+
timeoutMs: receiptWindow.timeoutMs + budget,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
10
26
|
|
|
11
27
|
function failureDetails(phase, response, mayHaveRegistered = false) {
|
|
12
28
|
return {
|
|
@@ -74,7 +90,7 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
74
90
|
return { available: true, body: response.body, action: response.body.action || response.body };
|
|
75
91
|
}
|
|
76
92
|
|
|
77
|
-
async function admit(invocation, journal, owner, aborted) {
|
|
93
|
+
async function admit(invocation, journal, owner, aborted, signal) {
|
|
78
94
|
const record = { ...journal.get(invocation.record.scope, invocation.record.operationId),
|
|
79
95
|
nativeAmount: invocation.context.native_amount,
|
|
80
96
|
nativeResource: invocation.context.native_resource,
|
|
@@ -92,7 +108,8 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
92
108
|
if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
|
|
93
109
|
|| actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
|
|
94
110
|
|| actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('runtime_session', session));
|
|
95
|
-
let claimed = false,
|
|
111
|
+
let claimed = false, dispatchDeadline = null;
|
|
112
|
+
let actionWindow = receiptWindow;
|
|
96
113
|
const claim = () => {
|
|
97
114
|
if (claimed) reject('OUTCOME_UNKNOWN');
|
|
98
115
|
if (aborted()) reject('ABORTED');
|
|
@@ -106,13 +123,36 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
106
123
|
api: { async request(method, endpoint, body, options) {
|
|
107
124
|
if (aborted()) reject('ABORTED');
|
|
108
125
|
const registering = method === 'POST' && endpoint === '/api/actions';
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
126
|
+
const guardRequest = endpoint === '/api/guard';
|
|
127
|
+
if (registering) {
|
|
128
|
+
claim();
|
|
129
|
+
dispatchDeadline = performance.now() + actionWindow.timeoutMs;
|
|
130
|
+
}
|
|
131
|
+
if (guardRequest && phase === 'requesting') body = { ...body, native_guard_replay: 'v1' };
|
|
132
|
+
const window = registering ? actionWindow : guardRequest ? { timeoutMs: guardTimeoutMs, signal } : options;
|
|
133
|
+
const response = await api.request(method, endpoint, body, {
|
|
134
|
+
...window, readForbiddenBody: registering || guardRequest,
|
|
135
|
+
});
|
|
136
|
+
if (guardRequest) {
|
|
137
|
+
if (aborted()) reject('ABORTED');
|
|
138
|
+
const issue = nativeAmountIssue(response.body?.code) || nativeAmountIssue(invocation.context.native_amount_issue);
|
|
139
|
+
if (issue && (!response.ok || invocation.context.native_amount_issue)) {
|
|
140
|
+
reject(issue.code, null, { ...failureDetails('guard', response), cause: issue.code,
|
|
141
|
+
...(issue.code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE' ? { retrySameOperation: true } : {}) });
|
|
142
|
+
}
|
|
143
|
+
if (!response.ok) {
|
|
144
|
+
reject(response.status === 403 && invocation.context.business_authority_assertion ? 'DELEGATION_REJECTED' : 'CURRENT_AUTHORITY_UNAVAILABLE',
|
|
145
|
+
null, failureDetails('guard', response));
|
|
146
|
+
}
|
|
147
|
+
actionWindow = registrationWindow(response.body);
|
|
114
148
|
}
|
|
115
149
|
if (registering) {
|
|
150
|
+
if (response.status === 403 && response.body?.decision?.decision === 'block'
|
|
151
|
+
&& response.body.action?.status === 'blocked' && matchesStoredAction(response.body, record, config)) {
|
|
152
|
+
const code = nativeAmountIssue(response.body.decision.code)?.code || 'POLICY_DENIED';
|
|
153
|
+
if (settle('denied')) reject(code, null, { ...failureDetails('action_registration', response),
|
|
154
|
+
cause: code, reason: response.body.decision.reason });
|
|
155
|
+
}
|
|
116
156
|
if (!response.ok || !matchesStoredAction(response.body, record, config)
|
|
117
157
|
|| !cavaFingerprint(response.body)) {
|
|
118
158
|
settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
|
|
@@ -129,11 +169,14 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
129
169
|
{ actionId: record.actionId, fingerprint: record.fingerprint }).authorized);
|
|
130
170
|
},
|
|
131
171
|
});
|
|
132
|
-
if (result.authorized) return { phase, dispatchDeadline
|
|
172
|
+
if (result.authorized) return { phase, dispatchDeadline, response: result.response,
|
|
133
173
|
ruleExpiresAt: result.ruleRolloutBinding?.expires_at ?? null };
|
|
134
174
|
if (result.reason === 'policy_block') {
|
|
175
|
+
const issue = nativeAmountIssue(result.response?.code);
|
|
176
|
+
if (issue?.code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE') reject(issue.code, null, { phase: 'guard', retrySameOperation: true });
|
|
135
177
|
if (!claimed) claim();
|
|
136
|
-
settle('denied')
|
|
178
|
+
if (!settle('denied')) reject('OPERATION_BUSY');
|
|
179
|
+
reject(issue?.code || 'POLICY_DENIED', null, { phase: 'guard', reason: result.response?.reason });
|
|
137
180
|
}
|
|
138
181
|
if (result.decision === 'require_approval' && result.response?.action?.status === 'pending_approval') {
|
|
139
182
|
if (!settle('held', { fingerprint: cavaFingerprint(result.response) })) reject('OUTCOME_UNKNOWN');
|
|
@@ -166,7 +209,7 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
166
209
|
async function closeOwnerOutcome(record, receipt) {
|
|
167
210
|
const response = await baseApi.request('POST', `/api/actions/${encodeURIComponent(record.actionId)}/resource-confirmation`,
|
|
168
211
|
{ agent_id: config.agentId, native_owner_receipt: receipt }, receiptWindow);
|
|
169
|
-
return response.ok && response.body.action_id === record.actionId ? response.body
|
|
212
|
+
return response.ok && response.body.action_id === record.actionId ? response.body : null;
|
|
170
213
|
}
|
|
171
214
|
|
|
172
215
|
return { admit, read, report, closeOwnerOutcome };
|