@zerc20/cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +20 -2
- package/dist/account.js +177 -0
- package/dist/account.js.map +1 -0
- package/dist/commands.js +454 -0
- package/dist/commands.js.map +1 -0
- package/dist/errors.js +27 -0
- package/dist/errors.js.map +1 -0
- package/dist/files.js +79 -0
- package/dist/files.js.map +1 -0
- package/dist/format.js +73 -0
- package/dist/format.js.map +1 -0
- package/dist/main.js +176 -0
- package/dist/main.js.map +1 -0
- package/dist/mergeKeys.js +19 -0
- package/dist/mergeKeys.js.map +1 -0
- package/dist/prover.js +71 -0
- package/dist/prover.js.map +1 -0
- package/dist/skill.js +34 -0
- package/dist/skill.js.map +1 -0
- package/dist/update.js +89 -0
- package/dist/update.js.map +1 -0
- package/networks/mainnet.json +153 -0
- package/networks/testnet.json +158 -0
- package/package.json +51 -4
- package/skill/SKILL.md +170 -0
- package/src/account.ts +181 -0
- package/src/commands.ts +520 -0
- package/src/errors.ts +26 -0
- package/src/files.ts +86 -0
- package/src/format.ts +87 -0
- package/src/main.ts +170 -0
- package/src/mergeKeys.ts +20 -0
- package/src/prover.ts +71 -0
- package/src/skill.ts +44 -0
- package/src/update.ts +103 -0
package/src/format.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// What commands take and print: amounts in a token's own units, chains by name, tables and CSV.
|
|
2
|
+
|
|
3
|
+
import { type ChainConfig, NATIVE, type Network, type Token } from '@zerc20/wallet-sdk';
|
|
4
|
+
import { formatUnits } from 'viem';
|
|
5
|
+
import * as viemChains from 'viem/chains';
|
|
6
|
+
import { Usage } from './errors.js';
|
|
7
|
+
|
|
8
|
+
/** An amount typed in a token's units, in its base units. Exact: one with more decimals than the token has is refused
|
|
9
|
+
* rather than rounded, as what is paid is what was typed. */
|
|
10
|
+
export function parseAmount(text: string, decimals: number): bigint {
|
|
11
|
+
const m = /^(\d+)(?:\.(\d+))?$/.exec(text);
|
|
12
|
+
if (!m) throw new Usage(`${text} is not an amount`);
|
|
13
|
+
const fraction = m[2] ?? '';
|
|
14
|
+
if (fraction.length > decimals) throw new Usage(`${text} has more than ${decimals} decimals`);
|
|
15
|
+
return BigInt(m[1] + fraction.padEnd(decimals, '0'));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** `value` in the token's units, as `parseAmount` takes it back. */
|
|
19
|
+
export const amount = (value: bigint, token: Pick<Token, 'decimals'>) => formatUnits(value, token.decimals);
|
|
20
|
+
|
|
21
|
+
/** Each chain's name, the first where several share an id, as the local chain's tools do. */
|
|
22
|
+
const names = new Map<bigint, string>();
|
|
23
|
+
for (const c of Object.values(viemChains)) {
|
|
24
|
+
if (typeof c === 'object' && 'id' in c && 'name' in c && !names.has(BigInt(c.id))) names.set(BigInt(c.id), c.name);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const chainName = (chainId: bigint) => names.get(chainId) ?? `chain ${chainId}`;
|
|
28
|
+
|
|
29
|
+
/** The chain of `network` named `text`: its id, its name, or where that names one alone, how its name starts
|
|
30
|
+
* (`base` for Base Sepolia). */
|
|
31
|
+
export function chainNamed(network: Network, text: string): ChainConfig {
|
|
32
|
+
const t = text.toLowerCase();
|
|
33
|
+
const name = (c: ChainConfig) => chainName(c.chainId).toLowerCase();
|
|
34
|
+
const exact = network.chains.filter((c) => String(c.chainId) === t || name(c) === t);
|
|
35
|
+
const found = exact.length ? exact : network.chains.filter((c) => name(c).startsWith(t));
|
|
36
|
+
if (found.length !== 1)
|
|
37
|
+
throw new Usage(`--chain ${text}: one of ${network.chains.map((c) => chainName(c.chainId)).join(', ')}`);
|
|
38
|
+
return found[0];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The symbol of the asset under `token`: the chain's native currency's, or the zERC20's own without its z. */
|
|
42
|
+
export function underlyingSymbol(network: Network, token: Token): string {
|
|
43
|
+
if (token.underlying.toLowerCase() !== NATIVE.toLowerCase()) return token.symbol.replace(/^z/, '');
|
|
44
|
+
return network.chains.find((c) => c.chainId === token.chainId)?.nativeCurrency?.symbol ?? 'ETH';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The tokens `symbol` names, on `chain` if given: a zERC20 by its own symbol or by that of the asset under it, as
|
|
48
|
+
* both name the one private balance. */
|
|
49
|
+
export function tokensNamed(network: Network, tokens: Token[], symbol: string, chain?: ChainConfig): Token[] {
|
|
50
|
+
const s = symbol.toLowerCase();
|
|
51
|
+
return tokens.filter(
|
|
52
|
+
(t) =>
|
|
53
|
+
(!chain || t.chainId === chain.chainId) &&
|
|
54
|
+
(t.symbol.toLowerCase() === s || underlyingSymbol(network, t).toLowerCase() === s),
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Rows under `head` in columns as wide as their widest cell, those named in `right` aligned to the right. */
|
|
59
|
+
export function table(head: string[], rows: string[][], right: number[] = []): string {
|
|
60
|
+
const all = [head, ...rows];
|
|
61
|
+
const width = head.map((_, i) => Math.max(...all.map((r) => r[i].length)));
|
|
62
|
+
return all
|
|
63
|
+
.map((r) =>
|
|
64
|
+
r
|
|
65
|
+
.map((cell, i) => (right.includes(i) ? cell.padStart(width[i]) : cell.padEnd(width[i])))
|
|
66
|
+
.join(' ')
|
|
67
|
+
.trimEnd(),
|
|
68
|
+
)
|
|
69
|
+
.join('\n');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export const csv = (rows: string[][]) =>
|
|
73
|
+
rows
|
|
74
|
+
.map((r) => r.map((cell) => (/[",\n]/.test(cell) ? `"${cell.replaceAll('"', '""')}"` : cell)).join(','))
|
|
75
|
+
.join('\n');
|
|
76
|
+
|
|
77
|
+
/** A long id or address with its middle cut, for a table a person reads. */
|
|
78
|
+
export const short = (text: string) => (text.length > 24 ? `${text.slice(0, 14)}…${text.slice(-6)}` : text);
|
|
79
|
+
|
|
80
|
+
/** A time to the minute, in UTC. */
|
|
81
|
+
export const minute = (at: Date | null) => (at ? at.toISOString().slice(0, 16).replace('T', ' ') : '');
|
|
82
|
+
|
|
83
|
+
/** How long until `at`, roughly. */
|
|
84
|
+
export function until(at: Date, now = Date.now()): string {
|
|
85
|
+
const mins = Math.max(1, Math.round((at.getTime() - now) / 60_000));
|
|
86
|
+
return mins < 90 ? `~${mins} min` : `~${Math.round(mins / 60)} h`;
|
|
87
|
+
}
|
package/src/main.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// zerc20: a zERC20 account from the terminal.
|
|
3
|
+
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import { WalletError } from '@zerc20/wallet-sdk';
|
|
7
|
+
import { Interrupted } from './account.js';
|
|
8
|
+
import * as commands from './commands.js';
|
|
9
|
+
import { Usage, told } from './errors.js';
|
|
10
|
+
import { until } from './format.js';
|
|
11
|
+
import { proverStart } from './prover.js';
|
|
12
|
+
import { installSkill, skillText } from './skill.js';
|
|
13
|
+
import { notices, update } from './update.js';
|
|
14
|
+
|
|
15
|
+
const HELP = `zerc20: a zERC20 account from the terminal
|
|
16
|
+
|
|
17
|
+
Usage: zerc20 <command> [options]
|
|
18
|
+
|
|
19
|
+
Look
|
|
20
|
+
balance what the account holds, by token and chain
|
|
21
|
+
history [--csv] [--tx] what it received, paid, deposited and withdrew
|
|
22
|
+
coins its unspent notes and deposits, which a merge joins
|
|
23
|
+
|
|
24
|
+
Receive
|
|
25
|
+
receive its zERC20 ID, which any account pays privately
|
|
26
|
+
receive <token> a receive code for one token
|
|
27
|
+
deposit <token> an address that takes the token from anywhere
|
|
28
|
+
|
|
29
|
+
Pay
|
|
30
|
+
send <amount> <token> <to> privately, to a zERC20 ID or a receive code
|
|
31
|
+
withdraw <amount> <token> <0x…> in public, to any address
|
|
32
|
+
merge <token> join the token's coins into one note
|
|
33
|
+
|
|
34
|
+
Account
|
|
35
|
+
new make an account, and print its recovery phrase once
|
|
36
|
+
view-key the key that shows the account and spends nothing
|
|
37
|
+
|
|
38
|
+
Run
|
|
39
|
+
prover start a merge prover on this machine, for --prover local
|
|
40
|
+
|
|
41
|
+
Agents
|
|
42
|
+
install-skill teach the coding agents on this machine to use zerc20
|
|
43
|
+
skill print that skill
|
|
44
|
+
|
|
45
|
+
Update
|
|
46
|
+
update install the newest release with npm, and its skill where one is installed
|
|
47
|
+
|
|
48
|
+
The key
|
|
49
|
+
A view key (zerc20view1…) to look, or the 24-word recovery phrase to pay. It is read
|
|
50
|
+
from --key-file, else ZERC20_KEY, else standard input, else asked for unseen. It is
|
|
51
|
+
never an argument, which a shell keeps, and nothing of it is written to disk.
|
|
52
|
+
|
|
53
|
+
Options
|
|
54
|
+
--network <mainnet|testnet|file> default mainnet, or ZERC20_NETWORK
|
|
55
|
+
--chain <name|id> where a token is on several chains
|
|
56
|
+
--key-file <file>
|
|
57
|
+
--json the answer as JSON
|
|
58
|
+
--yes pay without being asked
|
|
59
|
+
--max-fee <amount> fail on a higher fee
|
|
60
|
+
--wrapped withdraw: pay out the zERC20 token, not the asset under it
|
|
61
|
+
--tx history: look up each transaction (slower)
|
|
62
|
+
--csv history: as CSV
|
|
63
|
+
--prover <local|url> merge: prove on this machine, or ZERC20_PROVER
|
|
64
|
+
--port <port> prover start: default 3006
|
|
65
|
+
--version
|
|
66
|
+
|
|
67
|
+
Amounts are in the token's units (10.5), or max. A token goes by its name or its asset's:
|
|
68
|
+
zUSDC and USDC are the one private balance.
|
|
69
|
+
|
|
70
|
+
Once a day a command asks npm whether a newer release is out, and says so if one is.
|
|
71
|
+
ZERC20_NO_UPDATE_CHECK=1 asks nothing.`;
|
|
72
|
+
|
|
73
|
+
const COMMANDS: Record<string, (flags: commands.Flags, args: string[]) => Promise<void>> = {
|
|
74
|
+
balance: commands.balance,
|
|
75
|
+
history: commands.history,
|
|
76
|
+
coins: commands.coins,
|
|
77
|
+
receive: commands.receive,
|
|
78
|
+
deposit: commands.deposit,
|
|
79
|
+
send: commands.send,
|
|
80
|
+
withdraw: commands.withdraw,
|
|
81
|
+
merge: commands.merge,
|
|
82
|
+
new: commands.create,
|
|
83
|
+
'view-key': commands.viewKey,
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/** What to do about an error a wallet names by code, where its message does not say. */
|
|
87
|
+
function hint(e: WalletError): string | null {
|
|
88
|
+
switch (e.code) {
|
|
89
|
+
case 'needs-consolidation':
|
|
90
|
+
return 'Its coins are too scattered for one payment: `zerc20 merge <token>` first.';
|
|
91
|
+
case 'funds-settling':
|
|
92
|
+
return e.waitsOn?.readyBy ? `Enough of it should be spendable in ${until(e.waitsOn.readyBy)}.` : null;
|
|
93
|
+
case 'recipient-not-registered':
|
|
94
|
+
return 'A public address is paid with `zerc20 withdraw`.';
|
|
95
|
+
case 'attester-unverified':
|
|
96
|
+
return 'Where the network has moved on since this release: zerc20 update';
|
|
97
|
+
default:
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const { version } = createRequire(import.meta.url)('../package.json') as { version: string };
|
|
103
|
+
|
|
104
|
+
/** What an account's command ends with, once its own answer is out: asked for while the command runs. */
|
|
105
|
+
let ending: Promise<string[]> | undefined;
|
|
106
|
+
|
|
107
|
+
async function main(): Promise<void> {
|
|
108
|
+
const { values, positionals } = parseArgs({
|
|
109
|
+
allowPositionals: true,
|
|
110
|
+
options: {
|
|
111
|
+
network: { type: 'string', default: process.env.ZERC20_NETWORK ?? 'mainnet' },
|
|
112
|
+
chain: { type: 'string' },
|
|
113
|
+
'key-file': { type: 'string' },
|
|
114
|
+
'max-fee': { type: 'string' },
|
|
115
|
+
prover: { type: 'string', default: process.env.ZERC20_PROVER },
|
|
116
|
+
port: { type: 'string', default: '3006' },
|
|
117
|
+
json: { type: 'boolean', default: false },
|
|
118
|
+
yes: { type: 'boolean', default: false },
|
|
119
|
+
wrapped: { type: 'boolean', default: false },
|
|
120
|
+
csv: { type: 'boolean', default: false },
|
|
121
|
+
tx: { type: 'boolean', default: false },
|
|
122
|
+
help: { type: 'boolean', short: 'h', default: false },
|
|
123
|
+
version: { type: 'boolean', default: false },
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
const [name, ...args] = positionals;
|
|
127
|
+
if (values.version) return void console.log(version);
|
|
128
|
+
if (values.help || !name) return void console.log(HELP);
|
|
129
|
+
if (name === 'prover') {
|
|
130
|
+
if (args[0] !== 'start') throw new Usage('zerc20 prover start [--port <port>]');
|
|
131
|
+
return proverStart(values.port, commands.whenInterrupted);
|
|
132
|
+
}
|
|
133
|
+
if (name === 'skill') return void process.stdout.write(skillText());
|
|
134
|
+
if (name === 'install-skill') {
|
|
135
|
+
const files = installSkill();
|
|
136
|
+
console.error('An agent that is running reads it once started again.');
|
|
137
|
+
return void console.log(values.json ? JSON.stringify(files, null, 2) : files.join('\n'));
|
|
138
|
+
}
|
|
139
|
+
if (name === 'update') return update();
|
|
140
|
+
const command = COMMANDS[name];
|
|
141
|
+
if (!command) throw new Usage(`no command ${name}`);
|
|
142
|
+
ending = notices(version);
|
|
143
|
+
await command(values, args);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) process.on(signal, commands.onSignal);
|
|
147
|
+
|
|
148
|
+
try {
|
|
149
|
+
await main();
|
|
150
|
+
} catch (e) {
|
|
151
|
+
// parseArgs names its errors by a string code; another library's code may be an object that cannot be read as one
|
|
152
|
+
const code = (e as { code?: unknown } | null)?.code;
|
|
153
|
+
if (e instanceof Interrupted) process.exitCode = 130;
|
|
154
|
+
else if (e instanceof Usage || (typeof code === 'string' && code.startsWith('ERR_PARSE_ARGS'))) {
|
|
155
|
+
// parseArgs goes on to explain positionals that start with a dash
|
|
156
|
+
console.error(`${(e as Error).message.split('. ')[0]}\nzerc20 --help shows every command.`);
|
|
157
|
+
process.exitCode = 2;
|
|
158
|
+
} else {
|
|
159
|
+
// the message, and what caused it where a server out of reach did; whole where ZERC20_DEBUG asks, for a defect
|
|
160
|
+
if (process.env.ZERC20_DEBUG || !(e instanceof Error)) console.error(e);
|
|
161
|
+
else console.error(told(e));
|
|
162
|
+
const more = e instanceof WalletError ? hint(e) : null;
|
|
163
|
+
if (more) console.error(more);
|
|
164
|
+
process.exitCode = 1;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
for (const line of (await ending) ?? []) console.error(line);
|
|
168
|
+
await commands.close();
|
|
169
|
+
// a prover's worker threads would keep the process
|
|
170
|
+
process.exit();
|
package/src/mergeKeys.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// The merge decider keys a prover on this machine loads: those of the setup the chains' merge verifier is generated
|
|
2
|
+
// from, which every network shares. Pinned here rather than read beside the download, so that the server they come
|
|
3
|
+
// from cannot hand out another key: a proving key made to leak would put the witness in the proof.
|
|
4
|
+
|
|
5
|
+
export const MERGE_KEYS = {
|
|
6
|
+
setup: '20261021T210800Z-98c5f43',
|
|
7
|
+
pk: {
|
|
8
|
+
file: 'merge_decider_pk.bin',
|
|
9
|
+
bytes: 6_465_237_728,
|
|
10
|
+
sha256: 'e5c2f6ba4fc3fc10a9703fb5316f5b674c855e469310a23997912f5ef18ee037',
|
|
11
|
+
},
|
|
12
|
+
vk: {
|
|
13
|
+
file: 'merge_decider_vk.bin',
|
|
14
|
+
bytes: 50_466,
|
|
15
|
+
sha256: '144087672d80dcb11e0f9075f81d9453304328206c68e31d5b0d7b77474b36df',
|
|
16
|
+
},
|
|
17
|
+
} as const;
|
|
18
|
+
|
|
19
|
+
/** Where a key of the setup is served. */
|
|
20
|
+
export const mergeKeyUrl = (file: string) => `https://artifacts.v2.zerc20.io/merge/${MERGE_KEYS.setup}/${file}`;
|
package/src/prover.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// A merge prover on this machine: the node's own binary, with the keys it proves with fetched and checked first. A
|
|
2
|
+
// wallet here that merges with `--prover local` seals its witness to it rather than to the network's.
|
|
3
|
+
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { totalmem } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { Failure, Usage } from './errors.js';
|
|
9
|
+
import { download, home, showProgress } from './files.js';
|
|
10
|
+
import { MERGE_KEYS, mergeKeyUrl } from './mergeKeys.js';
|
|
11
|
+
|
|
12
|
+
/** The machines a release brings a prover for, each as a package of its own that npm installs where it fits. */
|
|
13
|
+
const SHIPPED = ['darwin-arm64', 'linux-x64', 'linux-arm64'];
|
|
14
|
+
|
|
15
|
+
/** The prover's binary: one named, else the one this install brought for this machine. */
|
|
16
|
+
function binary(): string {
|
|
17
|
+
if (process.env.ZERC20_MERGE_PROVER_BIN) return process.env.ZERC20_MERGE_PROVER_BIN;
|
|
18
|
+
const target = `${process.platform}-${process.arch}`;
|
|
19
|
+
try {
|
|
20
|
+
return createRequire(import.meta.url).resolve(`@zerc20/merge-prover-${target}/zerc20-merge-prover`);
|
|
21
|
+
} catch {
|
|
22
|
+
const own = 'name a `zerc20-merge-prover` built from the source in ZERC20_MERGE_PROVER_BIN';
|
|
23
|
+
throw new Failure(
|
|
24
|
+
SHIPPED.includes(target)
|
|
25
|
+
? `the merge prover for ${target} is not in this install, as after --omit=optional or in a checkout of the ` +
|
|
26
|
+
`source: install @zerc20/cli again, or ${own}`
|
|
27
|
+
: `no merge prover ships for ${target}, only for ${SHIPPED.join(', ')}: ${own}`,
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Runs the prover on `port` of this machine until it stops or is stopped. `interrupted` is told how to stop it. */
|
|
33
|
+
export async function proverStart(port: string, interrupted: (stop: () => void) => void): Promise<void> {
|
|
34
|
+
if (!/^\d+$/.test(port)) throw new Usage(`--port ${port} is not a port`);
|
|
35
|
+
const bin = binary();
|
|
36
|
+
const dir = join(home(), 'merge', MERGE_KEYS.setup);
|
|
37
|
+
for (const key of [MERGE_KEYS.vk, MERGE_KEYS.pk]) {
|
|
38
|
+
await download(mergeKeyUrl(key.file), join(dir, key.file), key.sha256, showProgress(`Fetching ${key.file}`));
|
|
39
|
+
}
|
|
40
|
+
const gb = totalmem() / 2 ** 30;
|
|
41
|
+
if (gb < 16) console.error(`This machine has ${gb.toFixed(0)} GB of memory: proving takes about 16 GB.`);
|
|
42
|
+
// only what the prover reads: nothing of this shell's can switch it to a development mode
|
|
43
|
+
const env = {
|
|
44
|
+
SELF_HOSTED: '1',
|
|
45
|
+
MERGE_PK_SHA256: MERGE_KEYS.pk.sha256,
|
|
46
|
+
MERGE_VK_SHA256: MERGE_KEYS.vk.sha256,
|
|
47
|
+
ARTIFACTS_DIR: dir,
|
|
48
|
+
LISTEN: `127.0.0.1:${port}`,
|
|
49
|
+
...(process.env.RUST_LOG ? { RUST_LOG: process.env.RUST_LOG } : {}),
|
|
50
|
+
};
|
|
51
|
+
const child = spawn(bin, [], { env, stdio: 'inherit' });
|
|
52
|
+
interrupted(() => child.kill());
|
|
53
|
+
const ended = new Promise<number>((resolve, reject) => {
|
|
54
|
+
child.on('error', reject);
|
|
55
|
+
child.on('exit', (code) => resolve(code ?? 1));
|
|
56
|
+
});
|
|
57
|
+
const url = `http://127.0.0.1:${port}`;
|
|
58
|
+
const ready = async () => {
|
|
59
|
+
for (;;) {
|
|
60
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
61
|
+
const status = await fetch(`${url}/status`)
|
|
62
|
+
.then((r) => r.json() as Promise<{ mergeKey?: boolean }>)
|
|
63
|
+
.catch(() => null);
|
|
64
|
+
if (status?.mergeKey) break;
|
|
65
|
+
}
|
|
66
|
+
const flag = port === '3006' ? 'local' : url;
|
|
67
|
+
console.error(`Ready. Merge through it with: zerc20 merge <token> --prover ${flag}`);
|
|
68
|
+
return ended;
|
|
69
|
+
};
|
|
70
|
+
process.exitCode = await Promise.race([ended, ready()]);
|
|
71
|
+
}
|
package/src/skill.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// The skill that teaches a coding agent this program. It ships with the program, so the two are of one release.
|
|
2
|
+
|
|
3
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { Failure } from './errors.js';
|
|
8
|
+
|
|
9
|
+
const SKILL = fileURLToPath(new URL('../skill/SKILL.md', import.meta.url));
|
|
10
|
+
|
|
11
|
+
export const skillText = () => readFileSync(SKILL, 'utf8');
|
|
12
|
+
|
|
13
|
+
/** Where agents read a user's skills, each with the directories that tell an agent reading it is on this machine.
|
|
14
|
+
* Claude Code reads its own; Codex, Cursor, Gemini CLI and opencode all read the shared one. */
|
|
15
|
+
const PLACES = [
|
|
16
|
+
{ skills: '.claude/skills', agents: ['.claude'] },
|
|
17
|
+
{ skills: '.agents/skills', agents: ['.agents', '.codex', '.cursor', '.gemini', '.config/opencode'] },
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
/** Where a copy of the skill goes in each place. */
|
|
21
|
+
const copyIn = (home: string, place: (typeof PLACES)[number]) => join(home, place.skills, 'zerc20-cli', 'SKILL.md');
|
|
22
|
+
|
|
23
|
+
/** The copies of the skill on this machine. */
|
|
24
|
+
export const installedSkills = (home = homedir()) => PLACES.map((p) => copyIn(home, p)).filter((f) => existsSync(f));
|
|
25
|
+
|
|
26
|
+
/** Whether a copy here is another release's: what it tells an agent may not hold of this one. */
|
|
27
|
+
export const staleSkill = (home = homedir()) =>
|
|
28
|
+
installedSkills(home).some((f) => readFileSync(f, 'utf8') !== skillText());
|
|
29
|
+
|
|
30
|
+
/** Copies the skill to where the agents on this machine read theirs, over an older copy, and returns the files it
|
|
31
|
+
* wrote. Nothing is written for an agent that is not here. */
|
|
32
|
+
export function installSkill(home = homedir()): string[] {
|
|
33
|
+
const written = PLACES.filter((p) => p.agents.some((a) => existsSync(join(home, a)))).map((p) => {
|
|
34
|
+
const file = copyIn(home, p);
|
|
35
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
36
|
+
copyFileSync(SKILL, file);
|
|
37
|
+
return file;
|
|
38
|
+
});
|
|
39
|
+
if (written.length === 0)
|
|
40
|
+
throw new Failure(
|
|
41
|
+
'no coding agent is on this machine: `zerc20 skill` prints the skill, for where yours reads its own',
|
|
42
|
+
);
|
|
43
|
+
return written;
|
|
44
|
+
}
|
package/src/update.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Whether this release is the newest, asked of npm once a day, and the command that brings the newest. What npm
|
|
2
|
+
// answers is only ever shown: nothing a command does or trusts comes from it.
|
|
3
|
+
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { Failure } from './errors.js';
|
|
8
|
+
import { home } from './files.js';
|
|
9
|
+
import { installedSkills, staleSkill } from './skill.js';
|
|
10
|
+
|
|
11
|
+
const PACKAGE = '@zerc20/cli';
|
|
12
|
+
const DAY = 24 * 3600 * 1000;
|
|
13
|
+
|
|
14
|
+
/** What npm last said of the release `version`: the newest one, and why this one is withdrawn, if it is. */
|
|
15
|
+
interface Seen {
|
|
16
|
+
version: string;
|
|
17
|
+
at: number;
|
|
18
|
+
latest: string;
|
|
19
|
+
withdrawn: string | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** What a user of `version` is told of `seen`: that their release is withdrawn, before that a newer one is out. */
|
|
23
|
+
export function notice(version: string, seen: Pick<Seen, 'latest' | 'withdrawn'>): string | null {
|
|
24
|
+
if (seen.withdrawn !== null)
|
|
25
|
+
return `This release of zerc20 (${version}) is withdrawn: ${seen.withdrawn}\nInstall the newest: zerc20 update`;
|
|
26
|
+
const newer = seen.latest.localeCompare(version, undefined, { numeric: true }) > 0;
|
|
27
|
+
return newer ? `zerc20 ${seen.latest} is out (this is ${version}): zerc20 update` : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What npm's short document of the package says of `version`. Its text reaches a terminal, so only printable
|
|
31
|
+
* characters of it are kept, and a version is one only if it reads as one. */
|
|
32
|
+
async function ask(version: string, registry: string, now: number): Promise<Seen> {
|
|
33
|
+
const r = await fetch(`${registry}/${PACKAGE}`, {
|
|
34
|
+
headers: { accept: 'application/vnd.npm.install-v1+json' },
|
|
35
|
+
signal: AbortSignal.timeout(2000),
|
|
36
|
+
});
|
|
37
|
+
const doc = (await r.json()) as {
|
|
38
|
+
'dist-tags': { latest: string };
|
|
39
|
+
versions: Record<string, { deprecated?: string } | undefined>;
|
|
40
|
+
};
|
|
41
|
+
const latest = doc['dist-tags'].latest;
|
|
42
|
+
if (!/^\d+\.\d+\.\d+$/.test(latest)) throw new Error('not a version');
|
|
43
|
+
const withdrawn = doc.versions[version]?.deprecated;
|
|
44
|
+
return {
|
|
45
|
+
version,
|
|
46
|
+
at: now,
|
|
47
|
+
latest,
|
|
48
|
+
withdrawn: withdrawn
|
|
49
|
+
? String(withdrawn)
|
|
50
|
+
.replace(/[^\x20-\x7e]/g, '')
|
|
51
|
+
.slice(0, 200)
|
|
52
|
+
: null,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** What to say of this release, `version`, after a command: null when it is the newest, when npm was asked within
|
|
57
|
+
* the day and said so, or when the user or a CI run wants nothing asked. A registry out of reach is asked again a
|
|
58
|
+
* day later, not by every command, and never fails the command. */
|
|
59
|
+
export async function updateNotice(
|
|
60
|
+
version: string,
|
|
61
|
+
registry = 'https://registry.npmjs.org',
|
|
62
|
+
now = Date.now(),
|
|
63
|
+
): Promise<string | null> {
|
|
64
|
+
if (process.env.ZERC20_NO_UPDATE_CHECK || process.env.CI) return null;
|
|
65
|
+
try {
|
|
66
|
+
const file = join(home(), 'update.json');
|
|
67
|
+
let seen: Seen | null = null;
|
|
68
|
+
try {
|
|
69
|
+
const kept = JSON.parse(readFileSync(file, 'utf8')) as Seen;
|
|
70
|
+
// what was said of another release says nothing of this one
|
|
71
|
+
if (kept.version === version) seen = kept;
|
|
72
|
+
} catch {
|
|
73
|
+
// never asked yet
|
|
74
|
+
}
|
|
75
|
+
if (!seen || now - seen.at > DAY) {
|
|
76
|
+
const known = seen ?? { version, latest: version, withdrawn: null };
|
|
77
|
+
seen = await ask(version, registry, now).catch(() => ({ ...known, at: now }));
|
|
78
|
+
mkdirSync(home(), { recursive: true });
|
|
79
|
+
writeFileSync(file, JSON.stringify(seen));
|
|
80
|
+
}
|
|
81
|
+
return notice(version, seen);
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The lines a command ends with, on standard error: of a newer release, and of a skill here that is not this
|
|
88
|
+
* release's. */
|
|
89
|
+
export async function notices(version: string): Promise<string[]> {
|
|
90
|
+
const lines = [await updateNotice(version)];
|
|
91
|
+
if (staleSkill()) lines.push('The zerc20 skill coding agents read here is of another release: zerc20 install-skill');
|
|
92
|
+
return lines.filter((line) => line !== null);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Installs the newest release with npm, as this one was, and has it copy its skill over those installed here: this
|
|
96
|
+
* process is still the release before it. */
|
|
97
|
+
export function update(): void {
|
|
98
|
+
const run = (command: string, args: string[]) =>
|
|
99
|
+
spawnSync(command, args, { stdio: 'inherit', shell: process.platform === 'win32' && command === 'npm' });
|
|
100
|
+
const npm = run('npm', ['install', '-g', `${PACKAGE}@latest`]);
|
|
101
|
+
if (npm.status !== 0) throw new Failure(`npm did not install it${npm.error ? `: ${npm.error.message}` : ''}`);
|
|
102
|
+
if (installedSkills().length > 0) run(process.execPath, [process.argv[1], 'install-skill']);
|
|
103
|
+
}
|