@mysten-incubation/sui-agent-pass 0.1.27 → 0.1.29

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.
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "network": "mainnet",
3
3
  "grpcUrl": "https://fullnode.mainnet.sui.io:443",
4
+ "graphqlUrl": "https://graphql.mainnet.sui.io/graphql",
4
5
  "chainIdentifier": "4btiuiMPvEENsttpZC7CZ53DruC3MAgfznDbASZ7DR6S",
5
6
  "packageId": "0x389b58171d057852dd4b071d47474a2a97a6e4489cc2094a527a57d57d58063f",
6
- "publishedAt": "0x389b58171d057852dd4b071d47474a2a97a6e4489cc2094a527a57d57d58063f",
7
+ "publishedAt": "0x21eff2fccc83a6c5ec789a0a44a73b7b7884eb50c418abb41796ac14a1fe4683",
7
8
  "configId": "0xd300382e608b07f96796e707ab92253597fc4c199172cc35627aad6c2d243f2c",
8
9
  "coins": [
9
10
  {
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "network": "testnet",
3
3
  "grpcUrl": "https://fullnode.testnet.sui.io:443",
4
+ "graphqlUrl": "https://graphql.testnet.sui.io/graphql",
4
5
  "chainIdentifier": "69WiPg3DAQiwdxfncX6wYQ2siKwAe6L9BZthQea3JNMD",
5
- "packageId": "0xb6e9d01e6718cf1ccc33598efc892e1891f564f82824cd4af5b7d40160e21bf0",
6
- "publishedAt": "0xb6e9d01e6718cf1ccc33598efc892e1891f564f82824cd4af5b7d40160e21bf0",
7
- "configId": "0xe465c9fc3225454f16f2212136f6b2ccea2dc5d4168502b42bbdff548dbca7c8",
6
+ "packageId": "0x00ab15079b220610fc6b22c44c0d1d9de5e614bf3249aac06c966f4f60903293",
7
+ "publishedAt": "0x00ab15079b220610fc6b22c44c0d1d9de5e614bf3249aac06c966f4f60903293",
8
+ "configId": "0x742f3b1ffd770d06308a72bb31265d85b2bfdfbeff82742788960f07830af35d",
8
9
  "coins": [
9
10
  {
10
11
  "type": "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
@@ -12,37 +13,59 @@
12
13
  "decimals": 9
13
14
  },
14
15
  {
15
- "type": "0x6829a10a5340763ad78735fea97f9e26c02cd774bb20cb1d12615b1e54e8deeb::usdc::USDC",
16
+ "type": "0x6547c10c36c29651d59686f3b5017eafd5ac8bce26e6e500368f8ec650188a72::usdc::USDC",
16
17
  "symbol": "USDC",
17
18
  "decimals": 6
18
19
  }
19
20
  ],
20
- "pools": [],
21
+ "pools": [
22
+ {
23
+ "venue": "deepbook",
24
+ "poolId": "0xfdadb096936979e624522b70f90234ad11bca114f658d2c7127bbcb98b193a69",
25
+ "coinA": "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
26
+ "coinB": "0x6547c10c36c29651d59686f3b5017eafd5ac8bce26e6e500368f8ec650188a72::usdc::USDC"
27
+ },
28
+ {
29
+ "venue": "cetus",
30
+ "poolId": "0x925f8ac4fdda84240133b447e575170a037be2e639d29647048a9b2df2d8d4d8",
31
+ "coinA": "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",
32
+ "coinB": "0x6547c10c36c29651d59686f3b5017eafd5ac8bce26e6e500368f8ec650188a72::usdc::USDC"
33
+ }
34
+ ],
21
35
  "maxTermDays": 365,
22
36
  "demoFaucet": {
23
- "packageId": "0x6829a10a5340763ad78735fea97f9e26c02cd774bb20cb1d12615b1e54e8deeb",
24
- "faucetId": "0xc93883668a3e6b44e8333936ea9e2817805be1f0d673a6887a78b3156e2e9ed4",
25
- "coin": "0x6829a10a5340763ad78735fea97f9e26c02cd774bb20cb1d12615b1e54e8deeb::usdc::USDC"
37
+ "packageId": "0x6547c10c36c29651d59686f3b5017eafd5ac8bce26e6e500368f8ec650188a72",
38
+ "faucetId": "0x371cc8f33cdbad58441aba8d828d29a341285136bc6a67bb9dc4344527ae8728",
39
+ "coin": "0x6547c10c36c29651d59686f3b5017eafd5ac8bce26e6e500368f8ec650188a72::usdc::USDC"
26
40
  },
27
41
  "protocols": {
28
42
  "deepbook": {
29
- "packageId": "0x5151e1122073b79c9aafeff11a10420d6c9c0d2d03a7428fa908ace0d368ebcb",
30
- "publishedAt": "0x5151e1122073b79c9aafeff11a10420d6c9c0d2d03a7428fa908ace0d368ebcb"
43
+ "packageId": "0xde09a6a70f6247b6bd843fa6c58d985c5fbde193ce1fc451210f213dea5fb805",
44
+ "publishedAt": "0xde09a6a70f6247b6bd843fa6c58d985c5fbde193ce1fc451210f213dea5fb805"
31
45
  },
32
46
  "cetus": {
33
- "packageId": "0x62618216842046496e2dfc46400a116558d474a595ccb1bfffbea0ba6e032885",
34
- "publishedAt": "0x62618216842046496e2dfc46400a116558d474a595ccb1bfffbea0ba6e032885",
35
- "configId": "0x1ba07f13168a8ce9016d4c11cf3c9e82b5750904d5ebd065b802d04e4497386c"
47
+ "packageId": "0x6389949994451e382b6e3f71ff60c8aeb7991c22626c64a9c0704c751ae3e762",
48
+ "publishedAt": "0x6389949994451e382b6e3f71ff60c8aeb7991c22626c64a9c0704c751ae3e762",
49
+ "configId": "0xca499c91f302284d5a71b85f2fda768ca58ff88e95ec73c69fb64d96dec7d809"
36
50
  },
37
51
  "navi": {
38
- "packageId": "0xac15f2796ef5484dc66e0ffe17464c9858f0b5d8cd199a05f0346dda0e0f6ab2",
39
- "publishedAt": "0xac15f2796ef5484dc66e0ffe17464c9858f0b5d8cd199a05f0346dda0e0f6ab2",
40
- "oraclePackageId": "0xf817a7885d31650680d4eeb2e55220316f57f902a23a1648f3d469876463a45d",
41
- "storageId": "0x073f220b58dd691ffa01505274677784472450ca845c813b3ee77fa8fc8654e3",
42
- "oracleId": "0x8c9198b2eca4e9b08b456a23ba2c9862df34e06b350f3912320250dfd1cc235f",
43
- "incentiveV2Id": "0xcc1b64820185219fe7554ea223a238aecece52733f772c76adcc94b2b68df60f",
44
- "incentiveV3Id": "0x24c969a0d6006b7b5e9cb0920b9ade50ba8acbfb30f5d5d5928538feb1984a4e",
45
- "reserves": {}
52
+ "packageId": "0xdaa41ff6a374d2e73f1750fbc707919e7cce491b4d0c3ef8ff7d8bbc880798e9",
53
+ "publishedAt": "0xdaa41ff6a374d2e73f1750fbc707919e7cce491b4d0c3ef8ff7d8bbc880798e9",
54
+ "oraclePackageId": "0xdcb7679d0bbc6577471f0d8e1f827f8c32f239fc1b5a993b3b5e0c7f5ab415ed",
55
+ "storageId": "0xe61937792bad26e06ae8a8238a42ff29c581ebb48167f54ef58b1d351e886b81",
56
+ "oracleId": "0xc56207ad573d9ccdddf9e8fe5f56f28b284504d836014ce31964cad70acbd0f2",
57
+ "incentiveV2Id": "0x9bc5bf093fef467da7c9830a180d0a2407074d401f8d15a50a289888b2747c6f",
58
+ "incentiveV3Id": "0x5af68707c38587a0a2a82ebdd147d3d6db8f0ab154e9e1564eab8717652ce48b",
59
+ "reserves": {
60
+ "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI": {
61
+ "poolId": "0xb1f1ef1f05c7236b3f0709bfd84200381a7fe2804531411ecb1b2ffb5ba001f2",
62
+ "assetId": 0
63
+ },
64
+ "0x6547c10c36c29651d59686f3b5017eafd5ac8bce26e6e500368f8ec650188a72::usdc::USDC": {
65
+ "poolId": "0xdc1b1f1e94654adfc08af5457e4f23c2375ad465bd1295b88dcb1c55b38eecfa",
66
+ "assetId": 1
67
+ }
68
+ }
46
69
  }
47
70
  }
48
71
  }
@@ -245,16 +245,25 @@ export async function applyPendingChange(store) {
245
245
  });
246
246
  return true;
247
247
  }
248
+ /** The pass on chain is not the one the owner reviewed; a failed chain read is any other error. */
249
+ export class RulesMismatch extends Error {
250
+ }
248
251
  export async function activate(store, digest, ownerInput) {
249
252
  const { deployment: d, setup, sessionAddress } = store.state;
250
253
  const owner = normalizeSuiAddress(ownerInput), client = clientFor(d);
251
254
  await assertChain(client, d);
252
255
  const tx = await readAuthorization(client, d, digest);
253
- if (tx.sender !== owner)
254
- throw new Error('Authorization sender does not match connected wallet');
255
- const active = await verifySession(store, tx, owner, digest);
256
- assertOnlyReviewedGrants(tx.objects, active);
257
- assertExactStipend(tx.balanceChanges, sessionAddress, SUI, setup.gasAmount);
256
+ let active;
257
+ try {
258
+ if (tx.sender !== owner)
259
+ throw new Error('Authorization sender does not match connected wallet');
260
+ active = await verifySession(store, tx, owner, digest);
261
+ assertOnlyReviewedGrants(tx.objects, active);
262
+ assertExactStipend(tx.balanceChanges, sessionAddress, SUI, setup.gasAmount);
263
+ }
264
+ catch (error) {
265
+ throw new RulesMismatch(error.message);
266
+ }
258
267
  await store.activate(active);
259
268
  return active;
260
269
  }
package/dist/agent.js CHANGED
@@ -13,7 +13,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
13
13
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
14
14
  import { Inputs, Transaction } from '@mysten/sui/transactions';
15
15
  import { fromBase64, normalizeStructTag, normalizeSuiAddress, toBase64 } from '@mysten/sui/utils';
16
- import { activeValidators, clientFor, quoteSwap, readAllowance, readControl } from './chain.js';
16
+ import { activeValidators, buildResignation, clientFor, quoteSwap, readAllowance, readControl, } from './chain.js';
17
17
  import { describeRefusal } from './describe.js';
18
18
  import { poolsFor, sameCoin, SUI, } from './domain.js';
19
19
  import { refreshNaviPrices } from './navi.js';
@@ -498,6 +498,13 @@ export function stake(i, amount, validator) {
498
498
  });
499
499
  return tx;
500
500
  }
501
+ /**
502
+ * Give up this key's authority for good: the chain refuses every later action under the pass.
503
+ * The owner closes the pass from its page when they want the storage deposit back.
504
+ */
505
+ export function resign(i) {
506
+ return buildResignation(i.deployment, i.active.passId);
507
+ }
501
508
  /** Withdraw one held stake, principal and rewards, into the owner's balance. No allowance is drawn. */
502
509
  export function unstake(i, stakeId) {
503
510
  const d = i.deployment, tx = new Transaction();
package/dist/chain.js CHANGED
@@ -153,6 +153,12 @@ export const allowanceType = (coin) => `0x2::allowance::Allowance<0x2::balance::
153
153
  export const allowanceCapType = (coin) => `0x2::allowance::AllowanceCap<0x2::balance::Balance<${coin}>>`;
154
154
  export const policyType = (d, module, name, typeArguments) => normalizeStructTag(`${d.packageId}::${module}::${name}${typeArguments.length ? `<${typeArguments.join(',')}>` : ''}`);
155
155
  const typeNameTag = (name) => normalizeStructTag(`0x${name}`);
156
+ /** The agent's own ending: `pass::resign`, signed by the session key; see `agent.resign`. */
157
+ export function buildResignation(d, passId) {
158
+ const tx = new Transaction();
159
+ tx.moveCall({ target: `${d.publishedAt}::pass::resign`, arguments: [tx.object(passId)] });
160
+ return tx;
161
+ }
156
162
  export async function readAuthorization(client, d, digest) {
157
163
  const result = await client.waitForTransaction({
158
164
  digest,
package/dist/describe.js CHANGED
@@ -252,6 +252,9 @@ export function describeAttempt(d, sessionAddress, recipients, tx) {
252
252
  what = `Unstake ${stake ? short(stake) : 'a stake'} back to your balance`;
253
253
  break;
254
254
  }
255
+ case 'resign':
256
+ what = 'Give up the agent key: the pass refuses it from now on';
257
+ break;
255
258
  default:
256
259
  what = OWNER_ONLY.has(main.function)
257
260
  ? `Call the owner-only ${main.module}::${main.function}`
package/dist/domain.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // Copyright (c) Mysten Labs, Inc.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
+ import { bcs } from '@mysten/sui/bcs';
3
4
  import { fromBase64, isValidSuiAddress, normalizeStructTag, normalizeSuiAddress, toBase64, } from '@mysten/sui/utils';
5
+ import { verifyPersonalMessageSignature } from '@mysten/sui/verify';
4
6
  import { z } from 'zod';
5
7
  /** The gas coin, in the normalized spelling every coin-keyed record uses. */
6
8
  export const SUI = normalizeStructTag('0x2::sui::SUI');
@@ -137,6 +139,8 @@ export const DeploymentSchema = z
137
139
  .object({
138
140
  network: z.enum(['localnet', 'testnet', 'devnet', 'mainnet']),
139
141
  grpcUrl: z.string().url(),
142
+ /** Serves the histories (passes created, an address's transactions) a pruned full node cannot. */
143
+ graphqlUrl: z.string().url().optional(),
140
144
  chainIdentifier: z.string().min(1),
141
145
  /** The original package: every type of the pass is addressed by it. */
142
146
  packageId: address,
@@ -259,11 +263,117 @@ export const ProposalSchema = z
259
263
  passId: address.optional(),
260
264
  })
261
265
  .strict();
262
- export const encodeProposal = (p) => toBase64(new TextEncoder().encode(JSON.stringify(ProposalSchema.parse(p))))
263
- .replaceAll('+', '-')
264
- .replaceAll('/', '_')
265
- .replace(/=+$/, '');
266
- export const decodeProposal = (s) => ProposalSchema.parse(JSON.parse(new TextDecoder().decode(fromBase64(s.replaceAll('-', '+').replaceAll('_', '/')))));
266
+ // The link's binary form. Amounts travel as u64, addresses as 32 bytes, so the link is short and
267
+ // its bytes are canonical for the signature. The health factor is a decimal string because BCS
268
+ // has no float; the session address is not here because the signature carries the key.
269
+ const ProposalBcs = bcs.struct('Proposal', {
270
+ v: bcs.u8(),
271
+ setup: bcs.struct('Setup', {
272
+ name: bcs.string(),
273
+ policy: bcs.struct('Policy', {
274
+ transfers: bcs.vector(bcs.struct('Transfer', {
275
+ coin: bcs.string(),
276
+ recipients: bcs.vector(bcs.struct('Recipient', { name: bcs.string(), address: bcs.Address })),
277
+ perTransfer: bcs.u64(),
278
+ daily: bcs.u64(),
279
+ })),
280
+ swaps: bcs.vector(bcs.struct('Swap', {
281
+ coinIn: bcs.string(),
282
+ coinOut: bcs.string(),
283
+ pools: bcs.vector(bcs.Address),
284
+ perTrade: bcs.u64(),
285
+ daily: bcs.u64(),
286
+ minPrice: bcs.u64(),
287
+ })),
288
+ lending: bcs.vector(bcs.struct('Lending', {
289
+ coin: bcs.string(),
290
+ allowBorrow: bcs.bool(),
291
+ perAction: bcs.u64(),
292
+ daily: bcs.u64(),
293
+ minHealthFactor: bcs.option(bcs.string()),
294
+ })),
295
+ staking: bcs.option(bcs.struct('Staking', {
296
+ validators: bcs.vector(bcs.Address),
297
+ perStake: bcs.u64(),
298
+ daily: bcs.u64(),
299
+ })),
300
+ }),
301
+ ttlMs: bcs.u64(),
302
+ expiresMs: bcs.u64(),
303
+ allowances: bcs.vector(bcs.struct('Allowance', { coin: bcs.string(), cap: bcs.u64() })),
304
+ gasAmount: bcs.u64(),
305
+ gasCap: bcs.u64(),
306
+ gasDaily: bcs.u64(),
307
+ }),
308
+ passId: bcs.option(bcs.Address),
309
+ });
310
+ const base64url = (bytes) => toBase64(bytes).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
311
+ const fromBase64url = (s) => fromBase64(s.replaceAll('-', '+').replaceAll('_', '/'));
312
+ /**
313
+ * The link payload: the proposal's bytes and the session key's signature over them, joined by a
314
+ * dot. The link passes through an agent's hands as text, so the page refuses one that changed on
315
+ * the way, and a proposal can only come from the key it is for.
316
+ */
317
+ export async function encodeProposal(p, key) {
318
+ const { sessionAddress, setup, ...rest } = ProposalSchema.parse(p);
319
+ if (key.toSuiAddress() !== sessionAddress)
320
+ throw new Error('A proposal is signed by the session key it is for');
321
+ const bytes = ProposalBcs.serialize({
322
+ ...rest,
323
+ setup: {
324
+ ...setup,
325
+ policy: {
326
+ ...setup.policy,
327
+ lending: setup.policy.lending.map((l) => ({
328
+ ...l,
329
+ minHealthFactor: l.minHealthFactor === null ? null : String(l.minHealthFactor),
330
+ })),
331
+ },
332
+ allowances: Object.entries(setup.allowances).map(([coin, cap]) => ({ coin, cap })),
333
+ },
334
+ passId: rest.passId ?? null,
335
+ }).toBytes();
336
+ const { signature } = await key.signPersonalMessage(bytes);
337
+ return `${base64url(bytes)}.${base64url(fromBase64(signature))}`;
338
+ }
339
+ export class AlteredLinkError extends Error {
340
+ }
341
+ export async function decodeProposal(s) {
342
+ const [payload, sig] = s.split('.');
343
+ if (!payload || !sig)
344
+ throw new AlteredLinkError('This link is incomplete');
345
+ let bytes, raw;
346
+ try {
347
+ bytes = fromBase64url(payload);
348
+ raw = ProposalBcs.parse(bytes);
349
+ }
350
+ catch {
351
+ throw new AlteredLinkError('This link was changed after the agent created it');
352
+ }
353
+ const key = await verifyPersonalMessageSignature(bytes, base64urlToStd(sig)).catch(() => null);
354
+ if (!key)
355
+ throw new AlteredLinkError('This link was changed after the agent created it');
356
+ const { passId, ...rest } = raw;
357
+ return ProposalSchema.parse({
358
+ ...rest,
359
+ sessionAddress: key.toSuiAddress(),
360
+ setup: {
361
+ ...raw.setup,
362
+ ttlMs: Number(raw.setup.ttlMs),
363
+ expiresMs: Number(raw.setup.expiresMs),
364
+ policy: {
365
+ ...raw.setup.policy,
366
+ lending: raw.setup.policy.lending.map((l) => ({
367
+ ...l,
368
+ minHealthFactor: l.minHealthFactor === null ? null : Number(l.minHealthFactor),
369
+ })),
370
+ },
371
+ allowances: Object.fromEntries(raw.setup.allowances.map((a) => [a.coin, a.cap])),
372
+ },
373
+ ...(passId ? { passId } : {}),
374
+ });
375
+ }
376
+ const base64urlToStd = (s) => toBase64(fromBase64url(s));
267
377
  const ttlMs = z
268
378
  .number()
269
379
  .int()
package/dist/explorer.js CHANGED
@@ -5,10 +5,57 @@
5
5
  * session state. Browser-safe: no Node imports.
6
6
  */
7
7
  import { bcs } from '@mysten/sui/bcs';
8
- import { deriveObjectID, normalizeSuiAddress } from '@mysten/sui/utils';
8
+ import { deriveObjectID, fromBase64, normalizeSuiAddress } from '@mysten/sui/utils';
9
9
  import { createdEventType, discoverAllowances, parseCreated, readControl, } from './chain.js';
10
10
  import { describeAttempt } from './describe.js';
11
+ /**
12
+ * Enumerations go through GraphQL where a deployment names it: a pruned public full node refuses
13
+ * any gRPC listing that would reach past what it retains, even newest-first, so the whole page
14
+ * fails once the package's history outgrows the node's window. Object reads, transaction detail
15
+ * and execution stay on gRPC.
16
+ */
17
+ async function graphql(url, query, variables) {
18
+ const res = await fetch(url, {
19
+ method: 'POST',
20
+ headers: { 'content-type': 'application/json' },
21
+ body: JSON.stringify({ query, variables }),
22
+ });
23
+ if (!res.ok)
24
+ throw new Error(`GraphQL ${url}: HTTP ${res.status}`);
25
+ const body = (await res.json());
26
+ if (body.errors?.length)
27
+ throw new Error(`GraphQL ${url}: ${body.errors.map((e) => e.message).join('; ')}`);
28
+ if (!body.data)
29
+ throw new Error(`GraphQL ${url}: empty response`);
30
+ return body.data;
31
+ }
32
+ /** Newest first: a page of `last` nodes before the cursor, which GraphQL orders oldest first. */
33
+ async function latest(url, field, selection, filterType, filter, limit, before) {
34
+ const data = await graphql(url, `query($filter: ${filterType}, $limit: Int!, $before: String) { ${field}(last: $limit, before: $before, filter: $filter) { pageInfo { hasPreviousPage startCursor } nodes { ${selection} } } }`, { filter, limit, before });
35
+ const page = data[field];
36
+ return {
37
+ nodes: page.nodes.slice().reverse(),
38
+ hasNextPage: page.pageInfo.hasPreviousPage,
39
+ endCursor: page.pageInfo.startCursor,
40
+ };
41
+ }
42
+ /** Digests of the newest transactions matching the filter, through GraphQL. */
43
+ async function latestDigests(url, filter, limit) {
44
+ const { nodes } = await latest(url, 'transactions', 'digest', 'TransactionFilter', filter, limit, null);
45
+ return nodes.map((n) => n.digest);
46
+ }
11
47
  async function createdEvents(client, d, limit, before = null) {
48
+ if (d.graphqlUrl) {
49
+ const { nodes, hasNextPage, endCursor } = await latest(d.graphqlUrl, 'events', 'timestamp contents { bcs } transaction { digest }', 'EventFilter', { type: createdEventType(d) }, limit, before);
50
+ const summaries = nodes
51
+ .filter((e) => e.contents && e.transaction)
52
+ .map((e) => ({
53
+ ...parseCreated(fromBase64(e.contents.bcs)),
54
+ digest: e.transaction.digest,
55
+ timestampMs: e.timestamp ? Date.parse(e.timestamp) : null,
56
+ }));
57
+ return { summaries, hasNextPage, endCursor };
58
+ }
12
59
  // Newest first; a continuation reads the page before the last cursor.
13
60
  const page = await client.listEvents({
14
61
  filter: { eventType: createdEventType(d) },
@@ -40,7 +87,11 @@ export async function findPassByAgent(client, d, agent) {
40
87
  const id = passIdOf(d, agent);
41
88
  const found = await client
42
89
  .getObject({ objectId: id, include: { previousTransaction: true } })
43
- .catch(() => null);
90
+ .catch((error) => {
91
+ if (error?.code === 'notExists')
92
+ return null;
93
+ throw error;
94
+ });
44
95
  if (!found?.object.previousTransaction)
45
96
  return null;
46
97
  const { owner } = await readControl(client, d, id);
@@ -90,42 +141,33 @@ export async function discoverActive(client, d, pass) {
90
141
  };
91
142
  }
92
143
  const include = { transaction: true, balanceChanges: true };
144
+ /** The newest transactions matching the filter, newest first, as the gRPC listing returns them. */
145
+ async function sentTransactions(client, d, filter, limit, included) {
146
+ const listed = d.graphqlUrl
147
+ ? await Promise.all((await latestDigests(d.graphqlUrl, 'sender' in filter ? { sentAddress: filter.sender } : filter, limit)).map((digest) => client.getTransaction({ digest, include: included })))
148
+ : (await client.listTransactions({ filter, order: 'descending', limit, include: included }))
149
+ .transactions;
150
+ return listed.map((r) => (r.Transaction ?? r.FailedTransaction));
151
+ }
93
152
  /** The agent's most recent transactions, newest first, read straight from the chain. */
94
153
  export async function agentAttempts(client, d, agent, recipients, limit = 30) {
95
- const page = await client.listTransactions({
96
- filter: { sender: agent },
97
- order: 'descending',
98
- limit,
99
- include,
100
- });
101
- return page.transactions.map((r) => describeAttempt(d, agent, recipients, (r.Transaction ?? r.FailedTransaction)));
154
+ const transactions = await sentTransactions(client, d, { sender: agent }, limit, include);
155
+ return transactions.map((tx) => describeAttempt(d, agent, recipients, tx));
102
156
  }
103
157
  /**
104
158
  * Recent transactions sent from a session address that are not among the digests this machine
105
159
  * signed for it: the key is being used somewhere else. Newest first.
106
160
  */
107
- export async function foreignTransactions(client, sessionAddress, signed, limit = 50) {
108
- const page = await client.listTransactions({
109
- filter: { sender: sessionAddress },
110
- order: 'descending',
111
- limit,
112
- include: {},
113
- });
114
- return page.transactions
115
- .map((r) => (r.Transaction ?? r.FailedTransaction))
161
+ export async function foreignTransactions(client, d, sessionAddress, signed, limit = 50) {
162
+ const transactions = await sentTransactions(client, d, { sender: sessionAddress }, limit, {});
163
+ return transactions
116
164
  .filter((t) => !signed.has(t.digest))
117
165
  .map((t) => ({ digest: t.digest, success: t.status.success }));
118
166
  }
119
167
  /** Every recent call into the package's `pass` module, from any agent or owner. */
120
168
  export async function packageFeed(client, d, limit = 40) {
121
- const page = await client.listTransactions({
122
- filter: { function: `${d.publishedAt}::pass` },
123
- order: 'descending',
124
- limit,
125
- include,
126
- });
127
- return page.transactions.map((r) => {
128
- const tx = (r.Transaction ?? r.FailedTransaction);
169
+ const transactions = await sentTransactions(client, d, { function: `${d.publishedAt}::pass` }, limit, include);
170
+ return transactions.map((tx) => {
129
171
  const sender = normalizeSuiAddress(tx.transaction?.sender ?? '0x0');
130
172
  return { ...describeAttempt(d, sender, [], tx), sender };
131
173
  });
package/dist/mcp.js CHANGED
@@ -141,8 +141,8 @@ export async function venues(client, d) {
141
141
  * When the chain shows transactions from the session address that this machine never signed, the
142
142
  * agent key is in use somewhere else; the agent must tell the owner, who can stop it.
143
143
  */
144
- export async function keyAlert(client, directory, sessionAddress) {
145
- const foreign = await foreignTransactions(client, sessionAddress, await SessionStore.signedDigests(directory)).catch(() => []);
144
+ export async function keyAlert(client, d, directory, sessionAddress) {
145
+ const foreign = await foreignTransactions(client, d, sessionAddress, await SessionStore.signedDigests(directory)).catch(() => []);
146
146
  if (!foreign.length)
147
147
  return {};
148
148
  return {
@@ -163,7 +163,7 @@ export async function sessionInfo(identity, directory = null) {
163
163
  readAllHoldings(client, d, active.owner).catch(() => null),
164
164
  ]);
165
165
  return {
166
- ...(directory ? await keyAlert(client, directory, sessionAddress) : {}),
166
+ ...(directory ? await keyAlert(client, d, directory, sessionAddress) : {}),
167
167
  ...identity,
168
168
  ...status,
169
169
  ...(directory ? { directory } : {}),
package/dist/plugin.js CHANGED
@@ -20,8 +20,8 @@ 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 { adoptAuthorization, applyPendingChange } from './activation.js';
24
- import { clientFor, deepbookSizes, findPools, quoteSwap, readAllHoldings, readHoldings, readStatus, withMarketFacts, } from './chain.js';
23
+ import { adoptAuthorization, applyPendingChange, RulesMismatch } from './activation.js';
24
+ import { buildResignation, clientFor, deepbookSizes, findPools, quoteSwap, readAllHoldings, readHoldings, readStatus, withMarketFacts, } from './chain.js';
25
25
  import { Deployments } from './deployments.js';
26
26
  import { describePolicy, describeSetup, renderRows } from './describe.js';
27
27
  import { address, coinBySymbol, coinInfo, connects, DAY_MS, defaultGasDaily, display, isStable, limitUnits, MAX_TERM_DAYS, poolsFor, recipientName, requiredSui, sameCoin, SetupSchema, showCoin, SUI, uncovered, units, VenueSchema, } from './domain.js';
@@ -344,7 +344,7 @@ async function summaryWithChain(s) {
344
344
  return {
345
345
  ...base,
346
346
  ...(state.active && !closed
347
- ? await keyAlert(client, s.store.directory, state.sessionAddress)
347
+ ? await keyAlert(client, state.deployment, s.store.directory, state.sessionAddress)
348
348
  : {}),
349
349
  ...(closed
350
350
  ? {
@@ -585,12 +585,17 @@ export function createPluginMcp(registry) {
585
585
  const session = await registry.find(pass);
586
586
  const { store } = session, { setup, deployment: d } = store.state;
587
587
  const deadline = Date.now() + wait * 1000;
588
- let mismatch = null;
588
+ let mismatch = null, chainError = null;
589
589
  for (;;) {
590
590
  await store.refresh();
591
591
  // Looks on chain itself rather than relying on a watcher in some longer-lived process.
592
592
  if (!store.state.active)
593
- await adoptAuthorization(store).then(() => (mismatch = null), (error) => (mismatch = error.message));
593
+ await adoptAuthorization(store).then(() => (mismatch = chainError = null), (error) => {
594
+ if (error instanceof RulesMismatch)
595
+ mismatch = error.message;
596
+ else
597
+ chainError = error.message;
598
+ });
594
599
  else if (store.state.pendingChange)
595
600
  await applyPendingChange(store).catch(() => false);
596
601
  if ((store.state.active && !store.state.pendingChange) || Date.now() >= deadline)
@@ -601,12 +606,17 @@ export function createPluginMcp(registry) {
601
606
  const { ownerUrl } = await registry.server(session);
602
607
  return result({
603
608
  ...summary(session),
604
- status: 'awaiting_authorization',
609
+ status: mismatch ? 'mismatch' : 'awaiting_authorization',
605
610
  reviewUrl: ownerUrl,
606
611
  rules: renderRows(describeSetup(d, setup)),
607
612
  ...(mismatch
608
613
  ? {
609
- authorizationError: `A pass for this key is on chain but does not match the reviewed rules: ${mismatch}. Do not act; tell the owner.`,
614
+ authorizationError: `A pass for this key is on chain but does not match the reviewed rules: ${mismatch}. Do not act; tell the owner, who can close the pass from its page.`,
615
+ }
616
+ : {}),
617
+ ...(chainError
618
+ ? {
619
+ chainError: `Could not read the chain to look for the owner's signature: ${chainError}. The status above is unknown until a read succeeds.`,
610
620
  }
611
621
  : {}),
612
622
  });
@@ -700,12 +710,12 @@ export function createPluginMcp(registry) {
700
710
  });
701
711
  await store.proposeChange(setup);
702
712
  const { origin } = await registry.server(session);
703
- const reviewUrl = ownerPageUrl(d, origin, {
713
+ const reviewUrl = await ownerPageUrl(d, origin, {
704
714
  v: 1,
705
715
  sessionAddress: store.state.sessionAddress,
706
716
  setup,
707
717
  passId: store.state.active.passId,
708
- });
718
+ }, await store.key());
709
719
  if (registry.options.openBrowser !== false)
710
720
  openBrowser(reviewUrl);
711
721
  const before = describeSetup(d, store.state.setup), after = describeSetup(d, setup);
@@ -726,6 +736,44 @@ export function createPluginMcp(registry) {
726
736
  return failure(error, 'Cannot propose the change');
727
737
  }
728
738
  });
739
+ server.registerTool('resign_pass', {
740
+ description: "End this key's authority yourself, with no owner signature: one transaction from the agent key, after which the chain refuses every action under the pass. Use it when the work is done and nothing recurring remains, when the owner says stop, after a keyAlert, or on a mismatch. The pass and its allowances stay on chain, inert, until the owner closes the pass from its page and gets the storage deposit back; tell them so. Irreversible: a new pass needs a new proposal.",
741
+ inputSchema: {
742
+ pass: z
743
+ .string()
744
+ .optional()
745
+ .describe('pass id prefix from list_passes; omit if there is one'),
746
+ },
747
+ annotations: { readOnlyHint: false, destructiveHint: true },
748
+ }, async ({ pass }) => {
749
+ try {
750
+ const session = await registry.find(pass);
751
+ const { store } = session, { deployment: d, active } = store.state;
752
+ if (!active)
753
+ throw new Error('This pass was never authorized; nothing to resign from');
754
+ const client = clientFor(d);
755
+ const tx = buildResignation(d, active.passId);
756
+ tx.setSender(store.state.sessionAddress);
757
+ const bytes = await tx.build({ client });
758
+ await SessionStore.recordSigned(store.directory, await Transaction.from(bytes).getDigest());
759
+ const outcome = await client.signAndExecuteTransaction({
760
+ transaction: bytes,
761
+ signer: await store.key(),
762
+ });
763
+ if (outcome.$kind !== 'Transaction')
764
+ throw new Error(`The chain refused the resignation: ${outcome.FailedTransaction.status.error?.message}`);
765
+ await client.waitForTransaction({ result: outcome });
766
+ return result({
767
+ pass: session.id,
768
+ digest: outcome.Transaction.digest,
769
+ status: 'revoked',
770
+ next: 'The key can no longer act. Tell the owner the pass is stopped and that closing it from its page refunds the storage deposit; then call forget_pass once it is closed.',
771
+ });
772
+ }
773
+ catch (error) {
774
+ return failure(error, 'Resignation failed');
775
+ }
776
+ });
729
777
  server.registerTool('forget_pass', {
730
778
  description: "Retire a session whose pass is over: refuses while the pass is live, returns the key's unspent gas float to the owner, then deletes the session directory and its key. Works on sessions an earlier version wrote (list_passes shows them as unreadable). Offer this for every pass list_passes reports as closed or stopped, and for proposals the owner never signed.",
731
779
  inputSchema: {
package/dist/server.js CHANGED
@@ -45,8 +45,8 @@ function json(response, status, value) {
45
45
  /** The site that serves the owner's pages: the hosted one when the deployment names it, else here. */
46
46
  const siteBase = (d, origin) => (d.siteUrl ?? origin).replace(/\/$/, '');
47
47
  /** The review page for a proposal. */
48
- export function ownerPageUrl(d, origin, proposal) {
49
- return `${siteBase(d, origin)}/?network=${d.network}#/authorize/${encodeProposal(proposal)}`;
48
+ export async function ownerPageUrl(d, origin, proposal, key) {
49
+ return `${siteBase(d, origin)}/?network=${d.network}#/authorize/${await encodeProposal(proposal, key)}`;
50
50
  }
51
51
  /** A pass's own page: rules, activity, and the owner's Stop, Close and Reclaim actions. */
52
52
  export function passPageUrl(d, origin, passId) {
@@ -212,13 +212,10 @@ export async function startServer(store, port = 0) {
212
212
  origin = `http://127.0.0.1:${bound.port}`;
213
213
  await writeFile(join(store.directory, 'runtime.json'), JSON.stringify({ mcpUrl: `${origin}/mcp`, pid: process.pid }), { mode: 0o600 });
214
214
  void watchChain(store, () => closed);
215
+ const ownerUrl = await ownerPageUrl(d, origin, { v: 1, sessionAddress: store.state.sessionAddress, setup: store.state.setup }, await store.key());
215
216
  return {
216
217
  origin,
217
- ownerUrl: ownerPageUrl(d, origin, {
218
- v: 1,
219
- sessionAddress: store.state.sessionAddress,
220
- setup: store.state.setup,
221
- }),
218
+ ownerUrl,
222
219
  // Read on use: the activation that makes a pass page exist lands after the server starts.
223
220
  get passUrl() {
224
221
  return store.state.active ? passPageUrl(d, origin, store.state.active.passId) : null;
package/docs/AGENT.md CHANGED
@@ -50,7 +50,8 @@ on one listed pool for the pair (the first when none is named), or along `route`
50
50
  pool ids in order, when the pair trades only through other coins, `supply(i, coin, amount)`, `await withdraw(i, coin, amount)`,
51
51
  `await borrow(i, coin, amount)`, `await repay(i, coin, amount)` (the three that check health first
52
52
  refresh NAVI's oracle prices, which on mainnet must be newer than its update interval), `stake(i, amount, validator)` in SUI with
53
- `await pickValidator(i)` for the validator, `unstake(i, stakeId)` and `refillGas(i, amount)`. Each
53
+ `await pickValidator(i)` for the validator, `unstake(i, stakeId)`, `refillGas(i, amount)` and
54
+ `resign(i)`, which ends this key's authority for good. Each
54
55
  returns a `Transaction`; `submit` tops up your gas from the gas allowance when your own balance
55
56
  is below 0.01 SUI (by what the allowance can still give, up to 0.05 SUI), builds with a dry run
56
57
  that sizes the gas budget, signs through the signer, executes and waits.
@@ -179,6 +180,7 @@ window; `0x3::validator_set` 10 below the 1 SUI minimum stake.
179
180
  | `pass::navi_repay` | `[coin]` | pass, config, allowance, withdrawal, oracle, storage, pool, asset, incentiveV2, incentiveV3, clock |
180
181
  | `pass::stake` | | pass, config, SUI allowance, withdrawal, `0x5`, validator address, clock; returns the stake's ID |
181
182
  | `pass::unstake` | | pass, config, `0x5`, stake ID, clock |
183
+ | `pass::resign` | | pass |
182
184
  | `pass::add_policy`, `remove_policy`, `set_term`, `revoke_agent`, `deposit_object`, `withdraw_object`, `navi_open`, `destroy` | | **owner sender only**; installs take `config` after the pass, exits do not |
183
185
 
184
186
  A swap is a route in one transaction: `begin_swap` charges the allowance and the `SwapPolicy<in,