@mysten-incubation/sui-agent-pass 0.1.9 → 0.1.11
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 +4 -3
- package/deployments/mainnet.json +1 -0
- package/deployments/testnet.json +1 -0
- package/dist/describe.js +5 -2
- package/dist/domain.js +48 -20
- package/dist/explorer.js +16 -0
- package/dist/float.js +3 -1
- package/dist/mcp.js +22 -1
- package/dist/owner.js +3 -1
- package/dist/plugin.js +42 -9
- package/dist/server.js +2 -1
- package/dist/signer.js +8 -7
- package/dist/storage.js +13 -1
- package/docs/AGENT.md +6 -1
- package/docs/PLAYBOOK.md +21 -8
- package/package.json +3 -3
- package/skills/agent-pass/SKILL.md +21 -8
- package/web-dist/assets/{index-Bt0vwsup.js → index-7G6YmGOW.js} +62 -62
- package/web-dist/assets/{mount-D_hAnWmA.js → mount-62qnVZBM.js} +1 -1
- package/web-dist/deployments/mainnet.json +1 -0
- package/web-dist/deployments/testnet.json +1 -0
- package/web-dist/index.html +1 -1
package/README.md
CHANGED
|
@@ -38,9 +38,10 @@ serves compatibility tests with small sums until launch.
|
|
|
38
38
|
|
|
39
39
|
The agent pays its own gas from the session address. Setup seeds an initial gas stipend and issues
|
|
40
40
|
a separate small SUI allowance for gas; when the session's balance runs low the agent tops it up
|
|
41
|
-
from that allowance, within its own lifetime cap and
|
|
42
|
-
|
|
43
|
-
|
|
41
|
+
from that allowance, within its own lifetime cap and a limit per 24 hours from its first top-up,
|
|
42
|
+
so gas spend is bounded apart from the asset rules, whose daily limits reset at 00:00 UTC
|
|
43
|
+
(`docs/ARCHITECTURE.md` §7). Owners cannot bill an agent's transaction gas to the wallet
|
|
44
|
+
directly yet, because gas is authorized by a signature and `sui::allowance` cannot authorize it.
|
|
44
45
|
|
|
45
46
|
Transfers and staking are the real thing on every network. DeepBook, Cetus and NAVI are called
|
|
46
47
|
through their mainnet interfaces; off mainnet the demo publishes local stand-ins with the same
|
package/deployments/mainnet.json
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
"packageId": "0x4c9010b0be6022e8a4bd91219d5174edc36d524b42d4790784035f424e01f403",
|
|
6
6
|
"publishedAt": "0x08d82880b61c531ffbe9eb9eccf3c025d6182ec50f7f61e1f6095a6b81a1f744",
|
|
7
7
|
"configId": "0xf7b33e20564b26c0685b8d86669345a0121ff6b290911a04f1ff37fcd1f5716d",
|
|
8
|
+
"maxTermDays": 30,
|
|
8
9
|
"siteUrl": "https://sui-agent-pass.vercel.app",
|
|
9
10
|
"coins": [
|
|
10
11
|
{
|
package/deployments/testnet.json
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
"packageId": "0xfea0b9f60c752e98e950c1994a3805ba28c5f559e3ea72da2ac3d68b90728b11",
|
|
6
6
|
"publishedAt": "0xfea0b9f60c752e98e950c1994a3805ba28c5f559e3ea72da2ac3d68b90728b11",
|
|
7
7
|
"configId": "0x3bb796cd3fe0d9b85b1db972478616e717fe5bdbd1ff864615a3995f4e1c1c60",
|
|
8
|
+
"maxTermDays": 30,
|
|
8
9
|
"coins": [
|
|
9
10
|
{
|
|
10
11
|
"type": "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
|
package/dist/describe.js
CHANGED
|
@@ -105,7 +105,7 @@ export function describeSetup(d, setup) {
|
|
|
105
105
|
.join(', '),
|
|
106
106
|
},
|
|
107
107
|
{
|
|
108
|
-
label: 'Max gas allowance, lifetime / per
|
|
108
|
+
label: 'Max gas allowance, lifetime / per 24 hours from first top-up',
|
|
109
109
|
value: `${showCoin(d, SUI, setup.gasCap)} / ${showCoin(d, SUI, setup.gasDaily)}`,
|
|
110
110
|
},
|
|
111
111
|
{
|
|
@@ -277,6 +277,8 @@ const normalizeType = (type) => type.replace(/^0x0*([0-9a-f]+)::/i, (_, a) => `$
|
|
|
277
277
|
/** The owner's rule behind an abort, from the codes the policy modules define. */
|
|
278
278
|
export function describeRefusal(d, error, recipient) {
|
|
279
279
|
const abort = error.MoveAbort;
|
|
280
|
+
if (error.message === 'InsufficientBalanceForWithdraw')
|
|
281
|
+
return "The owner's address balance does not hold enough of this coin right now. This is not one of the owner's rules: the action can run once the balance covers it (InsufficientBalanceForWithdraw)";
|
|
280
282
|
if (!abort?.location?.module)
|
|
281
283
|
return error.message;
|
|
282
284
|
const code = Number(abort.cleverError?.errorCode ?? abort.abortCode);
|
|
@@ -286,7 +288,8 @@ export function describeRefusal(d, error, recipient) {
|
|
|
286
288
|
const system = {
|
|
287
289
|
allowance: {
|
|
288
290
|
3: "Over the lifetime cap of the owner's allowance for this coin (checked before the daily limit, so when the two are equal the day is used up as well)",
|
|
289
|
-
|
|
291
|
+
// Only the gas allowance has a rate limit; the asset allowances have caps alone.
|
|
292
|
+
4: "Over the gas allowance's limit per 24 hours from first top-up",
|
|
290
293
|
},
|
|
291
294
|
validator_set: { 10: 'Below the 1 SUI minimum stake', 0: 'Not an active validator' },
|
|
292
295
|
};
|
package/dist/domain.js
CHANGED
|
@@ -5,6 +5,8 @@ import { z } from 'zod';
|
|
|
5
5
|
/** The gas coin, in the normalized spelling every coin-keyed record uses. */
|
|
6
6
|
export const SUI = normalizeStructTag('0x2::sui::SUI');
|
|
7
7
|
export const DAY_MS = 86_400_000;
|
|
8
|
+
/** The longest agent term the current contract accepts (`MAX_TERM_MS` in `control.move`). */
|
|
9
|
+
export const MAX_TERM_DAYS = 365;
|
|
8
10
|
/** NAVI's fixed-point scale for health factors: 1e27 is 1.0. */
|
|
9
11
|
export const RAY = 10n ** 27n;
|
|
10
12
|
export const address = z
|
|
@@ -151,6 +153,8 @@ export const DeploymentSchema = z
|
|
|
151
153
|
coins: z.array(CoinSchema).min(1),
|
|
152
154
|
/** The pools a swap rule can list, in either direction. */
|
|
153
155
|
pools: z.array(PoolSchema),
|
|
156
|
+
/** The longest agent term, in days, this deployment's contract accepts. */
|
|
157
|
+
maxTermDays: z.number().int().min(1).max(MAX_TERM_DAYS),
|
|
154
158
|
/** A demo stablecoin's faucet, which the authorization mints from instead of converting coins. */
|
|
155
159
|
demoFaucet: z
|
|
156
160
|
.object({ packageId: address, faucetId: address, coin: coinType })
|
|
@@ -244,9 +248,9 @@ const ttlMs = z
|
|
|
244
248
|
.number()
|
|
245
249
|
.int()
|
|
246
250
|
.positive()
|
|
247
|
-
.max(
|
|
251
|
+
.max(MAX_TERM_DAYS * DAY_MS);
|
|
248
252
|
const gasAmount = positive;
|
|
249
|
-
/** Absolute end of the agent's term, written on chain
|
|
253
|
+
/** Absolute end of the agent's term, written on chain, within the deployment's `maxTermDays`. */
|
|
250
254
|
const expiresMs = z.number().int().positive();
|
|
251
255
|
const name = z.string().regex(/^[\x20-\x7e]{1,64}$/);
|
|
252
256
|
/**
|
|
@@ -262,12 +266,13 @@ export const SetupSchema = z
|
|
|
262
266
|
/** Lifetime caps, by coin type: the hard backstop under the policies. */
|
|
263
267
|
allowances: z.record(coinType, positive),
|
|
264
268
|
gasAmount,
|
|
265
|
-
/** A separate SUI allowance for gas top-ups: lifetime cap and
|
|
269
|
+
/** A separate SUI allowance for gas top-ups: lifetime cap and a 24-hour window that the
|
|
270
|
+
* framework starts at the first top-up, not at UTC midnight. */
|
|
266
271
|
gasCap: positive,
|
|
267
272
|
gasDaily: positive,
|
|
268
273
|
})
|
|
269
274
|
.strict()
|
|
270
|
-
.refine((s) => BigInt(s.gasDaily) <= BigInt(s.gasCap), '
|
|
275
|
+
.refine((s) => BigInt(s.gasDaily) <= BigInt(s.gasCap), 'The 24-hour gas limit must not exceed the gas lifetime cap')
|
|
271
276
|
.refine((s) => {
|
|
272
277
|
const caps = new Set(Object.keys(s.allowances).map((c) => normalizeStructTag(c)));
|
|
273
278
|
const spent = spentCoins(s.policy);
|
|
@@ -391,8 +396,8 @@ export function limitDisplay(d, coinIn, coinOut, minPrice) {
|
|
|
391
396
|
}
|
|
392
397
|
/** Health factors are entered with two decimals and stored on chain in ray units. */
|
|
393
398
|
export const healthFactorRay = (hf) => hf === null ? '0' : ((BigInt(units(hf.toFixed(2), 2)) * RAY) / 100n).toString();
|
|
394
|
-
/** Gas top-ups per
|
|
395
|
-
* agent burns the gas budget over days, not hours. */
|
|
399
|
+
/** Gas top-ups per 24-hour window when the owner names none: a fifth of the lifetime cap, so a
|
|
400
|
+
* runaway agent burns the gas budget over days, not hours. */
|
|
396
401
|
export const defaultGasDaily = (gasCap) => {
|
|
397
402
|
const fifth = BigInt(gasCap) / 5n;
|
|
398
403
|
return (fifth > 0n ? fifth : BigInt(gasCap)).toString();
|
|
@@ -409,25 +414,48 @@ export function drawable(setup) {
|
|
|
409
414
|
return Object.fromEntries(Object.entries(need).map(([c, v]) => [c, v.toString()]));
|
|
410
415
|
}
|
|
411
416
|
/**
|
|
412
|
-
* Allowances draw only from the owner's address balance, never from coin objects.
|
|
413
|
-
* authorization converts
|
|
414
|
-
*
|
|
415
|
-
*
|
|
417
|
+
* Allowances draw only from the owner's address balance, never from coin objects. The
|
|
418
|
+
* authorization converts coin objects into that balance, per coin, as far as the rules can draw
|
|
419
|
+
* (`drawable`) and the owner has them; the caps are limits, not money that must exist at signing.
|
|
420
|
+
* SUI keeps the stipend and the fee reserve in coin objects for the transaction itself. `mintable`
|
|
421
|
+
* is a demo coin the transaction mints instead, converted in full. Converted coins stay the
|
|
422
|
+
* owner's to spend.
|
|
416
423
|
*/
|
|
417
|
-
export function conversion(setup, held) {
|
|
418
|
-
const
|
|
419
|
-
return Object.fromEntries(Object.entries(drawable(setup)).map(([coin, want]) =>
|
|
420
|
-
coin
|
|
421
|
-
|
|
422
|
-
|
|
424
|
+
export function conversion(setup, held, mintable = null) {
|
|
425
|
+
const of = (coin) => held[normalizeStructTag(coin)];
|
|
426
|
+
return Object.fromEntries(Object.entries(drawable(setup)).map(([coin, want]) => {
|
|
427
|
+
const short = BigInt(want) - BigInt(of(coin)?.addressBalance ?? '0');
|
|
428
|
+
if (short <= 0n)
|
|
429
|
+
return [coin, '0'];
|
|
430
|
+
if (mintable && sameCoin(mintable, coin))
|
|
431
|
+
return [coin, short.toString()];
|
|
432
|
+
let spare = BigInt(of(coin)?.coinBalance ?? '0');
|
|
433
|
+
if (sameCoin(coin, SUI))
|
|
434
|
+
spare -= BigInt(setup.gasAmount) + OWNER_FEE_RESERVE;
|
|
435
|
+
return [coin, (spare <= 0n ? 0n : short < spare ? short : spare).toString()];
|
|
436
|
+
}));
|
|
423
437
|
}
|
|
424
438
|
/**
|
|
425
|
-
*
|
|
426
|
-
*
|
|
427
|
-
*
|
|
439
|
+
* What the rules can draw beyond what the address balance will hold right after signing, per
|
|
440
|
+
* coin. Not an error: withdrawals work while the balance covers them, and swap proceeds land in
|
|
441
|
+
* it. Coins with nothing uncovered are left out.
|
|
442
|
+
*/
|
|
443
|
+
export function uncovered(setup, held, mintable = null) {
|
|
444
|
+
const convert = conversion(setup, held, mintable);
|
|
445
|
+
return Object.fromEntries(Object.entries(drawable(setup)).flatMap(([coin, want]) => {
|
|
446
|
+
const covered = BigInt(held[normalizeStructTag(coin)]?.addressBalance ?? '0') +
|
|
447
|
+
BigInt(convert[coin] ?? '0');
|
|
448
|
+
return covered >= BigInt(want)
|
|
449
|
+
? []
|
|
450
|
+
: [[coin, { drawable: want, covered: covered.toString() }]];
|
|
451
|
+
}));
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* SUI the owner must hold to sign, address balance and coin objects together: only what this
|
|
455
|
+
* transaction moves, the agent's gas stipend, plus a fee reserve. The caps need nothing up front.
|
|
428
456
|
*/
|
|
429
457
|
export function requiredSui(setup) {
|
|
430
|
-
return (BigInt(
|
|
458
|
+
return (BigInt(setup.gasAmount) + OWNER_FEE_RESERVE).toString();
|
|
431
459
|
}
|
|
432
460
|
/** Set aside for the owner's own transaction fees when checking what they hold. */
|
|
433
461
|
export const OWNER_FEE_RESERVE = 50000000n;
|
package/dist/explorer.js
CHANGED
|
@@ -127,6 +127,22 @@ export async function agentAttempts(client, d, agent, recipients, limit = 30) {
|
|
|
127
127
|
});
|
|
128
128
|
return page.transactions.map((r) => describeAttempt(d, agent, recipients, (r.Transaction ?? r.FailedTransaction)));
|
|
129
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Recent transactions sent from a session address that are not among the digests this machine
|
|
132
|
+
* signed for it: the key is being used somewhere else. Newest first.
|
|
133
|
+
*/
|
|
134
|
+
export async function foreignTransactions(client, sessionAddress, signed, limit = 50) {
|
|
135
|
+
const page = await client.listTransactions({
|
|
136
|
+
filter: { sender: sessionAddress },
|
|
137
|
+
order: 'descending',
|
|
138
|
+
limit,
|
|
139
|
+
include: {},
|
|
140
|
+
});
|
|
141
|
+
return page.transactions
|
|
142
|
+
.map((r) => (r.Transaction ?? r.FailedTransaction))
|
|
143
|
+
.filter((t) => !signed.has(t.digest))
|
|
144
|
+
.map((t) => ({ digest: t.digest, success: t.status.success }));
|
|
145
|
+
}
|
|
130
146
|
/** Every recent call into the package's `pass` module, from any agent or owner. */
|
|
131
147
|
export async function packageFeed(client, d, limit = 40) {
|
|
132
148
|
const page = await client.listTransactions({
|
package/dist/float.js
CHANGED
|
@@ -69,8 +69,10 @@ async function sweepOnce(client, directory, sessionAddress, owner) {
|
|
|
69
69
|
if (float <= budget)
|
|
70
70
|
return null;
|
|
71
71
|
const amount = float - budget;
|
|
72
|
+
const bytes = await build(amount, budget).build({ client });
|
|
73
|
+
await SessionStore.recordSigned(directory, await Transaction.from(bytes).getDigest());
|
|
72
74
|
const result = await client.signAndExecuteTransaction({
|
|
73
|
-
transaction:
|
|
75
|
+
transaction: bytes,
|
|
74
76
|
signer: await SessionStore.keyOf(directory),
|
|
75
77
|
});
|
|
76
78
|
if (result.$kind !== 'Transaction')
|
package/dist/mcp.js
CHANGED
|
@@ -7,6 +7,8 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
|
7
7
|
import { z } from 'zod';
|
|
8
8
|
import { clientFor, deepbookSizes, readAllHoldings, readStatus } from './chain.js';
|
|
9
9
|
import { coinInfo, DAY_MS } from './domain.js';
|
|
10
|
+
import { foreignTransactions } from './explorer.js';
|
|
11
|
+
import { SessionStore } from './storage.js';
|
|
10
12
|
export const result = (value) => ({
|
|
11
13
|
content: [{ type: 'text', text: JSON.stringify(value) }],
|
|
12
14
|
});
|
|
@@ -14,6 +16,9 @@ export const failure = (error, fallback) => ({
|
|
|
14
16
|
...result({ error: error instanceof Error ? error.message : fallback }),
|
|
15
17
|
isError: true,
|
|
16
18
|
});
|
|
19
|
+
/** Array elements and object members one tool call's arguments may hold. The largest real input,
|
|
20
|
+
* a full rule set, is a few hundred; the SDK validates without a limit unless one is set. */
|
|
21
|
+
export const MAX_TOOL_INPUT_ELEMENTS = 10_000;
|
|
17
22
|
/**
|
|
18
23
|
* What every client shows the model before any tool call, so a plain request ("sell 0.05 SUI")
|
|
19
24
|
* is enough: no resource to know about, no project file to read.
|
|
@@ -131,6 +136,21 @@ export async function venues(client, d) {
|
|
|
131
136
|
* Everything an agent needs to act: identity, live rules and usage, connection details and the
|
|
132
137
|
* SDK. `directory` is the session directory when the server knows it, for `Agent.open`.
|
|
133
138
|
*/
|
|
139
|
+
/**
|
|
140
|
+
* When the chain shows transactions from the session address that this machine never signed, the
|
|
141
|
+
* agent key is in use somewhere else; the agent must tell the owner, who can stop it.
|
|
142
|
+
*/
|
|
143
|
+
export async function keyAlert(client, directory, sessionAddress) {
|
|
144
|
+
const foreign = await foreignTransactions(client, sessionAddress, await SessionStore.signedDigests(directory)).catch(() => []);
|
|
145
|
+
if (!foreign.length)
|
|
146
|
+
return {};
|
|
147
|
+
return {
|
|
148
|
+
keyAlert: {
|
|
149
|
+
transactions: foreign,
|
|
150
|
+
note: `The chain shows ${foreign.length} transaction(s) from this agent key that this machine never signed, so a copy of the key is being used elsewhere. Tell the owner now, list the digests, and ask them to use "Stop the agent now" on the pass page (revoke_pass opens it). Do not act with this key until they decide.`,
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
134
154
|
export async function sessionInfo(identity, directory = null) {
|
|
135
155
|
const { deployment: d, active, sessionAddress } = identity;
|
|
136
156
|
const client = clientFor(d);
|
|
@@ -142,6 +162,7 @@ export async function sessionInfo(identity, directory = null) {
|
|
|
142
162
|
readAllHoldings(client, d, active.owner).catch(() => null),
|
|
143
163
|
]);
|
|
144
164
|
return {
|
|
165
|
+
...(directory ? await keyAlert(client, directory, sessionAddress) : {}),
|
|
145
166
|
...identity,
|
|
146
167
|
...status,
|
|
147
168
|
...(directory ? { directory } : {}),
|
|
@@ -194,7 +215,7 @@ export function registerDocs(server) {
|
|
|
194
215
|
}
|
|
195
216
|
/** The single-session server behind the authenticated HTTP transport. */
|
|
196
217
|
export function createMcp(identity, signer, directory = null) {
|
|
197
|
-
const server = new McpServer({ name: 'sui-agent-pass', version: '0.1.0' }, { instructions: INSTRUCTIONS });
|
|
218
|
+
const server = new McpServer({ name: 'sui-agent-pass', version: '0.1.0' }, { instructions: INSTRUCTIONS, maxToolInputElements: MAX_TOOL_INPUT_ELEMENTS });
|
|
198
219
|
registerDocs(server);
|
|
199
220
|
server.registerTool('session_info', {
|
|
200
221
|
description: "Read the pass's installed policies with their live usage, the owner's balances and allowances, the agent term, protocol object IDs, Sui connection details and the SDK install command. Act with a Node script against the SDK, which signs here and submits to Sui itself; or build your own PTB, call sign_transaction and submit the returned bytes and signature yourself.",
|
package/dist/owner.js
CHANGED
|
@@ -138,7 +138,9 @@ function rateLimitOption(tx, dailyLimit) {
|
|
|
138
138
|
}
|
|
139
139
|
/**
|
|
140
140
|
* A separate, non-app-bound SUI allowance the agent spends to top up its own gas float. Its own
|
|
141
|
-
* lifetime cap and
|
|
141
|
+
* lifetime cap and 24-hour window bound gas spend independently of the asset-management
|
|
142
|
+
* allowances. `periodic_rate_limit` starts its windows at the first successful charge, so the
|
|
143
|
+
* window runs from the agent's first top-up rather than from UTC midnight like the policy meters.
|
|
142
144
|
*/
|
|
143
145
|
function issueGasAllowance(tx, setup, session) {
|
|
144
146
|
tx.moveCall({
|
package/dist/plugin.js
CHANGED
|
@@ -20,12 +20,12 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/
|
|
|
20
20
|
import { Transaction } from '@mysten/sui/transactions';
|
|
21
21
|
import { fromBase64, normalizeSuiAddress } from '@mysten/sui/utils';
|
|
22
22
|
import { z } from 'zod';
|
|
23
|
-
import { clientFor, deepbookSizes, findPools, quoteSwap, readAllHoldings, readStatus, withMarketFacts, } from './chain.js';
|
|
23
|
+
import { clientFor, deepbookSizes, findPools, quoteSwap, readAllHoldings, readHoldings, readStatus, withMarketFacts, } from './chain.js';
|
|
24
24
|
import { describePolicy, describeSetup, renderRows } from './describe.js';
|
|
25
|
-
import { address, coinBySymbol, coinInfo, DAY_MS, defaultGasDaily, DeploymentSchema, display, isStable, limitUnits, poolsFor, recipientName, sameCoin, SetupSchema, showCoin, units, VenueSchema, } from './domain.js';
|
|
25
|
+
import { address, coinBySymbol, coinInfo, DAY_MS, defaultGasDaily, DeploymentSchema, display, isStable, limitUnits, MAX_TERM_DAYS, poolsFor, recipientName, requiredSui, sameCoin, SetupSchema, showCoin, SUI, uncovered, units, VenueSchema, } from './domain.js';
|
|
26
26
|
import { passesByAgent } from './explorer.js';
|
|
27
27
|
import { passEnded, returnGasFloat } from './float.js';
|
|
28
|
-
import { failure, INSTRUCTIONS, registerDocs, result, serverInfo, sessionInfo, SIGN_ANNOTATIONS, SIGN_DESCRIPTION, } from './mcp.js';
|
|
28
|
+
import { failure, INSTRUCTIONS, keyAlert, MAX_TOOL_INPUT_ELEMENTS, registerDocs, result, serverInfo, sessionInfo, SIGN_ANNOTATIONS, SIGN_DESCRIPTION, } from './mcp.js';
|
|
29
29
|
import { authenticated, body, ownerPageUrl, startServer } from './server.js';
|
|
30
30
|
import { SessionSigner } from './signer.js';
|
|
31
31
|
import { SessionStore, token } from './storage.js';
|
|
@@ -125,7 +125,7 @@ class Registry {
|
|
|
125
125
|
return session.server;
|
|
126
126
|
}
|
|
127
127
|
async signer(session) {
|
|
128
|
-
session.signer ??= new SessionSigner(await session.store.key(), session.store.state.deployment.chainIdentifier);
|
|
128
|
+
session.signer ??= new SessionSigner(await session.store.key(), session.store.state.deployment.chainIdentifier, (digest) => SessionStore.recordSigned(session.store.directory, digest));
|
|
129
129
|
return session.signer;
|
|
130
130
|
}
|
|
131
131
|
async close() {
|
|
@@ -295,6 +295,8 @@ async function toSetup(client, d0, input) {
|
|
|
295
295
|
pools: input.swaps.flatMap((sw) => sw.pools ?? []),
|
|
296
296
|
});
|
|
297
297
|
const coin = (s) => (isType(s) ? coinInfo(d, s) : coinBySymbol(d, s)), inUnits = (s, v) => units(v, coin(s).decimals), sui = (v) => units(v, 9);
|
|
298
|
+
if (input.days > d0.maxTermDays)
|
|
299
|
+
throw new Error(`The contract on ${d0.network} accepts an agent term of at most ${d0.maxTermDays} days; propose ${d0.maxTermDays} or fewer`);
|
|
298
300
|
const ttlMs = input.days * DAY_MS, gasCap = sui(input.gasCapSui);
|
|
299
301
|
const setup = SetupSchema.parse({
|
|
300
302
|
name: input.name,
|
|
@@ -383,6 +385,9 @@ async function summaryWithChain(s) {
|
|
|
383
385
|
const extra = onChain?.filter((c) => c.live && c.id !== state.active?.passId) ?? [];
|
|
384
386
|
return {
|
|
385
387
|
...base,
|
|
388
|
+
...(state.active && !closed
|
|
389
|
+
? await keyAlert(client, s.store.directory, state.sessionAddress)
|
|
390
|
+
: {}),
|
|
386
391
|
...(closed
|
|
387
392
|
? {
|
|
388
393
|
status: 'closed',
|
|
@@ -422,6 +427,7 @@ async function poolPrice(d, p) {
|
|
|
422
427
|
export function createPluginMcp(registry) {
|
|
423
428
|
const server = new McpServer({ name: 'agent-pass', version: '0.1.0' }, {
|
|
424
429
|
instructions: `${INSTRUCTIONS} This server also runs the owner flow: propose_authorization turns reviewed rules into a pass proposal and opens the owner's wallet page; session_info (with wait) reports when the owner has signed and the on-chain policies match; revoke_pass reopens the owner page for revocation. Show the owner the exact "rules" text returned by propose_authorization before they sign; never paraphrase amounts.`,
|
|
430
|
+
maxToolInputElements: MAX_TOOL_INPUT_ELEMENTS,
|
|
425
431
|
});
|
|
426
432
|
registerDocs(server);
|
|
427
433
|
server.registerTool('list_passes', {
|
|
@@ -436,6 +442,7 @@ export function createPluginMcp(registry) {
|
|
|
436
442
|
const path = registry.deploymentPath();
|
|
437
443
|
const markets = async (d) => ({
|
|
438
444
|
network: d.network,
|
|
445
|
+
maxTermDays: d.maxTermDays,
|
|
439
446
|
coins: d.coins,
|
|
440
447
|
pools: await Promise.all(d.pools.map(async (p) => ({
|
|
441
448
|
venue: p.venue,
|
|
@@ -511,7 +518,12 @@ export function createPluginMcp(registry) {
|
|
|
511
518
|
.regex(/^[\x20-\x7e]{1,64}$/)
|
|
512
519
|
.default('Agent session'),
|
|
513
520
|
...rulesInput,
|
|
514
|
-
days: z
|
|
521
|
+
days: z
|
|
522
|
+
.number()
|
|
523
|
+
.int()
|
|
524
|
+
.min(1)
|
|
525
|
+
.max(MAX_TERM_DAYS)
|
|
526
|
+
.describe("agent term; at most the network's maxTermDays from list_passes"),
|
|
515
527
|
gasSui: decimal
|
|
516
528
|
.default('0.05')
|
|
517
529
|
.describe('gas stipend to the agent address, outside the rules'),
|
|
@@ -520,7 +532,7 @@ export function createPluginMcp(registry) {
|
|
|
520
532
|
.describe('lifetime SUI the agent may pull to top up its gas, a separate allowance'),
|
|
521
533
|
gasDailySui: decimal
|
|
522
534
|
.optional()
|
|
523
|
-
.describe('SUI the agent may pull for gas per UTC day; defaults to a fifth of gasCapSui'),
|
|
535
|
+
.describe('SUI the agent may pull for gas in each 24 hours counted from its first top-up, not per UTC day; defaults to a fifth of gasCapSui'),
|
|
524
536
|
network: z
|
|
525
537
|
.enum(['mainnet', 'testnet', 'devnet', 'localnet'])
|
|
526
538
|
.optional()
|
|
@@ -529,9 +541,12 @@ export function createPluginMcp(registry) {
|
|
|
529
541
|
.string()
|
|
530
542
|
.optional()
|
|
531
543
|
.describe('path of a private deployment.json; overrides network'),
|
|
544
|
+
owner: address
|
|
545
|
+
.optional()
|
|
546
|
+
.describe("the owner's address, when they gave it: adds warnings where the caps reach past what they hold, or when they cannot sign yet"),
|
|
532
547
|
},
|
|
533
548
|
annotations: { readOnlyHint: false, destructiveHint: false },
|
|
534
|
-
}, async ({ deployment, network, ...input }) => {
|
|
549
|
+
}, async ({ deployment, network, owner, ...input }) => {
|
|
535
550
|
try {
|
|
536
551
|
const d0 = await registry.deployment(deployment, network);
|
|
537
552
|
const { setup, d } = await toSetup(clientFor(d0), d0, input);
|
|
@@ -557,6 +572,17 @@ export function createPluginMcp(registry) {
|
|
|
557
572
|
warnings.push(`DeepBook takes its fee from the input and fills nothing under its minimum order, so a sale needs at least ${showCoin(d, sw.coinIn, floor)} and this pass allows ${showCoin(d, sw.coinIn, sw.perTrade)}: no sale could ever happen. Propose again with Cetus added to venues or a larger perTrade, unless the owner wants exactly this.`);
|
|
558
573
|
}
|
|
559
574
|
}
|
|
575
|
+
if (owner) {
|
|
576
|
+
const holdings = await readHoldings(clientFor(d), d, owner).catch(() => null);
|
|
577
|
+
if (holdings) {
|
|
578
|
+
const sui = holdings[SUI];
|
|
579
|
+
const total = BigInt(sui?.addressBalance ?? '0') + BigInt(sui?.coinBalance ?? '0');
|
|
580
|
+
if (total < BigInt(requiredSui(setup)))
|
|
581
|
+
warnings.push(`The owner holds ${showCoin(d, SUI, total.toString())} and signing needs ${showCoin(d, SUI, requiredSui(setup))} for the agent's gas stipend and the fee; they must add SUI before they can sign.`);
|
|
582
|
+
for (const [coin, { drawable: most, covered }] of Object.entries(uncovered(setup, holdings, d.demoFaucet?.coin ?? null)))
|
|
583
|
+
warnings.push(`The rules can draw up to ${showCoin(d, coin, most)} but the owner's address balance will hold ${showCoin(d, coin, covered)} after signing. Signing still works; each action runs only while the balance covers it, and swap proceeds that land there count. Tell the owner before they sign.`);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
560
586
|
return result({
|
|
561
587
|
pass: session.id,
|
|
562
588
|
sessionAddress: session.store.state.sessionAddress,
|
|
@@ -671,9 +697,16 @@ export function createPluginMcp(registry) {
|
|
|
671
697
|
.optional()
|
|
672
698
|
.describe('pass id prefix from list_passes; omit if there is one'),
|
|
673
699
|
...rulesInput,
|
|
674
|
-
days: z
|
|
700
|
+
days: z
|
|
701
|
+
.number()
|
|
702
|
+
.int()
|
|
703
|
+
.min(1)
|
|
704
|
+
.max(MAX_TERM_DAYS)
|
|
705
|
+
.describe("agent term from now; at most the network's maxTermDays"),
|
|
675
706
|
gasCapSui: decimal.describe('lifetime SUI the agent may pull to top up its gas'),
|
|
676
|
-
gasDailySui: decimal
|
|
707
|
+
gasDailySui: decimal
|
|
708
|
+
.optional()
|
|
709
|
+
.describe('per 24 hours counted from the first top-up, not per UTC day; defaults to a fifth of gasCapSui'),
|
|
677
710
|
},
|
|
678
711
|
annotations: { readOnlyHint: false, destructiveHint: false },
|
|
679
712
|
}, async ({ pass, ...input }) => {
|
package/dist/server.js
CHANGED
|
@@ -19,6 +19,7 @@ import { findPassByAgent } from './explorer.js';
|
|
|
19
19
|
import { passClosed, returnGasFloat } from './float.js';
|
|
20
20
|
import { createMcp, sessionInfo } from './mcp.js';
|
|
21
21
|
import { SessionSigner } from './signer.js';
|
|
22
|
+
import { SessionStore } from './storage.js';
|
|
22
23
|
export function authenticated(request, expected) {
|
|
23
24
|
const supplied = Buffer.from(request.headers.authorization ?? ''), wanted = Buffer.from(`Bearer ${expected}`);
|
|
24
25
|
return supplied.length === wanted.length && timingSafeEqual(supplied, wanted);
|
|
@@ -102,7 +103,7 @@ async function sweepGasIfEnded(store, client) {
|
|
|
102
103
|
export async function startServer(store, port = 0) {
|
|
103
104
|
const d = store.state.deployment, client = clientFor(d);
|
|
104
105
|
await assertChain(client, d);
|
|
105
|
-
const mcpToken = await store.mcpToken(), signer = new SessionSigner(await store.key(), d.chainIdentifier);
|
|
106
|
+
const mcpToken = await store.mcpToken(), signer = new SessionSigner(await store.key(), d.chainIdentifier, (digest) => SessionStore.recordSigned(store.directory, digest));
|
|
106
107
|
let origin = '', closed = false;
|
|
107
108
|
const webRoot = fileURLToPath(new URL('../web-dist/', import.meta.url));
|
|
108
109
|
const server = createServer(async (request, response) => {
|
package/dist/signer.js
CHANGED
|
@@ -5,9 +5,13 @@ import { fromBase64, normalizeSuiAddress, toBase64 } from '@mysten/sui/utils';
|
|
|
5
5
|
export class SessionSigner {
|
|
6
6
|
key;
|
|
7
7
|
chainIdentifier;
|
|
8
|
-
|
|
8
|
+
record;
|
|
9
|
+
constructor(key, chainIdentifier,
|
|
10
|
+
/** Called with each digest before its signature is returned. */
|
|
11
|
+
record) {
|
|
9
12
|
this.key = key;
|
|
10
13
|
this.chainIdentifier = chainIdentifier;
|
|
14
|
+
this.record = record;
|
|
11
15
|
}
|
|
12
16
|
get address() {
|
|
13
17
|
return this.key.toSuiAddress();
|
|
@@ -29,12 +33,9 @@ export class SessionSigner {
|
|
|
29
33
|
throw new Error('Transaction must carry a ValidDuring/Validity expiration bound to the configured chain (use address-balance gas)');
|
|
30
34
|
// Sign precisely the supplied bytes with Sui's TransactionData intent. No rebuilding,
|
|
31
35
|
// simulation, submission, arbitrary-message signing, or financial allowlist here.
|
|
36
|
+
const digest = await tx.getDigest();
|
|
37
|
+
await this.record(digest);
|
|
32
38
|
const signed = await this.key.signTransaction(bytes);
|
|
33
|
-
return {
|
|
34
|
-
bytes: signed.bytes,
|
|
35
|
-
signature: signed.signature,
|
|
36
|
-
digest: await tx.getDigest(),
|
|
37
|
-
signer: this.address,
|
|
38
|
-
};
|
|
39
|
+
return { bytes: signed.bytes, signature: signed.signature, digest, signer: this.address };
|
|
39
40
|
}
|
|
40
41
|
}
|
package/dist/storage.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: Apache-2.0
|
|
3
3
|
/** Disk owns session persistence; it does not decide whether a chain session is valid. */
|
|
4
4
|
import { randomBytes } from 'node:crypto';
|
|
5
|
-
import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { appendFile, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
6
6
|
import { join } from 'node:path';
|
|
7
7
|
import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
|
|
8
8
|
import { normalizeSuiAddress } from '@mysten/sui/utils';
|
|
@@ -80,6 +80,18 @@ export class SessionStore {
|
|
|
80
80
|
throw new Error('session.key must be accessible only to its owner (chmod 600)');
|
|
81
81
|
return Ed25519Keypair.fromSecretKey((await readFile(path, 'utf8')).trim());
|
|
82
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* Notes a digest this machine signed with the session key, before the signature leaves it. The
|
|
85
|
+
* key signs nowhere else, so a transaction from the session address missing here was signed
|
|
86
|
+
* by a copy of the key.
|
|
87
|
+
*/
|
|
88
|
+
static async recordSigned(directory, digest) {
|
|
89
|
+
await appendFile(join(directory, 'signed.log'), `${digest}\n`, { mode: 0o600 });
|
|
90
|
+
}
|
|
91
|
+
static async signedDigests(directory) {
|
|
92
|
+
const text = await readFile(join(directory, 'signed.log'), 'utf8').catch(() => '');
|
|
93
|
+
return new Set(text.split('\n').filter(Boolean));
|
|
94
|
+
}
|
|
83
95
|
/** Deletes a session directory, key included. Callers make sure nothing on chain still needs it. */
|
|
84
96
|
static async forget(directory) {
|
|
85
97
|
await rm(directory, { recursive: true, force: true });
|
package/docs/AGENT.md
CHANGED
|
@@ -173,12 +173,17 @@ window; `0x3::validator_set` 10 below the 1 SUI minimum stake.
|
|
|
173
173
|
| `pass::deepbook_base_to_quote` / `deepbook_quote_to_base` | `[base, quote]` | pass, config, allowance, withdrawal, a DeepBook pool from `deployment.pools` (`coinA` is base, `coinB` quote), min_out, clock |
|
|
174
174
|
| `pass::cetus_a_to_b` / `cetus_b_to_a` | `[a, b]` | pass, config, allowance, withdrawal, `protocols.cetus.configId`, a Cetus pool from `deployment.pools`, min_out, clock |
|
|
175
175
|
| `pass::navi_supply` | `[coin]` | pass, config, allowance, withdrawal, `navi.storageId`, `navi.reserves[coin].poolId`, `navi.reserves[coin].assetId`, `navi.incentiveV2Id`, `navi.incentiveV3Id`, clock |
|
|
176
|
-
| `pass::
|
|
176
|
+
| `pass::navi_withdraw_v2` / `navi_borrow_v2` | `[coin]` | pass, config, `navi.oracleId`, storage, pool, asset, incentiveV2, incentiveV3, `0x5`, amount, clock |
|
|
177
177
|
| `pass::navi_repay` | `[coin]` | pass, config, allowance, withdrawal, oracle, storage, pool, asset, incentiveV2, incentiveV3, clock |
|
|
178
178
|
| `pass::stake` | | pass, config, SUI allowance, withdrawal, `0x5`, validator address, clock; returns the stake's ID |
|
|
179
179
|
| `pass::unstake` | | pass, config, `0x5`, stake ID, clock |
|
|
180
180
|
| `pass::add_policy`, `remove_policy`, `set_agent`, `rotate_allowance`, `revoke_agent`, `deposit_object`, `withdraw_object`, `navi_open`, `destroy` | | **owner sender only**; installs take `config` after the pass, exits do not |
|
|
181
181
|
|
|
182
|
+
The agent's actions and the owner's calls on a live pass are `entry` functions: a transaction
|
|
183
|
+
calls them directly, and other packages cannot. The calls that run while a new pass is still
|
|
184
|
+
unshared (`create`, `issue`, `add_policy`, `navi_open`, `deposit_object`), the ones that return
|
|
185
|
+
a value (`remove_policy`, `withdraw_object`) and the getters are `public`.
|
|
186
|
+
|
|
182
187
|
The allowance for a spend is `active.allowances[coin].allowance`, one per coin the rules
|
|
183
188
|
spend; the withdrawal's `type` is the coin, `from` is `"allowance"` and `funder` is
|
|
184
189
|
`active.owner`. Withdraw, borrow and unstake take a plain amount or ID because nothing leaves
|
package/docs/PLAYBOOK.md
CHANGED
|
@@ -78,14 +78,22 @@ the allowance back. A supply-and-withdraw or stake-and-unstake cycle costs the a
|
|
|
78
78
|
size lending and staking limits for the cycles the agent will run, and tell the owner when they
|
|
79
79
|
ask for something like "restake with a better validator".
|
|
80
80
|
|
|
81
|
-
**Term and gas.** `days` is the agent's term, 1 to
|
|
81
|
+
**Term and gas.** `days` is the agent's term, from 1 up to the network's `maxTermDays` in
|
|
82
|
+
`list_passes`. `gasSui` (default 0.05) is a stipend sent
|
|
82
83
|
to the agent key, outside the rules. `gasCapSui` (default 0.1) is a separate allowance the key
|
|
83
|
-
draws on to top up its gas, and `gasDailySui` (default a fifth of `gasCapSui`) its
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
84
|
+
draws on to top up its gas, and `gasDailySui` (default a fifth of `gasCapSui`) its limit per 24
|
|
85
|
+
hours from the first top-up. Call it that, not a limit per UTC day like the asset limits.
|
|
86
|
+
|
|
87
|
+
**What the owner needs.** Signing moves only the agent's gas stipend and pays the fee, so that is
|
|
88
|
+
all the owner must hold, in SUI. The caps are limits on what the rules may draw later, not money
|
|
89
|
+
needed now. Allowances draw only from the owner's address balance, never from coin objects; the
|
|
90
|
+
signature converts the owner's coin objects into that balance as far as each cap needs and they
|
|
91
|
+
have them, and the converted coins stay theirs. When a cap reaches past what the owner holds,
|
|
92
|
+
signing still works: each action runs while the balance covers it, and swap proceeds landing
|
|
93
|
+
there count right away, which is how a chain like TAKE to SUI to USDC funds its later legs. Pass
|
|
94
|
+
`owner` to `propose_authorization` when you know the address, and tell the owner about any
|
|
95
|
+
`warnings` it returns before they sign. An action refused because the balance was short is not
|
|
96
|
+
one of the owner's rules; say so.
|
|
89
97
|
|
|
90
98
|
Before you call anything, show the owner the rules you intend to propose as one short list and
|
|
91
99
|
ask for a yes, unless they already stated every rule explicitly.
|
|
@@ -125,6 +133,11 @@ Start with `session_info`. It returns:
|
|
|
125
133
|
- `directory`, `sdk` and `server`: the session directory, how to install and import the SDK,
|
|
126
134
|
and this server's version (after an upgrade the client must restart the server).
|
|
127
135
|
|
|
136
|
+
**Key alert.** When `list_passes` or `session_info` carries `keyAlert`, the chain shows
|
|
137
|
+
transactions from the agent key that this machine never signed: a copy of the key is in use
|
|
138
|
+
elsewhere. Stop acting, tell the owner at once with the digests, and offer `revoke_pass` so they
|
|
139
|
+
can stop the agent from the pass page.
|
|
140
|
+
|
|
128
141
|
**Updates.** When `server.update` is present in `list_passes` or `session_info`, a newer release
|
|
129
142
|
is out. Tell the owner once per conversation, with `server.update.command` and the reminder to
|
|
130
143
|
restart the agent afterwards, then carry on with the task; never run the command yourself.
|
|
@@ -172,7 +185,7 @@ enforcement. `submit` tops up your gas from the gas allowance when it runs low.
|
|
|
172
185
|
`@mysten/sui` following the guide, sign it with `sign_transaction` and execute it yourself. Every
|
|
173
186
|
spend takes the allowance object and a withdrawal input right after the pass. On this path gas is
|
|
174
187
|
yours: when the key holds under 0.01 SUI, draw on the gas allowance as the guide shows. That
|
|
175
|
-
allowance has its own cap and
|
|
188
|
+
allowance has its own cap and 24-hour limit and never touches the asset caps.
|
|
176
189
|
|
|
177
190
|
## 4. Report the state
|
|
178
191
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mysten-incubation/sui-agent-pass",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.11",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "AI builds transactions. A session signer signs. Your pass enforces the rules.",
|
|
6
6
|
"repository": {
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
},
|
|
66
66
|
"dependencies": {
|
|
67
67
|
"@inquirer/prompts": "7.10.1",
|
|
68
|
-
"@modelcontextprotocol/sdk": "1.
|
|
68
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
69
69
|
"@mysten-incubation/dev-wallet": "0.5.1",
|
|
70
70
|
"@mysten/dapp-kit-core": "1.6.33",
|
|
71
71
|
"@mysten/dapp-kit-react": "2.1.35",
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
"prettier": "3.6.2",
|
|
90
90
|
"tsx": "4.23.15",
|
|
91
91
|
"typescript": "5.9.2",
|
|
92
|
-
"vite": "7.3.
|
|
92
|
+
"vite": "7.3.7"
|
|
93
93
|
},
|
|
94
94
|
"overrides": {
|
|
95
95
|
"axios": ">=1.18.0"
|