migrating-pi-to-pydantic-ai

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Migrate Pi to Pydantic AI

将 Pi 迁移到 Pydantic AI

Preserve observable behavior, not Pi's TypeScript API. Migrate the smallest complete caller path and keep product/host infrastructure in the application.
保留可观察行为,而不是 Pi 的 TypeScript API。迁移最小但完整的调用方路径,并将产品和宿主基础设施保留在应用程序中。

Trace the source before choosing a target

在选择目标之前追踪源代码

  1. Read repository instructions,
    package.json
    , Pi settings, tests, extension/package manifests, and runtime entrypoints. Record the installed Pi, Pydantic AI, and Harness versions.
  2. Trace one real request from the Pi CLI, RPC boundary, or
    createAgentSession().prompt()
    through resource discovery, system instructions, tools, extensions, model requests, messages, compaction/retry, events, session entries, UI/RPC output, and side effects. Establish a focused baseline or characterization test.
  3. Inventory every active extension factory and package resource. For each
    pi.on(...)
    ,
    registerTool
    ,
    registerCommand
    , provider registration, renderer/UI contribution, skill, prompt, and persisted entry, record its firing point, trusted inputs, mutations, output, state owner, and caller-visible effect.
  4. Separate these contracts when present:
    • model messages, append-only session entries/tree branches, compaction summaries, and extension state;
    • model-chosen tool input, trusted host context, project trust, approval, authorization, and OS isolation;
    • token deltas, tool lifecycle, Pi extension events, capability events, RPC events, and terminal rendering;
    • agent-loop behavior, CLI/TUI host behavior, provider transport, package distribution, and external side effects.
  5. Record each observed contract, its owner, semantic difference, and executable proof. An installed but inactive Pi package feature is not migration scope.
Read Research and concept mapping for the detected features. Read Verification and cutover before implementation.
  1. 读取仓库说明、
    package.json
    、Pi 设置、测试、扩展/包清单以及运行时入口。记录已安装的 Pi、Pydantic AI 和 Harness 版本。
  2. 从 Pi CLI、RPC 边界或
    createAgentSession().prompt()
    出发,追踪一次真实请求所经过的资源发现、系统指令、工具、扩展、模型请求、消息、compaction/retry、事件、会话条目、UI/RPC 输出和副作用流程。建立一个聚焦的基线测试或特征测试。
  3. 盘点每个活动的扩展工厂和包资源。对于每个
    pi.on(...)
    、
    registerTool
    、
    registerCommand
    、provider 注册、渲染器/UI 贡献、skill、prompt 和持久化条目,记录其触发点、可信输入、变更、输出、状态所有者以及对调用方可见的效果。
  4. 存在以下契约时,将其分开:
    • 模型消息、仅追加的会话条目/树分支、compaction 摘要和扩展状态;
    • 由模型选择的工具输入、可信宿主上下文、project trust、审批、授权和操作系统隔离;
    • token 增量、工具生命周期、Pi 扩展事件、capability 事件、RPC 事件和终端渲染;
    • Agent 循环行为、CLI/TUI 宿主行为、provider 传输、包分发和外部副作用。
  5. 记录每个观察到的契约、其所有者、语义差异和可执行验证。已安装但未激活的 Pi 包功能不属于迁移范围。
阅读研究与概念映射以了解检测到的功能。实施前阅读验证与切换。

Treat extensions as capability candidates

将扩展视为 capability 候选

A Pi extension is the closest source concept to a Pydantic AI capability, but it is broader. An extension can combine agent behavior with terminal UI, commands, provider registration, resource discovery, and host lifecycle. Port responsibilities, not the extension file:
  1. Map reusable model-facing behavior—tools, instructions, model settings, history/event processing, guardrails, and agent-loop hooks—to an existing Core or Harness capability when its lifecycle matches.
  2. Bundle related instructions and tools in core
    Capability
    ; subclass
    AbstractCapability
    only for reusable behavior that needs lifecycle hooks, adaptive models/settings, native tools, or typed capability events.
  3. Keep CLI commands, flags, keyboard shortcuts, TUI renderers/dialogs, session selection, project trust, package installation, and provider credential setup in the Python application or interface adapter. They are not agent capabilities merely because a Pi extension owns them.
  4. Split mixed extensions at that seam. A permission extension may become a
    ToolGuardrail
    or approval capability plus an application-owned approver UI; a coding package may become
    Coder
    plus host configuration; a provider extension remains a model/provider integration.
  5. Preserve order only where evidence shows it matters. Pi handler load order and Pydantic AI capability/hook ordering are different contracts.
Pi 扩展是源概念中与 Pydantic AI capability 最接近的概念,但它涵盖的范围更广。扩展可以将 Agent 行为与终端 UI、命令、provider 注册、资源发现和宿主生命周期结合起来。迁移职责,而不是扩展文件:
  1. 当生命周期匹配时,将可复用的面向模型行为——tools、instructions、model settings、history/event processing、guardrails 和 agent-loop hooks——映射到现有的 Core 或 Harness capability。
  2. 将相关的 instructions 和 tools 打包到 core
    Capability
    中;仅当可复用行为需要 lifecycle hooks、自适应 models/settings、native tools 或 typed capability events 时,才派生
    AbstractCapability
    。
  3. 将 CLI commands、flags、keyboard shortcuts、TUI renderers/dialogs、session selection、project trust、package installation 和 provider credential setup 保留在 Python 应用程序或 interface adapter 中。仅仅因为 Pi extension 拥有这些内容,并不意味着它们属于 Agent capabilities。
  4. 在这一边界处拆分混合型扩展。权限扩展可以转换为
    ToolGuardrail
    或 approval capability,再加上由应用程序拥有的 approver UI;coding package 可以转换为
    Coder
    加宿主配置;provider extension 则仍然是 model/provider integration。
  5. 仅在证据表明顺序重要时保留顺序。Pi handler 加载顺序与 Pydantic AI capability/hook 顺序是不同的契约。

Choose the smallest target

选择最小目标

  • Core: use
    pydantic_ai.Agent
    for the agent loop, typed dependencies, tools/toolsets, outputs, normalized messages, capabilities/hooks, streaming, approvals, usage limits, instrumentation, MCP, and provider/model integration.
  • Harness: use
    Coder
    for Pi's ordinary coding tools only when its exact composition fits. Add focused capabilities such as
    FileSystem
    ,
    Shell
    ,
    Skills
    ,
    Planning
    ,
    SubAgents
    , guardrails, compaction, tool-output limits, or step persistence only for observed behavior.
  • Application/interface: retain or replace CLI/TUI/RPC, auth, project trust, settings, provider login/catalogs, session browsing, package management, deployment, and transport deliberately.
  • Graph: use plain async Python or
    pydantic_graph
    for deterministic workflows; do not encode them in prompts or subagents.
  • Gap: name behavior with no supported public seam, explain its impact, and test a bounded adapter. Do not clone Pi's extension bus or JSONL format just to claim parity.
The normal embedded migration is one reusable
Agent
,
Coder
or a smaller capability composition, application services in typed dependencies, an application-owned message/session store, and a thin adapter at the existing RPC or UI boundary.
  • Core: 使用
    pydantic_ai.Agent
    实现 Agent 循环、类型化依赖、tools/toolsets、输出、标准化消息、capabilities/hooks、流式传输、审批、用量限制、instrumentation、MCP 以及 provider/model 集成。
  • Harness: 仅当
    Coder
    的精确组成适合 Pi 的常规编程工具时,才使用
    Coder
    。仅在观察到相应行为后,才添加聚焦的 capabilities,例如
    FileSystem
    、
    Shell
    、
    Skills
    、
    Planning
    、
    SubAgents
    、guardrails、compaction、tool-output limits 或 step persistence。
  • Application/interface: 明确决定保留或替换 CLI/TUI/RPC、认证、project trust、设置、provider 登录/catalogs、会话浏览、包管理、部署和传输。
  • Graph: 使用原生异步 Python 或
    pydantic_graph
    实现确定性工作流;不要将其编码在 prompts 或 subagents 中。
  • Gap: 明确指出没有受支持公共接入点的行为,说明其影响,并测试一个受限适配器。不要仅为了宣称行为对等,就克隆 Pi 的 extension bus 或 JSONL 格式。
常见的嵌入式迁移方案包括一个可复用的
Agent
、
Coder
或更小的 capability 组合、以类型化依赖形式提供的应用程序服务、由应用程序拥有的消息/会话存储,以及位于现有 RPC 或 UI 边界的轻量适配器。

Apply high-risk gates

落实高风险防护门禁

  • ctx
    , project trust, credentials, session managers, and service handles are trusted host context. Put equivalents in typed dependencies or application services, never model-chosen tool arguments.
  • Pi session JSONL is an append-only branching host log containing more than model context.
    result.all_messages()
    preserves model history, not tree navigation, labels, extension entries, compaction records, model changes, queues, or abandoned branches. Choose and test conversion, a compatibility store, or an accepted fresh start.
  • Pi compaction, context interception, steering/follow-up queues, retries, and branch summaries have specific timing. Select matching core/Harness seams independently and test ordering; generic message history or summarization is not automatic parity.
  • Map
    tool_call
    permission gates by effect. Use guardrails for validation/block/redaction and deferred tools for an action that must await approval. Keep identity, authorization, UI, audit, persistence, and idempotency in the application.
  • Pi extensions run arbitrary TypeScript with host permissions. A Pydantic AI capability also runs application code; neither is a sandbox. Use an OS/container/cloud isolation boundary for untrusted commands or code.
  • Harness
    Skills
    loads configured
    SKILL.md
    instructions on demand but does not reproduce Pi's discovery roots, resource files, scripts, reload, package installation, or behavioral frontmatter. Preserve those separately when observed.
  • Use
    SubAgents
    only for model-directed isolated tasks. Keep deterministic orchestration and Pi subprocess/tmux/package-specific semantics in application code.
  • Map dynamic tool activation to core
    ToolSearch
    or on-demand capabilities only after testing load timing, schemas, prompt/cache changes, and provider fallback behavior.
  • Pydantic AI run events and capability events do not reproduce Pi's extension event bus, RPC protocol, or TUI render lifecycle. Adapt only stable fields consumers use.
  • Pi provider extensions and payload hooks may alter authentication, catalogs, wire payloads, headers, and streaming. Implement them at the Pydantic AI model/provider or application transport layer and run provider contract tests; do not hide them in a generic capability.
  • ctx
    、project trust、credentials、session managers 和 service handles 属于可信宿主上下文。将对应的功能放入类型化依赖或应用程序服务中,绝不能放入由模型选择的工具参数中。
  • Pi session JSONL 是仅追加且支持分支的宿主日志,其中包含的内容不止模型上下文。
    result.all_messages()
    保留模型历史,但不会保留树导航、标签、扩展条目、compaction 记录、模型变更、队列或已放弃的分支。选择并测试转换方案、兼容存储方案,或明确接受从头开始。
  • Pi compaction、context interception、steering/follow-up queues、retries 和 branch summaries 都有特定的时序。分别选择匹配的 Core/Harness 接入点并测试顺序;通用消息历史或摘要处理并不会自动实现行为对等。
  • 按实际作用映射
    tool_call
    权限门禁。使用 guardrails 完成验证、阻止和脱敏;对于必须等待审批的操作,使用 deferred tools。将身份、授权、UI、审计、持久化和幂等性保留在应用程序中。
  • Pi extensions 以宿主权限运行任意 TypeScript。Pydantic AI capability 同样会运行应用程序代码;两者都不是沙箱。对于不可信的命令或代码,应使用操作系统、容器或云隔离边界。
  • Harness
    Skills
    会按需加载已配置的
    SKILL.md
    instructions,但不会复现 Pi 的发现根目录、资源文件、脚本、重新加载、包安装或行为型 frontmatter。观察到这些行为时,应分别予以保留。
  • 仅对由模型指挥的隔离任务使用
    SubAgents
    。将确定性编排以及 Pi 的 subprocess/tmux/package 特有语义保留在应用程序代码中。
  • 只有在测试加载时机、schema、prompt/cache 变化和 provider fallback 行为后,才将动态工具激活映射到 core
    ToolSearch
    或按需 capabilities。
  • Pydantic AI run events 和 capability events 无法复现 Pi 的扩展事件总线、RPC 协议或 TUI 渲染生命周期。仅适配消费者使用的稳定字段。
  • Pi provider extensions 和 payload hooks 可能改变身份验证、catalog、传输载荷、headers 和流式处理。在 Pydantic AI model/provider 层或 application transport 层实现这些行为,并运行 provider 合约测试;不要将它们隐藏在通用 capability 中。

Implement and prove one vertical slice

实现并验证一个垂直切片

  1. Preserve the supported CLI, RPC, SDK, job, or UI boundary and replace only agent-owned internals.
  2. Start with core plus the smallest coding capabilities. Add broader Harness behavior only after a traced contract requires it.
  3. For each source extension, document the split: capability behavior, application/interface behavior, retained integration, and gap. Test each side through its real boundary.
  4. Use language-neutral fixtures for RPC/events and persisted records. Test tool arguments/results, errors, event order, session continuation, UI decisions, and side effects. Use deterministic models offline; add focused recorded/live provider tests only for provider behavior.
  5. Remove Pi packages, settings, Node runtime, or extension adapters only after no retained path needs them.
Explain consequential semantic changes before implementing them: state the Pi behavior, target behavior, caller impact, recommended choice, and remaining risk.
  1. 保留受支持的 CLI、RPC、SDK、job 或 UI 边界,只替换 Agent 所属的内部机制。
  2. 从 core 和最小 coding capabilities 开始。只有当已追踪的契约提出要求时,才加入更广泛的 Harness 行为。
  3. 对每个源扩展,记录拆分情况:capability 行为、application/interface 行为、保留的集成和 gap。通过各自的真实边界进行测试。
  4. 对 RPC/events 和持久化记录使用与语言无关的 fixtures。测试工具参数/结果、错误、事件顺序、会话延续、UI 决策和副作用。在离线环境中使用确定性模型;仅针对 provider 行为添加聚焦的录制/实时 provider 测试。
  5. 只有在所有保留路径都不再需要它们后,才移除 Pi packages、settings、Node runtime 或 extension adapters。
实施有重大影响的语义变更前应先加以说明:列出 Pi 行为、目标行为、对调用方的影响、推荐选择以及剩余风险。

Completion

完成

Apply the completion criterion in Verification and cutover. Label fake, recording, live-provider, terminal, restart, and sandbox evidence accurately.
应用验证与切换中的完成标准。准确标注伪造、录制、实时 provider、终端、重启和沙箱证据。