Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

Merge branch 'feat/p2-vendored-ink' into release/1.3.1-p2

Salman Qureshi8e43b9d047ca
diff --cc DECISIONS.md
index e8bf3662,10851767..5679862a
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@@ -136,16 -136,13 +136,23 @@@
- **Decision**: Accept and maintain. Verified empirically on macOS before merge: an xattr-bearing `web/` directory produced `._web` in the archive without `COPYFILE_DISABLE=1` and nothing with it. Full suite green (487 tests), `tsc --noEmit` clean. The allowlist change is a security positive (defense in depth — children can no longer invoke tools outside their allowlist, e.g. `list_agents`/`stop_agent`); the runtime filter subsumes the prompt-text filtering in `sub-agent.ts` line 516, which remains as harmless documentation. Merge commit authored by Mercury, feature commits retain the original author.
- **Consequence**: Release archives stay safe for GNU tar consumers; sub-agent tool scoping is now enforced at the SDK boundary rather than trusted to the model's cooperation. Maintenance owned by Mercury: any new tool surface exposed to sub-agents must respect `resolveTools()` (not `capabilities.getTools()` directly), and release builds on macOS must keep `COPYFILE_DISABLE=1` — re-verify archive contents with GNU tar or the `verify-standalone-release.cjs` path check before publishing.
+## ADR-016: Argv-lane auto-approval and per-agent permission contexts
+
+- **Context**: Ask Me mode auto-approved a list of "safe read" commands by matching regex patterns against the command string, then ran the string through `sh -c` with the daemon's `PATH`. Every fix to that classifier (find action flags #71/#77/#101, redirection #72/#82, variable expansion #76/#80, residual `find -fprint0`, `rg --pre`, `git --output`/`--ext-diff`) left the class open, because the check and the shell parsed the string differently, and an allowlisted name resolved through a mutable `PATH` (#103). Separately, channel, allow-all, skill elevation and session scopes were mutable fields on the one `PermissionManager` shared by the main agent and every sub-agent; an internal (scheduled) turn switched allow-all on for its duration and a concurrently running sub-agent inherited it (#75/#99 residual), a sub-agent's `use_skill` elevated the main agent, and the `/` scope an internal turn added was never removed.
+- **Decision**:
+ - **Two shell lanes.** The *argv lane* (`src/capabilities/shell/argv-lane.ts`) auto-approves only commands that a strict POSIX tokenizer turns into argv without meeting any shell syntax (it rejects `$`, backticks, `~`, redirection, pipes, lists, unquoted globs, `!`, `#`, subshells, env-assignment prefixes), whose `argv[0]` is a bare name on `ARGV_ALLOWLIST`, whose flags pass that program's policy (`SIDE_EFFECT_FLAGS` as the deny list over quote-removed argv, plus positive rules for `git` — read subcommands only, nothing before the subcommand — `git branch` listing, `ps` without `e`/`E`, `rg -z`, `tree -R`), whose path arguments stay inside the tool cwd or a readable scope, and whose binary exists in the pinned directories. It executes with `execFile(absBinary, argv, { cwd, env: minimalEnv(), shell: false })`; git gets `-c core.fsmonitor=false -c core.pager=cat --no-pager` and `--no-ext-diff --no-textconv`. `cd` runs in-process. Everything else is the *approval lane*: the user sees the exact string and, once approved, it may run through the shell (still via execFile when it is expressible as argv). Pipelines of read-only commands go to the approval lane — running each stage via execFile and piping in-process was rejected as more code and more policy surface for a convenience.
+ - **Pinned binaries.** Allowlisted programs are resolved once at startup from `/usr/bin`, `/bin`, `/usr/sbin`, `/sbin`, `/usr/local/bin`, `/opt/homebrew/bin` (Windows: `System32`, `Program Files\Git\cmd`), never `process.env.PATH`; world-writable binaries are skipped. The git read tools use the same pinned git. Service files write a fixed `PATH` (system dirs plus the node binary's directory); on Windows, where Task Scheduler XML has no environment block, the `--daemon` process pins its own `PATH`.
+ - **Immutable per-agent contexts.** `PermissionContext { channelType, channelId, senderRole, autoApprove, autoApproveOrigin, allowedTools, scopes, elevated }` is frozen. Sub-agents run under their own context through `AsyncLocalStorage` (`PermissionManager.withContext`), derived at spawn time by `deriveChildContext` (child ⊆ parent: tools intersected, scopes covered, no elevation, allow-all only from a user-chosen *session* grant). The supervisor stores the snapshot on `SubAgentConfig.permissionContext`, so a queued agent keeps it. The main agent's messages are serialised, so its context stays the root one; internal turns layer a turn grant (`beginTurnGrant`/`endTurnGrant`) over it that children neither see nor inherit. The legacy setters remain as shims that replace the calling agent's context. `AsyncLocalStorage.run` is used rather than `enterWith`, which on Node 20 leaks a store into the caller's continuation.
+- **Alternatives considered**: hardening the regex classifier further (the approach that kept failing); a full shell parser (bash-compatible parsing is large and still has to agree with the real shell); capability tokens passed explicitly through every tool factory (correct but touches every tool; ALS gives the same isolation behind the existing API); a separate `PermissionManager` per sub-agent (approval memory, the ask handler and manifest persistence would fork).
+- **Consequence**: The auto-approved path no longer involves a shell or `PATH`, so redirection/expansion/chaining/PATH-substitution bypasses do not apply to it; the remaining risk is an option of an allowlisted program that the flag policy misses. Some commands that used to run silently now prompt: pipelines and `&&` chains of read-only commands (including `cd dir && ls`), quoted absolute paths outside the workspace (`cat "/etc/passwd"`, which the old regex path gate missed), `ps -ef`/`ps e`, tools not installed in the pinned dirs (e.g. `rg` under `~/.cargo/bin`), and Windows `dir`/`type` (cmd builtins). Bare `ls`, `git status` and similar now auto-approve (the old `cmd *` patterns needed an argument). On the internal channel `requestApproval` approves only under allow-all. Maintenance owned by Mercury: new auto-approved programs go into `ARGV_ALLOWLIST` with a policy and a test row; never add a shell-dependent fallback to the argv path; any new agent-like runner must enter `withContext` with a derived context.
+
+ ## ADR-017: Vendor the patched Ink renderer
+
+ - **Context**: Mercury's TUI depends on seven fixes to ink 5.2.1 (Yoga free-node hygiene, `<Static itemKey>`, freeze gate, live-region guard, diff-render, resize invalidate and — new here — hardware cursor positioning for IME, #41/#66). Until now they were applied to `node_modules/ink` by `postinstall` (`patch-package || apply-ink-patch.cjs || echo`). That path failed silently on `--ignore-scripts` installs, npm policies that block lifecycle scripts, hoisted installs, and Termux containers without `patch-package`; the stock renderer then capped the transcript at ~100 messages and re-exposed the Yoga WASM crash (ROADMAP P0.9, P2.4). `ink` was a tsup external, so even the standalone binaries depended on whatever ink was on disk at build time.
+ - **Decision**: Commit the patched build to `vendor/ink/` (runtime files only: `build/` without source maps, a trimmed `package.json`, `license`) and bundle it: tsup aliases `ink` → `vendor/ink/build/index.js` with `noExternal: ['ink']`, vitest aliases the same path, and `tsconfig` `paths` point the types there. The files are generated, never hand-edited: `scripts/vendor-ink.cjs` verifies the stock tarball's registry integrity, copies it, runs the hunks in `scripts/apply-ink-patch.cjs` (the single source of truth), stamps `inkPatch.vendored = true`, and rewrites `patches/ink+5.2.1.patch` as the stock-vs-vendored diff for review. `--check` rebuilds into a temp dir and fails on any byte difference (run in CI's pack-verify job). The postinstall step is removed; `post-build.cjs` and `verify-package.cjs` fail if `dist/index.js` imports `ink` at runtime or lacks the patch markers. `ink-patch-check` judges a vendored build by its runtime globals only and reports `source: 'vendored'` (`mercury doctor`: "vendored (patched ink 5.2.1 bundled)").
+ - **Alternatives considered**: keep postinstall and harden it (still depends on lifecycle scripts running); publish a fork as `@cosmicstack/ink` (adds a release pipeline for a package whose fixes we want upstream anyway); upgrade to ink 6 (React 19 migration, and the same fixes would still be needed).
+ - **Consequence**: Every install path — npm with or without scripts, Termux, Bun binaries — runs the identical patched renderer. `ink` stays in `dependencies` for now, used only for its transitive packages at build time; moving it to `devDependencies` (and dropping `patch-package`) needs a lockfile regeneration and is left as a follow-up. Two bundling details: ink's DEV-only React DevTools module is replaced by an empty stub (esbuild would otherwise inline `react-devtools-core`, which crashes at load), and the bundle banner defines `require` via `createRequire` because ink's CommonJS dependencies require node builtins. Upgrading ink means: bump `INK_VERSION`/`INK_INTEGRITY` in `scripts/vendor-ink.cjs`, re-anchor the hunks, regenerate, and review the patch file. Each hunk's rationale and upstream status is in `docs/ink-patch.md`.
+
## ADR-018: SQLite backend selection: better-sqlite3 → bun:sqlite → node:sqlite → JSON
- **Context**: Four stores depend on SQLite — Second Brain (`src/memory/second-brain-db.ts`), the bots job queue (`src/bots/queue.ts`), boards (`src/core/board-db.ts`) and the cloud pool-search cache (`src/cloud/pool-search.ts`). Each carried its own `require('better-sqlite3')` probe. The standalone binaries (`bun build --compile`) bundle better-sqlite3's JavaScript but not its native addon, so inside a binary every probe failed on every target: Second Brain was silently disabled and bots/boards fell back to JSON (ROADMAP P1.9, §F, #96). Toolchain-less npm installs (Termux, no compiler) hit the same wall. Meanwhile both runtimes ship an embedded engine — `bun:sqlite` in Bun and `node:sqlite` (`DatabaseSync`) in Node ≥ 22.5 (unflagged in 22.13 / 23.4) — with the same synchronous shape better-sqlite3 has.
diff --cc package.json
index 1897a7e1,b36e437e..8eca1df9
--- a/package.json
+++ b/package.json
@@@ -20,8 -20,8 +20,9 @@@
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
+ "eval": "vitest run src/eval",
- "postinstall": "patch-package || node scripts/apply-ink-patch.cjs || echo 'WARNING: ink patch not applied — run: node scripts/apply-ink-patch.cjs'",
+ "vendor:ink": "node scripts/vendor-ink.cjs",
+ "vendor:ink:check": "node scripts/vendor-ink.cjs --check",
"prepublishOnly": "npm run build"
},
"keywords": [
diff --cc src/index.ts
index 02face45,97f4711b..8936888e
--- a/src/index.ts
+++ b/src/index.ts
@@@ -77,8 -77,8 +77,8 @@@ import { ask, InputClosedError } from '
import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntimeProcess, releaseRuntimeProcess, restartDaemon, tryAutoDaemonize, isStandaloneBinary, getForegroundRuntimeStatus, stopForegroundRuntime } from './cli/daemon.js';
import { runUninstall } from './cli/uninstall.js';
import { runAttach } from './cli/attach.js';
-import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';
+import { installService, uninstallService, showServiceStatus, isServiceInstalled, pinDaemonPathOnWindows } from './cli/service.js';
- import { detectInkPatch, inkPatchFixCommand } from './ui/ink-patch-check.js';
+ import { detectInkPatch, describeInkPatch, inkPatchFixCommand } from './ui/ink-patch-check.js';
import { runWithWatchdog } from './cli/watchdog.js';
import { setGitHubToken } from './utils/github.js';
import { selectWithArrowKeys } from './utils/arrow-select.js';