@attocash/cli 0.2.3 → 0.3.0

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.
Files changed (137) hide show
  1. package/README.md +148 -7
  2. package/dist/application/app.d.ts +34 -3
  3. package/dist/application/app.js +138 -126
  4. package/dist/application/operations.d.ts +3 -0
  5. package/dist/application/operations.js +30 -8
  6. package/dist/cli/cli.d.ts +1 -0
  7. package/dist/cli/cli.js +101 -13
  8. package/dist/cli/onboarding.d.ts +13 -0
  9. package/dist/cli/onboarding.js +99 -2
  10. package/dist/cli/output.js +18 -2
  11. package/dist/doctor/profile.js +2 -1
  12. package/dist/internal-marketplace.d.ts +25 -0
  13. package/dist/internal-marketplace.js +50 -0
  14. package/dist/marketplace/approval-files.d.ts +3 -0
  15. package/dist/marketplace/approval-files.js +97 -0
  16. package/dist/marketplace/approval-preview.d.ts +2 -0
  17. package/dist/marketplace/approval-preview.js +86 -0
  18. package/dist/marketplace/proof-approval.d.ts +82 -0
  19. package/dist/marketplace/proof-approval.js +671 -0
  20. package/dist/marketplace/topups.d.ts +82 -0
  21. package/dist/marketplace/topups.js +485 -0
  22. package/dist/network/batching.d.ts +2 -0
  23. package/dist/network/batching.js +23 -0
  24. package/dist/network/entry.d.ts +2 -0
  25. package/dist/network/entry.js +35 -0
  26. package/dist/network/reader.d.ts +2 -0
  27. package/dist/network/reader.js +125 -37
  28. package/dist/spending/approval.d.ts +5 -0
  29. package/dist/spending/approval.js +2 -0
  30. package/dist/spending/atto-x402.d.ts +31 -0
  31. package/dist/spending/atto-x402.js +174 -0
  32. package/dist/spending/ledger.d.ts +74 -2
  33. package/dist/spending/ledger.js +298 -7
  34. package/dist/spending/payments.d.ts +105 -5
  35. package/dist/spending/payments.js +795 -11
  36. package/dist/storage/recovery-seed.d.ts +13 -0
  37. package/dist/storage/recovery-seed.js +93 -0
  38. package/dist/storage/state.d.ts +4 -0
  39. package/dist/storage/state.js +32 -2
  40. package/dist/wallet/receive.d.ts +39 -0
  41. package/dist/wallet/receive.js +264 -0
  42. package/dist/wallet/signing.d.ts +1 -0
  43. package/dist/wallet/signing.js +37 -21
  44. package/dist/wallet/types.d.ts +1 -0
  45. package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs +1922 -1918
  46. package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs.map +1 -1
  47. package/node_modules/@attocash/commons-core/README.md +9 -0
  48. package/node_modules/@attocash/commons-core/commons-commons-core.d.mts +10 -0
  49. package/node_modules/@attocash/commons-core/commons-commons-core.mjs +2543 -2434
  50. package/node_modules/@attocash/commons-core/commons-commons-core.mjs.map +1 -1
  51. package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs +4695 -4227
  52. package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs.map +1 -1
  53. package/node_modules/@attocash/commons-core/kotlin_org_jetbrains_kotlin_kotlin_dom_api_compat.mjs.map +1 -1
  54. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs +60 -60
  55. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs.map +1 -1
  56. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs +651 -631
  57. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs.map +1 -1
  58. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs +2294 -2295
  59. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs.map +1 -1
  60. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  61. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  62. package/node_modules/@attocash/commons-core/package.json +1 -1
  63. package/node_modules/@attocash/commons-node/commons-commons-node.d.mts +1 -0
  64. package/node_modules/@attocash/commons-node/commons-commons-node.mjs +873 -847
  65. package/node_modules/@attocash/commons-node/commons-commons-node.mjs.map +1 -1
  66. package/node_modules/@attocash/commons-node/kotlin-logging.mjs +109 -109
  67. package/node_modules/@attocash/commons-node/kotlin-logging.mjs.map +1 -1
  68. package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  69. package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  70. package/node_modules/@attocash/commons-node/package.json +3 -3
  71. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.d.mts +1 -0
  72. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs +674 -640
  73. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs.map +1 -1
  74. package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs +109 -109
  75. package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs.map +1 -1
  76. package/node_modules/@attocash/commons-node-remote/kotlinx-browser.mjs.map +1 -1
  77. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  78. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  79. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  80. package/node_modules/@attocash/commons-node-remote/package.json +4 -4
  81. package/node_modules/@attocash/commons-transport/commons-commons-transport.d.mts +1 -0
  82. package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs +52 -51
  83. package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs.map +1 -1
  84. package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs +13 -13
  85. package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs.map +1 -1
  86. package/node_modules/@attocash/commons-transport/kotlinx-browser.mjs.map +1 -1
  87. package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs +2639 -2608
  88. package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs.map +1 -1
  89. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  90. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  91. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  92. package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs +411 -196
  93. package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs.map +1 -1
  94. package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs +2115 -1976
  95. package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs.map +1 -1
  96. package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs +7 -7
  97. package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs.map +1 -1
  98. package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs +385 -384
  99. package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs.map +1 -1
  100. package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs +1261 -1185
  101. package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs.map +1 -1
  102. package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs +668 -656
  103. package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs.map +1 -1
  104. package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs +89 -0
  105. package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs.map +1 -0
  106. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs +9 -9
  107. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs.map +1 -1
  108. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs +120 -128
  109. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs.map +1 -1
  110. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs +46 -49
  111. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs.map +1 -1
  112. package/node_modules/@attocash/commons-transport/ktor-ktor-sse.mjs.map +1 -1
  113. package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs +1041 -985
  114. package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs.map +1 -1
  115. package/node_modules/@attocash/commons-transport/ktor-ktor-websocket-serialization.mjs.map +1 -1
  116. package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs +530 -455
  117. package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs.map +1 -1
  118. package/node_modules/@attocash/commons-transport/package.json +4 -4
  119. package/node_modules/@attocash/commons-worker/commons-commons-worker.d.mts +1 -0
  120. package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs +230 -226
  121. package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs.map +1 -1
  122. package/node_modules/@attocash/commons-worker/kotlin-logging.mjs +109 -109
  123. package/node_modules/@attocash/commons-worker/kotlin-logging.mjs.map +1 -1
  124. package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  125. package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  126. package/node_modules/@attocash/commons-worker/package.json +3 -3
  127. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.d.mts +1 -0
  128. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs +91 -86
  129. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs.map +1 -1
  130. package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs +109 -109
  131. package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs.map +1 -1
  132. package/node_modules/@attocash/commons-worker-remote/kotlinx-browser.mjs.map +1 -1
  133. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  134. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  135. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  136. package/node_modules/@attocash/commons-worker-remote/package.json +4 -4
  137. package/package.json +9 -5
@@ -2,10 +2,11 @@ import { PersonalLabels } from '../labels/personal.js';
2
2
  import { GlobalDirectory } from '../labels/directory.js';
3
3
  import { AddressLabels } from '../labels/presentation.js';
4
4
  import { createHash } from 'node:crypto';
5
- import { AttoMnemonic, toAttoIndex, } from '@attocash/commons-core';
5
+ import { AttoMnemonic, AttoPublicKey, AttoSignature, toAttoIndex, } from '@attocash/commons-core';
6
6
  import { amountOutput, amountRaw } from '../domain/amount.js';
7
7
  import { AttoError } from '../domain/errors.js';
8
8
  import { NodeReader, parseAddress, publicModel } from '../network/reader.js';
9
+ import { resolveNodeBatchSize } from '../network/batching.js';
9
10
  import { OsSecretStore } from '../storage/secrets.js';
10
11
  import { StateStore } from '../storage/state.js';
11
12
  import { resolveWalletProfile } from '../storage/profiles.js';
@@ -16,13 +17,22 @@ import { WalletWork } from '../wallet/work.js';
16
17
  import { BackgroundReceiver } from '../wallet/background-receive.js';
17
18
  import { WatchManager } from '../watches/manager.js';
18
19
  import { AutoReceiver } from '../wallet/auto-receive.js';
20
+ import { WalletReceiver } from '../wallet/receive.js';
19
21
  import { defaultSettings } from '../wallet/defaults.js';
20
22
  import { derivedSigner, mnemonicSeed, signingWallet } from '../wallet/signing.js';
21
- import { operations, parseOperation } from './operations.js';
23
+ import { operationFor, parseOperation } from './operations.js';
22
24
  import { MarketData } from '../pricing/market.js';
23
25
  import { marketTerms } from '../pricing/terms.js';
24
26
  import { runDoctor } from '../doctor/doctor.js';
27
+ import { validateMarketplaceUserProofApproval, createMarketplaceProofApprovalResponse } from '../marketplace/proof-approval.js';
28
+ import { MarketplaceTopUpClient } from '../marketplace/topups.js';
25
29
  const RESET_KEY = 'wallet.reset';
30
+ function signedMessageBytes(args) {
31
+ const bytes = args.messageHex !== undefined
32
+ ? Buffer.from(args.messageHex, 'hex')
33
+ : Buffer.from(args.message, 'utf8');
34
+ return new Int8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
35
+ }
26
36
  export class AttoApplication {
27
37
  store;
28
38
  ledger;
@@ -31,12 +41,14 @@ export class AttoApplication {
31
41
  personal;
32
42
  labels;
33
43
  auto;
44
+ receiver;
34
45
  work;
35
46
  background;
36
47
  receivingAllowed;
37
48
  preparation;
38
49
  preparationAbort = new AbortController();
39
50
  payments;
51
+ topUps;
40
52
  watchManager;
41
53
  watchConfiguration = '';
42
54
  watchQueue = Promise.resolve();
@@ -46,6 +58,9 @@ export class AttoApplication {
46
58
  recoveryReads = 0;
47
59
  calls = new Set();
48
60
  mcp;
61
+ internalMarketplacePayment;
62
+ internalMarketplaceAuthorizeWrite;
63
+ internalMarketplaceReceiveSafety;
49
64
  doctorAbort = new AbortController();
50
65
  constructor(options = {}) {
51
66
  const profile = resolveWalletProfile(options.directory);
@@ -53,6 +68,9 @@ export class AttoApplication {
53
68
  try {
54
69
  this.secrets = options.secrets ?? new OsSecretStore(profile.credentialAccount, profile.credentialService);
55
70
  this.mcp = options.access === 'mcp';
71
+ this.internalMarketplacePayment = options.internalMarketplacePayment;
72
+ this.internalMarketplaceAuthorizeWrite = options.internalMarketplaceAuthorizeWrite;
73
+ this.internalMarketplaceReceiveSafety = options.internalMarketplaceReceiveSafety === true;
56
74
  this.ledger = new SpendLedger(this.store);
57
75
  this.personal = new PersonalLabels(this.store);
58
76
  this.labels = new AddressLabels(this.personal, options.globalDirectory ?? new GlobalDirectory(this.store.directory));
@@ -64,14 +82,24 @@ export class AttoApplication {
64
82
  this.work = new WalletWork(this.store, () => this.settings(), options.workExecution);
65
83
  this.background = new BackgroundReceiver(this.store);
66
84
  this.receivingAllowed = options.receivingAllowed ?? (() => true);
85
+ this.topUps = new MarketplaceTopUpClient(this.store, {
86
+ settings: () => this.settings(), addresses: () => this.addresses(), seed: () => this.seed(), mcp: this.mcp,
87
+ });
88
+ this.receiver = new WalletReceiver({
89
+ store: this.store, settings: () => this.settings(), address: (index, active) => this.address(index, active),
90
+ reader: () => this.reader(), seed: () => this.seed(), requireMcpWrite: () => this.requireMcpWrite(),
91
+ requireAccountAvailable: index => this.ledger.assertAccountAvailable(index), work: this.work, receivingAllowed: this.receivingAllowed,
92
+ internalMarketplaceReceiveSafety: this.internalMarketplaceReceiveSafety,
93
+ });
67
94
  this.payments = new Payments(this.store, this.ledger, {
68
95
  settings: () => this.settings(), addresses: () => this.addresses(), seed: () => this.seed(),
69
96
  requireWrite: () => this.requireMcpWrite(), mcp: this.mcp,
70
- }, this.market, this.work, options.sendRetry, options.onDestination);
97
+ ...(this.internalMarketplaceReceiveSafety ? { requireAccountsAvailable: (indexes) => this.receiver.requireReceivesResolved(indexes) } : {}),
98
+ }, this.market, this.work, options.sendRetry, options.onDestination, this.topUps, this.internalMarketplacePayment);
71
99
  this.auto = new AutoReceiver(() => ({
72
100
  settings: !this.receivingAllowed() || (this.mcp && this.ledger.mcpAccess() !== 'spend') ? { ...this.settings(), autoReceive: false } : this.settings(),
73
101
  addresses: this.addresses(),
74
- }), (index, hash) => this.receive({ index, hash }, true), event => options.onReceiveProgress?.(this.labels.decorate(event, this.settings().network)));
102
+ }), (index, hash) => this.receiver.receive({ index, hash }, true), event => options.onReceiveProgress?.(this.labels.decorate(event, this.settings().network)));
75
103
  }
76
104
  catch (error) {
77
105
  this.store.close();
@@ -106,6 +134,10 @@ export class AttoApplication {
106
134
  if (this.mcp && this.ledger.mcpAccess() !== 'spend') {
107
135
  throw new AttoError('MCP_READ_ONLY', 'MCP has read-only access to this wallet. Propose limits and obtain local terminal approval to enable transactions.');
108
136
  }
137
+ if (this.internalMarketplaceAuthorizeWrite) {
138
+ this.internalMarketplaceAuthorizeWrite({ initialized: Boolean(this.identity()), identity: this.identity() ?? null,
139
+ settings: this.settings(), addresses: this.addresses(), mcpAccess: this.ledger.mcpAccess(), pool: this.ledger.pool() });
140
+ }
109
141
  }
110
142
  proposalWallet() {
111
143
  return { directory: this.store.directory, walletFingerprint: this.identity()?.fingerprint ?? null, network: this.settings().network };
@@ -121,6 +153,7 @@ export class AttoApplication {
121
153
  proposal: this.ledger.reviewProposal(id, this.proposalWallet()), directory: this.store.directory,
122
154
  identity: this.identity() ?? null, network: this.settings().network,
123
155
  policy: this.ledger.policy(), mcpAccess: this.ledger.mcpAccess(), pool: this.ledger.pool(),
156
+ messageSigningIndexes: this.ledger.messageSigningIndexes(),
124
157
  }));
125
158
  }
126
159
  async approveLimitsProposal(id) {
@@ -341,122 +374,11 @@ export class AttoApplication {
341
374
  result(transaction, status = 'published') {
342
375
  return { status, hash: transaction.hash.toString(), transaction: publicModel(transaction) };
343
376
  }
344
- async pendingReceivable(address, hash) {
345
- let found;
346
- const controller = new AbortController();
347
- const timer = setTimeout(() => controller.abort(), 2000);
348
- try {
349
- await this.reader().stream({ event: 'receivable', addresses: [address], minAmountRaw: '1' }, model => {
350
- const receivable = model;
351
- if (receivable.hash.toString().toUpperCase() === hash.toUpperCase()) {
352
- found = receivable;
353
- controller.abort();
354
- }
355
- }, controller.signal);
356
- }
357
- catch (error) {
358
- if (!controller.signal.aborted)
359
- throw error;
360
- }
361
- finally {
362
- clearTimeout(timer);
363
- }
364
- if (!found && controller.signal.aborted) {
365
- throw new AttoError('RECEIVABLE_LOOKUP_TIMEOUT', 'Checking the pending payment timed out. Retry receiving it; its absence has not been confirmed.');
366
- }
367
- return found;
368
- }
369
- async receive(request, automatic = false) {
370
- if (automatic && !this.receivingAllowed())
371
- throw new AttoError('AUTO_RECEIVE_DISABLED', 'Automatic receiving is stopping.');
372
- const index = request.index ?? 0;
373
- const operation = async () => {
374
- await this.store.withWalletLock(async () => {
375
- this.requireMcpWrite();
376
- this.payments.requireAvailable(index);
377
- });
378
- if (automatic && !this.settings().autoReceive)
379
- throw new AttoError('AUTO_RECEIVE_DISABLED', 'Automatic receiving is disabled.');
380
- const address = this.address(index, automatic);
381
- const hash = request.hash.toUpperCase();
382
- const key = `receive.${this.settings().network}.${hash}`;
383
- const prior = this.store.get(key);
384
- if (prior && prior.index !== index)
385
- throw new AttoError('WRONG_RECEIVER', 'This receivable belongs to a different address.');
386
- if (prior?.result)
387
- return prior.result;
388
- if (prior) {
389
- const transaction = await this.reader().transaction(prior.blockHash);
390
- if (transaction && transaction.hash.toString() === prior.blockHash && await transaction.isValid()) {
391
- const result = this.result(transaction, 'received');
392
- this.store.set(key, { ...prior, result });
393
- this.work.prepareConfirmed(transaction.block);
394
- return result;
395
- }
396
- // Refresh pending state below: an unconsumed send permits retrying receive
397
- // against the current frontier without risking a second debit.
398
- }
399
- const receivable = await this.pendingReceivable(address.address, hash);
400
- if (!receivable)
401
- throw new AttoError('RECEIVABLE_NOT_PENDING', 'The payment is not pending for this address; it may already have been received.');
402
- if (receivable.receiverAddress.value !== address.address)
403
- throw new AttoError('WRONG_RECEIVER', 'The payment belongs to a different address.');
404
- if (automatic && BigInt(receivable.amount.toString()) < BigInt(this.settings().minReceiveRaw)) {
405
- throw new AttoError('RECEIVABLE_BELOW_MINIMUM', 'The payment is below the current automatic receiving minimum.');
406
- }
407
- const seed = await this.seed();
408
- let wallet;
409
- try {
410
- const execution = await signingWallet(seed, index, this.settings(), async (block) => {
411
- await this.store.withWalletLock(async () => {
412
- this.requireMcpWrite();
413
- this.payments.requireAvailable(index);
414
- if (automatic && !this.settings().autoReceive)
415
- throw new AttoError('AUTO_RECEIVE_DISABLED', 'Automatic receiving is disabled.');
416
- this.store.set(key, { hash, index, blockHash: block.hash.toString() });
417
- });
418
- }, this.work.worker());
419
- wallet = execution.wallet;
420
- const transaction = await wallet.receive(receivable, parseAddress(request.representative ?? this.settings().representative), null);
421
- const result = { ...this.result(transaction, 'received'), index, amount: amountOutput(receivable.amount.toString()) };
422
- this.store.set(key, { hash, index, blockHash: transaction.hash.toString(), result });
423
- this.work.prepareConfirmed(transaction.block);
424
- return result;
425
- }
426
- finally {
427
- wallet?.close();
428
- seed.value.fill(0);
429
- }
430
- };
431
- if (!automatic)
432
- return this.store.withAccountLocks([index], operation);
433
- // A busy account must not stall receiving for the rest of the wallet or
434
- // prevent this session from stopping. The receiver will retry this item.
435
- const release = this.store.tryAccountLocks([index]);
436
- if (!release)
437
- throw new AttoError('WALLET_BUSY', 'This account is busy. Automatic receiving will retry it.');
438
- try {
439
- return await operation();
440
- }
441
- finally {
442
- release();
443
- }
444
- }
445
- async receiveAll(input) {
446
- const index = input.index ?? 0;
447
- const address = this.address(index).address;
448
- const list = await this.reader().list({ event: 'receivable', addresses: [address], limit: input.limit ?? 100, timeoutMs: input.timeoutMs ?? 2000 });
449
- const results = [];
450
- for (const item of list.items) {
451
- results.push(await this.receive({ index, hash: item.hash, representative: input.representative }));
452
- }
453
- return { results, timedOut: list.timedOut, ...(list.limitReached ? { limitReached: true } : {}) };
454
- }
455
377
  async changeRepresentative(index, representative) {
456
378
  return this.store.withAccountLocks([index], async () => {
457
379
  await this.store.withWalletLock(async () => {
458
380
  this.requireMcpWrite();
459
- this.payments.requireAvailable(index);
381
+ this.ledger.assertAccountAvailable(index);
460
382
  });
461
383
  this.address(index);
462
384
  const seed = await this.seed();
@@ -465,7 +387,7 @@ export class AttoApplication {
465
387
  const execution = await signingWallet(seed, index, this.settings(), async () => {
466
388
  await this.store.withWalletLock(async () => {
467
389
  this.requireMcpWrite();
468
- this.payments.requireAvailable(index);
390
+ this.ledger.assertAccountAvailable(index);
469
391
  });
470
392
  }, this.work.worker());
471
393
  wallet = execution.wallet;
@@ -499,7 +421,34 @@ export class AttoApplication {
499
421
  const reader = this.reader();
500
422
  switch (name) {
501
423
  case 'doctor': return runDoctor({ directory: this.store.directory, access: this.mcp ? 'mcp' : undefined, signal: this.doctorAbort.signal, globalDirectory: args.globalDirectory });
502
- case 'wallet_status': return { directory: this.store.directory, initialized: Boolean(this.identity()), identity: this.identity() ?? null, settings: this.settings(), addresses: this.addresses(), autoReceive: this.auto.status(), backgroundReceive: this.background.status(), mcpAccess: this.ledger.mcpAccess(), pool: this.ledger.pool(), pendingSends: this.ledger.pending().map(({ id, hash, status }) => ({ requestId: id, hash, status })), resetPending: Boolean(this.store.get(RESET_KEY)) };
424
+ case 'wallet_status': return { directory: this.store.directory, initialized: Boolean(this.identity()), identity: this.identity() ?? null, settings: this.settings(), effectiveNodeBatchSize: resolveNodeBatchSize(this.settings()), addresses: this.addresses(), autoReceive: this.auto.status(), backgroundReceive: this.background.status(), mcpAccess: this.ledger.mcpAccess(), pool: this.ledger.pool(), messageSigningIndexes: this.ledger.messageSigningIndexes(), pendingSends: this.ledger.pending().map(({ id, hash, status }) => ({ requestId: id, hash, status })), resetPending: Boolean(this.store.get(RESET_KEY)) };
425
+ case 'message_sign': return this.store.withWalletLock(async () => {
426
+ this.requireMcpWrite();
427
+ const index = args.index;
428
+ if (!this.ledger.messageSigningIndexes().includes(index)) {
429
+ throw new AttoError('SIGNING_NOT_APPROVED', 'This profile has not locally approved message signing for that account index.');
430
+ }
431
+ const saved = this.address(index);
432
+ const seed = await this.seed();
433
+ try {
434
+ const signer = await derivedSigner(seed, index);
435
+ if (signer.address.value !== saved.address || signer.publicKey.toString() !== saved.publicKey) {
436
+ throw new AttoError('WALLET_MISMATCH', 'The signing key does not match the saved account metadata.');
437
+ }
438
+ return { index, address: signer.address.value, publicKey: signer.publicKey.toString(),
439
+ signature: (await signer.signMessage(signedMessageBytes(args))).toString() };
440
+ }
441
+ finally {
442
+ seed.value.fill(0);
443
+ }
444
+ });
445
+ case 'message_verify': {
446
+ const publicKey = args.address !== undefined
447
+ ? parseAddress(args.address).publicKey
448
+ : AttoPublicKey.Companion.parse(args.publicKey);
449
+ const signature = AttoSignature.Companion.parse(args.signature);
450
+ return { valid: await signature.isValidMessage(publicKey, signedMessageBytes(args)) };
451
+ }
503
452
  case 'wallet_configure': return this.configure(args);
504
453
  case 'address_list': return { addresses: this.addresses() };
505
454
  case 'address_add': return this.store.withWalletLock(async () => {
@@ -538,10 +487,17 @@ export class AttoApplication {
538
487
  await this.labels.global.refresh(args.refresh);
539
488
  return this.labels.list(this.settings().network, args.all, args.search);
540
489
  }
541
- case 'account_get': return { account: publicModel(await reader.account(args.address ?? this.address(args.index).address)) };
490
+ case 'account_get': {
491
+ if (args.addresses !== undefined) {
492
+ const addresses = this.selectedAddresses(args);
493
+ const accounts = await reader.accounts(addresses);
494
+ return { accounts: addresses.map((address, i) => ({ address, account: publicModel(accounts[i]) })) };
495
+ }
496
+ return { account: publicModel(await reader.account(args.address ?? this.address(args.index).address)) };
497
+ }
542
498
  case 'balances_get': {
543
499
  const addresses = this.selectedAddresses(args);
544
- const accounts = await Promise.all(addresses.map(address => reader.account(address)));
500
+ const accounts = await reader.accounts(addresses);
545
501
  const raw = accounts.reduce((sum, account) => sum + BigInt(account?.balance.toString() ?? '0'), 0n).toString();
546
502
  return { balances: addresses.map((address, i) => {
547
503
  const saved = this.addresses().find(value => value.address === address);
@@ -566,8 +522,20 @@ export class AttoApplication {
566
522
  case 'send': return this.payments.send({ ...args,
567
523
  destination: args.destinationIndex !== undefined ? this.address(args.destinationIndex).address : args.destination,
568
524
  });
569
- case 'receive': return this.receive(args);
570
- case 'receive_all': return this.receiveAll(args);
525
+ case 'marketplace_topup': return this.payments.marketplaceTopUp(args);
526
+ case 'marketplace_topup_status': return this.payments.marketplaceTopUpStatus(args.requestId);
527
+ case 'marketplace_pay_intent': {
528
+ if (!this.internalMarketplacePayment)
529
+ throw new AttoError('INTERNAL_ONLY', 'This operation is available only to the configured private Marketplace wallet child.');
530
+ return this.payments.marketplacePayIntent(args);
531
+ }
532
+ case 'marketplace_pay_intent_status': {
533
+ if (!this.internalMarketplacePayment)
534
+ throw new AttoError('INTERNAL_ONLY', 'This operation is available only to the configured private Marketplace wallet child.');
535
+ return this.payments.marketplacePayIntentStatus(args.requestId);
536
+ }
537
+ case 'receive': return this.receiver.receive(args);
538
+ case 'receive_all': return this.receiver.receiveAll(args);
571
539
  case 'representative_change': return this.changeRepresentative(args.index, args.representative);
572
540
  case 'limits_get':
573
541
  await this.payments.reconcile();
@@ -581,8 +549,9 @@ export class AttoApplication {
581
549
  return { record };
582
550
  }
583
551
  case 'limits_propose': return this.store.withWalletLock(async () => {
584
- const current = { access: this.ledger.mcpAccess(), policy: this.ledger.policy(), pool: this.ledger.pool() };
585
- const proposal = this.ledger.proposePolicy(args.policy, args.access, this.proposalWallet(), args.pool);
552
+ const current = { access: this.ledger.mcpAccess(), policy: this.ledger.policy(), pool: this.ledger.pool(),
553
+ messageSigningIndexes: this.ledger.messageSigningIndexes() };
554
+ const proposal = this.ledger.proposePolicy(args.policy, args.access, this.proposalWallet(), args.pool, args.messageSigningIndexes);
586
555
  return { proposal, approval: approvalInstructions(proposal, current) };
587
556
  });
588
557
  case 'metrics_get': return this.market.metrics();
@@ -619,11 +588,13 @@ export class AttoApplication {
619
588
  else
620
589
  this.requireReady();
621
590
  const args = parseOperation(name, input);
622
- if (!operations.find(operation => operation.name === name).readOnly && name !== 'limits_propose' && !['labels_set', 'labels_remove'].includes(name) && !name.startsWith('watch_'))
591
+ if (!operationFor(name).readOnly && name !== 'limits_propose' && !['labels_set', 'labels_remove'].includes(name) && !name.startsWith('watch_'))
623
592
  this.requireMcpWrite();
624
593
  const call = (async () => {
625
594
  const result = await this.invoke(name, args);
626
- if (name === 'doctor' || ['labels_get', 'labels_list'].includes(name))
595
+ if (this.internalMarketplaceReceiveSafety && name === 'receive' && result?.status === 'unknown')
596
+ return result;
597
+ if (name === 'doctor' || ['labels_get', 'labels_list', 'message_sign', 'message_verify', 'marketplace_pay_intent', 'marketplace_pay_intent_status'].includes(name))
627
598
  return result;
628
599
  if (this.settings().network === 'LIVE' && ['address_list', 'account_get', 'balances_get', 'transaction_get', 'entry_get', 'representative_weight', 'history_list', 'receivables_list'].includes(name))
629
600
  await this.labels.global.refresh();
@@ -637,6 +608,47 @@ export class AttoApplication {
637
608
  this.calls.delete(call);
638
609
  }
639
610
  }
611
+ /** Terminal-only Marketplace controller connection; session tokens remain in memory. */
612
+ async connectMarketplace(input) {
613
+ this.requireReady();
614
+ const connection = await this.store.withWalletLock(() => this.topUps.connect(input));
615
+ return { connected: true, apiUrl: connection.apiUrl, audience: connection.audience,
616
+ controllerIndex: connection.controllerIndex, accountId: connection.accountId, identityId: connection.identityId,
617
+ ...(connection.browserOrigins ? { browserOrigins: connection.browserOrigins } : {}) };
618
+ }
619
+ inspectMarketplaceProofApproval(input) {
620
+ this.requireReady();
621
+ return this.topUps.inspectProofApproval(input);
622
+ }
623
+ async approveMarketplaceProof(input) {
624
+ this.requireReady();
625
+ return this.store.withWalletLock(() => this.topUps.signProofApproval(input));
626
+ }
627
+ /** Private Marketplace terminal signing: no standalone connection is read or changed. */
628
+ async approveMarketplaceOwnedProof(input) {
629
+ this.requireReady();
630
+ if (this.mcp || !process.stdin.isTTY || !process.stderr.isTTY) {
631
+ throw new AttoError('LOCAL_APPROVAL_REQUIRED', 'Approve Marketplace controller actions in the local terminal.');
632
+ }
633
+ return this.store.withWalletLock(async () => {
634
+ const request = validateMarketplaceUserProofApproval(input, { network: 'ATTO', nativeNetwork: 'live' });
635
+ if (this.addresses().find(address => address.index === request.controller.index)?.address !== request.controller.address) {
636
+ throw new AttoError('WALLET_MISMATCH', 'The Marketplace controller does not match this selected wallet and index.');
637
+ }
638
+ const seed = await this.seed();
639
+ try {
640
+ const signer = await derivedSigner(seed, request.controller.index);
641
+ if (signer.address.value !== request.controller.address)
642
+ throw new AttoError('WALLET_MISMATCH', 'The selected controller key changed.');
643
+ validateMarketplaceUserProofApproval(input, { network: 'ATTO', nativeNetwork: 'live' });
644
+ const signature = (await signer.signMessage(new Int8Array(Buffer.from(request.challenge.message, 'utf8')))).toString();
645
+ return createMarketplaceProofApprovalResponse(request, signature);
646
+ }
647
+ finally {
648
+ seed.value.fill(0);
649
+ }
650
+ });
651
+ }
640
652
  // The receiver observes current MCP access on every snapshot, and receive()
641
653
  // rechecks it under the wallet lock before signing any queued payment.
642
654
  async start() {
@@ -4,6 +4,9 @@ export interface Operation {
4
4
  description: string;
5
5
  schema: z.ZodObject;
6
6
  readOnly: boolean;
7
+ internalOnly?: boolean;
7
8
  }
8
9
  export declare const operations: readonly Operation[];
10
+ export declare const internalOperations: readonly Operation[];
11
+ export declare function operationFor(name: string): Operation | undefined;
9
12
  export declare function parseOperation(name: string, input?: unknown): Record<string, unknown>;
@@ -3,6 +3,7 @@ import { z } from 'zod';
3
3
  import { AttoError } from '../domain/errors.js';
4
4
  import { paymentMetadataSchema } from '../spending/journal.js';
5
5
  const index = z.number().int().min(0).max(2_147_483_647);
6
+ const signingIndexes = z.array(index).max(100).refine(indexes => new Set(indexes).size === indexes.length, 'Message-signing indexes must be unique.');
6
7
  const address = z.string().min(1).max(128).describe('Atto address.');
7
8
  const addresses = z.array(address).min(1).max(100);
8
9
  const hash = z.string().regex(/^[a-fA-F0-9]{64}$/).describe('64-character hexadecimal transaction hash.');
@@ -17,6 +18,16 @@ const endpoint = z.url().max(2048).refine(value => {
17
18
  return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash;
18
19
  }, 'Use an HTTP(S) endpoint without credentials, query parameters, or fragments.');
19
20
  const amount = z.strictObject({ amount: decimal, unit });
21
+ const signedMessageInput = z.object({
22
+ message: z.string().refine(value => Buffer.byteLength(value, 'utf8') <= 65_536, 'Message UTF-8 bytes must not exceed 65536.').optional(),
23
+ messageHex: z.string().max(131_072).regex(/^(?:[a-fA-F0-9]{2})*$/, 'Message hex must contain complete bytes.').optional(),
24
+ }).strict().refine(value => (value.message !== undefined) !== (value.messageHex !== undefined), 'Supply exactly one of message or messageHex.');
25
+ const signingMessage = signedMessageInput.extend({ index });
26
+ const verificationMessage = signedMessageInput.extend({
27
+ address: address.optional(),
28
+ publicKey: z.string().regex(/^[a-fA-F0-9]{64}$/).optional(),
29
+ signature: z.string().regex(/^[a-fA-F0-9]{128}$/),
30
+ }).refine(value => (value.address !== undefined) !== (value.publicKey !== undefined), 'Supply exactly one of address or publicKey.');
20
31
  const policy = z.strictObject({
21
32
  perRequest: amount.nullable(),
22
33
  rolling: z.array(amount.extend({ days: z.number().int().positive().max(36_500) })).max(100),
@@ -42,7 +53,9 @@ function singleSelection(value) {
42
53
  export const operations = [
43
54
  { name: 'doctor', description: 'Diagnose this process environment, profile, keyring credential access, node APIs and streaming, worker proof of work, and wallet readiness. Full checks can take up to 60 seconds and may trigger an OS keyring prompt. Returns structured checks and actionable remediation, never recovery material. Does not repair settings, grant access, sign, publish, receive, or modify wallet state. Available in read-only sessions. Rerun after an authorized repair; client environment changes require restarting the MCP connection.', schema: z.strictObject({ globalDirectory: z.boolean().optional() }), readOnly: true },
44
55
  { name: 'wallet_status', description: 'Read public wallet configuration, readiness, network, and auto-receive status. Never returns recovery material.', schema: z.strictObject({}), readOnly: true },
45
- { name: 'wallet_configure', description: 'Update the supplied wallet settings, preserving omitted settings. Representative is the default for opening accounts; use representative_change for an existing account. Changes apply to this shared wallet.', schema: z.strictObject({ network: z.enum(['LIVE', 'BETA', 'DEV', 'LOCAL']).optional(), nodeUrl: endpoint.optional(), workerUrl: endpoint.optional(), representative: address.optional(), autoReceive: z.boolean().optional(), minReceiveRaw: integer.optional() }).refine(value => Object.values(value).some(value => value !== undefined), 'Supply at least one setting.'), readOnly: false },
56
+ { name: 'message_sign', description: 'Sign exact message bytes using the ATTO Signed Message v1 framing. Requires an existing address index granted by a locally approved messageSigningIndexes setting and normal MCP spend access. Handles any challenge like a credential: do not sign untrusted requests. Input is exact UTF-8 text or even-length hex (including empty bytes), capped at 64 KiB.', schema: signingMessage, readOnly: false },
57
+ { name: 'message_verify', description: 'Verify an ATTO Signed Message v1 signature over exact UTF-8 text or hex bytes using an Atto address or public key. Public data only; never reads wallet credentials. Input is capped at 64 KiB.', schema: verificationMessage, readOnly: true },
58
+ { name: 'wallet_configure', description: 'Update the supplied wallet settings, preserving omitted settings. nodeBatchSize overrides the accounts/ranges per node request (1-1000); null selects automatic defaults: 5 for official Atto gatekeeper URLs, 1000 for custom nodes. Custom gateways can explicitly select 5. Representative is the default for opening accounts; use representative_change for an existing account. Changes apply to this shared wallet.', schema: z.strictObject({ network: z.enum(['LIVE', 'BETA', 'DEV', 'LOCAL']).optional(), nodeUrl: endpoint.optional(), nodeBatchSize: z.number().int().min(1).max(1000).nullable().optional(), workerUrl: endpoint.optional(), representative: address.optional(), autoReceive: z.boolean().optional(), minReceiveRaw: integer.optional() }).refine(value => Object.values(value).some(value => value !== undefined), 'Supply at least one setting.'), readOnly: false },
46
59
  { name: 'address_add', description: 'Add and activate the next wallet address after the highest saved index. Includes it in default balances and automatic receiving. Does not open an account on the network. Each call adds a different address.', schema: z.strictObject({}), readOnly: false },
47
60
  { name: 'address_derive', description: 'Derive an address at a mnemonic key index and save its public metadata. Does not open an account on the network.', schema: z.strictObject({ index: index.default(0) }), readOnly: false },
48
61
  { name: 'address_list', description: 'List previously derived addresses and which are active for balances and automatic receiving.', schema: z.strictObject({}), readOnly: true },
@@ -52,14 +65,16 @@ export const operations = [
52
65
  { name: 'labels_remove', description: 'Remove a personal label for an address or existing wallet index. Idempotent; available without spending approval. Existing payment request destinations remain pinned.', schema: z.strictObject(labelTarget).refine(oneLabelTarget, 'Choose exactly one address or index.'), readOnly: false },
53
66
  { name: 'labels_get', description: 'Show personal and informational global address/voter labels for one address or saved index. refresh bypasses the global cache backoff. Sources and payout relationships remain distinct.', schema: z.strictObject({ ...labelTarget, refresh: z.boolean().optional() }).refine(oneLabelTarget, 'Choose exactly one address or index.'), readOnly: true },
54
67
  { name: 'labels_list', description: 'List personal labels; all includes LIVE global address and voter names. Search addresses, names, and entities case-insensitively. refresh forces a global refresh. Global names cannot resolve payments.', schema: z.strictObject({ all: z.boolean().optional(), search: z.string().max(4096).optional(), refresh: z.boolean().optional() }), readOnly: true },
55
- { name: 'account_get', description: 'Read an Atto account by public address or wallet key index. Defaults to index zero.', schema: z.strictObject({ address: address.optional(), index: index.optional() }).refine(value => !(value.address && value.index !== undefined), 'Specify an address or an index, not both.'), readOnly: true },
68
+ { name: 'account_get', description: 'Read full account snapshots, including height, balance and representative. Use addresses for up to 100 external or wallet accounts in one call. Node requests use nodeBatchSize: automatically 5 for official Atto gateways or 1000 for custom nodes. Bulk results preserve address order and include account: null for unopened accounts. Use address or index for one account; defaults to index zero.', schema: z.strictObject({ address: address.optional(), index: index.optional(), addresses: addresses.optional() }).refine(value => [value.address !== undefined, value.index !== undefined, value.addresses !== undefined].filter(Boolean).length <= 1, 'Choose an address, an index, or addresses.'), readOnly: true },
56
69
  { name: 'balances_get', description: 'Read individual and aggregate balances. Defaults to active wallet addresses. Select one saved index, explicit addresses (including foreign addresses), or all saved addresses with all=true.', schema: z.strictObject({ ...accountFields, all: z.boolean().optional() }).refine(singleSelection, 'Choose one account selection.'), readOnly: true },
57
- { name: 'transaction_get', description: 'Read a network transaction by hash.', schema: z.strictObject({ hash }), readOnly: true },
58
- { name: 'entry_get', description: 'Read an account entry by transaction hash.', schema: z.strictObject({ hash }), readOnly: true },
70
+ { name: 'transaction_get', description: 'Read the raw signed protocol transaction by hash, including block, signature and work. Use entry_get for action history; transactions are needed for protocol fields such as a receive block\'s sendHash.', schema: z.strictObject({ hash }), readOnly: true },
71
+ { name: 'entry_get', description: 'Read an action-oriented account entry by transaction hash. address is the account owner; subjectAddress and subjectRole identify the receiver for SEND, sender for OPEN/RECEIVE, or new representative for CHANGE. Transfers include exact amount.raw and amount.atto; representative changes do not transfer funds.', schema: z.strictObject({ hash }), readOnly: true },
59
72
  { name: 'representative_weight', description: 'Read a representative address voting weight.', schema: z.strictObject({ address }), readOnly: true },
60
- { name: 'history_list', description: 'Read bounded account-entry history by default, or full transaction history. Defaults to active wallet addresses; index selects one saved account and addresses can include foreign accounts. Supports heights and a continuation cursor.', schema: z.strictObject({ event: z.enum(['transaction', 'entry']).default('entry'), ...accountFields, fromHeight: integer.optional(), toHeight: integer.optional(), ...listFields }).refine(singleSelection, 'Choose an index or addresses.'), readOnly: true },
73
+ { name: 'history_list', description: 'Read action-oriented entries by default; use event=transaction for raw signed protocol records and receive sendHash linkage. Entries expose owner address, subjectAddress, subjectRole and exact transfer amount. Supply up to 100 addresses together for batched reads, or index for one saved account; defaults to active accounts. Results follow address order and ascending height. Limit is at most 1000 records. Reuse nextCursor with the same filters to continue frozen account heights without rescanning earlier pages; timedOut may return a partial page.', schema: z.strictObject({ event: z.enum(['transaction', 'entry']).default('entry'), ...accountFields, fromHeight: integer.optional(), toHeight: integer.optional(), ...listFields }).refine(singleSelection, 'Choose an index or addresses.'), readOnly: true },
61
74
  { name: 'receivables_list', description: 'Scan pending incoming payments, defaulting to active wallet addresses. Select a saved index or explicit addresses, including foreign accounts. This is a bounded scan, without continuation cursors; timedOut means the scan window ended and more payments may exist.', schema: z.strictObject({ ...accountFields, minAmountRaw: integer.optional(), limit: limit.optional(), timeoutMs: timeoutMs.optional() }).refine(singleSelection, 'Choose an index or addresses.'), readOnly: true },
62
75
  { name: 'send', description: 'Send funds to exactly one destination address, saved destinationIndex, or personal destinationLabel, subject to shared spending limits. Omit index to select an account from the approved pool. Explicit MCP indexes must belong to that pool and hold the full amount. Approved consolidation may combine pool funds only when index is omitted. Metadata is optional local journal data (up to 4096 UTF-8 bytes) and is never published on the network. USD uses an indicative price and requires accepted terms. Reuse requestId for retries; the original account, metadata, and USD conversion are preserved. Omit metadata to retain it; changed metadata is rejected.', schema: z.strictObject({ index: index.optional(), destination: address.optional(), destinationLabel: personalNameSchema.optional().describe('Exact personal name; global-only names fail locally. The original label and resolved address are pinned per request ID before network access.'), destinationIndex: index.optional().describe('Existing saved destination account index, instead of destination.'), amount: decimal, unit: z.enum(['ATTO', 'RAW', 'USD']).default('ATTO'), requestId: z.string().min(1).max(128), metadata: paymentMetadataSchema.optional() }).refine(value => [value.destination, value.destinationIndex, value.destinationLabel].filter(value => value !== undefined).length === 1, 'Choose exactly one destination address, destination index, or personal label.'), readOnly: false },
76
+ { name: 'marketplace_topup', description: 'Fund only the configured Marketplace ATTO account using a bounded native x402 exact payment. Uses this wallet’s approved spend policy and pool; no tasks or hiring actions are available. Reuse requestId to recover the same intent and exact signed payment after uncertainty. Amount is an exact ATTO or RAW decimal string.', schema: z.strictObject({ amount: decimal, unit: unit.default('ATTO'), requestId: z.string().min(1).max(128), index: index.optional() }), readOnly: false },
77
+ { name: 'marketplace_topup_status', description: 'Read the current Marketplace account top-up status by its original requestId and reconcile the same native payment. Does not create or replace a payment.', schema: z.strictObject({ requestId: z.string().min(1).max(128) }), readOnly: true },
63
78
  { name: 'pool_get', description: 'Read the approved send pool, its account balances, and readiness for payments. Does not reserve an account or move funds.', schema: z.strictObject({}), readOnly: true },
64
79
  { name: 'journal_list', description: 'List local payment journal records, newest first, with an optional status filter. Includes caller metadata and recorded payment progress; metadata is not an authenticated statement from the network.', schema: z.strictObject({ limit: z.number().int().min(1).max(100).default(50), cursor: cursor.optional(), status: z.enum(['reserved', 'signed', 'published', 'unknown', 'failed']).optional() }), readOnly: true },
65
80
  { name: 'journal_get', description: 'Read a local payment journal record by its request ID, including caller metadata and recorded payment progress.', schema: z.strictObject({ requestId: z.string().min(1).max(128) }), readOnly: true },
@@ -70,15 +85,22 @@ export const operations = [
70
85
  { name: 'receive', description: 'Receive one pending payment by hash, opening the account if needed.', schema: z.strictObject({ index: index.default(0), hash, representative: address.optional() }), readOnly: false },
71
86
  { name: 'receive_all', description: 'Receive a bounded set of pending payments for a key index, opening the account if needed.', schema: z.strictObject({ index: index.default(0), limit: limit.default(100), timeoutMs: timeoutMs.default(2000), representative: address.optional() }), readOnly: false },
72
87
  { name: 'representative_change', description: 'Publish a representative change for an existing account. Selecting its current representative returns REPRESENTATIVE_UNCHANGED without publishing.', schema: z.strictObject({ index: index.default(0), representative: address }), readOnly: false },
73
- { name: 'limits_get', description: 'Read spending policy, approved send pool, MCP access, proposal status, historical usage, reservations, and remaining allowances.', schema: z.strictObject({}), readOnly: true },
74
- { name: 'limits_propose', description: 'Propose spending limits, MCP access, and optional send-pool settings for local terminal approval. Omitted pool preserves the approved pool. Does not change active settings or grant access. A new proposal replaces the previous proposal and expires after 24 hours. Read limits_get for active settings and proposal status. Returns proposal plus approval.changes (changed access, policy, and pool with from/to values), approval.shell, and profile-specific approval.commands.atto/npx for the user to run in a local terminal. Preserve the returned directory and proposal ID; never run approval commands on the user\'s behalf. Spending access, amount limits, and source-pool approval are separate. Amounts are ATTO or RAW; null perRequest with empty rolling means unlimited spending, not missing authorization.', schema: z.strictObject({ policy, access: z.enum(['read-only', 'spend']).default('spend'), pool: pool.optional() }), readOnly: false },
88
+ { name: 'limits_get', description: 'Read spending policy, approved send pool, MCP access, message-signing indexes, proposal status, historical usage, reservations, and remaining allowances.', schema: z.strictObject({}), readOnly: true },
89
+ { name: 'limits_propose', description: 'Propose spending limits, MCP access, send-pool settings, and message-signing indexes for local terminal approval. Omitted pool and messageSigningIndexes preserve their current settings. Does not change active settings or grant access. A new proposal replaces the previous proposal and expires after 24 hours. Read limits_get for active settings and proposal status. Returns proposal plus approval.changes (changed access, policy, pool, and messageSigningIndexes with from/to values), approval.shell, and profile-specific approval.commands.atto/npx for the user to run in a local terminal. Preserve the returned directory and proposal ID; never run approval commands on the user\'s behalf. Spending access, amount limits, source-pool approval, and message-signing grants are separate. Amounts are ATTO or RAW; null perRequest with empty rolling means unlimited spending, not missing authorization.', schema: z.strictObject({ policy, access: z.enum(['read-only', 'spend']).default('spend'), pool: pool.optional(), messageSigningIndexes: signingIndexes.optional() }), readOnly: false },
75
90
  { name: 'watch_start', description: 'Start an observational, reconnecting watch for this session, defaulting to active wallet addresses. Choose one saved index, explicit addresses (including foreign accounts), a transaction/entry hash, or networkWide=true. Network-wide receivables are unsupported. Read buffered events and connection status with watch_read. Does not enable automatic receiving.', schema: z.strictObject({ event: z.enum(['account', 'transaction', 'entry', 'receivable']), ...streamFields, index: index.optional(), networkWide: z.boolean().optional() }).refine(singleSelection, 'Choose one watch selection.').refine(value => !(value.networkWide && value.event === 'receivable'), 'Receivable watches require addresses.'), readOnly: false },
76
91
  { name: 'watch_list', description: 'List watches owned by this process.', schema: z.strictObject({}), readOnly: true },
77
92
  { name: 'watch_read', description: 'Read buffered events after an optional numeric cursor. Gaps are reported if bounded event retention was exceeded.', schema: z.strictObject({ id: z.string().min(1).max(128), cursor: z.number().int().nonnegative().optional(), limit: limit.optional() }), readOnly: true },
78
93
  { name: 'watch_stop', description: 'Stop a watch owned by this process and cancel its network subscription.', schema: z.strictObject({ id: z.string().min(1).max(128) }), readOnly: false },
79
94
  ];
95
+ export const internalOperations = [
96
+ { name: 'marketplace_pay_intent', description: 'Private Marketplace-child operation. Sign one existing exact ATTO x402 intent supplied by the configured Marketplace process. Requires the matching locally configured API origin/audience/network and approved wallet spend access and pool. Persists the exact challenge and signature for same-request recovery. Never creates an intent or submits the payment.', schema: z.strictObject({ requestId: z.string().regex(/^[A-Za-z0-9_-]{16,128}$/), intentId: z.string().uuid(), amountAtomic: integer, paymentIdentifier: z.string().regex(/^[A-Za-z0-9_-]{16,128}$/), paymentRequired: z.string().min(1).max(90_000), apiUrl: z.string().min(1).max(2048), audience: z.string().min(1).max(255), resourceUrl: z.string().min(1).max(2048), expiresAt: z.string().min(1).max(128), index: index.optional() }), readOnly: false, internalOnly: true },
97
+ { name: 'marketplace_pay_intent_status', description: 'Private Marketplace-child operation. Reconcile the saved block against the configured native chain and return its binding. Recover the exact saved signature while unresolved or published; native rejection returns terminal FAILED without a signature. Never re-sign or replace the saved challenge.', schema: z.strictObject({ requestId: z.string().regex(/^[A-Za-z0-9_-]{16,128}$/) }), readOnly: true, internalOnly: true },
98
+ ];
99
+ export function operationFor(name) {
100
+ return [...operations, ...internalOperations].find(operation => operation.name === name);
101
+ }
80
102
  export function parseOperation(name, input = {}) {
81
- const operation = operations.find(operation => operation.name === name);
103
+ const operation = operationFor(name);
82
104
  if (!operation)
83
105
  throw new AttoError('UNKNOWN_OPERATION', 'Unknown Atto operation.');
84
106
  const parsed = operation.schema.safeParse(input);
package/dist/cli/cli.d.ts CHANGED
@@ -1 +1,2 @@
1
+ export { formatMarketplaceApprovalPreview } from '../marketplace/approval-preview.js';
1
2
  export declare function runCli(argv?: string[]): Promise<void>;