@mysten-incubation/sui-agent-pass 0.1.10 → 0.1.11

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