omp packages

pi-task-router0.1.0

Owner-configured model decisions for new Pi tasks

abix5 Published 15 hours ago MIT ~0 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

pi-task-router

Pi extension for previewing a model recommendation or applying it to the next user request. It does not intercept other tools or change their arguments.

Install and try

Use Node.js 24 or newer and Pi with virtual-model support (tested with Pi 1.7.0; peer range >=1.7.0 <2). You need a configured classifier and at least one available, authenticated worker in this Pi session. No Herdr or spawn tool is required.

Choose one install method (the registry release has not been verified):

# When published to your npm registry:
pi install npm:pi-task-router

# Or install an npm pack artifact directly, without a registry:
pi install "npm:pi-task-router@file:/absolute/path/to/pi-task-router-0.1.1.tgz"

For either npm install on Pi 1.7.0, copy the installed example into the Pi agent directory (back up any existing policy before replacing it):

agent="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}"
cp "$agent/npm/node_modules/pi-task-router/examples/task-router.json" "$agent/task-router.json"

Alternatively, unpack the tarball into a permanent directory and install that directory:

agent="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}"
mkdir -p "$agent/local/pi-task-router"
tar -xzf /absolute/path/to/pi-task-router-0.1.1.tgz -C "$agent/local/pi-task-router"
pi install "$agent/local/pi-task-router/package"
cp "$agent/local/pi-task-router/package/examples/task-router.json" "$agent/task-router.json"

Edit task-router.json: replace the placeholder classifier endpoint/model and bridge origin/provider mappings; check the worker IDs and effort levels against your Pi registry. Supply TASK_ROUTER_KEY and PI_PROXY_KEY in the environment, not the file, and configure Pi's credentials for the physical workers. If you have no quota bridge, set "quota": {"enabled": false}. Exit Pi and start a fresh process. /model should list pi-task-router/auto; /route previews a decision and route_task is available to the model.

For a minimal single-row setup without a bridge, an alternative policy is:

{
  "version": 2,
  "classifier": {
    "protocol": "system-one", "response": "choice-only",
    "endpoint": "https://classifier.example/v1/systemone", "model": "decider",
    "apiKeyEnv": "TASK_ROUTER_KEY", "timeoutMs": 2500, "maxTaskChars": 4000
  },
  "classes": [{"id": "review", "description": "Review a change for defects", "target": "example/reviewer", "substitute": "other/reviewer"}],
  "effort": {"levels":["medium","high","xhigh"],"thresholds":[0.5,1.5]},
  "onFailure": {"interactive": "ask", "unattended": "block", "maxUserRetries": 0}
}

First preview, then opt into routing:

pi -p '/route review this change'
pi --model pi-task-router/auto "review this change"
# From a checkout without a package install:
pi -e . --model pi-task-router/auto "review this change"

The preview discloses bounded task text to your classifier but starts no worker. See the full example for the six example pairs.

Route the next user request

Select automatic routing with pi --model pi-task-router/auto "your task", or type /model pi-task-router/auto in an existing session before sending the next task. The qualified model must be installed in the Pi session doing the work. Selecting it, loading history, or switching away without submitting a user task does not classify anything. /route <task> remains a preview, not an automatic switch.

On success, the same message goes once to the winning physical model at its recommended thinking level; the session keeps that pair. The Auto card records the outcome. Selecting auto again opts in for the next new task only. While Pi 1.7.0 is streaming, an auto-selected steer or follow-up cannot be matched safely to its later worker request. It is not queued; submit it after the current run finishes. Nothing is replayed automatically. While auto is choosing, model selection, model cycling, thinking-level changes and per-model thinking preferences are locked. Wait for the decision, or press Esc (RPC: abort) to cancel and restore the original model and level. Cancellation does not wait for credentials or extension observers. Auto also has a 60-second overall deadline: on expiry the run fails, restores the same pair, and unlocks without sending the task to a worker. Refused changes are not saved or replayed. You can change models again after routing finishes. The router does not change your global defaults.

If classification fails or the winner is unavailable, the TUI offers eligible model/level pairs from either configured role. Even if the primary is still eligible, a budget-selected substitute that cannot run does not fall back to it. Only an explicit pick starts a worker. The card distinguishes User pick from the original classification. Cancel, no eligible choices, session replacement or dialog expiry (60 seconds) means no worker is called. Print, JSON and RPC never ask: text print exits 1, JSON and RPC emit a terminal run error. An RPC prompt acknowledgement is not a successful run. Each decision also gets one router summary on stderr. If auto is still current, send a new message to try again; a failed task is not automatically resent.

On -c, --resume, --session <file> or fork, Pi restores the selection of that branch. A saved, available concrete pair stays concrete, including on the next message. Restoring auto (or overriding with --model pi-task-router/auto) waits for new input. A session killed before Pi’s first disk flush has no saved selection to restore. If its saved model disappeared, Pi may choose its own startup fallback; the router only acts if the resulting selection is auto.

Using auto with subagent modules

Add pi-task-router/auto alongside the physical worker models in the parent's enabledModels (or its --models list). Keep both in the child's scope too. Adding only auto lets a launcher select it but leaves the router no eligible worker.

For example, with fixture/worker replaced by your own worker ID, the equivalent child command is:

pi --model pi-task-router/auto --thinking high --models pi-task-router/auto,fixture/worker -p @task.md

In a subagent module, spawn with model: "pi-task-router/auto". Auto accepts all Pi thinking levels but ignores the one supplied by the launcher. The child classifies the task and sends it to the concrete worker at the router's effort level. The auto card notes the incoming selection, e.g. requested high ignored.

Install the router and make the owner policy available in the child's Pi agent directory. The child needs credentials for the classifier, the quota source (if enabled), and the physical worker. If the launcher doesn't inherit the classifier or quota environment variable, replace "apiKeyEnv": "TASK_ROUTER_KEY" (or the quota reference) with, for example, "apiKeyFile": "~/.config/pi/classifier.key". Provision that file privately for the child user; do not put the token in the spawn arguments or in task-router.json.

Preview a task

In an operator session, run /route review this migration. Pi displays the chosen class and eligible model/level (for example review → example/latest/review · high). The classifier can still choose a class whose target is unavailable in this session. In that case preview checks only the configured substitute in the same row. If neither role is eligible it reports the class and both IDs without recommending a worker. Preview sends the bounded task text to your configured classifier, so do not include anything you would not disclose to it. It does not send a worker prompt, launch a child or change your conversation’s model. /route without a task prints usage and sends nothing.

If the decision fails, Pi shows the reason. Choose Retry to send the same assignment again under the same settings, or Cancel to leave it unsent. Dismissal also cancels. Once the configured retry budget is spent, only Cancel is offered. Only an interactive Pi TUI can ask; after 60 seconds no answer means cancel. RPC (even with UI methods), print, JSON and unknown modes report a reason without retrying. No path silently picks another worker.

Print mode is not a scripting status API. On Pi 1.7.0 a failed pi -p '/route …' writes an extension error with the blocking reason to stderr, leaves stdout empty, and still exits 0: Pi catches extension command errors. Exit status is not evidence that a worker was selected or launched. /route is a human preview only.

Advice for the calling model

route_task({"task":"review this migration"}) returns the report as both JSON text in content and an object in details. It works in parent or child sessions without a spawner. The caller decides what to do next; asking for advice never sends the task to a worker. For example:

Classifier/registry outcome What the report tells you
Scored: review .8, build .2 evidence.byClass contains those values unchanged; target might be example/latest/review · high. candidates lists eligible class/model/level rows.
Label only: review evidence.kind is choice-only; there is no score map. why is the configured review description.
Review wins but its primary is unavailable If eligible, the same-row substitute is recommended with selectionReason: "primary-unavailable". No quota is read or changed. If that substitute is unavailable too, selectedClassEligible is false, target is null, and unavailableReason explains why.
Invalid policy before classification status: "failed", reason: "config"; no winning class, why, or fabricated classifier latency.

Where reports appear

In the interactive session /route adds one saved Preview card below the conversation. Reopening the session redraws it without classifying again or feeding it to the model. The tool shows an Advice card inside its normal result instead. Both fit 80 terminal columns and wrap to narrower windows. Class and effort percentages appear only for reported probabilities; a label alone reads “choice only, no probabilities”. Via identifies the classifier, adapter and elapsed classifier time, not time spent choosing a response.

Print, JSON and RPC emit one single-line summary on stderr per decision. For example (shortened): Preview: review → example/latest/review · high | review=0.8, build=0.2 | … | decider · system-one · 42 ms. Control characters are removed for display; long fields and lists may be abbreviated on stderr. Tool data remains complete on its normal channel.

Owner configuration

Start with examples/task-router.json. Copy it to task-router.json in your user Pi agent directory (normally ~/.pi/agent/task-router.json). Replace the illustrative classifier and worker IDs with your own. There is no built-in service, class list, or worker default. The loader takes a new snapshot on request, never searches the current project, and does not probe an endpoint. Missing/invalid settings fail the decision; ordinary Pi startup does not need a config.

  • Migrate to version: 2: replace every row's fixed thinking with an explicit substitute and add a shared effort scale. Old quota thresholds and plaintext API keys are rejected, not translated.

  • classes is nonempty. Each unique id has a nonblank description, target and substitute. Both routes must match exact registrations in your installation (provider, then everything after the first slash), or one-hop names in aliases mapping to exact IDs.

  • effort.levels lists unique Pi levels in increasing order; the first is the floor. Set one fewer strictly increasing numeric thresholds, each greater than zero and at most the last ordinal index. The example uses medium/high/xhigh. With probabilities, multiply each level's zero-based index by its probability and sum. Count thresholds at or below the unrounded score: 0.5 selects high, 1.5 selects xhigh on the example scale. With choice only, use the effort label and report a null score. Both roles get the same request. The nearest supported configured level wins (ties go higher); if none is supported the route is ineligible. A clamp is shown as requested → effective before dispatch; an unexpected host clamp fails the handoff.

  • classifier: all protocols require integer timeoutMs (1–120000) and maxTaskChars (1–65536). Choose one protocol and its own fields:

    protocol Other fields
    pi-registry ref: exact registered classifier provider/id. Credentials come from Pi.
    system-one endpoint, model, response: strict-pi or choice-only; exactly one of apiKeyEnv or apiKeyFile.
    openai-chat-json endpoint, model, output: json-schema or json-object; exactly one of apiKeyEnv or apiKeyFile.

    Remote endpoints are full URLs, not base URLs. Use HTTPS, or HTTP to localhost, 127.0.0.1 or [::1] for local deployments. URL credentials, queries and fragments are not accepted. apiKeyEnv refers to an environment variable by name. Alternatively, apiKeyFile names an absolute or ~/ path (expanded in the child). The router reads the token at request time, so rotation needs no restart. Symlinks are followed. The opened target must be a regular file owned by the child user with no group or other POSIX mode bits set (e.g. 0600). Extended ACLs are not inspected: an ACL can grant access even at 0600. Do not add ACLs to the key file. Keep the path and its target in directories you control. Store one nonempty printable ASCII token, at most 16 KiB including its optional trailing newline. Never put key material in the policy. Only configure a classifier you trust: the task text itself may contain sensitive information, even for a preview. The router only sends bounded input text and class/effort criteria, never images, history or target mappings. It does not open paths from task text or expand templates. Pi may already have folded CLI file arguments or stdin into the text before the router sees it; that text is not redacted.

  • onFailure: interactive: "ask", unattended: "block", integer maxUserRetries (0–3). No automatic retry or fallback model.

  • quota: omit or set {"enabled": false} to disable. The example declares a CLIProxyAPI pi-bridge source; replace its origin, key reference and registry-provider → upstream-provider mappings with your own installation’s values. Weekly settings are dailyBudgetPercent (default 100/7) and hysteresisPoints (default 3).

Release note: 0.1.1

Auto now accepts a subagent launcher's thinking setting without overriding the router's choice. Remote classifiers and quota sources can use a private key file instead of an inherited variable. Migration: remote classifiers previously configured without authentication now require one of the two credential references; Pi registry authentication is unchanged.

Development

With Node 24+, run npm ci, npm run typecheck, then npm test. The unit suite alone (node --experimental-strip-types --test tests/*.test.ts) needs no host installation. The full offline suite also uses an installed Pi 1.7.0 CLI (set PI_TEST_CLI if not on PATH) and a POSIX host with Python 3 and tar. Acceptance tests use temporary homes and fake providers. The package smoke runs npm pack --offline and loads the extracted package in isolated Pi.

Pi typed registry classifier

To use a classifier registered in Pi, replace the example's classifier with:

{"protocol":"pi-registry","ref":"example/decider","timeoutMs":2500,"maxTaskChars":4000}

This selects a classifier, not a chat model. Pi resolves its credentials; both named choices must complete and match their configured labels. For Pi 1.7.0’s native classifier, each call disables automatic retries and supplies a fetch that refuses redirects. Custom registry providers are trusted extension code: use only providers that honor these per-call options, or use a direct adapter.

System One endpoint

One POST to the full endpoint carries one bounded task and two questions. For example, with a small custom policy:

{"model":"decider","state":{"task":"Review the migration"},"questions":{"class":{"type":"choice","instructions":"Choose the deliverable","criteria":{"review":"Evaluate existing work","build":"Implement known behavior"}},"effort":{"type":"choice","instructions":"Choose effort independently","criteria":{"medium":"Known path","high":"Coupled parts"}}}}
{"answers":{"class":{"type":"choice","choice":"review","probabilities":{"review":0.9,"build":0.1},"confidence":0.9},"effort":{"type":"choice","choice":"high"}}}

This mixed response is valid in choice-only mode. strict-pi requires probabilities and finite confidence on each answer. On either axis, a provided map must contain exactly the configured labels, every value finite in [0,1], with sum within 0.001 of 1. Maps are never normalized. Missing probabilities in permissive mode mean choice only; a missing answer is a failure, not an invitation to retry. The native registry gets the same two questions in one call. Its System One provider appends systemone to its base URL (https://classifier.example/v1), unlike the direct adapter. Pi 1.7.0’s native System One transport requires probabilities and confidence for both questions. It rejects a missing answer or a choice-only wire reply before the router sees the answers, so the registry adapter reports unavailable, not a guessed incomplete-answer. Use the direct system-one adapter in choice-only mode for a permissive wire endpoint. A custom registry provider can still supply valid typed choice-only results. System One reads the two requested answer IDs and ignores unrelated question IDs; extra probability-map labels are invalid.

A CLIProxyAPI deployment with a System One plugin and path rewrite is one possible endpoint. The adapter sends System One data, not Chat Completions data, regardless of the proxy's internal path. No proxy is required or preconfigured.

OpenAI-compatible Chat Completions

For a chat classifier, use a full Chat Completions URL, for example:

{"protocol":"openai-chat-json","endpoint":"https://classifier.example/v1/chat/completions","model":"advisor","output":"json-schema","apiKeyEnv":"TASK_ROUTER_KEY","timeoutMs":2500,"maxTaskChars":4000}

json-schema requests strict structured output with two required enum fields: classId from the class IDs and effort from the configured levels. Choose json-object explicitly for services that support JSON objects but not schemas. Both modes require a completed, non-refused JSON answer such as {"classId":"review","effort":"high"} with exactly those keys. Both answers are choice-only: no probabilities or numeric effort score. Neither retries in a weaker mode, follows redirects, or treats a reply as a worker model name.

Known limitations

On Pi 1.7.0, another extension that changes thinking levels on a model-change event can overwrite a level you set immediately after cancelling auto routing. For example, you cancel, reselect the same model, and choose high; a delayed handler for the old selection may then apply low. Pi cannot cancel event delivery already in progress. The router does not resend the cancelled task. If the level changes, set it again after the other extension finishes. Pi source: dist/core/agent-session.js:2103–2111,2917–2918 and dist/core/extensions/runner.js:827–839.

Acknowledgments

Weekly quota source

Only the user agent policy can configure the trusted bridge origin. The router makes one cached GET /v0/resource/plugins/pi-bridge/usage with X-Pi-Contract: 2 and an ordinary client bearer key from apiKeyEnv or apiKeyFile (not a management key). Map the primary registry provider to claude or codex; its physical model ID must be the model name accepted by that proxy. The query contains that model, mapped provider, and current Pi session ID, not task text. No refresh, redirect, retry, or admin endpoint is used.

Single host namespace (default): leave quota.source.sessionPrefixes unset, as in the shipped example. The router sends the bare Pi session ID once. The bridge resolves it if the same client key has exactly one unexpired host identity with that suffix. No namespace detection or extra setup is needed in that case.

Multiple host namespaces: if that key uses two identities with the same suffix, the bare ID is ambiguous even with a provider filter. Set quota.source.sessionPrefixes by primary registry provider to the prefix verified for that worker’s actual transport. For example, {"openai":"header:"} uses session=header:<Pi session ID> even when providers.openai is codex. The local pi-cliproxyapi usage cache describes accounts and windows, not the host identity used by the client key. Neither a provider name nor a cached account establishes a prefix. When affinity is unknown the router uses the conservative rule below; it never probes a second identity.

The bridge returns account windows and, when available, the account bound to this model, client key and session. A new session may have no affinity until after its first completed request. The router uses Claude’s common seven-day group or Codex’s duration-confirmed 7d Window, never a family cap, five-hour floor, token count, pace or average across accounts.

Each account’s allowance accrues from its own weekly reset − 7 days: allowed percent = dailyBudgetPercent × elapsed fractional days. More than 3 points above allowance (by default) enters substitute mode; more than 3 below releases it. The band and its edges retain that account’s mode. A confirmed fresh new week starts in primary and is evaluated immediately; no other account can advance its reset marker or observation time.

  • Known binding: use only the serving account’s mode, retaining it if its weekly data is stale or missing. No record means primary. A and B may legitimately choose different roles on the same snapshot.
  • Unknown binding: use the most conservative fresh account record for this primary provider: any fresh substitute hold wins; otherwise primary. Expiry is bounded by both cache TTL and weekly reset. Structured results distinguish budget.basis: "serving-account" and "conservative" without identifying an account. Bridge routing.share estimates where new requests will go; it is not proof of a serving account and cannot override a session binding.

task-router-account-state.json in the Pi agent directory stores provider-scoped records under opaque account digests. One atomic write accepts all strictly newer account observations from a snapshot under a cross-process lock. Replaying a snapshot, even with alternating bindings, does not rewrite it. If upgrading from the provider-only format, the old task-router-state.json is left untouched: its holds cannot safely be assigned to any account. New records initialize from attributable readings. Errors reading or writing active state block the recommendation rather than discarding a hold. After a crash, confirm no writer is active before removing a leftover empty task-router-account-state.json.lock directory. Disabling quota bypasses this state and the source, not local eligibility.

Example header after three days, when the Anthropic build primary has used 52% against 43% allowed (wrapped on narrow screens):

Auto · applied → openai/gpt-6.2-sol · high (anthropic over daily budget: 7d 52% used vs 43% allowed)

A fresh reading inside the band shows (anthropic budget hold). Without a fresh reading the same choice shows (anthropic budget hold: last known), never old numbers presented as current. An availability-driven substitution says (primary unavailable). A primary recommendation has no suffix. There is no quota row or change to the existing quota footer.

The tool returns exact primary, substitute, chosenRole and selectionReason separately from evidence (class) and effortEvidence. score is unrounded or null, requested is common to both roles, and effective matches target.thinking when eligible. clamp is null unless that model required a permitted adjustment (for example {"requested":"xhigh","effective":"high"}).