oneie 5.7.6 → 5.8.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 (47) hide show
  1. package/README.md +19 -1
  2. package/dist/package.json +1 -1
  3. package/dist/src/ceiling.d.ts +36 -0
  4. package/dist/src/ceiling.js +189 -0
  5. package/dist/src/check.d.ts +11 -0
  6. package/dist/src/check.js +53 -0
  7. package/dist/src/credits.d.ts +29 -0
  8. package/dist/src/credits.js +88 -0
  9. package/dist/src/index.js +13 -0
  10. package/dist/src/join.js +4 -0
  11. package/dist/src/key-sweep.js +15 -8
  12. package/dist/src/lib/check-words.d.ts +57 -0
  13. package/dist/src/lib/check-words.js +144 -0
  14. package/dist/src/lib/journey-words.js +6 -3
  15. package/dist/src/lib/journey.d.ts +2 -0
  16. package/dist/src/lib/journey.js +20 -1
  17. package/dist/src/lib/net-choice.d.ts +28 -0
  18. package/dist/src/lib/net-choice.js +72 -0
  19. package/dist/src/lib/network.d.ts +7 -0
  20. package/dist/src/lib/network.js +13 -4
  21. package/dist/src/lib/next-words.d.ts +105 -0
  22. package/dist/src/lib/next-words.js +298 -0
  23. package/dist/src/lib/sui-grpc-send.d.ts +41 -1
  24. package/dist/src/lib/sui-grpc-send.js +44 -5
  25. package/dist/src/lib/timed-fetch.d.ts +33 -0
  26. package/dist/src/lib/timed-fetch.js +59 -0
  27. package/dist/src/lib/vaultfile.d.ts +15 -0
  28. package/dist/src/lib/vaultfile.js +28 -1
  29. package/dist/src/move.d.ts +36 -0
  30. package/dist/src/move.js +152 -0
  31. package/dist/src/network-cmd.d.ts +17 -0
  32. package/dist/src/network-cmd.js +74 -0
  33. package/dist/src/next.d.ts +12 -0
  34. package/dist/src/next.js +67 -0
  35. package/dist/src/shop-buy.d.ts +16 -0
  36. package/dist/src/shop-buy.js +101 -0
  37. package/dist/src/shop.js +2 -0
  38. package/dist/src/start.d.ts +12 -0
  39. package/dist/src/start.js +37 -15
  40. package/dist/src/thread.d.ts +2 -0
  41. package/dist/src/thread.js +52 -0
  42. package/dist/src/wallet-money.d.ts +7 -1
  43. package/dist/src/wallet-money.js +131 -31
  44. package/dist/src/wallet.d.ts +2 -0
  45. package/dist/src/wallet.js +122 -4
  46. package/dist/src/workflow.js +4 -1
  47. package/package.json +1 -1
@@ -0,0 +1,152 @@
1
+ /**
2
+ * move.ts — `one move publish <package dir>`: publish a Move package from a THROWAWAY deployer
3
+ * and hand everything it made to its owner, so no key that ever touched the publish keeps power.
4
+ *
5
+ * 1. build `sui move build --dump-bytecode-as-base64 -e <net>` in a temp copy (the repo's
6
+ * Move.lock and build/ are never written).
7
+ * 2. mint a fresh deployer key, in memory. It is kept, 0600, under ~/.one/deployers/ only so
8
+ * a crash between steps can still return the dust; it never prints and owns nothing
9
+ * once the run ends.
10
+ * 3. fund `--fund` SUI from the sealed vault in `--fund-dir` to the deployer.
11
+ * 4. publish one transaction: publish, and the UpgradeCap to `--owner` in the same PTB.
12
+ * 5. hand on one transaction from the deployer: every object `init` gave it goes to `--owner`
13
+ * (a `::WorkerCap` to `--worker-cap-to` when named), and the whole gas coin goes
14
+ * back to the funder.
15
+ * 6. read every created object is read back from the chain; the run is ok only if the
16
+ * UpgradeCap and every handed-on object sit with the address they were sent to and
17
+ * the deployer holds nothing.
18
+ *
19
+ * Dry by default: without --live it builds, prints the plan, and signs nothing. Only addresses,
20
+ * object ids and digests are printed. Every Sui act goes through suiExecGrpc, the CLI's one signer.
21
+ */
22
+ import { Command } from 'commander';
23
+ import { spawnSync } from 'node:child_process';
24
+ import { randomBytes } from 'node:crypto';
25
+ import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
26
+ import { homedir, tmpdir } from 'node:os';
27
+ import { basename, join, resolve } from 'node:path';
28
+ import { out } from './lib/client.js';
29
+ import { SuiSendError, loadSpec, mistToSui, suiExecGrpc, suiReadObjects, suiSendGrpc } from './lib/sui-grpc-send.js';
30
+ import { SUI_NATIVE } from './lib/wallet-money.js';
31
+ import { unlock } from './wallet.js';
32
+ import { netLine, resolveNet } from './lib/net-choice.js';
33
+ const SUI_ADDR = /^0x[0-9a-f]{64}$/i;
34
+ /** Compile in a temp copy so the repo's Move.lock and build/ stay untouched. */
35
+ export function buildBytecode(dir, net) {
36
+ const work = mkdtempSync(join(tmpdir(), 'one-move-'));
37
+ try {
38
+ const copy = join(work, basename(resolve(dir)));
39
+ cpSync(resolve(dir), copy, { recursive: true, filter: (p) => !p.includes(`${'/'}build${'/'}`) && !p.endsWith('/build') });
40
+ const r = spawnSync('sui', ['move', 'build', '--dump-bytecode-as-base64', '-e', net, '--path', copy], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
41
+ if (r.error)
42
+ throw new SuiSendError('sui_cli_missing', 'the `sui` CLI is not on PATH (brew install sui)');
43
+ const line = (r.stdout ?? '').split('\n').reverse().find((l) => l.trim().startsWith('{"modules"'));
44
+ if (r.status !== 0 || !line)
45
+ throw new SuiSendError('move_build_failed', ((r.stderr ?? '') + (r.stdout ?? '')).trim().split('\n').slice(-3).join(' | ') || 'no bytecode');
46
+ return JSON.parse(line);
47
+ }
48
+ finally {
49
+ rmSync(work, { recursive: true, force: true });
50
+ }
51
+ }
52
+ /** Where each object the deployer was given goes: a WorkerCap to its worker, everything else to the owner. */
53
+ export function handOnPlan(created, deployer, owner, workerCapTo) {
54
+ return created
55
+ .filter((c) => c.owner.toLowerCase() === deployer.toLowerCase())
56
+ .map((c) => ({ ...c, to: workerCapTo && /::WorkerCap$/.test(c.type) ? workerCapTo : owner }));
57
+ }
58
+ export function moveCmd() {
59
+ const cmd = new Command('move').description('Move packages on Sui — publish from a throwaway key and hand every cap to its owner');
60
+ cmd.command('publish <dir>')
61
+ .description('Publish a Move package from a THROWAWAY deployer: fund it from --fund-dir, publish, send the UpgradeCap and every init object to --owner (a WorkerCap to --worker-cap-to), return the gas, read it all back. Dry unless --live')
62
+ .requiredOption('--owner <address>', 'Sui address that receives the UpgradeCap and every owned object the package creates')
63
+ .option('--worker-cap-to <address>', 'Sui address for a ::WorkerCap (default: --owner)')
64
+ .option('--fund-dir <dir>', 'Sealed vault folder that funds the deployer (Keychain / Touch ID)')
65
+ .option('--fund <sui>', 'SUI to fund the deployer with', '1')
66
+ .option('--net <network>', 'testnet | mainnet (default: ONE_NETWORK, then `one network`, then the deploy)')
67
+ .option('--rpc <url>', 'gRPC base URL override')
68
+ .option('--live', 'Sign and send. Without it: build and print the plan only')
69
+ .action(async (dir, o, sub) => {
70
+ const t0 = Date.now();
71
+ const nc = await resolveNet(o.net);
72
+ if (!nc.ok)
73
+ return out(sub, nc);
74
+ const net = nc.net;
75
+ if (!SUI_ADDR.test(o.owner))
76
+ return out(sub, { ok: false, error: 'owner_not_a_sui_address' });
77
+ if (o.workerCapTo && !SUI_ADDR.test(o.workerCapTo))
78
+ return out(sub, { ok: false, error: 'worker_cap_to_not_a_sui_address' });
79
+ if (!/^\d+(\.\d{1,9})?$/.test(o.fund) || Number(o.fund) <= 0)
80
+ return out(sub, { ok: false, error: 'fund_not_an_amount' });
81
+ const fundMist = BigInt(o.fund.split('.')[0]) * 1000000000n + BigInt((o.fund.split('.')[1] ?? '').padEnd(9, '0') || '0');
82
+ let code;
83
+ try {
84
+ code = buildBytecode(dir, net);
85
+ }
86
+ catch (e) {
87
+ return out(sub, { ok: false, error: e.code ?? 'move_build_failed', detail: e.message });
88
+ }
89
+ const plan = {
90
+ package: basename(resolve(dir)), net, networkFrom: nc.from, says: netLine(nc), modules: code.modules.length, dependencies: code.dependencies,
91
+ owner: o.owner, workerCapTo: o.workerCapTo ?? o.owner, fund: `${o.fund} SUI`, fundDir: o.fundDir ?? null,
92
+ };
93
+ if (!o.live)
94
+ return out(sub, { ok: true, dry: true, plan, next: 'add --live (and --fund-dir) to publish' });
95
+ if (!o.fundDir)
96
+ return out(sub, { ok: false, error: 'fund_dir_required', detail: '--live needs --fund-dir <vault folder> to fund the deployer' });
97
+ const opened = await unlock(o.fundDir);
98
+ if ('error' in opened)
99
+ return out(sub, { ok: false, error: 'vault_locked', detail: opened.error });
100
+ const funderKey = opened.keys.find((k) => k.chain === 'sui');
101
+ if (!funderKey)
102
+ return out(sub, { ok: false, error: 'no_sui_key_in_vault' });
103
+ // The throwaway. Kept 0600 outside any repo only so dust can be recovered after a crash.
104
+ const kp = (await loadSpec('@mysten/sui/keypairs/ed25519'));
105
+ const secret = randomBytes(32);
106
+ const deployer = kp.Ed25519Keypair.fromSecretKey(secret).toSuiAddress();
107
+ const secretHex = secret.toString('hex');
108
+ const keep = join(homedir(), '.one', 'deployers');
109
+ mkdirSync(keep, { recursive: true, mode: 0o700 });
110
+ const keptAt = join(keep, `${net}-${plan.package}-${Date.now()}.json`);
111
+ writeFileSync(keptAt, JSON.stringify({ net, package: plan.package, address: deployer, secretKeyHex: secretHex, minted: new Date().toISOString() }), { mode: 0o600 });
112
+ const steps = { deployer, deployerKeptAt: keptAt };
113
+ try {
114
+ const fundTx = await suiSendGrpc({ asset: 'SUI', coinType: SUI_NATIVE, from: funderKey.address, to: deployer, amountUnits: fundMist, privateKeyHex: funderKey.privateKeyHex, net, rpc: o.rpc });
115
+ steps.fund = { digest: fundTx.digest, from: funderKey.address, amount: `${o.fund} SUI`, ms: fundTx.finalMs };
116
+ const pub = await suiExecGrpc({
117
+ net, rpc: o.rpc, from: deployer, privateKeyHex: secretHex,
118
+ build: (tx) => {
119
+ const [upgradeCap] = tx.publish({ modules: code.modules, dependencies: code.dependencies });
120
+ tx.transferObjects([upgradeCap], tx.pure.address(o.owner));
121
+ },
122
+ });
123
+ const pkg = pub.created.find((c) => c.owner === 'package');
124
+ const upgradeCap = pub.created.find((c) => /::package::UpgradeCap$/.test(c.type));
125
+ steps.publish = { digest: pub.digest, packageId: pkg?.objectId, upgradeCap: upgradeCap?.objectId, created: pub.created, gas: `${mistToSui(pub.gasMist)} SUI`, ms: pub.finalMs };
126
+ const hand = handOnPlan(pub.created, deployer, o.owner, o.workerCapTo);
127
+ const back = await suiExecGrpc({
128
+ net, rpc: o.rpc, from: deployer, privateKeyHex: secretHex,
129
+ build: (tx) => {
130
+ for (const to of new Set(hand.map((h) => h.to))) {
131
+ tx.transferObjects(hand.filter((h) => h.to === to).map((h) => tx.object(h.objectId)), tx.pure.address(to));
132
+ }
133
+ tx.transferObjects([tx.gas], tx.pure.address(funderKey.address));
134
+ },
135
+ });
136
+ steps.handOn = { digest: back.digest, objects: hand.map((h) => ({ objectId: h.objectId, type: h.type, to: h.to })), gasReturnedTo: funderKey.address, ms: back.finalMs };
137
+ // Read back. Ok only if every cap sits where it was sent and the deployer holds nothing.
138
+ const ids = [...(upgradeCap ? [upgradeCap.objectId] : []), ...hand.map((h) => h.objectId)];
139
+ const read = await suiReadObjects(net, ids, { rpc: o.rpc });
140
+ const want = new Map([...(upgradeCap ? [[upgradeCap.objectId, o.owner]] : []), ...hand.map((h) => [h.objectId, h.to])]);
141
+ const wrong = read.filter((r) => (want.get(r.objectId) ?? '').toLowerCase() !== r.owner.toLowerCase());
142
+ steps.readBack = read;
143
+ const ok = Boolean(pkg && upgradeCap) && wrong.length === 0;
144
+ return out(sub, { ok, ...(ok ? {} : { error: 'read_back_mismatch', wrong }), net, packageId: pkg?.objectId, upgradeCap: upgradeCap?.objectId, ...steps, wallMs: Date.now() - t0 });
145
+ }
146
+ catch (e) {
147
+ const err = e;
148
+ return out(sub, { ok: false, error: err.code ?? 'move_publish_failed', detail: err.message, ...(err.digest ? { digest: err.digest } : {}), ...steps, recover: `deployer key kept at ${keptAt} (0600) — return its SUI with a send from that key` });
149
+ }
150
+ });
151
+ return cmd;
152
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * network-cmd.ts — `one network [mainnet|testnet|auto]`: the one switch every chain command reads
3
+ * (lib/net-choice.ts). Bare: which network a command would use right now, and why. A name: save it in
4
+ * ~/.config/one/network. `auto`: clear it, so commands follow the deploy again.
5
+ *
6
+ * Tony, 2026-11-12: "making the switch between testnet to mainnet and back to testnet for training to be
7
+ * seamless and delightful." So the switch says, in one line, what it means for your money, then shows the
8
+ * wallet in this folder on that network — and on testnet with nothing in it, the one command for free coins.
9
+ */
10
+ import { Command } from 'commander';
11
+ import { type NetChoice } from './lib/net-choice.js';
12
+ import { type Net } from './lib/network.js';
13
+ /** The headline: what this network means for your money, in plain words. */
14
+ export declare function headline(c: NetChoice & {
15
+ ok: true;
16
+ }, deploy: Net | null): string;
17
+ export declare function networkCmd(): Command;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * network-cmd.ts — `one network [mainnet|testnet|auto]`: the one switch every chain command reads
3
+ * (lib/net-choice.ts). Bare: which network a command would use right now, and why. A name: save it in
4
+ * ~/.config/one/network. `auto`: clear it, so commands follow the deploy again.
5
+ *
6
+ * Tony, 2026-11-12: "making the switch between testnet to mainnet and back to testnet for training to be
7
+ * seamless and delightful." So the switch says, in one line, what it means for your money, then shows the
8
+ * wallet in this folder on that network — and on testnet with nothing in it, the one command for free coins.
9
+ */
10
+ import { Command } from 'commander';
11
+ import { jsonMode, out } from './lib/client.js';
12
+ import { NET_FILE, resolveNet, saveNet, savedNet, webBase } from './lib/net-choice.js';
13
+ import { readDeployNetwork } from './lib/network.js';
14
+ import { SUI, SUI_NATIVE, readSuiCoin } from './lib/wallet-money.js';
15
+ import { deadlineFetch, vaultSuiAddressOf } from './wallet-money.js';
16
+ /** The headline: what this network means for your money, in plain words. */
17
+ export function headline(c, deploy) {
18
+ const why = { flag: '--net', env: 'ONE_NETWORK', saved: 'your choice', deploy: 'one.ie' }[c.from];
19
+ if (c.net === 'testnet')
20
+ return `◐ Practice — test coins, free to get, nothing real moves. (${why})`;
21
+ return `● Real money — every send names MAINNET and waits for --live. (${why}${c.from !== 'deploy' && deploy === 'testnet' ? ', while one.ie still runs testnet' : ''})`;
22
+ }
23
+ const units = (v, d) => {
24
+ const w = (v / 10n ** BigInt(d)).toString();
25
+ const f = (v % 10n ** BigInt(d)).toString().padStart(d, '0').replace(/0+$/, '');
26
+ return f ? `${w}.${f}` : w;
27
+ };
28
+ export function networkCmd() {
29
+ return new Command('network')
30
+ .description('Testnet or mainnet for every chain command. Bare: the network now and why. `mainnet|testnet`: switch. `auto`: follow one.ie. Order: --net, ONE_NETWORK, this choice, the deploy')
31
+ .argument('[choice]', 'mainnet | testnet | auto')
32
+ .option('--api <url>', 'one.ie base URL whose deploy is followed')
33
+ .option('--dir <path>', 'The wallet folder to show on this network', '.')
34
+ .action(async (choice, o, sub) => {
35
+ const t0 = Date.now();
36
+ if (choice !== undefined) {
37
+ if (choice !== 'mainnet' && choice !== 'testnet' && choice !== 'auto')
38
+ return out(sub, { ok: false, error: 'bad_choice', message: 'one network mainnet | testnet | auto' });
39
+ saveNet(choice === 'auto' ? null : choice);
40
+ }
41
+ const base = webBase(o.api);
42
+ const [now, deploy] = await Promise.all([resolveNet(undefined, o.api), readDeployNetwork(base)]);
43
+ const saved = savedNet();
44
+ const env = process.env.ONE_NETWORK?.trim() || null;
45
+ // This folder's wallet, on the network just chosen. Public address only — the vault never opens.
46
+ const sui = vaultSuiAddressOf(o.dir);
47
+ let wallet = null;
48
+ if (now.ok && sui) {
49
+ const f = deadlineFetch(6000);
50
+ const [s, u] = await Promise.all([readSuiCoin(f, now.net, sui, SUI_NATIVE), readSuiCoin(f, now.net, sui, SUI[now.net].usdc)]);
51
+ wallet = { address: sui, sui: s === null ? null : units(s, 9), usdc: u === null ? null : units(u, 6) };
52
+ }
53
+ const empty = wallet && wallet.sui !== null && Number(wallet.sui) === 0;
54
+ if (jsonMode(sub))
55
+ return out(sub, { ok: now.ok, network: now.ok ? now.net : null, from: now.ok ? now.from : null, deploy, saved, env, wallet, ms: Date.now() - t0, ...(now.ok ? {} : { error: now.error }) });
56
+ if (!now.ok) {
57
+ process.exitCode = 1;
58
+ process.stdout.write(`? Which network? ${now.message}\n`);
59
+ return;
60
+ }
61
+ const short = (a) => `${a.slice(0, 6)}…${a.slice(-4)}`;
62
+ const lines = [
63
+ headline(now, deploy),
64
+ ...(wallet ? [` your wallet ${short(wallet.address)}: ${wallet.sui ?? '—'} SUI · ${wallet.usdc ?? '—'} USDC on ${now.net}`] : []),
65
+ ...(now.net === 'testnet' && wallet && empty ? [` free test coins: one wallet faucet ${wallet.address} --chain sui --network testnet`] : []),
66
+ '',
67
+ now.net === 'testnet' ? ' back to real money: one network mainnet' : ' practise first: one network testnet',
68
+ saved ? ' follow one.ie again: one network auto' : ` one.ie runs ${deploy ?? 'an unreadable network'} — this follows it`,
69
+ ...(env ? [` ONE_NETWORK=${env} is set in this shell and wins over the switch`] : []),
70
+ ` order: --net, then ONE_NETWORK, then this switch${saved ? ` (${NET_FILE})` : ''}, then one.ie`,
71
+ ];
72
+ process.stdout.write(lines.join('\n') + '\n');
73
+ });
74
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `one next` (alias `one learn`): where you are, and the one thing to do now.
3
+ * `one learn <topic>` teaches one thing: me · key · wallets · limit · sell · paid · ask · never · course.
4
+ *
5
+ * Reads this folder only (`.one/`), never the network: the "what now" door answers at
6
+ * once. The words are `lib/next-words.ts`; this file reads the disk and prints.
7
+ */
8
+ import { Command } from 'commander';
9
+ import { type NextFacts } from './lib/next-words.js';
10
+ /** The folder's facts. Secrets are checked for presence only; their contents are never read. */
11
+ export declare function readFacts(dir: string): NextFacts;
12
+ export declare function nextCmd(): Command;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * `one next` (alias `one learn`): where you are, and the one thing to do now.
3
+ * `one learn <topic>` teaches one thing: me · key · wallets · limit · sell · paid · ask · never · course.
4
+ *
5
+ * Reads this folder only (`.one/`), never the network: the "what now" door answers at
6
+ * once. The words are `lib/next-words.ts`; this file reads the disk and prints.
7
+ */
8
+ import { Command } from 'commander';
9
+ import { existsSync, readFileSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { jsonMode } from './lib/client.js';
12
+ import { cliPrefix } from './lib/invoked-as.js';
13
+ import { isAgentEnvironment } from './lib/agent-env.js';
14
+ import { KEY_DIR_NAME, KEY_FILE_NAME, LEGACY_KEY_DIR_NAME } from './lib/keyfile.js';
15
+ import { readVaultFolder } from './lib/vaultfile.js';
16
+ import { asciiOf } from './lib/journey-words.js';
17
+ import { isTopic, learnWords, nextData, nextWords, TOPICS } from './lib/next-words.js';
18
+ /** The folder's facts. Secrets are checked for presence only; their contents are never read. */
19
+ export function readFacts(dir) {
20
+ let state = null;
21
+ try {
22
+ const s = JSON.parse(readFileSync(join(dir, KEY_DIR_NAME, 'journey.json'), 'utf8'));
23
+ if (s && s.v === 1 && typeof s.workspace === 'string')
24
+ state = s;
25
+ }
26
+ catch { /* no journey here yet */ }
27
+ const hasKey = [KEY_DIR_NAME, LEGACY_KEY_DIR_NAME].some((d) => existsSync(join(dir, d, KEY_FILE_NAME)));
28
+ const v = readVaultFolder(dir);
29
+ return { state, hasKey, vault: v ? v.wrap : null };
30
+ }
31
+ export function nextCmd() {
32
+ return new Command('next')
33
+ .alias('learn')
34
+ .description(`Where you are, and the one thing to do now. Teach one thing: learn <${TOPICS.join('|')}>`)
35
+ .argument('[topic]', TOPICS.join(' | '))
36
+ .option('--for <reader>', 'agent (the whole primer) or person (one step). Default: agent in an agent shell, person at a terminal')
37
+ .option('--dir <path>', 'The agent\'s folder', '.')
38
+ .action((topic, opts, cmd) => {
39
+ if (topic && !isTopic(topic)) {
40
+ const error = `no lesson called "${topic}". Lessons: ${TOPICS.join(', ')}`;
41
+ if (jsonMode(cmd))
42
+ process.stdout.write(JSON.stringify({ ok: false, error }) + '\n');
43
+ else
44
+ process.stderr.write(`${error}\n`);
45
+ process.exitCode = 1;
46
+ return;
47
+ }
48
+ if (opts.for && opts.for !== 'agent' && opts.for !== 'person') {
49
+ process.stderr.write('--for is agent or person\n');
50
+ process.exitCode = 1;
51
+ return;
52
+ }
53
+ const facts = readFacts(opts.dir);
54
+ const cli = cliPrefix();
55
+ if (jsonMode(cmd)) {
56
+ const data = nextData(facts, cli);
57
+ // A topic narrows the answer to that one lesson; bare gives every lesson.
58
+ const body = topic ? { ...data, lessons: data.lessons.filter((l) => l.topic === topic) } : data;
59
+ process.stdout.write(JSON.stringify({ ok: true, ...body }) + '\n');
60
+ return;
61
+ }
62
+ const reader = opts.for ?? (isAgentEnvironment() ? 'agent' : 'person');
63
+ const text = topic && isTopic(topic) ? learnWords(facts, cli, reader, topic) : nextWords(facts, cli, reader);
64
+ const plain = !process.stdout.isTTY || 'NO_COLOR' in process.env;
65
+ process.stdout.write(plain ? asciiOf(text) : text);
66
+ });
67
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * shop-buy.ts — `one shop buy <workspace> <ppid>`: an agent buys a store's product with USDC on Sui from its own
3
+ * vault, through the same route the checkout page uses (/api/storefront/crypto):
4
+ *
5
+ * 1. quote action:'quote' — the store's price, its Sui option, usdcEligible
6
+ * 2. escrow action:'escrow' — a deposit address for THIS sale and the exact USDC amount pay recorded
7
+ * 3. pay the vault in --dir sends exactly that USDC to the deposit address (suiSendGrpc, the one Sui signer)
8
+ * 4. status action:'status' — polled until pay sees the money (completed); forwardTxHash once the sweep moves it on
9
+ *
10
+ * No address or amount is ever typed: both come back from the route, which reads them server-side. Dry by default:
11
+ * without --live it quotes and stops — the escrow address is minted only by a live run, because minting one is a write.
12
+ */
13
+ import { Command } from 'commander';
14
+ /** "1.000000" USDC → 1000000 base units (6 decimals); anything else → null. */
15
+ export declare function usdcUnits(v: unknown): bigint | null;
16
+ export declare function shopBuyCmd(): Command;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * shop-buy.ts — `one shop buy <workspace> <ppid>`: an agent buys a store's product with USDC on Sui from its own
3
+ * vault, through the same route the checkout page uses (/api/storefront/crypto):
4
+ *
5
+ * 1. quote action:'quote' — the store's price, its Sui option, usdcEligible
6
+ * 2. escrow action:'escrow' — a deposit address for THIS sale and the exact USDC amount pay recorded
7
+ * 3. pay the vault in --dir sends exactly that USDC to the deposit address (suiSendGrpc, the one Sui signer)
8
+ * 4. status action:'status' — polled until pay sees the money (completed); forwardTxHash once the sweep moves it on
9
+ *
10
+ * No address or amount is ever typed: both come back from the route, which reads them server-side. Dry by default:
11
+ * without --live it quotes and stops — the escrow address is minted only by a live run, because minting one is a write.
12
+ */
13
+ import { Command } from 'commander';
14
+ import { authHeaders, out, resolveBase } from './lib/client.js';
15
+ import { suiSendGrpc } from './lib/sui-grpc-send.js';
16
+ import { SUI } from './lib/wallet-money.js';
17
+ import { unlock } from './wallet.js';
18
+ import { netLine, resolveNet } from './lib/net-choice.js';
19
+ const SUI_ADDR = /^0x[0-9a-f]{64}$/i;
20
+ /** "1.000000" USDC → 1000000 base units (6 decimals); anything else → null. */
21
+ export function usdcUnits(v) {
22
+ if (typeof v !== 'string' || !/^\d{1,9}(\.\d{1,6})?$/.test(v.trim()))
23
+ return null;
24
+ const [w, f = ''] = v.trim().split('.');
25
+ const n = BigInt(w) * 1000000n + BigInt(f.padEnd(6, '0'));
26
+ return n > 0n ? n : null;
27
+ }
28
+ async function crypto(base, body) {
29
+ const res = await fetch(`${base.replace(/\/$/, '')}/api/storefront/crypto`, { method: 'POST', headers: { ...authHeaders(), 'content-type': 'application/json' }, body: JSON.stringify(body) });
30
+ return { status: res.status, json: (await res.json().catch(() => ({}))) };
31
+ }
32
+ export function shopBuyCmd() {
33
+ return new Command('buy')
34
+ .description("Buy a store's product with USDC on Sui from the vault in --dir: quote, escrow address for this sale, pay the exact USDC, poll until pay sees it. Dry (quote only) unless --live")
35
+ .argument('<workspace>', 'The store, e.g. one')
36
+ .argument('<ppid>', 'The price id, e.g. price_58bgh7w7y97ickj6')
37
+ .option('--dir <vault>', 'The sealed vault that pays', '.')
38
+ .option('--net <network>', 'mainnet | testnet (default: ONE_NETWORK, then `one network`, then the deploy)')
39
+ .option('--api <url>', 'one.ie base URL')
40
+ .option('--rpc <url>', 'Sui gRPC base URL override')
41
+ .option('--wait <seconds>', 'How long to poll status after paying', '120')
42
+ .option('--live', 'Mint the escrow address, pay it and poll. Without it: the quote only')
43
+ .action(async (workspace, ppid, o, sub) => {
44
+ const t0 = Date.now();
45
+ const nc = await resolveNet(o.net, o.api);
46
+ if (!nc.ok)
47
+ return out(sub, nc);
48
+ const net = nc.net;
49
+ const base = resolveBase({ api: o.api }, 'https://one.ie');
50
+ const q = await crypto(base, { action: 'quote', workspace, ppid, chains: ['SUI'] });
51
+ const sui = (q.json.options ?? []).find((x) => x.chain === 'SUI');
52
+ if (q.status !== 200 || !sui)
53
+ return out(sub, { ok: false, error: String(q.json.error ?? 'no_sui_option'), status: q.status });
54
+ if (sui.usdcEligible !== true)
55
+ return out(sub, { ok: false, error: 'usdc_not_offered', detail: 'this store does not take USDC on Sui for this price' });
56
+ const quote = { workspace, ppid, usd: q.json.amountUsd, escrow: q.json.escrow, custody: q.json.custody, net, networkFrom: nc.from, says: netLine(nc) };
57
+ if (!o.live)
58
+ return out(sub, { ok: true, dry: true, quote, next: 'add --live to mint this sale\'s deposit address and pay it in USDC from --dir' });
59
+ const opened = await unlock(o.dir);
60
+ if ('error' in opened)
61
+ return out(sub, { ok: false, error: 'vault_locked', detail: opened.error });
62
+ const key = opened.keys.find((k) => k.chain === 'sui');
63
+ if (!key)
64
+ return out(sub, { ok: false, error: 'no_sui_key_in_vault' });
65
+ const e = await crypto(base, { action: 'escrow', workspace, ppid, chain: 'SUI' });
66
+ const paymentId = String(e.json.paymentId ?? '');
67
+ const escrowAddress = String(e.json.escrowAddress ?? '');
68
+ const units = usdcUnits(e.json.usdc);
69
+ if (e.status !== 200 || !paymentId || !SUI_ADDR.test(escrowAddress))
70
+ return out(sub, { ok: false, error: String(e.json.error ?? 'escrow_failed'), status: e.status });
71
+ if (units === null)
72
+ return out(sub, { ok: false, error: 'usdc_not_offered_on_this_escrow', paymentId, detail: 'pay did not echo a USDC amount for this deposit address — nothing was sent' });
73
+ if (e.json.network === 'testnet' && net === 'mainnet')
74
+ return out(sub, { ok: false, error: 'network_mismatch', paymentId });
75
+ let digest;
76
+ let finalMs;
77
+ try {
78
+ const sent = await suiSendGrpc({ asset: 'USDC', coinType: SUI[net].usdc, from: key.address, to: escrowAddress, amountUnits: units, privateKeyHex: key.privateKeyHex, rpc: o.rpc, net });
79
+ digest = sent.digest;
80
+ finalMs = sent.finalMs;
81
+ }
82
+ catch (err) {
83
+ const se = err;
84
+ return out(sub, { ok: false, error: se.code ?? 'send_failed', detail: se.message, ...(se.digest ? { digest: se.digest } : {}), paymentId, escrowAddress });
85
+ }
86
+ const deadline = Date.now() + Math.max(10, Number(o.wait) || 120) * 1000;
87
+ let s = {};
88
+ while (Date.now() < deadline) {
89
+ s = (await crypto(base, { action: 'status', workspace, paymentId, chain: 'SUI', amount: String(e.json.amount ?? '') })).json;
90
+ if (s.status === 'completed' || s.status === 'forwarded' || s.forwardTxHash)
91
+ break;
92
+ await new Promise((r) => setTimeout(r, 4000));
93
+ }
94
+ const seen = s.status === 'completed' || s.status === 'forwarded' || Boolean(s.forwardTxHash);
95
+ return out(sub, {
96
+ ok: seen, ...(seen ? {} : { error: 'not_seen_yet', next: 'poll again: the money is at the deposit address' }),
97
+ paid: `${e.json.usdc} USDC`, paymentId, escrowAddress, digest, explorer: `${SUI[net].explorer}/tx/${digest}`, payer: key.address,
98
+ status: s.status ?? null, forwardTxHash: s.forwardTxHash ?? null, finalMs, wallMs: Date.now() - t0,
99
+ });
100
+ });
101
+ }
package/dist/src/shop.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Command } from 'commander';
2
+ import { shopBuyCmd } from './shop-buy.js';
2
3
  import { existsSync, readFileSync } from 'node:fs';
3
4
  import { authHeaders, jsonMode, out, resolveBase } from './lib/client.js';
4
5
  import { askPath } from './lib/api-path.js';
@@ -106,5 +107,6 @@ export function shopCmd() {
106
107
  const ascii = !process.stdout.isTTY || 'NO_COLOR' in process.env;
107
108
  process.stdout.write(drawSale(kinds, { ...draw, ascii }));
108
109
  });
110
+ cmd.addCommand(shopBuyCmd());
109
111
  return cmd;
110
112
  }
@@ -8,8 +8,20 @@
8
8
  * replace the machine key someone already logs in with.
9
9
  */
10
10
  import { Command } from 'commander';
11
+ import { type JourneyDeps } from './lib/journey.js';
11
12
  /** The flags bare `npx oneie --email …` hands to `start` — the journey's own, nothing else. */
12
13
  export declare const START_FLAGS: Set<string>;
13
14
  /** Bare `oneie`, or `oneie` led by a journey flag, runs `start`. Everything else is untouched. */
14
15
  export declare function startArgv(argv: string[]): string[];
16
+ /** A progress line for a person (stderr, so `--json` stdout stays one object). Silent in JSON mode. */
17
+ export type Say = (line: string) => void;
18
+ /**
19
+ * The journey's wiring. Exported, with `f` and `limits` injectable, so a test can
20
+ * drive these exact round trips against a server that never answers
21
+ * (`tests/journey-no-answer.test.ts`).
22
+ */
23
+ export declare function journeyDeps(dir: string, api: string, say: Say, f?: typeof fetch, limits?: {
24
+ askMs: number;
25
+ provisionMs: number;
26
+ }): JourneyDeps;
15
27
  export declare function startCmd(): Command;
package/dist/src/start.js CHANGED
@@ -21,6 +21,7 @@ import { promptSecret, registerSealedWallet } from './wallet.js';
21
21
  import { parseProductSpec, runJourney, } from './lib/journey.js';
22
22
  import { asciiOf, haveNow, journeyIntro, journeyResume, journeyWords } from './lib/journey-words.js';
23
23
  import { learnNetwork } from './lib/network.js';
24
+ import { ASK_TIMEOUT_MS, NoAnswerError, PROVISION_TIMEOUT_MS, fetchJson } from './lib/timed-fetch.js';
24
25
  const DEFAULT_API = process.env.ONEIE_BASE_URL ?? 'https://one.ie';
25
26
  /** The flags bare `npx oneie --email …` hands to `start` — the journey's own, nothing else. */
26
27
  export const START_FLAGS = new Set(['--name', '--email', '--product', '--currency', '--wait', '--api']);
@@ -76,8 +77,14 @@ async function walletStore(dir) {
76
77
  return { error: 'that passphrase is shorter than 8 characters, so no wallet was made. Run it again with a longer one' };
77
78
  return { kind: 'vault', dir, passphrase };
78
79
  }
79
- function deps(dir, api, say) {
80
+ /**
81
+ * The journey's wiring. Exported, with `f` and `limits` injectable, so a test can
82
+ * drive these exact round trips against a server that never answers
83
+ * (`tests/journey-no-answer.test.ts`).
84
+ */
85
+ export function journeyDeps(dir, api, say, f = fetch, limits = { askMs: ASK_TIMEOUT_MS, provisionMs: PROVISION_TIMEOUT_MS }) {
80
86
  return {
87
+ say,
81
88
  load: () => loadState(dir),
82
89
  save: (s) => saveState(dir, s),
83
90
  key: () => {
@@ -103,13 +110,19 @@ function deps(dir, api, say) {
103
110
  },
104
111
  provision: async (body) => {
105
112
  say('Making your agent\'s key and its own group on one.ie…');
106
- const res = await fetch(`${api}/api/provision/agent`, {
107
- method: 'POST',
108
- headers: { 'Content-Type': 'application/json' },
109
- body: JSON.stringify(body),
110
- });
111
- const json = (await res.json().catch(() => ({})));
112
- return { ok: res.ok, status: res.status, json };
113
+ // A write, so a silent server is reported and never retried: a second call would make a second group.
114
+ try {
115
+ return await fetchJson(f, `${api}/api/provision/agent`, {
116
+ method: 'POST',
117
+ headers: { 'Content-Type': 'application/json' },
118
+ body: JSON.stringify(body),
119
+ }, limits.provisionMs, `${api}/api/provision/agent`);
120
+ }
121
+ catch (e) {
122
+ if (!(e instanceof NoAnswerError))
123
+ throw e;
124
+ return { ok: false, status: 0, json: { error: `${e.message}. Nothing was saved in this folder, so run \`npx oneie\` again` } };
125
+ }
113
126
  },
114
127
  saveKey: (p) => writeKeyFolder({ dir, api, ...p }),
115
128
  wallet: async ({ key, workspace }) => {
@@ -132,12 +145,21 @@ function deps(dir, api, say) {
132
145
  return provisionLocalWallet({ api, key, workspace, store });
133
146
  },
134
147
  ask: async (key, receiver, data) => {
135
- const res = await fetch(askPath(api, receiver), {
136
- method: 'POST',
137
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
138
- body: JSON.stringify({ data }),
139
- });
140
- const body = (await res.json().catch(() => ({})));
148
+ let res;
149
+ try {
150
+ res = await fetchJson(f, askPath(api, receiver), {
151
+ method: 'POST',
152
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
153
+ body: JSON.stringify({ data }),
154
+ }, limits.askMs, receiver);
155
+ }
156
+ catch (e) {
157
+ // A silent server is its own outcome, so the journey can name it instead of hanging.
158
+ if (e instanceof NoAnswerError)
159
+ return { outcome: 'no_answer', error: e.message };
160
+ throw e;
161
+ }
162
+ const body = res.json;
141
163
  // A transport-level refusal is its own outcome — never read as an empty success.
142
164
  if (!res.ok)
143
165
  return { outcome: `http_${res.status}`, error: String(body.error ?? body.detail ?? '') };
@@ -183,7 +205,7 @@ export function startCmd() {
183
205
  // The network shapes the words and `have.network`; asked now, in parallel with the walk, never blocking it.
184
206
  const netP = learnNetwork(api);
185
207
  const say = json ? () => { } : (line) => process.stderr.write(` ${fmt(line)}\n`);
186
- const report = await runJourney(deps(process.cwd(), api, say), {
208
+ const report = await runJourney(journeyDeps(process.cwd(), api, say), {
187
209
  api,
188
210
  name: opts.name,
189
211
  ...(opts.email ? { email: opts.email } : {}),
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function threadCmd(): Command;
@@ -0,0 +1,52 @@
1
+ import { Command } from 'commander';
2
+ import { authHeaders, jsonMode, out, resolveBase } from './lib/client.js';
3
+ import { askPath } from './lib/api-path.js';
4
+ // Room text is written by other people (and strangers, through the sealed-note door): strip
5
+ // C0/C1 controls and ESC before it reaches a terminal, so a message cannot rewrite the screen.
6
+ // Newline and tab survive in message bodies; every other field is one line.
7
+ const clean = (v, multiline = false) => String(v ?? '').replace(multiline ? /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g : /[\u0000-\u001f\u007f-\u009f]/g, '');
8
+ export function threadCmd() {
9
+ const cmd = new Command('thread').description('Read a thread (a room, an inbox conversation) a page at a time — members of its group only');
10
+ cmd
11
+ .command('read <threadId>')
12
+ .description('Read one page of a thread, newest messages last (thread:read). Says when the page is short')
13
+ .option('--limit <n>', 'Messages per page (default 50, max 200)')
14
+ .option('--before <cursor>', 'Older page: the nextCursor of the previous read')
15
+ .option('--after <cursor>', 'Only what arrived after this cursor')
16
+ .option('--api <url>', 'API base URL')
17
+ .option('--json', 'One JSON line')
18
+ .action(async (threadId, opts, sub) => {
19
+ const base = resolveBase(opts, 'https://api.one.ie');
20
+ const data = { threadId };
21
+ if (opts.limit)
22
+ data.limit = Number(opts.limit);
23
+ if (opts.before)
24
+ data.before = opts.before;
25
+ if (opts.after)
26
+ data.after = opts.after;
27
+ const res = await fetch(askPath(base, 'thread:read'), { method: 'POST', headers: authHeaders(), body: JSON.stringify({ data }) });
28
+ const body = (await res.json().catch(() => null));
29
+ const ans = body && 'outcome' in body
30
+ ? (body.result ?? { ok: false, error: body.reason ?? body.outcome ?? 'no_answer' })
31
+ : (body ?? { ok: false, error: `http_${res.status}` });
32
+ if (!res.ok && ans.ok !== false)
33
+ ans.ok = false;
34
+ if (jsonMode(sub) || ans.ok === false) {
35
+ out(sub, ans);
36
+ return;
37
+ }
38
+ const msgs = ans.messages ?? [];
39
+ const head = `${clean(ans.thread?.name ?? ans.thread?.id ?? threadId)} · ${clean(ans.thread?.slug)} · ${msgs.length} message${msgs.length === 1 ? '' : 's'}`;
40
+ process.stdout.write(head + '\n');
41
+ if (ans.older && ans.nextCursor)
42
+ process.stdout.write(` … earlier messages exist — one thread read ${threadId} --before ${clean(ans.nextCursor)}\n`);
43
+ for (const m of msgs) {
44
+ const who = clean(m.sender ?? m.role);
45
+ const when = Number.isFinite(m.at) ? new Date(m.at > 1e12 ? m.at : m.at * 1000).toISOString() : '?';
46
+ process.stdout.write(`[${when}] ${who}: ${clean(m.text, true)}\n`);
47
+ }
48
+ if (ans.newer && ans.newerCursor)
49
+ process.stdout.write(` … more arrived — one thread read ${threadId} --after ${clean(ans.newerCursor)}\n`);
50
+ });
51
+ return cmd;
52
+ }