@cmdoss/agent-pass-plugin 0.0.0-stage → 0.1.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/README.md +131 -2
- package/dist/agentpass.js +199 -0
- package/dist/cli.js +37 -0
- package/dist/domain.js +103 -0
- package/dist/engine.js +260 -0
- package/dist/http.js +170 -0
- package/dist/mcp.js +259 -0
- package/dist/onboarding.js +258 -0
- package/dist/public/catalog.js +35 -0
- package/dist/public/http.js +89 -0
- package/dist/public-server.js +11 -0
- package/dist/runtime/config.js +16 -0
- package/dist/runtime/installation.js +107 -0
- package/dist/runtime/lock.js +38 -0
- package/dist/runtime/paths.js +56 -0
- package/dist/runtime/setup.js +155 -0
- package/dist/sdk-ui.js +48 -0
- package/dist/server.js +107 -0
- package/dist/shared/constants.js +9 -0
- package/dist/store.js +84 -0
- package/dist/testnet/adapter.js +275 -0
- package/dist/testnet/authorization.js +620 -0
- package/dist/testnet/chain/codec.js +68 -0
- package/dist/testnet/chain/inspection.js +54 -0
- package/dist/testnet/chain/policy.js +78 -0
- package/dist/testnet/chain/prepared.js +150 -0
- package/dist/testnet/chain/receipt.js +49 -0
- package/dist/testnet/chain/sdk.js +34 -0
- package/dist/testnet/chain/types.js +1 -0
- package/dist/testnet/engine.js +395 -0
- package/dist/testnet/http.js +139 -0
- package/dist/testnet/model.js +49 -0
- package/dist/testnet/policy.js +44 -0
- package/dist/testnet/read-model.js +217 -0
- package/dist/testnet/repository.js +62 -0
- package/dist/testnet/runner.js +306 -0
- package/dist/testnet/types.js +1 -0
- package/dist/workflows.js +379 -0
- package/docs/agent-pass-integration.md +75 -0
- package/docs/architecture.md +93 -0
- package/docs/npm-release.md +83 -0
- package/npm-shrinkwrap.json +5376 -0
- package/package.json +72 -4
- package/public/assets/agent-pass-plugin-client.js +16 -0
- package/public/assets/agent-pass-plugin-sdk.js +1 -0
- package/public/assets/sui-payment-rails.avif +0 -0
- package/public/assets/sui-payments-hero.json +1 -0
- package/public/fonts/TWKEverett-Medium.woff2 +0 -0
- package/public/fonts/TWKEverett-Regular.woff2 +0 -0
- package/public/fonts/TWKEverettMono-Medium.woff2 +0 -0
- package/public/fonts/TWKEverettMono-Regular.woff2 +0 -0
- package/public/index.html +81 -0
- package/public/styles/base.css +117 -0
- package/public/styles/catalog.css +279 -0
- package/public/styles/controls.css +118 -0
- package/public/styles/dialog.css +257 -0
- package/public/styles/home.css +82 -0
- package/public/styles/layout.css +45 -0
- package/public/styles/plans.css +271 -0
- package/public/styles/responsive.css +643 -0
- package/public/styles/review.css +150 -0
- package/public/styles/sdk-wallet.css +125 -0
- package/public/styles/sdk.css +441 -0
- package/public/styles/shell.css +348 -0
- package/public/styles/tokens.css +75 -0
- package/public/styles.css +11 -0
- package/scripts/setup.mjs +10 -0
- package/skills/agent-pass-plugin-trading/SKILL.md +60 -0
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
2
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { mkdir, readFile, realpath, writeFile } from "node:fs/promises";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
const DAY = 86_400_000;
|
|
8
|
+
const SUI = `0x${"2".padStart(64, "0")}::sui::SUI`;
|
|
9
|
+
const require = createRequire(import.meta.url);
|
|
10
|
+
const sdkRoot = dirname(dirname(require.resolve("@mysten-incubation/sui-agent-pass/agent")));
|
|
11
|
+
const deploymentPath = join(sdkRoot, "deployments/testnet.json");
|
|
12
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
13
|
+
function obj(value, label) {
|
|
14
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
15
|
+
throw new Error(`Missing or invalid ${label}.`);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
export function canonical(value) {
|
|
19
|
+
if (Array.isArray(value))
|
|
20
|
+
return `[${value.map(canonical).join(",")}]`;
|
|
21
|
+
if (value !== null && typeof value === "object")
|
|
22
|
+
return `{${Object.keys(value)
|
|
23
|
+
.sort()
|
|
24
|
+
.map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`)
|
|
25
|
+
.join(",")}}`;
|
|
26
|
+
return JSON.stringify(value);
|
|
27
|
+
}
|
|
28
|
+
function digest(value) {
|
|
29
|
+
return createHash("sha256").update(canonical(value)).digest("hex");
|
|
30
|
+
}
|
|
31
|
+
function equal(a, b, label) {
|
|
32
|
+
if (canonical(a) !== canonical(b))
|
|
33
|
+
throw new Error(`Authorization ${label} does not match the reviewed plan.`);
|
|
34
|
+
}
|
|
35
|
+
function address(value) {
|
|
36
|
+
if (typeof value !== "string" || !/^0x[0-9a-f]{1,64}$/i.test(value))
|
|
37
|
+
throw new Error("Invalid Sui address in authorization.");
|
|
38
|
+
return `0x${value.slice(2).toLowerCase().padStart(64, "0")}`;
|
|
39
|
+
}
|
|
40
|
+
function coin(value) {
|
|
41
|
+
if (typeof value !== "string" ||
|
|
42
|
+
!/^0x[0-9a-f]{1,64}::[A-Za-z_][\w]*::[A-Za-z_][\w]*$/i.test(value))
|
|
43
|
+
throw new Error("Unsupported coin type in authorization.");
|
|
44
|
+
const [a, module, name] = value.split("::");
|
|
45
|
+
return `${address(a)}::${module}::${name}`;
|
|
46
|
+
}
|
|
47
|
+
function integer(value) {
|
|
48
|
+
if (!/^(0|[1-9][0-9]*)$/.test(value))
|
|
49
|
+
throw new Error("Amounts must be integer base units.");
|
|
50
|
+
return BigInt(value).toString();
|
|
51
|
+
}
|
|
52
|
+
function units(value, decimals) {
|
|
53
|
+
if (!/^\d+(\.\d+)?$/.test(value))
|
|
54
|
+
throw new Error("Expected a positive decimal amount.");
|
|
55
|
+
const [whole, fraction = ""] = value.split(".");
|
|
56
|
+
if (fraction.length > decimals)
|
|
57
|
+
throw new Error("Amount exceeds supported coin precision.");
|
|
58
|
+
return (BigInt(whole) * 10n ** BigInt(decimals) +
|
|
59
|
+
BigInt(fraction.padEnd(decimals, "0") || "0")).toString();
|
|
60
|
+
}
|
|
61
|
+
function decimal(base, decimals) {
|
|
62
|
+
const n = BigInt(integer(base)), scale = 10n ** BigInt(decimals);
|
|
63
|
+
const fractional = (n % scale)
|
|
64
|
+
.toString()
|
|
65
|
+
.padStart(decimals, "0")
|
|
66
|
+
.replace(/0+$/, "");
|
|
67
|
+
return `${n / scale}${fractional ? `.${fractional}` : ""}`;
|
|
68
|
+
}
|
|
69
|
+
function minPrice(input) {
|
|
70
|
+
if (input.direction === "usdc_to_sui") {
|
|
71
|
+
const paid = BigInt(units(input.limitPrice, input.coinIn.decimals));
|
|
72
|
+
if (paid <= 0n)
|
|
73
|
+
throw new Error("The owner must set a positive maximum price.");
|
|
74
|
+
const scale = 10n ** BigInt(input.coinOut.decimals + 9);
|
|
75
|
+
return ((scale + paid - 1n) / paid).toString();
|
|
76
|
+
}
|
|
77
|
+
const result = units(input.limitPrice, input.coinOut.decimals + 9 - input.coinIn.decimals);
|
|
78
|
+
if (BigInt(result) <= 0n)
|
|
79
|
+
throw new Error("The owner must set a positive minimum price.");
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
function normalizedPolicy(value, chainShape = false) {
|
|
83
|
+
const p = obj(value, "policy");
|
|
84
|
+
for (const key of ["transfers", "swaps", "lending"])
|
|
85
|
+
if (!Array.isArray(p[key]))
|
|
86
|
+
throw new Error("Invalid authorization policy arrays.");
|
|
87
|
+
if (p.transfers.length ||
|
|
88
|
+
p.lending.length ||
|
|
89
|
+
(chainShape
|
|
90
|
+
? !Array.isArray(p.staking) || p.staking.length
|
|
91
|
+
: p.staking !== null))
|
|
92
|
+
throw new Error("Authorization contains extra operations.");
|
|
93
|
+
if (p.swaps.length !== 1)
|
|
94
|
+
throw new Error("Authorization must contain exactly one swap direction.");
|
|
95
|
+
const s = obj(p.swaps[0], "swap policy");
|
|
96
|
+
const pools = chainShape ? s.venues : s.pools;
|
|
97
|
+
if (!Array.isArray(pools))
|
|
98
|
+
throw new Error("Invalid swap pools.");
|
|
99
|
+
return {
|
|
100
|
+
transfers: [],
|
|
101
|
+
swaps: [
|
|
102
|
+
{
|
|
103
|
+
coinIn: coin(s.coinIn),
|
|
104
|
+
coinOut: coin(s.coinOut),
|
|
105
|
+
[chainShape ? "venues" : "pools"]: pools.map(address).sort(),
|
|
106
|
+
perTrade: String(s.perTrade),
|
|
107
|
+
daily: String(s.daily),
|
|
108
|
+
minPrice: String(s.minPrice),
|
|
109
|
+
},
|
|
110
|
+
],
|
|
111
|
+
lending: [],
|
|
112
|
+
staking: chainShape ? [] : null,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function expected(input, name, expiresMs) {
|
|
116
|
+
const policy = {
|
|
117
|
+
transfers: [],
|
|
118
|
+
swaps: [
|
|
119
|
+
{
|
|
120
|
+
coinIn: coin(input.coinIn.type),
|
|
121
|
+
coinOut: coin(input.coinOut.type),
|
|
122
|
+
pools: [address(input.poolId)],
|
|
123
|
+
perTrade: integer(input.amountIn),
|
|
124
|
+
daily: integer(input.dailyLimitIn),
|
|
125
|
+
minPrice: minPrice(input),
|
|
126
|
+
},
|
|
127
|
+
],
|
|
128
|
+
lending: [],
|
|
129
|
+
staking: null,
|
|
130
|
+
};
|
|
131
|
+
const allowances = { [coin(input.coinIn.type)]: integer(input.budgetIn) };
|
|
132
|
+
return {
|
|
133
|
+
setup: {
|
|
134
|
+
name,
|
|
135
|
+
policy,
|
|
136
|
+
ttlMs: input.durationDays * DAY,
|
|
137
|
+
expiresMs,
|
|
138
|
+
allowances,
|
|
139
|
+
gasAmount: units(input.gasSui, 9),
|
|
140
|
+
gasCap: units(input.gasCapSui, 9),
|
|
141
|
+
gasDaily: units(input.gasDailySui, 9),
|
|
142
|
+
},
|
|
143
|
+
policies: normalizedPolicy({
|
|
144
|
+
...policy,
|
|
145
|
+
swaps: policy.swaps.map(({ pools, ...swap }) => ({
|
|
146
|
+
...swap,
|
|
147
|
+
venues: pools,
|
|
148
|
+
})),
|
|
149
|
+
staking: [],
|
|
150
|
+
}, true),
|
|
151
|
+
allowanceCaps: allowances,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
export class AuthorizationEndedError extends Error {
|
|
155
|
+
status;
|
|
156
|
+
constructor(message, status = "revoked") {
|
|
157
|
+
super(message);
|
|
158
|
+
this.status = status;
|
|
159
|
+
this.name = "AuthorizationEndedError";
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** Pure immutable verification shared with the execution adapter. Usage meters may advance. */
|
|
163
|
+
export function assertLiveAuthorization(value, binding, gasAllowance) {
|
|
164
|
+
const info = obj(value, "live session"), d = obj(info.deployment, "deployment");
|
|
165
|
+
if (d.network !== "testnet" || binding.network !== "testnet")
|
|
166
|
+
throw new Error("Only testnet authorization is supported.");
|
|
167
|
+
equal(d.chainIdentifier, binding.chainIdentifier, "chain");
|
|
168
|
+
equal(address(d.packageId), address(binding.packageId), "package");
|
|
169
|
+
equal(address(d.configId), address(binding.configId), "config");
|
|
170
|
+
equal(digest(d), binding.deploymentHash, "complete deployment fingerprint");
|
|
171
|
+
if (info.status === "closed")
|
|
172
|
+
throw new AuthorizationEndedError("The owner closed this pass.", "closed");
|
|
173
|
+
if (info.keyAlert)
|
|
174
|
+
throw new Error("The official signer reports possible copied-key use; owner review is required.");
|
|
175
|
+
const active = obj(info.active, "active session"), control = obj(info.control, "on-chain control");
|
|
176
|
+
equal(address(info.sessionAddress), address(binding.sessionAddress), "agent");
|
|
177
|
+
equal(address(active.passId), address(binding.passId), "pass");
|
|
178
|
+
equal(address(active.owner), address(binding.owner), "owner");
|
|
179
|
+
equal(address(control.owner), address(binding.owner), "control owner");
|
|
180
|
+
equal(address(control.agent), address(binding.sessionAddress), "control agent");
|
|
181
|
+
equal(active.authorizationDigest, binding.authorizationDigest, "authorization digest");
|
|
182
|
+
if (info.revoked === true || control.revoked === true)
|
|
183
|
+
throw new AuthorizationEndedError("The owner revoked this pass.");
|
|
184
|
+
if (!Number.isFinite(control.chainTimeMs))
|
|
185
|
+
throw new Error("Chain time is unavailable; authorization cannot be verified.");
|
|
186
|
+
if (Number(control.agentExpiresMs) <= control.chainTimeMs)
|
|
187
|
+
throw new AuthorizationEndedError("The pass is expired.", "expired");
|
|
188
|
+
const ex = obj(binding.expected, "expected rules"), setup = obj(ex.setup, "expected setup");
|
|
189
|
+
equal(digest(ex), binding.policyHash, "immutable policy fingerprint");
|
|
190
|
+
equal(control.name, setup.name, "name");
|
|
191
|
+
equal(String(control.agentExpiresMs), String(setup.expiresMs), "expiry");
|
|
192
|
+
equal(new Date(Number(setup.expiresMs)).toISOString(), binding.expiresAt, "bound expiry");
|
|
193
|
+
equal(normalizedPolicy(control.policies, true), ex.policies, "on-chain policies");
|
|
194
|
+
const allowances = obj(info.allowances, "live allowances");
|
|
195
|
+
const normalizedAllowances = Object.fromEntries(Object.entries(allowances).map(([key, a]) => [coin(key), a]));
|
|
196
|
+
equal(Object.keys(normalizedAllowances).sort(), Object.keys(ex.allowanceCaps).sort(), "allowance coins");
|
|
197
|
+
equal(Object.keys(obj(active.allowances, "active allowance ids"))
|
|
198
|
+
.map(coin)
|
|
199
|
+
.sort(), Object.keys(ex.allowanceCaps).sort(), "active allowance coins");
|
|
200
|
+
for (const [type, cap] of Object.entries(ex.allowanceCaps)) {
|
|
201
|
+
const a = obj(normalizedAllowances[type], "live allowance");
|
|
202
|
+
equal(address(a.funder), address(binding.owner), "allowance funder");
|
|
203
|
+
equal(address(a.spender), address(binding.sessionAddress), "allowance spender");
|
|
204
|
+
equal(coin(a.coinType), type, "allowance coin");
|
|
205
|
+
equal(coin(a.app), `${address(binding.packageId)}::pass::PASS`, "allowance app");
|
|
206
|
+
equal(a.name, setup.name, "allowance name");
|
|
207
|
+
equal(a.lifetimeCap, cap, "lifetime cap");
|
|
208
|
+
equal(String(a.expirationMs), String(setup.expiresMs), "allowance expiry");
|
|
209
|
+
equal(a.startMs, null, "allowance start");
|
|
210
|
+
equal(a.rateLimit, null, "unexpected allowance rate limit");
|
|
211
|
+
const ids = obj(active.allowances[type], "allowance identity");
|
|
212
|
+
equal(address(a.id), address(ids.allowance), "allowance object");
|
|
213
|
+
}
|
|
214
|
+
if (gasAllowance !== undefined) {
|
|
215
|
+
const a = obj(gasAllowance, "gas allowance");
|
|
216
|
+
equal(address(a.id), address(active.gasAllowance), "gas allowance object");
|
|
217
|
+
equal(coin(a.coinType), SUI, "gas coin");
|
|
218
|
+
equal(address(a.funder), address(binding.owner), "gas funder");
|
|
219
|
+
equal(address(a.spender), address(binding.sessionAddress), "gas spender");
|
|
220
|
+
equal(a.app, null, "gas app");
|
|
221
|
+
equal(a.name, "agent gas", "gas name");
|
|
222
|
+
equal(a.lifetimeCap, setup.gasCap, "gas lifetime cap");
|
|
223
|
+
equal(String(a.expirationMs), String(setup.expiresMs), "gas expiry");
|
|
224
|
+
equal(a.startMs, null, "gas start");
|
|
225
|
+
const rate = obj(a.rateLimit, "gas rate limit");
|
|
226
|
+
equal(rate.limit, setup.gasDaily, "gas daily limit");
|
|
227
|
+
equal(String(rate.periodMs), String(DAY), "gas period");
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
export function assertBindingPolicy(binding, input) {
|
|
231
|
+
equal(binding.planHash, input.planHash, "plan fingerprint");
|
|
232
|
+
equal(address(binding.owner), address(input.expectedOwner), "expected owner");
|
|
233
|
+
equal(address(binding.poolId), address(input.poolId), "route");
|
|
234
|
+
equal(coin(binding.coinIn.type), coin(input.coinIn.type), "input coin");
|
|
235
|
+
equal(coin(binding.coinOut.type), coin(input.coinOut.type), "output coin");
|
|
236
|
+
const setup = obj(binding.expected.setup, "expected setup");
|
|
237
|
+
equal(binding.expected, expected(input, setup.name, Number(setup.expiresMs)), "bound plan rules");
|
|
238
|
+
equal(binding.policyHash, digest(binding.expected), "bound policy hash");
|
|
239
|
+
}
|
|
240
|
+
export class OfficialAuthorization {
|
|
241
|
+
options;
|
|
242
|
+
root;
|
|
243
|
+
client;
|
|
244
|
+
connecting;
|
|
245
|
+
queue = Promise.resolve();
|
|
246
|
+
constructor(options) {
|
|
247
|
+
this.options = options;
|
|
248
|
+
this.root = resolve(options.root);
|
|
249
|
+
}
|
|
250
|
+
async deployment() {
|
|
251
|
+
const d = this.options.deployment ??
|
|
252
|
+
JSON.parse(await readFile(deploymentPath, "utf8"));
|
|
253
|
+
if (d.network !== "testnet" ||
|
|
254
|
+
!d.chainIdentifier ||
|
|
255
|
+
!Array.isArray(d.coins) ||
|
|
256
|
+
!Array.isArray(d.pools))
|
|
257
|
+
throw new Error("Invalid official testnet deployment.");
|
|
258
|
+
return structuredClone(d);
|
|
259
|
+
}
|
|
260
|
+
async tool(name, args) {
|
|
261
|
+
if (this.options.tool) {
|
|
262
|
+
const value = obj(await this.options.tool(name, args), "official tool response");
|
|
263
|
+
if (value.error)
|
|
264
|
+
throw new Error(String(value.error));
|
|
265
|
+
return value;
|
|
266
|
+
}
|
|
267
|
+
if (!this.connecting)
|
|
268
|
+
this.connecting = (async () => {
|
|
269
|
+
const metadata = JSON.parse(await readFile(join(sdkRoot, "package.json"), "utf8"));
|
|
270
|
+
if (metadata.version !== "0.1.35")
|
|
271
|
+
throw new Error("Revalidate the official SDK version before testnet authorization.");
|
|
272
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
273
|
+
const client = new Client({
|
|
274
|
+
name: "agent-pass-plugin-authorization",
|
|
275
|
+
version: "0.1.0",
|
|
276
|
+
});
|
|
277
|
+
await client.connect(new StdioClientTransport({
|
|
278
|
+
command: process.execPath,
|
|
279
|
+
args: [
|
|
280
|
+
join(sdkRoot, "dist/cli.js"),
|
|
281
|
+
"mcp",
|
|
282
|
+
"--root",
|
|
283
|
+
this.root,
|
|
284
|
+
"--deployment",
|
|
285
|
+
deploymentPath,
|
|
286
|
+
"--no-open",
|
|
287
|
+
],
|
|
288
|
+
stderr: "ignore",
|
|
289
|
+
}));
|
|
290
|
+
this.client = client;
|
|
291
|
+
return client;
|
|
292
|
+
})().catch((error) => {
|
|
293
|
+
this.connecting = undefined;
|
|
294
|
+
throw error;
|
|
295
|
+
});
|
|
296
|
+
const client = await this.connecting;
|
|
297
|
+
const result = await client.callTool({ name, arguments: args });
|
|
298
|
+
const text = result.content.find((c) => c.type === "text")?.text;
|
|
299
|
+
if (!text)
|
|
300
|
+
throw new Error("Official SDK returned no response.");
|
|
301
|
+
if (result.isError)
|
|
302
|
+
throw new Error(text);
|
|
303
|
+
const value = obj(JSON.parse(text), "official tool result");
|
|
304
|
+
if (result.isError || value.error)
|
|
305
|
+
throw new Error(String(value.error ?? "Official authorization request failed."));
|
|
306
|
+
return value;
|
|
307
|
+
}
|
|
308
|
+
async session(directory) {
|
|
309
|
+
const lexical = relative(join(this.root, "sessions"), directory);
|
|
310
|
+
if (!lexical ||
|
|
311
|
+
lexical.startsWith(`..${sep}`) ||
|
|
312
|
+
lexical === ".." ||
|
|
313
|
+
isAbsolute(lexical) ||
|
|
314
|
+
lexical.includes(sep))
|
|
315
|
+
throw new Error("Session directory escapes the isolated SDK root.");
|
|
316
|
+
if (this.options.readSession)
|
|
317
|
+
return obj(await this.options.readSession(directory), "session metadata");
|
|
318
|
+
const [root, actual] = await Promise.all([
|
|
319
|
+
realpath(join(this.root, "sessions")),
|
|
320
|
+
realpath(directory),
|
|
321
|
+
]);
|
|
322
|
+
if (relative(root, actual) !== lexical)
|
|
323
|
+
throw new Error("Session directory symlink escapes the isolated SDK root.");
|
|
324
|
+
return obj(JSON.parse(await readFile(join(actual, "session.json"), "utf8")), "session metadata");
|
|
325
|
+
}
|
|
326
|
+
directory(id) {
|
|
327
|
+
if (!uuid.test(id))
|
|
328
|
+
throw new Error("Invalid official session id.");
|
|
329
|
+
return join(this.root, "sessions", id);
|
|
330
|
+
}
|
|
331
|
+
async validateInput(input) {
|
|
332
|
+
const d = await this.deployment();
|
|
333
|
+
address(input.expectedOwner);
|
|
334
|
+
if (!Number.isInteger(input.durationDays) ||
|
|
335
|
+
input.durationDays < 1 ||
|
|
336
|
+
input.durationDays > 365)
|
|
337
|
+
throw new Error("Testnet authorization requires a whole number of days (1–365).");
|
|
338
|
+
if (BigInt(integer(input.amountIn)) <= 0n ||
|
|
339
|
+
BigInt(integer(input.budgetIn)) < BigInt(input.amountIn) ||
|
|
340
|
+
BigInt(integer(input.dailyLimitIn)) < BigInt(input.amountIn))
|
|
341
|
+
throw new Error("Invalid input spending limits.");
|
|
342
|
+
const pool = d.pools.find((p) => address(p.poolId) === address(input.poolId) && p.venue === input.venue);
|
|
343
|
+
if (!pool ||
|
|
344
|
+
![coin(pool.coinA), coin(pool.coinB)].includes(coin(input.coinIn.type)) ||
|
|
345
|
+
![coin(pool.coinA), coin(pool.coinB)].includes(coin(input.coinOut.type)))
|
|
346
|
+
throw new Error("The reviewed route is not the bundled testnet pair.");
|
|
347
|
+
const symbols = input.direction === "usdc_to_sui" ? ["USDC", "SUI"] : ["SUI", "USDC"];
|
|
348
|
+
for (const [n, c] of [input.coinIn, input.coinOut].entries()) {
|
|
349
|
+
const listed = d.coins.find((x) => coin(x.type) === coin(c.type));
|
|
350
|
+
if (!listed ||
|
|
351
|
+
listed.symbol !== symbols[n] ||
|
|
352
|
+
c.symbol !== listed.symbol ||
|
|
353
|
+
c.decimals !== listed.decimals)
|
|
354
|
+
throw new Error("Coin metadata does not match the testnet direction.");
|
|
355
|
+
}
|
|
356
|
+
minPrice(input);
|
|
357
|
+
units(input.gasSui, 9);
|
|
358
|
+
units(input.gasCapSui, 9);
|
|
359
|
+
units(input.gasDailySui, 9);
|
|
360
|
+
return d;
|
|
361
|
+
}
|
|
362
|
+
async propose(input, attemptId) {
|
|
363
|
+
const operation = this.queue.then(() => this.proposeOnce(input, attemptId));
|
|
364
|
+
this.queue = operation.catch(() => undefined);
|
|
365
|
+
return operation;
|
|
366
|
+
}
|
|
367
|
+
async proposeOnce(input, attemptId) {
|
|
368
|
+
await this.validateInput(input);
|
|
369
|
+
if (!uuid.test(attemptId))
|
|
370
|
+
throw new Error("Authorization attemptId must be a UUID.");
|
|
371
|
+
const prefix = "Agent Pass Plugin-";
|
|
372
|
+
// SDK 0.1.35 accepts at most 64 ASCII characters, including the product prefix.
|
|
373
|
+
const name = `${prefix}${digest({ planId: input.planId, planHash: input.planHash, attemptId }).slice(0, 64 - prefix.length)}`;
|
|
374
|
+
const list = await this.tool("list_passes", {});
|
|
375
|
+
if (!Array.isArray(list.passes))
|
|
376
|
+
throw new Error("Cannot reconcile official proposal sessions.");
|
|
377
|
+
const matches = list.passes.filter((p) => p.name === name);
|
|
378
|
+
if (matches.length > 1)
|
|
379
|
+
throw new Error("Multiple official sessions match this attempt; inspect them before proceeding.");
|
|
380
|
+
if (matches.length === 1) {
|
|
381
|
+
const found = obj(matches[0], "recovered session");
|
|
382
|
+
if (found.network !== "testnet")
|
|
383
|
+
throw new Error("Recovered session is not testnet.");
|
|
384
|
+
const info = await this.tool("session_info", {
|
|
385
|
+
pass: found.pass,
|
|
386
|
+
wait: 0,
|
|
387
|
+
});
|
|
388
|
+
return this.fromInfo(input, found.pass, info, name);
|
|
389
|
+
}
|
|
390
|
+
if (Array.isArray(list.unreadable) && list.unreadable.length)
|
|
391
|
+
throw new Error("An unreadable SDK session prevents safe proposal recovery. Inspect it before retrying.");
|
|
392
|
+
await mkdir(join(this.root, "attempts"), { recursive: true, mode: 0o700 });
|
|
393
|
+
const journal = join(this.root, "attempts", `${digest({ attemptId, planId: input.planId })}.json`);
|
|
394
|
+
// Exclusive attempt record is deliberately fail-closed after an unknown response. No new key on blind retry.
|
|
395
|
+
try {
|
|
396
|
+
await writeFile(journal, JSON.stringify({ name, inputHash: digest(input), status: "attempted" }), { mode: 0o600, flag: "wx" });
|
|
397
|
+
}
|
|
398
|
+
catch (error) {
|
|
399
|
+
if (error.code === "EEXIST")
|
|
400
|
+
throw new Error("A prior proposal attempt has an uncertain result. Reconcile the SDK sessions; do not create another key blindly.");
|
|
401
|
+
throw error;
|
|
402
|
+
}
|
|
403
|
+
const result = await this.tool("propose_authorization", {
|
|
404
|
+
name,
|
|
405
|
+
network: "testnet",
|
|
406
|
+
owner: input.expectedOwner,
|
|
407
|
+
days: input.durationDays,
|
|
408
|
+
transfers: [],
|
|
409
|
+
lending: [],
|
|
410
|
+
staking: null,
|
|
411
|
+
swaps: [
|
|
412
|
+
{
|
|
413
|
+
sell: input.coinIn.type,
|
|
414
|
+
buy: input.coinOut.type,
|
|
415
|
+
pools: [input.poolId],
|
|
416
|
+
perTrade: decimal(input.amountIn, input.coinIn.decimals),
|
|
417
|
+
daily: decimal(input.dailyLimitIn, input.coinIn.decimals),
|
|
418
|
+
limitPrice: input.limitPrice,
|
|
419
|
+
},
|
|
420
|
+
],
|
|
421
|
+
caps: {
|
|
422
|
+
[input.coinIn.type]: decimal(input.budgetIn, input.coinIn.decimals),
|
|
423
|
+
},
|
|
424
|
+
gasSui: input.gasSui,
|
|
425
|
+
gasCapSui: input.gasCapSui,
|
|
426
|
+
gasDailySui: input.gasDailySui,
|
|
427
|
+
});
|
|
428
|
+
if (result.network !== "testnet")
|
|
429
|
+
throw new Error("Official proposal returned another network.");
|
|
430
|
+
return this.fromInfo(input, result.pass, { ...result, status: "awaiting_authorization" }, name);
|
|
431
|
+
}
|
|
432
|
+
async fromInfo(input, id, info, name) {
|
|
433
|
+
const directory = this.directory(id), state = await this.session(directory), d = await this.deployment();
|
|
434
|
+
equal(state.deployment?.network, "testnet", "stored network");
|
|
435
|
+
if (info.network !== undefined)
|
|
436
|
+
equal(info.network, "testnet", "reported network");
|
|
437
|
+
equal(state.deployment?.chainIdentifier, d.chainIdentifier, "stored chain");
|
|
438
|
+
equal(address(state.deployment?.packageId), address(d.packageId), "stored package");
|
|
439
|
+
equal(address(state.deployment?.configId), address(d.configId), "stored config");
|
|
440
|
+
equal(state.deployment, d, "stored testnet deployment");
|
|
441
|
+
if (info.deployment !== undefined)
|
|
442
|
+
equal(info.deployment, d, "reported testnet deployment");
|
|
443
|
+
const setup = obj(state.setup, "normalized setup");
|
|
444
|
+
if (name !== undefined)
|
|
445
|
+
equal(setup.name, name, "proposal name");
|
|
446
|
+
const ex = expected(input, setup.name, Number(setup.expiresMs));
|
|
447
|
+
equal({
|
|
448
|
+
...setup,
|
|
449
|
+
policy: normalizedPolicy(setup.policy),
|
|
450
|
+
allowances: Object.fromEntries(Object.entries(obj(setup.allowances, "caps")).map(([k, v]) => [
|
|
451
|
+
coin(k),
|
|
452
|
+
v,
|
|
453
|
+
])),
|
|
454
|
+
}, ex.setup, "normalized proposal");
|
|
455
|
+
if (!Number.isSafeInteger(setup.expiresMs))
|
|
456
|
+
throw new Error("Invalid proposal expiry.");
|
|
457
|
+
equal(address(info.sessionAddress), address(state.sessionAddress), "session address");
|
|
458
|
+
if (info.directory && resolve(info.directory) !== directory)
|
|
459
|
+
throw new Error("Official session directory does not match the isolated root.");
|
|
460
|
+
const result = {
|
|
461
|
+
sessionId: id,
|
|
462
|
+
sessionAddress: address(state.sessionAddress),
|
|
463
|
+
reviewUrl: typeof info.reviewUrl === "string" ? info.reviewUrl : "",
|
|
464
|
+
rules: typeof info.rules === "string" ? info.rules : "",
|
|
465
|
+
warnings: Array.isArray(info.warnings) ? info.warnings.map(String) : [],
|
|
466
|
+
status: String(info.status ?? "awaiting_authorization"),
|
|
467
|
+
};
|
|
468
|
+
if (result.reviewUrl) {
|
|
469
|
+
const url = new URL(result.reviewUrl);
|
|
470
|
+
if (url.protocol !== "http:" ||
|
|
471
|
+
url.hostname !== "127.0.0.1" ||
|
|
472
|
+
url.searchParams.get("network") !== "testnet" ||
|
|
473
|
+
!url.hash.startsWith("#/authorize/"))
|
|
474
|
+
throw new Error("Unexpected official testnet review URL.");
|
|
475
|
+
if (this.options.reviewOrigin)
|
|
476
|
+
result.reviewUrl = this.themedUrl(url);
|
|
477
|
+
}
|
|
478
|
+
if (info.status === "mismatch" ||
|
|
479
|
+
info.authorizationError ||
|
|
480
|
+
info.chainError)
|
|
481
|
+
throw new Error(String(info.authorizationError ??
|
|
482
|
+
info.chainError ??
|
|
483
|
+
"The onchain pass does not match the reviewed proposal."));
|
|
484
|
+
if (!info.active) {
|
|
485
|
+
if (info.status === "closed") {
|
|
486
|
+
const active = obj(state.active, "closed session metadata");
|
|
487
|
+
equal(address(active.owner), address(input.expectedOwner), "closed owner");
|
|
488
|
+
equal(address(info.passId), address(active.passId), "closed pass");
|
|
489
|
+
// SDK 0.1.35 maps every failed object read to "closed", including RPC outages.
|
|
490
|
+
// Require an independent structured not-found/deleted result before telling the user.
|
|
491
|
+
const absent = this.options.verifyClosed
|
|
492
|
+
? await this.options.verifyClosed(d, address(active.passId))
|
|
493
|
+
: await this.verifyClosed(d, address(active.passId));
|
|
494
|
+
if (!absent)
|
|
495
|
+
throw new Error("The pass still exists; the SDK closed status is unverified.");
|
|
496
|
+
}
|
|
497
|
+
return result;
|
|
498
|
+
}
|
|
499
|
+
if (!["active", "revoked", "expired"].includes(result.status))
|
|
500
|
+
return result;
|
|
501
|
+
equal(state.active, info.active, "active session metadata");
|
|
502
|
+
const active = obj(info.active, "active session");
|
|
503
|
+
if (typeof active.authorizationDigest !== "string" ||
|
|
504
|
+
!active.authorizationDigest)
|
|
505
|
+
throw new Error("Missing verified authorization digest.");
|
|
506
|
+
const binding = {
|
|
507
|
+
network: "testnet",
|
|
508
|
+
chainIdentifier: d.chainIdentifier,
|
|
509
|
+
packageId: address(d.packageId),
|
|
510
|
+
configId: address(d.configId),
|
|
511
|
+
deploymentHash: digest(d),
|
|
512
|
+
planHash: input.planHash,
|
|
513
|
+
owner: address(input.expectedOwner),
|
|
514
|
+
sessionAddress: result.sessionAddress,
|
|
515
|
+
passId: address(active.passId),
|
|
516
|
+
sessionId: id,
|
|
517
|
+
directory,
|
|
518
|
+
authorizationDigest: active.authorizationDigest,
|
|
519
|
+
policyHash: digest(ex),
|
|
520
|
+
expiresAt: new Date(setup.expiresMs).toISOString(),
|
|
521
|
+
poolId: address(input.poolId),
|
|
522
|
+
coinIn: structuredClone(input.coinIn),
|
|
523
|
+
coinOut: structuredClone(input.coinOut),
|
|
524
|
+
expected: ex,
|
|
525
|
+
};
|
|
526
|
+
assertLiveAuthorization(info, binding);
|
|
527
|
+
const gas = this.options.readGasAllowance
|
|
528
|
+
? await this.options.readGasAllowance(info)
|
|
529
|
+
: await this.gasAllowance(info);
|
|
530
|
+
assertLiveAuthorization(info, binding, gas);
|
|
531
|
+
assertBindingPolicy(binding, input);
|
|
532
|
+
result.binding = binding;
|
|
533
|
+
return result;
|
|
534
|
+
}
|
|
535
|
+
async verifyClosed(deployment, passId) {
|
|
536
|
+
const moduleName = "@mysten-incubation/sui-agent-pass/chain";
|
|
537
|
+
const chain = (await import(moduleName));
|
|
538
|
+
const client = chain.clientFor(deployment);
|
|
539
|
+
try {
|
|
540
|
+
await chain.assertChain(client, deployment);
|
|
541
|
+
await client.getObject({
|
|
542
|
+
objectId: passId,
|
|
543
|
+
signal: AbortSignal.timeout(12_000),
|
|
544
|
+
});
|
|
545
|
+
return false;
|
|
546
|
+
}
|
|
547
|
+
catch (error) {
|
|
548
|
+
const cause = error;
|
|
549
|
+
if (["notFound", "deleted"].includes(String(cause?.reason)) &&
|
|
550
|
+
typeof cause?.objectId === "string" &&
|
|
551
|
+
address(cause.objectId) === address(passId))
|
|
552
|
+
return true;
|
|
553
|
+
throw new Error("Could not independently verify pass closure on testnet. Chain status is unknown; retry the read.");
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
async gasAllowance(info) {
|
|
557
|
+
const moduleName = "@mysten-incubation/sui-agent-pass/chain";
|
|
558
|
+
const chain = (await import(moduleName));
|
|
559
|
+
return chain.readAllowance(chain.clientFor(info.deployment), info.active.gasAllowance, SUI);
|
|
560
|
+
}
|
|
561
|
+
async inspect(input, authorization) {
|
|
562
|
+
await this.validateInput(input);
|
|
563
|
+
this.directory(authorization.sessionId);
|
|
564
|
+
const info = await this.tool("session_info", {
|
|
565
|
+
pass: authorization.sessionId,
|
|
566
|
+
wait: 0,
|
|
567
|
+
});
|
|
568
|
+
equal(address(info.sessionAddress), address(authorization.sessionAddress), "persisted session address");
|
|
569
|
+
let next;
|
|
570
|
+
try {
|
|
571
|
+
next = await this.fromInfo(input, authorization.sessionId, info);
|
|
572
|
+
}
|
|
573
|
+
catch (error) {
|
|
574
|
+
if (!(error instanceof AuthorizationEndedError))
|
|
575
|
+
throw error;
|
|
576
|
+
return { ...authorization, status: error.status, binding: undefined };
|
|
577
|
+
}
|
|
578
|
+
if (authorization.binding && next.binding)
|
|
579
|
+
equal(next.binding, authorization.binding, "persisted binding");
|
|
580
|
+
return {
|
|
581
|
+
...next,
|
|
582
|
+
rules: next.rules || authorization.rules,
|
|
583
|
+
reviewUrl: next.reviewUrl || authorization.reviewUrl,
|
|
584
|
+
warnings: next.warnings.length ? next.warnings : authorization.warnings,
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
async revoke(binding) {
|
|
588
|
+
this.directory(binding.sessionId);
|
|
589
|
+
if (resolve(binding.directory) !== this.directory(binding.sessionId))
|
|
590
|
+
throw new Error("Invalid isolated session directory.");
|
|
591
|
+
const result = await this.tool("revoke_pass", { pass: binding.sessionId });
|
|
592
|
+
equal(result.network, "testnet", "revoke network");
|
|
593
|
+
equal(address(result.sessionAddress), address(binding.sessionAddress), "revoke agent");
|
|
594
|
+
equal(address(result.passId), address(binding.passId), "revoke pass");
|
|
595
|
+
const url = new URL(result.passUrl);
|
|
596
|
+
if (url.protocol !== "http:" ||
|
|
597
|
+
url.hostname !== "127.0.0.1" ||
|
|
598
|
+
url.searchParams.get("network") !== "testnet" ||
|
|
599
|
+
url.hash !== `#/pass/${binding.passId}`)
|
|
600
|
+
throw new Error("Unexpected testnet revocation URL.");
|
|
601
|
+
return {
|
|
602
|
+
reviewUrl: this.themedUrl(url),
|
|
603
|
+
alreadyRevoked: result.alreadyRevoked === true,
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
themedUrl(url) {
|
|
607
|
+
if (this.options.reviewOrigin) {
|
|
608
|
+
const origin = new URL(this.options.reviewOrigin);
|
|
609
|
+
if (origin.protocol !== "http:" || origin.hostname !== "127.0.0.1")
|
|
610
|
+
throw new Error("SDK review UI must use loopback.");
|
|
611
|
+
url.host = origin.host;
|
|
612
|
+
}
|
|
613
|
+
return url.toString();
|
|
614
|
+
}
|
|
615
|
+
async close() {
|
|
616
|
+
await this.client?.close();
|
|
617
|
+
this.client = undefined;
|
|
618
|
+
this.connecting = undefined;
|
|
619
|
+
}
|
|
620
|
+
}
|