Commit graph

906 commits

Author SHA1 Message Date
Armin Ronacher
18b142f2fe fix(codemode,durable,coding-agent): start() runs in one remote session; review fixes
- RemoteCodemodeSandbox ran start() step by step, saving the whole heap after
  every step (and failing on a WeakRef). Sandboxes now open a run with its
  lifetime (session or saved), and a start() run is one session on the remote,
  as on main.
- start()'s tests run on the worker, inline, and remote sandboxes again, with
  main's cases for globals numbered with tools and rejections carrying their
  properties; a test checks a remote start() takes no steps.
- start()'s fingerprint names the run's actual CPU budget (none, a number, or
  remote), not "default" for every sandbox.
- start()'s call records carry the module; the dropped calls are computed once.
- Durable skips a namespace named like a built-in global or a global's
  namespace (models) as a module, instead of failing every script; pi-codemode
  exports CODEMODE_RESERVED_NAMES from /declarations for it.
- Docs: CodemodeHostCall.id, durable's call keys and schema, the CHANGELOGs
  (start()'s jsName, the un-awaited calls rule, /remote, strict mode and UTC in
  the coding agent), the README on dropped calls and remote start() runs, and
  the coding agent's Bun caveat, which no longer holds (checked on Bun 1.4.4:
  a long sort or split stops at the deadline).
2026-11-30 19:15:05 +01:00
Armin Ronacher
5b74b2b7bc feat(codemode): local time is UTC in every run; store() errors without the host stack
- djs's local zone is one fixed offset (the host's current one, no DST), so
  dates across a DST change were an hour off. Every run now passes
  timeZoneOffset 0: getTimezoneOffset() is 0 and local time is UTC, as it
  already was in deterministic runs.
- A store() value JSON cannot hold no longer puts the host's
  JSON.stringify stack (absolute host paths) into the script's error; the
  reason is name and message only.
2026-11-30 19:15:05 +01:00
Armin Ronacher
8ce71fa54f feat(coding-agent): codemode on djs, a worker per script
Scripts run on djs in a worker of their own, as before with QuickJS: worker admission
and PI_CODEMODE_MAX_WORKERS stay, the bundle and the Bun binary embed djs.wasm and the
codemode worker. A script has a CPU budget of about a minute; TypeScript works.
2026-11-30 19:08:13 +01:00
David Brailovsky
8a35b0d44d docs(coding-agent): add Subscriptions page
Lists the plans Pi can use (sign in with an account or the plan's API key),
linked from Providers and Choose a Model.
2026-11-30 12:06:12 +01:00
Armin Ronacher
d87e3273f1 fix(tui): use 256 colors under GNU screen despite an inherited COLORTERM
closes #10618

Co-authored-by: Diego Sanchez Tirado <87272789+dsanchezt22@users.noreply.github.com>
2026-11-29 00:45:23 +01:00
Armin Ronacher
981a5ee961
feat(mcp): Mcp 2026 07 28 Support (#12652)
Adds MCP `2026-07-28`, the stateless protocol revision, to `pi-mcp` and
pi's MCP extension. Reworked from #12479 by @dmmulroy. Refs #10416.
2026-11-28 22:41:06 +01:00
Armin Ronacher
d9ebb41259 Revert "feat(mcp,coding-agent): support the stateless MCP protocol 2026-07-28"
This reverts commit 356d346e4. It was not meant to ship yet; the work
continues on the mcp-2026-07-28 branch.
2026-11-28 20:47:23 +01:00
Armin Ronacher
356d346e48 feat(mcp,coding-agent): support the stateless MCP protocol 2026-07-28
Every connection still starts with initialize, so servers of earlier
revisions see exactly what they saw before. Only servers that reject
initialize (a JSON-RPC error, or HTTP 400) are asked with server/discover
and spoken to with 2026-07-28; a stdio server that exits after rejecting
initialize with a 2026-07-28 error (rmcp) is started once more with it.
"protocol": "2026-07-28" pins the stateless revision.

On the stateless revision: per-request _meta, multi round-trip requests
answered with the client's handlers (roots/list), Mcp-Method, Mcp-Name and
Mcp-Param-* headers with x-mcp-header validation and one re-list on header
mismatch, sessionless HTTP with cancel by closing the stream, and logLevel.

Reworked from #12479 by @dmmulroy without probing servers first, which
broke Python servers before mcp 1.9.4 and rmcp 0.8.

Refs #10416
2026-11-28 13:51:43 +01:00
Armin Ronacher
1e7bc7213b fix(ai): preserve the deprecated Ant Ling thinking format
Update the release notes with the changelog audit.
2026-11-27 16:34:29 +01:00
Vegard Stikbakke
f7470d0668 feat(ai): add image model support to Radius provider
- Parse images[] from Radius /v1/config into ImageModel<"pi-image">
- Expose generateImages() on radiusProvider() while keeping getModels()
  chat-only, and persist/restore image models offline
- Add tests in packages/ai/test/radius-provider.test.ts and update docs
2026-11-27 09:54:15 +01:00
Petr Houška
145785f0d7
feat(coding-agent): repeat restriction and resource flags in the OSC 7577 resume command (#12602)
Follow-up to #12557 and #12595 (OSC 7577 program resume).

## Problem

pi reports `pi [--agent-dir A] [--session-dir S] --session <id>` as its
resume command, whatever flags it was started with. A session started
with restrictions or extra resources comes back without them:

```
started:   pi -t read,grep,find,ls --no-extensions
resumed:   pi --session <id>          # bash, edit, write and all extensions are back
```

## Changes

- `parseArgs()` records the restriction and resource flags in
`Args.resumeFlags`, as typed and in order, with the values the parser
consumed: `--tools`/`-t`, `--exclude-tools`/`-xt`, `--no-tools`,
`--no-builtin-tools`, `--extension`/`-e`, `--no-extensions`, `--no-mcp`,
`--skill`, `--no-skills`, `--prompt-template`, `--no-prompt-templates`,
`--theme`, `--no-themes`, `--no-context-files`, `--system-prompt`,
`--append-system-prompt`, `--approve`, `--no-approve`, `--models`. Not
repeated: what the session keeps (model, thinking level, name), session
pickers, cosmetic flags, and `--api-key` (a terminal stores the command
in plain text).
- `getProgramResumeCommand()` appends them after `--session <id>`. The
command printed on exit is unchanged.
- When the session's directory differs from the directory pi was started
in (after `/resume` into another project), pi clears the command:
relative paths in the flags would point elsewhere, and resuming without
them would drop the restrictions. pi never changes its working
directory, so `process.cwd()` is the directory the flags were typed in.
- Docs (`terminal-setup.md`): which flags are repeated, and that a
terminal rule must trust each combination.

## Why "as typed"

A Rex rule matches the reported command word for word, so the command
has to repeat what the user types (`-t read` stays `-t read`, `./ext.ts`
stays relative), and a rule per combination trusts it:

```lua
rex.set("resume.trust.pi_readonly", {
  command = { "pi", "--session", rex.match.uuid, "-t", "read,grep,find,ls" },
})
```

Rex rules with a `flags` table, which accept any combination, compare
the flags with `/proc/<pid>/cmdline`. pi's `process.title = "pi"`
overwrites that under Node on Linux (and, per the Node docs, macOS), so
such rules reject pi with `flags_differ`. Claude Code is not affected:
Bun's `process.title` only changes `comm`. Making flags tables work
needs either a change in how pi names its process (on Linux, writing
`/proc/self/comm` instead) or Rex reading the command line before the
program renames itself; not part of this PR.

## Testing

- `npm run check`
- `test/args.test.ts` (recorded flags, as typed and in order; flags left
out), `test/format-resume-command.test.ts` (`getProgramResumeCommand`:
flags appended, exit hint unchanged, cleared from another directory, no
flags from another directory still resumes)
- Manual with an isolated Rex server, real pi built from this branch,
and the rule above:
- `pi -t read,grep,find,ls`: reported with the flags, trusted by
`pi_readonly`; after a Rex restart resumed by that rule, and the resumed
pi reported `-t read,grep,find,ls` again.
- `pi --no-context-files` with no matching rule: `flags_differ`, the
pane came back as a plain shell instead of a session without the
restriction.
2026-11-27 00:48:27 +01:00
Petr Houška
dd71a6fc76
feat(coding-agent): add --agent-dir and carry it in the resume command (#12595)
Follow-up to #12557 (OSC 7577 program resume). Removes its known
limitation "`PI_CODING_AGENT_DIR` set for one run only is not carried".

## Problem

A terminal resumes pi's reported command without the environment pi was
started in. A session started with `PI_CODING_AGENT_DIR` (for example
from a shell function that picks a separate profile for one directory
tree) comes back with the settings and auth of `~/.pi/agent`.

Trace, before this change, with
`PI_CODING_AGENT_DIR=~/.pi/earendil/agent` and
`PI_CODING_AGENT_SESSION_DIR=~/.pi/earendil/agent/sessions`:

1. pi reports `pi --session-dir ~/.pi/earendil/agent/sessions --session
<id>`.
2. Rex restarts and runs that command through `exec`, so no shell
function and no old environment.
3. pi finds the session through `--session-dir`, but loads auth,
settings, models and extensions from `~/.pi/agent`.

The spec asks for exactly this case to go into argv: "A program whose
target depends on its environment or on other state outside the command,
such as a credentials profile ..., SHOULD put the resolved values in its
argv using its own flags." pi had no flag for the config directory.

## Changes

- `--agent-dir <dir>`: the flag form of `PI_CODING_AGENT_DIR`, taking
precedence like `--session-dir` over `PI_CODING_AGENT_SESSION_DIR`. It
is applied by setting `PI_CODING_AGENT_DIR` to the absolute path,
because pi, extensions (through the exported `getAgentDir()`) and child
processes all read the agent dir from there.
- When it is set: `main()` applies it first (`applyAgentDirArg`), before
anything reads the agent dir and before subcommands are recognized, so
`pi --agent-dir D install ...` works. Modules have loaded by then, so a
value cached from `getAgentDir()` at module load would ignore the flag.
`config.ts` and `cli/agent-dir-arg.ts` warn against such caches. Setting
the variable before any module loads (a setup module imported first by
the entries) was tried and dropped: esbuild code splitting put the
setup's imports into the chunk with `main()`, which needed its own
bundle entry and a build guard to keep the order.
- `getResumeArgs()` adds `--agent-dir <absolute dir>` when
`usesDefaultAgentDir()` is false. This covers both the command printed
on exit and the OSC 7577 report. Default setups keep `pi --session
<id>`.
- `tools-manager.ts` cached `getBinDir()` in a module constant at
import, before `main()` runs, so `fd`/`rg` downloads ignored the flag.
It now reads it per call. No other module-level reads of the agent dir
exist in `src/`.
- Docs: `cli.md`, `environment-variables.md`, `terminal-setup.md`
(Program resume: longer commands need their own terminal rule).

## Testing

- `npm run check`
- `test/agent-dir-arg.test.ts`: `applyAgentDirArg` (any position, last
wins, absolute and `~` paths, `--` stops scanning, missing value);
`src/cli.ts --agent-dir D --list-models` lists a model from
`D/models.json`
- Bundled `dist/bundle/cli.js --agent-dir D --list-models` lists the
same model
- Manual with an isolated Rex server (`rex server run --listen
unix:///tmp/... --state-dir ...`) and this rule:
  ```lua
  rex.set("resume.trust.pi_earendil", {
command = { "pi", "--agent-dir", "/home/houskape/.pi/earendil/agent",
"--session-dir", "/home/houskape/.pi/earendil/agent/sessions",
"--session", rex.match.uuid },
  })
  ```
pi started in `~/earendil/...` through the shell function reported the
command above (`trusted: true`). After `rex server stop` and start, the
log shows `resuming saved program program=pi rule=pi_earendil`; the
resumed process had no `PI_CODING_AGENT_DIR` in its initial environment,
`!echo $PI_CODING_AGENT_DIR` printed
`/home/houskape/.pi/earendil/agent`, and the conversation and profile's
model were back.
2026-11-26 23:48:27 +01:00
Petr Houška
f69c3e121a
docs(coding-agent): reset the terminal after Pi was killed (#12601)
Refs #12564.

A killed Pi leaves its terminal modes on. The previous advice, "run pi
again and quit", does not reset Kitty keyboard reporting: the terminal
keeps those settings on a stack, Pi pushes once and pops once per run,
so each killed run leaves one entry behind. It also only resets the
alternate screen and mouse reporting when the next run uses fullscreen
mode.

This updates "Recover the terminal after Pi was killed" in
`docs/terminal-setup.md`:

- States that the real fix is finding what kills Pi.
- Gives a reset command for bash/zsh and PowerShell: pops up to 16 Kitty
entries (`\e[<16u`), sets the rest to 0 (`\e[=0;1u`), turns off
modifyOtherKeys, bracketed paste, mouse and focus reporting, restores
wrap and cursor.
- `\e[?1049l` only when the alternate screen is still active, since on
the normal screen it desyncs the shell's line editor (reported in
#12564).
- When the pane cannot be typed in: start Pi in another tab and ask it
to write the reset to the stuck tab's terminal.

Both PowerShell variants (5.1 and 7) were checked to expand the sequence
correctly.

This PR is AI-generated.
2026-11-26 23:15:02 +01:00
Vegard Stikbakke
c863bdf19c feat(ai,coding-agent): add image generation options
- Add aspectRatio and size to ImagesOptions
- Forward aspectRatio and size to OpenRouter's image_config in
  openrouter-images
- Validate and forward optional { aspectRatio, size } as the third
  argument to codemode models.generateImages(); unknown option keys
  such as apiKey or aspect_ratio throw
- Document the options in the ai README and the codemode and models
  docs, and add tests
2026-11-26 15:25:51 +01:00
Vegard Stikbakke
484da3a869 feat(coding-agent): remove telemetry
Remove telemetry reporting from pi for new installs or updates.
2026-11-26 14:51:47 +01:00
Christian Klotz
bf3f6a2228
docs(coding-agent): revert telemetry page (#12589)
Reverts #12584 (524f015b3).
2026-11-26 13:42:44 +00:00
Christian Klotz
524f015b3c
docs(coding-agent): document telemetry and network requests (#12584)
Adds `packages/coding-agent/docs/telemetry.md` under Reference
("Telemetry"), based on a read of the current code.

The page covers:

- Requests to `pi.dev`: install/update ping (the only automatic
telemetry), version check, model catalog updates. For each: when, data
sent, how to turn it off.
- Metadata Pi adds to model requests: `User-Agent` and its exceptions,
attribution headers (OpenRouter, NVIDIA NIM, OpenCode), `originator: pi`
for Codex, session ID.
- Identifiers (`deviceId`, `trackingId`, session ID) and that extensions
can read them.
- The analytics opt-in: stored, but no code sends it.
- What `/bug` sends, and its redaction limits.
- Controls: `PI_TELEMETRY`, `enableInstallTelemetry`,
`PI_SKIP_VERSION_CHECK`, offline mode; Pi does not read `DO_NOT_TRACK`.
- What the controls do not cover: extensions, Pi packages, MCP servers,
tool commands.

Functional network traffic (MCP connections, provider model lists,
package checks, tool downloads, `/share`) is out of scope.

Also links the page from `settings.md` and `environment-variables.md`.

Findings in the code, not changed here:

- The experimental first-run setup tells users to inspect shared data
with `/privacy`, which does not exist.
- `enableAnalytics` and `trackingId` are stored but unused.
`pi.getSettings()` exposes both, and the merged value lets a trusted
project's `.pi/settings.json` override them.
- `PI_OFFLINE` is parsed inconsistently: some checks test whether it is
set, others parse the value, so `PI_OFFLINE=0` disables the `pi.dev`
requests but not package checks.

Claims were checked against the source and reviewed independently by
GPT-6.2 Astra, GPT-6.2 Sol, and Claude Opus 5.5. Verified with
`test/documentation.test.ts`.
2026-11-26 12:22:28 +00:00
Petr Houška
cf419553da
feat(tui,coding-agent): report session resume command via OSC 7577 (#12557)
Implements the program side of the [Program Resume Protocol (OSC
7577)](https://www.superlogical.com/rex/docs/build/program-resume):
terminals that set `OSC7577_TOKEN` can bring pi back after they restart.

## Problem

A terminal restart (update, crash, reboot) ends pi. The user has to find
and run the resume command themselves. OSC 7577 lets the program tell
the terminal the command, authenticated with a SHA-256 `mac` over the
report and a per-pane token, so text that only passes through the
terminal (`cat`, logs, `ssh`) cannot register commands.

## Changes

- **pi-tui** `program-resume.ts`: `formatProgramResume()`,
`formatProgramResumeClear()`, `takeProgramResumeToken()`. Commands the
spec cannot carry (control characters, relative program or cwd, over the
64-argument / 2048-byte limits) return `undefined`; the caller sends
`clear` instead so an older command is not resumed in its place. Tests
use the spec's example reports and `mac` values.
- **coding-agent** `ProgramResumeReporter` (sibling of
`ProgramStatusReporter`): reports the command pi already prints on exit,
`pi [--session-dir D] --session <id>`, with the session cwd.
`formatResumeCommand` now builds on a shared `getResumeArgs()`.

| Moment | Action |
|---|---|
| Startup, `/resume`, `/fork` | report |
| First message of a new session written | report |
| `/new` without messages | clear (no file to resume) |
| `fg` after Ctrl+Z | report again (a program may have replaced it while
suspended) |
| Ctrl+D, Ctrl+C twice, `/quit` | clear |
| SIGHUP / SIGTERM | keep (the terminal needs it then) |

- **main()** takes the token out of `process.env` first, in every mode,
so `!` shells, `$EDITOR`, extension processes and tool commands cannot
replace pi's command or register their own.

## Testing

- `npm run check`
- `packages/tui/test/program-resume.test.ts`,
`packages/coding-agent/test/program-resume-reporter.test.ts`,
`format-resume-command.test.ts`
- Manual in tmux with `PI_TUI_WRITE_LOG`: mac verified with `sha256sum`,
`!env | grep OSC7577` finds nothing, `fg` re-reports, Ctrl+D and `/new`
clear, killing the tmux session sends no clear.

## Known limitations

- The command uses the bare name `pi` (the spec's preference, survives
updates); a source checkout resumes the installed `pi`.
- `PI_CODING_AGENT_DIR` set for one run only is not carried; the spec
forbids sending environment variables and pi has no flag for it.
2026-11-26 00:02:34 +01:00
Petr Houška
f81d4bfdae
fix(ai): stop sending earlier reasoning to Bedrock Kimi K3 models (#12555)
Some checks are pending
CI / test (other) (push) Waiting to run
CI / mcp-conformance (push) Waiting to run
CI / build-check (push) Waiting to run
CI / test (chord) (push) Waiting to run
CI / test (coding-agent) (push) Waiting to run
CI / test (durable) (push) Waiting to run
## Problem

The AWS model cards for [Kimi
K3](https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-moonshot-ai-kimi-k3.html)
and [Kimi
K3.1](https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-moonshot-ai-kimi-k3-1-highspeed.html)
list a known Converse limitation: requests fail with
`InternalServerException` when reasoning content from earlier turns is
included. AWS says to remove reasoning blocks from prior turns.

Pi sends them back. `transformMessages()` keeps thinking from the same
model, and `convertMessages()` sends it as
`reasoningContent.reasoningText` for non-Claude models. A normal tool
loop hits this on the second request:

1. user -> assistant `[thinking, toolCall]`
2. request 2 sends `user, assistant[reasoningContent, toolUse],
user[toolResult]` -> `InternalServerException` per AWS

## Fix

- New Bedrock compat flag `compat.supportsReasoningReplay` (default
`true`). When `false`, `convertMessages()` skips thinking blocks of
earlier assistant messages, including redacted ones.
- The catalog sets it to `false` for the `moonshotai.kimi-k3` family (K3
and K3.1, all six profiles; `npm run diff:model-catalog --
amazon-bedrock`). A flag in the catalog rather than a model-name check
in the request code follows `compat.supportsStrictMode`, and lets
`models.json` set it for application inference profiles whose ID and
name do not say Kimi.
- `docs/models-configuration.md` regenerated from the schema.

Released clients ignore the unknown flag and keep today's behavior, so
the catalog minimum version does not change.

Trade-off: Kimi loses its earlier reasoning between turns on Bedrock
Converse. AWS documents no other way to make multi-turn Converse
requests work for these models.

Not verified against a live Bedrock account; the change follows the AWS
documentation. Tests in `test/bedrock-convert-messages.test.ts` check
that reasoning is still sent back by default and dropped for the
catalog's Kimi K3 and K3.1 models.
2026-11-25 23:36:33 +01:00
Petr Houška
0639c728b1
docs(coding-agent): explain how to recover the terminal after Pi was killed (#12554)
When Pi is killed (`kill -9`, Task Manager, out of memory), it cannot
turn off the alternate screen, mouse and focus reporting, or
extended-key protocols. The shell then gets mouse reports typed into its
prompt (#12133).

This adds a row to the troubleshooting table in `docs/terminal-setup.md`
and a short section "Recover the terminal after Pi was killed": run `pi`
again and quit it cleanly. The section also gives the steps for when
typed input is not visible: keep the pointer off the pane, press Ctrl+C,
type `pi`.

Refs #12133
2026-11-25 22:26:29 +01:00
David Brailovsky
9627ebab8e feat(ai,coding-agent): load Ant Ling models from models.dev
The ant-ling provider now maps models.dev's "bailing" entry instead of a
hardcoded list, replacing the retired Ling 2.6 and Ring 2.6 models with the
Ling 3.x models. Ant Ling only turns thinking off with thinking.type
"disabled" and ignores effort values, so models expose off and high and use
the deepseek thinking format. Removes the "ant-ling" thinking format and
changes the default model to Ling-3.1-flash.

Based on #11800 by @lvisei.

closes #12201
2026-11-25 21:59:42 +01:00
Vegard Stikbakke
e24c9d5f0b Revert "feat(coding-agent): show transcript notices by default"
This reverts commit cba14324c3.
2026-11-25 12:05:48 +01:00
Vegard Stikbakke
6906528da0 docs(ai,coding-agent): use decision models in prose and changelogs
Pi-Session: 01a2119a-06d9-7426-b332-0e6e6770881c
2026-11-25 08:43:24 +01:00
Vegard Stikbakke
cba14324c3 feat(coding-agent): show transcript notices by default
Users who never set notices.* or the legacy showCacheMissNotices now see
cache miss, cache warming, compaction cost and reasoning-drop notices.
Explicit values are kept.
2026-11-25 08:38:46 +01:00
Vegard Stikbakke
88c6e00f7d feat(coding-agent): add one setting per transcript notice
showCacheMissNotices also controlled cache warming, compaction cost and
provider reasoning-drop notices. Replace it with notices.cacheMisses,
notices.cacheWarming, notices.compactionCosts and notices.reasoningDrops,
shown under Notices in /settings. An existing showCacheMissNotices value
is migrated to all four. Defaults are unchanged.
2026-11-25 08:38:41 +01:00
Petr Houška
c7a5f2e784
docs(coding-agent): describe WebSocket connection failures for after_provider_response (#12503)
Follow-up to #12502 / #12376.

States when `after_provider_response` does not fire: errors inside an
already started SSE stream, and WebSocket transports, including a
WebSocket connection that fails to open.

Docs only.
2026-11-25 00:32:48 +01:00
Petr Houška
8a57d42a5d
fix(ai,coding-agent): report HTTP error responses to onResponse (#12502)
Refs #12376

Problem: `onResponse` (and the `after_provider_response` extension
event) never fired for 4xx/5xx responses on SDK-based adapters. Example
on `openai-completions`: a 429 makes
`client.chat.completions.create(...).withResponse()` reject with the
SDK's `APIError`, so the `onResponse` call after it never runs, and the
catch block keeps only `errorMessage` (`"429 ..."`). The status and
`retry-after` header on the `APIError` were dropped. The fetch-based
adapters (OpenAI Codex SSE, Mistral, pi-messages) and Amazon Bedrock
already reported error responses, once per attempt.

Change:

- `retryProviderRequest` gets `onErrorResponse`, called for each failed
attempt that carries an HTTP status, before the retry decision. Not
called after an abort or for failures without a status (connection
errors). A throwing callback fails the request, like every other pi-ai
callback.
- Wired into `openai-completions`, `openai-responses`,
`azure-openai-responses`, `anthropic-messages`, OpenRouter images and
Google (`retryGoogleRequest` now takes the model). Google's `ApiError`
has no headers, so Google reports the status with `{}`; Google still
reports no successful responses (unchanged).
- Classifiers (`classifier-shared`, `llama-cpp-classify`) call
`onResponse` right after `fetch`, before reading the body, like the
fetch-based chat adapters, so an error whose body fails to arrive still
reports its status.
- Docs: `onResponse` and `AfterProviderResponseEvent` comments,
`docs/extensions.md`, changelogs.

Behavior change: one request can now fire the hook several times (each
retried attempt, Anthropic thread and strict-tools fallbacks report the
rejected 400 and then the 200). Codex already behaved this way.
Extensions are not affected by throwing handlers: the extension runner
catches them.

Other changes:

- Classifiers now call `onResponse` before reading the body instead of
after parsing it. On success it fires before JSON parsing, and the
callback runs inside the attempt's `timeoutMs` window.
- `retryGoogleRequest` (`api/google-shared.ts`, reachable through the
`./api/*` export) takes `model` as its second parameter. No caller
outside pi-ai in the repo.

Not covered: errors inside an already started stream (SSE error event
after a 200) and the Codex WebSocket transport have no HTTP status to
report; documented in `docs/extensions.md`.

Tests: `provider-error-response.test.ts` runs a local server answering
429 with `retry-after` against five adapters (fails without the fix);
unit tests in `provider-retry.test.ts`, `google-shared-retry.test.ts`,
`pi-classifier.test.ts`, `llama-cpp-classify.test.ts`.
2026-11-25 00:22:38 +01:00
Petr Houška
90ef46ffeb
fix(ai,coding-agent): add Copilot gpt-6-luna-decisions and filter classifiers by account (#12495)
Some checks are pending
CI / build-check (push) Waiting to run
CI / test (chord) (push) Waiting to run
CI / test (coding-agent) (push) Waiting to run
CI / test (durable) (push) Waiting to run
CI / test (other) (push) Waiting to run
Environments / tests (ubuntu-24.04-arm) (push) Waiting to run
Environments / tests (ubuntu-latest) (push) Waiting to run
CI / mcp-conformance (push) Waiting to run
Environments / daemons (push) Waiting to run
Environments / check (push) Blocked by required conditions
Environments / release-daemons (darwin-arm64, macos-latest) (push) Blocked by required conditions
Environments / release-daemons (darwin-x64, macos-latest) (push) Blocked by required conditions
Environments / release-daemons (linux-arm64, ubuntu-24.04-arm) (push) Blocked by required conditions
Environments / release-daemons (linux-x64, ubuntu-latest) (push) Blocked by required conditions
Environments / release-daemons (windows-arm64, windows-11-arm) (push) Blocked by required conditions
Environments / release-daemons (windows-x64, windows-latest) (push) Blocked by required conditions
Environments / tests (macos-latest) (push) Waiting to run
Environments / tests (windows-11-arm) (push) Waiting to run
Environments / tests (windows-latest) (push) Waiting to run
Fixes #12395.

## Problem

GitHub Copilot listed `microsoft-decision-1` for every account. The
account's `/models` catalog shows it is limited to Business and
Enterprise plans (`billing.restricted_to`), and the reporter's Business
seat rejects it with HTTP 400. The catalog also lists
`gpt-6-luna-decisions` on `/v1/decisions` for Pro, Pro+, Business and
Enterprise, which pi did not have.

Classifiers were never filtered: the login records only picker-enabled
chat models in `availableModelIds`, decision models are never
picker-enabled, and `getAllAvailable()` filters chat models only.

## Change

- `gpt-6-luna-decisions` in the Copilot catalog on the
`openai-decisions` API (text and images, 872K prompt limit from the
Copilot catalog, OpenAI's Decisions price since GitHub publishes none).
The `/v1` prefix wrapper now covers both System One and Decisions.
- Login and token refresh record the catalog's decision models in
`availableClassifierModelIds`. The provider's new `filterAllModels`
lists only those classifiers. Credentials saved before this change have
no list and keep listing every classifier until the next refresh.
- The OpenAI Decisions price moved to `OPENAI_DECISIONS_COST` in
`catalog/families/openai.ts`, shared by `openai` and `github-copilot`.

models.dev has no Copilot decision models (only OpenRouter, Vercel and
others list `openai/gpt-6-luna-decisions`), so the entry is authored
like `microsoft-decision-1`.

## Released clients

pi.dev will serve the new catalog entry to 1.6.0, whose Copilot provider
has no `openai-decisions` implementation, so `classify` returns "no
classifier implementation" there. `MINIMUM_PI_VERSION` is unchanged;
raising it would stop all catalog updates for older clients.

## Verification

- `npm run check`; `classifier-models.test.ts`,
`github-copilot-oauth.test.ts`, `openai-decisions.test.ts`
- Live on a Copilot Enterprise seat: after refresh,
`availableClassifierModelIds` is `["gpt-6-luna-decisions",
"microsoft-decision-1"]`, and `models.classify()` succeeds for both
(choice and bool questions, images on `gpt-6-luna-decisions`). Not
verified on a Business seat.
2026-11-24 21:55:50 +01:00
Petr Houška
e8ee38887e
fix(coding-agent): find Git Bash of git on PATH on Windows (#12494)
Fixes #12408

## Problem

On Windows, bash resolution only probes `%ProgramFiles%\Git` and
`%ProgramFiles(x86)%\Git`, then takes the first `bash.exe` from `where`.
With Git for Windows installed elsewhere, that is usually the WSL
launcher `System32\bash.exe`: commands fail (WSL disabled) or run inside
the distro.

## Fix

Ask the `git.exe` on `PATH` where it is installed: `git var
GIT_SHELL_PATH` (Git 2.47+) reports `<root>/usr/bin/sh.exe`. Use
`<root>\bin\bash.exe`, Git's launcher, which sets up `MSYSTEM` and
`PATH` (`usr\bin\bash.exe` alone cannot find `ls`).

This avoids guessing the root from the location of `git.exe`, which
depends on the PATH option and MSYSTEM flavor (`cmd`, `bin`,
`mingw64\bin`, `ucrt64\bin`) and fails for package-manager shims.

Resolution order on Windows:

1. `shellPath`
2. Git Bash under Program Files (unchanged; no `git` process for default
installs)
3. Git Bash of `git.exe` on `PATH` (new)
4. `bash.exe` on `PATH`

If Git is older than 2.47, reports a shell outside the `usr\bin\sh.exe`
layout, or has no `bin\bash.exe`, resolution continues with step 4.

Durable's `NodeExecutionEnv` mirrors the same lookup.

## Tests

`packages/coding-agent/test/windows-shell-config.test.ts`: Git Bash of
git on PATH wins over the WSL launcher; Program Files still wins without
spawning git; fallbacks for old Git, unexpected shell path, missing
launcher.

This PR is AI-generated.
2026-11-24 21:44:36 +01:00
Petr Houška
642a705e11
fix(coding-agent): report project trust and first-time setup as permission requests (#12490)
Follow-up to #12487 (#12439).

## Problem

The [Program Status
Protocol](https://www.superlogical.com/rex/docs/build/program-status)
defines the `kind` of a `blocked` report as:

- `permission`: approval to do something
- `question`: the user must type an answer
- `auth`: a login, token, or credential

#12487 set the kind from the dialog type: select and input report
`question`, confirm reports `permission`. Two dialogs got the wrong kind
because of that:

- The project trust prompt asks to let pi load `.pi` settings and run
project extensions, which is a permission. It reported `question`,
because it is a select (five options, not Yes/No).
- First-time setup asks for consent to share usage data. It reported
`question`.

The trust prompt can't pass a kind today. It calls `ctx.ui.select()`
through `ProjectTrustContext`, and the dialog options only have `signal`
and `timeout`.

## Fix

- Add `blockedKind?: "permission" | "question" | "auth"` to
`ExtensionUIDialogOptions`, used by `select()`, `confirm()` and
`input()`. The defaults stay as they were (`confirm` -> `permission`,
the others -> `question`). This works like the `blocked` option of
`ctx.ui.custom()`. The message is still the first line of the title, so
callers only set the kind.
- The built-in trust prompt passes `{ blockedKind: "permission" }`,
which applies at startup and in a session. Extensions can do the same,
for example for an approval select.
- First-time setup reports `permission`.
- The startup trust context (`cli/project-trust.ts`) passes
`blockedKind` on to `showStartupSelector` and `showStartupInput`, and
`showExtensionConfirm` passes `permission` as the default. This removes
the extra `blocked` parameter from `showExtensionSelector`.

No change:
- The missing session folder prompt (continue / fork / cancel) stays
`question`. It is a choice of how to go on, not an approval.
- RPC mode doesn't send program status, so it ignores the option.

## Tests

- `test/startup-ui-program-status.test.ts`: the built-in trust prompt
(through `resolveProjectTrusted`), an extension trust select with
`blockedKind`, and first-time setup.
- `test/interactive-mode-extension-dialogs.test.ts`: an in-session
select with `blockedKind`.

`npm run check` passes for this change. Its only errors are in
`packages/ai/test/*` and come from locally generated model data.
2026-11-24 21:01:54 +01:00
Vegard Stikbakke
fe1c08109d docs(coding-agent): document classifier responseId in codemode 2026-11-24 14:59:33 +01:00
Petr Houška
943a99e3c2
fix(coding-agent,tui): stop temp file write failures from crashing pi (#12452)
Fixes #10585.

## Problem

Bash output past the truncation limit is copied to a temp file in
`$TMPDIR`. The `WriteStream` had no `error` listener, so any open or
write failure became an uncaught exception and killed pi, including the
in-flight turn, subagents and background jobs. Triggers seen in
practice: a full tmpfs `/tmp` (ENOSPC), per-user tmpfs quotas that
systemd sets on `/tmp` (EDQUOT, errno 122), an unwritable `TMPDIR`
(EACCES). Both paths were affected: the agent `bash` tool
(`OutputAccumulator`) and `!` commands (`executeBashWithOperations`).

Only adding a listener is not enough: `end()` on a stream that already
errored never emits `finish` or `error`, so `closeTempFile()` would hang
instead.

## Change

- `createOutputFileStream` returns an `OutputFileStream` wrapper: error
handling from the start, writes ignored after a failure, a partially
written file removed (never a file that was already at the path), and
`close()` that never rejects or hangs and returns `{ kind: "saved", path
} | { kind: "failed", error }`.
- Bash tool: the temp file is closed before the final result is built.
On failure the result keeps the in-memory tail and ends with `[Showing
lines X-Y of N. Could not save the full output: ENOSPC ...]`, without
`fullOutputPath` / `full_output_path`. `readFullOutput()` (structured
output for codemode) falls back to the tail. This matches what codemode
already does for its own output files.
- `!` commands: the executor waits for the file to flush before
returning its path. On failure it returns the tail without a path.
- Other crashes from temp dir failures: opening the external editor
(Ctrl+G) and `/share` now report the error instead of throwing from
key/submit handlers. The TUI width crash keeps its error and restores
the terminal when its debug log cannot be written.

Durable's bash spill handling (kills the command when the spill file
fails) is unchanged; aligning it is left for a separate PR.

## Tests

`test/output-file-failures.test.ts` covers failed open (missing
`TMPDIR`), failed writes (ENOSPC, injected), and `EEXIST` for the
stream, the bash tool and the `!` executor. New cases in
`external-editor.test.ts`, `session-share.test.ts` and
`tui-render.test.ts`.
2026-11-24 00:09:07 +01:00
Petr Houška
7135638709
houskape@gmail.com
Follow-up to #12164 / #12454.

## Problems

1. `/login` cannot tell a broken stored key from no key. After #12454, a
stored `!command` key whose command fails shows as `• not configured`,
while `/logout` lists the credential. Users may think the key was lost.
2. A failed command stays failed until pi restarts. Command results,
failures included, are cached for the process. Example: the `op` session
expires, pi starts, the key fails. The user runs `op signin` and enters
the same `!op read ...` key in `/login`. The cache returns the old
failure, so the provider stays unconfigured.

## Changes

**API.** For a stored credential that does not resolve,
`ModelRuntime.getProviderAuthStatus()` (and
`ModelRegistry.getProviderAuthStatus()`) returns `{ configured: false,
source: "stored" }` instead of `{ configured: false }`. The `AuthStatus`
type does not change, and its doc comment now describes this case.
#12454 is unreleased, so the released contract moves directly from `{
configured: true, source: "stored" }` (wrong) to this.

**UX.** `/login` shows `DeepSeek • stored key did not resolve` in error
color, rather than `• not configured`. A login option's `status` is now
a tagged union, `AuthSelectorStatus`: `{ kind: "configured", type,
source? }` or `{ kind: "unresolved" }`, and unset when nothing is
configured. The old shape was pi-ai's `AuthCheck`, which only describes
auth that works. `AuthSelectorProvider` is internal: it is not exported
from the package.

**Cache.** `AuthStorage.modify()` now drops the cached result of a
`!command` key it has just written, and the following availability
refresh runs the command again. Commands do not run on any new path: an
extra run only happens after the user saves a key. Reads, requests and
refreshes still use the cache, so a failing command does not rerun (and
block for up to 10 s) on every lookup.

**Docs.** `docs/providers.md` explains the status and how to retry.

## Tests

- `auth-storage.test.ts`: a failing `!printenv` key stays cached after
the variable is set, and resolves after it is saved again.
- `oauth-selector.test.ts`: a `{ configured: false, source: "stored" }`
status renders as `stored key did not resolve`.
- The 12164 regression test now expects `source: "stored"`.
- These tests fail without the change. `npm run check` passes, and 430
coding-agent tests pass (regressions, model-registry, model-runtime,
auth-storage, oauth-selector, resolve-config-value, bug-report).
- Checked by hand in tmux: with an `auth.json` containing `!exit 1` for
DeepSeek and `!echo gsk` for Groq, `/login` shows `DeepSeek • stored key
did not resolve` and `Groq ✓ stored`.
2026-11-23 23:09:01 +01:00
robopipi[bot]
d91ac96a49
docs(coding-agent): clarify xhigh and max in thinkingLevelMap (#12435)
The `thinkingLevelMap` description in the models.json schema and in
`docs/models-configuration.md` ended with "xhigh and max are
unsupported". The sentence was about levels left out of the map, but it
read as if pi does not support those thinking levels at all.

The actual behavior, from `getSupportedThinkingLevels()` in
`packages/ai/src/models.ts`:
- A level mapped to `null` is hidden.
- `off` through `high` fall back to the provider default when left out
of the map.
- `xhigh` and `max` are offered only when the map gives them a value.

Changes:
- Reworded the description where it is defined, in
`packages/ai/src/providers/model-schema.ts`, to match the "opt-in"
wording already used in `packages/ai/README.md`. Then regenerated
`schemas/models.schema.json` and `docs/models-configuration.md`; the
text appears twice in each, for custom models and for `modelOverrides`.
- Added a short "Map thinking levels" section with an example to
`docs/models.md`. It explains `null`, the default for `off` through
`high`, opt-in `xhigh`/`max`, and that the map goes in `models.json` (a
custom model or a `modelOverrides` entry), not in `settings.json`.
- Added a changelog entry.

Testing: ran `npm run generate:schemas` and `npm run
generate:references`, then `test/references.test.ts` and
`test/config-schemas.test.ts` (16 passed). `npm run check` passes.

Fixes #12281

Requested by @davidbrai

Co-authored-by: triagent <triagent@localhost>
2026-11-23 14:45:09 +01:00
Petr Houška
fe8a6f5dc7
fix(ai): Gemini 3+ detection for prefixed Google model IDs, add compat.supportsStrictMode (#12371)
Closes #12321

Google adapters decided Gemini 3+ behavior from model IDs starting with
`gemini-N`. Gemini models served under prefixed IDs, such as
`randomprefix-gemini-4-argon`, were treated as older Gemini: no strict
tools (`strict: "prefer"` fell back, `strict: "require"` failed), no
tool-call IDs, and tool-result images in a separate user turn. The
thinking-level check (`usesGoogleThinkingLevel`) already matched
`gemini-N` anywhere in the ID, so the same model got Gemini 3+ thinking
but pre-3 tool handling.

Two changes:

1. `getGeminiMajorVersion` matches `gemini-N` anywhere in the ID, like
`usesGoogleThinkingLevel`. Prefixed Gemini 3+ IDs get strict tools,
tool-call IDs, and multimodal function responses without configuration.
No built-in catalog model changes behavior (all built-in Google IDs
start with `gemini-`).
2. `compat.supportsStrictMode` for the `google-generative-ai` and
`google-vertex` APIs, following the OpenAI, Mistral, and Bedrock
adapters, for IDs that carry no version at all. When set, it decides;
when unset, the ID detection applies (as in `openai-completions`).

```json
"compat": { "supportsStrictMode": true }
```

- `google-shared.ts`: unanchored version match;
`supportsGoogleStrictToolSampling(model)` reads the override
- `compat-schema.ts`: `GoogleCompatSchema`, registered for both Google
APIs and in the provider-level schema
- `types.ts`: `Model<"google-generative-ai" | "google-vertex">` gets
`compat: GoogleCompat`
- Tests: prefixed IDs for strict mode, tool-call IDs, and image routing;
the override both ways; request payloads of both adapters
- README, regenerated `models-configuration.md`, changelogs
2026-11-20 22:00:39 +01:00
David Brailovsky
b82477b7bb
fix(ai,coding-agent): make system the default instruction role in openai-completions (#12134)
TLDR:
On chat-completions api, change the default instruction role from
developer to system.

Inspired by: #12101 by @qoli

---
The trigger was #10741: Groq's qwen/qwen3.8-27b failed on the first
message:
`400: minijinja: rendering failed: raise_exception: Unexpected message
role.`

Problem: openai-completions sent the system messages of every reasoning
model with the `developer` role unless the catalog turned it off.
`developer` is OpenAI's role; many other hosts' chat templates reject
it, as Groq's Qwen template does.

Every new OpenAI-compatible provider or reasoning model hit the same bug
until someone added `supportsDeveloperRole: false` to the catalog; about
20 provider files carried that line. Nothing in models.dev says which
role a model accepts, so the catalog could not get this right on its
own.

Solution: detectCompat() now defaults supportsDeveloperRole to true only
for api.openai.com. Every other host gets `system`. This applies to the
initial system prompt and to mid-conversation system messages.

Built-in models whose role changes from developer to system:
- groq: 5 (gpt-oss and Qwen)
- xiaomi, xiaomi-token-plan-*: 9 MiMo models
- openrouter: 89 openai/* and anthropic/* models; 12 of them (newer GPT
models) also support mid-conversation system messages
(supportsMidConvoSystemMessages), which change role too All other
built-in Chat Completions models already sent `system`.

Why the default is only api.openai.com:
- api.openai.com keeps `developer` because OpenAI documents it as the
role for its reasoning models. In practice this rarely matters: the
built-in OpenAI models all use the Responses API, so it only affects
custom models that call OpenAI through openai-completions.
- Azure is excluded. Its built-in OpenAI models also use the Responses
API; its only built-in Chat Completions model is DeepSeek, which needs
`system`.
- OpenRouter is excluded: its Chat Completions reference accepts
`system` ("System message for setting behavior") and `developer` with
the same fields, and gives no reason to prefer `developer` for any model
(https://openrouter.ai/docs/api/api-reference/chat/create-a-chat-completion).
The openai/* and anthropic/* exception came in with #5309 without a
reported need.
- compat.supportsDeveloperRole still overrides the default.
- The Responses API has its own setting and is unchanged.

The now-redundant `supportsDeveloperRole: false` lines are removed from
the catalog and the llama extension.

How we checked it is safe: live requests to the affected hosts, each
model given the same instruction once as `developer` and once as
`system`:
- Groq qwen/qwen3.8-27b: developer 400, system OK. Groq gpt-oss-20b:
both OK.
- Xiaomi mimo-v2.6-pro and mimo-v2.6-flash: both roles OK.
- OpenRouter openai/gpt-5-mini, openai/gpt-oss-20b,
anthropic/claude-haiku-4.5, moonshotai/kimi-k2.6, qwen/qwen3.6-plus,
deepseek/deepseek-v4-pro: both roles OK.
- OpenRouter openai/gpt-5.4-mini and openai/gpt-5.5 with an instruction
added mid-conversation: both roles OK.

Released clients: they fetch new catalogs from pi.dev and still default
supportsDeveloperRole to true, so the removed `false` lines would make
them send `developer` to hosts that reject it. MINIMUM_PI_VERSION is
raised to 1.5.3 so they keep the last catalog published for them.

closes #10741 #12101
2026-11-20 09:32:28 +01:00
Armin Ronacher
fcc33744b0 fix(ai,coding-agent): keep Codex prompt cache across thinking level changes
Send thinking level changes on GPT-6 Codex models as configuration_update
input items with a fixed reasoning.effort, as the openai provider and
Codex do, so a change no longer invalidates the prompt cache. Off is sent
as effort none so switching to it is covered too.

Also forward maxTokens as max_output_tokens on the Codex provider, which
was silently dropped, honoring compat.supportsMaxOutputTokens.

closes #12269
2026-11-20 07:49:26 +01:00
Petr Houška
b7bb7ca905
fix(tui,coding-agent): make fullscreen scroll frames O(viewport) (#11968)
Refs #9549 (fullscreen scroll part; regular-mode resize and the
regular-mode spinner cost remain open)

## Problem

In fullscreen mode pi draws scrolling itself. Every wheel event (up to
60 frames/s) rebuilt the whole transcript:

1. `renderLayoutFrame` started each frame with an empty cache, so the
whole transcript document was rendered.
2. `Container.render()` copied every line of every child into a new
array, once per nesting level (~5 levels in the transcript). `Box` then
compared all child lines one by one.
3. Only after that did the layout cut out the ~40 visible rows.

In regular mode the terminal scrolls its own scrollback, so pi does no
work. That is why switching `tuiMode` removes the cost, and why it shows
strongly on Windows Terminal with few cores. The cause itself is
platform-independent.

Measured with the real transcript components on real sessions:

| Transcript | Scroll frame, full render | Scroll frame, view-only |
Frame where content changed |
|---|---|---|---|
| 26k lines | 4.2 ms | 1.0 ms | 3.0 ms |
| 104k lines | 15.3 ms | 1.1 ms | 12.8 ms |

Measured after rebasing on main. Before container caching, content
frames at 60k lines took ~10.5 ms; with it, ~6 ms.

## Changes

- **View-only frames** (`tui.ts`, `layout.ts`, `tui-alt-screen.ts`):
wheel, page/line keys, top/bottom, prompt jumps, scrollbar drag and
selection auto-scroll call `requestViewRender()`, which reuses the
previous frame's component output. `requestRender()`, input to the
focused component, resize and focus changes still render everything.
- **Containers keep their output** (`tui.ts`, `box.ts`): `Container` and
`Box` share `renderChildLines()`, which returns the previous array when
children and their lines are unchanged, so ancestors skip their copy
too.
- **Faster column slicing** (`utils.ts`): `sliceWithWidth` and
`getGraphemeCellRange` skip `Intl.Segmenter` for runs of characters that
always form their own grapheme (ASCII, Latin, punctuation, arrows, box
drawing, CJK, kana, fullwidth forms). Only stretches around marks,
joiners, variation selectors and astral characters are segmented.
Single-character widths are cached. Verified against the previous
implementation on 30k random strings (0 differences). This was 88% of a
scroll frame after the other fixes, because the scrollbar slices every
visible row.
- **`Component.render()` returns `readonly string[]`**: `Container`,
`Box`, `Text`, `Markdown`, `Image`, `MouseRegion`, `ScrollView`,
`SettingsList` declare it; components that build a new array (`Editor`,
`Input`, `SelectList`, ...) keep `string[]`.
`AssistantMessageComponent`, `UserMessageComponent` and the radius login
selector modified `Container` output in place (OSC 133 markers would
accumulate every frame); they now copy.
- Docs (`packages/tui/README.md`, `packages/coding-agent/docs/tui.md`)
now state that render output is read-only. Neither said anything about
it before.

## Breaking change

Code that modifies render output in place, including `super.render()` in
a `Container` subclass or another component's output, must copy first. A
scan of the 300 most-downloaded `pi-package` npm packages found one real
break: `@xynogen/pix-runtime` splices tab rows into an embedded panel's
output every frame, which now grows if the panel is a `Container`.
`gentle-pi` pads `Container` output in place, which stays harmless.
`Text`, `Markdown`, `Box` and `Image` already returned cached arrays, so
the rule existed by implication; `Container` was the exception.

## Known limits

- A component that changes state without calling `requestRender()` now
stays stale while scrolling, instead of being refreshed by the scroll.
It was already stale without scrolling.
- Selection drag without scrolling still renders everything; it could
use view-only frames too.
- Regular-mode resize (scrollback rewrite) and the regular-mode spinner
(`applyLineResets` over the whole transcript) are not addressed.
- Not tested interactively in a real terminal yet.

## Tests

- `packages/tui/test/container.test.ts`: output reuse, invalidation on
change, mouse dispatch by child heights.
- `packages/tui/test/tui-alt-screen.test.ts`: wheel and keyboard
scrolling do not re-render components until content changes.
- `packages/tui/test/slice-graphemes.test.ts`: slicing across standalone
characters and clusters.
- `assistant-message.test.ts`, `user-message.test.ts`: OSC 133 markers
are added once across repeated renders.
- Build passes; root and examples `tsc`, browser smoke and biome pass.
`npm run check` stops early on this machine at the install-lock step
(unrelated; this PR changes no dependencies), so those steps were run
directly.
- tui tests pass except two pre-existing Windows path failures in
`terminal-image.test.ts`; 19 related coding-agent test files pass.
2026-11-16 23:24:25 +01:00
David Brailovsky
2145e3f609 docs(coding-agent): regenerate models configuration reference 2026-11-16 10:39:15 +01:00
Gangqiang Yao
ede360e4d6
fix(coding-agent): /copy skips turns that ended without an answer (#12121)
Closes #12119.

**Problem.** `getLastAssistantText()` takes the last assistant message,
skipping only aborted messages with no content (#351). Two common cases
leave a last assistant message without text:

- After Esc during a tool call, the last messages are a tool-call-only
message and an empty one.
- After a provider error, the last message is an empty error message.

So `/copy` says "No agent messages to copy yet." while the previous
answer is on screen. RPC `get_last_assistant_text` returns `null` in the
same cases.

**Fix.** Skip assistant messages without text whose turn did not end
normally (`stopReason` other than `stop`: aborted, error, toolUse,
length). This generalizes the existing aborted-and-empty check, in the
same function.

A reply that ended normally stays the last reply, even without text.
That keeps `/copy` from silently copying an older answer, and keeps the
evals harness unchanged: it relies on an empty final reply giving no
text to report "Agent run produced no assistant text."

The RPC doc for `get_last_assistant_text` notes the skipped messages.

**Validation** on main `d36266e066`:

- New `test/suite/regressions/12119-copy-after-abort-or-error.test.ts`,
using the faux provider:
  - Esc during a tool call returns the previous answer.
  - A provider error returns the previous answer.
  - A normal reply without text still returns `undefined`.
- The first two fail without the fix. The third passes before and after.
- These pass: `interactive-tui.test.ts`, `rpc.test.ts`, the 8409 abort
regression, and `packages/evals` `harness.test.ts`.
- `npm run check` passes. In `./test.sh` the only failures are unrelated
to this change:
- The find tool tests fail because fd is not installed here, and the
test config sets `PI_OFFLINE=1`, which prevents downloading it.
  - The pi-env tests need cargo, which is not installed here.
  - One `auth-storage` test also fails on main.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:37:46 +01:00
Petr Houška
1397070024
fix(ai): move Qwen Token Plan to current gateways and model lists (#12112)
Closes #11773. Also covers the remaining model-list problems from #7491
and #7674.

## Changes

- **Gateways.** All four Qwen Token Plan providers default to the
current hosts:
- international:
`https://token-plan.maas.qwencloudapi.com/compatible-mode/v1`
([QwenCloud
regions](https://docs.qwencloud.com/developer-guides/getting-started/regions))
- China: `https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1`
([Qianwen AI
Platform](https://platform.qianwenai.com/docs/developer-guides/clients-and-developer-tools/other-tools))

Provider IDs are unchanged. In DNS, each new host is a CNAME to the same
load balancer as its old
`token-plan.{ap-southeast-1,cn-beijing}.maas.aliyuncs.com` host. All
four hosts return the same `invalid_api_key` response to a fake key, so
`models.json` overrides that still name the old hosts keep working.
- **Individual (Personal) allowlist.** Adds `deepseek-v4.1-flash` and
`deepseek-v4.1-flash-1017`, which are on the current Personal lists for
both regions
([QwenCloud](https://docs.qwencloud.com/token-plan/personal/token-plan-personal-overview),
[China](https://help.aliyun.com/zh/model-studio/token-plan-personal-overview)).
- **Retired models.** The Token Plan catalogs now use `skipDeprecated:
true` in place of the hardcoded `qwen3.8-max-preview` exclusion.
models.dev marks `qwen3.8-max-preview`, `deepseek-v3.2` and
`deepseek-v4-flash` deprecated, and none of them is on the current Token
Plan lists. `qwen-token-plan` and `qwen-token-plan-cn` now match the 19
text models of the Team lists
([QwenCloud](https://docs.qwencloud.com/token-plan/team/token-plan-team-overview),
[China](https://help.aliyun.com/zh/model-studio/token-plan-team-overview)).
The Individual providers match the 12 Personal models. The dynamic
`auto` router is left out because it has no fixed model metadata.
- **Key variables.** New per-plan variables
`QWEN_TOKEN_PLAN_TEAM_API_KEY`, `QWEN_TOKEN_PLAN_TEAM_CN_API_KEY`,
`QWEN_TOKEN_PLAN_INDIVIDUAL_API_KEY` and
`QWEN_TOKEN_PLAN_INDIVIDUAL_CN_API_KEY`. Setting one configures only
that plan's provider, so Individual subscribers no longer see Team-only
models that fail with `AccessDenied.Unpurchased`. The shared
`QWEN_TOKEN_PLAN_API_KEY` and `QWEN_TOKEN_PLAN_CN_API_KEY` still work as
a fallback for both plans. Docs list only the new variables.
- **Names.** `qwen-token-plan` and `qwen-token-plan-cn` are now named
"Qwen Token Plan Team" and "Qwen Token Plan Team CN", since their
catalogs are the Team lists. IDs are unchanged.

## Not included

- No new edition IDs: the existing `*-individual*` providers already
separate Personal from Team.
- No `/models` discovery (#7674): it needs a subscription key to verify
that the list is filtered by plan.
- No live calls with a real subscription key.

## Testing

- `npm run generate-models`: 19 models for each Team provider, 12 for
each Individual provider
- `test/qwen-token-plan-models.test.ts`,
`test/generate-models-strict.test.ts`,
`test/openai-completions-tool-choice.test.ts`,
`test/model-data-validation.test.ts`
2026-11-12 23:47:12 +01:00
Gangqiang Yao
a83b75a07e
fix(coding-agent): report signal-terminated pi.exec commands as failed (#12089)
Closes #12088.

**Problem.** `pi.exec` mapped a missing exit code to 0 (`code ?? 0`).
Node reports no exit code for a process ended by a signal, so these
commands read as success:

- A timeout or an abort returns `code: 0` and `killed: true`.
- A crash (SIGSEGV) or an outside kill such as the OOM killer returns
`code: 0` and `killed: false`. That is indistinguishable from success.

An extension that checks `result.code === 0` treats these as passed. The
bundled `inline-bash.ts` example is one: it checks `code !== 0`.

**Fix.** Report 128 + the signal number, as a shell does: 143 for
SIGTERM and 137 for SIGKILL. This is the same expression the bash tool
uses (`bash.ts`), and #8994 made the same change in `NodeExecutionEnv`.
If there is neither a code nor a signal, `code` is 1.

Unchanged:

- Normal exit codes.
- `killed` and `truncated`.
- A truncated result is still never 0.

The docs for `pi.exec` and the `ExecResult.code` comment now describe
the signal case.

**Validation** on main `ad335fec19`:

- Three new tests in `test/exec.test.ts` cover a timeout (143), an abort
(143) and a command killing itself with SIGKILL (137, `killed: false`).
All three fail without the fix. They are skipped on Windows, like the
existing signal tests.
- `exec.test.ts`, `exec-utf8-chunks.test.ts` and
`exec-runtime-limit.test.ts` pass.
- `npm run check` passes. In `./test.sh` the only failures are unrelated
to this change:
  - The find tests fail because the sandbox cannot download fd.
  - The pi-env tests need cargo, which the sandbox does not have.
  - One `auth-storage` test also fails on main.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:14:36 +01:00
Julien Chaumond
74dcca7d41
use llama serve in the NVIDIA RTX guide (#12004)
Replace `llama-server` examples with `llama serve` and use its default
port `9931`, matching the main llama.cpp guide

disclaimer: my julien-cto agent helped me write this

Co-authored-by: David Brailovsky <davidbrai@gmail.com>
2026-11-11 10:36:43 +01:00
Julien Chaumond
b3c2e4a6be
fix llama.cpp default port (#12001)
use port 9931 for the llama.cpp provider default and update the examples
to match the current server default

`npm run check` and all 31 llama.cpp tests pass

disclaimer: my julien-cto agent helped me write this
2026-11-11 10:31:23 +01:00
David Brailovsky
49fe0a2374 fix(ai): default Anthropic message threads by endpoint, not provider id
Any provider with a baseUrl on api.anthropic.com now uses message threads by default.

closes #11987
2026-11-11 09:52:41 +01:00
Julien Chaumond
ffd3329bba
docs(coding-agent): use the unified llama entry point (#11958)
use `llama --version` to verify the installation

we're promoting `llama` as the simpler unified entry point for llama.cpp

disclaimer: my julien-cto agent helped me write this
2026-11-10 11:11:07 +01:00
Petr Houška
4ea8837927
fix(coding-agent): offer fork when a session cwd no longer exists (#11975)
Some checks are pending
CI / build-check (push) Waiting to run
CI / test (coding-agent) (push) Waiting to run
CI / test (durable) (push) Waiting to run
CI / test (other) (push) Waiting to run
CI / mcp-conformance (push) Waiting to run
Environments / daemons (push) Waiting to run
Environments / check (push) Blocked by required conditions
Environments / release-daemons (darwin-arm64, macos-latest) (push) Blocked by required conditions
Environments / release-daemons (darwin-x64, macos-latest) (push) Blocked by required conditions
Environments / release-daemons (linux-arm64, ubuntu-24.04-arm) (push) Blocked by required conditions
Environments / release-daemons (linux-x64, ubuntu-latest) (push) Blocked by required conditions
Environments / release-daemons (windows-arm64, windows-11-arm) (push) Blocked by required conditions
Environments / release-daemons (windows-x64, windows-latest) (push) Blocked by required conditions
Environments / tests (macos-latest) (push) Waiting to run
Environments / tests (ubuntu-24.04-arm) (push) Waiting to run
Environments / tests (ubuntu-latest) (push) Waiting to run
Environments / tests (windows-11-arm) (push) Waiting to run
Environments / tests (windows-latest) (push) Waiting to run
Closes #11060.

## Problem

A session stores the working directory (cwd) it was created in. If that
directory no longer exists, for example after the project folder was
renamed, interactive mode offered only to continue in the current
directory. That choice is kept in memory only, so every later resume of
the session asked again.

```
~/proj  (session X created)   ->  mv ~/proj ~/proj2
~/proj2$ pi --session <X.jsonl>   -> "continue in current cwd"  -> works
~/proj2$ pi --session <X.jsonl>   -> asks again, every time
```

## Solution

The missing-cwd prompt now offers three choices everywhere it appears:

- **Continue**: unchanged behavior. Runs the session in the current cwd,
not stored, asks again next time.
- **Fork**: copies the session into the current cwd as a new session
with a new ID and `parentSession` pointing at the original, like `pi
--fork` and like `pi --session <id>` already does for sessions from
another project. The original file is not modified. The copy has the
current cwd in its header, so resuming it does not ask again.
- **Cancel**: unchanged.

The session file is never rewritten. `docs/sessions.md` states that a
session records its cwd and never changes it; Fork keeps that rule.

Also fixes a bug on `main`: `/import` of a session whose cwd is missing
copied the file into the session directory before the cwd check, so
every such import left a stray copy, and Continue then created a second
copy with the same ID.

## Behavior changes

Example used below: session X was created in `~/proj` (file
`sessions/--home-me-proj--/X.jsonl`, header `cwd: ~/proj`). `~/proj` was
renamed to `~/proj2`; pi runs from `~/proj2`.

### Strings (verbatim)

| Where | Before | After |
|---|---|---|
| Prompt text, startup | `cwd from session file does not
exist`<br>`~/proj`<br><br>`continue in current cwd`<br>`~/proj2` |
`Session cwd does not exist: ~/proj` |
| Prompt text, TUI (`/resume`, `/import`, `ctx.switchSession`) |
`Session cwd not found`<br>`cwd from session file does not
exist`<br>`~/proj`<br><br>`continue in current cwd`<br>`~/proj2` |
`Session cwd does not exist: ~/proj` |
| Options, startup | `Continue`, `Cancel` | `Continue in ~/proj2 (asks
again next time)`, `Fork into ~/proj2 (new session ID, original kept)`,
`Cancel` |
| Options, TUI | `Yes`, `No` | `Continue in ~/proj2 (asks again next
time)`, `Fork into ~/proj2 (new session ID, original kept)`, `Cancel` |
| Status after `/resume` Continue | `Resumed session in current cwd` |
`Resumed session in ~/proj2` |
| Status after `/resume` or `/import` Fork | n/a | `Forked into new
session <id> in ~/proj2` |
| Status after `/resume` Cancel | `Resume cancelled` | `Resume
cancelled` (unchanged) |
| Status after `/import` Continue | `Session imported from: <path>` |
`Session imported from: <path>` (unchanged) |
| Status after `/import` Cancel | `Import cancelled` | `Import
cancelled` (unchanged) |
| Blocked program status (OSC 7501) while the TUI prompt is open | kind
`permission`, message `Session cwd not found` | kind `question`, message
`Session cwd does not exist: ~/proj` |
| Non-interactive error | `Stored session working directory does not
exist: ~/proj`<br>`Session file: <path>`<br>`Current working directory:
~/proj2` | unchanged |

### Invocations (startup), stored cwd missing

| Command | Before | After |
|---|---|---|
| `pi --session <path to X>` | Continue: runs X in `~/proj2`, header
unchanged, asks again next launch. Cancel: exit 0 | Continue: same as
before. Fork: writes copy Y (new ID, `cwd: ~/proj2`, `parentSession: <X
path>`) to `--session-dir` / `PI_CODING_AGENT_SESSION_DIR` /
`sessionDir` setting, else the default session directory for `~/proj2`,
and opens Y; X unchanged. Cancel: exit 0 |
| `pi --resume`, picking X | Same as `--session <path>` | Same as
`--session <path>` |
| `pi --session-id X` or `pi --session X` matching a file in this
folder's session directory whose header cwd is missing (after `/import`
or a manual move) | Same as `--session <path>` (Continue keeps ID X) |
Same as `--session <path>` (Continue keeps ID X, Fork gives a new ID) |
| `pi -p ...`, `pi --mode rpc ...` | Error, exit 1 | Unchanged |

### Invocations (startup), stored cwd exists or other cases (all
unchanged)

| Command | Behavior |
|---|---|
| `pi --session <path>` / `--resume` for a session whose cwd exists |
Opens it in its stored cwd, no prompt |
| `pi --session X` (ID) when X is only in another project's session
directory | `Session found in different project: ~/proj` / `Fork this
session into current directory? [y/N]`; the missing-cwd prompt is not
reached |
| `pi --fork X` | Forks without a prompt |
| `pi -c` | Runs the most recent session of this folder in the launch
cwd; header cwd not checked |

### TUI, stored cwd missing

| Action | Before | After |
|---|---|---|
| `/resume` -> pick X, Continue (old: Yes) | Switch to X in `~/proj2`,
not stored | Same |
| `/resume` -> pick X, Fork | n/a | Copy Y saved in the current
session's directory (like `/new`), switch to Y. X unchanged |
| `/resume` -> pick X, Cancel (old: No) | `Resume cancelled` | Same |
| `/import <file>`, Continue (old: Yes) | Switch to the imported copy in
`~/proj2`, not stored. Bug: two copies with the same ID (`s.jsonl`,
`s-1.jsonl`) | Same, exactly one copy `s.jsonl` |
| `/import <file>`, Fork | n/a | Like `pi --fork <file>`: one copy with
a new ID in the current session's directory, switch to it |
| `/import <file>`, Cancel (old: No) | `Import cancelled`, but `s.jsonl`
already copied (bug) | `Import cancelled`, no copy left |
| `/fork`, `/clone` after Continue | Clone or later-message fork runs in
the missing `~/proj` | Unchanged (known limitation, not addressed here)
|
| `/fork`, `/clone` after Fork | n/a | Stay in `~/proj2` (the copy's
header has `~/proj2`) |

### TUI, stored cwd exists (all unchanged)

| Action | Behavior |
|---|---|
| `/resume` -> pick a session from `~/other` | No prompt; pi switches
into `~/other` |
| `/import` of a file whose cwd `~/other` exists | No prompt; copied
next to the current session, runs in `~/other` |

### Extensions

| Case | Before | After |
|---|---|---|
| `ctx.switchSession(X)` in interactive mode, cwd missing | Yes/No
prompt; Yes switches to X in the current cwd | Three-option prompt.
Continue: switches to X, `withSession` gets X. Fork: switches to copy Y,
`withSession` gets Y. Cancel: `{ cancelled: true }` |
| `ctx.switchSession(X)` in print / RPC mode, cwd missing | Throws
`MissingSessionCwdError` | Unchanged |
| Events on Continue | `session_before_switch` (`resume`, target X)
before the prompt, `session_before_switch` (`resume`, target X) on
retry, `session_shutdown`, `session_start` (`resume`) | Unchanged |
| Events on Fork | n/a | `session_before_switch` (`resume`, target X)
before the prompt, `session_before_switch` (`resume`, target Y),
`session_shutdown` (`resume`, target Y), `session_start` (`resume`).
Reported as a resume, as `/import` reports its copy. No
`session_before_fork` |
| Extension cancels `session_before_switch` for Y | n/a | Y is deleted,
`{ cancelled: true }` |
| Events on `/import` with cwd missing | First `session_before_switch`
target `s.jsonl`, retry target `s-1.jsonl` (stray-copy bug) | Both
target `s.jsonl` |

### SDK / API

No public API changes. `AgentSessionRuntime.switchSession({ cwdOverride
})` and `importFromJsonl(path, cwdOverride)` are unchanged;
`importFromJsonl` no longer leaves a copy behind when it throws
`MissingSessionCwdError`.

## Docs

`docs/sessions.md`: the paragraph "Pi does not store that choice, so it
asks again the next time you open the session" is replaced by a
description of Continue, Fork, and Cancel, including where the fork is
stored (startup: like other new sessions for the current directory;
`/resume` and `/import`: next to the current session, like `/new`).

## Tests

- `test/interactive-mode-resume-missing-cwd.test.ts` (new): `/resume`
with Fork (copy location, header, original unchanged, status), Continue
(no file written), extension veto (copy removed), Cancel.
- `test/suite/agent-session-runtime.test.ts`: import with a missing cwd
leaves no copy, and the retry with a cwd override produces no `-1` file.
- Manually checked in tmux: startup Continue and Fork, `/resume`
Continue and Fork, `/import` Fork.
2026-11-10 00:16:08 +01:00
Vegard Stikbakke
7bcc15c92a feat(coding-agent): default cacheWarming to idle
Also keep eligible prompt caches warm for up to 30 minutes between agent runs. Refreshes are still only sent when expected to pay for themselves.
2026-11-09 14:50:41 +01:00
Petr Houška
7a6bd5a97c
fix(ai): omit empty tools array for tool history on openai-completions (#11891)
## Problem

`openai-completions` sends `"tools": []` whenever a request has no tools
but the transcript contains tool calls or tool results. vLLM 0.20+
rejects this
([vllm#39780](https://github.com/vllm-project/vllm/pull/39780)),
directly or behind LiteLLM:

```
400: `tools` must not be an empty array. Either provide at least one tool or omit the field entirely.
```

Trace: session uses tools -> all tools disabled (or SDK call without
tools) -> next request has `tools: []` -> 400 on every request. There
was no way to opt out.

The empty array came from #150 (2024), a workaround for LiteLLM raising
`Anthropic doesn't support tool calling without tools= param specified`.
Current LiteLLM adds a dummy tool itself for Anthropic in that case
(`litellm/llms/anthropic/chat/transformation.py`).

The OpenAI spec defines `tools` as an optional array, so omitting it is
valid. vLLM issue #39741 reports that OpenAI also rejects `tools: []`
with `empty_array`; not verified here.

## Change

- Omit `tools` by default when there are no tools.
- New `compat.requiresToolsWithToolHistory` (default `false`) restores
`"tools": []` for proxies that need it, such as older LiteLLM versions
in front of Anthropic.
- Regenerated `models.schema.json` and `models-configuration.md`.
- Tests: default omits the field (#11843), the compat flag sends `[]`.

## Risk

Setups that relied on the implicit `[]`: older LiteLLM with Anthropic,
and possibly OpenRouter Claude models (the only built-in Claude models
on `openai-completions`). Not verified against OpenRouter; those users
can set the flag.

Fixes #11843
2026-11-06 20:47:02 +01:00
robopipi[bot]
96667f342a
fix(coding-agent): keep apostrophes in prompt template arguments (#11873)
`parseCommandArgs` started a quoted section at every `'` or `"`, even in
the middle of a word, and dropped the quote character. As a result,
`/ask why doesn't the user's cache work` reached the model as `why
doesnt the users cache work`. With a single apostrophe, everything after
it became one argument, so `$1`/`$2` were wrong. Backslash-escaped
quotes were not supported either: `"quoted \"text\""` gave `quoted
\text\`.

What the change does:
- A quote only opens a quoted argument at the start of an argument.
Apostrophes inside words such as `doesn't` and `user's` stay as text.
- If a quote has no closing match, the parser goes back to the quote,
keeps it as text, and parses the rest of the input normally. For
example, `'tis the season` gives `'tis`, `the`, `season`.
- Inside a quoted argument, a backslash before that argument's quote
character gives a literal quote: `"quoted \"text\""` gives `quoted
"text"`, and `'it\'s here'` gives `it's here`. All other backslashes are
kept as typed, so paths such as `"C:\dir\file"` and `'\\server\share'`
don't change.
- `"..."`, `'...'`, `""` and `''` arguments behave as before.

One edge case: a quoted argument that ends in a backslash, such as
`"C:\dir\"`, now reads the final `\"` as an escaped quote. The quote
then never closes, so the whole argument is kept literally, quotes
included.

The prompt templates doc and the changelog describe the new behavior.

Testing:
- Added tests in `packages/coding-agent/test/prompt-templates.test.ts`
for apostrophes inside words, quotes with no closing match, and escaped
quotes (including paths that keep their backslashes). The existing
escaped-quote test now expects `quoted "text"`. All 96 tests in the file
pass.
- `npm run check` passes.
- Before: `parseCommandArgs("why doesn't the user's cache work")` →
`["why","doesnt the users","cache","work"]`. After:
`["why","doesn't","the","user's","cache","work"]`.

Fixes #11861

Requested by @davidbrai

---------

Co-authored-by: triagent <triagent@localhost>
2026-11-06 10:24:17 +01:00