New:Socket for Asana Is Now Available.Learn more
Get Started

moshcode

Package Overview
Dependencies
Maintainers
1
Versions
60
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

moshcode - npm Package Compare versions

Comparing version
0.73.0
to
0.74.0
+175
src/autosync.mjs
// Automatic settings sync — the unattended `/load` then `/save`.
//
// PRD 0010 ruled background sync out, and the reason it gave was the right
// reason for the mechanism it had in mind: "a daemon that pushes silently is a
// daemon that overwrites silently." What makes this one allowed is that it is
// not permitted to overwrite anything. It never passes `--force`, and both
// verbs already refuse rather than guess — `/load` stops when a settings file
// changed locally since the last sync, `/save` stops on the 409 when another
// machine saved first. So the worst an unattended tick can do is decline and
// leave the decision exactly where it was: with the person at the prompt.
//
// The order is `/load` then `/save`, and that order is the whole design:
//
// - `/load` first means this machine is at the account's revision before it
// pushes, so the ordinary two-machine case settles itself and nobody is
// ever shown a conflict they would only have resolved by loading anyway.
// - When `/load` declines because there are unsaved local edits, the `/save`
// that follows pushes exactly those edits — which is the resolution the
// manual conflict message already recommends ("`/save` to keep them").
//
// Quiet is a feature. A tick that changed nothing prints nothing, because a
// line every five minutes saying "still fine" trains you to stop reading the
// pit. Three things do print: settings that arrived from another machine (your
// aliases just changed under you and you are owed that sentence), a revision
// this machine pushed, and the two states that need a human — a conflict, and
// credentials the app rejected. Network failures stay silent; a laptop on a
// train would otherwise narrate every tunnel.
import os from "node:os";
import { loadCreds } from "./auth.mjs";
import { loadCommand, saveCommand } from "./settings-sync.mjs";
/** Five minutes. Long enough that a tick is never in the way of typing. */
export const DEFAULT_INTERVAL_MS = 5 * 60 * 1000;
/**
* A floor, not a suggestion. `MOSHCODE_AUTOSYNC_MS=1` would turn the account
* into a write loop, so anything under this is treated as the minimum rather
* than refused — an env var is not the place to learn you typed milliseconds
* where you meant minutes.
*/
export const MIN_INTERVAL_MS = 30 * 1000;
/**
* Off switch, in the shape the rest of the codebase already uses for one:
* presence disables, exactly like MOSHCODE_NO_MIRROR and MOSHCODE_NO_ADS.
*/
export function autoSyncEnabled(env = process.env) {
return !env.MOSHCODE_NO_AUTOSYNC;
}
/** `Number(x) || default`, the MOSHCODE_AD_COLS idiom, with a floor. */
export function autoSyncInterval(env = process.env) {
const raw = Number(env.MOSHCODE_AUTOSYNC_MS);
if (!Number.isFinite(raw) || raw <= 0) return DEFAULT_INTERVAL_MS;
return Math.max(MIN_INTERVAL_MS, raw);
}
/**
* Run one verb and read its answer as data rather than as prose.
*
* Both commands take `--json` and emit a single object through their `write`
* sink, which is the only reason this can be quiet: it can tell "loaded four
* files" from "already at revision 9" without matching on English.
*/
async function runJson(command, argv, deps) {
const chunks = [];
const code = await command([...argv, "--json"], {
...deps,
write: (line) => chunks.push(String(line)),
});
let body = null;
try { body = JSON.parse(chunks.join("\n")); } catch { /* not our business */ }
return { code, body, status: body?.status ?? null };
}
/**
* One tick: load, then save.
*
* Returns what happened, so the caller decides what is worth a line and the
* tests can assert on the sequence without reading output.
*/
export async function syncOnce({
load = loadCommand,
save = saveCommand,
creds = loadCreds(),
write = () => {},
...deps
} = {}) {
// Logged out is not an error and must never print. A pit that has never seen
// `/login` would otherwise nag about an account its owner has not asked for,
// every five minutes, forever.
if (!creds?.token) return { skipped: "not_logged_in" };
const loaded = await runJson(load, [], { ...deps, creds });
// `local_changes` is the expected, healthy half of this: you edited an alias
// and have not saved it. `/load` correctly declined to replace it, and the
// `/save` below is what carries it up. Anything else that failed is a reason
// to stop rather than push on top of a machine we could not read.
const loadBlocked = loaded.status === "expired";
if (loadBlocked) {
write("the app rejected this machine's credentials — run `/login` again");
return { load: loaded.status, save: null };
}
if (loaded.status === "loaded") {
const count = Array.isArray(loaded.body?.files) ? loaded.body.files.length : 0;
const from = loaded.body?.from;
write(`settings synced${from ? ` from ${from}` : ""} — ${count} file${count === 1 ? "" : "s"} changed (revision ${loaded.body?.revision ?? "?"})`);
}
const saved = await runJson(save, [], { ...deps, creds });
if (saved.status === "saved") {
write(`settings saved — revision ${saved.body?.revision ?? "?"}`);
} else if (saved.status === "conflict") {
// The one case an unattended tick cannot resolve: this machine loaded, and
// the account moved again between the load and the save. Say so once and
// stop; `--force` is a decision, not a retry.
write(`another machine saved first — \`/load\` to take theirs, or \`/save --force\` to keep this machine's`);
} else if (saved.status === "expired") {
write("the app rejected this machine's credentials — run `/login` again");
}
return { load: loaded.status, save: saved.status };
}
/**
* Start the timer. Returns the function that stops it.
*
* The caller must call that on the way out: `tui()` is re-entered after an
* engine session (bin/moshcode.mjs `backToPit`), so a timer left running would
* be joined by another on the next entry, and by a third after that.
*/
export function startAutoSync({
intervalMs = autoSyncInterval(),
enabled = autoSyncEnabled(),
write = (line) => console.log(` ${line}`),
timers = { setInterval, clearInterval },
...deps
} = {}) {
if (!enabled) return () => {};
// A tick that is still running when the next one fires would race two writes
// to the same files, so ticks are single-flight rather than queued: a sync
// this machine skipped is one it does five minutes later, unchanged.
let running = false;
let stopped = false;
const tick = async () => {
if (running || stopped) return;
running = true;
try { await syncOnce({ write, ...deps }); }
catch { /* a background sync never takes the pit down with it */ }
finally { running = false; }
};
// Deliberately no tick at startup. The pit is most likely to be typed into in
// the second after it opens, and that is the worst moment to rewrite the
// aliases under it — the first sync can wait five minutes.
const handle = timers.setInterval(tick, intervalMs);
// Never hold the process open for the sake of a sync. `pty.mjs` sets the
// precedent: a piped `moshcode` that has run out of stdin should exit now,
// not at the end of the interval.
handle?.unref?.();
return () => {
stopped = true;
try { timers.clearInterval(handle); } catch { /* already gone */ }
};
}
/** Exported for the tests; the pit has no reason to care. */
export const _internals = { runJson, hostname: os.hostname };
// Installer for the tools that only ship through a system package manager.
//
// ffmpeg and ImageMagick are the odd ones in TOOLS: they are not a vendor's CLI
// with a `curl … | sh` of its own, and they are not a static binary on a GitHub
// release either. They are distro packages, which is why they are installed the
// way a distro package is installed — and why this is a separate file from
// release-install.mjs rather than another descriptor in it.
//
// Static builds do exist for both. They are third-party redistributions of
// somebody else's codec stack, unsigned, and updated by nobody in particular.
// Downloading one to avoid a sudo prompt would be trading a password for a
// binary we cannot vouch for, on the two tools most likely to be pointed at a
// file from the internet.
//
// Everything that decides *what to run* is a pure function so the per-manager
// argv (which differ in irritating ways) is unit-tested offline; the only
// impure part is the loop at the bottom that runs it.
import { spawnSync } from "node:child_process";
import { realpathSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { findEscalator } from "./escalate.mjs";
/**
* How each manager installs, non-interactively.
*
* Non-interactive is the point: this runs inside `moshcode install` and inside
* `moshcode upgrade tools`, and a manager that stops to ask "Do you want to
* continue? [Y/n]" inside an upgrade sweep parks the whole plan.
*
* apt refreshes first because its index goes stale on its own: a box that has
* not run `apt-get update` in a few months gets a 404 on the archive rather
* than a package, and the error names a URL instead of the actual problem.
*/
export const MANAGERS = {
brew: {
// Never escalated. Homebrew refuses to run as root and says so at length.
root: false,
steps: (pkg) => [["brew", ["install", pkg]]],
},
"apt-get": {
root: true,
steps: (pkg) => [
["apt-get", ["update", "-qq"]],
["apt-get", ["install", "-y", "--no-install-recommends", pkg]],
],
},
dnf: { root: true, steps: (pkg) => [["dnf", ["install", "-y", pkg]]] },
zypper: { root: true, steps: (pkg) => [["zypper", ["--non-interactive", "install", pkg]]] },
pacman: { root: true, steps: (pkg) => [["pacman", ["-S", "--needed", "--noconfirm", pkg]]] },
apk: { root: true, steps: (pkg) => [["apk", ["add", "--no-cache", pkg]]] },
};
/** The order managers are probed in. brew first, and only because of macOS. */
export const MANAGER_ORDER = ["brew", "apt-get", "dnf", "zypper", "pacman", "apk"];
/**
* Package names per tool, per manager, in the order they are worth trying.
*
* Two entries have more than one name and both are facts about somebody else's
* archive rather than hedging:
*
* Fedora ships `ffmpeg-free` in the main repositories and the full `ffmpeg`
* only from RPM Fusion, so a box without that repo enabled has exactly one of
* the two names and `dnf install ffmpeg` fails outright on it.
*
* `imagemagick` is one name for two different programs: on Ubuntu up to
* 24.04 it depends on the 6.x package and puts `convert` on PATH, and from
* 25.04 it depends on the 7.x one and puts `magick` there instead. The
* package name is stable, which is why this table has one entry and the
* tool's `bin` has two.
*/
export const PACKAGES = {
ffmpeg: {
brew: ["ffmpeg"],
"apt-get": ["ffmpeg"],
dnf: ["ffmpeg", "ffmpeg-free"],
zypper: ["ffmpeg"],
pacman: ["ffmpeg"],
apk: ["ffmpeg"],
},
imagemagick: {
brew: ["imagemagick"],
"apt-get": ["imagemagick"],
dnf: ["ImageMagick"],
zypper: ["ImageMagick"],
pacman: ["imagemagick"],
apk: ["imagemagick"],
},
};
function defaultProbe(tool) {
return spawnSync("sh", ["-c", `command -v ${tool}`], { stdio: "ignore" }).status === 0;
}
/** Resolve a name to its package table, or throw. Own properties only. */
export function resolvePackage(tool) {
const key = String(tool ?? "").trim().toLowerCase();
if (!Object.hasOwn(PACKAGES, key)) {
throw new Error(
`unknown package ${JSON.stringify(tool)} — expected one of ${Object.keys(PACKAGES).join(", ")}`,
);
}
return [key, PACKAGES[key]];
}
/** Which package manager this machine has, or null. */
export function findManager({ probe = defaultProbe, order = MANAGER_ORDER } = {}) {
for (const name of order) {
if (probe(name)) return name;
}
return null;
}
/**
* The commands that install one package name with one manager.
*
* Escalation is applied here rather than by the caller because whether a step
* needs it is a property of the manager: brew must not be escalated, the rest
* must be unless we are already root. A `null` escalator on a manager that
* needs one yields the bare command, which fails with the manager's own
* permission message — better advice than anything we would write.
*/
export function installSteps(manager, pkg, { escalator = null, isRoot = false } = {}) {
const spec = MANAGERS[manager];
if (!spec) throw new Error(`unknown package manager ${JSON.stringify(manager)}`);
const escalate = spec.root && !isRoot && escalator;
return spec.steps(pkg).map(([cmd, args]) =>
escalate ? { cmd: escalator, args: [cmd, ...args] } : { cmd, args },
);
}
/**
* Install a tool through whichever package manager is here.
*
* Package names are tried in order and the first that installs wins, because a
* name that is absent from this box's archive is a normal outcome (see the
* Fedora note above) rather than a failure to report. Only when every candidate
* has failed is there something to say.
*/
export function installPackage(tool, { run = spawnSync, probe = defaultProbe, log = console.log } = {}) {
const [key, table] = resolvePackage(tool);
const manager = findManager({ probe });
if (!manager) {
throw new Error(
`no supported package manager found (${MANAGER_ORDER.join(", ")}) — install ${key} yourself and re-run`,
);
}
const candidates = table[manager];
if (!candidates?.length) {
throw new Error(`${key} has no known package name for ${manager} — install it yourself and re-run`);
}
const isRoot = typeof process.getuid === "function" && process.getuid() === 0;
const escalator = MANAGERS[manager].root && !isRoot ? findEscalator({ probe }) : null;
const failures = [];
for (const pkg of candidates) {
log(`↓ ${manager} ${pkg}`);
let ok = true;
for (const step of installSteps(manager, pkg, { escalator, isRoot })) {
const result = run(step.cmd, step.args, { stdio: "inherit" });
if (result?.error || result?.status !== 0) {
failures.push(`${pkg}: ${step.cmd} ${step.args.join(" ")} ${result?.error ? `(${result.error.message})` : `exited ${result?.status}`}`);
ok = false;
break;
}
}
if (ok) {
log(`✓ ${key} installed with ${manager}`);
return { manager, pkg };
}
}
throw new Error(`could not install ${key} with ${manager}:\n ${failures.join("\n ")}`);
}
/** True when this file was executed directly rather than imported. */
function invokedDirectly() {
try {
return realpathSync(process.argv[1] || "") === realpathSync(fileURLToPath(import.meta.url));
} catch {
return false;
}
}
if (invokedDirectly()) {
try {
installPackage(process.argv[2]);
} catch (e) {
console.error(`install failed: ${e.message}`);
process.exit(1);
}
}
+7
-4

@@ -13,2 +13,3 @@ #!/usr/bin/env node

openSession,
primaryBin,
resolveEngine,

@@ -113,3 +114,5 @@ resolveExecutable,

description: desc,
binary: bin,
// One name, even for an entry that answers to several: `binary` is a
// documented string in this JSON and something is parsing it.
binary: primaryBin(bin),
installed,

@@ -120,3 +123,3 @@ })), null, 2));

for (const entry of entries) {
console.log(`${entry.installed ? "●" : "○"} ${entry.key.padEnd(10)} ${entry.desc}`);
console.log(`${entry.installed ? "●" : "○"} ${entry.key.padEnd(11)} ${entry.desc}`);
}

@@ -381,3 +384,3 @@ }

console.error(r.error?.code === "ENOENT"
? `alpaca isn't installed (\`${tool.bin}\`). run: moshcode install alpaca`
? `alpaca isn't installed (\`${primaryBin(tool.bin)}\`). run: moshcode install alpaca`
: `launch failed: ${r.error?.message || r.error}`);

@@ -813,3 +816,3 @@ process.exitCode = 1;

console.error(r.error?.code === "ENOENT"
? `${key} isn't installed (\`${tool.bin}\`). run: moshcode install ${key}`
? `${key} isn't installed (\`${primaryBin(tool.bin)}\`). run: moshcode install ${key}`
: `launch failed: ${r.error?.message || r.error}`);

@@ -816,0 +819,0 @@ process.exitCode = 1;

{
"name": "moshcode",
"version": "0.73.0",
"version": "0.74.0",
"type": "module",
"description": "moshcode — a metal wrapper for coding engines and native UGig/CoinPay workflow CLIs, with OpenPRD and moshscript",
"description": "moshcode \u2014 a metal wrapper for coding engines and native UGig/CoinPay workflow CLIs, with OpenPRD and moshscript",
"repository": {

@@ -7,0 +7,0 @@ "type": "git",

@@ -44,4 +44,9 @@ ---

- Continuous or background sync. Settings are edited by a person at a moment they
can name; a daemon that pushes silently is a daemon that overwrites silently.
- Background sync that can *overwrite*. This line used to rule out background
sync altogether — "a daemon that pushes silently is a daemon that overwrites
silently" — and the reasoning was right about the daemon it imagined. R10
narrows it rather than dropping it: the pit does sync on its own, and is
allowed to because it is never permitted to force. Every refusal in R3 and R4
is what makes an unattended tick safe, and a background sync that could pass
`--force` would be exactly the thing this line was written to prevent.
- Syncing engine configuration (`~/.claude.json`, `~/.codex`, MCP registrations).

@@ -66,5 +71,13 @@ Those files carry provider API keys and are owned by other tools' schemas.

logged-in account. `/load` (`moshcode load`) brings them back down.
- R2 [P0] What syncs is an allowlist, not a directory walk: `aliases.json` and
`herd/rules.json` today. `credentials.json`, `herd/sessions.json`, `sync.json`
and `pkg/` are named as never-synced and asserted in tests.
- R2 [P0] What syncs is an allowlist, not a directory walk: the pit's settings
(`aliases.json`), herd's (`herd/rules.json`, `herd/config.json`), the feed and
news subscriptions, `pricing.json`, the DNS filter's policy, and
`business.json`. `~/.moshcode` is also where moshcode installs itself and
where the account token lives, so the allowlist is load-bearing rather than
tidy. `credentials.json`, `herd/sessions.json`, `sync.json` and `pkg/` are
named as never-synced and asserted in tests, alongside the state that is
meaningless or private off its own machine: task ledgers and transcripts,
`timers.json`, `dns-filter/stats.json` (a list of blocked domains is browsing
history), listing caches, and one box's pidfiles and logs. Directory and
extension rules are enforced, not only documented.
- R3 [P0] Each save is a numbered revision. `/save` sends the revision it last

@@ -88,2 +101,12 @@ agreed on and the app refuses the write if the account has moved past it, so

`--force`).
- R10 [P1] The pit syncs on its own every five minutes: `/load` then `/save`, in
that order, never with `--force`. Loading first means the ordinary
two-machine case settles itself; when `/load` declines because of unsaved
local edits, the `/save` behind it carries exactly those edits up, which is
the resolution R4 already recommends. It is silent when logged out, silent
when nothing changed, and silent about network failure; it speaks only for
settings that arrived from another machine, a revision it pushed, and the two
states that need a person — a conflict and a rejected credential. On by
default. `MOSHCODE_NO_AUTOSYNC` turns it off, `MOSHCODE_AUTOSYNC_MS` retimes
it.

@@ -90,0 +113,0 @@ ## UX Notes

@@ -286,16 +286,32 @@ // Agentic-coding engines moshcode can install + wrap. `moshcode install <name>`

// finding the one we just installed.
/**
* The name to print when talking about a `bin` that may be several.
*
* A `bin` is normally one string. ImageMagick is why it can be a list: the
* command is `magick` on ImageMagick 7 and `convert` on 6, both are current on
* supported distros at the same time, and picking either one alone makes a
* successful install report as missing on half of them. The first name is the
* one we prefer and the one worth naming in a message.
*/
export function primaryBin(bin) {
return Array.isArray(bin) ? bin[0] : bin;
}
function executableCandidates(bin, extraDirs = []) {
const exts = process.platform === "win32" ? ["", ...(process.env.PATHEXT || ".EXE;.CMD;.BAT").split(";")] : [""];
const dirs = path.isAbsolute(bin) || bin.includes(path.sep)
? [""]
: [...(process.env.PATH || "").split(path.delimiter).filter(Boolean), ...extraDirs.filter(Boolean)];
const names = (Array.isArray(bin) ? bin : [bin]).filter(Boolean);
const seen = new Set();
const candidates = [];
for (const dir of dirs) {
for (const ext of exts) {
const candidate = dir ? path.join(dir, bin + ext) : bin + ext;
const key = candidate.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
candidates.push(candidate);
for (const name of names) {
const dirs = path.isAbsolute(name) || name.includes(path.sep)
? [""]
: [...(process.env.PATH || "").split(path.delimiter).filter(Boolean), ...extraDirs.filter(Boolean)];
for (const dir of dirs) {
for (const ext of exts) {
const candidate = dir ? path.join(dir, name + ext) : name + ext;
const key = candidate.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
candidates.push(candidate);
}
}

@@ -327,3 +343,5 @@ }

const resolved = resolveExecutable(bin, extraDirs);
if (!resolved) return { cmd: bin, args };
// Unresolved, so hand the spawn the preferred name and let it produce the
// ENOENT — a list would be spawned as a single nonsense filename.
if (!resolved) return { cmd: primaryBin(bin), args };
if (process.platform === "win32" && path.extname(resolved) === "" && nodeShebang(resolved)) {

@@ -330,0 +348,0 @@ return { cmd: process.execPath, args: [resolved, ...args] };

@@ -32,2 +32,4 @@ // Installer for the workflow CLIs that ship ONLY as GitHub release binaries.

* - doctl separates its asset fields with "-" instead of "_".
* - yt-dlp publishes the executable itself rather than an archive, so there
* is nothing to unpack; `bare` is what says so.
*/

@@ -58,2 +60,23 @@ export const RELEASES = {

},
"yt-dlp": {
repo: "yt-dlp/yt-dlp",
binary: "yt-dlp",
// The asset IS the executable — a PyInstaller bundle, so it needs no
// python on the box, and there is no archive around it to unpack.
bare: true,
// `unversioned` is not a convenience here, it is required: yt-dlp tags
// releases by date with no leading "v" (2025.08.11), so the versioned URL
// this builds otherwise — /download/v2025.08.11/ — is a 404. The
// /releases/latest/download/ alias sidesteps the tag spelling entirely.
unversioned: true,
// macOS gets one universal2 build for both architectures; Linux names arm64
// "aarch64" while every other vendor here calls it arm64.
asset: ({ platform, arch }) =>
platform === "darwin"
? "yt-dlp_macos"
: arch === "arm64"
? "yt-dlp_linux_aarch64"
: "yt-dlp_linux",
binPath: () => "yt-dlp",
},
};

@@ -156,10 +179,14 @@

writeFileSync(archive, Buffer.from(await res.arrayBuffer()));
const unpacked = path.join(work, "unpacked");
mkdirSync(unpacked);
extract(archive, unpacked);
const relative = spec.binPath(target);
const from = path.join(unpacked, relative);
if (!existsSync(from)) {
throw new Error(`${spec.binary} was not at ${relative} inside ${path.basename(archive)} — the vendor's archive layout changed`);
let from = archive;
if (!spec.bare) {
const unpacked = path.join(work, "unpacked");
mkdirSync(unpacked);
extract(archive, unpacked);
const relative = spec.binPath(target);
from = path.join(unpacked, relative);
if (!existsSync(from)) {
throw new Error(`${spec.binary} was not at ${relative} inside ${path.basename(archive)} — the vendor's archive layout changed`);
}
}

@@ -166,0 +193,0 @@

@@ -77,2 +77,24 @@ // Cloud sync for the pit's own settings — `/save` and `/load`.

{ path: "news.opml", json: false, label: "news subscriptions" },
// Herd's notification preferences — which states nag you and whether they
// ask. `rules.json` above has been carried since the first version and this
// sat next to it, unsynced, which made "my herd settings came across" true
// of half of them.
{ path: "herd/config.json", json: true, label: "herd notifications" },
// Per-model price overrides for `/cost`. Nothing writes this file; a person
// types it, once, from a pricing page — which is exactly the kind of work
// `/save` exists so you only do once.
{ path: "pricing.json", json: true, label: "cost model prices" },
// The DNS filter's policy: categories, and your own allow and block lists.
// A curated decision, not machine state — the blocklists it names are a
// cache that re-downloads itself, and `dns-filter/stats.json` next to it is
// browsing history and named below as never-synced.
{ path: "dns-filter/filter.json", json: true, label: "dns filter policy" },
// Clients, teams, rates, invoices. The largest single "start from nothing"
// on a new machine, and safe to carry because payment gateways are stored
// here as references into a vault rather than as keys (see payments.mjs).
//
// Last on purpose. The total cap is spent in this order, so the file most
// likely to grow past it goes after the small ones — otherwise a year of
// invoices silently pushes your aliases out of the snapshot.
{ path: "business.json", json: true, label: "clients, rates and invoices" },
];

@@ -95,4 +117,53 @@

"herd/hook.json",
// A billing ledger, not a preference. Two machines both appending hours and
// then both saving means the later `/save` drops the earlier one's entries,
// and it grows without bound — the two properties that make a file wrong for
// a last-write-wins sync.
"timers.json",
// "the numbers you last saw here", so that `add 3` means something. Carrying
// them would make `add 3` on another machine refer to a listing it never saw.
"news-last.json",
"news-found.json",
// Counters, and `recent[]` — the last twenty domains this machine was
// blocked from reaching. That is browsing history, and it has no business in
// a settings snapshot even one belonging to the person who generated it.
"dns-filter/stats.json",
// One box's daemon.
"moshpit-dns.pid",
"moshpit-dns.log",
];
/**
* Whole subtrees that never sync, matched by prefix.
*
* `NEVER_SYNCED` is an exact-string list, so a directory named there would be
* inert — the entries under it would not match it and would fall through. Any
* rule about a directory has to live here to have an effect.
*/
export const NEVER_SYNCED_PREFIXES = [
// The program itself. ~/.moshcode is also the install directory.
"pkg/",
// Hook reports, remote polls and per-session task ledgers: all pinned to one
// runtime, and the task ledgers carry prompt text and output artifacts.
"herd/status/",
"herd/remote/",
"herd/tasks/",
// Cached copies of published feed lists, re-fetched on demand.
"lists/",
// Downloaded blocklists. Megabytes, and self-renewing.
"dns-filter/lists/",
];
/**
* The pty substrate, by extension.
*
* The header comment above has claimed since the first version that `*.sock`
* and `*.pid` are excluded "because they describe processes on exactly one
* box". That was true of the intent and never of the code: nothing enforced
* it, and the allowlist alone happened to be doing the work. Now it is a rule.
* A transcript is the one that matters — it is a full screen capture and will
* hold whatever was typed into that session.
*/
export const NEVER_SYNCED_SUFFIXES = [".transcript", ".stdin", ".exit", ".sock", ".pid", ".log"];
/** True for a path this build is willing to read or write. */

@@ -102,3 +173,4 @@ export function isSyncable(relative) {

if (NEVER_SYNCED.includes(name)) return false;
if (name.startsWith("pkg/")) return false;
if (NEVER_SYNCED_PREFIXES.some((prefix) => name.startsWith(prefix))) return false;
if (NEVER_SYNCED_SUFFIXES.some((suffix) => name.endsWith(suffix))) return false;
return SYNCED_FILES.some((f) => f.path === name);

@@ -105,0 +177,0 @@ }

@@ -48,4 +48,8 @@ // `/timer on` … `/timer off`. The whole feature, in two words.

if (total < 60) return `${total}s`;
const h = Math.floor(total / 3600);
const m = Math.round((total % 3600) / 60);
// Round to whole minutes first, then split — computing hours and minutes off
// the raw seconds lets a remainder that rounds up to 60 (59m30s..59m59s) print
// as "60m"/"1h 60m" instead of carrying into the hour it belongs in.
const minutes = Math.round(total / 60);
const h = Math.floor(minutes / 60);
const m = minutes % 60;
if (!h) return `${m}m`;

@@ -52,0 +56,0 @@ return m ? `${h}h ${m}m` : `${h}h`;

@@ -21,2 +21,8 @@ // Adjacent workflow CLIs moshcode can install and transparently invoke.

// ffmpeg and ImageMagick ship as distro packages and nothing else — no vendor
// installer, no release binary we would trust. See src/pkg-install.mjs for why
// the static rebuilds floating around are not an option here.
const PACKAGE_INSTALLER = path.join(path.dirname(fileURLToPath(import.meta.url)), "pkg-install.mjs");
const packageInstall = (tool) => ({ cmd: process.execPath, args: [PACKAGE_INSTALLER, tool] });
export const TOOLS = {

@@ -358,2 +364,51 @@ ugig: {

},
"yt-dlp": {
desc: "yt-dlp — download video and audio from a URL (a thousand sites, not just YouTube)",
bin: "yt-dlp",
// The three tools below are not workflow CLIs like everything above: they
// are the media toolchain `cli-tools` builds on. `dl` is a front for
// yt-dlp, `vid` for ffmpeg and `img` for ImageMagick, and all three used to
// tell you to go and install a system package by hand. Now the same
// registry that installs cli-tools can install what it runs on.
//
// A PyInstaller bundle from the project's own releases, so it needs no
// python and no package manager, and it lands in ~/.local/bin like
// gh/supabase/doctl. Distro packages of yt-dlp are the one thing worth
// avoiding here: extractors break whenever a site changes, upstream ships a
// fix within days, and a distro package is frozen for the life of a release.
install: releaseInstall("yt-dlp"),
// Which is also why the upgrade is yt-dlp's own `-U` rather than a
// re-download: it is the update path the project documents, it checks
// before it fetches, and it is the one an operator will reach for anyway.
// On a yt-dlp that came from a package manager instead, `-U` declines and
// says so, which is the correct answer rather than a failure.
upgrade: { cmd: "yt-dlp", args: ["-U"] },
// Same gap turso, gradient and kimi have: nothing appends to PATH.
binDirs: [path.join(homedir(), ".local", "bin")],
},
ffmpeg: {
desc: "ffmpeg — convert, cut, scale and inspect audio and video",
bin: "ffmpeg",
// Through the distro package manager, which means root everywhere but
// macOS, where Homebrew refuses to run as root at all. Same shape as
// tailscale, and for the same reason: get the password prompt out of the
// way before a sweep starts rather than partway through one.
needsRoot: { except: ["darwin"] },
install: packageInstall("ffmpeg"),
// No upgrade key: `apt-get install` / `brew install` on a package that is
// already there upgrades it, so re-running the install IS the upgrade —
// the same reasoning as mcpjam and railway, and toolUpgradeSpec falls back
// to install on its own.
},
imagemagick: {
desc: "ImageMagick — resize, convert and composite images from the command line",
// Two names, deliberately. The command is `magick` on ImageMagick 7 and
// `convert` on 6, and both are current: Ubuntu 24.04 and earlier ship 6,
// 25.04 and later ship 7, and the package is called `imagemagick` on both.
// A single name would report a perfectly good install as missing on
// whichever half of the fleet has the other one.
bin: ["magick", "convert"],
needsRoot: { except: ["darwin"] },
install: packageInstall("imagemagick"),
},
};

@@ -382,3 +437,3 @@

return Object.entries(TOOLS)
.map(([key, tool]) => ` ${key.padEnd(10)} ${tool.desc}`)
.map(([key, tool]) => ` ${key.padEnd(11)} ${tool.desc}`)
.join("\n");

@@ -385,0 +440,0 @@ }

@@ -192,2 +192,11 @@ // Making a Moshpit name work in a stock client, on this machine.

args: ["add-trusted-cert", "-d", "-r", "trustRoot", "-k", "/Library/Keychains/System.keychain", file],
// The one store that can only be told with the certificate in hand:
// `remove-trusted-cert` takes a file, not a nickname. `needsFile` is what
// lets the undo say so out loud instead of leaving an anchor behind and
// reporting success.
remove: {
needsFile: true,
command: "security",
args: ["remove-trusted-cert", "-d", file],
},
});

@@ -211,2 +220,9 @@ return stores;

args: ["-d", `sql:${path.join(home, ".pki", "nssdb")}`, "-A", "-t", "C,,", "-n", "Moshpit Local CA", "-i", file],
// By nickname, so the anchor can still be withdrawn after the root file
// itself is gone — which is the ordinary case, since a person who wants
// rid of this deletes the certificate first and asks questions after.
remove: {
command: "certutil",
args: ["-d", `sql:${path.join(home, ".pki", "nssdb")}`, "-D", "-n", "Moshpit Local CA"],
},
});

@@ -223,2 +239,10 @@ stores.push({

args: [],
// Delete the copy, then rebuild. `--fresh` rather than a bare refresh:
// the bare form adds what is new, and it is the rebuild that drops the
// symlink for a source file that is no longer there.
remove: {
removeFile: "/usr/local/share/ca-certificates/moshpit-local-ca.crt",
command: "update-ca-certificates",
args: ["--fresh"],
},
});

@@ -285,2 +309,126 @@ return stores;

/**
* What `dns disable` should do about trust.
*
* Deliberately not `trustPlan(...).steps.reverse()`. Installing is gated on the
* root being safe to install — name constraints, a certificate that parses —
* and none of that has any bearing on taking it back out: a root that should
* never have been trusted is the *most* important one to be able to withdraw.
* So this plan asks two questions only, whether the store can be reached and
* whether the undo needs the certificate file, and never refuses.
*
* Pure, like trustPlan, so `dns disable` can be tested without a trust store.
*/
export function untrustPlan({
platform = process.platform,
home = os.homedir(),
caFile = null,
isRoot = false,
haveCertutil = true,
haveFile = true,
} = {}) {
const file = caFile || caPath({ home });
const steps = [];
const skipped = [];
for (const store of trustStores({ platform, home, caFile: file })) {
if (!store.remove) {
skipped.push({ ...store, why: "this build knows how to install it but not how to remove it" });
continue;
}
if (store.id === "nss" && !haveCertutil) {
skipped.push({ ...store, why: "certutil is not installed (Debian/Ubuntu: libnss3-tools)" });
continue;
}
if (store.needsRoot && !isRoot) {
skipped.push({ ...store, why: "needs root" });
continue;
}
// The macOS case. Saying "the root is gone, so the anchor cannot be named"
// is worth a line, because the alternative is a machine that keeps trusting
// a certificate nobody can produce any more.
if (store.remove.needsFile && !haveFile) {
skipped.push({ ...store, why: `the root at ${file} is gone, and this store can only be told with it` });
continue;
}
steps.push(store);
}
return { ok: true, steps, skipped, file };
}
/**
* The trust half of `dns disable` — take back what `applyTrust` installed.
*
* Non-fatal throughout, for the same reason its counterpart is: resolution has
* already been put back by the time this runs, and failing the whole command
* over a trust store would undo working DNS to fix a certificate. What it must
* not do is report a removal it did not achieve, since a trust anchor believed
* gone is worse than one known to be present.
*/
export async function applyUntrust(out, deps = {}) {
const {
readFile = async (f) => (await import("node:fs/promises")).readFile(f, "utf8"),
runner = run,
env = process.env,
home = operatorHome({ env }),
platform = process.platform,
uid = typeof process.getuid === "function" ? process.getuid() : 0,
} = deps;
const owner = env.SUDO_USER || env.DOAS_USER || null;
const file = caPath({ home });
const haveFile = await readFile(file).then(() => true, () => false);
const plan = untrustPlan({
platform, home, caFile: file, isRoot: uid === 0,
haveCertutil: (await runner("which", ["certutil"])).ok,
haveFile,
});
if (!plan.steps.length && !plan.skipped.length) return { ok: true, removed: 0, skipped: 0 };
out("");
out("trust (taking the local root back out)");
let removed = 0;
for (const step of plan.steps) {
const undo = step.remove;
if (undo.removeFile) {
// `rm -f`: the copy not being there is the state we are trying to reach,
// so its absence is success rather than something to report.
const gone = await runner("rm", ["-f", undo.removeFile]);
if (!gone.ok) {
out(` FAIL ${step.label} — ${gone.stderr.split("\n")[0] || `could not remove ${undo.removeFile}`}`);
continue;
}
}
const done = await runner(undo.command, undo.args);
if (!done.ok) {
const first = done.stderr.split("\n")[0] || "";
// certutil says this when the nickname is not in the database, which is
// the same end state as a successful removal and must not read as a
// failure — most often it means `dns disable` is being run twice.
if (/SEC_ERROR_BAD_DATA|not found|PR_FILE_NOT_FOUND/i.test(first)) {
out(` ok ${step.label} — was not there`);
continue;
}
out(` FAIL ${step.label} — ${first || `${undo.command} failed`}`);
continue;
}
if (step.ownedDir && owner && uid === 0) {
const owned = await runner("chown", ["-R", `${owner}:`, step.ownedDir]);
if (!owned.ok) out(` -- ${step.ownedDir} is left owned by root — chown -R ${owner}: ${step.ownedDir}`);
}
removed++;
out(` ok removed from ${step.label}`);
}
for (const step of plan.skipped) {
out(` -- ${step.label} — ${step.why}`);
if (step.needsRoot && uid !== 0) out(" re-run with root to cover it: sudo moshcode dns disable");
}
return { ok: true, removed, skipped: plan.skipped.length };
}
/**
* What to do about a refusal, which depends entirely on which one it is.

@@ -287,0 +435,0 @@ *

@@ -19,2 +19,3 @@ // The moshcode shell — run `moshcode` with no args. A metal prompt that opens

import { loginAuto, whoami, logout } from "./auth.mjs";
import { startAutoSync } from "./autosync.mjs";
import { loadCommand, saveCommand } from "./settings-sync.mjs";

@@ -826,2 +827,10 @@ import { createMirror, pressKey, teeOutput } from "./mirror.mjs";

// Settings sync, unattended. Started per `tui()` call and stopped in the
// teardown below, because the pit is re-entered after an engine session
// (`backToPit`) and a timer left behind would be joined by another one.
// Deliberately holds no reference to `rl`: the loop closes and rebuilds it
// around a dozen commands, so a tick that captured it would be writing to a
// readline that no longer exists.
const stopAutoSync = startAutoSync();
let rl = mkrl();

@@ -1257,2 +1266,3 @@ // An alias expands into a line that is dispatched exactly as if it had been

stopAutoSync();
try { rl.close(); } catch { /* noop */ }

@@ -1259,0 +1269,0 @@ saveHistory();

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display