Skip to content

[feat] agent: add pi coding agent runtime - #461

Open
Zhangbo-cn wants to merge 6 commits into
ThinkFlowLab:mainfrom
Zhangbo-cn:feat/438-pi-runtime
Open

Zhangbo-cn wants to merge 6 commits into
ThinkFlowLab:mainfrom
Zhangbo-cn:feat/438-pi-runtime

Conversation

@Zhangbo-cn

Copy link
Copy Markdown
Contributor

Summary

  • Adds pi (@earendil-works/pi-coding-agent) as an external harness next to OpenCode, Codex, Claude Code, JiuwenSwarm and DeepSeek: one pi --mode json --print process per turn, reusing the existing terminate, stderr, trace and cancel handling.
  • Uses the user's own ~/.pi providers, sign-in, extensions and MCP servers (modelSource: cli); OpenDirector credentials are not injected.
  • Display text comes from message_update deltas, but message_end is authoritative: a retried attempt does not end the turn, and only an error on the final agent_end assistant message fails it. pi exits 0 for model errors, so the exit code alone cannot decide the outcome.
  • --approve is passed because print/json modes otherwise skip the project skills and .pi settings silently; --tools read,bash,write,edit keeps project content changes on the opendirector CLI.
  • Continuation reuses the turn workspace via --session-id, with sessions kept in agent-runs/pi-sessions/native so global session history is untouched and a missing directory degrades to a full replay.
  • Readiness is --version → --list-models → pi auth check --json, keeping "catalog unreadable" and "no models configured" distinguishable.
  • Adds the picker entry, a local monochrome logo, and the bilingual setup hint; runtime identifiers are carried through the API contract, docs and tests.

Known limitation: pi's message protocol accepts text and images only, so video and audio observation still depends on the pending project media commands. The visual gate is unchanged for that reason.

Linked issue

  • Fixes #N or Refs #N is included, or no issue applies

Refs #438

Labels

  • Labels applied

Suggested: type:feature, area:agent, area:web (cannot apply from outside; please add on triage).

Test plan

  • Local:
    • python3 -m pytest tests/test_pi_runtime.py tests/test_runtime_readiness.py (34 passed) — fake CLI covers argv, session reuse, single-shot final text, --thinking, retried failure, settled model error with trace, model table parsing, seven readiness branches and a missing installation.
    • python3 -m pytest -m ready (207 passed) and the full suite on the same tree (2905 passed, 120 skipped).
    • npm test (957 passed), npx tsc --noEmit, npm run check:i18n (3317 keys, 0 problems), python3 scripts/generate_contracts.py (no diff).
    • Browser: tests/browser/provider_settings.mjs passes against the isolated fixture API, with Pi in the harness list; the picker row, 配置 Pi panel and pi auth login <provider> command were checked in both languages.
    • Real CLI: two API turns on runtime=pi returned complete; the second turn recalled content from the first under one session id, and the session file landed under agent-runs/pi-sessions/native/.
  • Left to CI: full suite, release visual gate, and macOS/Windows platform differences.

Evidence that it works

  • Media attached, or N/A because:

Pi row in the harness picker (zh-CN) and the setup panel are locally captured but not attached; say the word and I will add screenshots. Automation evidence is the passing provider_settings.mjs check plus the two-turn session recall above.

@FayeSpica

Copy link
Copy Markdown
Collaborator

@Zhangbo-cn ci is red, PTAL

@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

@FayeSpica CI is green now — thanks for the nudge. Two things were red.

CodeQL: 3 py/path-injection alerts. The third commit had already reduced the requested name to a base name and rejected links, so the alerts were not a missing check in the business path; CodeQL simply did not accept it as a containment barrier. os.path.abspath only moves a value to the "normalized, unchecked" state, and a Path.parents comparison is not the safe-access check the query looks for, so taint from the request parameter still reached FileResponse, is_file and is_symlink.

child() now checks the normalized string against the directory prefix and builds the returned Path inside that branch, so callers only ever receive a path that passed the check. Reproduced and re-verified with CodeQL 2.27.5 on the same source tree (python-code-scanning.qls, the suite this workflow uses):

before: py/path-injection  apps/api/src/opendirector_api/agent.py:333
       py/path-injection  apps/api/src/opendirector_api/agent.py:335
       py/path-injection  packages/core/src/opendirector/infrastructure/local_projects.py:23
after:  (none)

tests/test_local_json.py now covers the traversal, separator and symbolic-link rejections.

checks / static failed on README.zh-CN.md, a file this PR does not touch: #471 added a trailing space on line 33, and any branch behind main gets it flagged because the hook runs on the merge commit. Rebased onto main (aff774a8), which drops that file from the diff range.

Also opened #487 — the media observation commands (asset probe, frame extraction returning a written image path) that #438 promised as a prerequisite, so the pi adapter can observe media through the shared CLI instead of hand-written ffmpeg.

All checks pass at e8935dd1; mergeStateStatus is CLEAN.

Comment thread src/canvas/traceTurns.ts
const RUNTIME_NAMES: Record<string, string> = {
default: "OpenCode", opencode: "OpenCode", codex: "Codex", claude: "Claude Code",
jiuwenswarm: "JiuwenSwarm", deepseek: "DeepSeek Harness",
jiuwenswarm: "JiuwenSwarm", deepseek: "DeepSeek Harness", pi: "Pi",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In manual testing, the Trace page didn’t recognize many of Pi’s message_* events or group its tool_execution_* events into tool calls. Please normalize both so messages render with the correct roles and each tool call appears once with its name, status, and expandable result.

@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

Fixed both, in 864c44da on top of main@63279266 (rebased, force-pushed).

Roles. src/canvas/piTrace.ts is now the pi branch of normalizeTrace(). Each message_end becomes one row with its own role: user text, assistant text, and assistant thinking blocks as reasoning. The system prompt and toolResult messages are not echoed as conversation rows, and the lifecycle records that produce the noise in your screenshot (session, agent_start, turn_start, message_start, message_update, turn_end, agent_settled, queue and thinking-level events) are dropped. Deltas stay out of the list because they repeat the finished message; the text row appears when its message ends, which is what the Claude and Codex normalizers already do.

Tool calls. tool_execution_start / _update / _end collapse into one row per toolCallId, carrying the tool name, in_progress → completed / failed, the arguments, the result text and durationMs. A late update no longer overwrites a settled result, and an _end without a matching _start still shows rather than disappearing. The call is no longer reported a second time from the assistant message's toolCall blocks.

I kept pi's retry semantics instead of guessing at them: an attempt that ends with stopReason: 'error' contributes no text, and only the settled agent_end assistant message reports the turn's error — the same rule agent/pi.py applies, so the trace cannot show a failure the turn survived.

Validation:

  • node --test tests/piTrace.test.ts — 4 new tests: role text and one tool row with its result; parallel calls keeping separate identities plus a failed call; a retried attempt not failing the turn and only agent_end reporting the error; an orphan _end and unknown records kept, malformed lines dropped.
  • node --test tests/*.test.ts 982 passed, npx tsc --noEmit clean, check-i18n 3352 keys / 0 problems.
  • Real stream, not a fixture: pi --mode json --print --tools read against a scratch directory produced 22 records; the normalizer returns the user message and one read · completed row with {"path": "..."} and the file text, dropping the system message and the other twenty records.

Boundary worth stating: the Trace page has no browser test, so what I verified is the normalized rows from a real pi stream plus the unit fixtures, not a screenshot of the page. If a screen recording of the Trace page for a runtime=pi turn would settle it for you, say so and I will record one against the isolated fixture stack.

@FayeSpica

Copy link
Copy Markdown
Collaborator

@Zhangbo-cn seems need resolve conflicts

dev added 6 commits November 25, 2026 17:12
- Run pi as an external harness: one `pi --mode json --print` process per
  turn over its JSONL event stream, reusing the existing terminate,
  stderr, trace and cancel handling.
- Take text from `message_update` deltas for display and from `message_end`
  as the authoritative body. A failed attempt that pi retries does not end
  the turn; only an error on the last `agent_end` assistant message is
  reported, because pi exits 0 for model errors.
- Keep the user's `~/.pi` providers and settings. Pass `--approve`, since
  print/json modes skip the project skills and `.pi` settings silently
  otherwise, and `--tools read,bash,write,edit` so project content changes
  still go through the opendirector CLI.
- Reuse a turn's workspace with `--session-id` and keep sessions inside
  `agent-runs/pi-sessions/native`, so continuation does not touch global
  session history and a missing directory degrades to a full replay.
- Probe readiness by version, model table and `pi auth check --json`;
  unreadable catalog and zero models stay distinguishable.
- Add the picker entry, local monochrome logo, bilingual setup hint and
  runtime identifiers in the API contract, docs and tests.

Refs: ThinkFlowLab#438
## summary

- Reject a joined name that leaves its directory. `child()` only refused a
  symlink at the final segment, so a request-derived identifier could still
  reach a sibling path through `..`; the check stays lexical, so hot paths
  take no extra filesystem call.
- Keep `pi` out of the credential-free release visual gate. The gate derives
  its cases from `RUNTIMES`, so adding a harness asserted a pinned CLI that
  release CI installs without credentials of its own. The opt-in nightly
  case still covers pi.
- State that exclusion and its reason in the validation guide in both
  languages.

## validation

- `python -m pytest -m ready` (207 passed)
- `python -m pytest tests/test_creation_storage.py tests/test_agent_gateway.py
  tests/test_pi_runtime.py tests/test_agent_visual_gate.py` (117 passed,
  14 skipped)
- `python -m pytest tests/test_agent_visual_gate.py --collect-only` lists
  five harness cases

Refs: ThinkFlowLab#438
## summary

- Reject a name that changes under `basename` before the join, so a request
  cannot carry a separator or `..` into the path at all. The lexical
  containment check stays as a second gate for the joined result.

## validation

- `python -m pytest -m ready` (207 passed)
- `python -m pytest tests/test_creation_storage.py tests/test_agent_gateway.py
  tests/test_pi_runtime.py tests/test_execution_files.py
  tests/test_local_json.py` (149 passed, 15 skipped)
`child()` reduced the requested name to a base name and compared the joined
path with the directory through `Path.parents`. That comparison is not a
containment check CodeQL recognizes for `py/path-injection`: `os.path.abspath`
only moves the value to the "normalized, unchecked" state, so every sink that
inherited the result stayed tainted. The PR run reported three such sinks —
`FileResponse` and `is_file` in the trace route, and `is_symlink` in `child()`
itself.

Check the normalized string against the directory prefix, and build the
returned `Path` only inside that branch, so every path handed to callers has
passed the check.

Verified by rerunning the scan locally (CodeQL 2.27.5, python-code-scanning
suite) on the same source: before, three `py/path-injection` results at
agent.py:333, agent.py:335 and local_projects.py:23; after, none. The new
`tests/test_local_json.py` case covers traversal, separators and links.
## summary

- Normalize pi's JSON mode stream before the page renders it. `message_end`
  becomes one row per message with its own role: user text, assistant text and
  assistant thinking. Lifecycle records (`session`, `agent_start`,
  `turn_start`, `message_start`, `message_update`, `turn_end`,
  `agent_settled`, queue and settings events) stay out of the list, and the
  system prompt and tool results are not echoed as conversation rows.
- Collapse `tool_execution_start`/`_update`/`_end` into one row per
  `toolCallId`, carrying the tool name, `in_progress`/`completed`/`failed`,
  the arguments and the result text, so a call is no longer three separate
  raw rows. An `_end` without a matching `_start` still shows, and a late
  update does not overwrite a settled result.
- Keep pi's retry semantics: an attempt that ends with `stopReason: 'error'`
  contributes no text, and only the settled `agent_end` message reports the
  turn's error — the same rule `agent/pi.py` applies.
- Streaming deltas are not drawn as their own rows because they repeat the
  finished message; a text row appears when its message ends, as the Claude
  and Codex normalizers already do.

## validation

- `node --test tests/piTrace.test.ts` (4 passed)
- `node --test tests/*.test.ts` (974 passed), `npx tsc --noEmit` (no error)
- `scripts/check-i18n.mjs` (3342 keys, 0 problems),
  `scripts/check-browser-manifest.mjs` (92 entries)
- Real stream: `pi --mode json --print --tools read` on a scratch directory,
  22 records; the normalizer returns the user message and one `read ·
  completed` row carrying `{"path": ...}` and the file text, and drops the
  system message and the 22 lifecycle records.

Refs: ThinkFlowLab#438
## summary

- `main` moved `RuntimeId` out of `agent/context.py` into
  `domain/agent_runtime.py`. This branch still added `pi` to the old literal,
  so resolving the conflict kept main's line — a module the branch never saw —
  and the new literal has no `pi`.
- `apps/api/.../agent.py` validates `Turn.runtime` and `Draft.runtime` against
  that type, so a pi turn was rejected with a 422 while every local test kept
  passing: `test_pi_runtime` builds a `RunContext`, a dataclass with no
  validation, and never crosses the request models.
- Declare `pi` in the shared literal, and guard the seam: every name in
  `RUNTIMES` must be declared and must construct `Turn` and `Draft`.

## validation

- `python -m pytest tests/test_pi_runtime.py` (20 passed)
- same file with the literal reverted (1 failed: `AssertionError: {'pi'}`)
- `python -m pytest tests/test_creation_api.py tests/test_creation_contracts.py
  tests/test_runtime_catalog.py tests/test_prompt_optimization.py
  tests/test_assistant_conversations.py tests/test_capability_contract.py`
  (295 passed)
- `python -m pytest tests/test_pi_runtime.py tests/test_native_runtime.py
  tests/test_runtime_readiness.py tests/test_agent_visual_gate.py`
  (62 passed, 21 skipped)
- `npx tsc --noEmit` (no errors), `node --test tests/piTrace.test.ts` (4 pass)
- `node scripts/check-i18n.mjs` (3376 keys, 0 problems, baseline 169)
- `python3 scripts/generate_contracts.py --check` (contracts verified)
@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

Conflicts resolved: rebased onto main@eecc35eb, tip is now 2c5f2564.

Where it conflicted. One file, one hunk — packages/core/src/opendirector/agent/context.py, where main no longer defines RuntimeId because it moved to domain/agent_runtime.py.

Why it was more than a text conflict. main extracted RuntimeId into a new module whose literal ends at deepseek. This branch added 'pi' to the old literal in context.py, and that file did not conflict — so resolving the one real hunk silently produced a tree where the shared literal has no pi. That type is what apps/api/.../agent.py validates against (Runtime = RuntimeId on Turn.runtime and Draft.runtime), so on the rebased tree a pi turn was rejected at the boundary:

Turn(id=uuid4(), text='hi', runtime='pi')   ->  ValidationError: runtime

Nothing local caught it. tests/test_pi_runtime.py builds RunContext(runtime='pi'), a plain dataclass with no validation, and runtime_spec('pi') — neither crosses the request models, and no test compared RUNTIMES with RuntimeId. The whole pi suite plus test_creation_api, test_creation_contracts and test_runtime_catalog were green on the broken tree.

Fix in 2c5f2564. Declare pi in domain/agent_runtime.py, and add a guard that every name in RUNTIMES is declared and constructs both Turn and Draft, so a future runtime id cannot land in the registry only. With the literal reverted the guard fails with AssertionError: {'pi'}; with the fix it passes.

Scope note. The three storage commits below the pi commit stay in this PR. I first read them as unrelated work, but they are this PR's own prerequisites: 0d9a6a43 keeps pi out of the credential-free release visual gate (Refs: #438, plus the bilingual note in the validation guide), and e90e76a2 clears the three py/path-injection sinks that the scan reported on this branch's trace route (agent.py:333, agent.py:335, local_projects.py:23). Dropping them would bring both back.

Ran: pytest tests/test_pi_runtime.py tests/test_native_runtime.py tests/test_runtime_readiness.py tests/test_agent_visual_gate.py (62 passed, 21 skipped); pytest tests/test_creation_api.py tests/test_creation_contracts.py tests/test_runtime_catalog.py tests/test_prompt_optimization.py tests/test_assistant_conversations.py tests/test_capability_contract.py (295 passed); npx tsc --noEmit; node --test tests/piTrace.test.ts (4 pass); node scripts/check-i18n.mjs (3376 keys, 0 problems); python3 scripts/generate_contracts.py --check
Not run: a pi turn against a real provider, and the release browser (isolated) lane, which runs on push

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent runtime, assistant chat and tools area:harness Harness and skill integration (Default, OpenCode, Codex, Claude Code, Jiuwen, DSH) type:feat New capability or behaviour

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants