@duyviet1804/pi-moa
Mixture of Agents (MoA) Fusion workflow provider for pi
Package details
Install @duyviet1804/pi-moa from npm and Pi will load the resources declared by the package manifest.
$ pi install npm:@duyviet1804/pi-moa- Package
@duyviet1804/pi-moa- Version
0.5.3- Published
- Aug 3, 2026
- Downloads
- 2,435/mo · 138/wk
- Author
- duyviet1804
- License
- MIT
- Types
- extension
- Size
- 307.4 KB
- Dependencies
- 1 dependency · 4 peers
Pi manifest JSON
{
"extensions": [
"./extensions/pi-moa.ts"
]
}Security note
Pi packages can execute code and influence agent behavior. Review the source before installing third-party packages.
README
pi-moa
pi-moa is a Pi 0.80.6+ package that adds two local Mixture of Agents workflow models. By default, one read-only advisor plan guides the normal Pi actor; successful tool batches stay actor-only and final review is off.
Choose a preset
Fusion Fast — stable
Fusion Fast is the recommended daily preset. Its built-in actor is opencode-go:deepseek-v4-flash; opencode-go:glm-5.2 supplies the initial plan with an 8000-token output cap.
Fusion — improving
Fusion uses the same actor with parallel plans from opencode-go:glm-5.2 and opencode-go:kimi-k2.6.
| Path | Actor calls | Advisor calls | Notes |
|---|---|---|---|
| Happy terminal answer | 1 | 1 | One initial advisor batch; no final review |
| First failed batch | 1 | 2 | Initial plan plus one failure checkpoint |
| Successful continuation | 1 | 0 | Retained plan is reused |
Both presets default to brain-once: initial planning, retained advice, failure-only checkpoints, and finalGate:false. actor-first-reviewed remains selectable when strict provider-owned final review is worth the extra latency and possible candidate withholding.
See CHANGELOG.md for release details.
0.5.3 highlights
- Hybrid task routing. Advisors classify work as
DIRECT,PLAN, orEXECUTION-CONTRACT: clear tasks go straight to the actor, ambiguous tasks retain a plan, approved plans remain authoritative, and materialized skills run actor-first with bounded review. - Brain on Demand is available without becoming the default.
actor-first-reviewedstarts with the actor, permits one failure rescue, privately reviews terminal candidates, allows one correction, and keeps unavailable reviews retryable; dailybrain-onceremains the default with final review off. - Actor-aware tool reliability is bundled. DeepSeek V4/GLM guidance, schema-shaped argument repair, exact-write and safety guards, failure hints, and conditional
apply_patchregistration use the configured actor rather than the outer Fusion model. - Live, bounded advisor visibility. Redacted reasoning tails and partial Markdown stream transiently while bounded final responses remain in local activity cards outside model context.
Compared with 0.5.2
| Area | 0.5.2 | 0.5.3 |
|---|---|---|
| Workflow | Initial advisor plan plus actor | Hybrid DIRECT/PLAN/EXECUTION-CONTRACT, plus opt-in actor-first review |
| Final review | Optional parallel unanimous approval | Ordered availability fallback, one persisted correction, and /pi-moa retry-review |
| Skills and plans | Approved plans execute directly | Approved plans become execution contracts; materialized skills run actor-first with bounded review |
| Actor tools | Prompt-level DeepSeek routing | Actor-aware repair, guards, recovery hints, and bundled apply_patch |
| Advisor UI | Completed bounded activity cards | Transient live stream plus completed bounded cards |
0.5.2 highlights
- Fusion Fast is the stable preset. It is the recommended daily default; the two-advisor Fusion preset remains available while its quality/latency tradeoff is still improving.
- Tool turns keep nested internals private. Final-gated tool steps publish only the
toolCallblocks, not actor thinking or prose, and execution/correction guidance no longer exposes MoA wrappers or provider labels. - Final corrections tolerate safe reviewer preambles. A valid trailing
REVISEblock is actionable even when the reviewer prefixes prose; only that revision block reaches the actor.APPROVEremains exact, unanimous, and fail-closed. - Fusion Fast now routes semantic work like direct DeepSeek. When Serena tools are active, symbol/declaration/reference work is directed to Serena first. Explicit run/build/lint requests use
bashfirst without exploratory file inspection, while discovery prompts are not forced down that path. - Controlled routing results reached parity on the target paths. Across 48 matched runs, Fusion first-tool correctness rose from 21/24 to 24/24, required sequences from 21/24 to 23/24, corrected completion from 20/24 to 24/24, and blank finals from four to zero. Serena-first improved from 0/3 to 3/3 and bash-first from 2/3 to 3/3.
0.5.1 highlights
- Fusion Fast acts with DeepSeek V4 Flash. The built-in fallback and shipped Fast example both use
opencode-go:deepseek-v4-flash; existing model-slot overrides remain authoritative. - Same-session follow-ups retain advisor context. The opt-in
advisorContextMode: "session"supplies the plan advisor with Pi's sanitized prior session context plus the latest turn, fixing follow-ups after a completed task and stop/switch/continuehandoffs without adding a second memory system. The default remainsturn. - The latest turn keeps the budget. Session history uses only the space left after current-turn evidence and preserves the history head and recent tail. By default Pi MoA derives the safe bound from the smallest configured advisor
contextWindow, reserving output/reasoning, prompts, read-only tools, and provider overhead; a positivemaxAdvisorContextCharsremains an optional smaller failsafe. - Context use is measurable. Advisor diagnostics record model-window tokens, reserved tokens, effective budget source/characters, configured/effective scope, source characters, sent characters, and truncation—never raw context.
/pi-moareportsautoor the explicit override. - Final review stays short and fail-closed. When the opt-in final gate is enabled, its primary verdict uses
minimalreasoning and at most 4096 output tokens; only unanimous validAPPROVEverdicts release the candidate. Malformed, unavailable, or repeatedly revising reviews withhold it; plan and failure-checkpoint budgets are unchanged. - Advisor work is visible live. While each Advisor runs, Pi shows a transient, secret-redacted reasoning tail and rendered partial Markdown. The widget is cleared after the batch; only the configured Advisors' bounded final responses enter the existing local activity card, never reasoning, actor messages, diagnostics, or model context.
- Cards stay compact and context-private. Pi shows a short collapsed preview and bounded multiline output when expanded. The display copy is stored in local session history but remains outside actor messages and LLM context; cache hits add no duplicate card or model call.
- Durable output is bounded safely. Each stored advisor display is capped at 20,000 Unicode code points with surrogate-safe middle truncation, and terminal control characters are stripped. The actor still receives the original authoritative response.
- Plan Mode stops at external approval. Under
pi-plan's canonical Plan Mode, Pi MoA keepswrite_planstatus atdraftand settles locally with zero tokens after the plan is written. After approval, the actor executes that plan directly without another planning-advisor call; failure checkpoints and the optional final review remain separate. - Blocking choices remain interactive. The actor retains
ask_plan_questionand the Plan Mode instructions, waits for the user's selection, then resumes planning and can write the draft. Deterministic coverage proves no plan write, approval, or implementation occurs before the answer, and no follow-up inner model call runs while the question is waiting. - Plans survive reloads without replanning. Generated plans are stored as Pi custom entries outside LLM context and restored only for the exact user-turn key. This removes dependence on transient
advisorTurnPlansstate without adding cross-session memory. - Parallel failures cannot hide behind later successes. Checkpoint gating evaluates every result from the latest actor tool-call batch, independent of completion order, while later successful batches still supersede failures that were already reviewed.
- Plans and reviews require usable evidence. Every explicit requirement maps to a finite criterion; current external facts must be verified before use, dependent operations stay sequential, and setup/deployment completion requires redacted effective-state evidence rather than health alone.
0.5.1 live validation
- Real tool routing passed. A fresh Fusion Fast run completed 9/9 representative calls across Serena, FFF, Munin, Brave/pi-web, and RTK. It used one plan plus the opt-in final review, and RTK rewriting appeared in the real tool event chain.
- Failure checkpoints corrected a real deployment fault. During a separate Crawl4AI 0.9.2 setup, failed health checks triggered evidence-based checkpoints that identified its secure-by-default loopback binding. Final approval waited for direct health, PNG, PDF, and Pi-tool evidence; all seven pi-web tools then passed in that local environment.
These are environment-specific integration results. Pi MoA does not install or bundle Serena, FFF, Munin, pi-web, RTK, Firecrawl, Brave, or Crawl4AI.
Bundled actor tool core
Installing pi-moa now includes a Pi-MoA-aware subset of pi-model-tools for
Fusion and Fusion Fast. It detects the configured actor rather than the outer
pi-moa/Fusion* model ID:
- DeepSeek V4 actors receive first-tool/Serena guidance, semantic-miss steering,
shared safety guards, schema-shaped argument repair, recovery hints, and
apply_patchpreference. - GLM actors receive the shared prompt-aware hints, argument repair, safety guards, and recovery hints without DeepSeek-only steering.
- Unsupported actor families cleanly disable the model-specific core.
/pi-moareports the effective family for each preset.
apply_patch is registered only when another extension has not already provided
it. The bundled core does not override Pi's seven built-ins and does not include
pi-model-tools reasoning cleanup, Super Power Mode, or automatic edit retry.
Install standalone @bacnh85/pi-model-tools only when direct, non-Pi-MoA
DeepSeek/GLM sessions also need its full behavior; both packages may coexist.
The bundled core reuses these optional pi-model-tools settings:
| Variable | Default | Purpose |
|---|---|---|
PI_MODEL_TOOLS_REPAIR_ENABLED |
1 |
Repair schema-shaped actor tool arguments |
PI_MODEL_TOOLS_SELECTION_GUIDANCE |
on | DeepSeek first-tool guidance |
PI_MODEL_TOOLS_STRICT_SERENA |
off | Block simple bash substitutes for dedicated tools |
PI_MODEL_TOOLS_AUTO_BLOCK_AFTER_REMINDERS |
0 |
Block repeated dedicated-tool misses after N reminders |
PI_MODEL_TOOLS_BLOCK_DANGEROUS_COMMANDS |
1 |
Block destructive absolute-path commands |
Serena and FFF with Fusion
pi-serena and pi-fff do not need source patches for Fusion. For persistent,
upgrade-safe routing, launch Pi with their public settings:
PI_FFF_MODE=override PI_SERENA_REMIND_ON_FIRST_MISS=1 pi
FFF is model-agnostic; override mode makes generic find and grep use FFF
even when the actor does not select fffind or ffgrep. Serena tools and
Serena-first guidance are also model-agnostic, while Pi MoA applies its own
DeepSeek behavior from the configured effective actor. Put these variables in a
shell profile or Pi wrapper to retain them across launches; /fff-mode override
only changes the current process. Strict Serena mode remains opt-in because an
actor that ignores blocked-call guidance can retry-loop.
Pi still reports ctx.model as pi-moa/Fusion*; Pi 0.82.1 has no delegated
effectiveModel lifecycle API. The configured actor is exposed as the response
model and in /pi-moa status, but changing generic extension lifecycle identity
requires upstream Pi support.
Install
pi install npm:@duyviet1804/pi-moa
Pinned version:
pi install npm:@duyviet1804/pi-moa@0.5.3
From git or a local checkout:
pi install git:github.com/duyviet1804/pi-moa
pi install ./path/to/pi-moa
Authentication
Fusion requires:
opencode-go:glm-5.2;opencode-go:kimi-k2.6;opencode-go:deepseek-v4-flash.
Fusion Fast keeps the OpenCode Go-only default:
opencode-go:glm-5.2;opencode-go:deepseek-v4-flash.
Run /login in Pi and authenticate OpenCode Go, or use its supported environment variable:
export OPENCODE_API_KEY="..."
Authenticate every provider referenced by the selected preset or a custom config. Never put credentials in MoA JSON or committed files. Z.AI (zai) models such as zai:glm-5.2 may also be selected for any advisor or actor slot through /pi-moa; authenticate Z.AI via /login or its environment variable first.
Usage
pi --provider pi-moa --model Fusion
pi --provider pi-moa --model "Fusion Fast" --thinking high
Use Fusion Fast:high for daily work. Fusion adds a second parallel planning advisor. /pi-moa selects the workflow, advisor/actor slots, reasoning budget, planning context, and optional brain-once final gate. Timeout/empty recovery remains minimal.
After a successful iteration, Pi's footer shows MoA <n> tok/s: acting-model output divided by the complete advisor-plus-actor elapsed time for that iteration.
Change settings with /pi-moa
In Pi's TUI, run /pi-moa. Select actor-first-reviewed (Brain on Demand) or brain-once, choose authenticated openai-codex, opencode-go, and zai model slots, and set advisor reasoning. turn/session controls brain-once initial-plan scope only; actor-first rescue/final packets always use a fixed bounded task/evidence envelope. Use Retry pending final review or /pi-moa retry-review only after an unavailable final review.
For example, change both Fusion Fast slots:
/pi-moa
Select: Change Fusion Fast advisor
Select: openai-codex:gpt-5.4-mini
/pi-moa
Select: Change Fusion Fast advisor reasoning
Select: max
/pi-moa
Select: Change Fusion Fast advisor context
Select: session
/pi-moa
Select: Change Fusion Fast actor
Select: opencode-go:deepseek-v4-flash
/reload
The advisor menu can instead select opencode-go:glm-5.2 or zai:glm-5.2 when available. Changing advisor reasoning also updates referenceMaxTokens to the preset's matching budget. Fusion Fast selections are saved to ~/.pi/agent/moa-fast.json; the corresponding Fusion actions save to ~/.pi/agent/moa.json. Cancelling either menu writes nothing and leaves the existing configuration unchanged. Run /reload after model changes so picker metadata follows the configured actor.
RPC, JSON, and print modes continue to show status immediately without opening a dialog.
Configuration
Each model reads its own optional file:
| Model | File |
|---|---|
Fusion |
~/.pi/agent/moa.json |
Fusion Fast |
~/.pi/agent/moa-fast.json |
PI_CODING_AGENT_DIR replaces ~/.pi/agent when set. Missing files use built-in defaults; selecting a setting creates the corresponding file from those defaults. /pi-moa preserves untouched settings and only lists currently available/authenticated opencode-go, openai-codex, and zai models. Invalid files fail loudly and are never overwritten by the menu.
Start from the shipped examples instead of copying defaults from this README. Both examples explicitly select brain-once with final review off; the Fast example uses GPT-5.4 Mini before the same DeepSeek V4 Flash actor.
mkdir -p ~/.pi/agent
cp pi-moa.example.json ~/.pi/agent/moa.json
cp pi-moa-fast.example.json ~/.pi/agent/moa-fast.json
| Field | Required | Meaning |
|---|---|---|
referenceModels |
yes | Non-empty advisor model list; each entry needs provider and model. |
aggregator |
yes | Acting model that retains normal Pi tools. It receives an approved/generated plan in brain-once, or acts directly in Brain on Demand. |
referenceReasoning |
no | Advisor reasoning level: high (default) or max. Final review and recovery remain minimal. |
advisorContextMode |
no | turn (default) or opt-in session; affects brain-once initial planning only and never controls advisor cadence. |
advisorWorkflow |
no | brain-once (default) or strict actor-first-reviewed. Legacy files without this field also load as brain-once. |
referenceTemperature |
yes | Advisor temperature when supported; omitted for openai-codex. |
aggregatorTemperature |
yes | Acting-aggregator temperature when supported; omitted for openai-codex. |
referenceMaxTokens |
yes | Per-advisor output limit; /pi-moa sets Fusion to 16k/32k and Fusion Fast to 8k/16k for high/max. |
maxToolResultChars |
no | Per-tool-result truncation limit; default 6000. |
maxAdvisorContextChars |
no | Optional smaller serialized-input failsafe. 0 (default) uses the advisor model metadata automatically; positive values cap characters without bypassing the safe model budget. |
finalGate |
no | false by default. Required true for actor-first-reviewed; brain-once may opt in. Final calls use minimal reasoning and at most 4096 output tokens. |
Advisor context and independent limits
Pi MoA uses the smallest configured advisor model's catalog contextWindow and Pi's conservative chars/4 estimate. It subtracts the stage's referenceMaxTokens reasoning/output allowance, the actual advisor system prompt, room for up to eight bounded read-only tool results, tool-schema overhead, and provider slack. maxAdvisorContextChars: 0 uses that computed capacity; a positive value is only a smaller failsafe. The 180-second advisor deadline remains independent.
| Advisor stage | turn |
session |
|---|---|---|
Plan without authoritative pi-plan |
Latest user turn and its evidence | Bounded sanitized prior Pi context, then the latest turn |
Approved pi-plan execution |
Actor executes the approved plan directly | Same as turn; no initial planning-advisor call |
| Failure checkpoint (brain-once) | Retained plan plus latest-turn evidence | Same as turn |
| Actor-first rescue/final | Fixed bounded current task, approved plan if any, candidate where relevant, and exact current-turn evidence | Same fixed packet; this setting does not apply |
| Final review (brain-once) | Retained/approved plan, latest-turn evidence, and candidate answer | Same as turn |
For a brain-once same-session follow-up that needs older task context, select session under /pi-moa, keep automatic budgeting, and run /reload:
{
"advisorContextMode": "session",
"maxAdvisorContextChars": 0
}
Larger brain-once planning input can increase provider disclosure, prefill cost, latency, and timeout risk. Set a positive character value only when a smaller operational failsafe is needed. Session mode still omits assistant draft prose, hidden thinking, image bytes, and normal tool arguments; user text and bounded tool-result text may be sent. Actor-first review packets ignore this scope setting. The retired initial, postTool, full, and speculative auto scope values fail validation.
After editing either file manually, run /reload so model-picker metadata follows the configured aggregator.
Upgrading
From 0.3.0
Valid 0.3.0-shaped configs need no field migration, but an override keeps the model slots it names. Remove it or start from the shipped examples to adopt the new defaults, then run /reload.
0.5.3-brain-on-demand adds advisorWorkflow. Existing override files without it load as brain-once; an omitted legacy finalGate remains off. Saving through /pi-moa writes both fields explicitly. Switch to actor-first-reviewed only to opt into Brain on Demand's strict final review.
From 0.2.9 or older
Migrate an override to the current fields shown in the shipped examples, or back up and remove moa.json / moa-fast.json to use built-in defaults. Retired and unknown fields are rejected without printing their values.
How it works
actor-first-reviewed — opt-in strict review
- Pi MoA binds the real user request to an immutable turn key and stores a bounded task envelope outside LLM context. A no-user continuation reuses that active turn; without a real/restored turn it fails locally with zero model calls.
- An approved
pi-planis loaded with workspace-containment checks and passed directly to the actor. Otherwise the actor begins from the user request and current tool evidence—there is no initial advisor. - Successful batches continue actor-only. The first failed current-turn batch may invoke one read-only rescue using configured advisors in order; later slots run only when an earlier slot is unavailable. The rescue is marked consumed even when none succeeds.
- A terminal no-tool candidate stays private. Final reviewers run in configured order under one shared deadline and must return the exact JSON verdict/checks/issues contract. Malformed or unavailable output falls through; the first valid
APPROVEorREVISEis authoritative. APPROVEreleases the candidate. The firstREVISEstores evidence-backed guidance and allows one actor correction plus one re-review, surviving tool calls and reloads. A secondREVISEwithholds. Exhausted availability stores the bounded sanitized packet and candidate locally for/pi-moa retry-review; retry never calls the actor or planner first.
brain-once — default
- Missing retained/approved plans invoke parallel planning advisors and pass their raw responses directly to the actor.
- The retained plan guides actor tool batches. Successful batches bypass advisors; a failed latest batch invokes the existing
PASS/REVISEcheckpoint. finalGate:falsestreams actor output as before. With the gate enabled, brain-once shares the same ordered structured final-review, persisted correction, and fail-closed retry machinery as actor-first.
Advisor stages appear in Pi's working row, with transient secret-redacted reasoning tails and partial Markdown while calls stream, then bounded local activity cards containing only final responses. Cache hits add no model usage. Diagnostics record workflow, stage, review attempt, correction count, fallback order/selected slot, safe digests, context budget/truncation/redaction counts, runtime/failure categories, and token usage—never task/candidate/context text, tool arguments, raw provider errors, credentials, or hidden reasoning. Explicit cancellation remains fail-closed.
Task guidance
For coding work, advisors and the acting model use generic task-derived checks:
- derive acceptance criteria from the request and repository contract;
- inspect relevant source, tests, and tool evidence;
- prefer the smallest compatible existing or standard-library solution;
- preserve API and data invariants;
- consider failure, concurrency, mutation, and ordering only when relevant;
- run requested tests plus one focused risk check, then stop.
Runtime prompts intentionally contain no benchmark-specific expected fixes or hidden-test vocabulary.
Maintenance
pi update npm:@duyviet1804/pi-moa
pi remove npm:@duyviet1804/pi-moa
If configuration fails, fix the JSON or remove it to restore defaults:
rm ~/.pi/agent/moa.json ~/.pi/agent/moa-fast.json
If a configured model is missing, inspect Pi's catalog:
pi --list-models
Package contents
package.json
README.md
CHANGELOG.md
THIRD_PARTY_NOTICES.md
LICENSE
extensions/pi-moa.ts
src/moa-core.ts
src/pi-moa-tools.ts
pi-moa.example.json
pi-moa-fast.example.json
node_modules/@bacnh85/pi-model-tools/ (bundled core helpers)
See test/README.md for the capability-v3 benchmark, isolation boundary, metrics, and no-live gate.
Security
- Inner-model credentials are resolved per request through Pi's model registry and never copied into prompts or diagnostics; advisor errors are reduced to stable categories before the actor sees them.
- Wrapper-provider API keys, headers, and environment values are discarded; only credentials resolved for the selected inner model are forwarded.
- Advisor contexts omit image bytes, hidden thinking, assistant draft text, and normal tool arguments. Opt-in session mode sends additional sanitized prior user/tool evidence to configured advisor providers only for plan stages without an authoritative plan.
- Completed advisor display copies plus exact-turn plan state are stored in local Pi session history but remain outside normal session LLM context and diagnostics. They may repeat workspace content, so protect session files like other local development history.
- Advisors may send content from any file they inspect inside the real workspace to their configured providers. Traversal, symlink escapes, missing targets, and unreadable targets are rejected without blocking the actor; advisors receive no write, shell, or network tools.
- The npm allowlist excludes local config, authentication, sessions, and environment files.
- Pi extensions run with local user permissions; install only trusted packages.
License
MIT