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