Przeglądaj źródła

Import MiniMax Code CLI source snapshot

Import the reviewed standalone TUI, headless CLI, and ACP source, including build tooling, verification, documentation, and desktop support integration.
hetaoBackend 2 miesięcy temu
rodzic
commit
c59cf53770
100 zmienionych plików z 13226 dodań i 198 usunięć
  1. 16 0
      .gitattributes
  2. 3 0
      .github/CODEOWNERS
  3. 37 69
      .github/ISSUE_TEMPLATE/01-bug-report.yml
  4. 25 34
      .github/ISSUE_TEMPLATE/02-feature-request.yml
  5. 23 20
      .github/ISSUE_TEMPLATE/03-question.yml
  6. 7 0
      .github/ISSUE_TEMPLATE/config.yml
  7. 17 0
      .github/ISSUE_TEMPLATE/docs.yml
  8. 23 0
      .github/PULL_REQUEST_TEMPLATE.md
  9. 15 0
      .github/actions/setup-gitleaks/action.yml
  10. 26 0
      .github/branch-protection.json
  11. 19 0
      .github/dependabot.yml
  12. 117 0
      .github/workflows/ci.yml
  13. 42 0
      .github/workflows/compatibility.yml
  14. 45 0
      .github/workflows/security.yml
  15. 136 0
      .github/workflows/source-candidate.yml
  16. 2 1
      .github/workflows/sync-issue-to-feishu.yml
  17. 10 0
      .gitignore
  18. 62 0
      .gitleaks.toml
  19. 2 0
      .npmrc
  20. 53 0
      AGENTS.md
  21. 52 0
      CONTRIBUTING.md
  22. 21 0
      LICENSE
  23. 21 0
      LICENSE-STATUS.md
  24. 6 0
      NOTICE
  25. 186 28
      README.md
  26. 0 46
      README.zh-CN.md
  27. 204 0
      README_ZH.md
  28. 19 0
      SECURITY.md
  29. 10 0
      THIRD_PARTY_NOTICES.md
  30. 26 0
      docs/README.md
  31. 24 0
      docs/architecture.md
  32. 1 0
      docs/assets/license.svg
  33. 1 0
      docs/assets/node.svg
  34. BIN
      docs/assets/social-preview.png
  35. 0 0
      docs/assets/social-preview.svg
  36. 1 0
      docs/assets/source-preview.svg
  37. BIN
      docs/assets/tui-demo.gif
  38. BIN
      docs/assets/tui-demo.mp4
  39. BIN
      docs/assets/tui-demo.png
  40. 0 0
      docs/assets/wordmark-dark.svg
  41. 0 0
      docs/assets/wordmark-light.svg
  42. 30 0
      docs/demo.md
  43. 74 0
      docs/examples.md
  44. 48 0
      docs/installation.md
  45. 52 0
      docs/maintainers.md
  46. 33 0
      docs/open-source-status.md
  47. 33 0
      docs/publication-authorization.md
  48. 40 0
      docs/release-audit.md
  49. 81 0
      docs/releasing.md
  50. 26 0
      docs/source-sync.md
  51. 82 0
      docs/telemetry.md
  52. 48 0
      docs/tui-capabilities.md
  53. 140 0
      docs/verification.md
  54. 9 0
      examples/clamp/README.md
  55. 4 0
      examples/clamp/clamp.mjs
  56. 6 0
      examples/clamp/clamp.test.mjs
  57. 63 0
      package.json
  58. 88 0
      packages/agent-core/package.json
  59. 273 0
      packages/agent-core/src/bash-subprocess-env.ts
  60. 1068 0
      packages/agent-core/src/event-bridge/bridge.ts
  61. 845 0
      packages/agent-core/src/event-bridge/converters.ts
  62. 224 0
      packages/agent-core/src/event-bridge/display-sanitize.ts
  63. 72 0
      packages/agent-core/src/event-bridge/index.ts
  64. 110 0
      packages/agent-core/src/event-bridge/plugin-capability-attribution.ts
  65. 31 0
      packages/agent-core/src/event-bridge/resp-data.ts
  66. 59 0
      packages/agent-core/src/event-bridge/runtime-warning.ts
  67. 98 0
      packages/agent-core/src/event-bridge/types.ts
  68. 34 0
      packages/agent-core/src/index.ts
  69. 137 0
      packages/agent-core/src/pi-turn-runner/agent.ts
  70. 71 0
      packages/agent-core/src/pi-turn-runner/assembly-fingerprint.ts
  71. 31 0
      packages/agent-core/src/pi-turn-runner/defaults.ts
  72. 425 0
      packages/agent-core/src/pi-turn-runner/events.ts
  73. 251 0
      packages/agent-core/src/pi-turn-runner/history.ts
  74. 268 0
      packages/agent-core/src/pi-turn-runner/hooks.ts
  75. 112 0
      packages/agent-core/src/pi-turn-runner/image-dimensions.ts
  76. 112 0
      packages/agent-core/src/pi-turn-runner/index.ts
  77. 963 0
      packages/agent-core/src/pi-turn-runner/llm-retry.ts
  78. 614 0
      packages/agent-core/src/pi-turn-runner/llm.ts
  79. 1230 0
      packages/agent-core/src/pi-turn-runner/metrics.ts
  80. 296 0
      packages/agent-core/src/pi-turn-runner/outbound-message-normalizer.ts
  81. 249 0
      packages/agent-core/src/pi-turn-runner/pi-turn-runner.ts
  82. 36 0
      packages/agent-core/src/pi-turn-runner/terminal.ts
  83. 238 0
      packages/agent-core/src/pi-turn-runner/tool-context-size.ts
  84. 246 0
      packages/agent-core/src/pi-turn-runner/tools.ts
  85. 393 0
      packages/agent-core/src/pi-turn-runner/turn.ts
  86. 221 0
      packages/agent-core/src/pi-turn-runner/types.ts
  87. 101 0
      packages/agent-core/src/prompt-read.ts
  88. 164 0
      packages/agent-core/src/protocol/agent-event.ts
  89. 264 0
      packages/agent-core/src/protocol/agent-message.ts
  90. 28 0
      packages/agent-core/src/protocol/context-usage.ts
  91. 16 0
      packages/agent-core/src/protocol/index.ts
  92. 209 0
      packages/agent-core/src/protocol/runtime-event.ts
  93. 57 0
      packages/agent-core/src/tools/bind.ts
  94. 245 0
      packages/agent-core/src/tools/builtin-defs.ts
  95. 59 0
      packages/agent-core/src/tools/define.ts
  96. 49 0
      packages/agent-core/src/tools/edit-prepare-arguments.ts
  97. 54 0
      packages/agent-core/src/tools/index.ts
  98. 13 0
      packages/agent-core/src/tools/input-validation.ts
  99. 153 0
      packages/agent-core/src/tools/types.ts
  100. 998 0
      packages/agent-core/test/unit/event-bridge/converters.test.ts

+ 16 - 0
.gitattributes

@@ -0,0 +1,16 @@
+* text=auto eol=lf
+release/public-source.json linguist-generated=true
+release/dependency-licenses.json linguist-generated=true
+tsconfig.standalone.json linguist-generated=true
+*.gz -text
+*.jar -text
+*.exe -text
+*.png -text
+*.jpg -text
+*.jpeg -text
+*.woff2 -text
+*.pdf -text
+*.gif -text
+*.mp4 -text
+# Preserve vendored Office schema bytes when importing the reviewed source archive.
+packages/local-runtime/assets/skills/xlsx/scripts/office/schemas/**/*.xsd -text

+ 3 - 0
.github/CODEOWNERS

@@ -0,0 +1,3 @@
+# Release coordinator; additional designated reviewers are pending.
+# Independent approval is enforced by branch protection, not by this file.
+* @hetaoBackend

+ 37 - 69
.github/ISSUE_TEMPLATE/01-bug-report.yml

@@ -1,132 +1,100 @@
-name: Bug report / 问题反馈
-description: Report a reproducible MiniMax Code desktop problem
+name: Bug report
+description: Report a reproducible problem with the Desktop app, CLI, or source build.
 title: "[Bug]: "
 labels: ["bug"]
-
 body:
   - type: markdown
     attributes:
-      value: |
-        Thanks for reporting. Please remove API keys, tokens, private code, and other sensitive information before submitting.
-        感谢反馈。提交前请移除 API Key、Token、私有代码和其他敏感信息。
-
+      value: Search existing issues first. Remove credentials, private code, account details, and sensitive paths. Report vulnerabilities privately using SECURITY.md.
+  - type: dropdown
+    id: product
+    attributes:
+      label: Product or interface
+      options:
+        - Desktop app
+        - CLI - interactive TUI
+        - CLI - headless
+        - CLI - ACP
+        - Source build or repository tooling
+    validations:
+      required: true
   - type: input
     id: version
     attributes:
-      label: Version / 版本号
-      description: Find this in MiniMax Code Settings.
-      placeholder: "Example: v3.0.35"
+      label: Version
+      description: Desktop Settings version, mcode --version, or source commit. For source builds, also include Node.js and pnpm versions.
     validations:
       required: true
-
   - type: dropdown
     id: platform
     attributes:
-      label: Platform / 平台
+      label: Platform
       options:
         - macOS
         - Windows
+        - Linux
+        - WSL
+        - Multiple platforms
     validations:
       required: true
-
   - type: input
     id: os-version
     attributes:
-      label: OS version / 系统版本
-      placeholder: "Example: macOS 15.5, Windows 11 23H2"
+      label: OS version and architecture
+      placeholder: "Example: Windows 11 x64, macOS 15 arm64, Ubuntu 24.04 x64"
     validations:
       required: true
-
   - type: dropdown
     id: issue-area
     attributes:
-      label: Issue area / 问题类型
+      label: Issue area
       options:
         - Startup / install / update
         - Agent stuck / slow / repeated loop
-        - Tool call / permission / daemon
+        - Tool call / permission / sandbox
         - MCP / OAuth / integration
         - File / workspace / path / encoding
         - Model output quality
         - UI / UX
+        - Build / CI / source distribution
         - Other
     validations:
       required: true
-
   - type: input
     id: upload-id
     attributes:
-      label: Upload ID / 日志上传 ID
-      description: In MiniMax Code, go to Settings → General → Upload logs. If the app cannot start, write "cannot upload" and attach crash logs below.
-      placeholder: "Example: upload_xxx, or cannot upload"
-    validations:
-      required: true
-
-  - type: textarea
-    id: summary
-    attributes:
-      label: What happened? / 问题描述
-      placeholder: "MiniMax Code crashes when..."
-    validations:
-      required: true
-
+      label: Desktop log upload ID (optional)
+      description: For Desktop only, include an existing ID from Settings → General → Upload logs if available. CLI and source-build reports do not require an upload. Do not paste account credentials or raw session files.
   - type: textarea
     id: steps
     attributes:
-      label: Steps to reproduce / 复现步骤
-      placeholder: |
-        1. Open MiniMax Code
-        2. Click...
-        3. Run...
-        4. See error...
+      label: Steps to reproduce
+      description: Include a minimal synthetic example. For CLI tasks, include permission mode, provider type, and the command without keys.
     validations:
       required: true
-
   - type: textarea
     id: expected
     attributes:
-      label: Expected behavior / 预期行为
+      label: Expected and actual behavior
     validations:
       required: true
-
-  - type: textarea
-    id: actual
-    attributes:
-      label: Actual behavior / 实际行为
-    validations:
-      required: true
-
   - type: textarea
     id: logs
     attributes:
-      label: Logs or crash report / 日志或崩溃信息
-      description: |
-        Paste the relevant log lines or stack trace here. They will be rendered as a code block.
-        Please remove secrets, tokens, API keys, private paths, and private code.
-        粘贴相关日志或堆栈,会自动按代码块渲染。
-        提交前请移除 Secret、Token、API Key、私有路径和私有代码。
+      label: Redacted error summary
+      description: Only include the relevant excerpt after removing credentials, account details, private paths, and project content.
       render: shell
-    validations:
-      required: false
-
   - type: textarea
     id: screenshots
     attributes:
-      label: Screenshots / 截图
-      description: |
-        Drag and drop screenshots here, or paste them directly. (GitHub disables image upload inside the Logs field above, so screenshots go here.)
-        把截图直接拖到这里,或者粘贴。(上面「日志」字段是代码块,GitHub 不允许在里面贴图,所以截图请放这里。)
-    validations:
-      required: false
-
+      label: Screenshots
+      description: Attach redacted screenshots here, outside the code-formatted error field.
   - type: checkboxes
     id: checklist
     attributes:
-      label: Before submitting / 提交前确认
+      label: Before submitting
       options:
         - label: I have searched existing issues.
           required: true
-        - label: I am using the latest version available to me.
-          required: true
-        - label: I have removed sensitive information from logs/screenshots.
+        - label: I have included my version and removed sensitive information.
           required: true

+ 25 - 34
.github/ISSUE_TEMPLATE/02-feature-request.yml

@@ -1,57 +1,48 @@
-name: Feature request / 功能建议
-description: Suggest an improvement for MiniMax Code desktop
+name: Feature request
+description: Suggest an improvement to the Desktop app, CLI, or source distribution.
 title: "[Feature]: "
 labels: ["enhancement"]
-
 body:
-  - type: markdown
+  - type: dropdown
+    id: product
     attributes:
-      value: |
-        Thanks for helping improve MiniMax Code. Please search existing issues before submitting.
-        感谢帮助我们改进 MiniMax Code。提交前请先搜索是否已有相关 Issue。
-
+      label: Product or interface
+      options:
+        - Desktop app
+        - CLI - interactive TUI
+        - CLI - headless
+        - CLI - ACP
+        - Source build or repository tooling
+    validations:
+      required: true
   - type: textarea
     id: problem
     attributes:
-      label: Problem / 你遇到的问题
-      description: What problem would this feature solve?
-      placeholder: "I often need to..."
+      label: Use case and problem
+      description: What are you trying to do, and what limits you today?
     validations:
       required: true
-
   - type: textarea
     id: proposal
     attributes:
-      label: Proposed solution / 期望方案
-      description: What would you like MiniMax Code to do?
-      placeholder: "I would like MiniMax Code to..."
+      label: Desired behavior
+      description: Include an interaction example or acceptance criteria.
     validations:
       required: true
-
   - type: dropdown
     id: platform
     attributes:
-      label: Platform / 平台
+      label: Platform
       options:
         - macOS
         - Windows
-        - Linux desktop support
-        - All desktop platforms
+        - Linux
+        - WSL
+        - Multiple platforms
     validations:
-      required: false
-
+      required: true
   - type: textarea
-    id: context
-    attributes:
-      label: Additional context / 补充信息
-      description: Add screenshots, examples, or related workflows if helpful.
-    validations:
-      required: false
-
-  - type: checkboxes
-    id: checklist
+    id: alternatives
     attributes:
-      label: Before submitting / 提交前确认
-      options:
-        - label: I have searched existing issues.
-          required: true
+      label: Alternatives and additional context
+      description: Include what you tried and any relevant examples without private project content.

+ 23 - 20
.github/ISSUE_TEMPLATE/03-question.yml

@@ -1,39 +1,42 @@
-name: Question / 使用问题
-description: Ask a question about MiniMax Code desktop
+name: Usage question
+description: Ask about the Desktop app, CLI, or building from source.
 title: "[Question]: "
 labels: ["question"]
-
 body:
+  - type: dropdown
+    id: product
+    attributes:
+      label: Product or interface
+      options:
+        - Desktop app
+        - CLI - interactive TUI
+        - CLI - headless
+        - CLI - ACP
+        - Source build or repository tooling
+    validations:
+      required: true
   - type: textarea
     id: question
     attributes:
-      label: Question / 问题
-      placeholder: "How do I..."
+      label: Question
     validations:
       required: true
-
   - type: dropdown
     id: platform
     attributes:
-      label: Platform / 平台
+      label: Platform
       options:
         - macOS
         - Windows
+        - Linux
+        - WSL
+        - Multiple platforms
     validations:
-      required: false
-
+      required: true
   - type: textarea
     id: context
     attributes:
-      label: Context / 补充信息
-      description: What have you tried? Add screenshots if useful.
+      label: Version and what you have tried
+      description: Include documentation you followed and relevant redacted output. Do not include keys or account data.
     validations:
-      required: false
-
-  - type: checkboxes
-    id: checklist
-    attributes:
-      label: Before submitting / 提交前确认
-      options:
-        - label: I have searched existing issues.
-          required: true
+      required: true

+ 7 - 0
.github/ISSUE_TEMPLATE/config.yml

@@ -1 +1,8 @@
 blank_issues_enabled: false
+contact_links:
+  - name: CLI quick start and troubleshooting
+    url: https://agent.minimax.io/docs/cli/quick-start
+    about: Installation, account regions, first tasks, and links to troubleshooting.
+  - name: Report a vulnerability privately
+    url: https://github.com/MiniMax-AI/minimax-code/blob/main/SECURITY.md
+    about: Follow the security reporting process. Do not disclose vulnerabilities or sensitive data in public issues.

+ 17 - 0
.github/ISSUE_TEMPLATE/docs.yml

@@ -0,0 +1,17 @@
+name: Documentation issue
+description: Report missing, incorrect, or unclear documentation.
+title: "[Docs] "
+body:
+  - type: input
+    id: location
+    attributes:
+      label: Documentation URL or path
+    validations:
+      required: true
+  - type: textarea
+    id: problem
+    attributes:
+      label: Problem and suggested improvement
+      description: Which step was unclear, or which command failed? Remove keys and account details.
+    validations:
+      required: true

+ 23 - 0
.github/PULL_REQUEST_TEMPLATE.md

@@ -0,0 +1,23 @@
+> Thanks for your interest in contributing. For now, code and documentation pull requests are accepted only from repository collaborators. If you are not a collaborator, please [open an issue](https://github.com/MiniMax-AI/minimax-code/issues/new/choose) so we can discuss your idea.
+
+## Change
+
+Describe the user-visible problem and resulting behavior. Link a public issue when applicable.
+
+## Validation
+
+- Checks run and results (include the revision/profile where relevant):
+- NOT RUN, platform limitations and live-service boundaries:
+
+## Publication and contribution checks
+
+- [ ] I have permission to contribute these changes under the existing licenses applicable to the changed files/packages; imported material and its provenance are identified and existing notices are preserved.
+- [ ] No credentials, account data, real user content, internal source history or private review material is included.
+- [ ] Added/removed source files were reviewed before regenerating `release/public-source.json`; new tests are declared in `test/vitest-suites.json` where applicable.
+- [ ] Shared English/Chinese documentation and capability/verification records are updated where applicable. Mock/offline results are not described as live-service acceptance.
+
+## Maintainer handoff
+
+Publication scope or license changes (if any):
+
+Shared-source port: not needed / pending / complete. Record public PR references only; keep private links and review material out of this PR.

+ 15 - 0
.github/actions/setup-gitleaks/action.yml

@@ -0,0 +1,15 @@
+name: Install reviewed Gitleaks
+description: Install the checksum-pinned Linux x64 scanner used by release audits.
+runs:
+  using: composite
+  steps:
+    - shell: bash
+      run: |
+        mkdir "$RUNNER_TEMP/gitleaks"
+        cd "$RUNNER_TEMP/gitleaks"
+        curl --fail --location --retry 3 --connect-timeout 15 --max-time 120 \
+          --output gitleaks.tar.gz \
+          https://github.com/gitleaks/gitleaks/releases/download/v8.24.3/gitleaks_8.24.3_linux_x64.tar.gz
+        echo '9991e0b2903da4c8f6122b5c3186448b927a5da4deef1fe45271c3793f4ee29c  gitleaks.tar.gz' | sha256sum --check --strict
+        tar -xzf gitleaks.tar.gz gitleaks
+        echo "$RUNNER_TEMP/gitleaks" >> "$GITHUB_PATH"

+ 26 - 0
.github/branch-protection.json

@@ -0,0 +1,26 @@
+{
+  "required_status_checks": {
+    "strict": true,
+    "checks": [
+      {
+        "context": "verification",
+        "app_id": 15368
+      },
+      {
+        "context": "source-history-artifact",
+        "app_id": 15368
+      }
+    ]
+  },
+  "enforce_admins": true,
+  "required_pull_request_reviews": {
+    "dismiss_stale_reviews": true,
+    "require_code_owner_reviews": false,
+    "required_approving_review_count": 1,
+    "require_last_push_approval": true
+  },
+  "restrictions": null,
+  "required_conversation_resolution": true,
+  "allow_force_pushes": false,
+  "allow_deletions": false
+}

+ 19 - 0
.github/dependabot.yml

@@ -0,0 +1,19 @@
+version: 2
+updates:
+  - package-ecosystem: github-actions
+    directory: /
+    schedule:
+      interval: weekly
+    groups:
+      actions:
+        patterns: ["*"]
+    open-pull-requests-limit: 3
+  - package-ecosystem: npm
+    directory: /
+    schedule:
+      interval: weekly
+    groups:
+      tooling-minor-patch:
+        dependency-type: development
+        update-types: [minor, patch]
+    open-pull-requests-limit: 3

+ 117 - 0
.github/workflows/ci.yml

@@ -0,0 +1,117 @@
+name: Source verification
+on:
+  push:
+    branches: [main]
+  pull_request:
+  workflow_dispatch:
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+permissions:
+  contents: read
+jobs:
+  changes:
+    runs-on: ubuntu-latest
+    timeout-minutes: 5
+    outputs:
+      docs_only: ${{ steps.scope.outputs.docs_only }}
+    steps:
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+        with:
+          fetch-depth: 0
+      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+        with:
+          node-version: "24"
+          package-manager-cache: false
+      - id: scope
+        run: node scripts/ci-changes.mjs
+  docs:
+    needs: changes
+    if: needs.changes.outputs.docs_only == 'true'
+    runs-on: ubuntu-latest
+    timeout-minutes: 10
+    steps:
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+      - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+        with:
+          node-version: "24"
+          cache: pnpm
+      - run: pnpm install --frozen-lockfile
+      - run: pnpm verify --profile docs
+        env:
+          MCODE_VERIFY_REPORT_DIR: ${{ runner.temp }}/verification
+      - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+        if: ${{ always() }}
+        with:
+          name: documentation-verification-${{ github.run_attempt }}
+          path: ${{ runner.temp }}/verification/
+          retention-days: 7
+  verify:
+    needs: changes
+    if: needs.changes.outputs.docs_only == 'false'
+    name: verify (${{ matrix.os }}, ${{ matrix.node }})
+    timeout-minutes: 15
+    strategy:
+      fail-fast: false
+      matrix:
+        os: [ubuntu-latest, macos-latest, windows-latest]
+        node: ["24"]
+        include:
+          - os: ubuntu-latest
+            node: "24"
+            profile: full
+    runs-on: ${{ matrix.os }}
+    steps:
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+      - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+        with:
+          version: 9.12.0
+      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+        with:
+          node-version: ${{ matrix.node }}
+          cache: pnpm
+      - run: pnpm install --frozen-lockfile
+      # Keep the gate list in the shared verifier. Every OS builds and tests its
+      # own native artifacts; only the duplicate compiler check is omitted.
+      - run: pnpm verify --profile ${{ matrix.profile || 'platform' }}
+        env:
+          MCODE_VERIFY_REPORT_DIR: ${{ runner.temp }}/verification
+      - name: Upload verification summary
+        if: ${{ always() }}
+        timeout-minutes: 2
+        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+        with:
+          name: verification-${{ matrix.os }}-node-${{ matrix.node }}-${{ github.run_attempt }}
+          path: |
+            ${{ runner.temp }}/verification/verification.json
+            ${{ runner.temp }}/verification/verification.md
+            ${{ runner.temp }}/verification/export.json
+          retention-days: 7
+          if-no-files-found: warn
+
+  verification:
+    name: verification
+    if: ${{ always() }}
+    needs: [changes, docs, verify]
+    runs-on: ubuntu-latest
+    timeout-minutes: 2
+    steps:
+      - name: Require every planned check
+        env:
+          CLASSIFICATION: ${{ needs.changes.result }}
+          DOCS_ONLY: ${{ needs.changes.outputs.docs_only }}
+          DOCS_RESULT: ${{ needs.docs.result }}
+          MATRIX_RESULT: ${{ needs.verify.result }}
+        shell: bash
+        run: |
+          test "$CLASSIFICATION" = success
+          if [ "$DOCS_ONLY" = true ]; then
+            test "$DOCS_RESULT" = success
+            test "$MATRIX_RESULT" = skipped
+          elif [ "$DOCS_ONLY" = false ]; then
+            test "$MATRIX_RESULT" = success
+            test "$DOCS_RESULT" = skipped
+          else
+            exit 1
+          fi

+ 42 - 0
.github/workflows/compatibility.yml

@@ -0,0 +1,42 @@
+name: Node compatibility
+on:
+  schedule:
+    - cron: "23 3 * * 1"
+  workflow_dispatch:
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+permissions:
+  contents: read
+jobs:
+  compatibility:
+    name: compatibility (${{ matrix.os }}, ${{ matrix.node }})
+    runs-on: ${{ matrix.os }}
+    timeout-minutes: 15
+    strategy:
+      fail-fast: false
+      matrix:
+        os: [ubuntu-latest, macos-latest, windows-latest]
+        node: ["22.19.0", "24.2.0", "25", "26"]
+        include:
+          - os: ubuntu-latest
+            node: "22.19.0"
+            profile: full
+    steps:
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+      - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+        with:
+          node-version: ${{ matrix.node }}
+          cache: pnpm
+      - run: pnpm install --frozen-lockfile
+      - run: pnpm verify --profile ${{ matrix.profile || 'platform' }}
+        env:
+          MCODE_VERIFY_REPORT_DIR: ${{ runner.temp }}/verification
+      - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+        if: ${{ always() }}
+        timeout-minutes: 2
+        with:
+          name: compatibility-${{ matrix.os }}-node-${{ matrix.node }}-${{ github.run_attempt }}
+          path: ${{ runner.temp }}/verification/
+          retention-days: 7

+ 45 - 0
.github/workflows/security.yml

@@ -0,0 +1,45 @@
+name: Release audit
+on:
+  push:
+    branches: [main]
+  pull_request:
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+permissions:
+  contents: read
+jobs:
+  source-history-artifact:
+    runs-on: ubuntu-latest
+    timeout-minutes: 10
+    steps:
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+        with:
+          fetch-depth: 0
+      - uses: ./.github/actions/setup-gitleaks
+      - name: Classify change
+        id: changes
+        run: node scripts/ci-changes.mjs
+      - name: Scan complete history and source snapshot
+        shell: bash
+        run: |
+          gitleaks git --redact --config .gitleaks.toml --log-opts=--all
+          mkdir "$RUNNER_TEMP/source-audit"
+          git archive HEAD | tar -x -C "$RUNNER_TEMP/source-audit"
+          gitleaks dir "$RUNNER_TEMP/source-audit" --redact --config .gitleaks.toml
+      - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+        if: steps.changes.outputs.docs_only != 'true'
+        with:
+          version: 9.12.0
+      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+        if: steps.changes.outputs.docs_only != 'true'
+        with:
+          node-version: "22"
+          cache: pnpm
+      - run: pnpm install --frozen-lockfile
+        if: steps.changes.outputs.docs_only != 'true'
+      - run: pnpm build
+        if: steps.changes.outputs.docs_only != 'true'
+      - name: Scan built distribution
+        if: steps.changes.outputs.docs_only != 'true'
+        run: gitleaks dir dist --redact --config .gitleaks.toml

+ 136 - 0
.github/workflows/source-candidate.yml

@@ -0,0 +1,136 @@
+name: Source candidate
+on:
+  workflow_dispatch:
+  workflow_call:
+    inputs:
+      revision:
+        type: string
+        required: true
+env:
+  MCODE_CANDIDATE_REVISION: ${{ inputs.revision || github.sha }}
+concurrency:
+  group: ${{ github.workflow }}-${{ inputs.revision || github.sha }}
+  cancel-in-progress: false
+permissions:
+  contents: read
+jobs:
+  export:
+    runs-on: ubuntu-latest
+    timeout-minutes: 10
+    steps:
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+        with:
+          ref: ${{ env.MCODE_CANDIDATE_REVISION }}
+          fetch-depth: 0
+      - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+        with:
+          node-version: "24"
+          cache: pnpm
+      - run: pnpm install --frozen-lockfile
+      - name: Export committed source
+        shell: bash
+        run: |
+          mkdir "$RUNNER_TEMP/candidate"
+          node scripts/export-source-preview.mjs --out "$RUNNER_TEMP/candidate/minimax-code-source.tar.gz"
+          node scripts/source-candidate.mjs unpack --archive "$RUNNER_TEMP/candidate/minimax-code-source.tar.gz" --revision "$REVISION" --destination "$RUNNER_TEMP/source-audit"
+        env:
+          REVISION: ${{ env.MCODE_CANDIDATE_REVISION }}
+      - uses: ./.github/actions/setup-gitleaks
+      - name: Scan history and the exact exported source
+        shell: bash
+        run: |
+          gitleaks git --redact --config .gitleaks.toml --log-opts=--all
+          gitleaks dir "$RUNNER_TEMP/source-audit" --redact --config .gitleaks.toml
+      - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+        with:
+          name: unverified-source-${{ env.MCODE_CANDIDATE_REVISION }}
+          path: ${{ runner.temp }}/candidate/
+          retention-days: 1
+          overwrite: true
+          if-no-files-found: error
+  validate:
+    needs: export
+    runs-on: ${{ matrix.os }}
+    timeout-minutes: 20
+    strategy:
+      fail-fast: false
+      matrix:
+        os: [ubuntu-latest, macos-latest, windows-latest]
+    steps:
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+        with:
+          ref: ${{ env.MCODE_CANDIDATE_REVISION }}
+      - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+        with:
+          node-version: "24"
+          cache: pnpm
+      - run: pnpm install --frozen-lockfile
+      - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
+        with:
+          name: unverified-source-${{ env.MCODE_CANDIDATE_REVISION }}
+          path: ${{ runner.temp }}/candidate
+      - name: Authenticate and unpack into a fresh directory
+        shell: bash
+        run: node scripts/source-candidate.mjs unpack --archive "$RUNNER_TEMP/candidate/minimax-code-source.tar.gz" --revision "$REVISION" --destination "$RUNNER_TEMP/candidate-source"
+        env:
+          REVISION: ${{ env.MCODE_CANDIDATE_REVISION }}
+      - name: Cold install from the exported source
+        working-directory: ${{ runner.temp }}/candidate-source/minimax-code
+        shell: bash
+        run: pnpm install --frozen-lockfile --store-dir "$RUNNER_TEMP/candidate-store" --registry https://registry.npmjs.org/
+      - name: Verify the exported source
+        working-directory: ${{ runner.temp }}/candidate-source/minimax-code
+        run: pnpm verify --profile archive
+        env:
+          MCODE_VERIFY_REPORT_DIR: ${{ runner.temp }}/candidate-report
+          MCODE_VERIFY_REVISION: ${{ env.MCODE_CANDIDATE_REVISION }}
+      - uses: ./.github/actions/setup-gitleaks
+        if: runner.os == 'Linux'
+      - name: Scan the candidate Linux distribution
+        if: runner.os == 'Linux'
+        shell: bash
+        run: gitleaks dir "$RUNNER_TEMP/candidate-source/minimax-code/dist" --redact --config .gitleaks.toml
+      - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+        if: ${{ always() }}
+        timeout-minutes: 2
+        with:
+          name: candidate-validation-${{ matrix.os }}
+          path: ${{ runner.temp }}/candidate-report/
+          retention-days: 14
+          overwrite: true
+  publish:
+    needs: [export, validate]
+    runs-on: ubuntu-latest
+    timeout-minutes: 10
+    steps:
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+        with:
+          ref: ${{ env.MCODE_CANDIDATE_REVISION }}
+      - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+        with:
+          node-version: "24"
+          cache: pnpm
+      - run: pnpm install --frozen-lockfile
+      - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
+        with:
+          name: unverified-source-${{ env.MCODE_CANDIDATE_REVISION }}
+          path: ${{ runner.temp }}/candidate
+      - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
+        with:
+          pattern: candidate-validation-*
+          path: ${{ runner.temp }}/candidate/reports
+      - name: Require three matching validation reports
+        shell: bash
+        run: node scripts/source-candidate.mjs finalize --archive "$RUNNER_TEMP/candidate/minimax-code-source.tar.gz" --revision "$REVISION" --reports "$RUNNER_TEMP/candidate/reports"
+        env:
+          REVISION: ${{ env.MCODE_CANDIDATE_REVISION }}
+      - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+        with:
+          name: source-candidate-${{ env.MCODE_CANDIDATE_REVISION }}
+          path: ${{ runner.temp }}/candidate/
+          retention-days: 14
+          overwrite: true
+          if-no-files-found: error

+ 2 - 1
.github/workflows/sync-issue-to-feishu.yml

@@ -13,7 +13,8 @@ jobs:
     name: Notify Feishu
     runs-on: ubuntu-latest
     timeout-minutes: 5
-    if: ${{ !github.event.issue.pull_request }}
+    # Preserve the public support integration without forwarding private review issues.
+    if: ${{ github.repository == 'MiniMax-AI/minimax-code' && github.event.repository.private == false && !github.event.issue.pull_request }}
     env:
       FEISHU_BOT_WEBHOOK: ${{ secrets.FEISHU_BOT_WEBHOOK }}
       FEISHU_BOT_SECRET: ${{ secrets.FEISHU_BOT_SECRET }}

+ 10 - 0
.gitignore

@@ -0,0 +1,10 @@
+node_modules/
+dist/
+.turbo/
+.cache/
+.pnpm-store/
+*.tsbuildinfo
+.env
+.env.*
+!.env.example
+.DS_Store

+ 62 - 0
.gitleaks.toml

@@ -0,0 +1,62 @@
+title = "MiniMax Code source and history scanning"
+[extend]
+useDefault = true
+
+[[rules]]
+id = "generic-api-key"
+
+[[rules.allowlists]]
+description = "Permission translation key, not a credential"
+condition = "AND"
+paths = ['''(^|/)packages/agent-modules/permission/src/tools/bash-checker\.ts$''']
+regexTarget = "match"
+regexes = ['''^labelKey: 'permission\.scope\.byArgvPrefix2'$''']
+
+[[rules.allowlists]]
+description = "Documented keyboard shortcut"
+condition = "AND"
+paths = ['''(^|/)(packages/local-runtime|dist)/assets/skills/cu-desktop/SKILL\.md$''']
+regexTarget = "match"
+regexes = ['''^desktop_key combo="ctrl\+shift\+Escape"$''']
+
+[[rules.allowlists]]
+description = "Pagination example ends with explicit xxxx placeholder"
+condition = "AND"
+paths = ['''(^|/)(packages/local-runtime|dist)/assets/skills/lark-tools/cli-skills/lark-im/references/lark-im-reactions\.md$''']
+regexTarget = "match"
+regexes = ['''^page_token": "YhljsPiGfUgnVAg9urvRFd-BvSqRLxxxx"$''']
+
+[[rules.allowlists]]
+description = "PDF form field identifier, not an API key"
+condition = "AND"
+paths = ['''(^|/)(packages/local-runtime|dist)/assets/skills/pdf/templates/form-fill-acroform/cases/italy-schengen-visa-(zhangwei|example)/field_values\.case\.json$''']
+regexTarget = "match"
+regexes = ['''^key": "p1-place-of-birth"$''']
+
+[[rules.allowlists]]
+description = "TUI next-prompt keyboard shortcut"
+condition = "AND"
+paths = ['''(^|/)packages/tui/src/tui/engine/keybindings\.ts$''']
+regexTarget = "match"
+regexes = ['''^defaultKeys: "ctrl\+shift\+down"$''']
+
+[[rules.allowlists]]
+description = "Bundled TUI shortcut and permission translation key"
+condition = "AND"
+paths = ['''(^|/)dist/chunks/(chunk|launcher)-[A-Z0-9]+\.js$''']
+regexTarget = "match"
+regexes = ['''^defaultKeys: "ctrl\+shift\+down"$''', '''^labelKey: "permission\.scope\.byArgvPrefix2"$''']
+
+[[rules.allowlists]]
+description = "node-forge PKCS12 function alias, no key material"
+condition = "AND"
+paths = ['''(^|/)dist/chunks/chunk-[A-Z0-9]+\.js$''']
+regexTarget = "match"
+regexes = ['''^[A-Za-z_$][A-Za-z0-9_$]*\.generateKey = [A-Za-z_$][A-Za-z0-9_$]*\.pbe\.generatePkcs12Key;?$''']
+
+[[rules.allowlists]]
+description = "Exact synthetic privacy regression marker, including historical commits"
+condition = "AND"
+paths = ['''(^|/)packages/local-runtime/test/unit/error-reporting-privacy\.test\.ts$''']
+regexTarget = "match"
+regexes = ['''^SECRET = 'SYNTHETIC_PRIVATE_4cd7'$''']

+ 2 - 0
.npmrc

@@ -0,0 +1,2 @@
+registry=https://registry.npmjs.org/
+node-linker=hoisted

+ 53 - 0
AGENTS.md

@@ -0,0 +1,53 @@
+# Agent guide
+
+This repository is the reviewed public projection of an internal monorepo, not an ordinary workspace. Every published file is listed in `release/public-source.json`, and upstream changes arrive through a three-way merge described in `docs/source-sync.md`. Moving or renaming files therefore has a cost that a normal repository does not have: it shows up as a conflict or an unreviewed new file at the next synchronization. Prefer changing content over changing layout.
+
+## Layout
+
+- `packages/` — first-party workspace packages. `packages/agent-modules/*` is a second level of packages, not a package itself.
+- `third_party/` — vendored upstream packages (`pi-mono`, `sandbox-runtime`) with their own licenses. Their test suites are not part of this distribution's verification.
+- `release/` — machine-read release contracts. `extraction.json` pins the source baseline and package scope, `public-source.json` is the file inventory, `dependency-licenses.json` records declared dependency licenses. Build, type-check, test resolution, and source checks all read from here.
+- `docs/` — human-read documentation only.
+- `scripts/` — build and verification tooling. Shared constants live in `scripts/lib/`; import them instead of repeating literal paths or lists.
+- `test/` — repository-level tests and `vitest-suites.json`, the declaration of every Vitest file this distribution runs.
+
+## Generated files
+
+Do not edit these by hand; regenerate them and commit the result.
+
+| File | Regenerate with | Checked by |
+| --- | --- | --- |
+| `release/public-source.json` | `node scripts/source-inventory.mjs --write` | `pnpm check:source` |
+| `tsconfig.standalone.json` (the `paths` block) | `pnpm gen:tsconfig` | `pnpm check:tsconfig` |
+
+Review what changed before regenerating the inventory: recording a file does not make it suitable for publication.
+
+## Single sources of truth
+
+| Concern | Declared in | Consumed by |
+| --- | --- | --- |
+| Package scope | `release/extraction.json` (`packageRoots`) | build, type-check paths, Vitest aliases, source check, source sync |
+| Package export → source file | each package's `exports` via `scripts/lib/package-exports.mjs` | `tsconfig.standalone.json`, `vitest.oss.config.mjs` |
+| Test files per gate | `test/vitest-suites.json` | `vitest.oss.config.mjs`, `scripts/run-vitest-suite.mjs` |
+| Retired source paths | `scripts/lib/retired-sources.mjs` | `check:source` (must not exist), `check:standalone` (must not be bundled) |
+| Verification pipeline | `scripts/verify.mjs` | GitHub CI, `pnpm verify` |
+| Documentation-only classification | `scripts/ci-changes.mjs` | source verification, release audit |
+| Source archive validation/extraction | `scripts/lib/source-archive.mjs` | source export, candidate validation |
+
+## Common changes
+
+Adding a workspace package: add it to `pnpm-workspace.yaml` and to `packageRoots` in `release/extraction.json`, then run `pnpm gen:tsconfig` and `node scripts/source-inventory.mjs --write`.
+
+Adding a test file: add its path to the appropriate group in `test/vitest-suites.json`. Do not add paths to `package.json` scripts or the Vitest config.
+
+Adding a verification gate: add a step to `scripts/verify.mjs`, with `platforms` when it cannot run everywhere. Do not add steps to the workflow file.
+
+## Verification
+
+`pnpm verify` runs the same gates as CI in the same order; `pnpm verify --list` shows which apply on the current platform. Run it before opening a pull request. Individual gates such as `pnpm typecheck`, `pnpm build`, and `pnpm test:byok` remain available for iteration.
+
+The full profile is the local default. `platform` omits only duplicate type checking; `docs` runs the source/export gates for documentation-only changes; `archive` validates an authenticated source candidate without attempting a Git export. Keep profile selection in the shared verifier. Add workflow safety and release-tool regressions to the existing `test/source-sync.test.mjs` suite.
+
+## Boundaries
+
+Do not reference internal hosts, generated IDL, or private services; `check:source` rejects them. Do not restore paths listed in `scripts/lib/retired-sources.mjs`. Do not commit account data, sessions, logs, or credentials. Documentation and commit messages are written in English; see `CONTRIBUTING.md`.

+ 52 - 0
CONTRIBUTING.md

@@ -0,0 +1,52 @@
+# Contributing
+
+This repository contains the standalone MiniMax Code TUI, headless CLI, and ACP source. Start with the [architecture](docs/architecture.md), [capability coverage](docs/tui-capabilities.md), and [installation guide](docs/installation.md).
+
+Thanks for your interest in contributing. For now, we only accept code and documentation contributions from repository collaborators. If you are not a collaborator but have an idea or proposal, please [open an issue](https://github.com/MiniMax-AI/minimax-code/issues/new/choose) so we can discuss it.
+
+Repository collaborators should submit pull requests from feature branches; do not push directly to the default branch. Describe user-visible changes, checks you ran, live-service or platform validation you did not run, and documentation impact. Preserve real author identities and existing copyright notices.
+
+## Maintainers and review
+
+See [Maintainers](docs/maintainers.md) for review ownership, independent approval, security/release routing and the public-to-internal contribution flow. The [PR template](.github/PULL_REQUEST_TEMPLATE.md) records checks, untested boundaries and permission to contribute under the existing applicable licenses. CODEOWNERS routes reviews; required checks and approvals must also be enabled in repository settings.
+
+## Documentation language
+
+English is the primary language for project documentation, examples, issue templates, and contributor guidance. Write new documentation and commit messages in English. Keep `README.md` in English and `README_ZH.md` as its Simplified Chinese translation, with reciprocal language links. `README.zh-CN.md` preserves the existing public repository URL and links to the canonical Chinese README; do not duplicate the full translation there. Update both when their shared content changes. Additional translations are optional and must be clearly labeled and linked from the English source.
+
+Preserve original third-party license text. Localized product strings, multilingual examples, and bundled runtime prompts / skill resources retain the languages required by their behavior; changing them is a runtime-content change, not a documentation translation.
+
+## Local validation
+
+```bash
+pnpm install --frozen-lockfile
+pnpm verify
+```
+
+`pnpm verify` runs the complete gate list in the same order as GitHub CI. Normal PR and main-branch checks use Node.js 24 on Linux, macOS and Windows. The Linux job runs this full profile; the other two platforms use `pnpm verify --profile platform`, which omits only the duplicate TypeScript compiler check. All three jobs still export source, build, and test their own platform artifacts. Gates that depend on platform behaviour are selected by platform rather than skipped silently; run `pnpm verify --list` or `pnpm verify --profile platform --list` to inspect either plan. Individual gates remain available as their own scripts, such as `pnpm typecheck` or `pnpm test:byok`, while you iterate.
+
+CI writes per-gate timing and exit metadata to the Job Summary and a seven-day `verification-<os>-node-<version>-<attempt>` artifact. For a local report, set `MCODE_VERIFY_REPORT_DIR` to a directory outside the repository. Reports distinguish `PASS`, `FAIL`, intentional `SKIP`, and `NOT_RUN` after a failure. JSON is checkpointed before and after each gate; a cancelled run may leave `RUNNING`, which is not a pass. If installation fails before verification starts, no verification report is available. Reports do not collect command output, environment variables, or runtime data; read the corresponding gate's job log for failure details, including the existing bounded BYOK timeout diagnostics. CI jobs have a 15-minute verification limit and a 10-minute release-audit limit.
+
+Existing README files, `CONTRIBUTING.md`, `.github/PULL_REQUEST_TEMPLATE.md`, Markdown under `docs/`, and media directly under `docs/assets/` use the `docs` profile when they are the only changed paths. That profile checks the source inventory and generated paths, exports the committed source, and tests release tooling. History and source-snapshot secret scans still run; platform builds and distribution scans are skipped. Mixed changes, unknown paths, missing comparisons, and any `release/` inventory change get full CI. Documentation-only changes skip the platform matrix entirely. The `verification` aggregate check always runs and rejects failed, cancelled, or unexpectedly skipped jobs. Use it together with `source-history-artifact` as required checks when configuring branch protection; this repository's automation does not change administrative settings.
+
+`Node compatibility` runs weekly and on demand against macOS, Linux and Windows with Node 22.19.0, 24.2.0, 25 and 26. It does not run automatically on PRs. Dispatch it on the selected branch for changes to supported Node versions, native dependencies or compatibility-sensitive verification tooling, and before a source release. This covers the minimum versions of the two supported ranges and the additional supported majors. Deferring those versions from ordinary PR checks can delay regression discovery; a known failure in a supported version still needs resolution before release. Dependabot proposes weekly Actions and npm updates, grouping Actions and development-tool minor/patch updates. External Actions use reviewed full commit SHAs, while local actions and reusable workflows come from the same checked-out revision.
+
+Source candidates are requested independently through the `Source candidate` workflow; ordinary PRs and main pushes do not produce them. Its three-platform archive validation is described in [Releasing](docs/releasing.md). Product npm and installer publication remains a separate release process.
+
+Source export reports separate archive creation, extraction, inventory validation, hashing, and cleanup timings in `export.json`. Windows uses native `tar` after complete archive preflight; other systems use the Node extractor. The preflight rejects traversal, links, duplicate entries and Git metadata before writing files. A machine without native `tar` falls back to Node. Set `MCODE_SOURCE_EXTRACTOR=node` or `native` when comparing extractors locally.
+
+Test files are declared in `test/vitest-suites.json`, grouped by the gate that runs them. Add a test file there instead of adding a path to `package.json` or to the Vitest config. Do not describe protocol fixtures or offline tests as live-model acceptance.
+
+`tsconfig.standalone.json` path mappings are generated from the package scope in `release/extraction.json` and each package's `exports`. After adding a package or an export subpath, run `pnpm gen:tsconfig`; `pnpm check:tsconfig` fails when the committed mapping has drifted.
+
+Review added or removed files before running `node scripts/source-inventory.mjs --write`. Updating the inventory must not bypass checks for private protocols, internal addresses, credentials, or third-party licensing. Before publication, also scan the complete Git history with Gitleaks; see the [release process](docs/releasing.md).
+
+## Capability boundaries
+
+Preserve MiniMax OAuth, Token Plan, BYOK, mcode-tools, search, plugins, connectors, updates, and feedback. Do not solve standalone-build problems by removing capabilities. Managed services use public clients; internal HTTP services, generated IDL, and cloud executor implementations are outside this repository.
+
+Do not commit account data, logs, sessions, API keys, or real user content. Use temporary data directories and synthetic inputs for tests. Do not attach unredacted diagnostic bundles to issues; follow the [security reporting process](SECURITY.md).
+
+## Synchronizing with the source repository
+
+The internal product repository remains the source of shared implementation. This repository maintains standalone distribution adaptations and a reviewed public projection. Use the [source synchronization process](docs/source-sync.md) to generate candidates, review them, validate changes, and submit a PR. Never merge internal Git history. Changes should land through pull requests before maintainers port them back internally; subsequent synchronization must preserve public adaptations.

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 MiniMax Code
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 21 - 0
LICENSE-STATUS.md

@@ -0,0 +1,21 @@
+# License status
+
+The default license for first-party code is [MIT](LICENSE), including the root workspace and first-party package manifests. The root `LICENSE` and `NOTICE` use the maintainer-supplied attribution **MiniMax Code**. Existing third-party and file-level declarations take precedence for those materials; this change does not relicense upstream code, dependencies or assets.
+
+## Third-party exceptions
+
+- `third_party/sandbox-runtime` remains **Apache-2.0**, including its retained upstream copyright and modification notices. Its `LICENSE` must accompany distributions containing that component; retain any applicable upstream notices.
+- Pi, derived terminal code, the model catalog and bundled assets retain their original declarations. See [Third-party notices](THIRD_PARTY_NOTICES.md) and the relevant file/package notices.
+- `release/dependency-licenses.json` records dependencies' declared licenses without changing their terms. Binary or installer distributions must retain applicable license texts and notices, including those for bundled native dependencies.
+
+The root MIT license is not a statement that every file or bundled component is MIT-licensed.
+
+## Publication decision
+
+The proposed material scope and rights-holder decision are tracked in [Publication authorization](docs/publication-authorization.md). Preparing the MIT change does not mark the exact source candidate, brand assets, npm publication or private Git history as approved for publication. That record remains **PENDING**.
+
+## Attribution history
+
+On 2026-09-12, review found that the original root license had been copied from Sandbox Runtime and contained Anthropic's attribution. It was corrected to the standard Apache-2.0 text; the subsequently supplied first-party attribution was recorded in `NOTICE`. The first-party default now changes to MIT using that same attribution. Sandbox Runtime's original Apache-2.0 license and copyright remain unchanged.
+
+The source gate pins the reviewed MIT license hash so a vendor-specific license cannot silently replace the root license during source synchronization.

+ 6 - 0
NOTICE

@@ -0,0 +1,6 @@
+MiniMax Code
+Copyright 2026 MiniMax Code
+
+This first-party project attribution does not replace existing file-level or
+package-level licenses, third-party copyright notices, or upstream attributions.
+See LICENSE-STATUS.md and THIRD_PARTY_NOTICES.md for the applicable declarations.

+ 186 - 28
README.md

@@ -1,46 +1,204 @@
-<div align="center">
+<p align="center">
+  <picture>
+    <source media="(prefers-color-scheme: dark)" srcset="docs/assets/wordmark-dark.svg">
+    <source media="(prefers-color-scheme: light)" srcset="docs/assets/wordmark-light.svg">
+    <img src="docs/assets/wordmark-light.svg" alt="MiniMax Code" width="760">
+  </picture>
+</p>
 
-<img src="https://filecdn.minimax.chat/public/c3ebbd2e-f55b-48d7-adff-030abb63e06d.png" alt="MiniMax Code" width="100%" />
+<h1 align="center">MiniMax Code</h1>
+<p align="center">A terminal coding agent with MiniMax, your own models, and tools beyond code.</p>
+<p align="center">
+  <a href="#quick-start">Get started</a> ·
+  <a href="docs/README.md">Documentation</a> ·
+  <a href="docs/examples.md">Examples</a> ·
+  <a href="CONTRIBUTING.md">Contributing</a>
+</p>
+<p align="center"><strong>English</strong> · <a href="README_ZH.md">简体中文</a></p>
+<p align="center">
+  <img src="docs/assets/source-preview.svg" alt="Source preview">
+  <img src="docs/assets/node.svg" alt="CI: Node.js 22 and 24">
+  <a href="LICENSE-STATUS.md"><img src="docs/assets/license.svg" alt="First-party default license: MIT"></a>
+</p>
 
-# MiniMax Code
+Understand a project, make changes, and run tests from your terminal. Use your MiniMax account or bring your own model, with search, plugins, and multimodal tools in the same workflow.
 
-**Remembers your habits, builds Agent teams, automates the repetitive work.**
+[![Real MiniMax Code TUI output: fixing clamp, inspecting the diff, and running tests](docs/assets/tui-demo.png)](docs/demo.md)
 
-[Download for macOS](https://agent.minimax.io/download) · [Download for Windows](https://agent.minimax.io/download) · [Submit an Issue](../../issues/new/choose)
+<p align="center"><a href="docs/demo.md">Watch the 20-second demo →</a> · Real terminal output, with pauses shortened</p>
 
-[简体中文](./README.zh-CN.md)
+## Quick start
 
-</div>
+### 1. Install MCode
 
----
+Use the official installer for your platform. It installs the latest CLI, prepares a compatible Node.js runtime when needed, and does not require `sudo` or administrator privileges. Alpine / musl Linux is not supported by the one-command installer.
 
-## Report an Issue
+**macOS / Linux / WSL**
 
-This repository collects issue reports for the MiniMax Code desktop app.
+```bash
+curl -fsSL https://filecdn.minimax.chat/public/install.sh | bash
+```
 
-> For bug reports, please upload logs from **Settings → General → Upload logs** and include the generated upload ID.
+**Windows (PowerShell)**
 
-### How to submit
+```powershell
+irm https://filecdn.minimax.chat/public/install.ps1 | iex
+```
 
-1. Tap **Issues** → **New issue** at the top right
-2. Pick a template (Bug / Feature / Question)
-3. Fill in the requested details:
-   - **Version** — found in Settings
-   - **Platform** — macOS / Windows
-   - **Upload ID** — found after uploading logs from Settings → General
-   - **Steps to reproduce** — short and reproducible
-   - **Screenshots or logs** — optional but appreciated
+**npm** — if you already have **Node.js 22.19+ (22.x), 24.2+ (24.x), 25, or 26**:
 
-### Before you submit
+```bash
+npm install -g @minimax-ai/code@latest --registry=https://registry.npmjs.org/ --ignore-scripts=false --include=optional --allow-scripts=@minimax-ai/code,better-sqlite3
+```
 
-- Search to see if the issue already exists
-- Make sure you are on the latest version
-- Strip out any sensitive information (API keys, tokens, etc.)
+The npm command uses the public registry, includes the optional SQLite dependency, and permits the package and SQLite installation scripts. See the [installation guide](docs/installation.md) for version pinning and Node.js compatibility.
 
----
+Reopen your terminal and check the installation:
 
-<div align="center">
+```bash
+mcode --version
+mcode --help
+```
 
-© 2026 MiniMax. All rights reserved.
+See the official [quick start](https://agent.minimax.io/docs/cli/quick-start), [features](https://agent.minimax.io/docs/cli/features), and [troubleshooting](https://agent.minimax.io/docs/cli/faq).
 
-</div>
+### 2. Sign in or bring your own API key
+
+For a mainland China account:
+
+```bash
+mcode login
+```
+
+For a Global account:
+
+```bash
+mcode login --region global
+```
+
+Complete sign-in in your browser, then open `mcode` and use `/status` to check your account and `/provider` to choose a model. Run `mcode logout` to sign out.
+
+Token Plan requires an account with available credits. User data is stored in `~/.minimax-code` by default.
+
+<details>
+<summary>Use your own API key (BYOK)</summary>
+
+BYOK does not require a MiniMax login. Set `MCODE_PROVIDER_API_KEY` in your current shell, then add a provider. Replace the example URL and model name with your provider's values:
+
+```bash
+mcode provider add --name my-provider --base-url https://example.com/v1 \
+  --api-format openai-completions --model my-model \
+  --api-key-env MCODE_PROVIDER_API_KEY --use
+mcode
+```
+
+Supported API formats: `openai-completions`, `openai-responses`, and `anthropic-messages`. See the [model examples](docs/examples.md#2-choose-your-own-model) for environment variable setup, connection checks, and model overrides for a single run.
+
+</details>
+
+### 3. Run your first task
+
+Open the project you want to work on:
+
+```bash
+cd /path/to/your/project
+mcode
+```
+
+Describe your task in the TUI, or submit it directly when you launch MCode:
+
+```bash
+mcode "Find a failing test, fix the implementation, and run the relevant tests."
+```
+
+Use `mcode init .` to generate or update project guidance in `AGENTS.md`. Describe the expected result, allowed changes, and how to verify the task.
+
+| Entry point | Command | Use it for |
+| --- | --- | --- |
+| Interactive TUI | `mcode [prompt]` | Explore code, continue a conversation, and review changes or permissions. |
+| Headless | `mcode exec [prompt]` | Shell scripts, CI, batch work, and evaluations. |
+| ACP | `mcode acp` | Editors and clients supporting Agent Client Protocol. |
+
+### Continue your work
+
+```bash
+# Resume the latest session in the current workspace
+mcode --continue
+
+# Open the session picker
+mcode --session
+```
+
+Inside the TUI, use `/sessions` to find previous sessions and `/help` to see all commands and shortcuts.
+
+| Action | Shortcut |
+| --- | --- |
+| Send a message or steer the running task | `Enter` |
+| Queue a follow-up while a task is running | `Alt+Enter` |
+| Insert a newline | `Shift+Enter` |
+| Reference a workspace file or directory | `@` |
+| Toggle Plan Mode | `Shift+Tab` |
+| Switch permission modes | `Alt+M` |
+| Close a panel or interrupt a running task | `Esc` |
+
+## What you can do
+
+| Task | Capabilities |
+| --- | --- |
+| **Edit and verify code** | Read files, inspect diffs, run shell commands and tests, and control tool execution with permissions and sandboxing. |
+| **Choose your model** | Use a MiniMax account / Token Plan, or custom providers with OpenAI- or Anthropic-compatible API formats. |
+| **Search and work with media** | Use built-in search, `mcode-tools` media tools, MCP, and managed connectors, subject to account access and service credits. |
+| **Keep work moving** | Resume sessions, plan tasks, use subagents, and extend the agent with official, local, or GitHub plugins and built-in skills. |
+| **Connect your workflow** | Run scripted tasks with the headless CLI, or connect compatible editors and clients through ACP. |
+
+Account features, updates, feedback, and diagnostics are also included. Managed tools require network access and the relevant authorization. See [capabilities and service boundaries](docs/tui-capabilities.md) for details.
+
+## Try it
+
+Start the TUI in a copy of the example project and enter:
+
+> Read clamp.mjs and clamp.test.mjs. Run node --test to reproduce the failure, fix clamp without changing the tests, then run the tests again.
+
+The [small, reproducible project](examples/clamp) is the same task used in the demo above. [More examples](docs/examples.md) cover switching models, calling real search, and using your own image inputs.
+
+## Build from source
+
+To develop MCode or run this source checkout, you need Git, **Node.js 22.19+ (22.x) or 24.2+ (24.x)**, and **pnpm 9.12.0**.
+
+```bash
+git clone https://github.com/MiniMax-AI/minimax-code.git
+cd minimax-code
+pnpm install --frozen-lockfile
+pnpm build
+pnpm mcode
+```
+
+The first build requires an internet connection. Dependencies and the integrity-checked `mcode-tools` bundle come from public npm. See the [source installation guide](docs/installation.md) for pnpm setup, system dependencies, and updates.
+
+From the source directory, use `pnpm mcode` in place of `mcode` in the examples above. To work on your own project, open its directory and launch the built CLI:
+
+```bash
+node /absolute/path/to/minimax-code/dist/cli.js
+```
+
+This repository targets the **0.4.12 source preview**. Installing the published package and building this checkout are separate paths. Matching versions do not prove identical build provenance; see the [version and evidence baseline](docs/open-source-status.md#version-and-evidence-baseline).
+
+## Documentation and contributing
+
+- [Installation and updates](docs/installation.md) · [Examples](docs/examples.md) · [TUI status line](packages/tui/docs/status-line-config.md)
+- [Contributor guide](CONTRIBUTING.md) · [Report a bug or propose an idea](https://github.com/MiniMax-AI/minimax-code/issues/new/choose) · [Report a security issue](SECURITY.md)
+- [All documentation](docs/README.md): architecture, capability coverage, verification records, source synchronization, and release preparation.
+
+English is the primary documentation language. The [Chinese README](README_ZH.md) mirrors this page.
+
+For now, code and documentation pull requests are accepted only from repository collaborators. If you are not a collaborator but have an idea or proposal, please [open an issue](https://github.com/MiniMax-AI/minimax-code/issues/new/choose) so we can discuss it. Remove secrets, account details, and private project content from reports.
+
+## Desktop app and support
+
+[Download for macOS or Windows](https://agent.minimax.io/download) · [Report a problem or ask a question](https://github.com/MiniMax-AI/minimax-code/issues/new/choose)
+
+This repository also hosts issue reporting for the MiniMax Code desktop app. The published source covers the terminal TUI, headless CLI, and ACP; it does not include the desktop application's source. Select the affected product when filing an issue. For a desktop bug, include the app version, operating system, and a log upload ID if available from **Settings → General → Upload logs**. For a CLI bug, include `mcode --version`, your interface, and a minimal reproduction. Remove credentials and private project content from reports.
+
+## License
+
+First-party code defaults to [MIT](LICENSE). Existing file-level and package-level licenses remain in place. See [third-party notices](THIRD_PARTY_NOTICES.md) and [license status](LICENSE-STATUS.md) for dependencies, assets, and `mcode-tools`.

+ 0 - 46
README.zh-CN.md

@@ -1,46 +0,0 @@
-<div align="center">
-
-<img src="https://filecdn.minimax.chat/public/c3ebbd2e-f55b-48d7-adff-030abb63e06d.png" alt="MiniMax Code" width="100%" />
-
-# MiniMax Code
-
-**记忆你的习惯,组建 Agent 团队,自动化重复工作。**
-
-[macOS 下载](https://agent.minimaxi.com/download) · [Windows 下载](https://agent.minimaxi.com/download) · [提交 Issue](../../issues/new/choose)
-
-[English](./README.md)
-
-</div>
-
----
-
-## 反馈问题
-
-本仓库用于收集 MiniMax Code 桌面端的问题反馈。
-
-> 提交 Bug 时,请在「设置 → 通用 → 上传日志」上传日志,并附上生成的 uploadId。
-
-### 提交步骤
-
-1. 点击右上角 **Issues** → **New issue**
-2. 选择对应模板(Bug / Feature / Question)
-3. 填写以下信息:
-   - **版本号** —— 在「设置」中可见
-   - **平台** —— macOS / Windows
-   - **uploadId** —— 在「设置 → 通用」上传日志后生成
-   - **复现步骤** —— 简短、可复现
-   - **截图或日志** —— 可选,但有则更佳
-
-### 提交前请确认
-
-- 搜索一下,确认没有重复 Issue
-- 已升级到最新版本
-- 已移除敏感信息(API Key、Token 等)
-
----
-
-<div align="center">
-
-© 2026 MiniMax. All rights reserved.
-
-</div>

+ 204 - 0
README_ZH.md

@@ -0,0 +1,204 @@
+<p align="center">
+  <picture>
+    <source media="(prefers-color-scheme: dark)" srcset="docs/assets/wordmark-dark.svg">
+    <source media="(prefers-color-scheme: light)" srcset="docs/assets/wordmark-light.svg">
+    <img src="docs/assets/wordmark-light.svg" alt="MiniMax Code" width="760">
+  </picture>
+</p>
+
+<h1 align="center">MiniMax Code</h1>
+<p align="center">A terminal coding agent with MiniMax, your own models, and tools beyond code.</p>
+<p align="center">
+  <a href="#快速开始">Get started</a> ·
+  <a href="docs/README.md">Documentation</a> ·
+  <a href="docs/examples.md">Examples</a> ·
+  <a href="CONTRIBUTING.md">Contributing</a>
+</p>
+<p align="center"><a href="README.md">English</a> · <strong>简体中文</strong></p>
+<p align="center">
+  <img src="docs/assets/source-preview.svg" alt="Source preview">
+  <img src="docs/assets/node.svg" alt="CI: Node.js 22 and 24">
+  <a href="LICENSE-STATUS.md"><img src="docs/assets/license.svg" alt="First-party default license: MIT"></a>
+</p>
+
+在终端里读懂项目、修改代码并运行测试。使用 MiniMax 账号或自己的模型,把搜索、插件和多模态工具接入同一个工作流。
+
+[![MiniMax Code 真实 TUI:修复 clamp、查看代码 diff 并运行测试](docs/assets/tui-demo.png)](docs/demo.md)
+
+<p align="center"><a href="docs/demo.md">观看 20 秒真实演示 →</a> · 真实终端输出回放,已压缩等待时间</p>
+
+## 快速开始
+
+### 1. 安装 MCode
+
+按操作系统选择官方安装器。安装器会安装最新版 CLI,并在需要时准备兼容的 Node.js,无需 `sudo` 或管理员权限;目前不支持 Alpine / musl Linux。
+
+**macOS / Linux / WSL**
+
+```bash
+curl -fsSL https://filecdn.minimax.chat/public/install.sh | bash
+```
+
+**Windows(PowerShell)**
+
+```powershell
+irm https://filecdn.minimax.chat/public/install.ps1 | iex
+```
+
+**npm**:适用于已安装 **Node.js 22.19+(22.x)、24.2+(24.x)、25 或 26** 的环境。
+
+```bash
+npm install -g @minimax-ai/code@latest --registry=https://registry.npmjs.org/ --ignore-scripts=false --include=optional --allow-scripts=@minimax-ai/code,better-sqlite3
+```
+
+该 npm 命令使用公共 registry,包含可选的 SQLite 依赖,并允许执行主包和 SQLite 的安装脚本。固定版本和 Node.js 兼容范围见[安装指南](docs/installation.md)。
+
+重新打开终端后检查安装:
+
+```bash
+mcode --version
+mcode --help
+```
+
+参阅官网的[快速开始](https://agent.minimaxi.com/docs/cli/quick-start)、[功能与配置](https://agent.minimaxi.com/docs/cli/features)和[故障排查](https://agent.minimaxi.com/docs/cli/faq)。
+
+### 2. 登录账号或配置 API Key
+
+中国大陆账号运行:
+
+```bash
+mcode login
+```
+
+Global 账号运行:
+
+```bash
+mcode login --region global
+```
+
+在浏览器中完成登录,再启动 `mcode`,通过 `/status` 检查账号、通过 `/provider` 选择模型。退出登录使用 `mcode logout`。
+
+Token Plan 需要账号与可用额度。默认用户数据保存在 `~/.minimax-code`。
+
+<details>
+<summary>使用自己的 API Key(BYOK)</summary>
+
+BYOK 无需先登录 MiniMax。先在当前 shell 中设置 `MCODE_PROVIDER_API_KEY`,再添加提供方;将下方示例地址和模型名替换为实际配置:
+
+```bash
+mcode provider add --name my-provider --base-url https://example.com/v1 \
+  --api-format openai-completions --model my-model \
+  --api-key-env MCODE_PROVIDER_API_KEY --use
+mcode
+```
+
+支持 `openai-completions`、`openai-responses` 和 `anthropic-messages`。连接测试、单次模型切换及环境变量设置见 [模型示例](docs/examples.md#2-choose-your-own-model)。
+
+</details>
+
+### 3. 完成第一个任务
+
+进入要处理的项目目录:
+
+```bash
+cd /path/to/your/project
+mcode
+```
+
+在 TUI 中描述任务,也可以在启动时直接提交:
+
+```bash
+mcode "Find a failing test, fix the implementation, and run the relevant tests."
+```
+
+使用 `mcode init .` 生成或更新 `AGENTS.md` 项目指导。任务中应说明期望结果、修改边界和验证方式。
+
+| 入口 | 命令 | 适用场景 |
+| --- | --- | --- |
+| 交互式 TUI | `mcode [prompt]` | 探索代码、持续对话、审阅修改与权限确认。 |
+| Headless | `mcode exec [prompt]` | Shell、CI、批处理与评测。 |
+| ACP | `mcode acp` | 支持 Agent Client Protocol 的编辑器与客户端。 |
+
+### 继续之前的工作
+
+```bash
+# 恢复当前工作区最近的会话
+mcode --continue
+
+# 打开会话选择器
+mcode --session
+```
+
+在 TUI 中输入 `/sessions` 查找历史会话,输入 `/help` 查看完整命令与快捷键。
+
+| 操作 | 快捷键 |
+| --- | --- |
+| 发送消息,或在任务运行中调整当前响应 | `Enter` |
+| 在任务运行中将后续消息加入队列 | `Alt+Enter` |
+| 在输入框中换行 | `Shift+Enter` |
+| 引用工作区文件或目录 | `@` |
+| 切换 Plan Mode | `Shift+Tab` |
+| 切换权限模式 | `Alt+M` |
+| 关闭面板或中断正在运行的任务 | `Esc` |
+
+## 可以做什么
+
+| 场景 | 使用方式 |
+| --- | --- |
+| **修改与验证代码** | 读取文件、编辑 diff、执行 Shell 和测试;通过权限与沙箱控制工具执行。 |
+| **选择模型** | MiniMax 账号 / Token Plan,或兼容 OpenAI、Anthropic 格式的自定义提供方。 |
+| **搜索与多模态** | 内置搜索、`mcode-tools` 媒体工具、MCP 和托管连接器;按账号权限和服务额度使用。 |
+| **延续工作** | 会话恢复、任务规划、子 Agent、官方 / 本地 / GitHub 插件与内置 Skills。 |
+| **接入工作流** | Headless CLI 用于脚本任务,ACP 用于兼容的编辑器和客户端。 |
+
+账号、更新、反馈与诊断能力也在。托管工具需要网络和相应授权,详细边界见 [能力与服务边界](docs/tui-capabilities.md)。
+
+## 试一试
+
+在示例目录启动 TUI,输入:
+
+> Read clamp.mjs and clamp.test.mjs. Run node --test to reproduce the failure, fix clamp without changing the tests, then run the tests again.
+
+这个 [可复现的小项目](examples/clamp) 就是上方演示使用的任务。[更多示例](docs/examples.md) 包括切换模型、执行真实搜索,以及使用自己的图片输入。
+
+## 从源码构建
+
+开发 MCode 或运行本仓库源码需要 Git、Node.js **22.19+(22 系列)或 24.2+(24 系列)**,以及 **pnpm 9.12.0**。
+
+```bash
+git clone https://github.com/MiniMax-AI/minimax-code.git
+cd minimax-code
+pnpm install --frozen-lockfile
+pnpm build
+pnpm mcode
+```
+
+首次构建需要联网;依赖和经过校验的 `mcode-tools` 均来自公共 npm。pnpm 安装、系统依赖和更新方法见[源码安装指南](docs/installation.md)。
+
+从源码目录运行时,将上方示例中的 `mcode` 替换为 `pnpm mcode`。要在自己的项目中工作,先切换到项目目录,再运行构建产物:
+
+```bash
+node /absolute/path/to/minimax-code/dist/cli.js
+```
+
+本仓库目标为 **0.4.12 源码预览**。安装已发布的包与构建本仓库是两条独立路径,版本一致不代表构建来源完全相同,详见[版本与证据基线](docs/open-source-status.md#version-and-evidence-baseline)。
+
+## 文档与贡献
+
+- [安装与更新](docs/installation.md) · [使用示例](docs/examples.md) · [TUI 状态栏](packages/tui/docs/status-line-config.md)
+- [贡献指南](CONTRIBUTING.md) · [报告 Bug / 提出建议](https://github.com/MiniMax-AI/minimax-code/issues/new/choose) · [报告安全问题](SECURITY.md)
+- [全部文档](docs/README.md):架构、能力对照、验证记录、源码同步和发布流程。
+
+项目文档以英文为主,本页为首页的简体中文译文。
+
+目前仅接受仓库协作者提交代码和文档 Pull Request。如果你不是协作者,但有想法或方案,欢迎先通过 [Issue](https://github.com/MiniMax-AI/minimax-code/issues/new/choose) 讨论。请在报告中移除密钥、账号信息和私人项目内容。
+
+## 桌面版与问题反馈
+
+[下载 macOS 或 Windows 桌面版](https://agent.minimaxi.com/download) · [报告问题或提问](https://github.com/MiniMax-AI/minimax-code/issues/new/choose)
+
+本仓库也承接 MiniMax Code 桌面版的问题反馈。公开源码范围为终端 TUI、Headless CLI 和 ACP,不包含桌面应用源码。提交 Issue 时请选择对应产品。桌面版问题请注明应用版本、操作系统,以及「设置 → 通用 → 上传日志」生成的日志上传 ID(如可用);CLI 问题请注明 `mcode --version`、运行入口与最小复现。报告中请移除凭据和私人项目内容。
+
+## 许可
+
+第一方代码默认采用 [MIT](LICENSE);文件或子包已有独立声明时保留原许可。依赖、资源与 `mcode-tools` 的许可分别见 [第三方声明](THIRD_PARTY_NOTICES.md) 和 [许可状态](LICENSE-STATUS.md)。

+ 19 - 0
SECURITY.md

@@ -0,0 +1,19 @@
+# Security
+
+This project is a source preview. Maintainers prioritize security issues on the default branch; no support period for older versions or response SLA has been committed.
+
+Report vulnerabilities privately through **Security → Advisories → Report a vulnerability** on GitHub. If that entry is not enabled, open an issue without vulnerability details asking maintainers for a private channel. Share reproduction details only after that channel is available. Do not put credentials, exploit details, or real user data in public issues.
+
+The release coordinator, @hetaoBackend, coordinates security triage; see [Maintainers](docs/maintainers.md). A public fallback security email and a second responder have not yet been confirmed. Before public launch, the release coordinator must enable and verify the private reporting entry on the destination repository, or publish and verify a staffed private contact address. Do not interpret this document as evidence that the GitHub reporting feature is already enabled.
+
+Include the affected version, operating system and Node.js version, a minimal reproduction, expected and actual permission boundaries, and necessary redacted evidence. Use synthetic files and dedicated test accounts; do not test other people's accounts or infrastructure.
+
+## Data and service boundaries
+
+- The default data directory, `~/.minimax-code`, stores login state, provider configuration, and sessions. It is not shareable project configuration. Restrict local access and keep it out of Git.
+- Models, official plugins, connectors, search, media, feedback, and telemetry may contact external services. Those services continue to control authorization and credits; source access does not grant access to accounts or third-party resources.
+- mcode-tools obtains short-lived access tokens through the host's lease broker. Never pass refresh tokens to tool processes.
+- Permissions and sandboxing do not replace review of untrusted plugins, MCP servers, and shell commands. If automatic permission classification is unavailable, retain user confirmation rather than allowing operations by default.
+- If credentials leak, revoke or rotate them with the service first, then remediate files and Git history. Deleting the current file does not remove historical copies.
+
+Scan source, Git history, and build artifacts separately. A passing scan does not guarantee the absence of unknown vulnerabilities.

+ 10 - 0
THIRD_PARTY_NOTICES.md

@@ -0,0 +1,10 @@
+# Third-party notices
+
+- **Pi**: `third_party/pi-mono` and derived terminal code, MIT. Full notices are in `third_party/pi-mono/LICENSE` and `packages/tui/THIRD_PARTY_NOTICES.md`. Local modifications are recorded in `third_party/pi-mono/MINIMAX_CHANGES.md`.
+- **Sandbox Runtime**: `third_party/sandbox-runtime`, Apache-2.0. See its README, LICENSE, and upstream.json for the upstream version, source revision, fork changes, and native build instructions.
+- **models.dev**: the bundled provider / model catalog snapshot, MIT; notices are in `packages/tui/THIRD_PARTY_NOTICES.md`.
+- **Bundled assets**: LICENSE, NOTICE, and file-level declarations in each asset directory retain their original attribution.
+- **npm dependencies**: versions and declared licenses are recorded in `release/dependency-licenses.json`; `pnpm-lock.yaml` is authoritative for dependency resolution and integrity.
+- **mcode-tools 0.0.4**: extracted unchanged from the public `@minimax-ai/code@0.3.11` package during the build. Its distribution manifest declares MIT; archive and CLI hashes are pinned in `scripts/lib/mcode-tools-artifact.mjs`. The tool's own manifest is retained, and the original distribution's third-party notices are copied to `dist/MCODE_TOOLS_NOTICES.md`. The root license does not replace this artifact's existing declarations.
+
+The root MIT license does not replace these materials' separate licenses or copyright notices.

+ 26 - 0
docs/README.md

@@ -0,0 +1,26 @@
+# Documentation
+
+[English README](../README.md) · [简体中文 README](../README_ZH.md)
+
+## Get started
+
+- [Official CLI quick start](https://agent.minimax.io/docs/cli/quick-start): installation, account regions, first tasks, and sessions.
+- [Install from source](installation.md): prerequisites, build, project usage, updates, and removal.
+- [Examples](examples.md): code fixes, model selection, search, and image input.
+- [Real TUI demo](demo.md): a 20-second replay, still image, and reproduction steps.
+- [Status line configuration](../packages/tui/docs/status-line-config.md): the default status line and optional machine-readable mode.
+- [Capabilities and service boundaries](tui-capabilities.md): accounts, tools, plugins, sandboxing, and network behavior.
+- [TUI usage telemetry](telemetry.md): opt-in settings, sent fields, destinations, and retention boundary.
+
+## Contribute
+
+- [Contributing](../CONTRIBUTING.md) · [Maintainers and review](maintainers.md) · [Security reporting](../SECURITY.md)
+- [Architecture](architecture.md) · [Verification records](verification.md)
+
+## Maintain and release
+
+- [Source synchronization](source-sync.md): shared implementation and standalone distribution adaptations.
+- [Release process](releasing.md) · [Release audit](release-audit.md) · [Preparation status](open-source-status.md)
+- [License status](../LICENSE-STATUS.md) · [Publication authorization](publication-authorization.md) · [Third-party notices](../THIRD_PARTY_NOTICES.md)
+
+Project documentation is primarily in English. Translations are labeled separately. Engineering review and live-service acceptance records describe evidence and limits; passing CI does not mean every external service has been tested.

+ 24 - 0
docs/architecture.md

@@ -0,0 +1,24 @@
+# Source boundaries
+
+`TUI / exec / ACP → CliService → local Applications → Session / Turn / Agent services → Pi / model providers / local tools`.
+
+- `packages/tui` owns terminal interaction and the headless and ACP adapters.
+- `packages/local-runtime-v2/src/local` is the in-process product entry point. Session query views and queue contracts derive from local service types and converters.
+- `packages/local-runtime-v2/src/application` handles sessions, queues, and interactions. It does not instantiate DesktopService, an HTTP front door, or cloud handoff services.
+- `packages/protocol/src/local.ts` contains CLI data structures; `runtime.ts` contains agent configuration and events. Neither includes RPC envelopes, service routing, authentication headers, or an IDL generation chain. Some numeric enums preserve compatibility with existing saved sessions.
+- `packages/local-runtime` supplies reused host facilities such as databases, file tools, permissions, and storage. Historical readers only read old session files; they do not proxy to a daemon or fall back to a legacy executor.
+- `third_party/pi-mono` supplies agent, model-protocol, and terminal infrastructure. `third_party/sandbox-runtime` retains the actual sandbox fork, native helpers, and corresponding source.
+
+`@mavis/*` names identify private workspace packages in this repository. The build resolves their source directly rather than downloading them from an internal registry. These packages are not independently published npm APIs.
+
+The unused `@mavis/team` cycle engine is excluded from this projection. TUI delegation uses the current runtime task services. Legacy queue, lock-owner and run-location files retain only the types consumed by shared adapters; V2 owns their execution and persistence.
+
+`release/public-source.json` explicitly lists delivered files. `check:source` checks that inventory, canonical root license text, internal addresses, retired modules, obvious credentials, and workspace exports. `check:standalone` separately checks the actual build dependency graph. New files require explicit inventory updates; absence from the bundle alone does not make source suitable for publication.
+
+## Managed capabilities and tool integration
+
+The TUI continues to use the same runtime through local applications and services. MiniMax OAuth Core manages profile credentials, refresh, and logout. mcode-tools-host provides short-lived access tokens to tool subprocesses through a local lease broker. Official plugins, connectors, accounts, and search use their public service clients without restoring DesktopService or an HTTP front door.
+
+Headless model overrides are passed to a read-only account-state check so authentication requirements follow the model selected for that run. The check does not change global configuration or the session model; execution still uses the existing model resolver, permissions, and tools.
+
+The public distribution configures production regional services only. Non-production environments retained in shared types use reserved `.example.invalid` placeholders. The public CLI rejects internal environment switches and provides no default connection to internal services.

+ 1 - 0
docs/assets/license.svg

@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="176.7" height="22" role="img" aria-label="first-party | MIT"><title>first-party | MIT</title><rect width="176.7" height="22" rx="4" fill="#174868"/><path d="M4 0H91.7V22H4Q0 22 0 18V4Q0 0 4 0" fill="#303942"/><g fill="#fff" text-anchor="middle" font-family="Verdana,sans-serif" font-size="11"><text x="45.85" y="15">first-party</text><text x="134.2" y="15">MIT</text></g></svg>

+ 1 - 0
docs/assets/node.svg

@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="149.9" height="22" role="img" aria-label="CI | Node.js 22 / 24"><title>CI | Node.js 22 / 24</title><rect width="149.9" height="22" rx="4" fill="#174868"/><path d="M4 0H31.4V22H4Q0 22 0 18V4Q0 0 4 0" fill="#303942"/><g fill="#fff" text-anchor="middle" font-family="Verdana,sans-serif" font-size="11"><text x="15.7" y="15">CI</text><text x="90.65" y="15">Node.js 22 / 24</text></g></svg>

BIN
docs/assets/social-preview.png


Plik diff jest za duży
+ 0 - 0
docs/assets/social-preview.svg


+ 1 - 0
docs/assets/source-preview.svg

@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="123.10000000000001" height="22" role="img" aria-label="source | preview"><title>source | preview</title><rect width="123.10000000000001" height="22" rx="4" fill="#174868"/><path d="M4 0H58.2V22H4Q0 22 0 18V4Q0 0 4 0" fill="#303942"/><g fill="#fff" text-anchor="middle" font-family="Verdana,sans-serif" font-size="11"><text x="29.1" y="15">source</text><text x="90.65" y="15">preview</text></g></svg>

BIN
docs/assets/tui-demo.gif


BIN
docs/assets/tui-demo.mp4


BIN
docs/assets/tui-demo.png


Plik diff jest za duży
+ 0 - 0
docs/assets/wordmark-dark.svg


Plik diff jest za duży
+ 0 - 0
docs/assets/wordmark-light.svg


+ 30 - 0
docs/demo.md

@@ -0,0 +1,30 @@
+# A real coding task
+
+![Real MiniMax Code terminal replay: request, failing tests, a code fix, and passing tests](assets/tui-demo.gif)
+
+[Play or download the MP4](assets/tui-demo.mp4) · [View the full-size still](assets/tui-demo.png) · [Example source](../examples/clamp)
+
+## What was recorded
+
+The interactive TUI built from this repository ran in a temporary directory containing only `clamp.mjs` and `clamp.test.mjs`, using an existing MiniMax Token Plan login and `MiniMax-M3`. The model actually read the files, ran `node --test`, edited the function, and reran the tests. Initially two failed and one passed; after the fix, all three passed. The test file was unchanged.
+
+The recorded task:
+
+> Read clamp.mjs and clamp.test.mjs. Run node --test to reproduce the failure, fix clamp without changing the tests, then run the tests again. Reply briefly in English.
+
+Full access was used only for this isolated synthetic project. Use `/permission` to choose an appropriate mode for your own work.
+
+## Recording and editing
+
+- Recorded on 2026-09-11 from source commit `fe49bbd73d4bb2df6e5873801af12695378c0b62`, TUI version 0.3.11.
+- Actual ANSI output was captured through a PTY and replayed at 110 columns × 36 rows. Application text, colors, and layout are retained; the outer window title and provenance caption are recording decoration.
+- The still shows the same session after `Ctrl+O` expanded tool details and the viewport was scrolled upward, including the actual diff and test output.
+- The 20-second edit keeps task order, shortens waits and thinking, and holds on the final diff and tests. **It is not real-time playback or a performance benchmark.** No model output, tool calls, or test results were fabricated.
+- `@xterm/headless` interpreted terminal cells, which were rendered as SVG / PNG. FFmpeg encoded the GIF and silent H.264 MP4. A border keeps the dark terminal frame visible on both light and dark GitHub backgrounds.
+- No private project, account page, or key was recorded, and no user test image was used. Raw recordings and runtime logs remain local and are not committed as release assets.
+
+This demonstrates one small code repair, not acceptance of every project, provider, or tool. See the [verification records](verification.md) for broader evidence.
+
+## Brand assets
+
+The README's light and dark wordmarks use the existing TUI welcome logo, with blue and cyan from its theme. `assets/social-preview.png` is a local 1280 × 640 sharing card for maintainers to configure as the GitHub Social Preview at release time. Creating these assets does not publish the repository; nothing was uploaded to a third-party media host.

+ 74 - 0
docs/examples.md

@@ -0,0 +1,74 @@
+# Examples
+
+Build the project using the [installation guide](installation.md). Run the `pnpm mcode` commands below from the source root. For interactive tasks, open the target project directory and launch the built CLI by absolute path.
+
+## 1. Edit code and run tests
+
+`examples/clamp` is an intentionally broken exercise with one function and three Node.js tests. It needs no additional dependencies. Copy the directory to a temporary location, open that copy, and start:
+
+```bash
+node /absolute/path/to/minimax-code/dist/cli.js
+```
+
+Enter:
+
+> Read clamp.mjs and clamp.test.mjs. Run node --test to reproduce the failure, fix clamp without changing the tests, then run the tests again.
+
+In the [real demo](demo.md), two tests initially failed. After correcting the bounds, all three passed. Use `Ctrl+O` to inspect tool details. Choose permissions appropriate for your project; the demo ran in a temporary directory containing only synthetic files.
+
+Resume the most recent session in the current directory:
+
+```bash
+node /absolute/path/to/minimax-code/dist/cli.js --continue
+```
+
+## 2. Choose your own model
+
+Use `/provider` in the interactive TUI to select a configured model. Before adding a custom provider, set a key in your current shell rather than putting it in command arguments or source:
+
+```bash
+# POSIX shell: read the key interactively without echoing it.
+read -s MCODE_PROVIDER_API_KEY
+export MCODE_PROVIDER_API_KEY
+```
+
+In PowerShell, use a process environment variable and treat the input as sensitive:
+
+```powershell
+$secureKey = Read-Host 'API Key' -AsSecureString
+$env:MCODE_PROVIDER_API_KEY = [System.Net.NetworkCredential]::new('', $secureKey).Password
+```
+
+Add, inspect, and test the provider:
+
+```bash
+pnpm mcode provider add --name my-provider --base-url https://example.com/v1 \
+  --api-format openai-completions --model my-model \
+  --api-key-env MCODE_PROVIDER_API_KEY --use
+pnpm mcode provider list
+pnpm mcode provider test <provider-id> --model <model-id>
+pnpm mcode exec "Explain this project's test entry points" --model <provider-id>/<model-id>
+```
+
+Replace the example URL, model name, and IDs with your configuration and the IDs returned by the list command. `--use` sets the default model; `exec --model` overrides only the current run. Backslash line continuations are for POSIX shells; use a single line in PowerShell.
+
+[Live acceptance](verification.md) separately verified MiniMax Token Plan and one configured BYOK provider. This is not a guarantee for every compatible service.
+
+## 3. Search and image input
+
+After signing in to MiniMax, try a task that explicitly requires search:
+
+> Use web_search to find the official Node.js test runner documentation. Summarize how to run tests and include the source URL. If the tool is unavailable, say so.
+
+Acceptance observed an actual `web_search` call and returned results; see the [verification record](verification.md). A model returning a URL alone does not prove it used search.
+
+Paste your own image into the TUI, or attach a file explicitly:
+
+```bash
+pnpm mcode exec "Describe this UI screenshot's layout and suggest three improvements" \
+  --file /absolute/path/to/your-screenshot.png
+```
+
+The image is sent as input to the selected model service. Use content suitable for sending and a model that supports images. This is an executable usage example, not a live-service acceptance result from this review. Search, image understanding, and media generation are separate capabilities; mcode-tools generation also requires the relevant account permissions and credits.
+
+Use `/plugins` to manage extensions. See [capability coverage](tui-capabilities.md) for custom MCP, managed connectors, and media tools.

+ 48 - 0
docs/installation.md

@@ -0,0 +1,48 @@
+# Install from source
+
+The official CLI is available as [`@minimax-ai/code`](https://www.npmjs.com/package/@minimax-ai/code). Public npm `latest` was 0.4.12 on 2026-09-18. Follow the [official quick start](https://agent.minimax.io/docs/cli/quick-start) or the [README installation steps](../README.md#quick-start) for the macOS / Linux / WSL installer, Windows PowerShell installer, or npm installation.
+
+For npm, use the command in the README: it explicitly selects the public registry, includes optional dependencies, and allows the `@minimax-ai/code` and `better-sqlite3` lifecycle scripts. SQLite is declared optional in the package metadata, but a working native SQLite binding is required at runtime. Do not omit optional dependencies or disable installation scripts. On npm versions that enforce script approvals, `--allow-scripts` grants these two packages permission without allowing every dependency script.
+
+`@latest` follows the stable npm dist-tag. For a reproducible CLI version, replace `@latest` with an exact published version such as `@0.4.12`, keeping the other options. Use Node.js 22.19+ (22.x), 24.2+ (24.x), 25, or 26 for both npm and source installations.
+
+This guide builds the 0.4.12 source preview. Workspace/local build manifests remain `private: true` to prevent accidental publishing. A source checkout may contain additional reviewed distribution changes; matching version strings alone do not establish byte-for-byte or build-provenance equivalence with the official npm tarball. Use the committed source revision and release receipt to identify a source build.
+
+For a source build, you need Git, Node.js 22.19+ (22.x) or 24.2+ (24.x), and pnpm 9.12.0. Node 25 and 26 are also covered by the weekly compatibility matrix; regular CI covers Node 22 and 24. Initial installation and build require access to public npm.
+
+Node 24.0 and 24.1 are unsupported: their bundled libuv can return inconsistent Windows file identity metadata, causing safe configuration reads to fail. [Node 24.2.0](https://nodejs.org/en/blog/release/v24.2.0) includes libuv 1.51.0 with the [upstream fix](https://github.com/libuv/libuv/commit/82cdfb75f). Use a current patch release of a supported Node line.
+
+```bash
+git clone https://github.com/MiniMax-AI/minimax-code.git
+cd minimax-code
+corepack enable
+corepack prepare pnpm@9.12.0 --activate
+pnpm install --frozen-lockfile
+pnpm build
+pnpm mcode --help
+pnpm mcode
+```
+
+If your Node.js installation does not include Corepack, install the exact pnpm version using your existing package manager. Native dependencies without matching prebuilt binaries require C/C++ build tools and Python: the C++ workload in Visual Studio Build Tools on Windows, Command Line Tools on macOS, or the system build toolchain on Linux.
+
+The build extracts mcode-tools from a pinned public `@minimax-ai/code` archive and verifies both archive and CLI hashes. The cache is in `.cache/artifacts`. On integrity failure, check the network or remove that cache and retry; never bypass hash verification.
+
+To use the CLI in another project, open that project's directory and run the built entry point by absolute path:
+
+```bash
+node /absolute/path/to/minimax-code/dist/cli.js
+```
+
+On Windows, also use `node` with the appropriate local absolute path. Do not overwrite another globally installed command with this source build.
+
+## Accounts and data
+
+Run `/login` in the TUI or `pnpm mcode login`, choosing the region for your account. Token Plan requires an account and available credits. See the root README for BYOK configuration and testing.
+
+The default data directory is `~/.minimax-code`. For tests, explicitly set `MINIMAX_DATA_DIR` to a temporary directory to keep normal sessions separate. Use `$env:MINIMAX_DATA_DIR = 'C:\path\to\test-profile'` in PowerShell or `export MINIMAX_DATA_DIR=/path/to/test-profile` in a POSIX shell.
+
+## Update or remove
+
+Save your changes, fetch a reviewed revision with Git, then repeat the frozen install and build. A source installation does not automatically become an official npm installation.
+
+To uninstall, remove the source directory you created. User data is separate and remains in place. Delete that directory only when you no longer need its account configuration or sessions.

+ 52 - 0
docs/maintainers.md

@@ -0,0 +1,52 @@
+# Maintainers and contribution workflow
+
+## Responsibility
+
+| Responsibility | Current routing | Responsibilities |
+| --- | --- | --- |
+| Repository administration and release coordination | @hetaoBackend, release coordinator | Maintain access and branch protection, assign reviewers, coordinate release approval and publish only verified candidates |
+| Code review | `.github/CODEOWNERS` routes to @hetaoBackend; an additional designated reviewer is PENDING | Review correctness, tests, capability boundaries, licenses and public-source scope; authors do not approve their own PRs |
+| Security triage | @hetaoBackend coordinates a private channel under [Security](../SECURITY.md) | Receive reports privately, appoint a responder and coordinate fixes/disclosure; no response SLA is currently promised |
+| Shared-source synchronization | The release coordinator assigns a maintainer to each sync PR | Preserve public adaptations, review conflicts and new files, and keep private history/review material out of public PRs |
+
+These are repository maintenance responsibilities, not an assertion that an account owns the product's copyright. An additional designated reviewer, a second security responder and a public fallback security address are not yet confirmed by the maintainers. Maintainer additions and changes to this policy should be reviewed in a PR; do not silently grant repository access.
+
+## Review and merge
+
+1. Repository collaborators open an issue for substantial scope or submit a focused feature-branch PR. Other users may open issues to discuss ideas and proposals. Security details follow the private reporting process.
+2. The release coordinator selects a reviewer other than the author. Use the PR template to record user-visible behavior, checks and untested boundaries.
+3. Review changed publication scope and existing licenses before regenerating the inventory. Run the shared verification profile required by the change. A test fixture is not live-service evidence.
+4. Require a current independent approval, resolved review conversations, and successful `verification` and `source-history-artifact` checks. Dismiss stale approvals when the reviewed code changes. A billing outage, cancellation or absent check is not a pass.
+5. Squash or merge the reviewed public PR while preserving contributor attribution. Do not bypass checks to unblock a release. No maintainer may substitute a self-approval for independent review.
+
+When migrating older CI configurations, replace required individual OS/Node check names with the two aggregate contexts above before removing the old names. Documentation-only changes intentionally skip platform jobs, so those individual contexts must not be required. Read back both classic branch protection and effective rulesets; workflow changes do not update either setting.
+
+CODEOWNERS requests reviewers; it does not enforce protection by itself. The intended administrative configuration is [`.github/branch-protection.json`](../.github/branch-protection.json). Applying it requires repository administration access. Read back the live settings after applying and when setting up the eventual public repository; committing this file does not activate it.
+
+```bash
+release_repo=MiniMax-AI/minimax-code
+gh-axi api "/repos/$release_repo/branches/main/protection"
+gh-axi api PUT "/repos/$release_repo/branches/main/protection" \
+  --input .github/branch-protection.json
+gh-axi api "/repos/$release_repo/branches/main/protection"
+```
+
+Inspect existing rules before applying: the PUT operation replaces classic branch protection. Preserve any stronger existing protections. This baseline requires the two GitHub Actions checks, one independent approval, resolved conversations and enforcement for administrators; force pushes and branch deletion remain disabled. Confirm that a reviewer other than the PR author has write access before enabling the rule. Required code-owner approval is currently disabled in this configuration because only the repository owner is designated in CODEOWNERS; enable it after a second code owner is confirmed. Independent PR approval remains required. Repository plan availability and token permissions must support the settings.
+
+## Contributions and licenses
+
+Contributors must have permission to submit their changes under the existing license applicable to each changed file/package. Preserve original authorship and notices, identify imported material and its provenance, and do not include credentials or third-party personal data. The PR template records this confirmation. This process introduces no separate CLA, DCO bot or copyright assignment. If a contribution needs different terms, resolve them before merging.
+
+## Collaborator contributions and internal synchronization
+
+Accepted changes land through public PRs first. The assigned sync maintainer ports accepted shared changes into the internal source, preserving attribution and recording the public PR reference internally. Public PRs may record that porting is pending or complete; they must not expose private links, commit messages or review reports.
+
+For the next sync, use the three-way process in [Source synchronization](source-sync.md). Confirm that the accepted public contribution remains present, inspect conflicts and deletions, and advance `sourceRevision` only after reviewing the complete candidate. Do not use a bulk overwrite or import internal Git history.
+
+## Release handoff
+
+The release coordinator explicitly dispatches `Node compatibility` and `Source candidate` for the reviewed revision before a source release; normal PR/main checks do not produce a candidate. Changes to supported Node versions, native dependencies or compatibility-sensitive verification tooling need the compatibility run before merge, and candidate/export changes need a selected-branch candidate run once its manual entry is available.
+
+The release coordinator records the selected source commit and archive receipt, current verification results, [publication authorization](publication-authorization.md), known limitations and the reviewer. Update [preparation status](open-source-status.md), [verification records](verification.md), and both README entry points when their shared content changes. Publish source previews separately from npm/installer releases, following [Releasing](releasing.md).
+
+The release coordinator applies administrative settings only on the intended repository and reads back the result. Current administrative readiness must be checked live. The 2026-09-12 inspection found `main` unprotected; protection/ruleset reads returned 403 and private vulnerability reporting returned 404 through the available CLI. The browser session was not authenticated. These errors leave configuration incomplete, and do not establish that private reporting is enabled or usable.

+ 33 - 0
docs/open-source-status.md

@@ -0,0 +1,33 @@
+# Standalone source preparation status
+
+The current source target is **TUI 0.4.12**. Preserve its capabilities while retaining the public distribution boundary. The earlier BYOK-only extraction strategy is no longer the target.
+
+## Version and evidence baseline
+
+| Concern | Current value | Source of truth |
+| --- | --- | --- |
+| TUI capability version | 0.4.12 | `packages/tui/package.json` |
+| Root workspace version | 0.4.12, aligned with the TUI | Root `package.json` |
+| Published npm observation | `@minimax-ai/code@0.4.12`; npm `latest` was 0.4.12 on 2026-09-18 | Public npm registry |
+| Shared-source baseline | `9b9885e42a3cf1a3df1cfa52a46e4fdb034cfcee` | `release/extraction.json` |
+| Embedded mcode-tools | 0.0.4, extracted from public `@minimax-ai/code@0.3.11` | `scripts/lib/mcode-tools-artifact.mjs` |
+| Historical live-service acceptance and demo | TUI 0.3.11, recorded 2026-09-11 | `docs/verification.md`, `docs/release-audit.md`, `docs/demo.md` |
+
+The product, TUI and root workspace use the same 0.4.12 version. The embedded tool has its own version; its pinned archive is not the TUI source version. Workspace/local build manifests remain `private: true` to prevent accidental publication. The existing npm release is already available; matching version strings do not prove that this source tree reproduces that exact tarball. Earlier live-service acceptance remains historical evidence; it does not establish acceptance of TUI 0.4.12.
+
+## Retained implementation
+
+- MiniMax OAuth / Token Plan, account and quota views, check-in, the official plugin marketplace, managed connectors, search, mcode-tools, updates, feedback, and diagnostic clients are restored.
+- The in-process runtime, public workspace dependencies, actual tools, and sandbox remain. Internal generated IDL, the Desktop HTTP front door, and cloud-executor-only implementations are not restored.
+- mcode-tools is extracted from a pinned public npm package with archive and file hash verification. Only the host holds refresh tokens.
+- Source scanning permits reviewed public service API paths while continuing to reject internal addresses, generated protocols, and obvious credentials. Build checks also verify that key capabilities remain present.
+- Original internal history stays outside this repository and is not merged into public history.
+
+See `tui-capabilities.md` for individual capabilities and `verification.md` for evidence. A private GitHub review repository and PR workflow are in place. The public npm registry was checked on 2026-09-18; that metadata check did not install the package, verify its runtime behavior, or publish source or packages. Historical TUI 0.3.11 Token Plan, BYOK, search, plugin catalog, and connector discovery checks have live evidence. Current-revision results and NOT RUN boundaries are tracked in `verification.md`. See `release-audit.md` for remaining limits; not every service or cross-platform interactive user path has been validated.
+
+
+## Prepared public destination
+
+The destination is `MiniMax-AI/minimax-code`. The private review tree now includes official CLI installation and first-task instructions, production documentation links, Desktop download/support entry points, the destination's established issue-form paths with product selection, a compatible Chinese README entry, and its support notification workflow restricted to the public destination. The reviewed source inventory includes these files. See [import preparation evidence](verification.md#public-import-preparation-2026-09-18) and [the import procedure](releasing.md#import-into-the-existing-public-repository).
+
+The 0.4.12 candidate deliberately excludes open dependency-upgrade PRs; each upgrade needs separate review and validation. The source boundary, retained licenses and private-history exclusion remain unchanged. Registry metadata, local tests, CI, live-service acceptance and publication authorization are distinct evidence categories.

+ 33 - 0
docs/publication-authorization.md

@@ -0,0 +1,33 @@
+# Publication authorization record
+
+Status: **PENDING rights-holder confirmation**. This document prepares a reviewable decision; it is not authorization to publish. On 2026-09-12 the repository owner supplied **MiniMax Code** as the first-party copyright attribution; it is recorded in the root `NOTICE`. Authorization to publish the exact candidate and each material group below remains pending.
+
+## Proposed publication scope
+
+Publish a source preview from the committed, reviewed file inventory in `release/public-source.json`, using the history-free export procedure in [Releasing](releasing.md). The first-party default and workspace package declarations use MIT. Third-party and file-level exceptions remain intact, including Apache-2.0 for `third_party/sandbox-runtime` and the original MIT notices for Pi and the bundled DOCX skill.
+
+| Material | Review required | Decision |
+| --- | --- | --- |
+| First-party code in the reviewed package roots, build/release scripts and tests | Identify the rights holder and confirm publication under the existing applicable declarations | PENDING |
+| First-party prompts, agents, skills, templates, examples and documentation | Confirm ownership/provenance, permission to redistribute and removal of private or personal material | PENDING |
+| MiniMax names, logos, screenshots, demo recordings and other brand assets | Confirm that the specific assets may be included and describe any separate brand-use terms | PENDING |
+| Vendored Pi and Sandbox Runtime; derived terminal code and model catalog | Retain upstream licenses, copyright and modification notices; review the exact included materials | Existing notices retained; final release review PENDING |
+| Downloaded mcode-tools artifact and npm dependencies | Retain their own terms and applicable notices; do not treat their public availability as first-party source authorization | Declared provenance recorded; final distribution review PENDING |
+
+The approval must cover the exact candidate, not an unspecified future branch. Untracked working files, private review reports, account data, internal Git history and later additions are outside this scope. Approval for source publication does not approve npm publishing, installer distribution, third-party account access or paid service operations.
+
+## Rights-holder decision to record
+
+An authorized representative must supply the following before the release owner marks this record approved:
+
+- First-party attribution supplied by the repository owner: **MiniMax Code**, recorded in `NOTICE`. The authorized representative must confirm that attribution as part of the publication decision.
+- Approver identity, authority to act for that holder, decision date and a non-sensitive reference to the approval. Keep confidential legal evidence outside the public repository.
+- Reviewed candidate commit, exported archive SHA-256 and public inventory SHA-256 from the release receipt/review.
+- Explicit approval or exclusions for each material group above, including package/file license exceptions and brand assets.
+- Any conditions that must be completed before publication.
+
+Current publication decision: **not recorded**. The supplied attribution is recorded; no approval date, authority or approval reference has been inferred. After confirmation, update this record; preserve the MIT text and maintain consistent project attribution in `LICENSE` and `NOTICE`. If the candidate changes afterward, review the changed scope and record a new approval or an explicitly authorized scope-preserving update.
+
+## Release-owner checks
+
+The release owner in [Maintainers](maintainers.md) verifies that the decision and candidate match, preserves all third-party notices, and links the approved record from the release notes. [License status](../LICENSE-STATUS.md) must agree with this record. Authorization alone does not replace CI, source/history/artifact scanning or the requirement to exclude private history when importing onto the existing public destination history.

+ 40 - 0
docs/release-audit.md

@@ -0,0 +1,40 @@
+# Private release audit
+
+This audit describes the historical TUI 0.3.11 baseline. The current source target is TUI 0.4.12; see [preparation status](open-source-status.md) and [current verification status](verification.md#current-source-verification-status). The earlier pass results are not current-release acceptance, and rights-holder authorization remains tracked separately in [Publication authorization](publication-authorization.md).
+
+Date: 2026-09-11. Scope: standalone TUI 0.3.11 source, retained capabilities, dependency provenance, Git history, and local build artifacts. The user requested review and CI before publication. GitHub remains private; no release or npm package was published.
+
+## Content and provenance
+
+- Gitleaks 8.24.3 scanned complete Git history, a standalone source snapshot, and `dist`. The initial history scan found five items: a permission translation key, two keyboard shortcuts, a form field key, and an example pagination token. Each was verified as a non-credential. The build scan also found a node-forge function alias. `.gitleaks.toml` excludes these false positives only by specific file and full matched value, not entire test or skill directories. Repeat scans had no unaddressed findings. GitHub's `Release audit` runs all three scans.
+- Manual review found a historical visa case with identity data in the PDF skill. Its original synthetic provenance could not be established. Current source uses explicitly synthetic people, documents, employers, and contact details while preserving AcroForm behavior, field structure, and workflow; internal case-origin labels were removed. Older private commits still contain the earlier version. Public distribution must therefore use a snapshot without history, not a visibility change on this review repository.
+- The source gate checks internal addresses, generated protocols, environment files, the explicit inventory, workspace exports, and native helper hashes. The standalone gate checks actual build dependencies and key TUI capabilities. Scanning and review do not prove the absence of every unknown issue.
+- `release/extraction.json` records the source baseline and 32 package roots: 27 declare Apache-2.0 and five MIT. Pi and Sandbox Runtime licenses, upstream revisions, and modification records remain. Assets retain their independent declarations.
+- `release/dependency-licenses.json` records 503 dependency entries and 13 license expressions. Multiple-license expressions and additional declarations such as Zlib remain intact. This is a declaration inventory, not a complete license-text bundle for binary distribution.
+- mcode-tools comes from pinned public `@minimax-ai/code@0.3.11`. The build verifies archive SHA-512 and embedded CLI SHA-256, retaining the 0.0.4 manifest and original distribution notices. The public package declares MIT; the root Apache-2.0 license does not relicense it. Rights-holder authorization to publish first-party source remains pending.
+
+## Live-service evidence
+
+The user authorized the existing production login on this machine. Sessions used dedicated temporary workspaces and synthetic inputs. Logs and account responses remain outside the repository and are not attached to public PRs.
+
+| Path | Result |
+| --- | --- |
+| Existing OAuth / Token Plan → MiniMax-M3 | Actual request succeeded and returned the requested marker |
+| Token Plan session resume | `--continue` successfully recovered the previous marker |
+| BYOK connection and actual model session | Existing custom provider passed its connection test; a real session returned the requested marker |
+| Built-in web_search | Events confirmed an actual tool call and successful search results; a request that only returned a known official URL was not counted as tool acceptance |
+| Official plugin catalog | Live service returned 54 available plugins; this does not claim all plugins were installed or tested on real tasks |
+| mcode-tools host lease | Real CLI launched through bash; `auth status` returned shared-broker authenticated |
+| Connector tool discovery | `connector tools` returned 13 tools with `partial: false` and no provider failures; no third-party business writes were performed |
+
+## Not run and publication boundaries
+
+Browser login / logout was not repeated, to preserve the user's normal account state. Paid media generation, website deployment, diagnostic / feedback uploads, new third-party connector grants, and business writes were not performed. Not all bundled skills were tested on real tasks. Updates have test coverage, but the global installation on this machine was not replaced.
+
+Use the PR checks for the final commit and cross-platform CI results. Offline tests, live-service evidence, and untested areas are recorded separately in `docs/verification.md`. Release documentation, source synchronization, and export tools are versioned. This audit does not grant publication authorization.
+
+## Follow-up: root license attribution, 2026-09-12
+
+The user identified a gap in the earlier audit: root `LICENSE` carried `Copyright 2025 Anthropic` and was byte-for-byte identical to `third_party/sandbox-runtime/LICENSE` (SHA-256 `1210bc93eb85dd786c33192d5bcb7153a93922fa99fbc1512af6a7199cb41080`). Git history confirmed these bytes were present in the first extraction commit, `2ca697f510ea1615280e47ade278fc60a330b28a`; the English translation did not introduce them. The previous audit did not establish correct first-party attribution.
+
+The root file was replaced with the exact [standard Apache-2.0 text](https://www.apache.org/licenses/LICENSE-2.0.txt), SHA-256 `cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30`, including its unfilled example appendix. The source gate now checks this hash. All third-party license files and copyright notices remain unchanged. The first-party copyright holder and permission to publish remain unconfirmed; see `LICENSE-STATUS.md`.

+ 81 - 0
docs/releasing.md

@@ -0,0 +1,81 @@
+# Releasing a source preview
+
+Public npm `latest` for `@minimax-ai/code` was 0.4.12 on 2026-09-18. This phase prepares the 0.4.12 GitHub source preview while keeping workspace/local build manifests `private: true` to prevent accidental npm publication. The source version follows the reviewed product baseline; checking registry metadata does not publish or validate an npm release. Record the exact source commit and archive receipt; version alignment alone does not establish provenance equivalence with the existing tarball.
+
+The current GitHub repository is a **private review repository**. Older commits include a case later replaced with synthetic data. Do not switch this repository directly to public or carry those old commits or private review reports into public history. After PR review, export committed source from a checkout with no tracked changes:
+
+```bash
+node scripts/export-source-preview.mjs --out /private/release/minimax-code-source.tar.gz
+```
+
+The script validates the committed source inventory and exports an archive with a SHA-256 receipt from the current Git tree. It excludes `.git`, old commits, untracked files, caches, and user profiles. It does not push, publish, or overwrite existing artifacts. Extract and scan the archive outside the repository. After the publication decision is recorded for the candidate, import that snapshot onto a branch based on the existing public destination history, following the procedure below.
+
+1. Complete the [publication authorization record](publication-authorization.md) for the exact candidate and verify the [maintainer handoff](maintainers.md#release-handoff). Confirm rights-holder authorization for the publication scope and first-party license. Confirm the first-party copyright attribution in the MIT `LICENSE` and `NOTICE`. Preserve third-party and package licenses; never copy a vendor-specific copyright statement into the project root. A public package manifest proves provenance, not authorization to publish previously private source.
+2. Check `git status`, all release commits' authors / committers, and refs. Exclude internal history, backup refs, and user data. Inspect identities with `git log --all --format='%h %an <%ae> | %cn <%ce>'`.
+3. Run `pnpm check:source` and review the public inventory, dependency licenses, and native helper hashes. Scan complete history rather than only the latest diff:
+
+   ```bash
+   gitleaks git --redact --log-opts=--all --report-format json --report-path /private/review/history.json
+   git archive HEAD -o /private/review/source.tar
+   ```
+
+   Extract source into a separate directory and run `gitleaks dir --redact`; scan build artifacts separately. Keep reports outside the repository. Disclose finding rules, locations, and remediation without exposing credential values. Explain false positives by exact path, rule, and context; do not exclude entire test or asset directories.
+4. In a clean directory, run frozen install, type checking, build, boundary checks, and the explicit test list. Wait for the macOS / Windows / Linux Node.js 24 checks, then explicitly run `Node compatibility` on the selected revision to cover all supported versions. Local macOS success is not acceptance evidence for other systems.
+5. Use a temporary project and synthetic inputs for live-service checks. Record login, Token Plan / BYOK sessions, search / tools, resume, plugins, connectors, and sandbox results. Mark unavailable accounts or third-party grants as NOT RUN; fixtures do not replace service evidence. Confirm costs and upload scope separately for media generation, deployment, and feedback uploads.
+6. After PR approval and publication authorization, create a prerelease tag and notes pointing to the verified public commit. State the capability baseline, installation steps, and untested areas. Publish the source archive, not a local `dist` directory or user profile presented as a cross-platform installer.
+
+Before npm or binary distribution, separately validate update installation, package name / version, native dependency packaging, installation scripts, and complete notices. A dependency license declaration inventory is not a collection of all license texts required in an installer.
+
+## Automated source candidates
+
+Source candidates are explicit release-preparation runs, separate from ordinary PR and main-branch verification. Select `Source candidate` in the Actions UI and dispatch it on the reviewed branch or tag. The dispatch resolves that ref to the event's immutable commit SHA; every checkout, archive receipt and platform report uses that revision. The existing reusable entry also accepts a caller-supplied full revision. Ordinary code pushes, documentation changes and dependency PRs do not create candidates automatically.
+
+For changes to the candidate/export workflow itself, dispatch a candidate on the PR branch and review its reports before merging. Also run `Node compatibility` explicitly for changes to supported Node versions, native dependencies or compatibility-sensitive verification tooling, and before a source release. Match the recorded run SHAs to the final candidate; a branch name may move after a dispatch. Candidate runs are grouped by revision and do not cancel an in-progress validation when another main-branch commit arrives.
+
+The reusable `Source candidate` workflow exports that commit without Git history, checks its SHA-256 receipt, and scans complete history and the exact extracted source. Three fresh runners (Linux, macOS and Windows, Node 24) authenticate the same archive, extract it outside the checkout, install from public npm into a new pnpm store, and run `pnpm verify --profile archive`. This profile runs all applicable gates except re-exporting from Git, since the candidate intentionally contains no `.git`. The Linux build also receives a distribution secret scan. Platform-inapplicable tests remain explicitly marked as skipped; these automated checks do not replace live-service acceptance.
+
+Only after all three validation jobs pass does the final job publish the `source-candidate-<full-SHA>` Actions artifact, retained for 14 days. It contains:
+
+- `minimax-code-source.tar.gz`: the reviewed source snapshot.
+- Its `.json` receipt and `.sha256` checksum file.
+- `candidate.json`: the exact revision, archive digest, and three-platform validation summary.
+- `reports/`: each platform's detailed verification JSON and Markdown.
+
+The intermediate `unverified-source-<full-SHA>` artifact is retained for one day and must not be treated as a validated candidate. Candidate generation does not create a GitHub Release, publish to npm, change repository visibility, or grant publication rights. The authorization and history-free public-release requirements above still apply. GitHub must know the workflow on the default branch before its manual entry is available. When introducing this entry, validate the declaration and shared archive tooling in the PR, then dispatch it after the workflow becomes available; do not claim candidate acceptance until the three-platform run and artifact readback finish.
+
+## Import into the existing public repository
+
+The destination is [MiniMax-AI/minimax-code](https://github.com/MiniMax-AI/minimax-code). It already hosts desktop-app issue reporting. Preserve its history, existing issues, desktop download links, and support workflows when adding the CLI source.
+
+A GitHub squash merge only controls the resulting base-branch commit. Pushing a private source branch to a public repository exposes its reachable history before that merge. Do not push the private review branch, mirror its refs, or use an unrelated-history merge. Import the reviewed history-free archive as files on a fresh branch based on the destination's `main`, then open a PR and squash that public import PR.
+
+### Before creating the public import PR
+
+1. Freeze the reviewed source commit. Decide whether each open dependency update belongs in that candidate; do not incorporate unverified dependency upgrades just to clear the PR queue.
+2. Run `pnpm verify` from a clean committed checkout. Require successful final-revision source verification, release audit, explicitly dispatched Node compatibility, and the validated three-platform `source-candidate-<full-SHA>` artifact. Check current runner annotations if jobs fail before starting; earlier local or historical passes do not replace these results.
+3. Review and scan the exact exported files and record the source revision, archive SHA-256, public inventory digest, and validation reports. Complete the existing publication authorization record for that material scope before exposing the snapshot in a public branch or PR.
+4. Prepare the destination integration in a local checkout. Preserve and extend its desktop bug / feature / question templates and `.github/workflows/sync-issue-to-feishu.yml`; retain the prepared Desktop / CLI product selector. The Chinese README is `README_ZH.md`; update active links to this path and remove the destination's superseded `README.zh-CN.md` during import.
+5. Replace active clone, support, and administration examples with the destination repository. Keep historical verification URLs identifiable as historical evidence. Use official production documentation links. Explain that this source distribution contains the TUI, headless CLI, and ACP implementation; it does not publish the desktop application's source.
+6. Verify destination settings: allow squash merges, configure `verification` and `source-history-artifact` as required checks, require independent review and resolved conversations, and prevent force pushes or deletion of the default branch. Assign reviewers with actual repository access. Enable private vulnerability reporting or verify a staffed private contact. Review Actions permissions and the existing support-workflow secret configuration without copying credentials into files.
+7. The combined destination tree includes files absent from the source inventory. Review those additions and regenerate `release/public-source.json` with `node scripts/source-inventory.mjs --write`; review the generated diff. Run full verification and source/artifact scans on the integrated candidate too. A validated source archive does not establish validation of a subsequently modified integration tree.
+
+### Import and readback
+
+- Record both the reviewed source revision and the destination base revision. Keep private approval evidence, scan reports and local review pages outside the public file inventory.
+- Extract the authenticated archive outside both repositories. Apply its reviewed files to the destination-based branch, resolving overlapping README and `.github` content individually. Do not bulk-delete destination-only files.
+- Before committing, compare the staged file bytes and modes with the reviewed snapshot. Vendored Office XML schemas are marked non-normalizing in `.gitattributes` so Git does not silently change their CRLF bytes during import.
+- Commit only the intended integration tree using public author/committer identities and an English message. Check that all new commits reachable from the import branch consist only of reviewed import work on top of the destination base.
+- After authorization and local review, push that branch and open the destination PR. Re-run checks against its final head, obtain independent review, and squash merge through the PR.
+- Read back the merged PR, resulting commit, default-branch tree, documentation links and checks. Record the import commit as the public synchronization baseline while retaining `release/extraction.json` for the separate shared-source baseline. Source synchronization continues through reviewed three-way candidates; the squash import does not replace that contract.
+- An npm release, installer update or GitHub Release is a separate action with its own validation. Do not infer a package publication from a merged source PR.
+
+
+### Prepared destination compatibility
+
+The private review tree includes the public destination's three established issue-form paths and its Feishu support workflow, imported from destination revision `cd025375799a1360d499d5c06cfb2e1111a960fc`. The forms now route Desktop, TUI, headless, ACP and source-build reports explicitly; Desktop upload IDs are optional and do not apply to CLI reports. The existing source-only bug and feature forms were consolidated into these destination paths to avoid duplicate choices. The documentation issue form remains available.
+
+The Feishu workflow retains the destination's payload and delivery behavior and runs only for issue-open events in the public `MiniMax-AI/minimax-code` repository. It cannot forward issues from this private review repository. Its existing `FEISHU_BOT_WEBHOOK` and optional `FEISHU_BOT_SECRET` must remain configured on the destination; secret values are not copied, and preparation tests must not send notifications. Offline tests exercise payload generation with synthetic issue data.
+
+The Chinese README uses a single entry, `README_ZH.md`; the destination's superseded `README.zh-CN.md` is intentionally removed during import. Both main READMEs retain Desktop download and support links while explaining the CLI-only source scope. Before import, compare the destination against the recorded revision again: later destination changes need review rather than replacement by this prepared snapshot.
+
+Repository description proposal: **MiniMax Code CLI source and Desktop support — terminal coding agent, headless automation, and ACP.** Website: `https://agent.minimax.io/docs/cli/quick-start`. Apply these to the public destination only as part of the authorized publication operation.

+ 26 - 0
docs/source-sync.md

@@ -0,0 +1,26 @@
+# Source synchronization
+
+`release/extraction.json` pins the source revision and package scope; `release/public-source.json` is the reviewed public file inventory. Maintain internal implementation and public distribution adaptations separately. Do not configure the internal repository as a mergeable upstream or cherry-pick internal commits into public history.
+
+## Generate candidates
+
+Run the following from this repository. The source repository must contain both the recorded baseline and the target revision. The output directory must not exist and must be outside both repositories.
+
+```bash
+node scripts/prepare-source-sync.mjs --source /path/to/source-repository \
+  --ref <reviewed-upstream-commit> --out /path/to/new-private-review-directory
+```
+
+The tool reads Git objects, not the source working tree or credentials. For source files in the public inventory, it compares the old source, target source, and current public version to produce three-way merge candidates that preserve public changes. Conflicts keep their markers; deletions are reported without deleting files. New upstream files are reported by path and require separate review before inclusion. Selecting a revision does not automatically advance the recorded baseline.
+
+Output includes `report.json`, `candidates/`, and `.private-review`. Candidates are **unreviewed internal material**: do not upload them directly to GitHub, attach them to a PR, or copy the entire directory into the public repository. The tool never changes the current repository, runs upstream scripts, or carries internal commit authors, messages, or history.
+
+## Review and apply
+
+1. Inspect conflicts, deletions, new files, non-regular files, and missing source files. Include new files only when actual dependencies require them; do not recursively copy whole packages.
+2. Review internal addresses, generated IDL, credentials, prompt / asset licenses, and service contracts. Preserve in-process boundaries and public environment configuration.
+3. Apply approved files individually to a public feature branch. Resolve all conflicts, then update `sourceRevision` in `release/extraction.json` to the report's `targetRevision`. Do not advance the baseline before reviewing all differences.
+4. Regenerate the dependency license inventory if dependencies changed, then review and update the public source inventory. Run source, standalone, type, build, and explicitly selected affected tests.
+5. Scan complete history and current source before creating the public PR. Include public changes, validation results, and capability descriptions, never private review reports.
+
+After accepted public changes are ported back, subsequent three-way comparisons should show them as synchronized or cleanly mergeable while retaining standalone adaptations. Synchronization is not a blind overwrite: conflicts, missing source, and new files require maintainer judgment.

+ 82 - 0
docs/telemetry.md

@@ -0,0 +1,82 @@
+# TUI usage telemetry
+
+MCode's TUI usage telemetry is disabled by default. No business telemetry client is created and no business telemetry request is sent until the user opts in.
+
+## Turn it on or off
+
+Add this to the active profile's `config.yaml`, normally `~/.minimax-code/config.yaml`, then restart MCode:
+
+```yaml
+telemetry:
+  enabled: true
+```
+
+Remove the setting or set it to `false` to turn reporting off. Either environment variable below also turns it off and takes precedence over the config file:
+
+```sh
+MCODE_DISABLE_TELEMETRY=1 mcode
+DO_NOT_TRACK=1 mcode
+```
+
+Inspect the effective setting with `mcode telemetry status`. Run `mcode telemetry preview` to see a representative decoded request. Preview does not send a request. When telemetry is disabled, preview shows `request: null`.
+
+## Data sent
+
+The HTTP body is `application/x-www-form-urlencoded` with two fields:
+
+| Field  | Value                                                       |
+| ------ | ----------------------------------------------------------- |
+| `data` | Base64-encoded JSON envelope described below                |
+| `ext`  | `crc=<number>`, an integrity checksum of the encoded `data` |
+
+The decoded JSON envelope contains:
+
+| Field                            | Value                                         |
+| -------------------------------- | --------------------------------------------- |
+| `identities.$identity_cookie_id` | Fresh random ID for this event                |
+| `distinct_id`                    | The same fresh random ID                      |
+| `lib.$lib`                       | `js`                                          |
+| `lib.$lib_method`                | `code`                                        |
+| `lib.$lib_version`               | MCode version                                 |
+| `properties`                     | Common and event-specific fields listed below |
+| `type`                           | `track`                                       |
+| `event`                          | Event name from the table below               |
+| `time`                           | Unix timestamp in milliseconds                |
+
+Every `properties` object includes:
+
+| Field         | Value                                                        |
+| ------------- | ------------------------------------------------------------ |
+| `surface`     | `tui`                                                        |
+| `os`          | Node.js platform name, such as `darwin`, `linux`, or `win32` |
+| `region`      | `cn` or `en`                                                 |
+| `build_env`   | `dev`, `test`, `staging`, or `prod`                          |
+| `app_version` | MCode version                                                |
+
+Event-specific fields are limited to:
+
+- `tui_launch`: `launch_type` (`cold`, `hot`).
+- `login_click`, `logout_click`: no extra fields.
+- `login_result`: `source` (`agent_web`, `agent_desktop`, `openplatform`, `mcode_tui`, `mcode_cli`); `result_type` (`1` success, `2` failure); `fail_reason` (empty for success, `1` server, `2` network, `3` cancelled, `4` other, `5` OAuth/authorization); `login_type` (`google`, `mobile`, `wechat`, `apple`, `minimax_sso`, `minimax_oauth`).
+- `btw_session_lifecycle`: `phase` (`opened`, `closed`); `duration_bucket` (`not_applicable`, `under_1m`, `1m_to_5m`, `5m_to_30m`, `over_30m`); `exit_reason` (empty, `ctrl_c`, `ctrl_d`, `navigation`, `replaced`).
+- `chat_send`: `chat_type` (`chat`, `agent_team`, `claw`, `hermes`, `IM`); `is_first_message` (`0`, `1`); `is_attachment` (`text`, `attachment`).
+- `slash_command_menu_view`, `at_command_menu_view`: `chat_type` (values above).
+- `slash_command_click`: `chat_type`; `command_type` (`skill`, `new_chat`, `summarize`, `plan_mode`, `goal_mode`, `other`).
+- `at_command_click`: `chat_type`; `command_type` (`plugins`, `goal_mode`, `plan_mode`, `file`, `directory`).
+
+MCode does not send account IDs, device IDs, workspace paths or names, session IDs, model names, prompts, responses, filenames, command text, plugin names, or credentials through this channel. The receiver requires an identity-shaped envelope, so the client creates a fresh random event ID for each request. It is never persisted or reused and cannot link two events on its own. MCode does not add an account authorization header to these requests.
+
+As with any network request, the receiving server can observe transport metadata such as the source IP address. The client does not add that value to the event payload. `mcode telemetry preview` displays the decoded envelope.
+
+## Destinations
+
+The destination depends on region and build environment:
+
+- China production: `https://data.hailuoai.com/meerkat-reporter/api/report?project=MiniMaxAgent`
+- Global production: `https://data.hailuo.ai/meerkat-reporter/api/report?project=MiniMaxAgent`
+- China non-production: `https://bigdata-test.xingyeai.com/meerkat-reporter/api/report?project=MiniMaxAgent`
+- Global non-production: `https://bigdata-test.talkie-ai.com/meerkat-reporter/api/report?project=MiniMaxAgent`
+
+The client keeps pending events only in memory and does not write them to disk. This repository does not define or verify server-side retention. Keep telemetry disabled when that policy does not meet your requirements.
+
+This page covers TUI usage telemetry. Login, model requests, update checks, user-submitted feedback, and bounded error diagnostics have separate network behavior described in [TUI capability coverage](tui-capabilities.md).

+ 48 - 0
docs/tui-capabilities.md

@@ -0,0 +1,48 @@
+# TUI capability coverage
+
+The current capability target is **TUI 0.4.12**; see [version and evidence baseline](open-source-status.md#version-and-evidence-baseline) for the separate workspace and embedded-tool versions. “Restored” below describes implementation and assembly, not acceptance of every account or online service.
+
+The evidence column summarizes the historical TUI 0.3.11 restoration record from 2026-09-11. It does not claim fresh TUI 0.4.12 live-service acceptance. Use [current verification status](verification.md#current-source-verification-status) for checks run against the updated source and explicit NOT RUN boundaries.
+
+| Capability | Implementation | Evidence |
+| --- | --- | --- |
+| MiniMax login, logout, Token Plan, quota, check-in | OAuth Core, account clients, and TUI / CLI entry points restored | Login-state, auth-command, check-in, provider, and ACP tests; production Token Plan session and resume passed |
+| BYOK / custom models | Retained; headless model overrides no longer inherit the default Token Plan login requirement | Local protocol server drives runtime, resume, and file tools; live BYOK session passed; managed models still reject unauthenticated requests |
+| mcode-tools | Public package's unchanged 0.0.4 artifact, launcher, and short-lived token leases restored | Archive SHA-512, CLI SHA-256, real CLI startup, lease and host integration tests; production shared-broker authentication passed |
+| Search and Matrix image / audio / video tools | Matrix MCP and tool assembly restored; search is independent of mcode-tools | MCP configuration and auth-isolation tests; actual search passed; generation requests not run |
+| Official, local, and GitHub plugins | Official sources, marketplace reads, and installation control restored; local sources retained | Plugin application, source-page, and offline local CLI tests; actual official catalog read passed |
+| Managed connectors | Cloud client, permissions, and invocation adapters restored | Connector runtime and cloud transport tests; actual tool discovery passed; business writes not run |
+| Updates | Update entry points, install-source detection, and signature verification restored; public packages use public npm | Update application and service tests; no real installation / upgrade on the development machine |
+| Feedback and diagnostic uploads | Reviewed feedback text and minimized diagnostic summaries | Synthetic fixtures exercise session collection and capture/decode the final ZIP upload; no live uploads or real content |
+| Automatic LLM error reports | Bounded diagnostic facts minimized before encryption | Synthetic provider errors and native Headers; final HTTP batches captured and decrypted locally |
+| Telemetry | Disabled by default; explicit opt-in with environment overrides; account, device, workspace, session, model, and command identifiers removed | Privacy regression tests intercept and decode requests locally; no live upload |
+| Auto permissions | Cloud classifier restored; local rules and confirmation on failure retained | Classifier client, permission facade, and sandbox tests |
+| Model catalog | Online catalog and bundled snapshot fallback restored | Actual build boundary checks and offline startup; online catalog contents not accepted |
+| Files, shell, subagents, sessions, headless, ACP | Actual runtime retained | BYOK, file reads, session resume, ACP, sandbox, and status protocol tests |
+| Built-in skills, MCP, plugin tools | Original TUI assets and activation conditions retained | Asset build, plugin, and MCP tests; no claim that every skill has passed a real task |
+
+## Desktop boundary
+
+Background workspace indexing is removed from this distribution. Runtime startup and conversation turns do not collect workspace snapshots, create workspace ZIP archives, or upload/retry them for cloud indexing. The semantic workspace search tool and its enablement policy are also removed; a saved indexing preference cannot reactivate them. Existing indexing records are left inert. User-directed file reading, search, and Git operations remain available.
+
+Desktop features not enabled by default in the original TUI are outside this restoration commitment: remote encrypted prompt updates, cloud session handoff, and native Electron desktop control. Earlier descriptions incorrectly counted removal of those sources as TUI feature loss. Desktop HTTP services and internal generated IDL remain outside the public repository.
+
+Website deployment tools and routes follow the original tool set. Successful deployment still depends on login, service permissions, and backend support; no real deployment has been performed.
+
+## Release boundary
+
+Production client paths are restored without internal registries or test-service addresses as build dependencies. Real account behavior, quota, billing, model quality, media generation, and deployment require separate acceptance. Mocks, protocol fixtures, and successful builds do not replace that evidence. A private GitHub review repository is in place; the source repository remains private. Public npm `latest` was 0.4.12 on 2026-09-18; that metadata observation does not validate the installed package or deploy a backend. See `release-audit.md` for actual acceptance results.
+
+## Diagnostic upload privacy
+
+Automatic LLM error reports use an allowlist before buffering and encryption. Schema 3 retains a numeric release version, the fixed metric error category, known error names/codes, HTTP statuses (100–599), and bounded error/cause/properties relationships. It excludes error messages, stacks, headers (including native `Headers`), prompts, request/model metadata, URLs, arbitrary property names/values, and binary data. Unknown event types are dropped; the event type and code location are fixed at the reporter boundary. Encryption remains a transport layer, not redaction. Authenticated transport still uses the signed-in account token and user ID.
+
+The separate TUI incident reporter uses schema 2. It retains a fixed event category, phase/severity/impact, handled flag, generated IDs, timestamps, numeric release/Node versions, known platform/architecture, known error names/codes and HTTP status, and up to 20 fixed breadcrumb names with an optional phase. It excludes free-form error text, stack/cause/aggregate contents, caller context, component/operation labels, terminal/OS strings, and original code locations. Fingerprints are derived only from the minimized category and error facts, so grouping is intentionally coarser. Legacy schema-1 pending and sent files are deleted best-effort at startup and never uploaded; current-schema pending files are projected again before encryption and replaced with their minimized copy before being marked sent. The gateway wire encryption format is unchanged. Production ingestion of schema 2 has not been tested.
+
+Feedback review describes the actual upload: user-reviewed feedback text, bounded client/platform and optional session metadata, and diagnostic **counts**, not original session files. Recognized credentials are redacted from the reviewed description; arbitrary personal text in that description is still sent, so review it before submitting.
+
+Every collected diagnostic artifact, including prioritized session artifacts, is projected through `diagnostic-counts-v1`. The ZIP contains counts of known roles, states, error types/codes, log levels and HTTP statuses, plus parsing/omission indicators. JSON/JSONL can contribute these facts; malformed data, binary attachments and free-text logs contribute no raw content. Source filenames and paths are replaced with opaque archive names; only a small fixed list of artifact kinds (such as `messages.jsonl`) is retained. Unrelated session manifests are not collected. Local source files are unchanged.
+
+There is no raw-attachment upload option in this flow. Prompts, conversation text, tool arguments/results, command output, workspace excerpts, raw errors and unknown fields are excluded even if they contain no recognizable credential pattern. This intentionally reduces diagnostic detail: reproducing an exact response or inspecting an original stack is not possible from these uploads. Future raw attachments would require a separate, explicit review and consent surface describing their contents and scope.
+
+The regression tests use temporary synthetic files and intercepted HTTP only. They decrypt the final automatic-report request as a receiver would, and unzip the actual feedback PUT body after real session-report collection. They do not validate production ingestion of the new schemas, retention policies, live services, other telemetry paths or other platforms.

+ 140 - 0
docs/verification.md

@@ -0,0 +1,140 @@
+# Verification records
+
+## Public import preparation, 2026-09-18
+
+The private preparation branch adds official CLI onboarding and preserves the existing public Desktop support entry points. At implementation revision `1670bafd684ebf8dbb03dd41330ac2b099ffaf23`, `pnpm verify` passed all 14 applicable gates on macOS arm64, Node.js 26.4.0 and pnpm 9.12.0, including 3,352 capability tests. The six affected platform-fixture files passed locally after correcting PowerShell command quoting, SQLite teardown order, native path expectations, missing synthetic Windows prompt layers, and a fixture process holding a disappearing working directory. These are test-fixture repairs, not changes to runtime behavior.
+
+The source preparation also tests public issue-form routing and offline Feishu payload generation; no notification was sent. Active documentation links use production sites, and all six CLI documentation links returned HTTP 200. Local Markdown file targets resolved successfully. History and built-distribution Gitleaks scans completed without unaddressed findings under the reviewed configuration; the exported source received a separate scan.
+
+Subsequent Windows CI runs identified fixture teardown races: completed Bash tasks could still schedule database reads after the test closed SQLite. The fixture now closes delivery scheduling and drains background work before closing the database and removing files. The shared Vitest runner resolves Windows temporary directories to their canonical paths to avoid the [libuv short-path watcher assertion](https://github.com/libuv/libuv/issues/5010), with a subprocess regression covering its environment, arguments and exit status. The built image-preview artifact test now requires both a valid PNG reply and a clean Worker exit; it no longer immediately force-terminates the successful Worker. An earlier Node 22 native crash did not recur in the next unchanged-artifact run, so that observation alone is not treated as proof of its cause. The single Chinese documentation entry is `README_ZH.md`.
+
+A local import rehearsal starts from public destination revision `cd025375799a1360d499d5c06cfb2e1111a960fc`, copies only authenticated archive files, and creates one new commit on that public base. The first comparison exposed Git newline normalization in 14 vendored Office XML schemas. The preparation now marks those schema assets as non-normalizing in `.gitattributes` and includes a staging regression for CRLF bytes. Rehearsal acceptance requires the imported Git tree to equal the reviewed source tree exactly, and the new reachable commit count to equal one. This local branch must not be pushed as part of private preparation.
+
+Final cross-platform and source-candidate results belong to the private preparation PR's final head; local passes do not establish Windows/Linux acceptance. Existing main runs were blocked before startup by billing, while later dependency-PR runs executed and exposed the Windows fixture failures above. Check current run annotations rather than carrying the older billing diagnosis forward. Fresh managed login, real model requests, interactive Windows/Linux use and official installer replacement were not performed in this preparation. Publication authorization, an independent human review and destination administrative settings remain separate release-owner steps.
+
+## Dependency security and unused implementation cleanup, 2026-09-18
+
+The standalone workspace pins Vitest and its coverage package to 4.1.11, Vite to 7.3.6, Hono to 4.13.5, and Ajv's fast-uri to 3.1.6 through root overrides. The runtime uses smol-toml 1.7.1. Central overrides also cover vendored workspace development dependencies without rewriting upstream manifests. The suite launcher resolves the executable from Vitest's package manifest because the newer package no longer exports its CLI as a module subpath.
+
+The TOML import regression runs the actual AgentImportService in a bounded child process: valid input succeeds, while comments ending unterminated arrays or inline tables are rejected. A subprocess timeout prevents a synchronous parser regression from hanging the test runner.
+
+The unused Team cycle engine and two unreferenced adapters are removed. Legacy queue, lock and run-location modules retain the compatibility types required by shared adapters; their unused implementations are removed in place. The source inventory, package paths, lockfile and declared dependency licenses are regenerated. This change does not claim live-service acceptance or publication authorization.
+
+## Current source verification status
+
+The current source target is TUI **0.4.12**, with the separate versions described in [Preparation status](open-source-status.md#version-and-evidence-baseline). The 0.3.11 results below remain a historical record and have not been relabeled as current acceptance.
+
+On 2026-09-12, source commit `edbd4bd483f9326fae14bed6852950f371d4feab` exported successfully without Git history: the source gate verified 4,090 files, workspace exports and native helper integrity; generated TypeScript paths matched 119 exports. These checks do not establish a complete build, test or live-service pass.
+
+The Source verification and Release audit workflow runs for that commit failed before their jobs started. GitHub reported failed account payments or a spending-limit issue. Platform verification and the candidate job were skipped; no candidate artifact was generated for that run. This is an infrastructure block, not evidence of a code-test failure.
+
+Current TUI 0.4.12 live-service acceptance, fresh login/logout, cross-platform interactive acceptance and a validated three-platform source candidate remain **NOT RUN / unavailable**. Add subsequent results with their revision, environment and scope instead of replacing the historical record.
+
+### Source synchronization verification, 2026-09-18
+
+The reviewed shared-source baseline is `9b9885e42a3cf1a3df1cfa52a46e4fdb034cfcee` (TUI 0.4.12). The standalone projection preserves its process-local protocol and public service configuration. Desktop HTTP/generated transports, cloud handoff, private packaging, and unrelated desktop additions remain excluded.
+
+`pnpm verify` passed all 14 gates on macOS arm64, Node.js 26.4.0 and pnpm 9.12.0: source inventory (4,210 files), generated paths (121 exports), source export, release tooling (13 tests), typecheck, build, standalone boundary, built artifacts (4 tests), capabilities (2,679 tests), status contract (9 tests), CLI/ACP smoke (7 tests), offline BYOK (1 test), permission policy (115 tests), and macOS sandbox (48 tests). The artifact checks start the packaged image-preview Worker, and the sandbox suite includes real `sandbox-exec` and Git probes.
+
+The expanded regressions cover model effort, headless preparation cancellation and response usage, image previews, MCP naming and cancellation, background Bash, prompt/agent storage, provider discovery, and content-safety V2. Image-header fixtures are synthetic; production-request images are excluded. Secret scanning covers all Git refs, the exported source, and build artifacts; the test token uses an explicit short placeholder.
+
+Windows/Linux execution, fresh managed-account login, real provider calls, and live content-safety V2 endpoints were not run locally. Offline BYOK fixtures do not establish live-model acceptance. This synchronization does not publish an npm release or change repository visibility.
+
+### Release-preparation verification, 2026-09-12
+
+`pnpm verify` was run on `3de31f0e365e635c52d661c0a14c9ee69e65f099` in an isolated worktree after a frozen-lockfile install, on macOS arm64 with Node.js 26.4.0 and pnpm 9.12.0.
+
+| Gate | Result |
+| --- | --- |
+| Source inventory, workspace exports and native helper integrity | PASS: 4,096 reviewed files |
+| Generated TypeScript paths | PASS: 119 exports |
+| History-free source export | PASS |
+| Release tooling | PASS: 13 tests |
+| Full typecheck | FAIL: `packages/tui/src/cli/network-proxy.ts:134`, TS2724; installed Undici 8 exposes `Dispatcher.DispatchHandler`, while the source references `Dispatcher.DispatchHandlers` |
+| Build, standalone checks, artifact/capability/status/smoke/BYOK/policy/sandbox tests | NOT RUN: the full verifier stopped at typecheck |
+
+The failing source file and dependency lockfile are unchanged from the reviewed base `edbd4bd483f9326fae14bed6852950f371d4feab`. At that revision, the preparation changed release metadata, attribution and contributor documentation without repairing the runtime/dependency mismatch. The follow-up below resolves it. A documentation-profile pass must not be substituted for full current-source acceptance.
+
+### Merge-review follow-up, 2026-09-12
+
+Commit `67ad241fb201c618bdedfba5998f7a6fb6f1d0cf` updates the proxy dispatcher's handler annotation to `Dispatcher.DispatchHandler`, matching Undici 8's installed `dispatch` signature. It forwards the handler unchanged and changes no runtime behavior.
+
+On that commit, `pnpm verify` **passed all 14 applicable gates** on macOS arm64, Node.js 26.4.0, pnpm 9.12.0: source checks, generated paths, history-free export, release tooling, typecheck, build, standalone checks, artifact/capability/status/smoke/BYOK/policy/sandbox tests. The capability suite passed 412 tests; the existing real macOS sandbox probes also passed. Local Gitleaks scans of complete Git history, the committed source snapshot and the built distribution reported no findings with the reviewed `.gitleaks.toml` rules.
+
+This resolves the local typecheck failure recorded above. It does not establish Windows/Linux acceptance, successful GitHub Actions runs, a three-platform source candidate or fresh live-service acceptance. The GitHub billing/spending-limit block and publication/admin prerequisites remain separate from this local verification result.
+
+## Historical TUI 0.3.11 acceptance
+
+Verification date: 2026-09-11. Environment: macOS arm64, Node.js 26.4.0, pnpm 9.12.0. Capability baseline: TUI 0.3.11.
+
+This record preserves the clean-directory baseline from managed-capability restoration and adds private release review evidence. Passing tests do not mean all online services have passed acceptance; live evidence appears below and in `release-audit.md`.
+
+## Clean-directory acceptance
+
+Final source was copied outside the repository without `.git`, `node_modules`, `dist`, or `.cache`. A new pnpm store and public npm only were used for a frozen-lockfile install. The build downloaded the pinned MCode package again and extracted mcode-tools without reusing development artifacts.
+
+| Check | Result |
+| --- | --- |
+| Cold install from public npm | Passed, approximately 1 minute 15 seconds |
+| Source inventory, internal references, workspace exports, native helper integrity | Passed, 3979 files at this baseline |
+| TypeScript check of the complete entry point | Passed |
+| Standalone build and dependency boundaries | Passed; key managed capabilities remained in the output |
+| Login, leases, accounts, plugins, connectors, feedback, updates, ACP, Matrix configuration | 21 explicitly selected test files; 321 tests passed |
+| Original mcode-tools archive / file hashes, tamper rejection, actual CLI startup | 3 passed |
+| CLI, providers, SQLite, ACP initialization, internal-switch rejection, offline local plugins | 7 passed |
+| BYOK, session resume, actual file tools, managed-model authentication gate | 1 passed |
+| Existing permission facade | 115 passed |
+| Vela status protocol | 9 passed |
+| Sandbox, executable resolution, actual macOS file / Git probes | 48 passed |
+
+**504 automated tests passed** in total, with relevant validation completed in both development and clean directories.
+
+The BYOK test uses a local OpenAI-format protocol server to drive the actual runtime. It verifies authorization headers, resume history, and real file contents in subsequent model requests, while ensuring Token Plan model overrides still require login. It does not establish real provider quality or production availability.
+
+After managed capabilities were restored, startup could request the model catalog and telemetry. Offline tests return local 503 responses for an explicit public-service allowlist, recording attempts without sending them. Unknown addresses and unexpected TCP connections still fail tests. This verifies some unavailable-service behavior; those failures are not counted as live-service successes.
+
+## Real TUI inspection
+
+A real PTY with an isolated data directory and the network guard confirmed:
+
+- Welcome shows Token Plan as unauthenticated.
+- `/provider` presents both MiniMax OAuth / Token Plan and API key options.
+- `/login` opens a cancellable China / international region selector.
+- `/plugins` shows a clear error for an injected 503. Successful loading and source switching have component / application coverage; this manual check did not connect successfully to the official marketplace.
+- `/exit` exits normally and restores terminal state.
+
+That offline PTY check did not open a browser or call a real model. Subsequent online acceptance with an existing account is recorded separately below.
+
+## Private release preparation additions
+
+- Three tests cover source synchronization candidates, preservation of public changes, conflicts, and unsafe-output rejection. A no-change comparison against the actual baseline reported zero changes.
+- Full-history, source-snapshot, and build-artifact Gitleaks scans were added. GitHub `Release audit` passed; see `release-audit.md` for false-positive handling and case sanitization.
+- Initial Windows CI exposed Git CRLF conversion affecting native helper hashes. `.gitattributes` now pins LF. Later fixes addressed POSIX temporary paths, mock install layouts, and cmd quoting in tests. The relevant 70 tests passed locally; use PR checks for final platform results.
+- GitHub runs macOS / Windows / Linux × Node.js 22 / 24. Each includes frozen install, source checks, source export, build, boundaries, tool artifacts, the 321-case capability suite, status protocol, smoke, and BYOK. Type checking runs once in the Linux / Node.js 22 full profile; the other five jobs use the platform profile, omitting only that compiler gate. Windows skips one POSIX-only capability case. Permission facade tests run outside Windows; actual sandbox probes run on macOS. GitHub runner success is not an interactive user-path check on each physical platform.
+
+## Live production-account acceptance
+
+Using the user-authorized existing login and dedicated temporary workspaces, the following were confirmed:
+
+- A Token Plan MiniMax-M3 session succeeded; resume recovered the previous marker.
+- BYOK provider connectivity and a real model session succeeded.
+- Events confirmed a successful actual `web_search` call. A separate response that returned a URL without calling the tool was not counted.
+- The official plugin marketplace returned 54 available plugins.
+- Real bash → mcode-tools → host-lease authentication succeeded. Connector discovery returned 13 tools with no provider failures.
+
+Actual service responses, credentials, and local account paths were not committed. Only synthetic acceptance results are recorded; this does not claim business calls for every plugin or generation tool.
+
+## Not yet verified
+
+- Fresh browser login / logout, full membership quota and billing validation, paid media generation, website deployment, new third-party connector grants / business writes, and feedback / diagnostic uploads.
+- Interactive TUI user paths on Windows and Linux; GitHub runner builds and tests are recorded separately.
+- Actual update installation / upgrade; the development machine's global installation was not changed.
+- Real task quality for each bundled skill, and Desktop features outside the original TUI's defaults.
+
+This historical acceptance did not publish the GitHub source repository or an npm package. The official npm product has a separate release history; its currently verified version is listed in [Preparation status](open-source-status.md). TypeScript remains strict; `noUncheckedIndexedAccess` and `noImplicitOverride` retain the vendored libraries' existing compatibility settings.
+
+## Windows timeout investigation, 2026-09-12
+
+On commit `4e7582c`, the Windows / Node.js 22 BYOK fixture exceeded its 35-second child-process deadline; the other six CI checks passed. The original failure reported only `Timed out: exec`, without the command phase or captured output, so it does not establish whether execution or process shutdown stalled.
+
+The fixture now records per-command duration, bounded stdout / stderr and execution progress on timeout, plus an opt-in unreferenced process-resource probe. It waits for child `close` before reading complete output, and force-terminates timed-out children before cleanup. The 35-second deadline, 90-second overall bound, default text output, and BYOK / resume / actual-file assertions remain. No runtime behavior or timeout was relaxed. Use the latest PR run for the result; a passing follow-up does not by itself explain the earlier timeout.

+ 9 - 0
examples/clamp/README.md

@@ -0,0 +1,9 @@
+# Fix the clamp function
+
+This intentionally incorrect function is a small MiniMax Code coding exercise. Copy this directory to a temporary location before trying it. Running `node --test` on the original version produces two failing tests.
+
+Ask MiniMax Code to read the function and tests, reproduce the failure, fix the function, and run the tests again. Do not change the tests to make them pass.
+
+Expected behavior: `clamp(5, 0, 10)` returns `5`, `clamp(-3, 0, 10)` returns `0`, and `clamp(14, 0, 10)` returns `10`.
+
+See the [demo and recording notes](../../docs/demo.md).

+ 4 - 0
examples/clamp/clamp.mjs

@@ -0,0 +1,4 @@
+// Intentionally incorrect: use this small fixture to try a coding task.
+export function clamp(value, min, max) {
+  return Math.min(min, Math.max(max, value));
+}

+ 6 - 0
examples/clamp/clamp.test.mjs

@@ -0,0 +1,6 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { clamp } from './clamp.mjs';
+test('keeps values inside the range', () => assert.equal(clamp(5, 0, 10), 5));
+test('clamps below the minimum', () => assert.equal(clamp(-3, 0, 10), 0));
+test('clamps above the maximum', () => assert.equal(clamp(14, 0, 10), 10));

+ 63 - 0
package.json

@@ -0,0 +1,63 @@
+{
+  "name": "minimax-code",
+  "version": "0.4.12",
+  "private": true,
+  "type": "module",
+  "description": "Standalone MiniMax Code TUI with managed accounts, BYOK models, cloud tools, plugins and ACP.",
+  "packageManager": "pnpm@9.12.0",
+  "engines": {
+    "node": ">=22.19 <23 || >=24.2 <27"
+  },
+  "scripts": {
+    "build": "node scripts/build.mjs",
+    "start": "node dist/cli.js",
+    "mcode": "node dist/cli.js",
+    "verify": "node scripts/verify.mjs",
+    "test:smoke": "node --test test/smoke.test.mjs",
+    "test:policy": "node scripts/run-vitest-suite.mjs policy",
+    "test:byok": "node --test test/byok.test.mjs",
+    "check:standalone": "node scripts/check-standalone-boundary.mjs",
+    "check:tsconfig": "node scripts/gen-tsconfig-paths.mjs",
+    "gen:tsconfig": "node scripts/gen-tsconfig-paths.mjs --write",
+    "typecheck": "tsc -p tsconfig.standalone.json",
+    "test:sandbox": "node scripts/run-vitest-suite.mjs sandbox",
+    "test:status-contract": "node scripts/run-vitest-suite.mjs status-contract",
+    "check:source": "node scripts/source-inventory.mjs",
+    "test:capabilities": "node scripts/run-vitest-suite.mjs capability",
+    "test:artifact": "node --test test/public-artifact.test.mjs",
+    "test:release-tools": "node --test test/source-sync.test.mjs"
+  },
+  "devDependencies": {
+    "@types/node": "^20.19.0",
+    "@typescript/native-preview": "7.0.0-dev.20260707.2",
+    "esbuild": "0.28.2",
+    "prettier": "3.9.6",
+    "shx": "^0.4.0",
+    "tsx": "4.23.13",
+    "typescript": "5.9.3",
+    "vitest": "4.1.11",
+    "yaml": "2.9.0",
+    "tar": "7.5.22",
+    "vite": "7.3.6"
+  },
+  "pnpm": {
+    "onlyBuiltDependencies": [
+      "better-sqlite3",
+      "esbuild",
+      "node-pty"
+    ],
+    "overrides": {
+      "react": "18.3.1",
+      "react-dom": "18.3.1",
+      "@modelcontextprotocol/sdk>@hono/node-server": "2.0.12",
+      "minimatch@>=10.2.5>brace-expansion": "5.0.9",
+      "ajv>fast-uri": "3.1.6",
+      "express-rate-limit>ip-address": "10.4.0",
+      "vitest": "4.1.11",
+      "@vitest/coverage-v8": "4.1.11",
+      "vite": "7.3.6",
+      "hono": "4.13.5"
+    }
+  },
+  "license": "MIT"
+}

+ 88 - 0
packages/agent-core/package.json

@@ -0,0 +1,88 @@
+{
+  "name": "@mavis/agent-core",
+  "version": "0.2.1",
+  "description": "Shared agent runtime contracts and PiTurnRunner assembly layer for Mavis local/cloud hosts.",
+  "type": "module",
+  "types": "./src/index.ts",
+  "exports": {
+    ".": {
+      "types": "./src/index.ts",
+      "import": "./dist/index.js"
+    },
+    "./protocol": {
+      "types": "./src/protocol/index.ts",
+      "import": "./dist/protocol/index.js"
+    },
+    "./protocol/agent-message": {
+      "types": "./src/protocol/agent-message.ts",
+      "import": "./dist/protocol/agent-message.js"
+    },
+    "./protocol/runtime-event": {
+      "types": "./src/protocol/runtime-event.ts",
+      "import": "./dist/protocol/runtime-event.js"
+    },
+    "./event-bridge": {
+      "types": "./src/event-bridge/index.ts",
+      "import": "./dist/event-bridge/index.js"
+    },
+    "./pi-turn-runner": {
+      "types": "./src/pi-turn-runner/index.ts",
+      "import": "./dist/pi-turn-runner/index.js"
+    },
+    "./tools": {
+      "types": "./src/tools/index.ts",
+      "import": "./dist/tools/index.js"
+    },
+    "./bash-subprocess-env": {
+      "types": "./src/bash-subprocess-env.ts",
+      "import": "./dist/bash-subprocess-env.js"
+    },
+    "./prompt-read": {
+      "types": "./src/prompt-read.ts",
+      "import": "./dist/prompt-read.js"
+    }
+  },
+  "typesVersions": {
+    "*": {
+      "protocol": [
+        "src/protocol/index.ts"
+      ],
+      "protocol/agent-message": [
+        "src/protocol/agent-message.ts"
+      ],
+      "protocol/runtime-event": [
+        "src/protocol/runtime-event.ts"
+      ],
+      "event-bridge": [
+        "src/event-bridge/index.ts"
+      ],
+      "pi-turn-runner": [
+        "src/pi-turn-runner/index.ts"
+      ],
+      "tools": [
+        "src/tools/index.ts"
+      ],
+      "prompt-read": [
+        "src/prompt-read.ts"
+      ]
+    }
+  },
+  "dependencies": {
+    "@mavis/protocol": "workspace:^",
+    "@mavis/shared": "workspace:^",
+    "@earendil-works/pi-agent-core": "workspace:*",
+    "@earendil-works/pi-ai": "workspace:*",
+    "@earendil-works/pi-coding-agent": "workspace:*",
+    "@sinclair/typebox": "^0.34.0",
+    "zod": "^3"
+  },
+  "devDependencies": {
+    "@mavis/config": "workspace:^",
+    "@types/node": "^20",
+    "tsx": "^4",
+    "typescript": "^5",
+    "vitest": "^2"
+  },
+  "private": true,
+  "license": "MIT"
+}

+ 273 - 0
packages/agent-core/src/bash-subprocess-env.ts

@@ -0,0 +1,273 @@
+/**
+ * Bash subprocess environment sanitizer — two independent layers applied
+ * before every bash tool child spawn (foreground LocalBashTool, background
+ * bash executor, and the pi-turn-runner builtin fallback).
+ *
+ * Layer A — MCode runtime boundary strip. ALWAYS on, no escape hatch.
+ *   Reuses the env-builder boundary key lists verbatim (import, never fork):
+ *   runtime/parent identity, session ids, profile/dataDir/port keys, safety
+ *   switches, and ASR proxy auth. Leaking these is not a "secret exfil"
+ *   problem but a boundary-correctness one: a child could impersonate the
+ *   parent session against the runtime API, or a nested `mavis` CLI inside
+ *   bash would silently bind to the parent runtime's profile.
+ *
+ * Layer B — third-party secret scrub. GATED, mirroring the reference CLI's
+ *   `subprocessEnv()` design (src/utils/subprocessEnv.ts):
+ *     - `off`    (interactive default): do not strip user secrets. CC parity —
+ *                interactive users rely on env credentials (gh, npm, ...).
+ *     - `scrub`  (auto in CI / non-interactive): precise blocklist of
+ *                credentials the *parent* process needs but subprocesses never
+ *                do. GH_TOKEN / GITHUB_TOKEN / NPM_TOKEN are intentionally NOT
+ *                on the list (CC parity: subprocesses have legitimate uses).
+ *     - `strict` (opt-in): pattern-based strip of credential-looking names,
+ *                with a protected-system-vars floor and an allowlist hatch.
+ *
+ * @module
+ */
+
+import { isAbsolute } from 'node:path';
+
+import { stripRuntimeBoundaryKeysFrom } from '@mavis/shared/runtime-boundary-env';
+
+export type BashEnvSanitizeMode = 'off' | 'scrub' | 'strict';
+
+export interface BashEnvPolicy {
+  mode: BashEnvSanitizeMode;
+  /** Names exempt from the `strict` pattern strip. Never applies to Layer A. */
+  allowlist?: readonly string[];
+  /**
+   * Absolute directories prepended to `PATH` for every bash subprocess.
+   *
+   * Used by the desktop runtime to install command shims (currently the
+   * recoverable-delete `rm` shim) so the EXECUTION layer decides how a verb is
+   * carried out, without any caller having to parse or rewrite command text.
+   * agent-core stays agnostic about what the directories contain.
+   */
+  prependPath?: readonly string[];
+  /**
+   * Host-injected gate that runs before every bash subprocess launch; throwing
+   * blocks the spawn. The desktop runtime uses it to verify — and re-seed when
+   * possible — the recoverable-delete `rm` shim, so a lost shim fails the
+   * spawn loudly instead of silently resolving `/bin/rm` (fail-closed). It is
+   * a callback rather than data because agent-core must stay free of
+   * filesystem imports (host boundary): only the host knows what the shim
+   * directories are supposed to contain and how to repair them.
+   */
+  spawnPreflight?: () => void;
+}
+
+export interface BashEnvSanitizeResult {
+  /** New env object; the input is never mutated. */
+  env: NodeJS.ProcessEnv;
+  /** Names (never values) of removed vars, sorted, for tool-result hints. */
+  removed: string[];
+}
+
+/**
+ * Precise `scrub` blocklist. Selection rule (reference CLI GHA_SUBPROCESS_SCRUB
+ * parity): the parent process needs these for API calls / lazy SDK reads, but
+ * bash subprocesses never legitimately do. Each entry also strips its
+ * `INPUT_<NAME>` alias (GitHub Actions duplicates `with:` inputs that way).
+ *
+ * Deliberately NOT listed (CC parity — legitimate subprocess uses):
+ * GH_TOKEN, GITHUB_TOKEN (gh CLI), NPM_TOKEN (private registry installs).
+ */
+export const BASH_SUBPROCESS_SCRUB: readonly string[] = [
+  // Provider / LLM auth — the runtime re-reads these per-request itself
+  'ANTHROPIC_API_KEY',
+  'ANTHROPIC_AUTH_TOKEN',
+  'CLAUDE_CODE_OAUTH_TOKEN',
+  'ANTHROPIC_FOUNDRY_API_KEY',
+  'ANTHROPIC_CUSTOM_HEADERS',
+  'OPENAI_API_KEY',
+
+  // OTLP exporter headers — documented to carry Authorization bearer tokens
+  'OTEL_EXPORTER_OTLP_HEADERS',
+  'OTEL_EXPORTER_OTLP_LOGS_HEADERS',
+  'OTEL_EXPORTER_OTLP_METRICS_HEADERS',
+  'OTEL_EXPORTER_OTLP_TRACES_HEADERS',
+
+  // Cloud provider creds — lazy SDK reads in the parent only
+  'AWS_SECRET_ACCESS_KEY',
+  'AWS_SESSION_TOKEN',
+  'AWS_BEARER_TOKEN_BEDROCK',
+  'GOOGLE_APPLICATION_CREDENTIALS',
+  'AZURE_CLIENT_SECRET',
+  'AZURE_CLIENT_CERTIFICATE_PATH',
+
+  // GitHub Actions OIDC + artifact/cache API — repo-takeover / supply-chain pivots
+  'ACTIONS_ID_TOKEN_REQUEST_TOKEN',
+  'ACTIONS_ID_TOKEN_REQUEST_URL',
+  'ACTIONS_RUNTIME_TOKEN',
+  'ACTIONS_RUNTIME_URL',
+
+  // MCode-side additions — runtime-only integration tokens, no subprocess use
+  'FIGMA_API_TOKEN',
+  'FIGMA_TOKEN',
+  'E2E_AUTH_TOKEN',
+];
+
+/**
+ * Credential keyword core (regex source fragment, no anchors/flags) shared by
+ * {@link SENSITIVE_ENV_NAME_RE} here and the permission layer's secret-read
+ * command patterns (`echo $X`, `printenv X`). Single source so the two stay
+ * aligned — a sync-guard test asserts the permission side imports this.
+ */
+export const SENSITIVE_ENV_KEYWORD_CORE =
+  'API_?KEY|KEY|SECRET|TOKEN|PASSWORD|PASSWD|CREDENTIALS?|PRIVATE_?KEY';
+
+/**
+ * Credential-looking env var names for the `strict` mode and for the
+ * permission layer's secret-read command rules (`echo $X`, `printenv X`).
+ * Segment-bounded on `_`/start/end so MONKEY / TOKENIZER / KEYBOARD survive.
+ */
+export const SENSITIVE_ENV_NAME_RE = new RegExp(
+  `(?:^|_)(?:${SENSITIVE_ENV_KEYWORD_CORE})S?(?:_|$)`,
+  'i',
+);
+
+/** System vars the `strict` pattern must never strip (POSIX + Windows). */
+const PROTECTED_ENV_NAMES: ReadonlySet<string> = new Set([
+  'PATH',
+  'HOME',
+  'SHELL',
+  'LANG',
+  'LOGNAME',
+  'USER',
+  'TERM',
+  'TMPDIR',
+  // Windows
+  'SYSTEMROOT',
+  'COMSPEC',
+  'TEMP',
+  'TMP',
+  'USERPROFILE',
+  'APPDATA',
+  'LOCALAPPDATA',
+]);
+
+function isProtectedName(name: string): boolean {
+  const upper = name.toUpperCase();
+  return PROTECTED_ENV_NAMES.has(upper) || upper.startsWith('LC_');
+}
+
+function isEnvTruthy(value: string | undefined): boolean {
+  if (!value) return false;
+  return !['0', 'false', 'no', 'off'].includes(value.toLowerCase());
+}
+
+const VALID_MODES: ReadonlySet<string> = new Set(['off', 'scrub', 'strict']);
+
+/**
+ * Resolve the effective Layer B policy. Precedence: explicit override >
+ * `MAVIS_BASH_ENV_SANITIZE` env switch > auto (CI markers → `scrub`,
+ * otherwise `off` — interactive default, reference CLI parity).
+ */
+export function resolveBashEnvPolicy(
+  overrides?: Partial<BashEnvPolicy>,
+  envSource: NodeJS.ProcessEnv = process.env,
+): BashEnvPolicy {
+  let mode: BashEnvSanitizeMode | undefined = overrides?.mode;
+  if (mode === undefined) {
+    const explicit = envSource.MAVIS_BASH_ENV_SANITIZE?.trim().toLowerCase();
+    if (explicit && VALID_MODES.has(explicit)) {
+      mode = explicit as BashEnvSanitizeMode;
+    } else if (isEnvTruthy(envSource.CI) || isEnvTruthy(envSource.GITHUB_ACTIONS)) {
+      mode = 'scrub';
+    } else {
+      mode = 'off';
+    }
+  }
+  return {
+    mode,
+    ...(overrides?.allowlist ? { allowlist: overrides.allowlist } : {}),
+    ...(overrides?.prependPath ? { prependPath: overrides.prependPath } : {}),
+    ...(overrides?.spawnPreflight ? { spawnPreflight: overrides.spawnPreflight } : {}),
+  };
+}
+
+export function sanitizeBashSubprocessEnv(
+  env: NodeJS.ProcessEnv,
+  policy: BashEnvPolicy,
+): BashEnvSanitizeResult {
+  policy.spawnPreflight?.();
+  const out: NodeJS.ProcessEnv = { ...env };
+  const removed: string[] = [];
+
+  // Layer A — MCode boundary strip. Always on; allowlist deliberately ignored.
+  removed.push(...stripRuntimeBoundaryKeysFrom(out, 'agent-runtime'));
+
+  // Layer B — third-party secret scrub, gated by mode.
+  if (policy.mode === 'scrub') {
+    for (const key of BASH_SUBPROCESS_SCRUB) {
+      for (const name of [key, `INPUT_${key}`]) {
+        if (out[name] !== undefined) removed.push(name);
+        delete out[name];
+      }
+    }
+  } else if (policy.mode === 'strict') {
+    const allow = new Set((policy.allowlist ?? []).map((name) => name.toUpperCase()));
+    for (const name of Object.keys(out)) {
+      if (isProtectedName(name)) continue;
+      if (allow.has(name.toUpperCase())) continue;
+      if (!SENSITIVE_ENV_NAME_RE.test(name)) continue;
+      if (out[name] !== undefined) removed.push(name);
+      delete out[name];
+    }
+  }
+
+  removed.sort();
+  applyPathPrefix(out, policy.prependPath);
+  return { env: out, removed };
+}
+
+/**
+ * Prepend runtime-managed shim directories to PATH, de-duplicating so repeated
+ * spawns cannot grow the variable without bound. Relative entries are ignored:
+ * a relative shim directory would resolve against the command's cwd and could
+ * be shadowed by repository content.
+ */
+function applyPathPrefix(env: NodeJS.ProcessEnv, prependPath?: readonly string[]): void {
+  if (!prependPath?.length) return;
+  const separator = process.platform === 'win32' ? ';' : ':';
+  const existing = env.PATH ?? env.Path ?? '';
+  const current = existing.split(separator).filter((entry) => entry !== '');
+  const additions = prependPath.filter(
+    (dir) => isAbsolute(dir) && !current.includes(dir),
+  );
+  if (additions.length === 0) return;
+  const nextPath = [...additions, ...current].join(separator);
+  // Windows env lookups are case-insensitive but the object keys are not:
+  // overwrite whichever casing the inherited environment actually used.
+  if (env.PATH === undefined && env.Path !== undefined) env.Path = nextPath;
+  else env.PATH = nextPath;
+}
+
+/**
+ * Minimal structural type of pi's `BashSpawnContext` — kept structural so
+ * this module needs no dependency on the vendored pi packages.
+ */
+export interface BashSpawnContextLike {
+  command: string;
+  cwd: string;
+  env: NodeJS.ProcessEnv;
+}
+
+/**
+ * Factory for a pi `createBashTool` spawnHook applying this sanitizer.
+ * Used by the non-interactive bash spawn sites (background executor and
+ * pi-turn-runner builtin fallback). The interactive LocalBashTool uses an
+ * equivalent inline hook instead so it can also capture the removed variable
+ * names for a one-time UX hint (`details.envSanitized`); the sanitizer applied
+ * is identical — only the removed-name capture differs.
+ */
+export function createBashEnvSpawnHook(
+  policy: BashEnvPolicy,
+  onSanitized?: (removed: string[]) => void,
+): <T extends BashSpawnContextLike>(ctx: T) => T {
+  return (ctx) => {
+    const { env, removed } = sanitizeBashSubprocessEnv(ctx.env, policy);
+    onSanitized?.(removed);
+    return { ...ctx, env };
+  };
+}

+ 1068 - 0
packages/agent-core/src/event-bridge/bridge.ts

@@ -0,0 +1,1068 @@
+/**
+ * `EventBridge` — convert pi `AgentEvent` stream to canonical `RuntimeEvent[]`.
+ *
+ * Callers feed pi events into the bridge as they arrive from
+ * `agentLoop()` / `Agent.subscribe()`; the bridge tracks
+ * per-turn state (active assistant `message_id`, chunk index, thinking
+ * timing) and emits the wire-level frames via {@link BridgedEvents.events}.
+ *
+ * The bridge is **per-turn**: callers create a new instance for every
+ * pi run, feed events to {@link processEvent} until the loop concludes,
+ * then call one of the terminal helpers ({@link emitCompleted},
+ * {@link emitAborted}, {@link emitFailed}) to close the turn with a
+ * terminal `session.status` frame.
+ *
+ * ### Scope: canonical stream only
+ *
+ * The bridge emits only the canonical streaming surface (`stream.resp`
+ * chunks + `completedAssistantMessage` + terminal status + `debug.trace`).
+ * The `message.persisted` side-channel events live OUTSIDE this layer —
+ * SessionController emits them right after `messageStore.append` (for
+ * both user and pi messages) because the bridge is a stateless
+ * `AgentEvent → RuntimeEvent[]` transformer with no access to the
+ * MessageStore-assigned ids and no view of user messages at all. Do
+ * NOT add `message.persisted` emission here.
+ *
+ * ### Message-id allocation contract
+ *
+ * pi assigns no `message_id` to assistant messages; the host owns that
+ * identity (e.g. via {@link MessageStore}). On the first
+ * `message_start` for an assistant role, the bridge returns an empty
+ * `events` array with `requestAssistantMessageId = true`. The caller
+ * MUST allocate a fresh id and call
+ * {@link setActiveAssistantMessageId} before delivering the next event.
+ * Until then, deltas are buffered conservatively — text/thinking deltas
+ * arriving without an active message id are dropped (with a debug trace)
+ * because they have no anchor.
+ *
+ * ### Thread-safety
+ *
+ * Bridges are NOT thread-safe — feed events serially. Per-event-loop
+ * usage is fine; pi delivers events synchronously inside `Agent.subscribe`.
+ *
+ * ### Side-effects
+ *
+ * The bridge mutates only its own per-turn state (chunk index counter,
+ * message id slot, thinking timer). Completed AgentMessage conversion may
+ * invoke the host-provided `respDataTransform`; transform failures are
+ * logged through agent-core's logger and fall back to the original RespData.
+ * Terminal failure messages are encoded as `debug.trace` events for the
+ * host to push.
+ *
+ * @see packages/cloud-runtime/README.md
+ */
+
+import type { AgentEvent } from '@earendil-works/pi-agent-core';
+import { LLM_ERROR_CODES, classifyLLMErrorToCode } from '@mavis/shared/llm-error-classifier';
+import {
+  InstalledPluginSource,
+  PluginCapabilityType,
+  type IPluginCapabilityProvenance,
+} from '@mavis/protocol';
+import type { RuntimeProtocolError, RuntimeToolCall } from '../protocol/runtime-event.js';
+import type { TokenUsage } from '../protocol/agent-message.js';
+import {
+  buildAbortedTerminalStatusEvent,
+  buildCompletedAssistantMessage,
+  buildCompletedTerminalStatusEvent,
+  buildDebugTraceEvent,
+  buildFailedTerminalStatusEvent,
+  buildFinishChunk,
+  buildTextDeltaChunk,
+  buildThinkingDeltaChunk,
+  buildToolCallChunk,
+  extractAssistantErrorMessage,
+  extractAssistantStopReason,
+  extractAssistantText,
+  extractAssistantThinking,
+  extractAssistantToolCalls,
+  extractAssistantUsage,
+  extractDeltaUpdate,
+  isAssistantError,
+  type ToolCallStreamUpdate,
+} from './converters.js';
+import type { BridgedEvents, EventBridgeContext, TurnTerminationReason } from './types.js';
+
+const defaultNowMs = () => Date.now();
+
+/**
+ * Fallback context window when the host does not supply one via
+ * {@link EventBridgeContext.contextWindow}. Kept at 200_000 to preserve
+ * pre-`feat/pi-integration-gaps` behaviour for callers that have not
+ * been updated yet — the bridge logs once when this fallback fires so
+ * observers can spot the misconfiguration.
+ */
+const DEFAULT_CONTEXT_WINDOW = 200_000;
+
+/**
+ * Runtime-side mirror of the UI typed session error messages
+ * (`packages/ui/src/i18n/locales/*::errors.codes`).
+ *
+ * Keep a local copy to avoid making `@mavis/agent-core` depend on the UI package. Keep both sets
+ * synchronized: when the UI adds a daemon code that should render as a localized session error
+ * during streaming, add it here so the terminal assistant `agent_message` carries `code:message`
+ * instead of bare `[Error] ...` text. The UI consumes assistant + finish_reason=error as session
+ * status, and local-runtime filters it out of display history.
+ *
+ * Codes outside this set (auth / generic upstream / unclassified) retain their original `[Error]
+ * ...` content as the only user-visible signal.
+ */
+const TYPED_TERMINAL_ERROR_CODES = new Set<number>([
+  LLM_ERROR_CODES.USAGE_LIMIT_EXCEEDED, // 42212
+  LLM_ERROR_CODES.LLM_CREDITS_EXHAUSTED, // 50110
+  LLM_ERROR_CODES.LLM_RATE_LIMITED, // 50111
+  LLM_ERROR_CODES.LLM_TPM_RATE_LIMITED, // 50150
+  LLM_ERROR_CODES.LLM_CLUSTER_OVERLOADED, // 50151
+  419, // Legacy daemon code retained for cross-version compatibility.
+]);
+
+/**
+ * Snapshot of `onMessageEnd` context, captured so the bridge can defer
+ * emitting the completed assistant `agent_message` (RespData.type=2) until
+ * every `tool_execution_end` for that message has arrived. See the
+ * {@link EventBridge.pendingCompletedMessage} field comment for the
+ * full rationale.
+ *
+ * `usage` is typed as the full {@link TokenUsage} so the deferred
+ * emit preserves the optional `cache_read` / `cache_write` fields that
+ * `extractAssistantUsage` may surface — narrowing this to a 2-field
+ * inline type would silently drop them on the tool-call code path.
+ */
+interface PendingCompletedMessageContext {
+  msgId: string;
+  text: string;
+  thinking: string | undefined;
+  thinkingDurationMs: number | undefined;
+  finishReason: string | undefined;
+  usage: TokenUsage;
+}
+
+/**
+ * Per-turn bridge from pi `AgentEvent` to canonical `RuntimeEvent`.
+ *
+ * Lifecycle:
+ *   1. `new EventBridge(ctx)` once per turn.
+ *   2. For each pi event: `await ev.processEvent(event)`. If
+ *      `requestAssistantMessageId === true`, allocate one and call
+ *      {@link setActiveAssistantMessageId} before the next event.
+ *   3. After the loop concludes: call exactly one of `emitCompleted`,
+ *      `emitAborted`, `emitFailed`.
+ */
+export class EventBridge {
+  private readonly ctx: EventBridgeContext;
+  private readonly now: () => number;
+  /** Whether to measure and stamp per-tool-call `duration_ms`. Non-prod only. */
+  private readonly captureToolTiming: boolean;
+  /** Resolved context-window size for this turn, captured at construction time. */
+  private readonly contextWindow: number;
+
+  /** Active assistant `message_id` for the message currently being streamed. */
+  private activeAssistantMessageId: string | undefined;
+  /** Per-message chunk index counter. Resets on each new assistant message. */
+  private chunkIndex: number = 0;
+  /** Latched flag — true while we have asked the host for an id and not received one. */
+  private awaitingMessageId: boolean = false;
+  /** Wall-clock ms when the first thinking_delta of the current msg arrived. */
+  private thinkingStartMs: number | undefined;
+  /** Wall-clock ms when thinking ended (first non-thinking delta or message_end). */
+  private thinkingEndMs: number | undefined;
+  /** Whether the current message has already produced a non-thinking delta. */
+  private thinkingClosed: boolean = false;
+  /** Most recent assistant message cached for diagnostics on terminal frames. */
+  private lastAssistantErrorMessage: string | undefined;
+
+  // ── Tool-call lifecycle tracking ─────────────────────────────────────
+  //
+  // pi emits the assistant `message_end` event the moment the LLM is done
+  // generating, BEFORE the host has executed any tool calls. If we emit the
+  // completed `agent_message` (RespData.type=2) at that point, its
+  // `tool_calls[].status` is necessarily "started" — the executions have
+  // not happened yet. The archon-server persists that RespData verbatim
+  // into `session_messages.data_json` and never updates it, so
+  // history-replay forever returns `tool_call_status=1` even though the
+  // tools later completed. The post-`tool_execution_end` chunk
+  // (RespData.type=6) carries the real `tool_call_status=2 + result_data`
+  // but is not persisted by archon-server's chunk path.
+  //
+  // Fix: defer emitting the completed `agent_message` from `onMessageEnd`
+  // until every `tool_execution_end` for that message has arrived, then
+  // emit it once with the fully-resolved `tool_calls` (status + result_data).
+  // Messages without any tool call still emit immediately at `onMessageEnd`.
+  // Terminal helpers (`emitCompleted` / `emitAborted` / `emitFailed`) flush
+  // any still-pending completed message so a host-side abort or failure
+  // mid-tool-execution does not leak a never-persisted message.
+
+  /** Number of `tool_execution_end` events still expected for the current message. */
+  private pendingToolCount: number = 0;
+  /** Final state of each completed tool call, keyed by tool_call_id. */
+  private completedToolCalls: Map<string, RuntimeToolCall> = new Map();
+  /** tool_execution_start wall-clock, keyed by tool_call_id (captureToolTiming only). */
+  private toolStartMs: Map<string, number> = new Map();
+  /**
+   * Identity of each tool call whose arguments the model is still streaming,
+   * keyed by pi's per-message `contentIndex` (only `toolcall_start` carries
+   * the call id / tool name; `toolcall_delta` / `toolcall_end` reference the
+   * index). Entries drop at `toolcall_end` or on message reset.
+   */
+  private preparingToolCalls: Map<number, { toolCallId: string; toolName: string }> = new Map();
+  /** Captured `onMessageEnd` context, replayed once `pendingToolCount === 0`. */
+  private pendingCompletedMessage: PendingCompletedMessageContext | undefined;
+
+  constructor(ctx: EventBridgeContext) {
+    this.ctx = ctx;
+    this.now = ctx.nowMs ?? defaultNowMs;
+    this.captureToolTiming = ctx.captureToolTiming === true;
+    if (
+      typeof ctx.contextWindow === 'number' &&
+      Number.isFinite(ctx.contextWindow) &&
+      ctx.contextWindow > 0
+    ) {
+      this.contextWindow = ctx.contextWindow;
+    } else {
+      this.contextWindow = DEFAULT_CONTEXT_WINDOW;
+      ctx.logger?.warn?.(
+        {
+          session_id: ctx.sessionId,
+          turn_id: ctx.turnId,
+          fallback: DEFAULT_CONTEXT_WINDOW,
+          received: ctx.contextWindow,
+        },
+        '[event-bridge] contextWindow missing or invalid, falling back to default',
+      );
+    }
+  }
+
+  /**
+   * Inject the host-allocated assistant `message_id` after the bridge
+   * requested one via {@link BridgedEvents.requestAssistantMessageId}.
+   *
+   * Calling this when no allocation was requested replaces the current
+   * id (used for unit tests / re-entry). Calling with an empty string
+   * clears the active id, which causes subsequent delta events to be
+   * dropped until another `message_start` arrives.
+   */
+  setActiveAssistantMessageId(messageId: string): void {
+    this.activeAssistantMessageId = messageId || undefined;
+    this.awaitingMessageId = false;
+  }
+
+  /** Returns the current active assistant message id for per-call runtime context. */
+  getActiveAssistantMessageId(): string | undefined {
+    return this.activeAssistantMessageId;
+  }
+
+  /**
+   * Drop the in-flight assistant response without emitting its message_end.
+   * Used when a response-control hook rejects an empty response before the
+   * bridge or history surfaces it to product consumers.
+   */
+  discardActiveAssistantMessage(): void {
+    this.activeAssistantMessageId = undefined;
+    this.awaitingMessageId = false;
+    this.pendingCompletedMessage = undefined;
+    this.completedToolCalls = new Map();
+    this.toolStartMs = new Map();
+    this.preparingToolCalls = new Map();
+    this.pendingToolCount = 0;
+  }
+
+  /**
+   * Feed a single pi `AgentEvent` and produce zero-or-more `RuntimeEvent`s.
+   *
+   * The bridge handles the events relevant to streaming assistant turns —
+   * `message_*`, `tool_execution_*`. Pi lifecycle frames (`agent_*`,
+   * `turn_*`, `tool_execution_update`) do not have a `stream.resp`
+   * representation — hosts already track turn outcome at a higher level
+   * (PiTurnRunner) and emit the terminal status explicitly. They are
+   * surfaced as `debug.trace` events so observers (replay tools, cloud
+   * tracing, daemon SSE consumers) can see Pi's full producer-side
+   * lifecycle without affecting the canonical wire format. Callers can
+   * still safely forward every event without coordination.
+   */
+  async processEvent(event: AgentEvent): Promise<BridgedEvents> {
+    switch (event.type) {
+      case 'message_start':
+        return this.onMessageStart(event);
+      case 'message_update':
+        return this.onMessageUpdate(event);
+      case 'message_end':
+        return this.onMessageEnd(event);
+      case 'tool_execution_start':
+        return this.onToolStart(event);
+      case 'tool_execution_end':
+        return this.onToolEnd(event);
+      case 'agent_start':
+        return this.onPiLifecycleTrace('pi_agent_start', 'Pi agent run started');
+      case 'agent_end':
+        return this.onPiLifecycleTrace('pi_agent_end', 'Pi agent run ended', {
+          message_count: event.messages.length,
+        });
+      case 'turn_start':
+        return this.onPiLifecycleTrace('pi_turn_start', 'Pi turn started');
+      case 'turn_end':
+        return this.onPiLifecycleTrace('pi_turn_end', 'Pi turn ended', {
+          tool_result_count: event.toolResults.length,
+        });
+      case 'tool_execution_update':
+        return this.onPiLifecycleTrace(
+          'pi_tool_execution_update',
+          'Pi tool execution partial update',
+          {
+            tool_name: event.toolName,
+            tool_call_id: event.toolCallId,
+          },
+        );
+      default: {
+        // Defensive — future pi variants surface here as a debug trace so
+        // we can detect them without crashing.
+        const e = event as { type?: string };
+        return this.onPiLifecycleTrace('pi_event_unknown', 'Unrecognised pi AgentEvent', {
+          event_type: e.type ?? 'unknown',
+        });
+      }
+    }
+  }
+
+  /**
+   * Emit a single `debug.trace` event carrying a Pi lifecycle marker.
+   * Used for the producer-side frames (`agent_*` / `turn_*` /
+   * `tool_execution_update`) that have no wire-level `stream.resp`
+   * representation — surfacing them as traces keeps observers informed
+   * without affecting the canonical streaming surface or message
+   * lifecycle.
+   */
+  private onPiLifecycleTrace(
+    phase: string,
+    message: string,
+    attrs?: Record<string, string | number | boolean>,
+  ): BridgedEvents {
+    return {
+      events: [
+        buildDebugTraceEvent({
+          sessionId: this.ctx.sessionId,
+          turnId: this.ctx.turnId,
+          eventId: this.ctx.eventIdGenerator(phase),
+          phase,
+          message,
+          ...(attrs ? { attrs } : {}),
+        }),
+      ],
+    };
+  }
+
+  private onMessageStart(event: Extract<AgentEvent, { type: 'message_start' }>): BridgedEvents {
+    const role = (event.message as { role?: unknown }).role;
+    if (role !== 'assistant') {
+      // Non-assistant messages (user / tool result) flow through without
+      // chunked streaming — pi emits them as single-shot frames.
+      return { events: [] };
+    }
+    // New assistant message — reset per-message state.
+    this.activeAssistantMessageId = undefined;
+    this.chunkIndex = 0;
+    this.thinkingStartMs = undefined;
+    this.thinkingEndMs = undefined;
+    this.thinkingClosed = false;
+    this.awaitingMessageId = true;
+    // Tool-call lifecycle reset — a fresh assistant message starts with no
+    // pending tool calls; the count + map are repopulated at onMessageEnd
+    // and onToolEnd respectively.
+    this.pendingToolCount = 0;
+    this.completedToolCalls = new Map();
+    this.toolStartMs = new Map();
+    this.preparingToolCalls = new Map();
+    this.pendingCompletedMessage = undefined;
+    return { events: [], requestAssistantMessageId: true };
+  }
+
+  private onMessageUpdate(event: Extract<AgentEvent, { type: 'message_update' }>): BridgedEvents {
+    const update = extractDeltaUpdate(event.assistantMessageEvent);
+    if (!update) return { events: [] };
+    if (!this.activeAssistantMessageId) {
+      // No anchor message id yet — drop this delta with a debug trace
+      // so observers can detect the misordering. Do NOT throw; the
+      // contract is "best-effort streaming".
+      return {
+        events: [
+          buildDebugTraceEvent({
+            sessionId: this.ctx.sessionId,
+            turnId: this.ctx.turnId,
+            eventId: this.ctx.eventIdGenerator('coding_delta_dropped'),
+            phase: 'event_bridge_delta_dropped',
+            message: this.awaitingMessageId
+              ? 'message_update arrived before host allocated assistant message_id'
+              : 'message_update arrived without an active assistant message_id',
+            level: 'warn',
+            attrs: { delta_kind: update.kind },
+          }),
+        ],
+      };
+    }
+    if (
+      update.kind === 'toolcall_start' ||
+      update.kind === 'toolcall_delta' ||
+      update.kind === 'toolcall_end'
+    ) {
+      return this.onToolCallStreamUpdate(this.activeAssistantMessageId, update);
+    }
+    if (update.kind === 'thinking') {
+      if (this.thinkingStartMs === undefined) this.thinkingStartMs = this.now();
+      // Thinking is still streaming — keep the closed flag false so a
+      // subsequent text_delta will close the thinking window.
+      return {
+        events: [
+          buildThinkingDeltaChunk({
+            sessionId: this.ctx.sessionId,
+            turnId: this.ctx.turnId,
+            eventId: this.ctx.eventIdGenerator('coding_thinking'),
+            runtimeSeq: this.ctx.runtimeSeqGenerator(),
+            msgId: this.activeAssistantMessageId,
+            chunkIndex: this.nextChunkIndex(),
+            delta: update.delta,
+            nowMs: this.now(),
+          }),
+        ],
+      };
+    }
+    // text delta — closes thinking window if we were tracking one.
+    if (this.thinkingStartMs !== undefined && !this.thinkingClosed) {
+      this.thinkingEndMs = this.now();
+      this.thinkingClosed = true;
+    }
+    return {
+      events: [
+        buildTextDeltaChunk({
+          sessionId: this.ctx.sessionId,
+          turnId: this.ctx.turnId,
+          eventId: this.ctx.eventIdGenerator('coding_text'),
+          runtimeSeq: this.ctx.runtimeSeqGenerator(),
+          msgId: this.activeAssistantMessageId,
+          chunkIndex: this.nextChunkIndex(),
+          delta: update.delta,
+          nowMs: this.now(),
+        }),
+      ],
+    };
+  }
+
+  /**
+   * Model-side tool-call argument streaming (pi `toolcall_start` /
+   * `toolcall_delta` / `toolcall_end` inside `message_update`). Surfaces the
+   * argument-generation phase to stream consumers ahead of
+   * `tool_execution_start` — for large arguments (a multi-minute novel edit)
+   * the stream is otherwise silent from the last text delta until dispatch.
+   * Provider streams carry the call identity on every frame via `partial`;
+   * proxy streams only on the start frame — the bridge keeps a
+   * contentIndex → identity mapping so identity-less frames still resolve.
+   */
+  private onToolCallStreamUpdate(msgId: string, update: ToolCallStreamUpdate): BridgedEvents {
+    const frameIdentity =
+      update.toolCallId !== undefined && update.toolName !== undefined
+        ? { toolCallId: update.toolCallId, toolName: update.toolName }
+        : undefined;
+    const identity = frameIdentity ?? this.preparingToolCalls.get(update.contentIndex);
+    if (!identity) {
+      // No identity on the frame and no start frame seen — drop with a trace
+      // so replay tooling can spot the misordering; streaming stays
+      // best-effort.
+      return {
+        events: [
+          buildDebugTraceEvent({
+            sessionId: this.ctx.sessionId,
+            turnId: this.ctx.turnId,
+            eventId: this.ctx.eventIdGenerator('coding_toolcall_stream_dropped'),
+            phase: 'event_bridge_toolcall_stream_dropped',
+            message: 'tool-call stream frame arrived without a resolvable call identity',
+            level: 'warn',
+            attrs: { frame_kind: update.kind, content_index: update.contentIndex },
+          }),
+        ],
+      };
+    }
+    if (update.kind === 'toolcall_end') {
+      this.preparingToolCalls.delete(update.contentIndex);
+      return this.buildToolCallStreamChunk(msgId, {
+        tool_name: identity.toolName,
+        tool_call_id: identity.toolCallId,
+        status: 'prepared',
+      });
+    }
+    this.preparingToolCalls.set(update.contentIndex, identity);
+    return this.buildToolCallStreamChunk(msgId, {
+      tool_name: identity.toolName,
+      tool_call_id: identity.toolCallId,
+      status: 'preparing',
+      ...(update.kind === 'toolcall_delta' ? { args_text_delta: update.delta } : {}),
+    });
+  }
+
+  private buildToolCallStreamChunk(msgId: string, toolCall: RuntimeToolCall): BridgedEvents {
+    return {
+      events: [
+        buildToolCallChunk({
+          sessionId: this.ctx.sessionId,
+          turnId: this.ctx.turnId,
+          eventId: this.ctx.eventIdGenerator('coding_tool'),
+          runtimeSeq: this.ctx.runtimeSeqGenerator(),
+          msgId,
+          chunkIndex: this.nextChunkIndex(),
+          toolCall,
+          nowMs: this.now(),
+        }),
+      ],
+    };
+  }
+
+  private async onMessageEnd(
+    event: Extract<AgentEvent, { type: 'message_end' }>,
+  ): Promise<BridgedEvents> {
+    const role = (event.message as { role?: unknown }).role;
+    if (role !== 'assistant') return { events: [] };
+    const messageId = this.activeAssistantMessageId;
+    if (!messageId) {
+      // message_end without an active id — emit a debug trace; the host
+      // is responsible for deciding whether to fail the turn.
+      return {
+        events: [
+          buildDebugTraceEvent({
+            sessionId: this.ctx.sessionId,
+            turnId: this.ctx.turnId,
+            eventId: this.ctx.eventIdGenerator('coding_message_end_dropped'),
+            phase: 'event_bridge_message_end_dropped',
+            message: 'message_end arrived without an active assistant message_id',
+            level: 'warn',
+          }),
+        ],
+      };
+    }
+    // Close the thinking window if it never closed via a text delta.
+    if (this.thinkingStartMs !== undefined && !this.thinkingClosed) {
+      this.thinkingEndMs = this.now();
+      this.thinkingClosed = true;
+    }
+    // Abort short-circuit: when pi's `handleRunFailure` synthesises a
+    // failureMessage for an aborted run (stopReason='aborted',
+    // content=[{type:'text', text:''}], errorMessage='Request was aborted'),
+    // suppress the message_end emit entirely. The outer host calls
+    // `emitTerminal({kind:'aborted'})` → `emitAborted()` to deliver the
+    // terminal session.status aborted frame, which is the
+    // sole user-visible signal for an abort. Without this short-circuit
+    // the bridge would emit a finish chunk + a completed assistant
+    // message whose body is `[Error] Request was aborted` (composed at
+    // L450-452 from the empty content fallback), surfacing on the wire
+    // as a fake assistant turn that the UI renders as a chat bubble.
+    // Drop pending state so a subsequent terminal helper's
+    // `flushPendingCompletedMessage()` cannot resurrect this message.
+    const stopReason = extractAssistantStopReason(event.message);
+    if (stopReason === 'aborted') {
+      this.activeAssistantMessageId = undefined;
+      this.pendingCompletedMessage = undefined;
+      this.completedToolCalls = new Map();
+      this.toolStartMs = new Map();
+      this.pendingToolCount = 0;
+      return { events: [] };
+    }
+    const errorMessage = extractAssistantErrorMessage(event.message);
+    if (errorMessage) this.lastAssistantErrorMessage = errorMessage;
+    // When an LLM error maps to a typed daemon code supported by the UI, emit a compact
+    // `code:message` terminal error. The UI consumes assistant + finish_reason=error
+    // as session status; local-runtime filters out these terminal assistant bubbles.
+    const classified = errorMessage ? classifyLLMErrorToCode(errorMessage) : null;
+    const typedErrorText =
+      classified !== null && TYPED_TERMINAL_ERROR_CODES.has(classified.status_code)
+        ? `${classified.status_code}:${classified.message}`
+        : undefined;
+    const text =
+      extractAssistantText(event.message) ||
+      typedErrorText ||
+      (errorMessage ? `[Error] ${errorMessage}` : '');
+    const thinking = extractAssistantThinking(event.message) || undefined;
+    const toolCalls = extractAssistantToolCalls(event.message);
+    const finishReason = isAssistantError(event.message) ? 'error' : stopReason;
+    const thinkingDurationMs =
+      this.thinkingStartMs !== undefined && this.thinkingEndMs !== undefined
+        ? Math.max(0, this.thinkingEndMs - this.thinkingStartMs)
+        : undefined;
+    const requestDurationMs =
+      this.ctx.includeDetailedUsage === true
+        ? this.ctx.requestDurationMs?.(event.message)
+        : undefined;
+    const usage: TokenUsage = {
+      ...(extractAssistantUsage(event.message, this.contextWindow) ?? {
+        total_tokens: 0,
+        context_window: this.contextWindow,
+      }),
+      ...(typeof requestDurationMs === 'number' &&
+      Number.isFinite(requestDurationMs) &&
+      requestDurationMs > 0
+        ? { request_duration_ms: requestDurationMs }
+        : {}),
+    };
+
+    // Always emit the finish chunk immediately at message_end — it signals
+    // "LLM is done generating" and downstream consumers (UI, archon-server
+    // queue gating) rely on it to advance state regardless of tool-execution
+    // status. The completed RespData (type=2) emit is decided next.
+    const finishEvent = buildFinishChunk({
+      sessionId: this.ctx.sessionId,
+      turnId: this.ctx.turnId,
+      eventId: this.ctx.eventIdGenerator('coding_finish'),
+      runtimeSeq: this.ctx.runtimeSeqGenerator(),
+      msgId: messageId,
+      chunkIndex: this.nextChunkIndex(),
+      ...(finishReason ? { finishReason } : {}),
+      ...(thinkingDurationMs !== undefined ? { thinkingDurationMs } : {}),
+      nowMs: this.now(),
+    });
+
+    if (toolCalls.length === 0) {
+      // No tool execution to wait for — emit the completed agent_message
+      // right away, same as the legacy path.
+      const completedEvent = await buildCompletedAssistantMessage(
+        {
+          sessionId: this.ctx.sessionId,
+          turnId: this.ctx.turnId,
+          eventId: this.ctx.eventIdGenerator('coding_completed'),
+          runtimeSeq: this.ctx.runtimeSeqGenerator(),
+          msgId: messageId,
+          text,
+          ...(thinking !== undefined ? { thinking } : {}),
+          ...(thinkingDurationMs !== undefined ? { thinkingDurationMs } : {}),
+          ...(finishReason ? { finishReason } : {}),
+          usage,
+          nowMs: this.now(),
+          logger: this.ctx.logger,
+        },
+        this.ctx.respDataTransform,
+      );
+      this.activeAssistantMessageId = undefined;
+      return { events: [finishEvent, completedEvent] };
+    }
+
+    // Tool calls present — defer the completed agent_message emit until
+    // every tool_execution_end arrives. Capture the message context;
+    // onToolEnd will fire the deferred emit when pendingToolCount drops
+    // to zero with fully-resolved tool_calls (status + result_data).
+    // activeAssistantMessageId stays set so subsequent tool_execution_*
+    // events attach to this message.
+    this.pendingToolCount = toolCalls.length;
+    this.completedToolCalls = new Map();
+    this.toolStartMs = new Map();
+    this.pendingCompletedMessage = {
+      msgId: messageId,
+      text,
+      thinking,
+      thinkingDurationMs,
+      finishReason,
+      usage,
+    };
+    return { events: [finishEvent] };
+  }
+
+  private onToolStart(event: Extract<AgentEvent, { type: 'tool_execution_start' }>): BridgedEvents {
+    if (!this.activeAssistantMessageId) {
+      return {
+        events: [
+          buildDebugTraceEvent({
+            sessionId: this.ctx.sessionId,
+            turnId: this.ctx.turnId,
+            eventId: this.ctx.eventIdGenerator('coding_tool_start_dropped'),
+            phase: 'event_bridge_tool_start_dropped',
+            message: 'tool_execution_start arrived without an active assistant message_id',
+            level: 'warn',
+            attrs: { tool_name: event.toolName, tool_call_id: event.toolCallId },
+          }),
+        ],
+      };
+    }
+    const args = event.args;
+    const toolCall: RuntimeToolCall = {
+      tool_name: event.toolName,
+      tool_call_id: event.toolCallId,
+      status: 'started',
+      ...(args !== undefined && typeof args === 'object' && args !== null
+        ? { args: args as Record<string, unknown> }
+        : {}),
+      ...this.resolveToolCallProvenance({
+        phase: 'start',
+        toolName: event.toolName,
+        ...(args !== undefined && typeof args === 'object' && args !== null
+          ? { args: args as Record<string, unknown> }
+          : {}),
+      }),
+    };
+    // Stage this tool call's started-state snapshot (with `args`) into the
+    // deferred completed-message buffer so that when `onToolEnd` later
+    // overlays status + result, the `args` payload survives into the
+    // flushed RespData. Prior behaviour only wrote on tool_execution_end,
+    // which dropped `args` from the persisted completed message — the
+    // frontend then could not render the tool call's input parameters
+    // after the turn finished.
+    this.completedToolCalls.set(event.toolCallId, toolCall);
+    if (this.captureToolTiming) {
+      this.toolStartMs.set(event.toolCallId, this.now());
+    }
+    return {
+      events: [
+        buildDebugTraceEvent({
+          sessionId: this.ctx.sessionId,
+          turnId: this.ctx.turnId,
+          eventId: this.ctx.eventIdGenerator('coding_trace_tool_call_started'),
+          phase: 'tool_call_started',
+          message: 'Host tool call started',
+          attrs: { tool_name: event.toolName, tool_call_id: event.toolCallId },
+        }),
+        buildToolCallChunk({
+          sessionId: this.ctx.sessionId,
+          turnId: this.ctx.turnId,
+          eventId: this.ctx.eventIdGenerator('coding_tool'),
+          runtimeSeq: this.ctx.runtimeSeqGenerator(),
+          msgId: this.activeAssistantMessageId,
+          chunkIndex: this.nextChunkIndex(),
+          toolCall,
+          nowMs: this.now(),
+        }),
+      ],
+    };
+  }
+
+  private async onToolEnd(
+    event: Extract<AgentEvent, { type: 'tool_execution_end' }>,
+  ): Promise<BridgedEvents> {
+    if (!this.activeAssistantMessageId) {
+      return {
+        events: [
+          buildDebugTraceEvent({
+            sessionId: this.ctx.sessionId,
+            turnId: this.ctx.turnId,
+            eventId: this.ctx.eventIdGenerator('coding_tool_end_dropped'),
+            phase: 'event_bridge_tool_end_dropped',
+            message: 'tool_execution_end arrived without an active assistant message_id',
+            level: 'warn',
+            attrs: { tool_name: event.toolName, tool_call_id: event.toolCallId },
+          }),
+        ],
+      };
+    }
+    // Preserve `args` captured at tool_execution_start: the started-state
+    // entry already in `completedToolCalls` carries the input parameters
+    // (pi's tool_execution_end event does not re-emit them). Overlay the
+    // terminal status + result on top of that snapshot so the flushed
+    // RespData has the full (args + status=completed/failed + result)
+    // shape — not just (status + result).
+    const startedSnapshot = this.completedToolCalls.get(event.toolCallId);
+    let durationMs: number | undefined;
+    if (this.captureToolTiming) {
+      const startMs = this.toolStartMs.get(event.toolCallId);
+      if (startMs !== undefined) {
+        durationMs = this.now() - startMs;
+        this.toolStartMs.delete(event.toolCallId);
+      }
+    }
+    const toolCall: RuntimeToolCall = {
+      tool_name: event.toolName,
+      tool_call_id: event.toolCallId,
+      ...(startedSnapshot?.args !== undefined ? { args: startedSnapshot.args } : {}),
+      status: event.isError ? 'failed' : 'completed',
+      ...(event.result !== undefined ? { result: event.result } : {}),
+      ...(durationMs !== undefined ? { duration_ms: durationMs } : {}),
+      ...this.resolveToolCallProvenance(
+        {
+          phase: 'end',
+          toolName: event.toolName,
+          ...(startedSnapshot?.args !== undefined ? { args: startedSnapshot.args } : {}),
+          ...(event.result !== undefined ? { result: event.result } : {}),
+          isError: event.isError,
+        },
+        startedSnapshot?.plugin_provenances,
+      ),
+    };
+    const events: BridgedEvents['events'] = [
+      buildDebugTraceEvent({
+        sessionId: this.ctx.sessionId,
+        turnId: this.ctx.turnId,
+        eventId: this.ctx.eventIdGenerator('coding_trace_tool_call_completed'),
+        phase: 'tool_call_completed',
+        message: 'Host tool call completed',
+        attrs: {
+          tool_name: event.toolName,
+          tool_call_id: event.toolCallId,
+          is_error: event.isError,
+          ...(durationMs !== undefined ? { duration_ms: durationMs } : {}),
+        },
+      }),
+      buildToolCallChunk({
+        sessionId: this.ctx.sessionId,
+        turnId: this.ctx.turnId,
+        eventId: this.ctx.eventIdGenerator('coding_tool'),
+        runtimeSeq: this.ctx.runtimeSeqGenerator(),
+        msgId: this.activeAssistantMessageId,
+        chunkIndex: this.nextChunkIndex(),
+        toolCall,
+        nowMs: this.now(),
+      }),
+    ];
+
+    // Record this tool's final state for the deferred completed-message emit.
+    // Last-write-wins per tool_call_id so re-emitted ends (defensive) collapse
+    // to a single entry.
+    this.completedToolCalls.set(event.toolCallId, toolCall);
+    if (this.pendingToolCount > 0) {
+      this.pendingToolCount--;
+    }
+
+    // Flush the deferred completed agent_message once every expected tool
+    // has reported back. Emitted with the fully-resolved tool_calls array
+    // (status=completed/failed + result_data), so the archon-server persist
+    // path writes the terminal-state message into session_messages.data_json
+    // — history-replay therefore returns the final tool_call_status,
+    // not the start-time snapshot.
+    if (this.pendingToolCount === 0 && this.pendingCompletedMessage) {
+      const flushed = await this.flushPendingCompletedMessage();
+      if (flushed) events.push(flushed);
+    }
+
+    return { events };
+  }
+
+  private resolveToolCallProvenance(
+    input: Parameters<NonNullable<EventBridgeContext['toolCallProvenanceResolver']>>[0],
+    fallback?: readonly IPluginCapabilityProvenance[],
+  ): Pick<RuntimeToolCall, 'plugin_provenances'> | object {
+    const resolver = this.ctx.toolCallProvenanceResolver;
+    if (!resolver) {
+      return fallback?.length ? { plugin_provenances: fallback.map((item) => ({ ...item })) } : {};
+    }
+    try {
+      const resolved = normalizePluginProvenances(resolver(input));
+      const effective = resolved.length > 0 ? resolved : fallback;
+      return effective?.length
+        ? { plugin_provenances: effective.map((item) => ({ ...item })) }
+        : {};
+    } catch (error) {
+      this.ctx.logger?.warn?.(
+        {
+          session_id: this.ctx.sessionId,
+          turn_id: this.ctx.turnId,
+          tool_name: input.toolName,
+          phase: input.phase,
+          error: error instanceof Error ? error.message : String(error),
+        },
+        '[event-bridge] Plugin provenance resolver failed open',
+      );
+      return fallback?.length ? { plugin_provenances: fallback.map((item) => ({ ...item })) } : {};
+    }
+  }
+
+  /**
+   * Emit the deferred completed `agent_message` captured at `onMessageEnd`,
+   * filling `tool_calls` with the final state collected from every
+   * subsequent `onToolEnd`. Returns the RespData StreamRespEvent (the
+   * caller appends it to its own event list), or `undefined` when there is
+   * nothing to flush. Always clears the deferred state on the way out so
+   * a subsequent terminal helper does not double-emit.
+   */
+  private async flushPendingCompletedMessage() {
+    const pending = this.pendingCompletedMessage;
+    if (!pending) return undefined;
+    const toolCalls = Array.from(this.completedToolCalls.values());
+    const event = await buildCompletedAssistantMessage(
+      {
+        sessionId: this.ctx.sessionId,
+        turnId: this.ctx.turnId,
+        eventId: this.ctx.eventIdGenerator('coding_completed'),
+        runtimeSeq: this.ctx.runtimeSeqGenerator(),
+        msgId: pending.msgId,
+        text: pending.text,
+        ...(pending.thinking !== undefined ? { thinking: pending.thinking } : {}),
+        ...(toolCalls.length ? { toolCalls } : {}),
+        ...(pending.thinkingDurationMs !== undefined
+          ? { thinkingDurationMs: pending.thinkingDurationMs }
+          : {}),
+        ...(pending.finishReason ? { finishReason: pending.finishReason } : {}),
+        usage: pending.usage,
+        nowMs: this.now(),
+        logger: this.ctx.logger,
+      },
+      this.ctx.respDataTransform,
+    );
+    // Clear deferred state and the active assistant id — the message
+    // lifecycle is fully complete (LLM done + all tools resolved + RespData
+    // emitted). Subsequent tool_execution_* events without a new
+    // message_start will fall into the "no active assistant id" debug-trace
+    // branch, which is the correct fail-loud behavior.
+    this.pendingCompletedMessage = undefined;
+    this.completedToolCalls = new Map();
+    this.toolStartMs = new Map();
+    this.pendingToolCount = 0;
+    this.activeAssistantMessageId = undefined;
+    return event;
+  }
+
+  // ─── Terminal helpers ─────────────────────────────────────────────────
+  //
+  // All terminal helpers are async so they can flush a deferred completed
+  // assistant message (captured by onMessageEnd + held by onToolEnd until
+  // the last `tool_execution_end`) that was still in flight when the turn
+  // terminated — e.g. the user aborted mid-tool-execution, or the host
+  // hit a runtime failure before every tool reported back. Flushing here
+  // means the message still reaches archon-server's persist path with
+  // whatever tool_call state is known so far, instead of being silently
+  // dropped. Subsequent debug/terminal events are appended after the
+  // flushed completed message.
+
+  /** Emit the terminal `session.status completed` frame. */
+  async emitCompleted(): Promise<BridgedEvents> {
+    const pending = await this.flushPendingCompletedMessage();
+    const events: BridgedEvents['events'] = [];
+    if (pending) events.push(pending);
+    events.push(
+      buildDebugTraceEvent({
+        sessionId: this.ctx.sessionId,
+        turnId: this.ctx.turnId,
+        eventId: this.ctx.eventIdGenerator('coding_trace_turn_completed'),
+        phase: 'turn_completed',
+        message: 'Coding agent loop completed',
+      }),
+      buildCompletedTerminalStatusEvent({
+        sessionId: this.ctx.sessionId,
+        turnId: this.ctx.turnId,
+        statusEventId: this.ctx.eventIdGenerator('coding_idle'),
+      }),
+    );
+    return { events };
+  }
+
+  /** Emit the terminal `session.status aborted` frame. */
+  async emitAborted(): Promise<BridgedEvents> {
+    const pending = await this.flushPendingCompletedMessage();
+    const events: BridgedEvents['events'] = [];
+    if (pending) events.push(pending);
+    events.push(
+      buildDebugTraceEvent({
+        sessionId: this.ctx.sessionId,
+        turnId: this.ctx.turnId,
+        eventId: this.ctx.eventIdGenerator('coding_trace_turn_aborted'),
+        phase: 'turn_failed',
+        message: 'Coding agent loop was aborted',
+        attrs: { reason: 'aborted' },
+      }),
+      buildAbortedTerminalStatusEvent({
+        sessionId: this.ctx.sessionId,
+        turnId: this.ctx.turnId,
+        statusEventId: this.ctx.eventIdGenerator('coding_aborted_status'),
+      }),
+    );
+    return { events };
+  }
+
+  /**
+   * Emit the terminal `session.status failed` frame with the supplied human-readable message.
+   * Callers that have already captured an `errorMessage` from a pi assistant message should pass
+   * that text in.
+   *
+   * When the host has classified the failure (e.g. LLM 401 -> LLM_AUTH_ERROR), pass `error` to
+   * forward the typed runtime status code to the `session.status` wire payload. If the caller omits
+   * `error`, use `{ code: INTERNAL_ERROR, message }` by default.
+   */
+  async emitFailed(message: string, error?: RuntimeProtocolError): Promise<BridgedEvents> {
+    const text = message || this.lastAssistantErrorMessage || 'Coding agent loop failed.';
+    const pending = await this.flushPendingCompletedMessage();
+    const events: BridgedEvents['events'] = [];
+    if (pending) events.push(pending);
+    events.push(
+      buildDebugTraceEvent({
+        sessionId: this.ctx.sessionId,
+        turnId: this.ctx.turnId,
+        eventId: this.ctx.eventIdGenerator('coding_trace_turn_failed'),
+        phase: 'turn_failed',
+        message: 'Coding agent loop returned an error',
+        attrs: { reason: 'assistant_error' },
+      }),
+      buildFailedTerminalStatusEvent({
+        sessionId: this.ctx.sessionId,
+        turnId: this.ctx.turnId,
+        statusEventId: this.ctx.eventIdGenerator('coding_failed_status'),
+        message: text,
+        ...(error ? { error } : {}),
+      }),
+    );
+    return { events };
+  }
+
+  /**
+   * Convenience dispatcher mapping a {@link TurnTerminationReason} to the
+   * right terminal helper. Useful when callers track termination state
+   * elsewhere and want a single emit point.
+   */
+  async emitTerminal(reason: TurnTerminationReason): Promise<BridgedEvents> {
+    switch (reason.kind) {
+      case 'completed':
+        return this.emitCompleted();
+      case 'aborted':
+        return this.emitAborted();
+      case 'failed':
+        return this.emitFailed(reason.message, reason.error);
+      default: {
+        const exhaustive: never = reason;
+        throw new Error(`Unhandled TurnTerminationReason: ${JSON.stringify(exhaustive)}`);
+      }
+    }
+  }
+
+  // ─── Internals ────────────────────────────────────────────────────────
+
+  private nextChunkIndex(): number {
+    const idx = this.chunkIndex;
+    this.chunkIndex = idx + 1;
+    return idx;
+  }
+}
+
+function normalizePluginProvenances(
+  input: readonly IPluginCapabilityProvenance[] | undefined,
+): IPluginCapabilityProvenance[] {
+  if (!input?.length) return [];
+  const normalized = input.flatMap((item) => {
+    const pluginName = item.plugin_name?.trim();
+    const capabilityName = item.capability_name?.trim();
+    const validSource =
+      item.source === InstalledPluginSource.OFFICIAL || item.source === InstalledPluginSource.LOCAL;
+    const validCapability =
+      item.capability_type === PluginCapabilityType.APP ||
+      item.capability_type === PluginCapabilityType.MCP ||
+      item.capability_type === PluginCapabilityType.SKILL;
+    if (!pluginName || !capabilityName || !validSource || !validCapability) return [];
+    const pluginVersion = item.plugin_version?.trim();
+    const iconUrl = item.icon_url?.trim();
+    const darkIconUrl = item.dark_icon_url?.trim();
+    return [
+      {
+        plugin_name: pluginName,
+        ...(pluginVersion ? { plugin_version: pluginVersion } : {}),
+        source: item.source,
+        capability_type: item.capability_type,
+        capability_name: capabilityName,
+        ...(iconUrl ? { icon_url: iconUrl } : {}),
+        ...(darkIconUrl ? { dark_icon_url: darkIconUrl } : {}),
+      },
+    ];
+  });
+  const unique = new Map<string, IPluginCapabilityProvenance>();
+  for (const item of normalized) {
+    const key = [
+      item.plugin_name.normalize('NFKC').toLocaleLowerCase('en-US'),
+      item.plugin_version ?? '',
+      item.source,
+      item.capability_type,
+      item.capability_name,
+    ].join('\0');
+    if (!unique.has(key)) unique.set(key, item);
+  }
+  return [...unique.values()].sort(
+    (left, right) =>
+      left.plugin_name.localeCompare(right.plugin_name, 'en-US') ||
+      (left.plugin_version ?? '').localeCompare(right.plugin_version ?? '', 'en-US') ||
+      left.capability_name.localeCompare(right.capability_name, 'en-US'),
+  );
+}

+ 845 - 0
packages/agent-core/src/event-bridge/converters.ts

@@ -0,0 +1,845 @@
+/**
+ * Pure converters from pi `AgentEvent` payloads to RuntimeEvent frames.
+ * Most helpers are synchronous; completed AgentMessage conversion is async
+ * because it can run the host-provided `respDataTransform` before
+ * serializing `stream.resp`.
+ *
+ * The Phase 1 wire shape uses `stream.resp` events whose `payload.stream_resp`
+ * is a JSON-serialised `RespData` envelope (see `protocol/agent-message.ts`).
+ * Status frames (`session.status`) are emitted natively because they have no
+ * equivalent in the legacy AgentMessageChunk format.
+ *
+ * @see packages/agent-core/ARCHITECTURE.md
+ */
+
+import {
+  RUNTIME_EVENT_SCHEMA,
+  RuntimeDebugTraceLevel,
+  RuntimeEventStatus,
+  RuntimeEventType,
+  RuntimeStopReasonType,
+  type RuntimeEvent,
+  type RuntimeProtocolError,
+  type RuntimeStopReason,
+  type RuntimeToolCall,
+  type RuntimeToolCallStatus,
+  type RuntimeUsage,
+  type SessionStatusEvent,
+  type StreamRespEvent,
+} from '../protocol/runtime-event.js';
+import { ProtocolErrorCode } from '@mavis/protocol';
+import { applyRespDataTransform, type RespDataTransform } from './resp-data.js';
+import { sanitizeToolCallForDisplay } from './display-sanitize.js';
+import type { PiTurnRunnerLogger } from '../pi-turn-runner/types.js';
+import {
+  MsgType,
+  Role,
+  type AgentMessage,
+  type AgentMessageChunk,
+  type RespData,
+  RespDataType,
+  type ToolCall,
+  ToolCallStatus,
+  type TokenUsage,
+} from '../protocol/agent-message.js';
+
+// ─── Stream event scaffolding ───────────────────────────────────────────
+
+interface StreamEventInput {
+  sessionId: string;
+  turnId: string;
+  eventId: string;
+  runtimeSeq: number;
+  respData: RespData;
+}
+
+/** Wrap a `RespData` envelope in a `stream.resp` runtime event. */
+export function buildStreamRespEvent(input: StreamEventInput): StreamRespEvent {
+  return {
+    schema: RUNTIME_EVENT_SCHEMA,
+    event_id: input.eventId,
+    session_id: input.sessionId,
+    turn_id: input.turnId,
+    runtime_seq: input.runtimeSeq,
+    type: RuntimeEventType.STREAM_RESP,
+    payload: { stream_resp: JSON.stringify(input.respData) },
+  };
+}
+
+// ─── AgentMessageChunk builders ─────────────────────────────────────────
+
+interface ChunkInput {
+  msgId: string;
+  turnId: string;
+  chunkIndex: number;
+  text?: string;
+  thinking?: string;
+  toolCalls?: ToolCall[];
+  finish?: boolean;
+  finishReason?: string;
+  thinkingDurationMs?: number;
+  nowMs: number;
+}
+
+function buildChunkRespData(input: ChunkInput): RespData {
+  const chunk: AgentMessageChunk = {
+    msg_id: input.msgId,
+    turn_id: input.turnId,
+    chunk_index: input.chunkIndex,
+    timestamp: input.nowMs,
+    role: Role.Assistant,
+    ...(input.text !== undefined ? { msg_content: input.text } : {}),
+    ...(input.thinking !== undefined ? { thinking_content: input.thinking } : {}),
+    ...(input.toolCalls?.length ? { tool_calls: input.toolCalls } : {}),
+    ...(input.finish ? { finish: true } : {}),
+    ...(input.finishReason ? { finish_reason: input.finishReason } : {}),
+    ...(input.thinkingDurationMs !== undefined
+      ? { thinking_duration_ms: input.thinkingDurationMs }
+      : {}),
+  };
+  return { type: RespDataType.AgentMessageChunk, agent_message_chunk: chunk };
+}
+
+interface CompletedInput {
+  msgId: string;
+  turnId: string;
+  text?: string;
+  thinking?: string;
+  toolCalls?: ToolCall[];
+  finishReason?: string;
+  thinkingDurationMs?: number;
+  usage?: AgentMessage['usage'];
+  nowMs: number;
+  logger?: PiTurnRunnerLogger;
+}
+
+function buildCompletedRespData(input: CompletedInput): RespData {
+  const msg: AgentMessage = {
+    msg_id: input.msgId,
+    turn_id: input.turnId,
+    timestamp: input.nowMs,
+    role: Role.Assistant,
+    // msg_type discriminates between content-only and tool-call messages.
+    // The IDL `MsgType` enum is consumed by the frontend (e.g.
+    // `ChatPanel.tsx` `MsgType.SystemEvent` branch) and persisted to
+    // `session_messages.data_json`. AgentToolCall (=2) must be emitted
+    // whenever the assistant produced any tool calls in this turn so
+    // downstream consumers don't have to peek into `tool_calls` length
+    // to discriminate.
+    msg_type:
+      input.toolCalls && input.toolCalls.length > 0 ? MsgType.AgentToolCall : MsgType.AgentContent,
+    ...(input.text !== undefined ? { msg_content: input.text } : {}),
+    ...(input.thinking !== undefined ? { thinking_content: input.thinking } : {}),
+    ...(input.toolCalls?.length ? { tool_calls: input.toolCalls } : {}),
+    ...(input.finishReason ? { finish_reason: input.finishReason } : {}),
+    ...(input.thinkingDurationMs !== undefined
+      ? { thinking_duration_ms: input.thinkingDurationMs }
+      : {}),
+    ...(input.usage ? { usage: input.usage } : {}),
+  };
+  return { type: RespDataType.AgentMessage, agent_message: msg };
+}
+
+// ─── Tool-call status mapping ───────────────────────────────────────────
+
+/**
+ * Map pi tool-execution lifecycle to the legacy `ToolCallStatus`
+ * tri-state. `started` → 1, `completed` → 2, `failed` → 3.
+ */
+function toLegacyToolCallStatus(status: RuntimeToolCallStatus): ToolCallStatus {
+  if (status === 'preparing') return ToolCallStatus.Preparing;
+  if (status === 'prepared') return ToolCallStatus.Prepared;
+  if (status === 'completed') return ToolCallStatus.Finished;
+  if (status === 'failed') return ToolCallStatus.Failed;
+  return ToolCallStatus.Start;
+}
+
+/**
+ * Convert a `RuntimeToolCall` to the wire-level `ToolCall` shape used
+ * inside `AgentMessageChunk` and `AgentMessage`. JSON-encodes args /
+ * result because the legacy envelope keeps tool payloads opaque.
+ *
+ * The `tc.result` object is deep-cloned and stripped of inline-binary
+ * content blocks (image / video / audio base64 payloads) before being
+ * serialised into `tool_call_result_data`. The original `tc.result`
+ * reference — which pi retains inside the assistant turn's `messages`
+ * array — is left untouched, so the next LLM request still receives the
+ * full base64 payload. See `display-sanitize.ts` for the rationale.
+ */
+export function toolCallFromRuntime(tc: RuntimeToolCall): ToolCall {
+  const displayTc = sanitizeToolCallForDisplay(tc);
+  const result =
+    displayTc.result !== undefined
+      ? displayTc.result
+      : displayTc.error
+        ? { error: displayTc.error }
+        : undefined;
+  return {
+    tool_name: displayTc.tool_name,
+    tool_call_id: displayTc.tool_call_id,
+    tool_call_status: toLegacyToolCallStatus(displayTc.status),
+    ...(displayTc.args !== undefined ? { tool_call_args: JSON.stringify(displayTc.args) } : {}),
+    ...(displayTc.args_text_delta !== undefined
+      ? { tool_call_args_delta: displayTc.args_text_delta }
+      : {}),
+    ...(result !== undefined ? { tool_call_result_data: JSON.stringify(result) } : {}),
+    ...(tc.duration_ms !== undefined ? { tool_call_duration_ms: tc.duration_ms } : {}),
+    ...(tc.plugin_provenances?.length
+      ? { plugin_provenances: tc.plugin_provenances.map((item) => ({ ...item })) }
+      : {}),
+  };
+}
+
+// ─── pi assistantMessageEvent extraction ────────────────────────────────
+
+/**
+ * The `assistantMessageEvent` on a pi `message_update` carries a
+ * discriminated union from `@earendil-works/pi-ai`. We only need a
+ * tagged subset (text/thinking deltas plus the tool-call streaming
+ * frames) — duck-type without depending on the upstream package so
+ * agent-core stays runtime-agnostic.
+ */
+type DeltaUpdate =
+  | { type: 'text_delta'; delta: string }
+  | { type: 'thinking_delta'; delta: string }
+  | { type: 'toolcall_start'; contentIndex: number }
+  | { type: 'toolcall_delta'; contentIndex: number; delta: string }
+  | { type: 'toolcall_end'; contentIndex: number }
+  | { type: string; [key: string]: unknown };
+
+/**
+ * Tagged tool-call streaming frame extracted from a pi `message_update`.
+ * Identity is best-effort per frame: provider streams carry it on every
+ * frame's `partial` snapshot, proxy streams only on the start frame — the
+ * bridge falls back to its contentIndex mapping when a frame has none.
+ */
+export type ToolCallStreamUpdate =
+  | { kind: 'toolcall_start'; contentIndex: number; toolCallId?: string; toolName?: string }
+  | {
+      kind: 'toolcall_delta';
+      contentIndex: number;
+      delta: string;
+      toolCallId?: string;
+      toolName?: string;
+    }
+  | { kind: 'toolcall_end'; contentIndex: number; toolCallId?: string; toolName?: string };
+
+/**
+ * Best-effort identity of the streaming tool call a frame refers to.
+ *
+ * Checked in priority order across the shapes pi actually emits:
+ * - `toolCall` on the frame itself (provider `toolcall_end`),
+ * - top-level `id` / `toolName` (proxy-transport `toolcall_start`),
+ * - the `partial` assistant-message snapshot's block at `contentIndex`
+ *   (provider streams carry `partial` on every frame; the block is a
+ *   `{ type: 'toolCall', id, name }` entry).
+ */
+function extractToolCallIdentity(
+  update: Record<string, unknown>,
+  contentIndex: number,
+): { toolCallId: string; toolName: string } | undefined {
+  const own = update.toolCall;
+  if (own && typeof own === 'object') {
+    const call = own as Record<string, unknown>;
+    if (typeof call.id === 'string' && typeof call.name === 'string') {
+      return { toolCallId: call.id, toolName: call.name };
+    }
+  }
+  if (typeof update.id === 'string' && typeof update.toolName === 'string') {
+    return { toolCallId: update.id, toolName: update.toolName };
+  }
+  const partial = update.partial;
+  if (partial && typeof partial === 'object') {
+    const content = (partial as Record<string, unknown>).content;
+    if (Array.isArray(content)) {
+      const block = content[contentIndex] as Record<string, unknown> | undefined;
+      if (
+        block &&
+        typeof block === 'object' &&
+        block.type === 'toolCall' &&
+        typeof block.id === 'string' &&
+        typeof block.name === 'string'
+      ) {
+        return { toolCallId: block.id, toolName: block.name };
+      }
+    }
+  }
+  return undefined;
+}
+
+/**
+ * Narrow an `unknown` `assistantMessageEvent` into a tagged delta payload.
+ *
+ * Returns one of the recognized variants (`text_delta` / `thinking_delta` /
+ * `toolcall_start` / `toolcall_delta` / `toolcall_end`) or `undefined` when
+ * the payload is irrelevant — the caller should treat irrelevant updates as
+ * no-ops. Tool-call frames identify their call by pi's `contentIndex`, with
+ * the per-frame identity attached whenever the frame shape carries one.
+ */
+export function extractDeltaUpdate(
+  raw: unknown,
+):
+  | { kind: 'text'; delta: string }
+  | { kind: 'thinking'; delta: string }
+  | ToolCallStreamUpdate
+  | undefined {
+  if (!raw || typeof raw !== 'object') return undefined;
+  const update = raw as DeltaUpdate;
+  if (update.type === 'text_delta' && typeof update.delta === 'string') {
+    return { kind: 'text', delta: update.delta };
+  }
+  if (update.type === 'thinking_delta' && typeof update.delta === 'string') {
+    return { kind: 'thinking', delta: update.delta };
+  }
+  if (update.type === 'toolcall_start' && typeof update.contentIndex === 'number') {
+    return {
+      kind: 'toolcall_start',
+      contentIndex: update.contentIndex,
+      ...(extractToolCallIdentity(update as Record<string, unknown>, update.contentIndex) ?? {}),
+    };
+  }
+  if (
+    update.type === 'toolcall_delta' &&
+    typeof update.contentIndex === 'number' &&
+    typeof update.delta === 'string'
+  ) {
+    return {
+      kind: 'toolcall_delta',
+      contentIndex: update.contentIndex,
+      delta: update.delta,
+      ...(extractToolCallIdentity(update as Record<string, unknown>, update.contentIndex) ?? {}),
+    };
+  }
+  if (update.type === 'toolcall_end' && typeof update.contentIndex === 'number') {
+    return {
+      kind: 'toolcall_end',
+      contentIndex: update.contentIndex,
+      ...(extractToolCallIdentity(update as Record<string, unknown>, update.contentIndex) ?? {}),
+    };
+  }
+  return undefined;
+}
+
+// ─── pi AgentMessage extraction ─────────────────────────────────────────
+
+/**
+ * Pull the visible text concatenation out of a pi assistant `AgentMessage`.
+ * pi stores content as an array of `{ type: 'text' | 'thinking' | 'toolCall' }`
+ * blocks; only `text` blocks contribute to the visible body.
+ */
+export function extractAssistantText(message: unknown): string {
+  if (!message || typeof message !== 'object') return '';
+  const content = (message as Record<string, unknown>).content;
+  if (typeof content === 'string') return content;
+  if (!Array.isArray(content)) return '';
+  return content
+    .map((block) => {
+      if (!block || typeof block !== 'object') return '';
+      const b = block as Record<string, unknown>;
+      if (b.type !== 'text') return '';
+      return typeof b.text === 'string' ? b.text : '';
+    })
+    .join('');
+}
+
+/** Pull the visible thinking concatenation out of a pi assistant message. */
+export function extractAssistantThinking(message: unknown): string {
+  if (!message || typeof message !== 'object') return '';
+  const content = (message as Record<string, unknown>).content;
+  if (!Array.isArray(content)) return '';
+  return content
+    .map((block) => {
+      if (!block || typeof block !== 'object') return '';
+      const b = block as Record<string, unknown>;
+      if (b.type !== 'thinking') return '';
+      return typeof b.thinking === 'string' ? b.thinking : '';
+    })
+    .join('');
+}
+
+/** Extract `RuntimeToolCall[]` from a pi assistant message's content blocks. */
+export function extractAssistantToolCalls(message: unknown): RuntimeToolCall[] {
+  if (!message || typeof message !== 'object') return [];
+  const content = (message as Record<string, unknown>).content;
+  if (!Array.isArray(content)) return [];
+  return content.flatMap((block): RuntimeToolCall[] => {
+    if (!block || typeof block !== 'object') return [];
+    const b = block as Record<string, unknown>;
+    if (b.type !== 'toolCall') return [];
+    const id = b.id;
+    const name = b.name;
+    if (typeof id !== 'string' || typeof name !== 'string') return [];
+    const args = b.arguments;
+    return [
+      {
+        tool_name: name,
+        tool_call_id: id,
+        status: 'started',
+        ...(args !== undefined && typeof args === 'object' && args !== null
+          ? { args: args as Record<string, unknown> }
+          : {}),
+      },
+    ];
+  });
+}
+
+/** True when a pi assistant message reports `stopReason === 'error'`. */
+export function isAssistantError(message: unknown): boolean {
+  if (!message || typeof message !== 'object') return false;
+  const m = message as Record<string, unknown>;
+  return m.role === 'assistant' && m.stopReason === 'error';
+}
+
+/** Extract `errorMessage` from a pi assistant message, if any. */
+export function extractAssistantErrorMessage(message: unknown): string | undefined {
+  if (!message || typeof message !== 'object') return undefined;
+  const errorMessage = (message as Record<string, unknown>).errorMessage;
+  return typeof errorMessage === 'string' && errorMessage ? errorMessage : undefined;
+}
+
+/** Pull `stopReason` (normalised `string | undefined`) off a pi message. */
+export function extractAssistantStopReason(message: unknown): string | undefined {
+  if (!message || typeof message !== 'object') return undefined;
+  const stopReason = (message as Record<string, unknown>).stopReason;
+  return typeof stopReason === 'string' && stopReason ? stopReason : undefined;
+}
+
+/**
+ * Extract token usage from a pi assistant message and convert to the
+ * IDL `TokenUsage` shape ({@link TokenUsage}). pi assistant messages
+ * carry usage on successful turns as
+ * `{ input, output, cacheRead, cacheWrite, totalTokens }`
+ * (see `@earendil-works/pi-ai` `Usage`); aborted / errored turns omit it.
+ *
+ * Returns `undefined` when no usage can be derived so the caller can
+ * fall back to a zero / window-only default rather than emit a spurious
+ * `total_tokens: 0` that masks a missing-usage producer bug.
+ *
+ * `contextWindow` is per-model metadata threaded in from the resolver
+ * (not present on the per-message usage block).
+ *
+ * `cache_read` / `cache_write` are populated when the provider reports
+ * non-zero values so downstream observability (cloud-runtime trace,
+ * daemon SSE) can distinguish a true zero from "field absent" — useful
+ * for diagnosing cache-retention configuration issues.
+ */
+export function extractAssistantUsage(
+  message: unknown,
+  contextWindow: number,
+): TokenUsage | undefined {
+  if (!message || typeof message !== 'object') return undefined;
+  const m = message as Record<string, unknown>;
+  if (m.role !== 'assistant') return undefined;
+  // pi suppresses usage on aborted / error turns — propagate undefined so
+  // downstream callers don't materialise 0 token counts that confuse
+  // billing / observability downstream.
+  const stop = m.stopReason;
+  if (stop === 'aborted' || stop === 'error') return undefined;
+  const usage = m.usage;
+  if (!usage || typeof usage !== 'object') return undefined;
+  const u = usage as Record<string, unknown>;
+  const finite = (v: unknown): number | undefined =>
+    typeof v === 'number' && Number.isFinite(v) ? v : undefined;
+  const input = finite(u.input);
+  const output = finite(u.output);
+  const cacheRead = finite(u.cacheRead) ?? 0;
+  const cacheWrite = finite(u.cacheWrite) ?? 0;
+  const total =
+    (finite(u.totalTokens) ?? 0) || (input ?? 0) + (output ?? 0) + cacheRead + cacheWrite;
+  return {
+    total_tokens: total,
+    context_window: contextWindow,
+    // input_tokens / output_tokens populate the main IRuntimeUsage columns. When the
+    // RecordTokenUsage RPC reports to token_usage, InputTokens/OutputTokens are required IDL fields;
+    // omitting them makes the archon-server billing pipeline write zeros for the whole batch, corrupting reports.
+    // Forward any finite provider value unchanged, including explicit 0: a full cache hit
+    // has 0 input tokens. Omitting it makes downstream consumers treat "known zero" as "unknown"
+    // and mark usageIncomplete. Still omit missing or non-finite values to preserve "unknown" semantics.
+    ...(input === undefined ? {} : { input_tokens: input }),
+    ...(output === undefined ? {} : { output_tokens: output }),
+    ...(cacheRead > 0 ? { cache_read: cacheRead } : {}),
+    ...(cacheWrite > 0 ? { cache_write: cacheWrite } : {}),
+  };
+}
+
+// ─── Stream event helpers (re-exported for the bridge) ──────────────────
+
+interface DeltaChunkInput {
+  sessionId: string;
+  turnId: string;
+  eventId: string;
+  runtimeSeq: number;
+  msgId: string;
+  chunkIndex: number;
+  delta: string;
+  nowMs: number;
+}
+
+/** Build the `text_delta` chunk frame. */
+export function buildTextDeltaChunk(ctx: DeltaChunkInput): StreamRespEvent {
+  return buildStreamRespEvent({
+    sessionId: ctx.sessionId,
+    turnId: ctx.turnId,
+    eventId: ctx.eventId,
+    runtimeSeq: ctx.runtimeSeq,
+    respData: buildChunkRespData({
+      msgId: ctx.msgId,
+      turnId: ctx.turnId,
+      chunkIndex: ctx.chunkIndex,
+      text: ctx.delta,
+      nowMs: ctx.nowMs,
+    }),
+  });
+}
+
+/** Build the `thinking_delta` chunk frame. */
+export function buildThinkingDeltaChunk(ctx: DeltaChunkInput): StreamRespEvent {
+  return buildStreamRespEvent({
+    sessionId: ctx.sessionId,
+    turnId: ctx.turnId,
+    eventId: ctx.eventId,
+    runtimeSeq: ctx.runtimeSeq,
+    respData: buildChunkRespData({
+      msgId: ctx.msgId,
+      turnId: ctx.turnId,
+      chunkIndex: ctx.chunkIndex,
+      thinking: ctx.delta,
+      nowMs: ctx.nowMs,
+    }),
+  });
+}
+
+interface ToolChunkInput {
+  sessionId: string;
+  turnId: string;
+  eventId: string;
+  runtimeSeq: number;
+  msgId: string;
+  chunkIndex: number;
+  toolCall: RuntimeToolCall;
+  nowMs: number;
+}
+
+/** Build a tool-call lifecycle chunk frame (start / completed / failed). */
+export function buildToolCallChunk(input: ToolChunkInput): StreamRespEvent {
+  return buildStreamRespEvent({
+    sessionId: input.sessionId,
+    turnId: input.turnId,
+    eventId: input.eventId,
+    runtimeSeq: input.runtimeSeq,
+    respData: buildChunkRespData({
+      msgId: input.msgId,
+      turnId: input.turnId,
+      chunkIndex: input.chunkIndex,
+      toolCalls: [toolCallFromRuntime(input.toolCall)],
+      nowMs: input.nowMs,
+    }),
+  });
+}
+
+interface FinishChunkInput {
+  sessionId: string;
+  turnId: string;
+  eventId: string;
+  runtimeSeq: number;
+  msgId: string;
+  chunkIndex: number;
+  finishReason?: string;
+  thinkingDurationMs?: number;
+  nowMs: number;
+}
+
+/**
+ * Build the `finish` chunk that marks the end of an assistant message's
+ * stream of partial chunks. Emitted before the `completed` materialised
+ * `AgentMessage` so consumers can flush deltas first.
+ */
+export function buildFinishChunk(input: FinishChunkInput): StreamRespEvent {
+  return buildStreamRespEvent({
+    sessionId: input.sessionId,
+    turnId: input.turnId,
+    eventId: input.eventId,
+    runtimeSeq: input.runtimeSeq,
+    respData: buildChunkRespData({
+      msgId: input.msgId,
+      turnId: input.turnId,
+      chunkIndex: input.chunkIndex,
+      finish: true,
+      ...(input.finishReason ? { finishReason: input.finishReason } : {}),
+      ...(input.thinkingDurationMs !== undefined
+        ? { thinkingDurationMs: input.thinkingDurationMs }
+        : {}),
+      nowMs: input.nowMs,
+    }),
+  });
+}
+
+interface CompletedAssistantInput {
+  sessionId: string;
+  turnId: string;
+  eventId: string;
+  runtimeSeq: number;
+  msgId: string;
+  text: string;
+  thinking?: string;
+  toolCalls?: RuntimeToolCall[];
+  thinkingDurationMs?: number;
+  finishReason?: string;
+  usage?: AgentMessage['usage'];
+  nowMs: number;
+  logger?: PiTurnRunnerLogger;
+}
+
+/**
+ * Build the materialised `AgentMessage` event emitted right after the
+ * matching `finish` chunk. Carries the full text + thinking + tool_calls
+ * + usage so consumers that missed deltas can still render the turn.
+ */
+export async function buildCompletedAssistantMessage(
+  input: CompletedAssistantInput,
+  respDataTransform?: RespDataTransform,
+): Promise<StreamRespEvent> {
+  const respData = await applyRespDataTransform(
+    respDataTransform,
+    buildCompletedRespData({
+      msgId: input.msgId,
+      turnId: input.turnId,
+      text: input.text,
+      ...(input.thinking !== undefined ? { thinking: input.thinking } : {}),
+      ...(input.toolCalls?.length ? { toolCalls: input.toolCalls.map(toolCallFromRuntime) } : {}),
+      ...(input.thinkingDurationMs !== undefined
+        ? { thinkingDurationMs: input.thinkingDurationMs }
+        : {}),
+      ...(input.finishReason ? { finishReason: input.finishReason } : {}),
+      ...(input.usage ? { usage: input.usage } : {}),
+      nowMs: input.nowMs,
+    }),
+    { sessionId: input.sessionId, turnId: input.turnId },
+    input.logger,
+  );
+  return buildStreamRespEvent({
+    sessionId: input.sessionId,
+    turnId: input.turnId,
+    eventId: input.eventId,
+    runtimeSeq: input.runtimeSeq,
+    respData,
+  });
+}
+
+// ─── Terminal pair builders ─────────────────────────────────────────────
+
+interface TerminalStatusInput {
+  sessionId: string;
+  turnId: string;
+  statusEventId: string;
+  terminalUsage?: RuntimeUsage;
+}
+
+interface SessionStatusInput {
+  sessionId: string;
+  turnId: string;
+  eventId: string;
+}
+
+/** Build the initial `session.status running` frame for a turn. */
+export function buildRunningSessionStatusEvent(input: SessionStatusInput): SessionStatusEvent {
+  return {
+    schema: RUNTIME_EVENT_SCHEMA,
+    event_id: input.eventId,
+    session_id: input.sessionId,
+    turn_id: input.turnId,
+    type: RuntimeEventType.SESSION_STATUS,
+    payload: { status: RuntimeEventStatus.RUNNING },
+  };
+}
+
+/** Build the terminal `session.status completed` frame. */
+export function buildCompletedTerminalStatusEvent(input: TerminalStatusInput): SessionStatusEvent {
+  return {
+    schema: RUNTIME_EVENT_SCHEMA,
+    event_id: input.statusEventId,
+    session_id: input.sessionId,
+    turn_id: input.turnId,
+    type: RuntimeEventType.SESSION_STATUS,
+    payload: {
+      status: RuntimeEventStatus.COMPLETED,
+      stop_reason: { type: RuntimeStopReasonType.END_TURN },
+      ...(input.terminalUsage ? { usage: input.terminalUsage } : {}),
+    },
+  };
+}
+
+/** Build the terminal `session.status aborted` frame. */
+export function buildAbortedTerminalStatusEvent(input: TerminalStatusInput): SessionStatusEvent {
+  return {
+    schema: RUNTIME_EVENT_SCHEMA,
+    event_id: input.statusEventId,
+    session_id: input.sessionId,
+    turn_id: input.turnId,
+    type: RuntimeEventType.SESSION_STATUS,
+    payload: {
+      status: RuntimeEventStatus.ABORTED,
+      stop_reason: { type: RuntimeStopReasonType.ABORT, message: 'aborted' },
+      ...(input.terminalUsage ? { usage: input.terminalUsage } : {}),
+    },
+  };
+}
+
+interface FailedTerminalInput extends TerminalStatusInput {
+  message: string;
+  error?: RuntimeProtocolError;
+}
+
+/** Build the terminal `session.status failed` frame. */
+export function buildFailedTerminalStatusEvent(input: FailedTerminalInput): SessionStatusEvent {
+  const stopReason: RuntimeStopReason = {
+    type: RuntimeStopReasonType.ERROR,
+    message: input.message,
+  };
+  const protocolError: RuntimeProtocolError = input.error ?? {
+    code: ProtocolErrorCode.INTERNAL_ERROR,
+    message: input.message,
+  };
+  return {
+    schema: RUNTIME_EVENT_SCHEMA,
+    event_id: input.statusEventId,
+    session_id: input.sessionId,
+    turn_id: input.turnId,
+    type: RuntimeEventType.SESSION_STATUS,
+    payload: { status: RuntimeEventStatus.FAILED, stop_reason: stopReason, error: protocolError },
+  };
+}
+
+interface DebugTraceInput {
+  sessionId: string;
+  turnId: string;
+  eventId: string;
+  phase: string;
+  message: string;
+  level?: 'debug' | 'info' | 'warn' | 'error';
+  attrs?: Record<string, string | number | boolean>;
+  durationMs?: number;
+}
+
+/** Map the legacy debug-trace level string to the protocol numeric enum. */
+function debugTraceLevelToEnum(level: 'debug' | 'info' | 'warn' | 'error'): RuntimeDebugTraceLevel {
+  switch (level) {
+    case 'info':
+      return RuntimeDebugTraceLevel.INFO;
+    case 'warn':
+      return RuntimeDebugTraceLevel.WARN;
+    case 'error':
+      return RuntimeDebugTraceLevel.ERROR;
+    default:
+      return RuntimeDebugTraceLevel.DEBUG;
+  }
+}
+
+/**
+ * Build a `debug.trace` event.
+ *
+ * Wire-format note: the new thrift IDL carries the `attrs` map as a
+ * `attrs_json` string (the generator does not emit `map<string,
+ * variant>`), so caller-supplied `attrs` are JSON-stringified into the
+ * payload. Consumers that want to read attrs must JSON.parse
+ * `payload.trace.attrs_json` back into a record.
+ */
+export function buildDebugTraceEvent(input: DebugTraceInput): RuntimeEvent {
+  return {
+    schema: RUNTIME_EVENT_SCHEMA,
+    event_id: input.eventId,
+    session_id: input.sessionId,
+    turn_id: input.turnId,
+    type: RuntimeEventType.DEBUG_TRACE,
+    payload: {
+      trace: {
+        phase: input.phase,
+        level: debugTraceLevelToEnum(input.level ?? 'debug'),
+        message: input.message,
+        ...(input.durationMs === undefined ? {} : { duration_ms: input.durationMs }),
+        ...(input.attrs ? { attrs_json: JSON.stringify(input.attrs) } : {}),
+      },
+    },
+  };
+}
+
+// ─── Buffered-event extraction (sub-agent helpers) ──────────────────────
+
+/**
+ * Walk a buffered `RuntimeEvent[]` and return the visible `msg_content` of
+ * the LAST closed assistant `AgentMessage` frame. Filters by
+ * `RespData.type === RespDataType.AgentMessage` — explicitly NOT
+ * `AgentMessageChunk`. Returns `''` when no terminal `AgentMessage` exists.
+ */
+export function extractFinalAssistantText(buffered: readonly RuntimeEvent[]): string {
+  for (let i = buffered.length - 1; i >= 0; i--) {
+    const ev = buffered[i];
+    if (!ev || ev.type !== RuntimeEventType.STREAM_RESP) continue;
+    const raw = ev.payload?.stream_resp;
+    if (typeof raw !== 'string') continue;
+    let parsed: unknown;
+    try {
+      parsed = JSON.parse(raw);
+    } catch {
+      continue;
+    }
+    if (!parsed || typeof parsed !== 'object') continue;
+    const respData = parsed as { type?: unknown; agent_message?: unknown };
+    if (respData.type !== RespDataType.AgentMessage) continue;
+    const msg = respData.agent_message;
+    if (!msg || typeof msg !== 'object') continue;
+    const content = (msg as { msg_content?: unknown }).msg_content;
+    return typeof content === 'string' ? content : '';
+  }
+  return '';
+}
+
+/**
+ * Same buffer-walk strategy as {@link extractFinalAssistantText} but returns
+ * the `usage` field on the last `AgentMessage` (matches the IDL `TokenUsage`
+ * shape: `{ total_tokens, context_window, cache_read?, cache_write? }`).
+ * Returns `undefined` when no `AgentMessage` exists or when it has no
+ * `usage` block. Cache fields are pulled through symmetrically with
+ * {@link extractAssistantUsage} — sub-agent paths (e.g. `cloud-task` buffer
+ * extraction) must not silently drop cache metrics.
+ */
+export function extractFinalAssistantUsageFromBuffer(
+  buffered: readonly RuntimeEvent[],
+): TokenUsage | undefined {
+  for (let i = buffered.length - 1; i >= 0; i--) {
+    const ev = buffered[i];
+    if (!ev || ev.type !== RuntimeEventType.STREAM_RESP) continue;
+    const raw = ev.payload?.stream_resp;
+    if (typeof raw !== 'string') continue;
+    let parsed: unknown;
+    try {
+      parsed = JSON.parse(raw);
+    } catch {
+      continue;
+    }
+    if (!parsed || typeof parsed !== 'object') continue;
+    const respData = parsed as { type?: unknown; agent_message?: unknown };
+    if (respData.type !== RespDataType.AgentMessage) continue;
+    const msg = respData.agent_message;
+    if (!msg || typeof msg !== 'object') continue;
+    const usage = (msg as { usage?: unknown }).usage;
+    if (!usage || typeof usage !== 'object') return undefined;
+    const u = usage as {
+      total_tokens?: unknown;
+      context_window?: unknown;
+      cache_read?: unknown;
+      cache_write?: unknown;
+    };
+    const total = typeof u.total_tokens === 'number' ? u.total_tokens : 0;
+    const cw = typeof u.context_window === 'number' ? u.context_window : 0;
+    const cacheRead = typeof u.cache_read === 'number' ? u.cache_read : 0;
+    const cacheWrite = typeof u.cache_write === 'number' ? u.cache_write : 0;
+    return {
+      total_tokens: total,
+      context_window: cw,
+      ...(cacheRead > 0 ? { cache_read: cacheRead } : {}),
+      ...(cacheWrite > 0 ? { cache_write: cacheWrite } : {}),
+    };
+  }
+  return undefined;
+}

+ 224 - 0
packages/agent-core/src/event-bridge/display-sanitize.ts

@@ -0,0 +1,224 @@
+/**
+ * Display-layer sanitisation for tool-call results.
+ *
+ * # Why this exists
+ *
+ * The pi `read` tool returns image and video payloads as
+ * `{ type: 'image', data: <base64>, mimeType: 'image/*' | 'video/*' }`
+ * content blocks. pi-ai needs those blocks intact in the assistant turn's
+ * `messages` array so the model can actually see the image / video.
+ *
+ * Before this helper existed, the wire-level
+ * `RuntimeEvent.stream.resp → AgentMessageChunk.tool_calls[*].tool_call_result_data`
+ * field JSON-serialised the entire result envelope, which dragged the full
+ * base64 payload into:
+ *
+ *   1. The local SQLite `local_runtime_message_rows.data_json` row
+ *   2. The `display.jsonl` session transcript
+ *   3. The `stream.resp` SSE payload streamed to the UI
+ *   4. The cloud runtime → archon-server exchange
+ *
+ * A single read-image call (3-4 MB base64) would inflate each row by that
+ * much; an 80-message page would balloon to >100 MB and freeze the
+ * Electron UI. The bug was introduced together with `EventBridge` in
+ * `a30533d9f` (2026-05-21) and remained latent until production users
+ * hit the symptom.
+ *
+ * # What this module guarantees
+ *
+ *   - `tc.result` is **never** mutated. pi keeps a reference to the same
+ *     object inside the assistant-turn `messages` array, which feeds the
+ *     next LLM request. We must deep-clone before stripping so the model
+ *     still sees the original binary.
+ *   - Image / video / audio content blocks have their `data` field removed
+ *     from the display copy. The block itself is dropped (not replaced by a
+ *     placeholder string) because the UI does not consume the wire payload
+ *     for read-image calls — see
+ *     `packages/ui/src/components/message/tool-renderers/ToolCallRow.tsx`
+ *     `isImageReadToolCall` short-circuit (success path returns no detail
+ *     panel). Dropping the block keeps the wire JSON compact and avoids
+ *     ever shipping base64 to the renderer.
+ *   - All other content blocks (`type === 'text'`, `toolCall`,
+ *     non-multimodal metadata blocks) pass through untouched.
+ *   - `details` is preserved as-is so future UI affordances can still read
+ *     `details.media.kind` / `size_bytes` if they want to surface "Read
+ *     video (12 MB)" without re-fetching the binary.
+ *
+ * # Where the function is wired in
+ *
+ *   - `packages/agent-core/src/event-bridge/converters.ts::toolCallFromRuntime`
+ *     — single chokepoint for the SSE / SQLite / display.jsonl / cloud
+ *     uplink channels.
+ *   - `packages/local-runtime/src/legacy-opencode/legacy-opencode-migrator.ts`
+ *     — companion `sanitizeWireToolCallResultData` for already-stringified
+ *     legacy payloads that bypass the converter.
+ */
+
+import type { RuntimeToolCall } from '../protocol/runtime-event.js';
+
+/** Threshold above which a string is treated as an inline binary payload. */
+export const INLINE_BINARY_INLINE_THRESHOLD = 1024;
+
+/**
+ * Pi / pi-ai content block shape used inside a tool result's `content`
+ * array. We deliberately duck-type rather than import `@earendil-works/pi-ai`
+ * so agent-core stays runtime-agnostic (same pattern as `extractAssistantText`).
+ */
+interface DisplayContentBlock {
+  readonly type?: unknown;
+  readonly text?: unknown;
+  readonly data?: unknown;
+  readonly mimeType?: unknown;
+  readonly [key: string]: unknown;
+}
+
+interface DisplayToolResultShape {
+  readonly content?: unknown;
+  readonly details?: unknown;
+  readonly text?: unknown;
+  readonly [key: string]: unknown;
+}
+
+/**
+ * Decide whether a content block carries an inline binary payload that
+ * must NOT be serialised into the display wire envelope.
+ *
+ * Matches:
+ *   - `{ type: 'image' | 'video' | 'audio', data: <base64>, mimeType: '...' }`
+ *   - `{ type: 'file', data: <base64> }`
+ *   - Any block whose `data` field is a large base64-shaped string, even if
+ *     the `type` discriminator is missing — this catches future block kinds
+ *     that we have not enumerated explicitly.
+ */
+export function isInlineBinaryContentBlock(block: unknown): boolean {
+  if (!block || typeof block !== 'object') return false;
+  const b = block as DisplayContentBlock;
+  const type = typeof b.type === 'string' ? b.type : '';
+  const data = b.data;
+  if (typeof data !== 'string') return false;
+
+  if (type === 'image' || type === 'video' || type === 'audio' || type === 'file') {
+    return true;
+  }
+
+  // Heuristic fallback: large base64-looking strings without a recognised
+  // type. Uses length + charset to avoid misclassifying normal prose.
+  if (data.length >= INLINE_BINARY_INLINE_THRESHOLD && isLikelyBase64(data)) {
+    return true;
+  }
+  return false;
+}
+
+const BASE64_CHARS_RE = /^[A-Za-z0-9+/_=\s-]+$/;
+
+/**
+ * Conservative base64 detector. Allows URL-safe alphabet and whitespace so
+ * the heuristic also catches line-wrapped base64 the way pi sometimes emits.
+ */
+export function isLikelyBase64(input: string): boolean {
+  if (!input.length) return false;
+  // Sample the first 256 chars to avoid scanning multi-megabyte strings.
+  const sample = input.length > 256 ? input.slice(0, 256) : input;
+  return BASE64_CHARS_RE.test(sample);
+}
+
+/**
+ * Return a deep-cloned `content` array with inline-binary blocks stripped.
+ *
+ * The clone uses `structuredClone` when available (Node 17+) and falls back
+ * to a JSON round-trip otherwise. The fallback is safe because every
+ * surviving block is plain JSON-serialisable data (text strings, mimeType,
+ * small metadata).
+ */
+export function stripInlineBinaryFromContent(content: unknown): unknown {
+  if (!Array.isArray(content)) return content;
+  const filtered = content.filter((block) => !isInlineBinaryContentBlock(block));
+  if (filtered.length === content.length) return content;
+  return cloneStructured(filtered);
+}
+
+/**
+ * Deep-clone a JSON-safe value. We need a clone (not in-place strip)
+ * because `tc.result` is the same object pi retains in its in-memory
+ * `messages` array.
+ */
+function cloneStructured<T>(value: T): T {
+  const structuredCloneFn = (globalThis as { structuredClone?: (v: unknown) => unknown })
+    .structuredClone;
+  if (typeof structuredCloneFn === 'function') {
+    return structuredCloneFn(value) as T;
+  }
+  return JSON.parse(JSON.stringify(value)) as T;
+}
+
+/**
+ * Produce a display-safe copy of a tool-call result envelope.
+ *
+ * Behaviour:
+ *   - `content[]` — inline-binary blocks removed (the rest pass through).
+ *   - everything else (`details`, `text`, `isError`, …) — preserved as-is
+ *     because none of it can ship megabytes.
+ *
+ * The input is never mutated.
+ */
+export function sanitizeToolResultForDisplay(raw: unknown): unknown {
+  if (raw === undefined || raw === null) return raw;
+  if (typeof raw !== 'object') return raw;
+  const shape = raw as DisplayToolResultShape;
+  const stripped = stripInlineBinaryFromContent(shape.content);
+  if (stripped === shape.content) return raw;
+  return { ...(raw as Record<string, unknown>), content: stripped };
+}
+
+/**
+ * Wrap a `RuntimeToolCall` for serialisation into the wire-level
+ * `ToolCall` shape. Always returns a deep clone — pi retains the
+ * original `tc.result` reference inside the assistant turn's `messages`
+ * array, and a future maintainer must not be able to mutate that state
+ * by editing the display copy. The clone additionally strips inline
+ * binary blocks from the display-side `result.content`.
+ */
+export function sanitizeToolCallForDisplay(tc: RuntimeToolCall): RuntimeToolCall {
+  if (tc.result === undefined) {
+    // No result to strip, but still clone so the caller can mutate the
+    // returned envelope without leaking back into pi's state.
+    return cloneStructured(tc);
+  }
+  const sanitisedResult = sanitizeToolResultForDisplay(tc.result);
+  return cloneStructured({
+    ...tc,
+    result: sanitisedResult,
+  });
+}
+
+/**
+ * Companion helper for legacy payloads that have already been
+ * JSON-stringified (the `tool_call_result_data` wire field). Parses,
+ * strips inline binary, re-serialises. Falls back to a length-capped
+ * placeholder when the payload is not valid JSON or carries raw binary
+ * outside the structured shape.
+ */
+export function sanitizeWireToolCallResultData(raw: string): string {
+  if (typeof raw !== 'string') return raw;
+  if (raw.length === 0) return raw;
+  // Quick reject: if the payload is not even wrapped as a JSON object, we
+  // cannot safely strip structured fields. Cap it instead so an opaque
+  // 4MB string cannot sneak through.
+  const firstNonWs = raw.trimStart()[0];
+  if (firstNonWs !== '{' && firstNonWs !== '[') {
+    return raw.length > INLINE_BINARY_INLINE_THRESHOLD
+      ? `<omitted:non-json ${raw.length} bytes>`
+      : raw;
+  }
+  let parsed: unknown;
+  try {
+    parsed = JSON.parse(raw);
+  } catch {
+    return raw.length > INLINE_BINARY_INLINE_THRESHOLD
+      ? `<omitted:invalid-json ${raw.length} bytes>`
+      : raw;
+  }
+  const cleaned = sanitizeToolResultForDisplay(parsed);
+  if (cleaned === parsed) return raw;
+  return JSON.stringify(cleaned);
+}

+ 72 - 0
packages/agent-core/src/event-bridge/index.ts

@@ -0,0 +1,72 @@
+/**
+ * `@mavis/agent-core/event-bridge` — convert pi `AgentEvent` streams into
+ * canonical `RuntimeEvent` frames consumed by `EventSink.pushRuntime`.
+ *
+ * This module is **stateless across turns**: callers create one
+ * {@link EventBridge} per pi `runAgentLoop` invocation, feed events to
+ * {@link EventBridge.processEvent}, then close the turn with one of the
+ * `emit*` terminal helpers.
+ *
+ * The conversion logic itself is split into pure functions in
+ * `./converters.ts` so consumers (local-runtime, cloud-runtime,
+ * unit tests) can reuse the building blocks without booting a full
+ * bridge instance.
+ *
+ * @see packages/cloud-runtime/README.md
+ */
+
+export { EventBridge } from './bridge.js';
+export type {
+  BridgedEvents,
+  EventBridgeContext,
+  ToolCallProvenanceResolutionInput,
+  ToolCallProvenanceResolver,
+  TurnTerminationReason,
+} from './types.js';
+export {
+  attachPluginCapabilityAttribution,
+  createPluginCapabilityAttributionResolver,
+  normalizedPluginSkillAttributionKey,
+  selectPreferredAppPluginOwners,
+  type PluginCapabilityAttributionIndex,
+} from './plugin-capability-attribution.js';
+export type { RespDataTransform, RespDataTransformContext } from './resp-data.js';
+export {
+  buildRuntimeWarningEvent,
+  RUNTIME_WARNING_EVENT_TYPE,
+  type RuntimeWarningEventInput,
+} from './runtime-warning.js';
+export { classifyLLMErrorToCode } from '@mavis/shared/llm-error-classifier';
+export {
+  buildAbortedTerminalStatusEvent,
+  buildCompletedAssistantMessage,
+  buildCompletedTerminalStatusEvent,
+  buildDebugTraceEvent,
+  buildFailedTerminalStatusEvent,
+  buildFinishChunk,
+  buildRunningSessionStatusEvent,
+  buildStreamRespEvent,
+  buildTextDeltaChunk,
+  buildThinkingDeltaChunk,
+  buildToolCallChunk,
+  extractAssistantErrorMessage,
+  extractAssistantStopReason,
+  extractAssistantText,
+  extractAssistantThinking,
+  extractAssistantToolCalls,
+  extractDeltaUpdate,
+  extractFinalAssistantText,
+  extractFinalAssistantUsageFromBuffer,
+  isAssistantError,
+  toolCallFromRuntime,
+} from './converters.js';
+
+export {
+  INLINE_BINARY_INLINE_THRESHOLD,
+  isInlineBinaryContentBlock,
+  isLikelyBase64,
+  sanitizeToolCallForDisplay,
+  sanitizeToolResultForDisplay,
+  sanitizeWireToolCallResultData,
+  stripInlineBinaryFromContent,
+} from './display-sanitize.js';

+ 110 - 0
packages/agent-core/src/event-bridge/plugin-capability-attribution.ts

@@ -0,0 +1,110 @@
+import type { IPluginCapabilityProvenance } from '@mavis/protocol';
+import type {
+  RuntimeTool,
+  ToolCallProvenanceResolutionInput,
+  ToolCallProvenanceResolver,
+} from '../tools/types.js';
+
+export interface PluginCapabilityAttributionIndex {
+  /** Direct runtime tool name -> Plugin owners. */
+  readonly directTools: ReadonlyMap<string, readonly IPluginCapabilityProvenance[]>;
+  /** Deferred target runtime tool name -> Plugin owners used through mcp_invoke. */
+  readonly deferredTools: ReadonlyMap<string, readonly IPluginCapabilityProvenance[]>;
+  /** Canonical Plugin Skill name -> Plugin owner. */
+  readonly skills: ReadonlyMap<string, readonly IPluginCapabilityProvenance[]>;
+}
+
+/**
+ * Build the host-independent resolver over a turn-local immutable attribution
+ * index. Hosts own the index; this function only understands the two generic
+ * access tools (`mcp_invoke` and `skill`).
+ */
+export function createPluginCapabilityAttributionResolver(
+  index: PluginCapabilityAttributionIndex,
+): ToolCallProvenanceResolver {
+  return (input) => resolvePluginCapabilityAttribution(index, input);
+}
+
+/** Attach one immutable attribution index to only the tools it can resolve. */
+export function attachPluginCapabilityAttribution<TTool extends RuntimeTool>(
+  tools: readonly TTool[],
+  index: PluginCapabilityAttributionIndex,
+): TTool[] {
+  const resolver = createPluginCapabilityAttributionResolver(index);
+  return tools.map((tool) => {
+    const name = tool.def.name;
+    const relevant =
+      index.directTools.has(name) ||
+      (name === 'mcp_invoke' && index.deferredTools.size > 0) ||
+      (name === 'skill' && index.skills.size > 0);
+    return relevant ? ({ ...tool, toolCallProvenanceResolver: resolver } as TTool) : tool;
+  });
+}
+
+function resolvePluginCapabilityAttribution(
+  index: PluginCapabilityAttributionIndex,
+  input: ToolCallProvenanceResolutionInput,
+): readonly IPluginCapabilityProvenance[] | undefined {
+  if (input.toolName === 'tool_search') return undefined;
+  if (input.toolName === 'mcp_invoke') {
+    const target = optionalString(input.args?.tool_name);
+    return target ? copy(index.deferredTools.get(target)) : undefined;
+  }
+  if (input.toolName === 'skill') {
+    if (input.phase !== 'end' || input.isError === true || !isSuccessfulPluginSkill(input.result)) {
+      return undefined;
+    }
+    const skillName = optionalString(input.args?.name);
+    return skillName ? copy(index.skills.get(normalizedSkillName(skillName))) : undefined;
+  }
+  return copy(index.directTools.get(input.toolName));
+}
+
+export function normalizedPluginSkillAttributionKey(name: string): string {
+  return normalizedSkillName(name);
+}
+
+/**
+ * Prefer the Plugin whose canonical name matches the App provider. A matching
+ * Plugin is the App's primary brand owner; when no such owner exists, retain
+ * every effective Plugin that declares the App.
+ */
+export function selectPreferredAppPluginOwners<TPlugin extends { readonly name: string }>(
+  provider: string,
+  owners: readonly TPlugin[],
+): readonly TPlugin[] {
+  const normalizedProvider = normalizedName(provider);
+  const preferred = owners.filter((plugin) => normalizedName(plugin.name) === normalizedProvider);
+  return preferred.length > 0 ? preferred : owners;
+}
+
+function isSuccessfulPluginSkill(result: unknown): boolean {
+  if (!isRecord(result) || !isRecord(result.details)) return false;
+  return (
+    (result.details.source === 'plugin' || result.details.source === 'desktop-plugin') &&
+    result.details.found === true &&
+    result.details.readable === true
+  );
+}
+
+function normalizedSkillName(name: string): string {
+  return normalizedName(name);
+}
+
+function normalizedName(name: string): string {
+  return name.trim().normalize('NFKC').toLocaleLowerCase('en-US');
+}
+
+function optionalString(value: unknown): string | undefined {
+  return typeof value === 'string' && value.trim() ? value.trim() : undefined;
+}
+
+function copy(
+  value: readonly IPluginCapabilityProvenance[] | undefined,
+): IPluginCapabilityProvenance[] | undefined {
+  return value?.length ? value.map((item) => ({ ...item })) : undefined;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+  return typeof value === 'object' && value !== null && !Array.isArray(value);
+}

+ 31 - 0
packages/agent-core/src/event-bridge/resp-data.ts

@@ -0,0 +1,31 @@
+import type { RespData } from '../protocol/agent-message.js';
+import type { PiTurnRunnerLogger } from '../pi-turn-runner/types.js';
+
+export type RespDataTransform = (
+  respData: RespData,
+  ctx: RespDataTransformContext,
+) => Promise<RespData> | RespData;
+
+export interface RespDataTransformContext {
+  sessionId: string;
+  turnId: string;
+}
+
+export async function applyRespDataTransform(
+  transform: RespDataTransform | undefined,
+  respData: RespData,
+  ctx: RespDataTransformContext,
+  logger?: PiTurnRunnerLogger,
+): Promise<RespData> {
+  if (!transform) return respData;
+  try {
+    return await transform(respData, ctx);
+  } catch (err) {
+    const reason = err instanceof Error ? err.message : String(err);
+    logger?.warn?.(
+      { session_id: ctx.sessionId, turn_id: ctx.turnId, error: reason },
+      'respDataTransform failed; using original RespData',
+    );
+    return respData;
+  }
+}

+ 59 - 0
packages/agent-core/src/event-bridge/runtime-warning.ts

@@ -0,0 +1,59 @@
+import {
+  MsgType,
+  RespDataType,
+  type AgentMessage,
+  type RespData,
+} from '../protocol/agent-message.js';
+import type { StreamRespEvent } from '../protocol/runtime-event.js';
+import { buildStreamRespEvent } from './converters.js';
+
+export const RUNTIME_WARNING_EVENT_TYPE = 'runtime.warning';
+
+export interface RuntimeWarningEventInput {
+  readonly sessionId: string;
+  readonly turnId: string;
+  readonly eventId: string;
+  readonly runtimeSeq: number;
+  readonly message: string;
+  readonly source: string;
+  readonly code?: string;
+  readonly pluginName?: string;
+  readonly hookEvent?: string;
+  /** Allowlisted terminal bytes; only a live TUI surface may execute them. */
+  readonly terminalSequence?: string;
+  readonly nowMs?: number;
+}
+
+/**
+ * Build a durable, user-visible runtime warning without adding it to model
+ * history. Hosts persist and fan out this ordinary `MsgType.SystemEvent`; UI
+ * clients project it into a warning surface while Pi history ignores it.
+ */
+export function buildRuntimeWarningEvent(input: RuntimeWarningEventInput): StreamRespEvent {
+  const message: AgentMessage = {
+    msg_id: input.eventId,
+    turn_id: input.turnId,
+    timestamp: input.nowMs ?? Date.now(),
+    msg_type: MsgType.SystemEvent,
+    msg_content: JSON.stringify({
+      eventType: RUNTIME_WARNING_EVENT_TYPE,
+      message: input.message,
+      source: input.source,
+      ...(input.code ? { code: input.code } : {}),
+      ...(input.pluginName ? { pluginName: input.pluginName } : {}),
+      ...(input.hookEvent ? { hookEvent: input.hookEvent } : {}),
+      ...(input.terminalSequence ? { terminalSequence: input.terminalSequence } : {}),
+    }),
+  };
+  const respData: RespData = {
+    type: RespDataType.AgentMessage,
+    agent_message: message,
+  };
+  return buildStreamRespEvent({
+    sessionId: input.sessionId,
+    turnId: input.turnId,
+    eventId: input.eventId,
+    runtimeSeq: input.runtimeSeq,
+    respData,
+  });
+}

+ 98 - 0
packages/agent-core/src/event-bridge/types.ts

@@ -0,0 +1,98 @@
+/**
+ * Shared types for the event-bridge subsystem.
+ *
+ * Hosts (daemon, cloud-runtime) wire concrete services in `host-utils.ts`;
+ * everything in this file is pure type vocabulary.
+ */
+
+import type { RuntimeEvent, RuntimeProtocolError } from '../protocol/runtime-event.js';
+import type { ToolCallProvenanceResolver } from '../tools/types.js';
+import type { RespDataTransform } from './resp-data.js';
+import type { PiTurnRunnerLogger } from '../pi-turn-runner/types.js';
+
+/**
+ * Stable identity hooks that callers must thread through every conversion
+ * call. Pulled into a single bag so the bridge stays decoupled from how
+ * hosts mint event ids and runtime sequence numbers (daemon uses an
+ * in-process counter, cloud-runtime delegates to archon_server).
+ *
+ * `eventIdGenerator` receives a short kind hint (`coding_text`,
+ * `coding_finish`, …) so loggers can identify the event source. The
+ * returned id MUST be globally unique within the session.
+ *
+ * `runtimeSeqGenerator` returns monotonically increasing positive
+ * integers within a single (session, turn) pair. Phase 1 archon_server
+ * uses these to order events; missing or reused values break replay.
+ *
+ * `nowMs` is optional — when omitted, the bridge falls back to `Date.now()`.
+ * Tests inject a deterministic source.
+ *
+ * `contextWindow` is optional and threaded in from the resolved Pi
+ * `Model<Api>` — it is used to populate the wire-level `TokenUsage`
+ * `context_window` field on every assistant message. When omitted the
+ * bridge falls back to `DEFAULT_CONTEXT_WINDOW` (200_000) and logs a
+ * one-shot warn so observability can spot misconfigured hosts.
+ */
+export interface EventBridgeContext {
+  sessionId: string;
+  turnId: string;
+  eventIdGenerator: (kind: string) => string;
+  runtimeSeqGenerator: () => number;
+  nowMs?: () => number;
+  /** Physical provider request duration associated with a completed assistant message. */
+  requestDurationMs?: (message: unknown) => number | undefined;
+  /** Include per-request input/output/duration fields in wire usage. */
+  includeDetailedUsage?: boolean;
+  /** Optional hook applied to completed AgentMessage RespData before serialization. */
+  respDataTransform?: RespDataTransform;
+  logger?: PiTurnRunnerLogger;
+  /** Optional context-window size for the active model. */
+  contextWindow?: number;
+  /** Measure per-tool-call `duration_ms` (start → end). Host sets it non-prod only. */
+  captureToolTiming?: boolean;
+  /** Turn-local, fail-open resolver for Plugin capability attribution. */
+  toolCallProvenanceResolver?: ToolCallProvenanceResolver;
+}
+
+/**
+ * Outcome of converting a single pi `AgentEvent`.
+ *
+ * `events` carries the canonical `RuntimeEvent[]` to forward to the host's
+ * `EventSink.pushRuntime`. The optional `requestAssistantMessageId` flag
+ * signals that the bridge needs the host to allocate a fresh assistant
+ * `message_id` before any further events for this turn can be emitted —
+ * see {@link EventBridge.processEvent} for the contract.
+ */
+export interface BridgedEvents {
+  /** RuntimeEvents ready to push to EventSink. */
+  events: RuntimeEvent[];
+  /**
+   * When set, the caller must allocate an assistant message id (via host
+   * port) and call {@link EventBridge.setActiveAssistantMessageId} BEFORE
+   * the next event is fed in. The bridge cannot emit `stream.resp` events
+   * without an assistant message id, so it returns no events on
+   * `message_start` until the host has resolved one.
+   */
+  requestAssistantMessageId?: boolean;
+}
+
+/**
+ * Reasons used to build a non-success terminal frame.
+ *
+ * The bridge produces a terminal `session.status` frame so downstream
+ * consumers see consistent `stop_reason` / `error` payloads.
+ *
+ * `failed.error` is optional — when the host has already classified the
+ * underlying failure (e.g. LLM 401 / 429), pass it through so
+ * `session.status.payload.error.code` carries the stable status code.
+ * Caller omits it → bridge falls back to `{ code: INTERNAL_ERROR, message }`.
+ */
+export type TurnTerminationReason =
+  | { kind: 'completed' }
+  | { kind: 'aborted' }
+  | { kind: 'failed'; message: string; error?: RuntimeProtocolError };
+
+export type {
+  ToolCallProvenanceResolutionInput,
+  ToolCallProvenanceResolver,
+} from '../tools/types.js';

+ 34 - 0
packages/agent-core/src/index.ts

@@ -0,0 +1,34 @@
+/**
+ * `@mavis/agent-core`
+ * -------------------
+ *
+ * Pure TypeScript core for Mavis agent-loop contracts.
+ *
+ * **Zero IO.** This package contains no filesystem access, no process
+ * spawning, no SQLite, no HTTP server. IO modules belong in the host
+ * packages (local-runtime, cloud-runtime).
+ *
+ * Subpath modules (`./event-bridge`, `./pi-turn-runner`, …) carry the
+ * agent-loop assembly and conversion layers — import them directly so
+ * consumers that only need protocol types pay no `@earendil-works/*`
+ * loading cost.
+ *
+ * @see packages/agent-core/ARCHITECTURE.md
+ */
+
+export * from './protocol/index.js';
+export * from './prompt-read.js';
+export { collectFetchedWebSources } from '@mavis/shared/fetched-web-sources';
+export { shellSourceStages } from '@mavis/shared/shell-source-stages';
+export { collapseAdjacentDuplicateFileCitations } from '@mavis/shared/file-source-citation';
+export {
+  collectWebSourceCitations,
+  collectUsedWebEvidenceIds,
+  type ContextualWebCitation,
+} from '@mavis/shared';
+export {
+  buildToolCallCitationId,
+  compactToolCallCitationKey,
+  findUniqueSingleSubstitutionCitationAlias,
+  resolveKnownCitationAlias,
+} from '@mavis/shared/source-citation-id';

+ 137 - 0
packages/agent-core/src/pi-turn-runner/agent.ts

@@ -0,0 +1,137 @@
+import { Agent } from '@earendil-works/pi-agent-core';
+import type { UserMessage } from '@earendil-works/pi-ai';
+import type { TurnTerminationReason } from '../event-bridge/types.js';
+import { projectAgentMessagesForModel } from './outbound-message-normalizer.js';
+import { failureReason } from './terminal.js';
+import type { turnState } from './turn.js';
+import type { UserMessageInput } from './types.js';
+
+type PiUserMessage = UserMessage &
+  Pick<UserMessageInput, 'canonicalTextRange' | 'genuineUserQueryText' | 'hostMetadata'>;
+
+export function toPiUserMessage(input: UserMessageInput): PiUserMessage {
+  const message: PiUserMessage = {
+    role: 'user',
+    content: [{ type: 'text', text: input.text }, ...(input.attachments ?? [])],
+    timestamp: input.timestamp ?? Date.now(),
+    ...(input.canonicalTextRange
+      ? {
+          canonicalTextRange: {
+            startOffset: input.canonicalTextRange.startOffset,
+            endOffset: input.canonicalTextRange.endOffset,
+          },
+        }
+      : {}),
+    ...(input.genuineUserQueryText !== undefined
+      ? { genuineUserQueryText: input.genuineUserQueryText }
+      : {}),
+    ...(input.hostMetadata ? { hostMetadata: { ...input.hostMetadata } } : {}),
+  };
+  return message;
+}
+
+export function newAgent(turn: turnState): Agent {
+  return new Agent({
+    initialState: {
+      systemPrompt: turn.input.systemPrompt,
+      model: turn.llm.model,
+      thinkingLevel: turn.thinkingLevel,
+      tools: turn.tools,
+      messages: turn.initialMessages,
+    },
+    convertToLlm: (messages) => {
+      const outbound = projectAgentMessagesForModel(messages, turn.llm.model);
+      if (outbound.removedCount > 0) {
+        turn.logger.warn(
+          {
+            session_id: turn.input.sessionId,
+            turn_id: turn.input.turnId,
+            provider: turn.llm.model.provider,
+            removed_count: outbound.removedCount,
+          },
+          '[pi-turn-runner] removed orphan tool results from provider-bound history',
+        );
+      }
+      const undeterminedImages = Object.entries(outbound.undeterminedImageMimeTypes);
+      if (undeterminedImages.length > 0) {
+        // Images kept because their size is unreadable. A recurring cluster here
+        // is the signal to teach imageDimensions another format. Diagnostic, not
+        // an error: nothing is broken, the block is deliberately passed through,
+        // and history is re-projected on every request of the session.
+        turn.logger.info(
+          {
+            event: 'outbound_image_size_undetermined',
+            session_id: turn.input.sessionId,
+            turn_id: turn.input.turnId,
+            provider: turn.llm.model.provider,
+            undetermined_image_count: undeterminedImages.reduce(
+              (total, [, count]) => total + count,
+              0,
+            ),
+            undetermined_image_mime_types: outbound.undeterminedImageMimeTypes,
+          },
+          '[pi-turn-runner] kept provider-bound images whose dimensions could not be determined',
+        );
+      }
+      return outbound.messages;
+    },
+    streamFn: turn.streamFn,
+    getApiKey: (provider) => (provider === turn.llm.model.provider ? turn.llm.apiKey : undefined),
+    toolExecution: 'parallel',
+    sessionId: turn.input.sessionId,
+    ...(turn.input.shouldStopAfterSteering
+      ? { shouldStopAfterSteering: turn.input.shouldStopAfterSteering }
+      : {}),
+    ...(turn.input.shouldStopAfterTurn
+      ? { shouldStopAfterTurn: turn.input.shouldStopAfterTurn }
+      : {}),
+    ...(turn.llm.payloadTransform ? { onPayload: turn.llm.payloadTransform } : {}),
+    ...(turn.llm.responseObserver ? { onResponse: turn.llm.responseObserver } : {}),
+  });
+}
+
+export async function runAgent(
+  agent: Agent,
+  turn: turnState,
+  convergeAtIdle?: () => Promise<void>,
+): Promise<TurnTerminationReason | undefined> {
+  const startMode = turn.input.startMode ?? 'prompt';
+  try {
+    if (startMode === 'continue') {
+      await agent.continue();
+    } else {
+      await agent.prompt([
+        ...(turn.input.beforeUserMessages ?? []),
+        toPiUserMessage(turn.input.userMessage),
+      ]);
+    }
+    await agent.waitForIdle();
+    await convergeAtIdle?.();
+    await agent.waitForIdle();
+    if (turn.input.signal?.aborted) {
+      return { kind: 'aborted' };
+    }
+    if (agent.state.errorMessage) {
+      return failureReason(
+        agent.state.errorMessage,
+        turn.metrics.getLLMFailureObservation()?.normalized,
+      );
+    }
+    return undefined;
+  } catch (err) {
+    if (turn.input.signal?.aborted) {
+      return { kind: 'aborted' };
+    }
+    const runError = err instanceof Error ? err.message : String(err);
+    turn.logger.error(
+      {
+        session_id: turn.input.sessionId,
+        turn_id: turn.input.turnId,
+        start_mode: startMode,
+        error: runError,
+      },
+      '[pi-turn-runner] agent start threw',
+    );
+    return failureReason(runError);
+  }
+}

+ 71 - 0
packages/agent-core/src/pi-turn-runner/assembly-fingerprint.ts

@@ -0,0 +1,71 @@
+import { createHash } from 'node:crypto';
+
+const FINGERPRINT_LENGTH = 16;
+
+export interface AssemblyFingerprintContext {
+  readonly systemPrompt?: string;
+  readonly tools?: readonly {
+    readonly name: string;
+    readonly description: string;
+    readonly parameters: unknown;
+  }[];
+}
+
+export interface AssemblyFingerprint {
+  readonly systemPrompt: string;
+  readonly tools: string;
+}
+
+/**
+ * Fingerprint only the provider-visible, cache-relevant assembly surfaces.
+ * Message history is intentionally excluded so normal loop growth does not
+ * look like system/tool assembly churn.
+ */
+export function fingerprintAssembly(context: AssemblyFingerprintContext): AssemblyFingerprint {
+  const toolInterfaces = (context.tools ?? []).map((tool) => ({
+    name: tool.name,
+    description: tool.description,
+    parameters: tool.parameters,
+  }));
+  return {
+    // Preserve whitespace exactly: prompt caches observe it even when humans do not.
+    systemPrompt: fingerprint(context.systemPrompt ?? ''),
+    // Preserve tool order but canonicalize object keys inside each definition.
+    tools: fingerprint(canonicalStringify(toolInterfaces)),
+  };
+}
+
+function fingerprint(value: string): string {
+  return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, FINGERPRINT_LENGTH);
+}
+
+function canonicalStringify(value: unknown): string {
+  return JSON.stringify(canonicalize(value, new Set())) ?? 'null';
+}
+
+function canonicalize(value: unknown, ancestors: Set<object>): unknown {
+  if (Array.isArray(value)) {
+    if (ancestors.has(value)) throw new TypeError('Cannot fingerprint cyclic assembly data');
+    ancestors.add(value);
+    try {
+      return value.map((item) => canonicalize(item, ancestors));
+    } finally {
+      ancestors.delete(value);
+    }
+  }
+  if (!value || typeof value !== 'object') return value;
+  if (ancestors.has(value)) throw new TypeError('Cannot fingerprint cyclic assembly data');
+
+  ancestors.add(value);
+  try {
+    const result: Record<string, unknown> = {};
+    for (const key of Object.keys(value).sort()) {
+      const item = (value as Record<string, unknown>)[key];
+      if (item === undefined || typeof item === 'function' || typeof item === 'symbol') continue;
+      result[key] = canonicalize(item, ancestors);
+    }
+    return result;
+  } finally {
+    ancestors.delete(value);
+  }
+}

+ 31 - 0
packages/agent-core/src/pi-turn-runner/defaults.ts

@@ -0,0 +1,31 @@
+import type { PiTurnRunnerLogger } from './types.js';
+import type { PiMessageIdAllocator } from './pi-turn-runner.js';
+
+export const noopLogger: Required<PiTurnRunnerLogger> = {
+  debug: (..._args: unknown[]) => {},
+  error: (..._args: unknown[]) => {},
+  info: (..._args: unknown[]) => {},
+  warn: (..._args: unknown[]) => {},
+};
+
+export const defaultNowMs = () => Date.now();
+
+/**
+ * Default per-call LLM HTTP timeout (ms) injected into every provider
+ * stream invocation via `wrapStreamFnWithTimeout`. 20 minutes is long
+ * enough for thinking turns without letting a wedged provider hang the
+ * agent loop indefinitely.
+ *
+ * Per-call upstream wrappers that explicitly set `options.timeoutMs` win.
+ */
+export const LLM_REQUEST_TIMEOUT_MS = 20 * 60 * 1000;
+
+export const defaultMessageIdAllocator: PiMessageIdAllocator = {
+  async allocateAssistantMessageId() {
+    // crypto.randomUUID is available in Node >=18 and modern runtimes.
+    return (
+      globalThis.crypto?.randomUUID?.() ??
+      `msg-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
+    );
+  },
+};

+ 425 - 0
packages/agent-core/src/pi-turn-runner/events.ts

@@ -0,0 +1,425 @@
+import type { Agent, AgentEvent, AgentMessage } from '@earendil-works/pi-agent-core';
+import type { AssistantMessage } from '@earendil-works/pi-ai';
+import { buildRunningSessionStatusEvent } from '../event-bridge/index.js';
+import type { TurnTerminationReason } from '../event-bridge/types.js';
+import type { PiEventWriter, RuntimeEvent } from './types.js';
+import type { turnHistory } from './history.js';
+import type { turnState } from './turn.js';
+import { immediateSendBatchId } from './outbound-message-normalizer.js';
+
+export interface eventSub {
+  unsubscribe(): void;
+  drain(): Promise<void>;
+  convergeAtIdle(): Promise<void>;
+  forcedTermination(): TurnTerminationReason | undefined;
+}
+
+export async function emitRunning(turn: turnState): Promise<void> {
+  try {
+    await flushEvents(turn.writer, [
+      buildRunningSessionStatusEvent({
+        sessionId: turn.input.sessionId,
+        turnId: turn.input.turnId,
+        eventId: turn.nextEventId('coding_running_status'),
+      }),
+    ]);
+  } catch (err) {
+    turn.metrics.tryRecordTerminalFailure({ errorSource: 'event_writer', errorKind: 'delivery' });
+    turn.logger.error(
+      {
+        sessionId: turn.input.sessionId,
+        turnId: turn.input.turnId,
+        errorSource: 'event_writer',
+        error: err instanceof Error ? err.message : String(err),
+      },
+      '[pi-turn-runner] running event writer failed',
+    );
+    throw err;
+  }
+}
+
+export async function emitTerminal(turn: turnState, reason: TurnTerminationReason): Promise<void> {
+  let events: RuntimeEvent[];
+  try {
+    events = (await turn.bridge.emitTerminal(reason)).events;
+  } catch (err) {
+    turn.metrics.tryRecordTerminalFailure({
+      errorSource: 'event_bridge',
+      errorKind: 'translation',
+    });
+    turn.logger.error(
+      {
+        sessionId: turn.input.sessionId,
+        turnId: turn.input.turnId,
+        secondaryErrorSource: 'event_bridge',
+        error: err instanceof Error ? err.message : String(err),
+      },
+      '[pi-turn-runner] terminal event bridge failed',
+    );
+    throw err;
+  }
+  try {
+    await flushEvents(turn.writer, events);
+  } catch (err) {
+    turn.metrics.tryRecordTerminalFailure({ errorSource: 'event_writer', errorKind: 'delivery' });
+    turn.logger.error(
+      {
+        sessionId: turn.input.sessionId,
+        turnId: turn.input.turnId,
+        secondaryErrorSource: 'event_writer',
+        error: err instanceof Error ? err.message : String(err),
+      },
+      '[pi-turn-runner] terminal event writer failed',
+    );
+    throw err;
+  }
+}
+
+export function subscribeEvents(agent: Agent, turn: turnState, history: turnHistory): eventSub {
+  let pendingMessageID: Promise<string> | undefined;
+  let queue: Promise<void> = Promise.resolve();
+  let forcedTermination: TurnTerminationReason | undefined;
+  let continuationsClosed = false;
+  const existingShouldStopAfterTurn = agent.shouldStopAfterTurn;
+  agent.shouldStopAfterTurn = async (context) =>
+    forcedTermination !== undefined || (await existingShouldStopAfterTurn?.(context)) === true;
+
+  const applyAfterLlmControl = async (
+    event: Extract<AgentEvent, { type: 'message_end' }>,
+  ): Promise<'emit' | 'discard'> => {
+    if (event.message.role !== 'assistant' || turn.hooks.afterLLM.length === 0) return 'emit';
+    for (const hook of turn.hooks.afterLLM) {
+      let decision: Awaited<ReturnType<typeof hook>>;
+      try {
+        decision = await hook({
+          sessionId: turn.input.sessionId,
+          turnId: turn.input.turnId,
+          message: event.message,
+          messages: [...agent.state.messages],
+          signal: turn.input.signal ?? agent.signal,
+        });
+      } catch (error) {
+        const message = error instanceof Error ? error.message : String(error);
+        turn.logger.error(
+          {
+            session_id: turn.input.sessionId,
+            turn_id: turn.input.turnId,
+            error: message,
+          },
+          '[pi-turn-runner] afterLlmCall hook threw; failing response control closed',
+        );
+        event.message.content = event.message.content.filter((block) => block.type !== 'toolCall');
+        forcedTermination = { kind: 'failed', message: `after_llm_call_failed: ${message}` };
+        return isEmptyAssistantResponse(event.message) ? 'discard' : 'emit';
+      }
+      if (!decision || decision.type === 'continue') continue;
+      if (decision.type === 'replaceText') {
+        event.message.content = [
+          ...event.message.content.filter((block) => block.type !== 'text'),
+          { type: 'text', text: decision.text },
+        ];
+        continue;
+      }
+      if (decision.type === 'retry') {
+        // Pi selects tool calls from this same final message after listeners
+        // settle. Strip rejected tool intent synchronously so retry cannot
+        // leak side effects before the recovery request is processed.
+        event.message.content = event.message.content.filter((block) => block.type !== 'toolCall');
+        agent.followUp({
+          role: 'user',
+          content: [{ type: 'text', text: decision.prompt }],
+          timestamp: Date.now(),
+        });
+        return 'discard';
+      }
+      // A failed response is rejected as a whole. Never let its still-pending
+      // tool intent execute.
+      event.message.content = event.message.content.filter((block) => block.type !== 'toolCall');
+      forcedTermination = { kind: 'failed', message: decision.reason };
+      return isEmptyAssistantResponse(event.message) ? 'discard' : 'emit';
+    }
+    return 'emit';
+  };
+
+  const discardAssistantMessage = (event: Extract<AgentEvent, { type: 'message_end' }>): void => {
+    // Agent.state and Pi's private loop context are distinct arrays containing
+    // the same final message object. Remove the public transcript copy now and
+    // let transformContext remove the loop-context copy before the next call.
+    turn.rejectedAssistantMessages.add(event.message);
+    const messages = agent.state.messages;
+    const messageIndex = messages.lastIndexOf(event.message);
+    if (messageIndex >= 0) {
+      agent.state.messages = [
+        ...messages.slice(0, messageIndex),
+        ...messages.slice(messageIndex + 1),
+      ];
+    }
+    turn.bridge.discardActiveAssistantMessage();
+  };
+
+  const cannotContinueAtIdle = (): boolean =>
+    forcedTermination !== undefined ||
+    turn.input.signal?.aborted === true ||
+    agent.state.errorMessage !== undefined;
+
+  const failContinuationPoll = (error: unknown): void => {
+    const message = formatUnknownError(error);
+    forcedTermination = {
+      kind: 'failed',
+      message: `continuation_poll_failed: ${message}`,
+    };
+    turn.logger.error(
+      {
+        session_id: turn.input.sessionId,
+        turn_id: turn.input.turnId,
+        error: message,
+      },
+      '[pi-turn-runner] continuation poll threw; failing the turn closed',
+    );
+  };
+
+  const pollExternalContinuations = async (
+    event: Extract<AgentEvent, { type: 'turn_end' }>,
+  ): Promise<void> => {
+    if (
+      cannotContinueAtIdle() ||
+      event.message.role !== 'assistant' ||
+      event.message.stopReason === 'aborted' ||
+      event.message.stopReason === 'error'
+    ) {
+      return;
+    }
+    try {
+      const hasToolCalls = event.message.content.some((block) => block.type === 'toolCall');
+      let closeRefused = false;
+      for (;;) {
+        // The poll reports whether more steps already follow. At an exit
+        // boundary the host may withhold messages so the close below hands
+        // them back to the session instead of extending a finished answer.
+        const boundary = hasToolCalls || agent.hasQueuedMessages() ? 'mid-turn' : 'exit';
+        const steering = [...((await turn.input.getSteeringMessages?.({ boundary })) ?? [])];
+        enqueueSteering(agent, steering);
+        if (steering.length > 0 || hasToolCalls || agent.hasQueuedMessages()) return;
+        if (!turn.input.tryBeginClose) return;
+        if (
+          await turn.input.tryBeginClose({
+            ...lastAssistantMessageContext(event.message),
+          })
+        ) {
+          continuationsClosed = true;
+          return;
+        }
+        if (closeRefused) {
+          throw new Error('continuation close was refused without drainable work');
+        }
+        closeRefused = true;
+      }
+    } catch (error) {
+      failContinuationPoll(error);
+    }
+  };
+
+  const convergeAtIdle = async (): Promise<void> => {
+    if (!turn.input.tryBeginClose || continuationsClosed || cannotContinueAtIdle()) return;
+    try {
+      let closeRefused = false;
+      while (!continuationsClosed && !cannotContinueAtIdle()) {
+        const boundary = agent.hasQueuedMessages() ? 'mid-turn' : 'exit';
+        const steering = [...((await turn.input.getSteeringMessages?.({ boundary })) ?? [])];
+        if (steering.length > 0) {
+          enqueueSteering(agent, steering);
+          closeRefused = false;
+          await agent.continue();
+          continue;
+        }
+        if (
+          await turn.input.tryBeginClose({
+            ...lastAssistantMessageContext(
+              [...agent.state.messages]
+                .reverse()
+                .find((message): message is AssistantMessage => message.role === 'assistant'),
+            ),
+          })
+        ) {
+          continuationsClosed = true;
+          return;
+        }
+        if (closeRefused) {
+          throw new Error('continuation close was refused without drainable work');
+        }
+        closeRefused = true;
+      }
+    } catch (error) {
+      failContinuationPoll(error);
+    }
+  };
+
+  const writeAgentEvent = async (event: AgentEvent): Promise<void> => {
+    let out: Awaited<ReturnType<typeof turn.bridge.processEvent>>;
+    try {
+      out = await turn.bridge.processEvent(event);
+    } catch (err) {
+      turn.metrics.recordDegradation('event_bridge', 'translation', err);
+      throw err;
+    }
+    if (out.requestAssistantMessageId) {
+      // The bridge may ask for the assistant message id before it can emit
+      // assistant deltas. Hold later events on the same allocation promise so
+      // deltas never race ahead of their message anchor.
+      const allocPromise = turn.allocator
+        .allocateAssistantMessageId(turn.input.sessionId, turn.input.turnId)
+        .then((id) => {
+          turn.bridge.setActiveAssistantMessageId(id);
+          return id;
+        })
+        .catch((err) => {
+          turn.metrics.recordDegradation('message_identity', 'identity', err);
+          const message = err instanceof Error ? err.message : String(err);
+          turn.logger.error(
+            { session_id: turn.input.sessionId, turn_id: turn.input.turnId, error: message },
+            '[pi-turn-runner] assistant message id allocation failed',
+          );
+          turn.bridge.setActiveAssistantMessageId('');
+          throw err;
+        });
+      pendingMessageID = allocPromise;
+      await allocPromise;
+    } else if (pendingMessageID) {
+      await pendingMessageID;
+    }
+    if (out.events.length > 0) {
+      try {
+        await flushEvents(turn.writer, out.events);
+      } catch (err) {
+        turn.metrics.recordDegradation('event_writer', 'delivery', err);
+        throw err;
+      }
+    }
+  };
+
+  const onAgentEvent = async (event: AgentEvent): Promise<void> => {
+    let discardMessage = false;
+    try {
+      if (event.type === 'message_end') {
+        discardMessage = (await applyAfterLlmControl(event)) === 'discard';
+        if (discardMessage) discardAssistantMessage(event);
+      }
+      if (!discardMessage) await writeAgentEvent(event);
+    } catch (err) {
+      turn.logger.error(
+        {
+          session_id: turn.input.sessionId,
+          turn_id: turn.input.turnId,
+          event_type: event.type,
+          error: err instanceof Error ? err.message : String(err),
+        },
+        '[pi-turn-runner] event handler threw',
+      );
+    }
+
+    if ((!discardMessage && event.type === 'message_end') || event.type === 'tool_execution_end') {
+      await history.flushTail();
+    }
+    if (event.type === 'turn_end' && turn.hooks.onStepEnd.length > 0) {
+      const blockedToolCalls = turn.blockedToolCalls;
+      turn.blockedToolCalls = [];
+      // Step-end hooks may enqueue follow-up messages into the same Agent.
+      // Pi polls those follow-ups after this listener settles, so await the
+      // hooks here but keep hook failures isolated to this event branch.
+      // (Pi's `turn_end` fires per-step in our vocabulary — see design §11.)
+      const signal = turn.input.signal ?? new AbortController().signal;
+      for (const hook of turn.hooks.onStepEnd) {
+        try {
+          await hook({
+            agent,
+            message: event.message,
+            toolResults: event.toolResults,
+            signal,
+            blockedToolCalls,
+          });
+        } catch (hookErr) {
+          turn.metrics.recordDegradation('turn_end_hook', 'hook_error', hookErr);
+          turn.logger.error(
+            {
+              session_id: turn.input.sessionId,
+              turn_id: turn.input.turnId,
+              error: hookErr instanceof Error ? hookErr.message : String(hookErr),
+            },
+            '[pi-turn-runner] onStepEnd hook threw; ignoring so agent loop continues',
+          );
+        }
+      }
+    }
+    if (event.type === 'turn_end') await pollExternalContinuations(event);
+  };
+
+  const unsubscribe = agent.subscribe((event: AgentEvent) => {
+    // Serialize caller-side work even when Pi emits events from parallel
+    // tool completions. History delivery failures reject the current Pi
+    // listener; the resolved queue link still lets Pi's failure events drain.
+    const queued = queue.then(() => onAgentEvent(event));
+    queue = queued.catch(() => undefined);
+    return queued;
+  });
+
+  return {
+    unsubscribe,
+    drain: () => queue,
+    convergeAtIdle,
+    forcedTermination: () => forcedTermination,
+  };
+}
+
+function enqueueSteering(agent: Agent, messages: AgentMessage[]): void {
+  if (messages.some((message) => immediateSendBatchId(message) !== undefined)) {
+    agent.steerBatch(messages);
+  } else {
+    messages.forEach((message) => agent.steer(message));
+  }
+}
+
+function lastAssistantMessageContext(message: AssistantMessage | undefined): {
+  readonly lastAssistantMessage?: string;
+} {
+  if (!message) return {};
+  const text = message.content
+    .filter(
+      (block): block is Extract<(typeof message.content)[number], { type: 'text' }> =>
+        block.type === 'text',
+    )
+    .map((block) => block.text)
+    .join('')
+    .trim();
+  return text ? { lastAssistantMessage: text } : {};
+}
+
+function formatUnknownError(error: unknown): string {
+  if (error instanceof Error) return error.message;
+  try {
+    return String(error);
+  } catch {
+    return 'unknown continuation error';
+  }
+}
+
+function isEmptyAssistantResponse(message: AssistantMessage): boolean {
+  const hasVisibleText = message.content.some(
+    (block) => block.type === 'text' && block.text.trim().length > 0,
+  );
+  const hasToolCall = message.content.some((block) => block.type === 'toolCall');
+  return !hasVisibleText && !hasToolCall;
+}
+
+export async function flushEvents(
+  eventWriter: PiEventWriter,
+  events: ReadonlyArray<RuntimeEvent>,
+): Promise<void> {
+  if (events.length === 0) return;
+  if (typeof eventWriter.appendEvents === 'function') {
+    await eventWriter.appendEvents([...events]);
+    return;
+  }
+  for (const event of events) {
+    await eventWriter.pushRuntime(event);
+  }
+}

+ 251 - 0
packages/agent-core/src/pi-turn-runner/history.ts

@@ -0,0 +1,251 @@
+import type { Agent, AgentMessage } from '@earendil-works/pi-agent-core';
+import type { PiBeforeLlmCallReplaceMetadata, PiHistoryChangedHookInput } from './hooks.js';
+import type { turnState } from './turn.js';
+
+export interface turnHistory {
+  replace(
+    messages: AgentMessage[],
+    previousMessages: AgentMessage[],
+    metadata: PiBeforeLlmCallReplaceMetadata,
+  ): Promise<void>;
+  flushTail(): Promise<void>;
+}
+
+export function newHistory(turn: turnState, agent: Agent): turnHistory {
+  // Cursor into agent.state.messages. Initial history belongs to the caller
+  // and must not be re-sent through onHistoryChangedHook.
+  let lastSnapshotLength = turn.initialMessages.length;
+  let deliveryFailed = false;
+
+  const notify = async (change: PiHistoryChangedHookInput): Promise<void> => {
+    if (turn.hooks.onHistory.length === 0) return;
+    for (const hook of turn.hooks.onHistory) {
+      await hook(change);
+    }
+  };
+
+  const deliver = async (change: PiHistoryChangedHookInput): Promise<boolean> => {
+    if (deliveryFailed) return false;
+    try {
+      await notify(change);
+      return true;
+    } catch (err) {
+      deliveryFailed = true;
+      turn.metrics.tryRecordTerminalFailure({
+        errorSource: 'history',
+        errorKind: 'persistence',
+      });
+      try {
+        const errors = flattenHistoryErrors(err);
+        const loggedErrors = errors.slice(0, MAX_LOGGED_HISTORY_ERRORS);
+        const loggedMessages = selectHistoryMessages(change.messages);
+        const toolCalls = summarizeToolCalls(loggedMessages);
+        turn.logger.error(
+          {
+            session_id: turn.input.sessionId,
+            turn_id: turn.input.turnId,
+            reason: change.reason,
+            message_count: change.messages.length,
+            message_roles: loggedMessages.map(({ message }) => readMessageRole(message)),
+            tool_names: loggedMessages.flatMap(({ message }) => readToolName(message)),
+            history_cursor: lastSnapshotLength,
+            agent_message_count: agent.state.messages.length,
+            history_messages: loggedMessages.map(({ message, index }) =>
+              summarizeHistoryMessage(message, index),
+            ),
+            sampled_tool_call_count: toolCalls.count,
+            tool_calls: toolCalls.entries,
+            ...(toolCalls.count > toolCalls.entries.length
+              ? { truncated_tool_call_count: toolCalls.count - toolCalls.entries.length }
+              : {}),
+            tool_results: loggedMessages.flatMap(({ message }) => readToolResult(message)),
+            ...(change.messages.length > loggedMessages.length
+              ? { truncated_message_count: change.messages.length - loggedMessages.length }
+              : {}),
+            error_count: errors.length,
+            errors: loggedErrors.map(summarizeHistoryError),
+            ...(errors.length > loggedErrors.length
+              ? { truncated_error_count: errors.length - loggedErrors.length }
+              : {}),
+            error: truncateHistoryText(describeHistoryError(err), MAX_HISTORY_ERROR_MESSAGE_LENGTH),
+          },
+          '[pi-turn-runner] history delivery failed',
+        );
+      } catch {
+        // History persistence remains the root failure when diagnostics are unavailable.
+      }
+      throw err;
+    }
+  };
+
+  return {
+    async replace(messages, previousMessages, metadata): Promise<void> {
+      const delivered = await deliver({
+        sessionId: turn.input.sessionId,
+        turnId: turn.input.turnId,
+        reason: 'replaceMessages',
+        messages: [...messages],
+        previousMessages,
+        metadata,
+      });
+      if (delivered) lastSnapshotLength = messages.length;
+    },
+    async flushTail(): Promise<void> {
+      if (deliveryFailed) return;
+      const total = agent.state.messages.length;
+      if (total <= lastSnapshotLength) return;
+      const delta = agent.state.messages.slice(lastSnapshotLength, total);
+      const delivered = await deliver({
+        sessionId: turn.input.sessionId,
+        turnId: turn.input.turnId,
+        reason: 'messageDelta',
+        messages: [...delta],
+      });
+      if (delivered) lastSnapshotLength = total;
+    },
+  };
+}
+
+function readMessageRole(message: AgentMessage): string {
+  return typeof message.role === 'string' && message.role.length > 0
+    ? truncateHistoryText(message.role, MAX_HISTORY_ROLE_LENGTH)
+    : 'unknown';
+}
+
+function readToolName(message: AgentMessage): string[] {
+  return message.role === 'toolResult' && message.toolName.length > 0
+    ? [truncateHistoryText(message.toolName, MAX_HISTORY_IDENTIFIER_LENGTH)]
+    : [];
+}
+
+function summarizeHistoryMessage(
+  message: AgentMessage,
+  index: number,
+): Readonly<Record<string, unknown>> {
+  const content = Reflect.get(message, 'content');
+  return {
+    index,
+    role: readMessageRole(message),
+    content_types: readContentTypes(content),
+    ...(Array.isArray(content) ? { content_part_count: content.length } : {}),
+  };
+}
+
+const MAX_LOGGED_HISTORY_MESSAGES = 24;
+const LOGGED_HISTORY_HEAD_MESSAGES = 4;
+const MAX_LOGGED_HISTORY_TOOL_CALLS = 24;
+const MAX_SCANNED_HISTORY_CONTENT_PARTS = 64;
+const MAX_LOGGED_HISTORY_CONTENT_TYPES = 8;
+const MAX_HISTORY_ROLE_LENGTH = 64;
+const MAX_HISTORY_IDENTIFIER_LENGTH = 256;
+
+function selectHistoryMessages(
+  messages: readonly AgentMessage[],
+): readonly { readonly message: AgentMessage; readonly index: number }[] {
+  if (messages.length <= MAX_LOGGED_HISTORY_MESSAGES) {
+    return messages.map((message, index) => ({ message, index }));
+  }
+  const head = messages
+    .slice(0, LOGGED_HISTORY_HEAD_MESSAGES)
+    .map((message, index) => ({ message, index }));
+  const tailStart = messages.length - (MAX_LOGGED_HISTORY_MESSAGES - LOGGED_HISTORY_HEAD_MESSAGES);
+  const tail = messages.slice(tailStart).map((message, offset) => ({
+    message,
+    index: tailStart + offset,
+  }));
+  return [...head, ...tail];
+}
+
+function readContentTypes(content: unknown): readonly string[] {
+  if (typeof content === 'string') return ['text'];
+  if (!Array.isArray(content)) return [];
+  return [
+    ...new Set(
+      content.slice(0, MAX_SCANNED_HISTORY_CONTENT_PARTS).map((part) => {
+        if (typeof part === 'string') return 'text';
+        if (part && typeof part === 'object') {
+          const type = Reflect.get(part, 'type');
+          if (typeof type === 'string' && type.length > 0) {
+            return truncateHistoryText(type, MAX_HISTORY_ROLE_LENGTH);
+          }
+        }
+        return typeof part;
+      }),
+    ),
+  ].slice(0, MAX_LOGGED_HISTORY_CONTENT_TYPES);
+}
+
+function summarizeToolCalls(messages: readonly { readonly message: AgentMessage }[]): {
+  readonly count: number;
+  readonly entries: readonly Readonly<Record<string, unknown>>[];
+} {
+  const summary: {
+    count: number;
+    entries: Readonly<Record<string, unknown>>[];
+  } = { count: 0, entries: [] };
+  messages.forEach(({ message }) => {
+    if (message.role !== 'assistant' || !Array.isArray(message.content)) return;
+    message.content.forEach((part) => {
+      if (part.type !== 'toolCall') return;
+      summary.count += 1;
+      if (summary.entries.length >= MAX_LOGGED_HISTORY_TOOL_CALLS) return;
+      summary.entries.push({
+        tool_name: truncateHistoryText(part.name, MAX_HISTORY_IDENTIFIER_LENGTH),
+        tool_call_id: truncateHistoryText(part.id, MAX_HISTORY_IDENTIFIER_LENGTH),
+      });
+    });
+  });
+  return summary;
+}
+
+function readToolResult(message: AgentMessage): readonly Readonly<Record<string, unknown>>[] {
+  if (message.role !== 'toolResult') return [];
+  return [
+    {
+      tool_name: truncateHistoryText(message.toolName, MAX_HISTORY_IDENTIFIER_LENGTH),
+      tool_call_id: truncateHistoryText(message.toolCallId, MAX_HISTORY_IDENTIFIER_LENGTH),
+      is_error: message.isError === true,
+    },
+  ];
+}
+
+const MAX_LOGGED_HISTORY_ERRORS = 4;
+const MAX_HISTORY_ERROR_MESSAGE_LENGTH = 1_024;
+const MAX_HISTORY_ERROR_STACK_LENGTH = 4_096;
+
+function flattenHistoryErrors(error: unknown): readonly unknown[] {
+  if (!(error instanceof AggregateError)) return [error];
+  return error.errors.flatMap(flattenHistoryErrors);
+}
+
+function summarizeHistoryError(error: unknown): Readonly<Record<string, unknown>> {
+  if (error instanceof Error) {
+    return {
+      name: error.name || 'Error',
+      message: truncateHistoryText(
+        error.message || 'Unknown error',
+        MAX_HISTORY_ERROR_MESSAGE_LENGTH,
+      ),
+      ...(error.stack
+        ? { stack: truncateHistoryText(error.stack, MAX_HISTORY_ERROR_STACK_LENGTH) }
+        : {}),
+    };
+  }
+  return {
+    name: typeof error,
+    message: truncateHistoryText(describeHistoryError(error), MAX_HISTORY_ERROR_MESSAGE_LENGTH),
+  };
+}
+
+function truncateHistoryText(value: string, maximum: number): string {
+  return value.length <= maximum ? value : `${value.slice(0, maximum)}…`;
+}
+
+function describeHistoryError(error: unknown): string {
+  if (error instanceof Error) return error.message;
+  try {
+    return String(error);
+  } catch {
+    return 'unknown history delivery error';
+  }
+}

+ 268 - 0
packages/agent-core/src/pi-turn-runner/hooks.ts

@@ -0,0 +1,268 @@
+import type {
+  AfterToolCallContext,
+  AfterToolCallResult,
+  Agent,
+  AgentMessage,
+  BeforeToolCallContext,
+  BeforeToolCallResult,
+  CustomMessage,
+  ThinkingLevel,
+  StreamFn,
+} from '@earendil-works/pi-agent-core';
+import type {
+  Api,
+  AssistantMessage,
+  CacheRetention,
+  Model,
+  SimpleStreamOptions,
+  Tool,
+  ToolResultMessage,
+} from '@earendil-works/pi-ai';
+import type { PiEventWriter } from './types.js';
+
+export type PiBeforeLlmCallPhase = 'initial' | 'iteration';
+
+export interface PiBeforeLlmCallHookInput {
+  sessionId: string;
+  turnId: string;
+  phase: PiBeforeLlmCallPhase;
+  /** Current provider request view after request-only hook transforms. */
+  messages: AgentMessage[];
+  /** Current durable history, updated only by canonical replacements. */
+  canonicalMessages: AgentMessage[];
+  model: Model<Api>;
+  apiKey?: string;
+  headers?: Record<string, string>;
+  maxTokens?: number;
+  /** Host-owned serialized request cap used by final context admission. */
+  maxSerializedInputBytes?: number;
+  cacheRetention?: CacheRetention;
+  /** Host-composed auxiliary provider stream (for example auto compaction). */
+  streamFn?: StreamFn;
+  /**
+   * The onPayload transform chain applied before this turn's actual provider request (e.g.
+   * local-runtime's video patcher / openplatform thinking patcher). Hooks performing
+   * payload-sensitive operations such as token counting must apply it to their constructed body
+   * first; otherwise, the counted payload differs from the request actually sent.
+   */
+  payloadTransform?: SimpleStreamOptions['onPayload'];
+  /** Provider payload transform for hook-owned auxiliary LLM calls. */
+  auxiliaryPayloadTransform?: SimpleStreamOptions['onPayload'];
+  /** Composed system prompt for this turn. */
+  systemPrompt?: string;
+  /** Provider-bound tool declarations for this turn. */
+  tools?: Tool[];
+  thinkingLevel: ThinkingLevel;
+  signal?: AbortSignal;
+  eventWriter?: PiEventWriter;
+  eventIdGenerator?: (kind: string) => string;
+  runtimeSeqGenerator?: () => number;
+}
+
+export interface PiBeforeLlmCallReplaceMetadata {
+  replacementId: string;
+  strategyVersion: string;
+  summary: string;
+  compactedMessages: AgentMessage[];
+  keptMessages: AgentMessage[];
+  firstKeptIndex: number;
+  tokensBefore?: number;
+  tokensAfter?: number;
+  messagesBefore?: number;
+  messagesAfter?: number;
+  /**
+   * Explicit output-to-input lineage for technical replacements. Each output
+   * message points at the index whose canonical identity it preserves.
+   */
+  replacementSourceIndexes?: number[];
+  /** Reserved lineage for a placement-owned exact current-user tail. */
+  currentUserSourceIndex?: number;
+}
+
+export type PiBeforeLlmCallAppendMessage = Omit<CustomMessage, 'content' | 'display'> & {
+  content: string;
+  display: false;
+};
+
+export type PiAfterLlmReplacementCommit = () =>
+  | Promise<PiBeforeLlmCallAppendMessage | undefined>
+  | PiBeforeLlmCallAppendMessage
+  | undefined;
+
+export type PiBeforeLlmCallHookDecision =
+  | { type: 'continue' }
+  | { type: 'skip'; reason: string }
+  | { type: 'respond'; reason: string; text: string }
+  | {
+      /** Replaces only the current Provider request context, never canonical history. */
+      type: 'replaceRequestMessages';
+      messages: AgentMessage[];
+      reason: string;
+    }
+  | {
+      type: 'replaceMessages';
+      messages: AgentMessage[];
+      metadata: PiBeforeLlmCallReplaceMetadata;
+      /** Runs after durable history replacement and before the Provider request. */
+      afterCommit?: PiAfterLlmReplacementCommit;
+    }
+  | {
+      /**
+       * Durably appends one hidden typed context message before the Provider request.
+       * A successful append ends the before-LLM decision pipeline.
+       */
+      type: 'appendMessage';
+      message: PiBeforeLlmCallAppendMessage;
+      reason: string;
+      /** Initial-compaction-only placement for a Host marker before the current real user. */
+      placement?: 'before-current-user';
+    }
+  | { type: 'abort'; reason: string };
+
+export type PiBeforeLlmCallHook = (
+  input: PiBeforeLlmCallHookInput,
+) => Promise<PiBeforeLlmCallHookDecision | undefined> | PiBeforeLlmCallHookDecision | undefined;
+
+/**
+ * Final main-agent request view, observed after every before-LLM decision has
+ * settled and immediately before the logical provider call starts.
+ *
+ * Unlike `PiBeforeLlmCallHook`, this hook cannot transform or stop a request
+ * and deliberately omits transport credentials and provider functions.
+ */
+export interface PiLlmCallPreparedHookInput {
+  readonly sessionId: string;
+  readonly turnId: string;
+  readonly phase: PiBeforeLlmCallPhase;
+  readonly scope: 'agent';
+  readonly messages: readonly AgentMessage[];
+  readonly model: Model<Api>;
+  readonly maxTokens?: number;
+  readonly hostMaxOutputTokens?: number;
+  readonly maxSerializedInputBytes?: number;
+  readonly cacheRetention?: CacheRetention;
+  readonly systemPrompt: string;
+  readonly tools: readonly Tool[];
+  readonly thinkingLevel: ThinkingLevel;
+  readonly signal?: AbortSignal;
+}
+
+export type PiOnLlmCallPreparedHook = (input: PiLlmCallPreparedHookInput) => Promise<void> | void;
+
+export interface PiAfterLlmCallHookInput {
+  sessionId: string;
+  turnId: string;
+  /** Assistant response, before Pi selects and executes any tool calls it contains. */
+  message: AssistantMessage;
+  /** Current transcript projection, including `message`. */
+  messages: readonly AgentMessage[];
+  signal?: AbortSignal;
+}
+
+export type PiAfterLlmCallHookDecision =
+  | { type: 'continue' }
+  /**
+   * Replaces an assistant message's text before completed-message delivery.
+   *
+   * PiTurnRunner applies this at assistant message_end, before EventBridge
+   * emits the completed message and before onHistoryChangedHook receives the
+   * message delta. Both downstream paths therefore observe the replacement
+   * text, never the original assistant text.
+   *
+   * The runner removes every existing text block and appends one replacement
+   * text block. It preserves every non-text block in order, including pending
+   * toolCall blocks. Pi selects those preserved tool calls after listeners
+   * settle, so replaceText changes only the delivered text; it does not block
+   * tool execution.
+   *
+   * Use retry or fail to reject a response and prevent its pending tool calls
+   * from causing side effects. Use the tool hooks for per-tool control.
+   */
+  | { type: 'replaceText'; text: string }
+  | { type: 'retry'; reason: string; prompt: string }
+  | { type: 'fail'; reason: string };
+
+export type PiAfterLlmCallHook = (
+  input: PiAfterLlmCallHookInput,
+) => Promise<PiAfterLlmCallHookDecision | undefined> | PiAfterLlmCallHookDecision | undefined;
+
+/** blockedBy is trusted admission provenance, observed in this step only. */
+export type PiBeforeToolCallHook = (
+  toolContext: BeforeToolCallContext,
+  signal?: AbortSignal,
+) =>
+  | Promise<(BeforeToolCallResult & { readonly blockedBy?: 'permission' }) | undefined>
+  | (BeforeToolCallResult & { readonly blockedBy?: 'permission' })
+  | undefined;
+
+export type PiAfterToolCallHook = (
+  toolContext: AfterToolCallContext,
+  signal?: AbortSignal,
+) => Promise<AfterToolCallResult | undefined> | AfterToolCallResult | undefined;
+
+export type PiHistoryChangeReason = 'messageDelta' | 'replaceMessages';
+
+export interface PiHistoryChangedHookInput {
+  sessionId: string;
+  turnId: string;
+  reason: PiHistoryChangeReason;
+  /**
+   * For `messageDelta`, the new messages since the previous notification.
+   * For `replaceMessages`, the full replacement history currently in Pi state.
+   */
+  messages: AgentMessage[];
+  /** Previous full history, only populated for `replaceMessages`. */
+  previousMessages?: AgentMessage[];
+  /** Replacement metadata, only populated for `replaceMessages`. */
+  metadata?: PiBeforeLlmCallReplaceMetadata;
+}
+
+export type PiOnHistoryChangedHook = (input: PiHistoryChangedHookInput) => Promise<void> | void;
+
+/** Fires after permission/pre-tool admission, immediately before tool execution. */
+export type PiToolExecutionStartHook = (input: BeforeToolCallContext) => void;
+
+export interface PiStepEndHookInput {
+  agent: Agent;
+  message: AgentMessage;
+  toolResults: ToolResultMessage[];
+  signal: AbortSignal;
+  /** Trusted admission interceptions for this step only; never inferred from tool output. */
+  readonly blockedToolCalls?: readonly {
+    readonly toolCallId: string;
+    readonly blockedBy: 'permission';
+  }[];
+}
+
+/** @deprecated Use `PiStepEndHookInput`; this payload is emitted per pi step. */
+export type PiTurnEndHookInput = PiStepEndHookInput;
+
+/**
+ * Fires when a single pi turn ends (one LLM assistant response + its tool
+ * execution). Per the agent-runtime design doc §11 that unit is called a
+ * "step" — a full `agent.run()` invocation (which the daemon exposes as a
+ * "turn") wraps N of these. Preferred name for the step-boundary hook per
+ * §11.6 Step A.
+ */
+export type PiOnStepEndHook = (input: PiStepEndHookInput) => Promise<void> | void;
+
+/** @deprecated Use `PiOnStepEndHook`; this hook fires once per pi step. */
+export type PiOnTurnEndHook = PiOnStepEndHook;
+
+export interface PiTurnHooks {
+  beforeLlmCallHook?: readonly PiBeforeLlmCallHook[];
+  /** Best-effort observers of actual logical main-agent provider calls. */
+  onLlmCallPreparedHook?: readonly PiOnLlmCallPreparedHook[];
+  afterLlmCallHook?: readonly PiAfterLlmCallHook[];
+  beforeToolCallHook?: readonly PiBeforeToolCallHook[];
+  onToolExecutionStartHook?: readonly PiToolExecutionStartHook[];
+  afterToolCallHook?: readonly PiAfterToolCallHook[];
+  onHistoryChangedHook?: readonly PiOnHistoryChangedHook[];
+  /**
+   * Step-boundary hook (fires per LLM step). Filled by agent-runtime and read
+   * by `PiTurnRunner`. See `PiOnStepEndHook` docstring for the vocabulary.
+   */
+  onStepEndHook?: readonly PiOnStepEndHook[];
+  /** @deprecated Use `onStepEndHook`; retained for legacy per-step consumers. */
+  onTurnEndHook?: readonly PiOnTurnEndHook[];
+}

+ 112 - 0
packages/agent-core/src/pi-turn-runner/image-dimensions.ts

@@ -0,0 +1,112 @@
+/**
+ * Pure, dependency-free image header reader for PNG and JPEG.
+ *
+ * Only the outbound request projection needs this, and only to answer one
+ * question: "is this image so small that the provider will reject the whole
+ * request?". Every unknown input — unrecognised format, truncated payload,
+ * invalid base64 — resolves to `undefined`, meaning "cannot determine", and the
+ * caller fails open by keeping the block untouched. Nothing in this module
+ * throws: a parser that rejects real-world bytes would be strictly worse than
+ * one that shrugs, because the fallback is the current (working) behaviour.
+ *
+ * Deliberately no third-party dependency and deliberately no GIF/BMP/WebP: the
+ * only producer that can emit a degenerate image here is our own Browser
+ * screenshot path, which encodes JPEG or PNG. Unparseable formats are counted
+ * and logged by the caller, which is the signal to widen this list if real
+ * traffic ever needs it.
+ */
+
+export interface ImageDimensions {
+  readonly width: number;
+  readonly height: number;
+}
+
+/**
+ * Only the leading bytes are ever needed. A JPEG's SOF marker sits after any
+ * EXIF/ICC segments, but never megabytes in, so decoding a bounded prefix keeps
+ * this cheap for the multi-megabyte screenshots that dominate real history.
+ */
+const MAX_HEADER_BYTES = 64 * 1024;
+
+const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] as const;
+
+/**
+ * `mimeType` is an advisory hint only, never a gate. Blocks projected from
+ * `video` content keep their source `video/*` type while carrying image bytes,
+ * so dispatch is driven by the magic bytes and the declared type merely picks
+ * which parser is tried first.
+ */
+export function imageDimensions(data: unknown, mimeType?: unknown): ImageDimensions | undefined {
+  const bytes = decodeHeaderBytes(data);
+  if (!bytes) return undefined;
+  const declaredPng = typeof mimeType === 'string' && mimeType.toLowerCase().includes('png');
+  return declaredPng
+    ? (readPngDimensions(bytes) ?? readJpegDimensions(bytes))
+    : (readJpegDimensions(bytes) ?? readPngDimensions(bytes));
+}
+
+function decodeHeaderBytes(data: unknown): Buffer | undefined {
+  if (typeof data !== 'string' || data.length === 0) return undefined;
+  // Trim to a whole base64 group so the bounded prefix decodes cleanly.
+  const maxChars = Math.ceil((MAX_HEADER_BYTES * 4) / 3);
+  const prefix = data.length > maxChars ? data.slice(0, maxChars - (maxChars % 4)) : data;
+  const bytes = Buffer.from(prefix, 'base64');
+  return bytes.length > 0 ? bytes : undefined;
+}
+
+function readPngDimensions(bytes: Buffer): ImageDimensions | undefined {
+  // Signature, then a fixed-offset IHDR chunk whose first two fields are the
+  // dimensions. Any deviation means this is not a PNG we can read.
+  if (bytes.length < 24) return undefined;
+  for (const [index, expected] of PNG_SIGNATURE.entries()) {
+    if (bytes[index] !== expected) return undefined;
+  }
+  if (bytes.toString('latin1', 12, 16) !== 'IHDR') return undefined;
+  return validDimensions(bytes.readUInt32BE(16), bytes.readUInt32BE(20));
+}
+
+function readJpegDimensions(bytes: Buffer): ImageDimensions | undefined {
+  if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return undefined;
+  let offset = 2;
+  // Walk the segment chain: the frame header can sit behind EXIF, ICC or
+  // comment segments, so a fixed offset is not safe.
+  while (offset + 3 < bytes.length) {
+    const marker = bytes[offset + 1];
+    if (bytes[offset] !== 0xff || marker === undefined) return undefined;
+    if (marker === 0xff) {
+      // Fill byte before the next marker.
+      offset += 1;
+      continue;
+    }
+    if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {
+      // Standalone marker, no payload length follows.
+      offset += 2;
+      continue;
+    }
+    // EOI or the start of entropy-coded data: no frame header will appear.
+    if (marker === 0xd9 || marker === 0xda) return undefined;
+    const segmentLength = bytes.readUInt16BE(offset + 2);
+    if (segmentLength < 2) return undefined;
+    if (isStartOfFrame(marker)) {
+      // A frame header is length(2) + precision(1) + height(2) + width(2) +
+      // component count(1). A shorter declared length means the dimension bytes
+      // would be read from outside the segment, fabricating a size.
+      if (segmentLength < 8) return undefined;
+      if (offset + 9 >= bytes.length) return undefined;
+      return validDimensions(bytes.readUInt16BE(offset + 7), bytes.readUInt16BE(offset + 5));
+    }
+    offset += 2 + segmentLength;
+  }
+  return undefined;
+}
+
+function isStartOfFrame(marker: number): boolean {
+  // SOF0..SOF15, excluding DHT (0xc4), JPG (0xc8) and DAC (0xcc).
+  return marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
+}
+
+function validDimensions(width: number, height: number): ImageDimensions | undefined {
+  return Number.isSafeInteger(width) && Number.isSafeInteger(height) && width > 0 && height > 0
+    ? { width, height }
+    : undefined;
+}

+ 112 - 0
packages/agent-core/src/pi-turn-runner/index.ts

@@ -0,0 +1,112 @@
+/**
+ * `@mavis/agent-core/pi-turn-runner` — assemble pi-coding-agent for a
+ * Mavis session and bridge its event stream into canonical
+ * `RuntimeEvent`s.
+ *
+ * This module is the "injection + assembly" layer. It does not implement
+ * `runAgentLoop()` itself (that ships in `@earendil-works/pi-agent-core`);
+ * it wires the pi runtime to explicit per-turn model / event writer /
+ * tool contracts supplied by runtime adapters.
+ *
+ * Runtime adapters such as local-runtime and cloud-runtime construct a
+ * {@link PiTurnRunner} with process-level wiring and call
+ * {@link PiTurnRunner.runTurn} for each LLM turn, supplying the resolved
+ * model, event writer and runtime tools as part of {@link RunTurnInput}.
+ *
+ * @see packages/agent-core/ARCHITECTURE.md
+ */
+
+export {
+  LLM_REQUEST_TIMEOUT_MS,
+  PiTurnRunner,
+  _computeFailureTerminationReasonForTest,
+  wrapStreamFnWithTimeout,
+  type PiMessageIdAllocator,
+  type PiTurnRunnerOptions,
+} from './pi-turn-runner.js';
+export { composeStreamFn } from './llm.js';
+export { normalizeAbortSource } from './types.js';
+export {
+  DEFAULT_LLM_RETRY_POLICY,
+  LLM_RETRY_CALL_IDENTITY,
+  LLM_RETRY_REQUEST_SETTLED_OBSERVER,
+  withLLMRetry,
+  type LLMCallErrorKind,
+  type LLMCallOutcome,
+  type LLMCallScope,
+  type LLMCallSettledEvent,
+  type LLMCallUsage,
+  type LLMExpectedToolIdentity,
+  type LLMRequestSettledEvent,
+  type LLMRequestSettledObserver,
+  type LLMRetryError,
+  type LLMRetryEvent,
+  type LLMRetryOptions,
+  type LLMRetryPolicy,
+  type LLMRetryStatus,
+} from './llm-retry.js';
+export type { LlmCaptureAgentEventSource, LlmCaptureRecorder } from './turn.js';
+export { createPiTurnHistogramBucketsByName, recordPiLLMCallMetrics } from './metrics.js';
+export type {
+  PiLLMCacheOutcome,
+  PiLLMRequestObserver,
+  PiLLMRequestFailureHook,
+  PiLLMRequestFailureInfo,
+  PiLLMRequestSettledInfo,
+  PiLLMRequestSettlementObserver,
+  PiLLMRequestStartedInfo,
+} from './metrics.js';
+export {
+  projectAgentMessagesForModel,
+  removeOrphanToolResults,
+} from './outbound-message-normalizer.js';
+export { toPiUserMessage } from './agent.js';
+export {
+  createToolContextHistogramBucketsByName,
+  measureToolArguments,
+  measureToolContext,
+  measureToolResult,
+  type MeasuredToolValue,
+  type ToolContextBreakdown,
+  type ToolContextContribution,
+  type ToolContextSizeEstimator,
+} from './tool-context-size.js';
+export type {
+  AbortSource,
+  LLMModelConfig,
+  PiAgentMessage,
+  PiEventWriter,
+  PiTurnRunnerLogger,
+  RunTurnCaller,
+  RunTurnInput,
+  RunTurnStartMode,
+  RuntimeEvent,
+  SteeringPollContext,
+  TurnEventReporter,
+  ToolConfig,
+  UserMessageInput,
+} from './types.js';
+export type {
+  PiAfterLlmCallHook,
+  PiAfterLlmCallHookDecision,
+  PiAfterLlmCallHookInput,
+  PiAfterToolCallHook,
+  PiBeforeLlmCallHook,
+  PiBeforeLlmCallAppendMessage,
+  PiBeforeLlmCallHookDecision,
+  PiBeforeLlmCallHookInput,
+  PiBeforeLlmCallPhase,
+  PiBeforeLlmCallReplaceMetadata,
+  PiBeforeToolCallHook,
+  PiHistoryChangedHookInput,
+  PiHistoryChangeReason,
+  PiLlmCallPreparedHookInput,
+  PiOnLlmCallPreparedHook,
+  PiOnHistoryChangedHook,
+  PiOnStepEndHook,
+  PiOnTurnEndHook,
+  PiStepEndHookInput,
+  PiToolExecutionStartHook,
+  PiTurnHooks,
+  PiTurnEndHookInput,
+} from './hooks.js';

+ 963 - 0
packages/agent-core/src/pi-turn-runner/llm-retry.ts

@@ -0,0 +1,963 @@
+import type { StreamFn } from '@earendil-works/pi-agent-core';
+import type {
+  AssistantMessage,
+  AssistantMessageEvent,
+  AssistantMessageEventStream,
+  ProviderResponse,
+  SimpleStreamOptions,
+} from '@earendil-works/pi-ai';
+import {
+  normalizeLLMError,
+  toLLMMetricErrorKind,
+  toLLMProtocolClassification,
+  toLLMRetryDecision,
+  type LLMMetricErrorKind,
+  type LLMRetryReason,
+  type NormalizedLLMError,
+} from '@mavis/shared/llm-error-classifier';
+
+function isByokProvider(provider: string): boolean {
+  return provider === 'minimax_api' || provider.startsWith('custom_provider:');
+}
+
+export type LLMCallScope = 'agent' | 'compaction' | 'title';
+export type LLMRetryStatus = 'waiting' | 'recovered' | 'exhausted' | 'cancelled';
+export type LLMCallOutcome = 'success' | 'error' | 'abort';
+export type LLMCallErrorKind = LLMMetricErrorKind | 'none';
+
+/** Symbol-keyed identity shared by physical attempts of one logical call. */
+export const LLM_RETRY_CALL_IDENTITY: unique symbol = Symbol('mavis.llmRetryCallIdentity');
+
+/** Symbol-keyed observer for every physical provider request in a logical call. */
+export const LLM_RETRY_REQUEST_SETTLED_OBSERVER: unique symbol = Symbol(
+  'mavis.llmRetryRequestSettledObserver',
+);
+
+export interface LLMRetryPolicy {
+  maxRetries: number;
+  baseDelayMs: number;
+  maxDelayMs: number;
+  maxRetryElapsedMs: number;
+}
+
+export const DEFAULT_LLM_RETRY_POLICY: Readonly<LLMRetryPolicy> = {
+  maxRetries: 5,
+  baseDelayMs: 1_000,
+  maxDelayMs: 30_000,
+  maxRetryElapsedMs: 120_000,
+};
+
+export interface LLMRetryError {
+  reason: LLMMetricErrorKind;
+  code?: number;
+  message: string;
+}
+
+export interface LLMRetryEvent {
+  sessionId: string;
+  turnId: string;
+  callId: string;
+  scope: LLMCallScope;
+  status: LLMRetryStatus;
+  /** Number of retries already used or about to start; the initial request is zero. */
+  retryAttempt: number;
+  maxRetries: number;
+  /** One-based physical provider request ordinal. */
+  requestAttempt: number;
+  delayMs?: number;
+  nextRetryAtMs?: number;
+  error?: LLMRetryError;
+}
+
+/** Raw provider token buckets from the final attempt of a successful call. */
+export interface LLMCallUsage {
+  input: number;
+  output: number;
+  cacheRead: number;
+  cacheWrite: number;
+}
+
+export interface LLMRequestSettledEvent {
+  /** One-based physical provider request ordinal within the logical call. */
+  requestAttempt: number;
+  outcome: LLMCallOutcome;
+  /** Known provider buckets, with invalid or missing buckets normalised to zero. */
+  usage?: LLMCallUsage;
+  /** False when the provider did not report all four valid buckets. */
+  usageComplete: boolean;
+}
+
+export type LLMRequestSettledObserver = (event: LLMRequestSettledEvent) => void;
+
+export interface LLMExpectedToolIdentity {
+  readonly toolCallId: string;
+  readonly toolName: string;
+}
+
+export interface LLMCallSettledEvent {
+  sessionId: string;
+  turnId: string;
+  callId: string;
+  scope: LLMCallScope;
+  provider: string;
+  model: string;
+  final: {
+    outcome: LLMCallOutcome;
+    errorKind: LLMCallErrorKind;
+  };
+  /** True once the framework schedules the first retry, even if the user cancels its backoff. */
+  retryTriggered: boolean;
+  retryReason?: LLMRetryReason;
+  /** Physical provider requests actually started for this logical call. */
+  requestAttempts: number;
+  /** Normalized tool identities from a successful final response; arguments are never exposed. */
+  expectedTools?: readonly LLMExpectedToolIdentity[];
+  /**
+   * Raw provider token buckets for a successful call. Absent when the call did
+   * not settle with a provider response, so consumers never report synthesised
+   * usage for a failed or cancelled call.
+   */
+  usage?: LLMCallUsage;
+}
+
+export interface LLMRetryOptions {
+  sessionId: string;
+  turnId: string;
+  scope: LLMCallScope;
+  policy?: Partial<LLMRetryPolicy>;
+  observer?: (event: LLMRetryEvent) => void | Promise<void>;
+  /** Final logical outcome observer. It is isolated from provider-call behavior. */
+  onCallSettled?: (event: LLMCallSettledEvent) => void | Promise<void>;
+  generateCallId?: () => string;
+  nowMs?: () => number;
+  random?: () => number;
+  sleep?: (delayMs: number, signal?: AbortSignal) => Promise<void>;
+}
+
+interface RetryFailure {
+  normalized: NormalizedLLMError;
+  error: LLMRetryError;
+  stream?: AssistantMessageEventStream;
+  iterator?: AsyncIterator<AssistantMessageEvent>;
+  buffered: AssistantMessageEvent[];
+  thrown?: unknown;
+  retryAfterMs?: number;
+}
+
+interface RetryableFailure extends RetryFailure {
+  retryReason: LLMRetryReason;
+}
+
+interface RetryCallState {
+  retryTriggered: boolean;
+  retryReason?: LLMRetryReason;
+  requestAttempts: number;
+}
+
+interface CallSettlementContext {
+  input: LLMRetryOptions;
+  model: Parameters<StreamFn>[0];
+  callId: string;
+  state: RetryCallState;
+  signal: AbortSignal | undefined;
+}
+
+type PreflightResult =
+  | { kind: 'committed'; stream: AssistantMessageEventStream }
+  | { kind: 'terminal'; failure: RetryFailure }
+  | { kind: 'failure'; failure: RetryableFailure };
+
+const PUBLIC_ERROR_MESSAGES: Record<LLMMetricErrorKind, string> = {
+  abort: 'LLM request was cancelled',
+  timeout: 'LLM request timed out',
+  rate_limited: 'LLM provider rate limited the request',
+  tpm_rate_limited: 'LLM provider token rate limit reached',
+  usage_limit: 'LLM usage limit reached',
+  credits_exhausted: 'LLM credits exhausted',
+  auth: 'LLM provider authentication failed',
+  bad_request: 'LLM provider rejected the request',
+  not_found: 'LLM provider resource not found',
+  content_filter: 'LLM provider blocked the response',
+  server_error: 'LLM provider request failed',
+  overloaded: 'LLM provider is overloaded',
+  network: 'LLM network connection failed',
+  empty_response: 'LLM provider returned an empty response',
+  unknown: 'LLM request failed',
+  length: 'LLM response reached the length limit',
+};
+
+/** Add framework-owned transport retry to a provider StreamFn. Hosts opt in explicitly. */
+export function withLLMRetry(inner: StreamFn, input: LLMRetryOptions): StreamFn {
+  const policy = resolvePolicy(input.policy);
+  const nowMs = input.nowMs ?? Date.now;
+  const random = input.random ?? Math.random;
+  const sleep = input.sleep ?? abortableSleep;
+
+  return (async (model, context, options) => {
+    const callId = input.generateCallId?.() ?? defaultCallId();
+    const callIdentity = {};
+    const callState: RetryCallState = { retryTriggered: false, requestAttempts: 0 };
+    let retryStartedAtMs: number | undefined;
+    let requestAttempt = 1;
+    let lastFailure: RetryableFailure | undefined;
+
+    while (requestAttempt <= policy.maxRetries + 1) {
+      if (options?.signal?.aborted) {
+        const error = abortError(options.signal);
+        notifyCallSettled(
+          { input, model, callId, state: callState, signal: options.signal },
+          error,
+        );
+        throw error;
+      }
+      const preflight = await preflightAttempt(
+        inner,
+        model,
+        context,
+        options,
+        nowMs,
+        callIdentity,
+        isByokProvider(model.provider),
+        requestAttempt,
+        requestSettledObserver(options),
+      );
+      callState.requestAttempts = requestAttempt;
+      if (preflight.kind === 'committed') {
+        if (requestAttempt > 1) {
+          await notify(input.observer, {
+            sessionId: input.sessionId,
+            turnId: input.turnId,
+            callId,
+            scope: input.scope,
+            status: 'recovered',
+            retryAttempt: requestAttempt - 1,
+            maxRetries: policy.maxRetries,
+            requestAttempt,
+          });
+        }
+        return observeCallSettlement(preflight.stream, {
+          input,
+          model,
+          callId,
+          state: callState,
+          signal: options?.signal,
+        });
+      }
+      if (preflight.kind === 'terminal') {
+        if (requestAttempt > 1 && lastFailure) {
+          const cancelled = options?.signal?.aborted || isAbortFailure(preflight.failure);
+          await notify(input.observer, {
+            sessionId: input.sessionId,
+            turnId: input.turnId,
+            callId,
+            scope: input.scope,
+            status: cancelled ? 'cancelled' : 'exhausted',
+            retryAttempt: requestAttempt - 1,
+            maxRetries: policy.maxRetries,
+            requestAttempt,
+            // The terminal attempt may differ from the transient failure that
+            // caused the retry (for example 529 followed by quota exhaustion).
+            // Expose the actual final error so downstream code/message handling
+            // never reports the stale previous attempt.
+            error: preflight.failure.error,
+          });
+        }
+        return observeTerminalFailure(preflight.failure, {
+          input,
+          model,
+          callId,
+          state: callState,
+          signal: options?.signal,
+        });
+      }
+
+      lastFailure = preflight.failure;
+      const retryAttempt = requestAttempt;
+      const delayMs = retryDelayMs(lastFailure.retryAfterMs, retryAttempt, policy, random);
+      const failureAtMs = nowMs();
+      retryStartedAtMs ??= failureAtMs;
+      const retryDeadlineExceeded =
+        failureAtMs + delayMs - retryStartedAtMs > policy.maxRetryElapsedMs;
+      if (requestAttempt > policy.maxRetries || retryDeadlineExceeded) {
+        await notify(input.observer, {
+          sessionId: input.sessionId,
+          turnId: input.turnId,
+          callId,
+          scope: input.scope,
+          status: 'exhausted',
+          retryAttempt: requestAttempt - 1,
+          maxRetries: policy.maxRetries,
+          requestAttempt,
+          error: lastFailure.error,
+        });
+        return observeTerminalFailure(lastFailure, {
+          input,
+          model,
+          callId,
+          state: callState,
+          signal: options?.signal,
+        });
+      }
+
+      callState.retryTriggered = true;
+      callState.retryReason ??= lastFailure.retryReason;
+      discardAttempt(lastFailure);
+      await notify(input.observer, {
+        sessionId: input.sessionId,
+        turnId: input.turnId,
+        callId,
+        scope: input.scope,
+        status: 'waiting',
+        retryAttempt,
+        maxRetries: policy.maxRetries,
+        requestAttempt: requestAttempt + 1,
+        delayMs,
+        nextRetryAtMs: failureAtMs + delayMs,
+        error: lastFailure.error,
+      });
+      try {
+        await sleep(delayMs, options?.signal);
+      } catch (error) {
+        await notify(input.observer, {
+          sessionId: input.sessionId,
+          turnId: input.turnId,
+          callId,
+          scope: input.scope,
+          status: 'cancelled',
+          retryAttempt,
+          maxRetries: policy.maxRetries,
+          requestAttempt: requestAttempt + 1,
+          error: lastFailure.error,
+        });
+        notifyCallSettled(
+          { input, model, callId, state: callState, signal: options?.signal },
+          error,
+        );
+        throw error;
+      }
+      requestAttempt += 1;
+    }
+
+    if (lastFailure) {
+      return observeTerminalFailure(lastFailure, {
+        input,
+        model,
+        callId,
+        state: callState,
+        signal: options?.signal,
+      });
+    }
+    const error = new Error('LLM retry loop ended without a provider result');
+    notifyCallSettled({ input, model, callId, state: callState, signal: options?.signal }, error);
+    throw error;
+  }) as StreamFn;
+}
+
+async function preflightAttempt(
+  inner: StreamFn,
+  model: Parameters<StreamFn>[0],
+  context: Parameters<StreamFn>[1],
+  options: Parameters<StreamFn>[2],
+  nowMs: () => number,
+  callIdentity: object,
+  retryAllErrors: boolean,
+  requestAttempt: number,
+  onRequestSettled: LLMRequestSettledObserver | undefined,
+): Promise<PreflightResult> {
+  let response: ProviderResponse | undefined;
+  const callerOnResponse = options?.onResponse;
+  const attemptOptions: SimpleStreamOptions = {
+    ...(options ?? {}),
+    maxRetries: 0,
+    onResponse: async (value, responseModel) => {
+      response = value;
+      await callerOnResponse?.(value, responseModel);
+    },
+  };
+  Object.defineProperty(attemptOptions, LLM_RETRY_CALL_IDENTITY, {
+    value: callIdentity,
+    // StreamFn composition uses object spread. Enumerable symbol keys survive
+    // those wrappers while remaining invisible to JSON/provider payloads.
+    enumerable: true,
+  });
+  let stream: AssistantMessageEventStream;
+  try {
+    stream = await inner(model, context, attemptOptions);
+  } catch (thrown) {
+    notifyRequestSettled(onRequestSettled, requestAttempt, undefined, thrown, options?.signal);
+    return failureResult({ thrown, response, buffered: [], nowMs, retryAllErrors });
+  }
+
+  let iterator: AsyncIterator<AssistantMessageEvent>;
+  try {
+    iterator = stream[Symbol.asyncIterator]();
+  } catch (thrown) {
+    notifyRequestSettled(onRequestSettled, requestAttempt, undefined, thrown, options?.signal);
+    return failureResult({ thrown, response, stream, buffered: [], nowMs, retryAllErrors });
+  }
+
+  const buffered: AssistantMessageEvent[] = [];
+  for (;;) {
+    let next: IteratorResult<AssistantMessageEvent>;
+    try {
+      next = await iterator.next();
+    } catch (thrown) {
+      notifyRequestSettled(onRequestSettled, requestAttempt, undefined, thrown, options?.signal);
+      return failureResult({ thrown, response, stream, iterator, buffered, nowMs, retryAllErrors });
+    }
+    if (next.done) {
+      try {
+        const final = await stream.result();
+        if (isFailureMessage(final)) {
+          notifyRequestSettled(onRequestSettled, requestAttempt, final, undefined, options?.signal);
+          return failureResult({
+            final,
+            response,
+            stream,
+            iterator,
+            buffered,
+            nowMs,
+            retryAllErrors,
+          });
+        }
+        notifyRequestSettled(onRequestSettled, requestAttempt, final, undefined, options?.signal);
+        return { kind: 'committed', stream: replayStream(stream, iterator, buffered) };
+      } catch (thrown) {
+        notifyRequestSettled(onRequestSettled, requestAttempt, undefined, thrown, options?.signal);
+        return failureResult({
+          thrown,
+          response,
+          stream,
+          iterator,
+          buffered,
+          nowMs,
+          retryAllErrors,
+        });
+      }
+    }
+
+    buffered.push(next.value);
+    if (next.value.type === 'error') {
+      notifyRequestSettled(
+        onRequestSettled,
+        requestAttempt,
+        next.value.error,
+        undefined,
+        options?.signal,
+      );
+      return failureResult({
+        final: next.value.error,
+        response,
+        stream,
+        iterator,
+        buffered,
+        nowMs,
+        retryAllErrors,
+      });
+    }
+    // A visible delta is the retry commit boundary for every provider. Once
+    // callers can observe output, silently replacing the physical request
+    // would either buffer the whole response or replay duplicate content.
+    // BYOK keeps its broader pre-output retry classification, but a later
+    // stream failure must stay on the already-committed attempt.
+    if (commitsOutput(next.value) || (!retryAllErrors && next.value.type === 'done')) {
+      return {
+        kind: 'committed',
+        stream: observeRequestSettlement(
+          replayStream(stream, iterator, buffered),
+          requestAttempt,
+          onRequestSettled,
+          options?.signal,
+        ),
+      };
+    }
+  }
+}
+
+function requestSettledObserver(
+  options: Parameters<StreamFn>[2],
+): LLMRequestSettledObserver | undefined {
+  return (
+    options as
+      | (Parameters<StreamFn>[2] & {
+          [LLM_RETRY_REQUEST_SETTLED_OBSERVER]?: LLMRequestSettledObserver;
+        })
+      | undefined
+  )?.[LLM_RETRY_REQUEST_SETTLED_OBSERVER];
+}
+
+function notifyRequestSettled(
+  observer: LLMRequestSettledObserver | undefined,
+  requestAttempt: number,
+  final: AssistantMessage | undefined,
+  thrown: unknown,
+  signal: AbortSignal | undefined,
+): void {
+  if (!observer) return;
+  const providerUsage = readProviderUsage(final);
+  try {
+    observer({
+      requestAttempt,
+      outcome: classifyCallOutcome(final, thrown, signal?.aborted === true).outcome,
+      ...(providerUsage.usage ? { usage: providerUsage.usage } : {}),
+      usageComplete: providerUsage.complete,
+    });
+  } catch {
+    // Physical-call observability must never change provider-call behavior.
+  }
+}
+
+function observeRequestSettlement(
+  source: AssistantMessageEventStream,
+  requestAttempt: number,
+  observer: LLMRequestSettledObserver | undefined,
+  signal: AbortSignal | undefined,
+): AssistantMessageEventStream {
+  if (!observer) return source;
+  let settled = false;
+  const settle = (final: AssistantMessage | undefined, error?: unknown): void => {
+    if (settled) return;
+    settled = true;
+    notifyRequestSettled(observer, requestAttempt, final, error, signal);
+  };
+  const result = Promise.resolve()
+    .then(() => source.result())
+    .then(
+      (final) => {
+        settle(final);
+        return final;
+      },
+      (error) => {
+        settle(undefined, error);
+        throw error;
+      },
+    );
+  void result.catch(() => undefined);
+
+  return {
+    [Symbol.asyncIterator]() {
+      let inner: AsyncIterator<AssistantMessageEvent>;
+      try {
+        inner = source[Symbol.asyncIterator]();
+      } catch (error) {
+        settle(undefined, error);
+        throw error;
+      }
+      const iterator: AsyncIterator<AssistantMessageEvent> = {
+        async next(...args) {
+          try {
+            return await inner.next(...args);
+          } catch (error) {
+            settle(undefined, error);
+            throw error;
+          }
+        },
+      };
+      if (inner.return) iterator.return = inner.return.bind(inner);
+      if (inner.throw) iterator.throw = inner.throw.bind(inner);
+      return iterator;
+    },
+    result: () => result,
+  } as unknown as AssistantMessageEventStream;
+}
+
+function failureResult(input: {
+  final?: AssistantMessage;
+  thrown?: unknown;
+  response?: ProviderResponse;
+  stream?: AssistantMessageEventStream;
+  iterator?: AsyncIterator<AssistantMessageEvent>;
+  buffered: AssistantMessageEvent[];
+  nowMs: () => number;
+  retryAllErrors?: boolean;
+}): PreflightResult {
+  const normalized = normalizeLLMError({
+    ...(input.thrown !== undefined ? { raw: input.thrown } : {}),
+    ...(input.final?.stopReason ? { finishReason: input.final.stopReason } : {}),
+    ...(input.final?.errorMessage ? { errorMessage: input.final.errorMessage } : {}),
+    ...(input.response ? { statusCode: input.response.status } : {}),
+    explicitAbort: input.final?.stopReason === 'aborted',
+  });
+  const decision =
+    input.retryAllErrors && !normalized.facts.explicitAbort
+      ? { retryable: true, reason: 'network' as const }
+      : toLLMRetryDecision(normalized);
+  if (!decision.retryable) {
+    return {
+      kind: 'terminal',
+      failure: {
+        normalized,
+        error: publicRetryError(normalized, decision.reason),
+        stream: input.stream,
+        iterator: input.iterator,
+        buffered: input.buffered,
+        thrown: input.thrown,
+      },
+    };
+  }
+  return {
+    kind: 'failure',
+    failure: {
+      normalized,
+      error: publicRetryError(normalized, decision.reason),
+      retryReason: decision.reason,
+      stream: input.stream,
+      iterator: input.iterator,
+      buffered: input.buffered,
+      thrown: input.thrown,
+      retryAfterMs: parseRetryAfterMs(input.response?.headers, input.nowMs()),
+    },
+  };
+}
+
+function isAbortFailure(failure: RetryFailure): boolean {
+  return failure.normalized.facts.explicitAbort;
+}
+
+function discardAttempt(failure: RetryFailure): void {
+  try {
+    const closed = failure.iterator?.return?.();
+    void Promise.resolve(closed).catch(() => undefined);
+  } catch {
+    // Best-effort provider cleanup must not block a framework retry.
+  }
+}
+
+function terminalFailure(failure: RetryFailure): AssistantMessageEventStream {
+  if (!failure.stream) throw asError(failure.thrown);
+  if (failure.thrown !== undefined) {
+    return throwingReplayStream(failure.buffered, failure.thrown);
+  }
+  if (!failure.iterator) throw new Error('LLM failure stream iterator is unavailable');
+  return replayStream(failure.stream, failure.iterator, failure.buffered);
+}
+
+function observeTerminalFailure(
+  failure: RetryFailure,
+  context: CallSettlementContext,
+): AssistantMessageEventStream {
+  try {
+    return observeCallSettlement(terminalFailure(failure), context);
+  } catch (error) {
+    notifyCallSettled(context, error);
+    throw error;
+  }
+}
+
+function observeCallSettlement(
+  source: AssistantMessageEventStream,
+  context: CallSettlementContext,
+): AssistantMessageEventStream {
+  if (!context.input.onCallSettled) return source;
+  let settled = false;
+  const settle = (final: AssistantMessage | undefined, error?: unknown): void => {
+    if (settled) return;
+    settled = true;
+    notifyCallSettled(context, error, final);
+  };
+  const result = Promise.resolve()
+    .then(() => source.result())
+    .then(
+      (final) => {
+        settle(final);
+        return final;
+      },
+      (error) => {
+        settle(undefined, error);
+        throw error;
+      },
+    );
+  void result.catch(() => undefined);
+
+  return {
+    [Symbol.asyncIterator]() {
+      let inner: AsyncIterator<AssistantMessageEvent>;
+      try {
+        inner = source[Symbol.asyncIterator]();
+      } catch (error) {
+        settle(undefined, error);
+        throw error;
+      }
+      const iterator: AsyncIterator<AssistantMessageEvent> = {
+        async next(...args) {
+          try {
+            return await inner.next(...args);
+          } catch (error) {
+            settle(undefined, error);
+            throw error;
+          }
+        },
+      };
+      if (inner.return) iterator.return = inner.return.bind(inner);
+      if (inner.throw) iterator.throw = inner.throw.bind(inner);
+      return iterator;
+    },
+    result: () => result,
+  } as unknown as AssistantMessageEventStream;
+}
+
+function notifyCallSettled(
+  context: CallSettlementContext,
+  thrown?: unknown,
+  final?: AssistantMessage,
+): void {
+  const observer = context.input.onCallSettled;
+  if (!observer) return;
+  const finalOutcome = classifyCallOutcome(final, thrown, context.signal?.aborted === true);
+  const usage = finalOutcome.outcome === 'success' ? callUsage(final) : undefined;
+  const event: LLMCallSettledEvent = {
+    sessionId: context.input.sessionId,
+    turnId: context.input.turnId,
+    callId: context.callId,
+    scope: context.input.scope,
+    provider: String(context.model.provider),
+    model: String(context.model.id),
+    final: finalOutcome,
+    retryTriggered: context.state.retryTriggered,
+    ...(context.state.retryReason ? { retryReason: context.state.retryReason } : {}),
+    requestAttempts: context.state.requestAttempts,
+    ...(finalOutcome.outcome === 'success' && final
+      ? { expectedTools: expectedToolsFrom(final) }
+      : {}),
+    ...(usage ? { usage } : {}),
+  };
+  try {
+    const observed = observer(event);
+    void Promise.resolve(observed).catch(() => undefined);
+  } catch {
+    // Final-call observability must never change provider-call behavior.
+  }
+}
+
+function expectedToolsFrom(final: AssistantMessage): readonly LLMExpectedToolIdentity[] {
+  return final.content.flatMap((block) =>
+    block.type === 'toolCall' ? [{ toolCallId: block.id, toolName: block.name }] : [],
+  );
+}
+
+function classifyCallOutcome(
+  final: AssistantMessage | undefined,
+  thrown: unknown,
+  explicitAbort: boolean,
+): { outcome: LLMCallOutcome; errorKind: LLMCallErrorKind } {
+  if (thrown === undefined && final?.stopReason !== 'error' && final?.stopReason !== 'aborted') {
+    return { outcome: 'success', errorKind: 'none' };
+  }
+  const normalized = normalizeLLMError({
+    ...(thrown !== undefined ? { raw: thrown } : {}),
+    ...(final?.stopReason ? { finishReason: final.stopReason } : {}),
+    ...(final?.errorMessage ? { errorMessage: final.errorMessage } : {}),
+    explicitAbort: explicitAbort || final?.stopReason === 'aborted',
+  });
+  const errorKind = toLLMMetricErrorKind(normalized.facts);
+  return { outcome: errorKind === 'abort' ? 'abort' : 'error', errorKind };
+}
+
+/**
+ * Project the provider usage of a successful call into the four raw buckets.
+ *
+ * Provider payloads are untrusted input, so a missing or non-finite bucket is
+ * normalised to zero rather than propagated as NaN. Absent usage yields
+ * `undefined` so observers can distinguish "no usage reported" from "zero
+ * tokens used".
+ */
+function callUsage(final: AssistantMessage | undefined): LLMCallUsage | undefined {
+  const usage = final?.usage;
+  if (!usage) return undefined;
+  return {
+    input: finiteTokens(usage.input),
+    output: finiteTokens(usage.output),
+    cacheRead: finiteTokens(usage.cacheRead),
+    cacheWrite: finiteTokens(usage.cacheWrite),
+  };
+}
+
+function readProviderUsage(final: AssistantMessage | undefined): {
+  usage?: LLMCallUsage;
+  complete: boolean;
+} {
+  try {
+    const usage = final?.usage;
+    if (!usage) return { complete: false };
+    const input = readTokenBucket(usage.input);
+    const output = readTokenBucket(usage.output);
+    const cacheRead = readTokenBucket(usage.cacheRead);
+    const cacheWrite = readTokenBucket(usage.cacheWrite);
+    return {
+      usage: {
+        input: input.value,
+        output: output.value,
+        cacheRead: cacheRead.value,
+        cacheWrite: cacheWrite.value,
+      },
+      complete: input.valid && output.valid && cacheRead.valid && cacheWrite.valid,
+    };
+  } catch {
+    return { complete: false };
+  }
+}
+
+function readTokenBucket(value: unknown): { value: number; valid: boolean } {
+  return typeof value === 'number' && Number.isFinite(value) && value >= 0
+    ? { value, valid: true }
+    : { value: 0, valid: false };
+}
+
+function finiteTokens(value: unknown): number {
+  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
+}
+
+function replayStream(
+  source: AssistantMessageEventStream,
+  iterator: AsyncIterator<AssistantMessageEvent>,
+  buffered: readonly AssistantMessageEvent[],
+): AssistantMessageEventStream {
+  return {
+    async *[Symbol.asyncIterator]() {
+      let index = 0;
+      while (index < buffered.length) {
+        const event = buffered[index];
+        index += 1;
+        if (event !== undefined) yield event;
+      }
+      for (;;) {
+        const next = await iterator.next();
+        if (next.done) return;
+        yield next.value;
+      }
+    },
+    result: () => source.result(),
+  } as unknown as AssistantMessageEventStream;
+}
+
+function throwingReplayStream(
+  buffered: readonly AssistantMessageEvent[],
+  thrown: unknown,
+): AssistantMessageEventStream {
+  return {
+    async *[Symbol.asyncIterator]() {
+      let index = 0;
+      while (index < buffered.length) {
+        const event = buffered[index];
+        index += 1;
+        if (event !== undefined) yield event;
+      }
+      throw thrown;
+    },
+    async result() {
+      throw thrown;
+    },
+  } as unknown as AssistantMessageEventStream;
+}
+
+function commitsOutput(event: AssistantMessageEvent): boolean {
+  if (
+    event.type === 'text_delta' ||
+    event.type === 'thinking_delta' ||
+    event.type === 'toolcall_delta'
+  ) {
+    return event.delta.length > 0;
+  }
+  if (event.type === 'text_end' || event.type === 'thinking_end') return event.content.length > 0;
+  if (event.type === 'toolcall_end') return true;
+  return 'partial' in event && hasCommittedContent(event.partial);
+}
+
+function hasCommittedContent(message: AssistantMessage): boolean {
+  return message.content.some((block) => {
+    if (block.type === 'text') return block.text.length > 0;
+    if (block.type === 'thinking') return block.thinking.length > 0;
+    return block.type === 'toolCall';
+  });
+}
+
+function isFailureMessage(message: AssistantMessage): boolean {
+  return message.stopReason === 'error' || message.stopReason === 'aborted';
+}
+
+function resolvePolicy(policy: Partial<LLMRetryPolicy> | undefined): LLMRetryPolicy {
+  return { ...DEFAULT_LLM_RETRY_POLICY, ...(policy ?? {}) };
+}
+
+function retryDelayMs(
+  retryAfterMs: number | undefined,
+  retryAttempt: number,
+  policy: LLMRetryPolicy,
+  random: () => number,
+): number {
+  if (retryAfterMs !== undefined) return Math.min(policy.maxDelayMs, Math.max(0, retryAfterMs));
+  const exponential = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (retryAttempt - 1));
+  return Math.floor(exponential / 2 + (clampRandom(random()) * exponential) / 2);
+}
+
+function clampRandom(value: number): number {
+  return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
+}
+
+function parseRetryAfterMs(
+  headers: Record<string, string> | undefined,
+  nowMs: number,
+): number | undefined {
+  if (!headers) return undefined;
+  const entries = Object.entries(headers);
+  const retryAfterMs = entries.find(([name]) => name.toLowerCase() === 'retry-after-ms')?.[1];
+  const parsedMillis = retryAfterMs === undefined ? undefined : Number(retryAfterMs);
+  if (parsedMillis !== undefined && Number.isFinite(parsedMillis)) return Math.max(0, parsedMillis);
+  const retryAfter = entries.find(([name]) => name.toLowerCase() === 'retry-after')?.[1];
+  if (!retryAfter) return undefined;
+  const parsedSeconds = Number(retryAfter);
+  if (Number.isFinite(parsedSeconds)) return Math.max(0, parsedSeconds * 1_000);
+  const parsedDate = Date.parse(retryAfter);
+  return Number.isNaN(parsedDate) ? undefined : Math.max(0, parsedDate - nowMs);
+}
+
+function publicRetryError(
+  normalized: NormalizedLLMError,
+  reason: LLMMetricErrorKind,
+): LLMRetryError {
+  const protocol = toLLMProtocolClassification(normalized);
+  return {
+    reason,
+    ...(protocol ? { code: protocol.code } : {}),
+    message: PUBLIC_ERROR_MESSAGES[reason],
+  };
+}
+
+async function notify(observer: LLMRetryOptions['observer'], event: LLMRetryEvent): Promise<void> {
+  try {
+    await observer?.(event);
+  } catch {
+    // Observability must never change provider-call correctness.
+  }
+}
+
+function abortableSleep(delayMs: number, signal?: AbortSignal): Promise<void> {
+  if (signal?.aborted) return Promise.reject(abortError(signal));
+  return new Promise((resolve, reject) => {
+    const onAbort = () => {
+      clearTimeout(timer);
+      signal?.removeEventListener('abort', onAbort);
+      if (signal) reject(abortError(signal));
+    };
+    const timer = setTimeout(() => {
+      signal?.removeEventListener('abort', onAbort);
+      resolve();
+    }, delayMs);
+    signal?.addEventListener('abort', onAbort, { once: true });
+  });
+}
+
+function abortError(signal: AbortSignal): Error {
+  return signal.reason instanceof Error ? signal.reason : new Error('LLM retry cancelled');
+}
+
+function asError(value: unknown): Error {
+  return value instanceof Error ? value : new Error(String(value ?? 'LLM request failed'));
+}
+
+function defaultCallId(): string {
+  return (
+    globalThis.crypto?.randomUUID?.() ??
+    `llm-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
+  );
+}

+ 614 - 0
packages/agent-core/src/pi-turn-runner/llm.ts

@@ -0,0 +1,614 @@
+import type { Agent, AgentMessage, StreamFn } from '@earendil-works/pi-agent-core';
+import { streamSimple, type CacheRetention, type SimpleStreamOptions } from '@earendil-works/pi-ai';
+import { LLM_REQUEST_TIMEOUT_MS } from './defaults.js';
+import type {
+  PiAfterLlmReplacementCommit,
+  PiBeforeLlmCallAppendMessage,
+  PiBeforeLlmCallReplaceMetadata,
+} from './hooks.js';
+import type { LLMModelConfig } from './types.js';
+import type { turnHistory } from './history.js';
+import type { turnState } from './turn.js';
+
+export function composeStreamFn(resolved: LLMModelConfig): StreamFn {
+  // Order matters: each wrapper only fills the option it owns, while
+  // explicit per-call options from upstream wrappers still win. The host
+  // ceiling is the exception and therefore the innermost link: it has to see
+  // the fully accumulated options in order to shrink them.
+  const callerHeaders =
+    resolved.headers && Object.keys(resolved.headers).length > 0 ? resolved.headers : undefined;
+  const hostClamped = withHostMaxOutputTokens(resolved.streamFn, resolved.hostMaxOutputTokens);
+  const cacheWrapped = withCacheRetention(hostClamped, resolved.cacheRetention);
+  const maxTokensWrapped =
+    typeof resolved.maxTokens === 'number' && resolved.maxTokens > 0
+      ? withMaxTokens(cacheWrapped, resolved.maxTokens)
+      : cacheWrapped;
+  const headerWrapped = callerHeaders
+    ? withHeaders(maxTokensWrapped, callerHeaders)
+    : maxTokensWrapped;
+  const fetchWrapped = resolved.fetch ? withFetch(headerWrapped, resolved.fetch) : headerWrapped;
+  return wrapStreamFnWithTimeout(fetchWrapped, LLM_REQUEST_TIMEOUT_MS);
+}
+
+export function setLLMHook(agent: Agent, turn: turnState, history: turnHistory): void {
+  if (turn.hooks.beforeLLM.length === 0 && turn.hooks.afterLLM.length === 0) return;
+
+  let checkpointCallCount = 0;
+  agent.transformContext = async (messages, signal) => {
+    const rejectedMessages = messages.filter((message) =>
+      turn.rejectedAssistantMessages.has(message),
+    );
+    if (rejectedMessages.length > 0) {
+      messages.splice(
+        0,
+        messages.length,
+        ...messages.filter((message) => !turn.rejectedAssistantMessages.has(message)),
+      );
+      for (const message of rejectedMessages) turn.rejectedAssistantMessages.delete(message);
+    }
+
+    if (turn.hooks.beforeLLM.length === 0) return messages;
+    const phase = checkpointCallCount === 0 ? 'initial' : 'iteration';
+    checkpointCallCount += 1;
+    const checkpoint = await runBeforeLLM(turn, messages, phase, signal);
+    if (checkpoint.type === 'abort') {
+      turn.metrics.tryRecordTerminalFailure({
+        errorSource: 'before_llm_hook',
+        errorKind: 'hook_error',
+      });
+      throw new Error(`before_llm_checkpoint_aborted: ${checkpoint.reason}`);
+    }
+    if (checkpoint.type === 'respond') {
+      turn.syntheticResponse.pending = {
+        text: checkpoint.text,
+        reason: checkpoint.reason,
+      };
+      return messages;
+    }
+    if (checkpoint.type === 'requestOnly') {
+      return checkpoint.messages;
+    }
+    if (checkpoint.type !== 'replace' && checkpoint.type !== 'append') return messages;
+
+    const replacement =
+      checkpoint.type === 'replace'
+        ? {
+            messages: checkpoint.durableMessages,
+            metadata: checkpoint.metadata,
+            ...(checkpoint.afterCommit ? { afterCommit: checkpoint.afterCommit } : {}),
+          }
+        : checkpoint.durableReplacement;
+    if (replacement) {
+      // Pi passes the provider-bound context array into transformContext, but
+      // Agent.state.messages is the transcript later event reducers read. A
+      // request-only hook may further filter the Provider copy after a durable
+      // replacement, so persist the durable snapshot independently.
+      const previousMessages = [...agent.state.messages];
+      messages.splice(0, messages.length, ...replacement.messages);
+      agent.state.messages = replacement.messages;
+      try {
+        await history.replace(replacement.messages, previousMessages, replacement.metadata);
+      } catch (err) {
+        const message = err instanceof Error ? err.message : String(err);
+        throw new Error(`before_llm_checkpoint_persistence_failed: ${message}`);
+      }
+      const postCommitMessage = await replacement.afterCommit?.();
+      if (postCommitMessage) {
+        const invalidAppendReason = validAppendMessage(postCommitMessage);
+        if (invalidAppendReason) {
+          throw new Error(`after_commit append message invalid: ${invalidAppendReason}`);
+        }
+        const appendMessage = checkpoint.type === 'append' ? checkpoint.messages.at(-1) : undefined;
+        checkpoint.messages = appendMessage
+          ? [...checkpoint.messages.slice(0, -1), postCommitMessage, appendMessage]
+          : [...checkpoint.messages, postCommitMessage];
+        messages.push(postCommitMessage);
+        agent.state.messages = [...agent.state.messages, postCommitMessage];
+        await history.flushTail();
+      }
+    }
+
+    if (checkpoint.type === 'replace') return checkpoint.messages;
+
+    messages.push(...checkpoint.tailMessages);
+    agent.state.messages = [...agent.state.messages, ...checkpoint.tailMessages];
+    try {
+      await history.flushTail();
+    } catch (err) {
+      const message = err instanceof Error ? err.message : String(err);
+      throw new Error(`before_llm_append_persistence_failed: ${message}`);
+    }
+    return checkpoint.messages;
+  };
+}
+
+async function runBeforeLLM(
+  turn: turnState,
+  messages: AgentMessage[],
+  phase: 'initial' | 'iteration',
+  signal?: AbortSignal,
+): Promise<
+  | { type: 'unchanged'; messages: AgentMessage[] }
+  | { type: 'requestOnly'; messages: AgentMessage[] }
+  | {
+      type: 'replace';
+      messages: AgentMessage[];
+      durableMessages: AgentMessage[];
+      metadata: PiBeforeLlmCallReplaceMetadata;
+      afterCommit?: PiAfterLlmReplacementCommit;
+    }
+  | {
+      type: 'append';
+      messages: AgentMessage[];
+      message: PiBeforeLlmCallAppendMessage;
+      tailMessages: AgentMessage[];
+      durableReplacement?: {
+        messages: AgentMessage[];
+        metadata: PiBeforeLlmCallReplaceMetadata;
+        afterCommit?: PiAfterLlmReplacementCommit;
+      };
+    }
+  | { type: 'respond'; text: string; reason: string }
+  | { type: 'abort'; reason: string }
+> {
+  const initialCurrentUser = captureInitialCurrentUser(messages, phase);
+  let currentMessages = [...messages];
+  let canonicalMessages = [...messages];
+  let requestMessagesReplaced = false;
+  let durableReplacement:
+    | {
+        messages: AgentMessage[];
+        metadata: PiBeforeLlmCallReplaceMetadata;
+        afterCommit?: PiAfterLlmReplacementCommit;
+      }
+    | undefined;
+  for (const hook of turn.hooks.beforeLLM) {
+    let decision: Awaited<ReturnType<typeof hook>>;
+    try {
+      decision = await hook({
+        sessionId: turn.input.sessionId,
+        turnId: turn.input.turnId,
+        phase,
+        messages: [...currentMessages],
+        canonicalMessages: [...canonicalMessages],
+        model: turn.llm.model,
+        apiKey: turn.llm.apiKey,
+        ...(turn.llm.headers && Object.keys(turn.llm.headers).length > 0
+          ? { headers: { ...turn.llm.headers } }
+          : {}),
+        ...(typeof turn.llm.maxTokens === 'number' && turn.llm.maxTokens > 0
+          ? { maxTokens: turn.llm.maxTokens }
+          : {}),
+        ...(turn.llm.maxSerializedInputBytes === undefined
+          ? {}
+          : { maxSerializedInputBytes: turn.llm.maxSerializedInputBytes }),
+        ...(turn.llm.cacheRetention ? { cacheRetention: turn.llm.cacheRetention } : {}),
+        ...(turn.auxiliaryStreamFn ? { streamFn: turn.auxiliaryStreamFn } : {}),
+        ...(turn.llm.payloadTransform ? { payloadTransform: turn.llm.payloadTransform } : {}),
+        ...(turn.llm.auxiliaryPayloadTransform
+          ? { auxiliaryPayloadTransform: turn.llm.auxiliaryPayloadTransform }
+          : {}),
+        systemPrompt: turn.input.systemPrompt,
+        tools: turn.tools.map((tool) => ({
+          name: tool.name,
+          description: tool.description,
+          parameters: tool.parameters,
+        })),
+        thinkingLevel: turn.thinkingLevel,
+        signal,
+        eventWriter: turn.writer,
+        eventIdGenerator: turn.nextEventId,
+        runtimeSeqGenerator: turn.nextRuntimeSeq,
+      });
+    } catch (err) {
+      const message = err instanceof Error ? err.message : String(err);
+      turn.logger.error(
+        {
+          session_id: turn.input.sessionId,
+          turn_id: turn.input.turnId,
+          phase,
+          error: message,
+        },
+        '[pi-turn-runner] beforeLlmCall hook threw; aborting provider call to keep context lifecycle fail-closed',
+      );
+      return { type: 'abort', reason: message };
+    }
+    if (!decision || decision.type === 'continue') continue;
+    if (decision.type === 'skip') {
+      if (typeof decision.reason !== 'string') {
+        turn.logger.warn(
+          {
+            session_id: turn.input.sessionId,
+            turn_id: turn.input.turnId,
+            phase,
+            reason_type: typeof decision.reason,
+          },
+          '[pi-turn-runner] before_llm_skip_reason_invalid; continuing provider call',
+        );
+        continue;
+      }
+      if (decision.reason.startsWith('context_lifecycle_')) {
+        turn.logger.warn(
+          {
+            session_id: turn.input.sessionId,
+            turn_id: turn.input.turnId,
+            phase,
+            reason: decision.reason,
+          },
+          '[pi-turn-runner] beforeLlmCall skipped context lifecycle replacement',
+        );
+      }
+      continue;
+    }
+    if (decision.type === 'abort') {
+      turn.logger.error(
+        {
+          session_id: turn.input.sessionId,
+          turn_id: turn.input.turnId,
+          phase,
+          reason: decision.reason,
+        },
+        '[pi-turn-runner] beforeLlmCall aborted provider call',
+      );
+      return { type: 'abort', reason: decision.reason };
+    }
+    if (decision.type === 'respond') {
+      if (typeof decision.text !== 'string' || decision.text.length === 0) {
+        return { type: 'abort', reason: 'beforeLlmCall trusted response must be non-empty' };
+      }
+      turn.logger.info(
+        {
+          session_id: turn.input.sessionId,
+          turn_id: turn.input.turnId,
+          phase,
+          reason: decision.reason,
+        },
+        '[pi-turn-runner] beforeLlmCall supplied a trusted response',
+      );
+      return { type: 'respond', text: decision.text, reason: decision.reason };
+    }
+    if (decision.type === 'replaceRequestMessages') {
+      if (typeof decision.reason !== 'string' || decision.reason.length === 0) {
+        return {
+          type: 'abort',
+          reason: 'beforeLlmCall request replacement reason must be non-empty',
+        };
+      }
+      currentMessages = [...decision.messages];
+      requestMessagesReplaced = true;
+      turn.logger.info(
+        {
+          session_id: turn.input.sessionId,
+          turn_id: turn.input.turnId,
+          phase,
+          reason: decision.reason,
+        },
+        '[pi-turn-runner] beforeLlmCall replaced request messages',
+      );
+      continue;
+    }
+    if (decision.type === 'appendMessage') {
+      const invalidAppendReason = validAppendMessage(decision.message);
+      if (typeof decision.reason !== 'string' || decision.reason.trim().length === 0) {
+        return { type: 'abort', reason: 'beforeLlmCall append reason must be non-empty' };
+      }
+      if (invalidAppendReason) {
+        return {
+          type: 'abort',
+          reason: `beforeLlmCall append message invalid: ${invalidAppendReason}`,
+        };
+      }
+      if (decision.placement === 'before-current-user') {
+        const placement = placeBeforeCurrentUser({
+          phase,
+          initialMessages: messages,
+          initialCurrentUser,
+          currentMessages,
+          durableReplacement,
+          marker: decision.message,
+        });
+        if (typeof placement === 'string') {
+          return { type: 'abort', reason: placement };
+        }
+        if (placement.type === 'defer') continue;
+        return {
+          type: 'append',
+          messages: placement.messages,
+          message: decision.message,
+          tailMessages: [],
+          durableReplacement: placement.durableReplacement,
+        };
+      }
+      return {
+        type: 'append',
+        messages: [...currentMessages, decision.message],
+        message: decision.message,
+        tailMessages: [decision.message],
+        ...(durableReplacement ? { durableReplacement } : {}),
+      };
+    }
+    const invalidReplacementReason = validReplacement(decision.metadata);
+    if (invalidReplacementReason) {
+      const reason = `beforeLlmCall replacement metadata invalid: ${invalidReplacementReason}`;
+      turn.logger.error(
+        {
+          session_id: turn.input.sessionId,
+          turn_id: turn.input.turnId,
+          phase,
+          reason,
+        },
+        '[pi-turn-runner] beforeLlmCall replacement rejected',
+      );
+      return { type: 'abort', reason };
+    }
+    currentMessages = [...decision.messages];
+    canonicalMessages = [...decision.messages];
+    durableReplacement = {
+      messages: currentMessages,
+      metadata: decision.metadata,
+      ...(decision.afterCommit ? { afterCommit: decision.afterCommit } : {}),
+    };
+    turn.logger.info(
+      {
+        session_id: turn.input.sessionId,
+        turn_id: turn.input.turnId,
+        phase,
+        replacement_id: decision.metadata.replacementId,
+        strategy_version: decision.metadata.strategyVersion,
+        summary_length: decision.metadata.summary.length,
+        first_kept_index: decision.metadata.firstKeptIndex,
+        ...(decision.metadata.tokensBefore === undefined
+          ? {}
+          : { tokens_before: decision.metadata.tokensBefore }),
+        ...(decision.metadata.tokensAfter === undefined
+          ? {}
+          : { tokens_after: decision.metadata.tokensAfter }),
+        ...(decision.metadata.messagesBefore === undefined
+          ? {}
+          : { messages_before: decision.metadata.messagesBefore }),
+        ...(decision.metadata.messagesAfter === undefined
+          ? {}
+          : { messages_after: decision.metadata.messagesAfter }),
+      },
+      '[pi-turn-runner] beforeLlmCall replaced context messages',
+    );
+  }
+  if (durableReplacement) {
+    return {
+      type: 'replace',
+      messages: currentMessages,
+      durableMessages: durableReplacement.messages,
+      metadata: durableReplacement.metadata,
+      ...(durableReplacement.afterCommit ? { afterCommit: durableReplacement.afterCommit } : {}),
+    };
+  }
+  return requestMessagesReplaced
+    ? { type: 'requestOnly', messages: currentMessages }
+    : { type: 'unchanged', messages };
+}
+
+function captureInitialCurrentUser(
+  messages: readonly AgentMessage[],
+  phase: 'initial' | 'iteration',
+): AgentMessage | undefined {
+  if (phase !== 'initial') return undefined;
+  const candidate = messages.at(-1);
+  if (candidate?.role !== 'user') return undefined;
+  return messages.filter((message) => message === candidate).length === 1 ? candidate : undefined;
+}
+
+function placeBeforeCurrentUser(input: {
+  readonly phase: 'initial' | 'iteration';
+  readonly initialMessages: readonly AgentMessage[];
+  readonly initialCurrentUser: AgentMessage | undefined;
+  readonly currentMessages: readonly AgentMessage[];
+  readonly durableReplacement:
+    | { readonly messages: AgentMessage[]; readonly metadata: PiBeforeLlmCallReplaceMetadata }
+    | undefined;
+  readonly marker: PiBeforeLlmCallAppendMessage;
+}):
+  | string
+  | { readonly type: 'defer' }
+  | {
+      readonly type: 'placed';
+      readonly messages: AgentMessage[];
+      readonly durableReplacement: {
+        readonly messages: AgentMessage[];
+        readonly metadata: PiBeforeLlmCallReplaceMetadata;
+      };
+    } {
+  if (input.phase !== 'initial') return 'before-current-user requires the initial phase';
+  if (!input.durableReplacement) return { type: 'defer' };
+  const currentUser = input.initialCurrentUser;
+  if (!currentUser) return 'before-current-user could not locate one current real user';
+  const sourceIndex = input.initialMessages.length - 1;
+  const sourceIndexes = input.durableReplacement.metadata.replacementSourceIndexes;
+  const durableMatches = input.durableReplacement.messages.flatMap((message, index) =>
+    message === currentUser || sourceIndexes?.[index] === sourceIndex ? [index] : [],
+  );
+  if (new Set(durableMatches).size > 1) {
+    return 'before-current-user located multiple replacement users';
+  }
+  const durableUserIndex = durableMatches[0];
+  const currentMatches = input.currentMessages.flatMap((message, index) =>
+    message === currentUser || index === durableUserIndex ? [index] : [],
+  );
+  if (new Set(currentMatches).size > 1) {
+    return 'before-current-user located multiple request users';
+  }
+  const currentUserIndex = currentMatches[0];
+  const requestBase = input.currentMessages.filter((_message, index) => index !== currentUserIndex);
+  const durableBase = input.durableReplacement.messages.filter(
+    (_message, index) => index !== durableUserIndex,
+  );
+  const durableMessages = [...durableBase, input.marker, currentUser];
+  return {
+    type: 'placed',
+    messages: [...requestBase, input.marker, currentUser],
+    durableReplacement: {
+      messages: durableMessages,
+      metadata: withCurrentUserTailMetadata(
+        input.durableReplacement.metadata,
+        durableUserIndex,
+        durableMessages.length,
+        sourceIndex,
+      ),
+    },
+  };
+}
+
+function withCurrentUserTailMetadata(
+  metadata: PiBeforeLlmCallReplaceMetadata,
+  removedIndex: number | undefined,
+  messagesAfter: number,
+  currentUserSourceIndex: number,
+): PiBeforeLlmCallReplaceMetadata {
+  const replacementSourceIndexes =
+    removedIndex === undefined
+      ? metadata.replacementSourceIndexes
+      : metadata.replacementSourceIndexes?.filter((_sourceIndex, index) => index !== removedIndex);
+  return {
+    ...metadata,
+    messagesAfter,
+    currentUserSourceIndex,
+    ...(replacementSourceIndexes === undefined ? {} : { replacementSourceIndexes }),
+  };
+}
+
+function validAppendMessage(message: PiBeforeLlmCallAppendMessage): string | undefined {
+  if (!message || typeof message !== 'object') return 'message is required';
+  if (message.role !== 'custom') return 'role must be custom';
+  if (message.display !== false) return 'display must be false';
+  if (typeof message.customType !== 'string' || message.customType.trim().length === 0) {
+    return 'customType must be non-empty';
+  }
+  if (typeof message.content !== 'string' || message.content.trim().length === 0) {
+    return 'content must be non-empty text';
+  }
+  if (typeof message.timestamp !== 'number' || !Number.isFinite(message.timestamp)) {
+    return 'timestamp must be finite';
+  }
+  return undefined;
+}
+
+function validReplacement(metadata: PiBeforeLlmCallReplaceMetadata): string | undefined {
+  if (!metadata || typeof metadata !== 'object') return 'metadata is required';
+  if (Object.hasOwn(metadata, 'currentUserSourceIndex')) {
+    return 'currentUserSourceIndex is reserved for placement';
+  }
+  if (!metadata.replacementId) return 'replacementId is required';
+  if (!metadata.strategyVersion) return 'strategyVersion is required';
+  if (typeof metadata.summary !== 'string') return 'summary is required';
+  if (!Array.isArray(metadata.compactedMessages)) return 'compactedMessages is required';
+  if (!Array.isArray(metadata.keptMessages)) return 'keptMessages is required';
+  if (
+    typeof metadata.firstKeptIndex !== 'number' ||
+    !Number.isInteger(metadata.firstKeptIndex) ||
+    metadata.firstKeptIndex < 0
+  ) {
+    return 'firstKeptIndex must be a non-negative integer';
+  }
+  return undefined;
+}
+
+function withCacheRetention(
+  inner: StreamFn | undefined,
+  cacheRetention: CacheRetention | undefined,
+): StreamFn {
+  const base = inner ?? streamSimple;
+  return ((model, context, options) => {
+    const mergedOptions: SimpleStreamOptions =
+      cacheRetention !== undefined
+        ? { ...(options ?? {}), cacheRetention: options?.cacheRetention ?? cacheRetention }
+        : (options ?? {});
+    return base(model, context, mergedOptions);
+  }) as StreamFn;
+}
+
+function withHeaders(inner: StreamFn | undefined, headers: Record<string, string>): StreamFn {
+  const base = inner ?? streamSimple;
+  return ((model, context, options) => {
+    const mergedHeaders: Record<string, string> = {
+      ...headers,
+      ...(options?.headers ?? {}),
+    };
+    return base(model, context, {
+      ...(options ?? {}),
+      headers: mergedHeaders,
+    });
+  }) as StreamFn;
+}
+
+function withFetch(inner: StreamFn | undefined, fetch: SimpleStreamOptions['fetch']): StreamFn {
+  const base = inner ?? streamSimple;
+  return ((model, context, options) => {
+    return base(model, context, {
+      ...(options ?? {}),
+      fetch: options?.fetch ?? fetch,
+    });
+  }) as StreamFn;
+}
+
+function withMaxTokens(inner: StreamFn | undefined, maxTokens: number): StreamFn {
+  const base = inner ?? streamSimple;
+  return ((model, context, options) => {
+    return base(model, context, {
+      ...(options ?? {}),
+      maxTokens:
+        options && typeof options.maxTokens === 'number' && options.maxTokens > 0
+          ? options.maxTokens
+          : maxTokens,
+    });
+  }) as StreamFn;
+}
+
+/**
+ * Binds a host-owned output ceiling to every provider request of this turn.
+ *
+ * `withMaxTokens` fills a default and steps aside once anything upstream has
+ * an opinion; a ceiling cannot work that way. This one takes the smallest of
+ * the host cap, whatever the request already asked for, and the model's own
+ * cap, so a provider that allows less still wins and nothing downstream can
+ * widen a budget the host already clamped.
+ *
+ * No cap means the caller keeps its stream function untouched. A cap that is
+ * present but not a positive integer is rejected here, while the turn is being
+ * assembled, rather than silently degrading into "no ceiling".
+ */
+function withHostMaxOutputTokens(
+  inner: StreamFn | undefined,
+  hostMaxOutputTokens: number | undefined,
+): StreamFn | undefined {
+  if (hostMaxOutputTokens === undefined) return inner;
+  if (!Number.isInteger(hostMaxOutputTokens) || hostMaxOutputTokens <= 0) {
+    throw new TypeError(
+      `host_max_output_tokens_invalid: ${String(hostMaxOutputTokens)} is not a positive integer`,
+    );
+  }
+  const base = inner ?? streamSimple;
+  return ((model, context, options) => {
+    return base(model, context, {
+      ...(options ?? {}),
+      maxTokens: smallestPositive([hostMaxOutputTokens, options?.maxTokens, model?.maxTokens]),
+    });
+  }) as StreamFn;
+}
+
+function smallestPositive(candidates: readonly (number | undefined)[]): number {
+  return Math.min(
+    ...candidates.filter(
+      (candidate): candidate is number =>
+        typeof candidate === 'number' && Number.isFinite(candidate) && candidate > 0,
+    ),
+  );
+}
+
+export function wrapStreamFnWithTimeout(inner: StreamFn | undefined, timeoutMs: number): StreamFn {
+  const base = inner ?? streamSimple;
+  return ((model, context, options) => {
+    return base(model, context, {
+      ...(options ?? {}),
+      timeoutMs: options?.timeoutMs ?? timeoutMs,
+    });
+  }) as StreamFn;
+}

+ 1230 - 0
packages/agent-core/src/pi-turn-runner/metrics.ts

@@ -0,0 +1,1230 @@
+/**
+ * pi-turn-runner metrics (MR1) — emit the `pi_*` metric family for the
+ * agent-core inner loop through the optionally injected `MetricsClient`.
+ *
+ * Design constraints:
+ * - Noop-safe: no client → the internal client is a noop and assembly
+ *   fingerprinting stays disabled.
+ * - Zero behavior change: every observation point is wrapped so that a
+ *   throwing client or a bug in the recorder can never break the turn.
+ * - Bare metric names (no `local_runtime_` prefix — the reporting layer
+ *   rejects prefixed names since MR0); labels are low-cardinality only.
+ */
+
+import type { Agent, AgentEvent, AgentMessage, StreamFn } from '@earendil-works/pi-agent-core';
+import type {
+  AssistantMessage,
+  AssistantMessageEvent,
+  AssistantMessageEventStream,
+  Context,
+} from '@earendil-works/pi-ai';
+import type { MetricLabels, MetricsClient } from '@mavis/shared/metrics-proxy';
+import {
+  normalizeLLMError,
+  toLLMMetricErrorKind,
+  type LLMMetricErrorKind,
+  type NormalizedLLMError,
+} from '@mavis/shared/llm-error-classifier';
+import type { TurnTerminationReason } from '../event-bridge/types.js';
+import type { RuntimeTool, ToolOperationClassifier } from '../tools/index.js';
+import type { LLMCallSettledEvent, LLMRetryEvent } from './llm-retry.js';
+import {
+  normalizeAbortSource,
+  type LLMModelConfig,
+  type RunTurnCaller,
+  type PiTurnRunnerLogger,
+} from './types.js';
+import {
+  createToolContextHistogramBucketsByName,
+  measureToolArguments,
+  measureToolContext,
+  measureToolResult,
+  type MeasuredToolValue,
+  type ToolContextSizeEstimator,
+} from './tool-context-size.js';
+import { fingerprintAssembly, type AssemblyFingerprint } from './assembly-fingerprint.js';
+
+const LARGE_TOOL_IO_TOKEN_THRESHOLD = 8_000;
+const MAX_ASSEMBLY_FINGERPRINT_BASELINES = 2_048;
+const MAX_LLM_REQUEST_GAP_BASELINES = 2_048;
+const LLM_TOKENS_PER_SECOND_BUCKETS = [0.1, 0.5, 1, 2, 5, 10, 20, 50, 100, 200];
+const LLM_GAP_MS_BUCKETS = [
+  100, 250, 500, 1000, 2500, 5000, 10_000, 30_000, 60_000, 120_000, 300_000, 600_000, 900_000,
+  1_800_000, 3_600_000,
+];
+const MAX_TOOL_OPERATION_VALUES = 128;
+const MAX_TOOL_OPERATION_VALUE_LENGTH = 64;
+
+export type PiLLMCacheOutcome = 'read' | 'no_read' | 'telemetry_unknown';
+
+export interface PiLLMRequestStartedInfo {
+  readonly sessionId: string;
+  readonly turnId: string;
+  readonly startedAtMs: number;
+  readonly provider: string;
+  readonly model: string;
+  readonly caller: string;
+}
+
+export interface PiLLMRequestSettledInfo {
+  readonly endedAtMs: number;
+  readonly cacheOutcome: PiLLMCacheOutcome;
+}
+
+/** Fail-open host observer for one physical provider request lifecycle. */
+export type PiLLMRequestSettlementObserver = (info: PiLLMRequestSettledInfo) => void;
+/**
+ * Called when a physical provider request starts. The optional returned closure
+ * is called exactly once when that request settles and may capture host state
+ * without asking agent-core to own product-specific correlation.
+ */
+export type PiLLMRequestObserver = (
+  info: PiLLMRequestStartedInfo,
+) => PiLLMRequestSettlementObserver | undefined | void;
+
+interface TurnMetricsDiagnostics {
+  sessionId: string;
+  turnId: string;
+  estimator?: ToolContextSizeEstimator;
+  logger: PiTurnRunnerLogger;
+}
+
+interface RegisteredToolOperationClassifier {
+  readonly allowedValues: ReadonlySet<string>;
+  /**
+   * How many declared values were dropped by the cardinality/length caps.
+   * Non-zero means some real operations will report as `unknown`.
+   */
+  readonly rejectedValueCount: number;
+  classify(args: unknown): string | undefined;
+}
+
+export type TurnErrorSource =
+  | 'llm'
+  | 'before_llm_hook'
+  | 'tool'
+  | 'history'
+  | 'event_bridge'
+  | 'message_identity'
+  | 'event_writer'
+  | 'turn_end_hook'
+  | 'runner'
+  | 'unknown';
+export type NonLLMTurnErrorKind =
+  | 'hook_error'
+  | 'persistence'
+  | 'translation'
+  | 'identity'
+  | 'delivery'
+  | 'runtime_error'
+  | 'unknown';
+export interface LLMFailureObservation {
+  normalized: NormalizedLLMError;
+  metricKind: LLMMetricErrorKind;
+}
+
+/**
+ * Data passed to the host-injected {@link PiLLMRequestFailureHook} after a physical provider
+ * request fails.
+ *
+ * agent-core is host-independent: it only classifies failures and forwards raw error data. The host
+ * (local-runtime) generates reportable error logs and handles formatting, encryption, and
+ * transport, keeping the reporting pipeline out of agent-core.
+ */
+export interface PiLLMRequestFailureInfo {
+  /**
+   * The value thrown directly by the physical request, such as a custom streamFn, transport error,
+   * or timeout. `undefined` if the failure is carried by a completed assistant message.
+   */
+  error?: unknown;
+  /** Raw exception captured by the provider before formatting the final error text. */
+  providerError?: unknown;
+  /**
+   * Final error text carried by a completed assistant message (`stopReason === 'error'`); present
+   * when {@link error} is `undefined`.
+   */
+  errorMessage?: string;
+  /**
+   * The framework's fixed-cardinality failure classification. User cancellation (`'abort'`) is
+   * filtered before invoking the hook, so hook implementations never receive abort.
+   */
+  metricKind: LLMMetricErrorKind;
+  /** The model and call source actually used for this physical request. */
+  request: {
+    api: string;
+    baseUrl: string;
+    caller: string;
+    model: string;
+    provider: string;
+  };
+  /** Unix timestamp in milliseconds when the failure was observed. */
+  occurredAtMs: number;
+}
+
+/**
+ * Optional host callback invoked once per confirmed physical provider request failure by {@link
+ * TurnMetricsRecorder.wrapStreamFn}, rather than the logical request wrapper. Each retry attempt's
+ * physical failure triggers it, but user cancellation does not.
+ *
+ * The hook may only produce out-of-band side effects and must not throw from the caller's
+ * perspective. agent-core always protects the call with `swallow`, ensuring hook errors cannot
+ * affect LLM requests, retries, or turn results.
+ */
+export type PiLLMRequestFailureHook = (info: PiLLMRequestFailureInfo) => void;
+export interface TurnFailureProvenance {
+  errorSource: TurnErrorSource;
+  errorKind: LLMMetricErrorKind | NonLLMTurnErrorKind;
+}
+
+const FIRST_TOKEN_EVENT_TYPES: ReadonlySet<AssistantMessageEvent['type']> = new Set([
+  'text_start',
+  'text_delta',
+  'thinking_start',
+  'thinking_delta',
+  'toolcall_start',
+  'toolcall_delta',
+]);
+
+const noopMetricsClient = {
+  counter() {},
+  gauge() {},
+  histogram() {},
+} as unknown as MetricsClient;
+
+export function newPiTurnMetrics(
+  client: MetricsClient | undefined,
+  nowMs: () => number,
+  onLLMRequestFailure?: PiLLMRequestFailureHook,
+  observeLLMRequest?: PiLLMRequestObserver,
+): PiTurnMetrics {
+  return new PiTurnMetrics(
+    client ?? noopMetricsClient,
+    nowMs,
+    client !== undefined,
+    onLLMRequestFailure,
+    observeLLMRequest,
+  );
+}
+
+export function createPiTurnHistogramBucketsByName(): Record<string, number[]> {
+  return {
+    pi_llm_tokens_per_second: [...LLM_TOKENS_PER_SECOND_BUCKETS],
+    pi_llm_inter_request_gap_ms: [...LLM_GAP_MS_BUCKETS],
+    ...createToolContextHistogramBucketsByName(),
+  };
+}
+
+/**
+ * Record the final outcome of one logical LLM call without conflating it with
+ * its physical retry attempts. All labels are fixed-cardinality framework
+ * classifications.
+ */
+export function recordPiLLMCallMetrics(
+  client: Pick<MetricsClient, 'counter'> | undefined,
+  caller: string,
+  event: LLMCallSettledEvent,
+): void {
+  if (!client) return;
+  const baseLabels = {
+    provider: event.provider,
+    model: event.model,
+    caller,
+    scope: event.scope,
+  };
+  swallow(() =>
+    client.counter('pi_llm_logical_call_total', 1, {
+      ...baseLabels,
+      outcome: event.final.outcome,
+      errorKind: event.final.errorKind,
+      retryTriggered: String(event.retryTriggered),
+    }),
+  );
+  const reason = event.retryReason;
+  if (!event.retryTriggered || !reason) return;
+  const outcome =
+    event.final.outcome === 'success'
+      ? 'recovered'
+      : event.final.outcome === 'abort'
+        ? 'cancelled'
+        : 'failed';
+  swallow(() =>
+    client.counter('pi_llm_retry_episode_total', 1, {
+      ...baseLabels,
+      reason,
+      outcome,
+    }),
+  );
+}
+
+/**
+ * Per-`PiTurnRunner` metrics host. Owns the concurrent-turn gauge state and
+ * hands out one {@link TurnMetricsRecorder} per `runTurn` call.
+ */
+export class PiTurnMetrics {
+  readonly client: MetricsClient;
+  readonly nowMs: () => number;
+  private readonly enabled: boolean;
+  /**
+   * Host-injected receiver for physical LLM request failures, used for error-log reporting.
+   * Independent of {@link enabled} and `client`: error reporting and metrics are separate
+   * pipelines, so it stays connected even without a MetricsClient.
+   */
+  readonly onLLMRequestFailure?: PiLLMRequestFailureHook;
+  readonly observeLLMRequest?: PiLLMRequestObserver;
+  // ponytail: gauge scope is per-runner instance — the local product path
+  // constructs a single PiTurnRunner per process, which is what the gauge is
+  // meant to describe. Move to a shared registry if multiple runners ever
+  // share one MetricsClient.
+  private readonly activeTurns = new Map<string, number>();
+  private readonly assemblyFingerprints = new Map<
+    string,
+    AssemblyFingerprint & { turnId: string }
+  >();
+  private readonly lastLLMRequestSettledAtBySession = new Map<string, number>();
+
+  constructor(
+    client: MetricsClient,
+    nowMs: () => number,
+    enabled = true,
+    onLLMRequestFailure?: PiLLMRequestFailureHook,
+    observeLLMRequest?: PiLLMRequestObserver,
+  ) {
+    this.client = client;
+    this.nowMs = nowMs;
+    this.enabled = enabled;
+    this.onLLMRequestFailure = onLLMRequestFailure;
+    this.observeLLMRequest = observeLLMRequest;
+  }
+
+  beginTurn(
+    caller: RunTurnCaller | undefined,
+    model: LLMModelConfig['model'],
+    diagnostics: TurnMetricsDiagnostics,
+  ): TurnMetricsRecorder {
+    return new TurnMetricsRecorder(this, caller ?? 'unknown', model, diagnostics);
+  }
+
+  bumpActiveTurns(caller: string, delta: number): void {
+    const next = Math.max(0, (this.activeTurns.get(caller) ?? 0) + delta);
+    if (next === 0) {
+      this.activeTurns.delete(caller);
+    } else {
+      this.activeTurns.set(caller, next);
+    }
+    this.client.gauge('pi_active_turns', next, { caller });
+  }
+
+  observeLLMRequestStarted(sessionId: string, startedAt: number): number | undefined {
+    const previous = this.lastLLMRequestSettledAtBySession.get(sessionId);
+    if (previous === undefined) return undefined;
+    return Math.max(0, startedAt - previous);
+  }
+
+  observeLLMRequestSettled(sessionId: string, settledAt: number): void {
+    this.lastLLMRequestSettledAtBySession.delete(sessionId);
+    this.lastLLMRequestSettledAtBySession.set(sessionId, settledAt);
+    if (this.lastLLMRequestSettledAtBySession.size <= MAX_LLM_REQUEST_GAP_BASELINES) return;
+    const oldest = this.lastLLMRequestSettledAtBySession.keys().next().value;
+    if (oldest !== undefined) this.lastLLMRequestSettledAtBySession.delete(oldest);
+  }
+
+  observeAssembly(
+    caller: string,
+    model: LLMModelConfig['model'],
+    diagnostics: TurnMetricsDiagnostics,
+    context: Context,
+  ): void {
+    if (!this.enabled) return;
+
+    const current = fingerprintAssembly(context);
+    const key = JSON.stringify([diagnostics.sessionId, String(model.provider), String(model.id)]);
+    const previous = this.assemblyFingerprints.get(key);
+
+    // Refresh insertion order so this map is a bounded process-local LRU.
+    this.assemblyFingerprints.delete(key);
+    this.assemblyFingerprints.set(key, { ...current, turnId: diagnostics.turnId });
+    if (this.assemblyFingerprints.size > MAX_ASSEMBLY_FINGERPRINT_BASELINES) {
+      const oldest = this.assemblyFingerprints.keys().next().value;
+      if (oldest !== undefined) this.assemblyFingerprints.delete(oldest);
+    }
+
+    if (!previous) return;
+    const scope = previous.turnId === diagnostics.turnId ? 'within_turn' : 'across_turn';
+    const labels = {
+      provider: String(model.provider),
+      model: String(model.id),
+      caller,
+      scope,
+    };
+    this.observeAssemblyPart(
+      diagnostics,
+      labels,
+      'system_prompt',
+      previous.systemPrompt,
+      current.systemPrompt,
+    );
+    this.observeAssemblyPart(diagnostics, labels, 'tools', previous.tools, current.tools);
+  }
+
+  private observeAssemblyPart(
+    diagnostics: TurnMetricsDiagnostics,
+    labels: MetricLabels,
+    part: 'system_prompt' | 'tools',
+    previousFingerprint: string,
+    currentFingerprint: string,
+  ): void {
+    const result = previousFingerprint === currentFingerprint ? 'stable' : 'changed';
+    this.client.counter('pi_llm_assembly_stability_total', 1, { ...labels, part, result });
+    if (result !== 'changed') return;
+    swallow(() =>
+      diagnostics.logger.info?.(
+        {
+          session_id: diagnostics.sessionId,
+          turn_id: diagnostics.turnId,
+          part,
+          scope: labels.scope,
+          provider: labels.provider,
+          model: labels.model,
+          caller: labels.caller,
+          previous_fingerprint: previousFingerprint,
+          current_fingerprint: currentFingerprint,
+        },
+        'pi_llm_assembly_fingerprint_changed',
+      ),
+    );
+  }
+}
+
+/**
+ * Per-turn recorder. `PiTurnRunner.runTurn` creates one before any work and
+ * always calls {@link finish} in a `finally`, so turn totals/gauges stay
+ * balanced on every exit path (completed / failed / aborted / thrown).
+ */
+export class TurnMetricsRecorder {
+  private readonly owner: PiTurnMetrics;
+  private readonly caller: string;
+  private readonly turnLabels: MetricLabels;
+  private readonly turnStartedAt: number;
+  private readonly diagnostics: TurnMetricsDiagnostics;
+  private loopSteps = 0;
+  private batchStartedAt: number | undefined;
+  private readonly toolStartedAt = new Map<string, number>();
+  private readonly toolIOStarted = new Map<
+    string,
+    { toolName: string; operation?: string; arguments: MeasuredToolValue }
+  >();
+  private readonly registeredToolNames = new Set<string>();
+  private readonly toolOperationClassifiers = new Map<string, RegisteredToolOperationClassifier>();
+  private finished = false;
+  private llmFailure?: LLMFailureObservation;
+  private terminalFailure?: TurnFailureProvenance;
+  // Caller abort can record llm/abort before the Turn settles as cancelled.
+  // Retain a real cleanup failure without changing first-wins semantics.
+  private firstNonLlmTerminalFailure?: TurnFailureProvenance;
+  private readonly pendingSettlements: Promise<unknown>[] = [];
+  private readonly degradationErrors = new WeakSet<object>();
+  // The provider result object is also carried by pi's message_end event. Keep the
+  // physical request duration beside that identity until EventBridge materialises usage.
+  private readonly requestDurationsMs = new WeakMap<object, number>();
+
+  constructor(
+    owner: PiTurnMetrics,
+    caller: string,
+    model: LLMModelConfig['model'],
+    diagnostics: TurnMetricsDiagnostics,
+  ) {
+    this.owner = owner;
+    this.caller = caller;
+    this.turnLabels = {
+      provider: String(model.provider),
+      model: String(model.id),
+      caller,
+    };
+    this.turnStartedAt = owner.nowMs();
+    this.diagnostics = diagnostics;
+    swallow(() => owner.bumpActiveTurns(caller, +1));
+  }
+
+  /**
+   * Wrap the fully composed streamFn so one LLM request maps to exactly one
+   * `pi_llm_request_total` observation. Request start = wrapper invocation.
+   */
+  wrapStreamFn(inner: StreamFn, settings: { recordTerminalFailure?: boolean } = {}): StreamFn {
+    const recordTerminalFailure = settings.recordTerminalFailure ?? true;
+    return (async (model, context, streamOptions) => {
+      const labels: MetricLabels = {
+        provider: String(model.provider),
+        model: String(model.id),
+        caller: this.caller,
+      };
+      const requestStartedAt = this.owner.nowMs();
+      const interRequestGapMs = this.owner.observeLLMRequestStarted(
+        this.diagnostics.sessionId,
+        requestStartedAt,
+      );
+      const settlementObserver = swallowValue(() =>
+        this.owner.observeLLMRequest?.({
+          sessionId: this.diagnostics.sessionId,
+          turnId: this.diagnostics.turnId,
+          startedAtMs: requestStartedAt,
+          provider: String(model.provider),
+          model: String(model.id),
+          caller: this.caller,
+        }),
+      );
+      if (interRequestGapMs !== undefined) {
+        swallow(() =>
+          this.owner.client.histogram('pi_llm_inter_request_gap_ms', interRequestGapMs, labels),
+        );
+      }
+      let providerError: unknown;
+      let hasProviderError = false;
+      const callerOnProviderError = streamOptions?.onProviderError;
+      const observedStreamOptions = {
+        ...streamOptions,
+        onProviderError(error: unknown, observedModel: typeof model): void {
+          providerError = error;
+          hasProviderError = true;
+          swallow(() => callerOnProviderError?.(error, observedModel));
+        },
+      };
+      swallow(() => this.owner.observeAssembly(this.caller, model, this.diagnostics, context));
+      swallow(() => this.recordToolContextResidency(model, context.messages as AgentMessage[]));
+      swallow(() => this.owner.client.counter('pi_llm_request_total', 1, labels));
+
+      let stream: AssistantMessageEventStream;
+      try {
+        stream = await inner(model, context, observedStreamOptions);
+      } catch (err) {
+        // StreamFn contract says failures should be encoded in the stream,
+        // but custom streamFns may still throw — count it, then rethrow.
+        swallow(() =>
+          this.recordLLMSettled(
+            labels,
+            requestStartedAt,
+            model,
+            undefined,
+            err,
+            hasProviderError ? providerError : undefined,
+            recordTerminalFailure,
+            interRequestGapMs,
+            settlementObserver,
+          ),
+        );
+        throw err;
+      }
+
+      // A custom stream may throw from iteration without ever resolving its
+      // result promise. Fold that failure into settlement so observability
+      // cannot keep runTurn's finally block pending forever.
+      const iteratorFailure = newIteratorFailure();
+      const observedResult = Promise.race([
+        Promise.resolve().then(() => stream.result()),
+        iteratorFailure.promise,
+      ]).then(
+        (final) => {
+          swallow(() =>
+            this.recordLLMSettled(
+              labels,
+              requestStartedAt,
+              model,
+              final,
+              undefined,
+              hasProviderError ? providerError : undefined,
+              recordTerminalFailure,
+              interRequestGapMs,
+              settlementObserver,
+            ),
+          );
+          return final;
+        },
+        (err) => {
+          swallow(() =>
+            this.recordLLMSettled(
+              labels,
+              requestStartedAt,
+              model,
+              undefined,
+              err,
+              hasProviderError ? providerError : undefined,
+              recordTerminalFailure,
+              interRequestGapMs,
+              settlementObserver,
+            ),
+          );
+          throw err;
+        },
+      );
+
+      this.pendingSettlements.push(observedResult.catch(() => undefined));
+      return observeFirstToken(
+        stream,
+        observedResult,
+        () => {
+          const observedAt = this.owner.nowMs();
+          swallow(() =>
+            this.owner.client.histogram(
+              'pi_llm_first_token_ms',
+              observedAt - requestStartedAt,
+              labels,
+            ),
+          );
+        },
+        iteratorFailure.reject,
+      );
+    }) as StreamFn;
+  }
+
+  requestDurationMsFor(message: unknown): number | undefined {
+    return message !== null && typeof message === 'object'
+      ? this.requestDurationsMs.get(message)
+      : undefined;
+  }
+
+  /** Observe only the final logical call outcome, without recounting provider requests. */
+  wrapLogicalStreamFn(
+    inner: StreamFn,
+    settings: { recordTerminalFailure?: boolean } = {},
+  ): StreamFn {
+    const recordTerminalFailure = settings.recordTerminalFailure ?? true;
+    return (async (model, context, options) => {
+      let stream: AssistantMessageEventStream;
+      try {
+        stream = await inner(model, context, options);
+      } catch (error) {
+        if (recordTerminalFailure) {
+          swallow(() => this.recordLogicalLLMFailure(undefined, error));
+        }
+        throw error;
+      }
+
+      const iteratorFailure = newIteratorFailure();
+      const observedResult = Promise.race([
+        Promise.resolve().then(() => stream.result()),
+        iteratorFailure.promise,
+      ]).then(
+        (final) => {
+          if (recordTerminalFailure) {
+            swallow(() => this.recordLogicalLLMFailure(final));
+          }
+          return final;
+        },
+        (error) => {
+          if (recordTerminalFailure) {
+            swallow(() => this.recordLogicalLLMFailure(undefined, error));
+          }
+          throw error;
+        },
+      );
+      this.pendingSettlements.push(observedResult.catch(() => undefined));
+      return observeFirstToken(stream, observedResult, () => {}, iteratorFailure.reject);
+    }) as StreamFn;
+  }
+
+  observeRetry(event: LLMRetryEvent): void {
+    const reason = event.error?.reason;
+    if (!reason) return;
+    const labels = { ...this.turnLabels, reason, scope: event.scope };
+    if (event.status === 'waiting') {
+      swallow(() => this.owner.client.counter('pi_llm_retry_total', 1, labels));
+      const { delayMs } = event;
+      if (delayMs !== undefined) {
+        swallow(() => this.owner.client.histogram('pi_llm_retry_delay_ms', delayMs, labels));
+      }
+    } else if (event.status === 'exhausted') {
+      swallow(() => this.owner.client.counter('pi_llm_retry_exhausted_total', 1, labels));
+    }
+  }
+
+  observeLLMCall(event: LLMCallSettledEvent): void {
+    recordPiLLMCallMetrics(this.owner.client, this.caller, event);
+  }
+
+  /** Second lightweight subscription — tool/loop/batch observations. */
+  observeAgent(agent: Agent, runtimeTools?: readonly RuntimeTool[]): void {
+    agent.state.tools.forEach((tool) => this.registeredToolNames.add(tool.name));
+    for (const tool of runtimeTools ?? []) {
+      swallow(() => {
+        const classifier = tool.def.operationClassifier;
+        if (!classifier || !this.registeredToolNames.has(tool.def.name)) return;
+        const registered = registerToolOperationClassifier(classifier);
+        if (registered.rejectedValueCount > 0) {
+          // Rejected entries silently collapse into the `unknown` bucket at
+          // query time, which looks like a product problem rather than a
+          // vocabulary problem. Name it once at registration instead.
+          this.diagnostics.logger.warn?.(
+            {
+              session_id: this.diagnostics.sessionId,
+              turn_id: this.diagnostics.turnId,
+              tool_name: tool.def.name,
+              accepted_operations: registered.allowedValues.size,
+              rejected_operations: registered.rejectedValueCount,
+              max_operations: MAX_TOOL_OPERATION_VALUES,
+              max_operation_length: MAX_TOOL_OPERATION_VALUE_LENGTH,
+            },
+            'pi_tool_operation_vocabulary_truncated',
+          );
+        }
+        this.toolOperationClassifiers.set(tool.def.name, registered);
+      });
+    }
+    agent.subscribe((event) => {
+      swallow(() => this.onAgentEvent(event));
+    });
+  }
+
+  getLLMFailureObservation(): LLMFailureObservation | undefined {
+    return this.llmFailure;
+  }
+
+  tryRecordTerminalFailure(provenance: TurnFailureProvenance): boolean {
+    if (provenance.errorSource !== 'llm') {
+      this.firstNonLlmTerminalFailure ??= provenance;
+    }
+    if (this.terminalFailure) return false;
+    this.terminalFailure = provenance;
+    return true;
+  }
+
+  recordDegradation(
+    errorSource: TurnErrorSource,
+    errorKind: NonLLMTurnErrorKind,
+    err?: unknown,
+  ): void {
+    if (err && typeof err === 'object') {
+      if (this.degradationErrors.has(err)) return;
+      this.degradationErrors.add(err);
+    }
+    swallow(() =>
+      this.owner.client.counter('pi_turn_degradation_total', 1, {
+        caller: this.caller,
+        errorSource,
+        errorKind,
+      }),
+    );
+  }
+
+  async settle(): Promise<void> {
+    await Promise.all(this.pendingSettlements);
+  }
+
+  finish(termination: TurnTerminationReason | undefined, abortReason?: unknown): void {
+    swallow(() => {
+      if (this.finished) return;
+      this.finished = true;
+      this.toolIOStarted.clear();
+      const { client } = this.owner;
+      const caller = this.caller;
+      const labels = this.turnLabels;
+      this.owner.bumpActiveTurns(caller, -1);
+      // Prometheus freezes a metric family's label keys. Keep the legacy
+      // family schema stable and put model dimensions under a new name.
+      client.counter('pi_turn_total', 1, { caller });
+      client.counter('pi_turn_model_total', 1, labels);
+      const isCancellation = termination?.kind === 'aborted';
+      let failure = this.terminalFailure;
+      if (isCancellation && failure?.errorSource === 'llm') {
+        failure = this.firstNonLlmTerminalFailure;
+      }
+      if (!failure && termination?.kind === 'failed' && this.llmFailure) {
+        failure = { errorSource: 'llm', errorKind: this.llmFailure.metricKind };
+      } else if (!failure && termination === undefined) {
+        failure = { errorSource: 'runner', errorKind: 'runtime_error' };
+      } else if (!failure && termination?.kind === 'failed') {
+        failure = { errorSource: 'unknown', errorKind: 'unknown' };
+      }
+      if (failure) {
+        // `pi_turn_error_total` shipped as {caller,errorKind}; errorSource
+        // belongs to a distinct family so older app versions remain accepted.
+        client.counter('pi_turn_error_total', 1, {
+          caller,
+          errorKind: failure.errorKind,
+        });
+        client.counter('pi_turn_failure_total', 1, { caller, ...failure });
+      }
+      if (isCancellation) {
+        // Preserve the legacy error family while keeping cancellations out of
+        // the failure family. A real terminal failure still takes precedence.
+        if (!failure) {
+          client.counter('pi_turn_error_total', 1, { caller, errorKind: 'abort' });
+        }
+        client.counter('pi_turn_abort_total', 1, {
+          ...labels,
+          abortSource: normalizeAbortSource(abortReason),
+        });
+      }
+      client.histogram('pi_turn_duration_ms', this.owner.nowMs() - this.turnStartedAt, { caller });
+      client.histogram('pi_loop_steps', this.loopSteps, { caller });
+    });
+  }
+
+  private onAgentEvent(event: AgentEvent): void {
+    const { client } = this.owner;
+    const caller = this.caller;
+    switch (event.type) {
+      case 'turn_start':
+        // One pi turn == one inner loop step (assistant response + tool batch).
+        this.loopSteps += 1;
+        client.counter('pi_loop_step_total', 1, this.turnLabels);
+        this.batchStartedAt = undefined;
+        break;
+      case 'tool_execution_start': {
+        const now = this.owner.nowMs();
+        const toolName = this.metricToolName(event.toolName);
+        this.toolStartedAt.set(event.toolCallId, now);
+        this.batchStartedAt ??= now;
+        client.counter('pi_tool_call_total', 1, { toolName, caller });
+        const operation = this.metricToolOperation(toolName, event.args);
+        this.toolIOStarted.set(event.toolCallId, {
+          toolName,
+          ...(operation !== undefined ? { operation } : {}),
+          arguments: measureToolArguments(event.args, this.diagnostics.estimator),
+        });
+        break;
+      }
+      case 'tool_execution_end': {
+        const now = this.owner.nowMs();
+        const toolName = this.metricToolName(event.toolName);
+        const startedAt = this.toolStartedAt.get(event.toolCallId);
+        this.toolStartedAt.delete(event.toolCallId);
+        if (startedAt !== undefined) {
+          client.histogram('pi_tool_call_duration_ms', now - startedAt, {
+            toolName,
+            caller,
+          });
+        }
+        if (event.isError) {
+          client.counter('pi_tool_call_error_total', 1, {
+            toolName,
+            caller,
+            errorKind: toolErrorKind(event.result),
+          });
+        }
+        const toolIO = this.toolIOStarted.get(event.toolCallId);
+        this.toolIOStarted.delete(event.toolCallId);
+        if (toolIO) {
+          this.recordToolIO(
+            event.toolCallId,
+            toolIO.toolName,
+            toolIO.operation,
+            'arguments',
+            toolIO.arguments,
+          );
+          this.recordToolIO(
+            event.toolCallId,
+            toolIO.toolName,
+            toolIO.operation,
+            'result',
+            measureToolResult(event.result, this.diagnostics.estimator),
+          );
+        }
+        break;
+      }
+      case 'turn_end':
+        if (this.batchStartedAt !== undefined) {
+          client.histogram('pi_tool_batch_duration_ms', this.owner.nowMs() - this.batchStartedAt, {
+            caller,
+          });
+          this.batchStartedAt = undefined;
+        }
+        this.toolIOStarted.clear();
+        break;
+      default:
+        break;
+    }
+  }
+
+  private metricToolName(toolName: string): string {
+    return this.registeredToolNames.has(toolName) ? toolName : 'unknown';
+  }
+
+  private metricToolOperation(toolName: string, args: unknown): string | undefined {
+    const classifier = this.toolOperationClassifiers.get(toolName);
+    if (!classifier) return undefined;
+    try {
+      const operation = classifier.classify(args);
+      return operation !== undefined && classifier.allowedValues.has(operation)
+        ? operation
+        : 'unknown';
+    } catch {
+      return 'unknown';
+    }
+  }
+
+  private recordToolIO(
+    toolCallId: string,
+    toolName: string,
+    operation: string | undefined,
+    direction: 'arguments' | 'result',
+    measured: MeasuredToolValue,
+  ): void {
+    const labels = { direction, toolName, caller: this.caller };
+    const client = this.owner.client;
+    client.histogram('pi_tool_io_bytes', measured.bytes, labels);
+    const tokens = measured.tokens;
+    if (tokens !== undefined) {
+      client.histogram('pi_tool_io_tokens', tokens, labels);
+      if (tokens >= LARGE_TOOL_IO_TOKEN_THRESHOLD) {
+        this.diagnostics.logger.info?.(
+          {
+            session_id: this.diagnostics.sessionId,
+            turn_id: this.diagnostics.turnId,
+            tool_call_id: toolCallId,
+            tool_name: toolName,
+            direction,
+            bytes: measured.bytes,
+            estimated_tokens: tokens,
+            caller: this.caller,
+            ...(operation !== undefined ? { tool_operation: operation } : {}),
+          },
+          'pi_tool_context_large_io_observed',
+        );
+      }
+    }
+    if (operation === undefined || direction !== 'result') return;
+    const operationLabels = { toolName, operation, caller: this.caller };
+    swallow(() =>
+      client.histogram('pi_tool_operation_result_bytes', measured.bytes, operationLabels),
+    );
+    if (tokens !== undefined) {
+      swallow(() => client.histogram('pi_tool_operation_result_tokens', tokens, operationLabels));
+    }
+  }
+
+  private recordToolContextResidency(
+    model: LLMModelConfig['model'],
+    messages: readonly AgentMessage[],
+  ): void {
+    const breakdown = measureToolContext(messages, this.diagnostics.estimator, (toolName) =>
+      this.metricToolName(toolName),
+    );
+    const labels = {
+      provider: String(model.provider),
+      model: String(model.id),
+      caller: this.caller,
+    };
+    this.owner.client.histogram('pi_tool_context_resident_bytes', breakdown.argumentBytes, {
+      kind: 'arguments',
+      ...labels,
+    });
+    this.owner.client.histogram('pi_tool_context_resident_bytes', breakdown.resultBytes, {
+      kind: 'result',
+      ...labels,
+    });
+    if (breakdown.argumentTokens !== undefined) {
+      this.owner.client.histogram('pi_tool_context_resident_tokens', breakdown.argumentTokens, {
+        kind: 'arguments',
+        ...labels,
+      });
+    }
+    if (breakdown.resultTokens !== undefined) {
+      this.owner.client.histogram('pi_tool_context_resident_tokens', breakdown.resultTokens, {
+        kind: 'result',
+        ...labels,
+      });
+    }
+
+    for (const [toolName, contribution] of breakdown.byTool) {
+      this.recordResidentContribution(toolName, 'arguments', {
+        bytes: contribution.argumentBytes,
+        ...(contribution.argumentTokens !== undefined
+          ? { tokens: contribution.argumentTokens }
+          : {}),
+      });
+      this.recordResidentContribution(toolName, 'result', {
+        bytes: contribution.resultBytes,
+        ...(contribution.resultTokens !== undefined ? { tokens: contribution.resultTokens } : {}),
+      });
+    }
+  }
+
+  private recordResidentContribution(
+    toolName: string,
+    kind: 'arguments' | 'result',
+    measured: MeasuredToolValue,
+  ): void {
+    const labels = { kind, toolName, caller: this.caller };
+    if (measured.bytes > 0) {
+      this.owner.client.counter('pi_tool_context_resident_bytes_total', measured.bytes, labels);
+    }
+    if (measured.tokens !== undefined && measured.tokens > 0) {
+      this.owner.client.counter('pi_tool_context_resident_tokens_total', measured.tokens, labels);
+    }
+  }
+
+  private recordLLMSettled(
+    labels: MetricLabels,
+    requestStartedAt: number,
+    model: LLMModelConfig['model'],
+    final: AssistantMessage | undefined,
+    thrown?: unknown,
+    providerError?: unknown,
+    recordTerminalFailure = true,
+    interRequestGapMs?: number,
+    settlementObserver?: PiLLMRequestSettlementObserver | void,
+  ): void {
+    const { client } = this.owner;
+    const responseCompletedAt = this.owner.nowMs();
+    swallow(() =>
+      this.owner.observeLLMRequestSettled(this.diagnostics.sessionId, responseCompletedAt),
+    );
+    const requestDurationMs = responseCompletedAt - requestStartedAt;
+    const cacheOutcome: PiLLMCacheOutcome =
+      typeof final?.usage?.cacheRead === 'number'
+        ? final.usage.cacheRead > 0
+          ? 'read'
+          : 'no_read'
+        : 'telemetry_unknown';
+    if (settlementObserver) {
+      swallow(() => settlementObserver({ endedAtMs: responseCompletedAt, cacheOutcome }));
+    }
+    client.histogram('pi_llm_response_ms', requestDurationMs, labels);
+    if (final && Number.isFinite(requestDurationMs) && requestDurationMs > 0) {
+      this.requestDurationsMs.set(final, requestDurationMs);
+    }
+    const observation = observeLLMFailure(final, thrown);
+    const gapClass = classifyLLMGap(interRequestGapMs);
+    swallow(() =>
+      client.counter('pi_llm_cache_outcome_total', 1, {
+        ...labels,
+        gapClass,
+        outcome: cacheOutcome,
+      }),
+    );
+
+    if (final?.usage) {
+      emitTokens(client, labels, 'input', final.usage.input);
+      emitTokens(
+        client,
+        labels,
+        'cache',
+        (final.usage.cacheRead ?? 0) + (final.usage.cacheWrite ?? 0),
+      );
+      emitCacheTokens(client, labels, 'read', final.usage.cacheRead);
+      emitCacheTokens(client, labels, 'write', final.usage.cacheWrite);
+      emitTokens(client, labels, 'output', final.usage.output);
+      if (!observation) {
+        emitOutputTokensPerSecond(
+          client,
+          labels,
+          final.usage.output,
+          requestStartedAt,
+          responseCompletedAt,
+        );
+      }
+    }
+    if (observation) {
+      if (recordTerminalFailure) {
+        this.llmFailure ??= observation;
+        this.tryRecordTerminalFailure({ errorSource: 'llm', errorKind: observation.metricKind });
+      }
+      client.counter('pi_llm_request_error_total', 1, {
+        ...labels,
+        errorKind: observation.metricKind,
+      });
+      // Host-injected error-log reporting hook, initially used for LLM provider failures.
+      // Fires for every physical request failure, including each retry attempt. Placed at physical request completion,
+      // rather than the logical request wrapper, to avoid collapsing retries into one log. `'abort'` is not a real
+      // provider failure, and the design excludes user cancellations from reporting by default.
+      // Protect the call with `swallow` so hook errors cannot disrupt requests, retries, or turns.
+      if (observation.metricKind !== 'abort' && this.owner.onLLMRequestFailure) {
+        const hook = this.owner.onLLMRequestFailure;
+        swallow(() =>
+          hook({
+            ...(thrown !== undefined ? { error: thrown } : {}),
+            ...(providerError !== undefined ? { providerError } : {}),
+            ...(final?.errorMessage ? { errorMessage: final.errorMessage } : {}),
+            metricKind: observation.metricKind,
+            request: {
+              api: String(model.api),
+              baseUrl: String(model.baseUrl),
+              caller: this.caller,
+              model: String(model.id),
+              provider: String(model.provider),
+            },
+            occurredAtMs: responseCompletedAt,
+          }),
+        );
+      }
+    }
+  }
+
+  private recordLogicalLLMFailure(final: AssistantMessage | undefined, thrown?: unknown): void {
+    const observation = observeLLMFailure(final, thrown);
+    if (!observation) return;
+    this.llmFailure ??= observation;
+    this.tryRecordTerminalFailure({ errorSource: 'llm', errorKind: observation.metricKind });
+  }
+}
+
+function classifyLLMGap(gapMs: number | undefined): 'first_request' | 'lt_5m' | 'gte_5m' {
+  if (gapMs === undefined) return 'first_request';
+  return gapMs < 300_000 ? 'lt_5m' : 'gte_5m';
+}
+
+function observeLLMFailure(
+  final: AssistantMessage | undefined,
+  thrown?: unknown,
+): LLMFailureObservation | undefined {
+  if (thrown === undefined && final?.stopReason !== 'error' && final?.stopReason !== 'aborted') {
+    return undefined;
+  }
+  const normalized = normalizeLLMError({
+    ...(thrown !== undefined ? { raw: thrown } : {}),
+    finishReason: final?.stopReason,
+    errorMessage: final?.errorMessage,
+    explicitAbort: final?.stopReason === 'aborted',
+  });
+  return { normalized, metricKind: toLLMMetricErrorKind(normalized.facts) };
+}
+
+function emitTokens(
+  client: MetricsClient,
+  labels: MetricLabels,
+  kind: 'input' | 'cache' | 'output',
+  count: number | undefined,
+): void {
+  if (typeof count !== 'number' || !Number.isFinite(count) || count <= 0) return;
+  client.counter('pi_llm_tokens_total', count, { ...labels, kind });
+}
+
+function emitOutputTokensPerSecond(
+  client: MetricsClient,
+  labels: MetricLabels,
+  outputTokens: number | undefined,
+  requestStartedAt: number,
+  responseCompletedAt: number,
+): void {
+  if (typeof outputTokens !== 'number' || !Number.isFinite(outputTokens) || outputTokens <= 0) {
+    return;
+  }
+  const requestDurationMs = responseCompletedAt - requestStartedAt;
+  if (!Number.isFinite(requestDurationMs) || requestDurationMs <= 0) return;
+  const tokensPerSecond = outputTokens / (requestDurationMs / 1_000);
+  if (!Number.isFinite(tokensPerSecond) || tokensPerSecond <= 0) return;
+  client.histogram('pi_llm_tokens_per_second', tokensPerSecond, labels);
+}
+
+function emitCacheTokens(
+  client: MetricsClient,
+  labels: MetricLabels,
+  operation: 'read' | 'write',
+  count: number | undefined,
+): void {
+  if (typeof count !== 'number' || !Number.isFinite(count) || count <= 0) return;
+  client.counter('pi_llm_cache_tokens_total', count, { ...labels, operation });
+}
+
+function registerToolOperationClassifier(
+  classifier: ToolOperationClassifier,
+): RegisteredToolOperationClassifier {
+  const allowedValues = new Set<string>();
+  let rejectedValueCount = 0;
+  for (const value of classifier.allowedValues) {
+    if (
+      allowedValues.size >= MAX_TOOL_OPERATION_VALUES ||
+      typeof value !== 'string' ||
+      value.length === 0 ||
+      value.length > MAX_TOOL_OPERATION_VALUE_LENGTH
+    ) {
+      rejectedValueCount += 1;
+      continue;
+    }
+    allowedValues.add(value);
+  }
+  return {
+    allowedValues,
+    rejectedValueCount,
+    classify: (args) => classifier.classify(args),
+  };
+}
+
+/**
+ * errorKind for tool failures. Tool errors at this layer are already
+ * collapsed into a text result, so keep the bucket set tiny and bounded.
+ */
+function toolErrorKind(result: unknown): 'abort' | 'timeout' | 'error' {
+  const content = (result as { content?: Array<{ type?: string; text?: string }> })?.content;
+  const text = Array.isArray(content)
+    ? (content.find((block) => block?.type === 'text')?.text ?? '')
+    : '';
+  if (/\babort/i.test(text)) return 'abort';
+  if (/\btimed?\s*out\b/i.test(text)) return 'timeout';
+  return 'error';
+}
+
+/**
+ * Duck-type stream wrapper: forwards iteration/result untouched and fires
+ * `onFirstToken` once on the first content-bearing event. The agent loop only
+ * consumes `[Symbol.asyncIterator]()` and `result()`.
+ */
+function observeFirstToken(
+  stream: AssistantMessageEventStream,
+  result: Promise<AssistantMessage>,
+  onFirstToken: () => void,
+  onIteratorError: (error: unknown) => void,
+): AssistantMessageEventStream {
+  let seen = false;
+  const wrapped = {
+    [Symbol.asyncIterator](): AsyncIterator<AssistantMessageEvent> {
+      const inner = createObservedIterator(stream, onIteratorError);
+      const iterator: AsyncIterator<AssistantMessageEvent> = {
+        next: async (...args) => {
+          try {
+            const step = await inner.next(...args);
+            if (!seen && !step.done && step.value && FIRST_TOKEN_EVENT_TYPES.has(step.value.type)) {
+              seen = true;
+              onFirstToken();
+            }
+            return step;
+          } catch (error) {
+            onIteratorError(error);
+            throw error;
+          }
+        },
+      };
+      if (inner.return) iterator.return = inner.return.bind(inner);
+      if (inner.throw) iterator.throw = inner.throw.bind(inner);
+      return iterator;
+    },
+    result: () => result,
+  };
+  return wrapped as unknown as AssistantMessageEventStream;
+}
+
+function createObservedIterator(
+  stream: AssistantMessageEventStream,
+  onIteratorError: (error: unknown) => void,
+): AsyncIterator<AssistantMessageEvent> {
+  try {
+    return stream[Symbol.asyncIterator]();
+  } catch (error) {
+    onIteratorError(error);
+    throw error;
+  }
+}
+
+function newIteratorFailure(): { promise: Promise<never>; reject: (error: unknown) => void } {
+  let rejectPromise: (error: unknown) => void = () => {};
+  const promise = new Promise<never>((_, reject) => {
+    rejectPromise = reject;
+  });
+  return { promise, reject: rejectPromise };
+}
+
+/** Metrics must never break the product path — not even on client bugs. */
+function swallow(fn: () => void): void {
+  try {
+    fn();
+  } catch {
+    // intentionally silent
+  }
+}
+
+function swallowValue<T>(fn: () => T): T | undefined {
+  try {
+    return fn();
+  } catch {
+    return undefined;
+  }
+}

+ 296 - 0
packages/agent-core/src/pi-turn-runner/outbound-message-normalizer.ts

@@ -0,0 +1,296 @@
+import type { AgentMessage } from '@earendil-works/pi-agent-core';
+import type {
+  Api,
+  AssistantMessage,
+  Message,
+  Model,
+  TextContent,
+  ThinkingContent,
+  UserMessage,
+} from '@earendil-works/pi-ai';
+import { convertToLlm } from '@earendil-works/pi-coding-agent';
+
+import { imageDimensions } from './image-dimensions.js';
+
+const PRIOR_THINKING_OPEN = '<|prior-thinking|>';
+const PRIOR_THINKING_CLOSE = '<|/prior-thinking|>';
+
+const SIBLING_NATIVE_THINKING_APIS = new Set<string>([
+  'anthropic-messages',
+  'bedrock-converse-stream',
+]);
+
+// Last-resort net: model gateways reject a request outright when any image in it
+// is degenerate, and because the image lives in persisted history the session
+// then fails forever. The producer-side guard in the Browser tool
+// (POST_ACTION_VISUAL_MIN_CLIP_EDGE_PX, 32) stops new ones being created; this
+// value exists to heal sessions that were already poisoned.
+//
+// It is deliberately far tighter than the producer's 32. The rejection
+// threshold is a server-side property that can move — measured at <=2px on the
+// production gateway and <=4px on the open-platform test gateway — so neither
+// side sits on the red line, but the two sides trade off in opposite
+// directions. The producer can be generous because it fully controls the clip
+// and a sub-32px sliver carries no information. Here the content is the user's,
+// the only job is "do not get the whole request rejected", and wrongly dropping
+// genuine content costs more than letting a small image through.
+const MIN_PROVIDER_IMAGE_EDGE_PX = 8;
+
+/**
+ * Build the exact temporary message list sent to a target model.
+ * Canonical Agent messages are never rewritten by this projection.
+ */
+export function projectAgentMessagesForModel(
+  messages: readonly AgentMessage[],
+  targetModel: Model<Api>,
+): {
+  messages: Message[];
+  removedCount: number;
+  /**
+   * Images kept because their size could not be determined, counted by declared
+   * mimeType. Empty in the normal case. The caller logs this; a recurring
+   * cluster is the signal to teach `imageDimensions` another format.
+   */
+  undeterminedImageMimeTypes: Record<string, number>;
+} {
+  const providerVisible = messages.filter((message) => !isHostOnlyMessage(message));
+  const compatible = removeOrphanToolResults(
+    mergeImmediateSendBatches(convertToLlm(providerVisible)).map(stripHostOnlyFields),
+  );
+  const normalized = normalizeOutboundMessagesForModel(compatible.messages, targetModel);
+  const undetermined = new Map<string, number>();
+  // Order matters: projectVideoBlocks turns `video` blocks into `image` blocks,
+  // so the size filter has to run after it or it would miss every
+  // video-derived image.
+  const projected = normalized
+    .map(projectVideoBlocks)
+    .map((message) => projectUndersizedImageBlocks(message, undetermined));
+  return {
+    removedCount: compatible.removedCount,
+    messages: projected,
+    undeterminedImageMimeTypes: Object.fromEntries(undetermined),
+  };
+}
+
+/** Explicit Host grouping; ordinary adjacent user messages remain independent. */
+export function immediateSendBatchId(message: AgentMessage): string | undefined {
+  if (message.role !== 'user') return undefined;
+  const metadata = Reflect.get(message, 'hostMetadata');
+  if (!metadata || typeof metadata !== 'object') return undefined;
+  const id = Reflect.get(metadata, 'immediateSendBatchId');
+  return typeof id === 'string' && id.length > 0 ? id : undefined;
+}
+
+function mergeImmediateSendBatches(messages: Message[]): Message[] {
+  const projected: Message[] = [];
+  const batchPositions = new Map<string, number>();
+  for (const message of messages) {
+    const batchId = immediateSendBatchId(message);
+    const position = batchId ? batchPositions.get(batchId) : undefined;
+    const previous = position === undefined ? undefined : projected[position];
+    if (position !== undefined && previous?.role === 'user' && message.role === 'user') {
+      const blocks = [
+        ...userContent(previous),
+        { type: 'text' as const, text: '\n\n' },
+        ...userContent(message),
+      ];
+      const content: ReturnType<typeof userContent> = [];
+      for (const block of blocks) {
+        const last = content.at(-1);
+        if (last?.type === 'text' && block.type === 'text') {
+          content[content.length - 1] = { ...last, text: last.text + block.text };
+        } else content.push(block);
+      }
+      projected[position] = { ...previous, content };
+    } else {
+      if (batchId) batchPositions.set(batchId, projected.length);
+      projected.push(message);
+    }
+  }
+  return projected;
+}
+
+function userContent(message: UserMessage): Exclude<UserMessage['content'], string> {
+  return typeof message.content === 'string'
+    ? [{ type: 'text', text: message.content }]
+    : message.content;
+}
+
+function stripHostOnlyFields(message: Message): Message {
+  if (
+    !Object.hasOwn(message, 'genuineUserQueryText') &&
+    !Object.hasOwn(message, 'canonicalTextRange') &&
+    !Object.hasOwn(message, 'hostMetadata')
+  ) {
+    return message;
+  }
+  const projected = { ...message };
+  Reflect.deleteProperty(projected, 'genuineUserQueryText');
+  Reflect.deleteProperty(projected, 'canonicalTextRange');
+  Reflect.deleteProperty(projected, 'hostMetadata');
+  return projected;
+}
+
+function isHostOnlyMessage(message: AgentMessage): boolean {
+  if (message.role !== 'custom') return false;
+  const metadata = Reflect.get(message, 'hostMetadata');
+  return (
+    !!metadata &&
+    typeof metadata === 'object' &&
+    !Array.isArray(metadata) &&
+    Reflect.get(metadata, 'providerVisibility') === 'omit'
+  );
+}
+
+function isSourceQualifiedByokProvider(provider: string): boolean {
+  return provider === 'minimax_api' || provider.startsWith('custom_provider:');
+}
+
+function shouldDropPortableThinking(message: AssistantMessage, targetModel: Model<Api>): boolean {
+  return (
+    isSourceQualifiedByokProvider(message.provider) ||
+    isSourceQualifiedByokProvider(targetModel.provider)
+  );
+}
+
+export function removeOrphanToolResults(messages: Message[]): {
+  messages: Message[];
+  removedCount: number;
+} {
+  const seenToolCallIds = new Set<string>();
+  const filtered = messages.filter((message) => {
+    if (message.role === 'assistant') {
+      message.content
+        .filter((block) => block.type === 'toolCall')
+        .forEach((block) => seenToolCallIds.add(block.id));
+      return true;
+    }
+    return message.role !== 'toolResult' || seenToolCallIds.has(message.toolCallId);
+  });
+  return {
+    messages: filtered.length === messages.length ? messages : filtered,
+    removedCount: messages.length - filtered.length,
+  };
+}
+
+/**
+ * Normalize provider-bound history before pi-ai's provider adapters apply their
+ * own model-distance rules.
+ *
+ * This works on the temporary LLM request copy only. Persisted Pi messages keep
+ * the original model/provider metadata for audit and replay.
+ */
+export function normalizeOutboundMessagesForModel(
+  messages: Message[],
+  targetModel: Model<Api>,
+): Message[] {
+  return messages.map((message) => {
+    if (message.role !== 'assistant') return message;
+    return normalizeAssistantMessage(message, targetModel);
+  });
+}
+
+function normalizeAssistantMessage(
+  message: AssistantMessage,
+  targetModel: Model<Api>,
+): AssistantMessage {
+  const sameProviderAndApi =
+    message.provider === targetModel.provider && message.api === targetModel.api;
+  const sameModel = sameProviderAndApi && message.model === targetModel.id;
+  if (sameModel) return message;
+
+  const canReplayNativeSibling =
+    sameProviderAndApi && SIBLING_NATIVE_THINKING_APIS.has(targetModel.api);
+  const dropPortableThinking = shouldDropPortableThinking(message, targetModel);
+  const content = message.content.flatMap((block) => {
+    if (block.type !== 'thinking') return block;
+    if (canReplayNativeSibling) return block;
+    if (dropPortableThinking) return [];
+    return thinkingToPortableText(block);
+  });
+
+  if (!canReplayNativeSibling) {
+    return { ...message, content };
+  }
+
+  // pi-ai's transformMessages treats a different model id as cross-model and
+  // strips provider-native thinking. For same-provider sibling APIs whose
+  // thinking signatures are known to be provider-bound rather than model-bound,
+  // stamp the outbound copy as the target model so pi-ai preserves the native
+  // blocks. Model-bound APIs (Google, OpenAI Responses, unknown APIs) are
+  // converted to portable text instead.
+  return {
+    ...message,
+    model: targetModel.id,
+    content,
+  };
+}
+
+function thinkingToPortableText(block: ThinkingContent): TextContent[] {
+  if (block.redacted || !block.thinking || block.thinking.trim().length === 0) return [];
+  return [
+    {
+      type: 'text',
+      text: `${PRIOR_THINKING_OPEN}\n${block.thinking}\n${PRIOR_THINKING_CLOSE}`,
+    },
+  ];
+}
+
+function projectVideoBlocks(message: Message): Message {
+  if (typeof message.content === 'string' || !Array.isArray(message.content)) return message;
+  let changed = false;
+  const content = message.content.map((block) => {
+    if (!block || typeof block !== 'object') return block;
+    const candidate = block as { type?: unknown; data?: unknown; mimeType?: unknown };
+    if (candidate.type !== 'video') return block;
+    changed = true;
+    return {
+      type: 'image' as const,
+      data: candidate.data as string,
+      mimeType: candidate.mimeType as string,
+    };
+  });
+  return changed ? ({ ...message, content } as Message) : message;
+}
+
+/**
+ * Replace images the provider would reject for being degenerate with a text
+ * placeholder, on the temporary request copy only.
+ *
+ * Fails open in every uncertain case: an image whose size cannot be read is
+ * kept untouched and only counted, because wrongly dropping real user content
+ * is worse than forwarding a small image. The replacement is a `text` block, so
+ * a message whose only block was an undersized image still has content — no
+ * special "would this message become empty" branch is needed.
+ */
+function projectUndersizedImageBlocks(
+  message: Message,
+  undetermined: Map<string, number>,
+): Message {
+  if (typeof message.content === 'string' || !Array.isArray(message.content)) return message;
+  let changed = false;
+  const content = message.content.map((block) => {
+    if (!block || typeof block !== 'object') return block;
+    const candidate = block as { type?: unknown; data?: unknown; mimeType?: unknown };
+    if (candidate.type !== 'image') return block;
+    const size = imageDimensions(candidate.data, candidate.mimeType);
+    if (!size) {
+      // The size check itself still ran above and still applies: only the
+      // telemetry skips blocks projected from `video`, which keep their
+      // `video/*` mimeType and are unparseable by design. Counting them would
+      // pre-pollute the very signal this counter exists to surface.
+      const mimeType = typeof candidate.mimeType === 'string' ? candidate.mimeType : 'unknown';
+      if (!mimeType.toLowerCase().startsWith('video/')) {
+        undetermined.set(mimeType, (undetermined.get(mimeType) ?? 0) + 1);
+      }
+      return block;
+    }
+    if (Math.min(size.width, size.height) >= MIN_PROVIDER_IMAGE_EDGE_PX) return block;
+    changed = true;
+    return {
+      type: 'text' as const,
+      text: `[image omitted: ${size.width}x${size.height} px is below the ${MIN_PROVIDER_IMAGE_EDGE_PX} px minimum edge required by the model provider]`,
+    };
+  });
+  return changed ? ({ ...message, content } as Message) : message;
+}

+ 249 - 0
packages/agent-core/src/pi-turn-runner/pi-turn-runner.ts

@@ -0,0 +1,249 @@
+/**
+ * `PiTurnRunner` — assemble pi-coding-agent's runtime for a single turn
+ * and bridge its event stream into canonical `RuntimeEvent`s.
+ *
+ * `PiTurnRunner` is reusable across sessions, but every call to
+ * {@link runTurn} constructs a fresh Agent, EventBridge, event queue and
+ * history cursor. Per-turn state stays inside the turn object created by
+ * `newTurn(...)`; the class only owns process-level defaults.
+ *
+ * @see packages/agent-core/ARCHITECTURE.md
+ */
+
+import type { MetricsClient } from '@mavis/shared/metrics-proxy';
+import type { TurnTerminationReason } from '../event-bridge/types.js';
+import { newAgent, runAgent } from './agent.js';
+import { defaultMessageIdAllocator, defaultNowMs, noopLogger } from './defaults.js';
+import { emitRunning, emitTerminal, subscribeEvents } from './events.js';
+import { newHistory } from './history.js';
+import { setLLMHook, wrapStreamFnWithTimeout } from './llm.js';
+import {
+  newPiTurnMetrics,
+  type PiTurnMetrics,
+  type PiLLMRequestFailureHook,
+  type PiLLMRequestObserver,
+} from './metrics.js';
+import { _computeFailureTerminationReasonForTest } from './terminal.js';
+import {
+  newTurn,
+  type LlmCaptureAgentEventSource,
+  type LlmCaptureRecorder,
+  type messageIDAllocator,
+} from './turn.js';
+import { setToolHooks } from './tools.js';
+import type { ToolContextSizeEstimator } from './tool-context-size.js';
+import type { PiTurnRunnerLogger, RunTurnInput as PiRunTurnInput } from './types.js';
+import type { ToolExecutionContext } from '../tools/index.js';
+
+export { LLM_REQUEST_TIMEOUT_MS } from './defaults.js';
+export { _computeFailureTerminationReasonForTest, wrapStreamFnWithTimeout };
+
+/** Optional message-id allocator (defaults to `crypto.randomUUID()`). */
+export interface PiMessageIdAllocator extends messageIDAllocator {
+  /**
+   * Allocate a globally-unique assistant `message_id` for the supplied
+   * turn. Callers that route through archon_server's `BeginAssistantMessage`
+   * RPC can return its assigned id; local callers can use a UUID.
+   */
+  allocateAssistantMessageId(sessionId: string, turnId: string): Promise<string>;
+}
+
+export interface PiTurnRunnerOptions {
+  messageIdAllocator?: PiMessageIdAllocator;
+  nowMs?: () => number;
+  metricsClient?: MetricsClient;
+  logger?: PiTurnRunnerLogger;
+  toolContextSizeEstimator?: ToolContextSizeEstimator;
+  /**
+   * Optional host callback invoked on each confirmed physical LLM provider request failure,
+   * excluding user cancellation. The host uses it for out-of-band error-log reporting; agent-core
+   * only classifies failures and forwards raw errors. See {@link PiLLMRequestFailureHook}.
+   */
+  onLLMRequestFailure?: PiLLMRequestFailureHook;
+  /** Optional host-owned observer for each physical LLM request lifecycle. */
+  observeLLMRequest?: PiLLMRequestObserver;
+  /**
+   * Optional factory for a per-turn LLM context capture recorder. Injected only by hosts that need
+   * to observe provider context (the development desktop Inspector). When omitted, turn assembly
+   * remains identical to the pre-injection behavior, with no capture code on the request path.
+   *
+   * Like the metrics recorder, it is created per turn: capture state must not be reused across
+   * turns.
+   */
+  llmCaptureFactory?: (input: {
+    readonly sessionId: string;
+    readonly turnId: string;
+  }) => LlmCaptureRecorder | undefined;
+}
+
+/**
+ * Pi assembly layer. Runtime adapters construct one instance and call
+ * {@link runTurn} for every LLM turn.
+ */
+export class PiTurnRunner {
+  private readonly messageIdAllocator: PiMessageIdAllocator;
+  private readonly now: () => number;
+  private readonly logger: Required<PiTurnRunnerLogger>;
+  private readonly metrics: PiTurnMetrics;
+  private readonly toolContextSizeEstimator?: ToolContextSizeEstimator;
+  private readonly llmCaptureFactory?: PiTurnRunnerOptions['llmCaptureFactory'];
+  readonly metricsClient?: MetricsClient;
+
+  constructor(options: PiTurnRunnerOptions = {}) {
+    this.messageIdAllocator = options.messageIdAllocator ?? defaultMessageIdAllocator;
+    this.now = options.nowMs ?? defaultNowMs;
+    this.metricsClient = options.metricsClient;
+    this.metrics = newPiTurnMetrics(
+      options.metricsClient,
+      this.now,
+      options.onLLMRequestFailure,
+      options.observeLLMRequest,
+    );
+    this.logger = { ...noopLogger, ...(options.logger ?? {}) };
+    this.toolContextSizeEstimator = options.toolContextSizeEstimator;
+    this.llmCaptureFactory = options.llmCaptureFactory;
+  }
+
+  /**
+   * Run a single LLM turn end-to-end:
+   * - build tools and Agent
+   * - bridge pi AgentEvents into RuntimeEvents
+   * - notify history hooks as pi state changes
+   * - emit the terminal session.status frame
+   */
+  async runTurn<TCtx extends ToolExecutionContext = ToolExecutionContext>(
+    input: PiRunTurnInput<TCtx>,
+  ): Promise<void> {
+    // Metrics recorder spans the whole turn; `finish` runs in the outer
+    // `finally` so turn totals / the active-turns gauge stay balanced on every
+    // exit path (completed / failed / aborted / thrown). `termination` staying
+    // undefined means runTurn threw before reaching a terminal frame.
+    const recorder = this.metrics.beginTurn(input.caller, input.llm.model, {
+      sessionId: input.sessionId,
+      turnId: input.turnId,
+      logger: this.logger,
+      ...(this.toolContextSizeEstimator ? { estimator: this.toolContextSizeEstimator } : {}),
+    });
+    let termination: TurnTerminationReason | undefined;
+    let llmCapture: LlmCaptureRecorder | undefined;
+    let unsubscribeCaptureRelay: (() => void) | undefined;
+    try {
+      // Step 1: Build state for a single turn. `newTurn` resolves model config and creates all
+      // objects that cannot be reused across turns: the tool list, composed streamFn, EventBridge
+      // (which translates AgentEvent into RuntimeEvent), and per-turn event-id / seq
+      // counters. The PiTurnRunner instance itself holds only process-level defaults.
+      llmCapture = this.llmCaptureFactory?.({
+        sessionId: input.sessionId,
+        turnId: input.turnId,
+      });
+      const turn = newTurn(input, {
+        allocator: this.messageIdAllocator,
+        nowMs: this.now,
+        logger: this.logger,
+        metrics: recorder,
+        ...(llmCapture ? { llmCapture } : {}),
+      });
+
+      // Step 2: Announce that the turn is running. Emit the first `session.status`
+      // RuntimeEvent so subscribers see the turn start before any LLM / tool output arrives.
+      await emitRunning(turn);
+
+      // Step 3: Create the pi Agent (injecting system prompt, model, tools, and history),
+      // and a history cursor tracking how much of `agent.state.messages` has been reported
+      // to the onHistoryChanged hook.
+      const agent = newAgent(turn);
+      if (llmCapture) {
+        type CaptureListener = Parameters<LlmCaptureAgentEventSource['subscribe']>[0];
+        const captureListeners = new Set<CaptureListener>();
+        unsubscribeCaptureRelay = agent.subscribe((event) => {
+          for (const listener of captureListeners) {
+            try {
+              listener(event);
+            } catch {
+              // Capture observation is best-effort and cannot affect Agent delivery.
+            }
+          }
+        });
+        llmCapture.observeAgentEvents({
+          subscribe(listener) {
+            captureListeners.add(listener);
+            return () => captureListeners.delete(listener);
+          },
+        });
+      }
+      recorder.observeAgent(agent, input.toolConfig.tools);
+      const history = newHistory(turn, agent);
+
+      // Step 4: Install Agent hooks. Tool hooks wrap tool execution; LLM hooks wrap
+      // each model call and feed compaction / message rewrites back through the history cursor.
+      setToolHooks(agent, turn);
+      setLLMHook(agent, turn, history);
+
+      // Step 5: Subscribe to the Agent event stream. Parallel pi tool calls may finish in different promise
+      // branches, so `subscribeEvents` feeds every AgentEvent into a single serial queue:
+      // translate events through the bridge, flush resulting RuntimeEvents to the writer, drive
+      // history.flushTail() at message / tool boundaries, and run onStepEnd. A single queue keeps
+      // RuntimeEvent ordering identical to the old monolithic runner. The later `events.drain()`
+      // waits for this queue.
+      const events = subscribeEvents(agent, turn, history);
+
+      // Step 6: Wire cancellation. If the caller's signal is already aborted, do not start
+      // the Agent: unsubscribe, drain queued events, and emit the terminal `aborted` frame. Otherwise,
+      // forward subsequent aborts to `agent.abort()` so `runAgent` settles promptly.
+      if (input.signal) {
+        if (input.signal.aborted) {
+          events.unsubscribe();
+          await events.drain();
+          termination = { kind: 'aborted' };
+          await emitTerminal(turn, termination);
+          return;
+        }
+        input.signal.addEventListener(
+          'abort',
+          () => {
+            agent.abort();
+          },
+          { once: true },
+        );
+      }
+
+      // Step 7: Drive the turn. `runAgent` prompts the Agent with the user message, or natively
+      // continues from existing history, and waits for idle;
+      // only abort / error returns a non-undefined TurnTerminationReason. Normal completion
+      // returns undefined. Always unsubscribe in `finally`, whether or not an error is thrown,
+      // to ensure the listener is detached.
+      let reason: Awaited<ReturnType<typeof runAgent>>;
+      try {
+        reason = await runAgent(agent, turn, events.convergeAtIdle);
+      } finally {
+        events.unsubscribe();
+      }
+
+      // Step 8: Finalize once the Agent stops producing events:
+      //   a) drain(): Wait for the serial event queue to flush completely.
+      //   b) flushTail(): Scan history one last time for messages appended by pi without matching
+      //      message_end / tool_execution_end callbacks.
+      //   c) emitTerminal(): Write the final `session.status` frame; if `runAgent`
+      //      returned no abort / error reason, default to `completed`.
+      await events.drain();
+      await history.flushTail();
+      termination = reason ?? events.forcedTermination() ?? { kind: 'completed' };
+      await emitTerminal(turn, termination);
+    } finally {
+      unsubscribeCaptureRelay?.();
+      unsubscribeCaptureRelay = undefined;
+      if (llmCapture?.drain) {
+        try {
+          await llmCapture.drain();
+        } catch (error) {
+          this.logger.warn(
+            { error, sessionId: input.sessionId, turnId: input.turnId },
+            'LLM capture drain failed',
+          );
+        }
+      }
+      await recorder.settle();
+      recorder.finish(termination, input.signal?.reason);
+    }
+  }
+}

+ 36 - 0
packages/agent-core/src/pi-turn-runner/terminal.ts

@@ -0,0 +1,36 @@
+import {
+  classifyLLMErrorToCode,
+  toLLMProtocolClassification,
+  type NormalizedLLMError,
+} from '@mavis/shared/llm-error-classifier';
+import type { TurnTerminationReason } from '../event-bridge/types.js';
+import type { RuntimeProtocolError } from '../protocol/runtime-event.js';
+
+/**
+ * Exported alias for unit testing — the LLM-error classify branch is
+ * significant enough to merit a focused regression test.
+ */
+export function _computeFailureTerminationReasonForTest(
+  runError: string | undefined,
+): TurnTerminationReason {
+  return failureReason(runError);
+}
+
+export function failureReason(
+  runError: string | undefined,
+  normalized?: NormalizedLLMError,
+): TurnTerminationReason {
+  const message = runError ?? 'pi-turn-runner: unknown failure';
+  const projected = normalized ? toLLMProtocolClassification(normalized) : null;
+  const classified = projected
+    ? { status_code: projected.code, message: projected.message ?? message }
+    : classifyLLMErrorToCode(message);
+  if (classified !== null) {
+    const protocolError: RuntimeProtocolError = {
+      code: classified.status_code,
+      message: classified.message,
+    };
+    return { kind: 'failed', message: classified.message, error: protocolError };
+  }
+  return { kind: 'failed', message };
+}

+ 238 - 0
packages/agent-core/src/pi-turn-runner/tool-context-size.ts

@@ -0,0 +1,238 @@
+import type { AgentMessage } from '@earendil-works/pi-agent-core';
+
+const UNSERIALIZABLE_PLACEHOLDER = '[unserializable]';
+
+const TOOL_CONTEXT_TOKEN_BUCKETS = [
+  16, 64, 256, 1_000, 4_000, 8_000, 16_000, 32_000, 64_000, 128_000, 256_000,
+];
+const TOOL_CONTEXT_BYTE_BUCKETS = [
+  64, 256, 1_000, 4_000, 16_000, 64_000, 256_000, 1_000_000, 4_000_000, 16_000_000,
+];
+
+export function createToolContextHistogramBucketsByName(): Record<string, number[]> {
+  return {
+    pi_tool_io_tokens: [...TOOL_CONTEXT_TOKEN_BUCKETS],
+    pi_tool_operation_result_tokens: [...TOOL_CONTEXT_TOKEN_BUCKETS],
+    pi_tool_context_resident_tokens: [...TOOL_CONTEXT_TOKEN_BUCKETS],
+    pi_tool_io_bytes: [...TOOL_CONTEXT_BYTE_BUCKETS],
+    pi_tool_operation_result_bytes: [...TOOL_CONTEXT_BYTE_BUCKETS],
+    pi_tool_context_resident_bytes: [...TOOL_CONTEXT_BYTE_BUCKETS],
+  };
+}
+
+export interface ToolContextSizeEstimator {
+  estimateTextTokens(text: string): number;
+  estimateVisualTokens(): number;
+}
+
+export interface MeasuredToolValue {
+  bytes: number;
+  tokens?: number;
+}
+
+export interface ToolContextContribution {
+  argumentBytes: number;
+  argumentTokens?: number;
+  resultBytes: number;
+  resultTokens?: number;
+}
+
+export interface ToolContextBreakdown extends ToolContextContribution {
+  itemCount: number;
+  byTool: ReadonlyMap<string, ToolContextContribution>;
+  largest?: {
+    kind: 'arguments' | 'result';
+    toolName: string;
+    bytes: number;
+    tokens?: number;
+  };
+}
+
+type MutableToolContextBreakdown = Omit<ToolContextBreakdown, 'byTool'> & {
+  byTool: Map<string, ToolContextContribution>;
+};
+
+function safeJsonStringify(value: unknown): string {
+  try {
+    return JSON.stringify(value) ?? 'undefined';
+  } catch {
+    return UNSERIALIZABLE_PLACEHOLDER;
+  }
+}
+
+function measureText(text: string, estimator?: ToolContextSizeEstimator): MeasuredToolValue {
+  const measured: MeasuredToolValue = { bytes: Buffer.byteLength(text, 'utf8') };
+  if (!estimator) return measured;
+  try {
+    const tokens = estimator.estimateTextTokens(text);
+    if (Number.isFinite(tokens) && tokens >= 0) measured.tokens = tokens;
+  } catch {
+    // Observability is fail-open: retain the byte count and omit tokens.
+  }
+  return measured;
+}
+
+export function measureToolArguments(
+  value: unknown,
+  estimator?: ToolContextSizeEstimator,
+): MeasuredToolValue {
+  return measureText(safeJsonStringify(value), estimator);
+}
+
+export function measureToolResult(
+  value: unknown,
+  estimator?: ToolContextSizeEstimator,
+): MeasuredToolValue {
+  const content = extractResultContent(value);
+  if (typeof content === 'string') return measureText(content, estimator);
+  if (!Array.isArray(content)) return measureText('', estimator);
+
+  let bytes = 0;
+  let tokens = estimator ? 0 : undefined;
+  for (const rawBlock of content) {
+    if (!rawBlock || typeof rawBlock !== 'object') continue;
+    const block = rawBlock as { type?: unknown; text?: unknown; data?: unknown };
+    if (block.type === 'text' && typeof block.text === 'string') {
+      const measured = measureText(block.text, estimator);
+      bytes += measured.bytes;
+      tokens = mergeTokens(tokens, measured.tokens);
+    } else if (block.type === 'image' || block.type === 'video') {
+      if (typeof block.data === 'string') bytes += Buffer.byteLength(block.data, 'utf8');
+      if (tokens !== undefined && estimator) {
+        try {
+          const visualTokens = estimator.estimateVisualTokens();
+          tokens =
+            Number.isFinite(visualTokens) && visualTokens >= 0 ? tokens + visualTokens : undefined;
+        } catch {
+          tokens = undefined;
+        }
+      }
+    }
+  }
+  return tokens === undefined ? { bytes } : { bytes, tokens };
+}
+
+export function measureToolContext(
+  messages: readonly AgentMessage[],
+  estimator?: ToolContextSizeEstimator,
+  normalizeToolName: (toolName: string) => string = (toolName) => toolName,
+): ToolContextBreakdown {
+  const toolNamesByCallId = new Map<string, string>();
+  const breakdown: MutableToolContextBreakdown = {
+    argumentBytes: 0,
+    ...(estimator ? { argumentTokens: 0 } : {}),
+    resultBytes: 0,
+    ...(estimator ? { resultTokens: 0 } : {}),
+    itemCount: 0,
+    byTool: new Map(),
+  };
+
+  for (const message of messages) {
+    if (message.role === 'assistant') {
+      const content = (message as AgentMessage & { content?: unknown }).content;
+      if (!Array.isArray(content)) continue;
+      for (const rawBlock of content) {
+        if (!rawBlock || typeof rawBlock !== 'object') continue;
+        const block = rawBlock as {
+          type?: unknown;
+          id?: unknown;
+          name?: unknown;
+          arguments?: unknown;
+        };
+        if (block.type !== 'toolCall' || typeof block.name !== 'string') continue;
+        const toolName = safeNormalizeToolName(block.name, normalizeToolName);
+        if (typeof block.id === 'string') toolNamesByCallId.set(block.id, toolName);
+        addMeasurement(
+          breakdown,
+          toolName,
+          'arguments',
+          measureToolArguments(block.arguments, estimator),
+          estimator !== undefined,
+        );
+      }
+      continue;
+    }
+
+    if (message.role === 'toolResult') {
+      const result = message as AgentMessage & { toolCallId?: unknown };
+      const toolName =
+        typeof result.toolCallId === 'string'
+          ? (toolNamesByCallId.get(result.toolCallId) ?? 'unknown')
+          : 'unknown';
+      addMeasurement(
+        breakdown,
+        toolName,
+        'result',
+        measureToolResult(message, estimator),
+        estimator !== undefined,
+      );
+    }
+  }
+
+  return breakdown;
+}
+
+function extractResultContent(value: unknown): unknown {
+  if (typeof value === 'string' || Array.isArray(value)) return value;
+  if (!value || typeof value !== 'object') return '';
+  return (value as { content?: unknown }).content ?? '';
+}
+
+function safeNormalizeToolName(
+  toolName: string,
+  normalizeToolName: (toolName: string) => string,
+): string {
+  try {
+    const normalized = normalizeToolName(toolName);
+    return normalized || 'unknown';
+  } catch {
+    return 'unknown';
+  }
+}
+
+function emptyContribution(withTokens: boolean): ToolContextContribution {
+  return {
+    argumentBytes: 0,
+    ...(withTokens ? { argumentTokens: 0 } : {}),
+    resultBytes: 0,
+    ...(withTokens ? { resultTokens: 0 } : {}),
+  };
+}
+
+function addMeasurement(
+  breakdown: MutableToolContextBreakdown,
+  toolName: string,
+  kind: 'arguments' | 'result',
+  measured: MeasuredToolValue,
+  withTokens: boolean,
+): void {
+  const contribution = breakdown.byTool.get(toolName) ?? emptyContribution(withTokens);
+  const bytesKey = kind === 'arguments' ? 'argumentBytes' : 'resultBytes';
+  const tokensKey = kind === 'arguments' ? 'argumentTokens' : 'resultTokens';
+
+  breakdown[bytesKey] += measured.bytes;
+  contribution[bytesKey] += measured.bytes;
+  breakdown[tokensKey] = mergeTokens(breakdown[tokensKey], measured.tokens);
+  contribution[tokensKey] = mergeTokens(contribution[tokensKey], measured.tokens);
+  breakdown.byTool.set(toolName, contribution);
+  breakdown.itemCount += 1;
+
+  const candidate = {
+    kind,
+    toolName,
+    bytes: measured.bytes,
+    ...(measured.tokens !== undefined ? { tokens: measured.tokens } : {}),
+  };
+  if (!breakdown.largest || measurementScore(candidate) > measurementScore(breakdown.largest)) {
+    breakdown.largest = candidate;
+  }
+}
+
+function mergeTokens(current: number | undefined, next: number | undefined): number | undefined {
+  if (current === undefined || next === undefined) return undefined;
+  return current + next;
+}
+
+function measurementScore(value: MeasuredToolValue): number {
+  return value.tokens ?? value.bytes;
+}

+ 246 - 0
packages/agent-core/src/pi-turn-runner/tools.ts

@@ -0,0 +1,246 @@
+import type {
+  AfterToolCallContext,
+  AfterToolCallResult,
+  Agent,
+  AgentTool,
+  AgentToolResult,
+  BeforeToolCallContext,
+} from '@earendil-works/pi-agent-core';
+import {
+  createBashTool,
+  createEditTool,
+  createReadTool,
+  createWriteTool,
+} from '@earendil-works/pi-coding-agent';
+import { createBashEnvSpawnHook, resolveBashEnvPolicy } from '../bash-subprocess-env.js';
+import type { TSchema } from '@sinclair/typebox';
+import type { RuntimeTool, ToolExecutionContext } from '../tools/index.js';
+import type { RuntimeToolSource } from '../tools/types.js';
+import type { turnState } from './turn.js';
+
+type SourcedAgentTool = AgentTool & { source?: RuntimeToolSource };
+type ToolCallContextWithSource<TContext extends { toolCall: { name: string } }> = TContext & {
+  toolCall: TContext['toolCall'] & { source?: RuntimeToolSource };
+};
+
+export function newTools<TCtx extends ToolExecutionContext>(
+  cwd: string,
+  bound: readonly RuntimeTool<TSchema, TCtx>[],
+  ctx: TCtx,
+  options: {
+    disableBuiltinFallback?: boolean;
+    readAssistantMessageId?: () => string | undefined;
+  } = {},
+): AgentTool[] {
+  const seen = new Set<string>();
+  const out: AgentTool[] = [];
+  for (const b of bound) {
+    if (seen.has(b.def.name)) {
+      throw new Error(`PiTurnRunner: duplicate tool name '${b.def.name}'`);
+    }
+    seen.add(b.def.name);
+    out.push(newTool(b, ctx, options.readAssistantMessageId));
+  }
+  if (!options.disableBuiltinFallback) {
+    if (!seen.has('read')) out.push(withFallbackExecutionMode(createReadTool(cwd), 'parallel'));
+    if (!seen.has('write')) out.push(withFallbackExecutionMode(createWriteTool(cwd), 'sequential'));
+    if (!seen.has('edit')) out.push(withFallbackExecutionMode(createEditTool(cwd), 'sequential'));
+    if (!seen.has('bash')) {
+      // Builtin fallback path must apply the same env sanitizer as
+      // LocalBashTool and the background executor — no side door
+      // (bash-tool-optimization.md §2.2).
+      //
+      // This is the ONE spawn site that keeps `resolveBashEnvPolicy()` as a
+      // default instead of a caller-supplied policy: it is unreachable in
+      // production (the local registry always binds LocalBashTool, and both
+      // local-runtime-v2 and cloud-task set disableBuiltinFallback), and
+      // agent-core cannot depend on the host's shim-aware policy without
+      // breaking the src boundary (no node:fs here). If this fallback ever
+      // becomes reachable with a dataDir, thread a policy in explicitly.
+      out.push(
+        withFallbackExecutionMode(
+          createBashTool(cwd, { spawnHook: createBashEnvSpawnHook(resolveBashEnvPolicy()) }),
+          'sequential',
+        ),
+      );
+    }
+  }
+  return out;
+}
+
+export function setToolHooks(agent: Agent, turn: turnState): void {
+  const sourceByToolName = new Map(
+    turn.tools
+      .map((tool) => [tool.name, readRuntimeToolSource(tool)] as const)
+      .filter((entry): entry is readonly [string, RuntimeToolSource] => entry[1] !== undefined),
+  );
+
+  if (turn.hooks.beforeTool.length > 0) {
+    agent.beforeToolCall = async (toolContext, signal) => {
+      const sourcedContext = attachRuntimeToolSource(toolContext, sourceByToolName);
+      for (const hook of turn.hooks.beforeTool) {
+        const result = await hook(sourcedContext, signal ?? turn.input.signal);
+        if (result?.block) {
+          if (turn.hooks.onStepEnd.length > 0 && result.blockedBy) {
+            turn.blockedToolCalls.push({
+              toolCallId: toolContext.toolCall.id,
+              blockedBy: result.blockedBy,
+            });
+          }
+          return result;
+        }
+      }
+      return undefined;
+    };
+  }
+
+  if (turn.hooks.onToolExecutionStart.length > 0) {
+    agent.onToolExecutionStart = (toolContext) => {
+      const sourcedContext = attachRuntimeToolSource(toolContext, sourceByToolName);
+      for (const hook of turn.hooks.onToolExecutionStart) hook(sourcedContext);
+    };
+  }
+
+  agent.afterToolCall = async (toolContext, signal) => {
+    let merged = toolResultErrorPatch(toolContext);
+    let currentContext = attachRuntimeToolSource(
+      merged ? applyToolResult(toolContext, merged) : toolContext,
+      sourceByToolName,
+    );
+    for (const hook of turn.hooks.afterTool) {
+      const patch = await hook(currentContext, signal ?? turn.input.signal);
+      if (!patch) continue;
+      merged = mergeToolResult(merged, patch);
+      currentContext = applyToolResult(currentContext, patch);
+    }
+    return merged;
+  };
+}
+
+function withFallbackExecutionMode(
+  tool: AgentTool,
+  executionMode: NonNullable<AgentTool['executionMode']>,
+): AgentTool {
+  return { ...tool, executionMode: tool.executionMode ?? executionMode };
+}
+
+function newTool<TCtx extends ToolExecutionContext>(
+  b: RuntimeTool<TSchema, TCtx>,
+  ctx: TCtx,
+  readAssistantMessageId?: () => string | undefined,
+): AgentTool {
+  const tool: SourcedAgentTool = {
+    name: b.def.name,
+    label: b.def.label ?? b.def.name,
+    description: b.def.description,
+    parameters: b.def.schema as AgentTool['parameters'],
+    ...(b.def.prepareArguments
+      ? { prepareArguments: b.def.prepareArguments as AgentTool['prepareArguments'] }
+      : {}),
+    executionMode: b.def.executionMode ?? 'sequential',
+    ...(b.source !== undefined ? { source: b.source } : {}),
+    async execute(
+      toolCallId,
+      params,
+      signal,
+      onUpdate,
+    ): Promise<AgentToolResult<Record<string, unknown>>> {
+      const input = (
+        typeof params === 'object' && params !== null ? (params as Record<string, unknown>) : {}
+      ) as never;
+      const assistantMessageId = readAssistantMessageId?.();
+      const callCtx = {
+        ...ctx,
+        toolCallId,
+        ...(assistantMessageId ? { assistantMessageId } : {}),
+      } as TCtx;
+      const result = await b.impl.execute(callCtx, input, signal, onUpdate);
+      return {
+        content: result.content as AgentToolResult<Record<string, unknown>>['content'],
+        details: toolResultDetails(result.details, result.isError),
+        ...(result.terminate !== undefined ? { terminate: result.terminate } : {}),
+      };
+    },
+  };
+  return tool;
+}
+
+function readRuntimeToolSource(tool: AgentTool): RuntimeToolSource | undefined {
+  const source = (tool as { source?: unknown }).source;
+  return source === 'builtin' || source === 'builtin-matrix' || source === 'configured'
+    ? source
+    : undefined;
+}
+
+function attachRuntimeToolSource<TContext extends BeforeToolCallContext | AfterToolCallContext>(
+  toolContext: TContext,
+  sourceByToolName: ReadonlyMap<string, RuntimeToolSource>,
+): TContext {
+  const source = sourceByToolName.get(toolContext.toolCall.name);
+  if (!source) return toolContext;
+  const sourced: ToolCallContextWithSource<TContext> = {
+    ...toolContext,
+    toolCall: {
+      ...toolContext.toolCall,
+      source,
+    },
+  };
+  return sourced;
+}
+
+function mergeToolResult(
+  base: AfterToolCallResult | undefined,
+  patch: AfterToolCallResult,
+): AfterToolCallResult {
+  return {
+    ...(base ?? {}),
+    ...(patch.content !== undefined ? { content: patch.content } : {}),
+    ...(patch.details !== undefined ? { details: patch.details } : {}),
+    ...(patch.isError !== undefined ? { isError: patch.isError } : {}),
+    ...(patch.terminate !== undefined ? { terminate: patch.terminate } : {}),
+    ...(patch.terminateAgent !== undefined ? { terminateAgent: patch.terminateAgent } : {}),
+  };
+}
+
+function applyToolResult(
+  context: AfterToolCallContext,
+  patch: AfterToolCallResult,
+): AfterToolCallContext {
+  const nextResult: AgentToolResult<unknown> = {
+    ...context.result,
+    ...(patch.content !== undefined ? { content: patch.content } : {}),
+    ...(patch.details !== undefined ? { details: patch.details } : {}),
+    ...(patch.terminate !== undefined ? { terminate: patch.terminate } : {}),
+  };
+  return {
+    ...context,
+    result: nextResult,
+    isError: patch.isError ?? context.isError,
+  };
+}
+
+function toolResultErrorPatch(context: AfterToolCallContext): AfterToolCallResult | undefined {
+  if (context.isError || !isRecord(context.result?.details)) {
+    return undefined;
+  }
+  return context.result.details.is_error === true || context.result.details.ok === false
+    ? { isError: true }
+    : undefined;
+}
+
+function toolResultDetails(
+  details: Record<string, unknown> | undefined,
+  isError: boolean | undefined,
+): Record<string, unknown> {
+  if (isError === undefined) {
+    return details ?? {};
+  }
+  return {
+    ...(details ?? {}),
+    is_error: isError,
+  };
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+  return typeof value === 'object' && value !== null && !Array.isArray(value);
+}

+ 393 - 0
packages/agent-core/src/pi-turn-runner/turn.ts

@@ -0,0 +1,393 @@
+import type {
+  AgentEvent,
+  AgentMessage,
+  AgentTool,
+  StreamFn,
+  ThinkingLevel,
+} from '@earendil-works/pi-agent-core';
+import type { AssistantMessage, AssistantMessageEventStream } from '@earendil-works/pi-ai';
+import { EventBridge } from '../event-bridge/index.js';
+import type { ToolExecutionContext } from '../tools/index.js';
+import type {
+  PiAfterLlmCallHook,
+  PiAfterToolCallHook,
+  PiBeforeLlmCallHook,
+  PiBeforeToolCallHook,
+  PiOnLlmCallPreparedHook,
+  PiOnHistoryChangedHook,
+  PiOnStepEndHook,
+  PiStepEndHookInput,
+  PiToolExecutionStartHook,
+} from './hooks.js';
+import { composeStreamFn } from './llm.js';
+import { withLLMRetry, type LLMCallScope, type LLMCallSettledEvent } from './llm-retry.js';
+import type { TurnMetricsRecorder } from './metrics.js';
+import { newTools } from './tools.js';
+import type {
+  LLMModelConfig,
+  PiEventWriter,
+  PiTurnRunnerLogger,
+  RunTurnInput as PiRunTurnInput,
+} from './types.js';
+
+export interface messageIDAllocator {
+  allocateAssistantMessageId(sessionId: string, turnId: string): Promise<string>;
+}
+
+export interface turnDeps {
+  allocator: messageIDAllocator;
+  nowMs: () => number;
+  logger: Required<PiTurnRunnerLogger>;
+  /** Per-turn metrics/provenance/degradation recorder; absent only disables emission. */
+  metrics?: TurnMetricsRecorder;
+  /**
+   * Per-turn LLM context capture recorder; absent disables capture entirely.
+   *
+   * Hosts that do not observe provider context — including cloud-runtime — never
+   * construct one, so the composed stream stays identical to the pre-capture
+   * composition and no capture code sits on the request path.
+   */
+  llmCapture?: LlmCaptureRecorder;
+}
+
+/**
+ * Observer that records the provider-bound context of main-agent LLM calls.
+ *
+ * The recorder owns every capture concern behind two methods: which scopes are
+ * captured, how the effective fetch is substituted, how physical attempts are
+ * reconciled into one logical call, and where the result is stored. None of
+ * that vocabulary belongs to the turn runner.
+ *
+ * Every method is best effort. An implementation must never change provider
+ * behaviour, retry semantics, or the outcome of the owning Turn.
+ */
+export interface LlmCaptureRecorder {
+  /**
+   * Wrap the composed stream function for one logical call scope.
+   *
+   * Implementations return `inner` unchanged when the scope is not captured or
+   * capture is disabled, so an inactive recorder costs nothing per request.
+   */
+  wrapLogicalStreamFn(inner: StreamFn, settings: { scope: LLMCallScope }): StreamFn;
+
+  /** Terminal observation for one logical call; idempotent per `callId`. */
+  observeCallSettled(event: LLMCallSettledEvent): void;
+
+  /** Receive only the raw event subscription capability owned by PiTurnRunner. */
+  observeAgentEvents(source: LlmCaptureAgentEventSource): void;
+
+  /** Wait for best-effort persistence before the owning Turn releases its lifecycle gate. */
+  drain?(): Promise<void>;
+}
+
+export interface LlmCaptureAgentEventSource {
+  subscribe(listener: (event: AgentEvent) => void): () => void;
+}
+
+export interface turnHooks {
+  beforeLLM: readonly PiBeforeLlmCallHook[];
+  onLLMPrepared: readonly PiOnLlmCallPreparedHook[];
+  afterLLM: readonly PiAfterLlmCallHook[];
+  beforeTool: readonly PiBeforeToolCallHook[];
+  onToolExecutionStart: readonly PiToolExecutionStartHook[];
+  afterTool: readonly PiAfterToolCallHook[];
+  onHistory: readonly PiOnHistoryChangedHook[];
+  /**
+   * Consolidated step-end handlers. Populated by `newTurn` from both
+   * `input.hooks.onStepEndHook` (preferred) and the deprecated per-step
+   * `input.hooks.onTurnEndHook` compatibility slot.
+   */
+  onStepEnd: readonly PiOnStepEndHook[];
+}
+
+export interface turnState<TCtx extends ToolExecutionContext = ToolExecutionContext> {
+  input: PiRunTurnInput<TCtx>;
+  llm: LLMModelConfig;
+  writer: PiEventWriter;
+  allocator: messageIDAllocator;
+  logger: Required<PiTurnRunnerLogger>;
+  metrics: TurnMetricsRecorder;
+  bridge: EventBridge;
+  hooks: turnHooks;
+  tools: AgentTool[];
+  streamFn: StreamFn;
+  auxiliaryStreamFn?: StreamFn;
+  thinkingLevel: ThinkingLevel;
+  initialMessages: AgentMessage[];
+  /** Step-local admission facts, handed off before step hooks run. Never persisted. */
+  blockedToolCalls: NonNullable<PiStepEndHookInput['blockedToolCalls']>[number][];
+  /** One trusted host response consumed by the next provider boundary. */
+  syntheticResponse: { pending?: { readonly text: string; readonly reason: string } };
+  /** Assistant responses rejected after message_end but still referenced by Pi's loop context. */
+  rejectedAssistantMessages: Set<AgentMessage>;
+  nextEventId(kind: string): string;
+  nextRuntimeSeq(): number;
+}
+
+export function newTurn<TCtx extends ToolExecutionContext>(
+  input: PiRunTurnInput<TCtx>,
+  deps: turnDeps,
+): turnState<TCtx> {
+  const resolved = input.llm;
+  const composedStreamFn = composeStreamFn(resolved);
+  const retryStream = (scope: LLMCallScope): StreamFn => {
+    const metricsStreamFn = deps.metrics
+      ? deps.metrics.wrapStreamFn(composedStreamFn, { recordTerminalFailure: false })
+      : composedStreamFn;
+    const callerObserver = input.llmRetry?.observer;
+    const callerOnCallSettled = input.llmRetry?.onCallSettled;
+    const retryingStreamFn = withLLMRetry(metricsStreamFn, {
+      ...input.llmRetry,
+      sessionId: input.sessionId,
+      turnId: input.turnId,
+      scope,
+      observer: async (event) => {
+        deps.metrics?.observeRetry(event);
+        await callerObserver?.(event);
+      },
+      onCallSettled: (event) => {
+        deps.metrics?.observeLLMCall(event);
+        deps.llmCapture?.observeCallSettled(event);
+        return callerOnCallSettled?.(event);
+      },
+    });
+    // One recorder spans the whole logical call. Physical retries overwrite its
+    // in-memory candidate; only the final successful settlement can persist.
+    const capturedStreamFn = deps.llmCapture
+      ? deps.llmCapture.wrapLogicalStreamFn(retryingStreamFn, { scope })
+      : retryingStreamFn;
+    return deps.metrics
+      ? deps.metrics.wrapLogicalStreamFn(capturedStreamFn, {
+          // Auto-compaction is an auxiliary degradation: local context lifecycle
+          // catches its failure and may continue with the main request. Keep its
+          // physical request/retry metrics, but never let it claim the turn's
+          // terminal LLM attribution or overwrite the main failure classification.
+          recordTerminalFailure: scope === 'agent',
+        })
+      : capturedStreamFn;
+  };
+  const mainStreamFn =
+    input.llmRetry || deps.llmCapture
+      ? retryStream('agent')
+      : deps.metrics
+        ? deps.metrics.wrapStreamFn(composedStreamFn)
+        : composedStreamFn;
+  const auxiliaryStreamFn = input.llmRetry ? retryStream('compaction') : undefined;
+  const syntheticResponse: turnState['syntheticResponse'] = {};
+  let eventSeq = 0;
+  let runtimeSeq = 0;
+  const nextEventId =
+    input.eventIdGenerator ?? ((kind: string) => `evt_${input.turnId}_${kind}_${++eventSeq}`);
+  const nextRuntimeSeq = input.runtimeSeqGenerator ?? (() => ++runtimeSeq);
+  const modelContextWindow = resolved.model.contextWindow;
+  const provenanceResolvers = new Map(
+    (input.toolConfig.tools ?? []).flatMap((tool) =>
+      tool.toolCallProvenanceResolver
+        ? ([[tool.def.name, tool.toolCallProvenanceResolver]] as const)
+        : [],
+    ),
+  );
+  const toolCallProvenanceResolver =
+    input.toolCallProvenanceResolver ??
+    (provenanceResolvers.size > 0
+      ? (resolution) => provenanceResolvers.get(resolution.toolName)?.(resolution)
+      : undefined);
+
+  const bridge = new EventBridge({
+    sessionId: input.sessionId,
+    turnId: input.turnId,
+    eventIdGenerator: nextEventId,
+    runtimeSeqGenerator: nextRuntimeSeq,
+    nowMs: deps.nowMs,
+    ...(deps.metrics && input.includeDetailedUsage === true
+      ? { requestDurationMs: deps.metrics.requestDurationMsFor.bind(deps.metrics) }
+      : {}),
+    ...(input.includeDetailedUsage === true ? { includeDetailedUsage: true } : {}),
+    logger: deps.logger,
+    ...(input.captureToolTiming ? { captureToolTiming: true } : {}),
+    ...(toolCallProvenanceResolver ? { toolCallProvenanceResolver } : {}),
+    ...(typeof modelContextWindow === 'number' &&
+    Number.isFinite(modelContextWindow) &&
+    modelContextWindow > 0
+      ? { contextWindow: modelContextWindow }
+      : {}),
+  });
+  const tools = newTools(
+    input.workspaceDir,
+    input.toolConfig.tools ?? [],
+    input.toolConfig.context,
+    {
+      disableBuiltinFallback: input.toolConfig.disableBuiltinToolFallback === true,
+      readAssistantMessageId: () => bridge.getActiveAssistantMessageId(),
+    },
+  );
+  const hooks: turnHooks = {
+    beforeLLM: input.hooks?.beforeLlmCallHook ?? [],
+    onLLMPrepared: input.hooks?.onLlmCallPreparedHook ?? [],
+    afterLLM: input.hooks?.afterLlmCallHook ?? [],
+    beforeTool: input.hooks?.beforeToolCallHook ?? [],
+    onToolExecutionStart: input.hooks?.onToolExecutionStartHook ?? [],
+    afterTool: input.hooks?.afterToolCallHook ?? [],
+    onHistory: input.hooks?.onHistoryChangedHook ?? [],
+    // Preserve legacy per-step handlers after preferred-name handlers.
+    onStepEnd: [...(input.hooks?.onStepEndHook ?? []), ...(input.hooks?.onTurnEndHook ?? [])],
+  };
+
+  return {
+    input,
+    llm: resolved,
+    writer: input.eventWriter,
+    allocator: deps.allocator,
+    logger: deps.logger,
+    metrics: deps.metrics!,
+    bridge,
+    hooks,
+    tools,
+    streamFn: withSyntheticResponse(
+      withLlmCallPreparedObservers(mainStreamFn, {
+        input,
+        llm: resolved,
+        tools,
+        thinkingLevel: resolved.thinkingLevel ?? 'off',
+        hooks: hooks.onLLMPrepared,
+        logger: deps.logger,
+      }),
+      syntheticResponse,
+      deps.nowMs,
+    ),
+    ...(auxiliaryStreamFn
+      ? {
+          auxiliaryStreamFn,
+        }
+      : {}),
+    thinkingLevel: resolved.thinkingLevel ?? 'off',
+    initialMessages: [...(input.history ?? [])],
+    blockedToolCalls: [],
+    syntheticResponse,
+    rejectedAssistantMessages: new Set(),
+    nextEventId,
+    nextRuntimeSeq,
+  };
+}
+
+function withLlmCallPreparedObservers(
+  inner: StreamFn,
+  options: {
+    readonly input: PiRunTurnInput;
+    readonly llm: LLMModelConfig;
+    readonly tools: readonly AgentTool[];
+    readonly thinkingLevel: ThinkingLevel;
+    readonly hooks: readonly PiOnLlmCallPreparedHook[];
+    readonly logger: Required<PiTurnRunnerLogger>;
+  },
+): StreamFn {
+  if (options.hooks.length === 0) return inner;
+  let logicalCallCount = 0;
+  return (async (model, context, streamOptions) => {
+    const phase = logicalCallCount === 0 ? 'initial' : 'iteration';
+    logicalCallCount += 1;
+    for (const hook of options.hooks) {
+      try {
+        await hook({
+          sessionId: options.input.sessionId,
+          turnId: options.input.turnId,
+          phase,
+          scope: 'agent',
+          messages: [...context.messages],
+          model,
+          ...(options.llm.maxTokens === undefined ? {} : { maxTokens: options.llm.maxTokens }),
+          ...(options.llm.hostMaxOutputTokens === undefined
+            ? {}
+            : { hostMaxOutputTokens: options.llm.hostMaxOutputTokens }),
+          ...(options.llm.maxSerializedInputBytes === undefined
+            ? {}
+            : { maxSerializedInputBytes: options.llm.maxSerializedInputBytes }),
+          ...(options.llm.cacheRetention === undefined
+            ? {}
+            : { cacheRetention: options.llm.cacheRetention }),
+          systemPrompt: options.input.systemPrompt,
+          tools: options.tools.map((tool) => ({
+            name: tool.name,
+            description: tool.description,
+            parameters: tool.parameters,
+          })),
+          thinkingLevel: options.thinkingLevel,
+          ...(streamOptions?.signal ? { signal: streamOptions.signal } : {}),
+        });
+      } catch (error) {
+        try {
+          options.logger.warn(
+            {
+              session_id: options.input.sessionId,
+              turn_id: options.input.turnId,
+              phase,
+              error: error instanceof Error ? error.message : String(error),
+            },
+            '[pi-turn-runner] onLlmCallPrepared hook failed; continuing provider call',
+          );
+        } catch {
+          // Observers and their diagnostics must never replace the provider call.
+        }
+      }
+    }
+    return inner(model, context, streamOptions);
+  }) as StreamFn;
+}
+
+function withSyntheticResponse(
+  inner: StreamFn,
+  state: turnState['syntheticResponse'],
+  nowMs: () => number,
+): StreamFn {
+  return ((model, context, options) => {
+    const pending = state.pending;
+    if (!pending) return inner(model, context, options);
+    delete state.pending;
+    const empty = trustedAssistantMessage(model, '', nowMs());
+    const final = trustedAssistantMessage(model, pending.text, nowMs());
+    const events = [
+      { type: 'start', partial: empty },
+      { type: 'text_start', contentIndex: 0, partial: empty },
+      { type: 'text_delta', contentIndex: 0, delta: pending.text, partial: final },
+      { type: 'text_end', contentIndex: 0, content: pending.text, partial: final },
+      { type: 'done', reason: 'stop', message: final },
+    ] as const;
+    return {
+      [Symbol.asyncIterator]() {
+        let index = 0;
+        return {
+          async next() {
+            const value = events[index];
+            index += 1;
+            return value ? { value, done: false } : { value: undefined, done: true };
+          },
+        };
+      },
+      result: async () => final,
+    } as AssistantMessageEventStream;
+  }) as StreamFn;
+}
+
+function trustedAssistantMessage(
+  model: Parameters<StreamFn>[0],
+  text: string,
+  timestamp: number,
+): AssistantMessage {
+  return {
+    role: 'assistant',
+    content: text ? [{ type: 'text', text }] : [],
+    api: model.api,
+    provider: model.provider,
+    model: model.id,
+    usage: {
+      input: 0,
+      output: 0,
+      cacheRead: 0,
+      cacheWrite: 0,
+      totalTokens: 0,
+      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+    },
+    stopReason: 'stop',
+    timestamp,
+  };
+}

+ 221 - 0
packages/agent-core/src/pi-turn-runner/types.ts

@@ -0,0 +1,221 @@
+/**
+ * Pi turn runner boundary types.
+ *
+ * These are explicit per-turn contracts owned by `pi-turn-runner`. They
+ * describe the model, event writer, user message, and tool configuration
+ * supplied to `PiTurnRunner.runTurn(...)`; hosts may own event identity when
+ * Pi attempts and native tools must share one logical-Turn sequence.
+ */
+
+import type { AgentMessage, StreamFn, ThinkingLevel } from '@earendil-works/pi-agent-core';
+import type {
+  Api,
+  CacheRetention,
+  ImageContent,
+  Model,
+  SimpleStreamOptions,
+} from '@earendil-works/pi-ai';
+import type { IRuntimeEvent } from '@mavis/protocol';
+import type {
+  RuntimeTool,
+  ToolCallProvenanceResolver,
+  ToolExecutionContext,
+} from '../tools/index.js';
+import type { TSchema } from '@sinclair/typebox';
+import type { PiBeforeLlmCallAppendMessage, PiTurnHooks } from './hooks.js';
+import type { LLMRetryOptions } from './llm-retry.js';
+
+export type RuntimeEvent = IRuntimeEvent;
+
+/** Canonical in-memory history message exposed at the agent-core boundary. */
+export type PiAgentMessage = AgentMessage;
+
+export interface LLMModelConfig {
+  model: Model<Api>;
+  apiKey?: string;
+  streamFn?: StreamFn;
+  thinkingLevel?: ThinkingLevel;
+  cacheRetention?: CacheRetention;
+  maxTokens?: number;
+  /** Host-owned serialized request cap used by before-LLM context admission. */
+  maxSerializedInputBytes?: number;
+  /**
+   * Ceiling the host owns for this turn's output, not a default.
+   *
+   * `maxTokens` above is the model's own configured cap and loses to any
+   * explicit per-call option; this one wins by taking the minimum of itself,
+   * whatever the request already asked for, and the model's own cap, so a
+   * budget the host already clamped can never be widened downstream. Leave it
+   * absent when the host has no such budget — every request then behaves
+   * exactly as before. Present but not a positive integer is rejected when the
+   * turn assembles its stream function, before any provider request.
+   */
+  hostMaxOutputTokens?: number;
+  headers?: Record<string, string>;
+  fetch?: SimpleStreamOptions['fetch'];
+  /** Provider payload transform for the main assistant response. */
+  payloadTransform?: SimpleStreamOptions['onPayload'];
+  /**
+   * Provider payload transform for auxiliary LLM calls made by hooks, such as
+   * automatic context-compaction checkpoints. Falls back to payloadTransform
+   * when omitted so existing hosts retain their request-shaping behavior.
+   */
+  auxiliaryPayloadTransform?: SimpleStreamOptions['onPayload'];
+  responseObserver?: SimpleStreamOptions['onResponse'];
+}
+
+export interface ToolConfig<TCtx extends ToolExecutionContext = ToolExecutionContext> {
+  tools?: readonly RuntimeTool<TSchema, TCtx>[];
+  disableBuiltinToolFallback?: boolean;
+  context: TCtx;
+}
+
+export interface UserMessageInput {
+  timestamp?: number;
+  text: string;
+  attachments?: readonly ImageContent[];
+  canonicalTextRange?: {
+    readonly startOffset: number;
+    readonly endOffset: number;
+  };
+  genuineUserQueryText?: string;
+  /** Opaque Host-owned metadata. Provider projection always removes it. */
+  hostMetadata?: Readonly<Record<string, unknown>> & { readonly immediateSendBatchId?: string };
+}
+
+/** How a fresh per-Turn Pi Agent starts its agent loop. */
+export type RunTurnStartMode = 'prompt' | 'continue';
+
+/**
+ * Who initiated the turn — becomes the low-cardinality `caller` metric label
+ * on turn metrics (MR1+). Values:
+ * - `'chat'`            direct user message over the local HTTP API
+ * - `'cron'`            scheduled cron task drain
+ * - `'channel_feishu'`  IM channel inbound (single bucket for all channels
+ *                       today; split per platform when more channels ship)
+ * - `'team'`            team/multi-agent orchestration
+ * - `'compact'`         history compaction (not yet populated — compaction
+ *                       drives the LLM directly and bypasses PiTurnRunner)
+ * - `'permission_llm'`  LLM-based permission evaluation
+ */
+export type RunTurnCaller =
+  | 'chat'
+  | 'cron'
+  | 'channel_feishu'
+  | 'team'
+  | 'compact'
+  | 'permission_llm';
+
+/** Bounded origin of a cancelled Pi turn. Unknown values collapse to `unknown`. */
+export type AbortSource =
+  | 'user_stop'
+  | 'immediate_send'
+  | 'input_safety'
+  | 'output_safety'
+  | 'lifecycle'
+  | 'unknown';
+
+export function normalizeAbortSource(value: unknown): AbortSource {
+  switch (value) {
+    case 'user_stop':
+    case 'immediate_send':
+    case 'input_safety':
+    case 'output_safety':
+    case 'lifecycle':
+      return value;
+    default:
+      return 'unknown';
+  }
+}
+
+/**
+ * Boundary classification the runner reports on every steering poll.
+ * `mid-turn`: further steps already follow (tool calls or queued follow-ups),
+ * so returned messages ride along before the next LLM hop. `exit`: the last
+ * step produced no further work and the runner attempts
+ * {@link RunTurnInput.tryBeginClose} as soon as the poll returns nothing —
+ * hosts may withhold messages here so the close hands them back to the
+ * session instead of extending a finished answer.
+ */
+export interface SteeringPollContext {
+  readonly boundary: 'mid-turn' | 'exit';
+}
+
+export interface RunTurnInput<TCtx extends ToolExecutionContext = ToolExecutionContext> {
+  sessionId: string;
+  turnId: string;
+  workspaceDir: string;
+  systemPrompt: string;
+  userMessage: UserMessageInput;
+  /** Omitted callers append `userMessage`; continuation re-enters from supplied history. */
+  startMode?: RunTurnStartMode;
+  llm: LLMModelConfig;
+  eventWriter: PiEventWriter;
+  history?: AgentMessage[];
+  /** Hidden Host messages appended immediately before the current real user. */
+  beforeUserMessages?: readonly (
+    | PiBeforeLlmCallAppendMessage
+    | import('@earendil-works/pi-ai').UserMessage
+  )[];
+  signal?: AbortSignal;
+  toolConfig: ToolConfig<TCtx>;
+  hooks?: PiTurnHooks;
+  /** Host opt-in for framework transport retry. Omitted hosts keep legacy behavior. */
+  llmRetry?: Omit<LLMRetryOptions, 'sessionId' | 'turnId' | 'scope'>;
+  /** Attribution captured from the same immutable capability snapshot as this turn's tools. */
+  toolCallProvenanceResolver?: ToolCallProvenanceResolver;
+  /** Forwarded to {@link EventBridgeContext.captureToolTiming}; host sets it non-prod only. */
+  captureToolTiming?: boolean;
+  /** TUI-only wire detail used to render output throughput. */
+  includeDetailedUsage?: boolean;
+  /** Turn initiator classification; see {@link RunTurnCaller}. */
+  caller?: RunTurnCaller;
+  /** Optional logical-Turn event identity source shared by host-owned retry attempts. */
+  eventIdGenerator?: (kind: string) => string;
+  /** Optional logical-Turn runtime sequence source shared by host-owned retry attempts. */
+  runtimeSeqGenerator?: () => number;
+  /** Messages accepted while the current step was running and injected before its next LLM hop. */
+  getSteeringMessages?: (
+    context?: SteeringPollContext,
+  ) => readonly AgentMessage[] | Promise<readonly AgentMessage[]>;
+  /** Gracefully ends the run when host-side steering admission rejects continuation. */
+  shouldStopAfterSteering?: () => boolean | Promise<boolean>;
+  /** Gracefully ends after the current assistant/tool step and before any follow-up poll. */
+  shouldStopAfterTurn?: () => boolean | Promise<boolean>;
+  /**
+   * Atomically seals external continuation acceptance once steering is empty.
+   * `false` means work won the close race and the runner must poll once more.
+   */
+  tryBeginClose?: (context: {
+    /** Text from the most recent assistant message at this close boundary. */
+    readonly lastAssistantMessage?: string;
+  }) => boolean | Promise<boolean>;
+}
+
+/**
+ * Per-turn event writer surface. PiTurnRunner batches multiple RuntimeEvents
+ * per pi `AgentEvent` and delegates actual event persistence / fan-out to the caller.
+ */
+export interface PiEventWriter {
+  /** Push a single canonical `RuntimeEvent`. */
+  pushRuntime(event: RuntimeEvent): void | Promise<void>;
+  /** Push a batch atomically when the caller supports it. */
+  appendEvents(events: RuntimeEvent[]): void | Promise<void>;
+}
+
+/**
+ * Turn-owned event identity and delivery surface shared by Pi and native tools.
+ * Hosts inject the same reporter for the full logical turn, including retries.
+ */
+export interface TurnEventReporter {
+  nextEventId(kind: string): string;
+  nextRuntimeSeq(): number;
+  appendEvents(events: RuntimeEvent[]): Promise<void>;
+}
+
+export interface PiTurnRunnerLogger {
+  debug?(obj: unknown, msg?: string): void;
+  info?(obj: unknown, msg?: string): void;
+  warn?(obj: unknown, msg?: string): void;
+  error?(obj: unknown, msg?: string): void;
+}

+ 101 - 0
packages/agent-core/src/prompt-read.ts

@@ -0,0 +1,101 @@
+/**
+ * Host-neutral prompt template read contracts and bounded internal-turn handoff.
+ *
+ * Local runtime produces internal model turns while local-runtime-v2 consumes
+ * them during preflight. Both packages already depend on agent-core.
+ */
+declare const promptReadSnapshotBrand: unique symbol;
+
+export interface PromptReadSnapshot {
+  readonly [promptReadSnapshotBrand]: never;
+}
+
+export type PromptTemplateRead =
+  | { readonly kind: 'found'; readonly content: string }
+  | { readonly kind: 'missing' }
+  | { readonly kind: 'invalid' };
+
+/** Signals that the enclosing model call must be rebuilt from builtin prompts. */
+export class PromptSnapshotInvalidError extends Error {
+  override readonly name = 'PromptSnapshotInvalidError';
+
+  constructor(message = 'Prompt snapshot is invalid') {
+    super(message);
+  }
+}
+
+export function isPromptSnapshotInvalidError(error: unknown): error is PromptSnapshotInvalidError {
+  return error instanceof PromptSnapshotInvalidError;
+}
+
+/** Production hosts own snapshot selection and consumers can only read it. */
+export interface PromptSnapshotSource {
+  capture(): Promise<PromptReadSnapshot>;
+  captureBuiltin(): Promise<PromptReadSnapshot>;
+  read(snapshot: PromptReadSnapshot, key: string): Promise<PromptTemplateRead>;
+}
+
+/** A host-captured prompt source and immutable snapshot for one model call. */
+export interface PromptReadScope {
+  readonly source: PromptSnapshotSource;
+  readonly snapshot: PromptReadSnapshot;
+}
+
+/** Process-local handoff for prompts rendered before an internal Turn is admitted. */
+export interface InternalTurnPromptReadRegistry {
+  reserve(turnId: string): boolean;
+  remember(turnId: string, promptRead: PromptReadScope): void;
+  rebind(fromTurnId: string, toTurnId: string): boolean;
+  take(turnId: string): PromptReadScope | undefined;
+  discard(turnId: string): void;
+  close(): void;
+}
+
+export class BoundedInternalTurnPromptReadRegistry implements InternalTurnPromptReadRegistry {
+  private readonly entries = new Map<string, PromptReadScope>();
+  private readonly reservations = new Set<string>();
+  private closed = false;
+
+  constructor(private readonly capacity = 128) {}
+
+  reserve(turnId: string): boolean {
+    if (this.closed || this.entries.has(turnId) || this.reservations.has(turnId)) return false;
+    if (this.entries.size + this.reservations.size >= this.capacity) return false;
+    this.reservations.add(turnId);
+    return true;
+  }
+
+  remember(turnId: string, promptRead: PromptReadScope): void {
+    if (this.closed || !this.reservations.delete(turnId)) return;
+    this.entries.set(turnId, promptRead);
+  }
+
+  rebind(fromTurnId: string, toTurnId: string): boolean {
+    if (this.closed) return false;
+    const promptRead = this.entries.get(fromTurnId);
+    if (!promptRead) return false;
+    if (fromTurnId === toTurnId) return true;
+    if (this.entries.has(toTurnId) || this.reservations.has(toTurnId)) return false;
+    this.entries.delete(fromTurnId);
+    this.entries.set(toTurnId, promptRead);
+    return true;
+  }
+
+  take(turnId: string): PromptReadScope | undefined {
+    const promptRead = this.entries.get(turnId);
+    this.entries.delete(turnId);
+    this.reservations.delete(turnId);
+    return promptRead;
+  }
+
+  discard(turnId: string): void {
+    this.reservations.delete(turnId);
+    this.entries.delete(turnId);
+  }
+
+  close(): void {
+    this.closed = true;
+    this.entries.clear();
+    this.reservations.clear();
+  }
+}

+ 164 - 0
packages/agent-core/src/protocol/agent-event.ts

@@ -0,0 +1,164 @@
+/**
+ * `AgentEvent` — the in-process event stream emitted by an agent runtime
+ * (e.g. `pi-agent-core`'s `Agent`) as it advances through an LLM turn.
+ *
+ * **Pure types only** — no implementations. This file exists so daemon and
+ * cloud-runtime can share a single event vocabulary without depending on
+ * `@earendil-works/pi-agent-core` directly. The shape mirrors pi-agent-core's
+ * `AgentEvent` so structural compatibility holds: an `EventBridge` wired to
+ * pi-agent-core can up-cast its events into this type without remapping.
+ *
+ * Lifecycle of a turn:
+ * ```
+ * agent_start
+ *   ↓
+ *   turn_start
+ *     ↓
+ *     message_start (assistant message handle opened)
+ *     message_update (delta — text/thinking/tool_call additions)
+ *     message_end (message body finalised)
+ *     ↓
+ *     tool_execution_start (tool dispatched)
+ *     tool_execution_update (partial result / progress)
+ *     tool_execution_end (tool resolved)
+ *   ↓
+ *   turn_end (this LLM turn concluded; another turn may follow)
+ *   ↓
+ * agent_end (the entire run is finished — emits the final message log)
+ * ```
+ *
+ * Daemon usage hint
+ * -----------------
+ * Daemon's bridge converts `AgentEvent` into `AgentMessageChunk` /
+ * `AgentMessage` for SSE delivery to local UI clients. `tool_execution_*`
+ * events become `AgentMessageChunk.tool_calls[].tool_call_status` updates.
+ *
+ * Cloud impl hint
+ * ---------------
+ * Cloud-runtime's `EventBridge` converts `AgentEvent` into the canonical
+ * `RuntimeEvent` (`stream.resp` / `session.status`), then `ExchangeSink`
+ * adapts to `AgentMessageChunk` for Phase 1 and pushes `RuntimeEvent`
+ * directly in Phase 2.
+ */
+
+import type { AgentMessage } from './agent-message.js';
+
+/**
+ * A "turn-result" tool-result frame attached to a `turn_end` event. Mirrors
+ * pi-agent-core's `ToolResultMessage` minimally — agent-core does not enforce
+ * a specific tool calling convention.
+ */
+export interface ToolResultMessage {
+  /** ID of the tool call that this result resolves. */
+  toolCallId: string;
+  /** Tool name (echoed for logging / routing convenience). */
+  toolName: string;
+  /** Free-form result payload — typically JSON-serialisable. */
+  result: unknown;
+  /** True when the tool reported a failure. */
+  isError: boolean;
+}
+
+/**
+ * Lower-level message-update payload carried inside `message_update`. The
+ * generic `unknown` is intentional — agent-core does not constrain the
+ * internal LLM-runtime delta shape, but downstream bridges may narrow.
+ */
+export type AssistantMessageEvent = unknown;
+
+/** Run started — fires once per `agent.run()`. */
+export interface AgentStartEvent {
+  type: 'agent_start';
+}
+
+/** Run ended — fires once per `agent.run()` after settlement. */
+export interface AgentEndEvent {
+  type: 'agent_end';
+  /** Snapshot of the message log at run end. */
+  messages: AgentMessage[];
+}
+
+/** A single LLM turn opened. Multiple turns may run within one agent run. */
+export interface TurnStartEvent {
+  type: 'turn_start';
+}
+
+/**
+ * A single LLM turn closed. Carries the assistant message that completed
+ * during this turn plus all tool results executed by the runtime.
+ */
+export interface TurnEndEvent {
+  type: 'turn_end';
+  message: AgentMessage;
+  toolResults: ToolResultMessage[];
+}
+
+/** Assistant message handle opened — first delta arrives next. */
+export interface MessageStartEvent {
+  type: 'message_start';
+  message: AgentMessage;
+}
+
+/** Streaming delta for the in-flight assistant message. */
+export interface MessageUpdateEvent {
+  type: 'message_update';
+  message: AgentMessage;
+  assistantMessageEvent: AssistantMessageEvent;
+}
+
+/** Assistant message body finalised — no further deltas for this msg. */
+export interface MessageEndEvent {
+  type: 'message_end';
+  message: AgentMessage;
+}
+
+/** A tool dispatch began. */
+export interface ToolExecutionStartEvent {
+  type: 'tool_execution_start';
+  toolCallId: string;
+  toolName: string;
+  args: unknown;
+}
+
+/**
+ * Tool reported progress — partial result before the call resolves.
+ * Optional and may not be emitted by every tool.
+ */
+export interface ToolExecutionUpdateEvent {
+  type: 'tool_execution_update';
+  toolCallId: string;
+  toolName: string;
+  args: unknown;
+  partialResult: unknown;
+}
+
+/** Tool dispatch resolved — `result` carries the final value. */
+export interface ToolExecutionEndEvent {
+  type: 'tool_execution_end';
+  toolCallId: string;
+  toolName: string;
+  result: unknown;
+  isError: boolean;
+}
+
+/**
+ * Discriminated union of all events an `Agent` runtime emits during a run.
+ *
+ * Consumers are expected to switch on `event.type`. New event variants may
+ * be added in non-breaking minor releases — handle the default case
+ * defensively.
+ */
+export type AgentEvent =
+  | AgentStartEvent
+  | AgentEndEvent
+  | TurnStartEvent
+  | TurnEndEvent
+  | MessageStartEvent
+  | MessageUpdateEvent
+  | MessageEndEvent
+  | ToolExecutionStartEvent
+  | ToolExecutionUpdateEvent
+  | ToolExecutionEndEvent;
+
+/** Type tag literal — handy for narrowing handlers. */
+export type AgentEventType = AgentEvent['type'];

+ 264 - 0
packages/agent-core/src/protocol/agent-message.ts

@@ -0,0 +1,264 @@
+/**
+ * Agent message protocol types.
+ *
+ * **Pure types only** — no implementations. Migrated from
+ * `packages/daemon/src/common/agent-protocol.ts` so the same shapes can be
+ * referenced by daemon (local) and cloud-runtime (remote) hosts without
+ * either side importing the other.
+ *
+ * `AgentMessage` represents a complete assistant turn (a closed message), and
+ * `AgentMessageChunk` represents a streaming delta. They were originally
+ * defined as part of the SSE wire format used by daemon → UI; runtime layers
+ * (cloud-runtime ExchangeSink) translate between this shape and the
+ * higher-level {@link RuntimeEvent} family.
+ *
+ * Phase 2 plan: this file becomes a pure structural representation while the
+ * canonical wire format unifies on `RuntimeEvent`. Until then,
+ * `AgentMessageChunk` is what daemon SSE pushes and what archon_server
+ * accepts (cloud-runtime adapts its `RuntimeEvent` stream into this shape
+ * before reporting upstream).
+ */
+
+/**
+ * Logical type tag for `RespData` envelope frames. Daemon SSE wraps each
+ * frame in `{ type, agent_message?, agent_message_chunk? }` and the type
+ * field tells the consumer which alternate is set.
+ */
+export const RespDataType = {
+  /** Complete `AgentMessage` (closed turn). */
+  AgentMessage: 2,
+  /** Streaming `AgentMessageChunk` (delta). */
+  AgentMessageChunk: 6,
+  /** Liveness ping — no payload. */
+  Heartbeat: 10,
+} as const;
+export type RespDataType = (typeof RespDataType)[keyof typeof RespDataType];
+
+/**
+ * Tool-call lifecycle stages emitted alongside an assistant message.
+ * `Preparing` / `Prepared` are the model-side argument-streaming phases
+ * (arguments still being generated / generated but not yet dispatched);
+ * `Start` is the host dispatching the tool for execution.
+ */
+export const ToolCallStatus = {
+  Start: 1,
+  Finished: 2,
+  Failed: 3,
+  Preparing: 4,
+  Prepared: 5,
+} as const;
+export type ToolCallStatus = (typeof ToolCallStatus)[keyof typeof ToolCallStatus];
+
+/**
+ * Tool invocation record carried by either {@link AgentMessage} or
+ * {@link AgentMessageChunk}. `tool_call_args` and `tool_call_result_data`
+ * are JSON-encoded strings so the wire format remains opaque to type
+ * narrowing consumers.
+ */
+export interface ToolCall {
+  tool_name: string;
+  tool_call_id: string;
+  tool_call_status: ToolCallStatus;
+  /** JSON string of the argument object the model produced. */
+  tool_call_args?: string;
+  /**
+   * Raw argument-JSON fragment streamed while the call is `Preparing`.
+   * Consumers accumulate fragments in chunk order; the concatenation
+   * converges on `tool_call_args` once the call leaves `Preparing`.
+   */
+  tool_call_args_delta?: string;
+  /** JSON string of the structured result returned by the tool runtime. */
+  tool_call_result_data?: string;
+  /** Tool execution wall-clock in ms; non-prod / debug only. */
+  tool_call_duration_ms?: number;
+  /** Plugin owners resolved by the turn-local runtime attribution snapshot. */
+  plugin_provenances?: import('@mavis/protocol').IPluginCapabilityProvenance[];
+}
+
+/**
+ * Marks display messages from flows not driven by the user. The UI uses these for lifecycle status
+ * outside model context, such as context compaction and parent-session Review activity.
+ *
+ * The local-runtime-v2 agent projection persists three compaction lifecycle states:
+ * - `compaction_start`: Compaction started (summary LLM call in progress). A running frame; the UI
+ *   displays "Compacting".
+ * - `compaction`: Terminal frame for successful compaction.
+ * - `compaction_failed`: Terminal frame for failed compaction. Besides live failures, orphaned
+ *   `compaction_start` frames left by a process crash are downgraded to this state on reload.
+ *
+ * The kind fully expresses whether compaction is running or terminal; do not include
+ * `finish_reason`. That field describes assistant response completion, and reusing it for
+ * compaction would confuse response terminal-state detection.
+ *
+ * All three frames share one `msg_id` (compactionId). Persistence upserts by msg_id, replacing the
+ * previous frame in place, so the session ultimately contains one compaction message whose kind is
+ * the latest state.
+ */
+export type MessageKind =
+  | 'compaction_start'
+  | 'compaction'
+  | 'compaction_failed'
+  | 'review_start'
+  | 'review_result'
+  | 'review_failed'
+  | 'review_aborted'
+  | 'review_interrupted';
+
+/** Speaker role on a message. */
+export const Role = {
+  User: 'user',
+  Assistant: 'assistant',
+} as const;
+export type Role = (typeof Role)[keyof typeof Role];
+
+/** Logical type of a single complete message — see UI message rendering. */
+export const MsgType = {
+  AgentContent: 1,
+  AgentToolCall: 2,
+  SystemEvent: 3,
+} as const;
+export type MsgType = (typeof MsgType)[keyof typeof MsgType];
+
+/** Token usage rolled into a turn-level message. */
+export interface TokenUsage {
+  total_tokens: number;
+  context_window: number;
+  /** Provider-reported prompt tokens for this physical request. */
+  input_tokens?: number;
+  /** Provider-reported generated tokens for this physical request. */
+  output_tokens?: number;
+  /**
+   * Physical provider request duration measured at the stream wrapper.
+   * Consumers use the elapsed duration directly instead of reconstructing
+   * throughput from downstream chunk timestamps, which may be buffered.
+   */
+  request_duration_ms?: number;
+  /**
+   * Cached prompt tokens reused across turns (provider-specific). Optional so
+   * legacy producers/consumers stay compatible; Pi providers surface this via
+   * `AssistantMessage.usage.cacheRead`.
+   */
+  cache_read?: number;
+  /**
+   * New cache writes recorded for this turn (provider-specific). Optional so
+   * legacy producers/consumers stay compatible; Pi providers surface this via
+   * `AssistantMessage.usage.cacheWrite`.
+   */
+  cache_write?: number;
+}
+
+export type ContextUsageSnapshotTrigger = 'terminal' | 'auto_compaction' | 'manual_compaction';
+
+export type ContextUsageToolCalibrationStatus = 'PENDING' | 'REMOTE' | 'EMPTY' | 'UNAVAILABLE';
+
+/**
+ * Ephemeral observability sidecar for a newly published Context Usage
+ * snapshot. UI consumes it only on the live stream and does not project it
+ * into Context Usage product state.
+ */
+export interface ContextUsageSnapshotTelemetry {
+  trigger: ContextUsageSnapshotTrigger;
+  turnId: string;
+  model: string;
+  localTokens: number;
+  providerTokens?: number;
+  divergenceRate?: number;
+  toolCalibrationStatus?: ContextUsageToolCalibrationStatus;
+}
+
+/** A streaming delta carrying partial text / thinking / tool-call updates. */
+export interface AgentMessageChunk {
+  msg_id: string;
+  parent_msg_id?: string;
+  msg_content?: string;
+  tool_calls?: ToolCall[];
+  thinking_content?: string;
+  thinking_duration_ms?: number;
+  chunk_index?: number;
+  finish?: boolean;
+  finish_reason?: string;
+  /** Unix-ms timestamp produced by the source runtime. */
+  timestamp?: number;
+  role?: Role;
+  /** Existing runtime turn identity. Historical frames may omit it. */
+  turn_id?: string;
+  /** Optional message classification — see {@link MessageKind}. */
+  kind?: MessageKind;
+}
+
+/** A complete (settled) assistant or user message. */
+export interface AgentMessage {
+  msg_id: string;
+  parent_msg_id?: string;
+  /** Unix-ms timestamp produced by the source runtime. */
+  timestamp?: number;
+  msg_content?: string;
+  msg_type?: MsgType;
+  role?: Role;
+  thinking_content?: string;
+  thinking_duration_ms?: number;
+  finish_reason?: string;
+  tool_calls?: ToolCall[];
+  attachments?: Array<{
+    type: 'file' | 'image';
+    file_path: string;
+    file_name: string;
+    mime_type: string;
+    desktop_path?: string;
+    data_url?: string;
+    asset_id?: string;
+  }>;
+  usage?: TokenUsage;
+  /** Electron-local current-context snapshot. Never sent to cloud runtime. */
+  context_usage?: {
+    contextWindowTokens: number;
+    usedTokens: number;
+    totalCountSource: 'LOCAL_ESTIMATE' | 'PROVIDER_USAGE_ANCHORED';
+    components: Array<{
+      kind:
+        | 'SYSTEM_PROMPT'
+        | 'MEMORY'
+        | 'TOOLS'
+        | 'SKILLS'
+        /** @deprecated Read-only compatibility for snapshots written before the six-category rollback. */
+        | 'PROJECT_INSTRUCTIONS'
+        | 'MESSAGES'
+        | 'OTHER';
+      tokens: number;
+    }>;
+  };
+  /** Live-only Guance reporting sidecar for `context_usage`. */
+  context_usage_telemetry?: ContextUsageSnapshotTelemetry;
+  source?: string;
+  source_message_id?: string;
+  /** Existing runtime turn identity. Historical rows may omit it. */
+  turn_id?: string;
+  origin?: unknown;
+  /** Optional message classification — see {@link MessageKind}. */
+  kind?: MessageKind;
+}
+
+/**
+ * Legacy aliases for {@link AgentMessageChunk} / {@link AgentMessage}.
+ *
+ * The harness-agent-era code imported these as `AgentMessageChunkProtocol`
+ * / `AgentMessageProtocol` (distinguishing the protocol-level shape from
+ * the channel-side `AgentMessage` envelope in `host/types.ts`). After
+ * absorbing harness-agent into agent-core, callers can use either name —
+ * the shapes are identical.
+ */
+export type AgentMessageChunkProtocol = AgentMessageChunk;
+export type AgentMessageProtocol = AgentMessage;
+
+/**
+ * SSE envelope frame used by daemon between
+ * `daemon → UI` and (Phase 1 only) `cloud-runtime → archon_server`.
+ *
+ * `agent_message` and `agent_message_chunk` are mutually exclusive — the
+ * `type` field disambiguates.
+ */
+export interface RespData {
+  type: RespDataType;
+  agent_message?: AgentMessage;
+  agent_message_chunk?: AgentMessageChunk;
+}

+ 28 - 0
packages/agent-core/src/protocol/context-usage.ts

@@ -0,0 +1,28 @@
+export const CONTEXT_USAGE_COMPONENT_KINDS = [
+  'SYSTEM_PROMPT',
+  'MEMORY',
+  'TOOLS',
+  'SKILLS',
+  'MESSAGES',
+  'OTHER',
+] as const;
+
+export type ContextUsageComponentKind = (typeof CONTEXT_USAGE_COMPONENT_KINDS)[number];
+
+export interface ContextUsageComponent {
+  readonly kind: ContextUsageComponentKind;
+  readonly tokens: number;
+}
+
+export interface ContextUsageSnapshot {
+  readonly contextWindowTokens: number;
+  readonly usedTokens: number;
+  readonly totalCountSource: 'LOCAL_ESTIMATE' | 'PROVIDER_USAGE_ANCHORED';
+  readonly components: readonly ContextUsageComponent[];
+}
+
+export interface ContextUsagePromptRange {
+  readonly kind: 'MEMORY' | 'SKILLS' | 'OTHER';
+  readonly startOffset: number;
+  readonly endOffset: number;
+}

+ 16 - 0
packages/agent-core/src/protocol/index.ts

@@ -0,0 +1,16 @@
+/**
+ * Protocol types shared by `agent-core` consumers.
+ *
+ * Three families:
+ * - `agent-message.ts` — `AgentMessage` / `AgentMessageChunk` (legacy SSE
+ *   wire format, kept for Phase 1 compatibility with daemon's UI clients).
+ * - `agent-event.ts` — `AgentEvent` (in-process event stream emitted by an
+ *   `Agent` runtime as it advances through an LLM turn).
+ * - `runtime-event.ts` — `RuntimeEvent` (canonical wire format, re-exported
+ *   from `@mavis/protocol`).
+ */
+
+export * from './agent-message.js';
+export * from './agent-event.js';
+export * from './context-usage.js';
+export * from './runtime-event.js';

+ 209 - 0
packages/agent-core/src/protocol/runtime-event.ts

@@ -0,0 +1,209 @@
+/**
+ * Runtime event surface — bridges `@mavis/protocol`'s thrift-generated
+ * shapes into the names agent-core internals use.
+ *
+ * The protocol package was regenerated from a thrift IDL via
+ * `@creditkarma/thrift-typescript`. The new surface differs from the old
+ * hand-written package in two important ways:
+ *
+ *  1. **Single struct + numeric enum** — instead of a discriminated union
+ *     of `StreamRespEvent | ActionRequiredEvent | …`, there is now one
+ *     `IRuntimeEvent` whose `type` is the numeric `RuntimeEventType` enum
+ *     and whose `payload` is one `IRuntimeEventPayload` struct with every
+ *     variant field optional. Narrow on `event.type === RuntimeEventType.X`
+ *     at consumption sites.
+ *  2. **No zod schemas** — `RuntimeEventSchema`, `RuntimeEventTypeSchema`
+ *     etc. are gone. We accept the loss of runtime validation here per
+ *     project owner directive.
+ *
+ * This file re-exports the protocol types under both their new `IXxx`
+ * names and the legacy `RuntimeXxx` aliases that the rest of agent-core
+ * already uses, plus defines small local types for the agent-core
+ * internal vocabulary (`RuntimeToolCall`, `RuntimeToolCallStatus`,
+ * `RuntimeRole`, `RuntimeMessageKind`, `RuntimeSessionStatus`,
+ * `RuntimeTerminalStatus`) that were never IDL-bound.
+ *
+ * Daemon usage hint
+ * -----------------
+ * Phase 1: daemon emits `AgentMessageChunk` (see {@link ./agent-message.ts}).
+ * Phase 2: daemon emits `RuntimeEvent` directly via `EventSink.pushRuntime`.
+ *
+ * Cloud impl hint
+ * ---------------
+ * Cloud-runtime always works with `RuntimeEvent` internally and translates
+ * into `AgentMessageChunk` only in `ExchangeSink` for Phase 1 compatibility.
+ */
+
+import type {
+  IPluginCapabilityProvenance,
+  IProtocolError,
+  IAttachment,
+  IRuntimeAction,
+  IRuntimeDebugTrace,
+  IRuntimeEvent,
+  IRuntimeStopReason,
+  IRuntimeUsage,
+} from '@mavis/protocol';
+
+// ── Legacy-name aliases for agent-core internal use ───────────────────
+//
+// The rest of agent-core (event-bridge, pi-turn-runner, tests) still
+// imports `RuntimeEvent`, `RuntimeAction`, … under the old names. Keep
+// them as type aliases over the generated `IXxx` shapes so call sites
+// don't have to flip every identifier in one pass.
+
+// ── Re-exports from the generated thrift surface ──────────────────────
+
+export type {
+  IAttachment,
+  IRuntimeAction,
+  IRuntimeDebugTrace,
+  IRuntimeEvent,
+  IRuntimeEventPayload,
+  IRuntimeStopReason,
+  IRuntimeUsage,
+} from '@mavis/protocol';
+
+export {
+  RuntimeActionType,
+  RuntimeDebugTraceLevel,
+  RuntimeEventStatus,
+  RuntimeEventType,
+  RuntimeStopReasonType,
+} from '@mavis/protocol';
+
+export { RUNTIME_EVENT_SCHEMA } from '@mavis/protocol';
+
+export type RuntimeEvent = IRuntimeEvent;
+export type RuntimeAction = IRuntimeAction;
+export type RuntimeStopReason = IRuntimeStopReason;
+export type RuntimeDebugTrace = IRuntimeDebugTrace;
+export type RuntimeUsage = IRuntimeUsage;
+export type RuntimeAttachment = IAttachment;
+
+// Variant aliases — the new protocol collapses the discriminated union
+// into one `IRuntimeEvent`, so each variant is just the same struct with
+// the type tag carrying the meaning. Narrow on `event.type === RuntimeEventType.X`.
+export type StreamRespEvent = IRuntimeEvent;
+export type ActionRequiredEvent = IRuntimeEvent;
+export type SessionStatusEvent = IRuntimeEvent;
+export type TurnTerminalEvent = IRuntimeEvent;
+export type DebugTraceEvent = IRuntimeEvent;
+
+// ── Agent-core-internal vocabulary ────────────────────────────────────
+//
+// These types describe shapes the agent-core bridge / pi-turn-runner
+// pass around in memory. They were never part of the IDL — the wire
+// format always lived under `IRuntimeEvent.payload.*` — so they stay
+// local to agent-core.
+
+export type RuntimeRole = 'user' | 'assistant' | 'system';
+export type RuntimeMessageKind =
+  | 'assistant'
+  | 'summary'
+  | 'compaction_start'
+  | 'compaction'
+  | 'compaction_failed'
+  | 'review_start'
+  | 'review_result'
+  | 'review_failed'
+  | 'review_aborted'
+  | 'review_interrupted';
+export type RuntimeSessionStatus = 'running' | 'waiting_action' | 'idle' | 'failed' | 'aborted';
+export type RuntimeTerminalStatus = 'completed' | 'failed' | 'aborted';
+/**
+ * `preparing` / `prepared` cover the model-side streaming phase: the LLM is
+ * still emitting the call's arguments (`preparing`) or has finished them
+ * (`prepared`) but the host has not dispatched the tool yet. `started`
+ * onwards is the host execution phase.
+ */
+export type RuntimeToolCallStatus =
+  | 'preparing'
+  | 'prepared'
+  | 'started'
+  | 'running'
+  | 'completed'
+  | 'failed';
+
+/**
+ * Runtime status errors carry product daemon status_code values on the wire
+ * (for example 50110 / 50111 / 50151), not only the low-cardinality thrift
+ * ProtocolErrorCode enum. Keep the JSON shape compatible with IProtocolError
+ * while allowing the broader numeric daemon code space.
+ */
+export interface RuntimeProtocolError extends Omit<IProtocolError, 'code'> {
+  code: number;
+}
+
+/**
+ * Tool-call state the bridge stages per assistant turn. Wire serialisation
+ * happens in {@link toolCallFromRuntime} (event-bridge/converters.ts) which
+ * folds `args` / `result` / `error` down to JSON strings on the legacy
+ * `ToolCall` envelope.
+ */
+export interface RuntimeToolCall {
+  tool_name: string;
+  tool_call_id: string;
+  status: RuntimeToolCallStatus;
+  args?: Record<string, unknown>;
+  /**
+   * Raw argument-JSON fragment for one `preparing` streaming update. Carried
+   * only on argument-streaming chunks; the consumer accumulates fragments in
+   * arrival order until the call leaves `preparing`.
+   */
+  args_text_delta?: string;
+  result?: unknown;
+  error?: RuntimeProtocolError;
+  /** Immutable Plugin owners of the capability actually used by this call. */
+  plugin_provenances?: IPluginCapabilityProvenance[];
+  /** Tool execution wall-clock in ms (bridge-measured); non-prod / debug only. */
+  duration_ms?: number;
+}
+
+/**
+ * Intermediate "runtime message" shape some host bridges build before
+ * they emit the wire-level `IRuntimeEvent`. Kept as an internal type
+ * because it's an agent-core ergonomic — the wire never carries it.
+ */
+export interface RuntimeMessage {
+  message_id: string;
+  parent_message_id?: string;
+  role: RuntimeRole;
+  message_kind?: RuntimeMessageKind;
+  text?: string;
+  thinking?: string;
+  tool_calls?: RuntimeToolCall[];
+  attachments?: RuntimeAttachment[];
+  usage?: RuntimeUsage;
+  source?: string;
+  origin?: unknown;
+  created_at_ms?: number;
+}
+
+/** Streaming delta companion to {@link RuntimeMessage}. */
+export interface RuntimeMessageChunk {
+  message_id: string;
+  parent_message_id?: string;
+  role?: 'assistant';
+  message_kind?: RuntimeMessageKind;
+  text_delta?: string;
+  thinking_delta?: string;
+  tool_calls?: RuntimeToolCall[];
+  chunk_index?: number;
+  created_at_ms?: number;
+}
+
+/** Draft variant used when the host hasn't yet allocated a final message id. */
+export interface RuntimeMessageDraft {
+  client_message_id?: string;
+  parent_message_id?: string;
+  role: RuntimeRole;
+  message_kind?: RuntimeMessageKind;
+  text?: string;
+  thinking?: string;
+  tool_calls?: RuntimeToolCall[];
+  attachments?: RuntimeAttachment[];
+  source?: string;
+  origin?: unknown;
+  created_at_ms?: number;
+}

+ 57 - 0
packages/agent-core/src/tools/bind.ts

@@ -0,0 +1,57 @@
+/**
+ * `@bindTool(def)`: TC39 stage-3 class decorator associating a `ToolDefinition` with a `ToolImpl`
+ * class. Different implementations of the same tool (`CloudBashTool` / `LocalBashTool`) can each
+ * use `@bindTool(BashToolDef)`.
+ *
+ * `toRuntimeTool(instance)`: Converts a decorated class instance to a `RuntimeTool`; PiTurnRunner
+ * accepts `RuntimeTool[]`.
+ *
+ * Decorator timing: TC39 stage-3 decorators run during class evaluation, so `CLASS_TO_DEF.set`
+ * completes when the decorated class's file is imported. `toRuntimeTool` can find the definition
+ * any time after instantiation.
+ */
+
+import type { TSchema } from '@sinclair/typebox';
+
+import type { RuntimeTool, ToolDefinition, ToolExecutionContext, ToolImpl } from './types.js';
+
+// eslint-disable-next-line @typescript-eslint/ban-types
+const CLASS_TO_DEF = new WeakMap<Function, ToolDefinition>();
+
+/**
+ * Class decorator associating a `ToolDefinition` with a `ToolImpl<S, TCtx>` implementation class.
+ *
+ * ```ts
+ * @bindTool(BashToolDef)
+ * export class CloudBashTool implements ToolImpl<typeof BashToolDef.schema, CloudRuntimeContext> {
+ *   async execute(ctx, input) { ... }   // input is inferred as Static<typeof BashToolDef.schema>
+ * }
+ * ```
+ */
+export function bindTool<S extends TSchema>(def: ToolDefinition<S>) {
+  return function <
+    TCtx extends ToolExecutionContext,
+    C extends new (...args: never[]) => ToolImpl<S, TCtx>,
+  >(target: C, _context: ClassDecoratorContext<C>): C {
+    // eslint-disable-next-line @typescript-eslint/ban-types
+    CLASS_TO_DEF.set(target as Function, def as ToolDefinition);
+    return target;
+  };
+}
+
+/**
+ * Converts a decorated class instance to a `RuntimeTool`. Throws for undecorated classes:
+ * forgetting `@bindTool` is a programming error and must not silently degrade.
+ */
+export function toRuntimeTool<
+  S extends TSchema = TSchema,
+  TCtx extends ToolExecutionContext = ToolExecutionContext,
+>(instance: ToolImpl<S, TCtx>): RuntimeTool<S, TCtx> {
+  const def = CLASS_TO_DEF.get(instance.constructor) as ToolDefinition<S> | undefined;
+  if (!def) {
+    throw new Error(
+      `toRuntimeTool: ${instance.constructor.name} is missing the @bindTool(...) decorator`,
+    );
+  }
+  return { def, impl: instance };
+}

+ 245 - 0
packages/agent-core/src/tools/builtin-defs.ts

@@ -0,0 +1,245 @@
+/**
+ * Builtin tool definitions: (name, description, schema) for the six LLM-facing tools.
+ *
+ * Schema fields mirror the read / write / edit / bash / grep schemas in
+ * `@earendil-works/pi-coding-agent`, ensuring identical LLM-visible argument shapes for pi builtins
+ * and host implementations. `find` / `ls` are excluded: neither is exposed to the LLM anywhere in
+ * the system (use grep / glob instead). `glob` has no same-named pi builtin, but corresponds to pi
+ * find (listing files by glob pattern).
+ *
+ * `read / write / edit / bash` share names with pi builtins. During assembly, PiTurnRunner
+ * automatically falls back to native pi `createXxxTool(cwd)` (local fs) when they are not
+ * explicitly bound; `grep / glob` have no fallback and must be registered explicitly.
+ */
+
+import { Type, type Static } from '@sinclair/typebox';
+
+import { prepareEditArguments } from './edit-prepare-arguments.js';
+import type { ToolDefinition } from './types.js';
+
+// ─── read ───────────────────────────────────────────────────────────────
+
+export const ReadToolDef = {
+  name: 'read',
+  executionMode: 'parallel',
+  description:
+    'Read the contents of a file. Supports text, images (jpg, png, gif, webp), and video (mp4, avi, mov, mkv) when the active model declares video support; otherwise video files are read as a text-only placeholder. Output is truncated to a maximum number of lines/bytes — use `offset` and `limit` to page through long files.',
+  schema: Type.Object({
+    path: Type.String({ description: 'Absolute or workspace-relative file path.' }),
+    offset: Type.Optional(
+      // 1-indexed to match the pi engine (`startLine = offset - 1`); this
+      // was mistakenly documented as 0-based before, which made models read
+      // off by one line. Keep in lockstep with Local/CloudReadToolDef.
+      Type.Number({
+        description:
+          'The line number to start reading from (1-indexed). Only provide if the file is too large to read at once.',
+      }),
+    ),
+    limit: Type.Optional(
+      Type.Number({
+        description:
+          'The number of lines to read. Only provide if the file is too large to read at once.',
+      }),
+    ),
+  }),
+} as const satisfies ToolDefinition;
+export type ReadToolInput = Static<typeof ReadToolDef.schema>;
+
+// ─── write ──────────────────────────────────────────────────────────────
+
+export const WriteToolDef = {
+  name: 'write',
+  executionMode: 'sequential',
+  // Guidance sentences (prefer-edit, read-before-overwrite, no line-number
+  // prefixes, no unsolicited docs) are kept in sync with Local/Cloud
+  // WriteToolDef. The wrapper-only result contract (true byte count,
+  // overwrote suffix) is intentionally absent: hosts consuming this base
+  // def fall back to the pi builtin, which does not implement it.
+  description:
+    'Write content to a file. Creates the file if it does not exist, overwrites it if it does, and creates parent directories as needed. ' +
+    'Prefer the edit tool for modifying existing files; only use write for new files or complete rewrites. ' +
+    'If the file already exists, read it first before overwriting; writing replaces the entire previous content. ' +
+    'Content is written literally, including line endings; NEVER include the line-number prefixes shown by the read tool. ' +
+    'Do not proactively create documentation files (*.md, README) unless explicitly requested.',
+  schema: Type.Object({
+    path: Type.String({ description: 'Absolute or workspace-relative file path.' }),
+    content: Type.String({ description: 'Full file content to write.' }),
+  }),
+} as const satisfies ToolDefinition;
+export type WriteToolInput = Static<typeof WriteToolDef.schema>;
+
+// ─── edit ───────────────────────────────────────────────────────────────
+
+const EditToolSchema = Type.Object({
+  path: Type.String({ description: 'Absolute or workspace-relative file path.' }),
+  edits: Type.Array(
+    Type.Object({
+      oldText: Type.String({ description: 'Exact existing text to replace.' }),
+      newText: Type.String({ description: 'Replacement text.' }),
+    }),
+    { description: 'Ordered list of replacements; all must succeed.' },
+  ),
+});
+
+export const EditToolDef = {
+  name: 'edit',
+  executionMode: 'sequential',
+  // Wording of everything from "Every `edits[].oldText`" onward is kept in
+  // lockstep with Local/CloudEditToolDef BY HAND — there is no
+  // edit-defs-contract test yet (only read/write have one), and the three
+  // edit schemas cannot be made identical (this def is pi-shaped
+  // {path, edits[]}, the wrappers are cc-shaped {file_path, old_string,...}).
+  // The compatibility shim is shared (edit-prepare-arguments.ts).
+  description:
+    'Edit a single file using exact text replacement. ' +
+    'Every `edits[].oldText` must match a unique, non-overlapping region of the original file, and all edits in one call apply atomically. ' +
+    'ALWAYS read the file with the read tool right before editing; do not construct oldText from memory, stale context, or guesses. ' +
+    'Copy oldText exactly from the file, including whitespace and indentation, and NEVER include the line-number prefixes shown by the read tool. ' +
+    'Keep each oldText as small as possible while still unique; do not pad it with large unchanged regions. ' +
+    'To change multiple places in one file, use a single call with multiple entries in edits[] instead of consecutive edit calls; each oldText is matched against the original file content, so edits must not overlap. ' +
+    'After a successful edit, re-read the file before editing it again.',
+  schema: EditToolSchema,
+  prepareArguments: prepareEditArguments,
+} as const satisfies ToolDefinition;
+export type EditToolInput = Static<typeof EditToolDef.schema>;
+
+// ─── bash ───────────────────────────────────────────────────────────────
+
+export const BashToolDef = {
+  name: 'bash',
+  executionMode: 'sequential',
+  description:
+    'Execute a bash command. Returns combined stdout + stderr after the command exits. Supports an optional timeout in seconds. ' +
+    'IMPORTANT: each invocation is stateless with respect to the working directory — every command starts from the same fixed default directory in a fresh shell, NOT from where a previous command left off. ' +
+    'A `cd` (e.g. `cd ..`) only affects that single command and does NOT change the cwd of the next call. ' +
+    'To operate in a different directory, scope it within the same call (e.g. `cd subdir && some-command`) or use absolute paths.',
+  schema: Type.Object({
+    command: Type.String({ description: 'Shell command line to execute.' }),
+    timeout: Type.Optional(
+      Type.Number({ description: 'Timeout in seconds. Default is host-defined.' }),
+    ),
+  }),
+} as const satisfies ToolDefinition;
+export type BashToolInput = Static<typeof BashToolDef.schema>;
+
+// ─── grep ───────────────────────────────────────────────────────────────
+
+export const GrepToolDef = {
+  name: 'grep',
+  executionMode: 'parallel',
+  description:
+    'Search file contents for a regex pattern using ripgrep. Respects .gitignore. Output is truncated to a maximum number of matches/bytes; long lines are clipped.',
+  schema: Type.Object({
+    pattern: Type.String({ description: 'Regex pattern (or literal if `literal=true`).' }),
+    path: Type.Optional(
+      Type.String({ description: 'Directory or file to search. Defaults to cwd.' }),
+    ),
+    glob: Type.Optional(
+      Type.String({ description: "File-glob filter, e.g. '*.ts' or '**/*.spec.ts'." }),
+    ),
+    ignoreCase: Type.Optional(Type.Boolean({ description: 'Case-insensitive search.' })),
+    literal: Type.Optional(
+      Type.Boolean({ description: 'Treat pattern as literal string instead of regex.' }),
+    ),
+    context: Type.Optional(
+      Type.Number({ description: 'Lines of context before and after each match.' }),
+    ),
+    limit: Type.Optional(Type.Number({ description: 'Maximum number of matches to return.' })),
+  }),
+} as const satisfies ToolDefinition;
+export type GrepToolInput = Static<typeof GrepToolDef.schema>;
+
+// ─── glob ───────────────────────────────────────────────────────────────
+
+export const GlobToolDef = {
+  name: 'glob',
+  executionMode: 'parallel',
+  description:
+    'Search for files by glob pattern. Respects .gitignore. Returns file paths relative to the search root, truncated when results exceed the limit.',
+  schema: Type.Object({
+    pattern: Type.String({ description: "Glob pattern, e.g. '**/*.ts' or 'src/**/*.tsx'." }),
+    path: Type.Optional(Type.String({ description: 'Search root. Defaults to cwd.' })),
+    limit: Type.Optional(Type.Number({ description: 'Maximum number of file paths to return.' })),
+  }),
+} as const satisfies ToolDefinition;
+export type GlobToolInput = Static<typeof GlobToolDef.schema>;
+
+// ─── todowrite ──────────────────────────────────────────────────────────
+
+/**
+ * `todowrite`: Session-scoped TODO list tool with the same name and shape as Pi / OpenCode /
+ * reference CLI `todowrite` / `TodoWrite` (status/priority use strings, not enums). The full
+ * description (When-to-Use / state machine) comes directly from OpenCode `todowrite.txt` to align
+ * expected model behavior with OSS models.
+ *
+ * Both paths (`daemon → ui` and `cloud-runtime → archon-server → archon-biz → ui`) render through
+ * the `packages/ui` branch for `MsgType.SystemEvent` + `eventType:'todo_updated'`. Each
+ * implementation constructs the event:
+ * - cloud-runtime `CloudTodoWriteTool`: Injects a `stream.resp` RuntimeEvent (RespData with
+ *   SystemEvent) through turn-event-context during tool execution, and calls `updateTodoState` to
+ *   update SR state.
+ * - Local daemon path: `framework-adapter/todo-extractor` extracts todos from tool_call args;
+ *   `ResponseBroadcaster.emitTodoUpdated` synthesizes and injects SSE.
+ */
+export const TodoWriteToolDef = {
+  name: 'todowrite',
+  executionMode: 'sequential',
+  description:
+    'Create or update a structured task list for a complex coding session. Use it for multi-step work or explicit user task lists; skip it for single, trivial, or purely conversational requests. Keep exactly one task in_progress and update statuses as work progresses.',
+  schema: Type.Object({
+    todos: Type.Array(
+      Type.Object({
+        content: Type.String({ description: 'Brief description of the task' }),
+        status: Type.String({
+          description: 'Current status of the task: pending, in_progress, completed, cancelled',
+        }),
+        priority: Type.String({
+          description: 'Priority level of the task: high, medium, low',
+        }),
+      }),
+      { description: 'The updated todo list' },
+    ),
+  }),
+} as const satisfies ToolDefinition;
+export type TodoWriteToolInput = Static<typeof TodoWriteToolDef.schema>;
+
+// ─── task ───────────────────────────────────────────────────────────────
+
+/**
+ * `task` —— Pi / OpenCode / reference-CLI-compatible sub-agent delegation tool.
+ * Description follows the upstream OpenCode task-tool shape, but omits
+ * unsupported background/resume/task_id guidance because cloud-runtime only
+ * supports synchronous one-shot sub-agent calls in this phase.
+ *
+ * Schema is exactly 3 required string fields, matching legacy local runtime's runtime
+ * shape after stripping background/model overrides:
+ *   - `description`: short 3-5 word label
+ *   - `prompt`: the actual task prompt for the sub-agent
+ *   - `subagent_type`: the requested sub-agent name (resolver looks this up)
+ *
+ * `additionalProperties:false` is intentionally NOT set — matches existing
+ * builtin-defs convention and pi/typebox silently drops unknown fields.
+ */
+export const TASK_TOOL_DESCRIPTION = `Launch a new agent to handle complex, multistep tasks autonomously.
+
+Use this for broad research, parallelizable investigation, or delegated implementation. Do not use it for targeted file reads, grep-style code searches, or work that is simpler to do directly.
+
+Each invocation is a stateless, one-shot task. The sub-agent's result is returned only to you, so summarize any user-visible outcome yourself.`;
+
+export const TaskToolDef = {
+  name: 'task',
+  executionMode: 'sequential',
+  description: TASK_TOOL_DESCRIPTION,
+  schema: Type.Object({
+    description: Type.String({
+      description: 'A short (3-5 words) description of the task',
+    }),
+    prompt: Type.String({
+      description: 'The task for the agent to perform',
+    }),
+    subagent_type: Type.String({
+      description: 'The type of specialized agent to use for this task',
+    }),
+  }),
+} as const satisfies ToolDefinition;
+export type TaskToolInput = Static<typeof TaskToolDef.schema>;

+ 59 - 0
packages/agent-core/src/tools/define.ts

@@ -0,0 +1,59 @@
+import type { Static, TSchema } from '@sinclair/typebox';
+
+import type {
+  RuntimeTool,
+  RuntimeToolSource,
+  ToolDefinition,
+  ToolExecutionContext,
+  ToolImpl,
+  ToolResult,
+} from './types.js';
+
+export type RuntimeToolDeclaration<
+  S extends TSchema,
+  TCtx extends ToolExecutionContext = ToolExecutionContext,
+> = ToolDefinition<S> & {
+  source?: RuntimeToolSource;
+  execute: ToolImpl<S, TCtx>['execute'];
+};
+
+/**
+ * Declare a platform-owned runtime tool as one object while preserving the
+ * protocol-level split between LLM-facing `def` and side-effecting `impl`.
+ */
+export function defineRuntimeTool<
+  S extends TSchema,
+  TCtx extends ToolExecutionContext = ToolExecutionContext,
+>(tool: RuntimeToolDeclaration<S, TCtx>): RuntimeTool<S, TCtx> {
+  const {
+    name,
+    label,
+    description,
+    schema,
+    promptGuidelines,
+    prepareArguments,
+    executionMode,
+    operationClassifier,
+    source,
+    execute,
+  } = tool;
+
+  const def: ToolDefinition<S> = {
+    name,
+    ...(label !== undefined ? { label } : {}),
+    description,
+    schema,
+    ...(promptGuidelines !== undefined ? { promptGuidelines } : {}),
+    ...(prepareArguments !== undefined
+      ? { prepareArguments: prepareArguments as (args: unknown) => Static<S> }
+      : {}),
+    ...(executionMode !== undefined ? { executionMode } : {}),
+    ...(operationClassifier !== undefined ? { operationClassifier } : {}),
+  };
+
+  return {
+    def,
+    impl: { execute },
+    ...(source !== undefined ? { source } : {}),
+  };
+}

+ 49 - 0
packages/agent-core/src/tools/edit-prepare-arguments.ts

@@ -0,0 +1,49 @@
+/**
+ * Shared compatibility shim for the `edit` tool's arguments.
+ *
+ * Two model-side quirks are normalized before schema validation runs (both
+ * mirror Pi 0.79's builtin edit tool shim):
+ *
+ * 1. Some models (MiniMax-M3 / GLM-5.1) emit `edits` as a JSON string even
+ *    though the public schema is `edits[]` — parse it back into an array.
+ * 2. Legacy single-edit input (`oldText` / `newText` at the top level) is
+ *    folded into `edits[]`.
+ *
+ * One shared implementation is referenced by all three edit defs
+ * (agent-core base, desktop, cloud); edit-defs-contract tests assert the
+ * references are identical.
+ */
+
+export interface PreparedEditArguments {
+  path: string;
+  edits: { oldText: string; newText: string }[];
+}
+
+export function prepareEditArguments(args: unknown): PreparedEditArguments {
+  if (!args || typeof args !== 'object' || Array.isArray(args)) {
+    return args as PreparedEditArguments;
+  }
+  const record = args as Record<string, unknown>;
+  let prepared = record;
+
+  if (typeof record.edits === 'string') {
+    try {
+      const parsed = JSON.parse(record.edits);
+      if (Array.isArray(parsed)) {
+        prepared = { ...record, edits: parsed };
+      }
+    } catch {
+      // Leave invalid JSON untouched so schema validation reports it normally.
+    }
+  }
+
+  if (typeof prepared.oldText !== 'string' || typeof prepared.newText !== 'string') {
+    return prepared as unknown as PreparedEditArguments;
+  }
+  const edits = Array.isArray(prepared.edits) ? [...prepared.edits] : [];
+  const { oldText: _oldText, newText: _newText, ...rest } = prepared;
+  return {
+    ...rest,
+    edits: [...edits, { oldText: prepared.oldText, newText: prepared.newText }],
+  } as PreparedEditArguments;
+}

+ 54 - 0
packages/agent-core/src/tools/index.ts

@@ -0,0 +1,54 @@
+/**
+ * `@mavis/agent-core/tools` —— tool protocol types, `defineRuntimeTool`, and
+ * decorated-class `bindTool` / `toRuntimeTool` helpers.
+ *
+ * Usage:
+ *
+ * ```ts
+ * import { defineRuntimeTool } from '@mavis/agent-core/tools';
+ * import { Type } from '@sinclair/typebox';
+ *
+ * const CloudBashTool = defineRuntimeTool({
+ *   name: 'bash',
+ *   description: 'Execute a command in the cloud sandbox executor.',
+ *   schema: Type.Object({ command: Type.String() }),
+ *   async execute(ctx, input, signal) { ... },
+ * });
+ * ```
+ */
+
+export type {
+  ToolDefinition,
+  ToolImpl,
+  ToolResult,
+  ToolResultContent,
+  ToolExecutionContext,
+  ToolExecutionMode,
+  ToolOperationClassifier,
+  RuntimeTool,
+  RuntimeToolSource,
+  ToolCallProvenanceResolutionInput,
+  ToolCallProvenanceResolver,
+} from './types.js';
+export { defineRuntimeTool, type RuntimeToolDeclaration } from './define.js';
+export { bindTool, toRuntimeTool } from './bind.js';
+export { prepareEditArguments, type PreparedEditArguments } from './edit-prepare-arguments.js';
+export { isRuntimeToolInputValid } from './input-validation.js';
+export {
+  ReadToolDef,
+  WriteToolDef,
+  EditToolDef,
+  BashToolDef,
+  GrepToolDef,
+  GlobToolDef,
+  TodoWriteToolDef,
+  TaskToolDef,
+  type ReadToolInput,
+  type WriteToolInput,
+  type EditToolInput,
+  type BashToolInput,
+  type GrepToolInput,
+  type GlobToolInput,
+  type TodoWriteToolInput,
+  type TaskToolInput,
+} from './builtin-defs.js';

+ 13 - 0
packages/agent-core/src/tools/input-validation.ts

@@ -0,0 +1,13 @@
+import { Value } from '@sinclair/typebox/value';
+
+import type { RuntimeTool } from './types.js';
+
+/** Revalidates a Hook-rewritten input against the authoritative runtime tool schema. */
+export function isRuntimeToolInputValid(
+  tools: readonly RuntimeTool[],
+  toolName: string,
+  value: Readonly<Record<string, unknown>>,
+): boolean {
+  const tool = tools.find((candidate) => candidate.def.name === toolName);
+  return Boolean(tool && Value.Check(tool.def.schema, value));
+}

+ 153 - 0
packages/agent-core/src/tools/types.ts

@@ -0,0 +1,153 @@
+/**
+ * Core tool contracts.
+ *
+ * `ToolDefinition`: The public tool contract. Its typebox schema (`TSchema`) is forwarded by
+ * PiTurnRunner to pi as `AgentTool.parameters` and used with `Static<S>` to infer strongly typed
+ * `ToolImpl.execute(input)` arguments. `prepareArguments` / `executionMode` map directly to the
+ * corresponding Pi 0.79.1 `AgentTool` fields.
+ *
+ * `ToolExecutionContext`: Minimal context built by the host each turn and captured by the pi
+ * `AgentTool` wrapper. Hosts can extend it (cloud-runtime's `CloudRuntimeContext` adds reporter /
+ * bizId / workspaceRoot, etc.) and declare their TCtx in `ToolImpl<S, TCtx>`. **Never** inject
+ * per-turn tool state through `AsyncLocalStorage`; the wrapper closure is the only injection point.
+ *
+ * `ToolImpl<S, TCtx>`: Tool implementation. The first argument to `execute(ctx, input, signal?,
+ * onUpdate?)` is per-turn context, captured by the host in `assembleAgentTools`. One ToolDefinition
+ * may have multiple ToolImpl implementations (cloud / local / mock), all sharing the same execute
+ * signature.
+ *
+ * `RuntimeTool<S, TCtx>` — the `(def, impl)` pair consumed by PiTurnRunner. New platform-owned
+ * tools should prefer declaring this object directly with `defineRuntimeTool(...)`, keeping the
+ * LLM-facing definition and runtime implementation co-located.
+ *
+ * `bindTool(def)` / `toRuntimeTool(instance)` remain available for decorated class implementations,
+ * but new code should prefer `defineRuntimeTool(...)`.
+ */
+
+import type { AgentToolUpdateCallback, ToolExecutionMode } from '@earendil-works/pi-agent-core';
+import type { ImageContent, TextContent } from '@earendil-works/pi-ai';
+import type { Static, TSchema } from '@sinclair/typebox';
+import type { IPluginCapabilityProvenance } from '@mavis/protocol';
+
+export type RuntimeToolSource = 'builtin' | 'builtin-matrix' | 'configured';
+
+export interface ToolCallProvenanceResolutionInput {
+  readonly phase: 'start' | 'end';
+  readonly toolName: string;
+  readonly args?: Readonly<Record<string, unknown>>;
+  readonly result?: unknown;
+  readonly isError?: boolean;
+}
+
+export type ToolCallProvenanceResolver = (
+  input: ToolCallProvenanceResolutionInput,
+) => readonly IPluginCapabilityProvenance[] | undefined;
+
+export interface VideoContent {
+  type: 'video';
+  data: string;
+  mimeType: string;
+}
+
+export type ToolResultContent = TextContent | ImageContent | VideoContent;
+
+/**
+ * Source-owned, bounded operation classification for observability.
+ *
+ * The tool owns its operation vocabulary; PiTurnRunner accepts a classifier
+ * result only when it belongs to this fixed allowlist. Unknown, malformed, or
+ * throwing classifications collapse to the shared `unknown` metric value.
+ */
+export interface ToolOperationClassifier {
+  readonly allowedValues: readonly string[];
+  classify(args: unknown): string | undefined;
+}
+
+export interface ToolDefinition<S extends TSchema = TSchema> {
+  readonly name: string;
+  readonly label?: string;
+  readonly description: string;
+  readonly schema: S;
+  readonly promptGuidelines?: readonly string[];
+  readonly prepareArguments?: (args: unknown) => Static<S>;
+  readonly executionMode?: ToolExecutionMode;
+  readonly operationClassifier?: ToolOperationClassifier;
+}
+
+/**
+ * Tool result. `content` stays compatible with pi `AgentToolResult` (a single text segment is
+ * sufficient); `details` holds structured byproducts (read by the UI / caller, not the LLM);
+ * `terminate` maps to Pi `AgentToolResult.terminate`; `output` is a legacy field retained only for
+ * migration compatibility. New code should use `details`.
+ */
+export interface ToolResult {
+  tool_name: string;
+  text: string;
+  content: ToolResultContent[];
+  isError?: boolean;
+  details?: Record<string, unknown>;
+  output?: Record<string, unknown>;
+  terminate?: boolean;
+}
+
+/**
+ * Per-turn execution context, captured by the host in each `AgentTool.execute` wrapper in
+ * `assembleAgentTools`. The minimal fields are sessionId / turnId. Hosts may extend it
+ * (cloud-runtime's `CloudRuntimeContext` adds `bizId` / `reporter` / `workspaceRoot`, etc.) and
+ * declare the corresponding TCtx in their `ToolImpl<S, TCtx>`.
+ */
+export interface ToolExecutionContext {
+  readonly sessionId: string;
+  readonly turnId: string;
+  /** Per-call id supplied by the provider loop; absent in older/direct test paths. */
+  readonly toolCallId?: string;
+  /** Assistant message carrying this tool call; supplied by the runtime bridge when available. */
+  readonly assistantMessageId?: string;
+}
+
+/**
+ * Tool implementation.
+ *
+ * `ctx` is host-built per-turn context injected via a closure in `assembleAgentTools`, not
+ * `AsyncLocalStorage`. `input` fields are strongly typed from ToolDefinition.schema using
+ * `Static<typeof schema>`.
+ *
+ * `signal` is an optional turn-level abort channel passed by pi `AgentTool.execute` and triggered
+ * when SessionController aborts. Potentially blocking implementations (HTTP, long-running sandbox
+ * shell, external resource IO) should forward it to fetch or check `signal.aborted` at key points,
+ * allowing SessionController to interrupt inflight operations instead of waiting for natural
+ * timeouts.
+ *
+ * `onUpdate` is Pi's partial tool result callback for streaming long-task progress. Implementations
+ * may ignore it; when used, partial results must share the semantics of the final
+ * `ToolResult.content/details`.
+ */
+export interface ToolImpl<
+  S extends TSchema = TSchema,
+  TCtx extends ToolExecutionContext = ToolExecutionContext,
+> {
+  execute(
+    ctx: TCtx,
+    input: Static<S>,
+    signal?: AbortSignal,
+    onUpdate?: AgentToolUpdateCallback<Record<string, unknown>>,
+  ): Promise<ToolResult>;
+}
+
+/**
+ * `(def, impl)` pair. PiTurnRunner only depends on this protocol shape; it
+ * does not care whether a tool comes from cloud, desktop, mobile, or a test
+ * host.
+ */
+export interface RuntimeTool<
+  S extends TSchema = TSchema,
+  TCtx extends ToolExecutionContext = ToolExecutionContext,
+> {
+  readonly def: ToolDefinition<S>;
+  readonly impl: ToolImpl<S, TCtx>;
+  readonly source?: RuntimeToolSource;
+  /** Turn-local display attribution; never affects execution or permission semantics. */
+  readonly toolCallProvenanceResolver?: ToolCallProvenanceResolver;
+}
+
+export type { ToolExecutionMode };

+ 998 - 0
packages/agent-core/test/unit/event-bridge/converters.test.ts

@@ -0,0 +1,998 @@
+import { describe, it, expect } from 'vitest';
+import {
+  buildAbortedTerminalStatusEvent,
+  buildCompletedAssistantMessage,
+  buildCompletedTerminalStatusEvent,
+  buildDebugTraceEvent,
+  buildFailedTerminalStatusEvent,
+  buildFinishChunk,
+  buildRunningSessionStatusEvent,
+  buildStreamRespEvent,
+  buildTextDeltaChunk,
+  buildThinkingDeltaChunk,
+  buildToolCallChunk,
+  extractAssistantErrorMessage,
+  extractAssistantStopReason,
+  extractAssistantText,
+  extractAssistantThinking,
+  extractAssistantToolCalls,
+  extractAssistantUsage,
+  extractDeltaUpdate,
+  extractFinalAssistantText,
+  extractFinalAssistantUsageFromBuffer,
+  isAssistantError,
+  toolCallFromRuntime,
+} from '../../../src/event-bridge/converters.js';
+import { MsgType, RespDataType, ToolCallStatus } from '../../../src/protocol/agent-message.js';
+import { RUNTIME_EVENT_SCHEMA } from '../../../src/protocol/runtime-event.js';
+import { buildRuntimeWarningEvent } from '../../../src/event-bridge/runtime-warning.js';
+import type { RuntimeEvent, StreamRespEvent } from '../../../src/protocol/runtime-event.js';
+import {
+  ProtocolErrorCode,
+  RuntimeDebugTraceLevel,
+  RuntimeEventStatus,
+  RuntimeEventType,
+  RuntimeStopReasonType,
+} from '@mavis/protocol';
+
+const fixture = {
+  sessionId: 'sess-1',
+  turnId: 'turn-1',
+  msgId: 'msg-1',
+  nowMs: 1_700_000_000_000,
+};
+
+describe('event-bridge/converters: extractDeltaUpdate', () => {
+  it('returns text delta for text_delta event', () => {
+    expect(extractDeltaUpdate({ type: 'text_delta', delta: 'hello', contentIndex: 0 })).toEqual({
+      kind: 'text',
+      delta: 'hello',
+    });
+  });
+
+  it('returns thinking delta for thinking_delta event', () => {
+    expect(
+      extractDeltaUpdate({ type: 'thinking_delta', delta: 'hmm', contentIndex: 0 }),
+    ).toEqual({
+      kind: 'thinking',
+      delta: 'hmm',
+    });
+  });
+
+  it('returns undefined for unrelated event types', () => {
+    expect(extractDeltaUpdate({ type: 'start' })).toBeUndefined();
+    expect(extractDeltaUpdate({ type: 'tool_call_start', delta: 'x' })).toBeUndefined();
+  });
+
+  it('returns undefined when payload is not an object', () => {
+    expect(extractDeltaUpdate(null)).toBeUndefined();
+    expect(extractDeltaUpdate(undefined)).toBeUndefined();
+    expect(extractDeltaUpdate('text_delta')).toBeUndefined();
+    expect(extractDeltaUpdate(42)).toBeUndefined();
+  });
+
+  it('returns undefined when delta is not a string', () => {
+    expect(extractDeltaUpdate({ type: 'text_delta', delta: 42 })).toBeUndefined();
+  });
+});
+
+describe('event-bridge/converters: extractAssistantText / Thinking / ToolCalls', () => {
+  it('joins all text blocks into a single string', () => {
+    const message = {
+      role: 'assistant',
+      content: [
+        { type: 'text', text: 'Hello' },
+        { type: 'text', text: ' world' },
+        { type: 'thinking', thinking: 'hidden' },
+      ],
+    };
+    expect(extractAssistantText(message)).toBe('Hello world');
+  });
+
+  it('returns empty string when content is missing or non-array', () => {
+    expect(extractAssistantText({})).toBe('');
+    expect(extractAssistantText(null)).toBe('');
+    expect(extractAssistantText({ content: 42 })).toBe('');
+  });
+
+  it('returns string content directly when content is a string', () => {
+    expect(extractAssistantText({ content: 'plain string' })).toBe('plain string');
+  });
+
+  it('joins all thinking blocks', () => {
+    const message = {
+      content: [
+        { type: 'thinking', thinking: 'plan' },
+        { type: 'text', text: 'visible' },
+        { type: 'thinking', thinking: ' more' },
+      ],
+    };
+    expect(extractAssistantThinking(message)).toBe('plan more');
+  });
+
+  it('returns empty thinking when content is a string (no thinking blocks)', () => {
+    expect(extractAssistantThinking({ content: 'plain' })).toBe('');
+  });
+
+  it('extracts toolCall blocks into RuntimeToolCall[]', () => {
+    const message = {
+      content: [
+        { type: 'text', text: 'plan' },
+        { type: 'toolCall', id: 'call-1', name: 'read', arguments: { path: '/x' } },
+        { type: 'toolCall', id: 'call-2', name: 'bash', arguments: { command: 'ls' } },
+      ],
+    };
+    expect(extractAssistantToolCalls(message)).toEqual([
+      { tool_name: 'read', tool_call_id: 'call-1', status: 'started', args: { path: '/x' } },
+      { tool_name: 'bash', tool_call_id: 'call-2', status: 'started', args: { command: 'ls' } },
+    ]);
+  });
+
+  it('omits args field when arguments is missing or not an object', () => {
+    const message = {
+      content: [
+        { type: 'toolCall', id: 'call-1', name: 'noop' },
+        { type: 'toolCall', id: 'call-2', name: 'foo', arguments: 'bad-args' },
+      ],
+    };
+    expect(extractAssistantToolCalls(message)).toEqual([
+      { tool_name: 'noop', tool_call_id: 'call-1', status: 'started' },
+      { tool_name: 'foo', tool_call_id: 'call-2', status: 'started' },
+    ]);
+  });
+
+  it('returns empty list for invalid input', () => {
+    expect(extractAssistantToolCalls(null)).toEqual([]);
+    expect(extractAssistantToolCalls({ content: 'not array' })).toEqual([]);
+    expect(extractAssistantToolCalls({ content: [{ type: 'toolCall', id: 42 }] })).toEqual([]);
+  });
+});
+
+describe('event-bridge/converters: isAssistantError / extractAssistantErrorMessage / extractAssistantStopReason', () => {
+  it('isAssistantError true when role=assistant and stopReason=error', () => {
+    expect(isAssistantError({ role: 'assistant', stopReason: 'error' })).toBe(true);
+  });
+
+  it('isAssistantError false when stopReason !== error', () => {
+    expect(isAssistantError({ role: 'assistant', stopReason: 'stop' })).toBe(false);
+  });
+
+  it('isAssistantError false when role !== assistant', () => {
+    expect(isAssistantError({ role: 'user', stopReason: 'error' })).toBe(false);
+  });
+
+  it('isAssistantError false for invalid input', () => {
+    expect(isAssistantError(null)).toBe(false);
+    expect(isAssistantError(undefined)).toBe(false);
+    expect(isAssistantError('not-a-message')).toBe(false);
+  });
+
+  it('extractAssistantErrorMessage returns string when present', () => {
+    expect(extractAssistantErrorMessage({ errorMessage: 'rate limited' })).toBe('rate limited');
+  });
+
+  it('extractAssistantErrorMessage returns undefined when missing', () => {
+    expect(extractAssistantErrorMessage({})).toBeUndefined();
+    expect(extractAssistantErrorMessage(null)).toBeUndefined();
+    expect(extractAssistantErrorMessage({ errorMessage: '' })).toBeUndefined();
+  });
+
+  it('extractAssistantStopReason returns string when present', () => {
+    expect(extractAssistantStopReason({ stopReason: 'stop' })).toBe('stop');
+    expect(extractAssistantStopReason({ stopReason: 'toolUse' })).toBe('toolUse');
+  });
+
+  it('extractAssistantStopReason returns undefined when missing or empty', () => {
+    expect(extractAssistantStopReason({})).toBeUndefined();
+    expect(extractAssistantStopReason({ stopReason: '' })).toBeUndefined();
+    expect(extractAssistantStopReason(null)).toBeUndefined();
+  });
+});
+
+describe('event-bridge/converters: toolCallFromRuntime', () => {
+  it('maps started status to ToolCallStatus.Start', () => {
+    expect(
+      toolCallFromRuntime({
+        tool_name: 'bash',
+        tool_call_id: 'c1',
+        status: 'started',
+        args: { command: 'ls' },
+      }),
+    ).toEqual({
+      tool_name: 'bash',
+      tool_call_id: 'c1',
+      tool_call_status: ToolCallStatus.Start,
+      tool_call_args: '{"command":"ls"}',
+    });
+  });
+
+  it('maps completed status to ToolCallStatus.Finished and serialises result', () => {
+    expect(
+      toolCallFromRuntime({
+        tool_name: 'read',
+        tool_call_id: 'c2',
+        status: 'completed',
+        result: { lines: 10 },
+      }),
+    ).toEqual({
+      tool_name: 'read',
+      tool_call_id: 'c2',
+      tool_call_status: ToolCallStatus.Finished,
+      tool_call_result_data: '{"lines":10}',
+    });
+  });
+
+  it('maps failed status to ToolCallStatus.Failed and wraps error', () => {
+    const out = toolCallFromRuntime({
+      tool_name: 'bash',
+      tool_call_id: 'c3',
+      status: 'failed',
+      error: { code: ProtocolErrorCode.INTERNAL_ERROR, message: 'boom' },
+    });
+    expect(out.tool_call_status).toBe(ToolCallStatus.Failed);
+    expect(out.tool_call_result_data).toBe('{"error":{"code":50001,"message":"boom"}}');
+  });
+
+  it('maps `running` status defensively to Start', () => {
+    expect(toolCallFromRuntime({ tool_name: 'x', tool_call_id: 'c', status: 'running' })).toEqual({
+      tool_name: 'x',
+      tool_call_id: 'c',
+      tool_call_status: ToolCallStatus.Start,
+    });
+  });
+
+  it('serialises duration_ms onto tool_call_duration_ms when present', () => {
+    expect(
+      toolCallFromRuntime({
+        tool_name: 'read',
+        tool_call_id: 'c4',
+        status: 'completed',
+        result: { lines: 1 },
+        duration_ms: 321,
+      }),
+    ).toEqual({
+      tool_name: 'read',
+      tool_call_id: 'c4',
+      tool_call_status: ToolCallStatus.Finished,
+      tool_call_result_data: '{"lines":1}',
+      tool_call_duration_ms: 321,
+    });
+  });
+
+  it('omits tool_call_duration_ms when duration_ms is absent', () => {
+    const out = toolCallFromRuntime({ tool_name: 'x', tool_call_id: 'c5', status: 'completed' });
+    expect(out).not.toHaveProperty('tool_call_duration_ms');
+  });
+
+  it('strips inline image base64 from tool_call_result_data', () => {
+    const bigBase64 = 'A'.repeat(3_500_000); // 3.5 MB base64 payload
+    const result = toolCallFromRuntime({
+      tool_name: 'read',
+      tool_call_id: 'c-image',
+      status: 'completed',
+      result: {
+        content: [
+          { type: 'text', text: 'Read image file [image/png]' },
+          { type: 'image', data: bigBase64, mimeType: 'image/png' },
+        ],
+        details: {},
+      },
+    });
+    const decoded = JSON.parse(result.tool_call_result_data!);
+    expect(decoded.content).toEqual([
+      { type: 'text', text: 'Read image file [image/png]' },
+    ]);
+    expect(result.tool_call_result_data!.length).toBeLessThan(200);
+  });
+
+  it('strips inline video base64 (read tool image block with video/* mime)', () => {
+    const bigBase64 = 'B'.repeat(12_000_000); // 12 MB video payload
+    const result = toolCallFromRuntime({
+      tool_name: 'read',
+      tool_call_id: 'c-video',
+      status: 'completed',
+      result: {
+        content: [
+          { type: 'text', text: 'Read video file [video/mp4]' },
+          { type: 'image', data: bigBase64, mimeType: 'video/mp4' },
+        ],
+        details: { media: { kind: 'video', mime_type: 'video/mp4', size_bytes: 9_000_000 } },
+      },
+    });
+    const decoded = JSON.parse(result.tool_call_result_data!);
+    expect(decoded.content).toEqual([
+      { type: 'text', text: 'Read video file [video/mp4]' },
+    ]);
+    expect(decoded.details).toEqual({
+      media: { kind: 'video', mime_type: 'video/mp4', size_bytes: 9_000_000 },
+    });
+    expect(result.tool_call_result_data!.length).toBeLessThan(400);
+  });
+
+  it('leaves text-only results untouched', () => {
+    const out = toolCallFromRuntime({
+      tool_name: 'bash',
+      tool_call_id: 'c-bash',
+      status: 'completed',
+      result: { content: [{ type: 'text', text: 'hi' }], details: { ok: true } },
+    });
+    expect(out.tool_call_result_data).toBe(
+      JSON.stringify({ content: [{ type: 'text', text: 'hi' }], details: { ok: true } }),
+    );
+  });
+
+  it('does NOT mutate the original tc.result object (pi retains it for LLM ctx)', () => {
+    const bigBase64 = 'C'.repeat(2_000_000);
+    const original = {
+      content: [
+        { type: 'text', text: 'Read image file [image/jpeg]' },
+        { type: 'image', data: bigBase64, mimeType: 'image/jpeg' },
+      ],
+      details: {},
+    };
+    toolCallFromRuntime({
+      tool_name: 'read',
+      tool_call_id: 'c-mut',
+      status: 'completed',
+      result: original,
+    });
+    expect(original.content).toHaveLength(2);
+    expect((original.content[1] as { data: string }).data).toBe(bigBase64);
+  });
+});
+
+describe('event-bridge/converters: stream-event builders', () => {
+  it('buildRuntimeWarningEvent uses a SystemEvent envelope rather than model history content', () => {
+    const event = buildRuntimeWarningEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'warning-1',
+      runtimeSeq: 1,
+      message: 'A Plugin Hook failed open.',
+      source: 'plugin-hook',
+      hookEvent: 'PreToolUse',
+      nowMs: 123,
+    });
+    const envelope = JSON.parse(event.payload.stream_resp) as {
+      type: number;
+      agent_message: { msg_type: number; msg_content: string };
+    };
+
+    expect(envelope.type).toBe(RespDataType.AgentMessage);
+    expect(envelope.agent_message.msg_type).toBe(MsgType.SystemEvent);
+    expect(JSON.parse(envelope.agent_message.msg_content)).toEqual({
+      eventType: 'runtime.warning',
+      message: 'A Plugin Hook failed open.',
+      source: 'plugin-hook',
+      hookEvent: 'PreToolUse',
+    });
+  });
+
+  it('buildStreamRespEvent serialises RespData into payload.stream_resp', () => {
+    const ev = buildStreamRespEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'evt-1',
+      runtimeSeq: 7,
+      respData: {
+        type: RespDataType.AgentMessageChunk,
+        agent_message_chunk: { msg_id: fixture.msgId, chunk_index: 0, msg_content: 'hi' },
+      },
+    });
+    expect(ev.schema).toBe(RUNTIME_EVENT_SCHEMA);
+    expect(ev.type).toBe(RuntimeEventType.STREAM_RESP);
+    expect(ev.event_id).toBe('evt-1');
+    expect(ev.runtime_seq).toBe(7);
+    expect(typeof ev.payload.stream_resp).toBe('string');
+    expect(ev.payload).toEqual({ stream_resp: ev.payload.stream_resp });
+    const inner = JSON.parse(ev.payload.stream_resp!);
+    expect(inner).toEqual({
+      type: RespDataType.AgentMessageChunk,
+      agent_message_chunk: { msg_id: fixture.msgId, chunk_index: 0, msg_content: 'hi' },
+    });
+    expect(inner).not.toHaveProperty('schema');
+    expect(inner).not.toHaveProperty('event_id');
+    expect(inner).not.toHaveProperty('payload');
+  });
+
+  it('buildTextDeltaChunk packs delta as msg_content with role=assistant', () => {
+    const ev = buildTextDeltaChunk({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'evt-2',
+      runtimeSeq: 1,
+      msgId: fixture.msgId,
+      chunkIndex: 0,
+      delta: 'hello',
+      nowMs: fixture.nowMs,
+    });
+    const respData = JSON.parse(ev.payload.stream_resp!);
+    expect(respData.type).toBe(RespDataType.AgentMessageChunk);
+    expect(respData.agent_message_chunk.msg_content).toBe('hello');
+    expect(respData.agent_message_chunk.role).toBe('assistant');
+    expect(respData.agent_message_chunk.turn_id).toBe(fixture.turnId);
+    expect(respData.agent_message_chunk.timestamp).toBe(fixture.nowMs);
+  });
+
+  it('buildThinkingDeltaChunk packs delta as thinking_content', () => {
+    const ev = buildThinkingDeltaChunk({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'evt-3',
+      runtimeSeq: 2,
+      msgId: fixture.msgId,
+      chunkIndex: 1,
+      delta: 'thought',
+      nowMs: fixture.nowMs,
+    });
+    const respData = JSON.parse(ev.payload.stream_resp!);
+    expect(respData.agent_message_chunk.thinking_content).toBe('thought');
+    expect(respData.agent_message_chunk.msg_content).toBeUndefined();
+  });
+
+  it('buildToolCallChunk wraps a single RuntimeToolCall', () => {
+    const ev = buildToolCallChunk({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'evt-4',
+      runtimeSeq: 3,
+      msgId: fixture.msgId,
+      chunkIndex: 2,
+      toolCall: {
+        tool_name: 'read',
+        tool_call_id: 'tc-1',
+        status: 'started',
+        args: { path: '/x' },
+      },
+      nowMs: fixture.nowMs,
+    });
+    const respData = JSON.parse(ev.payload.stream_resp!);
+    expect(respData.agent_message_chunk.tool_calls).toHaveLength(1);
+    expect(respData.agent_message_chunk.tool_calls[0]).toEqual({
+      tool_name: 'read',
+      tool_call_id: 'tc-1',
+      tool_call_status: ToolCallStatus.Start,
+      tool_call_args: '{"path":"/x"}',
+    });
+  });
+
+  it('buildFinishChunk emits a finish=true chunk with optional reason and thinking_duration_ms', () => {
+    const ev = buildFinishChunk({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'evt-5',
+      runtimeSeq: 4,
+      msgId: fixture.msgId,
+      chunkIndex: 3,
+      finishReason: 'stop',
+      thinkingDurationMs: 1234,
+      nowMs: fixture.nowMs,
+    });
+    const respData = JSON.parse(ev.payload.stream_resp!);
+    expect(respData.agent_message_chunk.finish).toBe(true);
+    expect(respData.agent_message_chunk.finish_reason).toBe('stop');
+    expect(respData.agent_message_chunk.thinking_duration_ms).toBe(1234);
+  });
+
+  it('buildFinishChunk omits finish_reason and thinking_duration_ms when not provided', () => {
+    const ev = buildFinishChunk({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'evt-6',
+      runtimeSeq: 5,
+      msgId: fixture.msgId,
+      chunkIndex: 4,
+      nowMs: fixture.nowMs,
+    });
+    const respData = JSON.parse(ev.payload.stream_resp!);
+    expect(respData.agent_message_chunk.finish).toBe(true);
+    expect(respData.agent_message_chunk.finish_reason).toBeUndefined();
+    expect(respData.agent_message_chunk.thinking_duration_ms).toBeUndefined();
+  });
+
+  it('buildCompletedAssistantMessage emits an AgentMessage with text/thinking/tools/usage', async () => {
+    const ev = await buildCompletedAssistantMessage({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'evt-7',
+      runtimeSeq: 6,
+      msgId: fixture.msgId,
+      text: 'final text',
+      thinking: 'final thinking',
+      thinkingDurationMs: 500,
+      finishReason: 'stop',
+      toolCalls: [{ tool_name: 'read', tool_call_id: 'tc-1', status: 'completed', result: 42 }],
+      usage: { total_tokens: 100, context_window: 200_000 },
+      nowMs: fixture.nowMs,
+    });
+    const respData = JSON.parse(ev.payload.stream_resp!);
+    expect(respData.type).toBe(RespDataType.AgentMessage);
+    expect(respData.agent_message.msg_content).toBe('final text');
+    expect(respData.agent_message.turn_id).toBe(fixture.turnId);
+    expect(respData.agent_message.thinking_content).toBe('final thinking');
+    expect(respData.agent_message.thinking_duration_ms).toBe(500);
+    expect(respData.agent_message.finish_reason).toBe('stop');
+    expect(respData.agent_message.tool_calls).toHaveLength(1);
+    expect(respData.agent_message.tool_calls[0].tool_call_status).toBe(ToolCallStatus.Finished);
+    expect(respData.agent_message.usage).toEqual({ total_tokens: 100, context_window: 200_000 });
+  });
+
+  it('buildCompletedAssistantMessage omits optional fields when missing', async () => {
+    const ev = await buildCompletedAssistantMessage({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'evt-8',
+      runtimeSeq: 7,
+      msgId: fixture.msgId,
+      text: 'plain',
+      nowMs: fixture.nowMs,
+    });
+    const respData = JSON.parse(ev.payload.stream_resp!);
+    expect(respData.agent_message.thinking_content).toBeUndefined();
+    expect(respData.agent_message.tool_calls).toBeUndefined();
+    expect(respData.agent_message.usage).toBeUndefined();
+    expect(respData.agent_message.thinking_duration_ms).toBeUndefined();
+  });
+
+  it('buildCompletedAssistantMessage applies respDataTransform when supplied', async () => {
+    let captured: { sessionId: string; turnId: string } | undefined;
+    const ev = await buildCompletedAssistantMessage(
+      {
+        sessionId: fixture.sessionId,
+        turnId: fixture.turnId,
+        eventId: 'evt-9',
+        runtimeSeq: 8,
+        msgId: fixture.msgId,
+        text: 'orig',
+        nowMs: fixture.nowMs,
+      },
+      async (respData, ctx) => {
+        captured = ctx;
+        if (!respData.agent_message) return respData;
+        return {
+          ...respData,
+          agent_message: { ...respData.agent_message, msg_content: 'rewritten' },
+        };
+      },
+    );
+    const respData = JSON.parse(ev.payload.stream_resp!);
+    expect(respData.agent_message.msg_content).toBe('rewritten');
+    expect(captured).toEqual({ sessionId: fixture.sessionId, turnId: fixture.turnId });
+  });
+
+  it('buildCompletedAssistantMessage falls back to original RespData when transform throws', async () => {
+    const ev = await buildCompletedAssistantMessage(
+      {
+        sessionId: fixture.sessionId,
+        turnId: fixture.turnId,
+        eventId: 'evt-10',
+        runtimeSeq: 9,
+        msgId: fixture.msgId,
+        text: 'unchanged',
+        nowMs: fixture.nowMs,
+      },
+      () => {
+        throw new Error('transform boom');
+      },
+    );
+    const respData = JSON.parse(ev.payload.stream_resp!);
+    expect(respData.agent_message.msg_content).toBe('unchanged');
+  });
+});
+
+describe('event-bridge/converters: terminal pair builders', () => {
+  it('buildRunningSessionStatusEvent returns running status', () => {
+    const status = buildRunningSessionStatusEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 's-running',
+    });
+    expect(status.type).toBe(RuntimeEventType.SESSION_STATUS);
+    expect(status.payload.status).toBe(RuntimeEventStatus.RUNNING);
+    expect(status.payload.stop_reason).toBeUndefined();
+  });
+
+  it('buildCompletedTerminalStatusEvent returns completed status', () => {
+    const status = buildCompletedTerminalStatusEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      statusEventId: 's-1',
+    });
+    expect(status.type).toBe(RuntimeEventType.SESSION_STATUS);
+    expect(status.payload.status).toBe(RuntimeEventStatus.COMPLETED);
+    expect(status.payload.stop_reason).toEqual({ type: RuntimeStopReasonType.END_TURN });
+  });
+
+  it('buildCompletedTerminalStatusEvent includes optional usage when supplied', () => {
+    const status = buildCompletedTerminalStatusEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      statusEventId: 's-1',
+      terminalUsage: { input_tokens: 10, output_tokens: 20, total_tokens: 30 },
+    });
+    expect(status.payload.usage).toEqual({ input_tokens: 10, output_tokens: 20, total_tokens: 30 });
+  });
+
+  it('buildAbortedTerminalStatusEvent returns aborted status', () => {
+    const status = buildAbortedTerminalStatusEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      statusEventId: 's-2',
+    });
+    expect(status.payload.status).toBe(RuntimeEventStatus.ABORTED);
+    expect(status.payload.stop_reason).toEqual({
+      type: RuntimeStopReasonType.ABORT,
+      message: 'aborted',
+    });
+  });
+
+  it('buildFailedTerminalStatusEvent packs message into stop_reason and protocol error', () => {
+    const status = buildFailedTerminalStatusEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      statusEventId: 's-3',
+      message: 'kaboom',
+    });
+    expect(status.payload.status).toBe(RuntimeEventStatus.FAILED);
+    expect(status.payload.stop_reason).toEqual({
+      type: RuntimeStopReasonType.ERROR,
+      message: 'kaboom',
+    });
+    expect(status.payload.error).toEqual({ code: ProtocolErrorCode.INTERNAL_ERROR, message: 'kaboom' });
+  });
+
+  it('buildFailedTerminalStatusEvent forwards explicit protocol error code', () => {
+    const status = buildFailedTerminalStatusEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      statusEventId: 's-4',
+      message: 'denied',
+      error: { code: ProtocolErrorCode.INTERNAL_ERROR, message: 'denied' },
+    });
+    expect(status.payload.error?.code).toBe(ProtocolErrorCode.INTERNAL_ERROR);
+  });
+});
+
+describe('event-bridge/converters: buildDebugTraceEvent', () => {
+  it('packs phase + level + attrs + duration_ms (attrs JSON-stringified into attrs_json)', () => {
+    const ev = buildDebugTraceEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'dbg-1',
+      phase: 'tool_call_started',
+      message: 'started',
+      level: 'info',
+      attrs: { tool: 'read', n: 1, flag: true },
+      durationMs: 42,
+    });
+    expect(ev.type).toBe(RuntimeEventType.DEBUG_TRACE);
+    expect(ev.payload).toBeDefined();
+    if (ev.type === RuntimeEventType.DEBUG_TRACE) {
+      expect(ev.payload.trace!.phase).toBe('tool_call_started');
+      expect(ev.payload.trace!.level).toBe(RuntimeDebugTraceLevel.INFO);
+      expect(ev.payload.trace!.message).toBe('started');
+      expect(JSON.parse(ev.payload.trace!.attrs_json!)).toEqual({
+        tool: 'read',
+        n: 1,
+        flag: true,
+      });
+      expect(ev.payload.trace!.duration_ms).toBe(42);
+    }
+  });
+
+  it('defaults level to debug', () => {
+    const ev = buildDebugTraceEvent({
+      sessionId: fixture.sessionId,
+      turnId: fixture.turnId,
+      eventId: 'dbg-2',
+      phase: 'phase-x',
+      message: 'msg',
+    });
+    if (ev.type === RuntimeEventType.DEBUG_TRACE) {
+      expect(ev.payload.trace!.level).toBe(RuntimeDebugTraceLevel.DEBUG);
+      expect(ev.payload.trace!.duration_ms).toBeUndefined();
+    }
+  });
+});
+
+describe('extractAssistantUsage', () => {
+  it('returns undefined for non-object input', () => {
+    expect(extractAssistantUsage(undefined, 200_000)).toBeUndefined();
+    expect(extractAssistantUsage(null, 200_000)).toBeUndefined();
+    expect(extractAssistantUsage(42, 200_000)).toBeUndefined();
+  });
+
+  it('returns undefined when message role is not assistant', () => {
+    expect(extractAssistantUsage({ role: 'user', usage: { totalTokens: 100 } }, 200_000)).toBeUndefined();
+  });
+
+  it('returns undefined when stopReason is aborted or error (pi suppresses usage)', () => {
+    expect(
+      extractAssistantUsage(
+        { role: 'assistant', stopReason: 'aborted', usage: { totalTokens: 100 } },
+        200_000,
+      ),
+    ).toBeUndefined();
+    expect(
+      extractAssistantUsage(
+        { role: 'assistant', stopReason: 'error', usage: { totalTokens: 100 } },
+        200_000,
+      ),
+    ).toBeUndefined();
+  });
+
+  it('returns undefined when usage block is missing', () => {
+    expect(extractAssistantUsage({ role: 'assistant' }, 200_000)).toBeUndefined();
+    expect(extractAssistantUsage({ role: 'assistant', usage: null }, 200_000)).toBeUndefined();
+  });
+
+  it('prefers totalTokens over input+output+cacheRead+cacheWrite', () => {
+    const result = extractAssistantUsage(
+      {
+        role: 'assistant',
+        stopReason: 'end_turn',
+        usage: { input: 100, output: 50, cacheRead: 0, cacheWrite: 0, totalTokens: 999 },
+      },
+      200_000,
+    );
+    expect(result).toEqual({
+      total_tokens: 999,
+      context_window: 200_000,
+      input_tokens: 100,
+      output_tokens: 50,
+    });
+  });
+
+  it('falls back to input+output+cacheRead+cacheWrite when totalTokens is missing or zero', () => {
+    const result = extractAssistantUsage(
+      {
+        role: 'assistant',
+        stopReason: 'end_turn',
+        usage: { input: 100, output: 50, cacheRead: 30, cacheWrite: 20 },
+      },
+      200_000,
+    );
+    // Cache hits/writes are also surfaced so observability can distinguish
+    // a true zero from "provider did not report cache stats".
+    expect(result).toEqual({
+      total_tokens: 200,
+      context_window: 200_000,
+      input_tokens: 100,
+      output_tokens: 50,
+      cache_read: 30,
+      cache_write: 20,
+    });
+  });
+
+  it('uses caller-provided contextWindow (per-model metadata)', () => {
+    const result = extractAssistantUsage(
+      { role: 'assistant', usage: { totalTokens: 500 } },
+      131_072,
+    );
+    expect(result?.context_window).toBe(131_072);
+  });
+
+  it('coerces non-finite usage values to 0', () => {
+    const result = extractAssistantUsage(
+      {
+        role: 'assistant',
+        usage: { input: NaN, output: 'oops', cacheRead: 30, cacheWrite: 20 },
+      },
+      200_000,
+    );
+    // input/output coerce to 0 but valid cacheRead/cacheWrite still surface.
+    expect(result).toEqual({
+      total_tokens: 50,
+      context_window: 200_000,
+      cache_read: 30,
+      cache_write: 20,
+    });
+  });
+
+  it('keeps an explicit zero input or output instead of dropping the field', () => {
+    // Full prompt-cache hits report input: 0 alongside cacheRead. Dropping the
+    // zero makes downstream usage summaries treat a known count as unknown and
+    // flag the turn incomplete, so explicit finite zeros must survive.
+    const result = extractAssistantUsage(
+      {
+        role: 'assistant',
+        stopReason: 'end_turn',
+        usage: { input: 0, output: 20, cacheRead: 50, cacheWrite: 0, totalTokens: 70 },
+      },
+      200_000,
+    );
+    expect(result).toEqual({
+      total_tokens: 70,
+      context_window: 200_000,
+      input_tokens: 0,
+      output_tokens: 20,
+      cache_read: 50,
+    });
+  });
+
+  it('still omits input and output when the provider did not report them', () => {
+    const result = extractAssistantUsage(
+      { role: 'assistant', stopReason: 'end_turn', usage: { totalTokens: 500 } },
+      200_000,
+    );
+    expect(result).toEqual({ total_tokens: 500, context_window: 200_000 });
+  });
+});
+
+// ─── Buffer-walk helpers (sub-agent extraction) ─────────────────────────
+
+/** Build a minimal `stream.resp` RuntimeEvent from a serialised RespData. */
+function fakeStreamResp(respData: object): StreamRespEvent {
+  return {
+    schema: RUNTIME_EVENT_SCHEMA,
+    event_id: 'ev-fake',
+    session_id: fixture.sessionId,
+    turn_id: fixture.turnId,
+    runtime_seq: 0,
+    type: RuntimeEventType.STREAM_RESP,
+    payload: { stream_resp: JSON.stringify(respData) },
+  };
+}
+
+describe('extractFinalAssistantText (buffer-walk helper)', () => {
+  it('returns the AgentMessage msg_content even when followed by tool-call chunks', () => {
+    const buffered: RuntimeEvent[] = [
+      // [0] AgentMessageChunk with partial text
+      fakeStreamResp({
+        type: RespDataType.AgentMessageChunk,
+        agent_message_chunk: { msg_id: 'msg-1', chunk_index: 0, msg_content: 'partial' },
+      }),
+      // [1] Completed AgentMessage with final text
+      fakeStreamResp({
+        type: RespDataType.AgentMessage,
+        agent_message: {
+          msg_id: 'msg-1',
+          msg_type: MsgType.AgentContent,
+          role: 'assistant',
+          msg_content: 'FINAL TEXT',
+          timestamp: fixture.nowMs,
+        },
+      }),
+      // [2] AgentMessageChunk with tool_calls (arrives after the closed message)
+      fakeStreamResp({
+        type: RespDataType.AgentMessageChunk,
+        agent_message_chunk: {
+          msg_id: 'msg-1',
+          chunk_index: 1,
+          tool_calls: [{ tool_name: 'bash', tool_call_id: 'tc-1', tool_call_status: 1 }],
+        },
+      }),
+      // [3] terminal session.status
+      {
+        schema: RUNTIME_EVENT_SCHEMA,
+        event_id: 'ev-term',
+        session_id: fixture.sessionId,
+        turn_id: fixture.turnId,
+        type: RuntimeEventType.SESSION_STATUS,
+        payload: {
+          status: RuntimeEventStatus.COMPLETED,
+          stop_reason: { type: RuntimeStopReasonType.END_TURN },
+        },
+      } as RuntimeEvent,
+    ];
+
+    expect(extractFinalAssistantText(buffered)).toBe('FINAL TEXT');
+  });
+
+  it('returns empty string when buffer has no AgentMessage frame', () => {
+    const buffered: RuntimeEvent[] = [
+      fakeStreamResp({
+        type: RespDataType.AgentMessageChunk,
+        agent_message_chunk: { msg_id: 'msg-1', chunk_index: 0, msg_content: 'chunk only' },
+      }),
+      fakeStreamResp({
+        type: RespDataType.AgentMessageChunk,
+        agent_message_chunk: { msg_id: 'msg-1', chunk_index: 1, finish: true },
+      }),
+      {
+        schema: RUNTIME_EVENT_SCHEMA,
+        event_id: 'ev-term',
+        session_id: fixture.sessionId,
+        turn_id: fixture.turnId,
+        type: RuntimeEventType.SESSION_STATUS,
+        payload: {
+          status: RuntimeEventStatus.COMPLETED,
+          stop_reason: { type: RuntimeStopReasonType.END_TURN },
+        },
+      } as RuntimeEvent,
+    ];
+
+    expect(extractFinalAssistantText(buffered)).toBe('');
+  });
+});
+
+describe('extractFinalAssistantUsageFromBuffer', () => {
+  it('returns usage from the last AgentMessage', () => {
+    const buffered: RuntimeEvent[] = [
+      fakeStreamResp({
+        type: RespDataType.AgentMessage,
+        agent_message: {
+          msg_id: 'msg-1',
+          msg_type: MsgType.AgentContent,
+          role: 'assistant',
+          msg_content: 'done',
+          timestamp: fixture.nowMs,
+          usage: { total_tokens: 500, context_window: 200_000 },
+        },
+      }),
+    ];
+
+    expect(extractFinalAssistantUsageFromBuffer(buffered)).toEqual({
+      total_tokens: 500,
+      context_window: 200_000,
+    });
+  });
+
+  it('returns undefined when buffer has no AgentMessage', () => {
+    const buffered: RuntimeEvent[] = [
+      fakeStreamResp({
+        type: RespDataType.AgentMessageChunk,
+        agent_message_chunk: { msg_id: 'msg-1', chunk_index: 0 },
+      }),
+    ];
+
+    expect(extractFinalAssistantUsageFromBuffer(buffered)).toBeUndefined();
+  });
+
+  // Regression: sub-agent buffer path (cloud-task.ts:207) must propagate
+  // cache_read / cache_write so sub-agent cache metrics aren't silently
+  // dropped — symmetric with extractAssistantUsage on the direct event path.
+  it('propagates cache_read / cache_write when present in usage', () => {
+    const buffered: RuntimeEvent[] = [
+      fakeStreamResp({
+        type: RespDataType.AgentMessage,
+        agent_message: {
+          msg_id: 'msg-1',
+          msg_type: MsgType.AgentContent,
+          role: 'assistant',
+          msg_content: 'done',
+          timestamp: fixture.nowMs,
+          usage: {
+            total_tokens: 1500,
+            context_window: 200_000,
+            cache_read: 800,
+            cache_write: 200,
+          },
+        },
+      }),
+    ];
+
+    expect(extractFinalAssistantUsageFromBuffer(buffered)).toEqual({
+      total_tokens: 1500,
+      context_window: 200_000,
+      cache_read: 800,
+      cache_write: 200,
+    });
+  });
+
+  it('omits cache_read / cache_write when zero or missing', () => {
+    const buffered: RuntimeEvent[] = [
+      fakeStreamResp({
+        type: RespDataType.AgentMessage,
+        agent_message: {
+          msg_id: 'msg-1',
+          msg_type: MsgType.AgentContent,
+          role: 'assistant',
+          msg_content: 'done',
+          timestamp: fixture.nowMs,
+          usage: {
+            total_tokens: 500,
+            context_window: 200_000,
+            cache_read: 0,
+            cache_write: 0,
+          },
+        },
+      }),
+    ];
+
+    expect(extractFinalAssistantUsageFromBuffer(buffered)).toEqual({
+      total_tokens: 500,
+      context_window: 200_000,
+    });
+  });
+});

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików