osuite 2.10.2 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+ # Native Tool Compatibility And Recovery
2
+
3
+ This opt-in API is introduced in 2.11.0; it is not part of 2.10.2. Confirm the
4
+ chosen version with `npm view osuite@2.11.0 version` before installing. A source
5
+ checkout alone does not establish npm availability or server compatibility;
6
+ consult the verified release record before enabling it for a workspace.
7
+
8
+ `osuite/governed-tools` is ESM and requires **Node 24 on POSIX**. It uses built-in
9
+ SQLite; it adds no production dependency. Existing `osuite` imports, CommonJS,
10
+ CLI, advisory MCP tools and Hook support are unchanged. Nothing is installed or
11
+ activated in a host by importing it.
12
+
13
+ ## What Changes In An Application
14
+
15
+ Keep your native tool name, JSON arguments, callback and successful result.
16
+ Configure a trusted mapping and a private journal once; give each business
17
+ operation a stable ID. The wrapper calls the original callback only after
18
+ current Studio admission. It does not ask the model to use a different tool.
19
+
20
+ Provision a new journal deliberately: construct once with
21
+ `initializeJournal: true`, then close it without running a tool. Normal
22
+ application starts use `false` (the default). A missing or uninitialized journal
23
+ then fails rather than quietly recreating operation history. Never leave the
24
+ initialization flag enabled as a restart/recovery shortcut.
25
+
26
+ ```js
27
+ import { createGovernedTools } from 'osuite/governed-tools';
28
+
29
+ const tools = createGovernedTools({
30
+ config: {
31
+ baseUrl: process.env.OSUITE_BASE_URL,
32
+ orgId: process.env.OSUITE_ORG_ID,
33
+ agentId: process.env.OSUITE_AGENT_ID,
34
+ runtimeId: 'sdk',
35
+ provider: 'sdk',
36
+ apiKey: process.env.OSUITE_API_KEY,
37
+ privateKeyBase64: process.env.OSUITE_PRIVATE_KEY_BASE64,
38
+ mode: 'enforce',
39
+ signatureMode: 'required',
40
+ guardFailureMode: 'block',
41
+ },
42
+ namespace: 'billing-service',
43
+ journalPath: '/absolute/private-directory/billing.sqlite',
44
+ initializeJournal: false,
45
+ bindings: {
46
+ 'ledger.append': {
47
+ revision: 'ledger-mapping-1',
48
+ describe: args => ({
49
+ action_type: 'api',
50
+ declared_goal: 'Append the specified billing ledger record',
51
+ systems_touched: ['billing-ledger'],
52
+ reversible: false,
53
+ input_summary: { target: args.target, amount: args.amount },
54
+ }),
55
+ },
56
+ },
57
+ });
58
+
59
+ try {
60
+ const result = await tools.run(
61
+ job.operationId,
62
+ { name: 'ledger.append', arguments: job.arguments },
63
+ ({ arguments: args }) => ledger.append(args),
64
+ { waitMs: 30000, signal: abortController.signal },
65
+ );
66
+ // The actual ledger result, not an OSuite-generated substitute.
67
+ consumeNativeResult(result);
68
+ } catch (error) {
69
+ if (error.code === 'AWAITING_APPROVAL') {
70
+ showExistingReview(error.status.actionId, error.status.reviewUrl);
71
+ // Resume this same operation later; do not create a replacement ID.
72
+ } else {
73
+ showExplicitFailure(error.code, error.status);
74
+ }
75
+ } finally {
76
+ tools.close();
77
+ }
78
+ ```
79
+
80
+ The description is an application-maintained semantic mapping, **not authority**.
81
+ Validate it against the real tool implementation. Include the consequential
82
+ target, operation, destination, amount/data boundary and relevant constraints;
83
+ the sample is not a universal banking policy. A signature proves who supplied
84
+ the mapping, not that the mapping is semantically complete. Studio still owns
85
+ the allow/hold/deny decision. Do not put secrets in `input_summary`: that bounded
86
+ description is sent to Studio even though full native arguments stay local.
87
+
88
+ Use a separately enrolled SDK/MCP identity with a current signing key. A Hook
89
+ credential is not interchangeable with an SDK credential. The new `sdk`/`mcp`
90
+ posture endpoint must be deployed server-side. Older servers fail explicitly;
91
+ there is no unsigned, offline, observe-mode or raw-client fallback. A configured
92
+ mandatory scoped policy is never ignored to make this wrapper work.
93
+ This profile does not implement assumption-capture workflows; a posture that
94
+ requires them is refused rather than silently reported as satisfied. Posture
95
+ is current client configuration, not a resource capability or proof that every
96
+ unsigned request to the server is prohibited. Actual signed action responses
97
+ and fresh admission are checked separately.
98
+
99
+ ## Connected MCP Client
100
+
101
+ ```js
102
+ import { wrapMcpClient } from 'osuite/governed-tools';
103
+ const governed = wrapMcpClient(alreadyConnectedMcpClient, tools);
104
+ const result = await governed.operation(job.operationId).callTool(
105
+ { name: 'ledger.append', arguments: job.arguments },
106
+ nativeResultSchema,
107
+ { signal: abortController.signal, timeout: 10000 },
108
+ );
109
+ ```
110
+
111
+ The supplied client's receiver, schema, allowed options and original returned
112
+ result are preserved. Its timeout is the native call timeout, not a new approval
113
+ wait budget. The adapter defaults to returning a held status promptly; invoke
114
+ the same operation after review. `governed.status(id)` reads existing status and
115
+ never executes or redeems an approval.
116
+
117
+ This bounded profile supports ordinary `callTool` with explicit `name` and
118
+ object `arguments`, and only `signal` / `timeout` options. Names and operation
119
+ IDs are 1-128 ASCII identifier characters (`A-Z`, `a-z`, digits, `_`, `.`, `-`),
120
+ must start with an alphanumeric character or `_`, and cannot contain `..`.
121
+ Inputs must be lossless JSON, at most 32 KiB, depth 16 and 8,192 nodes. Unsupported
122
+ accessors, proxy objects and prototype-sensitive keys (`__proto__`, `prototype`,
123
+ `constructor`) are rejected even when a native client might accept them.
124
+ Unsupported
125
+ metadata, tasks, streams, progress callbacks and arbitrary MCP requests are
126
+ rejected, not silently stripped. OAuth, discovery and connection setup remain
127
+ with your existing MCP client. This is not a universal MCP gateway certification.
128
+
129
+ ## Recovery Contract
130
+
131
+ An operation ID means one business intention, not equality of arguments or a
132
+ JSON-RPC request number. Persist it in your existing job record. Different IDs
133
+ with identical arguments remain different legitimate operations. Reusing an ID
134
+ with changed input or mapping is a conflict. Changing the namespace or identity
135
+ creates a different scope: never use that as a recovery shortcut.
136
+
137
+ | State / error | Required application behavior |
138
+ | --- | --- |
139
+ | `AWAITING_APPROVAL` | Show the existing review; resume the same ID and exact input. |
140
+ | `ALREADY_COMPLETED` | Do not execute again. Load business output from your own store. |
141
+ | `OPERATION_BUSY` | Another caller owns the transition; read status, do not invent an ID. |
142
+ | `OUTCOME_UNKNOWN` | Inspect the resource separately; do not automatically resend. |
143
+ | `POLICY_DENIED` / expiry / cancellation | Respect the terminal refusal. A new intention needs explicit operator action. |
144
+ | `CURRENT_AUTHORITY_UNAVAILABLE` | Restore current server/identity configuration; never fall back to ungoverned execution. |
145
+ | `JOURNAL_MISSING` / invalid journal | Restore the correct durable journal; do not initialize an empty replacement to replay old IDs. |
146
+ | `ABORTED` | The local waiter stopped. This does not revoke approval or undo a dispatched effect. |
147
+
148
+ Restart can resume a held review. It cannot infer that a request was not sent
149
+ from a timeout, missing response, crashed process, or lost completion report.
150
+ Only an exact server record that is still pending can repair an uncertain
151
+ initial creation into a held state. Redemption/dispatch fences are not reset.
152
+ A successful GET showing approval is not a grant to send: a fresh signed POST
153
+ must validate and redeem the original request.
154
+
155
+ There is no distributed transaction with an arbitrary SaaS. The journal commits
156
+ the dispatch fence before invoking the callback. This prevents automatic local
157
+ resend but can leave a request uncertain if the process dies between those two
158
+ steps. Third-party resource reconciliation and business idempotency remain
159
+ application responsibilities. A new machine must retain the same journal and
160
+ scope; deleting or restoring an old journal is not supported recovery.
161
+
162
+ ## Results And Storage
163
+
164
+ Successful native output is returned unchanged and is **not persisted**. A later
165
+ duplicate cannot reconstruct it. The journal stores bounded IDs, commitments,
166
+ states and an optional result digest. Opaque/non-JSON native returns can have a
167
+ null digest; neither a return nor a digest is independent resource verification.
168
+ MCP `isError: true` is returned unchanged but leaves the operation uncertain,
169
+ since native errors can occur after partial effects. Exceptions are sanitized;
170
+ arbitrary error strings, credentials and full outputs are not stored.
171
+
172
+ Outcome reporting is separate. If Studio loses the reporting acknowledgement,
173
+ the native result remains the return value and `reportState` is `uncertain`.
174
+ Do not replay the tool to repair a report. `close()` prevents new work; an
175
+ already-started native call is allowed to record its outcome before SQLite closes.
176
+
177
+ Use an owner-only directory and a durable local filesystem. Unsafe ownership,
178
+ permissions, symlinks/hardlinks and invalid database paths are rejected. SQLite
179
+ uses transactional CAS and full durability. The default limit is 10,000 retained
180
+ operations; exhaustion stops new work. Normal opening never creates a missing
181
+ database. Explicit initialization is a provisioning action, not recovery.
182
+ Do not delete completed or unknown rows
183
+ to make room: they are replay tombstones. Plan scoped lifecycle/retention with
184
+ the operator, retain the WAL correctly, and never share this database over an
185
+ unqualified network filesystem. Windows ACL qualification is not included.
186
+
187
+ ## Honest Coverage And Cost
188
+
189
+ Status reports `coverage: wrapped-call-only` and
190
+ `admissionPath: studio-current-action`. The raw client, alternative credentials,
191
+ direct resource access and a compromised application can bypass this wrapper.
192
+ It is not a resource-side enforcement boundary or a ZeroGate Action Pass path.
193
+ There is no claim that old Azure gate latency applies here. Current posture,
194
+ guard/action requests, durable writes and reporting all have real costs.
195
+ Studio responses are bounded to 1 MiB; larger responses refuse admission rather
196
+ than silently dropping evidence. Short configuration-cache contention can cause
197
+ bounded fresh configuration reads (at most six), never a repeated action POST
198
+ or tool invocation. A persistent cache lock is not removed automatically.
199
+
200
+ Production gateway deployment requires separate resource IAM, credentials,
201
+ network fencing, availability and recovery qualification. This release does not
202
+ enable Hook, modify the existing ZeroGate/Matoi algorithms or deploy that gateway.
package/README.md CHANGED
@@ -1,9 +1,13 @@
1
- # OSuite SDK (v2.10.2 Release Candidate)
1
+ # OSuite SDK (v2.11.0)
2
2
 
3
3
  **Governed action SDK for AI agents.**
4
4
 
5
5
  The OSuite SDK helps teams route approvals, record governed decisions, and produce replayable evidence for AI agent activity.
6
6
 
7
+ The opt-in Node 24 `osuite/governed-tools` entry preserves native tool calls
8
+ and adds durable approval recovery. See [Native Tool Compatibility](GOVERNED_TOOLS.md).
9
+ It is not in the published 2.10.2 package and does not enable Hook or a gateway.
10
+
7
11
  ## Installation
8
12
 
9
13
  ### Node.js
@@ -13,7 +17,7 @@ npm install osuite
13
17
 
14
18
  ### Connect And Verify
15
19
 
16
- For the checked-out 2.10.2 candidate source, run from the project you want to connect:
20
+ For a checked-out SDK source tree, run from the project you want to connect:
17
21
 
18
22
  ```bash
19
23
  node /absolute/path/to/osuite-sdk/sdk/cli.js connect
@@ -21,11 +25,11 @@ node /absolute/path/to/osuite-sdk/sdk/cli.js doctor
21
25
  node /absolute/path/to/osuite-sdk/sdk/cli.js try
22
26
  ```
23
27
 
24
- After the owner publishes 2.10.2 to npm, the equivalent pinned command is
25
- `npx osuite@2.10.2 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
- installation-identity or acknowledged-recovery behavior. npm's latest was 2.10.1
28
- when checked on 2026-10-22; this checkout is not a registry publication.
28
+ For this version, use `npx osuite@2.11.0 connect` after confirming availability
29
+ with `npm view osuite@2.11.0 version`. A source checkout or this document alone
30
+ does not establish registry publication, and npm's `latest` may differ from the
31
+ checked-out version. The stable credential-recovery behavior and the new
32
+ native-call operation journal are different mechanisms.
29
33
 
30
34
  The alternative installer follows npm's published `latest`:
31
35
 
@@ -61,7 +65,9 @@ Slack and email notifications require configured workspace channels.
61
65
 
62
66
  ## The Governance Loop
63
67
 
64
- The SDK transports requests; it does not execute your tool. A guard evaluation or
68
+ The default SDK transports requests; it does not execute your tool. The opt-in
69
+ native-tool wrapper invokes only the callback explicitly supplied to it.
70
+ A guard evaluation or
65
71
  `waitForApproval()` result is not execution authorization on its own. A secure
66
72
  integration must preserve all four steps:
67
73
 
@@ -535,7 +541,7 @@ identity; use an explicit new `--agent-id` if retaining the old project director
535
541
  Preserve historical records and signing keys instead of reassigning past actions
536
542
  to the replacement. A client-side installation ID is not permission to rotate.
537
543
 
538
- ### SDK and MCP Credential Separation (2.10.2 Candidate)
544
+ ### SDK and MCP Credential Separation (Since 2.10.2)
539
545
 
540
546
  SDK connections use `.osuite/.env`; MCP connections use `.osuite/mcp/.env`.
541
547
  Their installation metadata and recovery journals live beside their respective
@@ -559,8 +565,8 @@ rather than deleting its marker or copying credentials. Update the MCP launcher'
559
565
  credential-file reference to `.osuite/mcp/.env` before restarting it or creating an
560
566
  SDK connection. The command does not rewrite vendor launchers or enable hooks.
561
567
 
562
- This section describes the unpublished 2.10.2 candidate. Do not use a previous
563
- published CLI version to perform the new migration.
568
+ Use version 2.10.2 or newer for this credential migration. It does not install or
569
+ activate the separate native-tool execution wrapper.
564
570
 
565
571
  `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.
566
572
 
@@ -0,0 +1,134 @@
1
+ import path from 'node:path';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { canonicalJson, createApiClient } from '../runtime/protocol.mjs';
4
+ import { resolveRemotePosture } from '../runtime/posture.mjs';
5
+ import { createStateStore } from '../runtime/state.mjs';
6
+ import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
7
+ import { matchesStoredAction, reject } from './contract.mjs';
8
+
9
+ export function createStudioAuthority(config, journalPath) {
10
+ const responseLimits = { maxResponseBytes: 1048576 };
11
+ const baseApi = createApiClient(config, responseLimits);
12
+ const store = createStateStore({ ...config, stateDir: path.join(path.dirname(journalPath), 'posture') });
13
+
14
+ async function current(aborted) {
15
+ let remote;
16
+ const deadline = performance.now() + 2000;
17
+ for (let attempt = 0; attempt < 6; attempt++) {
18
+ if (aborted()) reject('ABORTED');
19
+ let readStatus = null;
20
+ remote = await resolveRemotePosture(config, { store, api: { async request(method, endpoint, ...args) {
21
+ const response = await baseApi.request(method, endpoint, ...args);
22
+ if (method === 'GET') readStatus = response.status;
23
+ return response;
24
+ } } });
25
+ if (remote.source === 'remote' || readStatus !== 200 || attempt === 5 || performance.now() >= deadline) break;
26
+ // A concurrent cache writer can supersede a valid response or hold its
27
+ // short lock. Reread current configuration, never replay an action POST.
28
+ await delay(10 * (attempt + 1));
29
+ }
30
+ const pinned = config.ruleRollout, actual = remote.ruleRollout;
31
+ const preservesConfiguredFloor = !pinned?.enabled || (actual?.enabled === true
32
+ && canonicalJson(actual.scope) === canonicalJson(pinned.scope)
33
+ && actual.credential_id === pinned.credential_id
34
+ && actual.connection_generation >= pinned.connection_generation && actual.version >= pinned.version
35
+ && (actual.version !== pinned.version || canonicalJson(actual) === canonicalJson(pinned)));
36
+ if (!remote.available || remote.blocked || remote.source !== 'remote'
37
+ || !preservesConfiguredFloor
38
+ || !['enforce', 'strict'].includes(remote.posture.mode)
39
+ || remote.posture.require_assumption_capture !== false
40
+ || remote.posture.require_signature !== true || remote.posture.on_guard_unavailable !== 'block') {
41
+ reject('CURRENT_AUTHORITY_UNAVAILABLE');
42
+ }
43
+ const effective = { ...config, mode: remote.posture.mode, guardFailureMode: 'block', signatureMode: 'required',
44
+ approvalWaitMs: 0, ruleRollout: remote.ruleRollout };
45
+ return { api: createApiClient(effective, responseLimits), effective };
46
+ }
47
+
48
+ async function read(record) {
49
+ const response = await baseApi.request('GET', `/api/actions/${encodeURIComponent(record.actionId)}`);
50
+ if (!response.ok) return { available: false, status: response.status };
51
+ if (!matchesStoredAction(response.body, record, config)) return { available: false, status: response.status, mismatch: true };
52
+ return { available: true, body: response.body, action: response.body.action || response.body };
53
+ }
54
+
55
+ async function admit(invocation, journal, owner, aborted) {
56
+ const record = journal.get(invocation.record.scope, invocation.record.operationId);
57
+ const phase = record.state === 'held' ? 'redeeming' : 'requesting';
58
+ const { api, effective } = await current(aborted);
59
+ if (aborted()) reject('ABORTED');
60
+ const session = await api.request('POST', '/api/runtime-sessions', {
61
+ runtime_session_id: record.sessionId, agent_id: config.agentId, runtime_adapter_id: config.runtimeId,
62
+ runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper', client_name: 'osuite/governed-tools',
63
+ governance_posture: effective.mode, signature_mode: 'required', status: 'active',
64
+ });
65
+ const actualSession = session.body?.session || session.body?.runtime_session;
66
+ if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
67
+ || actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
68
+ || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE');
69
+ let claimed = false, receivedAt = null;
70
+ const claim = () => {
71
+ if (claimed) reject('OUTCOME_UNKNOWN');
72
+ if (aborted()) reject('ABORTED');
73
+ if (!journal.claim(record.scope, record.operationId, [record.state], phase, owner)) reject('OPERATION_BUSY');
74
+ claimed = true;
75
+ };
76
+ const settle = (state, patch = {}) => journal.settle(record.scope, record.operationId, owner, phase, state, patch);
77
+ try {
78
+ const result = await admitAction(invocation.context, {
79
+ config: effective,
80
+ api: { async request(method, endpoint, body, options) {
81
+ if (aborted()) reject('ABORTED');
82
+ if (method === 'POST' && endpoint === '/api/actions') claim();
83
+ const response = await api.request(method, endpoint, body, options);
84
+ if (method === 'POST' && endpoint === '/api/actions') {
85
+ receivedAt = performance.now();
86
+ if (!response.ok || !matchesStoredAction(response.body, record, config)
87
+ || !cavaFingerprint(response.body)) {
88
+ settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
89
+ reject('OUTCOME_UNKNOWN');
90
+ }
91
+ }
92
+ return response;
93
+ } },
94
+ beforeRelease: async payload => {
95
+ if (aborted() || !matchesStoredAction(payload, record, config)) return false;
96
+ // A held operation must redeem its original one-use grant, even when
97
+ // a current guard decision has become less restrictive meanwhile.
98
+ return phase !== 'redeeming' || (Boolean(record.fingerprint) && actionAdmission(payload, 'require_approval', invocation.context,
99
+ { actionId: record.actionId, fingerprint: record.fingerprint }).authorized);
100
+ },
101
+ });
102
+ if (result.authorized) return { phase, receivedAt, response: result.response };
103
+ if (result.reason === 'policy_block') {
104
+ if (!claimed) claim();
105
+ settle('denied'); reject('POLICY_DENIED');
106
+ }
107
+ if (result.decision === 'require_approval' && result.response?.action?.status === 'pending_approval') {
108
+ if (!settle('held', { fingerprint: cavaFingerprint(result.response) })) reject('OUTCOME_UNKNOWN');
109
+ return null;
110
+ }
111
+ if (claimed) settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
112
+ reject(claimed ? 'OUTCOME_UNKNOWN' : 'CURRENT_AUTHORITY_UNAVAILABLE');
113
+ } catch (error) {
114
+ if (claimed) settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
115
+ throw error;
116
+ }
117
+ }
118
+
119
+ async function report(record, state, resultDigest) {
120
+ const response = await baseApi.request('PATCH', `/api/actions/${encodeURIComponent(record.actionId)}`, {
121
+ status: state === 'completed' ? 'completed' : 'failed',
122
+ timestamp_end: new Date().toISOString(),
123
+ output_summary: JSON.stringify({ schema_version: 'osuite.native_tool_observation.v1',
124
+ observation: state === 'completed' ? 'native_return' : 'outcome_unknown',
125
+ result_digest: resultDigest, result_retained: false, independent_resource_verification: false }),
126
+ ...(state === 'uncertain' ? { error_message: 'Native call outcome is uncertain; no automatic resend.' } : {}),
127
+ });
128
+ return response.ok && matchesStoredAction(response.body, record, config)
129
+ && response.body.action?.status === (state === 'completed' ? 'completed' : 'failed')
130
+ && typeof response.body.action?.timestamp_end === 'string';
131
+ }
132
+
133
+ return { admit, read, report };
134
+ }
@@ -0,0 +1,142 @@
1
+ import { types } from 'node:util';
2
+ import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
3
+
4
+ export const CALL_SCHEMA = 'osuite.native_tool_call.v1';
5
+ export const COVERAGE = 'wrapped-call-only';
6
+ export const ADMISSION_PATH = 'studio-current-action';
7
+ const unsafeKeys = new Set(['__proto__', 'prototype', 'constructor']);
8
+ const id = value => safeId(value) && value.length <= 128;
9
+
10
+ export class GovernedToolError extends Error {
11
+ constructor(code, status = null) {
12
+ super(`OSuite ${code}: no automatic repeat of this operation.`);
13
+ this.name = 'GovernedToolError';
14
+ this.code = code;
15
+ this.status = status;
16
+ this.retryAutomatically = false;
17
+ }
18
+ }
19
+ export function reject(code, status) { throw new GovernedToolError(code, status); }
20
+
21
+ // Validate descriptors before reading values: JSON.stringify alone can invoke
22
+ // accessors/toJSON or quietly change undefined, non-finite numbers and arrays.
23
+ export function jsonSnapshot(input, maxBytes = 65536) {
24
+ const ancestors = new Set();
25
+ let nodes = 0;
26
+ function copy(value, depth) {
27
+ if (++nodes > 8192 || depth > 16) reject('INVALID_INPUT');
28
+ if (value === null || typeof value === 'boolean') return value;
29
+ if (typeof value === 'string') {
30
+ if (value.length > maxBytes || !value.isWellFormed()) reject('INVALID_INPUT');
31
+ return value;
32
+ }
33
+ if (typeof value === 'number') {
34
+ if (!Number.isFinite(value) || Object.is(value, -0)) reject('INVALID_INPUT');
35
+ return value;
36
+ }
37
+ if (typeof value !== 'object' || types.isProxy(value) || ancestors.has(value)) reject('INVALID_INPUT');
38
+ const array = Array.isArray(value), prototype = Object.getPrototypeOf(value);
39
+ if (prototype !== (array ? Array.prototype : Object.prototype) && !(prototype === null && !array)) reject('INVALID_INPUT');
40
+ const descriptors = Object.getOwnPropertyDescriptors(value);
41
+ const keys = Reflect.ownKeys(descriptors);
42
+ if (keys.some(key => typeof key !== 'string' || unsafeKeys.has(key)
43
+ || !Object.hasOwn(descriptors[key], 'value') || (!descriptors[key].enumerable && !(array && key === 'length')))) reject('INVALID_INPUT');
44
+ if (array && (value.length > 8192 || keys.length !== value.length + 1
45
+ || keys.some(key => key !== 'length' && !/^(0|[1-9][0-9]*)$/.test(key)))) reject('INVALID_INPUT');
46
+ ancestors.add(value);
47
+ const result = array ? [] : {};
48
+ for (const key of keys) {
49
+ if (array && key === 'length') continue;
50
+ if (!key.isWellFormed()) reject('INVALID_INPUT');
51
+ result[key] = copy(descriptors[key].value, depth + 1);
52
+ }
53
+ ancestors.delete(value);
54
+ return Object.freeze(result);
55
+ }
56
+ const snapshot = copy(input, 0);
57
+ if (Buffer.byteLength(canonicalJson(snapshot)) > maxBytes) reject('INVALID_INPUT');
58
+ return snapshot;
59
+ }
60
+
61
+ export function scopeFor(config, namespace) {
62
+ const base = validatedBaseUrl(config?.baseUrl);
63
+ if (!base || !id(config.orgId) || !id(config.agentId) || !id(config.runtimeId) || !id(namespace)
64
+ || (config.provider != null && !id(config.provider))) reject('INVALID_CONFIGURATION');
65
+ return sha256(canonicalJson({ origin: base, org: config.orgId, agent: config.agentId,
66
+ runtime: config.runtimeId, provider: config.provider || null, namespace }));
67
+ }
68
+
69
+ const strings = { action_type: 128, declared_goal: 2000, authorization_scope: 1000,
70
+ data_classification: 64, data_residency_region: 128 };
71
+ const booleans = new Set(['reversible', 'privacy_review_required', 'data_minimization_declared', 'cross_border_transfer']);
72
+ const numbers = new Set(['risk_score', 'personal_data_likelihood']);
73
+ const arrays = new Set(['systems_touched', 'sensitive_data_categories', 'external_data_processors']);
74
+ const allowed = new Set([...Object.keys(strings), ...booleans, ...numbers, ...arrays, 'input_summary']);
75
+
76
+ function describe(binding, args) {
77
+ let value;
78
+ try { value = jsonSnapshot(binding.describe(args), 6000); } catch { reject('INVALID_MAPPING'); }
79
+ if (!value || Array.isArray(value) || typeof value !== 'object'
80
+ || Object.keys(value).some(key => !allowed.has(key)) || !value.action_type || !value.declared_goal) reject('INVALID_MAPPING');
81
+ for (const [key, item] of Object.entries(value)) {
82
+ if (strings[key] && (typeof item !== 'string' || !item.trim() || item.length > strings[key])) reject('INVALID_MAPPING');
83
+ if (booleans.has(key) && typeof item !== 'boolean') reject('INVALID_MAPPING');
84
+ if (numbers.has(key) && (!Number.isSafeInteger(item) || item < 0 || item > 100)) reject('INVALID_MAPPING');
85
+ if (arrays.has(key) && (!Array.isArray(item) || item.length > 20
86
+ || item.some(entry => typeof entry !== 'string' || entry.length > 500))) reject('INVALID_MAPPING');
87
+ }
88
+ if (value.input_summary !== undefined && (!value.input_summary || Array.isArray(value.input_summary)
89
+ || typeof value.input_summary !== 'object' || Object.hasOwn(value.input_summary, 'osuite_native_call'))) reject('INVALID_MAPPING');
90
+ return value;
91
+ }
92
+
93
+ export function makeInvocation({ config, namespace, bindings, operationId, params }) {
94
+ const scope = scopeFor(config, namespace);
95
+ if (!id(operationId)) reject('INVALID_OPERATION_ID');
96
+ const native = jsonSnapshot(params, 32768);
97
+ if (!native || Array.isArray(native) || !id(native.name) || !Object.hasOwn(native, 'arguments')
98
+ || Object.keys(native).some(key => !['name', 'arguments'].includes(key))) reject('INVALID_INPUT');
99
+ if (!bindings || !Object.hasOwn(bindings, native.name)) reject('UNSUPPORTED_TOOL');
100
+ const binding = bindings[native.name];
101
+ if (!binding || !id(binding.revision) || typeof binding.describe !== 'function') reject('INVALID_MAPPING');
102
+ const description = describe(binding, native.arguments);
103
+ // The historical Hook helper normalizes null to {}. Native calls must retain
104
+ // every JSON value exactly, including that distinction.
105
+ const inputDigest = sha256(canonicalJson({ tool_name: native.name, tool_input: native.arguments }));
106
+ const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description }));
107
+ const identity = sha256(canonicalJson([scope, operationId]));
108
+ const actionId = `act_${identity}`, sessionId = `sess_${identity}`, toolUseId = `tool_${identity}`;
109
+ const marker = { schema_version: CALL_SCHEMA, operation_digest: sha256(operationId), input_digest: inputDigest, binding_digest: bindingDigest };
110
+ const inputSummary = JSON.stringify({ ...description.input_summary, osuite_native_call: marker });
111
+ if (inputSummary.length > 4000) reject('INVALID_MAPPING');
112
+ const context = jsonSnapshot({ ...description, input_summary: inputSummary, action_id: actionId,
113
+ agent_id: config.agentId, runtime_session_id: sessionId, tool_use_id: toolUseId,
114
+ tool_input_digest: inputDigest, runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper' });
115
+ return Object.freeze({ params: native, context, marker, record: Object.freeze({ scope, operationId,
116
+ inputDigest, bindingDigest, contextDigest: sha256(canonicalJson(context)), actionId, sessionId, toolUseId }) });
117
+ }
118
+
119
+ export function matchesStoredAction(payload, record, config) {
120
+ try {
121
+ const action = payload?.action || payload;
122
+ const summary = typeof action?.input_summary === 'string' ? JSON.parse(action.input_summary) : action?.input_summary;
123
+ const marker = summary?.osuite_native_call;
124
+ const envelope = action?.action_envelope;
125
+ return action?.action_id === record.actionId && action.agent_id === config.agentId
126
+ && action.org_id === config.orgId && action.verified === true
127
+ && (!payload.action_id || payload.action_id === record.actionId)
128
+ && envelope?.runtime_session_id === record.sessionId
129
+ && marker?.schema_version === CALL_SCHEMA && marker.operation_digest === sha256(record.operationId)
130
+ && marker.input_digest === record.inputDigest && marker.binding_digest === record.bindingDigest;
131
+ } catch { return false; }
132
+ }
133
+
134
+ export function publicStatus(record, baseUrl) {
135
+ if (!record) return null;
136
+ return Object.freeze({ operationId: record.operationId, actionId: record.actionId, state: record.state,
137
+ resultDigest: record.resultDigest || null, reportState: record.reportState,
138
+ reviewUrl: `${baseUrl}/approvals?action=${encodeURIComponent(record.actionId)}`,
139
+ replayUrl: `${baseUrl}/replay/${encodeURIComponent(record.actionId)}`,
140
+ admissionPath: ADMISSION_PATH, coverage: COVERAGE, retryAutomatically: false,
141
+ resultRetained: false });
142
+ }
@@ -0,0 +1,47 @@
1
+ import { createGovernedTools } from '../../governed-tools.mjs';
2
+ import { sha256, canonicalJson, validatedBaseUrl } from '../../runtime/protocol.mjs';
3
+
4
+ const initializeJournal = process.argv.includes('--initialize-journal');
5
+ if (process.argv.includes('--help') || (!process.argv.includes('--execute') && !initializeJournal)) {
6
+ console.log('Native tool example (Node 24). No calls performed.\n'
7
+ + 'To execute one explicitly configured operation, set OSUITE_BASE_URL, OSUITE_ORG_ID, '
8
+ + 'OSUITE_AGENT_ID, OSUITE_API_KEY, OSUITE_PRIVATE_KEY_BASE64, OSUITE_JOURNAL_PATH, '
9
+ + 'NATIVE_TOOL_URL and OPERATION_ID. Provision once with --initialize-journal; '
10
+ + 'later pass --execute to run against the existing journal.\n'
11
+ + 'The target receives one synthetic append; use a dedicated resource you control.');
12
+ } else {
13
+ if (initializeJournal && process.argv.includes('--execute')) throw new Error('Provisioning and execution are separate operations.');
14
+ const url = validatedBaseUrl(process.env.NATIVE_TOOL_URL);
15
+ if (!url) throw new Error('NATIVE_TOOL_URL must be an explicit HTTPS or loopback resource.');
16
+ const tools = createGovernedTools({
17
+ config: { baseUrl: process.env.OSUITE_BASE_URL, orgId: process.env.OSUITE_ORG_ID,
18
+ agentId: process.env.OSUITE_AGENT_ID, runtimeId: 'sdk', provider: 'sdk',
19
+ apiKey: process.env.OSUITE_API_KEY, privateKeyBase64: process.env.OSUITE_PRIVATE_KEY_BASE64,
20
+ mode: 'enforce', signatureMode: 'required', guardFailureMode: 'block' },
21
+ namespace: 'native-example', journalPath: process.env.OSUITE_JOURNAL_PATH, initializeJournal,
22
+ bindings: { 'ledger.append': { revision: 'example-1', describe: args => ({
23
+ action_type: 'api', declared_goal: 'Append one synthetic native-tool example record',
24
+ systems_touched: [url], reversible: false,
25
+ input_summary: { url, method: 'POST', tool_name: 'ledger.append', payload_digest: sha256(canonicalJson(args)) },
26
+ }) } },
27
+ });
28
+ if (initializeJournal) {
29
+ tools.close();
30
+ console.log('Journal provisioned. No tool, network call or host installation performed.');
31
+ } else {
32
+ try {
33
+ await tools.run(process.env.OPERATION_ID,
34
+ { name: 'ledger.append', arguments: { example: true, amount: 3 } },
35
+ async ({ arguments: args }) => {
36
+ const response = await fetch(url, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10000),
37
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify(args) });
38
+ if (!response.ok) throw new Error('Native response was not successful.');
39
+ return response.json();
40
+ });
41
+ console.log(JSON.stringify(await tools.status(process.env.OPERATION_ID)));
42
+ } catch (error) {
43
+ console.error(JSON.stringify({ code: error.code || 'OUTCOME_UNKNOWN', status: error.status || null, retryAutomatically: false }));
44
+ process.exitCode = 1;
45
+ } finally { tools.close(); }
46
+ }
47
+ }