anon-pi 0.4.0 → 0.5.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/dist/cli.js CHANGED
@@ -1,77 +1,138 @@
1
1
  #!/usr/bin/env node
2
- // anon-pi CLI. Two commands:
3
- // anon-pi [WORKDIR] resolve the run plan (pure) and exec `netcage run ...`
4
- // with inherited stdio (so -it is a real interactive TTY).
5
- // The seed models.json is mounted read-only and copied
6
- // into the container's ~/.pi/agent by the run command, so
7
- // it layers onto the image's config (extensions survive).
8
- // anon-pi import generate the seed models.json from the host models.json,
9
- // carrying only the provider that serves ANON_PI_LLM.
10
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
11
- import { spawnSync } from 'node:child_process';
12
- import { isAbsolute, join, resolve } from 'node:path';
13
- import { AnonPiError, buildRunPlan, envFromProcess, HELP, MODELS_FILE, pickProviderForLlm, resolveConfigSeed, resolveSourceModelsPath, stateAgentDir, } from './anon-pi.js';
2
+ // anon-pi CLI: the THIN impure launch path. Parses grammar A (pure
3
+ // parseLaunchArgs), reads config.json / machine.json + resolves the machine,
4
+ // composes the LaunchIntent, resolves the RunPlan (pure resolveRunPlan), decides
5
+ // run-vs-start against real netcage for `--keep`, and spawns netcage with
6
+ // inherited stdio (so -it is a real interactive TTY), propagating the exit code.
7
+ //
8
+ // All the DECISIONS live in the pure module (anon-pi.ts); this file only does
9
+ // I/O: fs reads/mkdirs, the netcage query, the spawn, and the TTY discipline.
10
+ // The forced-egress invariant is the RunPlan's guarantee: the composed argv
11
+ // ALWAYS carries --proxy + the one --allow-direct; the CLI never strips or adds
12
+ // egress.
13
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
14
+ import { readSync } from 'node:fs';
15
+ import { spawnSync, execFileSync } from 'node:child_process';
16
+ import { join, dirname } from 'node:path';
17
+ import { AnonPiError, HELP, MODELS_FILE, SEED_MARKER, DEFAULT_MACHINE, envFromProcess, buildMenuChoiceList, buildMenuEntries, deriveProjectUsage, machineDir, machineHomeDir, machineJsonPath, machineSessionsDir, validateName, resolveDeleteHome, resolveDeleteProject, parseConfigJson, parseLaunchArgs, parseMachineArgs, parseMachineJson, projectHostDir, resolveAnonPiHome, resolveLlm, resolveProjectsRoot, resolveProxy, resolveRunPlan, resolveRunVsStart, serializeMachineJson, serializeConfigJson, setImageWarning, keptContainerKey, DEFAULT_SOCKS_PROBE_PORTS, SOCKS5_METHOD_SELECTOR, formatProxyFindings, interpretSocks5Handshake, initImageMenu, generateModelsJson, parseVerifyExitIp, processHint, socks5hUrl, hostPortKey, shippedDockerfilePath, shippedWebveilDockerfilePath, } from './anon-pi.js';
18
+ // The netcage label anon-pi stamps its launch-identity key onto (keptContainerKey)
19
+ // so a `--keep` re-entry can find and `netcage start` the same kept container.
20
+ // netcage's `netcage.managed` label marks it a managed container; this adds the
21
+ // anon-pi identity ON TOP (netcage's label IS the registry; anon-pi adds no file).
22
+ const ANON_PI_KEY_LABEL = 'anon-pi.key';
14
23
  function main(argv) {
15
24
  const args = argv.slice(2);
16
- if (args.includes('--help') || args.includes('-h')) {
25
+ // The global `--help`/`-h` prints the top-level HELP, EXCEPT when the first
26
+ // token is a subcommand that owns its own `--help` (so `anon-pi init --help`
27
+ // and `anon-pi machine --help` show THEIR help, not the global one). Those
28
+ // subcommands route to runInit / runMachine, which print INIT_HELP /
29
+ // MACHINE_HELP respectively.
30
+ const OWN_HELP_SUBCOMMANDS = new Set(['init', 'machine']);
31
+ if ((args.includes('--help') || args.includes('-h')) &&
32
+ !OWN_HELP_SUBCOMMANDS.has(args[0] ?? '')) {
17
33
  process.stdout.write(HELP);
18
34
  return 0;
19
35
  }
20
- // Subcommand dispatch: the first bare token may be `import`.
21
- if (args[0] === 'import') {
22
- return runImport(args.slice(1));
23
- }
24
- return runLaunch(args);
25
- }
26
- // --- anon-pi [WORKDIR] : launch pi jailed -----------------------------------
27
- function runLaunch(args) {
28
- // One optional positional (the workdir) + the --ephemeral / --fresh flags.
29
- // Reject other flags so a typo is not silently swallowed: anon-pi owns the
30
- // netcage argv.
31
- const known = new Set(['--ephemeral', '--eph', '--fresh']);
32
- const ephemeralFlag = args.includes('--ephemeral') || args.includes('--eph');
33
- const freshFlag = args.includes('--fresh');
34
- const positionals = args.filter((a) => !a.startsWith('-'));
35
- const flags = args.filter((a) => a.startsWith('-') && !known.has(a));
36
- if (flags.length > 0) {
37
- process.stderr.write(`anon-pi: unknown option(s): ${flags.join(' ')}\nRun \`anon-pi --help\`.\n`);
38
- return 2;
39
- }
40
- if (positionals.length > 1) {
41
- process.stderr.write('anon-pi: too many arguments (expected at most one WORKDIR).\nRun `anon-pi --help`.\n');
42
- return 2;
43
- }
44
- if (freshFlag && ephemeralFlag) {
45
- process.stderr.write('anon-pi: --fresh has no effect with --ephemeral (an ephemeral session is always fresh and never persisted).\nRun `anon-pi --help`.\n');
46
- return 2;
36
+ // `machine …` is the machine-management surface (create/list/set-image/rm),
37
+ // dispatched BEFORE the launch grammar so a bare `machine` is never parsed as
38
+ // a project named "machine". Everything else is a launch.
39
+ if (args[0] === 'machine') {
40
+ return runMachine(args.slice(1));
47
41
  }
48
- const env = envFromProcess(process.env);
49
- if (ephemeralFlag)
50
- env.ephemeral = true;
51
- // --fresh: delete this workdir's persistent state home BEFORE planning, so the
52
- // home is fresh and the image's (possibly rebuilt) defaults + models.json are
53
- // re-seeded on this launch. No-op for --ephemeral (handled above).
54
- if (freshFlag && !env.ephemeral) {
55
- const raw = positionals[0] && positionals[0].trim() !== ''
56
- ? positionals[0]
57
- : process.cwd();
58
- const wd = isAbsolute(raw) ? raw : resolve(raw);
59
- const stateDir = stateAgentDir(env, wd);
60
- if (existsSync(stateDir)) {
61
- rmSync(stateDir, { recursive: true, force: true });
62
- process.stderr.write(`anon-pi: --fresh removed ${stateDir}\n`);
63
- }
42
+ // The destructive cleanup verbs (replacing the old `--fresh`). Dispatched
43
+ // BEFORE the launch grammar: they are top-level data verbs, not launch flags,
44
+ // each with the confirm/`--yes`/non-TTY discipline. `--delete-home` takes an
45
+ // OPTIONAL machine (default machine when omitted); `--delete-project` REQUIRES
46
+ // a project.
47
+ if (args[0] === '--delete-home') {
48
+ return runDeleteHome(args.slice(1));
64
49
  }
65
- let plan;
50
+ if (args[0] === '--delete-project') {
51
+ return runDeleteProject(args.slice(1));
52
+ }
53
+ // `init` onboards: verify the proxy, capture the llm endpoint, pick/build the
54
+ // default machine image, write config.json + the default machine. Re-runnable.
55
+ if (args[0] === 'init') {
56
+ return runInit(args.slice(1));
57
+ }
58
+ let parsed;
66
59
  try {
67
- plan = buildRunPlan(env, positionals[0], existsSync, existsSync);
60
+ parsed = parseLaunchArgs(args);
68
61
  }
69
62
  catch (e) {
70
- if (e instanceof AnonPiError) {
71
- process.stderr.write(e.message + '\n');
72
- return 1;
63
+ return reportAnonPiError(e);
64
+ }
65
+ return runLaunch(parsed);
66
+ }
67
+ // --- the launch path --------------------------------------------------------
68
+ function runLaunch(parsed) {
69
+ const env = envFromProcess(process.env);
70
+ // config.json (the workspace default proxy/llm/defaultMachine/projects).
71
+ const config = readJsonConfig(env);
72
+ // Resolve the machine: an explicit -m wins, else config.defaultMachine, else
73
+ // the built-in DEFAULT_MACHINE (so an explicit `-m default` is honoured too).
74
+ const machineName = parsed.machineExplicit
75
+ ? parsed.machine
76
+ : (config.defaultMachine ?? DEFAULT_MACHINE);
77
+ const machineConf = readMachineJson(env, machineName);
78
+ // Forced-egress inputs, resolved (env over config); the proxy is REQUIRED and
79
+ // fails closed with the verbatim guidance.
80
+ let proxy;
81
+ let llm;
82
+ let intent;
83
+ try {
84
+ proxy = resolveProxy({ env, config });
85
+ llm = resolveLlm({ env, config });
86
+ if (llm === undefined) {
87
+ throw new AnonPiError('anon-pi: set ANON_PI_LLM (or config.llm) to the RFC1918/link-local IP[:port]\n' +
88
+ 'of your local model. It is the ONE direct hole; all other egress stays\n' +
89
+ 'forced through the proxy.');
90
+ }
91
+ // The machine's image: machine.json wins, ANON_PI_IMAGE is the fallback.
92
+ const image = machineConf.image ?? env.image ?? '';
93
+ // --mount re-roots at a HOST parent; otherwise the resolved projects root.
94
+ const mountParent = parsed.mountParent;
95
+ const projectsRoot = resolveProjectsRoot({
96
+ env,
97
+ config,
98
+ machine: machineConf,
99
+ mountParent,
100
+ });
101
+ const home = machineHomeDir(env, machineName);
102
+ const machine = { name: machineName, home, image };
103
+ // The generated models.json for this machine (mounted read-only for the
104
+ // first-launch seed) when present. Keyed per machine, not per import.
105
+ const modelsSeed = join(machineDir(env, machineName), MODELS_FILE);
106
+ intent = {
107
+ machine,
108
+ mode: parsed.mode,
109
+ projectsRoot,
110
+ project: parsed.project,
111
+ mountParent,
112
+ piArgs: parsed.piArgs,
113
+ keep: parsed.keep,
114
+ proxy,
115
+ llmDirect: llm,
116
+ modelsSeed: existsSync(modelsSeed) ? modelsSeed : undefined,
117
+ };
118
+ }
119
+ catch (e) {
120
+ return reportAnonPiError(e);
121
+ }
122
+ // No-TTY discipline: the bare MENU and every INTERACTIVE launch (interactive
123
+ // pi, or a shell) need a TTY; a HEADLESS pi run (`<project> <pi-args…>`) does
124
+ // NOT. Check BEFORE we mutate anything or spawn.
125
+ const headless = parsed.mode === 'pi' && !!parsed.piArgs && parsed.piArgs.length > 0;
126
+ if (!headless && !process.stdin.isTTY) {
127
+ if (parsed.mode === 'menu') {
128
+ process.stderr.write('anon-pi: no TTY. The menu needs an interactive terminal. Pick a project\n' +
129
+ 'directly, e.g. `anon-pi <project>`, or run anon-pi in a terminal.\n');
130
+ }
131
+ else {
132
+ process.stderr.write(`anon-pi: no TTY. An interactive ${parsed.mode === 'shell' ? 'shell' : 'pi session'} needs a terminal.\n` +
133
+ 'Forward a one-shot pi prompt instead, e.g. `anon-pi <project> -p "..."`.\n');
73
134
  }
74
- throw e;
135
+ return 1;
75
136
  }
76
137
  // Fail loud if netcage is not installed, before we mutate anything.
77
138
  if (!hasNetcage()) {
@@ -79,83 +140,1145 @@ function runLaunch(args) {
79
140
  '(https://github.com/wighawag/netcage). Linux only.\n');
80
141
  return 1;
81
142
  }
82
- mkdirSync(plan.workdir, { recursive: true });
83
- if (env.ephemeral) {
84
- // No host state dir: pi writes to the container's own --rm layer, so the
85
- // session leaves NO trace on the host and there is nothing to clean up.
86
- process.stderr.write('anon-pi: ephemeral session (nothing persisted; no host state)\n');
143
+ // Resolve the RunPlan (pure). homeFresh reads the real seed marker.
144
+ let plan;
145
+ try {
146
+ plan = resolveRunPlan(intent, homeFresh);
147
+ }
148
+ catch (e) {
149
+ return reportAnonPiError(e);
150
+ }
151
+ // Bare launch: hand off to the interactive host-side menu, which re-resolves
152
+ // the user's pick into a concrete launch and executes it.
153
+ if (plan.kind === 'menu') {
154
+ return runMenu(intent, plan.machine);
155
+ }
156
+ return executeLaunchPlan(intent, plan);
157
+ }
158
+ /**
159
+ * Execute a RESOLVED non-menu LaunchPlan: create the host dirs the mounts need,
160
+ * then run netcage (or `netcage start` a matching kept container under --keep).
161
+ * Shared by the direct launch path (runLaunch) and the menu dispatch (runMenu),
162
+ * so a menu-picked project/here/shell launches BYTE-FOR-BYTE identically to the
163
+ * same command typed directly.
164
+ */
165
+ function executeLaunchPlan(intent, plan) {
166
+ // Create the host dirs the mounts need BEFORE spawn: the machine home and,
167
+ // for a named project (not the root token `.` / a bare shell), its folder
168
+ // under the active root (the --mount parent or the projects root).
169
+ mkdirSync(plan.machine.home, { recursive: true });
170
+ if (intent.project !== undefined &&
171
+ intent.project !== '.' &&
172
+ intent.mode !== 'shell') {
173
+ const root = intent.mountParent ?? intent.projectsRoot;
174
+ mkdirSync(projectHostDir(root, intent.project), { recursive: true });
87
175
  }
88
176
  else {
89
- // Persistent mode: create the per-workdir state home to mount.
90
- mkdirSync(plan.stateDir, { recursive: true });
91
- if (plan.fresh) {
92
- process.stderr.write(`anon-pi: new session home ${plan.stateDir} (seeding on first launch)\n`);
177
+ // still ensure the active root exists (so a shell/`.`/menu-picked launch
178
+ // has a real dir to cwd into).
179
+ mkdirSync(intent.mountParent ?? intent.projectsRoot, { recursive: true });
180
+ }
181
+ // Run-vs-start: under --keep, ask netcage for its kept managed containers and
182
+ // resume a matching one via `netcage start`; else run the composed argv. A
183
+ // throwaway (`--rm`) launch is always a fresh run (the pure rule never
184
+ // consults the listing for it).
185
+ if (intent.keep) {
186
+ const decision = resolveRunVsStart(intent, queryKeptContainers());
187
+ if (decision.action === 'start') {
188
+ return spawnNetcage(['start', '-a', '-i', decision.ref]);
93
189
  }
190
+ // A fresh `--keep` run: stamp the identity key so a later re-entry can
191
+ // find this container. The RunPlan already omits --rm under --keep.
192
+ return spawnNetcage(withKeyLabel(plan.netcageArgs, keptContainerKey(intent)));
94
193
  }
95
- // Hand off to netcage with inherited stdio so -it is a real interactive TTY.
96
- const res = spawnSync('netcage', plan.netcageArgs, { stdio: 'inherit' });
97
- if (res.error) {
98
- process.stderr.write(`anon-pi: failed to run netcage: ${res.error.message}\n`);
194
+ return spawnNetcage(plan.netcageArgs);
195
+ }
196
+ // --- the interactive host-side menu (the ONLY untested I/O) -------------------
197
+ //
198
+ // Bare `anon-pi` (and bare `-m <machine>` / `--mount <parent>` with no project)
199
+ // dispatches here. The menu is a PURE host-side read: it lists the active root's
200
+ // projects (readdir) + each machine's pi session dirs (readdir) and feeds them
201
+ // to the pure buildMenuChoiceList / deriveProjectUsage / buildMenuEntries, which
202
+ // own ALL the logic (the entry order + the used-on / new-here annotation). This
203
+ // function does ONLY the I/O the pure seam cannot: the real dir reads, the raw-
204
+ // mode arrow-key render/select (select()), the new-project name prompt, and the
205
+ // dispatch of the pick back through resolveRunPlan + executeLaunchPlan (so a
206
+ // menu pick launches identically to the same command typed directly). No jail
207
+ // runs until the user chooses; the no-TTY case is handled BEFORE we reach here
208
+ // (runLaunch's discipline), so a TTY is guaranteed.
209
+ function runMenu(intent, machine) {
210
+ const env = envFromProcess(process.env);
211
+ // The active root the menu lists projects from: a --mount parent re-roots, else
212
+ // the resolved projects root. (Named projects live under it; `.` is the root.)
213
+ const root = intent.mountParent ?? intent.projectsRoot;
214
+ const rawProjects = readDirNames(root);
215
+ const choiceList = buildMenuChoiceList({ projects: rawProjects });
216
+ // Per-machine usage: the session-slug set present in each machine home's pi
217
+ // sessions dir, machine-invariant, so a shared project is credited on each.
218
+ const sessions = {};
219
+ for (const name of listMachineNames(env)) {
220
+ sessions[name] = readDirNames(machineSessionsDir(env, name));
221
+ }
222
+ // The current machine may be brand-new (no sessions dir yet); an absent entry
223
+ // reads as "new for it" in deriveProjectUsage.
224
+ if (sessions[machine.name] === undefined)
225
+ sessions[machine.name] = [];
226
+ const usage = deriveProjectUsage({
227
+ projects: choiceList.projects,
228
+ currentMachine: machine.name,
229
+ sessions,
230
+ });
231
+ const entries = buildMenuEntries({ choiceList, usage });
232
+ const picked = select(entries, {
233
+ header: `anon-pi: machine "${machine.name}" (\u2191/\u2193 move, Enter select, Ctrl-C quit)`,
234
+ });
235
+ if (picked === undefined) {
236
+ // Ctrl-C / EOF: a clean quit, nothing launched (the terminal is restored).
237
+ process.stderr.write('anon-pi: cancelled; nothing launched.\n');
238
+ return 130; // 128 + SIGINT, the conventional Ctrl-C exit code.
239
+ }
240
+ // Turn the pick into a concrete launch intent, then re-resolve + execute it
241
+ // EXACTLY as the equivalent direct command would (same resolveRunPlan path).
242
+ let launchIntent;
243
+ switch (picked.kind) {
244
+ case 'project':
245
+ case 'here':
246
+ launchIntent = { ...intent, mode: 'pi', project: picked.project };
247
+ break;
248
+ case 'shell':
249
+ launchIntent = { ...intent, mode: 'shell', project: undefined };
250
+ break;
251
+ case 'new': {
252
+ const name = promptNewProject();
253
+ if (name === undefined)
254
+ return 1;
255
+ launchIntent = { ...intent, mode: 'pi', project: name };
256
+ break;
257
+ }
258
+ }
259
+ let plan;
260
+ try {
261
+ plan = resolveRunPlan(launchIntent, homeFresh);
262
+ }
263
+ catch (e) {
264
+ return reportAnonPiError(e);
265
+ }
266
+ // A menu pick is always a concrete launch (never the menu marker again).
267
+ if (plan.kind !== 'launch') {
268
+ process.stderr.write('anon-pi: internal error resolving the menu pick.\n');
99
269
  return 1;
100
270
  }
101
- // Propagate netcage's exit code (which itself propagates the tool's).
102
- return res.status ?? 1;
271
+ return executeLaunchPlan(launchIntent, plan);
103
272
  }
104
- // --- anon-pi import : write the seed models.json ----------------------------
105
- function runImport(args) {
106
- const force = args.includes('--force') || args.includes('-f');
107
- const stray = args.filter((a) => a.startsWith('-') && a !== '--force' && a !== '-f');
108
- if (stray.length > 0) {
109
- process.stderr.write(`anon-pi import: unknown option(s): ${stray.join(' ')}\nRun \`anon-pi --help\`.\n`);
110
- return 2;
273
+ /**
274
+ * Prompt for a NEW project name and validate it (validateName, the same guard a
275
+ * direct `anon-pi <name>` uses), so a menu-created project is a safe single
276
+ * folder segment. Returns the validated name, or undefined on an empty entry /
277
+ * EOF / a rejected name (with the error printed). TTY is guaranteed here.
278
+ */
279
+ function promptNewProject() {
280
+ const ans = promptLine('New project name (a single folder segment): ');
281
+ if (ans === undefined || ans.trim() === '') {
282
+ process.stderr.write('anon-pi: no name given; nothing launched.\n');
283
+ return undefined;
284
+ }
285
+ try {
286
+ return validateName(ans.trim(), 'project');
287
+ }
288
+ catch (e) {
289
+ reportAnonPiError(e);
290
+ return undefined;
291
+ }
292
+ }
293
+ /**
294
+ * Read the entry NAMES of a directory (best-effort): the plain names of its
295
+ * direct children, or [] if the dir is absent / unreadable. Used for both the
296
+ * projects-root listing (pure buildMenuChoiceList filters it to folder-safe
297
+ * project names) and each machine's sessions dir (the session slugs present).
298
+ */
299
+ function readDirNames(dir) {
300
+ if (!existsSync(dir))
301
+ return [];
302
+ try {
303
+ return readdirSync(dir, { withFileTypes: true }).map((d) => d.name);
304
+ }
305
+ catch {
306
+ return [];
307
+ }
308
+ }
309
+ // --- the hand-rolled, zero-dependency raw-mode selector ----------------------
310
+ //
311
+ // A small supply-chain surface is on-brand for a security tool and the project
312
+ // list is short, so instead of a prompt library we drive stdin in raw mode
313
+ // ourselves: up/down (arrows or k/j) move a `>` cursor, Enter selects, Ctrl-C /
314
+ // q / Esc cancels. The active row is highlighted (reverse video). The terminal
315
+ // is ALWAYS restored (raw mode off, cursor shown) on every exit path, including
316
+ // Ctrl-C. Isolated here behind a tiny signature so a well-regarded prompt lib
317
+ // could swap in later as a localized change. This is the ONLY untested I/O in
318
+ // the menu; all logic (entries + labels) is the pure buildMenuEntries.
319
+ const ESC = '\u001b';
320
+ /**
321
+ * Present `entries` as an arrow-key list and return the chosen one, or undefined
322
+ * on cancel (Ctrl-C / q / Esc / EOF). Blocks on raw stdin; restores the terminal
323
+ * on every path. An empty entry list returns undefined immediately (nothing to
324
+ * pick), though the menu always offers at least the `.` here entry.
325
+ */
326
+ function select(entries, opts = {}) {
327
+ if (entries.length === 0)
328
+ return undefined;
329
+ const out = process.stdout;
330
+ const stdin = process.stdin;
331
+ let active = 0;
332
+ const render = (first) => {
333
+ if (!first) {
334
+ // move cursor up over the previously drawn rows to redraw in place.
335
+ out.write(`${ESC}[${entries.length}A`);
336
+ }
337
+ for (let i = 0; i < entries.length; i++) {
338
+ const selected = i === active;
339
+ const cursor = selected ? '>' : ' ';
340
+ const text = `${cursor} ${entries[i].label}`;
341
+ // clear the line, then draw; reverse-video the active row.
342
+ out.write(`${ESC}[2K`);
343
+ out.write(selected ? `${ESC}[7m${text}${ESC}[0m` : text);
344
+ out.write('\n');
345
+ }
346
+ };
347
+ const wasRaw = stdin.isRaw ?? false;
348
+ const restore = () => {
349
+ try {
350
+ if (stdin.setRawMode)
351
+ stdin.setRawMode(wasRaw);
352
+ }
353
+ catch {
354
+ /* best-effort */
355
+ }
356
+ out.write(`${ESC}[?25h`); // show the cursor again
357
+ };
358
+ if (opts.header)
359
+ out.write(opts.header + '\n');
360
+ out.write(`${ESC}[?25l`); // hide the cursor while navigating
361
+ try {
362
+ if (stdin.setRawMode)
363
+ stdin.setRawMode(true);
364
+ }
365
+ catch {
366
+ /* if raw mode is unavailable we still render + read line-ish below */
367
+ }
368
+ render(true);
369
+ const buf = Buffer.alloc(3);
370
+ for (;;) {
371
+ let n;
372
+ try {
373
+ n = readSync(0, buf, 0, 3, null);
374
+ }
375
+ catch (e) {
376
+ if (e.code === 'EAGAIN')
377
+ continue;
378
+ restore();
379
+ return undefined;
380
+ }
381
+ if (n === 0) {
382
+ restore();
383
+ return undefined; // EOF
384
+ }
385
+ const s = buf.toString('utf8', 0, n);
386
+ // Ctrl-C (ETX \x03), q, or a bare Esc: cancel.
387
+ if (s === '\u0003' || s === 'q' || s === ESC) {
388
+ restore();
389
+ return undefined;
390
+ }
391
+ // Enter (CR or LF): select the active row.
392
+ if (s === '\r' || s === '\n') {
393
+ restore();
394
+ return entries[active];
395
+ }
396
+ // Up: arrow `Esc [ A` / `Esc O A`, or k. Down: `Esc [ B` / `Esc O B`, or j.
397
+ if (s === `${ESC}[A` || s === `${ESC}OA` || s === 'k') {
398
+ active = (active - 1 + entries.length) % entries.length;
399
+ render(false);
400
+ continue;
401
+ }
402
+ if (s === `${ESC}[B` || s === `${ESC}OB` || s === 'j') {
403
+ active = (active + 1) % entries.length;
404
+ render(false);
405
+ continue;
406
+ }
407
+ // any other key: ignore, keep waiting.
408
+ }
409
+ }
410
+ // --- the `machine` verbs (thin dispatch over the pure parts) -----------------
411
+ //
412
+ // Parse the `machine <verb> …` grammar (pure parseMachineArgs), then do only the
413
+ // I/O: mkdir/write the machine layout (create), read machines/*/machine.json
414
+ // (list), rewrite machine.json + WARN (set-image), and rm the machine dir with
415
+ // the confirm/`--yes`/non-TTY discipline (rm). All validation + the machine.json
416
+ // body + the warning wording live in the pure module.
417
+ function runMachine(machineArgs) {
418
+ if (machineArgs.includes('--help') || machineArgs.includes('-h')) {
419
+ process.stdout.write(MACHINE_HELP);
420
+ return 0;
111
421
  }
112
422
  const env = envFromProcess(process.env);
113
- if (!env.llmDirect || env.llmDirect.trim() === '') {
114
- process.stderr.write('anon-pi import: set ANON_PI_LLM to the RFC1918/link-local IP[:port] of the local\n' +
115
- 'model whose provider should be imported (e.g. ANON_PI_LLM=192.168.1.150:8080).\n');
423
+ let cmd;
424
+ try {
425
+ cmd = parseMachineArgs(machineArgs);
426
+ }
427
+ catch (e) {
428
+ return reportAnonPiError(e);
429
+ }
430
+ try {
431
+ switch (cmd.verb) {
432
+ case 'create':
433
+ return machineCreate(env, cmd.name, cmd.image);
434
+ case 'list':
435
+ return machineList(env);
436
+ case 'set-image':
437
+ return machineSetImage(env, cmd.name, cmd.image);
438
+ case 'rm':
439
+ return machineRm(env, cmd.name, cmd.yes);
440
+ }
441
+ }
442
+ catch (e) {
443
+ return reportAnonPiError(e);
444
+ }
445
+ }
446
+ /**
447
+ * `machine create <name> [--image <ref>]`: write machines/<name>/{machine.json,
448
+ * home/} and PIN the image (from --image or a TTY prompt). The home is only a
449
+ * dir here; it is SEEDED on first LAUNCH, not now. Refuses to clobber an
450
+ * existing machine.
451
+ */
452
+ function machineCreate(env, name, image) {
453
+ const dir = machineDir(env, name);
454
+ if (existsSync(dir)) {
455
+ process.stderr.write(`anon-pi: machine ${JSON.stringify(name)} already exists (${dir}). ` +
456
+ 'Use `anon-pi machine set-image` to re-pin its image, or `anon-pi machine rm` first.\n');
457
+ return 1;
458
+ }
459
+ // Pin the image: --image wins; else prompt on a TTY; else it is an error (a
460
+ // machine with no image cannot launch, so we refuse a headless imageless create).
461
+ let pinned = image;
462
+ if (pinned === undefined) {
463
+ if (!process.stdin.isTTY) {
464
+ process.stderr.write('anon-pi: no image and no TTY to prompt. Pass `--image <ref>` to pin the ' +
465
+ "machine's image (a container ref with `pi` on PATH).\n");
466
+ return 1;
467
+ }
468
+ pinned = promptLine(`Image ref for machine ${JSON.stringify(name)} (a container with \`pi\` on PATH): `);
469
+ if (pinned === undefined || pinned.trim() === '') {
470
+ process.stderr.write('anon-pi: no image given; aborting create.\n');
471
+ return 1;
472
+ }
473
+ }
474
+ mkdirSync(machineHomeDir(env, name), { recursive: true });
475
+ writeFileSync(machineJsonPath(env, name), serializeMachineJson({ image: pinned }));
476
+ process.stdout.write(`anon-pi: created machine ${JSON.stringify(name)} (image ${pinned.trim()}) at ${dir}.\n` +
477
+ `Its home is seeded on first launch, e.g. \`anon-pi -m ${name} --shell\`.\n`);
478
+ return 0;
479
+ }
480
+ /**
481
+ * `machine list`: print each machine under machines/ with its pinned image
482
+ * (reading each machine's machine.json). An absent/garbage machine.json shows
483
+ * `(no image)` rather than erroring, so a hand-edited workspace still lists.
484
+ */
485
+ function machineList(env) {
486
+ const root = join(resolveAnonPiHome(env), 'machines');
487
+ const names = existsSync(root)
488
+ ? readdirSync(root, { withFileTypes: true })
489
+ .filter((d) => d.isDirectory())
490
+ .map((d) => d.name)
491
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
492
+ : [];
493
+ if (names.length === 0) {
494
+ process.stdout.write('anon-pi: no machines yet. Create one with `anon-pi machine create <name> --image <ref>`.\n');
495
+ return 0;
496
+ }
497
+ for (const name of names) {
498
+ const conf = readMachineJson(env, name);
499
+ const image = conf.image ?? '(no image)';
500
+ process.stdout.write(`${name}\t${image}\n`);
501
+ }
502
+ return 0;
503
+ }
504
+ /**
505
+ * `machine set-image <name> <ref>`: RE-PIN the image and WARN only. It does NOT
506
+ * reseed or touch the home (the home's extensions/bin were built for the OLD
507
+ * image). Preserves any per-machine projects override. The machine must exist.
508
+ */
509
+ function machineSetImage(env, name, image) {
510
+ const dir = machineDir(env, name);
511
+ if (!existsSync(dir)) {
512
+ process.stderr.write(`anon-pi: no machine ${JSON.stringify(name)} (${dir}). ` +
513
+ 'Create it first with `anon-pi machine create`.\n');
116
514
  return 1;
117
515
  }
118
- const source = resolveSourceModelsPath(env);
119
- if (!existsSync(source)) {
120
- process.stderr.write(`anon-pi import: host models.json not found at ${source}.\n` +
121
- 'Set ANON_PI_SOURCE_MODELS to your pi models.json, or run pi once to create it.\n');
516
+ const prev = readMachineJson(env, name);
517
+ writeFileSync(machineJsonPath(env, name), serializeMachineJson({ image, projects: prev.projects }));
518
+ process.stderr.write(setImageWarning(name, prev.image, image.trim()) + '\n');
519
+ return 0;
520
+ }
521
+ /**
522
+ * `machine rm <name> [--yes]`: delete the machine dir (its machine.json + home)
523
+ * after a confirm. Mirrors the destructive data-verb discipline: confirm on a
524
+ * TTY, `--yes` skips it, and a non-TTY WITHOUT `--yes` ABORTS (never deletes
525
+ * unprompted in a script). The machine must exist.
526
+ */
527
+ function machineRm(env, name, yes) {
528
+ const dir = machineDir(env, name);
529
+ if (!existsSync(dir)) {
530
+ process.stderr.write(`anon-pi: no machine ${JSON.stringify(name)} (${dir}); nothing to remove.\n`);
122
531
  return 1;
123
532
  }
124
- let hostModels;
533
+ if (!yes) {
534
+ if (!process.stdin.isTTY) {
535
+ process.stderr.write(`anon-pi: refusing to delete machine ${JSON.stringify(name)} without a TTY to confirm. ` +
536
+ 'Re-run with `--yes` to delete it (its home + conversations) non-interactively.\n');
537
+ return 1;
538
+ }
539
+ const answer = promptLine(`Delete machine ${JSON.stringify(name)} and its home (conversations, config) at ${dir}? [y/N] `);
540
+ if (answer === undefined || !/^y(es)?$/i.test(answer.trim())) {
541
+ process.stderr.write('anon-pi: aborted; nothing deleted.\n');
542
+ return 1;
543
+ }
544
+ }
545
+ rmSync(dir, { recursive: true, force: true });
546
+ process.stdout.write(`anon-pi: removed machine ${JSON.stringify(name)} (${dir}).\n`);
547
+ return 0;
548
+ }
549
+ // --- the destructive cleanup verbs (thin I/O over the pure resolvers) --------
550
+ //
551
+ // `--delete-home [<machine>]` and `--delete-project <project>` REPLACE the old
552
+ // `--fresh`. The pure module resolves the affected host paths (resolveDeleteHome
553
+ // / resolveDeleteProject); the CLI does ONLY the I/O: read config (for the
554
+ // default machine + the projects root), filter the resolved paths to those that
555
+ // exist, run the shared confirm/`--yes`/non-TTY discipline, then `rm`.
556
+ /**
557
+ * Parse the shared `[<positional>] [--yes|-y]` tail of a data verb. Returns the
558
+ * (optional) positional (a machine or project name) + the `--yes` flag, or an
559
+ * AnonPiError-style exit for an unknown flag / an extra positional.
560
+ */
561
+ function parseDeleteArgs(args, verb) {
562
+ let name;
563
+ let yes = false;
564
+ for (const a of args) {
565
+ if (a === '--yes' || a === '-y') {
566
+ yes = true;
567
+ continue;
568
+ }
569
+ if (a.startsWith('-')) {
570
+ process.stderr.write(`anon-pi: unknown option for ${verb}: ${a}. Run \`anon-pi --help\`.\n`);
571
+ return 1;
572
+ }
573
+ if (name !== undefined) {
574
+ process.stderr.write(`anon-pi: ${verb} takes one name, got extra: ${a}. Run \`anon-pi --help\`.\n`);
575
+ return 1;
576
+ }
577
+ name = a;
578
+ }
579
+ return { name, yes };
580
+ }
581
+ /**
582
+ * Run the confirm/`--yes`/non-TTY discipline for a destructive delete: `--yes`
583
+ * skips the prompt; a non-TTY WITHOUT `--yes` ABORTS (never deletes unprompted
584
+ * in a script); a TTY prompts `[y/N]`. Returns true to PROCEED, false to abort
585
+ * (the caller has already printed nothing; this prints the abort/refusal note).
586
+ */
587
+ function confirmDelete(what, yes) {
588
+ if (yes)
589
+ return true;
590
+ if (!process.stdin.isTTY) {
591
+ process.stderr.write(`anon-pi: refusing to delete ${what} without a TTY to confirm. ` +
592
+ 'Re-run with `--yes` to delete it non-interactively.\n');
593
+ return false;
594
+ }
595
+ const answer = promptLine(`Delete ${what}? [y/N] `);
596
+ if (answer === undefined || !/^y(es)?$/i.test(answer.trim())) {
597
+ process.stderr.write('anon-pi: aborted; nothing deleted.\n');
598
+ return false;
599
+ }
600
+ return true;
601
+ }
602
+ /**
603
+ * `--delete-home [<machine>]`: delete ONE machine's HOME (config + convos + shell
604
+ * env), keeping its machine.json image pin (so it can be relaunched to reseed a
605
+ * fresh home) and ALL project files (they live under the projects root). Default
606
+ * machine (config.defaultMachine, else the built-in DEFAULT_MACHINE) when the
607
+ * name is omitted. Confirm / `--yes` / non-TTY abort.
608
+ */
609
+ function runDeleteHome(args) {
610
+ if (args.includes('--help') || args.includes('-h')) {
611
+ process.stdout.write(HELP);
612
+ return 0;
613
+ }
614
+ const env = envFromProcess(process.env);
615
+ const parsed = parseDeleteArgs(args, '--delete-home');
616
+ if (typeof parsed === 'number')
617
+ return parsed;
618
+ const config = readJsonConfig(env);
619
+ const machine = parsed.name ?? config.defaultMachine ?? DEFAULT_MACHINE;
620
+ let plan;
125
621
  try {
126
- hostModels = JSON.parse(readFileSync(source, 'utf8'));
622
+ plan = resolveDeleteHome(env, machine);
127
623
  }
128
624
  catch (e) {
129
- process.stderr.write(`anon-pi import: could not parse ${source}: ${e.message}\n`);
625
+ return reportAnonPiError(e);
626
+ }
627
+ if (!existsSync(plan.home)) {
628
+ process.stderr.write(`anon-pi: no home for machine ${JSON.stringify(plan.machine)} (${plan.home}); nothing to delete.\n`);
629
+ return 1;
630
+ }
631
+ if (!confirmDelete(`machine ${JSON.stringify(plan.machine)} home (conversations + config) at ${plan.home}`, parsed.yes)) {
632
+ return 1;
633
+ }
634
+ rmSync(plan.home, { recursive: true, force: true });
635
+ process.stdout.write(`anon-pi: deleted machine ${JSON.stringify(plan.machine)} home (${plan.home}). ` +
636
+ 'Its image pin is kept; relaunch to seed a fresh home.\n');
637
+ return 0;
638
+ }
639
+ /**
640
+ * `--delete-project <project>`: delete the project's FILES (its folder under the
641
+ * resolved projects root) AND that project's per-machine session dir in EVERY
642
+ * machine home (the machine-invariant slug), keeping the homes otherwise intact.
643
+ * Confirm / `--yes` / non-TTY abort. The project name is REQUIRED.
644
+ */
645
+ function runDeleteProject(args) {
646
+ if (args.includes('--help') || args.includes('-h')) {
647
+ process.stdout.write(HELP);
648
+ return 0;
649
+ }
650
+ const env = envFromProcess(process.env);
651
+ const parsed = parseDeleteArgs(args, '--delete-project');
652
+ if (typeof parsed === 'number')
653
+ return parsed;
654
+ if (parsed.name === undefined) {
655
+ process.stderr.write('anon-pi: --delete-project needs a <project>. Run `anon-pi --help`.\n');
130
656
  return 1;
131
657
  }
132
- let result;
658
+ const config = readJsonConfig(env);
659
+ // The RESOLVED projects root (config/env override, else the built-in). No
660
+ // --mount here: a data verb targets the durable projects root, not a per-run
661
+ // host parent.
662
+ const projectsRoot = resolveProjectsRoot({ env, config });
663
+ const machines = listMachineNames(env);
664
+ let plan;
133
665
  try {
134
- result = pickProviderForLlm(hostModels, env.llmDirect);
666
+ plan = resolveDeleteProject({
667
+ env,
668
+ project: parsed.name,
669
+ projectsRoot,
670
+ machines,
671
+ });
135
672
  }
136
673
  catch (e) {
137
- if (e instanceof AnonPiError) {
138
- process.stderr.write(e.message + '\n');
139
- return 1;
140
- }
141
- throw e;
674
+ return reportAnonPiError(e);
142
675
  }
143
- const seedDir = resolveConfigSeed(env);
144
- const dest = join(seedDir, MODELS_FILE);
145
- if (existsSync(dest) && !force) {
146
- process.stderr.write(`anon-pi import: ${dest} already exists. Re-run with --force to overwrite.\n`);
676
+ // Only the paths that actually exist: the folder (maybe absent) + whichever
677
+ // machine homes hold this project's session dir.
678
+ const targets = [plan.folder, ...plan.sessions].filter((p) => existsSync(p));
679
+ if (targets.length === 0) {
680
+ process.stderr.write(`anon-pi: no files or sessions found for project ${JSON.stringify(plan.project)} ` +
681
+ `(looked in ${plan.folder} and each machine home); nothing to delete.\n`);
147
682
  return 1;
148
683
  }
149
- if (result.apiKeyLooksReal) {
150
- process.stderr.write(`anon-pi import: WARNING: provider "${result.name}" carries a real-looking apiKey; it\n` +
151
- 'will be written into the seed. For a local model this is usually fine, but review\n' +
152
- `${dest} if that key identifies you.\n`);
684
+ const sessionCount = targets.length - (existsSync(plan.folder) ? 1 : 0);
685
+ if (!confirmDelete(`project ${JSON.stringify(plan.project)}: its files (${plan.folder}) ` +
686
+ `and ${sessionCount} per-machine session dir(s)`, parsed.yes)) {
687
+ return 1;
153
688
  }
154
- mkdirSync(seedDir, { recursive: true });
155
- writeFileSync(dest, JSON.stringify(result.models, null, 2) + '\n');
156
- process.stderr.write(`anon-pi import: wrote ${dest} (provider "${result.name}"). Run \`anon-pi\` to launch.\n`);
689
+ for (const p of targets)
690
+ rmSync(p, { recursive: true, force: true });
691
+ process.stdout.write(`anon-pi: deleted project ${JSON.stringify(plan.project)} ` +
692
+ `(files + ${sessionCount} per-machine session dir(s)). The machine homes are kept.\n`);
157
693
  return 0;
158
694
  }
695
+ // --- `anon-pi init` onboarding (thin I/O over the pure detect/verify decisions) --
696
+ //
697
+ // init is the HONEST, re-runnable onboarding. It captures the socks5h PROXY (by
698
+ // evidence: open ports + a real SOCKS5 handshake + a real `netcage verify` exit
699
+ // IP, NEVER a provider label), the local-model ENDPOINT (generating models.json
700
+ // from it), and the default machine IMAGE (menu from shipped Dockerfiles / an
701
+ // existing ref / skip, building via `podman build`), then writes config.json +
702
+ // the `default` machine. It REPLACES the old `import`. All the DECISIONS are
703
+ // pure (anon-pi.ts); this does only the socket probes, the netcage/podman
704
+ // spawns, and the prompts. It NEVER destroys machines/homes: it pre-fills
705
+ // current values and only ADDS/updates config + a fresh default machine.
706
+ const INIT_HELP = `anon-pi init - onboard: verify your proxy, capture your local model, pick an image
707
+
708
+ USAGE
709
+ anon-pi init interactive onboarding (re-runnable reconfigure)
710
+
711
+ WHAT IT DOES
712
+ 1. PROXY: probes common SOCKS ports, confirms SOCKS5 via a real handshake,
713
+ shows the findings (EVIDENCE only, never a provider label), then runs
714
+ \`netcage verify\` and shows the real EXIT IP as proof. You confirm.
715
+ 2. LOCAL MODEL: captures host:port, probes reachability, generates models.json.
716
+ 3. IMAGE: pick a shipped Dockerfile (built via podman), an existing ref, or skip.
717
+ Then writes ~/.anon-pi/config.json + the \`default\` machine. Never destroys homes.
718
+ `;
719
+ function runInit(args) {
720
+ if (args.includes('--help') || args.includes('-h')) {
721
+ process.stdout.write(INIT_HELP);
722
+ return 0;
723
+ }
724
+ if (args.length > 0) {
725
+ process.stderr.write(`anon-pi: init takes no arguments, got: ${args.join(' ')}. Run \`anon-pi init --help\`.\n`);
726
+ return 1;
727
+ }
728
+ if (!process.stdin.isTTY) {
729
+ process.stderr.write('anon-pi: init is interactive and needs a TTY. Run it in a terminal. To set\n' +
730
+ 'values non-interactively, write ~/.anon-pi/config.json + a machine.json by hand,\n' +
731
+ 'or export ANON_PI_PROXY / ANON_PI_LLM (they override config.json).\n');
732
+ return 1;
733
+ }
734
+ const env = envFromProcess(process.env);
735
+ // Pre-fill from the CURRENT config (re-runnable: init doubles as reconfigure).
736
+ const current = readJsonConfig(env);
737
+ process.stdout.write('anon-pi init: honest, evidence-based onboarding. Nothing is destroyed; your\n' +
738
+ 'current values are pre-filled. Press Ctrl-C to abort at any prompt.\n\n');
739
+ // 1) PROXY: probe + handshake + findings + netcage verify + confirm.
740
+ const proxyHostPort = initProxyStep(current.proxy);
741
+ if (proxyHostPort === undefined)
742
+ return 1;
743
+ const proxyUrl = socks5hUrl(proxyHostPort);
744
+ // 2) LOCAL MODEL endpoint: capture + probe + generate models.json.
745
+ const llm = initLlmStep(current.llm);
746
+ // llm may be undefined if the user skipped it (the launch path still errors
747
+ // without one, but init lets you set it later; we do not force it here).
748
+ // 3) DEFAULT MACHINE IMAGE: menu (shipped Dockerfiles / existing ref / skip).
749
+ const image = initImageStep();
750
+ if (image === ABORT)
751
+ return 1;
752
+ // 4) WRITE config.json + the `default` machine (never destroying an existing
753
+ // home). The proxy is always present (we only reach here on a chosen proxy).
754
+ const anonHome = resolveAnonPiHome(env);
755
+ mkdirSync(anonHome, { recursive: true });
756
+ const configPath = join(anonHome, 'config.json');
757
+ const nextConfig = {
758
+ proxy: proxyUrl,
759
+ llm: llm ?? current.llm,
760
+ defaultMachine: current.defaultMachine ?? DEFAULT_MACHINE,
761
+ projects: current.projects,
762
+ };
763
+ writeFileSync(configPath, serializeConfigJson(nextConfig));
764
+ process.stdout.write(`\nanon-pi: wrote ${configPath}.\n`);
765
+ // The `default` machine: create it if absent (NEVER wipe an existing home),
766
+ // pin/re-pin its image when one was chosen. Its home seeds on first launch.
767
+ initWriteDefaultMachine(env, image);
768
+ // The per-machine models.json seed for the default machine, generated from the
769
+ // captured endpoint (this is the `import` replacement). Only when we have an
770
+ // endpoint; written next to the machine so the first-launch seed mounts it.
771
+ if ((llm ?? current.llm) !== undefined) {
772
+ const mdir = machineDir(env, DEFAULT_MACHINE);
773
+ mkdirSync(mdir, { recursive: true });
774
+ const models = generateModelsJson((llm ?? current.llm));
775
+ writeFileSync(join(mdir, MODELS_FILE), JSON.stringify(models, null, '\t') + '\n');
776
+ process.stdout.write(`anon-pi: wrote the local-model models.json for machine "${DEFAULT_MACHINE}".\n`);
777
+ }
778
+ process.stdout.write('\nanon-pi: onboarding complete. Launch with `anon-pi <project>` or ' +
779
+ '`anon-pi --shell`.\n');
780
+ return 0;
781
+ }
782
+ /** A sentinel a step returns when the user aborted (distinct from "skipped"). */
783
+ const ABORT = Symbol('abort');
784
+ /**
785
+ * The PROXY step: probe the default SOCKS ports, confirm SOCKS5 via a real
786
+ * handshake, show the EVIDENCE (never a provider label), let the user CHOOSE a
787
+ * SOCKS5-confirmed port or enter host:port, then run `netcage verify` and show
788
+ * the real EXIT IP before confirming. Returns the chosen host:port, or undefined
789
+ * on abort. The socket probes + the netcage spawn are the only I/O; the display
790
+ * + the handshake verdict come from the pure module.
791
+ */
792
+ function initProxyStep(currentProxy) {
793
+ process.stdout.write('Step 1/3 - proxy (the socks5h endpoint that anonymizes egress)\n');
794
+ if (currentProxy) {
795
+ process.stdout.write(` current: ${currentProxy}\n`);
796
+ }
797
+ process.stdout.write(' Probing common SOCKS ports (evidence only)...\n');
798
+ // Probe each default port: TCP-open + a real SOCKS5 handshake. The weak
799
+ // process hint (a running `tor`/`wireproxy` LOCAL process, never the exit
800
+ // provider) is HOST-WIDE, so gather it ONCE and pass it as the formatter's
801
+ // single general note rather than gluing it onto every port line. The display
802
+ // is the PURE formatter's job.
803
+ const runningProcesses = observeRunningProcesses();
804
+ const processNote = matchProcessHint(runningProcesses);
805
+ const findings = DEFAULT_SOCKS_PROBE_PORTS.map(({ port, hint }) => {
806
+ const { open, handshake } = probeSocks5('127.0.0.1', port);
807
+ return {
808
+ host: '127.0.0.1',
809
+ port,
810
+ open,
811
+ handshake,
812
+ portHint: hint,
813
+ };
814
+ });
815
+ process.stdout.write('\n' + formatProxyFindings(findings, processNote) + '\n\n');
816
+ // Offer the SOCKS5-confirmed candidates as quick picks; always allow a manual
817
+ // host:port entry (and pre-fill the current one).
818
+ const confirmed = findings.filter((f) => f.open && f.handshake?.socks5);
819
+ for (;;) {
820
+ if (confirmed.length > 0) {
821
+ process.stdout.write('SOCKS5-confirmed ports:\n');
822
+ confirmed.forEach((f, i) => {
823
+ process.stdout.write(` [${i + 1}] ${f.host}:${f.port}\n`);
824
+ });
825
+ }
826
+ const prefill = currentProxy
827
+ ? ` (or Enter to keep ${hostPortKey(currentProxy)})`
828
+ : '';
829
+ const ans = promptLine(`Choose a number, or enter host:port${prefill}: `);
830
+ if (ans === undefined) {
831
+ process.stderr.write('anon-pi: aborted; nothing written.\n');
832
+ return undefined;
833
+ }
834
+ const trimmed = ans.trim();
835
+ let chosen;
836
+ if (trimmed === '' && currentProxy) {
837
+ chosen = hostPortKey(currentProxy);
838
+ }
839
+ else if (/^\d+$/.test(trimmed) && confirmed.length > 0) {
840
+ const idx = Number(trimmed) - 1;
841
+ if (idx >= 0 && idx < confirmed.length) {
842
+ const f = confirmed[idx];
843
+ chosen = `${f.host}:${f.port}`;
844
+ }
845
+ }
846
+ else if (trimmed !== '') {
847
+ chosen = hostPortKey(trimmed);
848
+ }
849
+ if (chosen === undefined || chosen === '') {
850
+ process.stdout.write(' Please pick a listed number or enter a host:port.\n');
851
+ continue;
852
+ }
853
+ // VERIFY: run `netcage verify --proxy socks5h://<chosen>` and show the real
854
+ // exit IP as evidence it is NOT the host IP. The user confirms ON that
855
+ // evidence. netcage never announces the provider, so neither do we.
856
+ const url = socks5hUrl(chosen);
857
+ process.stdout.write(`\n Verifying via netcage: netcage verify --proxy ${url}\n`);
858
+ if (!hasNetcage()) {
859
+ process.stderr.write('anon-pi: `netcage` not found on PATH, cannot verify the exit IP. Install\n' +
860
+ 'it first (https://github.com/wighawag/netcage). Linux only.\n');
861
+ return undefined;
862
+ }
863
+ const verify = spawnSync('netcage', ['verify', '--proxy', url], {
864
+ encoding: 'utf8',
865
+ });
866
+ const output = `${verify.stdout ?? ''}${verify.stderr ?? ''}`;
867
+ if (verify.error || verify.status !== 0) {
868
+ process.stdout.write(output.trimEnd() + '\n');
869
+ process.stdout.write(` netcage verify FAILED for ${url} (exit ${verify.status ?? 'n/a'}). ` +
870
+ 'Pick another port or fix the proxy.\n\n');
871
+ continue;
872
+ }
873
+ const exitIp = parseVerifyExitIp(output);
874
+ if (exitIp) {
875
+ process.stdout.write(` Exit IP (via the proxy, NOT your host): ${exitIp}\n`);
876
+ }
877
+ else {
878
+ process.stdout.write(' netcage verify succeeded but no exit IP was parsed; raw output:\n' +
879
+ output.trimEnd() +
880
+ '\n');
881
+ }
882
+ const ok = promptLine(` Use ${url} as your proxy? [Y/n] `);
883
+ if (ok === undefined) {
884
+ process.stderr.write('anon-pi: aborted; nothing written.\n');
885
+ return undefined;
886
+ }
887
+ if (/^n(o)?$/i.test(ok.trim())) {
888
+ process.stdout.write(' OK, pick another.\n\n');
889
+ continue;
890
+ }
891
+ return chosen;
892
+ }
893
+ }
894
+ /**
895
+ * The LOCAL MODEL step: capture host:port (pre-filled from config), probe TCP
896
+ * reachability (evidence, not a gate), and return the endpoint (undefined if the
897
+ * user skips it). models.json is generated from it by runInit. The one direct
898
+ * hole; all other egress stays proxied.
899
+ */
900
+ function initLlmStep(currentLlm) {
901
+ process.stdout.write('\nStep 2/3 - local model endpoint (the ONE direct hole)\n');
902
+ if (currentLlm)
903
+ process.stdout.write(` current: ${currentLlm}\n`);
904
+ const prefill = currentLlm
905
+ ? ` (or Enter to keep ${currentLlm})`
906
+ : ' (or Enter to skip)';
907
+ const ans = promptLine(` Local model host:port, e.g. 192.168.1.150:8080${prefill}: `);
908
+ if (ans === undefined)
909
+ return currentLlm;
910
+ const trimmed = ans.trim();
911
+ if (trimmed === '')
912
+ return currentLlm;
913
+ const endpoint = trimmed;
914
+ // Probe reachability: evidence only. A closed port is not fatal (the model may
915
+ // start later); we just report it.
916
+ const key = hostPortKey(endpoint);
917
+ const colon = key.lastIndexOf(':');
918
+ const host = colon > 0 ? key.slice(0, colon) : key;
919
+ const port = colon > 0 ? Number(key.slice(colon + 1)) : 80;
920
+ if (Number.isFinite(port)) {
921
+ const reachable = probeTcp(host, port);
922
+ process.stdout.write(reachable
923
+ ? ` reachable: ${host}:${port} accepted a TCP connection.\n`
924
+ : ` note: ${host}:${port} did not accept a connection now (the model may not be up yet).\n`);
925
+ }
926
+ return endpoint;
927
+ }
928
+ /**
929
+ * The IMAGE step: the pure menu (shipped Dockerfiles / existing ref / skip), then
930
+ * the impure action for the pick (build via `podman build`, take a ref, or
931
+ * skip). Returns the resolved image ref, undefined for skip, or ABORT.
932
+ */
933
+ function initImageStep() {
934
+ process.stdout.write('\nStep 3/3 - default machine image (an image with `pi` on PATH)\n');
935
+ const menu = initImageMenu();
936
+ menu.forEach((e, i) => {
937
+ process.stdout.write(` [${i + 1}] ${e.label}\n`);
938
+ });
939
+ for (;;) {
940
+ const ans = promptLine(' Choose [1-4]: ');
941
+ if (ans === undefined)
942
+ return ABORT;
943
+ const idx = Number(ans.trim()) - 1;
944
+ if (!Number.isInteger(idx) || idx < 0 || idx >= menu.length) {
945
+ process.stdout.write(' Please pick a number 1-4.\n');
946
+ continue;
947
+ }
948
+ const choice = menu[idx].choice;
949
+ if (choice === 'skip') {
950
+ process.stdout.write(' Skipping the image; pin it later with `anon-pi machine set-image`.\n');
951
+ return undefined;
952
+ }
953
+ if (choice === 'existing') {
954
+ const ref = promptLine(' Image ref (a container with `pi` on PATH): ');
955
+ if (ref === undefined || ref.trim() === '') {
956
+ process.stdout.write(' No ref given; pick again.\n');
957
+ continue;
958
+ }
959
+ return ref.trim();
960
+ }
961
+ // basic | webveil: build the shipped Dockerfile via `podman build`.
962
+ const dockerfile = choice === 'basic'
963
+ ? shippedDockerfilePath()
964
+ : shippedWebveilDockerfilePath();
965
+ if (dockerfile === undefined || !existsSync(dockerfile)) {
966
+ process.stderr.write(` anon-pi: could not locate the shipped ${choice === 'basic' ? 'Dockerfile.pi' : 'examples/Dockerfile.pi-webveil'}. ` +
967
+ 'Pick an existing ref instead.\n');
968
+ continue;
969
+ }
970
+ const tag = choice === 'basic' ? 'anon-pi/pi:latest' : 'anon-pi/pi-webveil:latest';
971
+ const built = buildImage(dockerfile, tag);
972
+ if (!built) {
973
+ process.stdout.write(' Build failed; pick another option.\n');
974
+ continue;
975
+ }
976
+ return tag;
977
+ }
978
+ }
979
+ /**
980
+ * Create or update the `default` machine: create it (dir + machine.json) if
981
+ * absent, pinning the chosen image; if it already exists, re-pin the image only
982
+ * when one was chosen (preserving any per-machine projects override), and NEVER
983
+ * touch its home (init is non-destructive). A skipped image leaves an existing
984
+ * machine's image as-is, or creates an imageless machine.
985
+ */
986
+ function initWriteDefaultMachine(env, image) {
987
+ const name = DEFAULT_MACHINE;
988
+ const dir = machineDir(env, name);
989
+ const existed = existsSync(dir);
990
+ mkdirSync(machineHomeDir(env, name), { recursive: true });
991
+ if (!existed) {
992
+ writeFileSync(machineJsonPath(env, name), serializeMachineJson({ image }));
993
+ process.stdout.write(`anon-pi: created machine "${name}"${image ? ` (image ${image})` : ' (imageless; pin it later)'} at ${dir}.\n`);
994
+ return;
995
+ }
996
+ // Existing machine: re-pin only if a new image was chosen; keep its projects
997
+ // override and its home untouched.
998
+ const prev = readMachineJson(env, name);
999
+ if (image !== undefined) {
1000
+ writeFileSync(machineJsonPath(env, name), serializeMachineJson({ image, projects: prev.projects }));
1001
+ process.stdout.write(`anon-pi: re-pinned machine "${name}" image to ${image} (home kept intact).\n`);
1002
+ }
1003
+ else {
1004
+ process.stdout.write(`anon-pi: machine "${name}" already exists; kept its image + home.\n`);
1005
+ }
1006
+ }
1007
+ // --- init's thin I/O primitives (socket probes, process observe, podman build) --
1008
+ /**
1009
+ * Probe a TCP port for openness AND a SOCKS5 handshake: connect, send the
1010
+ * no-auth method-selection greeting, read the reply, and interpret it with the
1011
+ * PURE interpretSocks5Handshake. Fully synchronous + best-effort with a short
1012
+ * timeout so init stays a simple linear prompt flow. On any connect failure the
1013
+ * port is `open: false` with no handshake.
1014
+ */
1015
+ function probeSocks5(host, port) {
1016
+ // A synchronous SOCKS5 probe: node's net is async, so we drive a tiny state
1017
+ // machine over a blocking loop using a short deadline. To keep it simple and
1018
+ // dependency-free we use a child `bash`+`/dev/tcp`-style probe is unavailable
1019
+ // portably, so instead we do a promise-free spin with a hard cap via a
1020
+ // separate helper that returns synchronously.
1021
+ const reply = socks5Handshake(host, port, SOCKS5_METHOD_SELECTOR, 600);
1022
+ if (reply === undefined)
1023
+ return { open: false };
1024
+ return { open: true, handshake: interpretSocks5Handshake(reply) };
1025
+ }
1026
+ /**
1027
+ * Best-effort synchronous SOCKS5 handshake: open a TCP connection, write the
1028
+ * greeting, and collect the reply bytes, blocking up to `timeoutMs`. Returns the
1029
+ * reply bytes when the connection opened (possibly empty if the server sent
1030
+ * nothing), or undefined when the connection could not be opened at all (port
1031
+ * closed / refused). Implemented with a nested event loop drained via a shared
1032
+ * flag, so the caller stays a simple linear script.
1033
+ */
1034
+ function socks5Handshake(host, port, greeting, timeoutMs) {
1035
+ // node has no synchronous socket API; run a tiny worker via execFileSync on
1036
+ // the same node binary so the probe is fully synchronous and portable. The
1037
+ // worker connects, sends the greeting, reads up to 2 bytes, and prints them as
1038
+ // JSON (or prints "null" when the connection was refused).
1039
+ const script = `const net=require('net');` +
1040
+ `const s=net.connect({host:${JSON.stringify(host)},port:${port}});` +
1041
+ `let done=false;const bytes=[];` +
1042
+ `const fin=(v)=>{if(done)return;done=true;try{s.destroy()}catch(e){}` +
1043
+ `process.stdout.write(JSON.stringify(v));process.exit(0)};` +
1044
+ `s.setTimeout(${timeoutMs});` +
1045
+ `s.on('connect',()=>{s.write(Buffer.from(${JSON.stringify([...greeting])}))});` +
1046
+ `s.on('data',(d)=>{for(const b of d)bytes.push(b);if(bytes.length>=2)fin(bytes)});` +
1047
+ `s.on('timeout',()=>fin(bytes));` +
1048
+ `s.on('error',()=>fin(null));` +
1049
+ `s.on('close',()=>fin(bytes));`;
1050
+ try {
1051
+ const out = execFileSync(process.execPath, ['-e', script], {
1052
+ encoding: 'utf8',
1053
+ timeout: timeoutMs + 1500,
1054
+ });
1055
+ const parsed = JSON.parse(out);
1056
+ return parsed === null ? undefined : parsed;
1057
+ }
1058
+ catch {
1059
+ return undefined;
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Best-effort synchronous TCP reachability probe (open a connection, succeed or
1064
+ * not) for the local-model endpoint. Reuses the socks5Handshake worker with an
1065
+ * empty greeting: a non-undefined return means the connection opened.
1066
+ */
1067
+ function probeTcp(host, port) {
1068
+ return socks5Handshake(host, port, [], 500) !== undefined;
1069
+ }
1070
+ /**
1071
+ * Observe LOCAL process names (best-effort) so init can offer WEAK hints (a
1072
+ * running `tor` -> likely Tor). Returns the lowercased process names seen, or []
1073
+ * on any failure. This is a LOCAL observation only; it never claims the exit
1074
+ * provider.
1075
+ */
1076
+ function observeRunningProcesses() {
1077
+ const res = spawnSync('ps', ['-eo', 'comm='], { encoding: 'utf8' });
1078
+ if (res.error || res.status !== 0 || !res.stdout)
1079
+ return [];
1080
+ return res.stdout
1081
+ .split('\n')
1082
+ .map((l) => l.trim().split('/').pop() ?? '')
1083
+ .filter((n) => n !== '')
1084
+ .map((n) => n.toLowerCase());
1085
+ }
1086
+ /**
1087
+ * The weak process-hint text for the observed processes, if any maps (via the
1088
+ * PURE processHint). Returns the FIRST matching hint (tor before wireproxy), or
1089
+ * undefined. Never names the exit provider.
1090
+ */
1091
+ function matchProcessHint(processes) {
1092
+ for (const p of processes) {
1093
+ const h = processHint(p);
1094
+ if (h)
1095
+ return h.hint;
1096
+ }
1097
+ return undefined;
1098
+ }
1099
+ /**
1100
+ * Build a shipped Dockerfile into `tag` via `podman build`. Streams podman's
1101
+ * output (inherited stdio) so the user sees the build. Returns true on success.
1102
+ * The build CONTEXT is the Dockerfile's own directory (the shipped examples/
1103
+ * dir or the package root), which is where its COPY sources live.
1104
+ */
1105
+ function buildImage(dockerfile, tag) {
1106
+ const context = dirname(dockerfile);
1107
+ process.stdout.write(` Building ${tag} from ${dockerfile} (podman build)...\n`);
1108
+ const res = spawnSync('podman', ['build', '-t', tag, '-f', dockerfile, context], { stdio: 'inherit' });
1109
+ if (res.error) {
1110
+ process.stderr.write(` anon-pi: failed to run podman: ${res.error.message}. Is podman installed?\n`);
1111
+ return false;
1112
+ }
1113
+ return res.status === 0;
1114
+ }
1115
+ /** List machine names (readdir of machines/), or [] if the dir is absent. */
1116
+ function listMachineNames(env) {
1117
+ const root = join(resolveAnonPiHome(env), 'machines');
1118
+ if (!existsSync(root))
1119
+ return [];
1120
+ return readdirSync(root, { withFileTypes: true })
1121
+ .filter((d) => d.isDirectory())
1122
+ .map((d) => d.name);
1123
+ }
1124
+ /**
1125
+ * Read one line from stdin synchronously for a confirm/value prompt, writing the
1126
+ * prompt to stderr first. Returns undefined on EOF/error. Only called on a TTY
1127
+ * (the verbs enforce the non-TTY discipline before prompting), so a blocking
1128
+ * byte-at-a-time read from fd 0 is fine: the user types a line and hits enter.
1129
+ */
1130
+ function promptLine(prompt) {
1131
+ process.stderr.write(prompt);
1132
+ const byte = Buffer.alloc(1);
1133
+ let line = '';
1134
+ for (;;) {
1135
+ let n;
1136
+ try {
1137
+ n = readSync(0, byte, 0, 1, null);
1138
+ }
1139
+ catch (e) {
1140
+ // EAGAIN on a non-blocking TTY: retry; anything else ends the read.
1141
+ if (e.code === 'EAGAIN')
1142
+ continue;
1143
+ break;
1144
+ }
1145
+ if (n === 0)
1146
+ break; // EOF
1147
+ const ch = byte.toString('utf8', 0, 1);
1148
+ if (ch === '\n')
1149
+ return line;
1150
+ if (ch !== '\r')
1151
+ line += ch;
1152
+ }
1153
+ return line === '' ? undefined : line;
1154
+ }
1155
+ /** The `machine` subcommand help. */
1156
+ const MACHINE_HELP = `anon-pi machine - manage machines (an image + a persistent host home)
1157
+
1158
+ USAGE
1159
+ anon-pi machine create <name> [--image <ref>] create a machine, pin its image
1160
+ anon-pi machine list list machines and their images
1161
+ anon-pi machine set-image <name> <ref> re-pin the image (WARNS; no reseed)
1162
+ anon-pi machine rm <name> [--yes] delete the machine + its home
1163
+
1164
+ A machine is an image + a persistent host home (machines/<name>/{machine.json,home/}).
1165
+ The home is seeded on FIRST LAUNCH, not at create. \`set-image\` re-pins only and
1166
+ warns (the home was built for the old image); \`rm\` confirms on a TTY, skips with
1167
+ \`--yes\`, and aborts non-interactively without it.
1168
+ `;
1169
+ // --- impure helpers ---------------------------------------------------------
1170
+ /** Read + parse <anon-pi-home>/config.json (tolerant: absent/garbage => {}). */
1171
+ function readJsonConfig(env) {
1172
+ const path = join(resolveAnonPiHome(env), 'config.json');
1173
+ return parseConfigJson(readJsonFile(path));
1174
+ }
1175
+ /** Read + parse a machine's machine.json (tolerant: absent/garbage => {}). */
1176
+ function readMachineJson(env, name) {
1177
+ return parseMachineJson(readJsonFile(machineJsonPath(env, name)));
1178
+ }
1179
+ /** Read + JSON.parse a file, returning undefined if absent or unparseable. */
1180
+ function readJsonFile(path) {
1181
+ if (!existsSync(path))
1182
+ return undefined;
1183
+ try {
1184
+ return JSON.parse(readFileSync(path, 'utf8'));
1185
+ }
1186
+ catch {
1187
+ return undefined;
1188
+ }
1189
+ }
1190
+ /**
1191
+ * True iff a machine home is FRESH (no seed marker): the seed will run. The
1192
+ * marker lives under the mounted home at `.pi/agent/<SEED_MARKER>` (the host
1193
+ * side of the container's /root/.pi/agent = CONTAINER_AGENT_DIR).
1194
+ */
1195
+ function homeFresh(machineHome) {
1196
+ const marker = join(machineHome, '.pi', 'agent', SEED_MARKER);
1197
+ return !existsSync(marker);
1198
+ }
1199
+ /**
1200
+ * Query netcage for its KEPT managed containers, surfacing each one's stamped
1201
+ * anon-pi identity key so the pure run-vs-start decision can match it. Thin,
1202
+ * best-effort I/O: on any failure (netcage missing the query, no containers, a
1203
+ * parse error) it returns an EMPTY listing, so the decision falls back to a
1204
+ * fresh `run` (safe: it never wrongly resumes, it just creates a new container).
1205
+ */
1206
+ function queryKeptContainers() {
1207
+ // Ask netcage for its managed containers as JSON, reading back the anon-pi
1208
+ // key label. netcage is a podman drop-in, so `ps` accepts the same
1209
+ // label-filter + Go-template/JSON format flags.
1210
+ const res = spawnSync('netcage', [
1211
+ 'ps',
1212
+ '-a',
1213
+ '--filter',
1214
+ 'label=netcage.managed',
1215
+ '--format',
1216
+ '{{.ID}}\t{{.Labels}}',
1217
+ ], { encoding: 'utf8' });
1218
+ if (res.error || res.status !== 0 || !res.stdout)
1219
+ return [];
1220
+ const out = [];
1221
+ for (const line of res.stdout.split('\n')) {
1222
+ const trimmed = line.trim();
1223
+ if (trimmed === '')
1224
+ continue;
1225
+ const tab = trimmed.indexOf('\t');
1226
+ if (tab < 0)
1227
+ continue;
1228
+ const ref = trimmed.slice(0, tab).trim();
1229
+ const labels = trimmed.slice(tab + 1);
1230
+ const key = extractKeyLabel(labels);
1231
+ if (ref !== '' && key !== undefined)
1232
+ out.push({ key, ref });
1233
+ }
1234
+ return out;
1235
+ }
1236
+ /**
1237
+ * Pull the anon-pi key out of a podman `{{.Labels}}` rendering (a
1238
+ * comma-separated `k=v` list). The key is stamped as `anon-pi.key=<opaque>`;
1239
+ * because keptContainerKey embeds newlines, the CLI base64-encodes it when
1240
+ * stamping (withKeyLabel) and decodes it here, so a `\n` never breaks the label.
1241
+ */
1242
+ function extractKeyLabel(labels) {
1243
+ for (const pair of labels.split(',')) {
1244
+ const eq = pair.indexOf('=');
1245
+ if (eq < 0)
1246
+ continue;
1247
+ const k = pair.slice(0, eq).trim();
1248
+ if (k !== ANON_PI_KEY_LABEL)
1249
+ continue;
1250
+ const v = pair.slice(eq + 1).trim();
1251
+ try {
1252
+ return Buffer.from(v, 'base64').toString('utf8');
1253
+ }
1254
+ catch {
1255
+ return undefined;
1256
+ }
1257
+ }
1258
+ return undefined;
1259
+ }
1260
+ /**
1261
+ * Insert the anon-pi identity label into a `netcage run` argv (right after
1262
+ * `run`), so a kept container can be found on re-entry. The key is base64'd
1263
+ * (keptContainerKey embeds newlines) to keep it a single safe label value. This
1264
+ * is ADDITIVE and touches NO egress flag (the RunPlan owns --proxy/--allow-direct).
1265
+ */
1266
+ function withKeyLabel(netcageArgs, key) {
1267
+ const enc = Buffer.from(key, 'utf8').toString('base64');
1268
+ const out = netcageArgs.slice();
1269
+ // netcageArgs[0] is 'run'; splice the label right after it.
1270
+ out.splice(1, 0, '--label', `${ANON_PI_KEY_LABEL}=${enc}`);
1271
+ return out;
1272
+ }
1273
+ /** Spawn netcage with inherited stdio; propagate its exit code. */
1274
+ function spawnNetcage(netcageArgs) {
1275
+ const res = spawnSync('netcage', netcageArgs, { stdio: 'inherit' });
1276
+ if (res.error) {
1277
+ process.stderr.write(`anon-pi: failed to run netcage: ${res.error.message}\n`);
1278
+ return 1;
1279
+ }
1280
+ return res.status ?? 1;
1281
+ }
159
1282
  function hasNetcage() {
160
1283
  const which = spawnSync(process.platform === 'win32' ? 'where' : 'command', ['-v', 'netcage'], {
161
1284
  stdio: 'ignore',
@@ -167,5 +1290,13 @@ function hasNetcage() {
167
1290
  const probe = spawnSync('netcage', ['--help'], { stdio: 'ignore' });
168
1291
  return !probe.error;
169
1292
  }
1293
+ /** Print an AnonPiError's message verbatim (exit 1) or rethrow anything else. */
1294
+ function reportAnonPiError(e) {
1295
+ if (e instanceof AnonPiError) {
1296
+ process.stderr.write(e.message + '\n');
1297
+ return 1;
1298
+ }
1299
+ throw e;
1300
+ }
170
1301
  process.exit(main(process.argv));
171
1302
  //# sourceMappingURL=cli.js.map