@gangfun/cli 0.30.1 → 0.31.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.
package/README.md CHANGED
@@ -321,6 +321,8 @@ timed-out `gang_execute`, check `gang_status` / the wallet history instead of ex
321
321
  | `GANG_NOTES_DIR` | Local note queue, one file per note: salt and send status, kept 24h (default `~/.gang/notes`); `previews/` in it records what each trade preview carried (note, follow) for `gang execute`, also kept 24h |
322
322
  | `GANG_STREAM` | `0`: `gang watch` market mode polls instead of using the server's stream (same as `--poll`) |
323
323
  | `GANG_TELEMETRY` | `0` turns off the anonymous usage counts (0.24.0+; `DO_NOT_TRACK=1` too). See [Telemetry](#telemetry) |
324
+ | `GANG_CLIENT` | The agent host's name in the usage counts (0.31.0+). `gang mcp` fills it in from the MCP client unless you set it |
325
+ | `GANG_TOOL` | Your tool's id, tagged on mainnet trades and creates (0.31.0+). See [Tool id](#tool-id) |
324
326
  | `GANG_UPDATE_CHECK` | `0` turns off the once-a-day check for a newer CLI on npm (cached in `~/.gang/update.json`) |
325
327
  | `GANG_UPDATE_URL` | Where that check asks, default `https://registry.npmjs.org/@gangfun/cli/latest`; set an npm mirror's `…/@gangfun/cli/latest` if npmjs is slow or blocked |
326
328
  | `GANG_PAD` / `GANG_TESTNET_PAD` | The GangLaunchpad new tokens go to (mainnet / testnet), behind V3 and 打新. Defaults: mainnet 3.0 `0x2bEb…AB29` (2.0 `0x7703…E557` and 1.0 `0x15CF…4365` kept for their tokens); testnet 3.0 `0x0508…ceE2` (2.0 `0xb14d…3B3E`, the first 2.0 `0x6381…39be` and 1.0, set 10 `0xFebF…5BB1`, kept for their tokens). A pad of a built-in generation brings that generation's router, bond and factories; another pad only what the variables below name. Old names `GANG_V3_PAD` / `GANG_FAIR_PAD`, `GANG_V3_TESTNET_PAD` / `GANG_FAIR_TESTNET_PAD` still work as aliases |
@@ -340,12 +342,24 @@ From 0.24.0 the CLI counts how it is used, anonymously, so gang.fun can see wher
340
342
  Each command adds one event:
341
343
  - the command name (and subcommand), the names of the flags given (never their values);
342
344
  - whether it succeeded, and if not, a short error code (`NO_AGENT_ID`, `DEV_MODE_OFF`, a Binance risk code, `USAGE`…);
343
- - for `gang preflight`, which checks passed.
345
+ - for `gang preflight`, which checks passed;
346
+ - the agent host's name, when known (0.31.0+): the MCP client's own name (such as `claude-code`), or `GANG_CLIENT`. Only a
347
+ short name made of letters, digits, spaces, `-` and `_` goes out; anything else is sent as `other`.
344
348
 
345
349
  The only id is a random one made on first use (`~/.gang/install-id`). No wallet address, token, amount, note text or
346
350
  error message is sent. Events queue in `~/.gang/events.ndjson` and are posted to `GANG_API` + `/t` at most once a minute by
347
351
  a background process, so a command never waits on it. `GANG_TELEMETRY=0` (or `DO_NOT_TRACK=1`) turns it off.
348
352
 
353
+ ## Tool id
354
+
355
+ Building a tool on the CLI? Set `GANG_TOOL` (0.31.0+) to an id of 2–12 characters (`a-z`, `0-9`, `-`, not starting with
356
+ `-`). Mainnet creates, curve trades, and 打新 and 铸币飞轮 mints and withdraws then carry `"gang" 06 + id` at the end of their calldata,
357
+ in the same way as notes and invites; the contracts ignore it. The result shows `tool: { attached, id }`. A bad id never
358
+ stops a trade: it goes untagged and `tool` says why.
359
+
360
+ The tag is public and anyone can write any id, so it counts usage and proves nothing about who sent a trade. Leave
361
+ `GANG_TOOL` unset and nothing is added.
362
+
349
363
  ## Version
350
364
 
351
- `0.30.1` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
365
+ `0.31.0` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
package/README.zh-CN.md CHANGED
@@ -271,6 +271,8 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
271
271
  | `GANG_NOTES_DIR` | 附言的本地队列,每条一个文件,记着 salt 和提交状态,保留 24 小时(默认 `~/.gang/notes`);其中的 `previews/` 记着每次交易 preview 带了什么(附言、跟单),供 `gang execute` 使用,也保留 24 小时 |
272
272
  | `GANG_STREAM` | 设为 `0` 时 `gang watch` 全市场模式不用服务端推送、改为轮询(同 `--poll`) |
273
273
  | `GANG_TELEMETRY` | 设为 `0` 关闭匿名使用统计(0.24.0+;`DO_NOT_TRACK=1` 同样关闭),见[使用统计](#使用统计) |
274
+ | `GANG_CLIENT` | 使用统计里记录的 Agent 客户端名称(0.31.0+)。`gang mcp` 没设置时取 MCP 客户端自己的名称 |
275
+ | `GANG_TOOL` | 你的工具 ID,附在主网交易和发币的 calldata 上(0.31.0+),见[工具 ID](#工具-id) |
274
276
  | `GANG_UPDATE_CHECK` | 设为 `0` 关闭每天一次的新版本检查(查 npm,缓存在 `~/.gang/update.json`) |
275
277
  | `GANG_UPDATE_URL` | 新版本检查查询的地址,默认 `https://registry.npmjs.org/@gangfun/cli/latest`;npmjs 慢或打不开时,可以换成 npm 镜像的 `…/@gangfun/cli/latest` |
276
278
  | `GANG_PAD` / `GANG_TESTNET_PAD` | 覆盖合并后的内盘合约 GangLaunchpad(主网 / 测试网),V3 和打新共用(默认:主网 3.0 `0x2bEb…AB29`(2.0 `0x7703…E557`、1.0 `0x15CF…4365` 留给各自的币),测试网 3.0 `0x0508…ceE2`;测试网 2.0 `0xb14d…3B3E`、第一版 2.0 `0x6381…39be` 和第 10 套 `0xFebF…5BB1` 留给各自的币)。旧名 `GANG_V3_PAD` / `GANG_FAIR_PAD`、`GANG_V3_TESTNET_PAD` / `GANG_FAIR_TESTNET_PAD` 仍可用(别名) |
@@ -288,12 +290,22 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
288
290
  从 0.24.0 起,CLI 会匿名统计使用情况,让 gang.fun 知道 agent 在第一笔交易之前卡在哪一步。每条命令记一条事件:
289
291
  - 命令名(和子命令)、用到的参数名(不含参数值);
290
292
  - 是否成功;失败时带一个简短的错误码(`NO_AGENT_ID`、`DEV_MODE_OFF`、币安风控码、`USAGE` 等);
291
- - `gang preflight` 另记各项检查是否通过。
293
+ - `gang preflight` 另记各项检查是否通过;
294
+ - Agent 客户端名称(已知时,0.31.0+):MCP 客户端自己的名称(如 `claude-code`),或 `GANG_CLIENT`。只发送由字母、数字、空格、`-` 和 `_`
295
+ 组成的短名称,其他内容一律记为 `other`。
292
296
 
293
297
  唯一的标识是首次使用时随机生成的 ID(`~/.gang/install-id`)。不发送钱包地址、代币、金额、附言内容和报错原文。
294
298
  事件先存在 `~/.gang/events.ndjson`,由后台进程最多每分钟一次发到 `GANG_API` + `/t`,命令本身不会等它。
295
299
  设置 `GANG_TELEMETRY=0`(或 `DO_NOT_TRACK=1`)即可关闭。
296
300
 
301
+ ## 工具 ID
302
+
303
+ 如果你在 CLI 上开发工具,可以把 `GANG_TOOL`(0.31.0+)设为 2–12 个字符的 ID(`a-z`、`0-9`、`-`,不能以 `-` 开头)。之后主网的发币、
304
+ 曲线交易,以及打新和铸币飞轮的 mint 和退出,都会在 calldata 末尾带上 `"gang" 06 + ID`,和 notes、邀请标记的做法相同,合约会忽略它。结果里会显示
305
+ `tool: { attached, id }`。ID 不合法不会影响交易:这笔交易不带标记,`tool` 里会说明原因。
306
+
307
+ 这个标记是公开的,任何人都能写任意 ID,所以只用于统计使用量,不能证明交易是谁发的。不设置 `GANG_TOOL` 就不会附加任何内容。
308
+
297
309
  ## 版本
298
310
 
299
- `0.30.1` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
311
+ `0.31.0` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gangfun/cli",
3
- "version": "0.30.1",
3
+ "version": "0.31.0",
4
4
  "mcpName": "io.github.gangfun/gang",
5
5
  "description": "Gang launchpad CLI for Binance Agentic Wallet agents: create on GangLaunchpad (untaxed or tax tokens), 打新 fair mint, PancakeSwap pool trades, LaunchpadV2 and legacy Soft/U/S trade.",
6
6
  "type": "module",
package/src/fly.js CHANGED
@@ -3,6 +3,7 @@ import { defaultRefPool, dividendOf, VAULT_ABI, fundingStep as fund, parseAmount
3
3
  import { API, get as apiGet } from './discover.js'
4
4
  import { walletFor } from './fair.js'
5
5
  import { MERGED_ERRORS_ABI, MERGED_HINTS, PAD3_GEN, padNets, rpcTransport } from './gangpad.js'
6
+ import { withTool } from './notes.js'
6
7
  import { poolPayBnb, poolTrade } from './pool.js'
7
8
 
8
9
  /**
@@ -544,6 +545,8 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
544
545
  const ctx = flyCtx(testnet)
545
546
  const chainId = Number(ctx.chainId)
546
547
  const write = (tx, extra) => step(ctx, tx, { chainId, ...extra }, rawOnly, summarize)
548
+ // the GANG_TOOL tag on a create / mint / withdraw (mainnet: gang.fun does not index testnet txs)
549
+ const tagged = (data) => (testnet ? data : withTool(data))
547
550
  if (flag('note')) fail('--note is not matched to 铸币飞轮 trades yet: leave it out')
548
551
 
549
552
  const tokenArg = () => {
@@ -824,9 +827,9 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
824
827
  const sym = await symbolOf(ctx, quote)
825
828
  const pre = await fund(ctx, { me: who, token: quote, need, spender: ctx.pad, sym }, rawOnly, summarize)
826
829
  if (pre) return out(pre)
827
- const createData = (logoURI, metaURI) => encodeFunctionData({
830
+ const createData = (logoURI, metaURI) => tagged(encodeFunctionData({
828
831
  abi: padAbi, functionName: 'create', args: [[name, symbol, logoURI, metaURI], quote, refPool, cfg, BigInt(devShares)],
829
- })
832
+ }))
830
833
  const dry = await dryRun(ctx, who, ctx.pad, createData('', ''))
831
834
  if (dry) return out({ success: false, step: 'create', ...dry })
832
835
  const logo = await resolveLogo()
@@ -879,7 +882,7 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
879
882
  if (bnb) {
880
883
  const native = await ctx.client.getBalance({ address: who })
881
884
  if (native < need + GAS_RESERVE) fail('not enough BNB for this mint (native BNB must also cover gas)', { haveBnb: formatUnits(native, 18), needBnb: formatUnits(need, 18), hint: 'add --use-wbnb to pay from WBNB' })
882
- const data = encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mintWithBnb', args: [token, accepted, BigInt(minShares), referrer] })
885
+ const data = tagged(encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mintWithBnb', args: [token, accepted, BigInt(minShares), referrer] }))
883
886
  const dry = await dryRun(ctx, who, ctx.pad, data, need)
884
887
  if (dry) return out({ success: false, ...extra, ...dry })
885
888
  const tx = { from: who, to: ctx.pad, data, value: need }
@@ -888,7 +891,7 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
888
891
  }
889
892
  const pre = await fund(ctx, { me: who, token: sale.quote, need, spender: ctx.pad, sym: sale.quoteSymbol }, rawOnly, summarize)
890
893
  if (pre) return out(pre)
891
- const data = encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mint', args: [token, accepted, BigInt(minShares), referrer] })
894
+ const data = tagged(encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mint', args: [token, accepted, BigInt(minShares), referrer] }))
892
895
  const dry = await dryRun(ctx, who, ctx.pad, data)
893
896
  if (dry) return out({ success: false, ...extra, ...dry })
894
897
  const tx = { from: who, to: ctx.pad, data }
@@ -916,7 +919,7 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
916
919
  if (accepted === 0n) fail('no shares available to this wallet now', quota)
917
920
  const minTokensOut = minOf(tokensOut, slippage)
918
921
  const maxSpent = paid + fee
919
- const data = bnb
922
+ const call = bnb
920
923
  ? encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mintPostWithBnb', args: [token, accepted, minTokensOut, referrer] })
921
924
  : encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mintPost', args: [token, accepted, minTokensOut, maxSpent, referrer] })
922
925
  const extra = {
@@ -930,7 +933,7 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
930
933
  if (!ok) {
931
934
  // the preview says no: the same call, simulated, names the rule (a BNB sale: BNB lent for the simulation only). Only
932
935
  // a rule of the pad / handler / token counts: a quote-token revert (no allowance yet) says nothing about the rule
933
- const dry = await dryRun(ctx, who, ctx.pad, data, bnb ? maxSpent : 0n, bnb)
936
+ const dry = await dryRun(ctx, who, ctx.pad, call, bnb ? maxSpent : 0n, bnb)
934
937
  const r = dry?.reverted && HINTS[dry.error] ? dry : null
935
938
  // no rule from the simulation (e.g. it stopped at the quote transfer): the pad's rules read as gang info does,
936
939
  // and what is left when none applies is this wallet's own pace
@@ -946,6 +949,7 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
946
949
  if (bnb) {
947
950
  const native = await ctx.client.getBalance({ address: who })
948
951
  if (native < maxSpent + GAS_RESERVE) fail('not enough BNB for this mint (native BNB must also cover gas)', { haveBnb: formatUnits(native, 18), needBnb: formatUnits(maxSpent, 18), hint: 'add --use-wbnb to pay from WBNB' })
952
+ const data = tagged(call)
949
953
  const dry = await dryRun(ctx, who, ctx.pad, data, maxSpent)
950
954
  if (dry) return out({ success: false, ...extra, ...dry })
951
955
  const tx = { from: who, to: ctx.pad, data, value: maxSpent }
@@ -954,6 +958,7 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
954
958
  }
955
959
  const pre = await fund(ctx, { me: who, token: sale.quote, need: maxSpent, spender: ctx.pad, sym: sale.quoteSymbol }, rawOnly, summarize)
956
960
  if (pre) return out(pre)
961
+ const data = tagged(call)
957
962
  const dry = await dryRun(ctx, who, ctx.pad, data)
958
963
  if (dry) return out({ success: false, ...extra, ...dry })
959
964
  const tx = { from: who, to: ctx.pad, data }
@@ -977,7 +982,7 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
977
982
  const shares = flag('all') ? held : parseIntIn(fail, 'shares', opt('shares'), 1, held)
978
983
  const [payout, fee] = await ctx.read(ctx.pad, FLY_PAD_ABI, 'previewWithdraw', [token, who, BigInt(shares)])
979
984
  const minPayout = (payout * (10_000n - WITHDRAW_TOLERANCE_BPS)) / 10_000n
980
- const data = encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'withdraw', args: [token, BigInt(shares), minPayout] })
985
+ const data = tagged(encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'withdraw', args: [token, BigInt(shares), minPayout] }))
981
986
  const dry = await dryRun(ctx, who, ctx.pad, data)
982
987
  if (dry) return out({ success: false, step: 'withdraw', ...dry })
983
988
  return out(write({ from: who, to: ctx.pad, data }, {
package/src/index.js CHANGED
@@ -7,7 +7,7 @@ import { baw, bawAddress, bawError, bawFailed, bawSettings, bawStatus, bawPrevie
7
7
  import { uploadLogoFile, uploadMetadata, rehostLogoUrl, isGangLogo, checkGangLogo, tempHost, ipfsCid, ipfsUri, isIpfsUri, cdnUrl, LOGO_UI } from './logo.js'
8
8
  import { API, fetchMarket, get as apiGet, rank, watch, parseDuration } from './discover.js'
9
9
  import {
10
- makeNote, withNote, queueNote, findByRequestId, findByHashes, hashesIn, publishNote, hasQueued, followSuffix, readFollowRef,
10
+ makeNote, withNote, withTool, toolInfo, queueNote, findByRequestId, findByHashes, hashesIn, publishNote, hasQueued, followSuffix, readFollowRef,
11
11
  refSuffix, readRef,
12
12
  readTokenLinks,
13
13
  } from './notes.js'
@@ -50,6 +50,8 @@ let refTag = '', refInfo = null
50
50
  // the first result of a run is also counted (anonymously, telemetry.js) unless GANG_TELEMETRY=0
51
51
  const out = (o) => {
52
52
  if (refInfo && o && typeof o === 'object' && !('ref' in o)) o = { ...o, ref: refInfo }
53
+ // a failed result built no tx, so it claims no tag; a bad id is always said
54
+ if (toolInfo() && o && typeof o === 'object' && !('tool' in o) && (o.success !== false || !toolInfo().attached)) o = { ...o, tool: toolInfo() }
53
55
  record(args, o)
54
56
  console.log(JSON.stringify(update ? { ...o, update } : o, (_, v) => (typeof v === 'bigint' ? v.toString() : v), 2))
55
57
  }
@@ -213,8 +215,8 @@ async function withUsd(follow, token, track, spent, decimals) {
213
215
  }
214
216
  }
215
217
 
216
- // [calldata][ref][follow][note]: the invite tag (only set on a buy / mint / follow with --ref) and the follow ref
217
- const withFollow = (data, follow) => data + refTag + (follow ? followSuffix(follow.noteTx) : '')
218
+ // [calldata][tool][ref][follow][note]: the GANG_TOOL tag, the invite tag (only set on a buy / mint / follow with --ref) and the follow ref
219
+ const withFollow = (data, follow) => withTool(data) + refTag + (follow ? followSuffix(follow.noteTx) : '')
218
220
 
219
221
  /**
220
222
  * --ref <addr|handle> on a buy / mint / follow: asks gang.fun whether the wallet has never traded on Gang and the
@@ -633,6 +635,7 @@ off, GANG_UPDATE_URL points it at an npm mirror).
633
635
 
634
636
  env: GANG_RPC_URL (one URL or a comma list; unset: five public BSC nodes, the next one tried when one fails),
635
637
  GANG_LOGO_API, GANG_API (default ${API}), GANG_NOTES_DIR (default ~/.gang/notes), GANG_UPDATE_CHECK, GANG_UPDATE_URL,
638
+ GANG_CLIENT (the host's name in the usage counts), GANG_TOOL (a tool builder's id, tagged on mainnet trades and creates),
636
639
  GANG_PAD / GANG_TESTNET_PAD (the GangLaunchpad new tokens go to, behind both gang v3 and gang fair; old names GANG_V3_PAD /
637
640
  GANG_FAIR_PAD and GANG_V3_TESTNET_PAD / GANG_FAIR_TESTNET_PAD still work as aliases), GANG_TESTNET_RPC_URL (aliases
638
641
  GANG_V3_TESTNET_RPC_URL / GANG_FAIR_TESTNET_RPC_URL), GANG_ROUTER / GANG_TESTNET_ROUTER (alias GANG_ROUTER_TESTNET; GangRouter
@@ -961,13 +964,13 @@ async function legacySell(token) {
961
964
  const q = await quoteSell(token, amount)
962
965
  const minOut = (q.out * BigInt(Math.round((100 - slippage) * 100))) / 10000n
963
966
  if (pad.kind === 'soft') {
964
- const p = bawPreview({ from: me, to: pad.address, data: withNote(calldata.softSell(token, amount, minOut), note) })
967
+ const p = bawPreview({ from: me, to: pad.address, data: withNote(withTool(calldata.softSell(token, amount, minOut)), note) })
965
968
  return out(summarizeWithNote(p, {
966
969
  step: 'sell', kind: 'soft', token, symbol: info.symbol, pad: pad.id,
967
970
  amount: fmtTok(amount), expectOut: q.outFmt, fee: q.feeFmt, minOut: fmt(minOut), unit: 'BNB',
968
971
  }, note, 'sell'))
969
972
  }
970
- const p = bawPreview({ from: me, to: pad.address, data: withNote(calldata.v2Sell(token, amount, minOut), note) })
973
+ const p = bawPreview({ from: me, to: pad.address, data: withNote(withTool(calldata.v2Sell(token, amount, minOut)), note) })
971
974
  return out(summarizeWithNote(p, {
972
975
  step: 'sell', kind: 'v2', token, symbol: info.symbol, pad: pad.id, quote: info.quote,
973
976
  amount: fmtTok(amount), expectOut: q.outFmt, fee: q.feeFmt, minOut: fmt(minOut), unit: 'quote', quotePath: q.quotePath, deterministic: q.deterministic || false,
package/src/mcp.js CHANGED
@@ -10,6 +10,7 @@ import { homedir } from 'node:os'
10
10
  import { delimiter, dirname, join, sep } from 'node:path'
11
11
  import { createInterface } from 'node:readline'
12
12
  import { fileURLToPath } from 'node:url'
13
+ import { clientOf } from './telemetry.js'
13
14
  import { VERSION } from './version.js'
14
15
 
15
16
  const CLI = fileURLToPath(new URL('./index.js', import.meta.url))
@@ -262,9 +263,9 @@ export function childEnv(env = process.env, cli = CLI) {
262
263
  }
263
264
 
264
265
  /** Run the CLI with args → { code, stdout, stderr }. onChild(child): to kill a read when its request is cancelled. */
265
- function runCli(args, ms, onChild = () => {}) {
266
+ function runCli(args, ms, onChild = () => {}, env = childEnv()) {
266
267
  return new Promise((resolve) => {
267
- const child = spawn(process.execPath, [CLI, ...args], { env: childEnv(), stdio: ['ignore', 'pipe', 'pipe'] })
268
+ const child = spawn(process.execPath, [CLI, ...args], { env, stdio: ['ignore', 'pipe', 'pipe'] })
268
269
  onChild(child)
269
270
  let stdout = '', stderr = ''
270
271
  child.stdout.on('data', (d) => { stdout += d })
@@ -322,6 +323,8 @@ export function runMcp({ input = process.stdin, output = process.stdout, signals
322
323
  const write = (m) => output.write(`${JSON.stringify({ jsonrpc: '2.0', ...m })}\n`)
323
324
  const reply = (id, result) => write({ id, result })
324
325
  const error = (id, code, message) => write({ id, error: { code, message } })
326
+ // the MCP client's name, for the children's usage counts (telemetry.js); a GANG_CLIENT the user set wins
327
+ let host = ''
325
328
  const pending = new Set()
326
329
  const running = new Map() // request id -> { child, read }: a read's child is killed when the request is cancelled
327
330
  const cancelled = new Set() // answered with nothing: the client stopped waiting
@@ -338,6 +341,7 @@ export function runMcp({ input = process.stdin, output = process.stdout, signals
338
341
  switch (m.method) {
339
342
  case 'initialize': {
340
343
  const asked = m.params?.protocolVersion
344
+ host = clientOf(m.params?.clientInfo?.name)
341
345
  return reply(m.id, {
342
346
  protocolVersion: PROTOCOLS.includes(asked) ? asked : PROTOCOLS[0],
343
347
  capabilities: { tools: { listChanged: false } },
@@ -358,7 +362,7 @@ export function runMcp({ input = process.stdin, output = process.stdout, signals
358
362
  const read = t.annotations.readOnlyHint === true
359
363
  const ms = t.name === 'gang_watch' ? (WATCH_MAX_SEC + 30) * 1000 : read ? RUN_MS : WRITE_MS
360
364
  const args = t.args(a)
361
- const done = await runCli(args, ms, (child) => running.set(m.id, { child, read }))
365
+ const done = await runCli(args, ms, (child) => running.set(m.id, { child, read }), childEnv({ ...(host && { GANG_CLIENT: host }), ...process.env }))
362
366
  running.delete(m.id)
363
367
  // a cancelled request gets no answer (MCP: the client has stopped waiting for it)
364
368
  if (cancelled.delete(m.id)) return
package/src/notes.js CHANGED
@@ -6,6 +6,7 @@
6
6
  * follow ref = "gang" 0x03 followed note tx hash (37 bytes), right before the note suffix (or last without one)
7
7
  * token links (create) = "gang" 0x04 UTF-8(website "\n" twitter) uint16be(length), same place (see readTokenLinks; written by LaunchpadV2 creates before CLI 0.10)
8
8
  * ref = "gang" 0x05 referrer address (25 bytes), right before the follow ref: [calldata][ref][follow][note] (see readRef)
9
+ * tool = "gang" 0x06 tool id (17 bytes), right before the ref: [calldata][tool][ref][follow][note] (see readTool)
9
10
  * The text is sent after the tx lands (POST /api/notes), so anyone can check it was written before the trade.
10
11
  * v2 (sealed): the server holds the text and only shows it from blockTime + revealAfter.
11
12
  * Normalization and the commitment format must match the server byte for byte.
@@ -23,7 +24,8 @@ export const MAGIC = '67616e6701' // "gang" + version 1
23
24
  export const MAGIC_V2 = '67616e6702' // "gang" + version 2 (sealed)
24
25
  export const FOLLOW_MAGIC = '67616e6703' // "gang" + 03: follow ref
25
26
  export const LINKS_MAGIC = '67616e6704' // "gang" + 04: token links
26
- export const REF_MAGIC = '67616e6705' // "gang" + 05: who invited this wallet (01–05 are never reused)
27
+ export const REF_MAGIC = '67616e6705' // "gang" + 05: who invited this wallet
28
+ export const TOOL_MAGIC = '67616e6706' // "gang" + 06: which tool sent this tx (01–06 are never reused)
27
29
  const MAX_CP = 280
28
30
  const REVEAL_MIN_H = 1, REVEAL_MAX_H = 72
29
31
  const LINK = /https?:\/\/|www\.|t\.me\//i
@@ -147,6 +149,51 @@ export function readRef(input) {
147
149
  return r.length === 50 && r.startsWith(REF_MAGIC) && /^[0-9a-f]{40}$/.test(r.slice(10)) ? `0x${r.slice(10)}` : null
148
150
  }
149
151
 
152
+ /**
153
+ * Tool tag (same code as the server's indexer): which tool sent this tx, set by its builder with GANG_TOOL. The id is
154
+ * 2–12 of a-z 0-9 - (first not -), in ASCII, zero-padded to 12 bytes. "gang" 06 id (17 bytes), lower-case hex without
155
+ * 0x, right before the ref, the follow ref and the note suffix, if any: [calldata][tool][ref][follow][note]. Anyone can
156
+ * write any id: it is a usage count, not proof of who sent the tx.
157
+ */
158
+ export const TOOL_ID = /^[a-z0-9][a-z0-9-]{1,11}$/
159
+ export function toolSuffix(id) {
160
+ if (!TOOL_ID.test(String(id ?? ''))) throw new Error('bad tool id')
161
+ return `${TOOL_MAGIC}${Buffer.from(id, 'ascii').toString('hex').padEnd(24, '0')}`
162
+ }
163
+
164
+ /**
165
+ * The tool id a tx input names, or null. Only one place counts: the 17 bytes right before the ref (when the input has
166
+ * one), the follow ref and the note suffix, so one input names at most one tool.
167
+ */
168
+ export function readTool(input) {
169
+ const s = String(input || '').toLowerCase()
170
+ const c = readNoteCommit(s)
171
+ let end = s.length - (c ? (c.version === 2 ? 82 : 74) : 0)
172
+ const f = s.slice(Math.max(0, end - 74), end)
173
+ if (f.length === 74 && f.startsWith(FOLLOW_MAGIC) && TX_RE.test(`0x${f.slice(10)}`)) end -= 74
174
+ const r = s.slice(Math.max(0, end - 50), end)
175
+ if (r.length === 50 && r.startsWith(REF_MAGIC) && /^[0-9a-f]{40}$/.test(r.slice(10))) end -= 50
176
+ const t = s.slice(Math.max(0, end - 34), end)
177
+ if (t.length !== 34 || !t.startsWith(TOOL_MAGIC) || !/^[0-9a-f]{24}$/.test(t.slice(10))) return null
178
+ const id = Buffer.from(t.slice(10), 'hex').toString('latin1').replace(/\0+$/, '')
179
+ return TOOL_ID.test(id) ? id : null
180
+ }
181
+
182
+ // what GANG_TOOL did on this run, shown on its result (only once a write step was built with it)
183
+ let toolState = null
184
+ export const toolInfo = () => toolState
185
+
186
+ /** A write step's calldata with the GANG_TOOL tag. A bad id never fails the trade: it goes untagged and the result says so. */
187
+ export function withTool(data, id = process.env.GANG_TOOL) {
188
+ if (!id) return data
189
+ if (!TOOL_ID.test(id)) {
190
+ toolState = { attached: false, reason: 'GANG_TOOL must be 2–12 of a-z 0-9 - (first not -): left out' }
191
+ return data
192
+ }
193
+ toolState = { attached: true, id }
194
+ return data + toolSuffix(id)
195
+ }
196
+
150
197
  /*
151
198
  * Token links (create only): the creator's website and X (Twitter) link, in plain text since they're public anyway.
152
199
  * "gang" 04 UTF-8(website "\n" twitter) uint16be(payload bytes), right before the note suffix (or last without one):
package/src/telemetry.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Anonymous usage counts, on by default; GANG_TELEMETRY=0 (or DO_NOT_TRACK=1) turns them off.
3
3
  * One event per command: its name, the flag names (never their values), whether it succeeded and, when not, a short
4
- * error code. `gang preflight` adds which checks passed. The only id is a random one (~/.gang/install-id); no wallet,
5
- * address, amount, token, note text or flag value goes out. gang.fun uses it to see where agents get stuck before a
6
- * first trade.
4
+ * error code, and the host's name when known (`gang mcp`: the MCP client's own name; else GANG_CLIENT). `gang preflight`
5
+ * adds which checks passed. The only id is a random one (~/.gang/install-id); no wallet, address, amount, token, note text
6
+ * or flag value goes out. gang.fun uses it to see where agents get stuck before a first trade and which hosts they use.
7
7
  * Events queue in ~/.gang/events.ndjson and a detached child posts them to POST /api/t at most once a minute, so a
8
8
  * command never waits on the network; a failed post is dropped.
9
9
  */
@@ -71,6 +71,19 @@ export function codeOf(o = {}) {
71
71
  return 'ERROR'
72
72
  }
73
73
 
74
+ /**
75
+ * A host's name as the events carry it: a slug of a-z 0-9 -, at most 24 characters. Only what looks like a product's name
76
+ * goes out: anything else (a full address, an email, a path, a dotted hostname, a long key: other characters, too long, a
77
+ * long hex run) is 'other', never a shortened copy. '' when there is no name. These rules can't tell a person's name from
78
+ * a product's: a host that sends one as its own name sends it here too.
79
+ */
80
+ export function clientOf(raw = process.env.GANG_CLIENT) {
81
+ if (typeof raw !== 'string' || !raw.trim()) return ''
82
+ const s = raw.trim()
83
+ if (!/^[A-Za-z][A-Za-z0-9 _-]{0,23}$/.test(s) || /[0-9a-f]{12}/i.test(s)) return 'other'
84
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+$/, '')
85
+ }
86
+
74
87
  /** The event for one command (argv after `gang`) and its JSON result. */
75
88
  export function eventOf(argv, o = {}) {
76
89
  const c = NAME.test(argv[0] ?? '') ? argv[0] : 'other'
@@ -80,7 +93,8 @@ export function eventOf(argv, o = {}) {
80
93
  const pf = c === 'preflight'
81
94
  ? { signedIn: o.status === 'CONNECTED', agent: o.isAgent ?? null, dev: o.devMode ?? null, all: o.tradeAllTokens ?? null }
82
95
  : null
83
- return { t: Math.floor(Date.now() / 1000), c, s, f, ok, code: ok ? '' : codeOf(o), pf }
96
+ const cl = clientOf()
97
+ return { t: Math.floor(Date.now() / 1000), c, s, f, ok, code: ok ? '' : codeOf(o), pf, ...(cl && { cl }) }
84
98
  }
85
99
 
86
100
  let recorded = false