omp packages

pi-larva0.8.12

Larva PersonaSpec runtime, persona switching, and async subagent extension for Pi.

tefx Published 8 days ago AGPL-3.0-or-later ~566 downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

Larva Pi extension

Cross-harness subagent MCP

The MCP tool descriptions are harness-neutral: hosts with built-in subagents use those by default. The Codex plugin adds Strategy B routing guidance: use native spawn_agent / wait / send_input / close_agent for ordinary delegation; opt into Larva for an explicit Larva/Pi request or persona model-map.json cross-provider routing, persistent .jsonl resume, can_spawn parent policy, or larva_subagent_activity inspection. Keep handles separate: Larva .jsonl task_id values belong only to Larva subagent tools (including resume); native agent IDs belong to native tools.

Without an explicit CLI override, PATH discovery supports the Pi Managed Installer: ~/.local/bin/pi may point to ~/.pi/agent/bin/pi; Larva reads ~/.pi/agent/install/current-version and verifies the selected release's package name and bin.pi identity before launching its JavaScript entry. LARVA_PI_CLI_SCRIPT (or LARVA_PI_REAL_BIN) overrides discovery strictly: it must identify the real package bin script, never a shell launcher, and an invalid override fails closed without managed indirection or PATH fallback. inspectPiCliScript validates the selected ~/.pi/agent/install/releases/<ver>/node_modules/.bin/pi package entry. Native Pi continues using its captured package/bin identity. Larva CLI resolution uses an explicit LARVA_CLI_ARGV_JSON, otherwise settings (including ~/.pi/agent/settings.json larva.cliPath), then ~/.local/bin/larva and PATH. The later external-host section details the protocol and lifecycle; the linked setup guide supplies host configs.

node /absolute/path/to/larva/contrib/pi-extension/subagent-mcp-server.mjs exposes the same child runtime over stdio to Codex, Claude Code, Cursor, and OpenCode. The Codex plugin and direct MCP setup guide covers installation, explicit environment forwarding, and host tool timeouts. This server is orthogonal to Python larva mcp (persona registry CRUD); it provides nine child-runtime tools, not registry mutation.

External hosts can discover Pi automatically or set LARVA_PI_CLI_SCRIPT to the verified Pi package bin script. The server supplies externalHostCanSpawn: true; see external-host authority for how root and descendant MCP calls differ from native Pi. Use wait_for_completion: true for one delegated task, or accepted receipts plus wait/select for parallel work. MCP wait/select results add terminal_outputs to structured content, with captured result text and artifact metadata. The outbox retains 25 completed results, is process-local and non-consuming, and disappears on restart. Disconnect aborts active children. Native Pi still uses its push callback; native wait/select remain readiness-only.

Install the self-contained Codex plugin without configuration edits:

codex plugin marketplace add /path/to/larva
codex plugin add larva-subagent@larva

The marketplace resolves contrib/codex-plugin/; its five regular runtime files run from the plugin cache without node_modules or a sibling Pi extension. The bundled .mcp.json runs node ./subagent-mcp-server.mjs with cwd: ".". After updating the checkout, refresh the plugin cache with codex plugin remove larva-subagent@larva && codex plugin add larva-subagent@larva. Pi and the Python Larva CLI remain separate installations. The MCP host appends existing ~/.local/bin, ~/.pi/agent/bin, /opt/homebrew/bin, and /usr/local/bin to PATH without overriding explicit prefixes. External-host runs skip TUI presentation and timeline workers; native Pi presentation is unchanged.

Mention catalog preload and cache

Initialization advertises only capabilities: { tools: {}, resources: {} }; mention discovery uses the app-only search_mentions tool metadata: _meta["openai/extensions"]["mentions/search"] = { preload: true }. Omitting the initialize-level openai/mentions capability lets Codex Desktop honor that preload flag. notifications/initialized never imports larva.ts.

search_mentions({ query: '', preload: true, path: [] }) returns up to 200 persona resource links; ordinary searches return up to 30. Optional preload must be boolean and path must be an array of nonempty strings. Every link includes searchTerms containing its ID, @larva:<id>, and any description and model, allowing Codex Desktop to match its preloaded catalog locally. Registries larger than 200 entries exceed the preload response limit.

The server shares a process-local ten-second persona-list promise cache between search_mentions and resources/list, including concurrent requests. Registry changes appear on the next request after expiry; a failed scan is evicted for retry. Initialization and UI resource reads remain lazy.

Live activity panel and inline widget

MCP Apps hosts open the Larva Subagents thread side-panel tab through the app-only larva_subagent_panel tool → ui://larva-pi-subagent/panel-v3. The panel advertises fullscreen only and has no redundant Inline button. Spawn, wait, select, and status tool cards attach ui://larva-pi-subagent/widget-v3 as a collapsed-by-default inline card. The versioned URIs refresh Codex Desktop's cached UI resource. Legacy /panel, /panel-v2, /widget, and /widget-v2 resource reads still return the same current app.

The compact card shows persona, model · thinking, tool count, elapsed time, Cancel for active runs, and one activity or terminal-summary line. Details opens a scrollable drawer capped at 340px; Hide details collapses it again. Multiple runs use compact selectable rows. Only the widget offers Fullscreen / Inline switching. The panel always keeps its workbench layout.

The workbench shows an All / Active / Done run filter, grouped run selector, and an always-visible selected-run inspector. Below 680px, the selector stacks above the inspector and scrolls within a 148px cap; the inspector fills the remaining height. Wider windows use two columns. There is no list/detail screen switch.

The inspector defaults to All, showing Task Prompt, Timeline, and Result cards in that order, followed by a compact paired Session Metadata grid. Timeline, Result, and Task & Session filters each show only their corresponding card. Task Prompt displays the full multiline task_prompt (falling back to task_preview for older snapshots), with Copy prompt and Expand prompt / Collapse prompt controls. Its text viewport starts at a 110px maximum height; expansion removes that text height cap. Compact run cards continue using bounded activity/task previews.

Timeline shows bounded assistant output and collapsible tool rows; expanding a row reveals previews and Inspect args / result through larva_subagent_activity. Result and session metadata offer Copy controls. Refresh uses the host bridge. Host theme, style variables, and safe-area insets apply to both layouts. Display, clipboard, and bridge availability depend on host support.

The server advertises eleven tools: nine model-facing runtime tools and two app-only tools (search_mentions, larva_subagent_panel). UI resources load without importing larva.ts. The self-contained app uses only the parent JSON-RPC bridge and makes no network requests. Active runs poll every second; fullscreen panels and widgets awaiting their first run poll every 2.5 seconds when idle. Completed inline widgets stop scheduling polls. Switching to fullscreen or receiving a new active-run notification restarts polling. Hidden documents make no polling requests. Panel reads preserve the process-local outbox and never consume child output. Restart loses live state; recorded historical activity remains separate.

Status, panel, and wait/select snapshots include the full initial task_prompt with preserved newlines, alongside bounded task_preview and assistant previews, startup model/requested and effective thinking levels, thinking/tool indicators, the 25 most recent tool snapshots, last child activity, and terminal result preview. External-host runs populate these fields directly from child RPC frames without retaining native TUI presentation logs or spawning timeline workers. Preview text is bounded; Inspect retrieves paged recorded segments.

Native Pi package

Release 0.8.6 keeps this package separate from the Python wheel. Upgrading the Python backend alone does not update these extension files; install this release's source directory with pi install and restart Pi. See the Chinese release notes.

The release delivery check uses the manifest's local packed payload and isolated agent state, then executes the native panel assertions from that installed entry:

PI_BIN=/absolute/path/to/real/pi/cli.js node scripts/pi-native-journeys.mjs --scenario installed-panel --source-root /absolute/path/to/release-source --output /owned/path/installed-panel.json

Run from the repository root after npm --prefix contrib/pi-extension ci. --source-root selects the independently reconciled release tag/commit checkout; omit it to check this checkout. The installation and child loader use the selected real Pi; the tool-event parent API is headless with the development TUI renderer. Native fullscreen/regular PTY navigation then executes the same installed entry, including wheel/arrows, 42-to-14 resize, crossing-80 Worker arrival retention and pause/End/bottom resume. The loopback provider replaces only model service input; navigation issues no model requests. No npm publication or global settings change is performed.

This directory is the Larva extension package for native Pi. Install it into a Pi agent directory, bind the Larva CLI, and start pi from a normal project shell. The accepted native design owns setup, admission, settings, and child-capsule rules. PersonaSpec meaning is owned by Larva's local schema and Core validator/types.

Native pi is the only Pi session entry point. The Python larva package is used only as the persona data backend.

npm --prefix contrib/pi-extension ci
pi install /absolute/path/to/larva/contrib/pi-extension
pi --larva-persona python-senior --larva-agent-persona-switch confirm

Backend resolution order:

  1. LARVA_CLI_ARGV_JSON environment variable (explicit override)
  2. settings.json (~/.pi/agent/settings.json or .pi/settings.json):
    {
      "larva": {
        "cliPath": "/absolute/path/to/larva",
        "defaultPersona": "general"
      }
    }
    
  3. Auto-discovery fallback: ~/.local/bin/larva (standard uv tool install location) or PATH

Disable automatic loading with pi --no-extensions; explicit -e /absolute/path/to/larva.ts still loads this package. Two distinct copies diagnose a conflict and keep the first stateful instance.

--larva-persona is optional. A fresh session without it uses larva.defaultPersona if configured in settings.json, or starts as larva:none. Resume restores the stored session persona when that selection is still valid. An explicit ID is always resolved, including on resume, but an unused explicit persona's model is not validated. Invalid flag values that reach Larva fail with LARVA_BAD_INPUT and exit 2 before the first model request. Missing values and unknown flags stay Pi diagnostics.

--larva-agent-persona-switch manual|confirm|auto|free is optional and defaults to confirm for a fresh main session. The flag precedes LARVA_PI_AGENT_PERSONA_SWITCH. Saved session mode records keep their existing precedence.

The launcher loads the bundled extension with Pi's modern -e extension flag. The design document is the normative authority for native package, admission, and environment contracts; this README is an operator-facing summary.

Child Pi processes capture the current Node executable and Pi CLI script plus the installed extension entry and adjacent frame preload. They do not rediscover pi on PATH and do not require LARVA_PI_LAUNCHED as an external launcher marker. Missing identity or preload fails child startup with LARVA_CHILD_START_FAILED before spawn/prompt. Children still use a private settings capsule, pass --no-extensions while loading the explicit Larva entry and any sources listed in adapter-local ~/.pi/larva/subagent-runtime.json, and classify UI with ctx.mode. Configured sources load before Larva. When an earlier source such as context-mode registers tools lazily in its first before_agent_start hook, Larva's later hook re-enumerates the tool baseline and reapplies persona policy only when the visible set changed.

subagent-runtime.json is a closed JSON object with schema_version: 1 and an extension_sources array. Optional spawn policy keys are root_session_spawn ("persona" by default, or "allow" for native Pi roots), max_depth, and max_active_runs (each an integer in 1..100 if present). Omitting either limit adds no policy cap. These options do not change PersonaSpec or bypass Pi tool policy. Unknown keys or invalid values are rejected. Sources use Pi -e semantics: npm/git/URL sources are passed through, pi-agent: paths resolve inside PI_CODING_AGENT_DIR (default ~/.pi/agent), ~ local paths expand against the runtime home, and relative local paths resolve against the real directory containing the config file. Relative paths support repo-managed configs deployed through symlinks. Local sources must resolve to readable files or package directories. Configured sources load before the bundled Larva extension so child persona tool-policy enumeration sees their registered tools; --no-extensions remains present. A missing default file means an empty allowlist. Invalid config, an invalid absolute LARVA_PI_SUBAGENT_CONFIG_FILE override, or an unreadable local source fails the subagent before child spawn with LARVA_SUBAGENT_CONFIG_INVALID.

For each new or resumed subagent, the parent resolves the persona's mapped Pi model before spawn and passes it as request-scoped --model <provider>/<model-id>. It also passes LARVA_PI_INITIAL_PERSONA_MODEL_FROM_CLI with that exact value. Child startup re-resolves the mapping, verifies Pi's active ctx.model, and commits prompt/tool policy with applyModel: false; it must not call pi.setModel(). Pi 0.80.7 persists pi.setModel() to shared settings, while initial CLI --model selection is session-local. Snapshot/restore of shared settings is forbidden because concurrent children can overwrite one another.

For pi --larva-persona <id> on a fresh session, initial persona resolution/model/policy commit is startup-critical. Extension-detected model or policy failures write larva pi: <ERROR_CODE>: <message> to stderr and exit 2 before the first prompt/model turn. Stored-persona restore failures stay nonfatal after successful explicit-ID preflight.

Native MCP and discovery

Pi supplies MCP support. Remove a replacement extension such as pi-mcp-adapter to let native Pi read mcp.json; an extension registering /mcp replaces the native implementation. Larva adds no MCP wrapper/client.

For Larva children, explicitly retain the native extensions while automatic extension discovery remains disabled:

{
  "schema_version": 1,
  "extension_sources": ["builtin:mcp", "builtin:codemode", "builtin:tool-search"]
}

Only those three exact builtin: identifiers are admitted and passed unchanged to Pi -e. Unsupported/malformed identifiers, surrounding whitespace, duplicates, over 32 sources or over 4096 code points per source fail before spawn with LARVA_SUBAGENT_CONFIG_INVALID. Existing readable local/relative/symlinked-config, pi-agent:, npm/git/http/ssh/git source behavior remains unchanged. Remote strings are passed through; Larva does not install or rewrite them.

Configure servers in Pi's effective agent-directory mcp.json (normally ~/.pi/agent/mcp.json) or trusted project .pi/mcp.json. Child capsules refer to the base agent resources, including mcp.json. Pi owns trust, credentials, connection lifetimes and exposure. Default MCP codemode and deferred exposure remain callable and searchable without immediate model declarations. direct exposure declares tools while active; hidden makes them unreachable. defaultTools: ["+codemode", "+tool_search"] enables discovery explicitly; Pi can also activate it for configured servers. codemode.mode: "only" remains Pi's declaration-hiding mechanism.

Policy names are Pi's actual exact tool names: mcp__<server>__<tool> (using Pi's normalization), codemode, and tool_search. Resource access uses separate names list_mcp_resources, list_mcp_resource_templates, and read_mcp_resource; allowing an MCP tool or discovery tool does not implicitly allow resource tools. See Pi's installed docs/mcp.md and docs/extensions.md for its native contracts.

The native MCP journey uses a local stdio fixture and deterministic loopback provider, with no external model calls or ambient servers:

PI_BIN=/absolute/path/to/pi node scripts/pi-native-journeys.mjs --scenario mcp --output /owned/path/mcp.json

PI_BIN selects the real Pi package/bin consistently for parent, fixture SDK imports and captured child launch identity. It does not upgrade dependencies or check a version allowlist. Native MCP observations used Node 26.10.0 / Pi 0.99.2; the repository development lock remains 0.85.1.

Native runtime verification

The original native observations used Node 26.7.0 / Pi 0.85.1 on macOS. Versions are evidence context, not runtime admission restrictions. The local package lock reproduces development dependencies. Functional acceptance uses actual native execution in isolated fixtures, without version rejection, automatic upgrades, compatibility matrices or global installation changes. The Python package supplies data; native Pi owns session startup.

Child launch identity is captured once from the actual Node executable, Pi package manifest, and declared bin.pi entry. Parent argv changes and ambient LARVA_PI_TEST_CHILD_ARGV_JSON / LARVA_PI_REAL_BIN values cannot redirect it. Protocol fault fixtures use a repository-only test loader or disposable adapter copy. Neither mechanism belongs to the published package or native acceptance journeys.

tests/shell/test_pi_extension_real_runtime.py invokes the tracked native installation/admission inventory and scripts/pi-native-journeys.mjs scenarios. The journeys launch Pi, a loopback provider, and actual children; PTY cases send real selector/shortcut/completion/confirmation/console keys. The environment journey installs Larva in disposable A and maturin in disposable B, then invokes maturin develop --bindings bin --offline through native main/child bash tools. No external model service is contacted. The watchdog case waits the actual 120-second silence deadline.

See delivery evidence and applicability for commands, native versus controlled observations, cleanup, and exclusions. When using Invar as the test runner, scripts/pi-guard-checks.mjs supplies a 600-second deadline in a disposable verification config; it leaves the project pyproject.toml and rules unchanged. Normal CI invokes the same pytest inventory directly, followed by the full pinned Invar check.

Checkout-local CI

CI reproduces uv.lock and this package's lockfile, then launches contrib/pi-extension/node_modules/.bin/pi. Native fixture SDK imports resolve from that same local package; no standard global prefix or global Pi installation is required. Historical installed-pi test names now exercise the selected prepared installation. PI_BIN remains an explicit native-fixture executable selector. Workflow structure tests check dependency order, required functional selections and failure propagation; their result is separate from actual native execution and any remote CI result. See the current verification contract.

Adapter-local thinking policy and Pi capsules

Native main uses Pi's real agent directory. Larva does not create a parent settings capsule. Each child creates a capsule from the base agent directory (LARVA_PI_BASE_AGENT_DIR / Pi's effective agent dir), with directory mode 0700 and copied settings.json mode 0600. Other resources refer to base resources. Terminal cleanup removes only the known owned capsule root, never follows a root link, and never merges settings back into the base.

Starting another child does not sweep the shared runtime directory: an old directory mtime cannot prove that its owner terminated. Filesystem removal failure emits a bounded larva pi: capsule cleanup failed: stderr diagnostic with the retained capsule path and reason. Optional RPC traces retain that path and actual process state. Reconcile the named process before manually removing an orphan; preserve base resources and durable sessions outside the capsule.

Thinking policy defaults to $HOME/.pi/larva/thinking-policy.json. An absolute LARVA_PI_THINKING_POLICY_FILE overrides it. The exact shape is:

{
  "schema_version": 1,
  "default": "medium",
  "personas": {
    "software-architect": "high",
    "frontend-engineer": "low"
  }
}

The only levels are off, minimal, low, medium, high, xhigh, and max. Top-level keys, schema version, default, persona ids, and values are validated strictly. Missing policy uses medium; an existing unreadable, malformed, or structurally invalid policy returns LARVA_POLICY_INVALID before the affected prompt. This policy remains Pi-adapter configuration: it does not add PersonaSpec fields, model-specific entries, wildcard rules, or a public subagent argument.

Explicit parent persona activation and switching apply the persona policy. A parent without an active persona and ordinary parent session restore retain the session thinking level. A temporary persona borrow captures and restores both model and thinking. Every new or resumed child resolves policy again, starts Pi with explicit --model <provider>/<model-id> --thinking <level>, and verifies RPC get_state.model and get_state.thinkingLevel before prompt. A valid Pi clamp is recorded as requested/effective rather than rejected.

/larva-model-map <profile> keeps one serialized route generation. It applies model and thinking, verifies the resulting route, and attempts paired rollback on failure. Child admission and profile switching share one route lock; admission captures one complete generation before releasing it, then derives both the explicit --model route and child LARVA_PI_MODEL_MAP_FILE from that snapshot. The profile path is added only to the cloned spawn environment; the parent environment is not mutated. A switch after admission is handled by the same post-RPC generation fence. The Subagent Console selector shows think=<effective> or think=<requested>-><effective>. Metadata shows Startup model, Requested thinking, and Startup thinking. These bounded fields are presentation facts only and never status, events, wait, select, cancellation, or resume authority. The existing thinking hidden marker still means hidden reasoning content, not thinking level.

Adapter-local model map

PersonaSpec model remains canonical Larva data and is stored as the active variant's runtime routing label. Larva canonical validation requires it to be a non-empty string, but it does not maintain a static provider/model allowlist and it does not guarantee runtime availability. Pi-provider aliases and availability checks are adapter-local Larva-Pi configuration and must not be added to the local PersonaSpec contract.

The canonical model-map path is:

~/.pi/larva/model-map.json

Set LARVA_PI_MODEL_MAP_FILE to an absolute path to override the path for tests or local adapter experiments. When it is set, the extension reads only that path unless a process-local profile is active.

Named profiles use flat lexical entries beside the canonical map:

~/.pi/larva/model-map.<profile>.json

Use /larva-model-map <profile> to activate one in the running Pi process and /larva-model-map status to inspect the secret-safe source, lexical profile path, parent route, and ready/starting/terminal child counts. Profile names match exactly ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$: letters, digits, underscore, and hyphen are accepted; dots, separators, absolute paths, empty/dot names, and longer names are rejected. The lexical entry may be a symlink to an external regular file. The extension captures the lexical lstat identity, opens that entry once with a nonblocking descriptor, validates the opened target with descriptor-local fstat, and performs a bounded read from the same descriptor. After reading, it compares the lexical identity and target descriptor metadata (dev, ino, size, mtime, and ctime; read-mutated atime is excluded) with their pre-read values. It parses only after both stability checks pass and closes the descriptor on every path. The 1 MiB limit still applies. Dangling links, directories, FIFOs, devices, oversized files, malformed JSON, invalid/unknown schema fields, observed atomic symlink replacement, and observed target mutation fail closed. Status always reports the lexical entry and never discloses the resolved external target. Known child startup errors retain at most 200 sanitized code points of route-stage detail; child stderr/error trace previews use the same bound and redaction. ANSI/control characters and credential-like values are removed or redacted. A child that exits before task allocation is retained in the bounded process-local status/events stream as startup_failed, keyed by diagnostic-only startup_id and optional Pi call_id; no .jsonl task handle is fabricated, and wait/select/cancel/resume do not accept the provisional identifier.

Profile precedence is process-local profile, explicit LARVA_PI_MODEL_MAP_FILE, canonical model-map.json, then the first-slash fallback. Selection lasts for the current extension process and resets on process restart/resource recreation; it does not mutate environment variables, user files, PersonaSpec, registry state, models.yaml, or credentials.

A successful switch preflights all routes, commits the parent first, and then updates ready children with correlated bounded-timeout set_model RPCs. Ready child RPCs use a fixed maximum concurrency of four; profile commands remain serialized. With no active parent persona, selection still applies to future children and reports parent: not_applicable. New and resumed children resolve through the active profile; a starting child is generation-fenced before its first prompt. The switch rechecks a starting child immediately before reporting will_use_new_route, so a child that terminates in that interval reports ended_during_switch. Terminal or concurrently ended children receive no route command. A child request already in flight may finish on its old model; after a successful set_model, its next provider request uses the new route.

Parent failure restores the prior selection/model and reports failed. Child failures retain the committed parent and successful children, report partial with exact task/persona identities, and never trigger provider/profile fallback. Re-running the same profile retries unswitched live children.

Shape:

{
  "models": {
    "<PersonaSpec.model>": { "provider": "<pi-provider>", "model_id": "<pi-model-id>" }
  },
  "prefix_rules": [
    { "from_prefix": "<literal-prefix>", "to_provider": "<pi-provider>", "to_model_id_prefix": "<literal-prefix-or-empty>" }
  ]
}

Resolution rules:

  • First check models[spec.model] for an exact mapping.
  • If there is no exact hit, evaluate only literal prefix_rules.
  • Choose the longest from_prefix that matches spec.model.
  • If two or more matching prefixes have the same longest length, the config is invalid and must surface LARVA_MODEL_MAP_INVALID.
  • Prefix rules only strip from_prefix and prepend to_model_id_prefix to the remaining model string. Embedded slashes in the remainder are preserved.
  • Wildcards, regex, fuzzy matching, nearest-model behavior, and automatic guessing (including vendor guessing) are forbidden at runtime.
  • After exact or prefix mapping, call Pi modelRegistry.find(provider, model_id) with the mapped values.
  • If mapped values are valid but Pi registry lookup misses, or if pi.setModel rejects the model, keep using LARVA_MODEL_UNAVAILABLE.
  • If the model-map file is missing, preserve the current fallback: split PersonaSpec.model on the first / into provider/model id.
  • If the config file exists but has invalid JSON, invalid schema, or invalid rules, fail closed with LARVA_MODEL_MAP_INVALID.
  • If there is no exact hit and no prefix hit, preserve the current split fallback.
  • Startup persona application and /larva-persona switching must use the same resolver path.
  • Validation warnings from larva validate are not runtime model-availability verdicts. Use the model-map helper and Pi runtime diagnostics for provider inventory checks.

Runtime-map draft helper policy:

  • Use larva pi-model-map draft to build a redirect-safe draft from current Larva registry summaries, pi --list-models --offline, and an optional existing model-map file.
  • The helper must not read personal scaffold files or apply provider-family preference tables. It may choose automatically only when the Pi inventory leaves exactly one target candidate.
  • Add exact mappings only when the target provider/model id is present in Pi's offline registry. If no verified unique target exists, report the source model as unresolved instead of guessing.
  • Existing exact mappings are preserved only when the source model is still used and the target appears in the current Pi inventory.
  • Existing literal prefix rules may be preserved only when they cover current registry models, map them to current Pi targets, and do not conflict with another same-length prefix rule.
  • The written model-map.json contains only runtime-compatible models and prefix_rules; report metadata belongs on stderr or in the CLI --json envelope.

Contract verification cases for the implementation step:

  • Exact aliases resolve through models before any prefix rule is considered.
  • Prefix rules preserve embedded slashes after the matched literal prefix is stripped.
  • Two matching prefix rules with the same from_prefix length fail closed with LARVA_MODEL_MAP_INVALID at runtime and are rejected by the draft helper.
  • Startup persona application and /larva-persona switching use the same model resolver and the same unavailable-model error projection.
  • A valid model-map.<profile>.json symlink to an external regular file activates, while status retains the lexical path and omits the resolved target.
  • Descriptor validation, bounded bytes, strict parsing, and closure use one opened file descriptor. Stable near-limit A and B snapshots may each succeed whole; active atomic lexical retargeting and active target metadata mutation must each produce at least one typed failure, and no mixed, alternate, or fallback route may be committed.
  • Dangling, directory, FIFO/device where supported, oversized, malformed, unknown-schema, and invalid/traversal-name cases fail boundedly without fallback.
  • Installed Pi 0.83.0 proof calls ctx.reload() before the public /larva-model-map openrouter command and uses only a controlled external target plus a neutral loopback provider.
  • openrouter/google/gemini-3.5-flash resolves through an openrouter/ prefix rule with empty to_model_id_prefix to provider openrouter and model id google/gemini-3.5-flash; it must not require a Larva validation snapshot entry.

Adapter-local tool policy

Persona-specific Pi permissions use ~/.pi/larva/tool-policy.json. An absolute LARVA_PI_TOOL_POLICY_FILE selects only that file. Without the override, only the canonical path is read; a missing file means empty policy. Larva never probes legacy ~/.pi/tool-policy.json, merges, rewrites, creates, or migrates policy files. To use an old file temporarily, name its absolute path explicitly; otherwise move its intended contents to the canonical path yourself. If both files exist during migration, report the conflict and choose the intended file manually; Larva still never probes or merges them.

{
  "personas": {
    "python-senior": {
      "allow": ["read", "bash", "codemode", "tool_search", "mcp__docs__search"],
      "deny": ["write", "edit"]
    }
  }
}

The top level contains exactly personas, an object. Only the active persona's entry is validated beyond that shape. It may contain only optional allow and deny arrays of non-empty strings; duplicates are ignored. Matching uses exact Pi tool names, without aliases, prefixes, wildcards, path rules or bash-command rules. Unknown names do not create tools. deny wins. A missing allow permits known tools minus deny; allow: [] denies every tool. There is no ask action. This is adapter-local configuration, separate from PersonaSpec capabilities and can_spawn.

Permission and declaration are separate. Pi owns the live registry, exposure, active tools and branch-persisted discovery. Larva filters actual declarations by persona policy and self-switch mode. It remembers declarations it temporarily suppressed, so engineer → readonly → engineer and temporary borrow restoration recover the origin's tools. It never activates the entire permitted registry. Unloaded deferred/codemode tools remain undeclared; a search-loaded tool can be restored after a role mask because Pi actually declared it before the mask.

Tools disabled before a restrictive role stay disabled. Larva observes removals from its last applied loadout and respects those explicit Pi disables. Minimal current-branch custom entries retain selection and previously registered names. Missing/hidden tools during asynchronous registration or native withdrawal do not count as user disables. Re-registration restores that branch's selection instead of accepting Pi's direct-tool activation defaults. Explicit selection after registration/pruning remains available. Reload, tree, resume and fork cannot borrow intent from abandoned branches. A manual → confirm/auto/free command restores Larva's self-switch availability, subject to persona permission, without enabling the permitted registry.

An explicit disable of an already Larva-masked tool can leave Pi's active set unchanged. Pi's public selection API and declaration transcript carry no separate intent for that no-op. Larva cannot infer it; select the intended loadout while the tool is available. During re-registration, saved branch selection wins over initial defaults; make an explicit override after registration/pruning.

The common tool_call gate checks the committed exact policy independently of active-tool membership, including native nested codemode calls. An allowed undeclared deferred tool can be called from codemode; a denied tool stays denied even if another extension activates it. Pi enforces unknown, hidden, model-only and inactive-direct call restrictions. Larva does not replace Pi dispatch, search, or MCP clients. Discovery metadata may still list denied names; permission controls execution. Tool-result and before-agent-start hooks prune denied activation. The native context_with_system hook also filters Pi's outgoing system-message tool declarations after delayed MCP startup, restoring only selected declarations from Pi metadata. Pi still applies its exposure and codemode-only presentation afterward.

An absent/unsupported startup enumerator retains the empty-baseline startup behavior. Genuine registry/active-set failures fail closed with LARVA_TOOL_ENUMERATION_FAILED. A failed persona commit restores persona, model/thinking, live Pi declarations and declaration intent. Uncertain rollback preserves the existing instruction failure fence. The launcher passes the policy path; the extension owns parsing and application for startup, explicit switches, and real children.

Switching personas in Pi

The extension registers this slash command:

/larva-persona <persona-id>
/larva-persona --refresh-cache

--refresh-cache refreshes only the adapter-local persona candidate cache used by completion, selector, and @persona autocomplete. It does not switch persona, model, or active tools, does not change session state, and is not a model-facing LLM tool. No separate refresh slash command or alias is registered.

Switching resolves the target persona through the Larva CLI context supplied by the launcher, validates the target model and active policy entry, computes tool rules, and commits the persona atomically. A successful commit applies the persona's resolved Pi model as the default model for that activation, but it does not create a per-turn model lock. If the operator later changes Pi's active model with Pi's /model command or model-cycling shortcut, later prompt turns must not silently reapply PersonaSpec.model; the manual Pi runtime choice remains active until another explicit persona commit or fresh startup/session restore applies a persona model again. If any step fails, the previous persona, model, and tool rules remain active. This user-driven command is preserved in every agent self-switch mode, including manual.

With no argument, /larva-persona opens a selector only in interactive TUI mode. The selector is populated from the same adapter-local persona candidate cache as completion and mentions. When Pi exposes custom UI, the selector uses Pi TUI Input plus SelectList with a detail panel showing id, model, description, capabilities, and digest. The selector renders as a boxed modal surface with an accent-colored border, solid ANSI background, adaptive list viewport that expands to available terminal height while keeping detail/footer bounded, and terminal-compatible drop shadow; its frame height remains stable across filter, navigation, and width-safe render states. Enter confirms and Esc cancels. Mouse clicks are intentionally unsupported no-ops.

Interactive TUI mode also registers ctrl+alt+p as a conflict-screened Pi extension shortcut for opening the same no-argument selector path. The shortcut is intentionally an extension shortcut, not a keybindings.json command alias; if Pi is not idle it shows a warning and leaves active state unchanged. On a cold persona candidate cache, the no-argument selector path may wait for a foreground larva list --json refresh instead of showing an unreadable fallback label; a refresh failure is reported as a Larva notification and leaves active state unchanged. If the enhanced custom UI cannot be opened but Pi's simpler selector API is available, the command or shortcut may fall back to that selector. In RPC, print, JSON, SDK, malformed mode, unknown mode, or other non-interactive launcher classifications, the command returns an input error and leaves active state unchanged. The Pi status line shows:

larva: <id>

or, when no persona is active:

larva: none

Session persona restore

Successful persistent persona commits append a versioned custom entry, larva-active-persona-commit, containing persona_id, diagnostic spec_digest, source and time. Temporary borrows do not replace the stored primary persona.

Initialization resolves an explicit startup id even on resume. A valid stored persona on the current branch then takes precedence over the explicit id; without one, initialization uses the explicit id, the configured default, or larva:none. A stored persona's unused explicit model is not validated. Restore uses the current registry definition, with a notice if its digest changed. This stored-persona precedence applies to interactive sessions, not Larva-launched children: LARVA_PI_INITIAL_PERSONA_ID stays authoritative on initialization and switch_session. Child get_state verifies the active persona alongside model and thinking before the prompt is sent.

Larva reconstructs persona and self-switch mode from ctx.sessionManager.getBranch(), never abandoned branches returned by getEntries(). session_tree retires old branch work, clears temporary leases and restores policy for the branch Pi entered. A branch without persona records uses fresh-session selection rules and cannot inherit the abandoned persona. Pi restores native declarations; Larva applies the branch's saved role masks and selection intent, including previously loaded tools and explicit disables. Reload, resume and fork follow the same branch restoration path.

Ordinary prompt turns reuse the committed persona and preserve a later manual Pi model/thinking selection. A model-change entry after the branch's persona commit prevents restoration from overriding that selection. A failed explicit startup commit remains fatal. A stored-persona restore failure is nonfatal, shows unavailable status, and leaves the resolver unavailable without claiming stale persona authority. It does not recover leases, parse prompt blocks, scan JSONL files, or treat subagent presentation caches/task ids as persona authority.

Agent persona self-switch

Agent persona self-switch is session-level Pi extension policy. It does not add fields to PersonaSpec and does not give the model direct access to the internal commitPersona primitive.

Configure the launch default with either surface:

pi --larva-agent-persona-switch manual|confirm|auto|free ...
LARVA_PI_AGENT_PERSONA_SWITCH=manual|confirm|auto|free

Change the current Pi session mode with:

/larva-mode [manual|confirm|auto|free]

Mode behavior:

  • manual hides larva_persona_switch and larva_personas from the active model-facing tool set, and stale or forged calls to autonomous switch tools are rejected. Manual /larva-persona <id> remains available.
  • The default is confirm. The agent/runtime may request a temporary persona borrow. The borrow commits only after UI confirmation. Explicit Deny refusal, Escape/Ctrl+C cancellation, timeout (default: 15 minutes / 900000 ms), or missing UI fails safely without changing persona, model, or tool state, and returns model-visible recovery guidance so the active persona can continue or delegate to an authorized subagent without automatically retrying the borrow. The normal approval is "borrow once", not a persistent switch.
  • auto exposes the same tools and performs the same temporary borrow without UI confirmation. The extension records the persona and actual Pi model active immediately before the switch and restores both when the current assistant turn ends. If the user manually selected a different Pi model before the borrow, restore returns to that runtime model, not the origin persona's default model.
  • free exposes the same tools and allows a persistent self-switch without automatic restore.

Runtime guidance routes persona work by task need rather than rigid mechanical rules. A suitable executor should finish its assigned deliverable through necessary fixes, tests, and cleanup, avoiding gratuitous handoffs; simple tool operations are directly completed as an efficiency preference. Subagent delegation (larva_subagent) is decided by complete-task needs (clean context, independent review, specialized domain division, parallel speedup, handoff overhead, parent coordination) and may own full implementation steps. Autonomous persona borrowing/switching (larva_persona_switch) applies when the active persona is materially unsuitable and runtime conversation continuity is necessary; explicit user persona selections remain supported within host authority and runtime mode without imposing this dual-necessity threshold. For the full routing decision policy and prompt guidance, see ../../docs/reference/PI_AGENT_PERSONA_SWITCH_POLICY.md.

larva_personas is bounded discovery metadata; it is not a prompt/spec catalogue injection surface. larva_persona_switch requires a non-empty reason; handoff is optional and bounded. A temporary borrow is represented by a runtime persona lease whose restore target is the persona and actual Pi model active immediately before the borrow.

When continue_task=true, a successful switch result sets terminate=true so the old persona turn can stop. Pi honors termination only if every finalized tool result in the same batch has terminate=true; mixed batches with non-terminating results can keep the old turn alive, so the model guidance requires calling the switch tool alone. The first agent_end after the switch does not restore the origin. It schedules setTimeout(0), queues a hidden custom runtime message with customType: larva-agent-persona-switch-continuation, display: false, and deliverAs: "nextTurn" when that surface is available, then uses a minimal sendUserMessage("Continue.") trigger so Pi enters a fresh before_agent_start. The detailed Larva-generated continuation is injected as a one-turn system prompt addon under the borrowed persona/model rather than as the visible user message. The continuation run's agent_end restores the origin persona/model for temporary borrows. If the minimal trigger surface is unavailable or fails, the extension restores immediately and audits continuation delivery failure. free remains persistent and does not create an automatic restore lease.

User manual persona switching has highest priority: it clears any active lease and must not later be undone by automatic restore. Unknown mode values fail safe to confirm with a status/event warning rather than being treated as compatibility aliases.

In confirm, the required confirmation choices are:

[Borrow once] [Deny] [Auto-borrow for this session] [Switch persistently]

Any confirm UI must provide all four outcomes as visible text rows.

  • Borrow once creates a turn-scoped lease and restores the origin persona plus the actual pre-borrow Pi model at current assistant turn end.
  • Deny is the explicit refusal option; it rejects only this borrow request and leaves persona, model, and tool state unchanged.
  • Auto-borrow for this session sets a session-local mode override to auto and creates the same turn-scoped lease for the current request. It is not persisted as a global preference.
  • Switch persistently is treated as a user manual switch, clears any active lease, and does not automatically restore.

Escape, Ctrl+C, timeout (default 900000 ms, configurable via LARVA_PI_AGENT_PERSONA_SWITCH_TIMEOUT_MS or --larva-agent-persona-switch-timeout), missing UI, or an unrecognized/no selection is a fail-safe denial path with the same no-state-change result as Deny; these paths return model-visible recovery guidance to continue under the current persona or delegate to an authorized subagent without auto-retrying.

Restore notices are emitted through status UI, event logs, or audit entries, not assistant chat-body text. Restore is attempted on success, failure, cancellation, and timeout paths, and includes the captured pre-borrow Pi model when available. If restore fails, the extension must report the failure, preserve current runtime state, keep audit detail, and require explicit user persona choice before any further persona-changing action. There is no automatic safe-default persona fallback.

The full target policy is documented in ../../docs/reference/PI_AGENT_PERSONA_SWITCH_POLICY.md.

Prompt identity composition

When a Larva persona is active, the extension keeps Pi's operational prompt intact and adds Larva-owned identity blocks around it. This is intentionally not a replacement of Pi's full system prompt: Pi still owns the tool list, guidelines, Pi documentation notes, project context, skills, date, and working directory.

The effective prompt shape is:

<!-- larva:identity-policy:begin -->
Active Larva persona is the primary identity. Pi's generic coding-assistant
wording describes the runtime harness and tools only.
<!-- larva:identity-policy:end -->

<current Pi chained system prompt, unchanged>

<!-- larva:active-persona:begin -->
<!-- larva-spec: <persona-id>@<spec-digest> -->
<committed PersonaSpec prompt text>
Use Larva MCP or the larva CLI (`larva`, fallback `uvx larva`) to discover and
resolve personas when needed.
<!-- larva:active-persona:end -->

Prompt injection is idempotent by removing only previous Larva-managed blocks bounded by the larva:identity-policy and larva:active-persona markers before adding the current blocks. The extension must not match or rewrite Pi's default identity sentence or rebuild Pi's prompt builder. User-prompt turns compose identity in before_agent_start. Idle Larva triggerTurn custom messages skip that hook, so before_provider_request projects the same marker-bounded identity onto known provider system-instruction slots for every request in that turn, including tool continuations, without overwriting non-Larva system content.

Known APIs insert an instruction slot when the request already admits one (for example a messages/input array with no leading system message, or a config object without systemInstruction). That keeps a usable turn instead of cancelling it. If the API is unknown or the payload has no admitted instruction container, the hook calls public ctx.abort() before notifying. The warning says cancellation was requested; it does not claim that every transport stopped. Unknown custom transports that ignore the abort signal, and openai-codex-responses websocket dispatch after onPayload, can still emit a request.

Synchronous system prompt resolution (larva:resolve-system-prompt:v1)

For consumers such as Nunc that need effective systemPrompt before admission, Larva provides synchronous request-level prompt resolution via Pi's public pi.events:

type ResolveSystemPromptResult =
  | { status: "ok"; systemPrompt: string }
  | { status: "unavailable"; reason: string };

type ResolveSystemPromptRequest = {
  scope: "main";
  systemPrompt: string;
  reply: (result: ResolveSystemPromptResult) => void;
};

Consumer rules and lifecycle contract:

  • Channel and scope: In-process synchronous event emitted on pi.events. scope must be "main". Maintenance and auto-compaction requests keep their own system prompt and must not call this interface.
  • Synchronous reply-before-emit-return: The active Larva listener invokes reply exactly once before pi.events.emit() returns, without async deferral, promises, microtask delays, or retained request objects.
  • Zero-reply absence vs. unavailable: When Larva is not loaded or after extension shutdown, pi.events.emit() produces zero replies; consumers must recognize zero replies as interface absence. status: "unavailable" indicates Larva is loaded but cannot determine a valid prompt (e.g. extension still initializing, incomplete identity/lease transition, restore failure, or malformed/damaged input boundaries).
  • Duplicate-reply error: Multiple replies indicate a protocol violation; consumers must not pick one arbitrarily.
  • Pure fixed-point composition: Shared across before_agent_start, before_provider_request, and this resolver. Preserves foreign text, Unicode, internal whitespace, and relative ordering; strips only recognized managed blocks (identity-policy, active-persona, continuation) and cleans stale blocks under larva:none. Fixed-point guarantee: C(S, C(S, B)) = C(S, B).
  • Provider projection parity: When the prompt passed to the provider already matches the composed fixed point under the same runtime state, before_provider_request detects identical text, returns undefined, and leaves provider payloads, slots, roles, cache controls, and message structures untouched. True state changes (such as subsequent persona switch or lease restoration) project at request time.
  • Lifecycle and teardown: Registered synchronously on pi.events during extension setup. Cleaned up synchronously during session_shutdown before async teardown; reloads re-establish readiness under the new extension instance without duplicate handlers or revival of old initialization.
  • Read-side purity: Resolver calls have zero side effects on leases, continuation queues, session history, file system, or child runtimes.
  • Unperformed Nunc combination validation: This step delivers and verifies Larva's synchronous resolver, fixed-point composition, and provider projection parity in isolation. End-to-end combination testing with Nunc (capacity admission, usage receipts, auto-compaction, long tool loops) is explicitly not performed as part of this Larva delivery.

Diagnostics use fixed bounded categories and never echo caller exceptions, prompt text, or paths. A callable reply accessor is captured once; invalid fields still receive one synchronous unavailable reply, and a throwing reply gets no retry.

Opaque persona/continuation text may contain delimiter examples. Larva preserves that text using private length framing when needed. Consumers must treat the returned string as opaque, without parsing or editing its framing. Ambiguous unframed historical boundaries return unavailable instead of leaving a stale tail or discarding foreign text.

Readiness covers the complete outer borrow/restore and confirmed rollback. Incomplete or failed non-null identity cancels provider requests; a failed stored persona startup that leaves native larva:none retains its nonfatal fallback. The resolver remains unavailable for that failed initialization. Pi may reuse a module factory on new/resume/fork: Larva resets its retired instruction state and ignores publication from the previous generation's pending initialization.

/larva-persona Tab completion

The supported editor-autocomplete target is Pi interactive TUI with a runtime UI context that exposes ctx.ui.addAutocompleteProvider. In that target, the command keeps Pi's command-level argument completer and installs a narrow TUI autocomplete provider for editor Tab completion. In non-TUI modes, or when that hook is unavailable, the extension does not provide editor autocomplete; it keeps the command-level completer only and delegates or returns null for editor autocomplete. The provider intercepts only a slash-command line shaped as:

/larva-persona <query>

Implemented behavior:

  • Typing /larva-persona <query> and pressing Tab shows matching persona ids from the adapter-local persona candidate cache when the runtime exposes the editor provider hook. The cache source is public larva list --json.
  • Matching is case-insensitive substring matching over persona ids, not only prefix matching. For example, senior should match python-senior.
  • Prefix matches rank before non-prefix substring matches. Otherwise preserve the latest accepted candidate-cache order.
  • Forced Tab and regular completion use the same matching path.
  • All non-/larva-persona editor input is delegated to Pi's base provider so global and file completion remain Pi-owned.

Completion candidates have Pi's command item shape:

{"value": "persona-id", "label": "persona-id", "description": "optional description or model"}

Performance target:

  • The extension keeps a two-tier adapter-local persona candidate cache: process memory and a Pi-owned Larva cache file. The default disk path is ~/.pi/larva/persona-candidates-cache.json; tests may set the absolute-path override LARVA_PI_PERSONA_CANDIDATES_CACHE_FILE.
  • The cache is generated only from public larva list --json; the Pi extension must not directly read ~/.larva/registry for candidate population.
  • Cache entries are prompt-free UI projections containing exactly id, description, model, spec_digest, and capabilities. They never contain prompt or full PersonaSpec content.
  • Completion, no-argument selector, and @persona autocomplete hot paths return memory cache when present, else disk cache when present, and trigger background refresh when data is stale or missing. They must not synchronously wait on slow larva list --json.
  • If both caches are empty, the provider returns null or a bounded empty result compatible with the calling UI and starts background refresh.
  • Background refresh failure preserves stale cache and does not throw through the Pi TUI.
  • /larva-persona --refresh-cache forces a foreground refresh through public larva list --json. Success updates memory and disk cache; failure keeps the old cache and reports a bounded failure reason. This option is part of the existing /larva-persona command; it is not a new slash command, not an LLM tool, and not a persona/model/tool-policy/session-state change.
  • Tests must be able to reset process-local cache state and redirect disk cache to a temp path via LARVA_PI_PERSONA_CANDIDATES_CACHE_FILE.

This is substring matching, not fuzzy matching: no edit distance, wildcard, regex, nearest-persona guessing, or hidden aliases.

Troubleshooting commands for runtime autocomplete behavior:

node scripts/pi-extension-autocomplete-smoke.mjs --case tab-force --prefix vectl
node scripts/pi-extension-autocomplete-smoke.mjs --case tab-regular --prefix vectl
node scripts/pi-extension-autocomplete-smoke.mjs --case delegate-other-input
node scripts/pi-extension-autocomplete-smoke.mjs --case list-failure
uv run pytest tests/shell/test_pi_extension_real_runtime.py -k autocomplete -v

The runtime gate for editor autocomplete must prove the tested Pi build exposes ctx.ui.addAutocompleteProvider before claiming editor-autocomplete support. The local Node harness intentionally reports mock-only hook provenance as degraded: capability-gates.runtime.hardGates.uiAutocompleteProvider.supported stays false when the only observed hook is runtimeHarness.mock. Mock/local hook proof is useful for provider behavior, but it is never sufficient to claim live Pi interactive TUI editor-autocomplete support.

@persona:<id> mentions

When Pi interactive TUI exposes ctx.ui.addAutocompleteProvider, the extension adds a narrow autocomplete provider for Larva persona mentions in the editor:

@persona:<persona-id>

The mention is only an id-only user-facing reference to a Larva persona. It is not a command, does not switch the active parent persona, does not automatically call larva_subagent, and does not inject the mentioned persona's prompt or full spec into the parent context. The parent agent decides normally whether the mention is relevant and whether calling larva_subagent is useful.

Autocomplete uses the same adapter-local persona candidate cache and matching rules as /larva-persona completion. Candidate value and dedupe identity are exactly @persona:<id>. Any trailing space or suffix after insertion is Pi UI behavior outside the Larva candidate value. Candidates may include the persona description or model in the completion description. When persona candidates and Pi file-reference candidates are both present, Pi file-reference candidates keep their original order, persona candidates are appended after them, and exact duplicate insertion values across the merged list are removed by keeping the first candidate.

Larva handles only these mention tokens:

Token shape Larva behavior
@ Show persona candidates after Pi file-reference candidates.
Prefix of literal @persona: such as @p, @pe, @per, @persona Show namespace/persona candidates.
@persona:<query> Match persona ids using <query> and show only persona candidates.
Raw @<query> such as @vectl, @python, @doc, @python-senior, @foo/bar Ask Pi's base provider for file-reference suggestions first, preserve them in their original order, then append matching canonical @persona:<id> candidates and dedupe by insertion value keeping the first candidate.

Raw @<query> is an autocomplete convenience only: selecting a Larva candidate still inserts canonical @persona:<id>, and submitting raw @<id> does not become a persona semantic form. Mentions remain id-only user-facing references with no automatic persona switch, subagent call, prompt injection, model change, tool-policy change, or session-state side effect.

Compaction focus

Larva's implemented compaction focus behavior is documented in docs/reference/PI_EXTENSION_COMPACTION_FOCUS.md. The extension handles Pi's session_before_compact hook by calling Pi's exported compact(...) helper with Larva focus supplied as customInstructions.

Pi still owns the base compaction prompts, previous-summary update logic, split-turn handling, file-operation tracking, and session-context rebuild. Larva preserves those defaults and appends bounded focus through Pi's own customInstructions path; it does not replace Pi's SUMMARIZATION_PROMPT, UPDATE_SUMMARIZATION_PROMPT, split-turn prompt, result schema, or provider payload.

Focus is assembled in this order when the corresponding trimmed section is non-empty:

  1. manual /compact ... instructions from event.customInstructions;
  2. the active Larva persona's compaction_prompt from the committed runtime envelope;
  3. the adapter-local carry-forward rule.

The carry-forward rule exists to preserve unfinished work, next actions, files, commands, failing tests, and blockers in the generated summary. It improves state for the next agent turn only: threshold or manual compaction does not automatically continue execution, send a follow-up user message, or otherwise start more work after compaction.

Adapter-local compaction config

The default adapter-local config path is:

~/.pi/larva/compaction.json

Set LARVA_PI_COMPACTION_CONFIG_FILE to a non-empty absolute path to override that file for tests or local adapter experiments. Relative or empty override values are invalid. Missing config means defaults; the extension reads the default path but does not create ~/.pi, ~/.pi/larva, or ~/.pi/larva/compaction.json automatically.

Minimal shape:

{
  "enabled": true,
  "carry_forward_rule": {
    "enabled": true,
    "text": "If the task is unfinished, keep it in Progress/In Progress and Next Steps.\nDo not mark work as complete unless completion evidence exists.\nPreserve next concrete action, files changed, commands run, failing tests, and blockers."
  }
}

Defaults and disable switches:

  • Missing file or {}: enabled with Larva's built-in carry-forward rule.
  • Root "enabled": false: disable all Larva focused compaction while still validating any present keys/types; Pi performs native compaction.
  • "carry_forward_rule": {"enabled": false}: keep manual and persona focus available, but disable the carry-forward rule.
  • Unknown root keys, unknown carry_forward_rule keys, non-object roots, malformed JSON, empty enabled text, and over-limit enabled text are invalid.
  • Enabled carry-forward text is trimmed and bounded to 4000 Unicode code points; manual and persona focus are each bounded to 2000 code points, and total focus is bounded to 6000 code points.

Invalid config is not repaired in place. The extension does not rewrite, migrate, merge, delete, or create config files automatically.

Native fallback and diagnostics

Larva returns undefined so Pi performs native compaction when focused compaction is disabled, the composed focus is empty, config parsing/validation fails, mandatory model/auth/runtime prerequisites are unavailable, the event shape is unsupported, the compact adapter is unavailable, or focused compaction throws a non-abort error. User cancellation is distinct: an already-aborted signal or adapter AbortError/Compaction cancelled returns { cancel: true } so Pi does not restart native compaction after a user abort.

Diagnostics are adapter-local warnings only; they are not PersonaSpec fields and not compaction authority. Stable codes are:

  • LARVA_COMPACTION_CONFIG_INVALID: invalid path, JSON, schema, unknown key, or bounds failure.
  • LARVA_COMPACTION_FOCUS_UNAVAILABLE: missing mandatory runtime prerequisite, unavailable auth, or unavailable compact adapter.
  • LARVA_COMPACTION_FOCUS_FAILED: focused compact(...) was attempted and threw a non-abort error.

When possible, diagnostics use ctx.ui.notify(message, "warning"); otherwise they fall back to status text such as compaction focus: LARVA_COMPACTION_FOCUS_UNAVAILABLE. Diagnostic text is bounded and sanitized: it must not include raw conversation, summaries, API keys, headers, full prompts, or customInstructions.

Compaction focus non-goals

Compaction focus does not:

  • modify installed Pi packages under /opt/homebrew/...;
  • replace Pi's default compact