osuite 2.9.9 → 2.10.1
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 +21 -0
- package/README.md +98 -106
- package/activationMetrics.js +116 -0
- package/cli.js +369 -70
- package/credentials.js +234 -0
- package/osuite.js +41 -13
- package/package.json +9 -3
- package/projectHooks.js +916 -0
- package/reviewSurface.js +10 -2
- package/runtime/admission.mjs +150 -0
- package/runtime/config.mjs +56 -0
- package/runtime/context.mjs +122 -0
- package/runtime/cursor.mjs +83 -0
- package/runtime/git.mjs +46 -0
- package/runtime/hook.mjs +200 -0
- package/runtime/mcp.mjs +219 -0
- package/runtime/outcome.mjs +98 -0
- package/runtime/posture.mjs +103 -0
- package/runtime/protocol.mjs +96 -0
- package/runtime/shell.mjs +186 -0
- package/runtime/state.mjs +83 -0
- package/tryContract.js +47 -0
- package/tryFlow.js +90 -0
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.
|
|
1
|
+
# OSuite SDK (v2.10.1)
|
|
2
2
|
|
|
3
3
|
**Governed action SDK for AI agents.**
|
|
4
4
|
|
|
@@ -11,86 +11,72 @@ The OSuite SDK helps teams route approvals, record governed decisions, and produ
|
|
|
11
11
|
npm install osuite
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
###
|
|
15
|
-
```bash
|
|
16
|
-
curl -fsSL https://studio.osuite.ai/install.sh | bash
|
|
17
|
-
```
|
|
14
|
+
### Connect And Verify
|
|
18
15
|
|
|
19
|
-
|
|
16
|
+
For the checked-out 2.10.1 source, run from the project you want to connect:
|
|
20
17
|
|
|
21
|
-
### Python
|
|
22
18
|
```bash
|
|
23
|
-
|
|
19
|
+
node /absolute/path/to/osuite-sdk/sdk/cli.js connect
|
|
20
|
+
node /absolute/path/to/osuite-sdk/sdk/cli.js doctor
|
|
21
|
+
node /absolute/path/to/osuite-sdk/sdk/cli.js try
|
|
24
22
|
```
|
|
25
23
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
24
|
+
After the owner publishes 2.10.1 to npm, the equivalent pinned command is
|
|
25
|
+
`npx osuite@2.10.1 connect`. A source release does not mean that npm's `latest`
|
|
26
|
+
already contains it. Check `npm view osuite version` before relying on the new
|
|
27
|
+
credential-recovery or Node-hook behavior.
|
|
29
28
|
|
|
30
|
-
|
|
31
|
-
```javascript
|
|
32
|
-
import { OSuite } from 'osuite';
|
|
33
|
-
|
|
34
|
-
const osuite = new OSuite({
|
|
35
|
-
baseUrl: process.env.OSUITE_BASE_URL,
|
|
36
|
-
apiKey: process.env.OSUITE_API_KEY,
|
|
37
|
-
agentId: 'my-agent'
|
|
38
|
-
});
|
|
29
|
+
The alternative installer follows npm's published `latest`:
|
|
39
30
|
|
|
40
|
-
|
|
41
|
-
|
|
31
|
+
```bash
|
|
32
|
+
curl -fsSL https://studio.osuite.ai/install.sh | bash
|
|
33
|
+
```
|
|
42
34
|
|
|
43
|
-
|
|
44
|
-
|
|
35
|
+
The CLI detects Codex, Claude Code, Cursor, SDK, or MCP-style projects, opens a browser
|
|
36
|
+
handoff, and safely stores the approved runtime environment. Credential files
|
|
37
|
+
are owner-only on POSIX and explicitly ignored by Git. Tracked or symlinked
|
|
38
|
+
credential paths are refused. The client durably saves a recovery journal before
|
|
39
|
+
acknowledging a replacement, so reconnect does not revoke the old key before the
|
|
40
|
+
new credential can be recovered. Historical exposure still requires key rotation.
|
|
41
|
+
|
|
42
|
+
New 2.10.1 hook installations need Node.js 18 or newer and Git for repository
|
|
43
|
+
safety checks. Python is not required for the packaged Node hooks or MCP bridge.
|
|
44
|
+
Existing Python installations remain legacy until explicitly migrated. Custom
|
|
45
|
+
registrations and intentionally disabled hooks are preserved, not silently
|
|
46
|
+
re-enabled. `doctor` reports a direct hook probe; it is not proof that every host
|
|
47
|
+
tool or alternative resource path is governed. Windows file ACL and live vendor
|
|
48
|
+
host qualification are separate from POSIX tests.
|
|
49
|
+
|
|
50
|
+
Select `osuite connect cursor` explicitly when a project contains multiple host
|
|
51
|
+
configurations. Cursor uses its native flat hook protocol, not Claude's hook
|
|
52
|
+
response schema. It starts in observation mode; switch the agent posture in
|
|
53
|
+
Studio before relying on interception. Node 18.20.8 is the oldest tested runtime;
|
|
54
|
+
use a supported Node LTS release, preferably Node 24, for new installations.
|
|
55
|
+
|
|
56
|
+
`osuite try` opens one harmless, synthetic review. It prints one fixed local
|
|
57
|
+
acknowledgement only after an eligible human approves and the server freshly
|
|
58
|
+
redeems that exact grant. A missing, denied or unconfirmed grant does not execute.
|
|
59
|
+
Slack and email notifications require configured workspace channels.
|
|
45
60
|
|
|
46
|
-
|
|
47
|
-
await osuite.recordAssumption({ action_id, assumption: 'Tests passed' });
|
|
61
|
+
## The Governance Loop
|
|
48
62
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
63
|
+
The SDK transports requests; it does not execute your tool. A guard evaluation or
|
|
64
|
+
`waitForApproval()` result is not execution authorization on its own. A secure
|
|
65
|
+
integration must preserve all four steps:
|
|
52
66
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
headers = {
|
|
61
|
-
"content-type": "application/json",
|
|
62
|
-
"x-api-key": api_key,
|
|
63
|
-
}
|
|
67
|
+
1. Describe and sign the exact proposed action, including its target and effects.
|
|
68
|
+
2. Stop on a refusal or hold; an agent credential cannot approve its own request.
|
|
69
|
+
3. Immediately before dispatch, re-evaluate and redeem the same action through
|
|
70
|
+
the admission path. Check exact identity, current scope, expiry and receipt;
|
|
71
|
+
do not execute merely because a log exists or a prior GET showed approval.
|
|
72
|
+
4. Execute once, then report the actual result. A timeout after dispatch is an
|
|
73
|
+
unknown outcome, not permission to resend the write. Reconcile it separately.
|
|
64
74
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
).json()
|
|
71
|
-
|
|
72
|
-
# 2. Log intent
|
|
73
|
-
action = requests.post(
|
|
74
|
-
f"{base_url}/api/actions",
|
|
75
|
-
headers=headers,
|
|
76
|
-
json={"agent_id": "my-agent", "action_type": "deploy"},
|
|
77
|
-
).json()
|
|
78
|
-
action_id = action["action_id"]
|
|
79
|
-
|
|
80
|
-
# 3. Log evidence
|
|
81
|
-
requests.post(
|
|
82
|
-
f"{base_url}/api/assumptions",
|
|
83
|
-
headers=headers,
|
|
84
|
-
json={"action_id": action_id, "assumption": "Tests passed"},
|
|
85
|
-
)
|
|
86
|
-
|
|
87
|
-
# 4. Update result
|
|
88
|
-
requests.patch(
|
|
89
|
-
f"{base_url}/api/actions/{action_id}",
|
|
90
|
-
headers=headers,
|
|
91
|
-
json={"status": "completed"},
|
|
92
|
-
)
|
|
93
|
-
```
|
|
75
|
+
The packaged Node hooks implement this ordering for their documented runtime
|
|
76
|
+
profiles. `tryFlow.js` is the deliberately constrained walkthrough, not an
|
|
77
|
+
arbitrary side-effect executor. See `runtime/admission.mjs` and its independent
|
|
78
|
+
tests before implementing another host integration. A cooperative endpoint
|
|
79
|
+
hook is not a replacement for downstream IAM or mandatory resource mediation.
|
|
94
80
|
|
|
95
81
|
---
|
|
96
82
|
|
|
@@ -104,7 +90,7 @@ The v2 SDK exposes the core governance loop plus first-class PCAA, replay, proof
|
|
|
104
90
|
- `updateOutcome(id, outcome)` -- Result recording ("X finished with Y")
|
|
105
91
|
- `recordAssumption(assumption)` -- Integrity tracking ("I believe Z while doing X")
|
|
106
92
|
- `waitForApproval(id)` -- Polling helper for human-in-the-loop approvals
|
|
107
|
-
- `approveAction(id, decision, reasoning?)` --
|
|
93
|
+
- `approveAction(id, decision, reasoning?)` -- Transport an approval request; default SaaS policy requires an eligible signed-in person and rejects agent-key self-approval.
|
|
108
94
|
- `getPendingApprovals()` -- List actions awaiting human review
|
|
109
95
|
|
|
110
96
|
### Decision Integrity
|
|
@@ -381,72 +367,70 @@ await osuite.syncState({
|
|
|
381
367
|
|
|
382
368
|
## Agent Identity
|
|
383
369
|
|
|
384
|
-
Enroll agents via public-key pairing and manage approved identities for signature verification.
|
|
385
|
-
|
|
386
|
-
### Create Pairing
|
|
370
|
+
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
371
|
|
|
388
372
|
```javascript
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
373
|
+
async function identityRequest(route, { method = 'GET', body } = {}) {
|
|
374
|
+
const response = await fetch(`${baseUrl}${route}`, {
|
|
375
|
+
method,
|
|
376
|
+
headers: { 'content-type': 'application/json', 'x-api-key': adminApiKey },
|
|
377
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) })
|
|
378
|
+
});
|
|
379
|
+
if (!response.ok) throw new Error(`Identity request failed: ${response.status}`);
|
|
380
|
+
return response.json();
|
|
381
|
+
}
|
|
395
382
|
```
|
|
396
383
|
|
|
397
|
-
###
|
|
384
|
+
### Create Pairing
|
|
398
385
|
|
|
399
386
|
```javascript
|
|
400
|
-
const
|
|
387
|
+
const { pairing } = await identityRequest('/api/pairings', {
|
|
388
|
+
method: 'POST',
|
|
389
|
+
body: { agent_id: agentId, agent_name: 'my-agent', public_key: publicKeyPem, algorithm: 'RSASSA-PKCS1-v1_5' }
|
|
390
|
+
});
|
|
391
|
+
console.log(pairing.id); // pair_...
|
|
401
392
|
```
|
|
402
393
|
|
|
403
394
|
### Get Pairing
|
|
404
395
|
|
|
405
396
|
```javascript
|
|
406
|
-
const status = await
|
|
397
|
+
const status = await identityRequest(`/api/pairings/${encodeURIComponent(pairing.id)}`);
|
|
407
398
|
console.log(status.pairing.status); // pending | approved | expired
|
|
408
399
|
```
|
|
409
400
|
|
|
401
|
+
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.
|
|
402
|
+
|
|
410
403
|
### Approve Pairing (Admin)
|
|
411
404
|
|
|
412
405
|
```javascript
|
|
413
|
-
|
|
414
|
-
const res = await fetch(`${baseUrl}/api/pairings/${pairingId}/approve`, {
|
|
415
|
-
method: 'POST',
|
|
416
|
-
headers: { 'x-api-key': adminApiKey }
|
|
417
|
-
});
|
|
406
|
+
await identityRequest(`/api/pairings/${encodeURIComponent(pairing.id)}/approve`, { method: 'POST' });
|
|
418
407
|
```
|
|
419
408
|
|
|
420
409
|
### List Pairings (Admin)
|
|
421
410
|
|
|
422
411
|
```javascript
|
|
423
|
-
const
|
|
424
|
-
headers: { 'x-api-key': adminApiKey }
|
|
425
|
-
});
|
|
426
|
-
const { pairings } = await res.json();
|
|
412
|
+
const { pairings } = await identityRequest('/api/pairings');
|
|
427
413
|
```
|
|
428
414
|
|
|
429
415
|
### Register Identity (Admin)
|
|
430
416
|
|
|
431
417
|
```javascript
|
|
432
|
-
|
|
433
|
-
|
|
418
|
+
await identityRequest('/api/identities', {
|
|
419
|
+
method: 'POST',
|
|
420
|
+
body: { agent_id: 'agent-007', public_key: publicKeyPem, algorithm: 'RSASSA-PKCS1-v1_5' }
|
|
421
|
+
});
|
|
434
422
|
```
|
|
435
423
|
|
|
436
424
|
### List Identities (Admin)
|
|
437
425
|
|
|
438
426
|
```javascript
|
|
439
|
-
const { identities } = await
|
|
427
|
+
const { identities } = await identityRequest('/api/identities');
|
|
440
428
|
```
|
|
441
429
|
|
|
442
430
|
### Revoke Identity (Admin)
|
|
443
431
|
|
|
444
432
|
```javascript
|
|
445
|
-
|
|
446
|
-
const res = await fetch(`${baseUrl}/api/identities/${agentId}`, {
|
|
447
|
-
method: 'DELETE',
|
|
448
|
-
headers: { 'x-api-key': adminApiKey }
|
|
449
|
-
});
|
|
433
|
+
await identityRequest(`/api/identities/${encodeURIComponent(agentId)}`, { method: 'DELETE' });
|
|
450
434
|
```
|
|
451
435
|
|
|
452
436
|
---
|
|
@@ -508,6 +492,7 @@ npm install -g osuite
|
|
|
508
492
|
osuite # branded welcome and command map
|
|
509
493
|
osuite connect auto # detect the current project and start browser handoff
|
|
510
494
|
osuite doctor # check env, Studio health, runtime, and signature posture
|
|
495
|
+
osuite try # review a fixed local acknowledgement (CLI 2.10.1+)
|
|
511
496
|
osuite status # show the current Studio connection
|
|
512
497
|
osuite init codex # install .codex hook files into the current project
|
|
513
498
|
osuite init claude # install .claude hook files into the current project
|
|
@@ -518,19 +503,26 @@ osuite adapter init acme-erp # scaffold an enterprise custom adapter mapping
|
|
|
518
503
|
osuite adapter test .osuite/adapters/acme-erp.json
|
|
519
504
|
osuite approvals # approval inbox
|
|
520
505
|
osuite review <actionId> # Decision V2 review surface
|
|
521
|
-
osuite approve <actionId> # approve
|
|
506
|
+
osuite approve <actionId> # approve from the CLI where the workspace allows it; otherwise prints the Studio link
|
|
522
507
|
osuite deny <actionId> # deny a specific action
|
|
523
508
|
```
|
|
524
509
|
|
|
525
|
-
For local CLI agents, `osuite connect auto`
|
|
510
|
+
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, use your runtime secret manager or an owner-only, untracked and explicitly ignored project environment file. Do not commit credentials or put them into a broadly readable file. The CLI is intentionally more than an API wrapper:
|
|
526
511
|
- `doctor` tells a developer what is missing before they connect an agent.
|
|
512
|
+
- `try` waits for explicit approval of a synthetic action, prints one fixed local acknowledgement, and records its outcome. It never executes a supplied command or calls an external tool. A stricter workspace denial remains a denial. Missing, denied, expired or ambiguous approval produces no acknowledgement; an uncertain outcome is not retried automatically. Slack/email notifications require workspace configuration.
|
|
527
513
|
- `explain` gives a local CAVA preview before a command reaches OSuite.
|
|
528
514
|
- `adapters` explains the three Runtime Coverage tiers: reference adapters, managed OSuite adapters, and enterprise custom adapters.
|
|
529
515
|
- `adapter init/test` lets an enterprise team map a private runtime event into a CAVA-ready action object before registering it in Studio.
|
|
530
516
|
- `approvals` provides a readable approval inbox instead of raw JSON.
|
|
531
517
|
- `review` renders a PCAA/CAVA/Decision V2 review card with action understanding, evidence confidence, control posture, and score dimensions when present.
|
|
532
518
|
|
|
533
|
-
|
|
519
|
+
Project installation refuses settings or hook paths whose symlinks resolve outside the project's real root, including linked parent directories. Credential storage also refuses any symlink, hardlink or Git-tracked destination; successful POSIX writes use mode `0600` and exact ignore entries. A browser approval alone does not retire the previous runtime credential: the versioned connection protocol waits for durable local storage and acknowledgement. If interrupted, resume the same `osuite connect` command rather than deleting its recovery journal. Manual API keys and other runtime connections are not replaced. 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.
|
|
520
|
+
|
|
521
|
+
`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.
|
|
522
|
+
|
|
523
|
+
Onboarding diagnostics are opt-in: `OSUITE_ONBOARDING_METRICS=1 osuite doctor` reports only the first diagnostic pass/fail result and, when supplied by the installer, its start timestamp. It sends no command text, filesystem paths or diagnostic log. Reconnection or a later passing check does not erase the first failure. Without the opt-in, no diagnostic measurement is sent. Reporting failure never changes the doctor result. Aggregate dashboards distinguish reported samples from all connected agents.
|
|
524
|
+
|
|
525
|
+
When an agent calls `waitForApproval()`, it prints the action ID and replay link to stdout. Approval is rechecked on the next poll; dashboard access and approval authority are still required. An approval does not override a later policy denial or revocation.
|
|
534
526
|
|
|
535
527
|
### Runtime Coverage tiers
|
|
536
528
|
|
|
@@ -564,16 +556,16 @@ It detects `.claude`, creates `.claude/hooks/*`, `.claude/settings.json`, `.clau
|
|
|
564
556
|
|
|
565
557
|
---
|
|
566
558
|
|
|
567
|
-
##
|
|
559
|
+
## Legacy Import Compatibility
|
|
568
560
|
|
|
569
|
-
|
|
561
|
+
`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
562
|
|
|
571
563
|
```javascript
|
|
572
|
-
//
|
|
564
|
+
// Compatibility import for the current client
|
|
573
565
|
import { OSuite } from 'osuite/legacy';
|
|
574
566
|
```
|
|
575
567
|
|
|
576
|
-
|
|
568
|
+
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
569
|
|
|
578
570
|
---
|
|
579
571
|
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { acquireCredentialLock, readCredentialFile, writeCredentialFile } from './credentials.js';
|
|
3
|
+
|
|
4
|
+
const digest = (value) => crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
5
|
+
const isDigest = (value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
|
6
|
+
const isTime = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
7
|
+
|
|
8
|
+
function readJournal(cwd, file) {
|
|
9
|
+
const stored = readCredentialFile(cwd, file);
|
|
10
|
+
if (stored === null) return { version: 2, attempts: [] };
|
|
11
|
+
const journal = JSON.parse(stored);
|
|
12
|
+
const credentials = new Set();
|
|
13
|
+
if (journal?.version !== 2 || !Array.isArray(journal.attempts) || journal.attempts.length > 128) throw new Error('Invalid measurement journal');
|
|
14
|
+
for (const attempt of journal.attempts) {
|
|
15
|
+
if (!attempt || !isDigest(attempt.credential) || credentials.has(attempt.credential)
|
|
16
|
+
|| !(attempt.scope === null || isDigest(attempt.scope))
|
|
17
|
+
|| !['started', 'finished'].includes(attempt.state) || typeof attempt.reported !== 'boolean'
|
|
18
|
+
|| (attempt.state === 'finished' && typeof attempt.passed !== 'boolean')
|
|
19
|
+
|| (attempt.reported && (attempt.state !== 'finished' || !attempt.scope))
|
|
20
|
+
|| (attempt.install_started_at !== undefined && !isTime(attempt.install_started_at))) throw new Error('Invalid measurement attempt');
|
|
21
|
+
credentials.add(attempt.credential);
|
|
22
|
+
}
|
|
23
|
+
return journal;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Opt-in only. Reconnection and a later successful doctor must not erase a first failure.
|
|
27
|
+
export async function runDoctorWithMeasurement(run, {
|
|
28
|
+
config, cwd = process.cwd(), env = process.env, fetchImpl = fetch,
|
|
29
|
+
emit = () => {},
|
|
30
|
+
} = {}) {
|
|
31
|
+
if (env.OSUITE_ONBOARDING_METRICS !== '1') return run();
|
|
32
|
+
emit('Opt-in diagnostics: only the first pass/fail result and optional installer timestamp are reported; no commands or local paths.');
|
|
33
|
+
let journal; let file; let attempt; let baseUrl; let apiKey; let agentId; let release; let first = false;
|
|
34
|
+
const unlock = () => { try { release?.(); } catch { /* Measurement cleanup must not change the doctor's result. */ } };
|
|
35
|
+
const save = () => writeCredentialFile(cwd, file, `${JSON.stringify(journal)}\n`);
|
|
36
|
+
try {
|
|
37
|
+
const url = new URL(config?.baseUrl);
|
|
38
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash
|
|
39
|
+
|| typeof config?.apiKey !== 'string' || !config.apiKey.trim()
|
|
40
|
+
|| typeof config?.agentId !== 'string' || !config.agentId.trim()) throw new Error('Connected runtime required');
|
|
41
|
+
baseUrl = url.href.replace(/\/$/, ''); apiKey = config.apiKey.trim(); agentId = config.agentId;
|
|
42
|
+
file = `.osuite/diagnostics/v2-${digest([baseUrl, agentId])}.json`;
|
|
43
|
+
release = acquireCredentialLock(cwd, file);
|
|
44
|
+
// Old state has no credential/workspace binding. Never guess its tenant.
|
|
45
|
+
for (const base of new Set([config.baseUrl, baseUrl])) {
|
|
46
|
+
if (readCredentialFile(cwd, `.osuite/diagnostics/${digest([base, agentId])}.json`) !== null) throw new Error('Unscoped legacy measurement');
|
|
47
|
+
}
|
|
48
|
+
journal = readJournal(cwd, file);
|
|
49
|
+
const credential = digest(apiKey);
|
|
50
|
+
attempt = journal.attempts.find((value) => value.credential === credential);
|
|
51
|
+
if (!attempt) {
|
|
52
|
+
if (journal.attempts.length >= 128) throw new Error('Measurement journal is full');
|
|
53
|
+
attempt = { credential, scope: null, state: 'started', reported: false,
|
|
54
|
+
...(isTime(env.OSUITE_INSTALL_STARTED_AT) ? { install_started_at: env.OSUITE_INSTALL_STARTED_AT } : {}) };
|
|
55
|
+
journal.attempts.push(attempt);
|
|
56
|
+
save();
|
|
57
|
+
first = true;
|
|
58
|
+
}
|
|
59
|
+
} catch {
|
|
60
|
+
unlock();
|
|
61
|
+
emit('Diagnostic measurement is unavailable; the doctor check will still run.');
|
|
62
|
+
return run();
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
let verified = false;
|
|
66
|
+
try {
|
|
67
|
+
const response = await fetchImpl(`${baseUrl}/api/onboarding/measurement`, {
|
|
68
|
+
method: 'GET', redirect: 'error', signal: AbortSignal.timeout(3000), headers: { 'x-api-key': apiKey },
|
|
69
|
+
});
|
|
70
|
+
if (!response.ok) throw new Error('Identity unavailable');
|
|
71
|
+
const identity = await response.json();
|
|
72
|
+
if (identity?.version !== 1 || typeof identity.org_id !== 'string' || !identity.org_id.trim()
|
|
73
|
+
|| identity.org_id.length > 256 || identity.agent_id !== agentId) throw new Error('Identity mismatch');
|
|
74
|
+
const scope = digest([baseUrl, identity.org_id, identity.agent_id]);
|
|
75
|
+
if (attempt.scope && attempt.scope !== scope) throw new Error('Credential identity changed');
|
|
76
|
+
attempt.scope = scope;
|
|
77
|
+
save();
|
|
78
|
+
verified = true;
|
|
79
|
+
} catch {
|
|
80
|
+
emit('Diagnostic identity is unverified; the first result will remain local and unmeasured.');
|
|
81
|
+
}
|
|
82
|
+
const result = await run();
|
|
83
|
+
try {
|
|
84
|
+
if (first) {
|
|
85
|
+
attempt.state = 'finished'; attempt.passed = result === true;
|
|
86
|
+
save();
|
|
87
|
+
}
|
|
88
|
+
if (!verified) return result;
|
|
89
|
+
const index = journal.attempts.findIndex((value) => value.scope === attempt.scope);
|
|
90
|
+
const original = journal.attempts[index];
|
|
91
|
+
// A rotated but unresolved earlier credential might belong to this cohort.
|
|
92
|
+
// Keep the sample unavailable until that binding can actually be verified.
|
|
93
|
+
if (journal.attempts.slice(0, index).some((value) => value.scope === null)) {
|
|
94
|
+
emit('An earlier diagnostic identity is unresolved; no later result was reported as first.');
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
if (original.state !== 'finished' || original.reported) return result;
|
|
98
|
+
const payload = {
|
|
99
|
+
version: 1, event: 'doctor_first_result', passed: original.passed,
|
|
100
|
+
source: original.install_started_at ? 'installer' : 'manual_cli',
|
|
101
|
+
...(original.install_started_at ? { install_started_at: original.install_started_at } : {}),
|
|
102
|
+
};
|
|
103
|
+
const response = await fetchImpl(`${baseUrl}/api/onboarding/measurement`, {
|
|
104
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(3000),
|
|
105
|
+
headers: { 'content-type': 'application/json', 'x-api-key': apiKey }, body: JSON.stringify(payload),
|
|
106
|
+
});
|
|
107
|
+
if (response.ok) { original.reported = true; save(); }
|
|
108
|
+
else emit('The first diagnostic result is retained locally; it was not acknowledged by Studio.');
|
|
109
|
+
} catch {
|
|
110
|
+
emit('The first diagnostic result is retained locally; reporting failed without changing the check result.');
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
} finally {
|
|
114
|
+
unlock();
|
|
115
|
+
}
|
|
116
|
+
}
|