Repository navigation
feat(agent): mlx agent — first all-in-one local coding agent on pi - #95
Conversation
…i deps Co-Authored-By: Claude Fable 5 <[email protected]>
Proves the pi-side integration seam for mlx agent: an inline extension registering a custom 'mlx' provider (registerProvider + streamSimple) drives pi's full coding-agent loop via main() in headless print mode (--mode json). 8/8 checklist items PROVEN: boot with redirected PI_CODING_AGENT_DIR, model resolution without auth, text streaming, tool dispatch -> toolResult -> continuation, usage plumbing, malformed tool-call error feedback (pi owns the retry loop), and main() returning (not exiting) in print mode. Run: oxnode packages/agent/spikes/spike-a-fake-provider.ts Co-Authored-By: Claude Fable 5 <[email protected]>
Items 4-6 now fail-closed on event-contract or usage-field regressions:
- parse the --mode json stream into ordered assistant episodes
(message_start -> assistantMessageEvent types -> message_end)
- item 4: strict text trio (text_start, >=1 text_delta, text_end),
deltas reassemble TEXT_REPLY, message_end.stopReason === 'stop'
- item 5: strict toolcall trio + toolCall{name,id} on first episode,
stopReason === 'toolUse', text-trio continuation with 'stop'
- item 6: every usage field (input=7 output=5 cacheRead/Write=0
totalTokens=12) and all five cost fields === 0
Provider start/done are consumed by pi's agent loop and re-emitted as
message_start/message_end (done.reason survives only as
message.stopReason) — asserted via those reflections and documented.
Co-Authored-By: Claude Fable 5 <[email protected]>
…topReason finding pi's streamAssistantResponse never reads done.reason: on 'done' it emits message_end with the AssistantMessage from response.result() (= done.message), so message_end.message.stopReason is the message's own field. The fake provider now records each emitted done.reason as a SPIKE_DONE_REASON stderr marker; the judge asserts the captured reasons are exactly [stop] (item 4) and [toolUse, stop] (item 5) in addition to the message_end.stopReason checks. Mutation-tested: corrupting only done.reason fails item 5 on the provider-side assertion while all stream-side checks still pass. Co-Authored-By: Claude Fable 5 <[email protected]>
Proves the production bridge's per-call replay pattern (warm-reset -> primeHistory -> startFromHistoryStream) on qwen3.5-0.8b-mlx-bf16: KV-prefix reuse across growing histories (re-prefill is O(new turn), not O(history); tool-call turns replay byte-identically), multi-tool fan-out replay past the one-unresolved-tool-call gates, tool_calls emission + continuation, abort survival, real pi bash/edit TypeBox schema render, and thinking-turn prefix invalidation. 7/7 checklist items PROVEN; run via `oxnode packages/agent/spikes/spike-b-warm-replay.ts`. [skip ci] Co-Authored-By: Claude Fable 5 <[email protected]>
…alidation bound Turn 1 now REQUIRES thinking (reasoningTokens > 0 + non-empty visible text) instead of merely recording it; turn 2 asserts the invalidation invariant 0 < cachedTokens < promptTokens AND cachedTokens <= turn-1 promptTokens (replay strips <think>, so reuse cannot extend through the stripped thinking span). The 0.8b at temp=0 never emits </think> on its own (512/512 ramble, finish=length, empty text), so the scenario uses an explicit thinkingTokenBudget: 64 (engine budget-forced close) with bare prompts; observed: turn 1 reasoning=65 finish=stop text "17 + 25 = 42.", turn 2 cached=32 <= prompt1=38 < prompt2=70, finish=stop. 7/7 PROVEN, stable across 2 consecutive runs. Co-Authored-By: Claude Fable 5 <[email protected]>
process.exitCode alone was unreliable: a run whose native model load crashed still exited 0 under oxnode. Every terminal path now calls process.exit() explicitly via a flush-then-exit helper — fatal -> 2, any FAILED item -> 1, and exit 0 is only reachable after the "N items, 0 FAILED" summary has printed. Co-Authored-By: Claude Fable 5 <[email protected]>
Two self-contained ports from @mlx-node/server (the agent package must not depend on the server package), foundations for the provider bridge: - provider/tool-call-buffer.ts: byte-faithful port of the server's ToolCallTagBuffer (partial structural-tag suppression + false-alarm recovery for streamed deltas). - provider/warm-reuse.ts: port of the server-private resetPreservingNativeCacheForWarmReuse (JS-state-only ChatSession wipe that preserves the native KV cache for prefix reuse). Exports WARM_REUSE_TOUCHED_FIELDS, compile-time-locked to the internals interface via Record<keyof, true>, so the drift test can assert every touched private field still exists on a real ChatSession instance. Tests drive the real buffer and the real ChatSession class (mock model only satisfies the structural constructor arg). Drift test verified to fail on a simulated @mlx-node/lm private-field rename; behavior tests pin the resetCaches-not-called + lastAudioKey-untouched invariants that distinguish warm reuse from the full reset() path. Co-Authored-By: Claude Fable 5 <[email protected]>
…itter, model host Four model-free modules the streaming adapter (Task 6) will assemble: - convert-messages: pi Context → ChatMessage[] for primeHistory (deterministic rendering so warm KV-prefix reuse survives replays; image parts → "[image omitted]", thinking dropped, husk assistant turns skipped) + pi Tool[] → NAPI ToolDefinition[] (properties as byte-stable JSON string). - chat-config: LAUNCH_PRESETS sampling base + pi SimpleStreamOptions overlay; pi thinking level → reasoningEffort (undefined → 'none'); reuseCache left to ChatSession. - events (TurnEmitter): native ChatStreamEvent turn → pi AssistantMessageEvent protocol. Text routes through ToolCallTagBuffer so partial <tool_call> markup never leaks; toolcall trios emitted from the parsed final; usage input excludes cachedTokens; aborted streams (which end with no final event) synthesize the terminal message with stopReason 'aborted'; non-ok tool calls become deliberately-invalid pi ToolCalls so pi's validation feeds the error back; never throws. - model-host (MlxModelHost): single-resident lazy loader with one serialized promise chain (rejections don't break it) and drop-then-load swap semantics. Also re-exports ChatStreamDelta from @mlx-node/lm and adds the @mlx-node/server dep (LAUNCH_PRESETS only). Co-Authored-By: Claude Fable 5 <[email protected]>
…ents Review fixes on Task 5 (provider core): - MlxModelHost: selection + inference were not atomic — ensureResident serialized only the load, then exposed the session, so a queued swap could replace the resident mid-turn. New runWithResident(modelId, fn) runs the resident check/load AND the full inference callback inside one serialized closure; ensureResident is gone and runSerialized is private. fn rejection keeps the resident warm; load failure leaves no resident and never runs fn. Race test pins that a queued swap's load cannot begin until the current callback settles. - TurnEmitter: error/abort terminals left open blocks unclosed (streams could end text_start/text_delta/error with no text_end). finishWithError now flushes recoverable buffered text and closes the active text/thinking block before pushing the terminal event, shared by the finishReason=error final path, onAborted, and onError. Ordered-event tests now require *_end before every terminal. Co-Authored-By: Claude Fable 5 <[email protected]>
Final assembly of the pi provider bridge: - provider/stream-adapter.ts: makeMlxStreamSimple(host) — every pi LLM call runs the spike-proven warm replay (warm-reset -> primeHistory -> startFromHistoryStream) INSIDE one atomic MlxModelHost.runWithResident closure, feeding TurnEmitter. Never throws: load/prime/iteration failures become 'error' terminals; a final-less ended generator maps to 'aborted' when the signal fired, protocol-violation 'error' otherwise. StreamSimpleHost keeps the host seam structural for tests. - provider/models.ts: discoverMlxModels ports the launch-claude discovery walk (no packages/cli import) and pairs each checkpoint with its pi ProviderModelConfig: reasoning per family (gemma4 false), contextWindow from config.json max_position_embeddings (root, then text_config nesting, then documented per-family fallback), maxTokens from LAUNCH_PRESETS maxOutputTokens. - provider/index.ts: createMlxProviderExtension registers provider 'mlx' (api 'mlx', baseUrl mlx://local, literal apiKey so models are available without /login) with type-only pi-coding-agent imports. - model-host.ts: read-only modelInfo() lookup so the adapter can pick the launch preset for the model it is about to run. Tests: model-free adapter suite (event order, toolcall trio, abort synthesis, load-failure terminal, strict sequential closures) + tmp-dir discovery fixtures + gated live smoke (qwen3.5-0.8b: real text turn and tool round-trip with KV reuse across the replay). Co-Authored-By: Claude Fable 5 <[email protected]>
…scover lfm2_moe Three adversarial-review findings on the provider bridge: - Queued abort gap: a request aborted while parked behind stalled prior inference/loading stayed start-only forever. streamSimple now pre-checks an already-aborted signal (host never engaged), keeps an abort listener across the whole queued/running window, and a turn-wide `terminated` flag makes the terminal idempotent — a resident closure that finally runs after termination skips ALL session work. - Never-throw containment windows: synchronous emitter setup (hostile Model/options getters) now lives inside the containment, and a TurnEmitter-independent failsafe pushes a minimal terminal directly onto the stream when the emitter is missing or throws (e.g. onError choking on a null-prototype error or a poisoned message getter), with a safe error-coercion helper. Terminal push/end failures are swallowed — never cascaded into pi. - lfm2_moe discovery: FAMILY_TRAITS gains lfm2_moe (reasoning, 128000 fallback window per LFM2_CONFIGS) and preset resolution goes through a shared launchPresetFor that aliases lfm2_moe onto the lfm2 launch preset (same LFM2.5 family; packages/server untouched), used by both discovery and buildChatConfig so discovered == streamable. Fixture test flipped from codifying the skip to asserting discovery. Co-Authored-By: Claude Fable 5 <[email protected]>
…lass lfm2_moe sampling preset - coerceErrorMessage: the `err instanceof Error` check now lives inside the try guard — on a revoked Proxy (or any Proxy with a throwing getPrototypeOf trap) instanceof itself throws, which previously escaped the failsafe, left the stream start-only, and surfaced an unhandled rejection. Regression test reproduces the reviewer's revoked-Proxy repro and asserts exactly one error terminal, a settling result(), and no unhandled rejection. - chat-config: lfm2_moe gets a first-class agent-local launch preset for the actual MoE checkpoint (LFM2.5-8B-A1B, LiquidAI HF card: temperature 0.2, topK 80) instead of aliasing onto the dense lfm2 preset (LFM2.5-1.2B guidance: 0.05/50). repetitionPenalty 1.05 and the 8192 output budget are unchanged. Tests assert the concrete values, not alias-equality. packages/server untouched. Co-Authored-By: Claude Fable 5 <[email protected]>
TurnEmitter.onError evaluated `err instanceof Error` and read `err.message` unguarded: a revoked Proxy (or any value with a throwing getPrototypeOf trap / poisoned message getter) threw a TypeError out of onError, emitted only `start`, and left `stream.result()` unsettled — despite the class documenting every method as throw-safe. Extract the adapter's hardened `coerceErrorMessage` into a shared `provider/error-coercion.ts` and use it from BOTH the stream adapter's failsafe path and `TurnEmitter.onError` (no duplicated logic). The adapter's TurnEmitter-independent failsafe remains as defense in depth. Audit of the remaining public emitter surface found no other unguarded error-ish reads: onDelta/onFinal already route caller-data throws to the (now hardened) onError, onAborted takes no value, and finishWithError only receives plain strings. Regression test: onError(revokedProxy) on a fresh emitter → no throw, exactly one error terminal, result() settles. Verified the test fails against the previous unguarded expression. Co-Authored-By: Claude Fable 5 <[email protected]>
createPermissionGateExtension gates bash/write/edit tool calls behind ctx.ui.select approval (Yes / Always (this session) / No) with the command or file path as the prompt detail; the per-session allow list lives in the factory closure so each extension load starts clean. Non-interactive runs fail closed unless MLX_AGENT_AUTO_APPROVE=1, and malformed event input never throws. Type-only pi imports keep the module safe to load before pi's config env vars are set. MODEL_CATALOG carries the four settled wizard entries (Qwen3.6-27B default; Gemma-4-12B hidden until Task 9 publishes the repo) and visibleCatalog() filters hidden entries for the first-run wizard. Co-Authored-By: Claude Fable 5 <[email protected]>
The permission gate's ctx.ui.select title embedded the raw bash command or file path from the tool-call event. pi-tui does not strip ANSI from rendered text (wrapTextWithAnsi deliberately preserves escape codes), so a crafted tool call could cursor-move, erase, or restyle the approval prompt to disguise what is being approved. Add sanitizeDetail as defense in depth in our own safety layer: - strip ANSI escape sequences wholesale (CSI incl. the bare C1 CSI byte, OSC including its payload, two-byte ESC <Fe> sequences) - collapse remaining C0 (except \n and \t), DEL, and C1 controls to a visible U+FFFD placeholder - cap the detail at 6 lines / 500 chars with a visible truncation marker - render "(unprintable content)" if nothing printable survives Covered by 9 new tests (mutation-checked: removing the sanitize call fails 7 of them). Co-Authored-By: Claude Fable 5 <[email protected]>
… delete shell-significant text The sanitizer stripped ANSI escape sequences wholesale, but CSI parameter/final bytes and OSC payloads are ordinary printable bytes that bash still parses and executes: a command could display as a safe-looking prefix while a pipe or a second command hid inside what the sanitizer parsed as an escape payload. U+009C (C1 ST) was also not recognized as an OSC terminator, and the optional-terminator OSC regex could swallow a following executable line. Replace sequence-level deletion with a per-character encoding pass: every printable byte is preserved verbatim and every control byte (C0 except newline/tab, DEL, C1) is rendered as visible \xNN text, so no byte can drive the terminal and no shell text can hide. Caps are applied after encoding; the unprintable-content fallback now only fires for whitespace-only input. Tests flipped from asserting deletion to asserting encoding, plus regressions for the reviewer-demonstrated OSC-hiding and CSI-hidden- pipe shapes, ESC-backslash ST, C1 ST U+009C, and unterminated OSC, and a property-style guard that no printable-ASCII input char is ever lost or reordered. Removing the encoding pass fails 11/28 tests. Co-Authored-By: Claude Fable 5 <[email protected]>
`mlx agent` boots pi's main() on the in-process mlx provider with the
permission gate installed, making the local coding agent a runnable
product:
- packages/agent/src/run-agent.ts: runAgent boot shell — seeds
PI_CODING_AGENT_DIR / PI_SKIP_VERSION_CHECK /
MLX_PAGED_PREFILL_CHUNK_SIZE with ??= (never clobbering user values)
BEFORE the dynamic pi import, then hands off to main(argv,
{ extensionFactories: [provider, permission-gate] }). mainImpl test
seam keeps pi entirely out of unit tests.
- packages/cli/src/commands/agent/index.ts: manual arg scan (pi owns
most flags) — extracts --models-dir, intercepts the pi npm
self-update `update` positional (blocked, exit 1), prints an mlx
preamble before forwarding --help; package-manager positionals
(install/remove/uninstall/list) pass through untouched. Fresh runs
are pinned to the first discovered local model via injected
`--model mlx/<id>` — otherwise ambient cloud credentials (e.g. a
GROQ_API_KEY in the shell) win pi's "first available model" fallback
and the offline agent silently talks to a cloud provider; explicit
--model/--provider and session-carrying runs (-c/--resume/--session)
are left alone so pi's own restore semantics apply.
- packages/cli/src/commands/agent/wizard.ts: first-run download wizard
over visibleCatalog() (default entry first, hidden excluded) with
injectable IO (TokenPromptIO pattern); non-TTY throws the manual
`mlx download model -m <repo>` commands instead of touching stdin.
Downloads are pinned to <modelsDir>/<slug> so a custom --models-dir
receives the model it will re-scan.
- packages/cli/src/cli.ts: `agent` command + help entry/examples.
Manual smoke (qwen3.5-0.8b-mlx-bf16, isolated models dir): print-mode
reply verbatim + exit 0; --mode json event stream with
model=qwen3.5-0.8b-mlx-bf16; --help preamble + pi flag list; update
blocked exit 1; empty models dir non-TTY prints wizard hint, exit 1.
Co-Authored-By: Claude Fable 5 <[email protected]>
pi's parsePackageCommand (0.80.6) reads the package command strictly at args[0], so the unconditional withDefaultModel prepend turned 'mlx agent install <pkg>' into ['--model','mlx/<id>','install',<pkg>] and knocked it into the agent-prompt path; the empty-models-dir wizard also fired for commands that need no model. Detect install/remove/uninstall/list at the passthrough head before discovery, wizard and default-model injection, and forward them verbatim with an empty models list. 'update' stays blocked, now also behind a stripped --models-dir pair. Adds an AgentRunDeps seam and end-to-end argv routing tests (mutation-checked). Co-Authored-By: Claude Fable 5 <[email protected]>
pi's handleConfigCommand reads strictly args[0] (package-manager-cli.js: "const [command] = args; if (command !== 'config') return false") just like parsePackageCommand, so the injected "--model mlx/<id>" displaced "config" into the agent prompt path and the empty-dir wizard gated it. Fold config into the same pass-through set as install/remove/uninstall/ list: verbatim argv to runAgent, empty model list, no discovery, no wizard, and pi's own "config --help" wins over the mlx preamble. update stays blocked. A dist-wide sweep found no other argv[0]-only pi command with this gap. Co-Authored-By: Claude Fable 5 <[email protected]>
…fix headless download hint
- scanAgentArgs: the space-form --models-dir value must be a real path
token — absent, empty, or option-looking (-…) values now error
("Missing value for --models-dir", exit 1) instead of consuming the
next flag; `mlx agent install npm:x --models-dir --local` can no
longer create ./--local and silently go global. Dash-leading dirs use
the (still supported) --models-dir=<dir> form.
- withDefaultModel: add --fork to MODEL_CARRYING_ARGS. pi restores the
forked session's saved model only when no CLI --model is given
(createAgentSession), so the fresh-run prepend was overriding it.
- Fresh-run injection now honors pi's persisted /model default
(<agentDir>/settings.json defaultProvider/defaultModel): a
still-discovered mlx default wins over the lexicographic first; a
non-mlx default is overridden (local-first policy) with a one-line
stderr notice, never silently.
- wizard: non-TTY download hints share downloadModelArgv with the
interactive path, so they carry -o <modelsDir>/<slug> and a copy-
pasted command downloads where the custom --models-dir re-run scans.
Co-Authored-By: Claude Fable 5 <[email protected]>
…uote headless hint
Two review findings on the mlx agent command, both verified against pi
0.80.6 dist before fixing:
- readPersistedDefaultModel joined PI_CODING_AGENT_DIR verbatim, but pi
(getAgentDir -> expandTildePath -> normalizePath, default options)
expands a lone ~ / leading ~/ to the home dir and file:// URLs to
paths, so a tilde agent dir made the reader miss the user's saved
/model default and silently fall back to models[0]. New
expandPiAgentDir mirrors pi's exact semantics (no ~user, no trim);
resolution stays inside the try so an unresolvable value still means
"no persisted default", never a throw.
- The non-TTY first-run hint rendered the download argv with .join(' '),
splitting -o values containing spaces and leaving shell
metacharacters live. Hint elements are now POSIX-shell quoted (safe
charset passes through, everything else single-quoted with '\''
escapes); the interactive path still passes real argv elements.
Tests: pi-parity expansion table, end-to-end ~/-resolved settings.json
read, unresolvable-env tolerance, and /bin/sh round-trip of the rendered
hint for a models dir with spaces, a single quote, $, ; and &.
Co-Authored-By: Claude Fable 5 <[email protected]>
…mxfp8 attention)
The nvidia recipe's fixed data-free mxfp4/mxfp8 class-map already emits the
right per-layer decisions on a dense gemma4/gemma4_unified checkpoint —
self_attn.{q,k,v,o}_proj -> mxfp8, .mlp.{gate,up,down}_proj -> mxfp4, with
norms/embed_tokens/vision_embedder (and the tied gemma4 head) staying bf16 —
and the mode-aware loaders for those tensors already exist. The only blocker
was validate_nvidia_recipe_options, which hard-rejected everything but qwen.
Open the gate to gemma4/gemma4_unified, update the error message + docstrings
to name all four supported families honestly (this is the same format map
generalized to gemma4's standard attention, not an official NVIDIA gemma
recipe), and re-point the anti-smuggle integration test at a still-unsupported
family (lfm2) so it stays meaningful.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nt for --q-recipe nvidia on gemma4 The gemma4 gate opened in ce25261 had three holes: 1. [high] The gate validated the input config's model_type but the sanitizer dispatches from options.model_type (the caller's -m), so a gemma4 dir with `-m qwen3_5` sanitized as Qwen -> corrupt output. Add a config/-m family agreement check (gemma4 and gemma4_unified collapse to one family and agree). 2. [medium] The gate read only top-level config.model_type, so an architecture-only unified config (no model_type, architectures: ["Gemma4UnifiedForConditionalGeneration"]) was wrongly rejected. Resolve gemma4_unified from architectures at the call site. 3. [medium] A gemma4 MoE config (enable_moe_block: true, e.g. 26B-A4B) passed the gate but its experts.switch_glu.* keys have no .mlp. infix, so the nvidia predicate leaves them bf16. Reject gemma4 MoE (dense-only). validate_nvidia_recipe_options now takes (config_family, requested_model_type, is_moe, ...) with a nvidia_recipe_family helper collapsing model_type to the recipe family. build_nvidia_recipe is unchanged. GGUF caller updated to the new signature (still passes None -> rejected). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ias-robust for --q-recipe nvidia Round-2 review of the nvidia gemma4 gate found two residual gaps: - is_moe was resolved root-first, but real gemma configs carry enable_moe_block under text_config and the loader (get_config_bool) resolves nested-first. A root:false + nested:true config would read dense here yet load as MoE. Reuse get_config_bool so the gate's dense/MoE view always matches the loader. - is_gemma_prequantized keyed on the exact requested model_type "gemma4", so an aliased -m gemma4_unified on a gemma-QAT source slipped the already-quantized rejection into the generic quantizer. Key on the gemma family (via nvidia_recipe_family) instead — alias-robust, still options-keyed so QAT configs that omit model_type and pass -m gemma4 keep working. Adds two lightweight integration regression tests (text_config MoE reject; gemma-QAT alias-override reject); the existing gemma-prequant honest-block test still passes. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… mxfp build The local convert produced mxfp4 (MLP) + mxfp8 (attention) via `--q-recipe nvidia` (8.6 GB, coherent + tool-calling through `mlx agent`), not plain q4-affine. Update the hidden placeholder's slug/size/description to match; it stays hidden until the user uploads the repo (slug provisional). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Document the shipped `mlx agent` command: usage (interactive, `-c` resume, `-p`/`--no-session` print, `--mode json`, `--models-dir`), the first-run wizard over the 3 visible curated catalog entries, config home `~/.mlx-node/agent`, the bash/write/edit permission gate plus `MLX_AGENT_AUTO_APPROVE=1`, and the passthrough install/remove/list/config commands with `update` blocked. README gets a "first all-in-one local coding agent" feature row and a cli-package overview mention. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Spawn the built `packages/cli/dist/cli.js` via `process.execPath` and run one real `mlx agent -p ... --no-session` print-mode turn, asserting exit 0 and the model answer on stdout. Gated exactly like provider-live.test.ts (candidate qwen3.5-0.8b model paths, `describe.skipIf`) plus the built CLI entry, so it skips cleanly when no local model or build exists (CI has neither). stdin ignored so the pi print-mode wrapper never blocks; temp `PI_CODING_AGENT_DIR` cleaned up. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The Task 2/3 spike scripts carried fmt drift; format them so the branch's own files pass `vp fmt`. The 5 other files oxfmt flags are pre-existing drift on main (unchanged by this branch) and are left untouched. Co-Authored-By: Claude Opus 4.8 <[email protected]>
`gemma4_text` is a real dense gemma-4 root model_type in this repo (model-loader rawModelTypes; the CLI collapses it to --model-type gemma4). The nvidia gate read the input config's own model_type, so a gemma4_text config was rejected as unsupported even though the sanitizer dispatches on the already-collapsed gemma4 and would run fine. Collapse gemma4_text into the gemma4 family in nvidia_recipe_family; the dense-only and family-agreement guards still hold. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ne for new sessions
Persisting `layers` across EVERY session_start over-disclosed on fresh-session
lifecycles. pi's `SettingsManager.reload()` (reason 'reload') is its ONLY
retain-on-error path; the four fresh reasons ('startup'/'new'/'resume'/'fork')
build a NEW SettingsManager with BOOT semantics (bad file -> empty, no retain).
So after a session snapshotted PFX_A, a /new or /resume whose settings file is
malformed had the gate keep showing PFX_A while pi baked empty -> the prompt
showed a prefix pi won't execute.
Gate retention on `event.reason`, fail-safe: retain the prior snapshot ONLY for
a reload; use a blank baseline for the known fresh reasons; for any
unknown/missing/non-string reason RETAIN (over-disclosing a stale prefix is
safe, under-disclosing an executed one is not). Everything else is unchanged
(outer-closure layers/snapshotted, per-factory sessionAllowed, zero-byte clear,
retain-on-parse-error, lock-free read). Also documents the one accepted residual
(pi's locked read retains on lock-CONTENTION, undetectable by a lock-free read;
needs a concurrent lock-holder emptying the file at the reload instant -- an
actor who could just inject a disclosed prefix, so no escalation).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
A 0.8B model echoes the requested phrase but varies case, trailing punctuation, and line-wrapping run-to-run — a byte-exact toContain made this gated smoke test flake. Normalize case + whitespace; exit 0 stays the hard gate. 3/3 combined-suite runs green. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…e permission gate (WB-1)
pi does NO type validation on `shellCommandPrefix`: getShellCommandPrefix()
returns the raw merged value and bash.js:213 bakes
`commandPrefix ? `${commandPrefix}\n${command}` : command`, so pi executes
`String(v)+"\n"+cmd` for ANY truthy value (123, true, {…}, ["a","b"]) and the
bare command for any falsy value. The gate kept only STRING prefixes and merged
layers with `??`, so it under-disclosed a truthy non-string prefix (showed no
prefix while pi ran one) and let a present falsy/null project layer wrongly fall
through to the global.
Track the raw per-layer value + presence (`'shellCommandPrefix' in parsed`),
merge on key-presence (`project !== undefined ? project : global`, matching pi's
deepMergeSettings), and coerce once at the bash branch byte-identically to
bash.js:213 (`raw ? `${String(raw)}\n${command}` : command`). Reload retention,
the fresh-session reason gate, snapshot-primary + on-demand fallback, and the
never-throw reads are all preserved.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…mporter (WB-2) Task-9 (cd5d56a) changed `is_gemma_prequantized` from exact `model_type == "gemma4"` to `nvidia_recipe_family(model_type) == "gemma4"`, which collapses gemma4/gemma4_text/gemma4_unified. That single predicate fed 5 sites, so a requested `-m gemma4_unified` on a gemma-QAT source could reach the E2B prequantized importer — which hardcodes E2B's language schedule and DROPS AUDIO — violating the documented CLI contract (convert.ts: the exact-"gemma4" gate must not match unified). Split the predicate by role: `is_gemma_qat_family` (alias-robust) drives ONLY the pre-import already-quantized REJECT (preserving cd5d56a); the 4 import sites (validate_e2b_qat_schedule, import_gemma_prequantized, top_level_quant_metadata, config-write) use EXACT `model_type == "gemma4"`. A positively-unified gemma-QAT (which otherwise escapes both the family reject — needs a quant flag — and the exact import predicate) is now rejected explicitly and hermetically (pure config read, before the convert mutex + enter_cpu), computing is_unified exactly as models/gemma4/persistence.rs. Real E2B is model_type "gemma4", unaffected. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… calls (WB-4)
pi's canonical transformMessages DROPS every error/aborted assistant message
(partial or not) and synthesizes results for orphaned tool calls — but that runs
only inside pi's built-in providers, and our custom streamSimple bypasses it
(defaultConvertToLlm filters by role only). Our converter dropped only EMPTY
husks, so after a native error (R2-3 resets the native cache) or an Esc/abort the
invalid partial turn / dangling tool call was primed into the clean session,
garbling the continuation and corrupting unresolvedOkToolCallCount.
Mirror transformMessages with two passes: DROP every error/aborted assistant
(not tracking its tool calls), then before each following user/assistant and at
the end synthesize a native `{ role: 'tool', content: 'No result provided',
isError: true }` for any retained assistant tool call with no matching result.
The happy path and byte-stable joins are unchanged, so KV-prefix stability holds.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…arg scan (WB-3, WB-5)
WB-3: writePersistedDefaultModel collapsed absent / unreadable / malformed into
"start from {}" then overwrote the file with only the two default fields, so a
present-but-malformed settings.json lost every original setting (and it's
auto-invoked — readPersistedDefaultModel returns undefined on malformed → the
caller seeds). Now the seed writes ONLY on genuine ENOENT (fresh minimal file)
or a valid settings object (merging the two fields, preserving the rest); a
malformed / unreadable / non-object file is left byte-for-byte untouched, matching
pi's treat-as-load-error behavior.
WB-5: scanAgentArgs matched --models-dir/-h/--help by exact token at ANY
position, unlike withDefaultModel's value-aware model scan, so a value token
after a pi value-consumer (`--system-prompt --models-dir x`) was hijacked. Hoist
VALUE_CONSUMING_ARGS to module scope and rewrite scanAgentArgs as ONE pi-parity
value-aware walk sharing it: a pi value-consumer forwards its value verbatim
(never re-interpreted as mlx's flag), and --models-dir/help are recognized only
in an option-NAME position. All three call sites now parse identically.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_73bc658f-7241-4541-82db-481a9f4f39ae) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d38ce5f3dc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
spike-a-fake-provider / spike-b-warm-replay were exploration scratch; their conclusions live in the provider doc comments and tests. Co-Authored-By: Claude Fable 5 <[email protected]>
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_2b966511-6ed3-4cf9-9fc5-32d1baf45596) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 824458edc9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Yarn 4.17.0's builtin compat/typescript patch fails on the TS 7 package layout (lib/_tsc.js no longer exists), so the pinned yarn release moves to 4.17.1 which handles it. tsc -b, type-aware lint, and agent unit tests all pass. Co-Authored-By: Claude Fable 5 <[email protected]>
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_de55a1d5-33dc-4c0f-a271-4ea2cf28e71e) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 02da82ecef
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
On a fresh install with zero discovered models, `mlx agent --version`, `-v`, and `--export <session>` fell into the empty-model branch and hit the first-run wizard (non-TTY: exit 1) even though pi answers all three before model resolution. scanAgentArgs now detects them (value-position aware: --export only when it consumed a value; --version/-v only in an option-name position) and run() forwards them verbatim like the existing package/config passthrough. --list-models deliberately stays on the wizard path: with zero models pi prints a dead-end /login hint, while the wizard can actually produce a model. Found by Codex review on PR #95. Co-Authored-By: Claude Fable 5 <[email protected]>
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_f766d407-2a51-4b16-b587-7c2036475b9c) |
pi consumes '' as the export value but gates on truthiness (if (parsed.export)), so it never exports-and-exits — it falls into normal session startup. With piOneShot set, a fresh install ran that path with zero models and no wizard: silent no-op, exit 0. The one-shot now requires a non-empty consumed value; '--export ""' stays on the discovery/wizard path. Found by adversarial review of c01b8cb. Co-Authored-By: Claude Fable 5 <[email protected]>
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_d53ca335-04cd-469a-8b3c-e0b320d59044) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5374d69d75
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…untime
Bumps @earendil-works/pi-ai and pi-coding-agent 0.80.6 → 0.81.1 (agent pins;
dashboard ^0.81.1). 0.81.1 refactored pi's model layer: createAgentSession's
`modelRegistry` option was replaced with `modelRuntime`, and `ModelRegistry`
became a sync compatibility facade over a private `ModelRuntime` that internal
model listing/selection/resolution now reads directly.
- Subagent runtime (subagent.ts): the subagent runs with no extensions, so it
inherited the parent's mlx provider by passing `modelRegistry` — the removed
option. It now fetches the parent's registered mlx config publicly via
`modelRegistry.getRegisteredProviderConfig('mlx')` (fail-closed if absent),
builds a fresh `ModelRuntime.create()` (no network), registers that config on
it, and passes `modelRuntime` to createAgentSession. The config's streamSimple
closure is bound to the single shared MlxModelHost, so subagent inference
stays serialized on the one GPU-resident model (dispatch is by provider id).
- mlx-only filter (model-registry-filter.ts + run-agent.ts): retargeted from
`ModelRegistry.prototype` to `ModelRuntime.prototype`. In 0.81.1 the facade is
built once solely for ExtensionContext, so patching it no longer gates the
selector / /models / RPC / resolution / restore paths — they read the runtime
directly. Without this move the bump silently defeats PR #95's mlx-only
guarantee (an ambient cloud API key would surface cloud models). Patches
getModels / getAvailableSnapshot / getAvailable (async) / getModel /
hasConfiguredAuth(providerId); same allow-list; WeakSet + idempotent-restore +
fail-closed descriptor checks preserved.
- Tests: 0.81.1 removed AuthStorage from the barrel and ModelRegistry.inMemory,
which broke two agent tests (latent — excluded from tsc). Rebuilt them on real
ModelRuntime.create() + registerProvider; added a subagent fail-closed case
and a runtime-seam integration test proving provider-id dispatch on a fresh
runtime through the shared host.
Gate: typecheck 0; agent 277/277; dashboard 202/202; lint 0.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Third offline-boundary hole found in adversarial review, verified against the pi 0.81.1 dist: PI_OFFLINE and the model-read filters do NOT cover `/login`. pi builds the login list from `ModelRuntime.getProviders()` and dispatches sign-in through `ModelRuntime.login()`; the OAuth path (e.g. radius.pi.dev) fetches without consulting PI_OFFLINE. Our filter patched only the read methods, so `/login radius` reached cloud OAuth and could persist a cloud credential. (Pre-existing since PR #95 via 0.80.6's authStorage path; the 0.81.1 migration relocated the plumbing onto getProviders/login.) Fix: extend installMlxOnlyModelRegistryFilter to also patch, on ModelRuntime.prototype: - getProviders() -> filtered to id === 'mlx' (hides every cloud provider from the /login enumeration/autocomplete). - login(providerId, ...) -> rejects any non-mlx id BEFORE dispatch, so no OAuth fetch can fire even if a provider id is passed directly. The mlx provider is registered with a literal apiKey and never needs /login. Verified internally safe: the runtime's plural getProviders() has exactly one external caller (the /login list); streaming/resolution use getProvider (singular) / ModelsImpl, so filtering the plural to [mlx] breaks nothing. Tests: unit assertions for getProviders/login filter+restore; plus a real ModelRuntime fetch-spy regression proving `/login radius` is rejected with zero outbound fetch while filtered, and providers restore after. Gates: typecheck 0, agent 279/279, lint 0. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TJDW78dFbnx7ZrvVCeF7Yq
…untime
Bumps @earendil-works/pi-ai and pi-coding-agent 0.80.6 → 0.81.1 (agent pins;
dashboard ^0.81.1). 0.81.1 refactored pi's model layer: createAgentSession's
`modelRegistry` option was replaced with `modelRuntime`, and `ModelRegistry`
became a sync compatibility facade over a private `ModelRuntime` that internal
model listing/selection/resolution now reads directly.
- Subagent runtime (subagent.ts): the subagent runs with no extensions, so it
inherited the parent's mlx provider by passing `modelRegistry` — the removed
option. It now fetches the parent's registered mlx config publicly via
`modelRegistry.getRegisteredProviderConfig('mlx')` (fail-closed if absent),
builds a fresh `ModelRuntime.create()` (no network), registers that config on
it, and passes `modelRuntime` to createAgentSession. The config's streamSimple
closure is bound to the single shared MlxModelHost, so subagent inference
stays serialized on the one GPU-resident model (dispatch is by provider id).
- mlx-only filter (model-registry-filter.ts + run-agent.ts): retargeted from
`ModelRegistry.prototype` to `ModelRuntime.prototype`. In 0.81.1 the facade is
built once solely for ExtensionContext, so patching it no longer gates the
selector / /models / RPC / resolution / restore paths — they read the runtime
directly. Without this move the bump silently defeats PR #95's mlx-only
guarantee (an ambient cloud API key would surface cloud models). Patches
getModels / getAvailableSnapshot / getAvailable (async) / getModel /
hasConfiguredAuth(providerId); same allow-list; WeakSet + idempotent-restore +
fail-closed descriptor checks preserved.
- Tests: 0.81.1 removed AuthStorage from the barrel and ModelRegistry.inMemory,
which broke two agent tests (latent — excluded from tsc). Rebuilt them on real
ModelRuntime.create() + registerProvider; added a subagent fail-closed case
and a runtime-seam integration test proving provider-id dispatch on a fresh
runtime through the shared host.
Gate: typecheck 0; agent 277/277; dashboard 202/202; lint 0.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Third offline-boundary hole found in adversarial review, verified against the pi 0.81.1 dist: PI_OFFLINE and the model-read filters do NOT cover `/login`. pi builds the login list from `ModelRuntime.getProviders()` and dispatches sign-in through `ModelRuntime.login()`; the OAuth path (e.g. radius.pi.dev) fetches without consulting PI_OFFLINE. Our filter patched only the read methods, so `/login radius` reached cloud OAuth and could persist a cloud credential. (Pre-existing since PR #95 via 0.80.6's authStorage path; the 0.81.1 migration relocated the plumbing onto getProviders/login.) Fix: extend installMlxOnlyModelRegistryFilter to also patch, on ModelRuntime.prototype: - getProviders() -> filtered to id === 'mlx' (hides every cloud provider from the /login enumeration/autocomplete). - login(providerId, ...) -> rejects any non-mlx id BEFORE dispatch, so no OAuth fetch can fire even if a provider id is passed directly. The mlx provider is registered with a literal apiKey and never needs /login. Verified internally safe: the runtime's plural getProviders() has exactly one external caller (the /login list); streaming/resolution use getProvider (singular) / ModelsImpl, so filtering the plural to [mlx] breaks nothing. Tests: unit assertions for getProviders/login filter+restore; plus a real ModelRuntime fetch-spy regression proving `/login radius` is rejected with zero outbound fetch while filtered, and providers restore after. Gates: typecheck 0, agent 279/279, lint 0. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TJDW78dFbnx7ZrvVCeF7Yq
…untime
Bumps @earendil-works/pi-ai and pi-coding-agent 0.80.6 → 0.81.1 (agent pins;
dashboard ^0.81.1). 0.81.1 refactored pi's model layer: createAgentSession's
`modelRegistry` option was replaced with `modelRuntime`, and `ModelRegistry`
became a sync compatibility facade over a private `ModelRuntime` that internal
model listing/selection/resolution now reads directly.
- Subagent runtime (subagent.ts): the subagent runs with no extensions, so it
inherited the parent's mlx provider by passing `modelRegistry` — the removed
option. It now fetches the parent's registered mlx config publicly via
`modelRegistry.getRegisteredProviderConfig('mlx')` (fail-closed if absent),
builds a fresh `ModelRuntime.create()` (no network), registers that config on
it, and passes `modelRuntime` to createAgentSession. The config's streamSimple
closure is bound to the single shared MlxModelHost, so subagent inference
stays serialized on the one GPU-resident model (dispatch is by provider id).
- mlx-only filter (model-registry-filter.ts + run-agent.ts): retargeted from
`ModelRegistry.prototype` to `ModelRuntime.prototype`. In 0.81.1 the facade is
built once solely for ExtensionContext, so patching it no longer gates the
selector / /models / RPC / resolution / restore paths — they read the runtime
directly. Without this move the bump silently defeats PR #95's mlx-only
guarantee (an ambient cloud API key would surface cloud models). Patches
getModels / getAvailableSnapshot / getAvailable (async) / getModel /
hasConfiguredAuth(providerId); same allow-list; WeakSet + idempotent-restore +
fail-closed descriptor checks preserved.
- Tests: 0.81.1 removed AuthStorage from the barrel and ModelRegistry.inMemory,
which broke two agent tests (latent — excluded from tsc). Rebuilt them on real
ModelRuntime.create() + registerProvider; added a subagent fail-closed case
and a runtime-seam integration test proving provider-id dispatch on a fresh
runtime through the shared host.
Gate: typecheck 0; agent 277/277; dashboard 202/202; lint 0.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Third offline-boundary hole found in adversarial review, verified against the pi 0.81.1 dist: PI_OFFLINE and the model-read filters do NOT cover `/login`. pi builds the login list from `ModelRuntime.getProviders()` and dispatches sign-in through `ModelRuntime.login()`; the OAuth path (e.g. radius.pi.dev) fetches without consulting PI_OFFLINE. Our filter patched only the read methods, so `/login radius` reached cloud OAuth and could persist a cloud credential. (Pre-existing since PR #95 via 0.80.6's authStorage path; the 0.81.1 migration relocated the plumbing onto getProviders/login.) Fix: extend installMlxOnlyModelRegistryFilter to also patch, on ModelRuntime.prototype: - getProviders() -> filtered to id === 'mlx' (hides every cloud provider from the /login enumeration/autocomplete). - login(providerId, ...) -> rejects any non-mlx id BEFORE dispatch, so no OAuth fetch can fire even if a provider id is passed directly. The mlx provider is registered with a literal apiKey and never needs /login. Verified internally safe: the runtime's plural getProviders() has exactly one external caller (the /login list); streaming/resolution use getProvider (singular) / ModelsImpl, so filtering the plural to [mlx] breaks nothing. Tests: unit assertions for getProviders/login filter+restore; plus a real ModelRuntime fetch-spy regression proving `/login radius` is rejected with zero outbound fetch while filtered, and providers restore after. Gates: typecheck 0, agent 279/279, lint 0. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TJDW78dFbnx7ZrvVCeF7Yq
…untime
Bumps @earendil-works/pi-ai and pi-coding-agent 0.80.6 → 0.81.1 (agent pins;
dashboard ^0.81.1). 0.81.1 refactored pi's model layer: createAgentSession's
`modelRegistry` option was replaced with `modelRuntime`, and `ModelRegistry`
became a sync compatibility facade over a private `ModelRuntime` that internal
model listing/selection/resolution now reads directly.
- Subagent runtime (subagent.ts): the subagent runs with no extensions, so it
inherited the parent's mlx provider by passing `modelRegistry` — the removed
option. It now fetches the parent's registered mlx config publicly via
`modelRegistry.getRegisteredProviderConfig('mlx')` (fail-closed if absent),
builds a fresh `ModelRuntime.create()` (no network), registers that config on
it, and passes `modelRuntime` to createAgentSession. The config's streamSimple
closure is bound to the single shared MlxModelHost, so subagent inference
stays serialized on the one GPU-resident model (dispatch is by provider id).
- mlx-only filter (model-registry-filter.ts + run-agent.ts): retargeted from
`ModelRegistry.prototype` to `ModelRuntime.prototype`. In 0.81.1 the facade is
built once solely for ExtensionContext, so patching it no longer gates the
selector / /models / RPC / resolution / restore paths — they read the runtime
directly. Without this move the bump silently defeats PR #95's mlx-only
guarantee (an ambient cloud API key would surface cloud models). Patches
getModels / getAvailableSnapshot / getAvailable (async) / getModel /
hasConfiguredAuth(providerId); same allow-list; WeakSet + idempotent-restore +
fail-closed descriptor checks preserved.
- Tests: 0.81.1 removed AuthStorage from the barrel and ModelRegistry.inMemory,
which broke two agent tests (latent — excluded from tsc). Rebuilt them on real
ModelRuntime.create() + registerProvider; added a subagent fail-closed case
and a runtime-seam integration test proving provider-id dispatch on a fresh
runtime through the shared host.
Gate: typecheck 0; agent 277/277; dashboard 202/202; lint 0.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Third offline-boundary hole found in adversarial review, verified against the pi 0.81.1 dist: PI_OFFLINE and the model-read filters do NOT cover `/login`. pi builds the login list from `ModelRuntime.getProviders()` and dispatches sign-in through `ModelRuntime.login()`; the OAuth path (e.g. radius.pi.dev) fetches without consulting PI_OFFLINE. Our filter patched only the read methods, so `/login radius` reached cloud OAuth and could persist a cloud credential. (Pre-existing since PR #95 via 0.80.6's authStorage path; the 0.81.1 migration relocated the plumbing onto getProviders/login.) Fix: extend installMlxOnlyModelRegistryFilter to also patch, on ModelRuntime.prototype: - getProviders() -> filtered to id === 'mlx' (hides every cloud provider from the /login enumeration/autocomplete). - login(providerId, ...) -> rejects any non-mlx id BEFORE dispatch, so no OAuth fetch can fire even if a provider id is passed directly. The mlx provider is registered with a literal apiKey and never needs /login. Verified internally safe: the runtime's plural getProviders() has exactly one external caller (the /login list); streaming/resolution use getProvider (singular) / ModelsImpl, so filtering the plural to [mlx] breaks nothing. Tests: unit assertions for getProviders/login filter+restore; plus a real ModelRuntime fetch-spy regression proving `/login radius` is rejected with zero outbound fetch while filtered, and providers restore after. Gates: typecheck 0, agent 279/279, lint 0. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TJDW78dFbnx7ZrvVCeF7Yq
mlx agent— mlx-node's first all-in-one local coding agentOne command, a local model, local tools, no API keys and no cloud hop.
mlx agentembeds the pi coding-agent SDK (MIT,@earendil-works/*@0.80.6) and drives it against an in-process@mlx-node/lmChatSession — inference runs in the same process, so there is no HTTP server and no localhost port.What you get
mlx agentboots the full pi surface — TUI, JSONL session trees (-c/--resume/fork),/compactauto-compaction,/modelpicker, extensions/skills/prompts/themes, AGENTS.md/CLAUDE.md context loading, print (-p) and RPC modes — all pointed at a local model.pi.registerProvider("mlx", …)so mlx models are first-class at every LLM call site (main loop, compaction, branch summaries). Each turn cold-replays throughprimeHistory+startFromHistoryStreamwith native KV-prefix reuse, so it stays warm while sidestepping ChatSession's one-unresolved-tool-call limit.bash/write/edit, discloses pi's effectiveshellCommandPrefix, encodes (never deletes) shell-significant/control bytes in the prompt, fails closed, and blocks in non-interactive mode unlessMLX_AGENT_AUTO_APPROVE=1.mlx downloadmachinery → starts. Config home is~/.mlx-node/agent/*.--q-recipe nvidiaextended to dense gemma4 — mxfp4 MLP + mxfp8 attention, tied head + vision bf16; produced the validated Gemma-4-12B build the catalog points at.Structure
New
packages/agent(@mlx-node/agent): provider bridge (stream-adapter,convert-messages,chat-config,events,model-host,models, portedtool-call-buffer+warm-reuse),permission-gateextension, curatedcatalog,run-agentshell. Wired intopackages/cli(mlx agentcommand + wizard) andcrates/mlx-core/src/convert.rs(nvidia recipe for gemma4). Docs:docs/cli.md## mlx agent+ README.How it was built & verified
Executed via subagent-driven development — 10 tasks, each gated by an adversarial codex review, then a holistic whole-branch review. That final pass surfaced 5 cross-cutting interaction defects the per-task reviews structurally couldn't (non-string
shellCommandPrefixunder-disclosure, a gemma4_unified QAT reaching the audio-dropping E2B importer, a settings-seed clobber of malformedsettings.json, partial error/aborted turns replayed into a reset session, and an arg-scan value hijack) — all fixed and re-reviewed to VERDICT: PASS, zero findings.Gates (all green):
yarn typecheck, TS suites 146/146,cargo test -p mlx-core --lib(nvidia_recipe 18/0, gemma 321/0, + hermetic unified-QAT reject),vp lint --type-aware,cargo clippy -D warnings,cargo fmt --check. Model-heavy provider/E2E tests are gated behinddescribe.skipIfand skip cleanly in CI.Follow-up (non-blocking)
The Gemma-4-12B catalog slot is present but hidden pending the maintainer uploading the validated
Gemma-4-12B-IT-nvidia-mxfp-mlx(8.6 GB) build to Hugging Face. Once the repo slug is final: un-hide the entry inpackages/agent/src/catalog.tsand drop the wizard hidden-guard test block. The agent ships fully functional with the other catalog models in the meantime.🤖 Generated with Claude Code
Note
Medium Risk
New permission-gated tool execution and argv/settings handling affect local-first routing and user data paths; conversion recipe changes touch quantization for gemma4 dense builds but are gated with explicit rejects for MoE and gemma-QAT misuse.
Overview
Adds
mlx agent, an offline coding agent that embeds the pi SDK (@earendil-works/*@0.80.6) and routes every LLM turn through an in-process@mlx-node/lmChatSession(no HTTP server or API keys).The new
@mlx-node/agentpackage registers an mlx provider bridge (message conversion, streaming adapter, warm KV reuse via history replay), a permission gate forbash/write/edit(interactive approve orMLX_AGENT_AUTO_APPROVE=1), model discovery/hosting, and a curated download catalog.packages/cliwiresscanAgentArgs/withDefaultModel/run()so pi flags pass through, local models are injected ahead of cloud defaults, session/provider runs get--models mlx/*, settings under~/.mlx-node/agentare seeded write-once, andupdateis blocked.First-run wizard downloads a visible catalog entry via existing
mlx downloadwhen no local checkpoint exists.--q-recipe nvidiavalidation and the recipe map are extended to densegemma4/gemma4_unified(mxfp4 MLP, mxfp8 attention; MoE gemma4 rejected), supporting the validated Gemma-4-12B build (catalog entry present but hidden until HF publish). README anddocs/cli.mddocument the command.Reviewed by Cursor Bugbot for commit 5374d69. Bugbot is set up for automated code reviews on this repo. Configure here.