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

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,6 +1,7 @@
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
7
  "publishedAt": "0x389b58171d057852dd4b071d47474a2a97a6e4489cc2094a527a57d57d58063f",
@@ -1,6 +1,7 @@
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
6
  "packageId": "0xb6e9d01e6718cf1ccc33598efc892e1891f564f82824cd4af5b7d40160e21bf0",
6
7
  "publishedAt": "0xb6e9d01e6718cf1ccc33598efc892e1891f564f82824cd4af5b7d40160e21bf0",
@@ -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/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,7 +20,7 @@ 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';
23
+ import { adoptAuthorization, applyPendingChange, RulesMismatch } from './activation.js';
24
24
  import { 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';
@@ -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);
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/PLAYBOOK.md CHANGED
@@ -121,12 +121,18 @@ Call `propose_authorization` with the rules. It returns `rules`, the exact text
121
121
  shows, plus `reviewUrl` and `sessionAddress`, and opens the page in the browser. Paste `rules` to
122
122
  the owner word for word and never restate the amounts yourself. Tell them to connect their wallet,
123
123
  check the page against that text and sign once. The page shows what their wallet holds against
124
- what the pass needs. If the browser did not open, give them `reviewUrl`.
124
+ what the pass needs. If the browser did not open, give them `reviewUrl`. Hand the link over by
125
+ code, from the tool result into the message, never retyped: it is signed by the session key, and
126
+ the page refuses a link that differs by one character.
125
127
 
126
128
  Then call `session_info` with the pass and `wait: 120`, again while the status is
127
129
  `awaiting_authorization`. At `active` the signer has read the pass, the allowances and the
128
130
  policies back from chain and checked them against the proposal. Report the pass id, the
129
- authorization digest, the owner's balances and what the key may still withdraw.
131
+ authorization digest, the owner's balances and what the key may still withdraw. A status of
132
+ `mismatch` means the owner signed something other than the reviewed rules: quote
133
+ `authorizationError`, do not act, and ask the owner to close the pass from its page before you
134
+ propose again. A `chainError` means the signer could not read the chain; the status is unknown
135
+ until a read succeeds, so fix the connection and call again.
130
136
 
131
137
  ## 3. Act within the rules
132
138
 
@@ -192,7 +198,10 @@ still counts against the allowance.
192
198
  session's signer when none is running and `agent.close()` stops it, so a scheduled job (a daily
193
199
  sale on a cron) or a client that starts the MCP server for each call needs nothing kept alive in
194
200
  between. Always call `agent.close()`. On a machine behind a proxy, the script needs
195
- `HTTPS_PROXY` in its environment like the server does.
201
+ `HTTPS_PROXY` in its environment like the server does. If you run in a hosted VM that can be
202
+ replaced, check before each scheduled run that agent-pass is installed and the session directory
203
+ still exists. If the session directory is gone, the key is lost: tell the owner to close the pass
204
+ from its page and propose a new one.
196
205
 
197
206
  **Outcomes.** `submit` signs through this server, executes on Sui and returns what the chain
198
207
  recorded. `success: true` means done. `success: false` means the chain executed the transaction
@@ -209,8 +218,8 @@ allowance has its own cap and 24-hour limit and never touches the asset caps.
209
218
  ## 4. Report the state
210
219
 
211
220
  Call `list_passes`, then `session_info` for each pass the owner asks about (all of them when
212
- unclear). Report the status (`awaiting_authorization`, `active`, `changing`, `expired`, `revoked`
213
- or `closed`), the owner's address balances, what the key may still withdraw, its gas, any NAVI
221
+ unclear). Report the status (`awaiting_authorization`, `mismatch`, `active`, `changing`,
222
+ `expired`, `revoked` or `closed`), the owner's address balances, what the key may still withdraw, its gas, any NAVI
214
223
  position or stakes in the pass, and for each policy its limit and today's usage
215
224
  (`control.policies[*].usage.usedToday`). Quote the `rules` text as returned; do not recompute
216
225
  amounts.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mysten-incubation/sui-agent-pass",
3
- "version": "0.1.27",
3
+ "version": "0.1.28",
4
4
  "type": "module",
5
5
  "description": "AI builds transactions. A session signer signs. Your pass enforces the rules.",
6
6
  "repository": {
@@ -126,12 +126,18 @@ Call `propose_authorization` with the rules. It returns `rules`, the exact text
126
126
  shows, plus `reviewUrl` and `sessionAddress`, and opens the page in the browser. Paste `rules` to
127
127
  the owner word for word and never restate the amounts yourself. Tell them to connect their wallet,
128
128
  check the page against that text and sign once. The page shows what their wallet holds against
129
- what the pass needs. If the browser did not open, give them `reviewUrl`.
129
+ what the pass needs. If the browser did not open, give them `reviewUrl`. Hand the link over by
130
+ code, from the tool result into the message, never retyped: it is signed by the session key, and
131
+ the page refuses a link that differs by one character.
130
132
 
131
133
  Then call `session_info` with the pass and `wait: 120`, again while the status is
132
134
  `awaiting_authorization`. At `active` the signer has read the pass, the allowances and the
133
135
  policies back from chain and checked them against the proposal. Report the pass id, the
134
- authorization digest, the owner's balances and what the key may still withdraw.
136
+ authorization digest, the owner's balances and what the key may still withdraw. A status of
137
+ `mismatch` means the owner signed something other than the reviewed rules: quote
138
+ `authorizationError`, do not act, and ask the owner to close the pass from its page before you
139
+ propose again. A `chainError` means the signer could not read the chain; the status is unknown
140
+ until a read succeeds, so fix the connection and call again.
135
141
 
136
142
  ## 3. Act within the rules
137
143
 
@@ -197,7 +203,10 @@ still counts against the allowance.
197
203
  session's signer when none is running and `agent.close()` stops it, so a scheduled job (a daily
198
204
  sale on a cron) or a client that starts the MCP server for each call needs nothing kept alive in
199
205
  between. Always call `agent.close()`. On a machine behind a proxy, the script needs
200
- `HTTPS_PROXY` in its environment like the server does.
206
+ `HTTPS_PROXY` in its environment like the server does. If you run in a hosted VM that can be
207
+ replaced, check before each scheduled run that agent-pass is installed and the session directory
208
+ still exists. If the session directory is gone, the key is lost: tell the owner to close the pass
209
+ from its page and propose a new one.
201
210
 
202
211
  **Outcomes.** `submit` signs through this server, executes on Sui and returns what the chain
203
212
  recorded. `success: true` means done. `success: false` means the chain executed the transaction
@@ -214,8 +223,8 @@ allowance has its own cap and 24-hour limit and never touches the asset caps.
214
223
  ## 4. Report the state
215
224
 
216
225
  Call `list_passes`, then `session_info` for each pass the owner asks about (all of them when
217
- unclear). Report the status (`awaiting_authorization`, `active`, `changing`, `expired`, `revoked`
218
- or `closed`), the owner's address balances, what the key may still withdraw, its gas, any NAVI
226
+ unclear). Report the status (`awaiting_authorization`, `mismatch`, `active`, `changing`,
227
+ `expired`, `revoked` or `closed`), the owner's address balances, what the key may still withdraw, its gas, any NAVI
219
228
  position or stakes in the pass, and for each policy its limit and today's usage
220
229
  (`control.policies[*].usage.usedToday`). Quote the `rules` text as returned; do not recompute
221
230
  amounts.
@@ -0,0 +1,69 @@
1
+ # Set up Sui Agent Pass
2
+
3
+ You are setting up Sui Agent Pass for the person you work for. It lets you act on their Sui assets
4
+ within rules they sign once in their own wallet. Their coins stay in their wallet, you work with a
5
+ key of your own, and the chain refuses anything outside the rules.
6
+
7
+ Do the steps below, then ask them what they want to do. Do not propose a pass or make any
8
+ transaction during setup.
9
+
10
+ 1. **Install** the package (Node 22 or newer):
11
+
12
+ ```sh
13
+ npm install -g @mysten-incubation/sui-agent-pass
14
+ ```
15
+
16
+ If you are a coding agent in a terminal on the person's own machine (Claude Code, Codex,
17
+ Hermes, OpenClaw), run `agent-pass connect --client <claude-code|codex|hermes|openclaw>`
18
+ instead of the next step: it registers the server and the playbook with your client. Ask the
19
+ person to restart you, then continue at step 3. Agents in a hosted app or in their own VM or
20
+ sandbox take step 2.
21
+
22
+ Reinstalling or upgrading never touches existing passes or keys.
23
+
24
+ 2. **Connect to its MCP server.** If your app lets you add an MCP server, add a stdio server with
25
+ the command `agent-pass mcp`. Otherwise write a small client with the official MCP SDK
26
+ (`@modelcontextprotocol/sdk`) that starts `agent-pass mcp` over stdio, calls its tools and
27
+ reads its resources. Two settings matter:
28
+ - Pass your full environment to the server. The SDK's stdio transport forwards only a small
29
+ default set, and on a machine whose only way out is a proxy, the server needs `HTTPS_PROXY`.
30
+ - Give tool calls a timeout of several minutes. `session_info` can wait up to 120 seconds for
31
+ the owner's signature, longer than the SDK's 60-second default.
32
+
33
+ For example (in its own npm project, after `npm install @modelcontextprotocol/sdk`):
34
+
35
+ ```js
36
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
37
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
38
+
39
+ const client = new Client({ name: 'agent-pass-client', version: '1.0.0' });
40
+ await client.connect(
41
+ new StdioClientTransport({ command: 'agent-pass', args: ['mcp'], env: process.env }),
42
+ );
43
+ const [, , kind, name, args] = process.argv;
44
+ const result =
45
+ kind === 'read'
46
+ ? await client.readResource({ uri: name })
47
+ : await client.callTool({ name, arguments: JSON.parse(args ?? '{}') }, undefined, {
48
+ timeout: 300_000,
49
+ });
50
+ console.log(JSON.stringify(result, null, 2));
51
+ await client.close();
52
+ ```
53
+
54
+ Run it as `node client.mjs call list_passes '{}'` or `node client.mjs read agent-pass://playbook`.
55
+ Keep the client for later conversations, as a saved skill if your app has them.
56
+
57
+ 3. **Read the playbook.** Read the resource `agent-pass://playbook` in full and follow it for
58
+ everything you do with Agent Pass. It explains how to turn a request into rules, how the owner
59
+ signs, and how to act and report.
60
+
61
+ 4. **Check the connection.** Call `list_passes`. On mainnet, each pool should show a `price`. A
62
+ `priceError` means this machine cannot reach the Sui full node; check the network or proxy and
63
+ tell the person instead of going on.
64
+
65
+ 5. **Hand over.** Tell the person setup is done and ask what they want you to do with their Sui
66
+ assets. Ask for their wallet address so you can see what they hold.
67
+
68
+ Never print or copy the agent key or any file under `~/.sui-agent-pass`. If something fails, give
69
+ the person the exact error text and say whether anything executed on chain.