@vorim/sdk 3.12.0 → 3.15.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/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/integrations/coinbase-cdp.cjs +230 -0
- package/dist/integrations/coinbase-cdp.cjs.map +1 -0
- package/dist/integrations/coinbase-cdp.d.cts +169 -0
- package/dist/integrations/coinbase-cdp.d.ts +169 -0
- package/dist/integrations/coinbase-cdp.js +204 -0
- package/dist/integrations/coinbase-cdp.js.map +1 -0
- package/dist/integrations/fhir.cjs +304 -0
- package/dist/integrations/fhir.cjs.map +1 -0
- package/dist/integrations/fhir.d.cts +185 -0
- package/dist/integrations/fhir.d.ts +185 -0
- package/dist/integrations/fhir.js +278 -0
- package/dist/integrations/fhir.js.map +1 -0
- package/dist/integrations/guidewire.cjs +363 -0
- package/dist/integrations/guidewire.cjs.map +1 -0
- package/dist/integrations/guidewire.d.cts +258 -0
- package/dist/integrations/guidewire.d.ts +258 -0
- package/dist/integrations/guidewire.js +337 -0
- package/dist/integrations/guidewire.js.map +1 -0
- package/dist/integrations/legal.cjs +339 -0
- package/dist/integrations/legal.cjs.map +1 -0
- package/dist/integrations/legal.d.cts +225 -0
- package/dist/integrations/legal.d.ts +225 -0
- package/dist/integrations/legal.js +313 -0
- package/dist/integrations/legal.js.map +1 -0
- package/dist/integrations/life-sciences.cjs +335 -0
- package/dist/integrations/life-sciences.cjs.map +1 -0
- package/dist/integrations/life-sciences.d.cts +214 -0
- package/dist/integrations/life-sciences.d.ts +214 -0
- package/dist/integrations/life-sciences.js +309 -0
- package/dist/integrations/life-sciences.js.map +1 -0
- package/dist/integrations/lithic.cjs +290 -0
- package/dist/integrations/lithic.cjs.map +1 -0
- package/dist/integrations/lithic.d.cts +130 -0
- package/dist/integrations/lithic.d.ts +130 -0
- package/dist/integrations/lithic.js +264 -0
- package/dist/integrations/lithic.js.map +1 -0
- package/dist/integrations/marqeta.cjs +285 -0
- package/dist/integrations/marqeta.cjs.map +1 -0
- package/dist/integrations/marqeta.d.cts +121 -0
- package/dist/integrations/marqeta.d.ts +121 -0
- package/dist/integrations/marqeta.js +259 -0
- package/dist/integrations/marqeta.js.map +1 -0
- package/dist/integrations/ramp.cjs +206 -0
- package/dist/integrations/ramp.cjs.map +1 -0
- package/dist/integrations/ramp.d.cts +139 -0
- package/dist/integrations/ramp.d.ts +139 -0
- package/dist/integrations/ramp.js +180 -0
- package/dist/integrations/ramp.js.map +1 -0
- package/dist/integrations/stripe-issuing.cjs +316 -0
- package/dist/integrations/stripe-issuing.cjs.map +1 -0
- package/dist/integrations/stripe-issuing.d.cts +154 -0
- package/dist/integrations/stripe-issuing.d.ts +154 -0
- package/dist/integrations/stripe-issuing.js +290 -0
- package/dist/integrations/stripe-issuing.js.map +1 -0
- package/package.json +91 -1
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// src/integrations/coinbase-cdp.ts
|
|
2
|
+
var OPERATION_SCOPE = {
|
|
3
|
+
signMessage: "agent:write",
|
|
4
|
+
sendTransaction: "agent:transact",
|
|
5
|
+
transfer: "agent:transact"
|
|
6
|
+
};
|
|
7
|
+
var VorimCoinbaseCdp = class {
|
|
8
|
+
sdk;
|
|
9
|
+
agentId;
|
|
10
|
+
humanId;
|
|
11
|
+
maxTransactionAmount;
|
|
12
|
+
allowedNetworks;
|
|
13
|
+
allowedDestinations;
|
|
14
|
+
escalateOverCeiling;
|
|
15
|
+
approverId;
|
|
16
|
+
escalationTimeoutMs;
|
|
17
|
+
minTrustScore;
|
|
18
|
+
onError;
|
|
19
|
+
constructor(sdk, config) {
|
|
20
|
+
if (!config?.agentId) throw new Error("[vorim] Coinbase CDP integration requires an agentId.");
|
|
21
|
+
this.sdk = sdk;
|
|
22
|
+
this.agentId = config.agentId;
|
|
23
|
+
this.humanId = config.humanId;
|
|
24
|
+
this.maxTransactionAmount = config.maxTransactionAmount;
|
|
25
|
+
this.allowedNetworks = config.allowedNetworks ? new Set(config.allowedNetworks.map((n) => n.toLowerCase())) : void 0;
|
|
26
|
+
this.allowedDestinations = config.allowedDestinations ? new Set(config.allowedDestinations.map((a) => a.toLowerCase())) : void 0;
|
|
27
|
+
this.escalateOverCeiling = config.escalateOverCeiling ?? false;
|
|
28
|
+
this.approverId = config.approverId ?? config.humanId;
|
|
29
|
+
this.escalationTimeoutMs = config.escalationTimeoutMs ?? 6e4;
|
|
30
|
+
this.minTrustScore = config.minTrustScore ?? 0;
|
|
31
|
+
this.onError = config.onError ?? "closed";
|
|
32
|
+
}
|
|
33
|
+
scopeFor(operation) {
|
|
34
|
+
return OPERATION_SCOPE[operation] ?? "agent:transact";
|
|
35
|
+
}
|
|
36
|
+
isValueMoving(operation) {
|
|
37
|
+
return operation === "sendTransaction" || operation === "transfer";
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Decide whether the agent may broadcast, before it runs. Order: network
|
|
41
|
+
* allowlist, destination allowlist, trust floor, amount ceiling (deny or
|
|
42
|
+
* escalate), then permission scope. The allowlists are enforced before any
|
|
43
|
+
* Vorim round-trip.
|
|
44
|
+
*/
|
|
45
|
+
async authorize(action) {
|
|
46
|
+
const scope = this.scopeFor(action.operation);
|
|
47
|
+
const valueMoving = this.isValueMoving(action.operation);
|
|
48
|
+
if (valueMoving && this.allowedNetworks && action.network && !this.allowedNetworks.has(action.network.toLowerCase())) {
|
|
49
|
+
return { authorized: false, reason: `network ${action.network} is not in this agent's allowed set`, outcome: "network-blocked" };
|
|
50
|
+
}
|
|
51
|
+
if (valueMoving && this.allowedDestinations && action.to && !this.allowedDestinations.has(action.to.toLowerCase())) {
|
|
52
|
+
return { authorized: false, reason: `destination ${action.to} is not in this agent's allowed set`, outcome: "destination-blocked" };
|
|
53
|
+
}
|
|
54
|
+
const overCeiling = valueMoving && this.maxTransactionAmount != null && typeof action.amount === "number" && action.amount > this.maxTransactionAmount;
|
|
55
|
+
try {
|
|
56
|
+
if (this.minTrustScore > 0) {
|
|
57
|
+
const trust = await this.sdk.verify(this.agentId);
|
|
58
|
+
if ((trust?.trust_score ?? 0) < this.minTrustScore) {
|
|
59
|
+
return { authorized: false, reason: `trust score below ${this.minTrustScore}`, outcome: overCeiling ? "over-ceiling" : "within" };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (overCeiling) {
|
|
63
|
+
if (!this.escalateOverCeiling) {
|
|
64
|
+
return {
|
|
65
|
+
authorized: false,
|
|
66
|
+
reason: `transaction ${action.amount} exceeds this agent's ceiling of ${this.maxTransactionAmount}`,
|
|
67
|
+
outcome: "over-ceiling"
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const esc = await this.escalate(action, scope);
|
|
71
|
+
return {
|
|
72
|
+
authorized: esc.approved,
|
|
73
|
+
reason: esc.approved ? void 0 : esc.reason ?? "named approver denied",
|
|
74
|
+
outcome: esc.approved ? "escalated-approved" : "escalated-denied",
|
|
75
|
+
approverId: this.approverId,
|
|
76
|
+
decisionId: esc.decisionId
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
const perm = await this.sdk.check(this.agentId, scope);
|
|
80
|
+
return perm.allowed ? { authorized: true, outcome: "within" } : { authorized: false, reason: perm.reason ?? `missing scope ${scope}`, outcome: "within" };
|
|
81
|
+
} catch (e) {
|
|
82
|
+
return this.onError === "open" ? { authorized: true, reason: "vorim unreachable, failed open", outcome: overCeiling ? "over-ceiling" : "within" } : { authorized: false, reason: `vorim unreachable: ${e?.message ?? "error"}`, outcome: overCeiling ? "over-ceiling" : "within" };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
async escalate(action, scope) {
|
|
86
|
+
const decision = await this.sdk.beforeAction(
|
|
87
|
+
{
|
|
88
|
+
agentId: this.agentId,
|
|
89
|
+
actionType: "api_request",
|
|
90
|
+
actionTarget: `coinbase-cdp:${action.operation}`,
|
|
91
|
+
requiredScope: scope,
|
|
92
|
+
payload: { amount: action.amount, asset: action.asset, network: action.network, to: action.to, limit: this.maxTransactionAmount },
|
|
93
|
+
context: { integration: "coinbase-cdp", requires_named_approver: true, approver_hint: this.approverId }
|
|
94
|
+
},
|
|
95
|
+
{ throwOnDeny: false }
|
|
96
|
+
);
|
|
97
|
+
if (decision.decision === "escalate") {
|
|
98
|
+
const resolved = await this.sdk.waitForDecisionResolution(decision.decisionId, { timeoutMs: this.escalationTimeoutMs });
|
|
99
|
+
const approved = resolved.decision === "allow" || resolved.escalationResolution === "approved";
|
|
100
|
+
return { approved, reason: approved ? void 0 : "named approver denied", decisionId: decision.decisionId };
|
|
101
|
+
}
|
|
102
|
+
if (decision.decision === "allow") return { approved: true, decisionId: decision.decisionId };
|
|
103
|
+
if (decision.decision === "fallback")
|
|
104
|
+
return { approved: this.onError === "open", reason: "runtime unreachable", decisionId: decision.decisionId };
|
|
105
|
+
return { approved: false, reason: decision.reason ?? "denied", decisionId: decision.decisionId };
|
|
106
|
+
}
|
|
107
|
+
async record(action, result, extra = {}) {
|
|
108
|
+
const scope = this.scopeFor(action.operation);
|
|
109
|
+
try {
|
|
110
|
+
await this.sdk.emit(
|
|
111
|
+
{
|
|
112
|
+
agent_id: this.agentId,
|
|
113
|
+
event_type: "api_request",
|
|
114
|
+
action: `coinbase-cdp:${action.operation}${action.to ? " " + action.to : ""}`,
|
|
115
|
+
resource: action.to || action.network || "coinbase-cdp",
|
|
116
|
+
permission: scope,
|
|
117
|
+
result,
|
|
118
|
+
input_hash: action.inputHash,
|
|
119
|
+
metadata: {
|
|
120
|
+
integration: "coinbase-cdp",
|
|
121
|
+
operation: action.operation,
|
|
122
|
+
acts_for_human: this.humanId,
|
|
123
|
+
...action.network ? { network: action.network } : {},
|
|
124
|
+
...action.to ? { to: action.to } : {},
|
|
125
|
+
...action.amount != null ? { amount: action.amount } : {},
|
|
126
|
+
...action.asset ? { asset: action.asset } : {},
|
|
127
|
+
...extra.outcome ? { auth_outcome: extra.outcome } : {},
|
|
128
|
+
...extra.approverId ? { approver_id: extra.approverId } : {},
|
|
129
|
+
...extra.decisionId ? { decision_id: extra.decisionId } : {},
|
|
130
|
+
...extra.reason ? { reason: extra.reason } : {}
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
{ sign: true }
|
|
134
|
+
);
|
|
135
|
+
return true;
|
|
136
|
+
} catch {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* The full flow for one CDP op: authorize (allowlists, trust, ceiling, scope),
|
|
142
|
+
* run the CDP SDK call if allowed, sign a receipt either way. If not
|
|
143
|
+
* authorized, `run` is never called. Rethrows a CDP error from `run` after
|
|
144
|
+
* recording it, with the receipt attached as `vorimReceipt`.
|
|
145
|
+
*/
|
|
146
|
+
async guard(action, run) {
|
|
147
|
+
const auth = await this.authorize(action);
|
|
148
|
+
if (!auth.authorized) {
|
|
149
|
+
const recorded = await this.record(action, "denied", { reason: auth.reason, outcome: auth.outcome, approverId: auth.approverId, decisionId: auth.decisionId });
|
|
150
|
+
return { receipt: this.receipt(action, false, "denied", auth, recorded) };
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
const value = await run();
|
|
154
|
+
const recorded = await this.record(action, "success", { outcome: auth.outcome, approverId: auth.approverId, decisionId: auth.decisionId });
|
|
155
|
+
return { receipt: this.receipt(action, true, "success", auth, recorded), value };
|
|
156
|
+
} catch (e) {
|
|
157
|
+
const recorded = await this.record(action, "error", { reason: e?.message, outcome: auth.outcome, approverId: auth.approverId, decisionId: auth.decisionId });
|
|
158
|
+
throw Object.assign(e ?? new Error("coinbase cdp operation failed"), {
|
|
159
|
+
vorimReceipt: this.receipt(action, true, "error", { ...auth, reason: e?.message }, recorded)
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
// --- Named helpers ---------------------------------------------------------
|
|
164
|
+
/** Guard broadcasting a transaction. Requires agent:transact; enforces the
|
|
165
|
+
* value ceiling, network allowlist, and destination allowlist. */
|
|
166
|
+
guardedSendTransaction(meta, run) {
|
|
167
|
+
return this.guard({ operation: "sendTransaction", ...meta }, run);
|
|
168
|
+
}
|
|
169
|
+
/** Guard a transfer. Requires agent:transact; same attenuation as send. */
|
|
170
|
+
guardedTransfer(meta, run) {
|
|
171
|
+
return this.guard({ operation: "transfer", ...meta }, run);
|
|
172
|
+
}
|
|
173
|
+
/** Guard signing a message (no value moves). Requires agent:write. */
|
|
174
|
+
guardedSignMessage(meta, run) {
|
|
175
|
+
return this.guard({ operation: "signMessage", ...meta }, run);
|
|
176
|
+
}
|
|
177
|
+
receipt(action, authorized, result, auth, recorded) {
|
|
178
|
+
return {
|
|
179
|
+
authorized,
|
|
180
|
+
agentId: this.agentId,
|
|
181
|
+
humanId: this.humanId,
|
|
182
|
+
operation: action.operation,
|
|
183
|
+
network: action.network,
|
|
184
|
+
to: action.to,
|
|
185
|
+
amount: action.amount,
|
|
186
|
+
asset: action.asset,
|
|
187
|
+
authOutcome: auth.outcome,
|
|
188
|
+
approverId: auth.approverId,
|
|
189
|
+
result,
|
|
190
|
+
scope: this.scopeFor(action.operation),
|
|
191
|
+
reason: auth.reason,
|
|
192
|
+
decisionId: auth.decisionId,
|
|
193
|
+
recorded
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
function createVorimCoinbaseCdp(sdk, config) {
|
|
198
|
+
return new VorimCoinbaseCdp(sdk, config);
|
|
199
|
+
}
|
|
200
|
+
export {
|
|
201
|
+
VorimCoinbaseCdp,
|
|
202
|
+
createVorimCoinbaseCdp
|
|
203
|
+
};
|
|
204
|
+
//# sourceMappingURL=coinbase-cdp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/coinbase-cdp.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Coinbase CDP Wallet (agentic onchain wallet) Integration\n//\n// This guards an AI agent that holds a Coinbase Developer Platform (CDP) wallet\n// and broadcasts onchain transactions. It is DISTINCT from the shipped x402\n// connector: x402 is the payment protocol; this is the wallet that signs and\n// broadcasts. Before each broadcast this layer verifies the agent's identity and\n// scoped permission, enforces a per-transaction ceiling, a network allowlist,\n// and a destination-address allowlist, escalates above the ceiling to a named\n// approver, then signs a tamper-evident record of the broadcast (intent + result).\n//\n// SCOPE MAPPING (uses Vorim's real scopes)\n// sign a message -> agent:write\n// send a transaction / transfer -> agent:transact + amount + allowlists\n//\n// This layer never holds the CDP Secret API Key or the Wallet Secret. You pass\n// the CDP SDK call (`cdp.evm.sendTransaction`, `cdp.solana.sendTransaction`, a\n// transfer, a sign-message) as a closure; this layer authorizes, escalates if\n// needed, runs it, and signs the receipt.\n//\n// ONCHAIN ATTENUATION (the wedge)\n// A fiat spend ceiling is a number; an onchain intent is a value + a destination\n// + a network. So attenuation here is three-part: per-transaction value ceiling,\n// destination-address allowlist (an agent can only pay addresses it was granted),\n// and network allowlist. Everything is enforced before the broadcast and signed.\n//\n// COMPLIANCE FRAMING (honest)\n// No regime mandates cryptographic signing of onchain activity (the chain is\n// already immutable). Vorim's value is the ATTRIBUTABLE, POLICY-LEVEL record: it\n// binds a broadcast to a specific agent identity, the human it acts for, the\n// ceiling it was under, and the approval that authorized it, above what the chain\n// itself records. Say \"attributable, policy-signed record of every broadcast\".\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { createVorimCoinbaseCdp } from '@vorim/sdk/integrations/coinbase-cdp';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const cdp = createVorimCoinbaseCdp(vorim, {\n// agentId: 'agid_abc123',\n// maxTransactionAmount: 100_000_000, // ceiling in the token's base unit\n// allowedNetworks: ['base', 'base-sepolia'],\n// allowedDestinations: ['0xabc...'], // pay only these addresses\n// escalateOverCeiling: true, approverId: 'treasury_ops',\n// });\n//\n// const { receipt, value } = await cdp.guardedSendTransaction(\n// { network: 'base', to: '0xabc...', amount: 5_000_000 },\n// () => cdpClient.evm.sendTransaction({ address, network, transaction }),\n// );\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope } from '../types.js';\n\nexport type CdpOperation = 'sendTransaction' | 'transfer' | 'signMessage';\n\nconst OPERATION_SCOPE: Record<string, PermissionScope> = {\n signMessage: 'agent:write',\n sendTransaction: 'agent:transact',\n transfer: 'agent:transact',\n};\n\nexport interface CoinbaseCdpConfig {\n /** The acting agent's Vorim id (agid_...). */\n agentId: string;\n /** The person/team the agent acts for. Recorded and default escalation target. */\n humanId?: string;\n /** Attenuation: cap a single transaction's value, in the token's base unit\n * (e.g. wei, or USDC's 6-decimal base unit). Omit for no per-transaction\n * ceiling. */\n maxTransactionAmount?: number;\n /** Attenuation: only allow broadcasts on these networks (e.g. 'base',\n * 'base-sepolia', 'solana'). Omit to allow any network. Case-insensitive. */\n allowedNetworks?: string[];\n /** Attenuation: only allow paying these destination addresses. Omit to allow\n * any destination. Compared case-insensitively. */\n allowedDestinations?: string[];\n /** Over the ceiling, escalate to a named approver instead of denying.\n * Default false. */\n escalateOverCeiling?: boolean;\n /** Named approver for an over-ceiling transaction. Defaults to humanId. */\n approverId?: string;\n /** Max wait for an escalation, ms. Default 60000. */\n escalationTimeoutMs?: number;\n /** Minimum trust score before any op. Default 0. */\n minTrustScore?: number;\n /** Fail closed (deny on any Vorim error) or fail open. Default 'closed'. */\n onError?: 'closed' | 'open';\n}\n\nexport interface CdpAction {\n /** The CDP operation, e.g. 'sendTransaction'. Drives the scope. */\n operation: CdpOperation | string;\n /** The network the broadcast targets, e.g. 'base'. Checked against\n * allowedNetworks. */\n network?: string;\n /** The destination address (for a transfer / send). Checked against\n * allowedDestinations. */\n to?: string;\n /** The transaction value, in the token's base unit. Checked against the\n * ceiling. */\n amount?: number;\n /** The asset symbol, e.g. 'USDC' or 'ETH'. Recorded. */\n asset?: string;\n /** Optional hash of the transaction body. */\n inputHash?: string;\n}\n\nexport type AuthOutcome = 'within' | 'escalated-approved' | 'escalated-denied' | 'over-ceiling' | 'network-blocked' | 'destination-blocked';\n\nexport interface CoinbaseCdpReceipt {\n authorized: boolean;\n agentId: string;\n humanId?: string;\n operation: string;\n network?: string;\n to?: string;\n amount?: number;\n asset?: string;\n authOutcome?: AuthOutcome;\n approverId?: string;\n result: 'success' | 'denied' | 'error';\n scope: PermissionScope;\n reason?: string;\n decisionId?: string;\n recorded: boolean;\n}\n\nexport class VorimCoinbaseCdp {\n private sdk: VorimSDK;\n private agentId: string;\n private humanId?: string;\n private maxTransactionAmount?: number;\n private allowedNetworks?: Set<string>;\n private allowedDestinations?: Set<string>;\n private escalateOverCeiling: boolean;\n private approverId?: string;\n private escalationTimeoutMs: number;\n private minTrustScore: number;\n private onError: 'closed' | 'open';\n\n constructor(sdk: VorimSDK, config: CoinbaseCdpConfig) {\n if (!config?.agentId) throw new Error('[vorim] Coinbase CDP integration requires an agentId.');\n this.sdk = sdk;\n this.agentId = config.agentId;\n this.humanId = config.humanId;\n this.maxTransactionAmount = config.maxTransactionAmount;\n this.allowedNetworks = config.allowedNetworks ? new Set(config.allowedNetworks.map((n) => n.toLowerCase())) : undefined;\n this.allowedDestinations = config.allowedDestinations ? new Set(config.allowedDestinations.map((a) => a.toLowerCase())) : undefined;\n this.escalateOverCeiling = config.escalateOverCeiling ?? false;\n this.approverId = config.approverId ?? config.humanId;\n this.escalationTimeoutMs = config.escalationTimeoutMs ?? 60_000;\n this.minTrustScore = config.minTrustScore ?? 0;\n this.onError = config.onError ?? 'closed';\n }\n\n private scopeFor(operation: string): PermissionScope {\n return OPERATION_SCOPE[operation] ?? 'agent:transact';\n }\n\n private isValueMoving(operation: string): boolean {\n return operation === 'sendTransaction' || operation === 'transfer';\n }\n\n /**\n * Decide whether the agent may broadcast, before it runs. Order: network\n * allowlist, destination allowlist, trust floor, amount ceiling (deny or\n * escalate), then permission scope. The allowlists are enforced before any\n * Vorim round-trip.\n */\n async authorize(\n action: CdpAction,\n ): Promise<{ authorized: boolean; reason?: string; outcome: AuthOutcome; approverId?: string; decisionId?: string }> {\n const scope = this.scopeFor(action.operation);\n const valueMoving = this.isValueMoving(action.operation);\n\n // Network allowlist (value-moving ops).\n if (valueMoving && this.allowedNetworks && action.network && !this.allowedNetworks.has(action.network.toLowerCase())) {\n return { authorized: false, reason: `network ${action.network} is not in this agent's allowed set`, outcome: 'network-blocked' };\n }\n // Destination allowlist.\n if (valueMoving && this.allowedDestinations && action.to && !this.allowedDestinations.has(action.to.toLowerCase())) {\n return { authorized: false, reason: `destination ${action.to} is not in this agent's allowed set`, outcome: 'destination-blocked' };\n }\n\n const overCeiling =\n valueMoving && this.maxTransactionAmount != null && typeof action.amount === 'number' && action.amount > this.maxTransactionAmount;\n\n try {\n if (this.minTrustScore > 0) {\n const trust = await this.sdk.verify(this.agentId);\n if ((trust?.trust_score ?? 0) < this.minTrustScore) {\n return { authorized: false, reason: `trust score below ${this.minTrustScore}`, outcome: overCeiling ? 'over-ceiling' : 'within' };\n }\n }\n\n if (overCeiling) {\n if (!this.escalateOverCeiling) {\n return {\n authorized: false,\n reason: `transaction ${action.amount} exceeds this agent's ceiling of ${this.maxTransactionAmount}`,\n outcome: 'over-ceiling',\n };\n }\n const esc = await this.escalate(action, scope);\n return {\n authorized: esc.approved,\n reason: esc.approved ? undefined : (esc.reason ?? 'named approver denied'),\n outcome: esc.approved ? 'escalated-approved' : 'escalated-denied',\n approverId: this.approverId,\n decisionId: esc.decisionId,\n };\n }\n\n const perm = await this.sdk.check(this.agentId, scope);\n return perm.allowed\n ? { authorized: true, outcome: 'within' }\n : { authorized: false, reason: perm.reason ?? `missing scope ${scope}`, outcome: 'within' };\n } catch (e: any) {\n return this.onError === 'open'\n ? { authorized: true, reason: 'vorim unreachable, failed open', outcome: overCeiling ? 'over-ceiling' : 'within' }\n : { authorized: false, reason: `vorim unreachable: ${e?.message ?? 'error'}`, outcome: overCeiling ? 'over-ceiling' : 'within' };\n }\n }\n\n private async escalate(action: CdpAction, scope: PermissionScope): Promise<{ approved: boolean; reason?: string; decisionId?: string }> {\n const decision = await this.sdk.beforeAction(\n {\n agentId: this.agentId,\n actionType: 'api_request',\n actionTarget: `coinbase-cdp:${action.operation}`,\n requiredScope: scope,\n payload: { amount: action.amount, asset: action.asset, network: action.network, to: action.to, limit: this.maxTransactionAmount },\n context: { integration: 'coinbase-cdp', requires_named_approver: true, approver_hint: this.approverId },\n },\n { throwOnDeny: false },\n );\n if (decision.decision === 'escalate') {\n const resolved = await this.sdk.waitForDecisionResolution(decision.decisionId, { timeoutMs: this.escalationTimeoutMs });\n const approved = resolved.decision === 'allow' || resolved.escalationResolution === 'approved';\n return { approved, reason: approved ? undefined : 'named approver denied', decisionId: decision.decisionId };\n }\n if (decision.decision === 'allow') return { approved: true, decisionId: decision.decisionId };\n if (decision.decision === 'fallback')\n return { approved: this.onError === 'open', reason: 'runtime unreachable', decisionId: decision.decisionId };\n return { approved: false, reason: decision.reason ?? 'denied', decisionId: decision.decisionId };\n }\n\n async record(\n action: CdpAction,\n result: 'success' | 'denied' | 'error',\n extra: { reason?: string; outcome?: AuthOutcome; approverId?: string; decisionId?: string } = {},\n ): Promise<boolean> {\n const scope = this.scopeFor(action.operation);\n try {\n await this.sdk.emit(\n {\n agent_id: this.agentId,\n event_type: 'api_request',\n action: `coinbase-cdp:${action.operation}${action.to ? ' ' + action.to : ''}`,\n resource: action.to || action.network || 'coinbase-cdp',\n permission: scope,\n result,\n input_hash: action.inputHash,\n metadata: {\n integration: 'coinbase-cdp',\n operation: action.operation,\n acts_for_human: this.humanId,\n ...(action.network ? { network: action.network } : {}),\n ...(action.to ? { to: action.to } : {}),\n ...(action.amount != null ? { amount: action.amount } : {}),\n ...(action.asset ? { asset: action.asset } : {}),\n ...(extra.outcome ? { auth_outcome: extra.outcome } : {}),\n ...(extra.approverId ? { approver_id: extra.approverId } : {}),\n ...(extra.decisionId ? { decision_id: extra.decisionId } : {}),\n ...(extra.reason ? { reason: extra.reason } : {}),\n },\n },\n { sign: true },\n );\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * The full flow for one CDP op: authorize (allowlists, trust, ceiling, scope),\n * run the CDP SDK call if allowed, sign a receipt either way. If not\n * authorized, `run` is never called. Rethrows a CDP error from `run` after\n * recording it, with the receipt attached as `vorimReceipt`.\n */\n async guard<T>(action: CdpAction, run: () => Promise<T>): Promise<{ receipt: CoinbaseCdpReceipt; value?: T }> {\n const auth = await this.authorize(action);\n if (!auth.authorized) {\n const recorded = await this.record(action, 'denied', { reason: auth.reason, outcome: auth.outcome, approverId: auth.approverId, decisionId: auth.decisionId });\n return { receipt: this.receipt(action, false, 'denied', auth, recorded) };\n }\n try {\n const value = await run();\n const recorded = await this.record(action, 'success', { outcome: auth.outcome, approverId: auth.approverId, decisionId: auth.decisionId });\n return { receipt: this.receipt(action, true, 'success', auth, recorded), value };\n } catch (e: any) {\n const recorded = await this.record(action, 'error', { reason: e?.message, outcome: auth.outcome, approverId: auth.approverId, decisionId: auth.decisionId });\n throw Object.assign(e ?? new Error('coinbase cdp operation failed'), {\n vorimReceipt: this.receipt(action, true, 'error', { ...auth, reason: e?.message }, recorded),\n });\n }\n }\n\n // --- Named helpers ---------------------------------------------------------\n\n /** Guard broadcasting a transaction. Requires agent:transact; enforces the\n * value ceiling, network allowlist, and destination allowlist. */\n guardedSendTransaction<T>(meta: { network?: string; to?: string; amount?: number; asset?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'sendTransaction', ...meta }, run);\n }\n\n /** Guard a transfer. Requires agent:transact; same attenuation as send. */\n guardedTransfer<T>(meta: { network?: string; to?: string; amount?: number; asset?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'transfer', ...meta }, run);\n }\n\n /** Guard signing a message (no value moves). Requires agent:write. */\n guardedSignMessage<T>(meta: { network?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'signMessage', ...meta }, run);\n }\n\n private receipt(\n action: CdpAction,\n authorized: boolean,\n result: 'success' | 'denied' | 'error',\n auth: { reason?: string; outcome?: AuthOutcome; approverId?: string; decisionId?: string },\n recorded: boolean,\n ): CoinbaseCdpReceipt {\n return {\n authorized,\n agentId: this.agentId,\n humanId: this.humanId,\n operation: action.operation,\n network: action.network,\n to: action.to,\n amount: action.amount,\n asset: action.asset,\n authOutcome: auth.outcome,\n approverId: auth.approverId,\n result,\n scope: this.scopeFor(action.operation),\n reason: auth.reason,\n decisionId: auth.decisionId,\n recorded,\n };\n }\n}\n\n/**\n * Create a VorimCoinbaseCdp guard around a Vorim SDK instance.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimCoinbaseCdp } from '@vorim/sdk/integrations/coinbase-cdp';\n *\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const cdp = createVorimCoinbaseCdp(vorim, {\n * agentId: 'agid_abc123',\n * maxTransactionAmount: 100_000_000,\n * allowedNetworks: ['base'],\n * allowedDestinations: ['0xabc...'],\n * });\n *\n * const { receipt, value } = await cdp.guardedSendTransaction(\n * { network: 'base', to: '0xabc...', amount: 5_000_000, asset: 'USDC' },\n * () => cdpClient.evm.sendTransaction({ address, network, transaction }),\n * );\n * ```\n */\nexport function createVorimCoinbaseCdp(sdk: VorimSDK, config: CoinbaseCdpConfig): VorimCoinbaseCdp {\n return new VorimCoinbaseCdp(sdk, config);\n}\n"],"mappings":";AAyDA,IAAM,kBAAmD;AAAA,EACvD,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,UAAU;AACZ;AAoEO,IAAM,mBAAN,MAAuB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,KAAe,QAA2B;AACpD,QAAI,CAAC,QAAQ,QAAS,OAAM,IAAI,MAAM,uDAAuD;AAC7F,SAAK,MAAM;AACX,SAAK,UAAU,OAAO;AACtB,SAAK,UAAU,OAAO;AACtB,SAAK,uBAAuB,OAAO;AACnC,SAAK,kBAAkB,OAAO,kBAAkB,IAAI,IAAI,OAAO,gBAAgB,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"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/integrations/fhir.ts
|
|
21
|
+
var fhir_exports = {};
|
|
22
|
+
__export(fhir_exports, {
|
|
23
|
+
VorimFhir: () => VorimFhir,
|
|
24
|
+
createVorimFhir: () => createVorimFhir
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(fhir_exports);
|
|
27
|
+
var DEFAULT_ORDER_RESOURCES = ["MedicationRequest", "ServiceRequest"];
|
|
28
|
+
var VorimFhir = class {
|
|
29
|
+
sdk;
|
|
30
|
+
agentId;
|
|
31
|
+
fhirBaseUrl;
|
|
32
|
+
allowedResources;
|
|
33
|
+
readOnly;
|
|
34
|
+
orderResources;
|
|
35
|
+
clinicianId;
|
|
36
|
+
escalateOrders;
|
|
37
|
+
escalationTimeoutMs;
|
|
38
|
+
minTrustScore;
|
|
39
|
+
onError;
|
|
40
|
+
constructor(sdk, config) {
|
|
41
|
+
if (!config?.agentId) throw new Error("[vorim] FHIR integration requires an agentId.");
|
|
42
|
+
if (!config?.fhirBaseUrl) throw new Error("[vorim] FHIR integration requires a fhirBaseUrl.");
|
|
43
|
+
this.sdk = sdk;
|
|
44
|
+
this.agentId = config.agentId;
|
|
45
|
+
this.fhirBaseUrl = config.fhirBaseUrl;
|
|
46
|
+
this.allowedResources = config.allowedResources ? new Set(config.allowedResources) : void 0;
|
|
47
|
+
this.readOnly = config.readOnly ?? false;
|
|
48
|
+
this.orderResources = new Set(config.orderResources ?? DEFAULT_ORDER_RESOURCES);
|
|
49
|
+
this.clinicianId = config.clinicianId;
|
|
50
|
+
this.escalateOrders = config.escalateOrders ?? true;
|
|
51
|
+
this.escalationTimeoutMs = config.escalationTimeoutMs ?? 3e5;
|
|
52
|
+
this.minTrustScore = config.minTrustScore ?? 0;
|
|
53
|
+
this.onError = config.onError ?? "closed";
|
|
54
|
+
}
|
|
55
|
+
isRead(interaction) {
|
|
56
|
+
return interaction === "read";
|
|
57
|
+
}
|
|
58
|
+
isOrder(action) {
|
|
59
|
+
return !this.isRead(action.interaction) && this.orderResources.has(action.resourceType);
|
|
60
|
+
}
|
|
61
|
+
/** The Vorim scope an action requires. Reads need read; order-resource writes
|
|
62
|
+
* are elevated (draft + clinician sign); other writes need write. */
|
|
63
|
+
scopeFor(action) {
|
|
64
|
+
if (this.isRead(action.interaction)) return "agent:read";
|
|
65
|
+
if (this.isOrder(action)) return "agent:elevate";
|
|
66
|
+
return "agent:write";
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Decide whether the acting agent may run this FHIR interaction, before it
|
|
70
|
+
* runs. Order: trust floor, read-only cap, resource-type cap, order gate
|
|
71
|
+
* (escalate to clinician), then permission scope.
|
|
72
|
+
*/
|
|
73
|
+
async authorize(action) {
|
|
74
|
+
const isRead = this.isRead(action.interaction);
|
|
75
|
+
const isOrder = this.isOrder(action);
|
|
76
|
+
const scope = this.scopeFor(action);
|
|
77
|
+
if (!isRead && this.readOnly) {
|
|
78
|
+
return {
|
|
79
|
+
authorized: false,
|
|
80
|
+
reason: "agent is read-only; writes are not permitted",
|
|
81
|
+
orderOutcome: isOrder ? "blocked-read-only" : "not-an-order"
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
if (!isRead && this.allowedResources && !this.allowedResources.has(action.resourceType)) {
|
|
85
|
+
return {
|
|
86
|
+
authorized: false,
|
|
87
|
+
reason: `resource type ${action.resourceType} is not in this agent's allowed set`,
|
|
88
|
+
orderOutcome: isOrder ? "order-denied" : "not-an-order"
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
if (this.minTrustScore > 0) {
|
|
93
|
+
const trust = await this.sdk.verify(this.agentId);
|
|
94
|
+
if ((trust?.trust_score ?? 0) < this.minTrustScore) {
|
|
95
|
+
return {
|
|
96
|
+
authorized: false,
|
|
97
|
+
reason: `trust score below ${this.minTrustScore}`,
|
|
98
|
+
orderOutcome: isOrder ? "order-denied" : "not-an-order"
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (isOrder) {
|
|
103
|
+
if (!this.escalateOrders) {
|
|
104
|
+
return {
|
|
105
|
+
authorized: false,
|
|
106
|
+
reason: "order resource requires a clinician signature and escalateOrders is off",
|
|
107
|
+
orderOutcome: "order-denied"
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
if (!this.clinicianId) {
|
|
111
|
+
return {
|
|
112
|
+
authorized: false,
|
|
113
|
+
reason: "order resource requires a configured clinicianId (the signing clinician)",
|
|
114
|
+
orderOutcome: "order-denied"
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
const esc = await this.escalate(action, scope);
|
|
118
|
+
return {
|
|
119
|
+
authorized: esc.approved,
|
|
120
|
+
reason: esc.approved ? void 0 : esc.reason ?? "clinician did not sign the order",
|
|
121
|
+
orderOutcome: esc.approved ? "signed-by-clinician" : "order-denied",
|
|
122
|
+
signerId: esc.approved ? this.clinicianId : void 0,
|
|
123
|
+
decisionId: esc.decisionId
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const perm = await this.sdk.check(this.agentId, scope);
|
|
127
|
+
return perm.allowed ? { authorized: true, orderOutcome: "not-an-order" } : {
|
|
128
|
+
authorized: false,
|
|
129
|
+
reason: perm.reason ?? `missing scope ${scope}`,
|
|
130
|
+
orderOutcome: "not-an-order"
|
|
131
|
+
};
|
|
132
|
+
} catch (e) {
|
|
133
|
+
return this.onError === "open" ? {
|
|
134
|
+
authorized: true,
|
|
135
|
+
reason: "vorim unreachable, failed open",
|
|
136
|
+
orderOutcome: isOrder ? "signed-by-clinician" : "not-an-order"
|
|
137
|
+
} : {
|
|
138
|
+
authorized: false,
|
|
139
|
+
reason: `vorim unreachable: ${e?.message ?? "error"}`,
|
|
140
|
+
orderOutcome: isOrder ? "order-denied" : "not-an-order"
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Route an order-resource write through the runtime decision plane so a
|
|
146
|
+
* clinician can sign (approve) or refuse the unsigned draft, and wait. The
|
|
147
|
+
* elevate scope marks the segregation-of-duties gate: the agent proposes the
|
|
148
|
+
* order, the clinician signs it.
|
|
149
|
+
*/
|
|
150
|
+
async escalate(action, scope) {
|
|
151
|
+
const decision = await this.sdk.beforeAction(
|
|
152
|
+
{
|
|
153
|
+
agentId: this.agentId,
|
|
154
|
+
actionType: "api_request",
|
|
155
|
+
actionTarget: `fhir:${action.interaction}:${action.resourceType}`,
|
|
156
|
+
requiredScope: scope,
|
|
157
|
+
payload: {
|
|
158
|
+
interaction: action.interaction,
|
|
159
|
+
resource_type: action.resourceType,
|
|
160
|
+
resource_id: action.resourceId,
|
|
161
|
+
order_status: "unsigned-draft"
|
|
162
|
+
},
|
|
163
|
+
context: {
|
|
164
|
+
integration: "fhir-r4",
|
|
165
|
+
fhir_base_url: this.fhirBaseUrl,
|
|
166
|
+
requires_clinician_signature: true,
|
|
167
|
+
clinician_hint: this.clinicianId
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
{ throwOnDeny: false }
|
|
171
|
+
);
|
|
172
|
+
if (decision.decision === "escalate") {
|
|
173
|
+
const resolved = await this.sdk.waitForDecisionResolution(decision.decisionId, {
|
|
174
|
+
timeoutMs: this.escalationTimeoutMs
|
|
175
|
+
});
|
|
176
|
+
const approved = resolved.decision === "allow" || resolved.escalationResolution === "approved";
|
|
177
|
+
return {
|
|
178
|
+
approved,
|
|
179
|
+
reason: approved ? void 0 : "clinician refused to sign the order",
|
|
180
|
+
decisionId: decision.decisionId
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
if (decision.decision === "allow") return { approved: true, decisionId: decision.decisionId };
|
|
184
|
+
if (decision.decision === "fallback")
|
|
185
|
+
return { approved: this.onError === "open", reason: "runtime unreachable", decisionId: decision.decisionId };
|
|
186
|
+
return { approved: false, reason: decision.reason ?? "denied", decisionId: decision.decisionId };
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Emit a source-signed audit event for a FHIR write and return whether it was
|
|
190
|
+
* recorded. The event names the agent, the server, the resource type/id, and
|
|
191
|
+
* any clinician signer — attributable and independently verifiable offline,
|
|
192
|
+
* supporting HIPAA §164.312(b) audit controls. It carries NO PHI.
|
|
193
|
+
*/
|
|
194
|
+
async record(action, result, extra = {}) {
|
|
195
|
+
const scope = this.scopeFor(action);
|
|
196
|
+
try {
|
|
197
|
+
await this.sdk.emit(
|
|
198
|
+
{
|
|
199
|
+
agent_id: this.agentId,
|
|
200
|
+
event_type: "api_request",
|
|
201
|
+
action: `fhir:${action.interaction} ${action.resourceType}${action.resourceId ? "/" + action.resourceId : ""}`,
|
|
202
|
+
resource: `${action.resourceType}${action.resourceId ? "/" + action.resourceId : ""}`,
|
|
203
|
+
permission: scope,
|
|
204
|
+
result,
|
|
205
|
+
input_hash: action.inputHash,
|
|
206
|
+
metadata: {
|
|
207
|
+
integration: "fhir-r4",
|
|
208
|
+
fhir_base_url: this.fhirBaseUrl,
|
|
209
|
+
interaction: action.interaction,
|
|
210
|
+
resource_type: action.resourceType,
|
|
211
|
+
is_order: this.isOrder(action),
|
|
212
|
+
...extra.orderOutcome ? { order_outcome: extra.orderOutcome } : {},
|
|
213
|
+
...extra.signerId ? { signed_by_clinician: extra.signerId, signed_at: (/* @__PURE__ */ new Date()).toISOString() } : {},
|
|
214
|
+
...extra.decisionId ? { decision_id: extra.decisionId } : {},
|
|
215
|
+
...extra.reason ? { reason: extra.reason } : {}
|
|
216
|
+
}
|
|
217
|
+
},
|
|
218
|
+
{ sign: true }
|
|
219
|
+
// source-signed: the agent's key signs the record
|
|
220
|
+
);
|
|
221
|
+
return true;
|
|
222
|
+
} catch {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The full flow for one FHIR interaction: authorize (trust, caps, order gate,
|
|
228
|
+
* scope), run the FHIR call if allowed, sign a receipt either way. If not
|
|
229
|
+
* authorized, `run` is never called. Rethrows a FHIR error from `run` after
|
|
230
|
+
* recording it, with the receipt attached as `vorimReceipt`.
|
|
231
|
+
*/
|
|
232
|
+
async guard(action, run) {
|
|
233
|
+
const auth = await this.authorize(action);
|
|
234
|
+
if (!auth.authorized) {
|
|
235
|
+
const recorded = await this.record(action, "denied", {
|
|
236
|
+
reason: auth.reason,
|
|
237
|
+
orderOutcome: auth.orderOutcome,
|
|
238
|
+
signerId: auth.signerId,
|
|
239
|
+
decisionId: auth.decisionId
|
|
240
|
+
});
|
|
241
|
+
return { receipt: this.receipt(action, false, "denied", auth, recorded) };
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
const value = await run();
|
|
245
|
+
const recorded = await this.record(action, "success", {
|
|
246
|
+
orderOutcome: auth.orderOutcome,
|
|
247
|
+
signerId: auth.signerId,
|
|
248
|
+
decisionId: auth.decisionId
|
|
249
|
+
});
|
|
250
|
+
return { receipt: this.receipt(action, true, "success", auth, recorded), value };
|
|
251
|
+
} catch (e) {
|
|
252
|
+
const recorded = await this.record(action, "error", {
|
|
253
|
+
reason: e?.message,
|
|
254
|
+
orderOutcome: auth.orderOutcome,
|
|
255
|
+
signerId: auth.signerId,
|
|
256
|
+
decisionId: auth.decisionId
|
|
257
|
+
});
|
|
258
|
+
throw Object.assign(e ?? new Error("fhir operation failed"), {
|
|
259
|
+
vorimReceipt: this.receipt(action, true, "error", { ...auth, reason: e?.message }, recorded)
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// --- Named helpers ---------------------------------------------------------
|
|
264
|
+
/** Guard a FHIR `create` (POST [base]/[type]). Requires agent:write, or
|
|
265
|
+
* agent:elevate + a clinician signature for an order resource. */
|
|
266
|
+
guardedCreate(meta, run) {
|
|
267
|
+
return this.guard({ interaction: "create", resourceType: meta.resourceType, resourceId: meta.resourceId, inputHash: meta.inputHash }, run);
|
|
268
|
+
}
|
|
269
|
+
/** Guard a FHIR `update` (PUT [base]/[type]/[id]). */
|
|
270
|
+
guardedUpdate(meta, run) {
|
|
271
|
+
return this.guard({ interaction: "update", resourceType: meta.resourceType, resourceId: meta.resourceId, inputHash: meta.inputHash }, run);
|
|
272
|
+
}
|
|
273
|
+
/** Guard a FHIR `patch` (PATCH [base]/[type]/[id]). */
|
|
274
|
+
guardedPatch(meta, run) {
|
|
275
|
+
return this.guard({ interaction: "patch", resourceType: meta.resourceType, resourceId: meta.resourceId, inputHash: meta.inputHash }, run);
|
|
276
|
+
}
|
|
277
|
+
receipt(action, authorized, result, auth, recorded) {
|
|
278
|
+
return {
|
|
279
|
+
authorized,
|
|
280
|
+
agentId: this.agentId,
|
|
281
|
+
fhirBaseUrl: this.fhirBaseUrl,
|
|
282
|
+
interaction: action.interaction,
|
|
283
|
+
resourceType: action.resourceType,
|
|
284
|
+
resourceId: action.resourceId,
|
|
285
|
+
isOrder: this.isOrder(action),
|
|
286
|
+
orderOutcome: auth.orderOutcome ?? "not-an-order",
|
|
287
|
+
signerId: auth.signerId,
|
|
288
|
+
result,
|
|
289
|
+
scope: this.scopeFor(action),
|
|
290
|
+
reason: auth.reason,
|
|
291
|
+
decisionId: auth.decisionId,
|
|
292
|
+
recorded
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
function createVorimFhir(sdk, config) {
|
|
297
|
+
return new VorimFhir(sdk, config);
|
|
298
|
+
}
|
|
299
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
300
|
+
0 && (module.exports = {
|
|
301
|
+
VorimFhir,
|
|
302
|
+
createVorimFhir
|
|
303
|
+
});
|
|
304
|
+
//# sourceMappingURL=fhir.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/fhir.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Healthcare (HL7 FHIR R4 / SMART on FHIR) Integration\n//\n// This guards an AI agent that writes to an electronic health record through the\n// vendor-neutral HL7 FHIR R4 REST API (the surface Epic, Oracle Health, and any\n// ONC g(10)-certified server share). Before each write runs it checks the acting\n// agent holds the right permission and that the FHIR resource type is within the\n// agent's allowed set; for the highest-stakes orders (a prescription or a lab/\n// imaging order) it forces the write to remain an UNSIGNED draft and escalates\n// to a clinician to sign. Either way it signs a tamper-evident record of which\n// agent proposed which mutation and under what authority.\n//\n// WHY FHIR R4, NOT A VENDOR API\n// R4 (4.0.1) is the ONC-mandated baseline every certified EHR exposes; SMART on\n// FHIR is the shared auth layer. One connector runs against every server —\n// vendor differences (base URL, token URL, scope version) are configuration.\n//\n// ALIGNS WITH THE EHR'S OWN MODEL\n// On Epic, agent-writable orders (MedicationRequest, ServiceRequest) are created\n// as \"Unsigned\" drafts that a human clinician signs; the API deliberately does\n// not let software finalize an order. Vorim's escalate-to-human step matches\n// that draft-then-sign model rather than fighting it, and adds the attributable,\n// cryptographic record of which agent proposed the order — which the base FHIR\n// API and the EHR audit log do not natively provide for autonomous agents.\n//\n// SCOPE MAPPING (uses Vorim's real scopes; mirrors SMART v2 CRUDS)\n// read / search (.r .s) -> agent:read\n// create / update / patch -> agent:write\n// an order that needs a -> agent:elevate (draft + clinician sign;\n// clinician signature segregation of duties)\n//\n// HONEST COMPLIANCE FRAMING\n// HIPAA §164.312(b) audit controls and (c)(2) integrity, and 21 CFR Part 11\n// §11.10(e) audit trails, require tamper-evident, attributable, time-stamped\n// records — which a signed Vorim record satisfies. NEITHER mandates a\n// cryptographic signature as the mechanism. Say \"supports HIPAA §164.312 audit\n// controls and integrity\", never \"required by HIPAA\". A Vorim record is not a\n// Part 11 electronic signature.\n//\n// This layer never holds a SMART token and never calls the FHIR server itself.\n// You pass the write to run; it authorizes, escalates if needed, runs it, signs\n// the receipt.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { createVorimFhir } from '@vorim/sdk/integrations/fhir';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const fhir = createVorimFhir(vorim, {\n// agentId: 'agid_abc123',\n// fhirBaseUrl: 'https://fhir.epic.com/.../api/FHIR/R4',\n// allowedResources: ['DocumentReference', 'Observation'], // resource-type cap\n// readOnly: false,\n// clinicianId: 'dr_42', // who signs an escalated order\n// });\n//\n// const { receipt, value } = await fhir.guardedCreate(\n// { resourceType: 'Observation', resourceId: 'obs-1' },\n// () => fhirClient.create('Observation', body),\n// );\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope } from '../types.js';\n\n/** A FHIR REST write interaction. Reads/searches pass through as 'read'. */\nexport type FhirInteraction = 'create' | 'update' | 'patch' | 'transaction' | 'read';\n\n/** The two order resource types that, on real EHRs, must be signed by a\n * clinician — Vorim forces these to a draft and escalates. Any resource can be\n * added to this behaviour via `orderResources`. */\nconst DEFAULT_ORDER_RESOURCES = ['MedicationRequest', 'ServiceRequest'];\n\nexport interface FhirGuardConfig {\n /** The acting agent's Vorim id (agid_...). */\n agentId: string;\n /** The FHIR R4 base URL, e.g. an Epic/Oracle R4 endpoint. Recorded on every\n * receipt so a write is attributable to one server. */\n fhirBaseUrl: string;\n /** Attenuation: restrict this agent to these FHIR resource types. A write to\n * any other type is denied. Omit to allow any type (subject to readOnly). */\n allowedResources?: string[];\n /** Attenuation: cap this agent to read/search only. Any create/update/patch is\n * denied even if the SMART token was over-scoped. Default false. */\n readOnly?: boolean;\n /** Resource types that must be written as an UNSIGNED draft and signed by a\n * clinician (escalation). Defaults to MedicationRequest + ServiceRequest —\n * the order resources EHRs gate this way. */\n orderResources?: string[];\n /** The clinician who signs an escalated order. Required if any order-resource\n * write will be run. Recorded as the signer on the record. */\n clinicianId?: string;\n /** For an order resource, escalate to the clinician and wait for the signature\n * instead of denying. Requires the runtime decision plane. Default true.\n * Ignored when readOnly. */\n escalateOrders?: boolean;\n /** Max time to wait for a clinician signature, ms. Default 300000 (5 min). */\n escalationTimeoutMs?: number;\n /** Minimum trust score the agent must hold before any write. Default 0 (off). */\n minTrustScore?: number;\n /** Fail closed (deny on any Vorim error) or fail open. Default 'closed'. */\n onError?: 'closed' | 'open';\n}\n\nexport interface FhirAction {\n /** The FHIR interaction, e.g. 'create'. Drives the scope. Reads pass as\n * 'read'. Unknown labels are treated as a write. */\n interaction: FhirInteraction | string;\n /** The FHIR resource type, e.g. 'Observation'. Checked against\n * allowedResources and the order-resource set. */\n resourceType: string;\n /** The resource id, when known (update/patch, or the created id). */\n resourceId?: string;\n /** Optional hash of the resource body so the receipt covers the exact input\n * without the guard storing PHI. */\n inputHash?: string;\n}\n\n/** How an order-resource write resolved. */\nexport type OrderOutcome = 'not-an-order' | 'signed-by-clinician' | 'order-denied' | 'blocked-read-only';\n\n/** An offline-verifiable receipt for one FHIR write. Contains no PHI — only the\n * resource type/id, the agent, and the authorization outcome. */\nexport interface FhirReceipt {\n authorized: boolean;\n agentId: string;\n fhirBaseUrl: string;\n interaction: string;\n resourceType: string;\n resourceId?: string;\n /** True when the resource is an order that requires a clinician signature. */\n isOrder: boolean;\n orderOutcome: OrderOutcome;\n /** The clinician who signed, when an order was escalated and signed. */\n signerId?: string;\n result: 'success' | 'denied' | 'error';\n scope: PermissionScope;\n reason?: string;\n decisionId?: string;\n recorded: boolean;\n}\n\nexport class VorimFhir {\n private sdk: VorimSDK;\n private agentId: string;\n private fhirBaseUrl: string;\n private allowedResources?: Set<string>;\n private readOnly: boolean;\n private orderResources: Set<string>;\n private clinicianId?: string;\n private escalateOrders: boolean;\n private escalationTimeoutMs: number;\n private minTrustScore: number;\n private onError: 'closed' | 'open';\n\n constructor(sdk: VorimSDK, config: FhirGuardConfig) {\n if (!config?.agentId) throw new Error('[vorim] FHIR integration requires an agentId.');\n if (!config?.fhirBaseUrl) throw new Error('[vorim] FHIR integration requires a fhirBaseUrl.');\n this.sdk = sdk;\n this.agentId = config.agentId;\n this.fhirBaseUrl = config.fhirBaseUrl;\n this.allowedResources = config.allowedResources ? new Set(config.allowedResources) : undefined;\n this.readOnly = config.readOnly ?? false;\n this.orderResources = new Set(config.orderResources ?? DEFAULT_ORDER_RESOURCES);\n this.clinicianId = config.clinicianId;\n this.escalateOrders = config.escalateOrders ?? true;\n this.escalationTimeoutMs = config.escalationTimeoutMs ?? 300_000;\n this.minTrustScore = config.minTrustScore ?? 0;\n this.onError = config.onError ?? 'closed';\n }\n\n private isRead(interaction: string): boolean {\n return interaction === 'read';\n }\n\n private isOrder(action: FhirAction): boolean {\n return !this.isRead(action.interaction) && this.orderResources.has(action.resourceType);\n }\n\n /** The Vorim scope an action requires. Reads need read; order-resource writes\n * are elevated (draft + clinician sign); other writes need write. */\n private scopeFor(action: FhirAction): PermissionScope {\n if (this.isRead(action.interaction)) return 'agent:read';\n if (this.isOrder(action)) return 'agent:elevate';\n return 'agent:write';\n }\n\n /**\n * Decide whether the acting agent may run this FHIR interaction, before it\n * runs. Order: trust floor, read-only cap, resource-type cap, order gate\n * (escalate to clinician), then permission scope.\n */\n async authorize(\n action: FhirAction,\n ): Promise<{\n authorized: boolean;\n reason?: string;\n orderOutcome: OrderOutcome;\n signerId?: string;\n decisionId?: string;\n }> {\n const isRead = this.isRead(action.interaction);\n const isOrder = this.isOrder(action);\n const scope = this.scopeFor(action);\n\n // Read-only cap: enforced before any Vorim round-trip. A write cannot happen\n // even if the SMART token was over-scoped.\n if (!isRead && this.readOnly) {\n return {\n authorized: false,\n reason: 'agent is read-only; writes are not permitted',\n orderOutcome: isOrder ? 'blocked-read-only' : 'not-an-order',\n };\n }\n // Resource-type cap: also before any round-trip.\n if (!isRead && this.allowedResources && !this.allowedResources.has(action.resourceType)) {\n return {\n authorized: false,\n reason: `resource type ${action.resourceType} is not in this agent's allowed set`,\n orderOutcome: isOrder ? 'order-denied' : 'not-an-order',\n };\n }\n\n try {\n if (this.minTrustScore > 0) {\n const trust = await this.sdk.verify(this.agentId);\n if ((trust?.trust_score ?? 0) < this.minTrustScore) {\n return {\n authorized: false,\n reason: `trust score below ${this.minTrustScore}`,\n orderOutcome: isOrder ? 'order-denied' : 'not-an-order',\n };\n }\n }\n\n if (isOrder) {\n if (!this.escalateOrders) {\n return {\n authorized: false,\n reason: 'order resource requires a clinician signature and escalateOrders is off',\n orderOutcome: 'order-denied',\n };\n }\n if (!this.clinicianId) {\n return {\n authorized: false,\n reason: 'order resource requires a configured clinicianId (the signing clinician)',\n orderOutcome: 'order-denied',\n };\n }\n const esc = await this.escalate(action, scope);\n return {\n authorized: esc.approved,\n reason: esc.approved ? undefined : (esc.reason ?? 'clinician did not sign the order'),\n orderOutcome: esc.approved ? 'signed-by-clinician' : 'order-denied',\n signerId: esc.approved ? this.clinicianId : undefined,\n decisionId: esc.decisionId,\n };\n }\n\n const perm = await this.sdk.check(this.agentId, scope);\n return perm.allowed\n ? { authorized: true, orderOutcome: 'not-an-order' }\n : {\n authorized: false,\n reason: perm.reason ?? `missing scope ${scope}`,\n orderOutcome: 'not-an-order',\n };\n } catch (e: any) {\n return this.onError === 'open'\n ? {\n authorized: true,\n reason: 'vorim unreachable, failed open',\n orderOutcome: isOrder ? 'signed-by-clinician' : 'not-an-order',\n }\n : {\n authorized: false,\n reason: `vorim unreachable: ${e?.message ?? 'error'}`,\n orderOutcome: isOrder ? 'order-denied' : 'not-an-order',\n };\n }\n }\n\n /**\n * Route an order-resource write through the runtime decision plane so a\n * clinician can sign (approve) or refuse the unsigned draft, and wait. The\n * elevate scope marks the segregation-of-duties gate: the agent proposes the\n * order, the clinician signs it.\n */\n private async escalate(\n action: FhirAction,\n scope: PermissionScope,\n ): Promise<{ approved: boolean; reason?: string; decisionId?: string }> {\n const decision = await this.sdk.beforeAction(\n {\n agentId: this.agentId,\n actionType: 'api_request',\n actionTarget: `fhir:${action.interaction}:${action.resourceType}`,\n requiredScope: scope,\n payload: {\n interaction: action.interaction,\n resource_type: action.resourceType,\n resource_id: action.resourceId,\n order_status: 'unsigned-draft',\n },\n context: {\n integration: 'fhir-r4',\n fhir_base_url: this.fhirBaseUrl,\n requires_clinician_signature: true,\n clinician_hint: this.clinicianId,\n },\n },\n { throwOnDeny: false },\n );\n\n if (decision.decision === 'escalate') {\n const resolved = await this.sdk.waitForDecisionResolution(decision.decisionId, {\n timeoutMs: this.escalationTimeoutMs,\n });\n const approved = resolved.decision === 'allow' || resolved.escalationResolution === 'approved';\n return {\n approved,\n reason: approved ? undefined : 'clinician refused to sign the order',\n decisionId: decision.decisionId,\n };\n }\n if (decision.decision === 'allow') return { approved: true, decisionId: decision.decisionId };\n if (decision.decision === 'fallback')\n return { approved: this.onError === 'open', reason: 'runtime unreachable', decisionId: decision.decisionId };\n return { approved: false, reason: decision.reason ?? 'denied', decisionId: decision.decisionId };\n }\n\n /**\n * Emit a source-signed audit event for a FHIR write and return whether it was\n * recorded. The event names the agent, the server, the resource type/id, and\n * any clinician signer — attributable and independently verifiable offline,\n * supporting HIPAA §164.312(b) audit controls. It carries NO PHI.\n */\n async record(\n action: FhirAction,\n result: 'success' | 'denied' | 'error',\n extra: { reason?: string; orderOutcome?: OrderOutcome; signerId?: string; decisionId?: string } = {},\n ): Promise<boolean> {\n const scope = this.scopeFor(action);\n try {\n await this.sdk.emit(\n {\n agent_id: this.agentId,\n event_type: 'api_request',\n action: `fhir:${action.interaction} ${action.resourceType}${action.resourceId ? '/' + action.resourceId : ''}`,\n resource: `${action.resourceType}${action.resourceId ? '/' + action.resourceId : ''}`,\n permission: scope,\n result,\n input_hash: action.inputHash,\n metadata: {\n integration: 'fhir-r4',\n fhir_base_url: this.fhirBaseUrl,\n interaction: action.interaction,\n resource_type: action.resourceType,\n is_order: this.isOrder(action),\n ...(extra.orderOutcome ? { order_outcome: extra.orderOutcome } : {}),\n ...(extra.signerId ? { signed_by_clinician: extra.signerId, signed_at: new Date().toISOString() } : {}),\n ...(extra.decisionId ? { decision_id: extra.decisionId } : {}),\n ...(extra.reason ? { reason: extra.reason } : {}),\n },\n },\n { sign: true }, // source-signed: the agent's key signs the record\n );\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * The full flow for one FHIR interaction: authorize (trust, caps, order gate,\n * scope), run the FHIR call if allowed, sign a receipt either way. If not\n * authorized, `run` is never called. Rethrows a FHIR error from `run` after\n * recording it, with the receipt attached as `vorimReceipt`.\n */\n async guard<T>(action: FhirAction, run: () => Promise<T>): Promise<{ receipt: FhirReceipt; value?: T }> {\n const auth = await this.authorize(action);\n if (!auth.authorized) {\n const recorded = await this.record(action, 'denied', {\n reason: auth.reason,\n orderOutcome: auth.orderOutcome,\n signerId: auth.signerId,\n decisionId: auth.decisionId,\n });\n return { receipt: this.receipt(action, false, 'denied', auth, recorded) };\n }\n try {\n const value = await run();\n const recorded = await this.record(action, 'success', {\n orderOutcome: auth.orderOutcome,\n signerId: auth.signerId,\n decisionId: auth.decisionId,\n });\n return { receipt: this.receipt(action, true, 'success', auth, recorded), value };\n } catch (e: any) {\n const recorded = await this.record(action, 'error', {\n reason: e?.message,\n orderOutcome: auth.orderOutcome,\n signerId: auth.signerId,\n decisionId: auth.decisionId,\n });\n throw Object.assign(e ?? new Error('fhir operation failed'), {\n vorimReceipt: this.receipt(action, true, 'error', { ...auth, reason: e?.message }, recorded),\n });\n }\n }\n\n // --- Named helpers ---------------------------------------------------------\n\n /** Guard a FHIR `create` (POST [base]/[type]). Requires agent:write, or\n * agent:elevate + a clinician signature for an order resource. */\n guardedCreate<T>(meta: { resourceType: string; resourceId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ interaction: 'create', resourceType: meta.resourceType, resourceId: meta.resourceId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard a FHIR `update` (PUT [base]/[type]/[id]). */\n guardedUpdate<T>(meta: { resourceType: string; resourceId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ interaction: 'update', resourceType: meta.resourceType, resourceId: meta.resourceId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard a FHIR `patch` (PATCH [base]/[type]/[id]). */\n guardedPatch<T>(meta: { resourceType: string; resourceId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ interaction: 'patch', resourceType: meta.resourceType, resourceId: meta.resourceId, inputHash: meta.inputHash }, run);\n }\n\n private receipt(\n action: FhirAction,\n authorized: boolean,\n result: 'success' | 'denied' | 'error',\n auth: { reason?: string; orderOutcome?: OrderOutcome; signerId?: string; decisionId?: string },\n recorded: boolean,\n ): FhirReceipt {\n return {\n authorized,\n agentId: this.agentId,\n fhirBaseUrl: this.fhirBaseUrl,\n interaction: action.interaction,\n resourceType: action.resourceType,\n resourceId: action.resourceId,\n isOrder: this.isOrder(action),\n orderOutcome: auth.orderOutcome ?? 'not-an-order',\n signerId: auth.signerId,\n result,\n scope: this.scopeFor(action),\n reason: auth.reason,\n decisionId: auth.decisionId,\n recorded,\n };\n }\n}\n\n/**\n * Create a VorimFhir guard around a Vorim SDK instance.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimFhir } from '@vorim/sdk/integrations/fhir';\n *\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const fhir = createVorimFhir(vorim, {\n * agentId: 'agid_abc123',\n * fhirBaseUrl: 'https://fhir.epic.com/interconnect-fhir-oauth/api/FHIR/R4',\n * allowedResources: ['DocumentReference', 'Observation'],\n * clinicianId: 'dr_42',\n * });\n *\n * // An order resource forces a draft + clinician signature:\n * const { receipt } = await fhir.guardedCreate(\n * { resourceType: 'MedicationRequest' },\n * () => fhirClient.create('MedicationRequest', unsignedDraft),\n * );\n * ```\n */\nexport function createVorimFhir(sdk: VorimSDK, config: FhirGuardConfig): VorimFhir {\n return new VorimFhir(sdk, config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuEA,IAAM,0BAA0B,CAAC,qBAAqB,gBAAgB;AAuE/D,IAAM,YAAN,MAAgB;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,KAAe,QAAyB;AAClD,QAAI,CAAC,QAAQ,QAAS,OAAM,IAAI,MAAM,+CAA+C;AACrF,QAAI,CAAC,QAAQ,YAAa,OAAM,IAAI,MAAM,kDAAkD;AAC5F,SAAK,MAAM;AACX,SAAK,UAAU,OAAO;AACtB,SAAK,cAAc,OAAO;AAC1B,SAAK,mBAAmB,OAAO,mBAAmB,IAAI,IAAI,OAAO,gBAAgB,IAAI;AACrF,SAAK,WAAW,OAAO,YAAY;AACnC,SAAK,iBAAiB,IAAI,IAAI,OAAO,kBAAkB,uBAAuB;AAC9E,SAAK,cAAc,OAAO;AAC1B,SAAK,iBAAiB,OAAO,kBAAkB;AAC/C,SAAK,sBAAsB,OAAO,uBAAuB;AACzD,SAAK,gBAAgB,OAAO,iBAAiB;AAC7C,SAAK,UAAU,OAAO,WAAW;AAAA,EACnC;AAAA,EAEQ,OAAO,aAA8B;AAC3C,WAAO,gBAAgB;AAAA,EACzB;AAAA,EAEQ,QAAQ,QAA6B;AAC3C,WAAO,CAAC,KAAK,OAAO,OAAO,WAAW,KAAK,KAAK,eAAe,IAAI,OAAO,YAAY;AAAA,EACxF;AAAA;AA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