osuite 2.11.2 → 2.12.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,103 @@
1
+ import { createControlledTransfers } from './client.mjs';
2
+ import { CONTROLLED_TRANSFER_PROFILE as PROFILE, ControlledTransferError, fail,
3
+ identifier, record, snapshot } from './contract.mjs';
4
+ import { snapshotWithProjection } from './projection.mjs';
5
+
6
+ const instructions = 'Only the Matoi controlled-ledger transfer profile is covered, not arbitrary MCP tools or direct resource access. '
7
+ + 'Financial transfers require native Studio review on the slow-approved route. Preparation and status never execute. '
8
+ + 'Do not auto-approve or resend mutations. OUTCOME_UNKNOWN requires status-only recovery with the original operation ID. '
9
+ + 'Projection freshness describes only the derived evidence view, never execution authority. '
10
+ + 'A pending, stale, failed or unavailable view does not invalidate a verified receipt or permit resending.';
11
+ const idSchema = { type: 'string', minLength: 1, maxLength: 128, pattern: '^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$' };
12
+ const tool = (name, description, properties, required, readOnly = false) => ({ name, description,
13
+ inputSchema: { type: 'object', properties, required, additionalProperties: false },
14
+ annotations: { readOnlyHint: readOnly, destructiveHint: name === 'osuite_transfer_execute', idempotentHint: readOnly } });
15
+ const tools = snapshot([
16
+ tool('osuite_transfer_prepare', 'Prepare one signed controlled-ledger transfer operation for native Studio review. Never executes or approves.',
17
+ { operationId: idSchema, grantId: idSchema }, ['operationId', 'grantId']),
18
+ tool('osuite_transfer_execute', 'Explicitly request one ordinal of the exact signed preparation. The server enforces native approval; never retry automatically.',
19
+ { prepared: { type: 'object', description: 'The unchanged signed preparation returned by prepare or verified status recovery.' },
20
+ ordinal: { type: 'integer', minimum: 0, maximum: 63, default: 0 } }, ['prepared']),
21
+ tool('osuite_transfer_status', 'Read the original operation and verify available signed evidence. No preparation, approval, execution or automatic retry.',
22
+ { operationId: idSchema }, ['operationId'], true),
23
+ ]);
24
+
25
+ const preparationFields = ['profile', 'operationId', 'grantId', 'preparationDigest', 'actionId', 'fingerprint',
26
+ 'lease', 'effects', 'state', 'code', 'reviewUrl', 'retryAutomatically'];
27
+ const publicFields = [...preparationFields, 'receipt', 'newlyCommitted', 'lastDenial', 'reason', 'httpStatus', 'recovery'];
28
+ const effectFields = ['operation', 'paymentId', 'sourceAccount', 'destination', 'asset', 'network', 'amountMinor', 'decimals'];
29
+ function select(value, keys) {
30
+ return Object.fromEntries(keys.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
31
+ }
32
+
33
+ function publicResult(value, executing) {
34
+ // Do not echo configuration, arbitrary server metadata or caller arguments into the model context.
35
+ const result = select(value, publicFields);
36
+ if (value.effects) result.effects = value.effects.map(effect => select(effect, effect.operation === 'transfer'
37
+ ? effectFields : ['ordinal', 'paymentId', 'state', 'receipt', 'receiptVerified']));
38
+ if (value.prepared) result.prepared = select(value.prepared, preparationFields);
39
+ result.effect_executed = value.state === 'unknown' || value.code === 'OUTCOME_UNKNOWN'
40
+ ? null : executing && value.state === 'committed' && value.newlyCommitted === true;
41
+ result.retryAutomatically = false;
42
+ return snapshotWithProjection({ ...result, projection: value.projection });
43
+ }
44
+
45
+ function response(value, executing = false) {
46
+ const data = publicResult(value, executing);
47
+ return Object.freeze({ content: Object.freeze([Object.freeze({ type: 'text', text: JSON.stringify(data) })]),
48
+ structuredContent: data, ...(['denied', 'unknown', 'rejected'].includes(data.state) ? { isError: true } : {}) });
49
+ }
50
+
51
+ export function createControlledTransferMcpServer(config) {
52
+ const client = createControlledTransfers({ config });
53
+
54
+ async function callTool(name, args = {}) {
55
+ try {
56
+ const definition = tools.find(item => item.name === name);
57
+ if (!definition) fail('UNKNOWN_TOOL');
58
+ args = snapshot(args, 'INVALID_TOOL_ARGUMENTS');
59
+ if (!record(args) || Object.keys(args).some(key => !Object.hasOwn(definition.inputSchema.properties, key))
60
+ || definition.inputSchema.required.some(key => !Object.hasOwn(args, key))) fail('INVALID_TOOL_ARGUMENTS');
61
+ if (name === 'osuite_transfer_execute') {
62
+ if (!record(args.prepared)) fail('INVALID_PREPARATION');
63
+ return response(await client.execute(args.prepared, args.ordinal), true);
64
+ }
65
+ if (!identifier(args.operationId)) fail('INVALID_OPERATION_ID');
66
+ if (name === 'osuite_transfer_prepare') {
67
+ if (!identifier(args.grantId)) fail('INVALID_GRANT_ID');
68
+ return response(await client.prepare(args.operationId, args.grantId));
69
+ }
70
+ return response(await client.status(args.operationId));
71
+ } catch (error) {
72
+ const known = error instanceof ControlledTransferError;
73
+ const code = known ? error.code : 'REQUEST_FAILED';
74
+ return response({ profile: PROFILE, operationId: known ? error.operationId : null,
75
+ state: code === 'OUTCOME_UNKNOWN' ? 'unknown' : 'rejected', code, newlyCommitted: false,
76
+ ...(known ? { reason: error.reason, httpStatus: error.httpStatus, recovery: error.recovery } : {}) });
77
+ }
78
+ }
79
+
80
+ const listTools = () => Object.freeze({ tools });
81
+ async function handleRequest(input) {
82
+ let request;
83
+ try { request = snapshot(input, 'INVALID_REQUEST'); } catch { /* Return a protocol error without echoing input. */ }
84
+ if (!record(request) || request.jsonrpc !== '2.0' || typeof request.method !== 'string'
85
+ || (Object.hasOwn(request, 'id') && request.id !== null && typeof request.id !== 'string' && !Number.isSafeInteger(request.id))) {
86
+ return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } };
87
+ }
88
+ if (!Object.hasOwn(request, 'id')) return null;
89
+ const envelope = { jsonrpc: '2.0', id: request.id };
90
+ if (request.method === 'initialize') return { ...envelope, result: {
91
+ protocolVersion: ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'].includes(request.params?.protocolVersion)
92
+ ? request.params.protocolVersion : '2025-11-25',
93
+ capabilities: { tools: {} }, serverInfo: { name: 'osuite_controlled_transfers', version: '1' }, instructions,
94
+ } };
95
+ if (request.method === 'ping') return { ...envelope, result: {} };
96
+ if (request.method === 'tools/list') return { ...envelope, result: listTools() };
97
+ if (request.method === 'tools/call') return { ...envelope,
98
+ result: await callTool(request.params?.name, request.params?.arguments ?? {}) };
99
+ return { ...envelope, error: { code: -32601, message: 'Method not found' } };
100
+ }
101
+
102
+ return Object.freeze({ tools, listTools, callTool, handleRequest });
103
+ }
@@ -0,0 +1,57 @@
1
+ import { record, snapshot } from './contract.mjs';
2
+
3
+ const PROFILE = 'matoi.controlled-transfer.projection.v1';
4
+ const states = new Set(['current', 'pending_reconciliation', 'stale', 'failed', 'unavailable']);
5
+ const uuid = value => typeof value === 'string'
6
+ && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
7
+ const generation = value => typeof value === 'string' && /^(0|[1-9][0-9]{0,18})$/.test(value)
8
+ && BigInt(value) <= 9223372036854775807n;
9
+ const timestamp = value => typeof value === 'string' && value.length === 24
10
+ && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
11
+ const errorCode = value => typeof value === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(value);
12
+ const fields = { incarnation: uuid, requestedGeneration: generation, projectedGeneration: generation,
13
+ artifactIncarnation: uuid, artifactGeneration: generation, generatedAt: timestamp, observedAt: timestamp,
14
+ lastError: errorCode };
15
+ const unavailable = Object.freeze({ profile: PROFILE, state: 'unavailable', scope: 'derived-view',
16
+ incarnation: null, requestedGeneration: null, projectedGeneration: null, artifactIncarnation: null,
17
+ artifactGeneration: null, generatedAt: null, observedAt: null, lastError: null, authorizesExecution: false });
18
+
19
+ export function normalizeProjection(value, { cached = false } = {}) {
20
+ if (!record(value)) return unavailable;
21
+ // Inspect only public scalar fields; auxiliary graphs, accessors and debug data
22
+ // must not participate in receipt validation or enter the model context.
23
+ const read = key => {
24
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
25
+ return descriptor ? descriptor.enumerable && Object.hasOwn(descriptor, 'value') ? descriptor.value : undefined : null;
26
+ };
27
+ const state = read('state');
28
+ if (read('profile') !== PROFILE || read('scope') !== 'derived-view'
29
+ || read('authorizesExecution') !== false || !states.has(state)) return unavailable;
30
+ const result = { ...unavailable, state };
31
+ for (const [key, valid] of Object.entries(fields)) {
32
+ const field = read(key);
33
+ if (field !== null && !valid(field)) return unavailable;
34
+ result[key] = field;
35
+ }
36
+ if (state !== 'unavailable' && result.observedAt === null) return unavailable;
37
+ // Check only wire consistency; canonical UTC timestamps sort chronologically.
38
+ if (state === 'current') {
39
+ if (result.incarnation === null || result.incarnation !== result.artifactIncarnation
40
+ || result.requestedGeneration === null || result.requestedGeneration === '0'
41
+ || result.requestedGeneration !== result.projectedGeneration || result.projectedGeneration !== result.artifactGeneration
42
+ || result.generatedAt === null || result.generatedAt > result.observedAt) return unavailable;
43
+ if (cached) result.state = 'stale';
44
+ }
45
+ return Object.freeze(result);
46
+ }
47
+
48
+ export function snapshotWithProjection(value, code) {
49
+ if (!record(value)) return snapshot(value, code);
50
+ const descriptors = Object.getOwnPropertyDescriptors(value);
51
+ const projection = normalizeProjection(descriptors.projection?.value);
52
+ delete descriptors.projection;
53
+ // Freshness has its own fixed bound and cannot spend the resource snapshot's
54
+ // byte/node budget. Keep all other descriptors subject to the existing checks.
55
+ const resource = snapshot(Object.defineProperties(Object.create(Object.getPrototypeOf(value)), descriptors), code);
56
+ return Object.freeze({ ...resource, projection });
57
+ }
@@ -0,0 +1,191 @@
1
+ import { verify } from 'node:crypto';
2
+ import { canonicalJson, sha256 } from '../runtime/protocol.mjs';
3
+ import { CONTROLLED_TRANSFER_PROFILE as PROFILE, COMPACT_TRANSFER_LEASE_PROFILE as COMPACT,
4
+ TRANSFER_PASS_BUILDER_PROFILE, RECEIPT_PROFILE, digest, fail,
5
+ identifier, issuerIdentity, record, snapshot } from './contract.mjs';
6
+
7
+ const leaseFields = ['profile', 'id', 'orgId', 'actorId', 'keyId', 'grantId', 'operationId',
8
+ 'grantEpoch', 'authorityEpoch', 'issuedAt', 'expiresAt', 'issuer', 'workflowDigest',
9
+ 'evidenceDigest', 'effectDigests', 'context'];
10
+ const compactLeaseFields = [...leaseFields, 'transferProfile', 'passBuilder', 'passCommitments'];
11
+ const receiptFields = ['profile', 'issuer', 'receiptId', 'orgId', 'actorId', 'grantId', 'operationId',
12
+ 'ordinal', 'actionId', 'actionFingerprint', 'preparationDigest', 'authorityEpoch', 'grantEpoch',
13
+ 'effect', 'effectDigest', 'committedAt', 'state', 'evidenceDigest'];
14
+ const effectIds = ['paymentId', 'sourceAccount', 'destination', 'asset', 'network'];
15
+ const epoch = value => typeof value === 'string' && /^(0|[1-9][0-9]{0,37})$/.test(value);
16
+ const time = value => Number.isSafeInteger(value) && value >= 0;
17
+ const approvalFingerprint = value => typeof value === 'string' && /^(?:apfp_)?[a-f0-9]{64}$/.test(value);
18
+
19
+ function exact(value, keys, code, optional = []) {
20
+ if (!record(value) || keys.some(key => !Object.hasOwn(value, key))
21
+ || Object.keys(value).some(key => !keys.includes(key) && !optional.includes(key))) fail(code);
22
+ }
23
+
24
+ function checkedEffect(effect, code) {
25
+ exact(effect, ['operation', ...effectIds, 'amountMinor', 'decimals'], code);
26
+ if (effect.operation !== 'transfer' || effectIds.some(field => !identifier(effect[field]))
27
+ || typeof effect.amountMinor !== 'string' || !/^[1-9][0-9]{0,37}$/.test(effect.amountMinor)
28
+ || !Number.isInteger(effect.decimals) || effect.decimals < 0 || effect.decimals > 18) fail(code);
29
+ return effect;
30
+ }
31
+
32
+ // Finance's v1 domain separation; money stays a canonical integer string.
33
+ function effectDigest(effect, code) {
34
+ return sha256(canonicalJson([PROFILE, 'effect', checkedEffect(effect, code)]));
35
+ }
36
+
37
+ function signedPayload(envelope, issuer, fields, code, optional = []) {
38
+ exact(envelope, ['payload', 'signature'], code);
39
+ exact(envelope.payload, fields, code, optional);
40
+ if (!issuer || envelope.payload.issuer !== issuer.fingerprint
41
+ || typeof envelope.signature !== 'string' || !/^[A-Za-z0-9_-]{86}$/.test(envelope.signature)) fail(code);
42
+ const bytes = Buffer.from(envelope.signature, 'base64url');
43
+ if (bytes.length !== 64 || bytes.toString('base64url') !== envelope.signature) fail(code);
44
+ let valid = false;
45
+ try { valid = verify(null, Buffer.from(canonicalJson(envelope.payload)), issuer.key, bytes); } catch { /* Fail closed. */ }
46
+ if (!valid) fail(code);
47
+ return envelope.payload;
48
+ }
49
+
50
+ function verificationIssuer(envelope, issuer, config, historical) {
51
+ if (!historical || envelope?.payload?.issuer === issuer?.fingerprint) return issuer;
52
+ // Explicit caller configuration alone extends historical trust. A response's
53
+ // embedded public key or advertised key list is never a trust root.
54
+ return (config.trustedIssuerPublicKeys ?? []).map(pem => issuerIdentity(pem))
55
+ .find(key => key.fingerprint === envelope?.payload?.issuer) ?? null;
56
+ }
57
+
58
+ function verifyGate(payload, source, code) {
59
+ const lease = source?.lease.payload, compact = lease?.profile === COMPACT;
60
+ if (!Object.hasOwn(payload, 'gate')) {
61
+ if (compact) fail(code);
62
+ return;
63
+ }
64
+ const gate = payload.gate;
65
+ exact(gate, ['lane', 'admissionSequence', 'coreReceipt'], code);
66
+ if (gate.lane !== 'slow-approved' || !epoch(gate.admissionSequence)) fail(code);
67
+ exact(gate.coreReceipt, ['schema_version', 'pass_id', 'pass_hash', 'action_fingerprint',
68
+ 'lane', 'decision', 'reason', 'observed_at', 'sequence_number', 'receipt_hash'], code);
69
+ const { receipt_hash: receiptHash, ...core } = gate.coreReceipt;
70
+ const observedAt = Date.parse(core.observed_at);
71
+ if (core.schema_version !== 'osuite.action_pass.receipt.v1' || !identifier(core.pass_id)
72
+ || !digest(core.pass_hash) || !digest(core.action_fingerprint) || !digest(receiptHash)
73
+ || receiptHash !== sha256(canonicalJson(core)) || core.lane !== 'slow' || core.decision !== 'review'
74
+ || core.reason !== 'risk_exceeds_fast_lane' || core.sequence_number !== payload.ordinal
75
+ || typeof core.observed_at !== 'string' || !time(observedAt)
76
+ || new Date(observedAt).toISOString() !== core.observed_at || observedAt > payload.committedAt) fail(code);
77
+ if (lease) {
78
+ if (observedAt < lease.issuedAt) fail(code);
79
+ if (compact) {
80
+ const entry = lease.passCommitments?.[payload.ordinal];
81
+ if (!entry || core.pass_id !== entry.passId || core.pass_hash !== entry.passHash
82
+ || core.action_fingerprint !== entry.actionFingerprint) fail(code);
83
+ } else {
84
+ const pass = lease.passes?.[payload.ordinal];
85
+ if (pass && (core.pass_id !== pass.pass_id || core.pass_hash !== pass.pass_hash
86
+ || core.action_fingerprint !== pass.action_binding?.allowed_fingerprint)) fail(code);
87
+ }
88
+ }
89
+ }
90
+
91
+ function verifyCompactPayload(payload, count, code) {
92
+ if (payload.transferProfile !== PROFILE || payload.passBuilder !== TRANSFER_PASS_BUILDER_PROFILE
93
+ || ['orgId', 'actorId', 'keyId', 'grantId', 'operationId'].some(key =>
94
+ !identifier(payload[key]) || !/^[A-Za-z0-9]/.test(payload[key]))
95
+ || !Number.isFinite(new Date(payload.issuedAt).getTime()) || !Number.isFinite(new Date(payload.expiresAt).getTime())
96
+ || payload.expiresAt - payload.issuedAt > 300000
97
+ || payload.context.artifact_sha256 !== payload.workflowDigest
98
+ || payload.context.dependencies_sha256 !== payload.evidenceDigest
99
+ || !Array.isArray(payload.passCommitments) || payload.passCommitments.length !== count) fail(code);
100
+ const hashes = new Set();
101
+ for (const entry of payload.passCommitments) {
102
+ exact(entry, ['passHash', 'passId', 'actionFingerprint'], code);
103
+ if (!digest(entry.passHash) || !digest(entry.actionFingerprint)
104
+ || typeof entry.passId !== 'string' || !/^ap_[a-f0-9]{24}$/.test(entry.passId)
105
+ || hashes.has(entry.passHash)) fail(code);
106
+ hashes.add(entry.passHash);
107
+ }
108
+ }
109
+
110
+ export function verifyPreparation(input, { config, issuer, operationId, grantId, checkExpiry = true, historical = false }) {
111
+ const code = 'INVALID_PREPARATION', value = snapshot(input, code);
112
+ if (!record(value) || value.profile !== PROFILE || value.operationId !== operationId || value.grantId !== grantId
113
+ || !identifier(operationId) || !identifier(grantId)
114
+ || !['awaiting_approval', 'preparing', 'denied'].includes(value.state)
115
+ || (value.code !== undefined && !identifier(value.code))
116
+ || !digest(value.preparationDigest) || !Array.isArray(value.effects)
117
+ || value.effects.length < 1 || value.effects.length > 64) fail(code);
118
+ if (value.state !== 'preparing' ? !identifier(value.actionId) || !approvalFingerprint(value.fingerprint)
119
+ : !((value.actionId === null && value.fingerprint === null) || (identifier(value.actionId) && approvalFingerprint(value.fingerprint)))) fail(code);
120
+ const compact = value.lease?.payload?.profile === COMPACT;
121
+ const payload = signedPayload(value.lease, verificationIssuer(value.lease, issuer, config, historical),
122
+ compact ? compactLeaseFields : leaseFields, code, compact ? [] : ['passes']);
123
+ if (payload.profile !== (compact ? COMPACT : PROFILE) || payload.orgId !== config.orgId || payload.actorId !== config.agentId
124
+ || !identifier(payload.id) || !identifier(payload.keyId) || (config.keyId && payload.keyId !== config.keyId)
125
+ || payload.operationId !== operationId || payload.grantId !== grantId
126
+ || !epoch(payload.grantEpoch) || !epoch(payload.authorityEpoch)
127
+ || !time(payload.issuedAt) || !time(payload.expiresAt) || payload.expiresAt <= payload.issuedAt
128
+ || payload.issuedAt > Date.now() + 30000 || (checkExpiry && payload.expiresAt <= Date.now())
129
+ || !digest(payload.workflowDigest) || !digest(payload.evidenceDigest)
130
+ || !Array.isArray(payload.effectDigests) || payload.effectDigests.length !== value.effects.length
131
+ || payload.effectDigests.some(item => !digest(item))
132
+ || value.preparationDigest !== sha256(canonicalJson(payload))) fail(code);
133
+ exact(payload.context, ['artifact_sha256', 'config_sha256', 'dependencies_sha256'], code);
134
+ if (Object.values(payload.context).some(item => !digest(item))) fail(code);
135
+ if (compact) verifyCompactPayload(payload, value.effects.length, code);
136
+ // Passes are signed per-effect evidence, not a substitute for native Studio approval.
137
+ if (Object.hasOwn(payload, 'passes') && (!Array.isArray(payload.passes)
138
+ || payload.passes.length !== value.effects.length || payload.passes.some(pass => !record(pass)))) fail(code);
139
+ const payments = new Set();
140
+ for (const [ordinal, effect] of value.effects.entries()) {
141
+ if (effectDigest(effect, code) !== payload.effectDigests[ordinal] || payments.has(effect.paymentId)) fail(code);
142
+ payments.add(effect.paymentId);
143
+ }
144
+ return value;
145
+ }
146
+
147
+ function receiptPreparationBinding(payload, prepared, ordinal, original, code) {
148
+ const lease = prepared.lease.payload;
149
+ if (payload.grantId !== prepared.grantId || payload.effectDigest !== lease.effectDigests[ordinal]
150
+ || canonicalJson(payload.effect) !== canonicalJson(prepared.effects[ordinal])) fail(code);
151
+ if (original && (payload.issuer !== lease.issuer || payload.preparationDigest !== prepared.preparationDigest
152
+ || payload.actionFingerprint !== prepared.fingerprint || payload.evidenceDigest !== lease.evidenceDigest
153
+ || payload.authorityEpoch !== lease.authorityEpoch || payload.grantEpoch !== lease.grantEpoch
154
+ || payload.committedAt < lease.issuedAt || payload.committedAt >= lease.expiresAt)) fail(code);
155
+ }
156
+
157
+ export function verifyReceipt(input, { issuer, config, prepared, sourcePrepared, ordinal, historical = false,
158
+ operationId = prepared?.operationId, actionId = prepared?.actionId, paymentId = prepared?.effects[ordinal]?.paymentId }) {
159
+ const code = 'INVALID_RECEIPT', value = snapshot(input, code);
160
+ const payload = signedPayload(value, verificationIssuer(value, issuer, config, historical), receiptFields, code, ['gate']);
161
+ if (payload.profile !== RECEIPT_PROFILE || payload.state !== 'committed'
162
+ || payload.orgId !== config.orgId || payload.actorId !== config.agentId
163
+ || ['receiptId', 'orgId', 'actorId', 'grantId', 'operationId', 'actionId'].some(key => !identifier(payload[key]))
164
+ || !approvalFingerprint(payload.actionFingerprint)
165
+ || ['preparationDigest', 'effectDigest', 'evidenceDigest'].some(key => !digest(payload[key]))
166
+ || !epoch(payload.authorityEpoch) || !epoch(payload.grantEpoch)
167
+ || !Number.isSafeInteger(payload.ordinal) || payload.ordinal < 0 || payload.ordinal > 63
168
+ || !time(payload.committedAt) || payload.committedAt > Date.now() + 30000
169
+ || payload.effectDigest !== effectDigest(payload.effect, code) || payload.effect.paymentId !== paymentId) fail(code);
170
+ const earlierOperation = historical && payload.operationId !== operationId;
171
+ let source = earlierOperation ? null : prepared;
172
+ if (sourcePrepared != null) {
173
+ try {
174
+ source = verifyPreparation(sourcePrepared, { config, issuer, operationId: payload.operationId,
175
+ grantId: payload.grantId, checkExpiry: false, historical });
176
+ } catch { fail(code); }
177
+ receiptPreparationBinding(payload, source, payload.ordinal, true, code);
178
+ if (payload.actionId !== source.actionId) fail(code);
179
+ }
180
+ // An earlier operation's gate is bound only to its own known source, never to
181
+ // the current operation's ordinal. No source means signature/effect checks only.
182
+ verifyGate(payload, source, code);
183
+ if (prepared) {
184
+ receiptPreparationBinding(payload, prepared, ordinal, !earlierOperation, code);
185
+ } else if (earlierOperation) {
186
+ // A cold status read has no signed current lease to bind a historical payment.
187
+ fail(code);
188
+ }
189
+ if (!earlierOperation && (payload.operationId !== operationId || payload.ordinal !== ordinal || payload.actionId !== actionId)) fail(code);
190
+ return value;
191
+ }
@@ -0,0 +1,38 @@
1
+ import { createControlledTransferMcpServer } from './controlled-transfers/mcp.mjs';
2
+ import { CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES as MAX_FRAME_BYTES } from './controlled-transfers/contract.mjs';
3
+
4
+ const MAX_BUFFER_BYTES = 2 * MAX_FRAME_BYTES;
5
+
6
+ export async function runControlledTransferStdio(config, { input = process.stdin, output = process.stdout } = {}) {
7
+ const server = createControlledTransferMcpServer(config);
8
+ const write = payload => new Promise((resolve, reject) => {
9
+ if (payload === null) { resolve(); return; }
10
+ output.write(`${JSON.stringify(payload)}\n`, error => error ? reject(error) : resolve());
11
+ });
12
+ async function invalid(code, message) {
13
+ await write({ jsonrpc: '2.0', id: null, error: { code, message } });
14
+ return false;
15
+ }
16
+ async function dispatch(frame) {
17
+ if (frame.length > MAX_FRAME_BYTES) return invalid(-32600, 'Frame too large');
18
+ let request;
19
+ try { request = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(frame)); }
20
+ catch { return invalid(-32700, 'Parse error'); }
21
+ await write(await server.handleRequest(request));
22
+ return true;
23
+ }
24
+ let buffer = Buffer.alloc(0);
25
+ for await (const chunk of input) {
26
+ if (buffer.length + chunk.length > MAX_BUFFER_BYTES) return invalid(-32600, 'Input buffer limit exceeded');
27
+ buffer = Buffer.concat([buffer, chunk]);
28
+ let end;
29
+ // Await each request and output before consuming the next frame; no background mutation queue.
30
+ while ((end = buffer.indexOf(10)) !== -1) {
31
+ const frame = buffer.subarray(0, end);
32
+ buffer = buffer.subarray(end + 1);
33
+ if (!await dispatch(frame)) return false;
34
+ }
35
+ if (buffer.length > MAX_FRAME_BYTES) return invalid(-32600, 'Frame too large');
36
+ }
37
+ return buffer.length ? dispatch(buffer) : true;
38
+ }
@@ -0,0 +1,4 @@
1
+ export { createControlledTransfers } from './controlled-transfers/client.mjs';
2
+ export { createControlledTransferMcpServer } from './controlled-transfers/mcp.mjs';
3
+ export { ControlledTransferError, CONTROLLED_TRANSFER_PROFILE,
4
+ CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES } from './controlled-transfers/contract.mjs';
@@ -0,0 +1,44 @@
1
+ import { createControlledTransfers } from './controlled-transfers.mjs';
2
+ import { CONTROLLED_TRANSFER_PROFILE as PROFILE, QUALIFICATIONS, snapshot } from './controlled-transfers/contract.mjs';
3
+
4
+ export async function probeMatoiStatus({ config } = {}) {
5
+ const result = { profile: PROFILE, installed: true, localConfigured: false, configured: false,
6
+ capabilityAvailable: false, serverInstalled: null, serverConfigured: null,
7
+ scope: null, resourceEnforced: null, qualification: null, qualificationSource: null,
8
+ nodeVersion: process.versions.node, requiredNodeMajor: 24, code: null };
9
+ try {
10
+ const client = createControlledTransfers({ config });
11
+ result.localConfigured = true;
12
+ const capability = await client.capabilities();
13
+ return snapshot({ ...result, capabilityAvailable: true, serverInstalled: capability.installed,
14
+ serverConfigured: capability.configured, configured: capability.configured && capability.resourceEnforced,
15
+ scope: capability.scope, resourceEnforced: capability.resourceEnforced,
16
+ qualification: capability.qualification, qualificationSource: 'authenticated-capability' });
17
+ } catch (error) {
18
+ return snapshot({ ...result, code: error.code ?? 'PROBE_FAILED' });
19
+ }
20
+ }
21
+
22
+ export function formatMatoiStatus(input) {
23
+ let status;
24
+ try { status = snapshot(input); } catch { status = {}; }
25
+ const yesNo = value => value === true ? 'yes' : value === false ? 'no' : 'unknown';
26
+ const authenticated = status?.profile === PROFILE && status.capabilityAvailable === true
27
+ && status.qualificationSource === 'authenticated-capability';
28
+ const qualification = authenticated && QUALIFICATIONS.includes(status.qualification?.status)
29
+ ? `${status.qualification.status} (server-reported)` : 'unknown (not verified)';
30
+ const code = typeof status?.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(status.code) ? status.code : null;
31
+ return [
32
+ 'Matoi Controlled Transfers',
33
+ `SDK installed: ${yesNo(status?.installed)}`,
34
+ `Local strict configuration: ${yesNo(status?.localConfigured)}`,
35
+ `Profile configured: ${yesNo(authenticated ? status.serverConfigured : null)}`,
36
+ `Resource scope: ${authenticated && status.scope === 'controlled-ledger' ? 'controlled-ledger' : 'unknown'}`,
37
+ `Resource enforced: ${yesNo(authenticated ? status.resourceEnforced : null)}`,
38
+ `Qualification: ${qualification}`,
39
+ ...(code ? [`Diagnostic: ${code}`] : []),
40
+ 'Installing the SDK alone does not establish full-stack deployment protection.',
41
+ 'Ordinary SDK/Hook behavior is unchanged. Native Studio review is required.',
42
+ 'This probe only reads capabilities; it never prepares, approves or executes a transfer.',
43
+ ].join('\n');
44
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.11.2",
3
+ "version": "2.12.0",
4
4
  "description": "OSuite governed action SDK for AI agents. Approve, replay, prove, and verify runtime decisions.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -22,6 +22,9 @@
22
22
  },
23
23
  "./governed-tools": {
24
24
  "import": "./governed-tools.mjs"
25
+ },
26
+ "./controlled-transfers": {
27
+ "import": "./controlled-transfers.mjs"
25
28
  }
26
29
  },
27
30
  "files": [
@@ -36,6 +39,11 @@
36
39
  "governed-tools/*.mjs",
37
40
  "governed-tools/examples/*.mjs",
38
41
  "GOVERNED_TOOLS.md",
42
+ "controlled-transfers.mjs",
43
+ "controlled-transfers-stdio.mjs",
44
+ "controlled-transfers/*.mjs",
45
+ "CONTROLLED_TRANSFERS.md",
46
+ "matoiDoctor.mjs",
39
47
  "projectHooks.js",
40
48
  "reviewSurface.js",
41
49
  "osuite.js",