Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(sniper): fund dry trading arms from idle platform-bot SOL when the master is empty

nirholas41c7ad40c7b5
diff --git a/prompts/finish/_context/x-grok-PROGRESS.md b/prompts/finish/_context/x-grok-PROGRESS.md
index a91676a64..aa8c0001b 100644
--- a/prompts/finish/_context/x-grok-PROGRESS.md
+++ b/prompts/finish/_context/x-grok-PROGRESS.md
@@ -14,3 +14,9 @@ Cross-session handoff for the `x-grok-` orders ([x-grok-00-CONTEXT.md](x-grok-00
- Measured: @trythreews user id is `2049400807624527872` (derived from the access token prefix, no extra call). Real mentions include posts where our handle is only an auto-prefixed reply handle (someone replying in a thread we were tagged in); the parser (047) must treat those as reply context, not as an address.
- `X_OAUTH_CLIENT_ID` / `X_OAUTH_CLIENT_SECRET` are not on the Cloud Run service, so agent OAuth2 token refresh (both posting and the agent mention mode) cannot refresh in production until they are set. Relevant to orders 060 and 061.
- The probe was run twice (one stdout preview, one write), so two read calls were spent, not one.
+
+## 2026-10-08: order 047 (mention intent parser) done
+
+- Shipped `7c2382374`: `api/_lib/x-mention-intents.js` (`parseMentionIntent`, `parseLaunch`, `normalizeText`, `splitLeadingHandles`, `sanitizeArg`, `addressing`), 94 tests in `tests/x-mention-intents.test.js` (83-case corpus, 17 hostile), and a pointer in order 925 to consume this parser.
+- Step 0: no `api/_lib/x-mention*` existed besides 046's reader; order 925 had not built a parser, so its `launch <NAME> $<TICKER> [description]` grammar was written here first, held to the `/launch` form limits imported from `src/launch/launch-model.js` (the parser's only import; a test asserts it).
+- Behavior the next orders rely on: money-movement, secret and instruction-override phrasing returns `help` (reason `refused_*`) and never reaches a model. A handle that only rides along in reply handles of a thread already naming us is `inherited`: explicit commands still parse, chatter is `ignore` (the real 2026-10-08 "add me" shape). Unrecognized direct text is `chat` for both company and agent accounts (reason `company_chat` / `agent_chat`); order 051 decides whether the company account answers it. `image3d` args carry `sourceAuthorId` so order 053 can enforce its own-image rule. `$THREE` is a reserved ticker for `launch`.
diff --git a/scripts/sniper-fleet-restore.mjs b/scripts/sniper-fleet-restore.mjs
index 690088706..3669190f9 100644
--- a/scripts/sniper-fleet-restore.mjs
+++ b/scripts/sniper-fleet-restore.mjs
@@ -21,6 +21,20 @@
* node scripts/sniper-fleet-restore.mjs --json # machine-readable
* node scripts/sniper-fleet-restore.mjs --apply --yes # top up the deficits
* node scripts/sniper-fleet-restore.mjs --target 0.08 # override the per-arm target
+ * node scripts/sniper-fleet-restore.mjs --from-platform-bots # plan from idle bots
+ * node scripts/sniper-fleet-restore.mjs --from-platform-bots --apply --yes
+ *
+ * `--from-platform-bots` funds the arms from idle platform-owned agent wallets
+ * instead of the funding master, for when the master itself is dry. Sources are
+ * restricted to agents owned by the house account or a `*@agents.three.ws`
+ * circulation bot (`isPlatformOwnedAgent`, checked in SQL and again in JS) that
+ * have no sniper strategy at all and no open position, and each keeps the idle
+ * fee floor the economy reclaim leaves it (`agentReclaimFloorSol`). A customer's
+ * wallet is never a source. Only arms that opted into auto-funding AND whose one
+ * blocking stall is `wallet_dry` are targets: funding an arm parked on an offline
+ * model or an unreachable mcap band spends SOL that cannot trade, and funding an
+ * arm the auto-funder does not manage would be swept straight back by the
+ * reclaim leg, which only honors the funding target for opted-in wallets.
*/
import { config as dotenv } from 'dotenv';
@@ -35,6 +49,14 @@ const { MIN_OPERATIONAL_WALLET_SOL } = await import('../api/_lib/agent-trade-gua
const { autoFundTargetSol, fundTargetSol } = await import('../api/_lib/agent-funding-policy.js');
const { fundAgentForLaunch, masterBalanceSol } = await import('../api/_lib/launcher-funding.js');
const { diagnoseStall } = await import('../api/_lib/sniper-stall.js');
+const {
+ isPlatformOwnedAgent,
+ agentReclaimFloorSol,
+ PLATFORM_AGENT_OWNER_EMAIL,
+ PLATFORM_AGENT_EMAIL_SUFFIX,
+} = await import('../api/_lib/economy-sweepback.js');
+const { sendSol } = await import('../api/_lib/avatar-wallet.js');
+const { recoverSolanaAgentKeypair } = await import('../api/_lib/agent-wallet.js');
const args = process.argv.slice(2);
const has = (f) => args.includes(f);
@@ -48,6 +70,13 @@ const APPLY = has('--apply');
const CONFIRMED = has('--yes');
const JSON_OUT = has('--json');
const TARGET_SOL = Number(opt('--target', autoFundTargetSol()));
+const FROM_BOTS = has('--from-platform-bots');
+
+// Left in each source on top of its idle floor to pay the transfer's own fee
+// (base fee plus the priority fee submitProtected attaches; no Jito tip).
+const SOURCE_FEE_RESERVE_SOL = 0.0001;
+// Smallest pull worth a transaction: below this the fee is a real fraction of it.
+const MIN_SOURCE_PULL_SOL = 0.002;
const sol = (n) => `${Number(n).toFixed(4)} SOL`;
@@ -169,6 +198,11 @@ if (unfundable.length) {
console.log(`${unfundable.length} arm(s) are short but have NOT opted into auto-funding (auto_fund_enabled = false):`);
for (const a of unfundable) console.log(` · ${a.label} (${a.agentName}) short ${sol(a.deficitSol)}`);
}
+if (FROM_BOTS) {
+ await restoreFromPlatformBots();
+ process.exit(0);
+}
+
if (masterSol != null && totalDeficit > masterSol) {
console.log(`\n The master cannot cover this: it needs ${sol(totalDeficit - masterSol)} more before the fleet is whole.`);
}
@@ -202,3 +236,146 @@ for (const a of fundable) {
}
console.log(`\nMoved ${sol(moved)}.\n`);
process.exit(0);
+
+/**
+ * Whether topping this arm up actually lets it trade: its stall is `wallet_dry`
+ * and nothing else it reports is blocking.
+ * @param {{code:string, blocking?:boolean, also?:Array<{blocking?:boolean}>}|null} stall
+ */
+function fundingUnblocks(stall) {
+ return stall?.code === 'wallet_dry' && !(stall.also || []).some((x) => x.blocking);
+}
+
+/**
+ * Pair idle platform-bot SOL with arm deficits, biggest source first. A source can
+ * split across arms; every leg still leaves the source at or above its floor.
+ * @param {Array<{agentId:string,name:string,address:string,excessSol:number}>} sources
+ * @param {Array<{label:string,agentId:string,address:string,deficitSol:number}>} targets
+ */
+function planBotTransfers(sources, targets) {
+ const legs = [];
+ const pool = sources.map((s) => ({ ...s, left: s.excessSol })).sort((a, b) => b.left - a.left);
+ for (const t of targets) {
+ let need = t.deficitSol;
+ for (const s of pool) {
+ if (need <= 0) break;
+ if (s.left < MIN_SOURCE_PULL_SOL) continue;
+ const amount = Number(Math.min(s.left, need).toFixed(9));
+ if (amount < MIN_SOURCE_PULL_SOL && amount < need) continue;
+ legs.push({ from: s, to: t, amountSol: amount });
+ s.left = Number((s.left - amount).toFixed(9));
+ need = Number((need - amount).toFixed(9));
+ }
+ }
+ return legs;
+}
+
+async function restoreFromPlatformBots() {
+ const targets = arms.filter(
+ (a) => a.deficitSol > 0 && a.autoFundEnabled && isPlatformOwnedAgent(a.owner) && fundingUnblocks(a.stall),
+ );
+ const passed = arms.filter((a) => a.deficitSol > 0 && !targets.includes(a));
+
+ const sourceRows = await sql`
+ SELECT a.id AS agent_id, a.name,
+ a.meta->>'solana_address' AS address,
+ a.meta->>'encrypted_solana_secret' AS secret,
+ LOWER(u.email) AS owner
+ FROM agent_identities a
+ JOIN users u ON u.id = a.user_id
+ WHERE a.deleted_at IS NULL
+ AND a.meta->>'solana_address' IS NOT NULL
+ AND a.meta->>'encrypted_solana_secret' IS NOT NULL
+ AND (LOWER(u.email) = ${PLATFORM_AGENT_OWNER_EMAIL}
+ OR LOWER(u.email) LIKE ${'%' + PLATFORM_AGENT_EMAIL_SUFFIX})
+ AND NOT EXISTS (SELECT 1 FROM agent_sniper_strategies s WHERE s.agent_id = a.id)
+ AND NOT EXISTS (SELECT 1 FROM agent_sniper_positions p
+ WHERE p.agent_id = a.id AND p.status IN ('open', 'closing'))
+ `;
+
+ const floorSol = agentReclaimFloorSol({ enabled: false, autoFundEnabled: false });
+ const sources = [];
+ const unreadable = [];
+ for (const r of sourceRows) {
+ if (!isPlatformOwnedAgent(r.owner)) continue;
+ let bal;
+ try {
+ bal = (await connection.getBalance(new PublicKey(r.address), 'confirmed')) / 1e9;
+ } catch (err) {
+ unreadable.push({ name: r.name, reason: `balance: ${err.message}` });
+ continue;
+ }
+ const excessSol = Number((bal - floorSol - SOURCE_FEE_RESERVE_SOL).toFixed(9));
+ if (excessSol < MIN_SOURCE_PULL_SOL) continue;
+ // The same gate the real leg runs: a key that will not decrypt is not capital.
+ let keypair;
+ try {
+ keypair = await recoverSolanaAgentKeypair(r.secret, null);
+ } catch (err) {
+ unreadable.push({ name: r.name, address: r.address, sol: bal, reason: `secret_undecryptable: ${err.message}` });
+ continue;
+ }
+ if (keypair.publicKey.toBase58() !== r.address) {
+ unreadable.push({ name: r.name, address: r.address, sol: bal, reason: 'keypair_address_mismatch' });
+ continue;
+ }
+ sources.push({ agentId: r.agent_id, name: r.name, address: r.address, owner: r.owner, secret: r.secret, balanceSol: bal, excessSol });
+ }
+
+ const legs = planBotTransfers(sources, targets);
+ const available = Number(sources.reduce((s, x) => s + x.excessSol, 0).toFixed(6));
+ const planned = Number(legs.reduce((s, l) => s + l.amountSol, 0).toFixed(6));
+ const wanted = Number(targets.reduce((s, t) => s + t.deficitSol, 0).toFixed(6));
+
+ console.log(`\nSource: idle platform-owned bot wallets (floor ${sol(floorSol)} each + ${sol(SOURCE_FEE_RESERVE_SOL)} fee reserve)`);
+ console.log(` ${sources.length} wallet(s) with spare SOL, ${sol(available)} available above floor.`);
+ for (const u of unreadable) console.log(` ! skipped ${u.name}${u.sol != null ? ` (${sol(u.sol)})` : ''}: ${u.reason}`);
+
+ console.log('\nTargets (auto-funded, platform-owned, only blocker is wallet_dry):');
+ for (const t of targets) {
+ const got = legs.filter((l) => l.to === t).reduce((s, l) => s + l.amountSol, 0);
+ console.log(` ${t.label.padEnd(20)} ${t.address} +${sol(got)} of ${sol(t.deficitSol)}`);
+ }
+ for (const a of passed) {
+ const why = !a.autoFundEnabled ? 'not opted into auto-funding (reclaim would sweep it back)'
+ : !isPlatformOwnedAgent(a.owner) ? 'not platform-owned'
+ : `funding does not unblock it (${[a.stall?.code, ...(a.stall?.also || []).filter((x) => x.blocking).map((x) => x.code)].filter(Boolean).join(', ')})`;
+ console.log(` - ${a.label.padEnd(18)} passed over: ${why}`);
+ }
+ console.log(`\n${legs.length} transfer(s), ${sol(planned)} of the ${sol(wanted)} the targets need.`);
+
+ if (!APPLY) {
+ console.log('\nDry run: nothing moved. Re-run with `--from-platform-bots --apply --yes` to send these transfers.\n');
+ for (const l of legs) console.log(` ${l.from.name.padEnd(16)} ${l.from.address} → ${l.to.label.padEnd(18)} ${sol(l.amountSol)}`);
+ console.log('');
+ return;
+ }
+ if (!CONFIRMED) {
+ console.log('\nRefusing to move SOL without `--yes`. Review the plan above first.\n');
+ return;
+ }
+
+ let moved = 0;
+ for (const l of legs) {
+ try {
+ const keypair = await recoverSolanaAgentKeypair(l.from.secret, {
+ agentId: l.from.agentId,
+ reason: 'sniper_fleet_restore_from_bots',
+ meta: { to: l.to.address, sol: l.amountSol },
+ });
+ const signature = await sendSol({
+ connection,
+ fromKeypair: keypair,
+ to: l.to.address,
+ lamports: Math.round(l.amountSol * 1e9),
+ memo: `three.ws fleet restore ${l.from.name} → ${l.to.label}`,
+ network: NETWORK,
+ });
+ moved += l.amountSol;
+ console.log(` ✓ ${l.from.name.padEnd(16)} → ${l.to.label.padEnd(18)} ${sol(l.amountSol)} ${signature}`);
+ } catch (err) {
+ console.log(` ✗ ${l.from.name.padEnd(16)} → ${l.to.label.padEnd(18)} ${sol(l.amountSol)} ${err.message}`);
+ }
+ }
+ console.log(`\nMoved ${sol(moved)} of ${sol(planned)}.\n`);
+}