@mysten-incubation/sui-agent-pass 0.1.26 → 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/agent.js CHANGED
@@ -5,8 +5,10 @@
5
5
  * and the persisted outcome. Importable as `@mysten-incubation/sui-agent-pass/agent`; never imported by the
6
6
  * signing service.
7
7
  */
8
+ import { spawn } from 'node:child_process';
8
9
  import { readFile } from 'node:fs/promises';
9
10
  import { join } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
10
12
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
11
13
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
12
14
  import { Inputs, Transaction } from '@mysten/sui/transactions';
@@ -32,22 +34,87 @@ const GAS_TOPUP = 50000000n;
32
34
  const GAS_RESERVE = 2000000n;
33
35
  /** A build without simulation has nothing to estimate its budget; this covers any pass action. */
34
36
  const PROVE_BUDGET = 20_000_000;
37
+ /** The signer `runtime.json` names, unless the process that wrote it is gone. */
38
+ async function liveRuntime(directory) {
39
+ const runtime = await readFile(join(directory, 'runtime.json'), 'utf8')
40
+ .then((t) => JSON.parse(t))
41
+ .catch(() => null);
42
+ if (!runtime)
43
+ return null;
44
+ try {
45
+ process.kill(runtime.pid, 0);
46
+ return runtime;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ /** Starts `agent-pass serve` for a session and waits until it has written its own runtime.json. */
53
+ async function startSigner(directory) {
54
+ const cli = fileURLToPath(new URL(`./cli.${import.meta.url.endsWith('.ts') ? 'ts' : 'js'}`, import.meta.url));
55
+ const child = spawn(process.execPath, [
56
+ ...(cli.endsWith('.ts') ? ['--import', 'tsx'] : []),
57
+ cli,
58
+ 'serve',
59
+ '--session',
60
+ directory,
61
+ '--no-open',
62
+ ], { stdio: ['ignore', 'ignore', 'pipe'] });
63
+ let stderr = '';
64
+ child.stderr?.on('data', (chunk) => (stderr += chunk));
65
+ const exited = new Promise((_, reject) => child.once('exit', (code) => reject(new Error(`The session's signer exited (${code}) before it started: ${stderr.trim().slice(-500)}`))));
66
+ const ready = (async () => {
67
+ for (let i = 0; i < 300; i++) {
68
+ const runtime = await liveRuntime(directory);
69
+ if (runtime && runtime.pid === child.pid)
70
+ return runtime.mcpUrl;
71
+ await new Promise((r) => setTimeout(r, 100));
72
+ }
73
+ throw new Error("The session's signer did not start within 30 seconds");
74
+ })();
75
+ try {
76
+ return { child, mcpUrl: await Promise.race([ready, exited]) };
77
+ }
78
+ catch (error) {
79
+ child.kill();
80
+ throw error;
81
+ }
82
+ }
35
83
  export class Agent {
36
84
  mcp;
37
85
  identity;
38
86
  client;
87
+ /** A signer this agent started because none was running; stopped by `close`. */
88
+ signer;
39
89
  constructor(mcp, identity) {
40
90
  this.mcp = mcp;
41
91
  this.identity = identity;
42
92
  this.client = clientFor(identity.deployment);
43
93
  }
44
- /** Connects through the session directory `session_info` names: its signer URL and token. */
94
+ /**
95
+ * Connects to the session's signer through the directory `session_info` names. When no signer
96
+ * is running for it (the process that started one has exited, as with a client that starts
97
+ * the server for each call, or a scheduled run), starts `agent-pass serve` for this agent's
98
+ * lifetime. The key stays in that process; this one only ever sees signatures.
99
+ */
45
100
  static async open(directory) {
46
- const [runtime, token] = await Promise.all([
47
- readFile(join(directory, 'runtime.json'), 'utf8').then(JSON.parse),
48
- readFile(join(directory, 'mcp.token'), 'utf8'),
49
- ]);
50
- return Agent.connect(runtime.mcpUrl, token.trim());
101
+ const token = (await readFile(join(directory, 'mcp.token'), 'utf8')).trim();
102
+ const running = await liveRuntime(directory);
103
+ if (running) {
104
+ const agent = await Agent.connect(running.mcpUrl, token).catch(() => null);
105
+ if (agent)
106
+ return agent;
107
+ }
108
+ const signer = await startSigner(directory);
109
+ try {
110
+ const agent = await Agent.connect(signer.mcpUrl, token);
111
+ agent.signer = signer.child;
112
+ return agent;
113
+ }
114
+ catch (error) {
115
+ signer.child.kill();
116
+ throw error;
117
+ }
51
118
  }
52
119
  static async connect(url, bearer) {
53
120
  const client = new Client({ name: 'independent-agent', version: '0.1.0' });
@@ -65,6 +132,7 @@ export class Agent {
65
132
  }
66
133
  async close() {
67
134
  await this.mcp.close();
135
+ this.signer?.kill();
68
136
  }
69
137
  /** Tops up the session's own gas float from the gas allowance before it runs dry. A refused
70
138
  * refill (cap or window hit, owner balance empty) is not fatal while the float still covers one
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
@@ -41,7 +41,7 @@ async function sdkInfo(directory) {
41
41
  open: directory ? `await Agent.open(${JSON.stringify(directory)})` : null,
42
42
  // The whole surface, so a script needs nothing from the package's source tree.
43
43
  api: [
44
- 'Agent.open(directory): Promise<Agent>; agent.identity (pass this to builders); agent.client (SuiGrpcClient for reads); agent.submit(tx, { proveChainRefusal?: boolean }): Promise<Outcome>; agent.close()',
44
+ "Agent.open(directory): Promise<Agent>, which starts the session's signer when none is running (a scheduled run, a client that starts the server for each call) and stops it on agent.close(); agent.identity (pass this to builders); agent.client (SuiGrpcClient for reads); agent.submit(tx, { proveChainRefusal?: boolean }): Promise<Outcome>; agent.close() (always call it)",
45
45
  'quote(identity, { coinIn, coinOut, poolId?, venue? }, amountIn): Promise<{ pool, amountIn, amountOut }> prices a sale on a listed pool from the venue itself without touching any allowance; amountIn is what the pool would take (DeepBook pays its fee from the input and rounds down to its lot size) and amountOut what comes back. Quote before every swap and set minOut a little under amountOut; never size minOut from a mid price.',
46
46
  'Builders return a Transaction; coins are full type strings (session_info coins lists the ones these rules name, with symbol and decimals) and amounts are base-unit strings: send(identity, coin, amount, recipientName); swap(identity, { coinIn, coinOut, poolId?, venue? }, amountIn, minOut) sells coinIn for coinOut on a listed pool (the first matching pool when none is named); supply(identity, coin, amount) on NAVI, and await withdraw(identity, coin, amount), await borrow(identity, coin, amount), await repay(identity, coin, amount), which first add the oracle price refresh NAVI requires on mainnet; stake(identity, amount, validator) in SUI with validator from await pickValidator(identity); unstake(identity, stakeId); refillGas(identity, amount)',
47
47
  "Outcome: { digest, success, reason (the owner's rule behind a refusal, or null), error, balanceChanges: [{ address, coinType, amount }] }; submit throws when nothing executed",
@@ -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 } 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,19 @@ 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
+ });
599
+ else if (store.state.pendingChange)
600
+ await applyPendingChange(store).catch(() => false);
594
601
  if ((store.state.active && !store.state.pendingChange) || Date.now() >= deadline)
595
602
  break;
596
603
  await sleep(1000);
@@ -599,12 +606,17 @@ export function createPluginMcp(registry) {
599
606
  const { ownerUrl } = await registry.server(session);
600
607
  return result({
601
608
  ...summary(session),
602
- status: 'awaiting_authorization',
609
+ status: mismatch ? 'mismatch' : 'awaiting_authorization',
603
610
  reviewUrl: ownerUrl,
604
611
  rules: renderRows(describeSetup(d, setup)),
605
612
  ...(mismatch
606
613
  ? {
607
- 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.`,
608
620
  }
609
621
  : {}),
610
622
  });
@@ -698,12 +710,12 @@ export function createPluginMcp(registry) {
698
710
  });
699
711
  await store.proposeChange(setup);
700
712
  const { origin } = await registry.server(session);
701
- const reviewUrl = ownerPageUrl(d, origin, {
713
+ const reviewUrl = await ownerPageUrl(d, origin, {
702
714
  v: 1,
703
715
  sessionAddress: store.state.sessionAddress,
704
716
  setup,
705
717
  passId: store.state.active.passId,
706
- });
718
+ }, await store.key());
707
719
  if (registry.options.openBrowser !== false)
708
720
  openBrowser(reviewUrl);
709
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
 
@@ -188,6 +194,15 @@ owner's price limit on what went in against what came out.
188
194
  **Repayments.** Size a repayment from the live debt: an over-payment returns to the owner but
189
195
  still counts against the allowance.
190
196
 
197
+ **One-shot and scheduled runs.** Each run can be one script: `Agent.open(directory)` starts the
198
+ session's signer when none is running and `agent.close()` stops it, so a scheduled job (a daily
199
+ sale on a cron) or a client that starts the MCP server for each call needs nothing kept alive in
200
+ between. Always call `agent.close()`. On a machine behind a proxy, the script needs
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.
205
+
191
206
  **Outcomes.** `submit` signs through this server, executes on Sui and returns what the chain
192
207
  recorded. `success: true` means done. `success: false` means the chain executed the transaction
193
208
  and refused it; `reason` is the owner's rule that stopped it, and you quote it. A thrown error
@@ -203,8 +218,8 @@ allowance has its own cap and 24-hour limit and never touches the asset caps.
203
218
  ## 4. Report the state
204
219
 
205
220
  Call `list_passes`, then `session_info` for each pass the owner asks about (all of them when
206
- unclear). Report the status (`awaiting_authorization`, `active`, `changing`, `expired`, `revoked`
207
- 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
208
223
  position or stakes in the pass, and for each policy its limit and today's usage
209
224
  (`control.policies[*].usage.usedToday`). Quote the `rules` text as returned; do not recompute
210
225
  amounts.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mysten-incubation/sui-agent-pass",
3
- "version": "0.1.26",
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": {